MCPクライアント・サーバー通信

Model Context Protocol(MCP)入門

James Chapman

AI Curriculum Manager, DataCamp

クライアント・サーバー通信

client_server1.jpg

Model Context Protocol(MCP)入門

クライアント・サーバー通信

client_server2.jpg

Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio2_v2.png

Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio2_v2.png

 

  • サーバーは子プロセスとして実行
Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio3_v2.png

 

  • サーバーは子プロセスとして実行
  • パイプ(stdin/stdout)で通信
Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio7_v2.png

 

  • サーバーは子プロセスとして実行
  • パイプ(stdin/stdout)で通信
Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio7_v2.png

 

  • サーバーは子プロセスとして実行
  • パイプ(stdin/stdout)で通信
  • ローカルのみ - 同一マシン
Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio7_v2.png

 

  • サーバーは子プロセスとして実行
  • パイプ(stdin/stdout)で通信
  • ローカルのみ - 同一マシン
  • シンプル、ネットワーク設定不要
Model Context Protocol(MCP)入門

トランスポート:標準入出力(stdio)

stdio7_v2.png

 

  • サーバーは子プロセスとして実行
  • パイプ(stdin/stdout)で通信
  • ローカルのみ - 同一マシン
  • シンプル、ネットワーク設定不要
  • クライアント終了時にサーバーも停止
Model Context Protocol(MCP)入門

トランスポート:Streamable HTTP

 

streamable_http.png

Model Context Protocol(MCP)入門

MCPサーバー:timezone_server.py

import mcp
from mcp.server.fastmcp import FastMCP
import requests

mcp = FastMCP("Timezone Converter")

@mcp.tool()
def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str:
    ...

if __name__ == "__main__": mcp.run(transport="stdio")
Model Context Protocol(MCP)入門

MCPクライアント:サーバーツールの一覧取得

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def get_tools_from_mcp():
# Define the server parameters params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])
# Connect to the MCP server and open a session async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
# Initialize the session await session.initialize()
# Ask the server what tools it provides response = await session.list_tools()
Model Context Protocol(MCP)入門

MCPクライアント:サーバーツールの一覧取得

async def get_tools_from_mcp():
            # ...

            # Ask the server what tools it provides
            response = await session.list_tools()

print("Connected to MCP server!") print("Available tools:") for tool in response.tools: print(f" - {tool.name}: {tool.description}") return response.tools
asyncio.run(get_tools_from_mcp())
Model Context Protocol(MCP)入門

MCPクライアント:サーバーツールの一覧取得

Connected to MCP server!
Available tools:
 - convert_timezone: 
    Convert a datetime from one timezone to another.

    Args:
        date_time: The datetime string in ISO format (e.g., '2025-01-20T14:30:00')
        from_timezone: Source timezone (e.g., 'America/New_York')
        to_timezone: Target timezone (e.g., 'Europe/London')

    Returns:
        A string with the converted datetime and timezone information
Model Context Protocol(MCP)入門

MCPクライアント:サーバーツールの呼び出し

async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:

            await session.initialize()

result = await session.call_tool(tool_name, arguments)
text_content = result.content[0].text print(f"Conversion Result: {text_content}") return str(text_content)
Model Context Protocol(MCP)入門

MCPクライアント:サーバーツールの呼び出し

asyncio.run(
    call_mcp_tool(
        "convert_timezone",
        {"date_time": "2025-01-20T14:30:00",
         "from_timezone": "America/New_York",
         "to_timezone": "Asia/Tokyo"}
    )
)
'2025-01-21T04:30:00+09:00'
Model Context Protocol(MCP)入門

練習しましょう!

Model Context Protocol(MCP)入門

Preparing Video For Download...