To expose existing Python code as an MCP server, use fastMCP's decorators to annotate functions as tools or resources. This involves:
- Wrapping existing functions with
@mcp.toolfor executable actions or@mcp.resourcefor data access. - Adding type hints and docstrings for automatic schema generation.
- Handling context if needed (e.g., for logging or nested calls).
Assume existing code in existing_math.py with functions subtract and get_pi. (see file)
To expose functions subtract and get_pi as MCP server:
- Import and annotate in a new server file
annotated_mcp_server.py. (see file) - Run:
python annotated_mcp_server.py. Now, clients can callsubtract_toolor readmath://constants/pi.
This approach keeps original code unchanged while exposing it via MCP.