Lesson 11 · 55 minutes
Secure a remote tool server and its tokens
- Build a small HTTP tool server that checks the origin, the token, the audience and the scope
- Show that a foreign token, a missing scope and another tenant's handle are refused
- Stop two servers from offering the same tool name
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A vendor now offers a report tool server as a web service: you get an address and a token. The security lead asks: "What stops another customer's token, or a website in someone's browser, from using a server like it?" You build a small remote server on your own machine, send it requests that must fail, and name the check that stops each one.
Recall
Lesson 4. A token had a scope and a life. What did each of them limit?
The scope limits what the token can do. The life limits how long a stolen token is useful.
Lesson 8. A remote server has no file on your disk. Which pins can you still use?
The tool pin (the hash of each tool's name, description and schema). The file pin needs the code. An allowlist of addresses is the same idea, but lesson 8 does not build it.
The idea
A remote server listens on a network, so every program that can reach its address can send it a request, and it must decide who asks and what that caller may do.
- Ana → Auth server: asks for a token for this server
- Ana → Tool server: POST with the token
- Tool server → Report store: keeps each report with its owner
- Evil website → Tool server (blocked): POST from another Origin
- Ben → Report store (blocked): reads Ana's report by its handle
This lesson follows the MCP specification, revision 2026-07-28 (the pages Streamable HTTP, Authorization and Security Best Practices) and states only what they say. The specification stays the source: this lesson shows only the part of it that the lab uses.
The transport. The revision defines two standard transports: stdio and Streamable HTTP. The server has one address, the MCP endpoint, which accepts POST (the HTTP method that sends a body). The client sends every JSON-RPC message as its own POST. The reply is a JSON object (the lab) or an SSE stream (Server-Sent Events: a reply that stays open and sends events). There is no protocol-level session: Mcp-Session-Id is gone. A server that needs state hands out a handle, which the client sends back as a tool argument. Every POST carries the headers MCP-Protocol-Version and Mcp-Method, and Mcp-Name for tools/call, resources/read and prompts/get (the tool or prompt name, or the resource URI). A server must reject a request whose header differs from its body: status 400, error -32020.
Authorization is optional in MCP. An HTTP server that has it should follow the Authorization page. A stdio server should not, and takes its credentials from the environment. The server plays the role of an OAuth 2.1 resource server: it accepts access tokens that a separate authorization server issues. The client sends Authorization: Bearer <token> on every request, never in the URL. A bearer token works for whoever holds it. No good token gets status 401, and too few rights gets 403. The client asks for the token with the resource parameter (RFC 8707), which names the server. The server must accept only tokens issued for it: the audience. issue() stands in for the authorization server.
- Client → Server: POST with Origin and token
- Server: 1 Origin is on the list
- Server: 2 token is good, for this server
- Server: 3 headers match the body
- Server: 4 token has the scope of the tool
- Server: 5 the handle belongs to the caller
- Server → Client: the result, or a refusal
A tenant is one customer of a shared server. A confused deputy (an MCP proxy that uses its own power for a caller who has none) is beyond a short lab.
| Risk | Control in the lab |
|---|---|
| A website in a browser reaches the server (DNS rebinding) | Check Origin and answer 403. Servers MUST validate it |
| A token for server B is replayed at server A, or A forwards it (token passthrough) | Accept only tokens issued for this server. Never forward a client token. Servers MUST NOT |
| A token with too much power | A scope for each tool, and 403 |
| Another tenant's data (handle hijacking) | Bind each handle to the verified user. A handle is not authentication |
| A leaked token | A short life, the header only, never in the log |
This is MCP07 Insufficient Authentication & Authorization and, with the scopes, MCP02 Privilege Escalation via Scope Creep (OWASP MCP Top 10).
Results, resources, prompts and the instructions of server/discover are untrusted too, as in lesson 7. Two servers can offer one tool name, and a table of names lets the later one replace the earlier. Refusing the duplicate is a rule of this course, not of the specification.
Worked example
1. Write the server
Create remote_server.py. Its tokens work like those of labapi.py and also name the user (sub) and the server (aud). The handler makes the checks of the diagram in that order. BaseHTTPRequestHandler is the standard class for a web handler: its method do_POST runs for each POST. ThreadingHTTPServer serves each request in its own thread. threading.Thread(..., daemon=True).start() runs the server in the background, so that the same script can go on and send requests to it, and the server ends with the script. The server listens on 127.0.0.1 only. Every reply adds a line to LOG: status, user and call, never a token.
remote_server.py
"""remote_server.py: a small MCP server over HTTP, for the lab. Not a full implementation."""
import base64
import hashlib
import hmac
import json
import secrets
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PORT = 8511
VERSION = "2026-07-28"
KEY = secrets.token_bytes(32) # signs the lab tokens
URL = f"http://127.0.0.1:{PORT}/mcp" # the audience of its tokens
OTHER = "http://127.0.0.1:8512/mcp" # another server. It never runs
ORIGINS = {"https://app.lab.example"} # websites that may call it from a browser
SCOPES = {"create_report": "reports:write", "read_report": "reports:read"}
TOOLS = [{"name": "create_report", "description": "Store a report and return its handle.", "inputSchema": {"type": "object"}},
{"name": "read_report", "description": "Return the report with this handle.", "inputSchema": {"type": "object"}}]
META = f"http://127.0.0.1:{PORT}/.well-known/oauth-protected-resource" # where a client finds the server's metadata
REPORTS, LOG = {}, []
BIND = True # a report belongs to its maker. One test turns this off
def issue(sub, scopes, aud=URL, ttl=60):
body = json.dumps({"sub": sub, "scopes": sorted(scopes), "aud": aud, "exp": time.time() + ttl}).encode()
return base64.urlsafe_b64encode(body).decode() + "." + hmac.new(KEY, body, hashlib.sha256).hexdigest()
def verify(token, aud=URL):
"""Return the claims of a good token, or raise PermissionError."""
part, _, sig = token.partition(".")
try:
body = base64.urlsafe_b64decode(part)
ok = hmac.compare_digest(sig.encode(), hmac.new(KEY, body, hashlib.sha256).hexdigest().encode())
except ValueError:
ok = False
if not ok:
raise PermissionError("bad token")
claims = json.loads(body)
if time.time() > claims["exp"]:
raise PermissionError("token expired")
if claims["aud"] != aud:
raise PermissionError("token is for another server")
return claims
def run_tool(name, args, sub):
"""Return the text of the result and whether it is an error."""
if name == "create_report":
handle = secrets.token_hex(8) # random
REPORTS[handle] = {"owner": sub, "text": args.get("text", "")}
return handle, False
report = REPORTS.get(args.get("handle"))
if report is None or (BIND and report["owner"] != sub):
return "no such report", True # the same for "missing" and "not yours"
return report["text"], False
class Handler(BaseHTTPRequestHandler):
who = what = "-"
def reply(self, status, payload, headers=()):
LOG.append(f"{status} {self.who} {self.what}")
data = json.dumps(payload).encode()
self.send_response(status)
for key, value in [("Content-Type", "application/json"), ("Content-Length", str(len(data))), *headers]:
self.send_header(key, value)
self.end_headers()
self.wfile.write(data)
def do_POST(self):
origin, auth = self.headers.get("Origin"), self.headers.get("Authorization", "")
if self.path != "/mcp":
return self.reply(404, {"error": "not found"})
if origin is not None and origin not in ORIGINS: # a tab of another website
return self.reply(403, {"error": "origin not allowed"})
try:
claims = verify(auth.removeprefix("Bearer "))
except PermissionError as e:
return self.reply(401, {"error": str(e)}, [("WWW-Authenticate", f'Bearer resource_metadata="{META}"')])
self.who = claims["sub"]
try:
msg = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
method, params = msg["method"], msg.get("params") or {}
version, name = params.get("_meta", {}).get("io.modelcontextprotocol/protocolVersion"), params.get("name")
except (ValueError, KeyError, TypeError, AttributeError): # not JSON, not an object, no method
return self.reply(400, {"error": "bad request"})
self.what = f"{method} {name or ''}".strip()
if (self.headers.get("MCP-Protocol-Version"), self.headers.get("Mcp-Method"), self.headers.get("Mcp-Name")) != (version, method, name): # header and body must agree
return self.reply(400, {"error": {"code": -32020, "message": "Header mismatch"}})
if method == "tools/list":
result = {"tools": TOOLS}
elif method == "tools/call":
need = SCOPES.get(name, "unknown") # nobody has this scope
if need not in claims["scopes"]:
return self.reply(403, {"error": "insufficient scope"}, [("WWW-Authenticate", f'Bearer error="insufficient_scope", scope="{need}", resource_metadata="{META}"')])
text, bad = run_tool(name, params.get("arguments") or {}, claims["sub"])
result = {"content": [{"type": "text", "text": text}], "isError": bad}
else:
return self.reply(404, {"error": {"code": -32601, "message": "Method not found"}})
self.reply(200, {"jsonrpc": "2.0", "id": msg.get("id"), "result": {"resultType": "complete", **result}})
def log_message(self, *args):
pass # LOG is the record
def start():
server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return serverThe checks sit in do_POST, in the order of the drawing:
- 1:
origin not in ORIGINSgives 403. A client that is not a browser sends noOrigin, so this check stops websites: it does not identify callers. - 2:
verifyraises for a bad, expired or foreign token: 401. A body that is not JSON gets 400. - 3: the three headers must equal the body: 400.
- 4 and 5:
SCOPESgives 403, andrun_toolcompares the owner of the handle.
This is a minimal teaching server: no server/discover, no HTTPS, no Base64 form of Mcp-Name, and it accepts any version in _meta.
2. Send requests that must fail
Create remote_client.py. post sends one request with the headers of the specification. urllib raises HTTPError for a status of 400 or more, and post returns it as a normal result.
remote_client.py
"""remote_client.py: send one request to the remote lab server."""
import json
import urllib.error
import urllib.request
import remote_server as rs
def post(token, method, params=None, **headers):
"""One POST to the MCP endpoint. Return the HTTP status, the decoded body and the reply headers."""
params = {**(params or {}), "_meta": {"io.modelcontextprotocol/protocolVersion": rs.VERSION}}
sent = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
"MCP-Protocol-Version": rs.VERSION, "Mcp-Method": method}
if "name" in params:
sent["Mcp-Name"] = params["name"]
if token:
sent["Authorization"] = "Bearer " + token
sent.update({k.replace("_", "-"): v for k, v in headers.items()}) # Mcp_Name="x" sends Mcp-Name: x
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
try:
with urllib.request.urlopen(urllib.request.Request(rs.URL, body, sent)) as reply:
return reply.status, json.load(reply), reply.headers
except urllib.error.HTTPError as e:
return e.code, json.load(e), e.headersNow try_remote.py sends seven requests. Each row of rows is a lambda (lesson 1), so that the request is sent only when the loop calls it. The first line is the WWW-Authenticate header of a 401. It tells a client where the metadata document of the server is (RFC 9728), and the lab does not serve that document.
try_remote.py
import remote_server as rs
from remote_client import post
server = rs.start()
both = {"reports:read", "reports:write"}
good = rs.issue("ana", both)
write = {"name": "create_report", "arguments": {"text": "x"}}
print(post(None, "tools/list")[2]["WWW-Authenticate"])
rows = {
"good token": lambda: post(good, "tools/list"),
"no token": lambda: post(None, "tools/list"),
"token for another server": lambda: post(rs.issue("ana", both, aud=rs.OTHER), "tools/list"),
"expired token": lambda: post(rs.issue("ana", both, ttl=-1), "tools/list"),
"read-only token, write tool": lambda: post(rs.issue("ana", {"reports:read"}), "tools/call", write),
"origin of another website": lambda: post(good, "tools/list", Origin="http://evil.example"),
"header names another tool": lambda: post(good, "tools/call", write, Mcp_Name="read_report"),
}
for label, send in rows.items():
status, body, _ = send()
error = body.get("error") # a JSON-RPC error is a dict with a code
print(f"{label:28} {status} {error['code'] if isinstance(error, dict) else ''}".rstrip())
server.shutdown()python3 try_remote.pyBearer resource_metadata="http://127.0.0.1:8511/.well-known/oauth-protected-resource"
good token 200
no token 401
token for another server 401
expired token 401
read-only token, write tool 403
origin of another website 403
header names another tool 400 -32020The foreign token is valid and signed, and the server still refuses it: its audience is the other server. The read-only token is known, so it gets 403, not 401. The last row is the gap that a gateway would miss.
If port 8511 is busy on your machine, change PORT in remote_server.py, and OTHER to a different port. Only the first line of the output changes.
3. Separate two tenants
Create try_tenants.py. Ana makes a report, and Ben, another tenant with the same scopes, asks for it by its handle. The loop runs the test with BIND off, then on. LOG is the log of the server.
try_tenants.py
import remote_server as rs
from remote_client import post
server = rs.start()
both = {"reports:read", "reports:write"}
ana, ben = rs.issue("ana", both), rs.issue("ben", both)
def call(token, name, **arguments):
return post(token, "tools/call", {"name": name, "arguments": arguments})[1]["result"]["content"][0]["text"]
for rs.BIND in (False, True):
handle = call(ana, "create_report", text="Ana: salary review")
print(f"BIND={rs.BIND}: Ben reads Ana's report ->", call(ben, "read_report", handle=handle))
print("Ana reads her own report ->", call(ana, "read_report", handle=handle))
print("a token appears in the log:", any(t in line for t in (ana, ben) for line in rs.LOG))
server.shutdown()python3 try_tenants.pyBIND=False: Ben reads Ana's report -> Ana: salary review
BIND=True: Ben reads Ana's report -> no such report
Ana reads her own report -> Ana: salary review
a token appears in the log: FalseBoth calls of Ben had a valid token with the right scope. Only the owner check stopped the second. "No such report" is the same for a missing report and for another tenant's, so Ben learns nothing about other handles.
4. Refuse a tool name that two servers offer
Create try_merge.py. merge_tools takes the tool lists of several servers and refuses a name that two of them offer. A plain dictionary of tools would let the later entry replace the earlier one.
try_merge.py
import remote_server as rs
def merge_tools(lists):
"""lists maps a server name to its list of tools. Refuse two servers that offer the same tool name."""
owner = {}
for server, tools in lists.items():
for tool in tools:
if tool["name"] in owner:
raise ValueError(f"tool {tool['name']} is offered by {owner[tool['name']]} and by {server}")
owner[tool["name"]] = server
return owner
mine = {"invoices": rs.TOOLS}
for other in ({"name": "read_report"}, {"name": "send_report"}):
try:
print(merge_tools({**mine, "vendor": [other]}))
except ValueError as e:
print("refused:", e)python3 try_merge.pyrefused: tool read_report is offered by invoices and by vendor
{'create_report': 'invoices', 'read_report': 'invoices', 'send_report': 'vendor'}Your turn
The vendor asks for a third tool. There are no steps here: change remote_server.py and reuse try_tenants.py.
- Add the tool
count_reports. It takes no argument, needs the scopereports:read, and returns, as text, the number of reports of the caller. - Start the server. Ana makes two reports and Ben makes one, both with a token for both scopes. Call
count_reportsas Ana and as Ben. - Call it with a token for Ana that is issued for
rs.OTHER, and with a token for Ana that has onlyreports:write. Read both statuses.
Check yourself
A token has a valid signature. Why check its audience too?
Other servers get tokens that look the same. Without the check, a token issued for server B works at server A, and whoever runs B can replay the tokens that its users send to it.
The header says read_report, and the body calls create_report. Who is fooled if the server trusts the header?
A gateway that allows only read_report by header lets the request through, and the server runs create_report. The server must compare header and body.
Why is holding a handle not proof that the caller owns the report?
A handle can leak in a log or a chat. The server must store the owner with the handle and compare it with the user of the verified token.
Field notes
- Serve the MCP endpoint over HTTPS: a bearer token on plain HTTP can be read.
- A remote server's code can change at any time and your data leaves your machine. Treat the vendor as a supplier: contract, review, register.
- Keep access tokens short and per user, and never log the
Authorizationheader, not even in a gateway. Alert on a run of 401 or 403 from one user (lesson 10).