Model Context Protocol › Worked example: a fictional catalog
Language AI HandbookAll chapters The sample passes dictionaries directly between a simulated client and server. The catalog has two fictional titles. There is no transport or model in the loop. Pass request objects to the dispatcher. The toy covers discovery, tool listing and tool calls. A real protocol receiver handles notifications separately and sends no JSON-RPC reply to them. The role passed separately to the dispatcher stands in for an authenticated caller. It is outside the JSON-RPC payload.
PythonIn [10]Expand
TOOL_NAME = "catalog.lookup"
TOOL = {
"name": TOOL_NAME,
"description": "Find the title of a fictional catalog entry by its ID.",
"inputSchema": {
"type": "object",
"properties": {
"entry_id": {"type": "string", "minLength": 1, "maxLength": 32}
},
"required": ["entry_id"],
"additionalProperties": False,
},
"outputSchema": {
"type": "object",
"properties": {
"entry_id": {"type": "string"},
"title": {"type": "string"},
},
"required": ["entry_id", "title"],
"additionalProperties": False,
},
}
CATALOG = {"R-101": "Reading the Tides", "R-202": "The Night Index"}
@dataclass(frozen=True)
class Principal:
may_read_catalog: bool
def tool_failure(message):
return {"isError": True, "content": [{"type": "text", "text": message}]}
def catalog_lookup(arguments):
if (
set(arguments) != {"entry_id"}
or not isinstance(arguments["entry_id"], str)
or not 1 <= len(arguments["entry_id"]) <= 32
):
return tool_failure("Supply one entry_id string of 1 to 32 characters.")
entry_id = arguments["entry_id"]
if entry_id not in CATALOG:
return tool_failure("This ID has no entry in the catalog.")
record = {"entry_id": entry_id, "title": CATALOG[entry_id]}
return {
"structuredContent": record,
"content": [{"type": "text", "text": json.dumps(record)}],
}The request dispatcher accepts string and integer request IDs and rejects fractional IDs. The dated MCP base prose requires a string or integer even though the schema writes the union as string or number. Every request needs the required metadata. Discovery says which revision and server capabilities exist. Listing exposes the lookup only to a principal permitted to read this catalog, and the same decision is checked before any lookup. The toy's generic unavailable message avoids distinguishing a hidden tool from a nonexistent tool. The toy represents that outcome with its unknown-tool JSON-RPC error. It does not implement HTTP authentication errors or an OAuth flow.
PythonIn [11]Expand
def dispatch(message, principal):
if not isinstance(message, dict):
return failure(None, -32600, "Invalid request")
request_id = message.get("id")
method = message.get("method")
if (
message.get("jsonrpc") != "2.0"
or type(request_id) not in (str, int)
or not isinstance(method, str)
):
readable_id = request_id if type(request_id) in (str, int) else None
return failure(readable_id, -32600, "Invalid request")
params = message.get("params")
metadata = params.get("_meta") if isinstance(params, dict) else None
if (
not isinstance(metadata, dict)
or not isinstance(metadata.get(VERSION_KEY), str)
or not isinstance(metadata.get(CLIENT_CAPS_KEY), dict)
):
return failure(
request_id,
-32602,
"Required request metadata is missing or invalid",
)
version = metadata[VERSION_KEY]
if version != PROTOCOL:
return failure(
request_id,
-32022,
"Unsupported protocol version",
supported=[PROTOCOL],
requested=version,
)
if method == "server/discover":
return success(
request_id,
{"supportedVersions": [PROTOCOL], "capabilities": {"tools": {}}},
)
if method == "tools/list":
tools = [deepcopy(TOOL)] if principal.may_read_catalog else []
return success(request_id, {"tools": tools})
if method == "tools/call":
name = params.get("name")
arguments = params.get("arguments", {})
if not isinstance(name, str) or not isinstance(arguments, dict):
return failure(request_id, -32602, "Invalid tools/call parameters")
if name != TOOL_NAME or not principal.may_read_catalog:
return failure(request_id, -32602, "Tool unavailable")
return success(request_id, catalog_lookup(arguments))
return failure(request_id, -32601, "Method not found")On the host, approval is for the operation just reviewed by the user. The Boolean parameter stands in for that trusted UI decision. The model would supply a proposed name and arguments, never the approval or the application-injected principal. Only confirmed, allowed proposals reach the dispatcher. For a real service, bind approval to the exact tool identity, arguments and action being authorized.
PythonIn [12]Expand
def host_call(request_id, name, arguments, *, principal, approved):
if name != TOOL_NAME:
return {"host_status": "denied"}
if approved is not True:
return {"host_status": "approval_required"}
reply = dispatch(
request(
request_id, "tools/call", {"name": name, "arguments": arguments}
),
principal,
)
return {"host_status": "forwarded", "reply": reply}
reader = Principal(may_read_catalog=True)
guest = Principal(may_read_catalog=False)
discovered = dispatch(request(1, "server/discover"), reader)
reader_list = dispatch(request(2, "tools/list"), reader)
guest_list = dispatch(request(3, "tools/list"), guest)
lookup_args = {"entry_id": "R-101"}
unapproved = host_call(
4, TOOL_NAME, lookup_args, principal=reader, approved=False
)
approved = host_call(5, TOOL_NAME, lookup_args, principal=reader, approved=True)
forbidden = host_call(6, TOOL_NAME, lookup_args, principal=guest, approved=True)
missing = host_call(
7, TOOL_NAME, {"entry_id": "R-303"}, principal=reader, approved=True
)
invalid = dispatch(
request(8, "tools/call", {"name": TOOL_NAME, "arguments": []}), reader
)
bad_version = dispatch(request(9, "tools/list", version="2099-01-01"), reader)
omitted_arguments = dispatch(
request(10, "tools/call", {"name": TOOL_NAME}), reader
)
fractional_id = dispatch(request(10.5, "tools/list"), reader)
bad_entry_id = dispatch(
request(
11, "tools/call", {"name": TOOL_NAME, "arguments": {"entry_id": 123}}
),
reader,
)ConsoleOut [13]Expand
Discovery: ['2026-07-28']
Reader list: ['catalog.lookup']
Guest list: []
Unapproved proposal: approval_required
Approved reader: {'entry_id': 'R-101', 'title': 'Reading the Tides'}
Approved guest: Tool unavailable
Unknown entry: This ID has no entry in the catalog.
Malformed call: -32602
Unsupported version: -32022The approved reader gets the same entry ID and title in the structured result and its text form. A guest request remains unavailable after host approval, since that approval does not supply server permission. The catalog miss is a tool outcome. The malformed argument container fails at the protocol boundary. To inspect the difference, read the top-level error field for malformed requests and result.isError for failed lookups. This toy treats omitted arguments as an empty object. That call and an arguments object with a numeric entry_id both reach the tool and fail its input rules. The unsupported-version example displays the error without retrying.
PythonIn [14]Expand
assert reader_list["result"]["tools"] == [TOOL]
assert guest_list["result"]["tools"] == []
assert unapproved == {"host_status": "approval_required"}
assert "error" in forbidden["reply"]
assert missing["reply"]["result"]["isError"] is True
assert invalid["error"]["code"] == -32602
assert bad_version["error"]["data"]["supported"] == [PROTOCOL]
assert (
"error" not in omitted_arguments and omitted_arguments["result"]["isError"]
)
assert "error" not in bad_entry_id and bad_entry_id["result"]["isError"]
assert fractional_id["error"]["code"] == -32600 and "id" not in fractional_id
found = approved["reply"]["result"]
assert found["structuredContent"] == {
"entry_id": "R-101",
"title": CATALOG["R-101"],
}
assert json.loads(found["content"][0]["text"]) == found["structuredContent"]The figure shows four outcomes across three stages. A missing approval stops at the host. An approved guest is blocked by server authorization. The approved reader's two requests reach lookup, where the known record yields a result and the missing record yields a tool error.
PythonIn [15]Expand
call_outcomes = [
("Reader, no approval", unapproved["host_status"].replace("_", " ")),
("Guest, approved", forbidden["reply"]["error"]["message"]),
(
"Reader, missing entry",
"Tool error" if missing["reply"]["result"]["isError"] else "Lookup",
),
(
"Reader, known entry",
approved["reply"]["result"]["structuredContent"]["title"],
),
]VisualizationOut [16]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!