Unified MCP Server

Unified MCP Server

A server that exposes AI tools and resources through REST API, MCP, and WebSocket protocols using simple decorators.

Category
Visit Server

README

šŸš€ Unified MCP Server - One tool server; multiple protocols

Python 3.13+ FastAPI MCP Protocol License: MIT

A simple server that seamlessly exposes AI tools and resources through multiple protocols: REST API, MCP (Model Context Protocol), and WebSocket connections.

✨ Features

šŸ”Œ Triple Protocol Support

  • REST API: Standard HTTP endpoints for web integration
  • MCP over HTTP: Model Context Protocol for AI assistants (Claude, etc.)
  • WebSocket: Real-time bidirectional communication

šŸŽÆ Developer Experience

  • Simple Decorators: @tool, @resource, @resource_template, @prompt - that's it!
  • Type Safety: Full type hints with mypy support
  • Async/Await: Native async support throughout

šŸ—ļø Production Ready

  • Comprehensive Logging: Structured logging with configurable levels
  • Error Handling: Graceful error responses and recovery
  • CORS Support: Cross-origin requests handled
  • Health Checks: Built-in monitoring endpoints

šŸ“¦ Installation

Using uv (Recommended)

# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh

# Create and activate virtual environment
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install the package
uv add unified-mcp-server

Using pip

pip install unified-mcp-server

Development Installation

# Clone the repository
git clone <repository-url>
cd unified-mcp-server

# Using uv (recommended)
uv sync --dev

# Or using pip
pip install -e ".[dev]"

šŸš€ Quick Start

Basic Example

from unified_server import create_server, tool, resource, prompt

# Define tools with simple decorators
@tool(description="Add two numbers together")
def add(a: int, b: int) -> int:
    """Add two integers and return the result"""
    return a + b

@tool(description="Analyze text sentiment")
def analyze_sentiment(text: str) -> dict:
    """Analyze the sentiment of given text"""
    # Your sentiment analysis logic here
    return {"sentiment": "positive", "confidence": 0.95}

# Define resources (data sources)
@resource(
    uri="config://app/settings",
    description="Application configuration",
    mime_type="application/json"
)
def get_config():
    return {
        "app_name": "My App",
        "version": "1.0.0",
        "features": {"ai_enabled": True}
    }

# Define prompts for AI interactions
@prompt(description="Code review prompt")
def code_review_prompt(language: str):
    return [{
        "role": "user",
        "content": {
            "type": "text",
            "text": f"Review this {language} code for best practices"
        }
    }]

# Create and run server
if __name__ == "__main__":
    server = create_server(name="my-server", version="1.0.0")
    server.run(host="0.0.0.0", port=8000)

šŸ“ Complete Example

See src/tool_server.py for a comprehensive example with:

  • Multiple tools (math, search, sentiment analysis)
  • Various resources (config, user data, documentation)
  • Advanced prompts with parameters
  • Real file loading
  • Error handling

šŸ”§ Usage Examples

🌐 REST API

# List all available tools
curl http://localhost:8000/tools

# Execute a tool
curl -X POST http://localhost:8000/tools/add \
  -H "Content-Type: application/json" \
  -d '{"a": 15, "b": 27}'

# Get all resources
curl http://localhost:8000/resources

# Read a specific resource
curl http://localhost:8000/resources/get_config

# List available prompts
curl http://localhost:8000/prompts

# Generate a prompt
curl -X POST http://localhost:8000/prompts/code_review_prompt \
  -H "Content-Type: application/json" \
  -d '{"language": "python"}'

šŸ¤– MCP Integration

Claude Desktop Configuration

{
  "mcpServers": {
    "unified-server": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-everything", "http://localhost:8000/mcp"]
    }
  }
}

Direct MCP Client

