Skip to main content

03 - MCP Server Protocol Explained: Spec and Examples

MCP in the current revision 2026-07-28: requests with no handshake or sessions, and a server tested by hand with messages validated on the official schema.

What do you think about this article?

03 - MCP Server Protocol Explained: Spec and Examples
Claude Skills & MCPPhoto:Matheus BertelliPexels

At a Glance

MCP in the current revision 2026-07-28: requests with no handshake or sessions, and a server tested by hand with messages validated on the official schema.

The Model Context Protocol lets an application (the host, for example a programming assistant) talk to a program that offers tools and data (the server) using JSON-RPC messages, without either side knowing the other's internals. If you learned MCP from a tutorial with the sequence initialize, initialized, session, that protocol has changed: in revision 2026-07-28, indicated by the official site as the current revision, there is no handshake and there are no sessions any more. Here I write a server, talk to it by hand with messages validated against the official schema and provoke the errors, all of it executed.

Which revision I describe, and why it matters

If you come from the skill of the second article, the difference is sharp: a skill carries instructions and scripts that Claude reads or runs on your machine; an MCP server is a separate program that exposes tools and data through a protocol, and that any compatible host can connect. The two meet (a skill can explain how to use the tools of a server), but they are designed separately.

Protocol revisions are identified by a date. The specification's versioning page distinguishes three states (draft, current, final) and declares that the current revision, as of 13 November 2026, is 2026-07-28. The earlier ones, up to 2025-11-25, used a handshake and a stateful connection. Knowing the revision matters because a lot of material in circulation describes the old one: the messages change, the methods change and a client written for one can be rejected by the other, as we will see with a real error.

The specification's changelog lists as major changes, compared with 2025-11-25:

  • no sessions at the protocol level and no Mcp-Session-Id header: any state needed across several calls goes through as an explicit argument of the tools;
  • no handshake: every request carries the protocol version and the client capabilities in the _meta field;
  • a new mandatory method, server/discover, with which the server declares supported versions, capabilities and identity;
  • change notifications go through a single open stream with subscriptions/listen, which replaces the GET endpoint and the resource subscriptions;
  • the server no longer sends requests to the client: if it needs data (a user input, for example) it answers with a result of type input_required and the client retries the request with the answer;
  • every result carries a resultType field, and resumption of SSE streams has been removed.

From this I infer, for anyone running a server behind a load balancer, that if every request is self-sufficient two consecutive requests can land on different instances, with no sticky sessions (this is a deduction from the removal of sessions, not a sentence of the specification). For anyone writing a client the consequence is less ceremony at the start and more attention to the _meta fields in every message. The changelog marks as deprecated (still present but not to be adopted) the Roots, Sampling and Logging features and the old HTTP+SSE transport: I do not use them in the examples.

The three primitives: who decides when to use them

An MCP server exposes up to three kinds of things, and the specification distinguishes them not by what they contain but by who controls their use. Prompts are instruction templates chosen by the user (like a slash command or a menu item). Resources are data the application attaches to the context, such as the contents of a file or the history of a repository. Tools are functions the model can choose to call on its own. The distinction is practical: a tool is the only one of the three that the model invokes on its own initiative, and so it is the one on which to concentrate the security controls; the specification in fact recommends that there always be a person able to reject a call. The difference between primitives is covered in more depth in MCP Primitives: Tools, Resources and Prompts.

A server in thirty lines

The test server is a fictional hardware warehouse, with three articles and their stock levels. It exposes a tool (giacenza, "stock level"), a resource (the catalog of codes) and a prompt (the reorder request). I use the official Python SDK, version 2.3.0, installed in a separate folder: as of 13 November 2026 it is the SDK that declares the revision 2026-07-28 as the latest (LATEST_PROTOCOL_VERSION).

"""Test MCP server: a fictional warehouse with one tool, one resource and one prompt."""
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

GIACENZE = {"VITE-M4": 120, "DADO-M4": 0, "RONDELLA-M4": 560}

mcp = MCPServer("magazzino", instructions="Stock levels of a hardware warehouse (test data).")


