MCP 実行コンテキスト使用方法
概要
MCP 実行コンテキストは、ツールの実行を追跡するための仕組みです。 各ツールの実行には一意の相関ID(CorrelationId)が割り当てられ、ツール名と共に管理されます。
基本的な使い方
1. DI コンテナへの登録
using Ateliers.Ai.Mcp.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
// MCP 実行コンテキストを登録
services.AddMcpExecutionContext();
var serviceProvider = services.BuildServiceProvider();
2. コンストラクタインジェクション
using Ateliers.Ai.Mcp;
using Ateliers.Ai.Mcp.Context;
public class MyMcpTool
{
private readonly IMcpExecutionContext _context;
public MyMcpTool(IMcpExecutionContext context)
{
_context = context;
}
public async Task ExecuteAsync()
{
// ツールスコープを開始
using var scope = _context.BeginTool("my.tool");
// 相関IDとツール名が自動設定される
Console.WriteLine($"CorrelationId: {_context.CorrelationId}");
Console.WriteLine($"ToolName: {_context.ToolName}");
// ツール処理
await ProcessAsync();
}
private async Task ProcessAsync()
{
// このメソッド内でも同じコンテキストが利用可能
Console.WriteLine($"Still in context: {_context.CorrelationId}");
await Task.Delay(100);
}
}
スコ ープの管理
ツールスコープ
public async Task ExecuteToolAsync()
{
// using ステートメントでスコープを管理
using var scope = _context.BeginTool("notion.sync");
// スコープ内の処理
await SyncNotionAsync();
// スコープ終了時に自動的にクリーンアップ
}