FastAPI-MCP

MIT License
3,209
  • Linux
  • Apple

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

Integrations

  • Automatically exposes FastAPI endpoints as Model Context Protocol (MCP) tools, preserving schemas and documentation

  • Preserves documentation of all endpoints just as it is in Swagger

特徴

  • 直接統合- MCP サーバーを FastAPI アプリに直接マウントします
  • 設定は一切不要 - FastAPI アプリを指定するだけで動作します
  • すべてのFastAPIエンドポイントの自動検出とMCPツールへの変換
  • リクエストモデルとレスポンスモデルのスキーマの保持
  • Swaggerと同じように、すべてのエンドポイントのドキュメントを保存します
  • 柔軟な展開- MCP サーバーを同じアプリにマウントするか、個別に展開します

インストール

高速な Python パッケージ インストーラーであるuv の使用をお勧めします。

uv add fastapi-mcp

あるいは、pip を使用してインストールすることもできます。

pip install fastapi-mcp

基本的な使い方

FastAPI-MCP を使用する最も簡単な方法は、MCP サーバーを FastAPI アプリケーションに直接追加することです。

from fastapi import FastAPI from fastapi_mcp import FastApiMCP app = FastAPI() mcp = FastApiMCP( app, # Optional parameters name="My API MCP", description="My API description", base_url="http://localhost:8000", ) # Mount the MCP server directly to your FastAPI app mcp.mount()

これで完了です。自動生成された MCP サーバーがhttps://app.base.url/mcpで利用できるようになります。

base_urlに関する注意base_urlオプションですが、明示的に指定することを強くお勧めします。base_url base_url 、ツールが呼び出された際に MCP サーバーに API リクエストの送信先を指示します。base_url を指定しないと、ライブラリは URL を自動的に決定しようとしますが、内部 URL と外部 URL が異なる環境では正しく動作しない可能性があります。

ツールの命名

FastAPI-MCPは、FastAPIルートのoperation_id MCPツール名として使用します。operation_id operation_id指定しない場合はFastAPIが自動生成しますが、分かりにくい場合があります。

次の 2 つのエンドポイント定義を比較します。

# Auto-generated operation_id (something like "read_user_users__user_id__get") @app.get("/users/{user_id}") async def read_user(user_id: int): return {"user_id": user_id} # Explicit operation_id (tool will be named "get_user_info") @app.get("/users/{user_id}", operation_id="get_user_info") async def read_user(user_id: int): return {"user_id": user_id}

より明確で直感的なツール名にするには、FastAPI ルート定義に明示的なoperation_idパラメータを追加することをお勧めします。

詳細については、パス操作の高度な構成に関する FastAPI の公式ドキュメントをお読みください。

高度な使用法

FastAPI-MCPは、MCPサーバーの作成と構成をカスタマイズおよび制御するための複数の方法を提供します。以下に、高度な使用パターンをいくつか示します。

スキーマ記述のカスタマイズ

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

公開エンドポイントのカスタマイズ

Open API 操作 ID またはタグを使用して、どの FastAPI エンドポイントを MCP ツールとして公開するかを制御できます。

from fastapi import FastAPI from fastapi_mcp import FastApiMCP app = FastAPI() # Only include specific operations mcp = FastApiMCP( app, include_operations=["get_user", "create_user"] ) # Exclude specific operations mcp = FastApiMCP( app, exclude_operations=["delete_user"] ) # Only include operations with specific tags mcp = FastApiMCP( app, include_tags=["users", "public"] ) # Exclude operations with specific tags mcp = FastApiMCP( app, exclude_tags=["admin", "internal"] ) # Combine operation IDs and tags (include mode) mcp = FastApiMCP( app, include_operations=["user_login"], include_tags=["public"] ) mcp.mount()

フィルタリングに関する注意事項:

  • include_operationsexclude_operationsを同時に使用することはできません
  • include_tagsexclude_tags同時に使用することはできません
  • 操作フィルタリングとタグフィルタリングを組み合わせることができます(例: include_operationsinclude_tagsを使用する)
  • フィルターを組み合わせる場合は貪欲なアプローチが取られます。どちらかの条件に一致するエンドポイントが含まれます。

オリジナルのFastAPIアプリとは別にデプロイする

MCP は、それが作成されたのと同じ FastAPI アプリで提供することに限定されません。

1 つの FastAPI アプリから MCP サーバーを作成し、それを別のアプリにマウントすることができます。

from fastapi import FastAPI from fastapi_mcp import FastApiMCP # Your API app api_app = FastAPI() # ... define your API endpoints on api_app ... # A separate app for the MCP server mcp_app = FastAPI() # Create MCP server from the API app mcp = FastApiMCP( api_app, base_url="http://api-host:8001", # The URL where the API app will be running ) # Mount the MCP server to the separate app mcp.mount(mcp_app) # Now you can run both apps separately: # uvicorn main:api_app --host api-host --port 8001 # uvicorn main:mcp_app --host mcp-host --port 8000

MCP サーバー作成後のエンドポイントの追加

MCP サーバーを作成した後、FastAPI アプリにエンドポイントを追加する場合は、それらを含めるためにサーバーを更新する必要があります。

from fastapi import FastAPI from fastapi_mcp import FastApiMCP app = FastAPI() # ... define initial endpoints ... # Create MCP server mcp = FastApiMCP(app) mcp.mount() # Add new endpoints after MCP server creation @app.get("/new/endpoint/", operation_id="new_endpoint") async def new_endpoint(): return {"message": "Hello, world!"} # Refresh the MCP server to include the new endpoint mcp.setup_server()

完全な例については、のディレクトリを参照してください。

SSEを使用してMCPサーバーに接続する

MCP 統合された FastAPI アプリが実行されると、Cursor などの SSE をサポートする任意の MCP クライアントを使用してアプリに接続できます。

  1. アプリケーションを実行します。
  2. カーソル -> 設定 -> MCP で、MCP サーバー エンドポイントの URL (例: http://localhost:8000/mcp ) を sse として使用します。
  3. カーソルは利用可能なすべてのツールとリソースを自動的に検出します。

mcp-proxy stdioを使用して MCP サーバーに接続する

MCP クライアントが SSE をサポートしていない場合 (例: Claude Desktop)

  1. アプリケーションを実行します。
  2. mcp-proxyをインストールします。例: uv tool install mcp-proxy
  3. Claude Desktop MCP 構成ファイル ( claude_desktop_config.json ) に追加します。

Windowsの場合:

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

MacOSの場合:

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

ターミナルでwhich mcp-proxy proxy へのパスを見つけます。

  1. Claude Desktopは利用可能なすべてのツールとリソースを自動的に検出します

開発と貢献

FastAPI-MCP への貢献をご検討いただきありがとうございます。コミュニティの皆様には、問題やプルリクエストを投稿していただくようお願いいたします。

始める前に、貢献ガイドをご覧ください。

コミュニティ

MCParty Slack コミュニティに参加して、他の MCP 愛好家と交流したり、質問したり、FastAPI-MCP の経験を共有したりしましょう。

要件

  • Python 3.10+ (推奨 3.12)
  • 紫外線

ライセンス

MITライセンス。Copyright (c) 2024 Tadata Inc.

-
security - not tested
A
license - permissive license
-
quality - not tested

FastAPI エンドポイントをモデル コンテキスト プロトコル (MCP) ツールとして自動的に公開するゼロ構成ツール。これにより、Claude などの LLM システムが追加のコーディングなしで API と対話できるようになります。

  1. Installation
    1. Basic Usage
      1. Tool Naming
        1. Advanced Usage
          1. Customizing Schema Description
          2. Customizing Exposed Endpoints
          3. Deploying Separately from Original FastAPI App
          4. Adding Endpoints After MCP Server Creation
        2. Examples
          1. Connecting to the MCP Server using SSE
            1. Connecting to the MCP Server using mcp-proxy stdio
              1. Development and Contributing
                1. Community
                  1. Requirements
                    1. License
                      ID: otm6rcvu3e