Skip to content
Index Ai Academy
Phase 9 · Protocol foundations

Transports II: Streamable HTTP

One endpoint, required headers, JSON or event-stream replies.

About 40 minutes · Versions and API rules checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

Why would a server check a dispatch header against the operation inside the body?

Intermediaries can route and apply policy based on headers. Agreement with the body keeps intermediaries and the server evaluating the same operation.

  1. Starting point

    HTTP request carries headers and a protocol body

  2. What changes

    Receiver compares values before dispatch

  3. Result

    Matching requests continue to a JSON or event-stream response

Compare all three steps
  1. Starting point

    HTTP request carries headers and a protocol body

  2. What changes

    Receiver compares values before dispatch

  3. Result

    Matching requests continue to a JSON or event-stream response

Complete and reverse the trace

Given HTTP request carries headers and a protocol body and Matching requests continue to a JSON or event-stream response, write down the missing step that connects them.

Compare with the worked step

Receiver compares values before dispatch

Now take Receiver compares values before dispatch and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

HTTP request carries headers and a protocol body. Check that your implementation produces the result shown above.

Try it on a new case

A header names a report read, but the JSON body names a different operation. What should the server do?

Show worked reasoning

Reject the mismatched request before calling any handler. The server and intermediary must agree on which operation the policy evaluated.

Run, change, and build

Check this when debugging. Trusting headers without checking them against the body.

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. A header names a report read, but the JSON body names a different operation. What should the server do?

Why it matters

Remote MCP servers, the ones a company runs for its customers, speak Streamable HTTP. It's the transport behind "connect your account" in AI apps, and it's what you'll deploy when you ship a server for others. It uses everything from Phase 8: HTTP methods and status codes, headers, server-sent events, CORS-style origin checks and, in Securing remote servers with OAuth, OAuth.

What you'll be able to do

  • Send MCP requests over Streamable HTTP with the required headers
  • Explain why MCP mirrors body fields into headers, and enforce that they match
  • Map protocol outcomes onto HTTP status codes, and read JSON or event-stream replies
  • Protect a local HTTP server against DNS rebinding with Origin checks
Quick check
A company runs an MCP server on the internet for its customers. Which transport does it use?
  1. A shared folder that both sides write to
  2. stdio, through each customer's terminal
  3. Email, one message per request
  4. Streamable HTTP, with one endpoint for messages
Show the answer

Streamable HTTP, with one endpoint for messages

Remote servers speak Streamable HTTP: each message is a POST to one endpoint, and replies can stream back. stdio only works for programs started on the same machine.

The idea: one POST per message, and headers that repeat the body

This rests on Transports I: stdio: the same JSON-RPC messages, carried by a different wire. Here each message is an HTTP request, and a gateway that cannot read JSON still has to route it.

One endpoint, one POST per message

Think of a company with one mailing address. Every letter goes to the same place, in its own envelope. A Streamable HTTP server has a single URL, the MCP endpoint, such as https://shop.example/mcp. Every JSON-RPC message from the client is its own HTTP POST to that URL. The required headers:

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

{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
 "params": {"name": "get_campaign", "arguments": {"id": "cmp_103"},
            "_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
                      "io.modelcontextprotocol/clientCapabilities": {}}}}
  • Accept must list both application/json and text/event-stream, because the server may answer either way.
  • MCP-Protocol-Version repeats the version from _meta.
  • Mcp-Method repeats the method. Mcp-Name repeats the tool, prompt or resource being used, and is required for tools/call, prompts/get and resources/read.
Quick check
A client sends a tools/call for get_campaign over HTTP. Which header names the tool?
  1. Mcp-Method
  2. Content-Type
  3. Mcp-Name
  4. MCP-Protocol-Version
Show the answer

Mcp-Name

Mcp-Name repeats the tool, prompt or resource being used. It is required for tools/call, prompts/get and resources/read.

Why repeat things in headers?

A mailroom sorts by what's written on the envelope, without opening anything. Load balancers, API gateways and monitoring tools sit in front of a server in the same way. They can read headers cheaply, without parsing JSON bodies. With Mcp-Method and Mcp-Name, a gateway can rate-limit one expensive tool, route tools/call to a bigger machine pool, or chart calls per tool.

