/ Каталог / Песочница / FastAPI MCP
● Сообщество tadata-org ⚡ Сразу

FastAPI MCP

автор tadata-org · tadata-org/fastapi_mcp

Mount one line, turn every FastAPI route into an MCP tool — schemas from your Pydantic models, auth from your middleware.

fastapi-mcp wraps an existing FastAPI app and exposes its routes as MCP tools. Tool schemas are generated from your Pydantic request/response models. Your existing auth middleware runs unchanged. The fastest path from 'I have a Python API' to 'agents can call it'.

Зачем использовать

Ключевые функции

Живое демо

Как выглядит на практике

fastapi-mcp.replay ▶ готово
0/0

Установка

Выберите клиент

~/Library/Application Support/Claude/claude_desktop_config.json  · Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "fastapi-mcp": {
      "command": "uvx",
      "args": [
        "fastapi-mcp"
      ]
    }
  }
}

Откройте Claude Desktop → Settings → Developer → Edit Config. Перезапустите после сохранения.

~/.cursor/mcp.json · .cursor/mcp.json
{
  "mcpServers": {
    "fastapi-mcp": {
      "command": "uvx",
      "args": [
        "fastapi-mcp"
      ]
    }
  }
}

Cursor использует ту же схему mcpServers, что и Claude Desktop. Конфиг проекта приоритетнее глобального.

VS Code → Cline → MCP Servers → Edit
{
  "mcpServers": {
    "fastapi-mcp": {
      "command": "uvx",
      "args": [
        "fastapi-mcp"
      ]
    }
  }
}

Щёлкните значок MCP Servers на боковой панели Cline, затем "Edit Configuration".

~/.codeium/windsurf/mcp_config.json
{
  "mcpServers": {
    "fastapi-mcp": {
      "command": "uvx",
      "args": [
        "fastapi-mcp"
      ]
    }
  }
}

Тот же формат, что и Claude Desktop. Перезапустите Windsurf для применения.

~/.continue/config.json
{
  "mcpServers": [
    {
      "name": "fastapi-mcp",
      "command": "uvx",
      "args": [
        "fastapi-mcp"
      ]
    }
  ]
}

Continue использует массив объектов серверов, а не map.

~/.config/zed/settings.json
{
  "context_servers": {
    "fastapi-mcp": {
      "command": {
        "path": "uvx",
        "args": [
          "fastapi-mcp"
        ]
      }
    }
  }
}

Добавьте в context_servers. Zed перезагружается автоматически.

claude mcp add fastapi-mcp -- uvx fastapi-mcp

Однострочная команда. Проверить: claude mcp list. Удалить: claude mcp remove.

Сценарии использования

Реальные сценарии: FastAPI MCP

Expose an existing FastAPI app as MCP without refactoring

👤 Backend devs with a running FastAPI service ⏱ ~30 min intermediate

Когда использовать: You already ship a FastAPI API. You want agents to use it. You don't want a parallel codebase.

Предварительные требования
  • Working FastAPI app with Pydantic models on requests/responses — If your routes return dict, refactor to Pydantic BaseModel first — otherwise tool schemas will be object
Поток
  1. Install and mount
    Add fastapi-mcp to my project. In my main.py, after app = FastAPI(), add FastApiMCP(app).mount(). Show the diff.✓ Скопировано
    → Minimal diff; server still runs
  2. Verify tools appear
    Run the server. Connect with npx -y mcp-remote http://localhost:8000/mcp. List tools — do all my GET/POST routes show up?✓ Скопировано
    → Tools listed, names match route operation_ids
  3. Filter what's exposed
    I don't want /admin/* routes exposed. Reconfigure with include_operations or exclude by tag.✓ Скопировано
    → Admin routes no longer in tool list

Итог: Your existing API is now MCP-addressable with zero duplication of schemas or logic.

Подводные камни
  • Every route becomes a tool — including internal ones you didn't mean to expose — Explicitly set include_tags=['public'] or exclude_operations=[...] before going live
  • Routes without operation_id get generated names like read_item_items__item_id__get — ugly — Always set explicit operation_id on routes: @app.get('/items/{id}', operation_id='get_item')
Сочетать с: fastmcp

Expose an authenticated FastAPI app as MCP without breaking auth

👤 Backend devs with bearer/OAuth2 on FastAPI ⏱ ~30 min intermediate

Когда использовать: Your FastAPI routes use Depends(get_current_user) — you need that to still fire when called via MCP.

Предварительные требования
  • Existing auth dependencyDepends(oauth2_scheme) or equivalent
Поток
  1. Pass through the Authorization header
    Configure fastapi-mcp to forward the Authorization header from MCP context to the underlying route. Point me at the settings.✓ Скопировано
    → Config change; routes now receive the header
  2. Test an authed call
    Call the protected endpoint via MCP. First with no token (expect 401), then with a valid one (expect 200).✓ Скопировано
    → 401 unauth, 200 auth — same as direct HTTP
  3. Document the client-side setup
    Write the mcp-remote config users need so their Claude Desktop passes an Authorization header.✓ Скопировано
    → Copy-pasteable client config snippet

Итог: Auth enforced identically whether called from curl or from an agent.

Подводные камни
  • Agent accidentally uses a long-lived root token — Mint short-lived scoped tokens per user; rotate aggressively — treat MCP like any other API client

Deploy the MCP endpoint alongside your existing API

👤 Platform engineers ⏱ ~45 min advanced

Когда использовать: You run FastAPI on Cloud Run / Fly / Render. You want MCP to share that deploy.

Поток
  1. Mount at a stable path
    Mount fastapi-mcp at /mcp. Confirm /docs (Swagger) and /mcp both work from the same process.✓ Скопировано
    → Both paths respond
  2. Expose via your existing ingress
    Update my Cloud Run / nginx / API gateway config to route /mcp to this service with SSE-compatible timeouts (no buffering, long idle).✓ Скопировано
    → Remote mcp-remote connects cleanly
  3. Document the client setup
    Write the team-facing README: how to add this MCP to Claude Desktop + Cursor.✓ Скопировано
    → Copy-paste config per client

Итог: One deploy, two protocols (REST + MCP), zero extra infra.

Подводные камни
  • Proxy buffers SSE responses, connection appears hung — Disable proxy buffering — nginx: proxy_buffering off; Cloud Run: already fine; Cloudflare: enable streaming
Сочетать с: cloud-run · vercel

Комбинации

Сочетайте с другими MCP — эффект x10

fastapi-mcp + fastmcp

Use fastapi-mcp for legacy routes, FastMCP for greenfield agent-specific tools in the same process

Mount fastapi-mcp for my existing /api/* routes and register 3 new FastMCP tools for agent-only operations like bulk_sync.✓ Скопировано
fastapi-mcp + cloud-run

Deploy REST + MCP together on Cloud Run

Take my FastAPI service, add fastapi-mcp, containerize, and deploy to Cloud Run with IAM auth on /mcp.✓ Скопировано

Инструменты

Что предоставляет этот MCP

ИнструментВходные данныеКогда вызыватьСтоимость
FastApiMCP(app, **options) app: FastAPI, include_operations?, exclude_operations?, include_tags?, exclude_tags?, name?, description? Build-time wiring — create once at startup free
.mount(path='/mcp') path? Right after instantiation free
Auto-generated tools derived from each FastAPI route's request/response models No action — they appear once you mount same as your route

Стоимость и лимиты

Во что обходится

Квота API
Inherits from your API
Токенов на вызов
Same as direct HTTP calls — no overhead
Деньги
Free, open source
Совет
Exclude verbose admin/debug routes from MCP — they pollute the agent's tool list and cost tokens on every list_tools

Безопасность

Права, секреты, радиус поражения

Хранение учётных данных: Whatever your FastAPI uses — fastapi-mcp doesn't add a new auth layer
Исходящий трафик: Wherever your routes already go

Устранение неполадок

Частые ошибки и исправления

Tools appear but calls return 422 validation errors

Your route uses dict instead of Pydantic BaseModel — MCP passes typed JSON and your route can't parse it. Refactor to BaseModel.

Route exists at /items but no matching tool

fastapi-mcp skips routes without a response_model or operation_id in some cases. Add response_model=ItemOut and operation_id='get_item'.

Проверить: curl http://localhost:8000/openapi.json | jq '.paths'
Auth dependency doesn't fire when called via MCP

Configure header forwarding in FastApiMCP options. If your dependency reads cookies instead of headers, switch to header-based auth — MCP has no cookie jar.

SSE hangs behind nginx

Add proxy_buffering off; proxy_cache off; proxy_read_timeout 3600s; to the /mcp location block.

Альтернативы

FastAPI MCP в сравнении

АльтернативаКогда использоватьКомпромисс
FastMCPGreenfield — no existing FastAPI app, just writing an MCP serverCleaner DX for new projects; fastapi-mcp wins for retrofitting
Hand-written SDK serverYou need fine-grained control over tool names, descriptions, and schemasMore code, more maintenance — usually not worth it

Ещё

Ресурсы

📖 Читать официальный README на GitHub

🐙 Открытые задачи

🔍 Все 400+ MCP-серверов и Skills