FastAPI MCP Math and Tool Registration Demo
A FastAPI-integrated MCP server that provides mathematical operations like addition and multiplication using Pandas for data manipulation. It serves as a comprehensive example for implementing different tool registration patterns and real-time communication via Server-Sent Events.
README
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
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。