NewAI Content Creation is now live in Early Access
Turning Point Training Instituteby Training Center
Skip to content
0%
Module 2 — Build your first serverLesson 4 of 4
8 min readIntermediate
Downloads & resources
Download this lesson's materials, ready to use.

Skill packs and prompts are provided in English so they work best with the AI tools. Use them as-is.

From an existing API to MCP: wrap it safely

Example prompt

Updated 26 November 2026. This lesson replaces an earlier version whose install command no longer works and whose server was reachable from the whole network. If you followed it, stop that server (Ctrl+C in its terminal). Keep any work of your own and do this lab in a new, separate folder; delete the old lab files only if you choose to and they hold nothing you need. Do not follow the FastAPI-MCP steps shown in the earlier video either. The lab below was built and tested on 26 November 2026.

Example prompt

Where you are: Module 2. You have built a server from scratch. Now you have an API that already works, and you want an agent to use part of it.

What you will be able to do

  • Choose a small set of API operations that are safe and useful for a model, instead of exposing every endpoint.
  • Put an MCP server in front of an existing HTTP API with the official Python SDK, with every argument validated.
  • Run it on your own machine only, and prove with a scripted client that it works and refuses what it should.
  • Explain what has to change before the same server can be offered remotely.

Why not convert every endpoint automatically?

Libraries exist that turn each endpoint of an API into an MCP tool in two lines. It is tempting, and it is usually the wrong first move:

  • The model sees everything. Admin, delete and bulk endpoints become tools the model can call. A tool is an action the model may take, so the list should be short and deliberate.
  • Names and descriptions are written for programmers. A model chooses tools by their names and descriptions. Generated ones such as multiply_multiply_post work against you.
  • You inherit the library's pace. The library the earlier version of this lesson used, FastAPI-MCP, had its last release in July 2025. Installed today, its unpinned dependency pulls in version 2 of the official MCP SDK and the example crashes with a TypeError. Pinned to old versions it runs, but it speaks only the older protocol (2025-11-25), and in our test it accepted requests from a foreign web origin.

So in this lesson you wrap the API: you keep its logic and hand-write a few tools that call it.

The lab

Download Lab files (ZIP) from this lesson's links. It contains:

FileWhat it is
inventory_api.pyThe "existing API": a small inventory service with fake data. It has an admin DELETE that must not become a tool.
mcp_server.pyThe MCP server: three tools that call the API.
verify_client.pyA client that checks everything and exits with an error if any check fails.
pyproject.toml, uv.lockExact versions: Python 3.12, mcp 2.3.0, fastapi 0.165.0, uvicorn 0.54.0, httpx 0.28.1.
run.sh./run.sh verify or ./run.sh serve.

You need uv. Everything installs into the lab folder; nothing is installed globally. uv sync --locked refuses to run if the lock and the project disagree, which is what a pin is for. (The earlier lesson wrote >=0.3 and called it a pin; it was only a minimum, and that is what broke.)

Step 1: choose the operations

The API offers search, read, reserve and an admin delete. The server exposes three:

ToolChanges data?Why it is a tool
search_itemsNoLets the model find items by category and stock
get_itemNoReads one item by its SKU
reserve_stockYes, 1–10 unitsA useful action, small and bounded; the host should confirm it with the user

DELETE /items/{sku} stays in the API and out of the server. Ask of every endpoint: would I let a model do this, in a loop, after reading text from a stranger? If not, it is not a tool.

Step 2: write the tools

This is one tool from mcp_server.py (the file has all three):

python
@mcp.tool(
    name="reserve_stock",
    title="Reserve stock",
    annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False,
                                idempotent_hint=False, open_world_hint=False),
)
async def reserve_stock(
    sku: Annotated[str, Field(pattern=r"^[A-Z]{3}-\d{4}$", description="SKU like ELC-0001")],
    quantity: Annotated[int, Field(ge=1, le=10, description="Units to reserve (1-10)")],
) -> Reservation:
    """Reserve 1-10 units of an item for an order. This CHANGES stock; the host should confirm with the user."""
    resp = await _call_api("POST", f"/items/{sku}/reserve", json={"quantity": quantity})
    _raise_for_upstream(resp)
    return Reservation.model_validate(resp.json())

What each part does:

  • Validation in the signature. The pattern and the range go into the tool's input schema, and the SDK rejects bad arguments before your code runs. ../admin, elc-0001 and quantity=500 never reach the API.
  • A typed result. Returning a model gives the client structured output it can check, not just text.
  • Annotations are hints. read_only_hint and the others help the host decide what to confirm. They are not enforcement; your validation is.
  • Safe errors. _raise_for_upstream turns a 404 or 409 from the API into a short tool error ("No item with that SKU.") instead of a stack trace.
  • The model never chooses the URL. The API address comes from the operator and, in this lab, must be loopback. Nothing a model sends can make the server call another host.
  • No token passthrough. The server sends nothing from the incoming request to the API. If the API needed credentials, the server would use its own, never the client's.

Step 3: run it on your machine only

bash
./run.sh serve

The API listens on 127.0.0.1:8001 and the MCP endpoint on http://127.0.0.1:8000/mcp. 127.0.0.1 means "this computer only". The server also checks the Host and Origin headers, so a web page in your browser cannot reach it through a DNS trick: a foreign origin gets 403.

Do not change 127.0.0.1 to 0.0.0.0 to share it. That puts an unauthenticated server, able to call your API, on every network your computer joins.

To try it from Claude Code while it runs:

bash
claude mcp add --transport http demo-inventory http://127.0.0.1:8000/mcp

If you use the MCP Inspector, pin a patched version: npx @modelcontextprotocol/inspector@2.16.0. Keep its defaults (local only, random access token).

Step 4: prove it

bash
./run.sh verify

The client starts both services, then checks 22 things, including:

  • exactly three tools are listed, and the delete is not one of them;
  • each tool returns the expected result, and a reservation shows up in a later read;
  • bad input and unknown SKUs come back as tool errors;
  • a foreign Origin gets 403 and a foreign Host gets 421;
  • neither port answers on your network address.

It ends with ALL CHECKS PASSED (22). If port 8000 or 8001 is already taken by another program, it stops before starting anything and names the busy port; it never stops the other program. If a check fails, read its line, fix the cause and run it again.

Protocol versions: new and older clients

The SDK pinned here implements the current specification (2026-07-28), where a client discovers the server with server/discover and every request carries its own protocol version. It still serves older clients (2025-11-25 and earlier), which start with the initialize handshake, on the same endpoint. The verifier tries both. Do not assume every host already uses the new revision; some do not yet.

From practice to a remote server

This lab is safe because nothing outside your computer can reach it. Offering it to others needs, at least:

  • HTTPS, with the server behind a proxy you control.
  • Authorization as an OAuth 2.1 resource server: publish protected resource metadata, accept only tokens issued for this server (check the audience), and never forward a client's token to the API. Lesson 13 builds this.
  • Least privilege for the server's own credentials to the API.
  • Logs and limits: who called which tool, and rate limits on actions that change data.

Practice

  1. Add a fourth, read-only tool low_stock(threshold) that lists items below a threshold, with threshold limited to 1–100. Add one check for it to verify_client.py.
  2. Look at the admin DELETE. Write two sentences for a colleague explaining why it is not a tool.
  3. Change reserve_stock so that quantities above 5 are refused with a clear tool error. Run the verifier.

Check your result: ./run.sh verify still ends with all checks passed, your new check passes, and the tools list still has no delete.

Check your understanding

  1. Why does this lesson hand-write three tools instead of converting every endpoint?
  2. What does binding to 127.0.0.1 protect against, and what does it not protect against?
  3. A client sends a bearer token to your server. May the server pass it on to the API?

Answers. 1. Every tool is an action the model may take; a short, named, validated list is safer and easier for the model to use correctly. 2. It keeps other machines from reaching the server; it does not authenticate anyone on your own computer, which is why the Host and Origin checks are also on. 3. No. Token passthrough is forbidden: the server accepts only tokens issued for itself and uses its own credentials upstream.