Build and Deploy MCP Integrations
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
One endpoint, required headers, JSON or event-stream replies.
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.
HTTP request carries headers and a protocol body
Receiver compares values before dispatch
Matching requests continue to a JSON or event-stream response
HTTP request carries headers and a protocol body
Receiver compares values before dispatch
Matching requests continue to a JSON or event-stream response
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.
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.
HTTP request carries headers and a protocol body. Check that your implementation produces the result shown above.
A header names a report read, but the JSON body names a different operation. What should the server do?
Reject the mismatched request before calling any handler. The server and intermediary must agree on which operation the policy evaluated.
Check this when debugging. Trusting headers without checking them against the body.
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.
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.
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.
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.Mcp-Name
Mcp-Name repeats the tool, prompt or resource being used. It is required for tools/call, prompts/get and resources/read.
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".
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"))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.
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
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.
Mcp-Name: get_campaign in its headers, but the body calls the tool delete_campaign. What should the server do?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.
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:
| situation | HTTP status | JSON-RPC error |
|---|---|---|
| headers don't match the body | 400 | -32020 HeaderMismatch |
_meta is missing a required field | 400 | -32602 |
| protocol version not supported | 400 | -32022, with the supported list |
| a needed client capability wasn't declared | 400 | -32021 |
| unknown method | 404 | -32601 |
Origin header present but not allowed | 403 | (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.
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.
The same call as a gateway sees it. The mirrored headers are marked. Try the edit on the first request.
Write a sentence or two, then compare it with a good answer in the lesson.
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.
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))
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")))
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.
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"])
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.
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:
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.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.127.0.0.1, not on every network interface (0.0.0.0).In plain words: "only on my machine" doesn't mean "safe from websites". Check where each request says it came from.
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"}))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.
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"))
Write a sentence or two, then compare it with a good answer in the lesson.
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.
You'll meet older servers, so it helps to know the history. Deprecated below means still around, but on its way out.
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.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.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.
Mcp-Method and Mcp-Name on purpose.Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Which header must list both application/json and text/event-stream?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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