Skip to content

Instantly share code, notes, and snippets.

@vguhesan
Created February 16, 2026 22:42
Show Gist options
  • Select an option

  • Save vguhesan/cfd663382b372e025ffc4e71897d97c5 to your computer and use it in GitHub Desktop.

Select an option

Save vguhesan/cfd663382b372e025ffc4e71897d97c5 to your computer and use it in GitHub Desktop.
Example of existing API exposed as an MCP Server using annotations

MCP Server + Client Example (leveraging existing REST APIs)

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.tool for executable actions or @mcp.resource for 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:

  1. Import and annotate in a new server file annotated_mcp_server.py. (see file)
  2. Run: python annotated_mcp_server.py. Now, clients can call subtract_tool or read math://constants/pi.

This approach keeps original code unchanged while exposing it via MCP.

# Filename: annotated_mcp_server.py
from fastmcp import FastMCP, Context
from existing_math import subtract, get_pi # Import existing functions
mcp = FastMCP(name="Annotated Math Server", description="Exposes existing math functions as MCP tools and resources")
# Annotate existing subtract function as a tool
@mcp.tool
def subtract_tool(x: float, y: float, ctx: Context = None) -> float:
"""Subtract y from x using existing code. Logs via context if available."""
if ctx:
ctx.info(f"Subtracting {y} from {x}")
return subtract(x, y) # Call existing function
# Annotate existing get_pi as a resource
@mcp.resource("math://constants/pi")
def pi_resource():
"""Return the value of pi from existing code."""
return str(get_pi()) # Wrap existing function
if __name__ == "__main__":
mcp.run(transport="http", host="127.0.0.1", port=8001, path="/mcp")
# Existing code in: existing_math.py
import math
def subtract(x: float, y: float) -> float:
return x - y
def get_pi() -> float:
return math.pi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment