Ir para o conteúdo

tempest_fastapi_sdk.mcp

Model Context Protocol nas duas direções, sobre o FastMCP.

« Tempo real e mensageria


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

DEFAULT_MCP_CALL_TIMEOUT: float = 30.0

Seconds one remote tool call may take before it becomes a tool error.

DEFAULT_FORWARDED_HEADERS module-attribute

DEFAULT_FORWARDED_HEADERS: tuple[str, ...] = ('authorization', 'cookie')

Credential headers :func:add_fastapi_routes copies from the MCP request to the route it calls.

DEFAULT_MCP_TOOL_TIMEOUT module-attribute

DEFAULT_MCP_TOOL_TIMEOUT: float = 120.0

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

PRINCIPAL_STATE_KEY: str = 'tempest_mcp_principal'

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' search tools apart.

timeout float

Seconds one call may take.

include frozenset[str] | None

Remote tool names to adapt; None adapts every tool the server lists.

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 adapts all of them.

None

Raises:

Type Description
ImportError

When the [fastmcp] extra is not installed.

connected property

connected: bool

Whether :meth:connect ran and :meth:disconnect has not.

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 ("uvx", "npx", a Python).

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 [fastmcp] extra is not installed.

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. "https://api.example/mcp".

required
name str

The server's name, for error messages.

required
token str | None

Sent as Authorization: Bearer <token>.

None
headers Mapping[str, str] | None

Further headers on every request, e.g. the shared secret of a make_token_dependency.

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 [fastmcp] extra is not installed.

connect async

connect() -> None

Open the connection (and start the subprocess, for stdio).

Calling it on an open toolset does nothing.

disconnect async

disconnect() -> None

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 "tool <name> timed out". Defaults to :data:DEFAULT_MCP_TOOL_TIMEOUT; None removes the ceiling.

DEFAULT_MCP_TOOL_TIMEOUT

Returns:

Type Description
list[Tool]

list[Tool]: The registered FastMCP tools, in order.

Raises:

Type Description
ImportError

When the [fastmcp] extra is not installed.

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]

operation_id values to expose.

()
tags Collection[str]

OpenAPI tags whose routes are exposed.

()
forward_headers Collection[str]

Headers copied from the MCP request, case-insensitive. Defaults to Authorization and Cookie; add the header a make_token_dependency reads.

DEFAULT_FORWARDED_HEADERS
timeout float

Seconds a route call may take.

30.0

Returns:

Type Description
list[str]

list[str]: The operation_id of every exposed route, sorted.

Raises:

Type Description
ValueError

When neither operations nor tags is given, when an operation id does not exist, or when a tag matches no route.

ImportError

When the [fastmcp] extra is not installed.

mcp_principal

mcp_principal(kind: type[T]) -> T

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 dict for the claims of make_bearer_token_dependency. Checked with isinstance, so the return value is typed for the caller.

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 principal=.

TypeError

When the principal is not a kind.

ImportError

When the [fastmcp] extra is not installed.

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 mask_error_details=True.

required
path str

Where the endpoint lives. Defaults to "/mcp".

'/mcp'
principal Callable[..., Any] | None

A dependency that resolves the caller — typically your current_user. It runs on every MCP request, refuses the ones it would refuse on a route, and its result is what :func:mcp_principal returns inside a tool. A None result — what a soft=True dependency returns for an anonymous request — is answered with 401 unless allow_unauthenticated is True, so an optional-user dependency never opens the endpoint by accident.

None
dependencies Sequence[Depends]

Further gates, as on APIRouter(dependencies=...) — a permission or role check.

()
stateless bool

Serve each request on its own, without an Mcp-Session-Id. Defaults to True. Set False for server-to-client features that need a session (progress notifications on a later request, sampling); the session is then bound to the principal that opened it. The binding key is the sub claim of a mapping principal, or the type and id of an object one; a request presenting the id under any other principal — another user, or an anonymous caller — gets the 404 the transport answers for an unknown session, so whether the id exists is not revealed. A DELETE that ends the session releases the binding. Bindings live in the process, like the transport's sessions themselves. Without principal= every caller has the same identity and the binding does not tell them apart.

True
allow_unauthenticated bool

Serve without principal and without dependencies, or let a principal that resolved None through. Refused otherwise, because an MCP endpoint runs tools on the caller's behalf and an open one runs them for anyone who finds the URL.

False

Raises:

Type Description
ValueError

When neither principal nor dependencies is given and allow_unauthenticated is False, or when server (or a server mounted into it) does not mask error details.

TypeError

At request time with stateless=False, when the principal has no stable identity to bind the session to (a mapping without sub, an object without id).

ImportError

When the [fastmcp] extra is not installed.

DEFAULT_MCP_CALL_TIMEOUT module-attribute

DEFAULT_MCP_CALL_TIMEOUT: float = 30.0

Seconds one remote tool call may take before it becomes a tool error.

DEFAULT_FORWARDED_HEADERS module-attribute

DEFAULT_FORWARDED_HEADERS: tuple[str, ...] = ('authorization', 'cookie')

Credential headers :func:add_fastapi_routes copies from the MCP request to the route it calls.

DEFAULT_MCP_TOOL_TIMEOUT module-attribute

DEFAULT_MCP_TOOL_TIMEOUT: float = 120.0

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

PRINCIPAL_STATE_KEY: str = 'tempest_mcp_principal'

request.state attribute holding what the principal dependency resolved for the current MCP request.