MCP Fundamentals: Stateless Requests and JSON-RPC
Modern MCP has no handshake and no protocol session. Each request must carry enough metadata to be understood, authorized, routed, and retried on its own.
Learning Objectives
- Distinguish MCP's server primitives from its client-side features.
- Build valid JSON-RPC 2.0 requests and responses for MCP
2026-07-28. - Attach protocol version, client capabilities, and client identity to every request.
- Use
server/discoverand handleUnsupportedProtocolVersionErrorwithout a handshake. - Trace one independent request from validation through a complete result.
The Problem
An MCP server can receive two consecutive requests from different clients, with different capabilities, on the same process or HTTP worker. If the server remembers what the previous request declared, it can apply the wrong permissions or return the wrong wire shape.
MCP 2026-07-28 removes that ambiguity. The protocol core is stateless. A server must decide how to handle the current request from the current request, not from connection history.
This changes the mental model. The old sequence was connection first, handshake second, operations third. The modern sequence is simpler:
- The client sends a self-describing request.
- The server validates that request's version and capabilities.
- The server handles the method.
- The server returns a typed result or a JSON-RPC error.
The next request repeats the same process from scratch.
The Concept
Server primitives
MCP servers expose three primary primitives:
- Tools are model-controlled actions, discovered with
tools/listand invoked withtools/call. - Resources are URI-addressed data, discovered with
resources/listand retrieved withresources/read. - Prompts are reusable templates, discovered with
prompts/listand rendered withprompts/get.
Roots, sampling, and logging remain in the 2026-07-28 schema for compatibility, but they are deprecated. New implementations should use explicit tool or resource inputs for roots, direct model-provider APIs for sampling, and stderr or OpenTelemetry for logging. Elicitation remains available through Multi Round-Trip Requests, where a server returns an input request and the client retries the original operation. A modern server never starts an independent JSON-RPC request.
JSON-RPC envelopes
MCP uses JSON-RPC 2.0:
- Request:
{jsonrpc, id, method, params} - Response:
{jsonrpc, id, result}or{jsonrpc, id, error} - Notification:
{jsonrpc, method, params}with noid
The request id correlates one response. It does not create a protocol session.
Required request metadata
Every modern request carries a _meta object inside params:
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/list",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {
"name": "course-client",
"version": "1.0.0"
}
}
}
}The protocol version and client capabilities are required. Client identity is recommended. It is self-reported display and debugging data, not a security credential.
The server must not infer any of these values from an earlier request, a stdio process, an HTTP connection, or a transport header alone.
Complete results and server identity
Every successful modern result includes resultType. A normal final result uses "complete". Servers should also identify themselves in result metadata:
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"resultType": "complete",
"tools": [],
"ttlMs": 30000,
"cacheScope": "public",
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "notes-server",
"version": "1.0.0"
}
}
}
}tools/listresources/listprompts/listresources/templates/listresources/readand server/discover are cacheable results. They include ttlMs and cacheScope. A safe default is ttlMs: 0 and cacheScope: "private". List items should have deterministic ordering so equivalent responses produce stable cache keys and stable model context.
Discovery without a handshake
Every modern server must implement server/discover. The client may call it before another method to retrieve:
supportedVersions- server
capabilities - optional usage
instructions - server identity in result
_meta - cache hints
Discovery is useful, but it is not a gate. A client can send tools/list first because that request already carries its protocol version and capabilities.
If the requested version is unsupported, the server returns JSON-RPC code -32022 with:
{
"requested": "2027-01-01",
"supported": ["2026-07-28"]
}The client selects a mutually supported modern version and retries with a new JSON-RPC request id.
One request lifecycle
Trace a modern request in this order:
- Parse one JSON-RPC envelope.
- Confirm
jsonrpcis"2.0"anidexists,methodis a string, andparamsis an object. - Require the version string and capability object in
params._meta; malformed or missing metadata is-32602. - At an HTTP boundary, compare the version, method, and applicable name headers with the body. A mismatch is
-32020even when one of the two version values is unsupported. - After equality is established, reject a matched but unsupported version with
-32022. - Check required capabilities, then route by
methodand validate method-specific arguments. - Authenticate and authorize the concrete operation before its handler runs.
- Return a complete result with server identity.
- Forget request-scoped protocol metadata.
That order prevents two components from interpreting different calls. A gateway must not authorize Mcp-Name: notes.read while the origin executes params.name: notes.delete. It also keeps malformed input, header confusion, version negotiation, capability failure, authorization, and handler failure as distinct evidence.
Closing stdin or an HTTP response ends transport activity. It does not terminate a protocol session because modern MCP has no protocol session.
Explicit legacy compatibility
Versions through 2025-11-25 use initializenotifications/initializedconnection-scoped capabilities, and, on earlier Streamable HTTP, optional protocol sessions. That behavior is still relevant when a dual-era client talks to an old server.
Keep the eras separate. A modern request is identified by the required per-request metadata. A legacy connection is selected only through the documented fallback path. Do not send initialize as the default for a 2026-07-28 server.
“Stateless” therefore has an era-specific meaning. In 2026-07-28it is a protocol invariant: every ordinary request is independently interpretable and no MCP session exists. In versions through 2025-11-25initialization and negotiated capabilities belong to a connection, so a compatibility adapter may retain that legacy connection state. A dual-era implementation is not one permissive state machine. It is a stateless modern core beside an isolated legacy adapter, with an explicit selection decision before either parser runs.
Neither meaning forbids durable application state. A workflow, task, or draft can live behind an opaque handle in a shared store. The client sends that handle as ordinary input, and every replica authenticates and authorizes its use. Protocol context must not leak into that store as a substitute for the removed session.
Use It
code/main.py builds, validates, traces, and dispatches modern MCP messages without a framework. Run:
python3 code/main.py
python3 -m unittest discover code/tests -vWatch for three invariants in the output:
- Every request repeats its
_metafields. - Every successful result is
resultType: "complete"and includes server identity. - The list result is deterministically ordered and has explicit cache hints.
Ship It
This lesson ships outputs/skill-mcp-handshake-tracer.md. The historical filename remains stable, but the artifact is now a stateless request tracer. It audits each message independently and labels legacy handshake traffic only when it is genuinely present.
Exercises
- Change one request's protocol version to
2027-01-01. Confirm the error code is-32022and the data advertises the supported version. - Remove
io.modelcontextprotocol/clientCapabilitiesfrom the second request. Confirm the server does not reuse capabilities from the first request. - Reverse the in-memory tool registry. Confirm
tools/liststill returns the same deterministic order. - Change
cacheScopefrompublictoprivate. Explain which authorization contexts may reuse the response in each case. - Add an optional
clientInfoomission test. The request should remain valid because client identity is recommended, not required.
Key Terms
| Term | Meaning |
|---|---|
| Stateless protocol | Every request supplies the metadata needed to interpret it |
| Request metadata | Version, client capabilities, and recommended client identity in params._meta |
server/discover | Mandatory server method for versions, capabilities, instructions, and identity |
resultType | Discriminator on every successful modern result |
| Cacheable result | Result that includes required ttlMs and cacheScope hints |
| Protocol era | Modern per-request metadata or legacy connection-scoped initialization |
| Transport lifetime | Process, connection, or response-stream lifetime, not protocol session state |
-32022 | Unsupported protocol version error with requested and supported versions |
Further Reading
Check what you learned
6 questions. Answer each one to see why.
What creates protocol state between two MCP 2026-07-28 requests?
The full code
Every file for this lesson. Copy it, run it, then change it.
"""Phase 13 Lesson 06: trace the stateless MCP request lifecycle.
Lesson: phases/13-tools-and-protocols/06-mcp-fundamentals/docs/en.md
Specification: https://modelcontextprotocol.io/specification/2026-07-28/
Builds JSON-RPC requests, validates per-request metadata, and emits results.
Run: python3 main.py
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any
PROTOCOL_VERSION = "2026-07-28"
SUPPORTED_VERSIONS = [PROTOCOL_VERSION]
VERSION_KEY = "io.modelcontextprotocol/protocolVersion"
CAPABILITIES_KEY = "io.modelcontextprotocol/clientCapabilities"
CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo"
SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo"
CLIENT_INFO = {"name": "lesson-06-client", "version": "1.0.0"}
SERVER_INFO = {"name": "lesson-06-notes", "version": "1.0.0"}
SERVER_CAPABILITIES = {"tools": {"listChanged": False}}
TOOLS = [
{
"name": "notes_search",
"description": "Search notes by keyword.",
"inputSchema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
},
{
"name": "notes_list",
"description": "List note titles.",
"inputSchema": {
"type": "object",
"properties": {},
"required": [],
},
},
]
@dataclass(frozen=True)
class Trace:
kind: str
method: str
era: str
detail: str
def request_meta(
version: str = PROTOCOL_VERSION,
capabilities: dict[str, Any] | None = None,
include_client_info: bool = True,
) -> dict[str, Any]:
meta: dict[str, Any] = {
VERSION_KEY: version,
CAPABILITIES_KEY: {} if capabilities is None else capabilities,
}
if include_client_info:
meta[CLIENT_INFO_KEY] = CLIENT_INFO.copy()
return meta
def make_request(
request_id: int | str,
method: str,
params: dict[str, Any] | None = None,
*,
version: str = PROTOCOL_VERSION,
capabilities: dict[str, Any] | None = None,
) -> dict[str, Any]:
body_params = dict(params or {})
body_params["_meta"] = request_meta(version, capabilities)
return {
"jsonrpc": "2.0",
"id": request_id,
"method": method,
"params": body_params,
}
def rpc_error(
request_id: int | str | None,
code: int,
message: str,
data: Any | None = None,
) -> dict[str, Any]:
error: dict[str, Any] = {"code": code, "message": message}
if data is not None:
error["data"] = data
return {"jsonrpc": "2.0", "id": request_id, "error": error}
def complete_result(
payload: dict[str, Any],
*,
ttl_ms: int | None = None,
cache_scope: str | None = None,
) -> dict[str, Any]:
result = {
"resultType": "complete",
**payload,
"_meta": {SERVER_INFO_KEY: SERVER_INFO.copy()},
}
if ttl_ms is not None:
result["ttlMs"] = ttl_ms
result["cacheScope"] = cache_scope or "private"
return result
def validate_request(message: dict[str, Any]) -> dict[str, Any] | None:
request_id = message.get("id")
if message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
return rpc_error(request_id, -32600, "Invalid Request")
params = message.get("params")
if not isinstance(params, dict):
return rpc_error(request_id, -32602, "params must be an object")
meta = params.get("_meta")
if not isinstance(meta, dict):
return rpc_error(request_id, -32602, "params._meta is required")
version = meta.get(VERSION_KEY)
if not isinstance(version, str):
return rpc_error(request_id, -32602, f"{VERSION_KEY} is required")
if version not in SUPPORTED_VERSIONS:
return rpc_error(
request_id,
-32022,
"Unsupported protocol version",
{"requested": version, "supported": SUPPORTED_VERSIONS.copy()},
)
if not isinstance(meta.get(CAPABILITIES_KEY), dict):
return rpc_error(request_id, -32602, f"{CAPABILITIES_KEY} is required")
client_info = meta.get(CLIENT_INFO_KEY)
if client_info is not None and (
not isinstance(client_info, dict)
or not isinstance(client_info.get("name"), str)
or not isinstance(client_info.get("version"), str)
):
return rpc_error(request_id, -32602, f"{CLIENT_INFO_KEY} is malformed")
return None
def dispatch(message: dict[str, Any]) -> dict[str, Any] | None:
if "id" not in message:
return None
invalid = validate_request(message)
if invalid is not None:
return invalid
request_id = message["id"]
method = message["method"]
params = message["params"]
if method == "server/discover":
result = complete_result(
{
"supportedVersions": SUPPORTED_VERSIONS.copy(),
"capabilities": SERVER_CAPABILITIES.copy(),
"instructions": "Use notes_list for titles and notes_search for keywords.",
},
ttl_ms=3_600_000,
cache_scope="public",
)
elif method == "tools/list":
result = complete_result(
{"tools": sorted(TOOLS, key=lambda tool: tool["name"])},
ttl_ms=30_000,
cache_scope="public",
)
elif method == "tools/call":
name = params.get("name")
arguments = params.get("arguments", {})
if name == "notes_list":
text = "JSON-RPC notes, MCP metadata notes"
result = complete_result(
{"content": [{"type": "text", "text": text}], "isError": False}
)
elif name == "notes_search" and isinstance(arguments.get("query"), str):
text = f"Found notes matching {arguments['query']!r}"
result = complete_result(
{"content": [{"type": "text", "text": text}], "isError": False}
)
else:
result = complete_result(
{
"content": [{"type": "text", "text": f"Unknown or invalid tool: {name}"}],
"isError": True,
}
)
else:
return rpc_error(request_id, -32601, f"Method not found: {method}")
return {"jsonrpc": "2.0", "id": request_id, "result": result}
def trace_message(message: dict[str, Any]) -> Trace:
if "method" in message and "id" in message:
method = str(message["method"])
if method == "initialize":
return Trace("request", method, "legacy", "connection-scoped handshake")
params = message.get("params", {})
meta = params.get("_meta", {}) if isinstance(params, dict) else {}
if isinstance(meta, dict) and VERSION_KEY in meta and CAPABILITIES_KEY in meta:
detail = f"version={meta[VERSION_KEY]} capabilities=current-request"
return Trace("request", method, "modern", detail)
return Trace("request", method, "invalid", "missing modern request metadata")
if "result" in message or "error" in message:
if "error" in message:
return Trace("response", "error", "unknown", f"code={message['error']['code']}")
result = message["result"]
era = "modern" if result.get("resultType") else "legacy"
return Trace("response", "result", era, f"resultType={result.get('resultType', 'absent')}")
if "method" in message:
return Trace("notification", str(message["method"]), "unknown", "no response expected")
return Trace("unknown", "", "invalid", "not a JSON-RPC message")
def show(message: dict[str, Any]) -> None:
trace = trace_message(message)
print(f"[{trace.kind}/{trace.era}] {trace.method}: {trace.detail}")
print(json.dumps(message, indent=2, sort_keys=True))
def main() -> None:
requests = [
make_request(1, "server/discover"),
make_request(2, "tools/list"),
make_request(
3,
"tools/call",
{"name": "notes_search", "arguments": {"query": "JSON-RPC"}},
),
make_request(4, "tools/list", version="2027-01-01"),
]
print("MCP 2026-07-28 stateless request trace")
for current in requests:
print()
show(current)
response = dispatch(current)
if response is not None:
show(response)
print("\nTransport closes. No protocol session was created or terminated.")
if __name__ == "__main__":
main()