Backend

Model Context Protocol, Explained for Backend Engineers

A backend-focused guide to MCP’s stateless 2026 revision, server architecture, request handling, OAuth, migration, and security.

·
7 min read
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

Model Context Protocol, Explained for Backend Engineers

MCP is how AI agents call your services. In July 2026 it dropped protocol-level sessions, which changes how you scale, authenticate, and migrate an MCP server. It also leaves one problem untouched: the model is the attack surface.

What MCP is

MCP is an open protocol, introduced by Anthropic in 2024, that lets an AI application discover and call tools and data in other systems through one standard interface. Without it, every model needs its own integration with every system.

Three roles:

  • Host: the AI app the user works in, such as an IDE or chat client.

  • Client: a connector inside the host. Each client holds one connection to one server.

  • Server: your service, exposing capabilities over JSON-RPC 2.0.

A server offers three primitives, and the difference is who is in control:

Primitive

What it is

Who decides when it's used

Prompts

Reusable templates

The user

Resources

Read-only context

The host application

Tools

Functions that act

The model

Tools are the risky one. The model chooses when to call them, so a bad call can modify the wrong record or hit the wrong system.

The 2026 change: MCP went stateless

The 2026-07-28 spec revision, finalized on July 28, 2026, removes the initialize handshake and the Mcp-Session-Id header. Each request now stands alone.

Before (up to 2025-11-25)

After (2026-07-28)

Startup

initialize / initialized handshake

None

Client context

Exchanged once at startup

Sent in every request's _meta

Routing

Sticky sessions or a shared session store

Any instance can serve any request

Capability discovery

Returned by initialize

server/discover, which servers must implement

List results

Could vary per connection

No longer vary; carry ttlMs and cacheScope cache hints

Change notifications

HTTP GET stream, resources/subscribe

subscriptions/listen: one long-lived POST response stream, opt-in by notification type

Broken stream

Resume with Last-Event-ID

Not resumable; the client re-issues the request with a new request ID

Server-initiated asks (e.g. elicitation)

Requests sent to the client

Multi Round-Trip Requests: the server returns input_required, the client retries with the answers

Remote transport

HTTP+SSE (superseded by Streamable HTTP in 2025-03-26)

HTTP+SSE formally marked Deprecated

GitHub reportedly removed its Redis-backed protocol sessions when it adopted the new spec.

What a request looks like now

Every HTTP request is a self-contained POST. The headers mirror body fields so gateways and load balancers can route without parsing JSON:

POST /mcp HTTP/1.1
Authorization: Bearer <access-token>
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: create_order

{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
 "params": {"name": "create_order",
            "arguments": {"sku": "A1", "qty": 2, "idempotency_key": "k-1"},
            "_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
                      "io.modelcontextprotocol/clientCapabilities": {}}}}

The server's rules:

  • Mcp-Method is required on every request. Mcp-Name is required for tools/call, resources/read, and prompts/get.

  • Headers must match the body. Otherwise return 400 with error -32020 (HeaderMismatch).

  • An unsupported protocol version returns 400 with UnsupportedProtocolVersionError (-32022) listing what you do support. An unknown method returns 404 with -32601.

Building a stateless server

I wrote a runnable demo: stateless_mcp_demo.py, standard library only, tested on Python 3.13. It runs two server instances that share nothing but a SQLite file, and 19 checks cover discovery, headers, version errors, auth, Origin validation, and retries. I also broke three behaviors on throwaway copies (idempotency, token audience, Origin check), and each made its check fail. It is illustrative, not a conformance suite, and its token scheme is demo-grade.

The header validation, simplified from the demo:

if (version != meta["io.modelcontextprotocol/protocolVersion"]
        or headers.get("Mcp-Method") != method
        or (method == "tools/call" and headers.get("Mcp-Name") != params["name"])):
    return error(400, -32020, "Header mismatch")

Make writes idempotent. If a stream breaks after the server ran a tool, the client must re-issue the call as a new request with a new ID, so a retried write can execute twice. (This is my recommendation, not spec text.) The key has to live in a store every instance can see:

new_id = "ord_" + uuid.uuid4().hex[:8]
db.execute("INSERT OR IGNORE INTO orders VALUES (?,?,?,?)", (key, new_id, sku, qty))
db.commit()
oid = db.execute("SELECT order_id FROM orders WHERE idem_key=?", (key,)).fetchone()[0]
created = (oid == new_id)  # False on a retry, even if another instance served it

In the demo, the retry lands on the second instance and returns the same order. On PostgreSQL 19, INSERT ... ON CONFLICT DO SELECT can return the existing row in one statement.

Stateless protocol does not mean stateless app. If tools need state across calls, the spec's answer is explicit, server-minted handles passed as ordinary tool arguments.

Return tool failures as results. A bad argument the model can fix comes back as a normal result with isError: true. Reserve JSON-RPC errors for protocol problems.

Authorization

Authorization is optional. When you use an HTTP transport, you should follow the spec's OAuth 2.1-based flow. A stdio server should not; it takes credentials from the environment instead.

