Skip to content

Part 6, Build the MCP server โ€‹

Knowledge-share outline โ€‹

  1. Recap: MCP resources, prompts, and tools.
  2. What makes a good tool contract: clear description, typed inputs, predictable output.
  3. Why descriptions matter, they are how a client (and a model) picks the right tool.
  4. Input validation and predictable outputs: rejecting bad input clearly, never guessing.
  5. Read-only versus write operations, and why writes need extra care.
  6. Testing MCP capabilities standalone before putting an agent in front of them.
  7. How the package manager MCP server fits into the afternoon (the agent connects next).
  8. What you will build and validate in this segment.

At a glance โ€‹

Start stateEnd stateFallback baseline
The Part 5 MCP design on paperA small, running, inspectable MCP server exposing tools, a prompt, and a resource, validated standalonebaseline/06-1-mcp-server.py

Learning goals โ€‹

  • Create an MCP (Model Context Protocol) server from scratch
  • Run or inspect an MCP server and see the capabilities it exposes.
  • Explain why each exposed capability is a resource, prompt, or tool.
  • Validate a tool contract, description, inputs, outputs, and errors, with one successful and one failed call.

What you need before you start โ€‹

You need two things in place:

  1. Your Part 5 MCP design (the capability mapping and checklist from the design exercise).
  2. Your package-this fork cloned locally and running (from Part 5, Package manager fork). If you haven't started it yet, see Running the app.

The MCP server you are going to build in this segment wraps package-this's capabilities and exposes them over the MCP interface.

Why it matters โ€‹

In Part 5 you designed how the package manager's capabilities map to MCP resources, prompts, and tools. Now we make that design real. As Dunder Mifflin grows, many agents need the same package capabilities, so we run them once, as a shared server any agent can connect to, like a loading dock every truck can use instead of one per truck. Building it yourself shows that MCP is not magic: the capabilities, their descriptions, inputs, outputs, and errors are all explicit, inspectable, and testable.

What you will build โ€‹

A small MCP server for the package manager that exposes at least four tools (package lookup, order status lookup, route/driver information lookup), one reusable prompt, and one resource (a package status policy or data schema), then validate it standalone with a successful and a failed call. Nothing is hidden: you can list what the server offers, read each capability's description and input/output shape, and call it directly before any agent is involved. You finish ready to connect an agent; wiring the agent in comes afterward.

Lab steps โ€‹

  1. Copy the starter file.

    You will use FastMCP, the high-level Python class from the MCP Python SDK. FastMCP handles all the protocol wiring. You declare a server name, then decorate ordinary Python functions as tools, prompts, or resources; the SDK takes care of the rest.

    a. Confirm the SDK is installed. It is already listed in requirements.txt as mcp. If you have not installed dependencies yet, run this from the root of your fork with your virtual environment active:

    powershell
    pip install -r requirements.txt
    bash
    pip install -r requirements.txt

    b. Copy the starter file. From the root of your dm-ws fork, copy the provided starter into place:

    powershell
    copy starter\06-1-mcp-server.py mcp_server.py
    bash
    cp starter/06-1-mcp-server.py mcp_server.py

    Open mcp_server.py. It already contains the imports, the FastMCP("package-manager") instance, the _get() HTTP helper, all capability stubs with TODO markers, and the mcp.run() entry point. Your job in this segment is to replace each TODO.

  2. Review the stubs. Open mcp_server.py. The starter already registers placeholder stubs for all five capabilities โ€” four tools, one prompt, and one resource. Each stub returns "TODO" so you can inspect the server's shape immediately before writing any logic.

    Each decorator (@mcp.tool(), @mcp.prompt(), @mcp.resource(...)) registers the function with the server. The docstring becomes the capability's description; it is how a client or model knows what to call and when, so keep it clear and specific.

  3. Inspect the server. The MCP SDK ships with a built-in inspector. Run it with:

    powershell
    mcp dev --with "mcp[cli]" mcp_server.py
    bash
    mcp dev --with "mcp[cli]" mcp_server.py

    If you get prompted for installing the MCP inspector, install it first. This starts the server and opens the MCP Inspector in your browser. After clicking the โ–ถ๏ธ connect button, you will see all registered capabilities listed by kind: four tools, one prompt, and one resource โ€” all marked TODO for now.

    Expected output: the inspector shows list_packages, lookup_package, lookup_order_status, lookup_route, investigate_delayed_package, and package-status-policy, each with the description from its docstring.

  4. Complete the four tools.

Make sure package manager is running

Check out how to run the provided package manager: Running the app.

The tools call the package-this REST API running at http://localhost:8000. Each tool makes an HTTP request, handles a 404 as a clean "not found", and returns a human-readable string. The API uses an X-Persona-Id header for identity โ€” no password required.

a. Check the API is running and explore it. Before writing any code, open the Swagger UI at http://localhost:8000/docs in your browser. The four endpoints you will use are:

EndpointUsed by
GET /packageslist_packages
GET /packages/{package_id}lookup_package, lookup_order_status
GET /routes/{route_id}lookup_route
GET /packages/{package_id}/historyoptional stretch

b. Review the API client helper. Near the top of mcp_server.py the starter already includes the imports and the _get() helper. _BASE_URL and _PERSONA are read from the PACKAGE_API_URL and PACKAGE_API_PERSONA environment variables, with working defaults (http://localhost:8000, jim-halpert) โ€” you only need to set them in your .env if your backend runs elsewhere. The 404 guard turns "not found" into None so each tool can return a clear error string instead of letting an exception bubble up.

c. Implement list_packages. Replace its TODO stub. This calls GET /packages and returns all package IDs as a comma-separated list so an agent (or you) can discover valid IDs before looking up individual records:

python
@mcp.tool()
def list_packages() -> str:
    """Return all package IDs in the system. Use this to discover valid IDs before calling lookup_package or lookup_order_status."""
    data = _get("/packages")
    if data is None:
        return "Error: could not retrieve package list."
    items = data.get("items", []) if isinstance(data, dict) else data
    ids = [p["package_id"] for p in items]
    return ("Packages: " + ", ".join(ids)) if ids else "No packages found."

d. Implement lookup_package. Replace its TODO stub:

python
@mcp.tool()
def lookup_package(package_id: str) -> str:
    """Look up a package by its ID (e.g. PKG-2024-003).
    Returns status, destination, fragile flag, priority, and any delay information."""
    data = _get(f"/packages/{package_id}")
    if data is None:
        return f"Error: no package found with ID '{package_id}'."
    delay = f", delay_reason={data['delay_reason']}" if data.get("delay_reason") else ""
    return (
        f"Package {package_id}: status={data['status']}, "
        f"destination={data['destination']}, fragile={data['fragile']}, "
        f"priority={data['priority']}, truck={data.get('truck_id') or 'none'}"
        f"{delay}"
    )

e. Test lookup_package before moving on. Run the inspector and try it in the Tools tab:

powershell
mcp dev --with "mcp[cli]" mcp_server.py
bash
mcp dev --with "mcp[cli]" mcp_server.py

Use a real package_id from your seeded database (check http://localhost:8000/packages in the browser or the Swagger UI to find one), then try a made-up ID:

InputExpected
a real ID from the DBfull record line
DM-9999Error: no package found with ID 'DM-9999'.

f. Implement lookup_order_status. Replace its TODO stub. This uses the same endpoint as lookup_package but returns a narrower view focused on delivery progress:

python
@mcp.tool()
def lookup_order_status(package_id: str) -> str:
    """Return the current delivery status and delay details for a package (e.g. PKG-2024-003)."""
    data = _get(f"/packages/{package_id}")
    if data is None:
        return f"Error: no package found with ID '{package_id}'."
    parts = [f"status={data['status']}"]
    if data.get("delay_reason"):
        parts.append(f"delay_reason={data['delay_reason']}")
    if data.get("delay_duration_hours") is not None:
        parts.append(f"delay_hours={data['delay_duration_hours']}")
    if data.get("expected_delivery"):
        parts.append(f"expected_delivery={data['expected_delivery']}")
    return f"Order status for {package_id}: " + ", ".join(parts)

g. Implement lookup_route. Replace its TODO stub:

python
@mcp.tool()
def lookup_route(route_id: str) -> str:
    """Return route information for a given route ID (e.g. ROUTE-20260706-309DD0)."""
    data = _get(f"/routes/{route_id}")
    if data is None:
        return f"Error: no route found with ID '{route_id}'."
    return str(data)

The route response shape is a free-form object โ€” use the Swagger UI (GET /routes/{route_id}) to inspect what fields come back, then tighten the return string to match once you have seen a real response.

h. Test all four tools. Re-run mcp dev --with "mcp[cli]" mcp_server.py and confirm each row in the Tools tab:

ToolInputExpected
list_packages(none)comma-separated list of package IDs
lookup_packagereal package IDfull record
lookup_packageDM-9999Error: no package found...
lookup_order_statusreal package IDstatus=... line
lookup_order_statusDM-9999Error: no package found...
lookup_routereal route IDroute object
lookup_routeR-99Error: no route found...

Expected output: every valid lookup returns real API data; every bad ID returns an Error: ... string, never a Python traceback.

  1. Complete the prompt and resource.

    i. Implement investigate_delayed_package (the prompt). A prompt is a reusable instruction template the agent invokes to start a multi-step workflow. Replace its TODO stub:

    python
    @mcp.prompt()
    def investigate_delayed_package(orderId: str) -> str:
        """Reusable workflow for investigating a delayed or problematic package."""
        return f"""\
    Investigate the package for order {orderId}. Follow these steps:
    
    1. Call list_packages() to find the package ID matching order {orderId}.
    2. Call lookup_package(<packageId>) to get the full record.
    3. Call lookup_order_status(<packageId>) for delivery progress and any delay details.
    4. If a route is returned, call lookup_route(<routeId>) to see all packages on that route.
    5. Check the status against the policy (resource://package-status-policy).
    6. Summarise findings and propose one concrete next step for Darryl.
    
    Ground every claim in a tool result. If you have not looked something up, say so.
    """

    j. Implement package_status_policy (the resource). A resource is read-only reference data the agent can read but not call. Replace its TODO stub:

    python
    @mcp.resource("resource://package-status-policy")
    def package_status_policy() -> str:
        """The Dunder Mifflin package handling and status policy."""
        from pathlib import Path
        policy_path = Path(__file__).parent / "data" / "policy.md"
        if policy_path.exists():
            return policy_path.read_text()
        return "Package status policy: see Dunder Mifflin shipping guidelines."

    k. Verify in the inspector. Re-run mcp dev --with "mcp[cli]" mcp_server.py and check the Prompts and Resources tabs. Both should now show real content instead of TODO.

    CapabilityKindExpected content
    investigate_delayed_packagePromptStep-by-step investigation workflow
    package-status-policyResourceText from data/policy.md
  2. Validate a successful and a failed call using the inspector. A valid lookup returns the documented output; an invalid ID returns a clear error, never a stack trace.

Tool contract checklist โ€‹

Run each tool against this checklist before you trust it, or hand it to an agent.

  • Clear description: one sentence stating what the tool does and when to use it. This is how a client (and a model) selects the right tool; vague descriptions cause wrong calls.
  • Typed inputs: every input has a name and a type, declared in the tool's schema.
  • Input validation: invalid input (unknown id, wrong type, missing field) is rejected with a clear reason. The tool never guesses.
  • Predictable output: a documented, consistent output shape for valid input.
  • Honest read-only vs write marker: note whether the tool only reads or also changes data. Writes need extra care; today's package-manager tools are read-only.
  • Validated both paths: you have run one successful call (documented output) and one failed call (clear error), and confirmed both behave as designed.

What makes a good contract: a clear description (this is how a client or model selects the tool, vague descriptions cause wrong calls), typed inputs with validation (bad input is rejected with a reason, never guessed), a predictable output shape, and an honest read-only vs write marker. Of the four tools here, all are read-only lookups; a write such as "update package status" would be marked write and is intentionally left out of scope.

Expected output โ€‹

  • Inspecting the server: four tools (list_packages, lookup_package, lookup_order_status, lookup_route), one prompt (investigate-delayed-package), and one resource (package-status-policy), each with a description.
  • Successful tool call: a JSON (JavaScript Object Notation) object matching the tool's documented output shape.
  • Failed tool call: a structured error message naming what was wrong, never a stack trace or an invented answer.

Checkpoint โ€‹

  • The server runs or inspects and lists its capabilities.
  • It exposes four tools (package list, package lookup, order status, route/driver), one prompt, and one resource.
  • You validated one successful and one failed tool call, with a clear error on failure.
  • You are ready to connect an agent to the server.

See How checkpoints work.

Fallback baseline โ€‹

Try the build yourself first, then copy the fallback if you run out of time:

bash
copy baseline\06-1-mcp-server.py mcp_server.py
bash
cp baseline/06-1-mcp-server.py mcp_server.py

The baseline includes the completed server, all four tools, the prompt, and the resource, so you can adopt it and still be ready to connect an agent in the afternoon.

Troubleshooting โ€‹

  • The MCP Inspector shows a tool as TODO, its definition is incomplete; give it a description, typed inputs, and a return value. Run mcp dev --with "mcp[cli]" mcp_server.py and connect to verify. More help on Troubleshooting.
  • A valid call returns an error, check the input matches the tool's declared schema (field names and types).
  • A bad call crashes instead of erroring cleanly, add input validation so the tool rejects unknown identifiers with a message rather than raising.
  • Out of time, adopt the completed server from baseline/06-1-mcp-server.py and move on; you are still ready for the next segment.

Optional stretch task โ€‹

Add a fourth read-only tool (for example lookup_driver by route) with a full contract and a validation test, or write a tiny test script that calls every tool with one valid and one invalid input and prints a pass/fail line each, a preview of testing a server before an agent uses it.

Source-backed background โ€‹

  • MCP protocol concepts: primary source, modelcontextprotocol.io, for the server model and the resources, prompts, and tools primitives.
  • Server implementation: the official MCP Python SDK documentation for defining tools, prompts, resources, and their schemas. Everything the server exposes is explicit in code and inspectable at runtime, MCP is not magic.

For the full source list, see References.

Apply it: De LeesLantaarn โ€‹

Apply it to your own solution

If you were building the De LeesLantaarn MCP server, which typed tool would you implement first: borrow_book, place_backorder, or get_recommendations? Write its tool contract, typed inputs, validation (age category, subscription limits), predictable output, and a read-only vs write marker, the same way you just did for the package tools.

What we will not cover โ€‹

  • Building the full package manager application, it is supplied; we only expose a few of its capabilities.
  • Production authentication or authorization for the server.
  • Complex write operations or mutations, today's tools are read-only lookups.
  • A large tool catalog, a few well-formed capabilities beat many shallow ones.

You finish this segment ready to connect an agent to your validated server, that connection is the bridge into Part 7, where you build the first package manager agent that uses it.


Previous: Part 5, MCP fundamentals ยท Next: Part 7, Agent Framework & first MCP-connected agent