2️⃣

FastMCP 2.0を用いてHTTP RequestからHTTP headerやquery parameterを簡単に取得する方法

に公開

本記事では、FastMCP 2.0を用いて、MCP Client(Streamable HTTP)のHTTP RequestからHTTP HeaderやQuery Parameterを取得する方法を紹介します。

背景

筆者は、MCPを使用したサービスの開発を進める中で、MCPサーバ上でHTTPヘッダーやクエリーパラメータを取得する必要が生じました。
そのため、FastMCPを用いてMCP Client(Streamable HTTP)のHTTP RequestからHTTP Headerを取得する方法を調査しました。

MCPのorganizationから提供されているPython SDKは、MCP Client/Serverの実装を簡単に行うことができるSDKですが、HTTP RequestからHTTP Headerを簡単に取得する方法は提供されていませんでした。[1]

調査を進める中で、FastMCP 2.0を用いることで、HTTP RequestからHTTP Headerを簡単に取得する方法がわかり、情報を共有として記事を執筆することにしました。

FastMCP 2.0の位置付け

FastMCP 2.0のREADMEより引用。

Welcome to FastMCP 2.0! This is the actively developed successor, and it significantly expands on 1.0 by introducing powerful client capabilities, server proxying & composition, OpenAPI/FastAPI integration, and more advanced features.

Google翻訳を用いて翻訳すると以下のような内容になります。

FastMCP 2.0 へようこそ! これは現在開発中の後継バージョンであり、強力なクライアント機能、サーバー プロキシと構成、OpenAPI/FastAPI 統合、およびより高度な機能を導入することで 1.0 を大幅に拡張しています

MCPのpython-sdkのv1.2.0のリリースノートを覗くと、

A big thank you to @jlowin for the creation of the fantastic FastMCP, which is now included into the MCP SDK.

と記載があるためFastMCP 2.0は正統な後継のようです。

実際、ドキュメントやサンプルコードを覗くとHTTP RequestsOpenAIとの統合により、v1と比較してシンプルに実装できるようになっています。

実装するもの

今回は、そんなFastMCP 2.0を用いて以下の機能を持つMCPサーバとクライアントを実装し、HTTP RequestからHTTP HeaderやQuery Parameterが取得できていることを確認します。

  1. server.py: サーバー側。FastMCPを用いて加算を行うtoolを提供
  2. client.py: クライアント側。langchain-mcp-adaptersLangChain,LangGraphを使ってMCPサーバ上のtoolをcallし、ユーザの要求に応えるAIエージェント

必要なパッケージ

以下のコマンドで必要なライブラリをインストールします

サーバーに必要なライブラリ

FastMCP 2.0をインストールします。

pip install 'fastmcp>=2.3.3'

クライアントに必要なライブラリ

AIエージェントを実装するために必要なパッケージ(langgraph)やlangchain-mcp-adaptersをインストールします。langchain-mcp-adaptersは、MCP介してtoolを呼び出すためのアダプターです。

pip install 'langchain-mcp-adapters>=0.0.11' langgraph langchain-openai langchain

環境変数の設定

AIエージェントを動かすためのLLMとして、gpt-4.1-nanoを使用します。
OpenAIのAPIにアクセスするために環境変数OPENAI_API_KEYを設定します。

export OPENAI_API_KEY=your_api_key_here

server.pyの実装

MCPサーバを実装します。
toolは加算(およびHTTPヘッダーとクエリパラメータの取得)を行うaddを実装します。

from fastmcp import FastMCP, Context
from fastmcp.server.dependencies import get_http_request
from starlette.requests import Request

# stateless_htte=Trueとすると、ステートレスな通信になります
# json_response=Trueとすると、サーバからのレスポンスがSSEでなくなります
mcp = FastMCP("StatelessServer", stateless_http=True, json_response=True)

@mcp.tool('add')
async def add(a: int, b: int, ctx: Context) -> int:
    """
    Add two integers.
    """
    # http_requestを取得
    request: Request = get_http_request()
    header = request.headers.get("foo", None)
    query_param = request.query_params.get("fuga", None)

    # printでheaderを表示
    print(f"Request Header: {header}")

    # printでquery parameterを表示
    print(f"Query Parameter: {query_param}")
    
    return a + b

# Run server with streamable_http transport
if __name__ == "__main__":
    mcp.run(transport="streamable-http")

上記のように、get_http_request()を用いることで、HTTP Requestを取得することができます。

client.pyの実装

LangChainとLangGraphを使ってMCPサーバーのtoolをcallするクライアントを実装します。

from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

from langgraph.prebuilt import create_react_agent
from langchain_mcp_adapters.tools import load_mcp_tools

import asyncio

async def main():
    headers = {"foo": "bar"}
    async with streamablehttp_client("http://localhost:8000/mcp?fuga=hoge", headers=headers) as (read, write, _):
        async with ClientSession(read, write) as session:
            # セッションを初期化
            await session.initialize()

            # MCPからtools情報を取得
            tools = await load_mcp_tools(session)

            # AIエージェントのセットアップ
            agent = create_react_agent("openai:gpt-4.1-nano", tools)
            
            # メッセージを送信
            response = await agent.ainvoke({"messages": [{"role": "user", "content": "what's 3 + 5?"}]})
            messages = response["messages"]

            for message in messages:
                print(message.content)

if __name__ == "__main__":
    asyncio.run(main())

上記のように、追加したいヘッダー情報をheadersとして定義し、streamablehttp_clientに引数として渡すことで、MCPサーバーに追加のヘッダー情報を渡すことができます。

実行方法

まずサーバーを起動します。

python server.py

次に別のターミナルでクライアントを実行します。

python client.py

出力について

実行すると、MCPサーバーのログ以外に、以下のようなログが表示されているかと思います。

Request Header: bar
Query Parameter: hoge

これで、MCPサーバー側にHeaderやQuery Parameterが届いていることが確認できました。

まとめ

FastMCP 2.0を用いることで、簡単にHTTP RequestからHTTP HeaderやQuery Parameterを取得することができました。

参考リンク

FastMCP 2.0

https://github.com/jlowin/fastmcp

https://gofastmcp.com/getting-started/welcome

https://gofastmcp.com/patterns/http-requests#overview

脚注
  1. low-levelなサンプルは提供されています MCP Simple StreamableHttp Stateless Server Example ↩︎

Discussion