> ## 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 Messages and Schemas

> Demonstration of a modern MCP server and Inspector using a shipment-tracker example, showing startup, stdio transport, metadata via _meta, Pydantic models, and tool implementation.

Welcome. This lesson is a concise, hands-on demonstration of an MCP server and how an MCP Inspector client interacts with it. The Inspector connects to a single server process — in this demo the server is named `shipment-tracker`. We walk through: starting the server, what you see in the Inspector, the data model (fixtures), and the full server implementation.

## Running the server

Start the demo server from the project root:

```bash theme={null}
../.venv/bin/python server.py
```

When the server begins it prints a ready message to stderr, for example:

```text theme={null}
12:07:25 shipment-tracker ready on stdio
```

This indicates the process is running and ready to accept Inspector connections over stdio.

## Connecting with MCP Inspector

* The Inspector connects to one server process (here, `shipment-tracker`) and displays protocol and client/server metadata.
* This demo uses the modern MCP protocol era (`2026.07.28`). The Inspector shows:
  * protocol era (modern vs legacy),
  * supported transports (e.g., `stdio`),
  * server capabilities (tools/resources/prompts),
  * client capabilities (roots, sampling, elicitation, etc.).
* In the modern era the Inspector sends a single request containing a `_meta` object with client metadata. (Legacy-era MCP used a multi-step handshake.)

Example of a typical tool response when invoking `get_shipment_status` for shipment `PL-4417`:

```json theme={null}
{
  "ref": "PL-4417",
  "status": "in_transit",
  "location": "Rotterdam distribution centre",
  "estimatedDelivery": "2026-09-14",
  "lastScan": "2026-09-10T06:12:00Z"
}
```

Inspector’s protocol log contains both the client-to-server request (including `_meta`) and the server response (also including `_meta`). A key takeaway: the modern protocol embeds metadata in `_meta` on both requests and responses so client and server can exchange runtime capabilities and diagnostics.

### Response fields (quick reference)

| Field | Type | Description |
| - | - | - |
| `ref` | string | Shipment reference, e.g. `PL-4417`. |
| `status` | string | Carrier status using carrier vocabulary (e.g., `in_transit`). |
| `location` | string | Current physical location of the shipment. |
| `estimatedDelivery` | string or null | ISO-8601 date when carrier has committed to an ETA. |
| `lastScan` | string | ISO-8601 timestamp of the last carrier scan. |

## Console logs

When running over stdio, print human-readable logs to stderr so protocol messages on stdout remain uncorrupted. Example stderr output from the running server:

```text theme={null}
12:13:17 [shipment-tracker] lookup PL-4417
12:07:25 shipment-tracker ready on stdio
```

When using the stdio transport, log statements should be printed to stderr (not stdout). This prevents logs from being mixed with the protocol messages that travel over stdout.

## Fixtures: shipment model and demo data

This demo uses a small fixtures module (`mcpa_demo`) that:

* defines a Pydantic model representing a shipment, and
* provides an in-memory dataset of example shipments.

