0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamable HTTPのMCPサーバでヘッダーの情報を活用する

Posted at

概要

Streamable HTTPのMCPサーバにツールの引数以外で情報を渡す方法をひとつ紹介する。
何度も入力したくない、変更する頻度が少ない情報は、ヘッダーを介して渡すのも候補となると考える。
今回は、複数のクライアントがそれぞれの持つ認証情報でログインするというシチュエーションのMCPサーバを作成してみた。

今回のコードでできること(MCP Inspectorでの例)

①MCP Inspector上の「Authentication」の「JSON」をクリック
image.png
②「Custom Headers(JSON)」にidpasswordを設定し、「Switch to Form」をクリック
image.png
③「Custom Headers」に記述した項目が追加される
image.png

④あとは、Connectしてtoolからloginを実行すれば、②で設定した情報を使って処理が実行される。
image.png

ソースコード(Pythonファイル)

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

mcp = FastMCP("LoginServer", debug=True)

@mcp.tool('login')
async def login() -> str:
    """ログイン処理"""
    request: Request = get_http_request()
    id = request.headers.get("id", None)
    password = request.headers.get("password", None)
    # 実際のログイン処理追記してください
    
    return f"ID: {id},PASSWORD: {password}でログインしました。"

if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="localhost", port=7999)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?