Skip to content

mcp: OAuth token refresh omits scope, so Microsoft Entra ID rejects it (AADSTS90023) #66175

Done

Description

@aguileramontenegro

Description

OpenCode signs in to a remote MCP server correctly, then fails about an hour later, when the access token expires.

For an Entra ID app where the client and the resource are the same registration, Microsoft Entra ID rejects a refresh request that has no scope:

error=invalid_request
AADSTS90023: The request is not valid. The refresh token used contains only policy offers
and the scope parameter is not specified.

The authorization_code exchange succeeds (HTTP 200, hasRefreshToken=true, expiresIn=3599) and the server connects. Every refresh_token exchange returns HTTP 400, and the server ends in failed.

Cause: packages/core/src/mcp/oauth.ts, exchange(), calls refreshAuthorization(...) without scope:

const tokens = await refreshAuthorization(server.authorizationServerUrl, {
  metadata: server.authorizationServerMetadata,
  clientInformation: client,
  refreshToken: input.current.refresh,
  resource,
  fetchFn,
})

The granted scope is already stored (credential.metadata.scope), and the MCP client SDK already supports it: refreshAuthorization takes scope?: string, and AuthProvider.scopeForRefresh exists for this case. RFC 6749 §6 makes scope optional, but Entra requires it for these grants.

Proposed fix:

scope: input.current.metadata?.scope ?? oauth?.scope,

Verified manually against the same refresh token: adding scope returns HTTP 200.

Secondary issue: invalid_request is not in the rejections set (InvalidGrant, InvalidClient, UnauthorizedClient), so the failure maps to TemporarilyUnavailable and the server stays failed indefinitely. /mcps never offers to sign in again, and the dead credential is kept.

Plugins

No response

OpenCode version

2.4.1

Steps to reproduce

  1. Configure a remote MCP server with a pre-registered Entra client where client_id == resource:
    URL: https://partner.api.bingads.microsoft.com/ext/mcp/vnext
    scope: https://ads.microsoft.com/msads.manage offline_access
  2. Sign in through /mcps. The server connects and lists its tools.
  3. Wait ~60 minutes for the access token to expire (or force a refresh).
  4. Check ~/.local/share/opencode/log/opencode.log:

message="mcp oauth authorization completed" ... hasRefreshToken=true expiresIn=3599
message="mcp connected" server=microsoft-ads tools=14
message="mcp oauth request started" ... operation=refresh
message="mcp oauth request rejected" status=400 error=invalid_request
message="AADSTS90023: ... The refresh token used contains only policy offers
and the scope parameter is not specified ..."
message="mcp connect failed" status.status=failed
status.error="Could not refresh the OAuth token: invalid_request (temporarily_unavailable)"

Screenshot

No response

Operating System

Ubuntu 24.04.5 LTS (VM)

Terminal

SSH + VS Code Remote

Activity

  1. added
    area/mcp
    type/bug
    version/v2
    on Nov 24, 2026
  2. Guembri01 commented on Nov 24, 2026

    @Guembri01

    Taking this one. The refresh exchange at packages/core/src/mcp/oauth.ts:391 drops the granted scope, and the SDK already accepts it (refreshAuthorization(url, { …, scope, … })); the granted scope is stored at :257. One-line fix plus a test that asserts the token endpoint receives it — PR coming.

  3. opencodejr commented on Nov 24, 2026

    @opencodejr
    Contributor

    Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

    Thanks for the detailed report and analysis. I reproduced this on 2.4.1 with a mock server standing in for Entra ID. The mock rejects any refresh without scope with invalid_request / AADSTS90023, as you describe Entra doing.

    • The oauth config sets client_id and scope, sign-in works, and the server connects.
    • After the access token expired, every refresh_token request reached the token endpoint with only grant_type, refresh_token, resource and client_id. The configured scope was not sent.
    • The server then ended as failed: Could not refresh the OAuth token: invalid_request (temporarily_unavailable) and stayed there. It did not ask to sign in again.

    The same happens on the latest dev (d65b5d2) run from source. The script below reproduces it end to end, mock server included.

    Related issues:

    Reproduction script (repro.sh)
    #!/bin/sh
    # Reproduces #66175: the MCP OAuth refresh_token request carries no `scope`, an Entra-like
    # authorization server rejects it with invalid_request (AADSTS90023), and the server ends `failed`.
    # Starts a mock MCP + Entra-like authorization server (port 18765) and an opencode server (port 4199).
    # Needs: bun, curl, `opencode` on PATH (or OPENCODE="bun ... packages/cli/src/index.ts").
    set -u
    OC=${OPENCODE:-opencode}
    WORK=$(mktemp -d)
    export HOME=$WORK/home OPENCODE_PASSWORD=repro-password
    mkdir -p "$HOME" "$WORK/proj"
    cat > "$WORK/proj/opencode.json" <<'EOF'
    {
      "$schema": "https://opencode.ai/config.json",
      "mcp": { "servers": { "entra-mock": { "type": "remote", "url": "http://127.0.0.1:18765/mcp",
        "oauth": { "client_id": "11111111-2222-3333-4444-555555555555", "scope": "api://mock/.default offline_access" } } } }
    }
    EOF
    cat > "$WORK/mock-as.ts" <<'MOCK'
    // Mock MCP server + OAuth authorization server that behaves like Entra ID for the
    // case in #66175: a refresh_token grant without `scope` is rejected with AADSTS90023.
    const PORT = Number(process.env.MOCK_PORT ?? 18765)
    const BASE = `http://127.0.0.1:${PORT}`
    let n = 0
    const valid = new Map<string, number>() // token -> expiry (ms)
    const log = (...a: unknown[]) => console.log(new Date().toISOString(), ...a)
    
    const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
      new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } })
    
    Bun.serve({
      port: PORT,
      hostname: "127.0.0.1",
      async fetch(req) {
        const url = new URL(req.url)
        if (url.pathname.startsWith("/.well-known/oauth-protected-resource"))
          return json({ resource: `${BASE}/mcp`, authorization_servers: [BASE] })
        if (url.pathname.startsWith("/.well-known/oauth-authorization-server") || url.pathname.startsWith("/.well-known/openid-configuration"))
          return json({
            issuer: BASE,
            authorization_endpoint: `${BASE}/authorize`,
            token_endpoint: `${BASE}/token`,
            response_types_supported: ["code"],
            grant_types_supported: ["authorization_code", "refresh_token"],
            code_challenge_methods_supported: ["S256"],
            token_endpoint_auth_methods_supported: ["none"],
          })
        if (url.pathname === "/authorize") {
          log("AUTHORIZE", url.search)
          const to = new URL(url.searchParams.get("redirect_uri")!)
          to.searchParams.set("code", "code-" + ++n)
          to.searchParams.set("state", url.searchParams.get("state")!)
          return Response.redirect(to.toString(), 302)
        }
        if (url.pathname === "/token") {
          const body = new URLSearchParams(await req.text())
          log("TOKEN", Object.fromEntries([...body].map(([k, v]) => [k, k === "code_verifier" ? "…" : v])))
          const grant = body.get("grant_type")
          if (grant === "refresh_token" && !body.get("scope"))
            return json(
              {
                error: "invalid_request",
                error_description:
                  "AADSTS90023: The request is not valid. The refresh token used contains only policy offers and the scope parameter is not specified.",
              },
              400,
            )
          const access = "at-" + ++n
          valid.set(access, Date.now() + 20_000)
          // short lifetime so the next connection must refresh (OpenCode refreshes 30 s ahead of expiry)
          return json({ access_token: access, token_type: "Bearer", expires_in: 20, refresh_token: "rt-1" })
        }
        if (url.pathname === "/mcp") {
          const auth = req.headers.get("authorization")?.replace(/^Bearer /, "")
          if (!auth || !((valid.get(auth) ?? 0) > Date.now()))
            return new Response("unauthorized", {
              status: 401,
              headers: { "www-authenticate": `Bearer resource_metadata="${BASE}/.well-known/oauth-protected-resource/mcp"` },
            })
          if (req.method !== "POST") return new Response(null, { status: 405 })
          const msg = await req.json()
          if (!("id" in msg)) return new Response(null, { status: 202 })
          const result =
            msg.method === "initialize"
              ? { protocolVersion: msg.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "mock", version: "1" } }
              : msg.method === "tools/list"
                ? { tools: [{ name: "ping", description: "ping", inputSchema: { type: "object", properties: {} } }] }
                : {}
          return json({ jsonrpc: "2.0", id: msg.id, result })
        }
        return new Response("not found", { status: 404 })
      },
    })
    log("mock listening on", BASE)
    MOCK
    cd "$WORK/proj"
    $OC --version
    bun "$WORK/mock-as.ts" > "$WORK/mock.log" 2>&1 & MOCK=$!
    sleep 1
    
    echo "== 0. start a server"
    $OC serve --port 4199 --print-logs > "$WORK/serve.out" 2>&1 & SERVE=$!
    for i in $(seq 1 60); do grep -q 'server listening' "$WORK/serve.out" && break; sleep 1; done
    echo "== 1. sign in (the mock authorization endpoint approves at once)"
    $OC mcp auth entra-mock --server http://127.0.0.1:4199 > "$WORK/auth.out" 2>&1 & AUTH=$!
    for i in $(seq 1 120); do grep -q '18765/authorize' "$WORK/auth.out" && break; sleep 1; done
    curl -sL -o /dev/null "$(grep -o 'http://127.0.0.1:18765/authorize[^ ]*' "$WORK/auth.out" | head -1)"
    wait $AUTH; grep -E 'Connected|Done|rror' "$WORK/auth.out"
    
    echo "== 2. wait for the 20 s access token to expire"
    sleep 25
    
    echo "== 3. restart the server so it reconnects with the stored credential, then list MCP status"
    kill $SERVE; wait $SERVE 2>/dev/null; : > "$WORK/serve.out"
    $OC serve --port 4199 --print-logs > "$WORK/serve.out" 2>&1 & SERVE=$!
    for i in $(seq 1 60); do grep -q 'server listening' "$WORK/serve.out" && break; sleep 1; done
    $OC mcp list --server http://127.0.0.1:4199 >/dev/null; sleep 5
    $OC mcp list --server http://127.0.0.1:4199
    
    echo "== refresh requests the token endpoint received:"
    grep -A5 'grant_type: "refresh_token"' "$WORK/mock.log" | head -6
    echo "== opencode log:"
    grep -E 'oauth request rejected|connect failed' "$WORK/serve.out" | head -3 | sed 's/ http.span.*//'
    kill $SERVE $MOCK 2>/dev/null

    Run it: sh repro.sh

  4. added
    status/repro-simulated
    on Nov 24, 2026
  5. aguileramontenegro commented on Nov 27, 2026

    @aguileramontenegro
    Author

    Thanks for the fix — I verified it landed in dev as described: exchange() in packages/core/src/mcp/oauth.ts now reads the granted scope from the credential (input.current.metadata?.scope, falling back to the configured oauth.scope) and passes it to refreshAuthorization, which is exactly what Entra requires (AADSTS90023). The tests covering the refresh body are in place too.

    Two things worth flagging before this is fully closed for affected users:

    1. No release contains the fix yet. The latest release is v2.4.2 (Nov 26), and the PR merged Nov 27, so it is only on dev. Until a release ships it, anyone on a released build still needs the proxy/sign-in-again workaround.

    2. The secondary issue from the report is still open on dev. The rejections set is unchanged — it still only contains InvalidGrant, InvalidClient and UnauthorizedClient. Any other server that answers a failed refresh with invalid_request (or invalid_scope) still maps to TemporarilyUnavailable, leaving the server permanently failed with no re-auth offered in /mcps and the dead credential kept. For Entra the symptom disappears only because the refresh now succeeds; the misclassification itself is untouched. Since it affects refresh failures generally and not just this scope case, it seems worth tracking as its own issue rather than assuming this one covers it.

    For context, I ran the server through a local proxy (own grant, always sends scope on refresh) since Nov 24, so I will keep that until a release with the fix is out, then verify a session survives more than 60 minutes before removing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/mcpplatform/linuxstatus/repro-simulatedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions