FastAPI with MCP
A FastAPI application demonstrating MCP integration for mathematical operations and tool registration.
FastAPI with Model Context Protocol (MCP)
A FastAPI application integrated with Model Context Protocol (MCP) for mathematical operations and tool registration examples. This project demonstrates how to build MCP servers using FastAPI and shows different approaches to registering tools.
Features
- FastAPI web framework integration with MCP
- Multiple mathematical operations (add, multiply, subtract)
- Different tool registration patterns (decorators vs functions)
- Server-Sent Events (SSE) support for real-time communication
- Example configurations for MCP client integration
- Pandas integration for data manipulation demonstrations
Project Structure
fastapi-with-mcp/
├── fastapi_mcp.py # Main FastAPI + MCP application
├── test_tool_registration.py # Tool registration testing examples
├── config.json # MCP client configuration
├── pyproject.toml # Python project configuration
├── .python-version # Python version specification
├── .gitignore # Git ignore rules
├── uv.lock # UV lock file for dependencies
└── README.md # This file
Requirements
- Python 3.12+
- FastAPI[standard]
- FastMCP
- Pandas
- Pydantic
- MCP
Installation
- Clone the repository:
git clone <repository-url>
cd fastapi-with-mcp
- Create a virtual environment (using uv or standard Python):
# Using uv (recommended)
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Or using standard Python
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
- Install dependencies:
# Using uv
uv pip install -e .
# Or using pip
pip install -e .
Usage
Running the FastAPI + MCP Server
Start the main application:
uvicorn fastapi_mcp:app --reload --port 8000
The server will be available at:
- FastAPI docs:
http://localhost:8000/docs - MCP SSE endpoint:
http://localhost:8000/mcp-server/sse - MCP server mount:
http://localhost:8000/mcp-server
Available Tools
The application provides several mathematical tools that demonstrate Pandas integration:
- Add - Add two numbers using pandas DataFrame operations
- Multiply - Multiply two numbers using pandas DataFrame operations
- Subtract - Subtract two numbers using pandas DataFrame operations
Each operation creates a pandas DataFrame to perform the calculation, demonstrating how to integrate data manipulation libraries with MCP tools.
Tool Registration Methods
This project demonstrates multiple ways to register MCP tools:
Method 1: Decorator Approach
@mcp.tool
@app.get("/add", operation_id="add_two_numbers")
async def add(a: int, b: int):
"""Add two numbers and return the sum."""
summ = pd.DataFrame({"a": [a], "b": [b], "sum": [a + b]})
result = int(summ.loc[0, "sum"])
return {"sum": result}
Method 2: Function Registration
def multiply(a: int, b: int):
"""Multiply two numbers and return the product."""
product = pd.DataFrame({"a": [a], "b": [b], "product": [a * b]})
result = int(product.loc[0, "product"])
return {"product": result}
# Register the function as a tool
mcp.tool(multiply)
Method 3: Decorator as Function
def subtract(a: int, b: int):
"""Subtract two numbers and return the difference."""
diff = pd.DataFrame({"a": [a], "b": [b], "difference": [a - b]})
result = int(diff.loc[0, "difference"])
return {"difference": result}
# Register using the decorator syntax as a function
mcp.tool()(subtract)
Method 4: Combined FastAPI + MCP
@app.get("/multiply", operation_id="multiply_two_numbers")
async def multiply_endpoint(a: int, b: int):
"""FastAPI endpoint that also works as MCP tool."""
return multiply(a, b)
# Register the same function as an MCP tool
mcp.tool(multiply_endpoint)
MCP Client Configuration
The config.json file contains example configuration for MCP clients:
{
"mcpServers": {
"math-tools": {
"type": "http",
"url": "http://localhost:8000/mcp-server/sse",
"env": {}
}
}
}
This configuration:
- Uses
"math-tools"as the server identifier (reflecting the mathematical operations provided) - Sets type to
"http"for HTTP-based communication - Points to the mounted MCP server endpoint at
"/mcp-server/sse"
API Endpoints
FastAPI Endpoints
GET /add?a={int}&b={int}- Add two numbersGET /multiply?a={int}&b={int}- Multiply two numbersGET /docs- Interactive API documentationGET /redoc- ReDoc API documentation
MCP Endpoints
GET /mcp-server/sse- Server-Sent Events endpoint for MCP communication- MCP tools are accessible through the MCP protocol via the mounted server at
/mcp-server
Development
Testing Tool Registration
Run the tool registration test to see different registration methods:
python test_tool_registration.py
Simple MCP Server Example
For testing tool registration methods, see test_tool_registration.py:
python test_tool_registration.py
Dependencies
- FastAPI[standard]: Modern, fast web framework for building APIs with standard extras
- FastMCP: FastAPI integration for Model Context Protocol
- Pandas: Data manipulation library (used for mathematical operations)
- Pydantic: Data validation library
- MCP: Model Context Protocol implementation
Environment Variables
This project uses dotenv to load environment variables. Create a .env file for environment-specific configurations:
# Add any environment variables here if needed
# Example:
# DEBUG=true
# LOG_LEVEL=info
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Learn More
Troubleshooting
Common Issues
- Module name conflicts: Avoid naming files
mcp.pyas it conflicts with the MCP package - Port conflicts: Ensure port 8000 is available or change the port in uvicorn command
- Python version: This project requires Python 3.12+
- Dependencies: Make sure all dependencies are installed with the correct versions
Getting Help
If you encounter issues:
- Check the FastAPI docs at
/docsendpoint - Verify all dependencies are installed correctly
- Ensure Python 3.12+ is being used
- Check server logs for detailed error messages
- Verify that the MCP SSE endpoint is accessible at
/mcp-server/sse
Serveurs connexes
Alpha Vantage MCP Server
sponsorAccess financial market data: realtime & historical stock, ETF, options, forex, crypto, commodities, fundamentals, technical indicators, & more
MCP-Think
A Think Tool for LLMs to record and retrieve their thinking processes during reasoning.
Alertmanager
A Model Context Protocol (MCP) server that enables AI assistants to integrate with Prometheus Alertmanager
Chronos Protocol
A robust MCP server that eliminates temporal blindness in AI coding agents through intelligent time tracking, persistent memory, and complete session traceability.
Gemini Image Generator
Generate high-quality images from text prompts using Google's Gemini model.
Mesh Agent MCP Server
Connects to Heurist Mesh APIs to provide access to various blockchain and web3 tools.
MCPSwift
A Swift framework for building Model Context Protocol (MCP) servers with a simplified API.
Adaptive Graph of Thoughts
An intelligent scientific reasoning framework that uses graph structures and Neo4j to perform advanced reasoning via the Model Context Protocol (MCP).
BitFactory MCP
Simplifies and standardizes interactions with the BitFactory API.
Agent Forge
A platform for creating and managing AI agents with specific personalities and simulating their responses. Requires a DeepSeek API key.
Artificial Analysis
An unofficial MCP server for the Artificial Analysis API