GeezerVison is showing github.com — fix(core): refresh MCP OAuth tokens before they expire by rekram1-node · Pull Request #63008 · anomalyco/opencode
Conversation
Follows #62827.
Problem
MCP OAuth connections only refreshed after the server answered 401. Stored credentials keep expires, but nothing read it, so an expired access token was always sent once and rejected first. Provider logins already refresh when the token expires within 5 minutes.
Change
- When a connection backed by a stored credential sends a request and its access token expires within 5 minutes and has a refresh token, it refreshes first. This matches our provider logins; Claude Code, VS Code and Gemini CLI also refresh ahead of expiry.
- The check is in the provider's
tokens() in connectProvider (about 20 lines). It calls the SDK's auth() through the locked refresh from fix(core): refresh MCP OAuth tokens under the shared credential lock #62827, so rotation across processes stays correct; a flag keeps auth()'s own tokens() read from starting a second refresh.
- Requests that arrive while a refresh runs go out with the current token, which is still valid; the lock already guarantees a single refresh request. If the refresh fails, the request goes out with the current token and the existing 401 path still applies.
expires: 0 (no lifetime from the server) never refreshes ahead. Fixed the misleading comment about it in toCredential.
- No feature flag: bug fix on the existing refresh path.
Tests
packages/core/test/mcp-oauth.test.ts, real database and a fake token endpoint:
- A token expiring in 60 s is refreshed once before connecting, and the initialize request carries the new token.
- A token with 6 minutes left, and one with
expires: 0, are sent as is.
- Concurrent requests send one refresh; the others keep the still-valid token.
- An unreachable token endpoint leaves the current token in use and the credential unchanged.
Visual
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="72" viewBox="0 0 240 72" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
<style>
.b{transform-origin:40px 36px;animation:b 4s linear infinite}
.r{transform-origin:212px 36px;animation:r 4s ease-in-out infinite}
@keyframes b{0%{transform:scaleX(1)}70%{transform:scaleX(.62)}78%,100%{transform:scaleX(1)}}
@keyframes r{0%,62%{opacity:.25;transform:rotate(0)}72%{opacity:1}86%{opacity:1;transform:rotate(360deg)}100%{opacity:.25;transform:rotate(360deg)}}
@media (prefers-reduced-motion:reduce){.b,.r{animation:none}}
</style>
<rect x="40" y="28" width="140" height="16" rx="3" opacity=".35"/>
<rect class="b" x="40" y="28" width="140" height="16" rx="3" fill="currentColor" fill-opacity=".25" stroke="none"/>
<path d="M127 22v28" stroke-dasharray="3 3" opacity=".6"/>
<text x="127" y="64" font-size="9" fill="currentColor" stroke="none" text-anchor="middle" font-family="sans-serif" opacity=".7">5 min</text>
<circle cx="22" cy="36" r="9" opacity=".7"/>
<path d="M22 31v5l3 2" opacity=".7"/>
<g class="r"><path d="M219 36a7 7 0 1 1-2-5"/><path d="M218 26v5h-5"/></g>
</svg>
Added by the opencode bot (AI-generated).
Fixes #62199
Fixes #60269
Related: #50759
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good. I ran the PR's new tests against the base code: the token expiring in 60 s is sent unchanged and the concurrent-reads test times out. With the PR, all 37 tests in packages/core/test/mcp-oauth.test.ts pass, and typecheck:tsc passes for packages/core. The typecheck script itself fails on both base and PR because the check script it calls doesn't exist. I also checked in @modelcontextprotocol/client 2.4.0 that tokens() is called with no argument only when building the request headers (and before a 403 scope check, which is harmless), and that auth() always passes { issuer }, so the early refresh can't re-enter.
Public API: unchanged. Only the private Store.tokens type gains an optional context.
One non-blocking point inline: a failed early refresh is retried on every request until the token actually expires.
Fixes #62199
Fixes #60269
Related: #50759
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
),
|
|
|
),
|
|
|
).finally(() => {
|
|
|
ahead = undefined
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the early refresh fails, ahead is cleared, so the next request starts it again. The token endpoint may be unreachable, or discovery may fail because the server only gives its resource metadata URL in a 401 challenge, which this auth() call doesn't receive. In those cases every MCP request in the last 5 minutes before expiry first runs the full auth() lookup, which makes several round trips, and logs a warning. Could you remember the failure for this access token (or for a short cooldown) and let the existing 401 path handle it from there?
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My earlier point about retrying a failed early refresh on every request is not addressed yet. That thread stays open.
I checked this push with bun test test/mcp-oauth.test.ts in packages/core (41 pass) and typecheck:tsc (passes). On the base, the new ahead-of-expiry tests fail as before. I couldn't get the #60269 script to run end-to-end from source in this sandbox, because the background service wouldn't restart.
Public API: unchanged.
One new concern inline: requests that arrive during a refresh are sent with the stored token even when it has already expired.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
if (!oauth) return undefined
|
|
|
presented = oauth.refresh
|
|
|
return toTokens(oauth)
|
|
|
if (refreshing || !oauth.refresh || !oauth.expires || oauth.expires - Date.now() > REFRESH_AHEAD)
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
While refreshing is set, other requests get the stored token. That token is still valid only inside the 5-minute window. If it has already expired, for example after the machine wakes from sleep or when reconnecting hours later, parallel requests go out with an expired token. Servers that answer 401 recover through the locked refresh. Servers that answer 429 (#60269) or return a 200 token_expired tool result (#62199) fail those calls. Could requests wait for the refresh in progress when the token is already past expires, and keep the current token only when it is still valid?
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Closing in favor of a cleaner approach: a shared Credential.refresh used by provider logins and MCP, then MCP refresh-ahead on top of it. This version refreshes short-lived tokens on every request and can end in needs_auth on servers that only advertise their resource metadata in the 401.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Nov 10, 2026
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|