CC逆引きリファレンス

Python で MCP サーバーを作りたい

4. 権限・セキュリティ

コマンド / 機能

mcp Python SDK を使用

Python での MCP サーバー実装

設定例

# Python での MCP サーバー
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent

server = Server("my-python-server")

@server.list_tools()
async def list_tools():
    return [
        Tool(
            name="calculate",
            description="計算を実行",
            inputSchema={
                "type": "object",
                "properties": {
                    "expression": {"type": "string", "description": "計算式"}
                },
                "required": ["expression"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "calculate":
        result = eval(arguments["expression"])  # 本番では安全な評価を
        return [TextContent(type="text", text=str(result))]

async def main():
    async with stdio_server() as (read, write):
        await server.run(read, write, server.create_initialization_options())

import asyncio
asyncio.run(main())

こんな時に使う

  • Python で MCP サーバーを作りたい時
  • 既存の Python コードを MCP 化したい時

使い方

  1. 1pip install mcp
  2. 2@server.list_tools() でツール一覧を定義
  3. 3@server.call_tool() でツール実行ロジックを実装
  4. 4stdio_server() で標準入出力を使用

Tips

  • asyncio ベースの非同期実装
  • 複数ツールを1つのサーバーに定義可能
  • 既存の Python ライブラリをそのまま活用できる