Doramagic Project Pack · Human Manual

fastapi_mcp

FastAPI-MCP is a bridge library that converts FastAPI applications into MCP (Model Context Protocol) servers with minimal configuration. It allows developers to expose their existing FastA...

FastAPI-MCP Home

Related topics: System Architecture, Quickstart Guide, Installation

Section Related Pages

Continue reading this section for the full explanation and source context.

Section High-Level Architecture

Continue reading this section for the full explanation and source context.

Section Component Overview

Continue reading this section for the full explanation and source context.

Section FastApiMCP Constructor Parameters

Continue reading this section for the full explanation and source context.

Related topics: System Architecture, Quickstart Guide, Installation

FastAPI-MCP Home

Overview

FastAPI-MCP is a bridge library that converts FastAPI applications into MCP (Model Context Protocol) servers with minimal configuration. It allows developers to expose their existing FastAPI endpoints as MCP tools, enabling AI assistants to interact with FastAPI services through the MCP protocol.

Sources: README.md

Key Features

FeatureDescription
Authentication Built-inUses existing FastAPI dependencies for auth
FastAPI-NativeNot just another OpenAPI → MCP converter
Zero/Minimal ConfigurationPoint it at your FastAPI app and it works
Schema PreservationMaintains request and response model schemas
Documentation PreservationKeeps endpoint documentation from Swagger
Flexible DeploymentMount MCP servers separately or with the API

Sources: README.md

Requirements

  • Python 3.10+ (Recommended 3.12)
  • uv package manager

Sources: README.md

Installation

The package can be installed using uv:

uv add fastapi-mcp

For development dependencies:

uv add --group dev <package-name>

Sources: CONTRIBUTING.md

Quick Start

The simplest way to use FastAPI-MCP is to create an instance and mount it to your FastAPI app:

from examples.shared.apps.items import app  # Your FastAPI app
from fastapi_mcp import FastApiMCP

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

# Mount the MCP server to the FastAPI app
mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

After mounting, your MCP server will be available at /mcp endpoint by default.

Sources: examples/01_basic_usage_example.py

Architecture

High-Level Architecture

graph TD
    A[FastAPI Application] --> B[FastApiMCP]
    B --> C[MCP Tools]
    B --> D[OpenAPI Schema]
    C --> E[AI Assistant]
    E --> F[MCP Protocol]
    F --> C
    G[Authentication] --> B

Component Overview

The FastAPI-MCP library consists of the following key components:

ComponentFilePurpose
FastApiMCPfastapi_mcp/__init__.pyMain class for creating MCP servers from FastAPI apps
AuthConfigfastapi_mcp/types.pyConfiguration for MCP authentication
OAuthMetadatafastapi_mcp/types.pyOAuth 2.0 Server Metadata
Tool Conversionfastapi_mcp/openapi/convert.pyConverts OpenAPI schemas to MCP tools

Sources: fastapi_mcp/types.py Sources: fastapi_mcp/server.py

Configuration Options

FastApiMCP Constructor Parameters

ParameterTypeDefaultDescription
appFastAPIRequiredThe FastAPI application instance
namestr"fastapi-mcp"MCP server name
descriptionstrNoneMCP server description
describe_all_responsesboolFalseInclude all possible response schemas
describe_full_response_schemaboolFalseInclude full JSON schema for responses
http_clienthttpx.AsyncClientNoneCustom HTTP client for API calls
include_operationsList[str]NoneOperation IDs to include
exclude_operationsList[str]NoneOperation IDs to exclude
include_tagsList[str]NoneTags to include
exclude_tagsList[str]NoneTags to exclude
auth_configAuthConfigNoneAuthentication configuration
headersList[str]["authorization"]Headers to forward

Sources: fastapi_mcp/server.py

Mounting Options

The MCP server can be mounted using mount_http():

mcp.mount_http(mount_path="/custom-mcp-path")

Default mount path is /mcp.

Sources: fastapi_mcp/server.py

Endpoint Filtering

FastAPI-MCP supports filtering which endpoints are exposed as MCP tools through operation IDs and tags.

Filtering Rules

  • Cannot use both include_operations and exclude_operations simultaneously
  • Cannot use both include_tags and exclude_tags simultaneously
  • Can combine operation filtering with tag filtering (greedy approach)
  • Endpoints matching either criteria will be included when combining filters

Sources: examples/03_custom_exposed_endpoints_example.py

Filtering Examples

from fastapi_mcp import FastApiMCP

# Include specific operation IDs
mcp1 = FastApiMCP(
    app,
    include_operations=["get_item", "list_items"]
)

# Exclude specific operation IDs
mcp2 = FastApiMCP(
    app,
    exclude_operations=["create_item", "update_item", "delete_item"]
)

# Include specific tags
mcp3 = FastApiMCP(
    app,
    include_tags=["items"]
)

# Combine filters (include mode)
mcp4 = FastApiMCP(
    app,
    include_operations=["delete_item"],
    include_tags=["search"],
)

