aiohttp-mcp
构建在 aiohttp 之上的模型上下文协议 (MCP) 服务器的工具: Here are some tools and libraries that can help you build Model Context Protocol (MCP) servers on top of aiohttp: * **aiohttp:** This is the fundamental asynchronous HTTP server and client library for Python. You'll use it to handle incoming MCP requests and send responses. You'll need to understand how to define routes, handle requests, and serialize/deserialize data. * **asyncio:** Since aiohttp is built on asyncio, you'll need a good understanding of asynchronous programming concepts like event loops, coroutines, and tasks. This is crucial for handling concurrent requests efficiently. * **Marshmallow (or similar serialization library):** MCP often involves structured data. Marshmallow is a popular library for serializing and deserializing Python objects to and from formats like JSON. This helps you validate incoming requests and format outgoing responses according to the MCP specification. Alternatives include `attrs` with `cattrs`, or `pydantic`. * **JSON Schema (and a validator):** MCP implementations often use JSON Schema to define the structure and validation rules for the request and response payloads. Libraries like `jsonschema` can be used to validate incoming requests against a schema, ensuring that they conform to the MCP specification. * **gRPC (optional, but relevant for comparison):** While you're building on aiohttp, it's worth understanding gRPC. gRPC is a high-performance RPC framework that's often used for similar purposes as MCP. Understanding gRPC can help you make informed design decisions about your MCP implementation. If performance is critical, consider whether gRPC might be a better fit than a custom aiohttp-based solution. * **Logging:** Use Python's built-in `logging` module to log requests, errors, and other relevant information. This is essential for debugging and monitoring your MCP server. * **Testing Framework (pytest, unittest):** Write unit tests and integration tests to ensure that your MCP server is working correctly. `pytest` is a popular and flexible testing framework. * **OpenAPI/Swagger (optional):** If you want to document your MCP API, you can use OpenAPI (formerly Swagger). Tools like `aiohttp-apispec` can help you generate OpenAPI specifications from your aiohttp routes. This makes it easier for clients to understand and use your MCP server. **Example (Conceptual):** ```python import asyncio import json from aiohttp import web import marshmallow import jsonschema # Define your data models using Marshmallow class MyRequestSchema(marshmallow.Schema): input_data = marshmallow.fields.String(required=True) class MyResponseSchema(marshmallow.Schema): output_data = marshmallow.fields.String(required=True) # Define your JSON Schema (alternative to Marshmallow for validation) request_schema = { "type": "object", "properties": { "input_data": {"type": "string"} }, "required": ["input_data"] } async def handle_mcp_request(request): try: data = await request.json() # Option 1: Validate with JSON Schema try: jsonschema.validate(instance=data, schema=request_schema) except jsonschema.exceptions.ValidationError as e: return web.json_response({"error": str(e)}, status=400) # Option 2: Validate and deserialize with Marshmallow # try: # validated_data = MyRequestSchema().load(data) # except marshmallow.exceptions.ValidationError as err: # return web.json_response({"errors": err.messages}, status=400) # Process the request (replace with your actual logic) input_data = data['input_data'] # or validated_data['input_data'] output_data = f"Processed: {input_data}" # Serialize the response with Marshmallow response_data = MyResponseSchema().dump({"output_data": output_data}) return web.json_response(response_data) except Exception as e: print(f"Error: {e}") return web.json_response({"error": "Internal Server Error"}, status=500) async def main(): app = web.Application() app.add_routes([web.post('/mcp', handle_mcp_request)]) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, 'localhost', 8080) await site.start() print("Server started on http://localhost:8080") await asyncio.Future() # Run forever if __name__ == '__main__': asyncio.run(main()) ``` **Key Considerations for MCP:** * **Specification Adherence:** Carefully review the MCP specification you're implementing. Pay close attention to the required data formats, error codes, and communication protocols. * **Error Handling:** Implement robust error handling to gracefully handle invalid requests, unexpected errors, and other issues. Return informative error messages to the client. * **Security:** Consider security implications, especially if your MCP server is exposed to the internet. Implement authentication, authorization, and input validation to protect against malicious attacks. * **Performance:** Optimize your code for performance, especially if you expect a high volume of requests. Use asynchronous programming effectively, and consider caching frequently accessed data. * **Scalability:** Design your MCP server to be scalable, so that it can handle increasing traffic. Consider using a load balancer and multiple instances of your server. * **Monitoring:** Implement monitoring to track the performance and health of your MCP server. Use metrics like request latency, error rates, and resource utilization to identify and resolve issues. This comprehensive list should give you a good starting point for building your MCP server on top of aiohttp. Remember to adapt the tools and techniques to the specific requirements of your MCP implementation.
kulapard
README
aiohttp-mcp
用于在 aiohttp 之上构建 模型上下文协议 (MCP) 服务器的工具。
特性
- 易于与 aiohttp Web 应用程序集成
- 支持模型上下文协议 (MCP) 工具
- 异步优先设计
- 类型提示支持
- 用于开发的调试模式
- 灵活的路由选项
安装
使用 uv 包管理器:
uv add aiohttp-mcp
或者使用 pip:
pip install aiohttp-mcp
快速开始
基本服务器设置
创建一个带有自定义工具的简单 MCP 服务器:
import datetime
from zoneinfo import ZoneInfo
from aiohttp import web
from aiohttp_mcp import AiohttpMCP, build_mcp_app
# 初始化 MCP
mcp = AiohttpMCP()
# 定义一个工具
@mcp.tool()
def get_time(timezone: str) -> str:
"""获取指定时区的当前时间。"""
tz = ZoneInfo(timezone)
return datetime.datetime.now(tz).isoformat()
# 创建并运行应用程序
app = build_mcp_app(mcp, path="/mcp")
web.run_app(app)
用作子应用程序
您还可以将 aiohttp-mcp 用作现有 aiohttp 服务器中的子应用程序:
import datetime
from zoneinfo import ZoneInfo
from aiohttp import web
from aiohttp_mcp import AiohttpMCP, setup_mcp_subapp
mcp = AiohttpMCP()
# 定义一个工具
@mcp.tool()
def get_time(timezone: str) -> str:
"""获取指定时区的当前时间。"""
tz = ZoneInfo(timezone)
return datetime.datetime.now(tz).isoformat()
# 创建您的主应用程序
app = web.Application()
# 将 MCP 添加为子应用程序
setup_mcp_subapp(app, mcp, prefix="/mcp")
web.run_app(app)
客户端示例
以下是如何创建一个与 MCP 服务器交互的客户端:
import asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client
async def main():
# 连接到 MCP 服务器
async with sse_client("http://localhost:8080/mcp") as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# 初始化会话
await session.initialize()
# 列出可用工具
tools = await session.list_tools()
print("可用工具:", [tool.name for tool in tools.tools])
# 调用一个工具
result = await session.call_tool("get_time", {"timezone": "UTC"})
print("UTC 当前时间:", result.content)
if __name__ == "__main__":
asyncio.run(main())
更多示例
有关更多示例,请查看 examples 目录。
开发
设置开发环境
- 克隆存储库:
git clone https://github.com/kulapard/aiohttp-mcp.git
cd aiohttp-mcp
- 创建并激活虚拟环境:
uv venv
source .venv/bin/activate # 在 Windows 上: .venv\Scripts\activate
- 安装开发依赖项:
uv sync --all-extras
运行测试
uv run pytest
要求
- Python 3.10 或更高版本
- aiohttp >= 3.9.0, < 4.0.0
- aiohttp-sse >= 2.2.0, < 3.0.0
- anyio >= 4.9.0, < 5.0.0
- mcp >= 1.6.0, < 2.0.0
许可证
该项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅 LICENSE 文件。
贡献
欢迎贡献! 请随时提交 Pull Request。
推荐服务器
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
MCP Package Docs Server
促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。
Claude Code MCP
一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。
@kazuph/mcp-taskmanager
用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。
mermaid-mcp-server
一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。
Jira-Context-MCP
MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。

Linear MCP Server
一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

Sequential Thinking MCP Server
这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。
Curri MCP Server
通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。