Skip to content

mcp: re-auth after token expiry reuses the stored DCR client with a new loopback port, so the AS rejects it with Callback URL mismatch #62331

Description

@john-sarria

Description

After the first successful sign-in, re-authenticating a remote MCP server always fails at the authorization server with:

{"error":"unauthorized_client","error_description":"Callback URL mismatch. http://127.0.0.1:59270/callback is not in the list of allowed callbacks."}

The authorization server (Auth0, at https://auth.example.com/) supports Dynamic Client Registration and issues no refresh token (scopes_supported: [] in the protected-resource metadata, so offline_access is never requested). The access token lives 24 h.

What the stored credential shows (from opencode.db → credential, secrets omitted):

"metadata": {
  "serverUrl": "https://mcp.example.com/mcp",
  "issuer": "https://auth.example.com/",
  "client": {
    "client_name": "opencode",
    "token_endpoint_auth_method": "none",
    "redirect_uris": ["http://127.0.0.1:64394/callback"]
  }
}

"refresh": ""

So:

  1. First sign-in: OpenCode binds a random loopback port (64394), registers a client via DCR with redirect_uris: ["http://127.0.0.1:64394/callback"], and stores that client.
  2. After 24 h the token expires. There is no refresh token, so OpenCode starts a new browser flow.
  3. It binds a new random port (59270) but reuses the stored DCR client, whose only registered redirect URI is the old port. Redirect URIs are matched exactly, so the authorization server rejects the request.

Every OAuth-without-refresh-token server ends up broken after the first token expiry, and the only way out is opencode mcp logout <name> followed by opencode mcp auth <name>, which forces a new registration. In OpenChamber the server also shows no "Sign in again" action in this state.

Expected: a re-authentication either reuses the port the stored client was registered with, or detects that the redirect URI differs from the stored client's redirect_uris and re-registers (DCR) before sending the authorization request. Either keeps re-auth working without a manual logout.

Possibly related, but not the same: #54421 (CIMD client.json redirect_uris vs. loopback callback, closed), #57130 (engine-owned loopback listener per attempt), #58319 (repeated re-auth when the token response has no scope).

Plugins

None

OpenCode version

2.2.5

Steps to reproduce

  1. Add a remote MCP server whose authorization server supports DCR and does not issue refresh tokens, for example:
    { "mcp": { "servers": { "my-mcp": { "type": "remote", "url": "https://mcp.example.com/mcp", "disabled": false } } } }
    (/.well-known/oauth-protected-resource → authorization_servers: ["https://auth.example.com/"]; the AS metadata includes registration_endpoint.)
  2. Sign in (opencode mcp auth my-mcp or the first connect). It works.
  3. Wait until the access token expires (24 h here), or set the stored expires to the past.
  4. Reconnect. The browser opens and the authorization server answers Callback URL mismatch. http://127.0.0.1:<new port>/callback is not in the list of allowed callbacks.
  5. opencode mcp logout my-mcp && opencode mcp auth my-mcp works again, until the next expiry.

Screenshot and/or share link

No response

Operating System

macOS (Darwin)

Terminal

OpenChamber (OpenCode background service) and the opencode mcp CLI

Activity

  1. opencodejr commented on Nov 6, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report. I was able to reproduce this on 2.2.5, and it still happens on the latest dev (3ec9b3b0a).

    To test it, the script below runs a local mock in place of the MCP server and its authorization server. The mock supports dynamic client registration, checks redirect URIs exactly (like Auth0) and never issues a refresh token. The script then runs opencode mcp auth twice, using curl as the browser:

    • First sign-in: OpenCode registers a client with http://127.0.0.1:40221/callback and signs in fine.
    • Second sign-in: OpenCode reuses that same client but listens on a new port and sends redirect_uri=http://127.0.0.1:43071/callback. The mock rejects it with Callback URL mismatch. http://127.0.0.1:43071/callback is not in the list of allowed callbacks., and the CLI keeps waiting for authorization.

    In the code, the sign-in reuses the stored client but picks a random callback port unless oauth.callback_port or oauth.redirect_uri is configured. It never checks the new callback URL against the client's registered redirect_uris.

    Until this is addressed, besides opencode mcp logout followed by opencode mcp auth, setting a fixed oauth.callback_port on the server should keep the callback URL the same between sign-ins. I haven't tested that workaround against your server.

    Related issues, none of which covers this problem:

    Reproduction script (repro.sh)
    #!/usr/bin/env bash
    # Reproduces #62331: second `opencode mcp auth` reuses the stored DCR client but binds a new loopback port.
    # Usage: bash repro.sh            (uses `opencode` from PATH)
    #        OC_DEV=/path/to/checkout bash repro.sh  (runs from source)
    set -u
    DIR=$(cd "$(dirname "$0")" && pwd)
    W=$(mktemp -d /tmp/opencode/r62331.XXXX); mkdir -p "$W/proj"
    export HOME=$W/home XDG_CONFIG_HOME=$W/cfg XDG_DATA_HOME=$W/data XDG_STATE_HOME=$W/state XDG_CACHE_HOME=$W/cache
    mkdir -p $HOME
    if [ -n "${OC_DEV:-}" ]; then
      OC=(bun --conditions=browser --preload=$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js $OC_DEV/packages/cli/src/index.ts)
    else OC=(opencode); fi
    cat > "$W/proj/opencode.json" <<J
    { "mcp": { "servers": { "mock": { "type": "remote", "url": "http://127.0.0.1:18999/mcp" } } } }
    J
    cat > "$W/mock-as.ts" <<'MOCK'
    // Mock MCP server + OAuth AS with DCR, exact redirect_uri matching, and no refresh tokens (like Auth0).
    const PORT = Number(process.env.MOCK_PORT ?? 18999)
    const origin = `http://127.0.0.1:${PORT}`
    const clients = new Map<string, string[]>()
    const codes = new Map<string, string>()
    let n = 0
    const json = (b: unknown, s = 200, h: Record<string, string> = {}) =>
      new Response(JSON.stringify(b), { status: s, headers: { "content-type": "application/json", ...h } })
    Bun.serve({
      port: PORT, hostname: "127.0.0.1",
      async fetch(req) {
        const url = new URL(req.url)
        const p = url.pathname
        console.log(req.method, p + url.search)
        if (p.startsWith("/.well-known/oauth-protected-resource"))
          return json({ resource: `${origin}/mcp`, authorization_servers: [origin], scopes_supported: [] })
        if (p.startsWith("/.well-known/oauth-authorization-server") || p.startsWith("/.well-known/openid-configuration"))
          return json({ issuer: origin, authorization_endpoint: `${origin}/authorize`, token_endpoint: `${origin}/token`,
            registration_endpoint: `${origin}/register`, response_types_supported: ["code"], grant_types_supported: ["authorization_code"],
            code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"] })
        if (p === "/register") {
          const body: any = await req.json()
          const id = `client-${++n}`
          clients.set(id, body.redirect_uris)
          console.log("REGISTERED", id, JSON.stringify(body.redirect_uris))
          return json({ ...body, client_id: id }, 201)
        }
        if (p === "/authorize") {
          const id = url.searchParams.get("client_id")!, ru = url.searchParams.get("redirect_uri")!
          const allowed = clients.get(id) ?? []
          if (!allowed.includes(ru)) {
            console.log("AUTHORIZE REJECTED", id, ru, "allowed:", JSON.stringify(allowed))
            return json({ error: "unauthorized_client", error_description: `Callback URL mismatch. ${ru} is not in the list of allowed callbacks.` }, 403)
          }
          const code = `code-${Math.random()}`; codes.set(code, id)
          console.log("AUTHORIZE OK", id, ru)
          return Response.redirect(`${ru}?code=${code}&state=${url.searchParams.get("state")}`, 302)
        }
        if (p === "/token") return json({ access_token: `at-${Math.random()}`, token_type: "Bearer", expires_in: 86400 })
        if (p === "/mcp") {
          if (!req.headers.get("authorization"))
            return json({ error: "unauthorized" }, 401, { "www-authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` })
          if (req.method !== "POST") return new Response(null, { status: 405 })
          const msg: any = await req.json()
          if (msg.id === undefined) 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: [] } : {}
          return json({ jsonrpc: "2.0", id: msg.id, result })
        }
        return new Response("nf", { status: 404 })
      },
    })
    console.log("mock listening", origin)
    MOCK
    bun "$W/mock-as.ts" > "$W/mock.log" 2>&1 & MOCK=$!
    sleep 1
    cd "$W/proj"
    # From source, the auto-spawned service lacks the preload flags, so start it ourselves.
    if [ -n "${OC_DEV:-}" ]; then "${OC[@]}" serve --service > "$W/serve.log" 2>&1 & SRV=$!; sleep 8; fi
    signin() {
      echo "=== sign-in #$1 ==="
      "${OC[@]}" mcp auth mock > "$W/auth$1.log" 2>&1 < /dev/null & P=$!
      URL=""
      for i in $(seq 1 60); do URL=$(grep -o 'http://127.0.0.1:18999/authorize[^ ]*' "$W/auth$1.log" | head -1); [ -n "$URL" ] && break; sleep 0.5; done
      echo "authorize URL redirect_uri: $(python3 -c "import sys,urllib.parse as u;print(u.parse_qs(u.urlparse(sys.argv[1]).query)['redirect_uri'][0])" "$URL")"
      echo "browser (curl -L) result:"; curl -s -L "$URL" | grep -oE "Callback URL mismatch[^\"]*|Authorization successful" | head -1
      sleep 3; kill $P 2>/dev/null; wait $P 2>/dev/null
      sed 's/\x1b\[[0-9;]*m//g' "$W/auth$1.log" | tail -4
    }
    signin 1
    signin 2
    echo "=== mock AS log ==="; grep -E "REGISTERED|AUTHORIZE" "$W/mock.log"
    "${OC[@]}" service stop >/dev/null 2>&1; kill $MOCK ${SRV:-} 2>/dev/null

    Run it: bash repro.sh

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions