Platform Engineering · Lesson 301

MCP Lifecycle: Versions, Discovery, Timeouts, and Shutdown

An MCP connection has a lifecycle: agree a protocol version, learn what the server offers, keep the tool list current, bound every call with a timeout, and shut down without losing work. The protocol changed how this works in its 2026-07-28 revision: the initialize handshake and protocol sessions are gone, and every request carries its own version and the client's capabilities. Most servers in use still speak the handshake revisions, up to 2025-11-25, so a client has to handle both. This lesson follows one question from Quillfern's parcel assistant through the lifecycle, with two failures: a slow tool and no timeout, and a renamed tool the client never heard about.

Difficulty: Advanced · Know this first: Lesson 300, Lesson 296

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up milliseconds from starting the server to a clean shutdown, for one question. It is a worked example, not a measurement. The changes, timeout, and shutdown hops decide whether the answer is right and whether the assistant can get stuck.

Try it: one question, a server that changed overnight

The parcels server was upgraded last night: track is now track_parcel, and the weekly report tool hangs. A customer asks for a tracking update and the weekly report. Choose how the client behaves, and which server it meets.

2026-07-28version
answeredtracking
30 sreport wait

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Handling the MCP lifecycle grows in four levels: connecting correctly, bounding every call, handling change across versions and releases, and running a fleet of servers.

Basic — Connect and call correctly

At the basic level a client connects, reads what it got, and treats results properly.

  • Starts the server over stdio (or reaches it over HTTP) and keeps stdout for protocol messages only.
  • Reads the version the server agreed to, and the capabilities it offered.
  • Checks isError on every tool result, as well as JSON-RPC errors.

Where it breaks: a print statement in a stdio server writes to stdout and corrupts the message stream.

Try it: Basic

A stdio server prints "starting up" with print() before it reads its first message. What happens?

Now do it: Search your server for print() calls and send them to stderr.

Intermediate — Bound every call

At the intermediate level no call can hold the agent for ever.

  • A timeout on every request, reset by progress, under a hard maximum.
  • notifications/cancelled when a timeout expires, and a clear message to the user.
  • A shutdown that waits for replies or cancels first, then closes stdin, waits, and terminates.

Try it: Intermediate

The host closes the server's stdin while a 3-second tool call is running. What does the client receive?

Now do it: Run the lab's last steps and count the replies.

Advanced — Handle change across versions and releases

At the advanced level the client keeps working while servers change underneath it.

  • Listens for list changes (subscriptions/listen, or list_changed in the handshake era) and fetches again.
  • Speaks 2026-07-28 and falls back to the handshake for older servers; retries with a mutual version after -32022.
  • Moves off deprecated features (roots, sampling, logging) before servers drop them.

Try it: Advanced

A 2026-07-28 request gets error -32022 with data.supported ["2025-11-25"]. What should the client do?

Now do it: Send a request with an unsupported version, as in the lab, and read the error.

Master — Run a fleet of servers

At the master level the organisation knows every server's version and behaviour.

  • An inventory of servers with their negotiated version, era, tool list age, and owner.
  • Contract tests per server: discovery, the tool list, a call, a timeout, a cancellation, and shutdown.
  • Dashboards of isError rate, protocol errors, timeouts, and cancellations per server and tool.

Trade-off: supporting both eras doubles the paths to test; dropping the handshake early cuts off servers that have not upgraded.

Try it: Master

After a server release, the isError rate for one tool jumps from 0.1% to 40%. What do you check first?

Now do it: Add a contract test that calls each tool by its listed name after every server release.

Go deeper

The same tool call in both eras. Over stdio each message is one line of JSON, so here they are as the shell command that sends them, as in the lab. In the handshake era (2025-11-25 and earlier) the call is only valid after the handshake:

printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"assistant","version":"4.2"}}}' \
  '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"track","arguments":{"parcel_id":"QF48217"}}}' \
  | python3 server.py

In 2026-07-28 there is no handshake; the version, the client's capabilities, and its identity travel with the request itself. One request, formatted over several lines here (on the wire it is one line):

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"track","arguments":{"parcel_id":"QF48217"},
 "_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",
          "io.modelcontextprotocol/clientCapabilities":{},
          "io.modelcontextprotocol/clientInfo":{"name":"assistant","version":"4.2"}}}}

