aiohttp-mcp

A framework to easily make production-grade MCP servers for AI agents, built on aiohttp.

Installation

pip install aiohttp-mcp

Usage

import aiohttp_mcp
from aiohttp import web

async def get_weather(location: str) -> str:
    """Get current weather information for a location."""
    return f"Sunny in {location}."

app = web.Application()
aiohttp_mcp.setup(app, tools=aiohttp_mcp.ToolRegistry(get_weather))
web.run_app(app, handler_cancellation=True)

This serves the MCP endpoint at /mcp. It can be added to any existing aiohttp web application, or used as a standalone one as above.

Note that it is especially recommended to enable handler cancellation for MCP servers, but you should read the documentation first to understand the impact it has on your handlers: https://docs.aiohttp.org/en/stable/web_advanced.html#web-handler-cancellation

Remote servers

A server exposed on the internet needs two additions: the domain added to allowed_origins, and an authorization configuration. MCP uses OAuth 2.1, and aiohttp_mcp ships everything needed for it out of the box (including an authorization server) so a complete, working deployment is:

import os
import secrets

import aiohttp_mcp
from aiohttp import web

async def check_credentials(username: str, password: str, request: web.Request) -> bool:
    return username == "admin" and secrets.compare_digest(
        password, os.environ["MCP_PASSWORD"]
    )

app = web.Application()
aiohttp_mcp.setup(
    app,
    allowed_origins=("mcp.server.example",),
    authorization=aiohttp_mcp.LocalAuthorization(
        check_credentials,
        resource="https://mcp.server.example",
        secret=bytes.fromhex(os.environ["MCP_TOKEN_KEY"]),
    ),
)
web.run_app(app, handler_cancellation=True)

See Authorization for how the flow works, integrating with your application’s existing login, changing the consent page, and using an external authorization server.

Table of Contents