Lab: Wrap a REST API as an MCP Server
Wrap a mock issue-tracker REST API as an MCP server with three task-level tools, typed output schemas, cursor pagination over a stable order, a resource template and actionable tool errors, first with the official Python SDK and then by hand with the standard library, and compare both on the wire.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start the mock tracker API
- Step 2: A client that shapes answers for the model
- Step 3 (Track A): The server on the official SDK
- Step 4 (Track B): The same contract by hand
- Step 5: Compare both servers on the wire
- Check your understanding
- Apply it
- Review prompt
Lessons of Building MCP Servers
- A First Server with an Official SDK Worked example · 20 min
- Designing Tools for Agents, Not for APIs Concept · 15 min
- Lab: Wrap a REST API as an MCP Server Lab · 30 min
- Contract Tests and the Inspector Lab · 20 min
- Remote Deployment with OAuth Authorization Worked example · 25 min
- Check: Server Design Review Knowledge check · 8 questions
What you will learn
- Implement an MCP server with an official SDK that exposes tools with input and output schemas, plus at least one resource.
- Design server tools for agents: a few task-level tools with concise, paginated, deterministically ordered output instead of one tool per API endpoint.
Prerequisites: MCP Fundamentals
01. Goal and setup
You will put an MCP server in front of a REST API, applying the design rules from Designing Tools for Agents. The API is a mock issue tracker that you run locally: it needs a bearer token, returns verbose 19-field records, sorts by "last updated" by default, and fails with an HTML 503 page for issue 666, so you can test error handling. The server exposes:
search_issues(state, label, limit, cursor): concise results, ordered by issue number, with an opaque cursor;get_issue(number): one issue with a short body excerpt;set_issue_state(number, state): a narrow write tool;- the resource template
issues://{number}: the full record, for a user to attach as context.
There are two tracks that expose the same contract. Track A uses the official Python SDK, which is what you would ship. Track B writes the JSON-RPC by hand with the standard library, so you can see what the SDK does for you. Lab 4 tests both.
You need: Python 3.12 or later (mcp 2.3.0 declares 3.10 or newer on PyPI, but 3.10 reached end of life in October 2026), curl, and for Track A the package mcp==2.3.0 (it implements MCP revision 2026-07-28). Track B needs nothing beyond Python. All commands run inside the tracker-lab folder with the virtual environment active.
tracker-lab/
├── tracker_api.py step 1: the mock REST API (stdlib)
├── tracker_client.py step 2: calls the API, shapes results (stdlib)
├── tracker_mcp.py step 3: Track A server (official SDK)
├── try_tracker.py step 3: in-memory SDK client
├── mini_schema.py step 4: small JSON Schema checker (stdlib)
├── stdio_server.py step 4: Track B server (stdlib)
├── wire.py step 5: tiny stdio client for both tracks
└── sdk_client.py step 5: the official SDK client, for either trackmkdir tracker-lab && cd tracker-lab
python3 -m venv .venv && source .venv/bin/activate
python -m pip install "mcp==2.3.0" # Track A only
export TRACKER_API_TOKEN=lab-only-token-not-a-secret02. Step 1: Start the mock tracker API
The mock serves 60 issues. GET /api/issues filters by state and label, sorts by updated_at unless you pass sort=number, and supports after (only numbers greater than this) and per_page. PATCH /api/issues/{n} changes the state. Every request needs Authorization: Bearer <TRACKER_API_TOKEN>.
"""Mock issue-tracker REST API (stdlib only). Verbose on purpose, like real APIs."""
import json
import os
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
TOKEN = os.environ["TRACKER_API_TOKEN"] # the API refuses to start without it
LABELS = ["auth", "api", "ui", "export", "docs"]
PEOPLE = ["maya", "li", "sam", None]
def make_issue(n: int) -> dict:
who = PEOPLE[n % 4]
return {
"id": f"0b7c{n:04d}-9f1e-4c55-8d3a-1a2b3c4d{n:04d}", # internal key
"node_id": f"I_kwDOAbc{n:05d}",
"number": n,
"title": f"Issue {n}: {LABELS[n % 5]} problem",
"body": f"Steps to reproduce issue {n}. " * 12,
"state": "closed" if n % 3 == 0 else "open",
"labels": [{"id": 9000 + n % 5, "name": LABELS[n % 5], "color": "d73a4a"}],
"assignee": None if who is None else {
"login": who, "id": 4000 + n % 4, "type": "User", "site_admin": False,
"avatar_url": f"https://avatars.example/{who}.png"},
"comments": n % 4,
"created_at": f"2026-09-{1 + n % 28:02d}T09:00:00Z",
"updated_at": f"2026-10-{1 + n % 28:02d}T17:30:00Z",
"closed_at": None, "locked": False, "milestone": None,
"author_association": "MEMBER", "reactions": {"+1": n % 5, "-1": 0},
"url": f"https://tracker.example/api/issues/{n}",
"html_url": f"https://tracker.example/issues/{n}",
"timeline_url": f"https://tracker.example/api/issues/{n}/timeline",
}
ISSUES = {n: make_issue(n) for n in range(101, 161)} # 60 issues
class Handler(BaseHTTPRequestHandler):
def _send(self, status: int, body: object, ctype="application/json") -> None:
data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def _authorised(self) -> bool:
if self.headers.get("Authorization") == f"Bearer {TOKEN}":
return True
self._send(401, {"message": "Bad credentials"})
return False
def do_GET(self) -> None:
if not self._authorised():
return
url = urlsplit(self.path)
q = {k: v[0] for k, v in parse_qs(url.query).items()}
if url.path == "/api/issues":
items = [i for i in ISSUES.values()
if q.get("state", "open") in ("all", i["state"])
and q.get("label") in (None, i["labels"][0]["name"])]
if q.get("sort") == "number":
items.sort(key=lambda i: i["number"])
else: # default: most recently updated first, which shifts over time
items.sort(key=lambda i: i["updated_at"], reverse=True)
if "after" in q:
items = [i for i in items if i["number"] > int(q["after"])]
per_page = min(int(q.get("per_page", 30)), 100)
self._send(200, items[:per_page])
return
match = re.fullmatch(r"/api/issues/(\d+)", url.path)
if match and int(match[1]) == 666: # a broken upstream, for error tests
self._send(503, "<html><h1>Service Unavailable</h1></html>", "text/html")
elif match and int(match[1]) in ISSUES:
self._send(200, ISSUES[int(match[1])])
else:
self._send(404, {"message": "Not Found"})
def do_PATCH(self) -> None:
if not self._authorised():
return
match = re.fullmatch(r"/api/issues/(\d+)", urlsplit(self.path).path)
if not match or int(match[1]) not in ISSUES:
self._send(404, {"message": "Not Found"})
return
length = int(self.headers.get("Content-Length", 0))
change = json.loads(self.rfile.read(length) or b"{}")
if change.get("state") not in ("open", "closed"):
self._send(422, {"message": "state must be open or closed"})
return
ISSUES[int(match[1])]["state"] = change["state"]
self._send(200, ISSUES[int(match[1])])
def log_message(self, fmt: str, *args: object) -> None:
pass # keep the terminal quiet; real services log to stderr
if __name__ == "__main__":
port = int(os.environ.get("TRACKER_API_PORT", "8081"))
print(f"tracker API on http://127.0.0.1:{port}/api", flush=True)
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()python tracker_api.py &
sleep 1 # give the API a moment to start
curl -s -H "Authorization: Bearer $TRACKER_API_TOKEN" \
http://127.0.0.1:8081/api/issues/101 | python -m json.tool | cut -c1-60 | head -7
curl -s http://127.0.0.1:8081/api/issues/101; echotracker API on http://127.0.0.1:8081/api
{
"id": "0b7c0101-9f1e-4c55-8d3a-1a2b3c4d0101",
"node_id": "I_kwDOAbc00101",
"number": 101,
"title": "Issue 101: api problem",
"body": "Steps to reproduce issue 101. Steps to reproduc
"state": "open",
{"message": "Bad credentials"}03. Step 2: A client that shapes answers for the model
Both tracks share one module that talks to the API. Keeping it free of MCP code means you can test it on its own and reuse it in either server.
"""Calls the tracker REST API and shapes answers for a model (stdlib only)."""
import base64
import json
import os
import urllib.error
import urllib.request
from urllib.parse import urlencode
BASE_URL = os.environ.get("TRACKER_API_URL", "http://127.0.0.1:8081/api")
TOKEN = os.environ["TRACKER_API_TOKEN"] # fail fast at start-up if it is missing
class TrackerError(Exception):
"""A failure the model should read; the message says what to do next."""
class NotFound(TrackerError):
"""The issue does not exist."""
def _request(method: str, path: str, body: dict | None = None) -> object:
req = urllib.request.Request(
BASE_URL + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return json.load(resp)
except urllib.error.HTTPError as exc:
if exc.code == 404:
raise NotFound("Not found. Use search_issues to find valid "
"issue numbers.") from None
if exc.code in (401, 403):
raise TrackerError("The tracker rejected this server's credentials. "
"This is a configuration problem; retrying "
"will not help.") from None
if exc.code == 422:
raise TrackerError(f"The tracker refused the change: "
f"{json.load(exc).get('message')}") from None
raise TrackerError(f"The tracker is unavailable (HTTP {exc.code}). "
"Try again in a minute.") from None
except (urllib.error.URLError, TimeoutError):
raise TrackerError("The tracker did not answer in 10 s. "
"Try again in a minute.") from None
def summary(issue: dict) -> dict:
"""The fields an agent needs to pick its next step, IDs included."""
who = issue["assignee"]
return {"number": issue["number"], "title": issue["title"],
"state": issue["state"], "label": issue["labels"][0]["name"],
"assignee": who["login"] if who else None,
"comments": issue["comments"]}
def _cursor(after: int, state: str, label: str | None) -> str:
raw = json.dumps({"after": after, "state": state, "label": label})
return base64.urlsafe_b64encode(raw.encode()).decode()
def _after(cursor: str | None, state: str, label: str | None) -> int:
if cursor is None:
return 0
try:
data = json.loads(base64.urlsafe_b64decode(cursor.encode()))
if (data["state"], data["label"]) != (state, label):
raise ValueError("cursor belongs to another search")
return int(data["after"])
except (ValueError, KeyError, TypeError):
raise TrackerError("Invalid cursor. Start again without one, or reuse "
"the same state and label.") from None
def search(state: str, label: str | None, limit: int, cursor: str | None) -> dict:
after = _after(cursor, state, label)
query = {"state": state, "sort": "number", "after": after,
"per_page": limit + 1} # one extra row tells us if a page follows
if label:
query["label"] = label
rows = _request("GET", "/issues?" + urlencode(query))
page = [summary(i) for i in rows[:limit]]
more = len(rows) > limit
return {
"issues": page,
"next_cursor": _cursor(page[-1]["number"], state, label) if more else None,
"note": (f"Showing {len(page)} issues. More match: call again with "
"cursor=next_cursor." if more else f"All {len(page)} shown."),
}
def get(number: int) -> dict:
issue = _request("GET", f"/issues/{int(number)}")
return summary(issue) | {"body_excerpt": issue["body"][:160],
"url": issue["html_url"]}
def raw(number: int) -> dict:
return _request("GET", f"/issues/{int(number)}")
def set_state(number: int, state: str) -> dict:
return summary(_request("PATCH", f"/issues/{int(number)}", {"state": state}))The design decisions, in order of importance:
- The secret stays in the environment. The token is read from
TRACKER_API_TOKENat import, so a missing variable stops the server at start-up instead of at the first call. It is never written to a result or a log. The model never sees it, and the host passes it in through the server's environment. - Errors become instructions. 404 says to use
search_issues; 401 and 403 say this is a configuration problem that retrying will not fix; 422 passes on the API's validation message; 5xx, timeouts and connection failures say to try again later. The HTML body of the 503 is never parsed as JSON. - Concise but connected.
summary()keeps the issue number, which every follow-up tool needs, and resolves the assignee object to a login. - Keyset pagination.
search()asks the API forsort=number,after=<last number>and one row more thanlimit. The extra row reveals whether another page exists without a count query. The cursor is base64-encoded JSON that also records the filters, so a cursor reused with another label is rejected. - Input hygiene. Numbers are forced through
int()before they reach a URL, so a crafted value cannot add path segments; query strings are built withurlencode.
04. Step 3 (Track A): The server on the official SDK
"""Track A: the tracker as an MCP server on the official Python SDK (mcp 2.x)."""
import json
from typing import Annotated, Literal
from pydantic import BaseModel, Field
import tracker_client as api
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import (ResourceError, ResourceNotFoundError,
ToolError)
mcp = MCPServer("tracker", version="0.3.0")
class IssueSummary(BaseModel):
number: int
title: str
state: Literal["open", "closed"]
label: str
assignee: str | None
comments: int
class IssuePage(BaseModel):
issues: list[IssueSummary]
next_cursor: str | None = Field(description="Pass back to get the next page")
note: str
class IssueDetail(IssueSummary):
body_excerpt: str
url: str
@mcp.tool()
def search_issues(
state: Literal["open", "closed", "all"] = "open",
label: str | None = None,
limit: Annotated[int, Field(ge=1, le=50)] = 20,
cursor: str | None = None,
) -> IssuePage:
"""Find issues, ordered by number. Returns at most `limit` per call.
If next_cursor is set, call again with the same state and label and
cursor=next_cursor for the next page.
"""
try:
return IssuePage(**api.search(state, label, limit, cursor))
except api.TrackerError as exc:
raise ToolError(str(exc)) from None
@mcp.tool()
def get_issue(number: Annotated[int, Field(ge=1)]) -> IssueDetail:
"""One issue with a short body excerpt. Use search_issues to find numbers."""
try:
return IssueDetail(**api.get(number))
except api.TrackerError as exc:
raise ToolError(str(exc)) from None
@mcp.tool()
def set_issue_state(
number: Annotated[int, Field(ge=1)], state: Literal["open", "closed"]
) -> IssueSummary:
"""Open or close one issue. Changes data: confirm with the user first."""
try:
return IssueSummary(**api.set_state(number, state))
except api.TrackerError as exc:
raise ToolError(str(exc)) from None
@mcp.resource("issues://{number}", mime_type="application/json")
def issue_record(number: int) -> str:
"""The full tracker record of one issue, for a user to attach as context."""
try:
return json.dumps(api.raw(number))
except api.NotFound:
raise ResourceNotFoundError(f"No issue #{number}") from None
except api.TrackerError as exc:
raise ResourceError(str(exc)) from None
if __name__ == "__main__":
mcp.run() # stdioEvery tool returns a Pydantic model, so each one has an output schema and returns structured content with a text copy. Literal types become enums in the input schema, and Field(ge=1, le=50) bounds limit, so a model asking for 500 results gets a tool error instead of a flood. Every TrackerError is re-raised as ToolError, which sets isError: true. For the resource template, a missing issue becomes ResourceNotFoundError (JSON-RPC error -32602) and other failures become ResourceError.
The description of set_issue_state tells the model to confirm with the user first. Hosts usually also ask the user before running a tool, but the wording helps the model choose well. Try the server in memory:
"""Exercise the Track A server in memory, through the SDK's Client."""
import asyncio
import json
import textwrap
from mcp import Client
from tracker_mcp import mcp
def show(label: str, value: object) -> None:
text = value if isinstance(value, str) else json.dumps(value)
print(textwrap.fill(f"{label} {text}", 80, subsequent_indent=" "))
async def main() -> None:
async with Client(mcp) as client:
tools = (await client.list_tools()).tools
show("tools:", [t.name for t in tools])
page1 = await client.call_tool("search_issues", {"label": "auth", "limit": 3})
data = page1.structured_content
show("page 1:", [i["number"] for i in data["issues"]])
show("note:", data["note"])
page2 = await client.call_tool(
"search_issues",
{"label": "auth", "limit": 3, "cursor": data["next_cursor"]})
show("page 2:", [i["number"] for i in page2.structured_content["issues"]])
show("first item:", page1.structured_content["issues"][0])
for number in (99999, 666):
bad = await client.call_tool("get_issue", {"number": number})
show(f"get_issue {number} isError={bad.is_error}:", bad.content[0].text)
res = await client.read_resource("issues://101")
raw = res.contents[0].text
tool = await client.call_tool("get_issue", {"number": 101})
lean = json.dumps(tool.structured_content)
show("issues://101 (raw):", f"{len(json.loads(raw))} fields, {len(raw)} bytes")
show("get_issue 101:", f"{len(json.loads(lean))} fields, {len(lean)} bytes")
asyncio.run(main())python try_tracker.py 2>server.errtools: ["search_issues", "get_issue", "set_issue_state"]
page 1: [110, 115, 125]
note: Showing 3 issues. More match: call again with cursor=next_cursor.
page 2: [130, 140, 145]
first item: {"number": 110, "title": "Issue 110: auth problem", "state": "open",
"label": "auth", "assignee": "sam", "comments": 2}
get_issue 99999 isError=True: Error executing tool get_issue: Not found. Use
search_issues to find valid issue numbers.
get_issue 666 isError=True: Error executing tool get_issue: The tracker is
unavailable (HTTP 503). Try again in a minute.
issues://101 (raw): 19 fields, 1077 bytes
get_issue 101: 8 fields, 341 bytesPages 1 and 2 continue without a gap or a repeat (open auth issues are 110, 115, 125, 130, 140 and so on). Both failures are tool errors with a next step, and the raw record is about three times the size of what the tool returns. These sizes are measured on this mock; real APIs differ, so measure yours.
05. Step 4 (Track B): The same contract by hand
Without an SDK you write the schemas, validate arguments and frame every message yourself. Start with a small schema checker. It covers only the keywords these schemas use; for production, use a complete 2020-12 validator such as jsonschema.Draft202012Validator, which is installed with mcp.
"""A small JSON Schema checker for the keywords this lab uses (stdlib only).
Production code should use a full 2020-12 validator such as
jsonschema.Draft202012Validator (installed with mcp 2.x).
"""
TYPES = {"object": dict, "array": list, "string": str, "boolean": bool,
"null": type(None), "integer": int, "number": (int, float)}
def _is(value: object, name: str) -> bool:
if name in ("integer", "number") and isinstance(value, bool):
return False
return isinstance(value, TYPES[name])
def errors(schema: dict, value: object, root: dict | None = None,
path: str = "$") -> list[str]:
root = root or schema
if "$ref" in schema: # local references only, e.g. #/$defs/IssueSummary
target = root
for part in schema["$ref"].removeprefix("#/").split("/"):
target = target[part]
return errors(target, value, root, path)
if "anyOf" in schema:
if all(errors(s, value, root, path) for s in schema["anyOf"]):
return [f"{path}: matches no allowed shape"]
return []
found = []
kinds = schema.get("type")
if kinds and not any(_is(value, k) for k in
(kinds if isinstance(kinds, list) else [kinds])):
return [f"{path}: expected {kinds}, got {type(value).__name__}"]
if "enum" in schema and value not in schema["enum"]:
found.append(f"{path}: {value!r} is not one of {schema['enum']}")
if "minimum" in schema and value < schema["minimum"]:
found.append(f"{path}: {value} is below {schema['minimum']}")
if "maximum" in schema and value > schema["maximum"]:
found.append(f"{path}: {value} is above {schema['maximum']}")
if isinstance(value, dict):
props = schema.get("properties", {})
found += [f"{path}: missing {k}" for k in schema.get("required", [])
if k not in value]
for key, item in value.items():
if key in props:
found += errors(props[key], item, root, f"{path}.{key}")
elif schema.get("additionalProperties") is False:
found.append(f"{path}: unexpected field {key}")
if isinstance(value, list) and "items" in schema:
for i, item in enumerate(value):
found += errors(schema["items"], item, root, f"{path}[{i}]")
return found"""Track B: the same server by hand, JSON-RPC over stdio (stdlib only).
Implements the parts of MCP 2026-07-28 this lab uses: server/discover,
tools/list, tools/call, resources/list, resources/templates/list and
resources/read. No pagination of the lists, subscriptions or prompts.
"""
import json
import logging
import re
import sys
import tracker_client as api
from mini_schema import errors
VERSION = "2026-07-28"
SERVER_INFO = {"name": "tracker-stdlib", "version": "0.3.0"}
log = logging.getLogger("tracker")
logging.basicConfig(stream=sys.stderr, level=logging.INFO) # never stdout
SUMMARY = {"type": "object", "required": ["number", "title", "state", "label",
"assignee", "comments"],
"properties": {"number": {"type": "integer"},
"title": {"type": "string"},
"state": {"enum": ["open", "closed"]},
"label": {"type": "string"},
"assignee": {"type": ["string", "null"]},
"comments": {"type": "integer"}}}
NUMBER = {"type": "integer", "minimum": 1}
TOOLS = [ # a fixed list, so tools/list is deterministic
{"name": "search_issues",
"description": "Find issues, ordered by number. Returns at most `limit` "
"per call. If next_cursor is set, call again with the same "
"state and label and cursor=next_cursor for the next page.",
"inputSchema": {"type": "object", "additionalProperties": False,
"properties": {
"state": {"enum": ["open", "closed", "all"],
"default": "open"},
"label": {"type": ["string", "null"]},
"limit": {"type": "integer", "minimum": 1,
"maximum": 50, "default": 20},
"cursor": {"type": ["string", "null"]}}},
"outputSchema": {"type": "object",
"required": ["issues", "next_cursor", "note"],
"properties": {"issues": {"type": "array", "items": SUMMARY},
"next_cursor": {"type": ["string", "null"]},
"note": {"type": "string"}}}},
{"name": "get_issue",
"description": "One issue with a short body excerpt. Use search_issues "
"to find numbers.",
"inputSchema": {"type": "object", "additionalProperties": False,
"required": ["number"], "properties": {"number": NUMBER}},
"outputSchema": SUMMARY | {
"required": SUMMARY["required"] + ["body_excerpt", "url"],
"properties": SUMMARY["properties"] | {"body_excerpt": {"type": "string"},
"url": {"type": "string"}}}},
{"name": "set_issue_state",
"description": "Open or close one issue. Changes data: confirm with the "
"user first.",
"inputSchema": {"type": "object", "additionalProperties": False,
"required": ["number", "state"],
"properties": {"number": NUMBER,
"state": {"enum": ["open", "closed"]}}},
"outputSchema": SUMMARY},
]
HANDLERS = {
"search_issues": lambda a: api.search(a.get("state", "open"), a.get("label"),
a.get("limit", 20), a.get("cursor")),
"get_issue": lambda a: api.get(a["number"]),
"set_issue_state": lambda a: api.set_state(a["number"], a["state"]),
}
# Discovery, list and read results are cacheable in 2026-07-28: ttlMs and
# cacheScope are required fields. Definitions are static and the same for
# every caller; issue records change, so reads are not cached.
STATIC = {"ttlMs": 60_000, "cacheScope": "public"}
FRESH = {"ttlMs": 0, "cacheScope": "private"}
TEMPLATE = {"uriTemplate": "issues://{number}", "name": "issue",
"description": "The full tracker record of one issue.",
"mimeType": "application/json"}
class RpcError(Exception):
def __init__(self, code: int, message: str, data: object = None):
super().__init__(message)
self.code, self.message, self.data = code, message, data
def call_tool(params: dict) -> dict:
tool = next((t for t in TOOLS if t["name"] == params.get("name")), None)
if tool is None: # unknown tool: a protocol error, not a tool result
raise RpcError(-32602, f"Unknown tool: {params.get('name')}")
args = params.get("arguments") or {}
problems = errors(tool["inputSchema"], args)
try:
if problems:
raise api.TrackerError("Invalid arguments: " + "; ".join(problems))
data = HANDLERS[tool["name"]](args)
except api.TrackerError as exc:
return {"content": [{"type": "text", "text": str(exc)}], "isError": True}
return {"content": [{"type": "text", "text": json.dumps(data, indent=2)}],
"structuredContent": data, "isError": False}
def read_resource(params: dict) -> dict:
uri = params.get("uri", "")
match = re.fullmatch(r"issues://(\d+)", uri)
try:
if not match:
raise api.NotFound(uri)
text = json.dumps(api.raw(int(match[1])))
except api.NotFound:
raise RpcError(-32602, "Resource not found", {"uri": uri}) from None
except api.TrackerError as exc:
raise RpcError(-32603, str(exc)) from None
return {"contents": [{"uri": uri, "mimeType": "application/json",
"text": text}]} | FRESH
METHODS = {
"server/discover": lambda p: STATIC | {
"supportedVersions": [VERSION],
"capabilities": {"tools": {}, "resources": {}}},
"tools/list": lambda p: STATIC | {"tools": TOOLS},
"tools/call": call_tool,
"resources/list": lambda p: STATIC | {"resources": []},
"resources/templates/list": lambda p: STATIC | {"resourceTemplates": [TEMPLATE]},
"resources/read": read_resource,
}
def handle(msg: dict) -> dict:
params = msg.get("params") or {}
meta = params.get("_meta") or {}
if ("io.modelcontextprotocol/protocolVersion" not in meta
or "io.modelcontextprotocol/clientCapabilities" not in meta):
raise RpcError(-32602, "params._meta must carry protocolVersion "
"and clientCapabilities")
requested = meta["io.modelcontextprotocol/protocolVersion"]
if requested != VERSION:
raise RpcError(-32022, "Unsupported protocol version",
{"supported": [VERSION], "requested": requested})
if msg.get("method") not in METHODS:
raise RpcError(-32601, "Method not found", msg.get("method"))
result = METHODS[msg["method"]](params)
return result | {"resultType": "complete",
"_meta": {"io.modelcontextprotocol/serverInfo": SERVER_INFO}}
def main() -> None:
for line in sys.stdin:
try:
msg = json.loads(line)
except json.JSONDecodeError:
msg = {"id": None, "parse_error": True}
if "id" not in msg:
continue # a notification: never answered
try:
if msg.get("parse_error"):
raise RpcError(-32700, "Parse error")
reply = {"jsonrpc": "2.0", "id": msg["id"], "result": handle(msg)}
except RpcError as exc:
error = {"code": exc.code, "message": exc.message}
if exc.data is not None:
error["data"] = exc.data
reply = {"jsonrpc": "2.0", "id": msg["id"], "error": error}
sys.stdout.write(json.dumps(reply) + "\n")
sys.stdout.flush() # one message per line, sent at once
if __name__ == "__main__":
main()Compare this with Track A. The hand-written server must check that every request carries the required _meta keys (protocol version and client capabilities) and reject an unknown version with -32022 and the list of supported versions. It must answer server/discover, keep tools/list in a fixed order, validate arguments against inputSchema, put resultType: "complete" on every result, give discovery, list and read results the cache hints ttlMs and cacheScope (required fields in 2026-07-28), and write exactly one JSON object per line to stdout, flushed at once, with logs on stderr. The SDK does all of this from the decorated functions.
Before you compare the two tracks, check that Track B starts and enforces the first rule. Pipe it one request that has no _meta; the server answers and exits when its input ends.
printf '%s\n' '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' \
| python stdio_server.py | python -m json.tool{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "params._meta must carry protocolVersion and clientCapabilities"
}
}06. Step 5: Compare both servers on the wire
wire.py starts any stdio server as a subprocess and sends 2026-07-28 requests. It fails if a line on stdout is not a JSON-RPC message, and it sends the server's stderr to server-stderr.log. Lab 4 reuses it for contract tests.
"""A tiny MCP 2026-07-28 client over stdio, for trying and testing servers.
Usage: python wire.py <command that starts a stdio server>
"""
import itertools
import json
import queue
import subprocess
import sys
import threading
META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {"name": "wire", "version": "1"}}
class StdioServer:
def __init__(self, command: list[str]):
self.log = open("server-stderr.log", "a") # the server's own logs
self.proc = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=self.log,
text=True)
self.lines: queue.Queue[str] = queue.Queue()
threading.Thread(target=self._pump, daemon=True).start()
self.ids = itertools.count(1)
def _pump(self) -> None:
for line in self.proc.stdout:
self.lines.put(line)
def request(self, method: str, params: dict | None = None,
meta: dict | None = META) -> dict:
params = dict(params or {})
if meta is not None:
params["_meta"] = meta
msg_id = next(self.ids)
self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": msg_id,
"method": method, "params": params}))
self.proc.stdin.write("\n")
self.proc.stdin.flush()
while True:
line = self.lines.get(timeout=30) # first start can be slow
try: # stdout may carry JSON-RPC messages and nothing else
msg = json.loads(line)
assert msg["jsonrpc"] == "2.0"
except (ValueError, KeyError, AssertionError, TypeError):
raise AssertionError(f"not JSON-RPC on stdout: {line!r}")
if msg.get("id") == msg_id:
return msg
def close(self) -> None:
self.proc.stdin.close()
self.proc.wait(timeout=10)
self.log.close()
if __name__ == "__main__":
server = StdioServer(sys.argv[1:])
found = server.request("server/discover")["result"]
print("versions:", found["supportedVersions"])
tools = server.request("tools/list")["result"]["tools"]
print("tools:", [t["name"] for t in tools])
page = server.request("tools/call", {"name": "search_issues",
"arguments": {"label": "auth", "limit": 3}})
issues = page["result"]["structuredContent"]["issues"]
print("page 1:", [i["number"] for i in issues])
bad = server.request("tools/call", {"name": "search_issues",
"arguments": {"limit": 500}})
print("limit=500 -> isError:", bad["result"]["isError"])
gone = server.request("tools/call", {"name": "delete_everything"})
how = (f"JSON-RPC error {gone['error']['code']}" if "error" in gone
else f"tool result, isError={gone['result']['isError']}")
print("unknown tool ->", how)
old = server.request("tools/list", meta=META | {
"io.modelcontextprotocol/protocolVersion": "2025-11-25"})
print("version 2025-11-25 ->", old["error"]["code"], old["error"]["data"])
server.close()python wire.py python stdio_server.py
python wire.py python tracker_mcp.pyversions: ['2026-07-28']
tools: ['search_issues', 'get_issue', 'set_issue_state']
page 1: [110, 115, 125]
limit=500 -> isError: True
unknown tool -> JSON-RPC error -32602
version 2025-11-25 -> -32022 {'supported': ['2026-07-28'], 'requested': '2025-11-25'}
versions: ['2026-07-28']
tools: ['search_issues', 'get_issue', 'set_issue_state']
page 1: [110, 115, 125]
limit=500 -> isError: True
unknown tool -> tool result, isError=True
version 2025-11-25 -> -32022 {'supported': ['2026-07-28'], 'requested': '2025-11-25'}At this level the two servers agree on everything except an unknown tool. The specification lists "unknown tool" among protocol errors and shows a JSON-RPC error -32602, which Track B returns. The Python SDK 2.3.0 answers with a tool result marked isError: true instead. Either way the call fails visibly, and lab 4 writes a test that accepts both.
Matching on the wire is not proof that a real client accepts your server. The strongest check is to drive the hand-written server with the official SDK client, which parses every result with the 2026-07-28 result models and rejects a reply that lacks a required field. StdioServerParameters passes only a few safe environment variables to the server by default, so the script hands on the whole environment, including the API token.
"""Drive any stdio tracker server with the official SDK client (mcp 2.x).
Usage: python sdk_client.py <command that starts a stdio server>
"""
import asyncio
import os
import sys
from mcp import Client, StdioServerParameters
async def main() -> None:
server = StdioServerParameters(
command=sys.argv[1], args=sys.argv[2:],
env=dict(os.environ)) # the SDK passes only a few safe variables by default
async with Client(server) as client:
print("protocol:", client.protocol_version)
tools = (await client.list_tools()).tools
print("tools:", [t.name for t in tools])
page = await client.call_tool("search_issues", {"label": "ui", "limit": 2})
print("page 1:", [i["number"] for i in page.structured_content["issues"]])
record = await client.read_resource("issues://101")
print("issues://101 bytes:", len(record.contents[0].text))
asyncio.run(main())python sdk_client.py python stdio_server.py
python sdk_client.py python tracker_mcp.pyprotocol: 2026-07-28
tools: ['search_issues', 'get_issue', 'set_issue_state']
page 1: [107, 112]
issues://101 bytes: 1077
protocol: 2026-07-28
tools: ['search_issues', 'get_issue', 'set_issue_state']
page 1: [107, 112]
issues://101 bytes: 1077Both tracks now work with the official client. Now remove STATIC | from the tools/list entry of stdio_server.py and run the Track B command again. wire.py saw nothing wrong with that reply, but the official client rejects it: its result model requires ttlMs and cacheScope. The command below keeps only the lines that name the problem; the full traceback is long, and the client can take half a minute to shut the server down after the error. Put STATIC | back before you continue.
python sdk_client.py python stdio_server.py 2>&1 \
| grep -oE 'ValidationError: .*|(cacheScope|ttlMs)$'ValidationError: 2 validation errors for ListToolsResult
cacheScope
ttlMsTo use the Track A server from a host, register it as in lesson 1, with absolute paths and TRACKER_API_TOKEN in the env block. For anything beyond a lab token, prefer your host's support for reading variables from the environment or a secret store over pasting secrets into its configuration file.
07. Check your understanding
08. Apply it
Add the fourth task-level tool from your design in lesson 2, for example triage_summary(label), which returns counts of open issues per assignee and the five oldest open issues for one label, using only search() underneath. Give it a return model, a bounded output and actionable errors, and add it to both tracks so they still expose the same contract. Then point the tracker client at a real API you use (read-only token first) and measure raw versus shaped sizes. The next lab turns wire.py into contract tests and adds the MCP Inspector.
09. Review prompt
Without looking, describe the path of one search_issues call from the model to the REST API and back in both tracks: where arguments are validated, how the cursor is built and checked, how a 404, a 401 and a 503 are turned into tool errors, and where the API token lives. Then name four things the SDK did for you that the hand-written server had to do itself.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.