MCP FastMCPでサーバーとクライアントを試す
MCPをFastMCPを使用してどのようなものか試してみます
記事作成日:2025-12-10, 著者: Hi6
MPC(Model Context Protocol)とは
AI/機械学習モデルが扱うコンテキスト(文脈)情報を統一的に定義・管理・交換するためのプロトコルを指す概念です。MCPはAIアプリケーションを外部システムに接続するための標準化された方法を提供します。
MCPサーバー
- クライアントからの要求を受けてツール(関数)の実行やリソースの取得などを提供します。
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
mcp = FastMCP("My MCP Server", mask_error_details=True)
# ツールの作成
@mcp.tool
def divide(a: int, b: int) -> int:
"""Divide `a` and `b`.
Args:
a: First int
b: Second int
"""
if b == 0:
raise ToolError("Division by zero is not allowed.")
# Mask_error_details=True の場合、このメッセージはマスクされます。
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both arguments must be numbers.")
return a / b
if __name__ == "__main__":
mcp.run(transport="http", host="127.0.0.1",port=8081)
MCPクライアント
- サーバーからツール一覧を取得しMCPプロトコルに従ってMCPサーバーからサービスを受け取ります。
- クライアントはサーバー接続を可能にするプロトコルレベルのコンポーネントです。ユーザーが操作するアプリケーションはMCPホスト。
import asyncio
from fastmcp import Client
client = Client("http://localhost:8081/mcp")
async def call_tool(a:int, b:int):
async with client:
result = await client.call_tool("divide", {"a": a, "b": b})
print(f"Result of division: {result.structured_content["result"]}")
asyncio.run(call_tool(15, 5))
出力結果: Result of division: 3.0
[!NOTE] 参照サイト