跳至主要內容

使用 Logto 為你的 MCP 應用程式啟用驗證 (Authentication)

本指南將帶你整合 Logto 與你的 MCP 伺服器,透過 mcp-auth 實現,讓你能以標準 OpenID Connect 流程驗證使用者並安全取得其身分資訊。

你將學會:

  • 將 Logto 設定為 MCP 伺服器的授權伺服器 (Authorization server)。
  • 在 MCP 伺服器中設置「whoami」工具,回傳當前使用者的身分宣告 (Claims)。
  • 使用 MCP Inspector(MCP 用戶端)測試整個流程。

完成本教學後,你的 MCP 伺服器將能:

  • 在你的 Logto 租戶中驗證使用者。
  • 在呼叫「whoami」工具時回傳身分宣告(如 subusernamenameemail 等)。

整合完成後,你可以將 MCP Inspector 替換為你自己的 MCP 用戶端(如網頁應用程式),以存取 MCP 伺服器所提供的工具與資源。

先決條件

  • 一個 Logto Cloud(或自架)租戶
  • Node.js 或 Python 執行環境

架構說明

  • MCP 伺服器 (MCP server):對 MCP 用戶端 (client) 提供工具與資源的伺服器。
  • MCP 用戶端 (MCP client):用於啟動驗證流程並測試整合的用戶端。本指南將以 MCP Inspector 作為用戶端。
  • Logto:作為 OpenID Connect 提供者(授權伺服器),負責管理使用者身分。

以下是一個非標準(non-normative)的時序圖,說明整體流程:

備註:

由於 MCP 發展迅速,上述圖表可能未完全反映最新狀態。請參閱 mcp-auth 文件以取得最新資訊。

在 Logto 建立應用程式

  1. 登入你的 Logto Console。
  2. 前往 應用程式 (Applications)建立應用程式 (Create application)不依賴框架建立應用程式 (Create app without framework)
  3. 選擇類型:單頁應用程式 (Single-page app)。
  4. 輸入應用程式名稱及其他必要欄位,然後點擊 建立應用程式 (Create application)
  5. 儲存並複製 App ID簽發者端點 (Issuer endpoint)

設定 MCP 伺服器

建立專案並安裝相依套件

mkdir mcp-server
cd mcp-server
uv init # 或使用你自己的專案結構
uv add "mcp[cli]" starlette uvicorn mcpauth # 或使用你偏好的套件管理工具

使用 Logto 設定 MCP 驗證 (Authentication)

請記得將 <your-logto-issuer-endpoint> 替換為你先前複製的簽發者 (Issuer) 端點。

whoami.py 中:

from mcpauth import MCPAuth
from mcpauth.config import AuthServerType
from mcpauth.utils import fetch_server_config

auth_issuer = '<your-logto-issuer-endpoint>'
auth_server_config = fetch_server_config(auth_issuer, type=AuthServerType.OIDC)
mcp_auth = MCPAuth(server=auth_server_config)

實作存取權杖 (Access token) 驗證

由於我們將驗證存取權杖 (Access token) 並取得使用者資訊,因此需要如下實作存取權杖驗證:

import requests
from mcpauth.types import AuthInfo

def verify_access_token(token: str) -> AuthInfo:
endpoint = auth_server_config.metadata.userinfo_endpoint
response = requests.get(
endpoint,
headers={"Authorization": f"Bearer {token}"},
)
response.raise_for_status()
data = response.json()
return AuthInfo(
token=token,
subject=data.get("sub"),
issuer=auth_server_config.metadata.issuer,
claims=data,
)

實作 "whoami" 工具

現在,讓我們實作 "whoami" 工具,該工具會使用客戶端傳來的存取權杖 (Access token) 請求 userinfo 端點,並回傳目前使用者的身分宣告 (Claims)。

備註:

本範例採用 SSE 傳輸方式,因目前 SDK 尚未正式支援 Streamable HTTP 傳輸。理論上,你可以使用任何相容 HTTP 的傳輸方式。

from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.middleware import Middleware

mcp = FastMCP("WhoAmI")

@mcp.tool()
def whoami() -> dict:
"""
回傳目前使用者的身分資訊。
"""
return (
mcp_auth.auth_info.claims
if mcp_auth.auth_info
else {"error": "Not authenticated"}
)

bearer_auth = Middleware(mcp_auth.bearer_auth_middleware(verify_access_token))
app = Starlette(
routes=[
mcp_auth.metadata_route(), # 提供 OIDC metadata 供探索
Mount('/', app=mcp.sse_app(), middleware=[bearer_auth]),
],
)

啟動伺服器:

uvicorn whoami:app --host 0.0.0.0 --port 3001

測試整合流程

  1. 啟動 MCP 伺服器

  2. 啟動 MCP Inspector。

    由於目前 MCP Inspector 的實作限制,我們需要使用 mcp-auth 的 fork 版本:

    git clone https://github.com/mcp-auth/inspector.git
    cd inspector
    npm install
    npm run dev

    然後,開啟終端機顯示的網址。

  3. 在 MCP Inspector 中:

    • Transport TypeSSE
    • URLhttp://localhost:3001/sse
    • OAuth Client ID:貼上你的 Logto App ID
    • Auth Params{"scope": "openid profile email"}
    • Redirect URI:此網址應會自動填入,請複製它。
  4. 回到 Logto Console,找到你先前建立的應用程式,進入詳細頁面,將剛才複製的 redirect URI 貼到 設定 (Settings) / Redirect URIs 區塊,並儲存變更。

  5. 回到 MCP Inspector,點擊 Connect。這會將你導向 Logto 的登入體驗 (Sign-in experience)。

完成登入後,你應會被導回 MCP Inspector。前往 Tools -> List Tools -> whoami -> Run Tool

你應該會看到類似以下的使用者宣告 (Claims):

{
"sub": "user_XXXX",
"username": "alice",
"name": "Alice Smith",
"email": "[email protected]"
}

完整的 MCP 伺服器程式碼可在 mcp-auth/python 儲存庫中找到。