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
관련 서버
Scout Monitoring MCP
스폰서Put performance and error data directly in the hands of your AI assistant.
Alpha Vantage MCP Server
스폰서Access financial market data: realtime & historical stock, ETF, options, forex, crypto, commodities, fundamentals, technical indicators, & more
GhidraMCP
Enables LLMs to autonomously reverse engineer applications by exposing core Ghidra functionality.
Sleep MCP Server
Provides a sleep/wait tool to add delays between operations, such as waiting between API calls or testing eventually consistent systems.
vcpkg Package README MCP Server
Fetch comprehensive information about vcpkg packages, including READMEs, metadata, and search results.
Guardian MCP
Engineering discipline and persistent memory for AI coding assistants
Terraform MCP
A command-line tool that acts as an MCP server to interact with Terraform environments.
MCP SBOM Server
Performs a Trivy scan to produce a Software Bill of Materials (SBOM) in CycloneDX format.
Chrome DevTools MCP
Debug web applications by connecting to Chrome's developer tools via the Chrome DevTools Protocol.
ndlovu-code-reviewer
Manual code reviews are time-consuming and often miss the opportunity to combine static analysis with contextual, human-friendly feedback. This project was created to experiment with MCP tooling that gives AI assistants access to a purpose-built reviewer. Uses the Gemini cli application to process the reviews at this time and linting only for typescript/javascript apps at the moment. Will add API based calls to LLM's in the future and expand linting abilities. It's also cheaper than using coderabbit ;)
MCP Ollama Agent
A TypeScript agent that integrates MCP servers with Ollama, allowing AI models to use various tools through a unified interface.
HED MCP Server
An MCP server for Hierarchical Event Descriptors (HED) that automates sidecar creation and annotation for BIDS event files using LLMs.