Skip to main content

Synchronous utilities for Model Context Protocol (MCP) integration

Project description

mcp-utils

A Python utility package for building Model Context Protocol (MCP) servers.

Tests PyPI - Version

Overview

mcp-utils provides utilities and helpers for building MCP-compliant servers in Python, with a focus on synchronous implementations using Flask. This package is designed for developers who want to implement MCP servers in their existing Python applications without the complexity of asynchronous code.

Key Features

  • Basic utilities for MCP server implementation
  • Server-Sent Events (SSE) support
  • Simple decorators for MCP endpoints
  • Synchronous implementation
  • HTTP protocol support
  • SQLite response queue
  • Comprehensive msgspec models for MCP schema
  • Built-in validation and documentation

Installation

Install from PyPI:

pip install mcp-utils-msgspec

For development (from source):

pip install -e .[dev]

Requirements

  • Python 3.10+
  • msgspec >= 0.18

Optional Dependencies

  • Flask (for web server)

Usage

Basic MCP Server

Here's a simple example of creating an MCP server (using the built-in SQLite queue):

from mcp_utils.core import MCPServer
from mcp_utils.queue import SQLiteResponseQueue
from mcp_utils.schema import GetPromptResult, Message, TextContent, CallToolResult

# Create a basic MCP server with SQLite-backed queue
mcp = MCPServer("example", "1.0", response_queue=SQLiteResponseQueue("responses.db"))

@mcp.prompt()
def get_weather_prompt(city: str) -> GetPromptResult:
    return GetPromptResult(
        description="Weather prompt",
        messages=[
            Message(
                role="user",
                content=TextContent(
                    text=f"What is the weather like in {city}?",
                ),
            )
        ],
    )

@mcp.tool()
def get_weather(city: str) -> str:
    return "sunny"

Flask Example

For production use, you can use a simple Flask app with the mcp server and support Streamable HTTP from version 2025-06-18.

from flask import Flask, jsonify, request
import msgspec
from mcp_utils.core import MCPServer
from mcp_utils.queue import SQLiteResponseQueue

# Create Flask app and MCP server with SQLite-backed queue
app = Flask(__name__)
mcp = MCPServer("example", "1.0", response_queue=SQLiteResponseQueue("responses.db"))

@app.route("/mcp", methods=["POST"])
def mcp_route():
    response = mcp.handle_message(request.get_json())
    # Convert msgspec Struct to builtin types for jsonify
    return jsonify(msgspec.to_builtins(response))


if __name__ == "__main__":
    app.run(debug=True)

For a more comprehensive example including logging setup and session management, check out the example Flask application in the repository.

Running with Gunicorn

Gunicorn is a better approach to running even locally. To run the app with gunicorn

from gunicorn.app.base import BaseApplication

class FlaskApplication(BaseApplication):
    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {
            key: value
            for key, value in self.options.items()
            if key in self.cfg.settings
        }
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


if __name__ == "__main__":
    handler = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    options = {
        "bind": "0.0.0.0:9000",
        "workers": 1,
        "worker_class": "gevent",
        "loglevel": "debug",
    }
    FlaskApplication(app, options).run()

Related Projects

  • MCP Python SDK - The official async Python SDK for MCP
  • mcp-proxy - A proxy tool to connect Claude Desktop with MCP servers
  • mcp-utils - Original version with Pydantic support

License

MIT License

Testing with MCP Inspector

The MCP Inspector is a useful tool for testing and debugging MCP servers. It provides a web interface to inspect and test MCP server endpoints.

Installation

Install MCP Inspector using npm:

npm install -g @modelcontextprotocol/inspector

Usage

  1. Start your MCP server (e.g., the Flask example above)
  2. Run MCP Inspector:
git clone git@github.com:modelcontextprotocol/inspector.git
cd inspector
npm run build
npm start
  1. Open your browser and navigate to http://127.0.0.1:6274/
  2. Enter your MCP server URL (e.g., http://localhost:9000/sse)
  3. Use the inspector to:
    • Change transport type to SSE
    • Test server connections
    • Monitor SSE events
    • Send test messages
    • Debug responses

This tool is particularly useful during development to ensure your MCP server implementation is working correctly and complies with the protocol specification.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcp_utils_msgspec-2.1.0.tar.gz (21.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_utils_msgspec-2.1.0-py3-none-any.whl (14.4 kB view details)

Uploaded Python 3

File details

Details for the file mcp_utils_msgspec-2.1.0.tar.gz.

File metadata

  • Download URL: mcp_utils_msgspec-2.1.0.tar.gz
  • Upload date:
  • Size: 21.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for mcp_utils_msgspec-2.1.0.tar.gz
Algorithm Hash digest
SHA256 10ba3dcc076a6f707a976afc5f52a64e182cd629dd3bdf0c83d855fff1501ec6
MD5 b43ec09fc1894fb2fc999c9e7763e443
BLAKE2b-256 b6a0fec0823a6b3fc7ab76602f4152be20212c971cd3941cbf80f68a82077234

See more details on using hashes here.

File details

Details for the file mcp_utils_msgspec-2.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mcp_utils_msgspec-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c7e8cf611becdf0deda1025f8bcfc824bab3e4968dc8b548c9c2e91115952820
MD5 6fe5f13012e7a84f26f6e5266264cd94
BLAKE2b-256 2894ef4be039aa3129042b55bb431b2bffcac7135054f8c39490ebb825bbd322

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page