# Mount with different paths
mcp1.mount_http(mount_path="/filtered-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py

Internal Filtering Logic

The _filter_tools method processes filtering based on operation IDs and tags:

graph TD
    A[Tools List] --> B{Any Filters Set?}
    B -->|No| Z[Return All Tools]
    B -->|Yes| C[Build Operations by Tag Map]
    C --> D{Operation ID Filter?}
    D -->|Include| E[Keep Matching Operations]
    D -->|Exclude| F[Remove Matching Operations]
    E --> G{Tag Filter?}
    F --> G
    G -->|Include Tags| H[Keep Matching Tags]
    G -->|Exclude Tags| I[Remove Matching Tags]
    H --> J[Return Filtered Tools]
    I --> J

Sources: fastapi_mcp/server.py

Authentication Configuration

FastAPI-MCP provides built-in support for MCP authentication using OAuth 2.0.

AuthConfig Parameters

ParameterTypeDefaultDescription
versionLiteral["2025-03-26"]"2025-03-26"MCP spec version
dependenciesSequence[Depends]NoneFastAPI auth dependencies
issuerstrNoneOAuth 2.0 issuer URL
oauth_metadata_urlStrHttpUrlNoneOAuth metadata endpoint
authorize_urlStrHttpUrlNoneAuthorization endpoint
token_endpointStrHttpUrlNoneToken endpoint
revocation_endpointStrHttpUrlNoneToken revocation endpoint
jwks_uriStrHttpUrlNoneJWKS URI
signing_keystrNoneJWT signing key

Sources: fastapi_mcp/types.py

Token Passthrough Example

To reject requests without valid authorization tokens:

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()

Sources: examples/08_auth_example_token_passthrough.py

OAuth Configuration

The MCP client configuration for remote servers with auth headers:

{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}

Sources: examples/08_auth_example_token_passthrough.py

Development Setup

Local Development Environment

  1. Fork the repository
  2. Clone your fork:
git clone https://github.com/YOUR-USERNAME/fastapi_mcp.git
cd fastapi-mcp
git remote add upstream https://github.com/tadata-org/fastapi_mcp.git
  1. Set up development environment:
uv sync
  1. Install pre-commit hooks:
uv run pre-commit install
uv run pre-commit run

Sources: CONTRIBUTING.md

Running Tests and Checks

# Run all tests
pytest

# Check code formatting and style
ruff check .
ruff format .

# Check types
mypy .

Sources: CONTRIBUTING.md

Version History

VersionChanges
LatestSupport for deploying MCP servers separately; endpoint filtering capabilities; setup_server() for dynamic routes
0.1.8Removed unneeded dependency
0.1.7Fixed syntax error (Issue #34)
0.1.6Hid handle_mcp_connection tool (Issue #23)

Sources: CHANGELOG.md

Community

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

Sources: README.md

License

MIT License. Copyright (c) 2024-2025 Tadata Inc.

Sources: README.md Sources: README_zh-CN.md

Sources: README.md

System Architecture

Related topics: FastAPI-MCP Home, Authentication Overview, Transport Configuration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Architecture

Continue reading this section for the full explanation and source context.

Section FastApiMCP Server

Continue reading this section for the full explanation and source context.

Section Transport Layer

Continue reading this section for the full explanation and source context.

Related topics: FastAPI-MCP Home, Authentication Overview, Transport Configuration

System Architecture

Overview

FastAPI-MCP is a framework that automatically generates MCP (Model Context Protocol) servers from existing FastAPI applications. The architecture follows a FastAPI-first approach, meaning it integrates directly with FastAPI's ASGI interface rather than functioning as a separate HTTP service.

The primary design goals are:

  • Native dependencies: Use familiar FastAPI Depends() for authentication
  • ASGI transport: Communicate directly with the FastAPI app through its ASGI interface
  • Zero/minimal configuration: Point it at a FastAPI app and it works immediately
  • Schema preservation: Maintain request/response model schemas and documentation

Sources: README.md

Core Components

Component Architecture

graph TD
    subgraph "Client Layer"
        MCP_CLIENT[MCP Client<br/>Claude, etc.]
    end
    
    subgraph "FastAPI-MCP Core"
        MCP_SERVER[FastApiMCP Server]
        TRANSPORT[Transport Layer<br/>HTTP/SSE]
        CONVERT[OpenAPI Converter]
        FILTER[Tool Filter]
    end
    
    subgraph "FastAPI Application"
        FASTAPI[FastAPI App]
        DEPENDS[Dependencies<br/>Auth, etc.]
        ROUTES[Routes]
    end
    
    MCP_CLIENT <--> TRANSPORT
    MCP_SERVER --> TRANSPORT
    MCP_SERVER --> CONVERT
    MCP_SERVER --> FILTER
    TRANSPORT <--> FASTAPI
    FASTAPI --> DEPENDS
    FASTAPI --> ROUTES

FastApiMCP Server

The FastApiMCP class is the main entry point for the library. It handles:

  • MCP server initialization and lifecycle
  • Tool discovery from FastAPI endpoints
  • HTTP client operations for invoking endpoints
  • Tool filtering based on operations and tags
  • Mounting the MCP server to FastAPI applications

Sources: fastapi_mcp/server.py:1-100

Transport Layer

FastAPI-MCP supports multiple transport mechanisms:

TransportDescriptionUse Case
HTTPStandard HTTP transport with JSON-RPCDefault transport
SSEServer-Sent EventsStreaming responses

The transport layer handles:

  • Request/response serialization
  • MCP protocol encoding/decoding
  • Connection management

Sources: fastapi_mcp/transport/http.py, fastapi_mcp/transport/sse.py

OpenAPI Schema Converter

The converter transforms FastAPI endpoint definitions into MCP tool schemas:

graph LR
    subgraph "FastAPI"
        OPERATION[Operation]
        PARAMETERS[Parameters]
        REQUEST_BODY[Request Body]
        RESPONSE[Response Schema]
    end
    
    subgraph "Conversion Process"
        VALIDATE[Validate Schema]
        ORGANIZE[Organize Params]
        BUILD[Build Tool Description]
    end
    
    subgraph "MCP Tool"
        TOOL[Tool Definition]
        INPUT_SCHEMA[Input Schema]
        DESCRIPTION[Description]
    end
    
    OPERATION --> VALIDATE
    PARAMETERS --> ORGANIZE
    REQUEST_BODY --> ORGANIZE
    VALIDATE --> BUILD
    ORGANIZE --> BUILD
    RESPONSE --> BUILD
    BUILD --> TOOL
    BUILD --> INPUT_SCHEMA
    BUILD --> DESCRIPTION

The converter processes:

  • Path, query, and header parameters separately
  • Request body schemas
  • Response schemas with optional full schema inclusion
  • Documentation from OpenAPI descriptions

Sources: fastapi_mcp/openapi/convert.py

Data Flow

Tool Invocation Flow

sequenceDiagram
    participant Client as MCP Client
    participant MCP as FastApiMCP Server
    participant Filter as Tool Filter
    participant Convert as OpenAPI Converter
    participant API as FastAPI App
    participant Auth as Auth Dependencies

    Client->>MCP: ListTools Request
    MCP->>Filter: Get filtered tools
    Filter->>Convert: Request tool definitions
    Convert->>API: Fetch OpenAPI schema
    API-->>Convert: OpenAPI spec
    Convert-->>Filter: Tool definitions
    Filter-->>MCP: Filtered tools
    MCP-->>Client: Tool list

    Client->>MCP: CallTool Request
    MCP->>Filter: Validate tool allowed
    Filter-->>MCP: Tool valid
    MCP->>API: Invoke endpoint (HTTP)
    API->>Auth: Run dependencies
    Auth-->>API: Auth OK
    API-->>MCP: Response
    MCP-->>Client: Tool result

Parameter Organization

The converter organizes parameters into distinct categories:

CategoryOpenAPI LocationProcessing
Pathparameters[in=path]Required for route matching
Queryparameters[in=query]Optional filters
Headerparameters[in=header]Metadata forwarding
BodyrequestBodyJSON payload

Sources: fastapi_mcp/openapi/convert.py:50-80

Tool Filtering System

Filter Types

FastAPI-MCP provides granular control over which endpoints become MCP tools:

graph TD
    subgraph "Filter Configuration"
        INCL_OPS[include_operations]
        EXCL_OPS[exclude_operations]
        INCL_TAGS[include_tags]
        EXCL_TAGS[exclude_tags]
    end
    
    subgraph "Operations Index"
        OPS_BY_TAG[Operations by Tag]
        OPS_BY_ID[Operations by ID]
    end
    
    INCL_OPS --> OPS_BY_ID
    EXCL_OPS --> OPS_BY_ID
    INCL_TAGS --> OPS_BY_TAG
    EXCL_TAGS --> OPS_BY_TAG

Filter Rules

Filter TypeDescriptionMutual Exclusion
include_operationsWhitelist specific operation IDsCannot use with exclude_operations
exclude_operationsBlacklist specific operation IDsCannot use with include_operations
include_tagsWhitelist endpoints by tagCannot use with exclude_tags
exclude_tagsBlacklist endpoints by tagCannot use with include_tags

Greedy Matching: When combining operation and tag filters, endpoints matching either criteria are included.

Sources: fastapi_mcp/server.py:80-120, examples/03_custom_exposed_endpoints_example.py

Authentication Architecture

AuthConfig Structure

class AuthConfig(BaseType):
    version: Literal["2025-03-26"]  # MCP spec version
    dependencies: Sequence[Depends]  # FastAPI auth dependencies
    issuer: Optional[str]  # OAuth issuer URL
    oauth_metadata_url: Optional[StrHttpUrl]  # OAuth metadata endpoint
    authorize_url: Optional[StrHttpUrl]  # OAuth authorization endpoint

Authentication Flow

graph LR
    subgraph "Client"
        REQUEST[MCP Request]
        HEADER[Auth Header]
    end
    
    subgraph "FastAPI-MCP"
        FORWARD[Forward Headers]
        VALIDATE[Validate with Depends]
    end
    
    subgraph "FastAPI App"
        AUTH_DEP[Auth Dependency]
        PROTECTED[Protected Endpoint]
    end
    
    REQUEST --> HEADER
    HEADER --> FORWARD
    FORWARD --> VALIDATE
    VALIDATE --> AUTH_DEP
    AUTH_DEP --> PROTECTED

Header Forwarding

By default, the authorization header is forwarded from MCP requests to FastAPI endpoint invocations. Additional headers can be configured:

mcp = FastApiMCP(
    app,
    headers=["authorization", "x-custom-header"]
)

Sources: fastapi_mcp/types.py:100-150, examples/08_auth_example_token_passthrough.py

Configuration Options

FastApiMCP Constructor Parameters

ParameterTypeDefaultDescription
appFastAPIRequiredFastAPI application instance
namestrRequiredMCP server name
describe_all_responsesboolFalseInclude all possible response schemas
describe_full_response_schemaboolFalseInclude full JSON schema for responses
http_clienthttpx.AsyncClientNoneCustom HTTP client
include_operationsList[str]NoneOperation IDs to include
exclude_operationsList[str]NoneOperation IDs to exclude
include_tagsList[str]NoneTags to include
exclude_tagsList[str]NoneTags to exclude
auth_configAuthConfigNoneAuthentication configuration
headersList[str]["authorization"]Headers to forward

Sources: fastapi_mcp/server.py:150-200

Type System

Core Types

classDiagram
    class BaseType {
        +model_config: ConfigDict
        +model_dump() dict
    }
    
    class HTTPRequestInfo {
        +method: str
        +path: str
        +headers: Dict
        +cookies: Dict
        +query_params: Dict
        +body: Any
    }
    
    class OAuthMetadata {
        +issuer: StrHttpUrl
        +authorization_endpoint: StrHttpUrl
        +token_endpoint: StrHttpUrl
        +scopes_supported: List[str]
    }
    
    class AuthConfig {
        +version: str
        +dependencies: Sequence
        +issuer: str
    }
    
    BaseType <|-- HTTPRequestInfo
    BaseType <|-- OAuthMetadata
    BaseType <|-- AuthConfig

HTTPRequestInfo

Captures incoming HTTP request details for authentication and routing:

class HTTPRequestInfo(BaseType):
    method: str           # HTTP method (GET, POST, etc.)
    path: str             # Request path
    headers: Dict[str, str]
    cookies: Dict[str, str]
    query_params: Dict[str, str]
    body: Any             # Request body

Sources: fastapi_mcp/types.py:30-50

Deployment Models

Integrated Deployment (Default)

The MCP server is mounted directly into the FastAPI application:

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app, name="My MCP")
mcp.mount_http()

# MCP available at /mcp endpoint

Separate Deployment

FastAPI-MCP also supports running the MCP server separately from the original FastAPI application for advanced deployment scenarios.

Sources: README.md, fastapi_mcp/server.py

HTTP Client Operations

Supported Methods

MethodHandlerBody SupportQuery Support
GETclient.get()NoYes
POSTclient.post()YesYes
PUTclient.put()YesYes
DELETEclient.delete()NoYes
PATCHclient.patch()YesYes

The internal HTTP client executes requests to FastAPI endpoints:

async def _make_request(
    method: str,
    path: str,
    query: Dict[str, Any],
    headers: Dict[str, str],
    body: Any
) -> httpx.Response:
    if method.lower() == "get":
        return await client.get(path, params=query, headers=headers)
    elif method.lower() == "post":
        return await client.post(path, params=query, headers=headers, json=body)
    # ... other methods

Sources: fastapi_mcp/server.py:30-60

Summary

The FastAPI-MCP architecture provides a seamless bridge between FastAPI applications and the MCP protocol:

  1. Non-intrusive integration: Mounts directly onto existing FastAPI apps
  2. Flexible filtering: Fine-grained control over exposed tools
  3. Native auth: Leverages FastAPI's dependency injection system
  4. Schema preservation: Maintains OpenAPI documentation and type information
  5. Multiple transports: Supports both HTTP and SSE for different use cases

The system is designed for zero-configuration use while providing extensive customization options for advanced scenarios.

Sources: README.md

Installation

Related topics: FastAPI-MCP Home, Quickstart Guide

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Requirements

Continue reading this section for the full explanation and source context.

Section Installing uv

Continue reading this section for the full explanation and source context.

Section For Users: Installing the Package

Continue reading this section for the full explanation and source context.

Related topics: FastAPI-MCP Home, Quickstart Guide

Installation

This page provides comprehensive instructions for setting up the fastapi-mcp development environment, including prerequisites, installation methods, and post-installation configuration.

Overview

The fastapi-mcp project enables bridging FastAPI applications with the Model Context Protocol (MCP). The installation process involves setting up the Python environment, configuring the uv package manager, and preparing development tools for code quality assurance.

Sources: README.md

Prerequisites

Before installing fastapi-mcp, ensure your system meets the following requirements.

System Requirements

RequirementVersionDescription
Python3.10+Minimum supported Python version
Python (Recommended)3.12Preferred Python version for best compatibility
uvLatestASTRA's Python package manager

Sources: README.md, CONTRIBUTING.md:17

Installing uv

The project uses uv as its package manager. Install uv by following the official documentation:

# Installation command (refer to https://docs.astral.sh/uv/getting-started/installation/)
curl -LsSf https://astral.sh/uv/install.sh | sh

Alternatively, for pip users:

pip install uv

Sources: CONTRIBUTING.md:18

Installation Methods

For Users: Installing the Package

For end users who want to use fastapi-mcp as a dependency:

# Using uv
uv add fastapi-mcp

# Or using pip
pip install fastapi-mcp

For Developers: Setting Up the Development Environment

For contributors setting up the local development environment:

graph TD
    A[Fork Repository] --> B[Clone Your Fork]
    B --> C[Add Upstream Remote]
    C --> D[uv sync]
    D --> E[Install Pre-commit Hooks]
    E --> F[Ready for Development]

#### Step 1: Fork and Clone

# Fork the repository on GitHub
# Clone your fork
git clone https://github.com/YOUR-USERNAME/fastapi_mcp.git
cd fastapi-mcp

# Add the upstream remote
git remote add upstream https://github.com/tadata-org/fastapi_mcp.git

Sources: CONTRIBUTING.md:24-35

#### Step 2: Sync Dependencies

The uv sync command automatically creates and manages a virtual environment:

uv sync

This command will:

  • Create a .venv directory with a virtual environment
  • Install all runtime dependencies from pyproject.toml
  • Install development dependencies (marked with --group dev)

Sources: CONTRIBUTING.md:37-43

#### Step 3: Install Pre-commit Hooks

Pre-commit hooks automatically run code quality checks before each commit:

# Install the hooks
uv run pre-commit install

# Run all hooks manually (optional, for verification)
uv run pre-commit run

Sources: CONTRIBUTING.md:45-51

Running Commands

You have two options for executing commands within the development environment.

Option 1: Activate the Virtual Environment

# On Unix/macOS
source .venv/bin/activate

# On Windows
.venv\Scripts\activate

# Then run commands directly
pytest
mypy .
ruff check .
ruff format .

Option 2: Use uv run Prefix

# Without activating the environment
uv run pytest
uv run mypy .
uv run ruff check .
uv run ruff format .

Sources: CONTRIBUTING.md:53-75

Adding Dependencies

Runtime Dependencies

Packages needed to run the application:

uv add new-package

Development Dependencies

Packages needed for development, testing, or CI:

uv add --group dev new-package

After adding dependencies:

  1. Test that everything works with the new package
  2. Commit both pyproject.toml and uv.lock files:
git add pyproject.toml uv.lock
git commit -m "Add new-package dependency"

Sources: CONTRIBUTING.md:77-92

Code Quality Tools

The project enforces code quality using the following tools:

ToolPurposeCommand
ruffLinting and formattingruff check . / ruff format .
mypyType checkingmypy .
pytestTestingpytest
pre-commitAutomated checkspre-commit run

Sources: CONTRIBUTING.md:94-104

Running All Checks

Before submitting a pull request, ensure all checks pass:

# Format code
ruff format .

# Check code style
ruff check .

# Type checking
mypy .

# Run tests
pytest

Quick Start Checklist

Use this checklist to verify your installation is complete:

  • [ ] Python 3.10+ is installed (python --version)
  • [ ] uv is installed (uv --version)
  • [ ] Repository is forked and cloned
  • [ ] uv sync completed successfully
  • [ ] uv run pre-commit install executed
  • [ ] uv run pre-commit run passes (or first commit triggers it)
  • [ ] uv run pytest runs successfully
  • [ ] uv run mypy . passes type checking

Troubleshooting

Common Issues

Virtual environment not found

uv sync

Pre-commit hooks not running

uv run pre-commit install
uv run pre-commit run --all-files

Dependency conflicts

uv sync --refresh

Sources: README.md

Quickstart Guide

Related topics: FastAPI-MCP Home, Examples Overview, Endpoint Filtering and Selection

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 1. Import FastApiMCP

Continue reading this section for the full explanation and source context.

Section 2. Create the MCP Server Instance

Continue reading this section for the full explanation and source context.

Section 3. Mount the MCP Server

Continue reading this section for the full explanation and source context.

Related topics: FastAPI-MCP Home, Examples Overview, Endpoint Filtering and Selection

Quickstart Guide

This guide provides a comprehensive walkthrough for getting started with FastAPI-MCP, a library that seamlessly integrates FastAPI applications with the Model Context Protocol (MCP). It allows you to expose your FastAPI endpoints as MCP tools with minimal configuration.

Prerequisites

Before getting started, ensure you have the following installed:

RequirementVersionNotes
Python3.10+ (Recommended 3.12)The project uses modern Python features
uvLatestPackage manager for dependency installation

Sources: README.md

Installation

Install FastAPI-MCP using uv:

uv add fastapi-mcp

For development setup with all dependencies:

git clone https://github.com/YOUR-USERNAME/fastapi_mcp.git
cd fastapi-mcp
uv sync

Sources: CONTRIBUTING.md

Basic Usage

The simplest way to add an MCP server to your FastAPI application involves three steps:

1. Import FastApiMCP

from fastapi_mcp import FastApiMCP

Sources: examples/01_basic_usage_example.py:1

2. Create the MCP Server Instance

Pass your FastAPI app to the FastApiMCP constructor:

from examples.shared.apps.items import app  # Your FastAPI app
from examples.shared.setup import setup_logging

from fastapi_mcp import FastApiMCP

setup_logging()

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

Sources: examples/01_basic_usage_example.py:1-9

3. Mount the MCP Server

Mount the MCP server to your FastAPI app using mount_http():

# Mount the MCP server to the FastAPI app
mcp.mount_http()

Sources: examples/01_basic_usage_example.py:12

4. Run the Server

Start the uvicorn server:

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

Sources: examples/01_basic_usage_example.py:15-18

Complete Basic Example

Here is the full minimal example from examples/01_basic_usage_example.py:

from examples.shared.apps.items import app  # The FastAPI app
from examples.shared.setup import setup_logging

from fastapi_mcp import FastApiMCP

setup_logging()

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

# Mount the MCP server to the FastAPI app
mcp.mount_http()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

Sources: examples/01_basic_usage_example.py:1-19

Architecture Overview

graph TD
    A[FastAPI Application] --> B[FastApiMCP]
    B --> C[MCP Server]
    C --> D[HTTP Endpoint /mcp]
    D --> E[MCP Client]
    
    F[OpenAPI Schema] --> B
    B --> G[MCP Tools]
    
    style A fill:#e1f5ff
    style C fill:#fff3e0
    style D fill:#e8f5e9

Enhanced Schema Description

By default, FastAPI-MCP provides concise tool descriptions. You can enhance the descriptions by enabling additional options:

mcp = FastApiMCP(
    app,
    name="Item API MCP",
    description="MCP server for the Item API",
    describe_full_response_schema=True,  # Describe the full response JSON-schema
    describe_all_responses=True,         # Describe all possible responses, not just 2XX
)

mcp.mount_http()

Sources: examples/02_full_schema_description_example.py:1-18

Filtering Exposed Endpoints

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

Filter by Operation IDs

# Include specific operations
include_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)

# Exclude specific operations
exclude_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)

