/ Каталог / Песочница / FastMCP
● Официальный PrefectHQ ⚡ Сразу

FastMCP

автор PrefectHQ · PrefectHQ/fastmcp

The Pythonic way to build MCP servers — decorate a function, get a tool. Ship an MCP in 20 lines.

FastMCP is a Python framework for building MCP servers (not a server to install). One @mcp.tool decorator turns a typed function into an MCP tool, with schemas auto-derived from your annotations. Handles stdio/SSE transports, lifecycle, and the protocol details so you write business logic only.

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

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

Живое демо

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

fastmcp.replay ▶ готово
0/0

Установка

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

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

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

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

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

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

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

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

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

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

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

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

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

claude mcp add fastmcp -- uvx fastmcp

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

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

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

Expose an internal REST API as an MCP in under an hour

👤 Backend engineers with an existing Python service ⏱ ~45 min intermediate

Когда использовать: You have a company API that agents should be able to call, and you don't want to write a client spec from scratch.

Предварительные требования
  • Python 3.10+python --version
  • uv installedcurl -LsSf https://astral.sh/uv/install.sh | sh
Поток
  1. Bootstrap the project
    Scaffold a FastMCP server project called 'acme-api-mcp' with one starter tool. Use uv for dependency management.✓ Скопировано
    → pyproject.toml + server.py with a working @mcp.tool example
  2. Wrap the 3 highest-value endpoints
    My internal API has endpoints /orders/{id}, /customers/search, /invoices/{id}/pdf. Write a FastMCP tool for each, using httpx.AsyncClient and reading AUTH_TOKEN from env.✓ Скопировано
    → 3 decorated functions with type hints + docstrings that become tool descriptions
  3. Test locally with the MCP Inspector
    Run the server with uv run mcp dev server.py. Open the inspector and call each tool with a realistic input.✓ Скопировано
    → Tools return expected JSON, no stack traces

Итог: A working MCP server you can point Claude Desktop or any MCP client at.

Подводные камни
  • Secrets leak into tool descriptions because you printed them in docstrings — Use docstrings to describe behavior, not examples with real tokens. Load secrets via os.environ and never echo them in errors
  • Async + sync mixed, causes event loop errors — Pick one — if your HTTP client is async, make the whole tool async; don't call asyncio.run inside a tool

Expose company docs as MCP resources for RAG

👤 Platform engineers building agent infra ⏱ ~30 min intermediate

Когда использовать: You want the agent to auto-discover and pull company knowledge without tool calls for every file.

Поток
  1. Define a resource listing
    Define a FastMCP resource at URI docs://{path} that lists all markdown files under ./docs/ and returns their content on read.✓ Скопировано
    → Resource registered, inspector shows list
  2. Add a template resource
    Add a resource template docs://{category}/{slug} that returns the matching file. Document valid {category} values.✓ Скопировано
    → Template registered, parameterized fetches work
  3. Test in a real client
    Connect Claude Desktop to the server. Verify the Resources menu lists all docs and content loads.✓ Скопировано
    → Resources appear as attachable context

Итог: A resource-backed knowledge surface the agent can pull from natively — cleaner than tool calls for static content.

Подводные камни
  • Large resource lists overwhelm the client's UI — Paginate or filter in your list endpoint; not every file needs to be surfaced

Deploy a FastMCP server as a remote SSE endpoint

👤 Platform engineers serving multiple teams ⏱ ~60 min advanced

Когда использовать: Multiple devs need the same MCP — host it once, don't make everyone run stdio locally.

Предварительные требования
  • A container host (Cloud Run, Fly, Railway) — Any Docker-capable runtime works
Поток
  1. Switch transport to SSE
    Modify server.py to run mcp.run(transport='sse', host='0.0.0.0', port=8080). Add a minimal Dockerfile.✓ Скопировано
    → Local curl localhost:8080/sse shows SSE handshake
  2. Deploy behind auth
    Deploy to Cloud Run with IAM auth. Front the /sse endpoint with a header-based auth check in a FastAPI middleware.✓ Скопировано
    → Public URL with 401 on unauth'd requests
  3. Wire clients
    Share the connection command with teammates: npx -y mcp-remote https://mcp.acme.com/sse. Verify their Claude Desktop picks up the tools.✓ Скопировано
    → Team members' clients see the same tools

Итог: A shared remote MCP — one codebase, many users, easy to update.

Подводные камни
  • SSE connections drop behind some corporate proxies — Use streamable HTTP transport instead (newer spec) or document a VPN/direct-path requirement
Сочетать с: cloud-run

Комбинации

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

fastmcp + cloud-run

Build once, deploy to Cloud Run, share with the team

Wrap my internal pricing API as a FastMCP server, containerize it, and deploy to Cloud Run with IAM auth.✓ Скопировано
fastmcp + fastapi-mcp

Compare approaches — FastMCP for greenfield, fastapi-mcp for existing FastAPI apps

I have an existing FastAPI service. Should I add fastapi-mcp to expose it or rewrite in FastMCP? Compare based on my routes.✓ Скопировано

Инструменты

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

ИнструментВходные данныеКогда вызыватьСтоимость
@mcp.tool decorated function with typed signature Wrap any function you want agents to call free
@mcp.resource URI template + function Expose readable content (docs, config, data snapshots) free
@mcp.prompt decorated function returning Message[] Provide reusable multi-turn prompt scaffolds to clients free
mcp.run transport: 'stdio'|'sse'|'streamable-http', host?, port? Entry point — call at end of your main script free
Context (ctx) parameter inject ctx: Context into any tool Long-running tools that need to stream progress or log free

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

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

Квота API
None — this is a framework, not a service
Токенов на вызов
Your server runs any LLM calls; framework overhead is negligible
Деньги
Free, open source
Совет
Use resources instead of tools for static content — resources are cheaper in tokens because they're pre-declared

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

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

Хранение учётных данных: Your choice — env vars are idiomatic; load secrets at process start, not per call
Исходящий трафик: Wherever your tool functions reach out to

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

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

Tool schema missing required fields in the client

Your function params need type hints. Plain def foo(x) generates a useless schema — use def foo(x: str) with a docstring.

Проверить: Run `uv run mcp dev server.py` and check the Inspector's tool schema
Server starts but client sees 0 tools

You're mixing stdio with SSE misconfiguration. For Claude Desktop use transport='stdio'; for mcp-remote use 'sse'.

`ImportError: No module named 'fastmcp'`

Install with uv pip install fastmcp or add to pyproject.toml dependencies. Check that you're running the server from the same venv.

Проверить: uv pip show fastmcp
Async tool hangs on first call

You imported sync httpx inside an async tool. Use httpx.AsyncClient with async with — never mix.

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

FastMCP в сравнении

АльтернативаКогда использоватьКомпромисс
TypeScript MCP SDKYou're a TS/Node shop and want to stay thereOfficial, well-maintained, similar DX — just different language
fastapi-mcpYou already have a FastAPI app and want to expose routes as toolsLess control over the MCP surface but zero-refactor for existing services
csharp-sdk.NET shopFirst-party, but smaller ecosystem of examples

Ещё

Ресурсы

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

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

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