modelcontextprotocol / modelcontextprotocol/python-sdk

Error & Mismatch in OAuth scope resolution between Claude.ai/MCP Python SDK and Inspector

未关闭
#1,307 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

auth bug ready for work
主要语言
Python
星标
24.3k
派生
4k
平均合并
1 天 1 小时
30 天内合并 PR
31

描述

Initial Checks
Description

TLDR: The MCP Python SDK's OAuth flow and Claude.ai fetches scopes from the .well-known/oauth-authorization-server endpoint instead of the .well-known/oauth-protected-resource endpoint (RFC-9728) causing Claude.ai connector authorization failures with MCP servers that have downscoped scoping permissions.

Working MCP Inspector Authorization Flow with correct scopes VS Failing Claude.ai connector with incorrect scopes

Image Image

Per the MCP Authorization spec, the Claude client should start by fetching the (1) .well-known/oauth-protected-resource endpoint (per RFC-9728), which contains information about the authorization server and recommended scopes corresponding to that path. Currently, the MCP Python SDK only uses this endpoint to fetch the authorization server URL, but not the scopes. Instead, it fetches the scopes from the (2) .well-known/oauth-authorization-server metadata. In downscoped cases, this causes Claude to request incorrect scopes rather than the resource-specific scopes, resulting in access_denied during the auth callback stage.

I noticed there is a discrepancy in this logic between the Python SDK implementation and the MCP Inspector Authorization flow walkthrough. The MCP Inspector correctly prioritizes scopes from the oauth-protected-resource metadata, falling back to the authorization server metadata only if no scopes are defined:

/**
 * Discovers OAuth scopes from server metadata, with preference for resource metadata scopes
 * @param serverUrl - The MCP server URL
 * @param resourceMetadata - Optional resource metadata containing preferred scopes
 * @returns Promise resolving to space-separated scope string or undefined
 */
export const discoverScopes = async (
  serverUrl: string,
  resourceMetadata?: OAuthProtectedResourceMetadata,
): Promise<string | undefined> => {
  try {
    const metadata = await discoverAuthorizationServerMetadata(
      new URL("/", serverUrl),
    );

    // Prefer resource metadata scopes, but fall back to OAuth metadata if empty
    const resourceScopes = resourceMetadata?.scopes_supported;
    const oauthScopes = metadata?.scopes_supported;

    const scopesSupported =
      resourceScopes && resourceScopes.length > 0
        ? resourceScopes
        : oauthScopes;

    return scopesSupported && scopesSupported.length > 0
      ? scopesSupported.join(" ")
      : undefined;
  } catch (error) {
    console.debug("OAuth scope discovery failed:", error);
    return undefined;
  }
};

HOW TO REPRODUCE
I’ve validated this by updating the scopes being requested to the /authorize endpoint from Claude.
I have set up an OAuth application that has a limited set of scopes, example:

"scopes": [
        "mcp.functions",
        "offline_access"
    ],

