独自のMCPサーバーの構築
モデル・コンテキスト・プロトコル(MCP)サーバーは、モデルがコールできる、型が指定された関数であるツールを公開する小さなWebサービスです。"標準プロトコル上に独自のツールを持ち込む"ようなものと考えてください。
FastMCPによる独自のコードとのやり取りのためのエージェントの使用可能化
FastMCPは、LLMをツールおよびデータに接続するための標準化された方法であるモデル・コンテキスト・プロトコル(MCP)サーバーを迅速かつ簡単に作成できるpythonライブラリです。
次に、独自のMCPサーバーを作成し、エージェントとコードを接続するためのシンプルなpythonテンプレートを示します。これをカスタマイズして、ニーズに応じて新しいツールや機能を作成します。
-
fastmcpライブラリをインストールしますpip install fastmcp -
このコードをpythonファイルにコピー、貼付けおよびカスタマイズを行います。
import logging from fastmcp import FastMCP logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) mcp = FastMCP(name="Custom_Server") def log_request(tool_name: str, **kwargs): logger.info(f"[REQUEST RECEIVED] Tool: {tool_name}, Args: {kwargs}") def log_response(tool_name: str, result): logger.info(f"[RESPONSE SENT] Tool: {tool_name}, Result: {result}") @mcp.tool def custom_tool_name(a: a_type, b: b_type) -> type: log_request("my_custom_tool", a=a, b=b) response = custom_function(a,b) log_response("custom_tool_name", response) return response @mcp.resource("resource://config") def get_config() -> dict: return {"version": "1.1", "author": "FastMCP"} #Step 3: Initialize your MCP-Server using HTTP + SSE transport protocol # mcp.run(transport="sse", …) — starts the MCP server using the SSE transport. # host: network interface/hostname to bind. # Use 127.0.0.1 for local-only, 0.0.0.0 for all interfaces, or a FQDN that resolves to your machine. # port: TCP port to listen on (e.g., 8080). # Mount path: the SSE stream is served under /sse by default. if __name__ == "__main__": # Runs an SSE transport server; by default it mounts at /sse on localhost. # You can customize host/port/mount_path via mcp.settings.* if needed. mcp.run(transport="sse", host="your-host", port=PORT)