FastAPI-MCP

repository·main·Indexed 11 days ago

https://github.com/tadata-org/fastapi_mcp

An automatic Model Context Protocol (MCP) server generator for FastAPI applications (v0.4.0) that converts FastAPI endpoints into MCP tools for LLM integration. It supports ASGI and HTTP transport, OAuth 2 flow via AuthConfig, and allows developers to mount MCP servers directly to FastAPI apps or deploy them as separate instances while preserving native dependencies and schemas.

Tokens
11.9K
Snippets
41
Records
60
Agent score
94%

What's inside FastAPI-MCP

  1. Key features of FastAPI-MCP

    main

    FastAPI-MCP is designed to be a FastAPI-native solution rather than a simple OpenAPI converter. Key capabilities include:

    • Authentication: Uses your existing FastAPI dependencies to secure MCP tools.
    • Zero Configuration: Works immediately when pointed at a FastAPI app.
    • Schema & Doc Preservation: Maintains the exact request/response models and Swagger documentation from your endpoints.
    • Flexible Deployment: Supports mounting the MCP server directly to your app or deploying it separately.
    • High Performance: Uses FastAPI's ASGI interface directly for efficient internal communication.
  2. Understand ASGI vs HTTP transport in FastAPI-MCP

    main

    By default, fastapi-mcp uses ASGI transport. This allows the MCP server to communicate directly with your FastAPI application instance without making actual HTTP requests.

    Benefits of ASGI transport:

    • Higher efficiency.
    • No base URL required.
    • The FastAPI server does not even need to be running for the MCP communication to work (as it interacts with the app object directly).

    If you require a different transport method (e.g., communicating with a remote server), you must provide a custom httpx.AsyncClient.

  3. Control MCP tool names using operation_id

    main

    FastAPI-MCP uses the FastAPI route's operation_id as the MCP tool name. If not specified, FastAPI generates an obfuscated name (e.g., read_user_users__user_id__get). For clear, intuitive tool names, explicitly set the operation_id in your route decorator.

    # Tool will have an obfuscated name
    @app.get("/users/{user_id}")
    async def read_user(user_id: int):
        return {"user_id": user_id}
    
    # Tool will be named "get_user_info"
    @app.get("/users/{user_id}", operation_id="get_user_info")
    async def read_user(user_id: int):
        return {"user_id": user_id}
  4. How FastAPI-MCP works: The FastAPI-first approach

    main

    Unlike tools that simply convert OpenAPI specs to MCP, fastapi-mcp is a native extension of FastAPI. This provides several architectural benefits:

    • Native Dependencies: You can secure your MCP endpoints using standard FastAPI Depends() for authentication and authorization.
    • ASGI Transport: The MCP server communicates directly with your FastAPI app via its ASGI interface, which is more efficient than making external HTTP calls from the MCP to your API.
    • Unified Infrastructure: You can run the MCP server as part of your existing FastAPI application or deploy it separately.
  5. Choose between HTTP and SSE transport methods

    main

    FastAPI-MCP provides two transport methods for client-server communication:

    1. HTTP Transport (Recommended): Implements the latest MCP Streamable HTTP specification. It offers superior session management, more robust connection handling, and follows standard HTTP practices.
    2. SSE Transport (Backwards Compatibility): Uses Server-Sent Events. This is maintained primarily for compatibility with older MCP implementations.
  6. Use setup_proxies to improve OAuth compatibility

    main

    Setting setup_proxies=True in AuthConfig creates proxy endpoints that make standard OAuth 2 providers compatible with MCP clients. This is highly recommended because it solves three common issues:

    1. Missing registration endpoints: It provides a compatible endpoint for dynamic client registration (using setup_fake_dynamic_registration which is True by default) for providers that don't support RFC 7591.
    2. Scope handling: It automatically adds necessary scopes if the MCP client fails to request them.
    3. Audience requirements: It automatically injects the audience parameter if the provider requires it but the client does not provide it.
  7. Quickstart: Expose FastAPI endpoints as MCP tools

    main

    You can create a secured Model Context Protocol (MCP) server by pointing FastApiMCP at your existing FastAPI application. This automatically exposes your endpoints as MCP tools while preserving request/response schemas and Swagger documentation. By default, the MCP server is available at the /mcp path of your application.

    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP
    
    app = FastAPI()
    
    mcp = FastApiMCP(app)
    mcp.mount_http()
  8. Write effective documentation for MCP tools

    main

    High-quality documentation is critical for LLMs to understand how to invoke your tools. Ensure every tool includes:

    • Meaningful summaries: A clear, concise description of the tool's purpose.
    • Parameter descriptions: Detailed explanations of what each input parameter does.
    • Usage examples: Concrete examples of how to call the tool correctly.
    • Consistency: Standardize the format and structure of documentation across all tools to improve reliability.
  9. Create a basic MCP server with FastAPI-MCP

    main

    To create an MCP server, you need to wrap an existing FastAPI application instance with the FastApiMCP class and then call mcp.mount_http() to mount the MCP endpoints to your application. By default, the MCP server will be available at the /mcp path of your FastAPI application.

    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP
    
    # Create (or import) a FastAPI app
    app = FastAPI()
    
    # Create an MCP server based on this app
    mcp = FastApiMCP(app)
    
    # Mount the MCP server directly to your app
    mcp.mount_http()
  10. Mount MCP using HTTP transport

    main

    To use the recommended HTTP transport method, call mcp.mount_http() on your FastApiMCP instance. This implements the latest MCP Streamable HTTP specification.

    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP
    
    app = FastAPI()
    mcp = FastApiMCP(app)
    
    # Mount using HTTP transport (recommended)
    mcp.mount_http()
  11. Basic usage: Mount MCP server to FastAPI app

    main

    The simplest way to use FastAPI-MCP is to instantiate FastApiMCP with your FastAPI app and call .mount(). This automatically exposes your endpoints as MCP tools at the /mcp path.

    from fastapi import FastAPI
    from fastapi_mcp import FastApiMCP
    
    app = FastAPI()
    
    mcp = FastApiMCP(app)
    
    # Mount the MCP server directly to your FastAPI app
    mcp.mount()