Filter by Tags

# Include endpoints with specific tags
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)

# Exclude endpoints with specific tags
exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)

Sources: examples/03_custom_exposed_endpoints_example.py:1-50

Adding Authentication

FastAPI-MCP supports authentication by leveraging your existing FastAPI dependencies. Use the AuthConfig class to configure authentication:

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

# Define your authentication scheme
token_auth_scheme = HTTPBearer()

# Create protected endpoint
@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

# Configure MCP with authentication
mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()

Sources: examples/08_auth_example_token_passthrough.py:1-50

Key Parameters

ParameterTypeDefaultDescription
appFastAPIRequiredThe FastAPI application instance
namestrAuto-generatedName of the MCP server
descriptionstrAuto-generatedDescription of the MCP server
describe_full_response_schemaboolFalseInclude full JSON schema for responses
describe_all_responsesboolFalseInclude all response types, not just success
include_operationsList[str]NoneOperation IDs to include
exclude_operationsList[str]NoneOperation IDs to exclude
include_tagsList[str]NoneTags to include
exclude_tagsList[str]NoneTags to exclude
auth_configAuthConfigNoneAuthentication configuration
headersList[str]["authorization"]Headers to forward to tool invocations

Sources: fastapi_mcp/server.py:1-100

Running the Quickstart

To run the basic example:

# Navigate to the examples directory
cd examples

# Run the basic usage example
uv run python 01_basic_usage_example.py

Once running, the MCP server will be available at http://localhost:8000/mcp.

Verification

After starting the server, you can verify it's working by:

  1. Accessing the OpenAPI docs at http://localhost:8000/docs
  2. Checking the MCP endpoint at http://localhost:8000/mcp

Next Steps

Sources: README.md

Examples Overview

Related topics: Quickstart Guide, OAuth Authentication, Deployment Options, Dynamic Tool Registration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Category 1: Basic Integration

Continue reading this section for the full explanation and source context.

Section Category 2: Endpoint Filtering

Continue reading this section for the full explanation and source context.

Section Category 3: Authentication Examples

Continue reading this section for the full explanation and source context.

Related topics: Quickstart Guide, OAuth Authentication, Deployment Options, Dynamic Tool Registration

Examples Overview

The examples/ directory in the FastAPI-MCP repository provides a comprehensive collection of runnable examples demonstrating the library's capabilities. These examples serve as practical guides for developers learning how to integrate FastAPI applications with the MCP (Model Context Protocol) server infrastructure.

Directory Structure

The examples directory follows a modular organization pattern:

examples/
├── README.md
├── 01_basic_usage_example.py
├── 02_multiple_apps_example.py
├── 03_custom_exposed_endpoints_example.py
├── 04_separate_server_example.py
├── 05_reregister_tools_example.py
├── 06_custom_tools_example.py
├── 07_external_app_example.py
├── 08_auth_example_token_passthrough.py
├── 09_auth_example_auth0.py
├── 10_standalone_server.py
└── shared/
    ├── apps/
    │   └── items.py
    └── setup.py

Sources: examples/README.md

Example Categories

Category 1: Basic Integration

The foundational examples demonstrate core FastAPI-MCP functionality.

#### 01 - Basic Usage

This is the simplest possible integration demonstrating how to mount an MCP server onto a FastAPI application.

from examples.shared.apps.items import app  # The FastAPI app
from examples.shared.setup import setup_logging
from fastapi_mcp import FastApiMCP

setup_logging()

# Add MCP server to the FastAPI app
mcp = FastApiMCP(app)

# Mount the MCP server to the FastAPI app
mcp.mount_http()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Key Components:

ComponentPurpose
FastApiMCP(app)Creates MCP server instance bound to FastAPI app
mcp.mount_http()Exposes MCP endpoint at /mcp path
setup_logging()Configures logging for debugging

Sources: examples/01_basic_usage_example.py:1-19

Category 2: Endpoint Filtering

These examples demonstrate how to control which FastAPI endpoints are exposed as MCP tools.

#### 03 - Custom Exposed Endpoints

The filtering system allows selective exposure of endpoints using operation IDs or tags.

Filtering Rules:

  • Cannot use both include_operations and exclude_operations simultaneously
  • Cannot use both include_tags and exclude_tags simultaneously
  • Operation filtering can be combined with tag filtering (greedy approach)
# Filter by including specific operation IDs
include_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)

# Filter by excluding specific operation IDs
exclude_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)

# Filter by including specific tags
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)

Sources: examples/03_custom_exposed_endpoints_example.py:1-39

Filtering Parameters:

ParameterTypeDescription
include_operationsList[str]Operation IDs to include as MCP tools
exclude_operationsList[str]Operation IDs to exclude from MCP tools
include_tagsList[str]Tags to include as MCP tools
exclude_tagsList[str]Tags to exclude from MCP tools

Sources: fastapi_mcp/server.py:85-100

Category 3: Authentication Examples

FastAPI-MCP supports OAuth 2.0 authentication integration using FastAPI's dependency injection system.

#### 08 - Token Passthrough Authentication

This example demonstrates protecting endpoints using HTTP Bearer tokens passed through the MCP client.

Configuration for MCP Client:

{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    }
  }
}

Server Implementation:

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)
mcp.mount_http()

Sources: examples/08_auth_example_token_passthrough.py:1-47

#### 09 - Auth0 Integration

This example shows integration with Auth0 as an OAuth 2.0 provider, demonstrating the full OAuth flow setup.

from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="Auth0 Protected MCP",
    auth_config=AuthConfig(
        issuer="https://your-tenant.auth0.com",
        # Additional OAuth configuration
    ),
)

AuthConfig Parameters:

ParameterTypeDescription
versionLiteral["2025-03-26"]MCP spec version (currently only "2025-03-26")
dependenciesSequence[Depends]FastAPI dependencies for auth checking
issuerOptional[str]OAuth 2.0 server issuer URL
oauth_metadata_urlOptional[StrHttpUrl]Full OAuth provider metadata endpoint URL
authorize_urlOptional[StrHttpUrl]OAuth provider authorization endpoint

Sources: examples/09_auth_example_auth0.py and fastapi_mcp/types.py:95-140

Category 4: Advanced Integration Patterns

#### 04 - Separate Server Example

Demonstrates running the MCP server as a standalone process, separate from the main FastAPI application.

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()

# Create MCP server
mcp = FastApiMCP(
    app,
    name="Separate MCP Server",
    # Configuration options
)

# Run MCP as standalone server
if __name__ == "__main__":
    mcp.run(...)

Sources: examples/04_separate_server_example.py

#### 05 - Reregister Tools Example

Demonstrates dynamic tool reregistration, useful for applications where available tools may change at runtime.

from fastapi_mcp import FastApiMCP

mcp = FastApiMCP(app)

# Initial registration
mcp.mount_http()

# Later, reregister tools
mcp.reregister_tools()

Sources: examples/05_reregister_tools_example.py

Architecture Diagram

graph TD
    A[FastAPI Application] --> B[FastApiMCP Instance]
    B --> C[mount_http]
    B --> D[Separate Server]
    
    C --> E[MCP Endpoint /mcp]
    D --> F[Standalone MCP Server]
    
    E --> G[MCP Client]
    F --> G
    
    G --> H[Tool Invocations]
    H --> I[HTTP Requests to FastAPI]
    I --> A
    
    J[AuthConfig] --> B
    J --> K[OAuth 2.0 Flow]
    K --> L[Auth0 / OAuth Provider]
    
    M[Filtering Options] --> B
    M --> N[include_operations]
    M --> O[exclude_operations]
    M --> P[include_tags]
    M --> Q[exclude_tags]

Common Setup Module

All examples share a common setup module that configures logging:

from examples.shared.setup import setup_logging

setup_logging()

The shared items application provides a sample FastAPI app with CRUD operations for an Item model, used across multiple examples:

Sources: examples/shared/apps/items.py

Running Examples

# Install dependencies
uv sync

# Run an example
uv run python examples/01_basic_usage_example.py

Using pre-commit hooks

uv run pre-commit install
uv run pre-commit run

Sources: CONTRIBUTING.md:1-30

Requirements Summary

RequirementVersionNotes
Python3.10+Recommended 3.12
Package ManageruvRequired for development

Sources: README.md:45-48

Example Selection Guide

Use CaseRecommended Example
First-time integration01_basic_usage_example.py
Selective endpoint exposure03_custom_exposed_endpoints_example.py
OAuth with existing tokens08_auth_example_token_passthrough.py
Auth0 integration09_auth_example_auth0.py
Standalone MCP server04_separate_server_example.py
Dynamic tool updates05_reregister_tools_example.py

Sources: examples/README.md

Authentication Overview

Related topics: System Architecture, OAuth Authentication

Section Related Pages

Continue reading this section for the full explanation and source context.

Section AuthConfig

Continue reading this section for the full explanation and source context.

Section OAuthMetadata

Continue reading this section for the full explanation and source context.

Section Metadata Proxy

Continue reading this section for the full explanation and source context.

Related topics: System Architecture, OAuth Authentication

Authentication Overview

FastAPI-MCP provides a built-in authentication system that leverages your existing FastAPI dependencies. This approach eliminates the need to configure a separate authentication mechanism and seamlessly integrates with MCP clients that support OAuth 2.0 flows.

Architecture Overview

The authentication system in FastAPI-MCP is built around the MCP specification version 2025-03-26. It supports two primary authentication modes:

  1. Token Passthrough - Validates bearer tokens using FastAPI dependencies
  2. OAuth 2.0 Flow - Full OAuth 2.0 authorization code flow with proxy endpoints
graph TD
    A[MCP Client] -->|HTTP Request| B[FastAPI-MCP Server]
    B -->|Validate| C{FastAPI Dependencies}
    C -->|Valid| D[Tool Execution]
    C -->|Invalid| E[401 Unauthorized]
    
    F[OAuth Flow] -->|Token Request| G[OAuth Provider]
    G -->|Access Token| F
    
    B -->|Proxy| H[OAuth Metadata Endpoint]
    B -->|Proxy| I[Authorization Endpoint]

Core Data Models

AuthConfig

The AuthConfig class is the central configuration model for authentication in FastAPI-MCP.

Sources: fastapi_mcp/types.py:88-147

ParameterTypeDefaultDescription
versionLiteral["2025-03-26"]"2025-03-26"MCP spec version for authorization
dependenciesSequence[Depends]NoneFastAPI dependencies for authentication checks
custom_oauth_metadataOAuthMetadataDictNoneCustom OAuth metadata instead of proxy setup
issuerstrNoneOAuth 2.0 server issuer URL
oauth_metadata_urlStrHttpUrlNoneFull URL of OAuth provider's metadata endpoint
authorize_urlStrHttpUrlNoneOAuth provider's authorization endpoint URL
token_endpointStrHttpUrlNoneOAuth provider's token endpoint URL
metadata_pathstr"/.well-known/oauth-authorization-server"Path to serve OAuth metadata
client_idstrNoneOAuth client ID
client_secretstrNoneOAuth client secret
audiencestrNoneExpected audience claim in tokens
setup_proxiesboolFalseWhether to set up OAuth proxy endpoints
setup_fake_dynamic_registrationboolFalseSetup fake dynamic client registration endpoint
default_scopestr"openid profile email"Default OAuth scope

OAuthMetadata

Represents OAuth 2.0 Server Metadata according to RFC 8414.

Sources: fastapi_mcp/types.py:33-86

FieldTypeRequiredDescription
issuerStrHttpUrlYesAuthorization server's issuer identifier (HTTPS URL)
authorization_endpointStrHttpUrlNoAuthorization endpoint URL
token_endpointStrHttpUrlYesToken endpoint URL
scopes_supportedList[str]NoSupported OAuth 2.0 scopes
response_types_supportedList[str]NoSupported response types
grant_types_supportedList[str]NoSupported grant types

Authentication Setup Flow

The authentication system is initialized during FastApiMCP construction. The _setup_auth_2025_03_26() method handles the setup based on the configuration.

Sources: fastapi_mcp/server.py:150-190

sequenceDiagram
    participant Client as MCP Client
    participant Server as FastAPI-MCP
    participant Proxy as OAuth Proxies
    participant Provider as OAuth Provider
    
    Note over Server: AuthConfig provided
    Server->>Server: _setup_auth_2025_03_26()
    
    alt Custom OAuth Metadata
        Server->>Proxy: setup_oauth_custom_metadata()
        Note over Proxy: Serve custom metadata at metadata_path
    else Setup Proxies
        Server->>Proxy: setup_oauth_metadata_proxy()
        Server->>Proxy: setup_oauth_authorize_proxy()
        
        alt Fake Dynamic Registration
            Server->>Proxy: setup_oauth_fake_dynamic_register_endpoint()
        end
    end
    
    Client->>Server: Request with Auth Header
    Server->>Server: Run dependencies
    alt Dependencies Pass
        Server->>Server: Execute Tool
    else Dependencies Fail
        Server-->>Client: 401 Unauthorized
    end

Proxy Endpoints

FastAPI-MCP automatically sets up proxy endpoints when setup_proxies=True is configured.

Sources: fastapi_mcp/auth/proxy.py:1-50

Metadata Proxy

Serves OAuth 2.0 server metadata. When oauth_metadata_url is not provided, it constructs the URL from issuer and metadata_path.

setup_oauth_metadata_proxy(
    app=self.fastapi,
    metadata_url=f"{issuer}{metadata_path}",
    path="/.well-known/oauth-authorization-server",
    register_path="/oauth/register"  # if setup_fake_dynamic_registration is True
)

Authorization Proxy

Proxies authorization requests to the OAuth provider, with fallback handling for missing parameters.

Sources: fastapi_mcp/auth/proxy.py:80-140

ParameterPurpose
client_idDefault client ID when not provided by client
authorize_urlTarget OAuth authorization endpoint
audienceDefault audience when not specified
default_scopeDefault scope (openid profile email)

Fake Dynamic Registration

For development or testing environments, a fake dynamic client registration endpoint can be enabled.

setup_oauth_fake_dynamic_register_endpoint(
    app=self.fastapi,
    client_id="test-client-id",
    client_secret="test-client-secret"
)

Usage Examples

Token Passthrough Authentication

The simplest form of authentication uses FastAPI dependencies to validate bearer tokens.

Sources: examples/08_auth_example_token_passthrough.py:1-50

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)]
    )
)

mcp.mount_http()

Auth0 Integration

Full OAuth 2.0 flow with Auth0 as the identity provider.

Sources: examples/09_auth_example_auth0.py:1-60

from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="MCP With Auth0",
    auth_config=AuthConfig(
        issuer=f"https://{settings.auth0_domain}/",
        authorize_url=f"https://{settings.auth0_domain}/authorize",
        oauth_metadata_url=settings.auth0_oauth_metadata_url,
        audience=settings.auth0_audience,
        client_id=settings.auth0_client_id,
        client_secret=settings.auth0_client_secret,
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
    )
)

mcp.mount_http()

MCP Client Configuration

For token passthrough authentication, configure your MCP client to include the authorization header.

{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}

Key Implementation Details

Dependency Injection

Authentication is enforced through standard FastAPI dependency injection. Any Depends() callable that raises HTTPException(401) or HTTPException(403) will trigger the OAuth flow in supporting clients.

Sources: fastapi_mcp/types.py:103-130

async def authenticate_request(request: Request, token: str = Depends(oauth2_scheme)):
    payload = verify_token(request, token)
    if payload is None:
        raise HTTPException(status_code=401, detail="Unauthorized")
    return payload

Metadata Serialization

The OAuthMetadata model uses special serialization to ensure compatibility with OAuth clients:

  • exclude_unset=True - Never include unset fields
  • exclude_none=True - Never include fields with None values

Sources: fastapi_mcp/types.py:69-86

Base Type Configuration

All authentication-related models inherit from BaseType which configures:

  • extra="ignore" - Silently ignore unexpected fields
  • arbitrary_types_allowed=True - Allow complex type annotations

Workflow Summary

StepComponentAction
1FastApiMCP.__init__()Accept AuthConfig parameter
2setup_server()Call _setup_auth_2025_03_26()
3Proxy SetupRegister endpoints based on config
4Request HandlingDependencies validate tokens
5Tool ExecutionProceed if authentication succeeds

The authentication system is designed to be non-intrusive, requiring minimal configuration while providing full OAuth 2.0 compatibility for production deployments.

Sources: fastapi_mcp/types.py:88-147

OAuth Authentication

Related topics: Authentication Overview, Deployment Options

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Configuration Parameters

Continue reading this section for the full explanation and source context.

Section Example Configuration

Continue reading this section for the full explanation and source context.

Related topics: Authentication Overview, Deployment Options

OAuth Authentication

Overview

FastAPI-MCP provides built-in OAuth 2.0 authentication support that integrates seamlessly with your existing FastAPI dependencies. The authentication system follows the MCP (Model Context Protocol) specification version 2025-03-26, enabling MCP clients to authenticate requests using OAuth 2.0 flows.

The authentication layer serves three primary purposes:

  1. Metadata Discovery - Exposes OAuth server metadata at standardized endpoints
  2. Authorization Flow - Proxies authorization requests to your OAuth provider
  3. Dynamic Client Registration - Provides a fake dynamic client registration endpoint for clients that require it

Architecture

The OAuth authentication system consists of several coordinated components that work together to bridge MCP clients with your OAuth provider.

graph TD
    subgraph "MCP Client"
        A[MCP Client] -->|OAuth Request| B[MCP Server]
    end
    
    subgraph "FastAPI-MCP Server"
        B --> C{Auth Dependencies Check}
        C -->|Valid Token| D[MCP Tool Handler]
        C -->|Invalid/Missing| E[401 Unauthorized]
        C -->|Trigger OAuth| F[OAuth Proxy Endpoints]
        
        F --> G[Metadata Proxy<br/>/.well-known/oauth-authorization-server]
        F --> H[Authorize Proxy<br/>/oauth/authorize]
        F --> I[Dynamic Registration<br/>/oauth/register]
    end
    
    subgraph "External OAuth Provider"
        G -->|Fetch & Transform| J[Provider Metadata]
        H -->|Redirect| K[Provider Authorization]
        I -->|Fake Response| L[Client Credentials]
    end

Core Components

ComponentFilePurpose
AuthConfigfastapi_mcp/types.pyConfiguration container for OAuth settings
OAuthMetadatafastapi_mcp/types.pyOAuth 2.0 Server Metadata model (RFC 8414)
setup_oauth_custom_metadata()fastapi_mcp/auth/proxy.pyServes custom OAuth metadata
setup_oauth_metadata_proxy()fastapi_mcp/auth/proxy.pyProxies external OAuth metadata with modifications
setup_oauth_authorize_proxy()fastapi_mcp/auth/proxy.pyProxies authorization endpoint
setup_oauth_fake_dynamic_register_endpoint()fastapi_mcp/auth/proxy.pyProvides fake client registration

AuthConfig Specification

The AuthConfig class is the central configuration point for OAuth authentication in FastAPI-MCP.

Sources: fastapi_mcp/types.py:127-217

Configuration Parameters

ParameterTypeDefaultDescription
versionLiteral["2025-03-26"]"2025-03-26"MCP spec version for authorization
dependenciesSequence[Depends]NoneFastAPI dependencies for auth verification
issuerstrNoneOAuth provider issuer URL
oauth_metadata_urlStrHttpUrlNoneFull URL of OAuth provider's metadata endpoint
authorize_urlStrHttpUrlNoneOAuth provider's authorization endpoint
audiencestrNoneDefault audience for requests
default_scopestr"openid profile email"Default OAuth scopes
client_idstrNoneDefault client ID
client_secretstrNoneClient secret for dynamic registration
custom_oauth_metadataOAuthMetadataDictNoneCustom OAuth metadata object
setup_proxiesboolFalseEnable OAuth proxy setup
setup_fake_dynamic_registrationboolFalseEnable fake dynamic client registration
metadata_pathstr"/.well-known/oauth-authorization-server"Path for metadata endpoint

Example Configuration

from fastapi import Depends
from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        issuer="https://your-tenant.auth0.com/",
        authorize_url="https://your-tenant.auth0.com/authorize",
        oauth_metadata_url="https://your-tenant.auth0.com/.well-known/openid-configuration",
        audience="https://your-tenant.auth0.com/api/v2/",
        client_id="your-client-id",
        client_secret="your-client-secret",
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
        setup_fake_dynamic_registration=True,
    ),
)

Sources: examples/09_auth_example_auth0.py:1-50

OAuthMetadata Model

The OAuthMetadata class represents OAuth 2.0 Authorization Server Metadata as defined in RFC 8414.

Sources: fastapi_mcp/types.py:36-118

Metadata Fields

FieldTypeRequiredDescription
issuerStrHttpUrlYesAuthorization server issuer identifier (https URL)
authorization_endpointStrHttpUrlNoAuthorization endpoint URL
token_endpointStrHttpUrlYesToken endpoint URL
scopes_supportedList[str]NoSupported OAuth 2.0 scopes (default: ["openid", "profile", "email"])
response_types_supportedList[str]NoSupported response types (default: ["code"])
grant_types_supportedList[str]NoSupported grant types (default: ["authorization_code", "client_credentials"])
token_endpoint_auth_methods_supportedList[str]NoClient auth methods (default: ["none"])
code_challenge_methods_supportedList[str]NoPKCE challenge methods (default: ["S256"])
registration_endpointStrHttpUrlNoClient registration endpoint URL

