Model Context Protocol
Learn how MCP connects AI hosts to tools, resources, and prompts using JSON-RPC, covering versions, capabilities, transports, and trust boundaries.
Language AI HandbookAll chapters Model Context Protocol
Why a protocol at all
Consider a small company with a reading assistant in its web application and another assistant in its editor. A researcher asks either assistant for a title, then needs the same record in the other application. The catalog owner would like to publish the lookup once, describe what input it accepts and maintain its own reader permissions. Each host still has a separate job. The editor may offer lookup only when someone opens a catalog panel. The web app may offer it during a research conversation but ask for approval before sending a call.
You could write two adapters for those surfaces, and for a stable internal API that may be a reasonable choice. The reusable interface matters when separate teams own the applications and data. An app author can connect a new catalog without rewriting the model's conversation interface, and the catalog owner can update the server without shipping a new prompt for every connected model. Both still need compatible features and a clear agreement about policy. The adapter count below is a way to express the interface savings under ideal reuse. It leaves out testing, installation and changes peculiar to a deployment.
First decide what needs to be shared. Lookups that operate on server data fit tools. An existing record with a stable identifier may fit a resource. A repeatable user-invoked request with intentional inputs may fit a prompt. Choosing one clarifies which participant initiates the interaction and where the application should show state. It also helps a team avoid adding a general-purpose operation when the task needs a single bounded lookup.
Suppose two assistants need the same reading catalog. Each has its own model-facing tool format, but both need to list the catalog's operations, send arguments and receive a result. A shared protocol gives the catalog one interface to implement. The assistants still decide which actions to offer, how to show approvals and what to do with returned content.
With hosts and providers, one adapter for every host–provider pair gives adapters. If each participant implements a common interface once, the model counts implementations. This counts interfaces under ideal interoperability. Testing deployment-specific combinations, setting policy and adapting incompatible features can still take separate work.
Model Context Protocol (MCP) defines that common interface using JSON-RPC 2.0. This chapter follows the dated 2026-07-28 revision and calls out where the 2025-11-25 handshake differs. The worked example uses a fictional in-memory catalog and a read-only lookup. One caller can see the tool, and the host asks for approval before sending the request. A separate server check decides whether the caller can read the catalog.
PythonIn [3]Expand
host_counts = range(1, 21)
pairwise_adapters = [n * n for n in host_counts]
shared_implementations = [2 * n for n in host_counts]VisualizationOut [4]Expand