The model ensures the JSON structure returned by the tool is typed and validated. See Pydantic documentation for details: [https://docs.pydantic.dev/latest/](https://docs.pydantic.dev/latest/)

```python theme={null}
# mcpa_demo.py
from typing import Optional
from pydantic import BaseModel, Field

#: The canonical shipment used in these examples. Every example uses this one.
CANONICAL_REF = "PL-4417"

class Shipment(BaseModel):
    """One shipment's current status."""

    ref: str = Field(description="The shipment reference, e.g. PL-4417.")
    status: str = Field(description="Current status in the carrier's own vocabulary.")
    location: str = Field(description="Where the shipment physically is right now.")
    estimated_delivery: Optional[str] = Field(
        default=None,
        alias="estimatedDelivery",
        description="ISO-8601 date, or null when the carrier has not committed to one.",
    )
    last_scan: str = Field(
        alias="lastScan",
        description="Last time the carrier reported movement. ISO-8601 timestamp.",
    )

    model_config = {"populate_by_name": True}

    def describe(self) -> str:
        """A human-readable one-liner, for a tool result's text content."""
        eta = self.estimated_delivery or "not yet committed"
        pretty_status = self.status.replace("_", " ")
        return (
            f"{self.ref} is {pretty_status} at {self.location}. "
            f"Estimated delivery: {eta}."
        )

SHIPMENTS: dict[str, Shipment] = {
    "PL-4417": Shipment(
        ref="PL-4417",
        status="in_transit",
        location="Rotterdam distribution centre",
        estimatedDelivery="2026-09-14",
        lastScan="2026-09-10T06:12:00Z",
    ),
    "PL-4418": Shipment(
        ref="PL-4418",
        status="delivered",
        location="Signed for at reception",
        estimatedDelivery="2026-09-08",
        lastScan="2026-09-08T14:31:00Z",
    ),
    "PL-9002": Shipment(
        ref="PL-9002",
        status="held_at_customs",
        location="Felixstowe",
        estimatedDelivery=None,
        lastScan="2026-09-09T22:04:00Z",
    ),
}

def find_shipment(ref: str) -> Optional[Shipment]:
    return SHIPMENTS.get(ref.strip().upper())
```

Note: `find_shipment` normalizes the supplied reference by stripping whitespace and uppercasing, then looks up the value in `SHIPMENTS`. It returns either a `Shipment` instance or `None` when not found.

## Server implementation

The server is an asyncio-based MCP server that exposes a single tool: `get_shipment_status`. The tool accepts a `ref` argument with validation, logs the lookup to stderr, queries the fixture helper `find_shipment`, and returns the `Shipment` model or raises `ToolError` when no matching shipment exists.

```python theme={null}
# server.py
import sys
from typing import Annotated

from pydantic import Field
from mcp.server import MCPServer
from mcp.server.mcpserver import Context
from mcp.server.mcpserver.exceptions import ToolError
from mcpa_demo import Shipment, find_shipment

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

@server.tool(
    description=(
        "Look up the current status of a shipment by its reference. "
        "Returns the status, the shipment's current location, and the "
        "estimated delivery date when the carrier has committed to one."
    )
)
async def get_shipment_status(
    ref: Annotated[
        str,
        Field(
            pattern=r"^PL-\d{4}$",
            description=(
                "The shipment reference to look up, for example PL-4417. "
                "Case-insensitive. This is the only thing the tool needs."
            ),
        ),
    ],
    ctx: Context,
) -> Shipment:
    # Log the lookup to stderr so protocol messages on stdout remain clean.
    print(f"[shipment-tracker] lookup {ref}", file=sys.stderr)

    shipment = find_shipment(ref)

    if shipment is None:
        raise ToolError(
            f"No shipment found with reference {ref}. "
            "This demo knows about PL-4417, PL-4418 and PL-9002."
        )

    return shipment

if __name__ == "__main__":
    print("shipment-tracker ready on stdio", file=sys.stderr)
    server.run("stdio")
```

Key implementation notes:

* The `@server.tool(...)` decorator exposes this function as an MCP tool.
* The `ref` parameter is typed as `Annotated[str, Field(...)]` so the generated tool schema includes validation (regex) and a description that clients (Inspector) can present to users.
* Lookups are logged to stderr; if a shipment is not found the function raises `ToolError`. The MCP framework will propagate this as a tool execution error to the client.

Caveat about case sensitivity:

* The Field description mentions “Case-insensitive”, but the regex `^PL-\d{4}$` is case-sensitive. Pydantic will validate the raw input against that pattern, so lowercased input like `pl-4417` will fail validation before `find_shipment` runs.
* Options to make it truly case-insensitive include:
  * use a case-insensitive pattern (for example `(?i)^PL-\d{4}$`), or
  * normalize input (e.g., uppercase) before validation/lookup.

If a tool raises a `ToolError`, the client will receive a proper tool-execution error. Use `ToolError` to signal user-facing failures instead of returning partial or malformed data.

## mcp.json — registering the server

The local MCP configuration instructs the Inspector how to start the server process. For this demo, the configuration looks like:

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

This tells the Inspector to launch `shipment-tracker` by running the virtualenv’s Python interpreter with `server.py`, and that the server speaks the modern protocol over stdio.

## Files & responsibilities

| File | Purpose |
| - | - |
| `server.py` | MCP server process that registers tools and runs over stdio. |
| `mcpa_demo.py` | Pydantic models and in-memory demo data (fixtures). |
| `mcp.json` | Local MCP configuration for launching the server from the Inspector. |

> When including examples or configuration snippets in tables, keep any JSON or object literals quoted or in code blocks to avoid MDX/JS parsing issues.

## Summary

* The MCP Inspector acts as a client that connects to a single server process (here, `shipment-tracker`).
* Servers expose tools (for example `get_shipment_status`) with typed, validated arguments and structured return values (Pydantic models).
* In the modern MCP era a single request payload is used and both client and server embed runtime metadata in the `_meta` object.
* When using stdio transport, print logs to stderr so stdout remains reserved for protocol traffic.

This lesson covered how to run and inspect an MCP server, how request/response metadata flows are handled with `_meta`, and the structure of a minimal server plus fixtures for a demo implementation.

## Links and references

* Pydantic documentation: [https://docs.pydantic.dev/latest/](https://docs.pydantic.dev/latest/)
* (For MCP specifics, consult your project's MCP protocol documentation or internal reference materials.)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/model-context-protocol-associate-mcpa-certification/module/282d97e2-04f7-4beb-8301-695ecb3f3f99/lesson/306bdbcf-772b-4694-9d66-375548e7a1e1)


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