Authentication Dependencies

FastAPI-MCP leverages FastAPI's dependency injection system for authentication checks. Dependencies must raise 401 or 403 errors when requests are unauthorized, which triggers the MCP client to initiate an OAuth flow.

Sources: fastapi_mcp/types.py:149-174

Dependency Implementation Pattern

from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

security = HTTPBearer()

async def verify_auth(request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)):
    """Verify the bearer token and return user information."""
    token = credentials.credentials
    
    # Validate token with your OAuth provider
    payload = verify_token(token)
    
    if payload is None:
        raise HTTPException(
            status_code=401,
            detail="Unauthorized",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    return payload

# Usage with FastAPI-MCP
mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(dependencies=[Depends(verify_auth)]),
)

Sources: fastapi_mcp/types.py:155-172

OAuth Proxy Setup Functions

setup_oauth_custom_metadata()

Serves custom OAuth metadata provided directly in the AuthConfig.

Sources: fastapi_mcp/auth/proxy.py:50-75

def setup_oauth_custom_metadata(
    app: FastAPI,
    auth_config: AuthConfig,
    metadata: OAuthMetadataDict,
    include_in_schema: bool = False,
) -> None:
    """
    Serve custom metadata at the path specified in auth_config.metadata_path.
    """
    auth_config = AuthConfig.model_validate(auth_config)
    metadata = OAuthMetadata.model_validate(metadata)

    @app.get(
        auth_config.metadata_path,
        response_model=OAuthMetadata,
        response_model_exclude_unset=True,
        response_model_exclude_none=True,
        include_in_schema=include_in_schema,
        operation_id="oauth_custom_metadata",
    )
    async def oauth_metadata_proxy():
        return metadata

setup_oauth_metadata_proxy()

Proxies an external OAuth provider's metadata endpoint while modifying specific fields.

Sources: fastapi_mcp/auth/proxy.py:78-135

def setup_oauth_metadata_proxy(
    app: FastAPI,
    metadata_url: str,
    path: str = "/.well-known/oauth-authorization-server",
    authorize_path: str = "/oauth/authorize",
    register_path: Optional[str] = None,
    include_in_schema: bool = False,
) -> None:
    """
    Fetch OAuth metadata from provider and override specific endpoints.
    """
    @app.get(
        path,
        response_model=OAuthMetadata,
        response_model_exclude_unset=True,
        response_model_exclude_none=True,
        include_in_schema=include_in_schema,
        operation_id="oauth_metadata_proxy",
    )
    async def oauth_metadata_proxy(request: Request):
        base_url = str(request.base_url).rstrip("/")

        async with httpx.AsyncClient() as client:
            response = await client.get(metadata_url)
            if response.status_code != 200:
                raise HTTPException(
                    status_code=502,
                    detail="Failed to fetch OAuth metadata",
                )
            oauth_metadata = response.json()

        # Override registration endpoint if provided
        if register_path:
            oauth_metadata["registration_endpoint"] = f"{base_url}{register_path}"

        # Replace authorization endpoint with our proxy
        oauth_metadata["authorization_endpoint"] = f"{base_url}{authorize_path}"

        return OAuthMetadata.model_validate(oauth_metadata)

setup_oauth_authorize_proxy()

Creates a proxy for the OAuth provider's authorization endpoint.

Sources: fastapi_mcp/auth/proxy.py:138-210

def setup_oauth_authorize_proxy(
    app: FastAPI,
    client_id: str,
    authorize_url: Optional[StrHttpUrl] = None,
    audience: Optional[str] = None,
    default_scope: str = "openid profile email",
    path: str = "/oauth/authorize",
) -> None:
    """
    Proxy authorization requests to the OAuth provider.
    """
    @app.get(
        path,
        response_class=RedirectResponse,
        operation_id="oauth_authorize_proxy",
    )
    async def oauth_authorize_proxy(request: Request, redirect_uri: str):
        params = {
            "client_id": client_id,
            "redirect_uri": redirect_uri,
            "response_type": "code",
            "scope": default_scope,
        }
        
        if audience:
            params["audience"] = audience
            
        # Redirect to actual OAuth provider
        query = urlencode(params)
        return f"{authorize_url}?{query}"

Authorization Flow

MCP Spec Version 2025-03-26 Setup

The auth setup is triggered in the FastApiMCP initialization flow.

Sources: fastapi_mcp/server.py:1-50

sequenceDiagram
    participant Client as MCP Client
    participant FastAPI as FastAPI App
    participant Proxy as OAuth Proxies
    participant Provider as OAuth Provider

    Client->>FastAPI: MCP Request with Bearer Token
    FastAPI->>FastAPI: Run Auth Dependencies
    alt Token Invalid or Missing
        FastAPI-->>Client: 401 Unauthorized
        Client->>Proxy: Discover OAuth Metadata
        Proxy->>Provider: Fetch Metadata
        Provider-->>Proxy: OAuth Metadata
        Proxy-->>Client: Modified Metadata
        Client->>Proxy: Authorization Request
        Proxy->>Provider: Redirect to /authorize
        Provider-->>Client: Authorization Code
        Client->>Proxy: Token Request
        Proxy->>Provider: Token Exchange
        Provider-->>Proxy: Access Token
        Proxy-->>Client: Access Token
        Client->>FastAPI: MCP Request with Token
        FastAPI->>FastAPI: Validate Token
    end

Server-Side Setup Logic

The _setup_auth_2025_03_26() method in FastApiMCP orchestrates the OAuth setup:

Sources: fastapi_mcp/server.py:50-100

def _setup_auth_2025_03_26(self):
    if self._auth_config:
        if self._auth_config.custom_oauth_metadata:
            setup_oauth_custom_metadata(
                app=self.fastapi,
                auth_config=self._auth_config,
                metadata=self._auth_config.custom_oauth_metadata,
            )
        elif self._auth_config.setup_proxies:
            metadata_url = self._auth_config.oauth_metadata_url
            if not metadata_url:
                metadata_url = f"{self._auth_config.issuer}{self._auth_config.metadata_path}"

            setup_oauth_metadata_proxy(
                app=self.fastapi,
                metadata_url=metadata_url,
                path=self._auth_config.metadata_path,
                register_path="/oauth/register" if self._auth_config.setup_fake_dynamic_registration else None,
            )
            setup_oauth_authorize_proxy(
                app=self.fastapi,
                client_id=self._auth_config.client_id,
                authorize_url=self._auth_config.authorize_url,
                audience=self._auth_config.audience,
                default_scope=self._auth_config.default_scope,
            )
            if self._auth_config.setup_fake_dynamic_registration:
                setup_oauth_fake_dynamic_register_endpoint(
                    app=self.fastapi,
                    client_id=self._auth_config.client_id,
                    client_secret=self._auth_config.client_secret,
                )

Complete Example: Auth0 Integration

This example demonstrates a full OAuth authentication setup with Auth0.

Sources: examples/09_auth_example_auth0.py:1-80

from fastapi import FastAPI, Depends, HTTPException, Request, status
from pydantic_settings import BaseSettings
import logging

from fastapi_mcp import FastApiMCP, AuthConfig
from examples.shared.auth import fetch_jwks_public_key

setup_logging()
logger = logging.getLogger(__name__)

class Settings(BaseSettings):
    auth0_domain: str
    auth0_audience: str
    auth0_client_id: str
    auth0_client_secret: str

    @property
    def auth0_oauth_metadata_url(self):
        return f"https://{self.auth0_domain}/.well-known/openid-configuration"

    class Config:
        env_file = ".env"

settings = Settings()

async def lifespan(app: FastAPI):
    app.state.jwks_public_key = await fetch_jwks_public_key(
        settings.auth0_jwks_url
    )
    logger.info(f"Auth0 client ID: {settings.auth0_client_id}")

app = FastAPI(lifespan=lifespan)

async def verify_auth(request: Request):
    """Verify JWT token from Auth0."""
    # Token verification logic
    pass

mcp = FastApiMCP(
    app,
    name="MCP With Auth0",
    description="Example of FastAPI-MCP with Auth0 authentication",
    auth_config=AuthConfig(
        issuer=f"https://{settings.auth0_domain}/",
        authorize_url=f"https://{settings.auth0_domain}/authorize",
        oauth_metadata_url=settings.auth0_oauth_metadata_url,
        audience=settings.auth0_audience,
        client_id=settings.auth0_client_id,
        client_secret=settings.auth0_client_secret,
        dependencies=[Depends(verify_auth)],
        setup_proxies=True,
    ),
)

mcp.mount_http()

Token Passthrough Example

For simpler scenarios where you just need to verify bearer tokens:

Sources: examples/08_auth_example_token_passthrough.py:1-60

from fastapi import Depends
from fastapi.security import HTTPBearer

from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()

Environment Configuration

For Auth0, create a .env file:

AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://your-tenant.auth0.com/api/v2/
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret

MCP Client Configuration

Configure your MCP client to use OAuth authentication:

{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp",
        "--header",
        "Authorization:${AUTH_HEADER}"
      ]
    },
    "env": {
      "AUTH_HEADER": "Bearer <your-token>"
    }
  }
}

Sources: examples/08_auth_example_token_passthrough.py:8-22

Troubleshooting

Common Issues

IssueCauseSolution
401 on all requestsAuth dependencies always failEnsure token verification returns user info instead of raising 401
Metadata endpoint returns 502OAuth provider unreachableVerify oauth_metadata_url is correct and accessible
Client not triggering OAuthDependencies not raising 401Dependencies must raise HTTPException with 401 for OAuth flow
Dynamic registration failsFake endpoint not enabledSet setup_fake_dynamic_registration=True in AuthConfig

Debug Logging

Enable debug logging to trace authentication issues:

import logging
logging.basicConfig(level=logging.DEBUG)

Sources: fastapi_mcp/types.py:127-217

Endpoint Filtering and Selection

Related topics: Quickstart Guide, Tool Naming and Schema

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Parameter Validation Rules

Continue reading this section for the full explanation and source context.

Section Filter Logic Flow

Continue reading this section for the full explanation and source context.

Section The filtertools Method

Continue reading this section for the full explanation and source context.

Related topics: Quickstart Guide, Tool Naming and Schema

Endpoint Filtering and Selection

The Endpoint Filtering and Selection feature in FastAPI-MCP provides granular control over which FastAPI endpoints are exposed as MCP tools. This allows developers to create specialized MCP servers that expose only a subset of their FastAPI API, enabling targeted integrations, improved security through principle of least privilege, and support for multi-tenant or use-case-specific MCP deployments.

Overview

FastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. The filtering system operates on top of this conversion, enabling selective exposure of endpoints based on operation IDs and tags defined in the OpenAPI specification.

This feature was introduced to support:

  • Multi-tenant deployments: Different MCP servers for different client types
  • Security isolation: Limiting exposed functionality to minimize attack surface
  • Use-case specificity: Creating focused MCP servers for particular workflows
  • Separate deployment: Deploying MCP servers independently from the main API service

Sources: CHANGELOG.md:5-11

Filter Parameters

The filtering is controlled through four mutually-exclusive parameters in the FastApiMCP constructor:

ParameterTypeDescription
include_operationsOptional[List[str]]List of operation IDs to include as MCP tools
exclude_operationsOptional[List[str]]List of operation IDs to exclude from MCP tools
include_tagsOptional[List[str]]List of tags to include as MCP tools
exclude_tagsOptional[List[str]]List of tags to exclude from MCP tools

Sources: fastapi_mcp/server.py:1-100

Parameter Validation Rules

The filtering system enforces several validation constraints to prevent ambiguous configurations:

  1. Operation exclusion: include_operations and exclude_operations cannot be used together
  2. Tag exclusion: include_tags and exclude_tags cannot be used together
  3. Flexible combination: Operation filtering can be combined with tag filtering using a greedy approach