The curves use the same count on both sides. At five hosts and five providers, the pairwise model needs 25 adapters. The shared model counts 10 implementations. At one host and one provider, the pairwise model counts one adapter and the shared model counts two implementations.
Host, client, and server
The host is the application that coordinates the model, the user and their connections. An MCP client is the protocol component that communicates with a server on the host's behalf. The server offers capabilities such as a catalog lookup, a readable record or a reusable prompt. A host can manage distinct clients for multiple servers. Those connections have independent configuration and trust policies. Isolation depends on how the host and its runtime enforce the boundaries. See the MCP architecture overview.
When a model proposes a call, the host can restrict which tools it exposes and can ask the user to approve a particular operation. It passes an approved call to its MCP client. The server separately checks whose request it received and what that caller may access. These decisions are separate even when all three roles happen to run inside one process.
JSON-RPC: the wire format
JSON-RPC 2.0 defines the message envelope. A request has a version marker, an ID and a method. A response carries either a result or an error and echoes the request ID when it can be read. Generic JSON-RPC 2.0 places null in the response ID when a malformed request's ID cannot be recovered. Dated MCP permits the error response to omit the ID in that case. A notification omits the ID and receives no JSON-RPC reply. The MCP revision defines which directions and message patterns it uses. In 2026-07-28, clients send JSON-RPC requests and servers send the responses. Optional input such as elicitation can be requested within a response using the multi round-trip pattern.
Every modern MCP request declares its protocol revision and relevant client capabilities in params._meta. An empty client-capability object is valid for a client with none to declare. Client metadata can identify an implementation name and version. It is descriptive, so identity and permissions still belong to the transport and application policy. Clients can send server/discover to learn supported versions and capabilities. A modern server implements it, and a modern client can also make another operation first. If the revision is unsupported, the error names supported versions. The client should retry with a mutually supported revision or tell the user that the peers have no compatible version. Base protocol, versioning and compatibility, discovery.
PythonIn [5]Expand
import json
from copy import deepcopy
from dataclasses import dataclass
PROTOCOL = "2026-07-28"
VERSION_KEY = "io.modelcontextprotocol/protocolVersion"
CLIENT_CAPS_KEY = "io.modelcontextprotocol/clientCapabilities"
CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo"
SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo"
def request(request_id, method, payload=None, *, version=PROTOCOL):
params = dict(payload or {})
params["_meta"] = {
VERSION_KEY: version,
CLIENT_CAPS_KEY: {},
CLIENT_INFO_KEY: {"name": "catalog-notebook", "version": "1.0"},
}
return {
"jsonrpc": "2.0",
"id": request_id,
"method": method,
"params": params,
}
def success(request_id, result):
return {
"jsonrpc": "2.0",
"id": request_id,
"result": {
"resultType": "complete",
"_meta": {
SERVER_INFO_KEY: {"name": "fictional-catalog", "version": "1.0"}
},
**result,
},
}
def failure(request_id, code, message, **details):
error = {"code": code, "message": message}
if details:
error["data"] = details
response = {"jsonrpc": "2.0", "error": error}
if request_id is not None:
response["id"] = request_id
return responseThe 2025-11-25 revision used initialize followed by notifications/initialized. In that revision the handshake exchanged capabilities, and a Streamable HTTP server could issue an optional Mcp-Session-Id during initialization. The modern revision removes that handshake and protocol session header. Servers can still retain application state, for example a catalog service keeps records, but the modern protocol does not use a connection's prior lifecycle exchange to interpret a request. Check the SDK and server revision when porting a client. A version mismatch does not imply a malformed tool argument. Legacy lifecycle, legacy transport, 2026-07-28 changelog.
The lifecycle
For a migration, write down the first message expected by each deployed peer. The older handshake moved an implementation into a point where both peers had exchanged information. In the modern request-oriented design, inspect the particular request for the revision and applicable client capabilities. Discovery is useful before choosing a method when you know little about a server. A client with a configured compatible revision can start with the operation it needs, then handle any revision error using the returned supported versions.
Keep the request vocabulary separate from application state. If the server persists a reading list, ownership and concurrency of updates still belong to the application. When a client reconnects and sends a valid read request, the server can resolve the requested record based on its current data and authorization. A separate request can safely reference the same record using the application's stable ID. The toy uses only read operations; for a service with writes, decide when retrying is safe based on the operation's semantics and application policy.
Version choice is a useful first deployment test because each side can have more than one supported revision. Here the inputs are ordered by client preference. The intersection produces a choice for a client that includes the modern date and no choice for a client with only an older date. This is a local selection example. A real integration still needs a client implementation for each revision it is prepared to use.
PythonIn [6]Expand
catalog_supported_versions = (PROTOCOL,)
preferred_versions = (PROTOCOL, "2025-11-25")
older_only_versions = ("2025-11-25",)
def preferred_match(preferences, server_supported):
return next(
(version for version in preferences if version in server_supported),
None,
)
version_choices = (
preferred_match(preferred_versions, catalog_supported_versions),
preferred_match(older_only_versions, catalog_supported_versions),
)
assert version_choices == (PROTOCOL, None)
print("Compatible choice:", version_choices[0])
print("Older-only choice:", version_choices[1])ConsoleOut [6]Expand
Compatible choice: 2026-07-28 Older-only choice: None
If the second case occurs during a migration, the useful message names the observed mismatch and directs the owner to the version configuration. Debugging an argument on a method the peers have yet to agree to interpret wastes time. Keep a test for ordinary compatible requests and a separate one for incompatible versions, because the two should lead to distinct messages in the host.
Capability negotiation
Capability declarations help a peer decide whether an operation is appropriate. The server declaration says which features it implements. Client capability information on a modern request lets the server account for what the client can handle for that request. Compare capability information on the relevant connection when the host has multiple connections. An operation that works against a library server says little about what a workshop server implements, even if both speak MCP.
Picture three fictional connections. The catalog provides tools and resources. The style guide offers resources and prompts. The workshop offers tools and prompts. Their declarations are independent. Keeping a matrix of the operation families each test server implements catches a common integration mistake, where the host copies capabilities from one connection into another. The matrix below records those three fixture declarations. Authorization and individual tool inventories belong in separate records.
PythonIn [7]Expand
capability_families = ("Tools", "Resources", "Prompts")
fixture_features = {
"Reading catalog": {"Tools", "Resources"},
"Style guide": {"Resources", "Prompts"},
"Workshop": {"Tools", "Prompts"},
}
capability_matrix = [
[family in supported for family in capability_families]
for supported in fixture_features.values()
]
assert capability_matrix == [
[True, True, False],
[False, True, True],
[True, False, True],
]VisualizationOut [8]Expand

