Joseph1977/py-mcp-server
If you are the rightful owner of py-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 henry@mcphub.com.
The Model Context Protocol (MCP) server is a robust and extensible server built with Python and FastAPI, designed to handle real-time data and web search capabilities.
weather
Get comprehensive weather information for any location using the wttr.in API.
brave_search_tool
Search the web with Brave Search API.
google_search_tool
Search the web with Google Custom Search API.
Python MCP Server ๐
A fully functional Model Context Protocol (MCP) server built with Python and FastAPI, featuring real-time weather data, web search capabilities, and a robust HTTP/SSE transport layer. This server demonstrates best practices for MCP implementation with proper async handling, configuration management, and extensible tool architecture.
โจ What's Working Right Now
- โ Fully Operational MCP Server - Running on HTTP transport with auto-reload
- โ Real-time Weather Tool - Live weather data using wttr.in API
- โ Web Search Tools - Brave Search and Google Search implementations
- โ Complete MCP Protocol Support - Tool discovery, calling, resources, and prompts
- โ
Health Monitoring -
/health
and/info
endpoints for monitoring - โ Professional Logging - Comprehensive structured logging
- โ Async Session Management - Proper FastMCP lifecycle management
- โ Test Client Included - Ready-to-use MCP client for testing
๐ Key Features
Core MCP Implementation
- Standards Compliant: Full adherence to Model Context Protocol specifications
- HTTP/SSE Transport: Persistent connections with Server-Sent Events
- Tool Discovery: Dynamic tool registration and discovery
- Resource Management: Complete resource and prompt handling
- Session Lifecycle: Proper async session management with FastMCP
Built-in Tools
- ๐ค๏ธ Weather Tool: Real-time weather data from wttr.in (no API key required)
- ๐ Brave Search: Web search via Brave Search API (API key required)
- ๐ Google Search: Web search via Google Custom Search (API key required)
- ๏ฟฝ File Watcher: Real-time file system monitoring with SSE notifications
- ๏ฟฝ๐ System Info: Server health and information endpoints
Production Ready
- Auto-reload Development: Hot reloading during development
- Structured Logging: Comprehensive logging with proper levels
- Error Handling: Robust async error handling across all tools
- Configuration Management: Environment-based configuration
- Docker Support: Complete containerization with Docker Compose
- Health Monitoring: Built-in health check and server info endpoints
For a complete technical overview, see the document.
๐ Project Structure
py-mcp-server/
โโโ app/ # Main application package
โ โโโ __init__.py
โ โโโ main.py # FastAPI app with FastMCP integration
โ โโโ config/ # Configuration management
โ โ โโโ __init__.py
โ โ โโโ config.py # Settings and logging configuration
โ โโโ core/ # Core MCP logic
โ โ โโโ __init__.py
โ โ โโโ mcp_core.py # MCP base classes and utilities
โ โโโ tools/ # Tool implementations
โ โ โโโ __init__.py
โ โ โโโ weather.py # Weather tool (wttr.in API)
โ โ โโโ web_search.py # Brave/Google search tools
โ โ โโโ file_watcher.py # File system monitoring core
โ โ โโโ file_watcher_sse.py # SSE integration for file events
โ โโโ transports/ # Transport layer (future expansion)
โ โโโ __init__.py
โโโ .env.example # Environment configuration template
โโโ .gitignore # Git ignore patterns
โโโ docker-compose.yml # Docker Compose configuration
โโโ Dockerfile # Docker build configuration
โโโ get_mcp_tools_cli.ps1 # PowerShell MCP client (Windows)
โโโ mcp-flow.md # MCP protocol flow documentation
โโโ requirements.txt # Python dependencies
โโโ run.py # Server startup script
โโโ test_mcp_client.py # Python MCP client for testing
โโโ README.md # This documentation
๐ Quick Start
Prerequisites
- Python 3.11+ (recommended 3.11 or higher)
- pip package manager
- Git for version control
- Docker & Docker Compose (optional, for containerized deployment)
Optional API Keys (for enhanced functionality)
- Brave Search API Key - For web search capabilities
- Google Custom Search API Key + CX ID - For Google search integration
1. Clone and Setup
# Clone the repository
git clone <your-repo-url>
cd py-mcp-server
# Create virtual environment (Windows PowerShell)
python -m venv .venv
.\.venv\Scripts\Activate.ps1
# For Linux/macOS
python3 -m venv .venv
source .venv/bin/activate
2. Install Dependencies
pip install -r requirements.txt
3. Configure Environment (Optional)
# Copy example environment file
cp .env.example .env
# Edit .env file with your API keys (optional)
# BRAVE_API_KEY=your_brave_api_key_here
# GOOGLE_API_KEY=your_google_api_key_here
# GOOGLE_CX=your_google_custom_search_engine_id
4. Start the Server
python run.py
๐ That's it! Your MCP server is now running at http://localhost:8001
5. Test the Server
# Test weather tool (works without API keys)
python test_mcp_client.py
# Check server health
curl http://localhost:8001/health
# View server info
curl http://localhost:8001/info
๐ ๏ธ Available Tools
๐ค๏ธ Weather Tool (Fully Functional)
Get comprehensive weather information for any location using the wttr.in API.
Usage:
{
"method": "tools/call",
"params": {
"name": "weather",
"arguments": {
"location": "San Francisco, CA"
}
}
}
Features:
- โ No API Key Required - Uses free wttr.in service
- โ Detailed Forecasts - Current conditions, 3-day forecast, hourly data
- โ Global Coverage - Works for cities worldwide
- โ Multiple Formats - Temperature, humidity, wind, precipitation
๐ Web Search Tools (API Keys Required)
Brave Search
{
"method": "tools/call",
"params": {
"name": "brave_search_tool",
"arguments": {
"query": "python fastapi tutorial"
}
}
}
Google Search
{
"method": "tools/call",
"params": {
"name": "google_search_tool",
"arguments": {
"query": "machine learning python"
}
}
}
Note: Search tools require valid API keys in your .env
file to function properly.
๐ File Watcher Tools (Real-time File Monitoring)
Monitor file system changes in real-time with comprehensive filtering and SSE notifications.
Key Features:
- โ Real-time Monitoring - Instant file change notifications
- โ Pattern Filtering - Include/exclude patterns for targeted monitoring
- โ SSE Notifications - Live updates via Server-Sent Events
- โ Recursive Watching - Monitor directories and subdirectories
- โ Multi-format Support - Watch specific file types or all changes
Create File Watcher
{
"method": "tools/call",
"params": {
"name": "create_watcher",
"arguments": {
"watcher_id": "project_watcher",
"watch_path": "/path/to/project",
"file_patterns": ["*.py", "*.js", "*.ts"],
"exclude_patterns": ["__pycache__", "*.pyc", "node_modules"],
"recursive": true,
"auto_start": true
}
}
}
Other File Watcher Tools
start_watcher_tool
- Start a stopped watcherstop_watcher_tool
- Stop a running watcherremove_watcher_tool
- Remove a watcher completelylist_watchers_tool
- List all watchers and their statusget_watcher_status_tool
- Get detailed watcher information
SSE Live Notifications
Connect to real-time file change events:
// Connect to SSE stream
const eventSource = new EventSource('http://localhost:8001/file-watcher/sse?watchers=project_watcher');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.type === 'file_change') {
console.log(`File ${data.event.event_type}: ${data.event.filename}`);
}
};
Testing File Watcher:
# Test file watcher tools
python test_file_watcher.py
# Open SSE test client in browser
# file_watcher_test.html
๐ง Server Endpoints
Endpoint | Method | Description |
---|---|---|
/mcp | POST/SSE | Main MCP protocol endpoint |
/health | GET | Server health check |
/info | GET | Server information and capabilities |
/file-watcher/sse | GET | SSE stream for file watcher events |
/docs | GET | Interactive API documentation |
/ | GET | Welcome message |
๐ณ Docker Deployment
๐ Optimized Docker Configuration
This project includes two optimized Docker configurations:
Configuration | Image Size | Use Case | Build Time |
---|---|---|---|
Standard (Dockerfile ) | 181MB | General development | ~45s |
Alpine (Dockerfile.alpine ) | 111MB | Production (Recommended) | ~40s |
๐ฆ Size Comparison: Alpine version is 38.7% smaller (70MB reduction)
๐ฏ Production Deployment (Recommended)
# Using optimized Alpine image with Docker Compose
docker-compose up --build
# Run in background (detached mode)
docker-compose up --build -d
# View logs
docker-compose logs -f
# Stop the service
docker-compose down
๐ ๏ธ Development Mode
# Start development container with hot reloading
docker-compose --profile development up --build
# This runs on port 8001 with source code mounting
๐ Multi-Stage Builds
Both Dockerfiles use multi-stage builds for optimization:
- Builder stage: Compiles dependencies in virtual environment
- Production stage: Minimal runtime image with only necessary components
- Development stage: Additional tools for debugging (Alpine only)
๐ Security Features
- โ Non-root user (mcpuser:1001) for security
- โ Minimal attack surface with Alpine Linux
- โ Health checks built into containers
- โ Resource limits configured in docker-compose.yml
Using Docker Directly
# Build Alpine image (recommended for production)
docker build -f Dockerfile.alpine -t py-mcp-server:alpine .
# Build standard image
docker build -t py-mcp-server:standard .
# Run Alpine container
docker run -p 8001:8001 --env-file .env py-mcp-server:alpine
# Run with resource limits
docker run -p 8001:8001 --env-file .env \
--memory=512m --cpus=1.0 \
py-mcp-server:alpine
๐ง Docker Configuration Options
Environment Variables for Docker
# Port configuration (original port 8001)
MCP_SERVER_PORT=8001
# Environment mode
ENV=production
# Resource optimization
PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1
Volume Mounts
# Persistent logs
./logs:/app/logs:rw
# Development source mounting
.:/app:rw # Development only
๐๏ธ Build Targets
# Production build (default)
docker build -f Dockerfile.alpine --target production -t mcp:prod .
# Development build with additional tools
docker build -f Dockerfile.alpine --target development -t mcp:dev .
๐งช Testing the Server
Using the Included Test Clients
Python MCP Client (Recommended)
# Test all tools with comprehensive output (works without API keys)
python test_mcp_client.py
# Expected output:
# Connected to MCP server successfully!
# Available tools: ['weather', 'brave_search_tool', 'google_search_tool']
# Weather result: [Detailed weather information for San Francisco]
PowerShell MCP Client (Windows)
# Get MCP tools list using PowerShell (Windows users)
powershell -ExecutionPolicy Bypass -File "get_mcp_tools_cli.ps1"
# Expected output:
# === MCP PowerShell Client (CLI-based) ===
# MCP TOOLS LIST:
# Found 3 tools:
# 1. weather
# Description: Get the current weather for a location...
# 2. brave_search_tool
# Description: Search the web with Brave Search...
# 3. google_search_tool
# Description: Search the web with Google Search...
Manual Testing with curl
# Test server health
curl http://localhost:8001/health
# Get server information
curl http://localhost:8001/info
# Note: Direct MCP protocol testing requires proper SSE handling
# Use the Python or PowerShell clients above for MCP protocol testing
Expected Server Logs
2025-06-09 19:24:01,509 - mcp.server.streamable_http_manager - INFO - StreamableHTTP session manager started
2025-06-09 19:24:01,510 - app.main - INFO - FastMCP session manager started
2025-06-09 19:24:01,511 - app.main - INFO - MCP Server (HTTP/SSE) available at /mcp endpoint on host 0.0.0.0:8001
2025-06-09 19:24:01,512 - app.main - INFO - Registered routes:
2025-06-09 19:24:01,512 - app.main - INFO - Route: Path='/health', Name='health_check', Methods=['GET']
2025-06-09 19:24:01,512 - app.main - INFO - Route: Path='/info', Name='server_info', Methods=['GET']
โ๏ธ Configuration
Environment Variables
Create a .env
file in the project root with the following options:
# API Keys (Optional - Weather tool works without any keys)
BRAVE_API_KEY=your_brave_search_api_key
GOOGLE_API_KEY=your_google_api_key
GOOGLE_CX=your_google_custom_search_engine_id
# Server Configuration
MCP_TRANSPORT_MODE=http # Transport mode: 'http' or 'stdio'
MCP_SERVER_HOST=0.0.0.0 # Server host address
MCP_SERVER_PORT=8001 # Server port number
LOG_LEVEL=INFO # Logging level: DEBUG, INFO, WARNING, ERROR
Configuration Files
app/config/config.py
- Main configuration management.env
- Environment-specific variablesrequirements.txt
- Python dependenciesdocker-compose.yml
- Docker deployment configuration
๐ง Development
Adding New Tools
- Create a new tool file in
app/tools/
:
# app/tools/my_new_tool.py
import asyncio
from typing import Any
async def my_new_tool(param1: str, param2: int = 10) -> dict[str, Any]:
"""Description of what your tool does.
Args:
param1: Description of parameter 1
param2: Description of parameter 2 (optional)
Returns:
Dictionary with tool results
"""
# Your tool implementation here
result = {"message": f"Processing {param1} with value {param2}"}
return result
- Register in main.py:
# In app/main.py
from app.tools.my_new_tool import my_new_tool
@mcp_server.tool()
async def my_new_tool_endpoint(param1: str, param2: int = 10) -> str:
"""Tool description for MCP clients"""
result = await my_new_tool(param1, param2)
return str(result)
Project Architecture
app/main.py
- FastAPI application and MCP server setupapp/config/
- Configuration and logging managementapp/tools/
- Individual tool implementationsapp/core/
- Core MCP utilities and base classesapp/transports/
- Transport layer implementations (future)
Development Commands
# Start development server with auto-reload
python run.py
# Run with debug logging
LOG_LEVEL=DEBUG python run.py
# Test specific tool
python -c "from app.tools.weather import get_weather; import asyncio; print(asyncio.run(get_weather('London')))"
๐ Monitoring & Health Checks
Health Check Endpoint
curl http://localhost:8001/health
Response:
{
"status": "healthy",
"server": "MCP Server with FastMCP",
"version": "1.0.0"
}
Server Information Endpoint
curl http://localhost:8001/info
Response:
{
"name": "Benraz-MCP-Server",
"description": "An MCP server using FastMCP",
"transport_mode": "http",
"endpoints": {
"mcp": "/mcp",
"health": "/health",
"info": "/info"
},
"tools": ["weather", "brave_search_tool", "google_search_tool"]
}
Logging
The server provides comprehensive structured logging:
- INFO level: General operation information
- DEBUG level: Detailed execution traces
- ERROR level: Error conditions and exceptions
- Tool execution: Detailed tool call logging
๐ฆ Troubleshooting
Common Issues
Port Already in Use
# Error: [Errno 10048] Only one usage of each socket address
# Solution: Change port in .env file
MCP_SERVER_PORT=8002
Import Errors
# Error: ModuleNotFoundError
# Solution: Ensure virtual environment is activated
.\.venv\Scripts\Activate.ps1 # Windows
source .venv/bin/activate # Linux/macOS
API Key Issues
# Brave Search returns 422 error
# Solution: Add valid API key to .env file
BRAVE_API_KEY=your_actual_api_key_here
Checking Server Status
# Check if server is running
curl -f http://localhost:8001/health || echo "Server not responding"
# View detailed server logs
tail -f server.log # If logging to file
# Test MCP protocol
python test_mcp_client.py
๐ API Documentation
Interactive Documentation
- Swagger UI: http://localhost:8001/docs
- ReDoc: http://localhost:8001/redoc
- OpenAPI Spec: http://localhost:8001/openapi.json
MCP Protocol Endpoints
Method | Endpoint | Description |
---|---|---|
POST | /mcp | Main MCP protocol communication |
GET | /health | Server health status |
GET | /info | Server capabilities and information |
๐ค Contributing
Development Setup
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-new-tool
- Make your changes following the existing code style
- Add tests for new functionality
- Submit a pull request
Code Style
- Follow PEP 8 Python style guide
- Use type hints for all function parameters and returns
- Add comprehensive docstrings to all functions
- Include proper error handling and logging
Testing
# Run the test client
python test_mcp_client.py
# Test individual tools
python -m app.tools.weather
python -m app.tools.web_search
๐ License
This project is licensed under the MIT License. See the file for details.
๐ Resources
๐ Ready to extend your MCP server? The architecture is designed for easy expansion - add new tools, integrate APIs, and build powerful AI-assisted workflows!
๐ค For AI Agents & Automated Systems
Project Summary
This is a production-ready MCP server with:
- โ 3 working tools: Weather (no API key), Brave Search, Google Search
- โ Full MCP protocol: Complete implementation with FastMCP
- โ Test clients: Python and PowerShell clients included
- โ Docker ready: Optimized containers with health checks
- โ Monitoring: Built-in health and info endpoints
Key Files for Understanding
- - Main application entry point
- - Working MCP client example
- - Configuration management
- - Python dependencies
- - Docker deployment
Instant Test Commands
# Start server
python run.py
# Test in another terminal
python test_mcp_client.py
# Expected: Weather data for San Francisco + tool discovery
Code Patterns to Follow
- Tool registration: Use
@mcp_server.tool()
decorator - Async functions: All tools are async with proper error handling
- Type hints: Full typing for parameters and returns
- Logging: Comprehensive logging at INFO/DEBUG levels
- Configuration: Environment variables with
.env
support