@mcp.tool()
def giacenza(sku: str) -> dict:
    """Returns the units available for an article code (sku)."""
    if sku not in GIACENZE:
        raise ToolError(f"unknown sku: {sku}. Valid codes: {', '.join(sorted(GIACENZE))}")
    return {"sku": sku, "disponibili": GIACENZE[sku]}


@mcp.resource("magazzino://catalogo")
def catalogo() -> str:
    """List of the known article codes, one per line."""
    return "\n".join(sorted(GIACENZE))


@mcp.prompt()
def riordino(sku: str) -> str:
    """Prepares the reorder request for an article."""
    return f"Check the stock of {sku} and propose a reorder quantity with a rationale."


if __name__ == "__main__":
    mcp.run("stdio")

There are three points to look at. The @mcp.tool() decorator derives the input schema from the type of the parameter (sku: str) and the description from the docstring: it is this text the model will read to decide whether to call the tool, so it must be written for the model. Then the ToolError: when the sku does not exist the tool does not fail with a generic exception, it raises a deliberate error whose message lists the valid codes, so that the model can correct itself on the next call. Finally mcp.run("stdio"): the server talks on standard input and output, and is launched as a child process by the client.

Talking to it by hand, and validating every message

Before using any SDK it is worth seeing the real messages. The following script launches the server as a subprocess, writes the requests one per line (so that the stdio transport frames the messages) and validates both the request and the response against the official JSON schema of revision 2026-07-28, which I downloaded from the specification repository. It opens no ports: it is a child process with two pipes.

"""Test client without an SDK: writes the JSON-RPC messages by hand and validates them against the official schema."""
import json
import subprocess
import sys

from jsonschema import Draft202012Validator
from jsonschema.exceptions import best_match

SCHEMA = json.load(open("schema.json", encoding="utf-8"))
VERSIONE = "2026-07-28"
META = {
    "io.modelcontextprotocol/protocolVersion": VERSIONE,
    "io.modelcontextprotocol/clientInfo": {"name": "test-client", "version": "0.1"},
    "io.modelcontextprotocol/clientCapabilities": {},
}


def valida(messaggio, definizione):
    """Confirms that the message complies with the definition in the official schema: returns "ok" or the kind of violation."""
    schema = {"$ref": f"#/$defs/{definizione}", "$defs": SCHEMA["$defs"]}
    errore = best_match(Draft202012Validator(schema).iter_errors(messaggio))
    return "ok" if errore is None else f"REJECTED ({errore.validator})"