The two connections with tools can also publish a tool with the same local name. An application can keep those entries distinct internally by storing the connection and the tool name together. It can label the two choices differently when it presents them. Include the destination in an approval prompt when a user could reasonably choose either. This way the action a user sees can match the server to which the host sends the call.
A capability can help select a call, and the server's available tool list can depend on the requesting identity. The application still checks whether a specific action is appropriate to expose in that interface. For example, an operator may connect a workshop server that supports tools while the reading interface never offers the workshop's operations. The host filters that view under its own policy even when it connects successfully.
The three primitives
MCP servers can expose different capabilities. The table describes the intended interaction patterns of the three server primitives. Hosts can build different interfaces around them.
| Primitive | Intended selection | Discovery | Operation |
|---|---|---|---|
| Tools | Model proposes an operation | tools/list | tools/call identifies a tool and supplies arguments |
| Resources | Application selects context | resources/list | resources/read retrieves content by URI |
| Prompts | User selects a named template | prompts/list | prompts/get returns messages with supplied arguments |
Tools
A tool uses a name and a JSON Schema for inputs. A description helps the host and model identify its purpose. An optional output schema describes structured results. When the tool advertises an output schema, a successful structured result must conform to it and clients should validate it. Responses can also carry typed content, for example a text representation of the same result. Tools specification.
A JSON-RPC error reports a protocol problem, such as an unknown method or a malformed request. A tool execution failure can instead return a result with isError: true, so the host can present useful information from the operation. A non-object arguments field fails at the protocol boundary. If the arguments object is well formed but its values fail the tool's own input rules, the tool reports the validation problem in its result. Both still need explicit handling in the host.
Resources and prompts
A resource has a URI. resources/read can return text or base64-encoded binary data. For a family of related resources the server may list URI templates through resources/templates/list. The application still chooses which returned content to include in model context. Resources specification.
A server defines prompt templates and their arguments. A user might pick a catalog summary template in a menu, and the application would request its messages with prompts/get. The prompt name describes a user-facing choice. Returned messages still come from the server and the host controls how they enter the conversation. Prompts specification.
A concrete primitive test can use the app's own routing table. This one keeps discovery and follow-up operations paired. The resource-template route is listed separately because it lists families of resource URIs. Operations such as writing a reading list belong to the service design and do not enter this fixture.
PythonIn [9]Expand
primitive_methods = {
"tool": ("tools/list", "tools/call"),
"resource": ("resources/list", "resources/read"),
"prompt": ("prompts/list", "prompts/get"),
}
resource_template_method = "resources/templates/list"
assert (
len({method for pair in primitive_methods.values() for method in pair}) == 6
)
assert all(
discovery.split("/")[0] == operation.split("/")[0]
for discovery, operation in primitive_methods.values()
)When teaching these routes to a model-facing application, keep discovery information and fetched content in separate fields. A retrieved resource might provide a sentence to cite. A tool description helps decide whether an operation fits the request. A selected prompt becomes input to the conversation under the host's chosen roles. The application uses those fields to choose what it shows the model and which role to give each item.
Transports
The transport decides how the same protocol messages are framed and delivered. The standard bindings are stdio and Streamable HTTP. Stdio uses newline-delimited messages on the standard input and output of a subprocess. Diagnostic text goes on standard error. Restrict the process's privileges and data access separately.
In modern Streamable HTTP the client sends a JSON-RPC request using POST. The client accepts both JSON and a request-scoped server-sent event stream. The request carries the protocol version in the MCP-Protocol-Version header as well as in params._meta. The Mcp-Method header mirrors the method, and calls such as tools/call also include a matching Mcp-Name. A server that processes the body checks the mirrored headers against it. For a header validation failure, the server returns HTTP 400 with JSON-RPC error -32020. SSE is one response framing option within Streamable HTTP. The older transport called HTTP+SSE is separately deprecated. Streamable HTTP.
For an integration that needs protected HTTP access, MCP defines an optional authorization framework based on the OAuth 2.1 Internet-Draft and related standards. In that framework the MCP server is the protected resource server. It validates the access token for its own audience. Tokens for a different resource cannot be accepted or passed through as the MCP server's own credentials. The server still needs to enforce access rules for the selected operation and data. Transport identity, permission to access a service and approval to perform a particular action answer separate questions.
A tools capability means the server implements tool operations. Its catalog can vary by authorization on the request. A tool listing is not a reason to skip the permission check on a call. For a cacheable list result, ttlMs gives the freshness hint in milliseconds and cacheScope indicates public or private scope. Keep any cached view within its permitted scope and enforce the current permission on each protected operation. See tools and caching.
Worked example: a fictional catalog
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

Trust boundaries
The protocol describes messages between participants. A host still limits which capabilities enter the model context, and the application or operating system restricts what a server can access. Keep returned content in its proper role. A prompt template, tool description or catalog record is data from a server. It cannot grant additional privileges or approve a subsequent action. Human approval and server authorization can work together without either taking the other's place.
Older deployments may still use roots and sampling. The modern specification deprecates roots and sampling. A roots declaration does not confine a process. Use operating-system or application-level restrictions to enforce access, and pass necessary resource identifiers or tool arguments explicitly. For modern interaction patterns that request user input, the host still decides what information to share.
When debugging an integration, start by distinguishing four questions.
- Does the client support the revision the server speaks?
- Does the server implement the operation and advertise the applicable capability?
- Does the server accept the caller and permit that operation on this data?
- Does the host policy allow the model to propose or submit the action?
A schema says what arguments fit, so check the advertised schema against the handler and exercise malformed calls separately from expected business failures. Validate the authorization behavior for a permitted and a denied caller. Restrict returned data to what the task needs. Logs for approvals and decisions can be useful without storing raw sensitive inputs unnecessarily.
Which tools enter the interface
A server can implement several legitimate operations while the task needs one. In the following inventory the server implements lookup, export and a feature unrelated to reading. For the illustrated reader identity, the server lists lookup and export. The reading host offers only lookup in this interface. The offered set is the intersection of the permitted list and the host's task list.
PythonIn [17]Expand
implemented_tools = {"lookup", "export", "index_status"}
listed_for_reader = {"lookup", "export"}
reading_interface_policy = {"lookup"}
offered_for_reading = listed_for_reader & reading_interface_policy
assert offered_for_reading == {"lookup"}
tool_stage_counts = {
"Implemented": len(implemented_tools),
"Listed to reader": len(listed_for_reader),
"Offered by host": len(offered_for_reading),
}VisualizationOut [18]Expand

The host applies the task filter before creating model-facing tool descriptions. An approval screen can then confirm an individual call. Both restrictions matter if the caller changes or the catalog is updated after discovery. In a multi-user host, a shared connection cache also needs a key compatible with the discovery response's scope, so a cached private view cannot accidentally leak to another identity.
Bounding returned content
A read-only call can still return more data than the model or interface needs. Set a separate response budget for the representation passed into the model context. In this example the application builds a serialized JSON object from one fictional record and sends a small summary when the full object exceeds a local UTF-8 byte cap. The cap is deliberately about application context assembly. Model token and transport limits need their own checks.
PythonIn [19]Expand
context_byte_cap = 120
full_context_record = {
**found["structuredContent"],
"notes": "Fictional catalog annotation for the seminar reading list. " * 4,
}
compact_context_record = {**found["structuredContent"], "notes_omitted": True}
def encode_context(record):
return json.dumps(record, ensure_ascii=False, separators=(",", ":")).encode(
"utf-8"
)
full_context_bytes = encode_context(full_context_record)
compact_context_bytes = encode_context(compact_context_record)
chosen_context_bytes = full_context_bytes
if len(chosen_context_bytes) > context_byte_cap:
chosen_context_bytes = compact_context_bytes
if len(chosen_context_bytes) > context_byte_cap:
chosen_context_bytes = b""
assert len(full_context_bytes) > context_byte_cap >= len(chosen_context_bytes)
assert json.loads(chosen_context_bytes) == compact_context_record
context_sizes = {
"Complete record": len(full_context_bytes),
"Submitted summary": len(chosen_context_bytes),
}
print("Context sizes in bytes:", context_sizes)ConsoleOut [19]Expand
Context sizes in bytes: {'Complete record': 295, 'Submitted summary': 69}VisualizationOut [20]Expand

