pymcp-sse: Python MCP over SSE Library について
pymcp-sseは、HTTP/SSE経由でMCPサーバーとクライアントを構築するPythonライブラリです。非同期通信、ツール検出、サーバープッシュ、複数サーバー対応のクライアントを備え、アプリへのMCP統合に利用できます。
主な機能
- 01セッション管理付きHTTP/SSE通信
- 02非同期サーバー・クライアント部品
- 03デコレーターによるツール登録
- 04describe_toolsによるツール検出
- 05プッシュ通知とキープアライブ
- 06バックグラウンドタスク対応
活用シーン
- 01PythonでHTTP/SSE MCPサーバーを構築
- 02複数のMCPサーバーにクライアント接続
- 03クライアントへの定期通知
MCP 対応
HTTP/SSEを使ってMCPサーバーとクライアントを実装します。サーバーは登録したツールを公開し、クライアントはツール詳細の取得や複数サーバーへの接続ができます。
設定
ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。
このサーバーのパッケージやリモートエンドポイントはまだ取得できていません。プロジェクトの README の手順に従ってください。
ツール
ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。
詳細
pymcp-sse:SSE 経由の Python MCP ライブラリ
堅牢な HTTP/SSE トランスポートに特化した、Python アプリケーション向けの軽量で柔軟な Model Context Protocol(MCP)の実装です。
特長
- モジュール式フレームワーク:
BaseMCPServer、BaseMCPClient、MultiMCPClientをすっきりと実装しています。 - HTTP/SSE トランスポート:セッション管理の自動化、設定可能なタイムアウト、再接続処理を備えた堅牢な HTTP/SSE 実装です。
- 並行タスクの実行:
BaseMCPServer.run_with_tasks()メソッドを使用して、永続的なバックグラウンド非同期タスクとともにサーバーを簡単に実行できます。 - ツールの登録と検出:デコレーターによるシンプルなツール登録(
@server.register_tool())と、クライアントが詳細なツール機能(パラメーター、説明)を動的に照会できる標準のdescribe_toolsエンドポイントを備えています。 - サーバープッシュ:サーバーからクライアントへのプッシュ通知と、定期的なキープアライブ ping に標準で対応しています。ヘルパークラス
NotificationSchedulerも含まれます。 - LLM 統合:さまざまな LLM プロバイダーと簡単に統合できる
BaseLLMClient抽象化を含みます(Anthropic Claude の例が用意されています)。 - 柔軟なログ記録:
pymcp_sse.utilsを介してログ記録を設定できます。
インストール
開発用にライブラリをローカルにインストールするには:
# Navigate to the directory containing pyproject.toml
cd /path/to/your/pymcp-sse
# Install in editable mode
pip install -e .
(公開後は、pip install pymcp-sseによるインストールが可能になります。)
基本的な使い方
MCP サーバーの作成(シンプルな例)
from pymcp_sse.server import BaseMCPServer
from pymcp_sse.utils import configure_logging
configure_logging() # Configure logging (optional)
# Create a server instance
server = BaseMCPServer("My Simple Server")
# Register tools using the decorator
# Type hints are used by describe_tools
@server.register_tool("echo")
async def echo_tool(text: str) -> dict:
'''Echoes the provided text back.'''
return {"response": f"Echo: {text}"}
# Run the server using the standard method
if __name__ == "__main__":
# Additional kwargs are passed to uvicorn.run (e.g., timeout_keep_alive=65)
server.run(host="0.0.0.0", port=8000)
MCP サーバーの作成(バックグラウンドタスクあり)
import asyncio
from pymcp_sse.server import BaseMCPServer
from pymcp_sse.utils import configure_logging
configure_logging() # Configure logging (optional)
# Create a server instance
server = BaseMCPServer("My Background Task Server")
# Define your background task
async def my_periodic_task():
while True:
print("Task running...")
await asyncio.sleep(5)
# Define a shutdown callback
async def cleanup():
print("Cleaning up...")
# Run the server using run_with_tasks
async def main():
await server.run_with_tasks(
host="0.0.0.0",
port=8001,
concurrent_tasks=[my_periodic_task],
shutdown_callbacks=[cleanup]
)
if __name__ == "__main__":
asyncio.run(main())
単一クライアントの作成
import asyncio
from pymcp_sse.client import BaseMCPClient
from pymcp_sse.utils import configure_logging
configure_logging() # Configure logging (optional)
async def main():
# Configure timeouts for stability (read timeout > server ping interval)
client = BaseMCPClient(
"http://localhost:8000", # Point to your server
http_read_timeout=65,
http_connect_timeout=10
)
try:
# Connect and initialize
if await client.connect() and await client.initialize():
print(f"Connected. Available tools: {client.available_tools}")
# Call a tool
result = await client.call_tool("echo", text="Hello, world!")
print(f"Tool Result: {result}")
# Assign a notification handler if needed
# client.notification_handler = your_async_handler
except Exception as e:
print(f"An error occurred: {e}")
finally:
await client.close()
if __name__ == "__main__":
asyncio.run(main())
複数サーバーに接続するクライアントの作成
import asyncio
from pymcp_sse.client import MultiMCPClient
from pymcp_sse.utils import configure_logging
configure_logging() # Configure logging (optional)
async def main():
# Use servers from the examples section
servers = {
"server_basic": "http://localhost:8101",
"server_tasks": "http://localhost:8102"
}
# Configure timeouts for stability (read timeout > server ping interval)
client = MultiMCPClient(
servers,
http_read_timeout=65,
http_connect_timeout=10
)
try:
# Connect to all servers (automatically fetches tool details if describe_tools exists)
connection_results = await client.connect_all()
print(f"Connection Results: {connection_results}")
# Get info about connected servers (including tool details)
server_info = client.get_server_info()
print("\nServer Info:")
for name, info in server_info.items():
print(f"- {name}: Status={info['status']}, Tools={len(info.get('available_tools', []))}, Details Fetched={bool(info.get('tool_details'))}")
# Call a tool on a specific server
if server_info.get("server_basic", {}).get("status") == "connected":
result = await client.call_tool("server_basic", "echo", text="Hello from MultiClient!")
print(f"\nServer Basic Echo Result: {result}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
await client.close()
if __name__ == "__main__":
asyncio.run(main())
ドキュメント
詳しい使い方、HTTP/SSE 実装に関する注意事項、LLM 統合ガイド、プロトコル仕様については、docs/ディレクトリ内のドキュメントを参照してください。
例
examples/ディレクトリには、以下を含む、すぐに実行できる完全な例があります。
server_basic:server.run()を使用したシンプルなサーバーの例です。server_tasks:server.run_with_tasks()を使用した、バックグラウンドタスク(通知スケジューラー)を備えるサーバーの例です。client:MultiMCPClientとLLMAgentを使用し、自然言語で両方のサーバーとやり取りする、複数サーバーに接続するクライアントです。API キーが必要です(プロジェクトルートの.envファイルにANTHROPIC_API_KEYを設定してください)。run_all.py:server_basic、server_tasks、clientを同時に簡単に起動するためのランチャースクリプトです。notification_listener.py:互換性のある任意のサーバーからプッシュ通知を受信する、シンプルなスタンドアロンクライアントです。
ライセンス
MIT
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。