When combining filters in include mode, endpoints matching either the operation criteria or the tag criteria will be included in the MCP server.

Sources: examples/03_custom_exposed_endpoints_example.py:1-30

Architecture

graph TD
    A[FastAPI Application] --> B[OpenAPI Schema Generation]
    B --> C[FastApiMCP Constructor]
    C --> D{Filtering Parameters?}
    D -->|No filters| E[All Tools Exposed]
    D -->|With filters| F[_filter_tools Method]
    
    F --> G{include_operations?}
    G -->|Yes| H[Filter by Operation IDs]
    
    F --> I{exclude_operations?}
    I -->|Yes| J[Exclude by Operation IDs]
    
    F --> K{include_tags?}
    K -->|Yes| L[Filter by Tags]
    
    F --> M{exclude_tags?}
    M -->|Yes| N[Exclude by Tags]
    
    H --> O[Build Operations Map]
    J --> O
    L --> O
    N --> O
    O --> P[Filtered Tool List]
    
    P --> Q[MCP Server]
    E --> Q

Filter Logic Flow

graph LR
    A[Tools List] --> B{_include_operations<br/>is None?}
    B -->|Yes| C{_exclude_operations<br/>is None?}
    B -->|No| D[Keep only tools with<br/>matching operationId]
    C -->|No| E[Remove tools with<br/>matching operationId]
    C -->|Yes| F{_include_tags<br/>is None?}
    D --> G[Operations By Tag Map]
    E --> G
    F -->|No| H[Keep tools with<br/>matching tags]
    F -->|Yes| I{_exclude_tags<br/>is None?}
    H --> J[Final Tool Set]
    I -->|No| K[Remove tools with<br/>matching tags]
    I -->|Yes| J
    K --> J

Implementation Details

The `_filter_tools` Method

The core filtering logic resides in the _filter_tools method within fastapi_mcp/server.py. This method:

  1. Returns the original tool list if no filters are configured
  2. Builds a mapping of tags to operation IDs from the OpenAPI schema
  3. Applies inclusion/exclusion logic based on operation IDs and tags
  4. Returns the filtered tool list
def _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:
    """
    Filter tools based on operation IDs and tags.
    """
    if (
        self._include_operations is None
        and self._exclude_operations is None
        and self._include_tags is None
        and self._exclude_tags is None
    ):
        return tools

    operations_by_tag: Dict[str, List[str]] = {}
    for path, path_item in openapi_schema.get("paths", {}).items():
        for method, operation in path_item.items():
            if method not in ["get", "post", "put", "delete", "patch"]:
                continue
            # ... filtering logic continues

Sources: fastapi_mcp/server.py:1-50

Parameter Organization in OpenAPI Conversion

When endpoints are converted to MCP tools, parameters are organized into four categories:

Parameter TypeOpenAPI LocationDescription
Path Parametersparameters[in=path]URL path variables
Query Parametersparameters[in=query]Query string parameters
Header Parametersparameters[in=header]HTTP header values
Body ParametersrequestBodyRequest body content

Sources: fastapi_mcp/openapi/convert.py:1-80

Usage Examples

Basic Operation ID Filtering

from fastapi_mcp import FastApiMCP

# Include only specific operations
include_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)

# Exclude specific operations
exclude_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)

Sources: examples/03_custom_exposed_endpoints_example.py:18-30

Tag-Based Filtering

# Include only operations with specific tags
include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)

# Exclude operations with specific tags
exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)

Combined Filtering

# Combine operation IDs and tags in include mode
combined_include_mcp = FastApiMCP(
    app,
    name="Item API MCP - Combined Include",
    include_operations=["delete_item"],
    include_tags=["search"],
)

When using combined include filters, the MCP server exposes endpoints that match either criteria—the operation ID filter or the tag filter. This greedy approach ensures comprehensive coverage of relevant endpoints.

Sources: examples/03_custom_exposed_endpoints_example.py:55-65

Available Examples

FastAPI-MCP provides a dedicated example demonstrating endpoint filtering capabilities:

ExampleFileDescription
Custom Exposed Endpoints03_custom_exposed_endpoints_example.pyComprehensive filtering examples

Sources: examples/README.md:1-15

To run the example:

cd examples
uv run python 03_custom_exposed_endpoints_example.py

Mounting Filtered Servers

After creating filtered MCP servers, mount them at different HTTP paths:

include_operations_mcp.mount_http(mount_path="/include-operations-mcp")
exclude_operations_mcp.mount_http(mount_path="/exclude-operations-mcp")
include_tags_mcp.mount_http(mount_path="/include-tags-mcp")
exclude_tags_mcp.mount_http(mount_path="/exclude-tags-mcp")
combined_include_mcp.mount_http(mount_path="/combined-include-mcp")

This allows clients to connect to specific filtered MCP servers based on their needs.

Sources: examples/03_custom_exposed_endpoints_example.py:68-74

Best Practices

  1. Use descriptive operation IDs: Ensure your FastAPI endpoints have clear, consistent operationId values for easier filtering
  2. Leverage tags for organization: Group related endpoints with consistent tags to enable effective tag-based filtering
  3. Principle of least privilege: Only expose the minimum set of endpoints required for each MCP use case
  4. Combine filters strategically: Use combined include filters to create focused MCP servers that serve specific workflows
  5. Test filtering combinations: Verify that the greedy approach of combined filters produces the expected tool set

Sources: CHANGELOG.md:5-11

Tool Naming and Schema

Related topics: Endpoint Filtering and Selection, System Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Object Schema Example

Continue reading this section for the full explanation and source context.

Section Array Schema Example

Continue reading this section for the full explanation and source context.

Related topics: Endpoint Filtering and Selection, System Architecture

Tool Naming and Schema

This page documents how FastAPI-MCP derives MCP tool names, descriptions, and input schemas from FastAPI/OpenAPI endpoint definitions.

Overview

When a FastAPI application is mounted as an MCP server, every route operation becomes an MCP tool. The conversion pipeline performs the following high-level steps:

  1. Resolve all $ref references in the OpenAPI schema
  2. Extract operation metadata (operationId, summary, description)
  3. Classify parameters by location (path, query, header)
  4. Parse request body schemas into tool input schemas
  5. Generate human-readable tool descriptions including example values
  6. Build the types.Tool objects returned to the MCP runtime

Sources: fastapi_mcp/openapi/convert.py:21-45

graph TD
    A[OpenAPI Schema] --> B[resolve_schema_references]
    B --> C[Iterate paths]
    C --> D[Extract operationId]
    D --> E[Classify Parameters]
    E --> F[Parse Request Body]
    F --> G[Build Tool Description]
    G --> H[types.Tool]

Tool Naming

Tool names are derived directly from the operationId field in the OpenAPI operation object. The function convert_openapi_to_mcp_tools skips any operation that lacks an operationId:

operation_id = operation.get("operationId")
if not operation_id:
    logger.warning(f"Skipping non-HTTP method: {method}")
    continue

Sources: fastapi_mcp/openapi/convert.py:56-62

The resulting tool names are exactly the operationId strings, without any namespace prefix. For example, given a FastAPI route:

@app.get("/items/{item_id}", response_model=Item, operation_id="get_item")
async def get_item(item_id: int):
    ...

The MCP tool will be named get_item.

Schema Resolution

Before any schema processing occurs, all JSON Pointer references ($ref) are resolved upfront by calling resolve_schema_references:

resolved_openapi_schema = resolve_schema_references(openapi_schema, openapi_schema)

This single-pass resolution replaces all $ref values with their referenced definitions, ensuring that downstream code works with concrete schemas rather than indirection.

Sources: fastapi_mcp/openapi/convert.py:50-53

Parameter Classification

Parameters are classified by their in field into four groups:

Groupin valueDescription
Path parameters"path"Required URL segment parameters
Query parameters"query"Optional query string parameters
Header parameters"header"HTTP header parameters
Body parameters"requestBody"JSON request body (handled separately)

The classification code:

for param in operation.get("parameters", []):
    param_name = param.get("name")
    param_in = param.get("in")
    required = param.get("required", False)

    if param_in == "path":
        path_params.append((param_name, param))
    elif param_in == "query":
        query_params.append((param_name, param))
    elif param_in == "header":
        header_params.append((param_name, param))

Sources: fastapi_mcp/openapi/convert.py:79-93

Example Generation

The utility generate_example_from_schema produces human-readable example values for each schema type to include in tool descriptions. The function handles the following OpenAPI types:

OpenAPI TypeGenerated Example
string (no format)"string" or the title field value
string with format: date-time"2023-01-01T00:00:00Z"
string with format: date"2023-01-01"
string with format: email"[email protected]"
string with format: uri"https://example.com"
integer1
number1.0
booleantrue
arrayA single-item array with an example of the items type
objectA dict with one example per properties entry
nullnull

Sources: fastapi_mcp/openapi/utils.py:45-70

Object Schema Example

elif schema_type == "object":
    result = {}
    if "properties" in schema:
        for prop_name, prop_schema in schema["properties"].items():
            prop_example = generate_example_from_schema(prop_schema)
            if prop_example is not None:
                result[prop_name] = prop_example
    return result

Array Schema Example

elif schema_type == "array":
    if "items" in schema:
        item_example = generate_example_from_schema(schema["items"])
        if item_example is not None:
            return [item_example]
    return []

Tool Description Building

The convert_openapi_to_mcp_tools function constructs a human-readable description field for each tool by concatenating:

  1. The operation's summary and description fields from OpenAPI
  2. Parameter documentation with names, types, required status, and descriptions
  3. Request body schema details (if present)
  4. Output schema with example values
tool_description += response_info

The response information is only included when the describe_all_responses or describe_full_response_schema flags are set. The description includes:

  • The HTTP method and path
  • Parameter documentation grouped by type
  • Request body schema examples
  • Output schema examples for both array and object responses

Output Schema Handling

Response schemas are processed to produce two display formats:

  1. Array responses: The items schema is extracted and shown as an array of items with the item structure
  2. Object responses: The full properties schema is displayed
if items_schema := schema.get("items", {}).get("properties"):
    response_info += "\n\n**Output Schema:** Array of items with the following structure:\n```json\n"
    response_info += json.dumps(items_schema, indent=2)
elif "properties" in display_schema:
    response_info += "\n\n**Output Schema:**\n```json\n"
    response_info += json.dumps(display_schema, indent=2)

Supported HTTP Methods

Only standard HTTP methods are converted to tools:

if method not in ["get", "post", "put", "delete", "patch"]:
    logger.warning(f"Skipping non-HTTP method: {method}")
    continue
MethodSupported
GETYes
POSTYes
PUTYes
DELETEYes
PATCHYes
HEAD, OPTIONS, etc.No (logged and skipped)
FunctionFilePurpose
resolve_schema_referencesopenapi/utils.pyResolves all $ref pointers in the schema
generate_example_from_schemaopenapi/utils.pyCreates example values for tool descriptions
clean_schema_for_displayopenapi/utils.pySanitizes schema for display
get_single_param_type_from_schemaopenapi/utils.pyExtracts parameter type from schema
convert_openapi_to_mcp_toolsopenapi/convert.pyMain conversion function

Sources: fastapi_mcp/openapi/convert.py:21-45

Transport Configuration

Related topics: System Architecture, Deployment Options

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Basic HTTP Mounting

Continue reading this section for the full explanation and source context.

Section HTTP Client Configuration

Continue reading this section for the full explanation and source context.

Section Default Timeout Behavior

Continue reading this section for the full explanation and source context.

Related topics: System Architecture, Deployment Options

Transport Configuration

FastAPI-MCP supports multiple transport mechanisms for exposing MCP (Model Context Protocol) servers. This document covers the available transport options, configuration parameters, and how to customize transport behavior for different deployment scenarios.

Overview

FastAPI-MCP provides two primary transport mechanisms:

Transport TypeMethodDescription
HTTPmount_http()Standard HTTP transport for MCP communication
SSEmount_sse()Server-Sent Events transport for streaming responses
Legacymount()Deprecated combined method (use mount_http() or mount_sse() instead)

Sources: fastapi_mcp/server.py:1-200