The compact object marks that notes were omitted, which gives the caller enough information to request more detail through the application if it is needed. In this fixture the second check emits empty context when even a summary exceeds the cap. Serializing the summary before checking its size keeps the application from passing an incomplete JSON value. Authorization applies before context assembly, so a smaller representation still needs to come from a record the caller may access.
Common failure modes
Once the request arrives, inspect the response layer before deciding how to recover. An HTTP transport check, a JSON-RPC error and a failed tool lookup can leave similar-looking messages in a chat interface. They give different directions to the person diagnosing the bug. For HTTP, verify the request framing and mirrored headers first when the transport rejects the request. For a structured JSON-RPC error, read its code and safe diagnostic fields. For a tool outcome, use that tool's application semantics. A missing catalog title can be a valid outcome that the reader can correct by checking the entry ID.
The notebook records one outcome per chosen probe. Two use the JSON-RPC error path, one reaches the tool and fails to find a record, and one returns a record. This table concerns requests that reached the toy dispatcher; the separate host diagram includes proposals stopped before dispatch. It gives a small regression set you can keep next to your adapter tests.
PythonIn [21]Expand
probe_replies = {
"Unsupported revision": bad_version,
"Malformed arguments": invalid,
"Unknown record": missing["reply"],
"Known record": approved["reply"],
}
reply_channels = ("Protocol error", "Tool error", "Success")
observed_channels = {}
for label, reply in probe_replies.items():
if "error" in reply:
channel = "Protocol error"
elif reply["result"].get("isError", False):
channel = "Tool error"
else:
channel = "Success"
observed_channels[label] = channel
assert list(observed_channels.values()) == [
"Protocol error",
"Protocol error",
"Tool error",
"Success",
]VisualizationOut [22]Expand

Make the positive case prove more than successful deserialization. In a connection test, inspect whether the discovered operation schema matches the handler that executed, and verify that the actual output maps to the expected user result. Pair it with a denied-caller case, a declined-approval case, an unsupported-revision case and a missing-record case. Durable tests assert the reason or response shape, so one generic failure cannot make every test appear to pass.
For diagnosis in a shared app, record the selected server, protocol revision, method, decision stage and outcome with the information needed to correlate the request. Agree on a format with the service owner, particularly if two servers use the same method names. Keep credentials and unrelated catalog content out of diagnostics. A useful incident record can explain which check failed without disclosing the record that the permission check was meant to protect.
Limitations and impact
A common protocol saves adapters when both ends can speak compatible revisions and agree on the relevant features. It does not ensure that all servers offer equivalent tools, that tool descriptions produce the same model behavior, or that permission policies work the same across hosts. Stdio also inherits practical process risks, and remote access adds network and credential management. The in-memory example demonstrates request shape, a policy decision and the two failure channels. An implementation using real transports needs separate interoperability, authentication and authorization tests.
When a direct interface fits
For one known backend, a typed client for that backend may save work. It can preserve domain-specific transactions, expose familiar error types and reuse the permissions already built into the application. MCP earns its place when several hosts need an interface they can discover or when the server publishes multiple useful kinds of interaction. Measure the maintenance cost you would actually remove and the new work in connector operation, including version support and reviewing tool descriptions as they change.
Before shipping across organizational boundaries, agree on who maintains each interface and how schema changes become visible to clients. Keep a small compatibility table by connection and run a representative read after an upgrade. When a host filters what the model can see, test both the exposed view and the server's own permission enforcement. That combination leaves a reviewer with evidence about what users can do through the host and what a request reaching the server can do.
Summary
- MCP uses JSON-RPC to expose tools, resources and prompts to clients managed by a host.
- The
2026-07-28revision carries version and client capabilities on every request. The older handshake belongs to earlier revisions. - Stdio and Streamable HTTP carry the messages with different framing. The optional HTTP authorization framework applies separately to protected services.
- The host decides which tools to present or forward. A server implements the request and enforces the caller's permission. The toy showed why both checks matter.
- Discovery, protocol errors and tool execution outcomes each answer a different question. Test them separately when connecting a new server.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about the Model Context Protocol.
Model Context Protocol
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!