tempest_fastapi_sdk.mcp¶
Model Context Protocol nas duas direções, sobre o FastMCP.
mcp
¶
Model Context Protocol, both directions, over FastMCP.
Serve. Build a fastmcp.FastMCP server, register tools on it, and
mount it on your app behind the dependencies your routes already use:
>>> server = FastMCP("orders")
>>> add_agent_tools(server, [lookup_order_tool])
>>> add_fastapi_routes(server, app, operations=["create_order"])
>>> mount_mcp(app, server, principal=current_user)
Consume. Connect to someone else's MCP server and hand its tools to an
:class:~tempest_fastapi_sdk.agents.Agent:
>>> async with MCPToolset.http(url, name="crm", token=token) as crm:
... agent = Agent(backend, tools=await crm.tools())
Submodule import, like agents:
from tempest_fastapi_sdk.mcp import mount_mcp. Needs the [fastmcp]
extra; the import itself works without it, and each helper raises an
ImportError naming the extra.
DEFAULT_MCP_CALL_TIMEOUT
module-attribute
¶
Seconds one remote tool call may take before it becomes a tool error.
DEFAULT_FORWARDED_HEADERS
module-attribute
¶
Credential headers :func:add_fastapi_routes copies from the MCP request
to the route it calls.
DEFAULT_MCP_TOOL_TIMEOUT
module-attribute
¶
Seconds an exposed agent tool may run per call — the same ceiling
:class:~tempest_fastapi_sdk.agents.AgentBudget puts on a whole run, since
a hung tool otherwise holds the client's HTTP request open indefinitely.
PRINCIPAL_STATE_KEY
module-attribute
¶
request.state attribute holding what the principal dependency
resolved for the current MCP request.
MCPToolset
¶
MCPToolset(
client: Client[Any],
*,
name: str,
prefix: str = "",
timeout: float = DEFAULT_MCP_CALL_TIMEOUT,
include: Collection[str] | None = None,
)
One MCP server connection, its tools adapted for the agents.
Build it with :meth:stdio or :meth:http (or hand it a configured
fastmcp.Client), open it with async with or :meth:connect, and
read :meth:tools. The adapted tools call through this connection,
so they work while the toolset is open and fail with an
:class:~tempest_fastapi_sdk.agents.AgentToolError the model can read
once it is closed.
Every failure the model can act on becomes an AgentToolError: a
result the server flagged as an error (its text), a call that ran past
timeout or past the agent's own deadline, and a JSON-RPC error. A
broken transport is left to the agent, which reports it as
"tool failed: <Type>" — its text can carry the server URL.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The server's name, used in error messages. |
prefix |
str
|
Prepended to every remote tool name, to keep two
servers' |
timeout |
float
|
Seconds one call may take. |
include |
frozenset[str] | None
|
Remote tool names to adapt; |
Wrap a configured, not yet connected fastmcp.Client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Client[Any]
|
The client; this toolset enters and exits it. |
required |
name
|
str
|
The server's name, for error messages. |
required |
prefix
|
str
|
Prepended to each remote tool name. |
''
|
timeout
|
float
|
Seconds one call may take. |
DEFAULT_MCP_CALL_TIMEOUT
|
include
|
Collection[str] | None
|
Remote tool names to adapt;
|
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
stdio
classmethod
¶
stdio(
command: str,
args: Sequence[str] = (),
*,
name: str,
env: Mapping[str, str] | None = None,
cwd: str | None = None,
prefix: str = "",
timeout: float = DEFAULT_MCP_CALL_TIMEOUT,
include: Collection[str] | None = None,
) -> MCPToolset
Connect to a server started as a subprocess, over stdio.
The subprocess starts on :meth:connect and is stopped on
:meth:disconnect — the transport's keep_alive is turned off,
so closing the toolset does not leave the process running.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
The executable ( |
required |
args
|
Sequence[str]
|
Its arguments. |
()
|
name
|
str
|
The server's name, for error messages. |
required |
env
|
Mapping[str, str] | None
|
Environment for the subprocess. |
None
|
cwd
|
str | None
|
Its working directory. |
None
|
prefix
|
str
|
Prepended to each remote tool name. |
''
|
timeout
|
float
|
Seconds one call may take. |
DEFAULT_MCP_CALL_TIMEOUT
|
include
|
Collection[str] | None
|
Remote tool names to adapt. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MCPToolset |
MCPToolset
|
The toolset, not yet connected. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
http
classmethod
¶
http(
url: str,
*,
name: str,
token: str | None = None,
headers: Mapping[str, str] | None = None,
prefix: str = "",
timeout: float = DEFAULT_MCP_CALL_TIMEOUT,
include: Collection[str] | None = None,
) -> MCPToolset
Connect to a server over streamable HTTP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The MCP endpoint, e.g. |
required |
name
|
str
|
The server's name, for error messages. |
required |
token
|
str | None
|
Sent as |
None
|
headers
|
Mapping[str, str] | None
|
Further headers on every
request, e.g. the shared secret of a |
None
|
prefix
|
str
|
Prepended to each remote tool name. |
''
|
timeout
|
float
|
Seconds one call may take. |
DEFAULT_MCP_CALL_TIMEOUT
|
include
|
Collection[str] | None
|
Remote tool names to adapt. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MCPToolset |
MCPToolset
|
The toolset, not yet connected. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
connect
async
¶
Open the connection (and start the subprocess, for stdio).
Calling it on an open toolset does nothing.
disconnect
async
¶
Close the connection (and stop the subprocess, for stdio).
Calling it on a closed toolset does nothing.
tools
async
¶
tools() -> list[AgentTool]
List the server's tools and adapt them for an agent.
Each tool keeps the server's description and input schema; its name
gets :attr:prefix.
Returns:
| Type | Description |
|---|---|
list[AgentTool]
|
list[AgentTool]: One agent tool per remote tool, in server order. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the toolset is not connected. |
add_agent_tools
¶
add_agent_tools(
server: FastMCP,
tools: Iterable[AgentTool],
*,
timeout: float | None = DEFAULT_MCP_TOOL_TIMEOUT,
) -> list[Tool]
Expose agent tools as MCP tools, with the schema they already declare.
Each call runs the tool's handler under a fresh
:class:~tempest_fastapi_sdk.agents.AgentContext — an MCP call carries
no earlier artifacts — and returns its text followed by its artifacts:
images and audio as MCP image/audio content, anything else as an
embedded binary resource. The failure contract is the agent's: an
:class:~tempest_fastapi_sdk.agents.AgentToolError reaches the client
with its message, any other exception as "tool failed: <Type>".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server
|
FastMCP
|
The server to register on. |
required |
tools
|
Iterable[AgentTool]
|
The agent tools to expose. |
required |
timeout
|
float | None
|
Seconds one call may take before the client
gets |
DEFAULT_MCP_TOOL_TIMEOUT
|
Returns:
| Type | Description |
|---|---|
list[Tool]
|
list[Tool]: The registered FastMCP tools, in order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
add_fastapi_routes
¶
add_fastapi_routes(
server: FastMCP,
app: FastAPI,
*,
operations: Collection[str] = (),
tags: Collection[str] = (),
forward_headers: Collection[str] = DEFAULT_FORWARDED_HEADERS,
timeout: float = 30.0,
) -> list[str]
Expose selected routes of app as MCP tools.
The tool schema comes from the app's OpenAPI document — the Pydantic
models the routes already declare — and each call goes to the route
in process (an ASGI transport, no socket). Only what you name is exposed:
a route is picked when its operation_id is in operations or it
carries one of tags.
The headers in forward_headers are copied from the MCP request onto
the route call, and removed from the call when the MCP request has none,
so the route's own dependencies authenticate the MCP caller — never
an anonymous internal call, and never a value the model put in the
arguments. Header and cookie parameters with those names are taken out
of the tool's input schema for the same reason.
Call it after the routes are included. The OpenAPI document is generated once, here, and the app's cached copy is left as it was.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server
|
FastMCP
|
The server to register on. |
required |
app
|
FastAPI
|
The application whose routes are exposed. |
required |
operations
|
Collection[str]
|
|
()
|
tags
|
Collection[str]
|
OpenAPI tags whose routes are exposed. |
()
|
forward_headers
|
Collection[str]
|
Headers copied from the MCP
request, case-insensitive. Defaults to |
DEFAULT_FORWARDED_HEADERS
|
timeout
|
float
|
Seconds a route call may take. |
30.0
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The |
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither |
ImportError
|
When the |
mcp_principal
¶
Return the caller mount_mcp(principal=...) resolved, inside a tool.
Example:
>>> @server.tool
... async def my_orders() -> list[str]:
... user = mcp_principal(User)
... return await orders_of(user.id)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type[T]
|
The type the principal dependency returns — your user
model, or |
required |
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The resolved principal of the request being served. |
Raises:
| Type | Description |
|---|---|
LookupError
|
Outside an MCP HTTP request, or when the endpoint was
mounted without |
TypeError
|
When the principal is not a |
ImportError
|
When the |
mount_mcp
¶
mount_mcp(
app: FastAPI,
server: FastMCP,
*,
path: str = "/mcp",
principal: Callable[..., Any] | None = None,
dependencies: Sequence[Depends] = (),
stateless: bool = True,
allow_unauthenticated: bool = False,
) -> None
Serve server over streamable HTTP at path of app.
The endpoint is an ordinary FastAPI route (GET, POST and
DELETE on path, kept out of the OpenAPI document), so the
dependencies you pass run exactly as they do on your other routes: the
SDK's current_user built by make_jwt_user_dependency, a
make_token_dependency shared secret, a make_permission_dependency
scope check. A request they refuse gets the same 401/403 your API
answers and never reaches the MCP server.
The MCP transport has to run inside the app's lifespan (it owns a task
group for its sessions), so app.router.lifespan_context is replaced by
one that enters your existing lifespan first and the transport inside it:
the transport stops before the resources your lifespan opened are closed.
Serve the app with its lifespan on (uvicorn does by default; a test client
needs with TestClient(app) or an equivalent).
The server must mask error details: an exception raised in a tool of a
default FastMCP reaches the MCP client as Error calling tool 'x':
<message> — a DSN or a token included — while one built with
FastMCP(..., mask_error_details=True) sends Error calling tool
'x' and keeps the text in the server log. A ToolError you raise on
purpose still reaches the client with its message. Servers mounted into
server with server.mount(...) are checked too, because each
answers its own tool errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
FastAPI
|
The application to mount on. Call this after setting the app's own lifespan. |
required |
server
|
FastMCP
|
The MCP server, already holding its tools, built
with |
required |
path
|
str
|
Where the endpoint lives. Defaults to |
'/mcp'
|
principal
|
Callable[..., Any] | None
|
A dependency that resolves the
caller — typically your |
None
|
dependencies
|
Sequence[Depends]
|
Further gates, as on
|
()
|
stateless
|
bool
|
Serve each request on its own, without an
|
True
|
allow_unauthenticated
|
bool
|
Serve without |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither |
TypeError
|
At request time with |
ImportError
|
When the |
DEFAULT_MCP_CALL_TIMEOUT
module-attribute
¶
Seconds one remote tool call may take before it becomes a tool error.
DEFAULT_FORWARDED_HEADERS
module-attribute
¶
Credential headers :func:add_fastapi_routes copies from the MCP request
to the route it calls.
DEFAULT_MCP_TOOL_TIMEOUT
module-attribute
¶
Seconds an exposed agent tool may run per call — the same ceiling
:class:~tempest_fastapi_sdk.agents.AgentBudget puts on a whole run, since
a hung tool otherwise holds the client's HTTP request open indefinitely.
PRINCIPAL_STATE_KEY
module-attribute
¶
request.state attribute holding what the principal dependency
resolved for the current MCP request.