# Claude Agent SDKの便利だけど知られていない機能
🌍
@tool デコレータと create_sdk_mcp_server で、独自の関数をエージェントのツールとしてインプロセスで実行できます。
データベースアクセス、外部API呼び出し、ドメイン固有のロジックをエージェントに提供する方法を解説します。
📌 タイトル:インプロセス・カスタムツール (create_sdk_mcp_server /
@tool)
🔗 URL:
🧩 概要
カスタムツールは、SDK のインプロセス MCP サーバーを使って独自の関数を Claude から呼び出せるようにする機能です。Python では `
@tool` デコレータ、TypeScript では `tool()` ヘルパーでツールを定義し、`create_sdk_mcp_server` でラップして `query()` に渡します。ツールはアプリケーションプロセス内で実行され、別プロセスは不要です。ツール名は `mcp__{server_name}__{tool_name}` の形式になります。`readOnlyHint` アノテーションで並列実行を有効にし、`isError` で復旧可能なエラーをエージェントに伝え、画像(base64)やリソースの返却も可能です。
🛠 使い方
`
@tool` デコレータでツールを定義し、`create_sdk_mcp_server` でサーバーにまとめます。
```python
from typing import Any
import httpx
from claude_agent_sdk import tool, create_sdk_mcp_server, query, ClaudeAgentOptions, ResultMessage
@tool(
"get_temperature",
"Get the current temperature at a location",
{"latitude": float, "longitude": float},
)
async def get_temperature(args: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient() as client:
response = await client.get(
"",
params={
"latitude": args["latitude"],
"longitude": args["longitude"],
"current": "temperature_2m",
},
)
data = response.json()
return {
"content": [
{"type": "text", "text": f"Temperature: {data['current']['temperature_2m']}"}
]
}
# インプロセスMCPサーバーにラップ
weather_server = create_sdk_mcp_server(
name="weather",
version="1.0.0",
tools=[get_temperature],
)
# query() に渡して使用
async for message in query(
prompt="What's the temperature in Tokyo?",
options=ClaudeAgentOptions(
mcp_servers={"weather": weather_server},
allowed_tools=["mcp__weather__get_temperature"],
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
```
🏗 本番システムへの組み込み方
・エラーハンドリングでは例外をスローせず `{"is_error": True}` を返すことで、エージェントループを継続させつつ Claude にリカバリーさせることができます
・`readOnlyHint=True` アノテーションを設定すると、副作用のないツールを他のリードオンリーツールと並列実行できます
・画像を返す場合は `{"type": "image", "data": base64_str, "mimeType": "image/png"}` 形式のコンテンツブロックを使用します
・`structuredContent` フィールドでツール結果を機械可読な JSON として返却できます(ただし Python の `
@tool` では未サポート、スタンドアロン MCP サーバーが必要)
💡 ユースケース
🗄 データベースアクセス:エージェントに直接 DB クエリを実行させる
🌐 外部API連携:社内 API やサードパーティサービスをツールとして公開する
📊 データ可視化:グラフを生成し画像(base64)として返却する
🔧 ドメインロジック:計算、変換、バリデーションなど特定の業務ロジックをツール化する
⚠️ 注意点
・Python の dict スキーマではすべてのキーが必須になります。オプションパラメータは schema に含めず、description で説明して `args.get()` で読み取ってください
・`structuredContent` は Python の `
@tool` デコレータでは転送されません(スタンドアロン MCP サーバーを使用)
・ツール検索(tool search)はデフォルトで有効で、SDK MCP ツールのスキーマは必要になるまで遅延ロードされます。無効にすると `tools` 配列のすべてのツールが毎ターンのコンテキストを消費します
・アノテーションはメタデータであり強制力はありません。`readOnlyHint=True` でも handler が書き込みを行う場合があります
✨ インプロセスのカスタムツールにより、エージェントの能力を自由に拡張でき、外部プロセスの管理も不要です。
#
ClaudeAgentSDK# #
AIAgent#