跳到內容

MCP Client 的 OAuth 2.1 要求

MCP Client 在 OAuth 2.1 中扮演 Client 角色,代表使用者向 MCP Server 發出受保護的資源請求。以下是 MCP 規範對 Client 的具體要求。

MCP Client 需要透過兩個步驟找到 Authorization Server:

步驟一:取得 Protected Resource Metadata

Section titled “步驟一:取得 Protected Resource Metadata”

當 MCP Server 回傳 401 Unauthorized 時:

  1. Client MUST 解析 WWW-Authenticate header,從中取得 resource_metadata URL
  2. 若 header 中沒有 resource_metadata,Client MUST fallback 到 well-known URI:
    • 先嘗試 /.well-known/oauth-protected-resource/{server-path}
    • 再嘗試 /.well-known/oauth-protected-resource

從 Protected Resource Metadata 中取得 Authorization Server 的位置後:

  • Client MUST 支援 RFC 8414(OAuth 2.0 AS Metadata) OIDC Discovery 兩種 Discovery 機制
  • 對於有 path 的 issuer URL(如 https://auth.example.com/tenant1),MUST 依序嘗試:
    1. https://auth.example.com/.well-known/oauth-authorization-server/tenant1
    2. https://auth.example.com/.well-known/openid-configuration/tenant1
    3. https://auth.example.com/tenant1/.well-known/openid-configuration
  • 對於沒有 path 的 issuer URL,MUST 依序嘗試:
    1. /.well-known/oauth-authorization-server
    2. /.well-known/openid-configuration

MCP 支援三種 Client 註冊方式,Client SHOULD 依以下優先順序選擇:

如果 Client 已有該 Server 的 client_id,直接使用。

2. Client ID Metadata Documents(SHOULD)

Section titled “2. Client ID Metadata Documents(SHOULD)”

Client 使用 HTTPS URL 作為 client_id,指向一個包含 Client metadata 的 JSON 文件。這是最常見的情境——Client 和 Server 事先沒有關係。

Client MUST 在 HTTPS URL 上提供 metadata 文件,至少包含:

{
"client_id": "https://app.example.com/oauth/client-metadata.json",
"client_name": "My AI Assistant",
"redirect_uris": ["http://localhost:3000/callback"],
"grant_types": ["authorization_code"],
"response_types": ["code"],
"token_endpoint_auth_method": "none"
}

Client 可以透過 AS Metadata 中的 client_id_metadata_document_supported 欄位確認 Authorization Server 是否支援此機制。

若 Authorization Server 支援(AS Metadata 中有 registration_endpoint),Client MAY 使用 RFC 7591 動態註冊。

以上皆不可行時,提示使用者手動輸入 client_id

  • Client MUST 實作 PKCE
  • Client MUST 使用 S256 作為 code challenge method
  • Client MUST 在開始授權前,透過 AS Metadata 確認 code_challenge_methods_supported 欄位存在;若不存在,MUST 拒絕繼續
  • Client MUST 在 authorization request 和 token request 中帶上 resource 參數
  • resource MUST 是 MCP Server 的 canonical URI
  • Client MUST 不管 Authorization Server 是否支援都要送這個參數

例如,存取 https://mcp.example.com 時:

&resource=https%3A%2F%2Fmcp.example.com
  • MUST 使用 Authorization: Bearer <token> header
  • MUST 在每個 HTTP 請求中都帶上 Token,即使是同一個邏輯 session
  • MUST NOT 把 Token 放在 URL query string
  • MUST NOT 把 Token 送到非該 Token 目標的 MCP Server

初始授權時,Client SHOULD 依以下順序選擇 scope:

  1. 使用 401 回應的 WWW-Authenticate header 中的 scope 參數(格式定義於 OAuth 2.1 Section 5.3.1
  2. 若沒有,使用 Protected Resource Metadata 中的 scopes_supported

收到 403 Forbiddeninsufficient_scope)時,Client SHOULD 發起 step-up authorization,用增加的 scope 重新授權。

要求等級
實作 PKCE(S256)MUST
安全儲存 TokenMUST
Redirect URI 必須向 AS 註冊MUST
使用並驗證 state 參數SHOULD
所有 redirect URI 使用 localhost 或 HTTPSMUST