Failing flow (where scopes are retrieved from .well-known/oauth-authorization-server endpoint:

GET /oidc/v1/authorize?response_type=code&client_id=910a86cd-07e2...
**&scope=all-apis+email+offline_access+openid+profile+sql**

Callback response looks something like:

https://claude.ai/api/mcp/auth_callback?error=access_denied&error_description=Scopes+%27email+openid+profile%27+are+not+assigned+to+the+client

I then resubmitted the authorize request, but this time overrided the scope values to match that needed by our OAuth application (this follows the behavior in MCP Inspecotr):

GET /oidc/v1/authorize?response_type=code&client_id=910a86cd-07e2...
**&scope=mcp.functions**

Callback response successfully returns an authorization code ✅

https://claude.ai/api/mcp/auth_callback?code=dcod...

In my setup, the first url (1) .well-known/oauth-protected-resource endpoint contains the proper set of scopes we need (in the scopes_supported field) while the second (2) .well-known/oauth-authorization-server endpoint advertises the list of all available scopes, but not for our particular resource.

THE ASK:
Update the scope requesting logic to be consistent with that in the MCP Inspector so the proper scopes are obtained during the authorization process. Otherwise, downscoping will not work properly with Claude connectors for MCP servers who rely on OAuth App connections for authentication/authorization. This may look like:
1. Store and apply scopes_supported from .well-known/oauth-protected-resource to the authorize endpoint.
2. Only fall back to .well-known/oauth-authorization-server if no scopes are present in the resource metadata.

Example Code
# From Python SDK in src/mcp/client/auth.py - we currently store authorization server information from the oauth protected resource endpoint but that's it:

async def _handle_protected_resource_response(self, response: httpx.Response) -> None:
    if response.status_code == 200:
        content = await response.aread()
        metadata = ProtectedResourceMetadata.model_validate_json(content)
        self.context.protected_resource_metadata = metadata
        if metadata.authorization_servers:
            self.context.auth_server_url = str(metadata.authorization_servers[0])

# Notice how there is no `scopes_supported` retrieved here.
# Later, scopes are instead pulled from the authorization server metadata:

async def _handle_oauth_metadata_response(self, response: httpx.Response) -> None:
    content = await response.aread()
    metadata = OAuthMetadata.model_validate_json(content)
    self.context.oauth_metadata = metadata
    if self.context.client_metadata.scope is None and metadata.scopes_supported is not None:
        self.context.client_metadata.scope = " ".join(metadata.scopes_supported)


# Example Tentative Fix where we fetch scopes from the protected resource response:

 async def _handle_protected_resource_response(self, response: httpx.Response) -> None:
        """Handle discovery response."""
        if response.status_code == 200:
            try:
                content = await response.aread()
                metadata = ProtectedResourceMetadata.model_validate_json(content)
                self.context.protected_resource_metadata = metadata
                if metadata.authorization_servers:
                    self.context.auth_server_url = str(metadata.authorization_servers[0])
                
                # Apply scopes from protected resource metadata if available
                if (metadata.scopes_supported is not None):
                    self.context.client_metadata.scope = " ".join(metadata.scopes_supported)



# Current logic from MCP Inspector in which authorization flow works:

/**
 * Discovers OAuth scopes from server metadata, with preference for resource metadata scopes
 * @param serverUrl - The MCP server URL
 * @param resourceMetadata - Optional resource metadata containing preferred scopes
 * @returns Promise resolving to space-separated scope string or undefined
 */
export const discoverScopes = async (
  serverUrl: string,
  resourceMetadata?: OAuthProtectedResourceMetadata,
): Promise<string | undefined> => {
  try {
    const metadata = await discoverAuthorizationServerMetadata(
      new URL("/", serverUrl),
    );

    // Prefer resource metadata scopes, but fall back to OAuth metadata if empty
    const resourceScopes = resourceMetadata?.scopes_supported;
    const oauthScopes = metadata?.scopes_supported;

    const scopesSupported =
      resourceScopes && resourceScopes.length > 0
        ? resourceScopes
        : oauthScopes;

    return scopesSupported && scopesSupported.length > 0
      ? scopesSupported.join(" ")
      : undefined;
  } catch (error) {
    console.debug("OAuth scope discovery failed:", error);
    return undefined;
  }
};
Python & MCP Python SDK
Using Claude.ai site on 08/25/25
MCP Python SDK: v1.13.1

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 src/mcp/client/auth.py 中的 _handle_protected_resource_response 和 _handle_oauth_metadata_response 开始,然后跟踪 client_metadata.scope 如何传递到授权请求。使用资源特定的 scopes 和更宽泛的授权服务器 scopes 复现该流程。完成标准是优先使用受保护资源的 scopes,以授权服务器 scopes 作为回退,并让最终的授权请求使用资源特定的集合。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
authentication, authorization
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
48/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。