/ Diretório / Playground / FastMCP
● Oficial PrefectHQ ⚡ Instantâneo

FastMCP

por 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.

Por que usar

Principais recursos

Demo ao vivo

Como fica na prática

fastmcp.replay ▶ pronto
0/0

Instalar

Escolha seu cliente

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

Abra Claude Desktop → Settings → Developer → Edit Config. Reinicie após salvar.

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

Cursor usa o mesmo esquema mcpServers que o Claude Desktop. Config de projeto vence a global.

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

Clique no ícone MCP Servers na barra lateral do Cline, depois "Edit Configuration".

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

Mesmo formato do Claude Desktop. Reinicie o Windsurf para aplicar.

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

O Continue usa um array de objetos de servidor em vez de um map.

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

Adicione em context_servers. Zed recarrega automaticamente ao salvar.

claude mcp add fastmcp -- uvx fastmcp

Uma linha só. Verifique com claude mcp list. Remova com claude mcp remove.

Casos de uso

Usos do mundo real: FastMCP

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

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

Quando usar: You have a company API that agents should be able to call, and you don't want to write a client spec from scratch.

Pré-requisitos
  • Python 3.10+python --version
  • uv installedcurl -LsSf https://astral.sh/uv/install.sh | sh
Fluxo
  1. Bootstrap the project
    Scaffold a FastMCP server project called 'acme-api-mcp' with one starter tool. Use uv for dependency management.✓ Copiado
    → 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.✓ Copiado
    → 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.✓ Copiado
    → Tools return expected JSON, no stack traces

Resultado: A working MCP server you can point Claude Desktop or any MCP client at.

Armadilhas
  • 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

Quando usar: You want the agent to auto-discover and pull company knowledge without tool calls for every file.

Fluxo
  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.✓ Copiado
    → 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.✓ Copiado
    → 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.✓ Copiado
    → Resources appear as attachable context

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

Armadilhas
  • 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

Quando usar: Multiple devs need the same MCP — host it once, don't make everyone run stdio locally.

Pré-requisitos
  • A container host (Cloud Run, Fly, Railway) — Any Docker-capable runtime works
Fluxo
  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.✓ Copiado
    → 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.✓ Copiado
    → 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.✓ Copiado
    → Team members' clients see the same tools

Resultado: A shared remote MCP — one codebase, many users, easy to update.

Armadilhas
  • SSE connections drop behind some corporate proxies — Use streamable HTTP transport instead (newer spec) or document a VPN/direct-path requirement
Combine com: cloud-run

Combinações

Combine com outros MCPs para 10× de alavancagem

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.✓ Copiado
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.✓ Copiado

Ferramentas

O que este MCP expõe

FerramentaEntradasQuando chamarCusto
@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

Custo e limites

O que custa rodar

Cota de API
None — this is a framework, not a service
Tokens por chamada
Your server runs any LLM calls; framework overhead is negligible
Monetário
Free, open source
Dica
Use resources instead of tools for static content — resources are cheaper in tokens because they're pre-declared

Segurança

Permissões, segredos, alcance

Armazenamento de credenciais: Your choice — env vars are idiomatic; load secrets at process start, not per call
Saída de dados: Wherever your tool functions reach out to

Solução de problemas

Erros comuns e correções

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.

Verificar: 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.

Verificar: 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.

Alternativas

FastMCP vs. outros

AlternativaQuando usarTroca
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

Mais

Recursos

📖 Leia o README oficial no GitHub

🐙 Ver issues abertas

🔍 Ver todos os 400+ servidores MCP e Skills