MCP ExplorerExplorer

Fastapi Mcp

@nguyendinhsinh361on 9 months ago
1 MIT
FreeCommunity
AI Systems
FastAPI-MCP is a zero-configuration tool for exposing FastAPI endpoints as MCP tools.

Overview

What is Fastapi Mcp

FastAPI-MCP is a zero-configuration tool designed to automatically expose FastAPI endpoints as Model Context Protocol (MCP) tools, simplifying the integration of FastAPI applications with MCP.

Use cases

Use cases for FastAPI-MCP include developing APIs that need to be exposed as MCP tools, integrating FastAPI applications with other systems that utilize MCP, and creating documentation for endpoints in a user-friendly manner.

How to use

To use FastAPI-MCP, simply install it using ‘uv add fastapi-mcp’ or ‘pip install fastapi-mcp’. Then, mount the MCP server directly to your FastAPI app, and it will automatically discover and expose all FastAPI endpoints as MCP tools.

Key features

- Direct integration with FastAPI applications.

  • Zero configuration required for setup.
  • Automatic discovery of FastAPI endpoints and conversion to MCP tools.
  • Preservation of request and response model schemas.
  • Maintains documentation of endpoints as seen in Swagger.
  • Flexible deployment options.

Where to use

FastAPI-MCP can be used in any application that utilizes FastAPI and requires integration with Model Context Protocol, making it suitable for web services, APIs, and microservices architectures.

Content

fastapi-to-mcp

FastAPI-MCP

A zero-configuration tool for automatically exposing FastAPI endpoints as Model Context Protocol (MCP) tools.

PyPI version
Python Versions
FastAPI

CI
codecov

fastapi-mcp-usage

Features

  • Direct integration - Mount an MCP server directly to your FastAPI app
  • Zero configuration required - just point it at your FastAPI app and it works
  • Automatic discovery of all FastAPI endpoints and conversion to MCP tools
  • Preserving schemas of your request models and response models
  • Preserve documentation of all your endpoints, just as it is in Swagger
  • Flexible deployment - Mount your MCP server to the same app, or deploy separately

Installation

We recommend using uv, a fast Python package installer:

uv add fastapi-mcp

Alternatively, you can install with pip:

pip install fastapi-mcp

Basic Usage

The simplest way to use FastAPI-MCP is to add an MCP server directly to your FastAPI application:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
    app,

    # Optional parameters
    name="My API MCP",
    description="My API description",
    base_url="http://localhost:8000",
)

# Mount the MCP server directly to your FastAPI app
mcp.mount()

That’s it! Your auto-generated MCP server is now available at https://app.base.url/mcp.

Note on base_url: While base_url is optional, it is highly recommended to provide it explicitly. The base_url tells the MCP server where to send API requests when tools are called. Without it, the library will attempt to determine the URL automatically, which may not work correctly in deployed environments where the internal and external URLs differ.

Tool Naming

FastAPI-MCP uses the operation_id from your FastAPI routes as the MCP tool names. When you don’t specify an operation_id, FastAPI auto-generates one, but these can be cryptic.

Compare these two endpoint definitions:

# Auto-generated operation_id (something like "read_user_users__user_id__get")
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

# Explicit operation_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}

For clearer, more intuitive tool names, we recommend adding explicit operation_id parameters to your FastAPI route definitions.

To find out more, read FastAPI’s official docs about advanced config of path operations.

Advanced Usage

FastAPI-MCP provides several ways to customize and control how your MCP server is created and configured. Here are some advanced usage patterns:

Customizing Schema Description

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

mcp = FastApiMCP(
    app,
    name="My API MCP",
    base_url="http://localhost:8000",
    describe_all_responses=True,     # Include all possible response schemas in tool descriptions
    describe_full_response_schema=True  # Include full JSON schema in tool descriptions
)

mcp.mount()

Customizing Exposed Endpoints

You can control which FastAPI endpoints are exposed as MCP tools using Open API operation IDs or tags:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# Only include specific operations
mcp = FastApiMCP(
    app,
    include_operations=["get_user", "create_user"]
)