import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    # Connect to your unified server
    async with stdio_client(StdioServerParameters(
        command="python",
        args=["-m", "your_server_module"]
    )) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the connection
            await session.initialize()
            
            # List available tools
            tools = await session.list_tools()
            print(f"Available tools: {[tool.name for tool in tools.tools]}")
            
            # Call a tool
            result = await session.call_tool("add", {"a": 10, "b": 20})
            print(f"Result: {result.content}")

asyncio.run(main())

šŸ”Œ WebSocket Connection

// Connect via WebSocket for real-time communication
const ws = new WebSocket('ws://localhost:8000/ws');

ws.onopen = function() {
    // Send tool execution request
    ws.send(JSON.stringify({
        type: 'tool_call',
        tool: 'add',
        parameters: { a: 5, b: 3 }
    }));
};

ws.onmessage = function(event) {
    const response = JSON.parse(event.data);
    console.log('Tool result:', response.result);
};

šŸ“š Examples

Basic Usage

Production Example

  • src/tool_server.py - Full-featured server with:
    • šŸ”§ Tools: Math operations, search, sentiment analysis
    • šŸ“„ Resources: Configuration, user data, documentation
    • šŸ’¬ Prompts: System prompts, code review, debugging
    • šŸ“ File Operations: Loading real files from disk

šŸ—ļø Architecture

src/unified_server/
ā”œā”€ā”€ šŸ›ļø core/              # Core server and registry
│   ā”œā”€ā”€ server.py         # Main FastAPI server
│   ā”œā”€ā”€ registry.py       # Tool/resource registry
│   └── config.py         # Configuration management
ā”œā”€ā”€ šŸŽØ decorators/         # Decorator implementations
│   ā”œā”€ā”€ tool.py          # @tool decorator
│   ā”œā”€ā”€ resource.py      # @resource decorator
│   ā”œā”€ā”€ resource_template.py  # @resource template decorator
│   └── prompt.py        # @prompt decorator
ā”œā”€ā”€ šŸ›£ļø routes/            # HTTP route handlers
│   ā”œā”€ā”€ tools.py         # Tool execution endpoints
│   ā”œā”€ā”€ resources.py     # Resource access endpoints
│   ā”œā”€ā”€ prompts.py       # Prompt generation endpoints
│   └── mcp.py           # MCP protocol endpoints
ā”œā”€ā”€ šŸ”§ handlers/          # Protocol handlers
│   └── mcp_handlers.py  # MCP message handling
└── šŸ› ļø utils/             # Utilities
    ā”œā”€ā”€ inspection.py    # Function signature analysis
    └── logging.py       # Logging configuration

šŸ” API Documentation

Once your server is running, visit:

  • šŸ“– Interactive Docs: http://localhost:8000/docs (Swagger UI)
  • šŸ“‹ ReDoc: http://localhost:8000/redoc (Alternative documentation)
  • šŸ”§ OpenAPI Schema: http://localhost:8000/openapi.json

šŸ› ļø Development

Setup Development Environment

# Using uv (recommended)
uv sync --dev
source .venv/bin/activate

# Using pip
pip install -e ".[dev]"

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=unified_server

# Run specific test file
pytest tests/test_tools.py -v

Code Quality

# Format code
black src tests examples

# Lint code
ruff check src tests examples

# Type checking
mypy src

# Run all quality checks
make lint  # if using the provided Makefile

Project Commands

# Start development server with auto-reload
uv run python src/tool_server.py

# Run basic example
uv run python examples/basic_example.py

# Run advanced example
uv run python examples/advanced_example.py

🐳 Docker Support

# Build image
docker build -t unified-mcp-server .

# Run container
docker run -p 8000:8000 unified-mcp-server

# Using docker-compose
docker-compose up

šŸ¤ Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

šŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

šŸ™ Acknowledgments

  • FastAPI for the excellent web framework
  • MCP Protocol for standardizing AI tool interfaces
  • Pydantic for data validation and serialization
  • uvicorn for ASGI server implementation

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured