py-mcp-server

Joseph1977/py-mcp-server

3.2

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.

Tools
  1. weather

    Get comprehensive weather information for any location using the wttr.in API.

  2. brave_search_tool

    Search the web with Brave Search API.

  3. google_search_tool

    Search the web with Google Custom Search API.

Python MCP Server ๐Ÿš€

Python FastAPI MCP Docker

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 watcher
  • stop_watcher_tool - Stop a running watcher
  • remove_watcher_tool - Remove a watcher completely
  • list_watchers_tool - List all watchers and their status
  • get_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

EndpointMethodDescription
/mcpPOST/SSEMain MCP protocol endpoint
/healthGETServer health check
/infoGETServer information and capabilities
/file-watcher/sseGETSSE stream for file watcher events
/docsGETInteractive API documentation
/GETWelcome message

๐Ÿณ Docker Deployment

๐Ÿš€ Optimized Docker Configuration

This project includes two optimized Docker configurations:

ConfigurationImage SizeUse CaseBuild Time
Standard (Dockerfile)181MBGeneral development~45s
Alpine (Dockerfile.alpine)111MBProduction (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 variables
  • requirements.txt - Python dependencies
  • docker-compose.yml - Docker deployment configuration

๐Ÿ”ง Development

Adding New Tools

  1. 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
  1. 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 setup
  • app/config/ - Configuration and logging management
  • app/tools/ - Individual tool implementations
  • app/core/ - Core MCP utilities and base classes
  • app/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

MCP Protocol Endpoints

MethodEndpointDescription
POST/mcpMain MCP protocol communication
GET/healthServer health status
GET/infoServer capabilities and information

๐Ÿค Contributing

Development Setup

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-new-tool
  3. Make your changes following the existing code style
  4. Add tests for new functionality
  5. 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

  1. - Main application entry point
  2. - Working MCP client example
  3. - Configuration management
  4. - Python dependencies
  5. - 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