Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Example: CodeMode transform — search and execute tools via code.
CodeMode replaces the entire tool catalog with two meta-tools: `search`(keyword-based tool discovery) and `execute` (run Python code that chainstool calls in a sandbox). This dramatically reduces round-trips andcontext window usage when an LLM needs to orchestrate many tools.
Requires pydantic-monty for the sandbox: pip install "fastmcp[code-mode]"
Run with: uv run python examples/code_mode/server.py"""
from fastmcp import FastMCPfrom fastmcp.experimental.transforms.code_mode import CodeMode
mcp = FastMCP("CodeMode Demo")
@mcp.tooldef add(a: int, b: int) -> int: """Add two numbers together.""" return a + b
@mcp.tooldef multiply(x: float, y: float) -> float: """Multiply two numbers.""" return x * y
@mcp.tooldef fibonacci(n: int) -> list[int]: """Generate the first n Fibonacci numbers.""" if n <= 0: return [] seq = [0, 1] while len(seq) < n: seq.append(seq[-1] + seq[-2]) return seq[:n]
@mcp.tooldef reverse_string(text: str) -> str: """Reverse a string.""" return text[::-1]
@mcp.tooldef word_count(text: str) -> int: """Count the number of words in a text.""" return len(text.split())
@mcp.tooldef to_uppercase(text: str) -> str: """Convert text to uppercase.""" return text.upper()
@mcp.tooldef list_files(directory: str) -> list[str]: """List files in a directory.""" import os
return os.listdir(directory)
@mcp.tooldef read_file(path: str) -> str: """Read the contents of a file.""" with open(path) as f: return f.read()
# CodeMode collapses all 8 tools into just `search` + `execute`.# The LLM discovers tools via keyword search, then writes Python# scripts that chain multiple tool calls in a single round-trip.mcp.add_transform(CodeMode())
if __name__ == "__main__": mcp.run()