def main():
    server = subprocess.Popen([sys.executable, "server_magazzino.py"], stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
    prove = [
        ("server/discover", None, "DiscoverRequest", "DiscoverResultResponse"),
        ("tools/list", None, "ListToolsRequest", "ListToolsResultResponse"),
        ("tools/call", {"name": "giacenza", "arguments": {"sku": "VITE-M4"}}, "CallToolRequest", "CallToolResultResponse"),
        ("tools/call", {"name": "giacenza", "arguments": {"sku": "XX"}}, "CallToolRequest", "CallToolResultResponse"),
    ]
    for numero, (metodo, parametri, def_richiesta, def_risposta) in enumerate(prove, start=1):
        richiesta = {"jsonrpc": "2.0", "id": numero, "method": metodo,
                     "params": {**(parametri or {}), "_meta": META}}
        server.stdin.write(json.dumps(richiesta) + "\n")
        server.stdin.flush()
        risposta = json.loads(server.stdout.readline())
        print(f"> {metodo}  request: {valida(richiesta, def_richiesta)}  response: {valida(risposta, def_risposta)}")
        risultato = risposta["result"]
        if metodo == "server/discover":
            print("  versions:", risultato["supportedVersions"], "capabilities:", sorted(risultato["capabilities"]))
        elif metodo == "tools/list":
            print("  tools:", [t["name"] for t in risultato["tools"]], "ttlMs:", risultato["ttlMs"], "cacheScope:", risultato["cacheScope"])
        else:
            print("  isError:", risultato["isError"], "text:", risultato["content"][0]["text"].replace("\n", " "))
    server.stdin.close()
    server.wait(5)
    guasta = {k: v for k, v in risposta.items()}
    guasta["result"] = {k: v for k, v in risultato.items() if k != "resultType"}
    print("> counter-check, response without resultType:", valida(guasta, "CallToolResultResponse"))


main()

The valida function builds a schema that points to a definition of the official schema (#/$defs/CallToolRequest, and so on) and returns "ok" or the kind of violation. The META constant is the heart of the revision: protocol version, identity and capabilities of the client in every request, in place of the handshake. The last line is a counter-check: I remove resultType from a real response and verify that the validator rejects it, because a validator that always says "ok" proves nothing.

$ python3 client_grezzo.py
# Output:
# > server/discover  request: ok  response: ok
#   versions: ['2026-07-28'] capabilities: ['prompts', 'resources', 'tools']
# > tools/list  request: ok  response: ok
#   tools: ['giacenza'] ttlMs: 0 cacheScope: private
# > tools/call  request: ok  response: ok
#   isError: False text: {   "sku": "VITE-M4",   "disponibili": 120 }
# > tools/call  request: ok  response: ok
#   isError: True text: Error executing tool giacenza: unknown sku: XX. Valid codes: DADO-M4, RONDELLA-M4, VITE-M4
# > counter-check, response without resultType: REJECTED (anyOf)

The reading is this. server/discover answers with the supported versions (just one, 2026-07-28) and the three capabilities of the server. tools/list returns the tool and two new fields of the revision: ttlMs, for how long the client can consider the list fresh, and cacheScope. This server returns ttlMs at 0 and private scope, meaning no caching: they are the values the SDK uses if you configure nothing. The two calls to tools/call show the most important distinction of the whole protocol: the first succeeds, the second returns a valid result with isError: true and a readable message. It is a tool execution error, meant for the model, not a protocol error.

Protocol errors, provoked

The specification distinguishes two families. Tool execution errors (wrong format of a date, value out of range, an external service answering badly) travel inside a result with isError: true, and the client should pass them to the model so that it corrects itself. Protocol errors (malformed request, unknown method) are JSON-RPC errors, which the model can hardly repair. I provoke three of them, and add a fourth case that is not an error.

"""Provokes three protocol errors and shows how the server decides the era of a connection, without an SDK."""
import json
import subprocess
import sys


def avvia():
    return subprocess.Popen([sys.executable, "server_magazzino.py"], stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)


def scambia(server, messaggio):
    server.stdin.write(json.dumps(messaggio) + "\n")
    server.stdin.flush()
    return json.loads(server.stdout.readline())


def meta(versione):
    return {"io.modelcontextprotocol/protocolVersion": versione,
            "io.modelcontextprotocol/clientInfo": {"name": "test-client", "version": "0.1"},
            "io.modelcontextprotocol/clientCapabilities": {}}


def mostra(descrizione, risposta):
    errore = risposta["error"]
    print(f"{descrizione}\n  code {errore['code']}: {errore['message']}\n  data: {errore.get('data')}")


HANDSHAKE = {"jsonrpc": "2.0", "id": 3, "method": "initialize",
             "params": {"protocolVersion": "2025-11-25", "capabilities": {},
                        "clientInfo": {"name": "old-client", "version": "1"}}}

moderno = avvia()
mostra("1) unknown version", scambia(moderno, {"jsonrpc": "2.0", "id": 1, "method": "tools/list",
                                               "params": {"_meta": meta("2099-01-01")}}))
mostra("2) request without _meta", scambia(moderno, {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}))
scambia(moderno, {"jsonrpc": "2.0", "id": 4, "method": "server/discover", "params": {"_meta": meta("2026-07-28")}})
mostra("3) initialize after a modern request, on the same connection", scambia(moderno, HANDSHAKE))
moderno.stdin.close()
moderno.wait(5)

vecchio = avvia()
risposta = scambia(vecchio, HANDSHAKE)
print("4) initialize as the first message of a new connection\n  negotiated version:", risposta["result"]["protocolVersion"])
vecchio.stdin.close()
vecchio.wait(5)
$ python3 errori.py
# Output:
# 1) unknown version
#   code -32022: Unsupported protocol version
#   data: {'supported': ['2026-07-28'], 'requested': '2099-01-01'}
# 2) request without _meta
#   code -32602: params._meta must be an object carrying the required 'io.modelcontextprotocol/protocolVersion' and 'io.modelcontextprotocol/clientCapabilities' envelope keys
#   data: None
# 3) initialize after a modern request, on the same connection
#   code -32022: connection is serving the 2026-07-28 protocol; the initialize handshake is not accepted
#   data: {'supported': ['2026-07-28'], 'requested': '2025-11-25'}
# 4) initialize as the first message of a new connection
#   negotiated version: 2025-11-25

The first error uses code -32022: the specification reserves the range from -32020 to -32099 for the protocol, and -32022 is "unsupported version", with the versions the server accepts in the data. The client can retry with one of those. The second is a -32602 (invalid parameters) because the required keys of _meta are missing. The third and fourth cases should be read together and concern anyone with clients of different generations. This server, with SDK 2.3.0, decides the era of a connection from the first message it receives: after a modern request it rejects an initialize with the same -32022, while if initialize is the first message of a new connection it negotiates 2025-11-25 and answers like a server of the previous generation.

That is the behavior of the test server in this configuration, not a general rule: the specification describes in a dedicated section how clients and servers of different eras recognize each other and fall back, and anyone who must support both generations needs to read it. For you it means that an old client does not necessarily break against a new server, and that the order of messages on a connection matters.

One difference to point out: the specification lists "unknown tool" among the protocol errors (-32602), while the SDK 2.3.0 server called with a nonexistent name answered with a result isError: true and the text "Unknown tool". I did not include it in the script so as not to weigh it down, but I tried it: if you write a client, do not take for granted which of the two will arrive, and handle both.

With the high-level SDK

In real work you do not write the messages by hand. The same server, with the SDK client connected in-process (the server runs in the same process, with no subprocess and no transport):

"""Same server, now with the high-level client of the official SDK, in-process (no process, no port)."""
import json

import anyio
from mcp.client.client import Client

from server_magazzino import mcp


async def main():
    async with Client(mcp) as client:
        print("negotiated version:", client.protocol_version)
        elenco = await client.list_tools()
        print("tools:", [t.name for t in elenco.tools])
        ok = await client.call_tool("giacenza", {"sku": "DADO-M4"})
        print("DADO-M4 ->", json.loads(ok.content[0].text), "isError:", ok.is_error)
        ko = await client.call_tool("giacenza", {"sku": "XX"})
        print("XX ->", ko.content[0].text, "isError:", ko.is_error)
        risorsa = await client.read_resource("magazzino://catalogo")
        print("catalog:", risorsa.contents[0].text.split("\n"))


anyio.run(main)
$ python3 client_sdk.py
# Output:
# negotiated version: 2026-07-28
# tools: ['giacenza']
# DADO-M4 -> {'sku': 'DADO-M4', 'disponibili': 0} isError: False
# XX -> Error executing tool giacenza: unknown sku: XX. Valid codes: DADO-M4, RONDELLA-M4, VITE-M4 isError: True
# catalog: ['DADO-M4', 'RONDELLA-M4', 'VITE-M4']

The client negotiates the version on its own (here 2026-07-28), discards the ceremony and returns objects. call_tool reports the deliberate error as a result with is_error true, not as a Python exception: it is the same scheme as on the wire, and the caller's code must check that flag. This is the method I use for the tests in this article, because it requires neither processes nor ports; the next article keeps the same principle, with the in-memory transport of the TypeScript SDK.

The transports: stdio and Streamable HTTP

The specification defines two standard transports. With stdio the client starts the server as a subprocess and exchanges JSON-RPC messages separated by a newline, which cannot contain internal newlines; the server may write logs to stderr, but must not write to stdout anything that is not a valid message. It is what the scripts above used. With Streamable HTTP the server exposes a single endpoint that accepts POST: every client message is an HTTP request of its own, and the response is a JSON object or an SSE stream tied to that request. I did not run it, because it requires a server listening on a port; here is what a tool call looks like, derived from the specification (a sketch to adapt, not executed).

POST /mcp HTTP/1.1
Accept: application/json, text/event-stream
Content-Type: application/json
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: giacenza

{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"giacenza","arguments":{"sku":"VITE-M4"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"test-client","version":"0.1"},"io.modelcontextprotocol/clientCapabilities":{}}}}

