AI and machine learning · Advanced · 30 min
Serve an MCP server over Streamable HTTP with authentication
By Padding · Updated 18 Nov 2026
Python 3.15 · mcp 2.3.0 · uvicorn 0.54.0
You will run an MCP server over Streamable HTTP on localhost that checks the Origin header, accepts only bearer tokens your token verifier knows, limits each tool to the right scope, and refuses calls without a token.
On this page
A stdio MCP server runs as a child process of one app on one machine. That is the safest place for it, and it is also the limit: a team cannot share it, and a web-based assistant cannot reach it. The Streamable HTTP transport moves the server behind a single HTTP endpoint, usually /mcp, where every client message is an HTTP POST and every reply is JSON or a short event stream.
Once a server listens on a port, anything that can reach that port can call its tools. The MCP specification asks HTTP servers for three things: check the Origin header so a web page cannot use DNS rebinding to reach a local server, bind to 127.0.0.1 when running locally, and authenticate every connection. For authentication it uses the OAuth 2.1 model. The MCP server is a resource server: it never handles passwords or logins. A separate authorisation server issues access tokens, the client sends one in an Authorization: Bearer header on every request, and the MCP server checks that the token is valid, was issued for this server and carries the scopes the tool needs.
In this tutorial you build that resource server for a small clinic-hours service with two tools: one that reads opening hours and one that sets a notice, such as a holiday closure. You use the official Python SDK, mcp 2.3.0, served by uvicorn. In place of an authorisation server you start with two static tokens, then write the JWT verifier you would use with a real one. The token checks, the scopes and the Origin rule are the same either way.
Step 1 · Create the project
Make a throwaway project folder and add the SDK and uvicorn at exact versions, so a later release cannot change behaviour under you:
mkdir -p ~/mcp-http-demo
cd ~/mcp-http-demo
uv init --no-package
uv add "mcp==2.3.0" "uvicorn==0.54.0"mcp brings its own HTTP stack with it: Starlette for the server side, httpx2 for the client, and PyJWT for token handling. You use all three later.
Check it worked
uv run python -c "import importlib.metadata as m; print(m.version('mcp'), m.version('uvicorn'))"The command prints 2.3.0 0.54.0.
Step 2 · Create two tokens and keep them out of Git
The demo has two callers: a front desk that may only read hours, and a clinic admin who may also post notices. Each gets a long random token. Create the file that holds them with private permissions from the start, so the tokens are never readable by other users, even for a moment:
(umask 077; python3 - > tokens.env <<'PY'
import secrets
print(f"MCP_READ_TOKEN={secrets.token_urlsafe(32)}")
print(f"MCP_ADMIN_TOKEN={secrets.token_urlsafe(32)}")
PY
)
echo "tokens.env" >> .gitignore
ls -l tokens.envsecrets.token_urlsafe(32) returns 32 random bytes as 43 URL-safe characters. The server and the client read the tokens from environment variables loaded from this file, so they never appear in your code, your shell history or a process list.
Check it worked
ls -l shows -rw------- at the start of the line: only you can read or write tokens.env. grep -c TOKEN tokens.env prints 2, and git will ignore the file if you turn the folder into a repository.
Step 3 · Write the server
Create server.py. It has four parts: the clinic data, a token verifier, a helper that checks scopes inside tools, and the HTTP app with its Host and Origin rules.
cat > server.py <<'PY'
import hmac
import os
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
HOST = "127.0.0.1"
PORT = 8765
RESOURCE = f"http://{HOST}:{PORT}/mcp"
ISSUER = "https://auth.example.com" # replace with your authorisation server
CLINICS = {
"ikeja": {"name": "Ikeja Family Clinic", "hours": "Mon-Fri 08:00-18:00, Sat 09:00-13:00", "notice": ""},
"westlands": {"name": "Westlands Health Centre", "hours": "Mon-Sat 07:30-19:00", "notice": ""},
}
def require_env(name: str) -> str:
value = os.environ.get(name, "")
if len(value) < 32:
raise SystemExit(f"{name} must be set to a random token of at least 32 characters")
return value
class StaticTokenVerifier:
"""Accepts a fixed set of tokens. Stands in for a real authorisation server."""
def __init__(self, grants: list[tuple[str, str, list[str]]]):
self._grants = grants
async def verify_token(self, token: str) -> AccessToken | None:
for secret, client_id, scopes in self._grants:
if hmac.compare_digest(token.encode(), secret.encode()):
return AccessToken(token=token, client_id=client_id, scopes=scopes, resource=RESOURCE)
return None
verifier = StaticTokenVerifier([
(require_env("MCP_READ_TOKEN"), "front-desk", ["clinic:read"]),
(require_env("MCP_ADMIN_TOKEN"), "clinic-admin", ["clinic:read", "clinic:write"]),
])
mcp = MCPServer(
"clinic-hours",
token_verifier=verifier,
auth=AuthSettings(
issuer_url=ISSUER,
resource_server_url=RESOURCE,
required_scopes=["clinic:read"],
validate_token_resource=True,
),
)
def require_scope(scope: str) -> AccessToken:
token = get_access_token()
if token is None or scope not in token.scopes:
raise ToolError(f"This token does not have the {scope} scope.")
return token
def find_clinic(clinic: str) -> dict:
key = clinic.strip().lower()
if key not in CLINICS:
raise ToolError(f"Unknown clinic {clinic!r}. Choose one of: {', '.join(sorted(CLINICS))}.")
return CLINICS[key]
@mcp.tool()
def get_hours(clinic: str) -> str:
"""Return the opening hours and any notice for a clinic: ikeja or westlands."""
require_scope("clinic:read")
record = find_clinic(clinic)
text = f"{record['name']}: {record['hours']}"
if record["notice"]:
text += f". Notice: {record['notice']}"
return text
@mcp.tool()
def set_notice(clinic: str, notice: str) -> str:
"""Set a short notice shown with a clinic's hours, such as a holiday closure."""
token = require_scope("clinic:write")
record = find_clinic(clinic)
if len(notice) > 200:
raise ToolError("Keep the notice under 200 characters.")
record["notice"] = notice.strip()
return f"Notice for {record['name']} saved by {token.client_id}."
app = mcp.streamable_http_app(
host=HOST,
transport_security=TransportSecuritySettings(
allowed_hosts=[f"127.0.0.1:{PORT}", f"localhost:{PORT}"],
allowed_origins=[f"http://127.0.0.1:{PORT}", f"http://localhost:{PORT}"],
),
)
PYWhat each part does:
StaticTokenVerifierfollows the SDK'sTokenVerifiershape: one async method,verify_token, that returns anAccessTokenfor a good token andNonefor anything else.hmac.compare_digestcompares in constant time, so response timing does not leak how much of a guess was right. The SDK also rejects anAccessTokenwhoseexpires_athas passed.AuthSettingsturns authentication on.required_scopes=["clinic:read"]means every request needs at least that scope, or it gets403 insufficient_scope.resource_server_urlnames this server, andvalidate_token_resource=Truemakes the SDK refuse a token whoseresource(its audience) is a different server.issuer_urlis the authorisation server that clients are told to get tokens from.require_scopereads the token for the current request withget_access_token(). RaisingToolErrorreturns the message to the client as a tool error, which the model can read, instead of crashing the request.TransportSecuritySettingslists theHostandOriginvalues the server accepts. A request with any otherHostgets421, and one with any otherOrigingets403. A request with noOriginat all is allowed, because programs that are not browsers (the SDK client, curl) do not send one. The SDK turns on similar rules by itself whenhostis a localhost address; writing them out with the exact port makes the policy visible and lets you add your public hostname later.
The server refuses to start without its tokens. Failing closed is the point: a missing variable must never mean "no authentication".
Check it worked
uv run python -c "import server" || echo "refused to start without tokens"
uv run --env-file tokens.env python -c "import server; print(server.RESOURCE)"The first command prints MCP_READ_TOKEN must be set to a random token of at least 32 characters and then refused to start without tokens. The second loads the tokens with --env-file and prints http://127.0.0.1:8765/mcp.
Step 4 · Start the server on localhost
Start uvicorn in your second terminal, from ~/mcp-http-demo, and leave it running. --host 127.0.0.1 keeps the port closed to the rest of the network:
cd ~/mcp-http-demo
uv run --env-file tokens.env uvicorn server:app --host 127.0.0.1 --port 8765uvicorn logs Uvicorn running on http://127.0.0.1:8765. Never start it with --host 0.0.0.0 on a laptop or a shared network. To serve other people, keep it on 127.0.0.1, put a reverse proxy with TLS in front (as in the Nginx reverse proxy tutorial), and add the public hostname and origin to the two lists in server.py. Tokens sent over plain HTTP can be read by anyone on the path.
Run the rest of the commands in your first terminal, in ~/mcp-http-demo.
Check it worked
Because resource_server_url is set, the SDK publishes OAuth protected resource metadata (RFC 9728) at a well-known address. It tells a client which authorisation server to ask for a token:
curl -s http://127.0.0.1:8765/.well-known/oauth-protected-resource/mcp
echoYou see one line of JSON with "resource":"http://127.0.0.1:8765/mcp", an authorization_servers list holding https://auth.example.com, and "scopes_supported":["clinic:read"].
Step 5 · Confirm that unauthenticated and cross-site requests are refused
Send an MCP request with no token:
curl -s -i -X POST http://127.0.0.1:8765/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
echoThe reply is HTTP/1.1 401 Unauthorized with a www-authenticate header that starts Bearer error="invalid_token" and ends with resource_metadata="http://127.0.0.1:8765/.well-known/oauth-protected-resource/mcp". That header is how a real MCP client discovers where to log in: it fetches the metadata from the last step, finds the authorisation server, gets a token for this resource and retries.
Two more refusals need a token, so do them from Python, which reads the tokens from the environment and keeps them off the command line. Create probe.py:
cat > probe.py <<'PY'
import os
import httpx2
URL = "http://127.0.0.1:8765/mcp"
BODY = {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}
ACCEPT = {"Accept": "application/json, text/event-stream"}
def post(headers: dict) -> httpx2.Response:
return httpx2.post(URL, json=BODY, headers={**ACCEPT, **headers}, timeout=10.0)
wrong = post({"Authorization": "Bearer not-a-token-we-issued"})
print("wrong token:", wrong.status_code)
reader = os.environ["MCP_READ_TOKEN"]
cross_site = post({"Authorization": f"Bearer {reader}", "Origin": "https://clinic-offers.example"})
print("other origin:", cross_site.status_code, cross_site.text.strip())
PY
uv run --env-file tokens.env python probe.pyThe second request carries a valid token but claims to come from a web page on another site. That is what a DNS rebinding attack looks like from the server's side, and the Origin check stops it even though the token is good.
Check it worked
The output is two lines: wrong token: 401 and other origin: 403 Invalid Origin header.
Step 6 · Call the tools with the SDK client
The SDK's Client connects to a URL over Streamable HTTP. To add the bearer token, give its transport your own httpx2.AsyncClient with the header set. Create client.py. It lists the tools, then tries each tool with each token, and finally connects with no token at all:
cat > client.py <<'PY'
import asyncio
import os
import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
URL = "http://127.0.0.1:8765/mcp"
def http_client(token: str | None) -> httpx2.AsyncClient:
headers = {"Authorization": f"Bearer {token}"} if token else {}
return httpx2.AsyncClient(headers=headers, timeout=30.0)
async def tool_names(token: str) -> list[str]:
async with http_client(token) as http:
async with Client(streamable_http_client(URL, http_client=http)) as client:
listing = await client.list_tools()
return sorted(tool.name for tool in listing.tools)
async def call(token: str | None, tool: str, arguments: dict) -> str:
async with http_client(token) as http:
async with Client(streamable_http_client(URL, http_client=http)) as client:
result = await client.call_tool(tool, arguments)
label = "error" if result.is_error else "ok"
return f"{label}: {result.content[0].text}"
async def main() -> None:
reader = os.environ["MCP_READ_TOKEN"]
admin = os.environ["MCP_ADMIN_TOKEN"]
notice = {"clinic": "ikeja", "notice": "Closed on 1 January"}
print("tools:", await tool_names(reader))
print("front desk reads:", await call(reader, "get_hours", {"clinic": "ikeja"}))
print("front desk writes:", await call(reader, "set_notice", notice))
print("admin writes:", await call(admin, "set_notice", notice))
print("front desk reads:", await call(reader, "get_hours", {"clinic": "ikeja"}))
try:
await call(None, "get_hours", {"clinic": "ikeja"})
print("no token: accepted")
except Exception as exc:
print(f"no token: refused ({type(exc).__name__})")
asyncio.run(main())
PY
uv run --env-file tokens.env python client.pyEach call opens its own connection here, so that every line shows one token's result on its own. In an app you keep one Client open per user for as long as you need it. If your users are on mobile data, that is also kinder to their bundle: each tool call is one small POST, and nothing stays open between calls.
Check it worked
The output has six lines, something like:
tools: ['get_hours', 'set_notice']
front desk reads: ok: Ikeja Family Clinic: Mon-Fri 08:00-18:00, Sat 09:00-13:00
front desk writes: error: Error executing tool set_notice: This token does not have the clinic:write scope.
admin writes: ok: Notice for Ikeja Family Clinic saved by clinic-admin.
front desk reads: ok: Ikeja Family Clinic: Mon-Fri 08:00-18:00, Sat 09:00-13:00. Notice: Closed on 1 January
no token: refused (MCPError)The front-desk token can read but not write. The scope check returns a readable tool error, not a crash, and the admin's write shows up in the next read. The last line proves the SDK client cannot get in without a token. The exception name may differ between SDK releases; what matters is the word refused.
Step 7 · Verify tokens from a real authorisation server
Static tokens are fine for one machine. They do not expire, and changing one means a restart. With a real authorisation server (your identity provider, or a hosted one), clients get short-lived access tokens, usually signed JWTs. Your server checks the signature against the provider's published keys (its JWKS) and then checks the claims. Two of those checks matter most here. The issuer (iss) must be your authorisation server. The audience (aud) must be this MCP server. The spec requires the audience check, because without it a token issued for some other service would work here too.
Add PyJWT as a direct dependency, since you now import it yourself. The version matches the one mcp already installed:
uv add "pyjwt[crypto]==2.15.1"Create jwt_verifier.py:
cat > jwt_verifier.py <<'PY'
import asyncio
import jwt
from mcp.server.auth.provider import AccessToken
class JWTVerifier:
"""Accepts RS256 access tokens from one issuer, issued for one audience: this server."""
def __init__(self, issuer: str, audience: str, *, jwks_url: str | None = None, key=None):
if (jwks_url is None) == (key is None):
raise ValueError("pass exactly one of jwks_url or key")
self.issuer = issuer
self.audience = audience
self.jwks = jwt.PyJWKClient(jwks_url) if jwks_url else None
self.key = key
async def verify_token(self, token: str) -> AccessToken | None:
try:
if self.jwks is not None:
signing_key = await asyncio.to_thread(self.jwks.get_signing_key_from_jwt, token)
key = signing_key.key
else:
key = self.key
claims = jwt.decode(
token,
key,
algorithms=["RS256"],
audience=self.audience,
issuer=self.issuer,
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.PyJWTError:
return None
return AccessToken(
token=token,
client_id=claims.get("client_id", claims["sub"]),
scopes=claims.get("scope", "").split(),
expires_at=claims["exp"],
resource=self.audience,
subject=claims["sub"],
)
PYalgorithms=["RS256"] is a fixed list on purpose: never take the algorithm from the token itself. client_id and scope (space-separated) are the claim names that RFC 9068 sets for JWT access tokens. Check your provider's tokens, because some use other names. The key lookup runs in a thread because PyJWKClient fetches the keys over the network with blocking I/O. It caches them after the first fetch.
You can check the verifier without an authorisation server by making a signing key and three tokens yourself. Create jwt_check.py:
cat > jwt_check.py <<'PY'
import asyncio
import time
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from jwt_verifier import JWTVerifier
ISSUER = "https://auth.example.com"
RESOURCE = "http://127.0.0.1:8765/mcp"
signing_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
verifier = JWTVerifier(ISSUER, RESOURCE, key=signing_key.public_key())
def make_token(audience: str, lifetime: int) -> str:
now = int(time.time())
claims = {
"iss": ISSUER,
"aud": audience,
"sub": "user-42",
"client_id": "front-desk",
"scope": "clinic:read",
"iat": now,
"exp": now + lifetime,
}
return jwt.encode(claims, signing_key, algorithm="RS256")
async def main() -> None:
cases = {
"for this server": make_token(RESOURCE, 300),
"for another server": make_token("http://127.0.0.1:9999/mcp", 300),
"expired": make_token(RESOURCE, -60),
}
for label, token in cases.items():
access = await verifier.verify_token(token)
result = f"accepted, {access.client_id} {access.scopes}" if access else "rejected"
print(f"{label}: {result}")
asyncio.run(main())
PY
uv run python jwt_check.pyTo use it in server.py, you would replace the StaticTokenVerifier(...) call with the line below. Take the real JWKS address from the jwks_uri field of your provider's metadata (at /.well-known/openid-configuration or /.well-known/oauth-authorization-server) and set ISSUER to its exact issuer value:
verifier = JWTVerifier(ISSUER, RESOURCE, jwks_url="https://auth.example.com/.well-known/jwks.json")Never forward the token your server receives to another API. The spec forbids this token passthrough: if a tool calls another service, the server gets its own token for that service.
Check it worked
The output is three lines: for this server: accepted, front-desk ['clinic:read'], for another server: rejected and expired: rejected.
Step 8 · Clean up
Stop the server with Ctrl+C in the second terminal.
Then delete the demo project. This removes tokens.env too, so the two tokens stop existing. Python and uv stay installed:
cd ~
rm -rf ~/mcp-http-demoCheck it worked
ls ~/mcp-http-demo reports No such file or directory, and curl -s http://127.0.0.1:8765/mcp exits with an error because nothing listens on the port any more.
Next steps
- Build the stdio version of this server first, with resources, prompts and pytest: build an MCP server in Python.
- Review what can still go wrong once tools are reachable, from injected tool descriptions to over-broad access: secure the MCP servers you build and the ones you install.
- Compare this with key-based protection for an ordinary REST API: protect an API with API keys.
Related tutorials
- Use MCP server tools from your own Claude appYou will connect a Python app to the stdio clinic-hours MCP server, hand an allowlisted set of its tools to Claude, pass every tool call through to the server with a tested bridge, and know when the API's MCP connector can do the connecting for you.
- Trace LLM calls with OpenTelemetryYou will have a Python app whose Claude calls, retries and tool runs appear as one OpenTelemetry trace with GenAI attributes, token and latency metrics, prompts kept out by default, and an export path from the console to an OpenTelemetry Collector.
- Secure the MCP servers you build and the ones you installYou will harden a small clinic MCP server with a read-only database connection, a file allowlist, input limits and its own credential, prove each guard with pytest, and pin a server's tool list so a changed or poisoned tool is caught before you approve it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials