mcp-code-mode
Design and configure FastMCP 3.1+ CodeMode servers for scalable tool discovery and server-side composition. Use this skill when deciding between direct tools and CodeMode, tuning 2-stage vs 3-stage discovery, reducing schema token bloat, or implementing server-side `call_tool` composition in a sandbox.
MCP CodeMode (FastMCP 3.1+)
CodeMode is for tool catalogs where direct exposure is too expensive or noisy.
Instead of exposing every tool schema upfront, the server exposes discovery tools
plus an execute tool that runs Python using await call_tool(name, params).
Use this when you need better scalability for large tool sets, or when workflows often require multi-step tool composition.
Version and Stability
- Install with
fastmcp>=3.1.0. - CodeMode was introduced in FastMCP 3.1.
- Treat as experimental: core concept is stable, discovery details may evolve.
Direct Tools vs CodeMode
Choose based on workflow certainty and catalog size:
| Situation | Preferred Pattern |
|---|---|
| Small server, known calls, fixed workflow | Direct tools (or no-discovery CodeMode) |
| Medium/large catalog with uncertain tool choice | CodeMode with discovery |
| Repetitive multi-step composition | CodeMode execute |
| Deterministic orchestration you fully control | Direct known tool calls |
Rule: if your workflow already knows the target tool, skip discovery overhead.
Discovery Stages
CodeMode supports configurable discovery depth:
- 2-stage (common default):
search(detailed)->execute - 3-stage (precision mode):
search(brief)->get_schemas->execute - 0-stage (fixed workflow): no discovery tools; execute description lists known tools
Use 2-stage for most servers. Move to 3-stage when parameter trees are complex and search results alone are not enough to write correct calls.
Detail Levels and Token Budget
Discovery tools can return different detail:
brief: names + one-line descriptions (lowest token cost)detailed: compact parameter info (usually best)full: complete JSON Schema (highest cost)
Use progressive detail by default: start brief or detailed, request full only
for tricky schemas.
Sandbox Model
CodeMode execute runs Python in a sandbox with call_tool and standard Python.
Default expectation: no filesystem and no network access in generated code.
Important caveat: sandboxing generated code does not neutralize side effects of called tools. Keep destructive tool annotations, approval gates, and permission design exactly as strict as before.
Recommended Defaults
- Start with direct tools for tiny servers.
- For larger catalogs, enable CodeMode with 2-stage discovery.
- Keep
get_schemasavailable as fallback for complex tools. - Explicitly document when to skip discovery and call known tools directly.
- Keep a script fallback pattern when portability matters across environments.
For implementation snippets and patterns, read references/patterns.md.