/ Annuaire / Playground / FastMCP
● Officiel PrefectHQ ⚡ Instantané

FastMCP

par PrefectHQ · PrefectHQ/fastmcp

La manière Pythonique de créer des serveurs MCP : décorez une fonction, obtenez un outil. Expédiez un MCP en 20 lignes.

FastMCP est un framework Python pour créer des serveurs MCP (pas un serveur à installer). Un décorateur @mcp.tool transforme une fonction typée en un outil MCP, avec des schémas dérivés automatiquement de vos annotations. Gère les transports stdio/SSE, le cycle de vie et les détails du protocole afin que vous écriviez uniquement la logique métier.

Pourquoi l'utiliser

Fonctionnalités clés

Démo en direct

Aperçu en pratique

fastmcp.replay ▶ prêt
0/0

Installer

Choisissez votre client

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

Ouvrez Claude Desktop → Settings → Developer → Edit Config. Redémarrez après avoir enregistré.

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

Cursor utilise le même schéma mcpServers que Claude Desktop. La config projet l'emporte sur la globale.

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

Cliquez sur l'icône MCP Servers dans la barre latérale Cline, puis "Edit Configuration".

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

Même format que Claude Desktop. Redémarrez Windsurf pour appliquer.

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

Continue utilise un tableau d'objets serveur plutôt qu'une map.

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

Ajoutez dans context_servers. Zed recharge à chaud à la sauvegarde.

claude mcp add fastmcp -- uvx fastmcp

Une seule ligne. Vérifiez avec claude mcp list. Supprimez avec claude mcp remove.

Cas d'usage

Usages concrets : FastMCP

Exposez une API REST interne en tant que MCP en moins d'une heure

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

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

Résultat : A working MCP server you can point Claude Desktop or any MCP client at.

Pièges
  • 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

Quand l'utiliser : You want the agent to auto-discover and pull company knowledge without tool calls for every file.

Déroulement
  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.✓ Copié
    → 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.✓ Copié
    → 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.✓ Copié
    → Resources appear as attachable context

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

Pièges
  • 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

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

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

Résultat : A shared remote MCP — one codebase, many users, easy to update.

Pièges
  • SSE connections drop behind some corporate proxies — Use streamable HTTP transport instead (newer spec) or document a VPN/direct-path requirement
Combiner avec : cloud-run

Combinaisons

Associez-le à d'autres MCPs pour un effet 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.✓ Copié
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.✓ Copié

Outils

Ce que ce MCP expose

OutilEntréesQuand appelerCoût
@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

Coût et limites

Coût d'exécution

Quota d'API
None — this is a framework, not a service
Tokens par appel
Your server runs any LLM calls; framework overhead is negligible
Monétaire
Free, open source
Astuce
Use resources instead of tools for static content — resources are cheaper in tokens because they're pre-declared

Sécurité

Permissions, secrets, portée

Stockage des identifiants : Your choice — env vars are idiomatic; load secrets at process start, not per call
Sortie de données : Wherever your tool functions reach out to

Dépannage

Erreurs courantes et correctifs

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.

Vérifier : 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.

Vérifier : 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.

Alternatives

FastMCP vs autres

AlternativeQuand l'utiliserCompromis
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

Plus

Ressources

📖 Lire le README officiel sur GitHub

🐙 Voir les issues ouvertes

🔍 Parcourir les 400+ serveurs MCP et Skills