# Exclude specific operations
mcp = FastApiMCP(
    app,
    exclude_operations=["delete_user"]
)

# Only include operations with specific tags
mcp = FastApiMCP(
    app,
    include_tags=["users", "public"]
)

# Exclude operations with specific tags
mcp = FastApiMCP(
    app,
    exclude_tags=["admin", "internal"]
)

# Combine operation IDs and tags (include mode)
mcp = FastApiMCP(
    app,
    include_operations=["user_login"],
    include_tags=["public"]
)

mcp.mount()

Notes on filtering:

  • You cannot use both include_operations and exclude_operations at the same time
  • You cannot use both include_tags and exclude_tags at the same time
  • You can combine operation filtering with tag filtering (e.g., use include_operations with include_tags)
  • When combining filters, a greedy approach will be taken. Endpoints matching either criteria will be included

Deploying Separately from Original FastAPI App

You are not limited to serving the MCP on the same FastAPI app from which it was created.

You can create an MCP server from one FastAPI app, and mount it to a different app:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

# Your API app
api_app = FastAPI()
# ... define your API endpoints on api_app ...

# A separate app for the MCP server
mcp_app = FastAPI()

# Create MCP server from the API app
mcp = FastApiMCP(
    api_app,
    base_url="http://api-host:8001",  # The URL where the API app will be running
)

# Mount the MCP server to the separate app
mcp.mount(mcp_app)

# Now you can run both apps separately:
# uvicorn main:api_app --host api-host --port 8001
# uvicorn main:mcp_app --host mcp-host --port 8000

Adding Endpoints After MCP Server Creation

If you add endpoints to your FastAPI app after creating the MCP server, you’ll need to refresh the server to include them:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
# ... define initial endpoints ...

# Create MCP server
mcp = FastApiMCP(app)
mcp.mount()

# Add new endpoints after MCP server creation
@app.get("/new/endpoint/", operation_id="new_endpoint")
async def new_endpoint():
    return {"message": "Hello, world!"}

# Refresh the MCP server to include the new endpoint
mcp.setup_server()

Examples

See the examples directory for complete examples.

Connecting to the MCP Server using SSE

Once your FastAPI app with MCP integration is running, you can connect to it with any MCP client supporting SSE, such as Cursor:

  1. Run your application.

  2. In Cursor -> Settings -> MCP, use the URL of your MCP server endpoint (e.g., http://localhost:8000/mcp) as sse.

  3. Cursor will discover all available tools and resources automatically.

Connecting to the MCP Server using mcp-proxy stdio

If your MCP client does not support SSE, for example Claude Desktop:

  1. Run your application.

  2. Install mcp-proxy, for example: uv tool install mcp-proxy.

  3. Add in Claude Desktop MCP config file (claude_desktop_config.json):

On Windows:

{
  "mcpServers": {
    "my-api-mcp-proxy": {
      "command": "mcp-proxy",
      "args": [
        "http://127.0.0.1:8000/mcp"
      ]
    }
  }
}

On MacOS:

{
  "mcpServers": {
    "my-api-mcp-proxy": {
      "command": "/Full/Path/To/Your/Executable/mcp-proxy",
      "args": [
        "http://127.0.0.1:8000/mcp"
      ]
    }
  }
}

Find the path to mcp-proxy by running in Terminal: which mcp-proxy.

  1. Claude Desktop will discover all available tools and resources automatically

Development and Contributing

Thank you for considering contributing to FastAPI-MCP! We encourage the community to post Issues and Pull Requests.

Before you get started, please see our Contribution Guide.

Community

Join MCParty Slack community to connect with other MCP enthusiasts, ask questions, and share your experiences with FastAPI-MCP.

Requirements

  • Python 3.10+ (Recommended 3.12)
  • uv

License

MIT License. Copyright © 2024 Tadata Inc.

Tools

No tools

Comments

Recommend MCP Servers

View All MCP Servers