Skip to main content
Build MCP Servers with a FastAPI APIRouter.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from agentor.mcp import MCPAPIRouter
import uvicorn

# Create FastAPI app
app = FastAPI()

# Add CORS middleware to access from UI
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Create MCP router
mcp_router = MCPAPIRouter()


# Register a single tool
@mcp_router.tool(description="Get current weather for a location")
def get_weather(location: str) -> str:
    """Get current weather information"""
    return f"The weather in {location} is sunny with a temperature of 72°F!"


# Register a single prompt
@mcp_router.prompt(description="Generate a code review prompt")
def code_review(language: str, code: str) -> list:
    """Generate a code review prompt"""
    return [
        {
            "role": "user",
            "content": {
                "type": "text",
                "text": f"Please review this {language} code:\n\n```{language}\n{code}\n```",
            },
        }
    ]


# Include the MCP router
app.include_router(mcp_router.get_fastapi_router())

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
You can test your MCP Server with an interactive UI called MCP Inspector:
npx -y @modelcontextprotocol/inspector@latest