Sub topic 4
How messages and capabilities work
This chapter covers the wire format under the SDK calls you have used so far. It also covers how a client and server agree on what each side can do. It assumes you can read Python and JSON, and that you have seen the server.py and client session from the earlier chapters. You do not need to know JSON-RPC beforehand.
Why look below the SDK
The SDK hides the messages, but you will meet them in logs, in the Inspector, and in error reports. Capabilities also decide which calls are legal. If you call a method the server never declared, you get an error. Knowing the message shapes lets you tell a protocol failure from a tool failure and from a model failure.
The three kinds of message
MCP uses JSON-RPC 2.0, a small standard for calling methods with JSON. Every message is a JSON object with "jsonrpc": "2.0". There are three kinds.
| Kind | Has `id` | Has `method` | Expects a reply |
|---|---|---|---|
| Request | yes | yes | yes, exactly one response |
| Response | yes (copied from the request) | no | no |
| Notification | no | yes | no |
A request carries a unique id. The response repeats that id, so the sender can match replies to requests even when several are in flight. A response contains either result or error, never both. A notification is fire and forget. Nobody replies to it, so a failure in handling one is invisible to the sender.
Either side can send requests. Usually the client asks and the server answers, for example tools/list or tools/call. The server can also ask the client for things, such as an LLM completion (sampling) or a list of roots. That is why both sides keep a table of pending request ids.
Here is a tool call as it appears on the wire:
{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 2, "b": 3}}}The matching response:
{"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "5"}], "isError": false}}Two kinds of failure
MCP has two separate error channels, and mixing them up is a common mistake.
- Protocol errors use the JSON-RPC
errorfield. They mean the request itself was wrong. Standard codes include-32601(method not found),-32602(invalid params) and-32603(internal error). An unknown tool name or arguments that fail schema validation usually arrive this way. - Tool execution errors arrive as a normal
resultwith"isError": trueand an explanation incontent. They mean the tool ran and failed, for example a file was missing or an API returned 500.
The distinction matters for your agent loop. A tool execution error is information for the model. You pass it back as a tool_result and the model can retry or change course. A protocol error usually points to a bug in your host or a mismatch with the server, and you should log it. Some hosts also pass it to the model so the conversation does not stop.
Capability negotiation
Servers differ. One exposes only tools, another exposes tools and resources. Clients differ too. So the first exchange on every connection is a negotiation, using the initialize request.
The client declares its protocol version, its capabilities and who it is:
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "my-host", "version": "0.1.0"}}}The server replies with the version it will use, its own capabilities, and its identity:
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18", "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "calc", "version": "1.0.0"}}}Finally the client sends a notification, notifications/initialized, to say it is ready. Until the handshake finishes, only a few messages such as ping are allowed.
What the capability objects mean
Each key in capabilities is a feature, and presence of the key means "I support this". Nested flags refine it.
| Side | Capability | Meaning |
|---|---|---|
| Server | `tools` | Handles `tools/list` and `tools/call`. `listChanged` means it may send `notifications/tools/list_changed`. |
| Server | `resources` | Handles `resources/list` and `resources/read`. `subscribe` allows update subscriptions. |
| Server | `prompts` | Handles `prompts/list` and `prompts/get`. |
| Server | `logging` | Can send log messages to the client. |
| Client | `roots` | Can tell the server which directories it may work in. |
| Client | `sampling` | Can run an LLM completion when the server asks. |
| Client | `elicitation` | Can ask the user for input on the server's behalf. |
The rule is simple: do not use a feature the other side did not declare. Your host should check capabilities before it calls resources/list on a server that only offers tools. The SDK exposes the result of the handshake from session.initialize(), which returns the server's capabilities and info.
If you declare sampling as a client, you accept a duty. When the server sends sampling/createMessage, your host must handle it, and should show it to the user for approval. Declare only what you implement.
Version negotiation
The client proposes a protocolVersion, the date of a spec revision. If the server supports it, it echoes the same value. If not, it answers with another version it does support. The client then decides whether it can work with that version. If it cannot, it should disconnect. Do not carry on with a version you do not understand.
Seeing the messages yourself
The script below speaks the protocol with no SDK. It starts server.py from the earlier chapter, performs the handshake, lists tools, and calls add. Over stdio, each message is one line of JSON, terminated by a newline. Run it from the folder that holds server.py.
import json
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "server.py"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
def send(message):
proc.stdin.write(json.dumps(message) + "\n")
proc.stdin.flush()
def request(request_id, method, params=None):
send({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}})
while True:
message = json.loads(proc.stdout.readline())
if message.get("id") == request_id and "method" not in message:
return message
print("skipped:", message)
init = request(
1,
"initialize",
{
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "raw-client", "version": "0.1.0"},
},
)
print("server capabilities:", init["result"]["capabilities"])
send({"jsonrpc": "2.0", "method": "notifications/initialized"})
tools = request(2, "tools/list")
print([t["name"] for t in tools["result"]["tools"]])
call = request(3, "tools/call", {"name": "add", "arguments": {"a": 2, "b": 3}})
print(call["result"])
bad = request(4, "no/such/method")
print(bad["error"])
proc.stdin.close()
proc.wait(timeout=5)The last request has no matching handler, so you should see an error object with code -32601, not a result. The loop in request skips any message that does not answer our id, such as a notification from the server. A server-initiated request would also carry an id, which is why the loop checks that method is absent.
Other messages you will meet
- Pagination. List methods may return a
nextCursor. Pass it back asparams.cursorto fetch the next page. A host that reads only the first page silently misses tools on large servers. - Change notifications. If a server declared
listChanged, it may sendnotifications/tools/list_changed. Your host should calltools/listagain and rebuild the tool definitions it gives the model. - Cancellation.
notifications/cancelledcarries arequestIdand tells the receiver that the sender no longer wants the answer. You send it when a tool call exceeds your timeout. - Progress. A request can include
_meta.progressToken. The server may then sendnotifications/progresswhile it works. - Ping.
pingis a request either side can send to check that the other is alive.
Common mistakes
- Treating
isError: trueas an exception in the host. It is data for the model. - Calling a method the server did not declare, then reading the resulting error as a server bug.
- Reusing a request
idwhile an earlier request with that id is still pending. - Forgetting the
notifications/initializedmessage when writing a raw client. - Ignoring
nextCursorandlist_changed, so the model works from a stale or partial tool list.
Exercise
A tool call to a weather server returns {"result": {"content": [{"type": "text", "text": "City not found"}], "isError": true}}. A call to a tool named forecast that the server does not have returns {"error": {"code": -32602, ...}}. How should your agent loop treat each, and why?
Show answer
The first is a tool execution error. The tool ran and failed, so send the text back to the model as a tool_result with is_error set, and let the model retry or explain. The second is a protocol error: the request was invalid because the tool name is unknown. It usually points to a stale tool list or a host bug, so log it, refresh the tool list, and either report it to the model as a failed call or stop. Both outcomes keep the conversation valid, but only the first is expected during normal use.
Exercise
Your client's initialize request sends "capabilities": {}. The server later sends a sampling/createMessage request. What went wrong, and what is the correct behavior?
Show answer
The server used a feature the client never declared. A well-behaved server must not send it. If your host does not implement sampling, it should answer with a JSON-RPC error such as method not found. If it does implement sampling, it should declare sampling during initialization and ask the user to approve the request.