What your server must do:

  • Publish Protected Resource Metadata (RFC 9728), so clients can find your authorization server. Servers must implement this.

  • Challenge correctly. Unauthenticated requests get 401 with a WWW-Authenticate: Bearer header. The spec's example carries resource_metadata (the metadata URL), and servers should include the scope needed.

  • Check the token on every request. Clients send Authorization: Bearer on every HTTP request and never in the query string.

  • Validate the audience. Clients must send the RFC 8707 resource parameter, and your server must reject tokens not issued for it.

  • Never pass a client's token upstream. If you call another API, use a separate token issued by that API's authorization server.

  • Use 403 for scope gaps. Return error="insufficient_scope" with all the scopes the operation needs in one challenge, so the client can step up in a single round trip.

What changed in this revision:

  • Client registration. Client ID Metadata Documents are now the recommended mechanism (SHOULD). Dynamic Client Registration is deprecated and kept for older authorization servers. If you run your own authorization server, supporting both eases the migration (my suggestion, not spec text).

  • Issuer checks. Authorization servers should return iss (RFC 9207), and clients must validate it before redeeming the code, which blocks mix-up attacks. The spec says a future revision is expected to make iss a MUST.

  • Baseline requirements. Clients must use PKCE with S256, authorization server endpoints must be served over HTTPS, and redirect URIs must be HTTPS or localhost.

stdio vs Streamable HTTP

stdio

Streamable HTTP

Launch

The client spawns your server as a subprocess

Your server is an independent process with one POST endpoint

Framing

Newline-delimited JSON-RPC, no embedded newlines

One message per POST; the reply is JSON or an SSE stream scoped to that request

Metadata

Inline in _meta; no header layer

_meta plus MCP-Protocol-Version, Mcp-Method, Mcp-Name

Diagnostics

stderr; stdout carries only valid MCP messages

Your normal logging and OpenTelemetry

Auth

Credentials from the environment

OAuth flow above

Cancel

notifications/cancelled

Close the response stream

Failure

Client restarts a crashed server and retries

Re-issue the request with a new ID

Shutdown

Client closes stdin; server exits on EOF

n/a

Security

The process can read whatever the user can; scope file access

Must validate Origin (403 if invalid); should bind local servers to 127.0.0.1 and authenticate every connection

Both transports require servers to implement server/discover. On stdio, clients use it as a probe to detect older servers.

Migrating

Deprecated (still work, minimum twelve-month window, don't adopt in new code):

  • Roots, Sampling, Logging. Pass paths via tool parameters or resource URIs, call LLM provider APIs directly, and log to stderr or OpenTelemetry.

  • HTTP+SSE transport. Use Streamable HTTP.

  • Dynamic Client Registration. Use Client ID Metadata Documents.

  • includeContext values "thisServer" and "allServers". Omit the field or use "none".

Removed outright: the handshake, Mcp-Session-Id, ping, logging/setLevel, notifications/roots/list_changed, SSE resumability, tasks/list, and the elicitation completion notification. Tasks moved out of the core protocol into an official extension, io.modelcontextprotocol/tasks.

Checklist:

  1. Serve both eras if you have mixed clients. Answer GET and DELETE on the MCP endpoint with 405 and ignore any Mcp-Session-Id or Last-Event-ID. Keep the old HTTP+SSE endpoints only if you must support older clients.

  2. Implement server/discover. Add resultType: "complete" to every result, ttlMs and cacheScope to list results, and return tools/list in a deterministic order.

  3. Move session state into explicit handles or an external store.

  4. Check your SDK's mode. The official blog says all four Tier 1 SDKs support the new revision, but the TypeScript SDK v2 doesn't speak it by default; you opt in. The Python SDK emits deprecation warnings for the retired features, and sampling and roots raise on a modern connection because there is no back-channel.

  5. Clients: probe first. Send server/discover. A modern JSON-RPC error means don't fall back. Any other error or a timeout means fall back to initialize.

  6. Update your gateway to route on Mcp-Method and Mcp-Name, and to reject header/body disagreements.

Security: the model is the attack surface

Everything a server returns (data, tool descriptions, tool results) ends up in the model's context, and the model can't reliably tell data from instructions. That produces four recurring risks:

  1. Indirect prompt injection: hostile text hidden in a record, web page, or document your server fetches steers the agent.

  2. Confused deputy: a hijacked agent makes the host run privileged tools with the user's authority, without the user approving.

  3. Tool poisoning: a malicious or compromised server hides instructions in its tool descriptions or responses.

  4. Credential theft: an injected prompt tells the agent to read environment variables or config files and send the secrets out.

The exposure is real. A Cloud Security Alliance paper counted nearly 7,000 internet-exposed MCP servers by early 2026, roughly half with no authentication. The NSA published MCP security design guidance in May 2026.

Statelessness is a scalability fix, not a security fix. It does nothing about prompt injection. On top of the auth rules above:

  • Least privilege per tool. Default to read-only and split write tools out.

  • Human approval for destructive actions, enforced in the host.

  • Treat returned data as untrusted. Return only what the task needs.

  • Keep secrets out of the agent's reach, and run servers without root.

  • Pin and review tool definitions. Scan the code and dependencies of any third-party server before deploying it.

  • Log every tool call (who, what, when) and keep an inventory of the servers your teams run.

Takeaway

MCP is now much easier to run behind a load balancer. It is no easier to run safely, so build the server like an API that a confused, easily persuaded caller can reach.

Sources

Comments(0)

Join the discussion by logging into your account.

No comments yet. Be the first to comment!

Emma Clements

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Emma Clements's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.