Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 12: Model Context Protocol

Week 12 / Lesson 2

Building a local protocol integration

Connect a real local client and server and exercise discovery, reads, calls, and errors.

Section 2.1 1 of 7

Overview

Focus

Connect a real local client and server and exercise discovery, reads, calls, and errors.

Your route through the lesson

  • 2.2 Local process transport and message framing
  • 2.3 Discovery, pagination, and resource reads
  • 2.4 Tool results, protocol errors, and cancellation
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 A server capability missing after restart

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Local process transport and message framing

Focus

Frame local process messages correctly and keep diagnostics off the protocol stream.

A transport carries messages between participants. The local standard-input/output transport launches a server process, writes client messages to its input, and reads server messages from its output. Each message is UTF-8 JSON on one line. Newlines within a text value are escaped by JSON encoding rather than emitted as extra framing lines.

Standard output must contain only protocol messages. A friendly startup banner would be parsed as a malformed response. Diagnostic messages belong on standard error, which the client can capture separately. A response carries the request identifier; a notification has no identifier and does not receive a response.

The lab client uses a reader thread and a queue because waiting on a process pipe needs a bounded strategy that also works on Windows. A deadline limits how long it waits for a response. Shutdown closes server input, waits briefly, and terminates a stuck child if necessary. The official process-transport binding specifies these framing and lifecycle responsibilities. The implementation is small enough to inspect rather than treating process management as an invisible success claim.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A server writes “Ready!” to standard output before a JSON response. What is wrong?
2. A resource text contains a line break. How should JSON framing preserve it?
3. A server fails to exit after its input is closed. What should a bounded client do?

Section 2.3 3 of 7

Discovery, pagination, and resource reads

Focus

Enumerate paginated entries and read resources using exact identifiers.

Discovery of server capabilities is different from listing individual tools or resources. resources/list returns resource entries; resources/read retrieves content for a chosen address. List operations can paginate: a response with nextCursor tells the client that another page exists. The cursor is opaque, so the client returns it unchanged rather than inventing an offset.

The local server advertises two public documents but returns one per resource-list page. A completed client loops until nextCursor is absent, collecting both addresses. It then reads docs://public/reset and verifies that the returned contents carry that same address. Stopping after the first page would incorrectly conclude that only one document exists.

Cacheable results include ttlMs, a freshness hint in milliseconds, and cacheScope, public or private. A private result cannot be shared across authorization contexts merely because its address looks generic. The official resource documentation explains listing and reading. The lab checks these fields and uses an explicit two-page fixture, making pagination part of executed evidence rather than a claim based on a single convenient response.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A resource-list response includes nextCursor. What should the client do to enumerate all entries?
2. Does server/discover itself return every resource’s text?
3. A resource read is marked cacheScope private. May a shared cache serve it to another authorization context?

Section 2.4 4 of 7

Tool results, protocol errors, and cancellation

Focus

Distinguish protocol errors from tool failures and bound cancellation behavior.

A protocol error reports a problem with the request or method, such as an unsupported method or invalid parameters. A tool can instead execute and return an application-level failure using its result’s isError field. The client must inspect both the envelope and the tool result rather than treating every received JSON object as success.

The local client sends an unknown method and checks the method-not-found code -32601, then makes a valid resource read on the same process. This demonstrates recovery from one request error without assuming the entire server is broken. A tool call asking for a forbidden project returns a tool-level denial and no private data.

For this process transport, a client can send notifications/cancelled with the outstanding request identifier. Cancellation does not establish rollback of any external effect. The lab’s operations are bounded read-only functions; its timeout test closes an unresponsive process rather than claiming an unimplemented asynchronous cancellation exchange. The official tools documentation distinguishes tool-result errors from protocol errors.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. An unknown method returns -32601. What kind of event is this?
2. A tools/call response has isError true. Should the host treat its text as successful task completion?
3. The lab terminates an unresponsive read-only server after timeout. What should it avoid claiming?

Section 2.5 5 of 7

Put it into practice

Focus

Run the full local integration and inspect reads, tools, errors, and restart recovery.

Save week12.py in your exercise folder and run python week12.py --lesson 2. The client launches a real server subprocess, discovers capabilities, lists every advertised tool and prompt, follows resource pagination, reads a document, gets a prompt template, and calls the search tool. It then tests an unknown method, terminates a server, and reconnects to a fresh process.

queue.Queue is a thread-safe handoff between the pipe reader and the requesting code. get(timeout=...) waits only for the declared duration. Here a complete miniature example illustrates the bound:

import queue
messages = queue.Queue()
messages.put({"id": 2, "result": {"resultType": "complete"}})
reply = messages.get(timeout=1)
assert reply["id"] == 2

The full file supplies pipe reads, serialization, correlation checks, and cleanup. Expected PASS lines include two resources across two pages and a successful read after restart. It uses no protocol software package, so the pinned dependency is the documented standard-library implementation itself. The supported subset and omitted subscription and remote-transport features are listed in the file header.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What does queue.get(timeout=1) prevent in the illustrated client pattern?
2. The server returns two resources across two pages. A client collects only one. Which competency failed?
3. A restarted process answers a valid read with fresh request metadata. What does this demonstrate?

Section 2.6 6 of 7

Guided comparison

Focus

Use a complete protocol trace as reproducible integration evidence.

The completed trace begins with discovery, then tools/list, prompts/list, and both pages of resources/list. It reads docs://public/reset, receives text with matching address and cache fields, requests the summarize_doc template, and calls search_docs for reset. Each response identifier matches its request, and each ordinary result carries resultType complete.

The next request deliberately names a nonexistent method. The server returns a protocol error. A subsequent valid read succeeds, showing request-level recovery. After the client closes the process, a fresh client performs discovery and reads again. No earlier handshake state is needed because every request supplies its metadata.

The final timeout fixture launches a deliberately unresponsive child in a separate mode. The client’s queue deadline expires and cleanup terminates that process. The report labels this as a timeout and process-cleanup test. It does not present synthetic silence as a successful tool result. These records give the weekly extensible-agent milestone a real protocol boundary while preserving honest limits about the model and remote infrastructure not exercised.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. After a method-not-found error, the same process handles a valid read. What is shown?
2. Why repeat discovery after starting a fresh server process?
3. A child stays silent until the queue deadline expires. Which report is accurate?

Section 2.7 7 of 7

A server capability missing after restart

Focus

Handle a capability that disappears after a server restart.

Before restart, a documentation server advertises search_docs. After an upgrade, it advertises only project_status. The host still has an old cached tool list. Calling the removed tool without checking can produce a confusing failure or tempt the model to invent a result.

A completed client rechecks discovery and the tool list when restarting or when cached assumptions fail. It notices that search_docs is absent and adapts the task: use an available authorized resource read if that supplies the needed evidence, or report that the requested search capability is unavailable. It does not claim that an advertised tool from the old process still exists.

Cache freshness, version compatibility, and task capability are related but distinct. The protocol version can stay 2026-07-28 while the server’s offered tools change. A successful version check therefore does not guarantee the presence of a particular operation. This transfer case teaches a concrete recovery rule: refresh the relevant inventory, validate the new observation, and revise the plan within existing permissions.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. The protocol version is unchanged after restart, but search_docs disappeared. Can version compatibility alone guarantee search?
2. A removed tool is needed, but an authorized resource read can supply the same evidence. What is reasonable?
3. What should happen when refreshed inventory has no suitable capability?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Securing a protocol server →