A server built with the current SDK accepts both, but not mixed: after a handshake, a request carrying the 2026-07-28 envelope on the same connection is refused with error -32600. A connection belongs to one era.

A client in Python with the official SDK (pip install "mcp==2.3.0"). mode="auto" tries 2026-07-28 and falls back to the handshake for older servers; mode="legacy" forces the handshake. The timeout applies to every request, and a call can set its own:

import anyio
from mcp import Client, MCPError, StdioServerParameters

async def main():
    server = StdioServerParameters(command="python3", args=["server.py"])
    async with Client(server, mode="auto", read_timeout_seconds=30) as client:
        print("speaking", client.session.protocol_version)        # 2026-07-28, or a handshake version
        r = await client.call_tool("track", {"parcel_id": "QF48217"})
        if r.is_error:                                            # a result, not an exception
            print("tool failed:", r.content[0].text)
        try:
            await client.call_tool("report", {"days": 7}, read_timeout_seconds=5)
        except MCPError as e:                                     # "Request 'tools/call' timed out after 5.0 s"
            print("gave up:", e)

anyio.run(main)

Shutting down a stdio server you started yourself, with the standard library, in the order the specification gives: replies or cancellations first, then close stdin, wait, terminate, kill.

import subprocess

proc = subprocess.Popen(["python3", "server.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# ... exchange messages; before shutting down, wait for replies or send notifications/cancelled ...
proc.stdin.close()                   # 1. closing stdin tells the server to exit
try:
    proc.wait(timeout=5)             # 2. give it time to finish
except subprocess.TimeoutExpired:
    proc.terminate()                 # 3. SIGTERM on Linux
    try:
        proc.wait(timeout=2)
    except subprocess.TimeoutExpired:
        proc.kill()                  # 4. SIGKILL

What to record for every server connection: the era and the version it ended up on, serverInfo, when discovery and the tool list were last fetched, and counts of -32022 errors, protocol errors, isError results, timeouts, and cancellations per tool. Those numbers show a server release that renamed a tool, or a client that still cannot speak a server's version, before customers do.

Deprecated in 2026-07-28 but still working: roots (pass paths and scopes as tool parameters instead), sampling (call a model API directly), and the logging capability (log to stderr or OpenTelemetry). Server-to-client requests such as elicitation now travel inside the call itself: the server returns a result that asks for input, and the client retries the call with the answers.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. Tracking unavailable.

Timeline

  • Tue 09:00The parcels MCP server ships a release that renames track to track_parcel, to match a naming convention. The server announces the list change.
  • Tue 09:02The customer assistant, which caches tool lists when it starts and never listens for changes, starts getting results with isError true: "Unknown tool: track". Its error dashboards count JSON-RPC errors only, so they stay green.
  • Tue 11:40Support tickets about "tracking unavailable" reach the assistant team. A restart of the assistant fetches the new list and fixes it.
  • Tue 14:00The same day, a report tool hangs; the assistant has no timeout, and conversations stall for minutes until customers leave.

What changed after

The assistant listens for list changes and fetches again; isError results are counted per tool and alert on a jump; every call has a 30-second timeout under a 120-second maximum, with a cancellation and a clear message; the server team runs a contract test against the assistant before releases that change tool names; and renames ship with the old name kept for one release.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Linux with Python 3.10 or later, the venv module (sudo apt install -y python3-venv), and jq (sudo apt install -y jq). The first step installs the MCP Python SDK into a virtual environment, so it needs the internet once.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make a practice folder and a virtual environment, install the official MCP Python SDK at a pinned version, and print the protocol revisions it knows.

    Reversible

    mkdir -p ~/labs/mcp-life && cd ~/labs/mcp-life
    python3 -m venv .venv && . .venv/bin/activate
    pip install -q "mcp==2.3.0"
    python -c "from mcp_types.version import KNOWN_PROTOCOL_VERSIONS as v; print(*v)"

    Options: python3 -m venv .venv makes an isolated environment and . .venv/bin/activate switches this shell to it, so the install touches nothing else; ==2.3.0 pins the version, so the output below stays true.

    Expect: 2024-11-05 2025-03-26 2025-06-18 2025-11-25 2026-07-28: five dated revisions. The first four use the initialize handshake; 2026-07-28 does not.

    Clean up: deactivate; rm -rf ~/labs/mcp-life (the last step).

  2. Write a server with two tools: a fast one, and a slow one that takes 3 seconds.

    Reversible

    cat > server.py <<'EOF'
    import time
    from mcp.server import MCPServer
    
    mcp = MCPServer("parcels")
    
    @mcp.tool()
    def track(parcel_id: str) -> str:
        """Where a parcel is now."""
        return f"{parcel_id}: at the north depot, out for delivery at 10:40"
    
    @mcp.tool()
    def report(days: int) -> str:
        """A slow weekly report: takes 3 seconds."""
        time.sleep(3)
        return f"report for {days} days"
    
    if __name__ == "__main__":
        mcp.run()
    EOF
    python -c "import ast; ast.parse(open('server.py').read()); print('server.py parses')"

    Options: <<'EOF' writes the lines up to EOF into the file; the quotes stop the shell from changing anything inside. mcp.run() serves over stdio: JSON-RPC messages, one per line, on stdin and stdout.

    Expect: server.py parses.

  3. The handshake era (2025-11-25): initialize, then the initialized notification, then the tool list. The sleep keeps stdin open for a second, because closing stdin tells the server to shut down.

    Read-only

    INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"lab","version":"1.0"}}}'
    { printf '%s\n' "$INIT" '{"jsonrpc":"2.0","method":"notifications/initialized"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | {id, version: .result.protocolVersion, server: .result.serverInfo.name, tools: (.result.tools // [] | map(.name))}'

    Options: printf '%s\n' prints each message on its own line, which is how stdio frames messages; the notification has no id, so it gets no reply. jq -s reads all replies, sort_by(.id) puts them in order, and the filter keeps the fields that matter.

    Expect: {"id":1,"version":"2025-11-25","server":"parcels","tools":[]} then {"id":2,"version":null,"server":null,"tools":["track","report"]}: the server agreed to 2025-11-25 and listed both tools.

  4. Ask for a version the server does not know. In the handshake era it does not refuse: it answers with a version it supports, and the client decides whether it can speak that.

    Read-only

    { echo "$INIT" | sed 's/2025-11-25/1999-01-01/'; sleep 1; } | python server.py | jq -c '{asked: "1999-01-01", server_answered: .result.protocolVersion}'

    Expect: {"asked":"1999-01-01","server_answered":"2025-11-25"}. A client that cannot speak 2025-11-25 should disconnect rather than carry on.

  5. The 2026-07-28 way: no handshake. Every request carries the version and the client's capabilities in _meta. Ask the server to describe itself, and call a tool in the same breath.

    Read-only

    META='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"lab","version":"1.0"}}'
    { printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\",\"params\":{$META}}" "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"track\",\"arguments\":{\"parcel_id\":\"QF48217\"},$META}}"; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | .result | {resultType, supportedVersions, cacheScope, ttlMs, text: .content[0].text}'

    Options: The _meta keys are namespaced (io.modelcontextprotocol/…); protocolVersion and clientCapabilities are required on every request, clientInfo is recommended. Over HTTP the version also goes in the MCP-Protocol-Version header.

    Expect: {"resultType":"complete","supportedVersions":["2026-07-28"],"cacheScope":"private","ttlMs":0,"text":null}, then {"resultType":"complete","supportedVersions":null,"cacheScope":null,"ttlMs":null,"text":"QF48217: at the north depot, out for delivery at 10:40"}. The tool call worked with no handshake at all.

  6. Two mistakes a 2026-07-28 client can make: a version the server does not support, and a request without the client's capabilities.

    Read-only

    { printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}}}' '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}'; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | .error'

    Expect: {"code":-32022,"message":"Unsupported protocol version","data":{"supported":["2026-07-28"],"requested":"1900-01-01"}}: the error names the versions the server does support, so a client can retry with one of them. Then {"code":-32602,"message":"params._meta is missing the required envelope key(s): io.modelcontextprotocol/clientCapabilities"}.

  7. A tool name the server does not have, as a client with a stale tool list would send it; and ping, which 2026-07-28 removed.

    Read-only

    { printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"track_parcel\",\"arguments\":{\"parcel_id\":\"QF48217\"},$META}}" "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\",\"params\":{$META}}"; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | {id, isError: .result.isError, text: .result.content[0].text, error: .error.message}'

    Expect: First the server's own log line on stderr, Tool 'track_parcel' failed: 'Unknown tool: track_parcel', then {"id":1,"isError":true,"text":"Unknown tool: track_parcel","error":null}: an unknown tool is a result with isError, not a protocol error, so a client that only checks for errors misses it. Then {"id":2,"isError":null,"text":null,"error":"Method not found"}: no ping in 2026-07-28 (it still works after a 2025-11-25 handshake).

  8. What closing stdin does to work in progress: the slow tool takes 3 seconds. Close stdin after 1 second, after 4 seconds, and cancel after 1 second.

    Read-only

    CALL="{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/call\",\"params\":{\"name\":\"report\",\"arguments\":{\"days\":7},$META}}"
    echo "close stdin after 1 s: $({ echo "$CALL"; sleep 1; } | python server.py | wc -l) reply"
    echo "close stdin after 4 s: $({ echo "$CALL"; sleep 4; } | python server.py | wc -l) reply"
    echo "cancel after 1 s:      $({ echo "$CALL"; sleep 1; echo '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7,"reason":"client timeout"}}'; sleep 4; } | python server.py | wc -l) reply"

    Options: $( … | wc -l) counts the reply lines; notifications/cancelled names the request by its id.

    Expect: 0 reply, 1 reply, 0 reply. Closing stdin mid-call loses the work and the reply; waiting gets it; a cancellation stops the work and, as the specification says, gets no reply.

  9. Clean up.

    Potentially destructive

    deactivate; cd ~ && rm -rf ~/labs/mcp-life
    ls ~/labs

    Expect: No error; mcp-life is gone.

2. Python: mcp_client_policy.py

This program is a client's lifecycle policy without the network, so every rule is visible: which protocol version it ends up speaking with servers of different ages, how long it waits for a call when progress keeps arriving (a timeout that progress resets, under a hard maximum), and what happens to a tool call after the server renames a tool, with and without listening for list changes. Save it as mcp_client_policy.py, then run it.

# mcp_client_policy.py
HANDSHAKE = ["2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"]   # reached with initialize
MODERN = ["2026-07-28"]                                                # version in every request
CLIENT = ["2025-06-18", "2025-11-25", "2026-07-28"]                    # what this client speaks


def connect(server_versions, has_discover):
    """An 'auto' client: try the modern way, fall back to the handshake."""
    if has_discover:                                    # server/discover answered
        mutual = [v for v in MODERN if v in CLIENT and v in server_versions]
        if mutual:
            return f"modern, {mutual[-1]} in every request"
    offer = [v for v in CLIENT if v in HANDSHAKE][-1]   # our newest handshake version
    answer = offer if offer in server_versions else [v for v in server_versions if v in HANDSHAKE][-1]
    if answer not in CLIENT:                            # the server counter-offered something we lack
        return f"disconnect: the server answered {answer}, which this client cannot speak"
    return f"handshake, {answer}" + ("" if answer == offer else f" (server counter-offered; we asked {offer})")


SERVERS = [("current SDK server", HANDSHAKE + MODERN, True), ("2025-11-25 server", HANDSHAKE, False),
           ("2025-06-18 server", HANDSHAKE[:3], False), ("2024-11-05 server", HANDSHAKE[:1], False)]
for name, versions, discover in SERVERS:
    print(f"{name:<19} -> {connect(versions, discover)}")
print()


def wait(progress, result, timeout=30, maximum=120):
    """Each progress notification resets the timeout, but never past the maximum."""
    deadline = min(timeout, maximum)
    for t in progress:
        if t > deadline:
            break
        deadline = min(t + timeout, maximum)
    if result is not None and result <= deadline:
        return f"result at {result} s"
    return f"cancel at {deadline} s: send notifications/cancelled, stop waiting"


CALLS = [("fast tool", [], 1.2), ("slow, reports progress", [20, 40, 60, 80, 100], 110),
         ("hung, silent", [], None), ("progress forever", list(range(10, 600, 10)), None)]
for name, progress, result in CALLS:
    print(f"{name:<23} -> {wait(progress, result)}")
print()


class Server:
    def __init__(self):
        self.tools = {"track"}
        self.listeners = []

    def rename(self, old, new):                         # a release renames a tool
        self.tools = self.tools - {old} | {new}
        for notify in self.listeners:                   # list-changed notification
            notify()

    def call(self, name):
        if name not in self.tools:
            return {"isError": True, "text": f"Unknown tool: {name}"}
        return {"isError": False, "text": "QF48217: out for delivery at 10:40"}


class Client:
    def __init__(self, server, listen):
        self.server, self.cache, self.fetches = server, None, 0
        if listen:
            server.listeners.append(self.invalidate)

    def invalidate(self):
        self.cache = None

    def tool_names(self):
        if self.cache is None:
            self.cache, self.fetches = set(self.server.tools), self.fetches + 1
        return self.cache

    def track(self):
        name = next(n for n in sorted(self.tool_names()) if n.startswith("track"))
        return name, self.server.call(name)


for listen in (True, False):
    server = Server()
    client = Client(server, listen)
    client.tool_names()                                 # cached on Monday
    server.rename("track", "track_parcel")              # Tuesday's release
    name, r = client.track()
    print(f"{'listening' if listen else 'not listening':<13} -> calls {name:<12} isError={r['isError']!s:<5} "
          f"{r['text']} (tool list fetched {client.fetches}x)")

Run it, and you should see this output:

$ python3 mcp_client_policy.py
current SDK server  -> modern, 2026-07-28 in every request
2025-11-25 server   -> handshake, 2025-11-25
2025-06-18 server   -> handshake, 2025-06-18 (server counter-offered; we asked 2025-11-25)
2024-11-05 server   -> disconnect: the server answered 2024-11-05, which this client cannot speak

fast tool               -> result at 1.2 s
slow, reports progress  -> result at 110 s
hung, silent            -> cancel at 30 s: send notifications/cancelled, stop waiting
progress forever        -> cancel at 120 s: send notifications/cancelled, stop waiting

listening     -> calls track_parcel isError=False QF48217: out for delivery at 10:40 (tool list fetched 2x)
not listening -> calls track        isError=True  Unknown tool: track (tool list fetched 1x)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/mcp-lifecycle-versions-discovery-timeouts-and-shutdown && cd ~/labs/mcp-lifecycle-versions-discovery-timeouts-and-shutdown) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "MCP Lifecycle: Versions, Discovery, Timeouts, and Shutdown", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Make a practice folder and a virtual environment, install the official MCP Python SDK at a pinned version, and print the protocol revisions it knows.'
  'Write a server with two tools: a fast one, and a slow one that takes 3 seconds.'
  'The handshake era (2025-11-25): initialize, then the initialized notification, then the tool list. The sleep keeps stdin open for a second, because closing stdin tells the server to shut down.'
  'Ask for a version the server does not know. In the handshake era it does not refuse: it answers with a version it supports, and the client decides whether it can speak that.'
  'The 2026-07-28 way: no handshake. Every request carries the version and the client'\''s capabilities in _meta. Ask the server to describe itself, and call a tool in the same breath.'
  'Two mistakes a 2026-07-28 client can make: a version the server does not support, and a request without the client'\''s capabilities.'
  'A tool name the server does not have, as a client with a stale tool list would send it; and ping, which 2026-07-28 removed.'
  'What closing stdin does to work in progress: the slow tool takes 3 seconds. Close stdin after 1 second, after 4 seconds, and cancel after 1 second.'
  'Clean up.'
)

