MCP (Model Context Protocol)¶
MCP is the protocol an AI client (Claude
Desktop, an IDE, another agent) uses to discover and call a server's tools.
The tempest_fastapi_sdk.mcp module covers both directions, on top of
FastMCP:
| You want… | Use |
|---|---|
| an MCP client to call tools of your service | mount_mcp + add_agent_tools / add_fastapi_routes |
an SDK Agent to use tools of an external MCP server |
MCPToolset |
Installation¶
The extra declares fastmcp>=4.1.0. The floor is 4.1.0 because it is the
first release that validates path-parameter segments in tools generated from
OpenAPI — the same code path through which add_fastapi_routes passes
model-chosen arguments. The module's suite passes on 4.1.0 (with mcp 2.0.0)
and on 4.1.8.
Out of [all]
In a fresh Python 3.12 venv, the extra added 47 packages to the SDK's base
install (fastmcp 4.1.8), a second HTTP client (httpx2) among them, and it
requires starlette>=1.0.1. That is why it is opt-in and stays out of
[all]. Without the extra, import tempest_fastapi_sdk.mcp works; each
function raises an ImportError saying what to install.
Serve: an MCP endpoint in your application¶
An orders service that already has an authenticated POST /orders route, and
wants an MCP client to be able to create orders, ask who is logged in, and use
an agent tool that already exists:
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
from fastapi import Depends, FastAPI
from fastmcp import FastMCP
from pydantic import BaseModel, Field
from tempest_fastapi_sdk import (
JWTUtils,
make_bearer_token_dependency,
register_exception_handlers,
)
from tempest_fastapi_sdk.agents import AgentContext, text_tool
from tempest_fastapi_sdk.mcp import (
add_agent_tools,
add_fastapi_routes,
mcp_principal,
mount_mcp,
)
jwt = JWTUtils("replace-with-a-secret-of-32-bytes-or-more")
current_user = make_bearer_token_dependency(jwt)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
print("app: opening resources")
yield
print("app: closing resources")
app = FastAPI(lifespan=lifespan)
register_exception_handlers(app)
class OrderInSchema(BaseModel):
sku: str = Field(min_length=1, description="Product code.")
quantity: int = Field(ge=1, description="Quantity.")
class OrderOutSchema(BaseModel):
sku: str
quantity: int
owner: str
@app.post("/orders", operation_id="create_order", tags=["orders"])
async def create_order(
order: OrderInSchema,
claims: dict[str, Any] = Depends(current_user),
) -> OrderOutSchema:
return OrderOutSchema(sku=order.sku, quantity=order.quantity, owner=claims["sub"])
async def shout(arguments: dict[str, Any], _context: AgentContext) -> str:
return str(arguments["text"]).upper()
server = FastMCP("orders", mask_error_details=True)
@server.tool
def whoami() -> str:
"""Return the subject of the token that called this tool."""
return str(mcp_principal(dict)["sub"])
add_agent_tools(server, [text_tool("shout", "Return the text in upper case.", shout)])
add_fastapi_routes(server, app, operations=["create_order"])
mount_mcp(app, server, principal=current_user)
Run it with uvicorn mcp_server:app. The endpoint lives at /mcp.
The server is yours: FastMCP¶
The SDK does not wrap FastMCP. You build it and register tools, resources
and prompts with its decorators (@server.tool, @server.resource,
@server.prompt), which derive the schema from the type hints — a parameter
annotated with a Pydantic model gets that model's schema.
One thing mount_mcp requires of it: mask_error_details=True. On a
default FastMCP, a tool's exception reaches the client with its text
(measured on fastmcp 4.1.8, a tool raising
RuntimeError("postgres://admin:hunter2@db/prod")):
With mask_error_details=True, the client reads only the tool name, and the
text stays in the server log:
A server that does not mask is refused when mounted:
ValueError: mount_mcp serves only FastMCP servers that mask error details, or a tool exception reaches the MCP client with its text; build 'orders' with FastMCP(..., mask_error_details=True)
The check also walks the servers mounted into yours with
server.mount(child): each answers its own errors, and an unmasking child
leaks the text even under a masking parent. The global fastmcp setting
(FASTMCP_MASK_ERROR_DETAILS=true) counts too, because FastMCP reads it when
built. When a message should reach the model, raise
fastmcp.exceptions.ToolError("order 42 is already closed"): it passes the mask
on purpose.
Authentication is your routes': mount_mcp¶
mount_mcp registers /mcp as an ordinary FastAPI route (GET, POST
and DELETE, kept out of OpenAPI). So the dependency you pass as
principal= runs exactly as it runs on POST /orders: the same
current_user, the same refusal. Without a token, the request stops before it
reaches the MCP server:
HTTP/1.1 401 Unauthorized
content-type: application/json
{"detail":"Authorization token is missing or invalid","code":"UNAUTHORIZED","details":{}}
Whatever principal= resolved is available inside a tool through
mcp_principal(type) — dict for the claims of
make_bearer_token_dependency, your user model for
make_jwt_user_dependency. The isinstance is checked, so the return value is
already typed. Extra gates (permission, role) go in dependencies=, as on an
APIRouter.
A soft=True dependency (the kind that returns None for a request without a
token instead of refusing it) does not open the endpoint: when principal=
resolves None, mount_mcp answers the same 401 as above. To accept
anonymous callers on purpose, pass allow_unauthenticated=True — then the
anonymous caller reaches the tool, and mcp_principal(dict) raises TypeError
for it (None is not a dict) — the client reads Error calling tool
'<name>', because the server masks the error.
An open endpoint only by explicit choice
mount_mcp with neither principal= nor dependencies= raises
ValueError. An MCP endpoint runs tools on behalf of whoever calls it;
left open, it runs them for anyone who finds the URL. To serve without
authentication on purpose (a local demo), pass
allow_unauthenticated=True.
Sessions: none by default, and bound to their owner when there is one¶
By default the transport runs without a session (stateless=True): each
request is authenticated on its own and no Mcp-Session-Id is issued. Features
that need a session (a progress notification on a later request, sampling)
need stateless=False.
With stateless=False, the session is bound to the principal that opened
it. mount_mcp records Mcp-Session-Id → owner when the transport issues
the id, and every later request carrying that id goes through the same
principal= dependency and is compared with the owner. The owner is the sub
claim when the principal is a claims dictionary (it survives a token refresh),
and the type plus id when it is an object, such as your user model. Another
user with a valid token — or an anonymous caller, with
allow_unauthenticated=True — presenting the id gets exactly what the
transport answers for a session that does not exist:
HTTP/1.1 404 Not Found
content-type: application/json
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Session not found"}}
It is 404, not 403, because that is what the MCP specification says to
answer for a session the server no longer serves — the client opens another —
and because 403 would tell whoever tried that the id exists.
The binding is released when a DELETE ends the session, and a binding with no
request in flight for more than 30 minutes (the same window in which the MCP
SDK closes an idle session) is dropped when another session opens. It lives in
the process, like the transport's sessions themselves: behind several workers,
a session only works when its requests reach the worker that opened it.
Without principal=, everyone is the same owner
The binding compares the principal. Mounted with dependencies= only (a
shared secret, say), every caller has the same identity and the session
does not tell them apart. A principal with no stable identity — a
dictionary without sub, an object without id — makes the request fail
with TypeError; serve that case with stateless=True.
The lifespan is composed, not replaced¶
The MCP transport has to run inside the application's lifespan. mount_mcp
replaces app.router.lifespan_context with one that enters your lifespan
first and the transport's inside it — MCP stops before the resources you opened
are closed. Running the example and stopping it with Ctrl+C:
INFO: Waiting for application startup.
app: opening resources
INFO: Application startup complete.
...
INFO: Waiting for application shutdown.
app: closing resources
INFO: Application shutdown complete.
Call mount_mcp after setting the app's lifespan, and serve with the lifespan
on (uvicorn does by default; in a test, with TestClient(app)).
Agent tools you already have: add_agent_tools¶
add_agent_tools(server, tools) publishes AgentTools with the parameters
they already declare — the MCP client sees the same schema an SDK Agent sees.
The failure contract is the agents':
| The tool… | The MCP client gets |
|---|---|
raises AgentToolError("order 42 is already closed") |
the error with that message |
| raises any other exception | tool failed: <Type> — the text stays in the server log, because it can carry a DSN or a token |
runs past timeout (default 120 s) |
tool '<name>' timed out after <n>s |
returns a ToolResult with artifacts |
the text, and each artifact as MCP image/audio content or an embedded binary resource |
Each call runs under a fresh AgentContext: an MCP call carries no artifacts
from earlier calls.
FastAPI routes, without duplicating schemas: add_fastapi_routes¶
add_fastapi_routes(server, app, operations=[...], tags=[...]) publishes the
routes you picked — by operation_id or by tag — with the schema taken from
the application's own OpenAPI document. Without a selection it raises
ValueError: exposing every route (DELETEs included) is not a default. An
operation_id that does not exist, or a tag with no route, also raises — which
is what tells you the function ran before the routes were included.
The call goes to the route in the same process (ASGI transport, no socket),
and the MCP client's credentials go with it: Authorization and Cookie
(the names in forward_headers) are copied from the MCP request. The route
authenticates with its own dependencies, and it authenticates whoever called
MCP — in the example, the order's owner is the sub of the client's token.
Those headers are also taken out of the tool's schema, and a value the model
puts in the arguments is overwritten (or removed, when the MCP request had no
such header).
The route sees the call as it would see the MCP request: the Host and the
client address are the MCP request's (a TrustedHostMiddleware accepts it, and
a per-IP limit counts each client in its own bucket), and an unhandled
exception in the route ends in the 500 the app answers over HTTP, never as the
exception itself — and the MCP client reads Error calling tool '<name>',
without its text.
The make_token_dependency header
A route protected by a shared secret reads another header (X-Token by
default). Add it:
forward_headers=("authorization", "cookie", "x-token").
The OpenAPI document is generated once, during the call, and the application's
cache (app.openapi_schema) is left as it was — the /docs page still sees
routes included later.
A native tool over your controller: FastMCP's Depends¶
Use this when the tool has no matching route — or when you want it to call the
controller directly, without going through HTTP — in a layered service
(router → controller → service → repository). The path is the one the
composition root already takes: a build_* function assembles
the graph from a session, and each entry point only decides where the
session comes from. The route gets it through FastAPI's Depends; the MCP tool,
through FastMCP's:
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
from uuid import UUID
from fastapi import Depends, FastAPI
from fastmcp import FastMCP
from fastmcp.dependencies import Depends as McpDepends
from pydantic import BaseModel as PydanticModel
from sqlalchemy import String, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column
from tempest_fastapi_sdk import (
AsyncDatabaseManager,
BaseModel,
JWTUtils,
LogUtils,
RequestIDMiddleware,
make_bearer_token_dependency,
register_exception_handlers,
)
from tempest_fastapi_sdk.mcp import mcp_principal, mount_mcp
logger: LogUtils = LogUtils(__name__, log_dir=None)
db: AsyncDatabaseManager = AsyncDatabaseManager("sqlite+aiosqlite:///:memory:")
jwt: JWTUtils = JWTUtils("troque-por-um-segredo-de-32-bytes-ou-mais")
current_user = make_bearer_token_dependency(jwt)
class OrderModel(BaseModel):
__tablename__ = "orders"
sku: Mapped[str] = mapped_column(String(32))
owner: Mapped[str] = mapped_column(String(64))
class OrderResponseSchema(PydanticModel):
id: UUID
sku: str
owner: str
class OrderRepository:
def __init__(self, session: AsyncSession) -> None:
self.session: AsyncSession = session
async def list_by_owner(self, owner: str) -> list[OrderModel]:
logger.info("repository.list_by_owner", owner=owner)
rows = await self.session.scalars(
select(OrderModel).where(OrderModel.owner == owner),
)
return list(rows)
class OrderService:
def __init__(self, repository: OrderRepository) -> None:
self.repository: OrderRepository = repository
async def list_mine(self, owner: str) -> list[OrderResponseSchema]:
logger.info("service.list_mine", owner=owner)
orders = await self.repository.list_by_owner(owner)
return [
OrderResponseSchema(id=order.id, sku=order.sku, owner=order.owner)
for order in orders
]
class OrderController:
def __init__(self, service: OrderService) -> None:
self.service: OrderService = service
async def list_mine(self, owner: str) -> list[OrderResponseSchema]:
logger.info("controller.list_mine", owner=owner)
return await self.service.list_mine(owner)
def build_order_controller(session: AsyncSession) -> OrderController:
return OrderController(OrderService(OrderRepository(session)))
def get_order_controller(
session: AsyncSession = Depends(db.session_dependency),
) -> OrderController:
return build_order_controller(session)
@asynccontextmanager
async def order_controller_for_tool() -> AsyncIterator[OrderController]:
async with db.get_session_context() as session:
yield build_order_controller(session)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
await db.connect()
async with db.engine.begin() as connection:
await connection.run_sync(BaseModel.metadata.create_all)
async with db.get_session_context() as session:
session.add_all(
[OrderModel(sku="CAFE", owner="maria"), OrderModel(sku="PAO", owner="joao")],
)
await session.commit()
yield
await db.disconnect()
app: FastAPI = FastAPI(lifespan=lifespan)
app.add_middleware(RequestIDMiddleware)
register_exception_handlers(app)
@app.get("/orders/mine")
async def my_orders(
claims: dict[str, Any] = Depends(current_user),
controller: OrderController = Depends(get_order_controller),
) -> list[OrderResponseSchema]:
return await controller.list_mine(claims["sub"])
server: FastMCP = FastMCP("pedidos", mask_error_details=True)
@server.tool
async def list_my_orders(
controller: OrderController = McpDepends(order_controller_for_tool),
) -> list[OrderResponseSchema]:
"""List the orders that belong to the caller."""
return await controller.list_mine(str(mcp_principal(dict)["sub"]))
mount_mcp(app, server, principal=current_user)
Run it with uvicorn pedidos_camadas:app --port 8765, and call the tool with
MCPToolset, sending your own X-Request-ID:
import asyncio
from tempest_fastapi_sdk import JWTUtils
from tempest_fastapi_sdk.agents import AgentContext
from tempest_fastapi_sdk.mcp import MCPToolset
jwt: JWTUtils = JWTUtils("troque-por-um-segredo-de-32-bytes-ou-mais")
async def main() -> None:
token = jwt.encode({"sub": "maria", "typ": "access"})
async with MCPToolset.http(
"http://127.0.0.1:8765/mcp",
name="pedidos",
token=token,
headers={"X-Request-ID": "pedido-mcp-1"},
) as pedidos:
tools = {tool.name: tool for tool in await pedidos.tools()}
print(tools["list_my_orders"].parameters)
result = await tools["list_my_orders"].invoke({}, AgentContext())
print(result.text)
asyncio.run(main())
The output:
{'type': 'object', 'additionalProperties': False, 'properties': {}}
[{"id":"3896f995-4a24-403d-8026-1fc3059f5088","sku":"CAFE","owner":"maria"}]
The controller parameter does not appear in the tool's schema: FastMCP
resolves the Depends parameters before calling the function and leaves them
out of what the model sees. The caller comes from mcp_principal(dict), which
reads what principal= resolved in mount_mcp — the controller receives the
token's sub, never an argument the model picks.
One request, three layers, the same request_id¶
RequestIDMiddleware applies to /mcp too, because mount_mcp serves the
transport on an ordinary application route. The call above and a
GET /orders/mine with X-Request-ID: pedido-http-1 left this in the server
log:
{"timestamp": "2026-12-02T17:38:59.694700Z", "level": "INFO", "logger": "pedidos_camadas", "message": "controller.list_mine", "request_id": "pedido-mcp-1", "owner": "maria"}
{"timestamp": "2026-12-02T17:38:59.694772Z", "level": "INFO", "logger": "pedidos_camadas", "message": "service.list_mine", "request_id": "pedido-mcp-1", "owner": "maria"}
{"timestamp": "2026-12-02T17:38:59.694799Z", "level": "INFO", "logger": "pedidos_camadas", "message": "repository.list_by_owner", "request_id": "pedido-mcp-1", "owner": "maria"}
{"timestamp": "2026-12-02T17:39:00.402457Z", "level": "INFO", "logger": "pedidos_camadas", "message": "controller.list_mine", "request_id": "pedido-http-1", "owner": "maria"}
{"timestamp": "2026-12-02T17:39:00.402531Z", "level": "INFO", "logger": "pedidos_camadas", "message": "service.list_mine", "request_id": "pedido-http-1", "owner": "maria"}
{"timestamp": "2026-12-02T17:39:00.402553Z", "level": "INFO", "logger": "pedidos_camadas", "message": "repository.list_by_owner", "request_id": "pedido-http-1", "owner": "maria"}
The MCP tool and the route go through the same three layers, and every line
carries the id of the request that produced it — filtering the log by
pedido-mcp-1 shows the whole call, from controller to repository.
The session opens before the tool and closes after it¶
FastMCP enters order_controller_for_tool() before calling list_my_orders
and leaves it when the function returns — with a print at each point, the
measured order was session open → tool returning → session closed, before
the response reached the client. get_session_context() commits on exit and
rolls back if the tool raises (see AI agents (database)).
FastAPI's dependency does not work for FastMCP
They are two different injection systems, and neither obvious mistake
raises at mount time — only when the tool runs, and the MCP client reads
just Error calling tool 'list_my_orders', because the server masks the
error:
You pass to McpDepends… |
The server log shows | mypy |
|---|---|---|
get_order_controller (the route's factory, with Depends(db.session_dependency)) |
AttributeError: 'Depends' object has no attribute 'scalars' — in the repository, after the controller and the service already ran |
silent |
an async def ... yield generator without @asynccontextmanager |
AttributeError: 'async_generator' object has no attribute 'list_mine' |
flags it: Incompatible default for parameter "controller" |
The bare generator is injected as is, and the parameter carrying FastAPI's
Depends(...) keeps the Depends object itself as its value. That is why
the MCP entry point has its own function, decorated with
@asynccontextmanager, and the two entry points share only
build_order_controller.
Route or native tool?
If the operation is already a route, add_fastapi_routes reuses all of it
— validation, auth dependencies, error handling — without a new line. A
native tool pays off when the operation does not exist as a route, or when
what the model gets back should differ from what the API returns.
Consume: another MCP server's tools in an Agent¶
MCPToolset holds one connection to an MCP server and turns the tools it
lists into AgentTools. Against the server above, with the model scripted by
ScriptedBackend (see AI agents (testing)):
import asyncio
from tempest_fastapi_sdk import JWTUtils
from tempest_fastapi_sdk.agents import Agent
from tempest_fastapi_sdk.agents.testing import (
ScriptedBackend,
replies,
replies_with_tool,
tool_steps,
)
from tempest_fastapi_sdk.mcp import MCPToolset
jwt = JWTUtils("replace-with-a-secret-of-32-bytes-or-more")
async def main() -> None:
token = jwt.encode({"sub": "maria", "typ": "access"})
backend = ScriptedBackend(
[
replies_with_tool("orders_whoami"),
replies_with_tool("orders_create_order", {"sku": "COFFEE", "quantity": 2}),
replies("Order placed."),
],
)
async with MCPToolset.http(
"http://127.0.0.1:8000/mcp",
name="orders",
token=token,
prefix="orders_",
) as orders:
tools = await orders.tools()
print([tool.name for tool in tools])
run = await Agent(backend, tools=tools).run("Order 2 coffees.")
for step in tool_steps(run):
print(step.name, "->", step.output)
print(run.stop_reason, run.output)
asyncio.run(main())
With mcp_server.py running on port 8000, it prints:
['orders_whoami', 'orders_shout', 'orders_create_order']
orders_whoami -> maria
orders_create_order -> {"sku":"COFFEE","quantity":2,"owner":"maria"}
completed Order placed.
prefix= keeps apart the tools of two servers that use the same name;
include= adapts only the ones you list.
A local server, over stdio¶
MCP servers distributed as a program (uvx, npx, a Python script) speak
stdio. MCPToolset.stdio starts the process on connect and stops it on
disconnect:
import asyncio
import sys
from tempest_fastapi_sdk.agents import AgentContext
from tempest_fastapi_sdk.mcp import MCPToolset
async def main() -> None:
async with MCPToolset.stdio(
sys.executable,
["local_server.py"],
name="local",
) as local:
tools = {tool.name: tool for tool in await local.tools()}
print(tools["add"].parameters)
result = await tools["add"].invoke({"a": 2, "b": 3}, AgentContext())
print(result.text)
asyncio.run(main())
With a local_server.py that defines add(a: int, b: int) -> int on a
FastMCP and ends in server.run(transport="stdio"), the output is:
{'type': 'object', 'additionalProperties': False, 'properties': {'a': {'type': 'integer'}, 'b': {'type': 'integer'}}, 'required': ['a', 'b']}
5
FastMCP's StdioTransport, by default (keep_alive=True), leaves the
subprocess running after the Client leaves its with — measured on fastmcp
4.1.8: the server's PID still answered 1 s later. MCPToolset.stdio passes
keep_alive=False, and the suite checks that the server process is gone after
disconnect().
Lifecycle¶
MCPToolset has idempotent connect() and disconnect() — it is a
LifecycleResource, so it also opens in the application lifespan or in
TaskQueue(resources=[...]) and stays open for the life of the process. The
adapted tools call through the toolset's connection: after disconnect they
answer with AgentToolError("... is not connected"), which the model reads,
instead of hanging.
Errors the model reads¶
| When… | The tool raises |
|---|---|
| the server flags the result as an error | AgentToolError with the server's text |
the call runs past timeout (default 30 s) or past the agent run's deadline |
AgentToolError("... timed out after <n>s") |
| the agent run has no time left | AgentToolError("no time left ..."), without calling |
| the server answers with a JSON-RPC error | AgentToolError with the error's message |
| the transport breaks | the exception propagates, and the agent shows it as tool failed: <Type> — its text can carry the server URL |
Images, audio and binary resources the server returns become agent
artifacts (<tool>.png, …), never base64 in the prompt; the tool's text
says the name each one was saved under.
Recap¶
mount_mcp(app, server, principal=current_user)serves aFastMCPat/mcpbehind the same dependencies as your routes, inside the app's lifespan — and only aFastMCP(..., mask_error_details=True).- With
stateless=False, the session is bound to whoever opened it; another principal gets404. add_agent_toolspublishesAgentTools with the schema they already have;add_fastapi_routespublishes the routes you picked, with the OpenAPI schema and the caller's credentials.- A native tool reaches the controller through FastMCP's
Dependsover an@asynccontextmanagerfunction that opens the session and calls the samebuild_*the route uses; FastAPI's factory does not work there. TheRequestIDMiddlewarerequest_idcrosses the layers in an MCP call too. MCPToolset.http/.stdiobring another server's tools into anAgent, with timeouts and errors turned intoAgentToolError.