From an existing API to MCP, safely — Lab code (L11)
MCP Engineering course · M2
Module 2 · MCP Engineering · Turning Point Academy · Updated 26 November 2026
This replaces an earlier version. The earlier guide used FastAPI-MCP withpip install "fastapi-mcp>=0.3",mount()anduvicorn --host 0.0.0.0. Installed today, that command pulls in version 2 of the official MCP SDK and the example crashes with aTypeError;mount()serves the deprecated SSE transport; and0.0.0.0exposes an unauthenticated server to every network your computer joins. Do not use it. If you ran it, stop that server (Ctrl+C in its terminal). Keep any work of your own and use a new, separate folder for this lab; delete the old lab files only if you choose to and they hold nothing you need.
This guide is the code of the lesson's lab, explained. The same files, with the lock file, are in Lab files (ZIP) (lab-l11.zip) in the lesson's links. The lab was built and run on 26 November 2026: ./run.sh verify passed all 22 checks.
What you build
- A small "existing" REST API (
inventory_api.py): a demo inventory with fake data. It has an adminDELETEthat must not become a tool. - An MCP server (
mcp_server.py) with the official Python SDK, exposing three hand-picked tools:search_items,get_itemandreserve_stock. - A verifier (
verify_client.py) that starts both services on your machine and checks 22 things with the official SDK client.
Why hand-written tools instead of converting every endpoint automatically: every tool is an action a model may take, so the list should be short, well named and validated. The admin delete stays out.
Versions (exact)
| Item | Version |
|---|---|
| Python | 3.12 |
mcp (official MCP Python SDK; MCPServer, formerly FastMCP) | 2.3.0 |
fastapi | 0.165.0 |
uvicorn | 0.54.0 |
httpx | 0.28.1 |
uv.lock (in the ZIP) pins every transitive dependency with hashes. uv sync --locked refuses to run if the lock and pyproject.toml disagree. A pin is an exact version; >= is only a minimum.
Run it
You need uv. Everything installs into the lab folder; nothing is installed globally.
./run.sh verify # installs the locked dependencies, starts both services on 127.0.0.1, runs every check
./run.sh serve # API on 127.0.0.1:8001, MCP endpoint at http://127.0.0.1:8000/mcp
Expected end of verify: ALL CHECKS PASSED (22).
To try it from Claude Code while serve runs:
claude mcp add --transport http demo-inventory http://127.0.0.1:8000/mcp
If you use the MCP Inspector, pin a patched release: npx @modelcontextprotocol/inspector@2.16.0 (it needs Node ^22.23.4 || ^24.22.1 || >=26.12.1). Keep its defaults: local only, random access token. Never set DANGEROUSLY_OMIT_AUTH or DANGEROUSLY_BIND_ALL_INTERFACES.
pyproject.toml
[project]
name = "lab-l11-inventory-mcp"
version = "1.0.0"
description = "MCP Engineering L11 lab: wrap an existing HTTP API as curated MCP tools (official Python SDK, mcp 2.x)"
requires-python = "==3.12.*"
# Exact pins for direct dependencies; uv.lock pins every transitive dependency with hashes.
dependencies = [
"mcp==2.3.0",
"fastapi==0.165.0",
"uvicorn==0.54.0",
"httpx==0.28.1",
]
[tool.uv]
package = false
run.sh
#!/usr/bin/env bash
# Lab L11 runner. Everything stays on 127.0.0.1. Requires uv (https://docs.astral.sh/uv/).
# ./run.sh verify -> install the locked deps into .venv and run the scripted end-to-end check
# ./run.sh serve -> start the demo API (8001) and the MCP server (8000) in the foreground
set -euo pipefail
cd "$(dirname "$0")"
uv sync --locked --quiet # exact versions + hashes from uv.lock; fails if the lock is stale
.venv/bin/python port_preflight.py # refuses (exit 3) if 8000 or 8001 is busy; never stops other programs
case "${1:-verify}" in
verify)
exec .venv/bin/python verify_client.py ;;
serve)
.venv/bin/python -m uvicorn inventory_api:app --host 127.0.0.1 --port 8001 --log-level warning &
API_PID=$!
trap 'kill $API_PID 2>/dev/null' EXIT
echo "MCP endpoint: http://127.0.0.1:8000/mcp (Ctrl+C to stop)"
.venv/bin/python mcp_server.py ;;
*) echo "usage: $0 [verify|serve]"; exit 2 ;;
esac
port_preflight.py — refuse to start if a lab port is busy
The lab always uses 127.0.0.1:8001 and 127.0.0.1:8000. If another program already holds one of them, run.sh stops before starting anything and names the busy port. It never stops the other program.
"""Fail-closed check that the lab's fixed loopback ports are free.
The lab always uses 127.0.0.1:8001 (API) and 127.0.0.1:8000 (MCP). If another
program already holds one of them, a check could silently talk to that program
instead of the lab. This script never stops or signals the other program: it
only refuses to start and tells you which port is busy.
Usage: python port_preflight.py (exit 0 = both free, exit 3 = a port is busy)
"""
from __future__ import annotations
import socket
import sys
LAB_PORTS = {8001: "inventory API", 8000: "MCP server"}
def busy_ports(ports=LAB_PORTS) -> list[int]:
busy = []
for port in ports:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(("127.0.0.1", port))
except OSError:
busy.append(port)
return busy
def main() -> int:
busy = busy_ports()
if not busy:
return 0
for port in busy:
print(f"STOP: 127.0.0.1:{port} ({LAB_PORTS[port]}) is already in use by another program.", file=sys.stderr)
print("Nothing was started and nothing was stopped. Close that program (or wait for the other lab run "
"to finish) and run this again.", file=sys.stderr)
return 3
if __name__ == "__main__":
sys.exit(main())
inventory_api.py — the "existing" API
Fake data only. The DELETE endpoint exists to show what not to expose.
"""The "existing API": a tiny synthetic inventory service built with FastAPI.
Everything here is fake demo data. It stands in for the REST API your company
already runs. It has nothing to do with MCP.
It deliberately includes an admin endpoint (DELETE /items/{sku}) that the MCP
server must NOT expose to a model: wrapping an API means choosing a small,
safe subset of operations, not mirroring every endpoint.
Run (loopback only): uvicorn inventory_api:app --host 127.0.0.1 --port 8001
"""
from __future__ import annotations
import threading
from typing import Annotated, Literal
from fastapi import FastAPI, HTTPException, Path, Query
from pydantic import BaseModel, Field
SKU_PATTERN = r"^[A-Z]{3}-\d{4}$"
Category = Literal["hardware", "electronics", "office"]
class Item(BaseModel):
sku: str
name: str
category: Category
quantity: int
unit_price_usd: float
class ReserveRequest(BaseModel):
quantity: int = Field(ge=1, le=10)
class Reservation(BaseModel):
sku: str
reserved: int
remaining: int
# Synthetic data only. No real products, people or prices.
_SEED: list[Item] = [
Item(sku="HWD-0001", name="Demo hex bolt M6 (box of 100)", category="hardware", quantity=40, unit_price_usd=7.50),
Item(sku="HWD-0002", name="Demo wood screw 4x40 (box of 200)", category="hardware", quantity=0, unit_price_usd=5.25),
Item(sku="ELC-0001", name="Demo USB-C cable 1 m", category="electronics", quantity=120, unit_price_usd=4.99),
Item(sku="ELC-0002", name="Demo 9V battery", category="electronics", quantity=8, unit_price_usd=2.10),
Item(sku="OFF-0001", name="Demo A4 paper ream", category="office", quantity=55, unit_price_usd=6.00),
]
_lock = threading.Lock()
_items: dict[str, Item] = {item.sku: item.model_copy() for item in _SEED}
app = FastAPI(title="Demo Inventory API", version="1.0.0")
SkuPath = Annotated[str, Path(pattern=SKU_PATTERN, description="SKU such as ELC-0001")]
@app.get("/items", operation_id="list_items")
def list_items(
category: Category | None = None,
in_stock_only: bool = False,
limit: Annotated[int, Query(ge=1, le=50)] = 20,
) -> list[Item]:
"""List items, optionally filtered by category and stock."""
with _lock:
items = list(_items.values())
if category is not None:
items = [i for i in items if i.category == category]
if in_stock_only:
items = [i for i in items if i.quantity > 0]
return items[:limit]
@app.get("/items/{sku}", operation_id="get_item")
def get_item(sku: SkuPath) -> Item:
"""Return one item by SKU."""
with _lock:
item = _items.get(sku)
if item is None:
raise HTTPException(status_code=404, detail="item not found")
return item
@app.post("/items/{sku}/reserve", operation_id="reserve_item")
def reserve_item(sku: SkuPath, body: ReserveRequest) -> Reservation:
"""Reserve stock for an order (decrements quantity)."""
with _lock:
item = _items.get(sku)
if item is None:
raise HTTPException(status_code=404, detail="item not found")
if body.quantity > item.quantity:
raise HTTPException(status_code=409, detail=f"only {item.quantity} in stock")
item.quantity -= body.quantity
return Reservation(sku=sku, reserved=body.quantity, remaining=item.quantity)
@app.delete("/items/{sku}", operation_id="delete_item")
def delete_item(sku: SkuPath) -> dict[str, str]:
"""ADMIN ONLY: remove an item permanently. Intentionally NOT exposed as an MCP tool."""
with _lock:
if _items.pop(sku, None) is None:
raise HTTPException(status_code=404, detail="item not found")
return {"deleted": sku}
mcp_server.py — the MCP server
Read the docstring first: it lists the design choices.
"""MCP server that wraps the existing inventory API with three curated tools.
Official MCP Python SDK (mcp==2.3.0, `MCPServer`, formerly `FastMCP`).
Transport: Streamable HTTP at http://127.0.0.1:8000/mcp.
Design choices you should copy:
* Only 3 hand-picked operations become tools. DELETE /items/{sku} is NOT exposed.
* Every argument is validated (types, regex, ranges) before any HTTP call.
* The upstream API URL is fixed by the operator and must be loopback here:
the model can never choose which host the server calls (no SSRF).
* No client token is ever forwarded upstream (no token passthrough).
* Binds 127.0.0.1 and keeps the SDK's DNS-rebinding protection (Host/Origin checks) on.
Run: python mcp_server.py (expects inventory_api on 127.0.0.1:8001)
"""
from __future__ import annotations
import os
from typing import Annotated, Literal
from urllib.parse import urlsplit
import httpx
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from mcp_types import ToolAnnotations
from pydantic import BaseModel, Field
LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1"}
SKU_PATTERN = r"^[A-Z]{3}-\d{4}$"
MCP_HOST = "127.0.0.1"
MCP_PORT = int(os.environ.get("LAB_MCP_PORT", "8000"))
def _upstream_base_url() -> str:
"""Operator-configured upstream URL. Restricted to loopback in this lab."""
url = os.environ.get("INVENTORY_API_URL", "http://127.0.0.1:8001")
parts = urlsplit(url)
if parts.scheme != "http" or parts.hostname not in LOOPBACK_HOSTS:
raise SystemExit(f"Refusing upstream {url!r}: this lab only calls a loopback API.")
return url.rstrip("/")
UPSTREAM = _upstream_base_url()
class Item(BaseModel):
sku: str
name: str
category: str
quantity: int
unit_price_usd: float
class ItemList(BaseModel):
items: list[Item]
count: int
class Reservation(BaseModel):
sku: str
reserved: int
remaining: int
mcp = MCPServer(
"demo-inventory",
instructions="Read-mostly access to a DEMO inventory with synthetic data. Reserving stock changes state.",
version="1.0.0",
)
async def _call_api(
method: str, path: str, *, params: dict | None = None, json: dict | None = None
) -> httpx.Response:
# A fresh client per call keeps the example simple; no auth header is sent upstream.
async with httpx.AsyncClient(base_url=UPSTREAM, timeout=5.0, follow_redirects=False) as client:
try:
return await client.request(method, path, params=params, json=json)
except httpx.HTTPError as exc:
raise ToolError("The inventory API is unavailable. Try again later.") from exc
def _raise_for_upstream(resp: httpx.Response) -> None:
"""Translate upstream errors into short, safe messages for the model."""
if resp.status_code == 404:
raise ToolError("No item with that SKU.")
if resp.status_code == 409:
raise ToolError(f"Cannot reserve: {resp.json().get('detail', 'insufficient stock')}.")
if resp.status_code >= 400:
raise ToolError(f"Inventory API rejected the request (HTTP {resp.status_code}).")
@mcp.tool(
name="search_items",
title="Search inventory",
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
async def search_items(
category: Annotated[
Literal["hardware", "electronics", "office"] | None, Field(description="Optional category filter")
] = None,
in_stock_only: Annotated[bool, Field(description="Only items with quantity > 0")] = False,
limit: Annotated[int, Field(ge=1, le=20, description="Max items to return (1-20)")] = 10,
) -> ItemList:
"""Search the demo inventory by category and stock. Returns SKU, name, quantity and price."""
params = {"in_stock_only": str(in_stock_only).lower(), "limit": limit}
if category is not None:
params["category"] = category
resp = await _call_api("GET", "/items", params=params)
_raise_for_upstream(resp)
items = [Item.model_validate(i) for i in resp.json()]
return ItemList(items=items, count=len(items))
@mcp.tool(
name="get_item",
title="Get item by SKU",
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
async def get_item(
sku: Annotated[str, Field(pattern=SKU_PATTERN, description="SKU like ELC-0001 (3 capital letters, dash, 4 digits)")],
) -> Item:
"""Get one inventory item, including current stock, by its SKU."""
resp = await _call_api("GET", f"/items/{sku}")
_raise_for_upstream(resp)
return Item.model_validate(resp.json())
@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=SKU_PATTERN, 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())
def main() -> None:
# Explicit settings (the SDK also enables these automatically when host is loopback).
security = TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=[f"127.0.0.1:{MCP_PORT}", f"localhost:{MCP_PORT}"],
allowed_origins=[f"http://127.0.0.1:{MCP_PORT}", f"http://localhost:{MCP_PORT}"],
)
mcp.run(
"streamable-http",
host=MCP_HOST, # never 0.0.0.0 without TLS + OAuth in front
port=MCP_PORT,
streamable_http_path="/mcp",
transport_security=security,
)
if __name__ == "__main__":
main()
What to notice:
- Validation in the signature. Patterns and ranges become the tool's input schema, and the SDK rejects bad arguments server-side before your code runs.
../admin, a lowercase SKU andquantity=500never reach the API. - Typed results. Returning a model gives structured output a client can check.
- Annotations are hints, not enforcement. Your validation is the enforcement.
- Safe errors. Upstream 404 and 409 become short tool errors, not stack traces.
- No SSRF. The API address comes from the operator and must be loopback in this lab; the model never chooses a host.
- No token passthrough. Nothing from the incoming request is forwarded to the API.
- Loopback and Host/Origin checks. The server binds
127.0.0.1and refuses a foreignOrigin(403) orHost(421).
verify_client.py — the checks
"""End-to-end verification with the official MCP Python SDK client.
Starts the inventory API and the MCP server as local subprocesses (loopback only),
then checks, with assertions:
1. A modern client (mode="auto") negotiates protocol 2026-07-28 via server/discover.
2. Exactly the 3 curated tools are listed; the admin DELETE is not a tool.
3. Each tool works and returns the expected structured content.
4. Invalid input and upstream errors come back as is_error results, not crashes.
5. A legacy client (mode="legacy", initialize handshake) still works on the same endpoint.
6. DNS-rebinding protection: a foreign Origin gets 403, a foreign Host gets 421.
7. Nothing listens on a non-loopback interface.
Exit code 0 means every check passed.
"""
from __future__ import annotations
import asyncio
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
import httpx
import mcp_types
from mcp import Client
HERE = Path(__file__).resolve().parent
API_PORT = 8001
MCP_PORT = 8000
MCP_URL = f"http://127.0.0.1:{MCP_PORT}/mcp"
EXPECTED_TOOLS = {"search_items", "get_item", "reserve_stock"}
passed = 0
def check(condition: bool, label: str) -> None:
global passed
if not condition:
raise AssertionError(f"FAIL: {label}")
passed += 1
print(f" PASS {label}")
def wait_for_port(port: int, timeout: float = 20.0) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
with socket.socket() as s:
if s.connect_ex(("127.0.0.1", port)) == 0:
return
time.sleep(0.2)
raise RuntimeError(f"port {port} did not open")
def lan_ip() -> str | None:
"""Best-effort non-loopback local address (no packets are sent)."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("192.0.2.1", 9)) # TEST-NET-1, UDP connect sends nothing
ip = s.getsockname()[0]
return None if ip.startswith("127.") else ip
except OSError:
return None
def start_services() -> list[subprocess.Popen]:
from port_preflight import busy_ports # fail closed if 8000/8001 are taken
if busy_ports():
raise SystemExit("STOP: a lab port (8000 or 8001) is already in use; run port_preflight.py for details. Nothing was started.")
env = {**os.environ, "INVENTORY_API_URL": f"http://127.0.0.1:{API_PORT}", "LAB_MCP_PORT": str(MCP_PORT)}
api = subprocess.Popen(
[sys.executable, "-m", "uvicorn", "inventory_api:app", "--host", "127.0.0.1", "--port", str(API_PORT),
"--log-level", "warning"],
cwd=HERE, env=env,
)
server = subprocess.Popen([sys.executable, "mcp_server.py"], cwd=HERE, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wait_for_port(API_PORT)
wait_for_port(MCP_PORT)
return [api, server]
async def modern_checks() -> None:
print("\n[1-4] Modern client (mode='auto')")
async with Client(MCP_URL) as client:
print(f" negotiated protocol version: {client.protocol_version}")
check(client.protocol_version == "2026-07-28", "negotiated protocol 2026-07-28")
info = client.server_info
print(f" server_info: {info.name if info else None} {info.version if info else ''}")
tools = (await client.list_tools()).tools
names = {t.name for t in tools}
print(f" tools: {sorted(names)}")
check(names == EXPECTED_TOOLS, "exactly the 3 curated tools are exposed")
check(not any("delete" in n for n in names), "admin delete endpoint is NOT a tool")
by_name = {t.name: t for t in tools}
check(by_name["get_item"].input_schema["properties"]["sku"].get("pattern") == r"^[A-Z]{3}-\d{4}$",
"get_item input schema carries the SKU regex")
check(by_name["search_items"].annotations is not None and by_name["search_items"].annotations.read_only_hint is True,
"search_items annotated read-only")
check(by_name["reserve_stock"].output_schema is not None, "reserve_stock declares an output schema")
r = await client.call_tool("search_items", {"category": "electronics", "in_stock_only": True})
print(f" search_items -> {r.structured_content}")
check(not r.is_error and r.structured_content["count"] == 2, "search_items returns 2 electronics in stock")
r = await client.call_tool("get_item", {"sku": "ELC-0002"})
print(f" get_item -> {r.structured_content}")
check(not r.is_error and r.structured_content["quantity"] == 8, "get_item ELC-0002 has quantity 8")
r = await client.call_tool("reserve_stock", {"sku": "ELC-0002", "quantity": 3})
print(f" reserve_stock -> {r.structured_content}")
check(not r.is_error and r.structured_content == {"sku": "ELC-0002", "reserved": 3, "remaining": 5},
"reserve_stock reserves 3, leaves 5")
r = await client.call_tool("get_item", {"sku": "ELC-0002"})
check(r.structured_content["quantity"] == 5, "state change visible through get_item")
print(" -- negative cases --")
for args, label in [
({"sku": "../admin"}, "path-traversal-like SKU rejected by schema"),
({"sku": "elc-0001"}, "lowercase SKU rejected by schema"),
]:
r = await client.call_tool("get_item", args)
print(f" get_item {args} -> is_error={r.is_error}: {r.content[0].text[:90]!r}")
check(r.is_error, label)
r = await client.call_tool("reserve_stock", {"sku": "ELC-0001", "quantity": 500})
print(f" reserve_stock qty=500 -> is_error={r.is_error}: {r.content[0].text[:90]!r}")
check(r.is_error, "quantity above 10 rejected by schema")
r = await client.call_tool("reserve_stock", {"sku": "HWD-0002", "quantity": 1})
print(f" reserve_stock out-of-stock -> is_error={r.is_error}: {r.content[0].text!r}")
check(r.is_error and "Cannot reserve" in r.content[0].text, "upstream 409 mapped to a safe tool error")
r = await client.call_tool("get_item", {"sku": "ZZZ-9999"})
print(f" get_item unknown -> is_error={r.is_error}: {r.content[0].text!r}")
check(r.is_error and r.content[0].text.endswith("No item with that SKU."), "upstream 404 mapped to a safe tool error")
async def legacy_checks() -> None:
print("\n[5] Legacy client (mode='legacy', initialize handshake)")
async with Client(MCP_URL, mode="legacy") as client:
print(f" negotiated protocol version: {client.protocol_version}")
check(client.protocol_version == mcp_types.version.LATEST_HANDSHAKE_VERSION,
f"legacy handshake negotiates {mcp_types.version.LATEST_HANDSHAKE_VERSION}")
r = await client.call_tool("get_item", {"sku": "OFF-0001"})
check(not r.is_error and r.structured_content["sku"] == "OFF-0001", "legacy client can call get_item")
def http_security_checks() -> None:
print("\n[6-7] Transport security (raw HTTP)")
meta = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}
body = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": meta}}
base_headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "server/discover"}
with httpx.Client(timeout=5.0) as http:
r = http.post(MCP_URL, json=body, headers={**base_headers, "Origin": f"http://127.0.0.1:{MCP_PORT}"})
print(f" control: allowed Origin -> HTTP {r.status_code}, supportedVersions="
f"{r.json().get('result', {}).get('supportedVersions')}")
check(r.status_code == 200, "control: well-formed request with allowed Origin accepted (200)")
r = http.post(MCP_URL, json=body, headers={**base_headers, "Origin": "http://evil.example"})
print(f" foreign Origin -> HTTP {r.status_code}")
check(r.status_code == 403, "foreign Origin rejected with 403")
r = http.post(MCP_URL, json=body, headers={**base_headers, "Host": "evil.example:8000"})
print(f" foreign Host -> HTTP {r.status_code}")
check(r.status_code == 421, "foreign Host rejected with 421")
ip = lan_ip()
if ip is None:
print(" (no non-loopback IPv4 address found; skipping LAN reachability check)")
return
for port in (MCP_PORT, API_PORT):
with socket.socket() as s:
s.settimeout(1.0)
reachable = s.connect_ex((ip, port)) == 0
check(not reachable, f"port {port} not reachable on LAN address (bound to loopback only)")
def main() -> int:
import importlib.metadata as md
print("Lab L11 verification")
print(f" python {sys.version.split()[0]} | mcp {md.version('mcp')} | fastapi {md.version('fastapi')} | "
f"uvicorn {md.version('uvicorn')} | httpx {md.version('httpx')}")
procs = start_services()
try:
asyncio.run(modern_checks())
asyncio.run(legacy_checks())
http_security_checks()
finally:
for p in procs:
p.terminate()
for p in procs:
p.wait(timeout=10)
print(f"\nALL CHECKS PASSED ({passed})")
return 0
if __name__ == "__main__":
sys.exit(main())
Protocol versions: new and older clients
mcp 2.3.0 implements the current specification (2026-07-28): a modern client discovers the server with server/discover, and every request carries its own protocol version. Older clients (2025-11-25 and earlier) use the initialize handshake; the server serves them on the same /mcp endpoint. The verifier tries both. Not every host supports the new revision yet.
Local practice vs remote production
This lab is safe because nothing outside your computer can reach it. Do not change 127.0.0.1 to 0.0.0.0 to share it. A remote deployment needs at least:
- HTTPS, behind a proxy you control.
- OAuth 2.1 authorization as a 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).
- Least privilege for the server's own credentials to the API.
- Logs and rate limits, especially on tools that change data.