A copy can disagree with the original, so the server must check. If a header doesn't match the body, the answer is 400 with the HeaderMismatch error (code -32020). Otherwise a gateway could approve "get_campaign" while the server runs "delete_campaign".

Quick check
From the lesson on building a server: 404 means no path matches, and 405 means the path matches and the method doesn't. This toy server has one endpoint that takes POST. What does this print?
ROUTES = {"/mcp": {"POST"}}

def status(method, path):
    if path not in ROUTES:
        return 404
    return 200 if method in ROUTES[path] else 405

print(status("POST", "/mcp"), status("PUT", "/mcp"), status("POST", "/tools"))
  1. 200 404 405
  2. 200 405 404
  3. 200 404 404
  4. 200 405 405
Show the answer

200 405 404

A POST to the endpoint is accepted. A PUT to the same path finds the path and not the method: 405. A POST to a path that doesn't exist is a 404. One address, and one POST for each message: nearly everything else about this transport is in the headers and the body.

Quick check
What does this print?
calls = ["tools/list", "tools/call"]
url = "https://shop.example/mcp"
posts = [(url, c) for c in calls]
print(len({u for u, _ in posts}), len(posts))
  1. 2 1
  2. 1 2
  3. 2 2
  4. 1 1
Show the answer

1 2

The set of URLs holds just 1, and there are 2 posts, so it prints 1 2. It's one URL, with a separate POST for each message.

Quick check
A request says Mcp-Name: get_campaign in its headers, but the body calls the tool delete_campaign. What should the server do?
  1. Run get_campaign, because headers come first
  2. Reject it with 400 and HeaderMismatch (-32020)
  3. Run both
  4. Run delete_campaign, because the body is what counts
Show the answer

Reject it with 400 and HeaderMismatch (-32020)

A mismatch could trick a gateway that filters on headers. The server must refuse it rather than pick one.

Replies: status codes and two content types

For a request, the server answers with one of two content types, and clients must handle both. It's the difference between one letter and a parcel's tracking updates, which end with "delivered":

  • Content-Type: application/json: one JSON-RPC response, the simple case.
  • Content-Type: text/event-stream: a stream of server-sent events for this one request. Notifications about it, such as progress updates, come first, and the final response ends the stream:
HTTP/1.1 200 OK
Content-Type: text/event-stream
X-Accel-Buffering: no

data: {"jsonrpc":"2.0","method":"notifications/progress",
data: "params":{"progressToken":"t1","progress":50,"total":100}}

data: {"jsonrpc":"2.0","id":1,"result":{"resultType":"complete",
data: "content":[{"type":"text","text":"done"}]}}

(A data: event may span several lines, which the client joins with a newline; the JSON stays valid.) X-Accel-Buffering: no asks proxies such as nginx not to hold events back in a buffer. For a notification POST, the server answers 202 Accepted with no body.

The spec ties several protocol failures to HTTP statuses, so even code that only reads the status can react sensibly:

situationHTTP statusJSON-RPC error
headers don't match the body400-32020 HeaderMismatch
_meta is missing a required field400-32602
protocol version not supported400-32022, with the supported list
a needed client capability wasn't declared400-32021
unknown method404-32601
Origin header present but not allowed403(optional body)

Over Streamable HTTP, closing the event stream cancels the request, the way hanging up ends a call. Each request has its own stream, so a disconnect is unambiguous, and no cancel message is needed.

Quick check
A Streamable HTTP server receives a request for a method it doesn't know. What does it answer?
  1. 200 with an empty result, so the client isn't stuck
  2. 404 with JSON-RPC error -32601 (method not found)
  3. 500 Internal Server Error, with the traceback
  4. No response at all, since the method isn't known
Show the answer

404 with JSON-RPC error -32601 (method not found)

The JSON-RPC error tells the client what went wrong; the HTTP status lets gateways see it too.

Try it now

The same call as a gateway sees it. The mirrored headers are marked. Try the edit on the first request.

In your own words
How do messages travel over Streamable HTTP, and why mirror fields into headers?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: handlers, events and a live call

