Skip to content

FastMCP context

Add FastMCPProvider() to expose FastMCP operation objects through Dishka's normal from_context mechanism.

from dishka import make_async_container
from fastmcp import Context, FastMCP

from dishka_fastmcp import (
    FastMCPProvider,
    FromDishka,
    dishka_lifespan,
    inject,
    setup_dishka,
)

container = make_async_container(FastMCPProvider())
mcp = FastMCP('app', lifespan=dishka_lifespan(container))
setup_dishka(container, mcp)


@mcp.tool
@inject
async def request_id(ctx: FromDishka[Context]) -> str:
    return ctx.request_id

Available objects

All entries are request-scoped and resolved only when requested:

Type Value
fastmcp.Context Current FastMCP operation context
fastmcp.FastMCP Current server instance

Use Context for request IDs, progress reporting, and resource access. When a child server is mounted, the injected FastMCP value is the server that owns the executing component. Its dependencies come from the container selected as described in Mounted servers.

Under DishkaMiddleware the REQUEST scope is opened once per MCP request, so its Context and FastMCP describe the request as the middleware sees it: FastMCP is the server whose DishkaMiddleware opened the scope, also for the handlers of mounted routers that share it. A mounted router set up with a container of its own opens its own scope, and FastMCP there is that router. See Request scope for the whole MCP request.

Using context in providers

Dependencies can consume the same context, so the handler needs no Context parameter:

from typing import NewType

from dishka import Provider, Scope, make_async_container, provide
from fastmcp import Context

from dishka_fastmcp import FastMCPProvider

RequestId = NewType('RequestId', str)


class RequestProvider(Provider):
    @provide(scope=Scope.REQUEST)
    def request_id(self, context: Context) -> RequestId:
        return RequestId(context.request_id)


container = make_async_container(FastMCPProvider(), RequestProvider())

Context and FastMCP live in Scope.REQUEST, so only REQUEST factories can take them.

Operation arguments

FastMCPProvider does not register CallToolRequestParams, ReadResourceRequestParams, or GetPromptRequestParams. Receive tool and prompt arguments in the handler signature, receive resource parameters from the resource URI template, and use Context for request metadata.