Repository navigation
fix(agent-core-v2): mark MCP servers needs-auth when a tool call returns 401 - #3846
Conversation
🦋 Changeset detectedLatest commit: b5be692 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
@codex review |
1 similar comment
|
@codex review |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb2f1065fe
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| await this.closeClient(entry); | ||
| this.emit(entry); |
There was a problem hiding this comment.
Recheck the entry after closing it
When a call-time 401 overlaps with an exposed reconnect or a config upsert, closeClient() yields after clearing the client, allowing reconnect() to advance this same entry or connect() to replace it. On resumption, this code still emits the stale or mutated entry and returns true; the tool wrapper can consequently direct the model to an authenticate tool that was never registered, or a stale needs-auth event can replace tools from the new configuration. Preserve/check an attempt or entry identity after the await, as connectOne() already does.
Useful? React with 👍 / 👎.
| try { | ||
| result = await callTool(client, args, context.signal); | ||
| } catch (error) { | ||
| if ((await options.onUnauthorized?.(error)) === true) { |
There was a problem hiding this comment.
Apply unauthorized handling to retried tool calls
When the initial call fails with a connection-closed or other transport error, retryAfterReconnect() may issue another call on the live or newly connected client; a 401 from either retry bypasses this sole onUnauthorized invocation and propagates while the server remains connected. This reproduces the original no-login failure when, for example, a stale connection is replaced by an anonymously initialized connection whose first real tool call requires OAuth. Route errors from every internal callTool attempt through the unauthorized callback.
Useful? React with 👍 / 👎.
…g and recheck entry after close
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b194aedc92
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| onUnauthorized: (error) => | ||
| this.mcpHandle.connectionManager.markNeedsAuth(serverName, error), |
There was a problem hiding this comment.
Bind unauthorized reports to the originating client
When a reconnect or config upsert advances this server before an older tool invocation reports its 401, this callback identifies the connection only by serverName, so markNeedsAuth accepts the currently connected entry and closes the replacement client. The new post-close isCurrent guard only covers an operation that overtakes markNeedsAuth; it does not cover this reverse ordering, which is fresh evidence that the earlier race remains. Pass the originating client or attempt identity here and reject the report unless it still matches the active entry.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7c8dde677
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| await this.closeClient(entry); | ||
| if (!this.isCurrent(entry, attemptId)) return false; | ||
| entry.status = 'needs-auth'; |
There was a problem hiding this comment.
Invalidate rejected OAuth tokens before offering reauthentication
When a server already has stored OAuth credentials but rejects them during tools/call because they were revoked or lack the required scope, this transition leaves those credentials intact. The generated authenticate tool subsequently calls beginAuthorization, whose auth flow treats the existing tokens as already authorized (oauth/service.ts lines 373–386) and merely reconnects with them (tools/auth.ts lines 65–75), causing the next tool call to return 401 again without ever presenting a browser login. Invalidate the rejected credentials, or otherwise force a fresh authorization flow, when entering needs-auth from a runtime 401.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7bcff4585b
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| isRemoteMcpConfig(entry.config) && | ||
| (await oauthService.hasTokens(name, entry.config.url)) | ||
| ) { | ||
| await oauthService.invalidate(name, entry.config.url, 'tokens'); | ||
| } |
There was a problem hiding this comment.
Recheck the connection after credential awaits
When reconnect() or connect() advances this server while hasTokens() or invalidate() is awaiting, the existing post-close identity check no longer protects this continuation: it emits the old needs-auth entry and returns true. With a config upsert, the replacement may already be connected, but this stale event makes AgentMcpService unregister its tools and install an authenticate tool instead. The newly added credential awaits create a fresh race window after the earlier guard, so revalidate the entry and attempt before emitting or reporting success.
Useful? React with 👍 / 👎.
| (await oauthService.hasTokens(name, entry.config.url)) | ||
| ) { | ||
| await oauthService.invalidate(name, entry.config.url, 'tokens'); | ||
| } |
There was a problem hiding this comment.
Preserve tokens produced by a concurrent refresh
When a tool request made with token A returns 401 while the scheduled refresh persists replacement token B, this unconditional invalidate(..., 'tokens') eventually calls OAuthTokenTransaction.clear(). If the refresh wins the transaction lock first, the handler deletes B even though the server never rejected it, discarding a valid refreshed grant and forcing an unnecessary interactive login; invalidate only the credentials associated with the rejected request or otherwise coordinate with the refresh.
Useful? React with 👍 / 👎.
…entry after credential awaits
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3afa637460
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (serverUrl === undefined || canonicalMcpOAuthResource(serverUrl) !== event.serverUrl) return; | ||
| if (event.type === 'tokens-invalidated') { | ||
| this.oauthService.forgetProvider(event.serverName, event.serverUrl); | ||
| if (entry.status === 'needs-auth') return; |
There was a problem hiding this comment.
Mark needs-auth before emitting token invalidation
When a runtime 401 rejects stored credentials, markNeedsAuth() calls oauthService.invalidate() while the entry is still connected. The resulting tokens-invalidated event reaches this check with that old status, so the handler starts reconnectAndJoin(); this advances the attempt before markNeedsAuth() resumes, causing its isCurrent check to return false and preventing the needs-auth event and authenticate tool from appearing. Set the state before invalidating, or suppress the reconnect caused by this internal invalidation.
Useful? React with 👍 / 👎.
| | StoredMcpOAuthTokens | ||
| | undefined; | ||
| if (tokens !== undefined) { | ||
| if (isConcurrentGrant(tokens)) return false; |
There was a problem hiding this comment.
Restore the connection after preserving a fresh grant
When tokens were saved within the ten-second grace window, this branch returns after closeClient() has already cleared and closed the active client. The entry therefore remains labeled connected with its old tools but resolved() returns undefined, and no token event reconnects it because tokens-saved events for connected entries are ignored. This occurs whenever the first call after login rejects a freshly issued token, as well as in the concurrent-refresh case this guard targets; inspect the grant before closing or reconnect before returning false.
Useful? React with 👍 / 👎.
…g rejected tokens
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a5318afe2e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| : undefined; | ||
| if (!this.isCurrent(entry, attemptId)) return false; | ||
| if (tokens !== undefined && isConcurrentGrant(tokens)) return false; | ||
| await this.closeClient(entry); |
There was a problem hiding this comment.
Prevent sibling retries from canceling needs-auth
When multiple tool calls are in flight, closing the shared client here can reject a sibling call with a connection-closed error; that call's retryAfterReconnect() then invokes reconnectForToolCall(), which advances attemptId and reconnects the server anonymously. This makes the current transition fail its following isCurrent check, so no needs-auth event or authenticate tool appears. Fresh evidence beyond the earlier external-reconnect race is that closeClient() itself can trigger the competing reconnect through another registered tool invocation.
Useful? React with 👍 / 👎.
| entry.enabledNames = undefined; | ||
| entry.rawTools = undefined; | ||
| if (tokens !== undefined && oauthService !== undefined && isRemoteMcpConfig(entry.config)) { | ||
| await oauthService.invalidate(name, entry.config.url, 'tokens'); |
There was a problem hiding this comment.
Invalidate only the token snapshot that returned 401
When a refresh saves token B after tokens() returned old token A but before this invalidation runs, the new grace check has only inspected A, and this unconditional invalidate(..., 'tokens') calls OAuthTokenTransaction.clear() and deletes the current B. Fresh evidence is the newly introduced gap between the token snapshot and invalidation, including the awaited client close; compare-and-clear against the rejected snapshot instead of clearing whichever grant is current.
Useful? React with 👍 / 👎.
| entry.enabledNames = undefined; | ||
| entry.rawTools = undefined; | ||
| if (tokens !== undefined && oauthService !== undefined && isRemoteMcpConfig(entry.config)) { | ||
| await oauthService.invalidate(name, entry.config.url, 'tokens'); |
There was a problem hiding this comment.
Emit needs-auth even if credential cleanup fails
If the OAuth store removal rejects here—for example because of a transient filesystem or permission error—the entry has already been changed to needs-auth and its client and tools cleared, but execution never reaches emit(entry). AgentMcpService therefore keeps the obsolete real tools registered and never installs the authenticate tool, while the tool call surfaces the storage error instead of recoverable login guidance; make cleanup failure-safe so the state transition is still published.
Useful? React with 👍 / 👎.
…olerate cleanup failures
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 41639b1039
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } catch (invalidateError) { | ||
| this.log.warn('mcp oauth token invalidation failed', { | ||
| server: name, | ||
| reason: | ||
| invalidateError instanceof Error ? invalidateError.message : String(invalidateError), |
There was a problem hiding this comment.
Prevent rejected tokens from short-circuiting reauthentication
When compare-and-clear throws after a runtime 401, such as during a transient document-store removal failure, this catch continues into the needs-auth emission while leaving the rejected token stored. The authenticate tool then calls beginAuthorization; the existing token makes the flow take the AlreadyAuthorizedError path (oauth/service.ts lines 374–387), and tools/auth.ts lines 65–75 reconnects with that same rejected token and reports success, so the next tool call returns 401 again. Fresh evidence beyond the earlier cleanup-failure comment is this new catch-and-continue path; retry or bypass the rejected token before offering the authenticate tool.
Useful? React with 👍 / 👎.
|
Re: codex P2 "Prevent rejected tokens from short-circuiting reauthentication" — no code change, the loop self-heals for transient cleanup failures. When the invalidation throws, the rejected token stays on disk and the authenticate tool takes the AlreadyAuthorizedError path: reconnect → next call 401 → markNeedsAuth runs again, and its credential block re-attempts the CAS invalidation (the rejected grant's obtained_at is well past the 10s freshness window, so it is never skipped as a concurrent grant). A transient store error is therefore cleared on the second cycle, after which beginAuthorization starts a real browser flow. The only non-converging case is a permanently broken credential store (disk full / permission), where persisting new tokens would fail anyway — the repeated auth errors are the honest signal there. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 958ae5eaf9
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| function isConcurrentGrant(tokens: StoredMcpOAuthTokens): boolean { | ||
| return ( | ||
| typeof tokens.obtained_at === 'number' && | ||
| Date.now() - tokens.obtained_at < CONCURRENT_GRANT_GRACE_MS |
There was a problem hiding this comment.
Compare grant age using the injected scheduler clock
When McpOAuthService uses a custom scheduler, providers stamp obtained_at with scheduler.now(), but this check compares that value with wall-clock Date.now(). If those clocks use different epochs, a freshly refreshed grant overlapping a 401 can be misclassified as old and invalidated, or an old rejected grant can be retained as concurrent. Compute the grace period with the same scheduler clock used to stamp the token.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f2bd2877b1
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
| function isConcurrentGrant(tokens: StoredMcpOAuthTokens, now: number): boolean { | ||
| return ( | ||
| typeof tokens.obtained_at === 'number' && now - tokens.obtained_at < CONCURRENT_GRANT_GRACE_MS |
There was a problem hiding this comment.
Reject future timestamps from the concurrent-grant window
When the scheduler clock moves backward after a token is stored—for example after a VM restore or wall-clock correction—now - tokens.obtained_at is negative and therefore always satisfies this upper-bound-only check. Every runtime 401 is then treated as overlapping a fresh grant, so markNeedsAuth() leaves the rejected credentials and real tools active until the clock catches up, preventing the authenticate tool from appearing. Require the computed age to be nonnegative before applying the grace window.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca7da288e1
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (!this.isCurrent(entry, attemptId)) return false; | ||
| if (rejectedGrant?.concurrent === true) return false; |
There was a problem hiding this comment.
Distinguish replacement grants from freshly rejected grants
When the connected client was created from a grant issued less than ten seconds ago and that grant itself is rejected—for example because the authorization omitted a required scope—peekRejectedGrant() labels the same grant as concurrent solely from its age, so this branch returns false. The wrapper then propagates the raw 401 while retaining the rejected credentials and real tools, and no authenticate tool appears unless another call happens after the grace window. Fresh evidence in the final code is that the branch now runs before closing the client, but it still cannot tell a concurrently refreshed grant from the fresh grant that produced the 401; compare against the credentials used by the failed request or retry the replacement grant before suppressing needs-auth.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9ed6739a04
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const entry = this.entries.get(name); | ||
| if (entry === undefined) return false; | ||
| if (entry.status !== 'connected' && entry.status !== 'needs-auth') return false; | ||
| if (!this.shouldMarkNeedsAuth(entry, error)) return false; |
There was a problem hiding this comment.
Require an HTTP 401 before invalidating OAuth credentials
When an MCP tool throws an application-level or JSON-RPC error whose message merely contains unauthorized (or an unrelated standalone 401), this newly added runtime path accepts it because isUnauthorizedLikeError() matches those strings. A server can therefore report an ordinary resource-permission failure such as “Unauthorized to edit this project,” and the manager will close the healthy connection, clear valid stored tokens, unregister every real tool, and incorrectly demand OAuth login. Restrict call-time handling to a verified HTTP 401/UnauthorizedError transport challenge rather than arbitrary tool-error text.
Useful? React with 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
Brings the fork's Rust engine up to the behaviors ported from upstream since 0.42.0, and moves the version to 2.0.0 to follow upstream (never bumped independently). Ports landed here, each recorded in packages/kimi-agent/ROADMAP.md §6.2 and scripts/upstream-v2-delta-allowlist.json with its own evidence: - MoonshotAI#3688 MCP media originals are preserved instead of flattened to a text preview: src/mcp/output.rs adds the content-block conversion and the result-to-delivery path, FileStore gains content-addressed writing, and the attachment reference is resolvable by Read/ReadMediaFile. - MoonshotAI#3734 streamed attempt state is invalidated when the LLM requester retries: a turn-scoped tool-call id ledger, streamed tool-call deltas from all three wire protocols, and an attempt guard that rolls back on every failure exit. - MoonshotAI#3697 steer interrupts a background-task wait — plus the blocking wait it needed. The engine's WaitFor had been routed through a synchronous local store, so a 5s wait returned in 6ms reporting a timeout; the toolset now waits on its own task runner, and a steer signal ends that wait early without cancelling the turn or its tasks. WaitFor gains the wait-any form. - MoonshotAI#3846 an MCP tool call returning 401 flips the server to needs-auth. - MCP servers connect once per process, starting at startup. - AI session titles are generated through the managed chat_title tool. - The abort fix in the preceding commit. Also refreshes the ROADMAP evidence blocks, the upstream delta allowlist, the bilingual docs those behaviors surface in, and the TUI rendering for the new wait status.
Step 6 of the incremental sync to 2.1.1: 29 upstream commits over 370 files. 35 conflicts, concentrated in the TUI layer where the fork's i18n and pi-tui work sits on top of upstream's message components. Upstream's changes in this step, all absorbed: - mermaid code blocks render as terminal diagrams, with a new `MermaidRenderMode` preference and a settings entry (MoonshotAI#3851) - Windows CLI binaries are signed with Azure Artifact Signing (MoonshotAI#3858) - MCP servers flip to needs-auth when a tool call returns 401, and the rejected grant's tokens are invalidated (MoonshotAI#3846) - the `/desktop` slash command and the `install-app` subcommand (MoonshotAI#3849) - skill scopes: `SkillScope` joins the catalog types and custom-theme becomes tui-only (MoonshotAI#3843) - Windows 8.3 short paths are watched through their long form (MoonshotAI#3840) - images upload as file references for Kimi models (MoonshotAI#3784) - `/usage` and `/status` no longer prompt for login before the first message (MoonshotAI#3818) - completed subagent scopes are evicted behind an LRU cache (MoonshotAI#3778) - the human layer's request/recovery stage names were aligned (MoonshotAI#3766) and its names clarified (MoonshotAI#3727) - WebBridge's display name became "Kimi Browser Extension" (MoonshotAI#3803) - diff code blocks are highlighted (MoonshotAI#3802) - feedback surveys are gated by the resolved kfc model id (MoonshotAI#3795) Fork behaviour that had to survive: - the i18n layer: every new upstream string went through `t()` with en/zh locale entries (mermaid preference, WebBridge intro, usage panel), and the fork's locale JSONs were regenerated - the pi-tui intent cards and the fork's local Markdown component, kept over upstream's pi-tui Markdown import in the message components - the 128 KiB `max_completion_tokens` cap on the kimi trait - the fork's media tool folding (read-media-file) and the `isMediaUploadAuthError` rename carried through - the Bun toolchain: flake.nix keeps `impureEnvVars`, the native build workflow keeps the Bun steps while taking upstream's Azure signing env block, and 05-verify.mjs verifies the checksum before the Authenticode branch - proactiveMediaEviction in the LLM requester, after upstream's warning dispatch - the fork's stricter `isUnauthorizedLikeError` (no message-regex fallback) and its OAuth token transaction This merge also fixes a fork bug the new upstream tests exposed: the TUI's background-task handler had been switched to the v2 `task.*` event spelling during the v1→v2 migration, but the SDK's event mapper translates those back to `background.task.*` before delivery (the fork's own `notify.ts` already listened for the translated names), so the handler had been dead code at runtime. The handler and the three test fixtures that fed it now use `background.task.*` again. Test expectations re-pinned where the fork's shape differs from upstream's: - `assistant-message.test.ts` reads the local Markdown's `sourceText` instead of pi-tui's `text` - the new `markdown.test.ts` calls `setPalette(palette, family)`, the fork's two-argument signature - `choice-picker.test.ts` asserts the mermaid entry, because the fork's longer settings list pushes `upgrade` past the 8-row page - "invalidates stored OAuth tokens when a runtime 401 fails the refresh": the fork's token transaction removes the revoked tokens while the refresh fails, and the transport closes before the caller can flip the entry into needs-auth, so the server ends up failed rather than needs-auth. The security-relevant half (stale tokens are gone) still holds; the status difference is a known gap to revisit. Verified: typecheck clean across every package and app; full suite 17594 passed / 81 skipped / 1 todo. The four failures under parallel load (rpc-events ×2, taskManager ×2) pass in isolation — load-induced flakes, not regressions.
…ks for sign-in; `hermes mcp login` sets up OAuth for it Port from MoonshotAI/kimi-code#3846. Some MCP servers (Hyper3D) serve initialize and tools/list without auth and return 401 + WWW-Authenticate only on tools/call — the MCP authorization spec's runtime challenge. Hermes only knew about 401s on OAuth-configured servers, so this shape had two dead ends: - Runtime: with mcp >= 2.0 Streamable HTTP the SDK folds any non-2xx tools/call into a generic INTERNAL_ERROR ("Server returned an error response") and the status is lost. The model saw a plain tool error and retried. The owned httpx client now records a 401 on the server task (_make_unauthorized_recorder, anonymous servers only — with OAuth attached the SDK's auth flow owns 401s); the auth recoverer consumes it once (_swallowed_401) and returns the structured needs_reauth error. For a url-only server the wording says "accepted the connection anonymously but rejected this call with 401 — requires sign-in", not "re-authentication" of credentials that never existed. - CLI: `hermes mcp login <s>` refused a server without `auth: oauth` and sent the user through remove + add. For a url-only entry (no auth, no headers) it now runs the OAuth flow and persists `auth: oauth` once a token lands. A server with static headers is still refused: its 401 means the token is wrong. Live repro against a Streamable HTTP server that 401s tools/call: before — {"error": "MCP call failed: MCPError: Server returned an error response"} after — {"error": "MCP server 'hyper' accepted the connection anonymously but rejected this call with 401 — ...Run `hermes mcp login hyper`...", "needs_reauth": true, "server": "hyper"} `hermes mcp login hyper`: before "not configured for OAuth"; after enters the flow.
Related Issue
No linked issue — the problem is described below.
Problem
Some MCP servers (e.g. Hyper3D) allow anonymous
initializeandtools/listbut return401 + WWW-Authenticateontools/call— a shape the MCP authorization spec explicitly anticipates (runtime auth challenges + RFC 9728 discovery). kimi-code only probed for 401 during the initial handshake, so these servers connected anonymously and the call-time 401 surfaced as a plain tool error: the server never enteredneeds-auth, noauthenticatetool appeared, and/mcp-config loginhad nothing to run. There was no way to log in at all.What changed
When a tool call fails with a transport-level 401, the server now flips into
needs-authand the existing syntheticmcp__<server>__authenticateflow takes over (browser OAuth → reconnect → real tools back).agent/mcp/tools/mcp.ts): the wrapper consults the connection manager viaonUnauthorizedat all three call points (initial call, liveness-probe retry, post-reconnect call), reporting the client the call was made on. On a flip it throws guidance pointing the model at the authenticate tool instead of doing a pointless reconnect-retry.mcpCore/connection-manager.tsmarkNeedsAuth): guards unchanged from the startup probe (remote only, nobearerTokenEnvVar, no pinned static headers,McpErrorapplication errors excluded); rejects stale reports whose originating client is no longer current; rechecks attempt identity after every await so concurrent reconnects/config upserts can't produce stale state; flips toneeds-authbefore invalidating so the OAuth event listener leaves the flip alone.mcpCore/oauth/): a concurrently minted grant (newer than the connection within a short grace window, compared with the scheduler clock) is preserved rather than flipped; otherwise the rejected grant is cleared via compare-and-clear (OAuthTokenTransaction.clearIfCurrent, only removes tokens if the store still matches the rejected snapshot), so a valid grant minted by another session/refresh is never deleted. Cleanup failures are tolerated — the flip is still published.workspaceMcpService): skips the reconnect forneeds-authentries on token invalidation (their state is owned by the pending login flow).Tests cover the core contract: flip on call-time 401 (real MCP server that 401s only
tools/call), rejected-token invalidation through the real401 → refresh → invalid_grantSDK flow, application-level errors being ignored, and the CAS primitive. All previous behavior (connect-time probing, static-header/bearer servers, reconnect-retry for transport failures) is unchanged.Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.