This part writes the checks a Streamable HTTP server applies, reads an event stream by hand, and calls the practice server with the headers it expects.

Drill

Headers must agree with the body

Write mismatches(headers, body): headers has lowercase names. If there's an mcp-method header, it must equal the body's method; for a tools/call, an mcp-name header, if present, must equal params.name. Return a list of the header names that disagree.

def mismatches(headers, body):
    return []


body = {"jsonrpc": "2.0", "id": 5, "method": "tools/call",
        "params": {"name": "delete_campaign", "arguments": {}}}
print(mismatches({"mcp-method": "tools/call", "mcp-name": "get_campaign"}, body))
In the lesson, your code is checked as you write it.

An event stream is plain text. Each event is a data: line followed by a blank line, and the last event carries the result:

import json

body = ('data: {"jsonrpc":"2.0","method":"notifications/progress",'
        '"params":{"progressToken":"t1","progress":50,"total":100}}\n\n'
        'data: {"jsonrpc":"2.0","id":1,"result":{"resultType":"complete",'
        '"content":[{"type":"text","text":"done"}]}}\n\n')
messages = [json.loads(chunk[len("data: "):]) for chunk in body.strip().split("\n\n")]
for message in messages:
    kind = "result" if "result" in message else "notification"
    print(kind, message.get("method", message.get("id")))
It runs right here in your browser, with nothing to install.

A -32602 that comes back from the dispatcher, such as an unknown tool or a bad argument, stays an HTTP 200 with the error in the body, as the practice server does. Only a missing required _meta field is a 400, and the exercise's step 5 handles it before the dispatcher runs.

Worked example

Calling the practice server over Streamable HTTP

The practice server speaks the 2026-07-28 revision when it sees the modern metadata. It always answers with plain JSON.

import requests

URL = "https://api.gradient.test/mcp"
META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientCapabilities": {},
        "io.modelcontextprotocol/clientInfo": {
            "name": "lesson-client", "version": "1.0"}}

def call(method, params=None, name=None, id=1):
    headers = {"Accept": "application/json, text/event-stream",
               "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": method}
    if name is not None:
        headers["Mcp-Name"] = name
    body = {"jsonrpc": "2.0", "id": id, "method": method,
            "params": {**(params or {}), "_meta": META}}
    r = requests.post(URL, json=body, headers=headers, timeout=10)
    return r.status_code, r.json()

args = {"name": "get_campaign", "arguments": {"id": "cmp_103"}}
status, reply = call("tools/call", args, name="get_campaign")
print(status, reply["result"]["structuredContent"]["name"])

status, reply = call("tools/call", args, name="list_campaigns")
print(status, reply["error"]["code"], reply["error"]["message"][:40])

status, reply = call("tools/delete")
print(status, reply["error"])
In the lesson you can change this and run it.

The first call succeeds. The second sends a wrong Mcp-Name, so the server refuses it with 400 and -32020. The third names a method that doesn't exist: 404 with -32601. Because each request is independent, there was no setup step at all.

Security: Origin checks and localhost

A server running on your own machine at http://127.0.0.1:8000/mcp seems unreachable from the internet. 127.0.0.1 is the address a computer uses for itself. But a web page you visit runs inside your browser, on your machine. It's a visitor already inside your house, within reach of your intercom. Through a trick called DNS rebinding, where a hostile site changes what its own name points to, the page can make your browser send requests to your local server. So:

  • Servers must check the Origin header on every request. If it's present and not on the allowlist, answer 403. Browsers always send Origin, and command-line clients usually don't.
  • A local server can also check the Host header. After rebinding, the browser still names the attacker's site there (Host: evil.example), so a server that answers only localhost, 127.0.0.1 or [::1] refuses the request.
  • Local servers should listen only on 127.0.0.1, not on every network interface (0.0.0.0).
  • Remote servers need real authentication: OAuth, covered in Securing remote servers with OAuth.

In plain words: "only on my machine" doesn't mean "safe from websites". Check where each request says it came from.

Worked example

A page that tries to reach your local server

A browser attaches an Origin header to requests a page makes, and page scripts can't fake it. A malicious website can aim at a server on your own machine, so the server must check.

ALLOWED = {"http://localhost:3000", "https://app.shop.example"}

def check_origin(headers):
    origin = headers.get("Origin")
    if origin is None:
        return 200, "no Origin: not a browser page"
    if origin in ALLOWED:
        return 200, "allowed"
    return 403, f"refused {origin}"

print(check_origin({}))
print(check_origin({"Origin": "https://app.shop.example"}))
print(check_origin({"Origin": "https://evil.example"}))
In the lesson you can change this and run it.

The last request is what an attack looks like: you visit a bad site and its script calls your local server. Binding to 127.0.0.1 alone doesn't stop it, because the request comes from your own browser, on your own machine.

Drill

Is this request really for localhost?

A local server should only answer requests addressed to itself, which blocks DNS rebinding tricks. Write local_host(host): given a Host header, return True only for localhost, 127.0.0.1 or [::1], with or without a port.

def local_host(host):
    return "localhost" in host or "127.0.0.1" in host


print(local_host("localhost:3000"), local_host("localhost.evil.test"))
In the lesson, your code is checked as you write it.
In your own words
Why does a server that only runs on your own machine still check the Origin header?

Write a sentence or two, then compare it with a good answer in the lesson.

In the SDK and a real host: serving it for real

Purpose. See the one line that turns an SDK server into a Streamable HTTP server, and what sits in front of it in production.

With the Python SDK the server you already wrote for stdio becomes an HTTP server by changing the last line. Your http_handle is what that line gives you: one POST per message at the /mcp path, the header checks, the Origin check and the status codes.

How the transport changed

You'll meet older servers, so it helps to know the history. Deprecated below means still around, but on its way out.

  • HTTP+SSE (2024-11-05) used two endpoints: one for POSTs, and one long-lived event stream for all replies. It's deprecated.
  • Streamable HTTP, legacy revisions (2025-03-26 to 2025-11-25) used one endpoint but kept sessions. The server issued an Mcp-Session-Id header at initialize, and the client sent it on every request. There was also a GET stream for server messages, and resumable streams using Last-Event-ID.
  • Streamable HTTP, 2026-07-28 removed sessions, the GET stream and resumption. Long-lived change notifications now come from a subscriptions/listen request, covered in Progress, subscriptions and multi-round-trip requests. A broken stream means the client re-sends the request with a new id.
Quick check
A modern client POSTs a notification to an MCP endpoint, and the server accepts it. What comes back?
  1. 202 Accepted with no body
  2. An event stream
  3. 204 with a JSON-RPC error
  4. 200 with a JSON-RPC result
Show the answer

202 Accepted with no body

Notifications get no JSON-RPC reply, so the HTTP answer is 202.

Behind a proxy, one setting matters: turn response buffering off for the MCP path, or progress events arrive all at once when the work ends. That is what the X-Accel-Buffering: no header in the stream above asks nginx to do. A load balancer needs no stickiness, because no session ties a client to a copy.

In an engineer's week. A remote server works from the Inspector and fails behind the company's gateway. The causes are almost always the three in this lesson: the gateway strips or rewrites Mcp-Method, so the server returns 400; it buffers the stream, so progress never shows; or an Origin it doesn't know gets a 403. Read the status and the -32020 message before anything else.

Goes deeper in

In your own words
A server works from the Inspector but returns 400 behind the company gateway. What do you look at first?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Which header must list both application/json and text/event-stream?

  1. Accept
  2. Content-Type
  3. MCP-Protocol-Version
  4. Mcp-Method

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 9 · about 13 hours of study

Model Context Protocol

Build MCP servers, clients and hosts, from the wire format to production 17 lessons 1 free
  1. JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
  2. Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
  3. Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
  4. Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
  5. Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
  6. Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
  7. Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
  8. The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
  9. Build a clientMetadata on every request, version fallback, paging and caching.40 min
  10. Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
  11. Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
  12. Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
  13. MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
  14. Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
  15. Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
  16. MCP in production: gateways, limits and auditAn allowlist, per-user rate limits, header checks and an audit log in front of many servers.35 min
  17. Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
Part of a free course 15 lessons

Build and Deploy MCP Integrations

Build a Model Context Protocol client and server, then verify the integration with a compatible host.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write