mfciaccio/auto-mcp-server
If you are the rightful owner of auto-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
The Auto MCP Server is a dynamic and flexible server that automatically registers and exposes tools as both MCP tools and FastAPI endpoints, facilitating seamless integration and experimentation.
Auto MCP Server
A flexible, auto-registering MCP (Model Context Protocol) server that dynamically discovers and exposes tools as both MCP tools and FastAPI endpoints. Simply drop Python files into the tools/ folder and they're automatically registered!
Features
- 🔄 Auto-registration: Tools are automatically discovered and registered from the
tools/folder - 🚀 FastAPI Integration: All tools are exposed as REST endpoints with automatic Swagger documentation
- 📊 Database Registry: JSON-based database registry that tools can access for persistence
- 🛠️ FastMCP Framework: Built on the powerful FastMCP framework for MCP protocol support
- 📦 uvx Ready: Easy to run with
uvxfor quick experimentation - 🔧 Flexible Tool Definitions: Support for both automatic function discovery and custom tool definitions
- 📚 Comprehensive Documentation: Auto-generated API docs at
/docs
Quick Start with uvx
The fastest way to get started is using uvx:
# Clone the repository
git clone <repository-url>
cd auto-mcp-server
# Run directly with uvx (automatically installs dependencies)
uvx run src.main
# Or install and run
uvx install .
auto-mcp-server
Manual Installation
# Clone the repository
git clone <repository-url>
cd auto-mcp-server
# Install dependencies
pip install -e .
# Run the server
python -m src.main
Usage
Starting the Server
# Run both MCP and FastAPI servers (default)
python -m src.main
# Run only MCP server
python -m src.main --mcp-only
# Run only FastAPI server
python -m src.main --fastapi-only
# Custom host and port
python -m src.main --host 0.0.0.0 --port 9000
# Custom tools and databases paths
python -m src.main --tools-path ./my-tools --databases-path ./my-databases
Command Line Options
--host: Host to bind to (default: localhost)--port: Port to bind to (default: 8000)--mcp-only: Run MCP server only--fastapi-only: Run FastAPI server only--tools-path: Path to tools directory (default: tools)--databases-path: Path to databases directory (default: databases)
Creating Tools
Tools are Python files placed in the tools/ directory. There are several ways to create tools:
Method 1: Simple Functions (Auto-discovery)
Create a Python file with functions, and they'll be automatically registered:
# tools/my_tool.py
def hello_world(name: str = "World") -> str:
"""Say hello to someone."""
return f"Hello, {name}!"
async def calculate_square(number: float) -> float:
"""Calculate the square of a number."""
return number ** 2
Method 2: Tool Definition with get_tool_definition()
For more control, implement get_tool_definition():
# tools/advanced_tool.py
def get_tool_definition():
"""Return tool definition for MCP registration."""
return [
{
"name": "custom_name",
"function": "my_function",
"description": "Custom description"
}
]
def my_function(param1: str, param2: int = 10) -> dict:
"""Your tool function."""
return {"result": f"{param1} x {param2}"}
Method 3: Custom FastAPI Routes
For advanced FastAPI integration:
# tools/api_tool.py
from fastapi import HTTPException
from pydantic import BaseModel
class MyRequest(BaseModel):
data: str
async def my_endpoint(request: MyRequest):
"""Custom endpoint logic."""
return {"processed": request.data.upper()}
def get_fastapi_routes():
"""Return custom FastAPI routes."""
return [
{
"path": "custom-endpoint",
"method": "POST",
"function": my_endpoint,
"tags": ["Custom"]
}
]
Using Database Registry
Tools can access the database registry for persistence:
# tools/db_tool.py
async def store_data(key: str, value: str, db_registry=None) -> dict:
"""Store data using database registry."""
if db_registry is None:
return {"error": "Database registry not available"}
# Get a registered database
db_config = await db_registry.get_database("my_db")
if not db_config:
return {"error": "Database not found"}
# Use the database...
return {"status": "success"}
Database Registry
The server includes a JSON-based database registry for managing database connections:
Registering Databases
# Via API
POST /databases
{
"name": "my_db",
"connection_string": "sqlite:///path/to/db.sqlite",
"db_type": "sqlite",
"description": "My application database"
}
# Via MCP tool
await register_database("my_db", "sqlite:///path/to/db.sqlite")
Accessing Databases
# In your tools
async def my_tool(db_registry=None):
db_config = await db_registry.get_database("my_db")
connection_string = db_config["connection_string"]
# Use the database...
API Endpoints
When running with FastAPI integration, the following endpoints are available:
Core Endpoints
GET /- Server informationGET /health- Health checkGET /docs- Swagger documentationGET /redoc- ReDoc documentation
MCP Endpoints
GET /mcp/tools- List all MCP toolsPOST /mcp/tools/reload- Reload tools from filesystem
Database Endpoints
GET /databases- List registered databasesPOST /databases- Register a new databaseGET /databases/{name}- Get database configuration
Tool Endpoints
Each tool gets automatically generated endpoints:
GET|POST /tools/{tool_name}/{function_name}- Execute tool function
Example Tools Included
The server comes with several example tools:
Calculator Tool (tools/calculator.py)
- Basic math operations: add, subtract, multiply, divide, power
- Expression evaluation
API Examples:
POST /tools/calculator/add
{"a": 5, "b": 3}
POST /tools/calculator/calculate_expression
{"expression": "2 + 3 * 4"}
Text Utils Tool (tools/text_utils.py)
- Word/character counting
- Text transformations (uppercase, lowercase, reverse)
- Find and replace
- Email/URL extraction
- Hashing and base64 encoding
API Examples:
POST /tools/text_utils/count_words
{"text": "Hello world example"}
POST /tools/text_utils/analyze
{"text": "Contact us at support@example.com or visit https://example.com"}
Database Tools (tools/database_tools.py)
- SQLite database creation
- SQL query execution
- Table management
- Sample data creation
API Examples:
POST /tools/database_tools/create_sqlite_database
{"name": "test_db", "description": "Test database"}
POST /tools/database_tools/execute_sql_query
{
"database_name": "test_db",
"query": "SELECT * FROM users WHERE age > ?",
"parameters": [25]
}
Directory Structure
auto-mcp-server/
├── src/
│ ├── __init__.py
│ ├── main.py # Entry point
│ ├── server.py # MCP server logic
│ ├── registry.py # Database and tool registries
│ └── fastapi_integration.py # FastAPI integration
├── tools/ # Auto-discovered tools
│ ├── __init__.py
│ ├── calculator.py # Math operations
│ ├── text_utils.py # Text processing
│ └── database_tools.py # Database utilities
├── databases/ # Database files and registry
│ └── registry.json # Database registry
├── pyproject.toml # Project configuration
└── README.md # This file
Development
Adding Dependencies
Add dependencies to pyproject.toml:
[project]
dependencies = [
"fastmcp>=0.2.0",
"your-new-dependency>=1.0.0"
]
Running Tests
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run with coverage
pytest --cov=src
Code Formatting
# Format code
black src/ tools/
# Lint code
ruff src/ tools/
# Type checking
mypy src/
Configuration
Environment Variables
AUTO_MCP_HOST: Default host (default: localhost)AUTO_MCP_PORT: Default port (default: 8000)AUTO_MCP_TOOLS_PATH: Tools directory path (default: tools)AUTO_MCP_DATABASES_PATH: Databases directory path (default: databases)
Tool Configuration
Tools can include configuration by adding metadata:
# tools/configured_tool.py
TOOL_CONFIG = {
"enabled": True,
"rate_limit": 100,
"auth_required": False
}
def my_function():
"""Tool function."""
pass
Troubleshooting
Common Issues
- Tools not loading: Check for syntax errors in Python files
- Import errors: Ensure all dependencies are installed
- Database connection issues: Verify database registry configuration
- Port conflicts: Use
--portto specify a different port
Debug Mode
Enable debug logging:
import logging
logging.basicConfig(level=logging.DEBUG)
Tool Reload
Reload tools without restarting:
curl -X POST http://localhost:8000/mcp/tools/reload
Examples
Complete Tool Example
# tools/weather_tool.py
"""Weather information tool."""
import asyncio
from typing import Dict, Any, Optional
def get_tool_definition():
"""Tool definition for MCP."""
return [
{
"name": "get_weather",
"function": "get_current_weather",
"description": "Get current weather for a city"
},
{
"name": "weather_forecast",
"function": "get_weather_forecast",
"description": "Get weather forecast for a city"
}
]
async def get_current_weather(
city: str,
units: str = "metric",
db_registry=None
) -> Dict[str, Any]:
"""Get current weather for a city."""
# Your weather API logic here
return {
"city": city,
"temperature": 22,
"units": units,
"description": "Sunny"
}
async def get_weather_forecast(
city: str,
days: int = 5,
db_registry=None
) -> Dict[str, Any]:
"""Get weather forecast for a city."""
# Your forecast logic here
return {
"city": city,
"days": days,
"forecast": [
{"day": 1, "temp": 22, "description": "Sunny"},
{"day": 2, "temp": 20, "description": "Cloudy"}
]
}
# Custom FastAPI routes
def get_fastapi_routes():
"""Custom FastAPI routes."""
from pydantic import BaseModel
class WeatherRequest(BaseModel):
city: str
units: str = "metric"
async def weather_endpoint(request: WeatherRequest):
return await get_current_weather(request.city, request.units)
return [
{
"path": "current",
"method": "POST",
"function": weather_endpoint,
"tags": ["Weather"]
}
]
Contributing
- Fork the repository
- Create a feature branch
- Add your changes
- Add tests if applicable
- Run tests and linting
- Submit a pull request
License
MIT License - see LICENSE file for details.
Support
- Issues: GitHub Issues
- Documentation:
/docsendpoint when running - Examples: Check the
tools/directory