step_1() {
mkdir -p ~/labs/mcp-life && cd ~/labs/mcp-life
python3 -m venv .venv && . .venv/bin/activate
pip install -q "mcp==2.3.0"
python -c "from mcp_types.version import KNOWN_PROTOCOL_VERSIONS as v; print(*v)"
}

step_2() {
cat > server.py <<'EOF'
import time
from mcp.server import MCPServer

mcp = MCPServer("parcels")

@mcp.tool()
def track(parcel_id: str) -> str:
    """Where a parcel is now."""
    return f"{parcel_id}: at the north depot, out for delivery at 10:40"

@mcp.tool()
def report(days: int) -> str:
    """A slow weekly report: takes 3 seconds."""
    time.sleep(3)
    return f"report for {days} days"

if __name__ == "__main__":
    mcp.run()
EOF
python -c "import ast; ast.parse(open('server.py').read()); print('server.py parses')"
}

step_3() {
INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"lab","version":"1.0"}}}'
{ printf '%s\n' "$INIT" '{"jsonrpc":"2.0","method":"notifications/initialized"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | {id, version: .result.protocolVersion, server: .result.serverInfo.name, tools: (.result.tools // [] | map(.name))}'
}

step_4() {
{ echo "$INIT" | sed 's/2025-11-25/1999-01-01/'; sleep 1; } | python server.py | jq -c '{asked: "1999-01-01", server_answered: .result.protocolVersion}'
}

step_5() {
META='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"lab","version":"1.0"}}'
{ printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\",\"params\":{$META}}" "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"track\",\"arguments\":{\"parcel_id\":\"QF48217\"},$META}}"; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | .result | {resultType, supportedVersions, cacheScope, ttlMs, text: .content[0].text}'
}

step_6() {
{ printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}}}' '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}'; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | .error'
}

step_7() {
{ printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"track_parcel\",\"arguments\":{\"parcel_id\":\"QF48217\"},$META}}" "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\",\"params\":{$META}}"; sleep 1; } | python server.py | jq -s -c 'sort_by(.id)[] | {id, isError: .result.isError, text: .result.content[0].text, error: .error.message}'
}

step_8() {
CALL="{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/call\",\"params\":{\"name\":\"report\",\"arguments\":{\"days\":7},$META}}"
echo "close stdin after 1 s: $({ echo "$CALL"; sleep 1; } | python server.py | wc -l) reply"
echo "close stdin after 4 s: $({ echo "$CALL"; sleep 4; } | python server.py | wc -l) reply"
echo "cancel after 1 s:      $({ echo "$CALL"; sleep 1; echo '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7,"reason":"client timeout"}}'; sleep 4; } | python server.py | wc -l) reply"
}

step_9() {
deactivate; cd ~ && rm -rf ~/labs/mcp-life
ls ~/labs
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your company's assistant connects to 25 MCP servers owned by different teams; some have moved to 2026-07-28, and most still speak the handshake. Design the client's lifecycle handling and how you will run the fleet.

Clarifying questions to ask

How does the client choose a version for each server, and what does it log? How long are discovery results and tool lists cached, and what clears them? What are the timeout and maximum per call, and what does the user see when one expires? How is a server shut down when the assistant restarts? Which deprecated features do servers use, and what is the plan to move off them? Which tests run before a server release?

Rough sizing

Say 25 servers, 180 tools, 2 million tool calls a month, a p95 call time of 3 seconds, and two server releases a week across the fleet.

Shape of the answer

An auto-mode client (2026-07-28 first, handshake fallback) that logs era, version, and serverInfo per connection; discovery cached within ttlMs and cacheScope; tool lists fetched again on list-change notifications; a 30-second timeout reset by progress under a 120-second maximum, with notifications/cancelled and a user-facing message; shutdown that waits for or cancels in-flight calls, then closes stdin with 5 s and 2 s grace periods; dashboards of -32022 errors, protocol errors, isError rate, timeouts, and cancellations per server and tool; a contract test suite each server runs before release; and a register of deprecated features in use.

Trade-offs to name

Supporting both eras doubles the paths to test but keeps every server reachable; short caches and listening cost a few requests and stop stale-tool failures; a strict maximum will occasionally cut off a legitimately long call, so such tools should be redesigned to return quickly and report progress, or to run as background jobs.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
No timeout on a slow toolHop 7: CallDegradestools/call report(days=7) is sent. The reports backend behind the tool has hung, and no progress arrives.
No timeout on a slow toolHop 8: TimeoutBreaksThe client was written with no timeout. The assistant waits, and the chat shows "working" for five minutes until the customer closes the window. Nothing cancels the call, so the hung report keeps a worker busy on the server.
No timeout on a slow toolHop 9: ShutdownBreaksWhen the customer leaves, the host closes stdin with the call still running. The half-built report is lost, and the logs do not say it ever ran.
Stale tool list after an upgradeHop 6: ChangesBreaksTuesday's release renamed track to track_parcel, and the server announced the change. The assistant never opened subscriptions/listen, so it still holds Monday's list and still offers the model a tool called track.
Stale tool list after an upgradeHop 7: CallBreakstools/call track returns a result with isError true: "Unknown tool: track". The assistant retries twice, then tells the customer tracking is unavailable.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Start → Version → Discovery → Capabilities → Tool list → Changes → Call → Timeout → Shutdown. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 302
Agentic AI

An agent is a program that takes a goal in plain words and figures out the steps itself. You say 'clear the stuck deploy.' A script would run a fixed list of commands and stop, even if the first one failed.

Go to Lesson 302 →

Or browse the full course from the Lessons index.