FastMCP

repository·main·Indexed 12 days ago

https://github.com/prefecthq/fastmcp

A full Model Context Protocol (MCP) application framework for building MCP servers, clients, and interactive applications in Python. It automates schema generation, validation, and protocol lifecycle management. Includes fastmcp-remote, a stdio bridge for connecting local MCP clients to remote servers over HTTP or SSE, and contrib modules like BulkToolCaller and Component Manager for dynamic runtime control of tools, resources, and prompts.

Tokens
607.3K
Snippets
1.7K
Records
2.1K
Agent score
95%

What's inside FastMCP

  1. Overview of the fastmcp CLI commands

    main

    The fastmcp CLI is the primary interface for running, testing, installing, and interacting with MCP servers. It is installed automatically with FastMCP.

    Core Commands

    CommandDescription
    runRun a server from a local file, factory function, remote URL, or config file
    dev appsLaunch a browser-based preview UI for Prefab App tools
    dev inspectorLaunch a server inside the MCP Inspector for interactive testing
    installInstall a server into Claude Code, Claude Desktop, Cursor, Gemini CLI, or Goose
    inspectPrint a server's tools, resources, and prompts as a summary or JSON report
    listList a server's tools (and optionally resources and prompts)
    callCall a tool, read a resource, or get a prompt
    discoverFind MCP servers configured in your editors and tools
    generate-cliScaffold a standalone typed CLI from a server's tool schemas
    project preparePre-install dependencies into a reusable uv project
    auth cimdCreate and validate CIMD documents for OAuth
    versionPrint version info (use --copy to copy to clipboard)
    fastmcp --help
  2. Overview of FastMCP CLI commands

    main

    The FastMCP CLI provides several commands to manage the lifecycle of MCP servers.

    CommandPurposeDependency Management
    runRun a FastMCP server directlySupports local files, factory functions, URLs, fastmcp.json, and MCP configs. Uses local environment by default, or uv run when using --python, --with, --project, or --with-requirements.
    devRun a server with the MCP Inspector for testingAlways runs via uv run subprocess. Dependencies must be specified or available in a uv-managed project.
    installInstall a server in MCP client applicationsCreates an isolated environment. Dependencies must be explicitly specified with --with and/or --with-editable (or via fastmcp.json).
    inspectGenerate a JSON report about a FastMCP serverUses your current environment; you must ensure dependencies are available.
    project prepareCreate a persistent uv project from fastmcp.jsonCreates a uv project directory with all dependencies pre-installed for reuse with the --project flag.
    versionDisplay version informationN/A
  3. Use the FastMCP Client for programmatic MCP interactions

    main

    The fastmcp.Client class provides a programmatic, type-safe Python interface for interacting with Model Context Protocol (MCP) servers. It is designed for deterministic control rather than autonomous agentic behavior, making it suitable for testing servers or building the foundation for LLM-based applications.

    Important: All client operations must be wrapped in an async with context manager to ensure proper connection lifecycle management (establishment and automatic closure).

    import asyncio
    from fastmcp import Client, FastMCP
    
    server = FastMCP("TestServer")
    client = Client(server)
    
    async def main():
        async with client:
            await client.ping()
            tools = await client.list_tools()
            # ... perform operations
    
    asyncio.run(main())
  4. Expose agent skills as MCP resources

    main

    The Skills Provider allows you to expose AI agent skill directories (like those used by Claude Code, Cursor, or VS Code Copilot) as standardized MCP resources. This makes local skills discoverable and shareable across different AI tools and clients. A skill is a directory containing a main instruction file (default: SKILL.md) and optional supporting files.

    from pathlib import Path
    from fastmcp import FastMCP
    from fastmcp.server.providers.skills import SkillsDirectoryProvider
    
    mcp = FastMCP("Skills Server")
    mcp.add_provider(SkillsDirectoryProvider(roots=Path.home() / ".claude" / "skills"))
  5. Benefits of Upgrading to FastMCP

    main

    Moving from the low-level SDK to FastMCP provides several architectural advantages:

    • Server Composition: Mount one server inside another to split large, unwieldy dispatch chains into independent, testable modules.
    • Middleware: Implement cross-cutting concerns like logging, rate limiting, error handling, and caching across all requests using hooks.
    • Proxy Servers: Place a FastMCP server in front of existing MCP servers to bridge transports or add authentication.
    • OpenAPI Integration: Automatically generate a server from an existing API specification.
    • Unified Authentication: Consolidate token verification and authorization into a single auth= provider (supporting GitHub, Google, Auth0, Keycloak, etc.).
    • Simplified Testing: Use the built-in FastMCP client to connect to a server object within the same Python process, eliminating the need for subprocesses or stdio pipes.
  6. What is the OAuth Proxy and when to use it

    main

    The OAuth proxy is a bridge that allows FastMCP servers to authenticate with traditional OAuth providers that do not support Dynamic Client Registration (DCR).

    Use the OAuth Proxy when:

    • You are using traditional providers like GitHub, Google, Azure, AWS, Discord, or Facebook.
    • The provider requires manual app registration through a developer console.
    • The provider does not support DCR.

    Do NOT use the OAuth Proxy when:

    • The provider supports DCR (e.g., Descope, WorkOS AuthKit). In this case, use RemoteAuthProvider instead.
    • The provider supports OIDC discovery (e.g., Auth0, Google with OIDC configuration, Azure AD). In these cases, use the OIDC Proxy for automatic configuration via the /.well-known/openid-configuration URL.
  7. Overview of Background Tasks in FastMCP (SEP-2663)

    main

    FastMCP implements background task support via the io.modelcontextprotocol/tasks extension (SEP-2663). This allows servers to execute long-running operations as tasks rather than standard synchronous tool calls.

    Key characteristics of the FastMCP implementation:

    • Execution Engine: Uses Docket (a queue, worker, and result store) with memory:// or redis:// backends for durability.
    • Task Identification: Task IDs are server-generated.
    • Polling Model: Clients retrieve results by polling tasks/get until a terminal status is reached. The result is inlined in the response.
    • In-task Input: If a task requires user input during execution, the status changes to input_required. The client provides answers via tasks/update.
    • Zero-Code Migration: Servers already using the @mcp.tool(task=True) decorator in FastMCP 3 require no code changes to move to the v4 implementation.

    Note: Background task support is provided by the optional fastmcp-tasks package and is gated by the task=True parameter.

    # Example of how a tool is marked as a task
    @mcp.tool(task=True)
    def long_running_operation(param: str):
        ...
  8. What is MCP Context and how to use it

    main

    The Context object provides a clean interface to interact with the underlying MCP session and access advanced server capabilities during the execution of tools, resources, or prompts.

    Capabilities provided by Context:

    • Logging: Send debug, info, warning, and error messages to the client.
    • Progress Reporting: Update the client on the status of long-running operations.
    • Resource & Prompt Access: List and read data from resources or prompts registered with the server.
    • LLM Sampling: Request the client's LLM to generate text.
    • User Elicitation: Request structured input from users during execution.
    • Session Management: Access session state, visibility controls, and request metadata.
    • Server Access: Access the underlying FastMCP server instance.

    Important Lifecycle Rules:

    • Request Scoped: Each MCP request receives a new context object. State set in one request is not available in subsequent requests.
    • Async Required: Context methods are asynchronous, so your tool/resource/prompt functions should generally be async.
    • Request-Only: Context is only available during an active request; using it outside a request will raise errors.
    from fastmcp import FastMCP
    from fastmcp.dependencies import CurrentContext
    from fastmcp.server.context import Context
    
    mcp = FastMCP(name="Context Demo")
    
    @mcp.tool
    async def process_file(file_uri: str, ctx: Context = CurrentContext()) -> str:
        """Processes a file, using context for logging and resource access.""
        await ctx.info(f"Processing {file_uri}")
        return "Processed file"
  9. What is MCP Context and its capabilities

    main

    The Context object in FastMCP provides an interface to access advanced Model Context Protocol (MCP) features within your tools, resources, and prompts. It allows your functions to interact with the underlying MCP session and perform server-side operations.

    Key Capabilities:

    • Logging: Send debug, info, warning, and error messages to the client.
    • Progress Reporting: Update the client on the status of long-running operations.
    • Resource & Prompt Access: List and read data from registered resources or prompts.
    • User Elicitation: Request structured input from users during execution.
    • Request State: Pass non-serializable resources or values between middleware and handlers within a single request using ctx.set_state().
    • Session Visibility: Control which components are visible to the current session.
    • Request Information: Access metadata about the current request.
    • Server Access: Access the underlying FastMCP server instance when required.
  10. What is the Bulk Tool Caller and when to use it

    main

    The BulkToolCaller is a class that extends MCPMixin to allow performing multiple Model Context Protocol (MCP) tool calls in a single request to a FastMCP server.

    Use this module to optimize interactions with a server by reducing the network and processing overhead associated with making many individual tool calls. It supports two primary patterns: calling many different tools at once, or calling the same tool multiple times with different sets of arguments.

  11. What is the Model Context Protocol (MCP)?

    main

    The Model Context Protocol (MCP) is an open standard that acts as a bridge between Large Language Models (LLMs) and external tools, data, and services. It provides a standardized interface (similar to USB-C for AI) that allows any MCP-compliant client (like Claude, Gemini, or OpenAI) to interact with any MCP-compliant server without custom integration code.

    Key benefits include:

    • Interoperability: One server works with any compliant client.
    • Discoverability: Clients can dynamically query a server's capabilities at runtime.
    • Explicit boundaries: Provides a typed inventory of capabilities for easier security and validation.
    • Composability: Small, specialized servers can be combined into complex applications.