FastMCP · Chapter 5 of 6
FastMCP over HTTP with JWT authentication and scopes
14 min study · Examples checked with FastMCP 4.2 and MCP Python SDK 2.3 on Python 3.14 ·
Stdio lets one client own a local process. HTTP lets clients connect to a running service, which introduces a network boundary and a separate identity problem. This chapter exposes a tiny protected editor through Streamable HTTP, verifies development JWTs, and gives readers and publishers different capabilities.
Separate authentication from authorization
Authentication verifies the credential. Authorization decides which operation that identity may perform. A valid reader token should not gain publishing access merely because it can connect to the same endpoint.
This example uses locally signed, short-lived development tokens and a fixed public key. It demonstrates verification and scope checks; it does not implement an identity provider or a complete browser OAuth flow. A deployed user-facing integration should connect to appropriate identity infrastructure and MCP discovery metadata rather than distribute shared development tokens.
Create a scoped server
In a fresh directory, save server.py:
from pathlib import Path
from threading import Lock
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from fastmcp.server.auth import require_scopes
from fastmcp.server.auth.providers.jwt import JWTVerifier
ISSUER = "https://learning.example.test"
AUDIENCE = "learning-catalog-mcp"
def create_server(public_key: str) -> FastMCP:
verifier = JWTVerifier(public_key=public_key, issuer=ISSUER, audience=AUDIENCE)
server = FastMCP("Protected catalog editor", auth=verifier, mask_error_details=True)
lesson = {"id": 1, "title": "Python functions", "published": False}
lock = Lock()
@server.tool(auth=require_scopes("catalog:read"), annotations={"readOnlyHint": True})
def get_lesson() -> dict:
"""Read the example editor's lesson and current publication state."""
with lock:
return lesson.copy()
@server.tool(
auth=require_scopes("catalog:publish"),
annotations={"readOnlyHint": False, "idempotentHint": True},
)
def publish_lesson(lesson_id: int) -> dict:
"""Mark the example lesson as published; repeating the call keeps it published."""
if lesson_id != 1:
raise ToolError("Lesson not found")
with lock:
lesson["published"] = True
return lesson.copy()
return server
if __name__ == "__main__":
public_key = (Path(__file__).resolve().parent / ".tokens" / "public.pem").read_text()
create_server(public_key).run(transport="http", host="127.0.0.1", port=8000)
The example’s draft is private editor data and requires a read scope. Publishing requires a separate scope and is enforced by the registered component, even when a caller guesses the tool name. The lock protects this process’s demonstration state. It does not make that state durable or shared across server workers.
Generate development credentials
Create make_tokens.py:
from pathlib import Path
from fastmcp.server.auth.providers.jwt import RSAKeyPair
from server import AUDIENCE, ISSUER
def main():
directory = Path(__file__).resolve().parent / ".tokens"
directory.mkdir(mode=0o700, exist_ok=True)
keys = RSAKeyPair.generate()
(directory / "public.pem").write_text(keys.public_key, encoding="utf-8")
for name, scopes in {
"reader": ["catalog:read"],
"editor": ["catalog:read", "catalog:publish"],
}.items():
token = keys.create_token(
subject=f"development-{name}", issuer=ISSUER, audience=AUDIENCE,
scopes=scopes, expires_in_seconds=900,
)
path = directory / f"{name}.token"
path.write_text(token, encoding="utf-8")
path.chmod(0o600)
if __name__ == "__main__":
main()
Run python make_tokens.py, then python server.py. Keep .tokens/ out of version control and application logs. The public key is not secret, but the bearer tokens grant access until expiry. Regenerating credentials changes the public key, so restart the server after regeneration. Filesystem permission semantics vary by platform; use your operating system’s controls for real credentials.
Connect as a reader
Create client.py:
import asyncio
from pathlib import Path
from fastmcp import Client
async def main():
token = (Path(__file__).resolve().parent / ".tokens" / "reader.token").read_text().strip()
async with Client("http://127.0.0.1:8000/mcp", auth=token, timeout=10) as client:
names = {tool.name for tool in await client.list_tools()}
assert "get_lesson" in names
assert "publish_lesson" not in names
result = await client.call_tool("get_lesson", {})
print(result.data)
if __name__ == "__main__":
asyncio.run(main())
The client sends the bearer credential through its HTTP transport. Do not put tokens in URL query strings, which can leak through logs and history. Replace reader.token with editor.token when testing the publisher role, then explicitly call publish_lesson with {"lesson_id": 1}.
Understand discovery and invocation checks
FastMCP can hide components that the caller is not authorized to use. This makes discovery useful, but hiding a name is not the only defense: invocation must enforce the same policy. A denied lookup can appear as an unavailable component rather than a guaranteed HTTP 403 response. Test the observable denial and unchanged state instead of assuming one error mapping for every authorization layer.
The verifier checks signature and claims such as issuer, audience, and expiry. A token issued for a different service must fail even if its signature is valid. Production issuers commonly provide a JWKS endpoint for key rotation. The token verification guide covers provider options, and the authorization guide describes component checks.
Scopes describe broad capabilities. A multi-user catalog also needs per-record access rules based on verified identity. Do not accept a user_id argument as proof of who is calling. Keep host approval for a consequential action separate from the server’s access decision: a client can invoke the protocol without using the host’s usual interface.
Keep the HTTP boundary explicit
Streamable HTTP carries MCP messages through the endpoint; it is not one REST URL per tool. An HTTP 200 alone does not prove a tool operation succeeded, because the protocol result can still carry a tool error. Let the client library manage framing, current protocol metadata, and request-scoped streaming.
The example binds to loopback for local testing. A remote deployment needs HTTPS, explicit host and origin policy, correct proxy paths, bounded input sizes and timeouts, and logs that avoid credentials. Preserve framework host/origin protections rather than disabling them to bypass a local error. Configure the public endpoint URL and identity-provider discovery together when enabling OAuth clients.
Practice
Test no token, a reader token, an editor token, an expired token, and a token for the wrong audience. Confirm a reader cannot publish even by calling the tool name directly. Publish twice as the editor and compare results.
Answer check: authentication failures prevent access, readers cannot mutate state, and repeated publication leaves the lesson published. Restarting this teaching server resets its in-memory state; durable catalog storage is the next chapter’s concern.
Summary
Protect the transport with credential verification and the operation with authorization. Discovery, user approval, identity, record access, and durable state each have their own contract.