Skip to content

Forward insufficient_scope challenges from the Kernel API - #284

Open
rgarcia wants to merge 4 commits into
mainfrom
hypeship/forward-insufficient-scope
Open

rgarcia wants to merge 4 commits into
mainfrom
hypeship/forward-insufficient-scope

Conversation

@rgarcia

@rgarcia rgarcia commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The Kernel API is getting an RFC 6750 insufficient_scope challenge for native OAuth sign-ins that lack a permission the consent page can grant (WWW-Authenticate: Bearer error="insufficient_scope", scope="<held + missing actions>", resource_metadata="<API metadata>", plus missing_scopes in the JSON body). This server now passes that on to MCP clients so they can re-authorize (MCP step-up authorization), pointing them at this server's own protected resource metadata.

  • Transport-level 403s (src/app/[transport]/route.ts):
    • The token exchange's invalid_scope answers 403 with WWW-Authenticate: Bearer error="insufficient_scope", resource_metadata="<origin>/.well-known/oauth-protected-resource/mcp", error_description=....
    • A /auth/context 403 that carries the API's challenge is forwarded with the API's scope and this server's resource_metadata; the JSON body uses the challenge's description.
    • A /auth/context 403 without a challenge (for example a credential scoped to another project) no longer gets WWW-Authenticate. The old Bearer realm="OAuth", error="insufficient_scope" invited a re-authorization that could not fix it.
  • Tool calls (src/lib/mcp/scope-challenge-results.ts): a tool that is already running cannot be turned into an HTTP 403, since a client retrying the call could repeat work it already did. When the API refuses a tool's request with a challenge, the call fails as a tool error (isError) whose text names the missing permissions and asks the user to reconnect, with the challenge in _meta["mcp/www_authenticate"], naming the metadata of the host the client connected to (as the transport 403s do).
    • ToolCallError keeps the API error as its cause so the challenge survives throwToolError.
    • The managed-auth login tools (open_auth_login, begin_auth_login) route challenged denials through throwToolError instead of a generic retry message.
    • The manage_auth_connections wait loop stops at a challenged denial instead of polling until timeout.
    • The managed-auth panel shows the begin tool's error text instead of always saying "close and retry" (the generated bundle is rebuilt).
  • docs/native-oauth.md documents the outcomes.

mcp_connection_scope_failure events keep the same stage, outcome and status codes. One analytics difference: tool calls answered with a challenge return a tool error instead of throwing, so their PostHog tool event records a generic error type rather than KernelApiError403.

Rollout

Safe before and after the API change ships: with an API that sends no challenge, every path behaves as before, except that a /auth/context 403 no longer carries the old challenge header. Rolling back restores the old headers.

Merge after kernel/kernel#5800, the API change that sends the challenge, has deployed. It is stacked on kernel/kernel#5799, the step-up consent page.

Testing

  • bun test: 1364 pass, 0 fail. New tests cover challenge parsing, rewriting resource_metadata, tool-result _meta, the forwarded and unforwarded /auth/context 403, the exchange 403, the wait loop and the panel.
  • bunx tsc --noEmit clean. bun run check:managed-auth-app passes.
  • Prettier is clean on new and changed files; some files already fail format:check on main and are left untouched.

Reviewed with sol-loop: 4 rounds with openai-codex/gpt-6.2-sol on extra-high reasoning. Sol verdict: approved.

@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
mcp Ready Ready Preview Nov 27, 2026 5:15pm UTC

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 17cf198. Configure here.

Comment thread src/lib/mcp/scope-challenge-results.ts Resolved
@rgarcia
rgarcia requested a review from masnwilliams November 27, 2026 16:12

@masnwilliams masnwilliams left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. The behavior looks right and the change is small (about 110 lines of logic outside tests and docs).

Before merging: per the rollout note, wait until kernel/kernel#5800 is deployed, then check in staging with a real MCP client that a native OAuth token missing a grantable scope (1) gets the transport 403 and is sent to step-up consent through this server's resource_metadata, and (2) gets the reconnect text on a tool call that hits the missing scope.

Suggestions. The first is strongly recommended; the rest are optional.

  1. returnScopeChallenges and analytics. The wrapper turns a thrown ToolCallError back into a returned isError result. This contradicts the throwToolError docstring ("Throws rather than returning an isError result: analytics reads the error category from a thrown error's name"), and the PostHog event loses KernelApiError403. The wrapper also only looks for the challenge at error.cause, so an APIError that escapes a tool without going through throwToolError is missed. Consider detecting the challenge once in ToolCallError's constructor (this.scopeChallenge = scopeChallengeOf(cause)) and checking error instanceof ToolCallError && error.scopeChallenge in the wrapper. Type the context as the SDK's ServerContext instead of params.at(-1) as { http?: { req?: Request } }. Parse missing_scopes in scopeChallengeOf too, rather than casting cause again in reconnectNote. At minimum, update the docstring.
  2. One WWW-Authenticate builder. createAuthErrorResponse (401) and mcpScopeChallenge (403) now differ: one includes realm and the other doesn't, and one escapes nothing while the other strips quotes and backslashes. One shared builder, or the SDK's bearerAuthChallengeResponse, would keep them consistent. resourceMetadataUrl could also be required, rather than falling back to mcpServerOrigin().
  3. Store the description once. The rejected-403 failure keeps it in description and in challenge.description, and each producer sets only one. That's what forces the ?? chain in connectionScopeFailureResponse and the challenge: {} marker in exchangeFailure. If producers always set description and the 403 variant has challenge: { scope?: string } | null, the route needs no fallback logic.
  4. Nits:
    • The identical challenge block in the open_auth_login and begin_auth_login catches could be one helper.
    • Most of scope-challenge-results.test.ts tests src/lib/scope-challenge.ts and could move to scope-challenge.test.ts; apiScopeChallenge is exported only for those tests.
    • The comment above classifyAuthContextError still describes 403 only as "not entitled to this project".

This branch was successfully deployed

1 active deployment
Preview — 4fd0dac4 Deployed Nov 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants