Skip to content
Index Ai Academy
Phase 9 · Clients and hosts

Build a client

Metadata on every request, version fallback, paging and caching.

About 40 minutes · Versions and API rules checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers10

First principles

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.

  1. Starting point

    Client records pending requests for IDs 21 and 22

  2. What changes

    Transport delivers the reply for 22 ahead of 21

  3. Result

    Session resolves the operation associated with each reply ID

Compare all three steps
  1. Starting point

    Client records pending requests for IDs 21 and 22

  2. What changes

    Transport delivers the reply for 22 ahead of 21

  3. Result

    Session resolves the operation associated with each reply ID

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

Client records pending requests for IDs 21 and 22. Check that your implementation produces the result shown above.

Try it on a new case

Requests 21 and 22 ask for different reports. Reply 22 arrives first. Which caller receives it?

Show worked reasoning

The caller that owns request 22 receives it. Request 21 stays pending, so completion order can vary without swapping results.

Run, change, and build

Check this when debugging. Assuming replies arrive in request order.

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. Requests 21 and 22 ask for different reports. Reply 22 arrives first. Which caller receives it?

Why it matters

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.

What you'll be able to do

  • Separate a client into a transport (moving bytes) and a session layer (MCP rules)
  • Attach the required _meta to every request and match replies to requests by id
  • Fall back to a supported protocol version when the server says UnsupportedProtocolVersion
  • Page through list results and cache them for as long as ttlMs allows
Quick check
A client asks a server for its tools and gets back a page of 50 plus a cursor. What should it do?
  1. Ask again with the cursor until there are no more pages
  2. Guess the names of the tools on the next page
  3. Report an error, since lists should come all at once
  4. Use the first 50 and ignore the cursor
Show the answer

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.

The idea: a client is a transport and a session

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.

Two layers

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:

  • The transport moves one message and brings back the reply. Over HTTP that's a POST with the right headers. Over stdio it writes a line and waits for the line with the matching id. In tests it can be a plain function call into a server object, an in-memory transport.
  • The session layer knows MCP's rules: build the message, add _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.

Quick check
Why can a client's session logic be tested with no network at all?
  1. The session never knows its transport, so a plain function call can stand in
  2. The session caches every reply the first time and replays it in tests
  3. Tests switch the client to stdio, which needs no process to talk to
  4. The session opens its own local server whenever tests are running
Show the answer

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.

Every request: new id, full metadata

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)
It runs right here in your browser, with nothing to install.
Quick check
From the lesson on discovery: a client sends 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}}))
  1. modern modern modern
  2. modern legacy modern
  3. legacy legacy modern
  4. modern legacy legacy
Show the answer

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.

Quick check
What does this print?
next_id = 0
ids = []
for _ in range(3):
    next_id += 1
    ids.append(next_id)
print(ids)
  1. [1, 1, 1]
  2. [3]
  3. [0, 1, 2]
  4. [1, 2, 3]
Show the answer

[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.

Try it now

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.

In your own words
What are a client's two layers, and why fresh ids?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: ids, versions and caches

This part writes the bookkeeping: a pending table, a version retry, a loop over pages and a cache with a lifetime.

Quick check
A client receives a reply with an id it isn't waiting for. What's the right move?
  1. Treat it as the answer to the oldest pending request
  2. Crash, because the server is broken
  3. Ignore it (and log it): it doesn't answer any pending request
  4. Resend every pending request
Show the answer

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.

Drill

Match replies to what you're waiting for

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": {}}))
In the lesson, your code is checked as you write it.
Drill

Give up on a request that never answers

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))
In the lesson, your code is checked as you write it.

Reading results carefully

  • resultType. "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.)
  • Errors come back as JSON-RPC errors. Raise them as an exception carrying the code, message and data, so callers can react to specific codes.

Version fallback

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.

Paging and caching

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.

Worked example

Follow the cursor to the end

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)
In the lesson you can change this and run it.

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.

Quick check
tools/list comes back with a nextCursor. What should the client do?
  1. Stop: the first page holds all the tools, and the cursor is for later
  2. Ask the user to scroll down until the rest of the tools load
  3. Guess the next page number and request that page directly
  4. Call tools/list again with that cursor, until a page has no nextCursor
Show the answer

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)
Worked example

A minimal client against the practice server

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])
In the lesson you can change this and run it.

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.

Quick check
A client's cached tools list has ttlMs: 300000 and was fetched 2 minutes ago. Should it ask the server again?
  1. No: a cached tools list never needs refreshing
  2. No: it's still fresh for about 3 more minutes
  3. Yes: ttlMs is in seconds, so it expired long ago
  4. Yes: a client should always ask before each use
Show the answer

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.

Worked example

Pages on a live server

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])
In the lesson you can change this and run it.

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.

Drill

Is the cached list still fresh?

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))
In the lesson, your code is checked as you write it.

Don't fetch what you already have

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.

Quick check
A server says it doesn't support your protocol version. What should the client do?
  1. Switch to a different server
  2. Keep retrying until the request works
  3. Send the same request again, more slowly
  4. Pick a version both know, retry once, or stop
Show the answer

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.

In your own words
How do you page through a list, and when is a cached list still fresh?

Write a sentence or two, then compare it with a good answer in the lesson.

In the SDK and a real host: the SDK's client

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.

Treat every result as untrusted

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.

Goes deeper in

In your own words
Two tool calls are in flight and the replies arrive in the opposite order. How does a client still give each caller the right answer?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

Why split a client into a transport and a session layer?

  1. The same MCP logic then works over stdio, HTTP or an in-memory test transport
  2. Because MCP requires two processes: one to hold the connection, and another to run the logic
  3. To make messages smaller, since the session layer can remove the fields the transport adds
  4. So the server can choose the transport, by sending the session layer a request to switch over

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 9 · about 13 hours of study

Model Context Protocol

Build MCP servers, clients and hosts, from the wire format to production 17 lessons 1 free
  1. JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
  2. Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
  3. Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
  4. Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
  5. Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
  6. Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
  7. Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
  8. The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
  9. Build a clientMetadata on every request, version fallback, paging and caching.40 min
  10. Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
  11. Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
  12. Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
  13. MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
  14. Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
  15. Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
  16. MCP in production: gateways, limits and auditAn allowlist, per-user rate limits, header checks and an audit log in front of many servers.35 min
  17. Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
Part of a free course 15 lessons

Build and Deploy MCP Integrations

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