メインコンテンツへスキップ
見出し画像

FastMCP 入門 (6) - コンテキスト

    「FastMCP」の「コンテキスト」についてまとめました。

    ・MCP Context

    前回

    1. コンテキスト

    FastMCPのツール、リソース、リソーステンプレート、またはプロンプトを定義する際に、関数が基盤となるMCPセッションやアクセスサーバの機能とやり取りする必要がある場合があります。FastMCPは、この目的のために「Context」オブジェクトを提供します。

    「Context」オブジェクトは、関数内で MCP 機能にアクセスするための明確なインターフェースを提供します。以下の機能が含まれます。

    ・ログ記録
    デバッグ、情報、警告、エラーメッセージをクライアントに送信します。

    ・進行状況レポート
    長時間実行操作の進行状況をクライアントに通知します。

    ・リソースアクセス
    サーバに登録されているリソースからデータを読み込みます。

    ・LLMサンプリング
    提供されたメッセージに基づいてクライアントの LLM にテキスト生成を要求します。

    ・リクエスト情報
    現在のリクエストに関するメタデータにアクセスします。

    ・サーバアクセス
    必要に応じて、基盤となる FastMCP サーバインスタンスにアクセスします。

    2. コンテキストへのアクセス

    関数内でコンテキストオブジェクトを使用するには、関数シグネチャにパラメータを追加し、型ヒントで「Context」と指定します。FastMCP は、関数が呼び出されると自動的にコンテキストインスタンスを挿入します。

    from fastmcp import FastMCP, Context
    
    mcp = FastMCP(name="ContextDemo")
    
    @mcp.tool()
    async def process_file(file_uri: str, ctx: Context) -> str:
        """ログ記録とリソース アクセスのコンテキストを使用して、ファイルを処理"""
        request_id = ctx.request_id
        await ctx.info(f"[{request_id}] Starting processing for {file_uri}")
    
        try:
            # コンテキストを使用してリソースを読み取る
            contents_list = await ctx.read_resource(file_uri)
            if not contents_list:
                await ctx.warning(f"Resource {file_uri} is empty.")
                return "Resource empty"
    
            data = contents_list[0].content # Assuming TextResourceContents
            await ctx.debug(f"Read {len(data)} bytes from {file_uri}")
    
            # 進捗状況を報告
            await ctx.report_progress(progress=50, total=100)
            
            # 作業をシミュレーション
            processed_data = data.upper() # Example processing
    
            await ctx.report_progress(progress=100, total=100)
            await ctx.info(f"Processing complete for {file_uri}")
    
            return f"Processed data length: {len(processed_data)}"
    
        except Exception as e:
            # コンテキストを使用してエラーを記録
            await ctx.error(f"Error processing {file_uri}: {str(e)}")
            raise # Re-raise to send error back to client

    ・パラメータ名 (例:ctx、context) は重要ではなく、型ヒントのContextのみが重要です。
    ・contextパラメータは関数シグネチャ内の任意の場所に配置できます。
    ・contextはオプションです。contextを必要としない関数ではパラメータを省略できます。
    ・contextはリクエスト中のみ利用可能です。リクエスト外でcontextメソッドを使用しようとするとエラーが発生します。
    ・contextメソッドは非同期であるため、通常は関数も非同期にする必要があります。

    3. コンテキスト機能

    3-1. ログ記録

    MCPクライアントにログメッセージを送り返します。これは、デバッグやリクエスト中の関数実行の可視化に役立ちます。

    @mcp.tool()
    async def analyze_data(data: list[float], ctx: Context) -> dict:
        """ログ記録を使用して数値データを分析"""
        await ctx.debug("Starting analysis of numerical data")
        await ctx.info(f"Analyzing {len(data)} data points")
        
        try:
            result = sum(data) / len(data)
            await ctx.info(f"Analysis complete, average: {result}")
            return {"average": result, "count": len(data)}
        except ZeroDivisionError:
            await ctx.warning("Empty data list provided")
            return {"error": "Empty data list"}
        except Exception as e:
            await ctx.error(f"Analysis failed: {str(e)}")
            raise

    ・ctx.debug(message: str) : デバッグに役立つ低レベルの詳細
    ・ctx.info(message: str) : 実行に関する一般情報
    ・ctx.warning(message: str) : 実行を妨げなかった潜在的な問題
    ・ctx.error(message: str) : 実行中に発生したエラー
    ・ctx.log(level: Literal["debug", "info", "warning", "error"], message: str, logger_name: str | None = None) : カスタムロガー名をサポートする汎用ログメソッド

    3-2. 進行状況レポート

    長時間実行される操作の場合、クライアントに進行状況を通知します。これにより、クライアントは進行状況インジケータを表示し、より優れたユーザーエクスペリエンスを提供できます。

    @mcp.tool()
    async def process_items(items: list[str], ctx: Context) -> dict:
        """進捗状況の更新を含むアイテムのリストを処理"""
        total = len(items)
        results = []
        
        for i, item in enumerate(items):
            # Report progress as percentage
            await ctx.report_progress(progress=i, total=total)
            
            # Process the item (simulated with a sleep)
            await asyncio.sleep(0.1)
            results.append(item.upper())
        
        # 100%完了を報告
        await ctx.report_progress(progress=total, total=total)
        
        return {"processed": len(results), "results": results}

    ・ctx.report_progress(progress: float, total: float | None = None)
     ・progress : 現在の進捗状況の値(例:24)
     ・total : 合計値(オプション) (例:100)。指定されている場合、クライアントはこれをパーセンテージとして解釈する可能性があります。

    進捗状況の報告には、クライアントが最初のリクエストで progressToken を送信している必要があります。クライアントが進捗状況の報告をサポートしていない場合、これらの呼び出しは効果がありません。

    3-3. リソースアクセス

    FastMCPサーバに登録されたリソースからデータを読み取ります。これにより、関数はファイル、設定、または動的に生成されたコンテンツにアクセスできます。

    @mcp.tool()
    async def summarize_document(document_uri: str, ctx: Context) -> str:
        """リソースURI別にドキュメントを要約"""
        # 文書の内容を読む
        content_list = await ctx.read_resource(document_uri)
        
        if not content_list:
            return "Document is empty"
        
        document_text = content_list[0].content
        
        # 例: 簡単な要約を生成 (長さベース)
        words = document_text.split()
        total_words = len(words)
        
        await ctx.info(f"Document has {total_words} words")
        
        # 簡単な要約を返す
        if total_words > 100:
            summary = " ".join(words[:100]) + "..."
            return f"Summary ({total_words} words total): {summary}"
        else:
            return f"Full document ({total_words} words): {document_text}"

    ・ctx.read_resource(uri: str | AnyUrl) -> list[ReadResourceContents]
     ・uri
    : 読み取るリソースURI
     ・リソースコンテンツパーツのリストを返します (通常は1つの項目のみを含みます)

    返されるコンテンツは通常content_list[0].contentを介してアクセスされ、リソースに応じてテキストまたはバイナリデータになります。

    3-4. LLMサンプリング

    クライアントのLLMに、提供されたメッセージに基づいてテキストを生成するよう要求します。これは、関数がLLMの機能を利用してデータを処理したりレスポンスを生成したりする必要がある場合に便利です。

    @mcp.tool()
    async def analyze_sentiment(text: str, ctx: Context) -> dict:
        """クライアントの LLM を使用してテキストの感情を分析"""
        # 感情分析を求めるサンプリングプロンプトを作成
        prompt = f"次のテキストの感情を、positive、negative、neutralの3つに分類して分析します。「positive」「negative」「neutral」のいずれか1つの単語を出力してください。分析対象テキスト:{text}"
        
        # サンプリングリクエストをクライアントのLLMに送信
        response = await ctx.sample(prompt)
        
        # LLMの応答を処理
        sentiment = response.text.strip().lower()
        
        # 標準的な感情値にマッピング
        if "positive" in sentiment:
            sentiment = "positive"
        elif "negative" in sentiment:
            sentiment = "negative"
        else:
            sentiment = "neutral"
        
        return {"text": text, "sentiment": sentiment}

    ・ctx.sample(messages: str | list[str | SamplingMessage], system_prompt: str | None = None, temperature: float | None = None, max_tokens: int | None = None) -> TextContent | ImageContent
     ・messages
    : LLMに送信する文字列または文字列/メッセージオブジェクトのリスト
     ・system_prompt : LLMの動作を指示するシステムプロンプト(オプション)
     ・temperature : サンプリング温度(オプション)(ランダム性を制御)
     ・max_tokens : 生成するトークンの最大数(オプション)(デフォルトは512)
     ・LLMのレスポンスをTextContentまたはImageContentとして返します。

    単純な文字列を指定した場合、それはユーザーメッセージとして扱われます。より複雑なシナリオでは、異なる役割を持つメッセージのリストを提供できます。

    @mcp.tool()
    async def generate_example(concept: str, ctx: Context) -> str:
        """特定の概念の Python コード例を生成"""
        # システムプロンプトとユーザーメッセージの使用
        response = await ctx.sample(
            messages=f"'{concept}' を説明する簡単な Python コード例を記述します。",
            system_prompt="あなたはPythonのエキスパートプログラマーです。説明なしで簡潔かつ動作するコード例を提供してください。",
            temperature=0.7,
            max_tokens=300
        )
        
        code_example = response.text
        return f"```python\n{code_example}\n```"

    詳しくは、Client Samplingを参照してください。

    3-5. リクエスト情報

    現在のリクエストとクライアントに関するメタデータにアクセスします。

    @mcp.tool()
    async def request_info(ctx: Context) -> dict:
        """現在のリクエストに関する情報を返す。"""
        return {
            "request_id": ctx.request_id,
            "client_id": ctx.client_id or "Unknown client"
        }

    ・ctx.request_id -> str : 現在のMCPリクエストの一意のIDを取得します
    ・ctx.client_id -> str | None : 初期化時に指定された場合、リクエストを行っているクライアントのIDを取得します

    3-6. 高度なアクセス

    高度なユースケースでは、基盤となるMCPセッション、FastMCPサーバ、HTTPリクエストにアクセスできます。

    ・Accessing FastMCP and Sessions

    @mcp.tool()
    async def advanced_tool(ctx: Context) -> str:
        """高度なコンテキスト アクセスをデモンストレーション"""
        # FastMCPサーバインスタンスにアクセス
        server_name = ctx.fastmcp.name
        
        # 低レベルのセッションアクセス (あまり使用しない)
        session = ctx.session
        request_context = ctx.request_context
        
        return f"Server: {server_name}"

    ・Accessing HTTP Requests
    Webアプリケーションの場合、基盤となるHTTPリクエストにアクセスできます。

    @mcp.tool()
    async def handle_web_request(ctx: Context) -> dict:
        """Starlette リクエストから HTTP リクエスト情報にアクセス"""
        request = ctx.get_http_request()
        
        # HTTP ヘッダ、クエリパラメータなどにアクセス
        user_agent = request.headers.get("user-agent", "Unknown")
        client_ip = request.client.host if request.client else "Unknown"
        
        return {
            "user_agent": user_agent,
            "client_ip": client_ip,
            "path": request.url.path,
        }

    ・ctx.fastmcp -> FastMCP : コンテキストが属するサーバインスタンスにアクセスします
    ・ctx.session : mcp.server.session.ServerSession オブジェクト(生データ)にアクセスします
    ・ctx.request_context : mcp.shared.context.RequestContext オブジェクト(生データ)にアクセスします
    ・ctx.get_http_request() -> Request : アクティブな Starlette リクエストオブジェクトにアクセスします(Web サーバで実行している場合)

    4. 異なるコンポーネントでのコンテキストの使用

    すべてのFastMCPコンポーネント(ツール、リソース、テンプレート、プロンプト)は、同じパターンに従ってコンテキストオブジェクトを使用できます。コンテキスト型アノテーションを使用してパラメータを追加するだけです。

    4-1. リソースとテンプレートのコンテキスト

    リソースとリソーステンプレートはコンテキストにアクセスして動作をカスタマイズできます。

    @mcp.resource("resource://user-data")
    async def get_user_data(ctx: Context) -> dict:
        """リクエストのコンテキストに基づいてパーソナライズされたユーザー データを取得"""
        user_id = ctx.client_id or "anonymous"
        await ctx.info(f"Fetching data for user {user_id}")
        
        # 動的リソース生成にコンテキストを使用する例
        return {
            "user_id": user_id,
            "last_access": datetime.now().isoformat(),
            "request_id": ctx.request_id
        }
    
    @mcp.resource("resource://users/{user_id}/profile")
    async def get_user_profile(user_id: str, ctx: Context) -> dict:
        """コンテキスト認識ログを使用してデータベースからユーザー プロファイルを取得"""
        await ctx.info(f"Fetching profile for user {user_id}")
        
        # テンプレートリソースでコンテキストを使用する例
        # 実際の実装では、データベースにクエリを実行する場合がある
        return {
            "id": user_id,
            "name": f"User {user_id}",
            "request_id": ctx.request_id
        }

    4-2. プロンプトのコンテキスト

    プロンプトはコンテキストを使用して、より動的なテンプレートを生成できます。

    @mcp.prompt()
    async def data_analysis_request(dataset: str, ctx: Context) -> str:
        """コンテキスト情報を使用してデータを分析するためのリクエストを生成"""
        await ctx.info(f"Generating data analysis prompt for {dataset}")
        
        # コンテキストを使用して構成を読み取ったり、プロンプトをカスタマイズしたりできる
        return f"""Please analyze the following dataset: {dataset}
        
    Request initiated at: {datetime.now().isoformat()}
    Request ID: {ctx.request_id}
    """

    すべての FastMCP オブジェクトは同じ一貫したパターンを使用したコンテキスト インジェクションをサポートするようになったため、MCP サーバのあらゆる側面にセッション対応機能を簡単に追加できるようになりました。

    次回



     
     

    npaka

     
     
    プログラマー。iPhone / Android / Unity / ROS / AI / AR / VR / RasPi / ロボット / ガジェット。年2冊ペースで技術書を執筆。アニソン / カラオケ / ギター / 猫 twitter : @npaka123

    あなたへのおすすめ