Transport Architecture

graph TD
    A[FastAPI Application] --> B[FastApiMCP Server]
    B --> C[mount_http]
    B --> D[mount_sse]
    C --> E[HTTP Transport]
    D --> F[SSE Transport]
    E --> G[httpx.AsyncClient]
    F --> H[FastApiSseTransport]
    G --> I[ASGI Transport]
    H --> I

HTTP Transport Configuration

The HTTP transport is the recommended method for MCP communication. It uses an httpx.AsyncClient internally with ASGI transport.

Basic HTTP Mounting

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI()
mcp = FastApiMCP(app)
mcp.mount_http()

Sources: examples/01_basic_usage_example.py:1-15

HTTP Client Configuration

The FastApiMCP class accepts an optional http_client parameter for custom HTTP client configuration:

import httpx
from fastapi_mcp import FastApiMCP

# Custom HTTP client with specific timeout
custom_client = httpx.AsyncClient(
    timeout=30.0
)

mcp = FastApiMCP(
    app,
    http_client=custom_client
)

Default Timeout Behavior

When no custom client is provided, FastAPI-MCP creates an internal HTTP client with a default timeout of 10.0 seconds:

self._http_client = http_client or httpx.AsyncClient(
    transport=httpx.ASGITransport(app=self.fastapi, raise_app_exceptions=False),
    base_url=self._base_url,
    timeout=10.0,
)

Sources: fastapi_mcp/server.py:1-100

Configuring Custom Timeouts

For long-running API operations, you can configure custom timeout values:

import httpx
from fastapi_mcp import FastApiMCP

# Create client with extended timeout
client = httpx.AsyncClient(timeout=httpx.Timeout(60.0))

mcp = FastApiMCP(
    app,
    name="Extended Timeout MCP",
    http_client=client,
)

Sources: examples/07_configure_http_timeout_example.py

SSE Transport Configuration

The SSE (Server-Send Events) transport provides streaming capabilities for MCP communication.

Basic SSE Mounting

from fastapi_mcp import FastApiMCP

mcp = FastApiMCP(app)
mcp.mount_sse(router, mount_path="/sse")

Sources: fastapi_mcp/server.py:1-200

SSE Endpoint Registration

The SSE transport registers two endpoints:

EndpointMethodPurpose
{mount_path}GETSSE connection establishment
{mount_path}/messages/POSTMessage handling
def _register_mcp_connection_endpoint_sse(
    self,
    router: FastAPI | APIRouter,
    transport: FastApiSseTransport,
    mount_path: str,
    dependencies: Optional[Sequence[params.Depends]],
):
    @router.get(mount_path, include_in_schema=False, operation_id="mcp_connection", dependencies=dependencies)
    async def handle_mcp_connection(request: Request):
        async with transport.connect_sse(request.scope, request.receive, request._send) as (reader, writer):
            await self.server.run(
                reader,
                writer,
                self.server.create_initialization_options(notification_options=None, experimental_capabilities={}),
                raise_exceptions=False,
            )

Sources: fastapi_mcp/server.py:100-200

Header Forwarding Configuration

FastAPI-MCP allows forwarding specific HTTP headers from incoming MCP requests to tool invocations.

Default Header Forwarding

By default, only the authorization header is forwarded:

headers: Annotated[
    List[str],
    Doc(
        """
        List of HTTP header names to forward from the incoming MCP request into each tool invocation.
        Only headers in this allowlist will be forwarded. Defaults to ['authorization'].
        """
    ),
] = ["authorization"],

Sources: fastapi_mcp/server.py:1-100

Custom Header Forwarding

from fastapi_mcp import FastApiMCP

# Forward multiple headers
mcp = FastApiMCP(
    app,
    headers=["authorization", "x-api-key", "x-request-id"],
)

Token Passthrough Example

For authenticated APIs, headers can be forwarded to maintain authentication:

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    name="Protected MCP",
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
    headers=["authorization"],  # Forward the auth header
)

Sources: examples/08_auth_example_token_passthrough.py:1-50

Authentication Configuration

The AuthConfig class provides OAuth and authentication support:

ParameterTypeDescription
versionLiteral["2025-03-26"]MCP spec version for authorization
dependenciesOptional[Sequence[params.Depends]]FastAPI dependencies for auth checks
issuerOptional[str]OAuth 2.0 issuer URL
oauth_metadata_urlOptional[StrHttpUrl]Full URL of OAuth metadata endpoint
authorize_urlOptional[StrHttpUrl]Authorization endpoint URL

Sources: fastapi_mcp/types.py:1-100

OAuth Configuration Example

from fastapi_mcp import FastApiMCP, AuthConfig

mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(
        version="2025-03-26",
        issuer="https://your-tenant.auth0.com",
        dependencies=[Depends(authenticate_request)],
    ),
)

Tool Filtering by Transport

When mounting the MCP server, you can filter which operations are exposed:

ParameterTypeDescription
include_operationsOptional[List[str]]Operation IDs to include
exclude_operationsOptional[List[str]]Operation IDs to exclude
include_tagsOptional[List[str]]Tags to include
exclude_tagsOptional[List[str]]Tags to exclude
# Include specific operations only
mcp = FastApiMCP(
    app,
    name="Filtered MCP",
    include_operations=["get_item", "list_items"],
)

# Exclude specific operations
mcp = FastApiMCP(
    app,
    name="Filtered MCP",
    exclude_operations=["delete_item", "update_item"],
)

Sources: examples/03_custom_exposed_endpoints_example.py

Deprecation Notice

The legacy mount() method is deprecated and will be removed in a future version:

# DEPRECATED - Do not use
mcp.mount(router, mount_path, transport="sse")

# RECOMMENDED - Use these instead
mcp.mount_http()
mcp.mount_sse(router, mount_path)

Sources: fastapi_mcp/server.py:1-100

Complete Configuration Example

import httpx
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

app = FastAPI()
token_auth_scheme = HTTPBearer()

# Custom authentication dependency
async def authenticate_request(request: Request, token: str = Depends(token_auth_scheme)):
    payload = verify_token(request, token)
    if payload is None:
        raise HTTPException(status_code=401, detail="Unauthorized")
    return payload

# Configure MCP with all transport options
mcp = FastApiMCP(
    app,
    name="Complete Example MCP",
    describe_all_responses=True,
    describe_full_response_schema=True,
    http_client=httpx.AsyncClient(timeout=30.0),
    include_tags=["items", "search"],
    auth_config=AuthConfig(
        dependencies=[Depends(authenticate_request)],
    ),
    headers=["authorization", "x-api-key"],
)

# Mount with HTTP transport
mcp.mount_http()

Summary

FastAPI-MCP provides flexible transport configuration options:

  • HTTP Transport: Default transport using httpx.AsyncClient with configurable timeouts
  • SSE Transport: Server-Sent Events for streaming scenarios
  • Header Forwarding: Customizable header allowlist for request passthrough
  • Authentication: OAuth and dependency-based authentication support
  • Tool Filtering: Operation ID and tag-based filtering for exposed endpoints

Choose the appropriate transport based on your deployment requirements, with HTTP being the recommended default for most use cases.

Sources: fastapi_mcp/server.py:1-200

Deployment Options

Related topics: Transport Configuration, Dynamic Tool Registration, Examples Overview

Section Related Pages

Continue reading this section for the full explanation and source context.

Section HTTP Transport

Continue reading this section for the full explanation and source context.

Section SSE Transport

Continue reading this section for the full explanation and source context.

Section Basic HTTP Mount

Continue reading this section for the full explanation and source context.

Related topics: Transport Configuration, Dynamic Tool Registration, Examples Overview

Deployment Options

FastAPI-MCP provides multiple deployment options for integrating MCP (Model Context Protocol) servers with FastAPI applications. These options allow developers to mount MCP servers using different transports (HTTP and SSE), deploy them separately from the main API service, or integrate them with custom APIRouter configurations.

Overview

FastAPI-MCP supports three primary deployment patterns:

Deployment ModeTransportDescriptionUse Case
Integrated (HTTP)HTTPMCP server mounted directly into the FastAPI appDefault option, simple deployment
Integrated (SSE)Server-Sent EventsMCP server using SSE transportLegacy support, browser compatibility
Separate ServerHTTPMCP server running as standalone serviceMicroservices architecture, independent scaling

Sources: fastapi_mcp/server.py:1-50

Transport Types

HTTP Transport

HTTP transport is the recommended deployment option for FastAPI-MCP. It provides a FastAPI-native approach that integrates seamlessly with the existing FastAPI ecosystem.

Key characteristics:

  • Uses httpx.AsyncClient for making HTTP requests
  • Supports streaming responses
  • Compatible with all major MCP clients
  • Better performance compared to SSE

Sources: fastapi_mcp/server.py:85-120

graph TD
    A[MCP Client] -->|HTTP Request| B[FastAPI App /mcp]
    B --> C[FastApiMCP Server]
    C -->|Tool Call| D[FastAPI Endpoints]
    D -->|Response| C
    C -->|MCP Response| A

SSE Transport

Server-Sent Events (SSE) transport is provided for legacy compatibility and specific use cases requiring browser-based connections.

Key characteristics:

  • Bidirectional communication via SSE streams
  • Requires specific endpoint registration
  • Uses FastApiSseTransport class

Sources: fastapi_mcp/server.py:150-200

Mounting Methods

Basic HTTP Mount

The simplest deployment option mounts the MCP server directly to the root FastAPI application using HTTP transport.

from fastapi import FastAPI
from fastapi_mcp import FastApiMCP

app = FastAPI(__name__)
mcp = FastApiMCP(app, name="My MCP Server")

# Mount with HTTP transport (default)
mcp.mount_http()

Sources: examples/08_auth_example_token_passthrough.py:40-48

Custom Router Mount

Deploy the MCP server to a specific APIRouter instead of the root application. This is useful for organizing endpoints under a specific path prefix.

from fastapi import FastAPI, APIRouter
from fastapi_mcp import FastApiMCP

app = FastAPI(__name__)

# Create a custom router with a prefix
other_router = APIRouter(prefix="/other/route")
app.include_router(other_router)

mcp = FastApiMCP(app)

# Mount to the custom router
# MCP will be available at /other/route/mcp
mcp.mount_http(other_router)

Sources: examples/06_custom_mcp_router_example.py:1-28

SSE Mount

For SSE transport, the server provides dedicated mounting methods:

mcp.mount_sse(router=app, mount_path="/mcp")

The SSE transport registers two endpoints:

  • GET /mcp - Connection endpoint
  • POST /mcp/messages/ - Message handling endpoint

Sources: fastapi_mcp/server.py:200-250

Separate Server Deployment

FastAPI-MCP supports deploying MCP servers as separate, standalone services. This is particularly useful in microservices architectures where the MCP server and API service need independent scaling and deployment.

Architecture

graph LR
    subgraph "API Service"
        A[FastAPI App] --> B[API Endpoints]
    end
    
    subgraph "MCP Server"
        C[MCP Server] --> D[Tool Definitions]
        D --> E[HTTP Client]
        E -->|Forward Requests| B
    end
    
    F[MCP Client] --> C

Configuration

When deploying separately, the MCP server configuration specifies the remote server URL:

{
  "mcpServers": {
    "remote-example": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "http://localhost:8000/mcp"
      ]
    }
  }
}

Implementation

To enable separate server deployment:

  1. Configure the API service to run normally
  2. Mount the MCP server with appropriate transport
  3. Configure the remote MCP client to connect to the API service

Sources: examples/04_separate_server_example.py

Advantages

BenefitDescription
Independent ScalingScale MCP server and API separately based on load
Independent DeploymentDeploy updates without coordinating both services
Resource IsolationDifferent resource allocation for each service
Network FlexibilityServices can run on different hosts/ports

Endpoint Filtering

When deploying MCP servers, you can control which FastAPI endpoints are exposed as MCP tools using operation IDs and tags.

Filter by Operation IDs

# Include only specific operations
mcp = FastApiMCP(
    app,
    include_operations=["get_item", "list_items"]
)

# Exclude specific operations
mcp = FastApiMCP(
    app,
    exclude_operations=["create_item", "update_item", "delete_item"]
)

Filter by Tags

# Include only operations with specific tags
mcp = FastApiMCP(
    app,
    include_tags=["items"]
)

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

Combining Filters

Operation and tag filters can be combined. When combining filters, a greedy approach is taken—endpoints matching either criteria will be included.

Sources: examples/03_custom_exposed_endpoints_example.py:1-50

Authentication Integration

FastAPI-MCP integrates with FastAPI's dependency injection system for authentication. When mounting the MCP server, you can configure authentication that will be applied to all MCP tool executions.

Token Passthrough

from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi_mcp import FastApiMCP, AuthConfig

token_auth_scheme = HTTPBearer()

@app.get("/private")
async def private(token=Depends(token_auth_scheme)):
    return token.credentials

mcp = FastApiMCP(
    app,
    auth_config=AuthConfig(
        dependencies=[Depends(token_auth_scheme)],
    ),
)

mcp.mount_http()

Sources: examples/08_auth_example_token_passthrough.py:1-55

Auth Configuration Options

ParameterTypeDescription
dependenciesList[Depends]FastAPI dependencies for authentication
issuerstrOAuth 2.0 issuer URL
oauth_metadata_urlStrHttpUrlFull OAuth metadata endpoint URL
authorize_urlStrHttpUrlOAuth authorization endpoint URL

Running the Server

Development Mode

uvicorn.run(app, host="0.0.0.0", port=8000)

With uv

# Install dependencies
uv sync

# Run the server
uv run uvicorn main:app --host 0.0.0.0 --port 8000

Sources: CONTRIBUTING.md:1-80

Migration from Deprecated `mount()`

The mount() method is deprecated. Use the specific transport methods instead:

DeprecatedReplacement
mount(transport="sse")mount_sse()
mount(transport="http")mount_http()
# Old (deprecated)
mcp.mount(app, "/mcp", transport="sse")

# New (recommended)
mcp.mount_sse(app, "/mcp")

Sources: CHANGELOG.md:1-50

Summary

FastAPI-MCP provides flexible deployment options to accommodate various architectural requirements:

  • HTTP Transport: Recommended for most use cases, provides best performance
  • SSE Transport: Legacy support for browser-compatible deployments
  • Separate Server: Ideal for microservices architectures
  • Custom Router: Organize MCP endpoints under specific paths
  • Endpoint Filtering: Control which tools are exposed to MCP clients
  • Auth Integration: Leverage existing FastAPI authentication

Sources: fastapi_mcp/server.py:1-50

Dynamic Tool Registration

Related topics: Deployment Options, Endpoint Filtering and Selection

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Mutual Exclusivity Rules

Continue reading this section for the full explanation and source context.

Section Operation ID Mapping

Continue reading this section for the full explanation and source context.

Section Include Specific Operations

Continue reading this section for the full explanation and source context.

Related topics: Deployment Options, Endpoint Filtering and Selection

Dynamic Tool Registration

Dynamic Tool Registration is a core feature of FastAPI-MCP that enables runtime filtering, registration, and management of MCP tools derived from FastAPI endpoints. This capability allows developers to create multiple MCP server instances with different tool subsets from a single FastAPI application, providing fine-grained control over which tools are exposed to MCP clients.

Overview

FastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. Dynamic Tool Registration extends this capability by allowing selective exposure of tools based on operation IDs and tags, enabling scenarios such as:

  • Creating multiple specialized MCP servers from one FastAPI app
  • Protecting sensitive endpoints by excluding them from MCP exposure
  • Creating tenant-specific or role-based tool visibility
  • Supporting incremental updates to tool availability

The feature is implemented through the FastApiMCP class constructor parameters that control which operations are registered as MCP tools.

Architecture

graph TD
    A[FastAPI Application] --> B[OpenAPI Schema Analysis]
    B --> C[All Discovered Endpoints]
    C --> D{Filter Criteria}
    D -->|include_operations| E[Whitelist Mode]
    D -->|exclude_operations| F[Blacklist Mode]
    D -->|include_tags| G[Tag Filter - Include]
    D -->|exclude_tags| H[Tag Filter - Exclude]
    E --> I[Filtered Tool Set]
    F --> I
    G --> I
    H --> I
    I --> J[MCP Server Instance]

Core Filter Parameters

The FastApiMCP class accepts four mutually-exclusive filter parameters:

ParameterTypeDescription
include_operationsOptional[List[str]]List of operation IDs to include as MCP tools
exclude_operationsOptional[List[str]]List of operation IDs to exclude from MCP tools
include_tagsOptional[List[str]]List of tags to include as MCP tools
exclude_tagsOptional[List[str]]List of tags to exclude from MCP tools

Sources: fastapi_mcp/server.py:1-100

Mutual Exclusivity Rules

The filtering parameters follow strict mutual exclusivity rules:

  1. Operation filters: Cannot use include_operations and exclude_operations together
  2. Tag filters: Cannot use include_tags and exclude_tags together
  3. Cross-type combination: Can combine operation filters with tag filters (greedy approach)

When combining filters, a greedy union strategy is applied: endpoints matching either the operation criteria or the tag criteria will be included.

Sources: examples/03_custom_exposed_endpoints_example.py:1-30

Filter Implementation

The filtering logic is implemented in the _filter_tools method of the FastApiMCP class:

def _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:
    """
    Filter tools based on operation IDs and tags.

    Args:
        tools: List of tools to filter
        openapi_schema: The OpenAPI schema

    Returns:
        Filtered list of tools
    """
    if (
        self._include_operations is None
        and self._exclude_operations is None
        and self._include_tags is None
        and self._exclude_tags is None
    ):
        return tools

Sources: fastapi_mcp/server.py:85-105

Operation ID Mapping

The filtering mechanism builds an operations map indexed by both operation ID and tags:

operations_by_tag: Dict[str, List[str]] = {}
for path, path_item in openapi_schema.get("paths", {}).items():
    for method, operation in path_item.items():
        if method not in ["get", "post", "put", "delete", "patch"]:
            continue

        operation_id = operation.get("operationId")
        if not operation_id:
            continue

        tags = operation.get("tags", [])
        for tag in tags:
            if tag not in operations_by_tag:
                operations_by_tag[tag] = []
            operations_by_tag[tag].append(operation_id)

Sources: fastapi_mcp/server.py:107-125

Usage Patterns

Include Specific Operations

Create an MCP server exposing only specified operation IDs:

include_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Operations",
    include_operations=["get_item", "list_items"],
)
include_operations_mcp.mount_http(mount_path="/include-operations-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py:20-26

Exclude Specific Operations

Create an MCP server with all operations except specified ones:

exclude_operations_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Operations",
    exclude_operations=["create_item", "update_item", "delete_item"],
)
exclude_operations_mcp.mount_http(mount_path="/exclude-operations-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py:28-34

Tag-Based Inclusion

Filter tools by including endpoints with specific OpenAPI tags:

include_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Included Tags",
    include_tags=["items"],
)
include_tags_mcp.mount_http(mount_path="/include-tags-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py:36-41

Tag-Based Exclusion

Exclude all endpoints with specific tags:

exclude_tags_mcp = FastApiMCP(
    app,
    name="Item API MCP - Excluded Tags",
    exclude_tags=["search"],
)
exclude_tags_mcp.mount_http(mount_path="/exclude-tags-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py:43-48

Combined Filtering

Combine operation ID and tag filters for complex scenarios:

combined_include_mcp = FastApiMCP(
    app,
    name="Item API MCP - Combined Include",
    include_operations=["delete_item"],
    include_tags=["search"],
)
combined_include_mcp.mount_http(mount_path="/combined-include-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py:50-57

Re-registering Tools

The library supports re-registering tools at runtime through multiple FastApiMCP instances mounted on different paths:

# Mount all MCP servers with different paths
include_operations_mcp.mount_http(mount_path="/include-operations-mcp")
exclude_operations_mcp.mount_http(mount_path="/exclude-operations-mcp")
include_tags_mcp.mount_http(mount_path="/include-tags-mcp")
exclude_tags_mcp.mount_http(mount_path="/exclude-tags-mcp")
combined_include_mcp.mount_http(mount_path="/combined-include-mcp")

Sources: examples/03_custom_exposed_endpoints_example.py:62-68

Each mounted instance operates independently, allowing different clients to access different tool sets from the same underlying FastAPI application.

Custom Tools Integration

Beyond API-derived tools, FastAPI-MCP supports adding custom MCP tools alongside auto-generated ones:

Added

  • Main add_mcp_server function for simple MCP server integration
  • Support for adding custom MCP tools alongside API-derived tools

Sources: CHANGELOG.md:1-20

This enables scenarios where developers need to add supplementary tools that don't correspond to FastAPI endpoints, such as helper utilities or integration points with external services.

HTTP Client Configuration

The tool registration system includes support for custom HTTP client configuration:

http_client: Annotated[
    Optional[httpx.AsyncClient],
    Doc(
        """
        Optional custom HTTP client to use for API calls to the FastAPI app.
        Has to be an instance of `httpx.AsyncClient`.
        """
    ),
] = None,

Sources: fastapi_mcp/server.py:50-58

This allows fine-grained control over the HTTP client used to invoke tools, enabling custom timeouts, authentication, or proxy configuration.

Header Passthrough

The system supports forwarding specific HTTP headers from MCP requests to tool invocations:

headers: Annotated[
    List[str],
    Doc(
        """
        List of HTTP header names to forward from the incoming MCP request 
        into each tool invocation. Only headers in this allowlist will be 
        forwarded. Defaults to ['authorization'].
        """
    ),
] = ["authorization"],

Sources: fastapi_mcp/server.py:85-93

This is particularly important for maintaining authentication context when tools are invoked through the MCP protocol.

Summary

Dynamic Tool Registration in FastAPI-MCP provides a flexible mechanism for controlling which FastAPI endpoints become MCP tools. By supporting operation ID filtering, tag-based filtering, and their combinations, developers can:

  • Create specialized MCP servers for different use cases
  • Implement fine-grained access control
  • Support multi-tenant or role-based tool visibility
  • Combine auto-generated and custom tools in a single MCP server

The implementation uses a greedy union strategy when combining filters, ensuring maximum flexibility while maintaining predictable behavior. All filtering occurs at registration time, ensuring optimal runtime performance for tool invocation.

Sources: fastapi_mcp/server.py:1-100

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high [BUG] MCP session 404 in multi worker production environment

Users may get misleading failures or incomplete behavior unless configuration is checked carefully.

medium v0.1.8

First-time setup may fail or require extra isolation and rollback planning.

medium v0.2.0

First-time setup may fail or require extra isolation and rollback planning.

medium v0.3.4

First-time setup may fail or require extra isolation and rollback planning.

Doramagic Pitfall Log

Doramagic extracted 16 source-linked risk signals. Review them before installing or handing real data to the project.

1. Configuration risk: [BUG] MCP session 404 in multi worker production environment

  • Severity: high
  • Finding: Configuration risk is backed by a source signal: [BUG] MCP session 404 in multi worker production environment. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/issues/189

2. Installation risk: v0.1.8

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: v0.1.8. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8

3. Installation risk: v0.2.0

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: v0.2.0. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0

4. Installation risk: v0.3.4

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: v0.3.4. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4

5. Configuration risk: Configuration risk needs validation

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: Configuration risk needs validation. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor

6. Configuration risk: Suggestion: MCPWatch observability example for fastapi_mcp users

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: Suggestion: MCPWatch observability example for fastapi_mcp users. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/issues/303

7. Configuration risk: clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/issues/304

8. Configuration risk: v0.3.6

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: v0.3.6. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6

9. Capability assumption: README/documentation is current enough for a first validation pass.

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass.

10. Maintenance risk: [BUG] Description incorrectly passed as version to MCP Server

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: [BUG] Description incorrectly passed as version to MCP Server. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/issues/293

11. Maintenance risk: v0.3.0

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: v0.3.0. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0

12. Maintenance risk: v0.3.3 - Fix OpenAPI Conversion Regression

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: v0.3.3 - Fix OpenAPI Conversion Regression. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using fastapi_mcp with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence