How an MCP server answers over HTTP
Streamable HTTP is the MCP transport for a server that runs on its own, on your machine or across the internet. Every message from the client is one HTTP POST to one address.
It matters because a server on the web is reachable by anyone. You will run one and send it good and bad requests.
By the end of this lesson
Note
I can read an MCP request over Streamable HTTP and say how the server must answer it.
Key words
| Word | What it means | Example |
|---|---|---|
| Endpoint | the one address an MCP server takes requests at | /mcp |
| Header | a named line of information sent before the body | |
| Event stream | a reply sent in pieces, each a data line | text/event-stream |
| Origin | the web site a browser request came from | |
| Loopback | the address that reaches only this machine | 127.0.0.1 |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsEvery message is its own POST
The server offers one endpoint, such as /mcp, and takes POST. Each JSON-RPC request is the body of one POST.
The client sends Accept: application/json, text/event-stream, because the server may answer either way. It also copies parts of the body into headers: MCP-Protocol-Version, Mcp-Method, and Mcp-Name for a tool call. A gateway can route on the headers without reading the body.
Worked example: a tools/call request
| Line | Value | Why |
|---|---|---|
| POST /mcp | One endpoint | Every message goes to the same address |
| Accept | application/json, text/event-stream | The client takes either kind of answer |
| MCP-Protocol-Version | 2026-07-28 | Must equal the version in the body's _meta |
| Mcp-Method | tools/call | Must equal the body's method |
| Mcp-Name | count_down | Must equal params.name |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsTwo ways to answer, and the refusals
For a quick answer the server replies with one JSON object. For slow work it replies with an event stream: progress notifications first, then the final result, all about that one request.
If a header disagrees with the body, the server answers 400 with error -32020. An unknown version gets 400 with -32022. A notification the server accepts gets 202 with no body.
Try it: read an event stream
# An event stream is lines of text. Each "data:" line carries one JSON message.
import json
body = """data: {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progress": 1, "total": 2}}
data: {"jsonrpc": "2.0", "id": 1, "result": {"resultType": "complete", "content": []}}
"""
for line in body.splitlines():
if line.startswith("data: "):
message = json.loads(line[6:])
print("final answer" if "id" in message else "on the way", message)
# Add a third data line with a second progress message, then press Run.
Make a free account to save your work and track your progress.
A local server checks the Origin
A web page you visit can try to send requests to a server on your own machine. So the server must check the Origin header, and answer 403 when it comes from a site it does not trust.
A local server should also listen only on the loopback address, 127.0.0.1, so other machines cannot reach it at all. Since 2026-07-28 there are no sessions, so a GET to the endpoint gets 405.
Write the HTTP server, part 1
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"An MCP server on Streamable HTTP: one endpoint, /mcp, that takes POST.\"\"\"' 'import json' 'import threading' 'from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer' 'VERSION = \"2026-07-28\"' 'ALLOWED = [\"http://127.0.0.1:8765\"]' 'TOOLS = [{\"name\": \"count_down\", \"description\": \"Counts down from 3.\",' ' \"inputSchema\": {\"type\": \"object\", \"properties\": {}}}]' 'class Handler(BaseHTTPRequestHandler):' ' def log_message(self, *args):' ' pass' '' ' def send(self, status, kind, text):' ' self.send_response(status)' ' if kind:' ' self.send_header(\"Content-Type\", kind)' ' self.send_header(\"Content-Length\", str(len(text.encode())))' ' self.end_headers()' ' self.wfile.write(text.encode())' '' ' def refuse(self, status, msg_id, code, message, data=None):' > mcp/web.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the HTTP server, part 2
docker exec tools sh -c "printf '%s\n' ' body = {\"jsonrpc\": \"2.0\", \"id\": msg_id, \"error\": {\"code\": code, \"message\": message}}' ' if data:' ' body[\"error\"][\"data\"] = data' ' self.send(status, \"application/json\", json.dumps(body))' '' ' def do_GET(self):' ' self.send(405, None, \"\")' ' def do_POST(self):' ' origin = self.headers.get(\"Origin\")' ' if origin and origin not in ALLOWED:' ' return self.send(403, None, \"\")' ' msg = json.loads(self.rfile.read(int(self.headers[\"Content-Length\"])))' ' if \"id\" not in msg:' ' return self.send(202, None, \"\")' ' meta = msg.get(\"params\", {}).get(\"_meta\", {})' ' said = meta.get(\"io.modelcontextprotocol/protocolVersion\")' ' if not self.headers.get(\"MCP-Protocol-Version\") == said:' ' return self.refuse(400, msg[\"id\"], -32020, \"Header mismatch: MCP-Protocol-Version\")' >> mcp/web.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the HTTP server, part 3
docker exec tools sh -c "printf '%s\n' ' if not self.headers.get(\"Mcp-Method\") == msg[\"method\"]:' ' return self.refuse(400, msg[\"id\"], -32020, \"Header mismatch: Mcp-Method\")' ' if msg[\"method\"] == \"tools/call\" and not self.headers.get(\"Mcp-Name\") == msg[\"params\"].get(\"name\"):' ' return self.refuse(400, msg[\"id\"], -32020, \"Header mismatch: Mcp-Name\")' ' if not said == VERSION:' ' return self.refuse(400, msg[\"id\"], -32022, \"Unsupported protocol version\",' ' {\"supported\": [VERSION], \"requested\": said})' ' if msg[\"method\"] == \"tools/list\":' ' result = {\"resultType\": \"complete\", \"tools\": TOOLS, \"ttlMs\": 60000, \"cacheScope\": \"public\"}' ' reply = {\"jsonrpc\": \"2.0\", \"id\": msg[\"id\"], \"result\": result}' ' return self.send(200, \"application/json\", json.dumps(reply))' >> mcp/web.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the HTTP server, part 4
docker exec tools sh -c "printf '%s\n' ' if msg[\"method\"] == \"tools/call\":' ' events = []' ' for left in [3, 2, 1]:' ' note = {\"progressToken\": meta.get(\"progressToken\"), \"progress\": 4 - left, \"total\": 3}' ' events.append({\"jsonrpc\": \"2.0\", \"method\": \"notifications/progress\", \"params\": note})' ' done = {\"resultType\": \"complete\", \"content\": [{\"type\": \"text\", \"text\": \"Lift off\"}]}' ' events.append({\"jsonrpc\": \"2.0\", \"id\": msg[\"id\"], \"result\": done})' ' text = \"\".join(\"data: \" + json.dumps(one) + chr(10) + chr(10) for one in events)' ' return self.send(200, \"text/event-stream\", text)' ' self.refuse(404, msg[\"id\"], -32601, \"Method not found\")' 'def start():' ' \"\"\"Serves in a thread on the loopback address only, so nothing outside this box can reach it.\"\"\"' >> mcp/web.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the HTTP server, part 5
docker exec tools sh -c "printf '%s\n' ' server = ThreadingHTTPServer((\"127.0.0.1\", 8765), Handler)' ' threading.Thread(target=server.serve_forever, daemon=True).start()' ' return server' >> mcp/web.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the client, part 1
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A client for web.py: each JSON-RPC message is its own POST to /mcp.\"\"\"' 'import http.client' 'import json' 'import web' 'web.start()' '' '' 'def post(method, version=\"2026-07-28\", header=None, origin=None, name=None):' ' meta = {\"io.modelcontextprotocol/protocolVersion\": version, \"progressToken\": \"t1\"}' ' msg = {\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": method, \"params\": {\"_meta\": meta}}' ' headers = {\"Content-Type\": \"application/json\", \"Accept\": \"application/json, text/event-stream\",' ' \"MCP-Protocol-Version\": header or version, \"Mcp-Method\": method}' ' if origin:' ' headers[\"Origin\"] = origin' ' if name:' ' msg[\"params\"][\"name\"] = name' ' headers[\"Mcp-Name\"] = name' ' link = http.client.HTTPConnection(\"127.0.0.1\", 8765)' ' link.request(\"POST\", \"/mcp\", json.dumps(msg), headers)' > mcp/webclient.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the client, part 2
docker exec tools sh -c "printf '%s\n' ' answer = link.getresponse()' ' body = answer.read().decode().strip()' ' print(answer.status, answer.getheader(\"Content-Type\"))' ' for line in body.splitlines():' ' if line:' ' print(\" \", line)' '' '' 'print(\"1. tools/list\")' 'post(\"tools/list\")' 'print(\"2. tools/call, answered as a stream\")' 'post(\"tools/call\", name=\"count_down\")' 'print(\"3. a header that does not match the body\")' 'post(\"tools/list\", header=\"2025-06-18\")' 'print(\"4. a version the server does not know\")' 'post(\"tools/list\", version=\"2025-11-25\")' 'print(\"5. a page on another site tries to call it\")' 'post(\"tools/list\", origin=\"http://evil.example\")' 'link = http.client.HTTPConnection(\"127.0.0.1\", 8765)' 'link.request(\"GET\", \"/mcp\")' 'print(\"6. GET\", link.getresponse().status)' >> mcp/webclient.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Send six requests to the server
docker exec tools python3 mcp/webclient.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What webclient.py printed
| Request | Status and type | Body |
|---|---|---|
| 1 tools/list | 200 application/json | The count_down tool, ttlMs 60000 |
| 2 tools/call | 200 text/event-stream | Progress 1, 2 and 3 of 3, then "Lift off" |
| 3 Header says 2025-06-18 | 400 application/json | Error -32020, Header mismatch: MCP-Protocol-Version |
| 4 Version 2025-11-25 | 400 application/json | Error -32022 with supported ["2026-07-28"] |
| 5 Origin http://evil.example | 403 | No body |
| 6 GET /mcp | 405 | No body |
The cells students fill in are left blank in this preview.
Check the Run
Have a go
Check the Run
3 questionsA common mistake
Warning
Many people think a server on their own laptop is safe because it is local. A web page in your browser can still send it requests. Check the Origin header and listen on 127.0.0.1 only, then add real authentication as lesson 3 shows.
The checks a server makes on each POST
flowchart TD
A[POST /mcp] --> B{Origin allowed?}
B -->|no| X[403]
B -->|yes| C{Has an id?}
C -->|no| N[202]
C -->|yes| D{Headers match body?}
D -->|no| E[400, -32020]
D -->|yes| F{Version known?}
F -->|no| G[400, -32022]
F -->|yes| H[200, JSON or stream]Match each answer to its cause
Have a go
Loading…
Your answers are marked here and are not kept. An account keeps your marks.
Assignment: check a POST
Write the checks an MCP server makes on each POST, and read an event stream.
check_post(headers, body, allowed) returns [status, code] by the rules in the starter's comments, in that order. Header names may arrive in any case. sse_messages(text) returns the JSON on each data: line of an event stream, in order.
import json
SUPPORTED = ["2026-07-28"]
def check_post(headers, body, allowed):
# headers: a dictionary of HTTP headers (names in any case). body: the JSON text.
# allowed: the Origin values this server accepts.
# Return [status, code], code being a JSON-RPC error code or None. In this order:
# an Origin not in allowed: [403, None]
# a body with no "id" (a notification): [202, None]
# MCP-Protocol-Version or Mcp-Method missing or unlike the body: [400, -32020]
# tools/call whose Mcp-Name is missing or unlike params.name: [400, -32020]
# a version not in SUPPORTED: [400, -32022]
# otherwise [200, None]
return [200, None]
def sse_messages(text):
# The JSON messages on the "data: " lines of an event stream, in order.
return []
Make a free account to save your work and track your progress.
Exit quiz
Have a go