The three headers MCP-Protocol-Version, Mcp-Method and Mcp-Name repeat information that is already in the body, but let a load balancer or an application firewall route and filter without reading the JSON; the body remains the source of truth. The old HTTP+SSE transport is deprecated and should be migrated to Streamable HTTP. For a local server the specification asks to validate the Origin header (403 response if invalid), to bind only to 127.0.0.1 and to require authentication: without these protections a remote website can talk to a local server through DNS rebinding.

Security: what the protocol asks for and what it cannot guarantee

An MCP tool is code the model can cause to run, often with access to files, networks or databases. The specification puts in writing a minimal list of server-side obligations (validate all inputs, check access, limit the call rate, sanitize outputs) and one client-side (ask for confirmation for sensitive operations, show the user the inputs before the call, validate results before passing them to the model, use timeouts, log the calls). It also treats tool annotations as untrusted, unless the server itself is trusted. The "Security Best Practices" page describes the typical attacks: confused deputy, token passthrough, SSRF, compromise of a local server, overly broad scopes.

What remains is the risk that none of these rules fully solves: a server that reads external content (web pages, tickets, emails) returns to the model text written by others, and that text can contain instructions. The Claude Code documentation says so plainly: check that you trust each server before connecting it, because those that fetch external content expose you to the risk of prompt injection. The practical countermeasures are few and boring:

  • connect only servers whose origin you know, and read their code if they run on your machine;
  • give each tool the minimum permission (read-only where it suffices), because what an injection can do is limited by what the tool can do;
  • keep user confirmation on operations that write or delete;
  • log the calls, so that you can reconstruct afterwards what was executed and why.

These items are not in order of importance, but the second is the most effective: a read-only server that is tricked produces at worst a wrong answer, one with write permissions produces damage. For authentication of HTTP servers the specification builds on OAuth 2.1 (the MCP server as a resource server) and on the resource indicators of RFC 8707; for a stdio server it says not to follow it and to take credentials from the environment. A more extensive treatment of the compliance aspects is in EU AI Act, MCP Security and Italian Compliance for Claude.

Frequently asked questions

Is MCP an open standard or does it belong to Anthropic?

The specification is public and changes follow a proposal process (SEP) with public review, as the changelog documents. I did not find a governance statement in the documentation I consulted, and so I do not say who owns it: you will find it on the official site and in the specification repository.

Can I use MCP without Claude?

Yes. In this article the server was tested with a hand-written script and with the SDK client, without any model. MCP is a protocol between programs; whether there is an assistant on the other side is a choice of the host.

Does one server serve several clients at the same time?

With Streamable HTTP yes, and that is exactly the case for which revision 2026-07-28 removed sessions. With stdio no: the server is a subprocess of the single client. For shared use among several people you need HTTP and authentication.

What you can do now

You know which revision you are on and what has changed compared with the one in many tutorials. You have a test server, a way of talking to it without an SDK with messages validated against the official schema and one for testing it in-process. You can tell protocol errors from tool errors and which security checks to put in place before connecting a server to an assistant. The next step is the client side: in the next article we see how the TypeScript SDK speaks both generations of the protocol and how to build a robust client on top of it.

Later in the series you will also find skills, plugins and MCP servers in an organization, how to follow a call to an MCP tool and Claude Code hooks.

Sources

  • Model Context Protocol, Versioning - revision states and current revision 2026-07-28, version negotiation. Consulted on 2026-11-13.
  • Key Changes, revision 2026-07-28 - major and minor changes, deprecated features, partition of the error codes. Consulted on 2026-11-13.
  • Server Features, Tools - tools/list, tools/call, protocol and execution errors, security obligations. Consulted on 2026-11-13.
  • Transports, Streamable HTTP (and the stdio page in the same section) - POST on a single endpoint, metadata headers, Origin validation; stdio with newline-separated messages. Consulted on 2026-11-13.
  • schema.json of revision 2026-07-28 - official JSON schema used to validate the messages. Downloaded on 2026-11-13.
  • Connect Claude Code to tools via MCP - warning on servers that fetch external content. Consulted on 2026-11-13.
  • SDK: PyPI package mcp 2.3.0 (pip index versions mcp), LATEST_PROTOCOL_VERSION field read from the installed package; consulted on 2026-11-13.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects