> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Three primitives Part 3

> Explains MCP prompt templates, how clients list and fetch them, server prompt registration examples, and differences between prompts tools and resources to guide user-driven prompt use.

Welcome back. In this lesson we cover prompts and prompt templates in the Model Context Protocol (MCP) and how clients discover and fetch them.

Prompts are a distinct server-side primitive: they are templates the application exposes for users to choose. Unlike tools and some resources, prompts are user-controlled — the model will not invoke them automatically, and the application reads them only when a user requests one.

Prompts are templates the user picks. The model does not call them by itself, and the application only reads them when the user asks for one.

## How a client discovers prompts

Clients enumerate available prompts by calling the `prompts/list` RPC method. The server responds with a list of prompt templates and metadata. After the user chooses a prompt and provides any required arguments, the client requests a filled-in prompt with `prompts/get`.

Example (simplified) JSON-RPC response for `prompts/list`:

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "_meta": {
      "io.modelcontextprotocol/serverInfo": {
        "name": "shipment-tracker",
        "version": "3.2.0"
      }
    },
    "prompts": [
      {
        "name": "escalate_shipment",
        "description": "Draft an escalation note for a delayed shipment",
        "arguments": {
          "ref": {
            "type": "string",
            "description": "Shipment reference"
          }
        }
      }
    ]
  }
}
```

Notes on the `prompts/list` response:

* `_meta` provides server identity and versioning.
* `prompts` is an array of templates the client can present to the user.
* Each prompt includes `name`, `description`, and an `arguments` schema the client can use to render a form or elicitation UI.

When the user selects a prompt (for example, `escalate_shipment` with `ref = "PL-4417"`), the client calls `prompts/get`. The server returns the assembled prompt content and metadata.

Example (simplified) request and response for `prompts/get`:

Request (client -> server):

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "prompts/get",
  "params": {
    "name": "escalate_shipment",
    "arguments": { "ref": "PL-4417" },
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07",
      "io.modelcontextprotocol/clientInfo": {
        "name": "mcp-inspector",
        "version": "2.13.0"
      },
      "io.modelcontextprotocol/clientCapabilities": {
        "sampling": {},
        "elicitation": { "form": {}, "url": {} }
      }
    }
  }
}
```

Response (server -> client):

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "_meta": {
      "io.modelcontextprotocol/serverInfo": {
        "name": "shipment-tracker",
        "version": "3.2.0"
      }
    },
    "description": "Draft an escalation note for a delay",
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "Shipment PL-4417 is in transit at Rotterdam distribution centre. Draft a short, factual escalation note to the carrier asking for a revised delivery commitment. State what we know, ask one specific question, and keep it under 120 words."
        }
      }
    ],
    "resultType": "complete"
  }
}
```

Important: the `messages` array contains the assembled prompt text and its role. The client should surface this message as the user input to the model (or otherwise present it in the UI).

Prompts are not tools. They are user-facing templates and must be selected and filled by a user (or user-driven UI). Do not assume the model will request or use prompts automatically.

## Example server implementation (server.py)

Below is a focused example showing how to register a prompt template on the server side using the MCP server API. This demonstrates a prompt that builds a short escalation note for a shipment reference.

```python theme={null}
from typing import Dict
from pydantic import Field

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

# Example application data structures (simplified).
# In a real application these would come from the application's data model or demo data.
class Shipment:
    def __init__(self, ref: str, status: str, location: str):
        self.ref = ref
        self.status = status
        self.location = location

# Sample shipment registry for the demo.
SHIPMENTS: Dict[str, Shipment] = {
    "PL-4417": Shipment(ref="PL-4417", status="in_transit", location="Rotterdam distribution centre"),
    # ... other shipments ...
}

server = MCPServer(name="shipment-tracker", version="3.2.0")

# ---------------------------------------------------------------------------
# PROMPTS - user-controlled. A prompt is a template the USER picks, not
# something the model invokes and not something the application reads on its
# own initiative.
# ---------------------------------------------------------------------------
@server.prompt(
    description=(
        "Draft an escalation note for a delayed shipment. The user picks this; "
        "the model does not call it and the application does not read it."
    )
)
def escalate_shipment(ref: str) -> str:
    """Build an escalation prompt for one shipment."""
    shipment = SHIPMENTS.get(ref.strip().upper())

    if shipment is None:
        raise ToolError(f"No shipment {ref}. Known: {', '.join(sorted(SHIPMENTS.keys()))}.")

    return (
        f"Shipment {shipment.ref} is {shipment.status.replace('_', ' ')} at "
        f"{shipment.location}. Draft a short, factual escalation note to the "
        f"carrier asking for a revised delivery commitment. State what we know, "
        f"ask one specific question, and keep it under 120 words."
    )

if __name__ == "__main__":
    # Start the MCP server (simplified; real code may pass stdio/stdout handlers).
    server.serve()
```

What this function demonstrates:

* The `@server.prompt` decorator registers a prompt template called `escalate_shipment`.
* The prompt function accepts `ref: str` and returns a concrete text prompt based on application data.
* Returning a factual, specific prompt helps reduce model hallucination by grounding the prompt in known data.

## Prompts vs. Tools vs. Resources — quick comparison

| Primitive | Purpose | Typical behavior |
| -: | - | - |
| Tool | Execute actions or computations | Model can invoke directly; may cause side effects |
| Resource | Read-only data manifests or structured data | App exposes for the model or UI; not fetched autonomously by the model |
| Prompt | User-facing templates | Exposed for users to select; application returns assembled text when requested |

## Example mcp.json snippet (register server)

Below is an example client-side MCP config to launch the server locally:

```json theme={null}
{
  "mcpServers": {
    "shipment-tracker": {
      "type": "stdio",
      "command": "../.venv/bin/python",
      "args": ["server.py"],
      "protocolEra": "modern"
    }
  }
}
```

## Typical client workflow

1. Discover available servers (server discovery).
2. Client calls `prompts/list` to enumerate available prompt templates.
3. User selects a prompt and provides any required arguments (for example, `ref = "PL-4417"`).
4. Client calls `prompts/get` to fetch the filled-in prompt text.
5. Client presents the returned `messages` text as the user input to a model or surfaces it in the UI.

## References and further reading

* MCP protocol and server patterns — see your project's MCP documentation for protocol details and conventions.
* JSON-RPC specification: [https://www.jsonrpc.org/specification](https://www.jsonrpc.org/specification)
* Pydantic (used in many MCP server examples): [https://pydantic-docs.helpmanual.io/](https://pydantic-docs.helpmanual.io/)

This article covered how to define prompt templates on the server, how clients discover and fetch them, and how returning specific, factual prompt text helps reduce model hallucination.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/model-context-protocol-associate-mcpa-certification/module/282d97e2-04f7-4beb-8301-695ecb3f3f99/lesson/5e67c858-bdf5-4709-9a18-99e8403f5308)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.