MCPハンドラーの実装パターン
MCP
効果的なハンドラー関数の実装パターン:
async function handleAction(args: Record<string, unknown> | undefined) {
// 1. パラメータの検証
if (!args || typeof args.param1 !== 'string') {
return {
content: [{ type: 'text', text: "パラメータが不正です" }],
isError: true
};
}
// 2. パラメータの構築
const params = {
param1: args.param1,
// オプションパラメータの処理
param2: typeof args.param2 === 'boolean' ? args.param2 : false
};
try {
// 3. APIリクエスト
const result = await apiService.callAction(params);
// 4. 結果の処理
if (!result.success) {
return {
content: [{ type: 'text', text: `エラー: ${result.error}` }],
isError: true
};
}
// 5. 成功レスポンス
return {
content: [{ type: 'text', text: "処理が完了しました" }]
};
} catch (error) {
// 6. エラーハンドリング
return {
content: [{ type: 'text', text: `例外が発生: ${error.message}` }],
isError: true
};
}
}