Build and Deploy MCP Integrations
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
Metadata on every request, version fallback, paging and caching.
When two tool calls are outstanding, how does a client know which result belongs to each?
Transport carries messages. The session layer correlates each reply with a pending request and makes pagination and protocol negotiation explicit.
Client records pending requests for IDs 21 and 22
Transport delivers the reply for 22 ahead of 21
Session resolves the operation associated with each reply ID
Client records pending requests for IDs 21 and 22
Transport delivers the reply for 22 ahead of 21
Session resolves the operation associated with each reply ID
Given Client records pending requests for IDs 21 and 22 and Session resolves the operation associated with each reply ID, write down the missing step that connects them.
Transport delivers the reply for 22 ahead of 21
Now take Transport delivers the reply for 22 ahead of 21 and the result above. Write an input and an implementation that could produce this trace.
Client records pending requests for IDs 21 and 22. Check that your implementation produces the result shown above.
Requests 21 and 22 ask for different reports. Reply 22 arrives first. Which caller receives it?
The caller that owns request 22 receives it. Request 21 stays pending, so completion order can vary without swapping results.
Check this when debugging. Assuming replies arrive in request order.
Servers get most of the attention, but every host, agent and IDE plugin contains an MCP client, and so will the harness you build in Phase 10. The client is where interoperability is won or lost. It's the part that must cope with servers of different versions, slow servers, servers that page their results, and servers that return errors. A small, careful client makes every server it talks to easier to use.
Ask again with the cursor until there are no more pages
Paging keeps each reply small. A client that stops at the first page silently misses tools; following the cursor to the end gets them all.
This rests on JSON-RPC 2.0 in depth: a request has an id, and its reply carries the same one. A client is the code that sends the first and waits for the second, on any wire.
Think of a secretary and a mail carrier. The secretary knows how letters should be written, keeps copies and notices when an answer doesn't match. The carrier only moves envelopes, and it doesn't matter to the secretary whether that's by van or by bike. Split a client the same way:
_meta, check the reply, handle errors, page and cache.The session layer never knows which transport it's using. That means one client works over stdio, HTTP or a test double, and you can test all its logic without a network.
The session never knows its transport, so a plain function call can stand in
The session only asks its transport to move one message and bring back the reply. An in-memory transport that calls a server object directly does that with no wire.
Modern MCP is stateless, so the client attaches its identity on every request:
{"jsonrpc": "2.0", "id": 12, "method": "tools/list", "params": {
"cursor": "...", # method params, if any
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {"elicitation": {}},
"io.modelcontextprotocol/clientInfo": {"name": "shop-assistant",
"version": "0.3.0"}}}}
Each request gets a fresh id. When the reply arrives, its id must match. On stdio, several requests can be in flight at once and replies can return in any order. So the client keeps a table of pending requests, keyed by id, like the rail of order tickets in a kitchen:
import json pending = {} # id -> what was asked next_id = 0 def send(method): global next_id next_id += 1 pending[next_id] = method return {"jsonrpc": "2.0", "id": next_id, "method": method} for m in ["tools/list", "prompts/list", "resources/list"]: send(m) # Replies arrive out of order; the id says which question each one answers. for reply in [ {"id": 3, "result": {}}, {"id": 1, "result": {}}, {"id": 2, "result": {}}]: print(f"reply {reply['id']} answers {pending.pop(reply['id'])}") print("still waiting:", pending)
server/discover first. A result, or one of the two modern errors, means a modern server. Any other error means a legacy one. What does this print?def era(reply): if "result" in reply: return "modern" return "modern" if reply["error"]["code"] in (-32022, -32021) else "legacy" print(era({"result": {"supportedVersions": ["2026-07-28"]}}), era({"error": {"code": -32601}}), era({"error": {"code": -32022}}))
modern legacy modern
A result means the server knows the method. "Method not found", −32601, means it has never heard of server/discover, so it is a legacy server and the client falls back to the old handshake. −32022 is a modern server saying it wants a different version. This decision is one piece of the session layer that this lesson builds.
next_id = 0 ids = [] for _ in range(3): next_id += 1 ids.append(next_id) print(ids)
[1, 2, 3]
Each pass adds one to next_id and appends it, so ids ends as [1, 2, 3]. Each request gets a fresh id, so each reply can be matched to its request.
One call, down through the layers and back up. The pending table at the Session is the client's memory of what it is waiting for.
Write a sentence or two, then compare it with a good answer in the lesson.
This part writes the bookkeeping: a pending table, a version retry, a loop over pages and a cache with a lifetime.
Ignore it (and log it): it doesn't answer any pending request
It may be a late reply to a canceled request. Only ids in the pending table mean anything.
Finish Pending: add(msg_id) records a request you've sent; resolve(reply) returns True and forgets the id if the reply's id is one you're waiting for, and False (ignoring it) otherwise, so a stray or duplicate reply can't be mistaken for an answer.
class Pending: def __init__(self): self.waiting = set() def add(self, msg_id): self.waiting.add(msg_id) def resolve(self, reply): return True p = Pending() p.add(1) print(p.resolve({"id": 1, "result": {}}), p.resolve({"id": 1, "result": {}}))
A reply that never comes must not leave a caller stuck. Write expired(sent_at_ms, now_ms, timeout_ms): sent_at_ms maps each pending id to the time it was sent. Return the sorted ids that have waited at least timeout_ms.
def expired(sent_at_ms, now_ms, timeout_ms): return [] print(expired({1: 0, 2: 9_000}, 10_000, 5_000))
"complete" is an ordinary result. Results from legacy servers have no resultType at all, and clients must treat that as "complete". A value the client doesn't recognize is invalid. ("input_required" is a request for more information, covered in Progress, subscriptions and multi-round-trip requests.)A client usually prefers the newest version it knows. If the server answers UnsupportedProtocolVersion (-32022), error.data.supported lists what it speaks. The client picks the best version both sides know, remembers it for this server, and retries the request once. If there's nothing in common, it raises a clear error instead of looping.
In plain words: if you ask in French and they say "English or German", switch once and remember. Don't keep asking in French.
tools/list, prompts/list, resources/list and resources/templates/list can be paged. A helper should follow nextCursor until it's absent, the way you turn pages until the book ends. It should also guard against a server that returns the same cursor twice, which would loop forever.
List results carry ttlMs, which works like a "best before" date. A client can reuse a cached list for that long instead of asking again, which saves round trips and keeps the model's tool list stable. Remember cacheScope too: a "private" result must never be shared with another user.
A list can come back in pages. A client keeps asking, passing the cursor back untouched, until there isn't one.
TOOLS = [f"tool_{n}" for n in range(1, 8)] def tools_list(cursor=None, page=3): start = int(cursor) if cursor else 0 result = {"tools": TOOLS[start:start + page]} if start + page < len(TOOLS): result["nextCursor"] = str(start + page) return result tools, cursor, requests_made = [], None, 0 while True: reply = tools_list(cursor) requests_made += 1 tools += reply["tools"] cursor = reply.get("nextCursor") if cursor is None: break print(len(tools), "tools in", requests_made, "requests") print(tools)
Treat the cursor as opaque: never read it or build one yourself, since a server may change its format at any time. A client that stops after the first page silently loses tools, and that's a hard bug to spot.
tools/list comes back with a nextCursor. What should the client do?Call tools/list again with that cursor, until a page has no nextCursor
Cursors are opaque bookmarks. Keep asking with the latest one until the server has no more pages.
A client now has three outcomes for a result. Here is the reading step with the third added: a result that needs more input is handed to the user and retried, as in Progress, subscriptions and multi-round-trip requests:
def read_result(reply): result = reply["result"] kind = result.get("resultType", "complete") if kind == "complete": return "done", result if kind == "input_required": return "ask the user", result["inputRequests"] raise ValueError(f"unknown resultType {kind!r}") print(read_result({"result": {"content": []}})[0]) print(read_result({"result": {"resultType": "input_required", "inputRequests": {"confirm": {}}}})[0]) try: read_result({"result": {"resultType": "maybe"}}) except ValueError as error: print(error)
An HTTP transport and a small session layer, talking to the live practice server.
import requests URL = "https://api.gradient.test/mcp" NAMED = {"tools/call": "name", "prompts/get": "name", "resources/read": "uri"} def http_transport(msg): params = msg["params"] version = params["_meta"]["io.modelcontextprotocol/protocolVersion"] headers = {"Accept": "application/json, text/event-stream", "MCP-Protocol-Version": version, "Mcp-Method": msg["method"]} if msg["method"] in NAMED: headers["Mcp-Name"] = str(params[NAMED[msg["method"]]]) return requests.post(URL, json=msg, headers=headers, timeout=10).json() class Session: def __init__(self, transport): self.transport, self.next_id = transport, 0 def request(self, method, params=None): self.next_id += 1 meta = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": {"name": "lesson", "version": "1.0"}} reply = self.transport({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": {**(params or {}), "_meta": meta}}) if "error" in reply: raise RuntimeError(f"{reply['error']['code']}: {reply['error']['message']}") return reply["result"] s = Session(http_transport) info = s.request("server/discover") print(info["_meta"]["io.modelcontextprotocol/serverInfo"], info["supportedVersions"]) print([t["name"] for t in s.request("tools/list")["tools"]]) reply = s.request("resources/read", {"uri": "docs://help/doc_care"}) print(reply["contents"][0]["text"][:60])
The transport knows about HTTP headers; the session knows about ids and _meta. Swap http_transport for a function that calls a server object directly, and the same Session works in tests with no network. That's the design the exercise builds out.
ttlMs: 300000 and was fetched 2 minutes ago. Should it ask the server again?No: it's still fresh for about 3 more minutes
300,000 milliseconds is 5 minutes. After 2 minutes, the cached list is still within its freshness window.
The practice shop's operations server, /mcp-ops, has eight tools and hands them out three at a time. The loop is the one above, with a real server deciding where each page ends.
import requests URL = "https://api.gradient.test/mcp-ops" META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}} HEADERS = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "tools/list"} def tools_list(cursor, request_id): params = {"_meta": META} if cursor is not None: params["cursor"] = cursor msg = {"jsonrpc": "2.0", "id": request_id, "method": "tools/list", "params": params} return requests.post(URL, json=msg, headers=HEADERS, timeout=10).json() names, cursor, pages = [], None, 0 while True: pages += 1 result = tools_list(cursor, pages)["result"] names += [tool["name"] for tool in result["tools"]] cursor = result.get("nextCursor") if cursor is None: break print(pages, "pages,", len(names), "tools") print(names[:3], "...", names[-1]) made_up = tools_list("3", 99) print(made_up["error"]["code"], made_up["error"]["message"][:14])
Three requests fetch eight tools: pages of three, three and two, and the last page has no nextCursor. The cursor this server sends is signed text, so the made-up cursor "3" is refused with -32602. A client that stopped after the first page would never offer the model export_report or get_doc, and nothing would tell it so.
Write fresh(fetched_at_ms, ttl_ms, now_ms): True if a cached list fetched at fetched_at_ms is younger than ttl_ms milliseconds at now_ms. If ttl_ms is None, the server gave no lifetime, so don't trust the cache: return False.
def fresh(fetched_at_ms, ttl_ms, now_ms): return True print(fresh(0, 300_000, 120_000), fresh(0, 300_000, 400_000))
Calling tools/list before each model call adds a slow request to every turn. List results carry a ttlMs saying how long they stay good, so cache them until then. That also keeps the tool list stable, which helps prompt caching (Managing the context window).
Be careful what you share, though. A result marked private belongs to one user. Include the user in the cache key, or don't cache it.
Pick a version both know, retry once, or stop
The error lists the versions the server supports. One retry with a shared version is enough, and if none matches, report it clearly.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. See your Session and transports as the official client writes them.
The Python SDK's Client takes a URL for a Streamable HTTP server or a stdio server's launch parameters, and does the ids, the _meta, the version retry and the matching for you. The TypeScript package is @modelcontextprotocol/client. Underneath the Python client, a ClientSession still exists, reached as client.session.
Check a parcel before you carry it into the house. A client passes tool results to a model, and those results come from outside your system. They may be huge, oddly shaped, or carefully written to mislead the model. So check the structure before you use it, cap the size, and don't follow instructions found inside a result. Your code is the last place that can catch this before the model reads it, so it's well worth the few extra lines of code it takes.
In an engineer's week. A client bug shows up as a wrong answer on one call in a thousand, only under load. The usual cause is a reply matched by order instead of by id, or a timeout that is never cleared. What goes wrong is a retry loop on a version error. Add the pending table, the timeout and the single retry before anything else.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Why split a client into a transport and a session layer?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write