Skip to content

Commit 54f904d

Browse files
cliffhallclaude
andcommitted
fix(core): key the connect retry leg off attempt, bound nested recoveries
Second-pass review findings on #1809: - The satisfied-recovery short-circuit keyed off live connection status, so an onclose landing between the nested connect() and the retry leg fell through to the rejected handshake promise and reported the stale 401 as the reason the session died. withDirectAuthRecovery now passes `attempt` to its operation, so connect() identifies the retry leg structurally and reports the teardown when the recovered session is already gone. - Bound nested silent recoveries. The `attempt >= 1` guard is per-call and a satisfied outcome recovers via a nested connect() with a fresh counter, so a server that keeps rejecting freshly refreshed tokens recursed without bound. Counted across the nesting boundary, capped at 3. - Strengthen the regression test (server info populated by the nested connect, no duplicate statusChange) and add the two missing cases: a failed reconnect still rejects, and the recursion bound terminates. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016S7h83UKNQ7kvSiFDNksCt
1 parent fc0395e commit 54f904d

2 files changed

Lines changed: 112 additions & 9 deletions

File tree

‎clients/web/src/test/core/mcp/inspectorClient-satisfied-recovery-connect.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,19 @@ describe("InspectorClient connect() after a silently satisfied auth challenge",
114114
client.addEventListener("connect", () => {
115115
connectEvents += 1;
116116
});
117+
let connectedStatusEvents = 0;
118+
client.addEventListener("statusChange", (event) => {
119+
if (event.detail === "connected") connectedStatusEvents += 1;
120+
});
117121

118122
await expect(client.connect()).resolves.toBeUndefined();
119123
expect(client.getStatus()).toBe("connected");
124+
// The outer call skips fetchServerInfo(); this pins that the nested connect
125+
// populated it, i.e. the early return loses nothing.
126+
expect(client.getServerInfo()?.name).toBe("recovered-server");
127+
// The duplicate statusChange("connected") is suppressed with the duplicate
128+
// connect event.
129+
expect(connectedStatusEvents).toBe(1);
120130
expect(transportsCreated).toBe(2);
121131
// The nested connect() already ran the post-connect block; the outer call
122132
// must not run it a second time (a duplicate `connect` re-triggers every
@@ -125,4 +135,56 @@ describe("InspectorClient connect() after a silently satisfied auth challenge",
125135

126136
await client.disconnect();
127137
});
138+
139+
it("still rejects when the reconnect underneath the recovery fails", async () => {
140+
// The short-circuit must not mask a failed re-handshake: the nested
141+
// connect() throws, so connect() rejects and the status lands on "error".
142+
const client = new InspectorClient(
143+
{ type: "streamable-http", url: "https://mcp.example/mcp" },
144+
{
145+
environment: {
146+
transport: () => ({ transport: new ChallengingTransport() }),
147+
oauth: oauthEnvironment(),
148+
},
149+
oauth: { clientId: "satisfied-recovery-test" },
150+
directAuthRecovery: true,
151+
},
152+
);
153+
vi.spyOn(client, "handleAuthChallenge").mockResolvedValue({
154+
kind: "satisfied",
155+
});
156+
157+
await expect(client.connect()).rejects.toThrow();
158+
expect(client.getStatus()).not.toBe("connected");
159+
});
160+
161+
it("bounds nested recoveries when refreshed credentials keep being rejected", async () => {
162+
// Every transport challenges and every challenge reports satisfied, so each
163+
// recovery reconnects into a fresh challenge. Recovery is counted across
164+
// the nesting boundary, so this terminates instead of recursing forever.
165+
let transportsCreated = 0;
166+
const client = new InspectorClient(
167+
{ type: "streamable-http", url: "https://mcp.example/mcp" },
168+
{
169+
environment: {
170+
transport: () => {
171+
transportsCreated += 1;
172+
return { transport: new ChallengingTransport() };
173+
},
174+
oauth: oauthEnvironment(),
175+
},
176+
oauth: { clientId: "satisfied-recovery-test" },
177+
directAuthRecovery: true,
178+
},
179+
);
180+
vi.spyOn(client, "handleAuthChallenge").mockResolvedValue({
181+
kind: "satisfied",
182+
});
183+
184+
await expect(client.connect()).rejects.toBeInstanceOf(AuthChallengeError);
185+
// One transport per connect attempt: the initial one plus the three
186+
// bounded nested recoveries (MAX_NESTED_AUTH_RECOVERIES), not an unbounded
187+
// chain.
188+
expect(transportsCreated).toBe(4);
189+
});
128190
});

‎core/mcp/inspectorClient.ts‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,22 @@ export class InspectorClient extends InspectorClientEventTarget {
535535
private transportConfig: MCPServerConfig;
536536
/** null until first transport is built; then true for in-process OAuth runners. */
537537
private directAuthRecoveryActive: boolean | null = null;
538+
/**
539+
* Nesting depth of in-flight silent auth recoveries. `withDirectAuthRecovery`
540+
* bounds retries per call (`attempt >= 1`), but a satisfied outcome recovers
541+
* by running a *nested* `connect()`, which starts its own recovery with a
542+
* fresh counter — so a server that keeps answering 401 with freshly refreshed
543+
* tokens would recurse without bound. Counted across the nesting boundary and
544+
* capped at {@link InspectorClient.MAX_NESTED_AUTH_RECOVERIES}.
545+
*/
546+
private authRecoveryDepth = 0;
547+
/**
548+
* Cap on nested silent recoveries. One is the normal case (challenge →
549+
* refresh → reconnect); a couple more absorb a legitimately re-challenged
550+
* reconnect. Beyond that the credentials are not fixing the challenge, so the
551+
* challenge is surfaced to the caller instead of recovered again.
552+
*/
553+
private static readonly MAX_NESTED_AUTH_RECOVERIES = 3;
538554
/**
539555
* Opt-in from {@link InspectorClientOptions.directAuthRecovery}: when true and
540556
* the live transport is direct (not {@link RemoteClientTransport}), RPCs use
@@ -1809,10 +1825,10 @@ export class InspectorClient extends InspectorClientEventTarget {
18091825
// Set when a satisfied auth recovery already completed a full connect()
18101826
// underneath us — see the short-circuit in `runConnect`.
18111827
let recoveredByNestedConnect = false;
1812-
const runConnect = async (): Promise<void> => {
1813-
if (this.status === "connected") {
1814-
// We are the *retry* leg of `withDirectAuthRecovery`: the challenge
1815-
// was satisfied silently (e.g. a refresh token), so
1828+
const runConnect = async (attempt: number): Promise<void> => {
1829+
if (attempt > 0) {
1830+
// The *retry* leg of `withDirectAuthRecovery`: the challenge was
1831+
// satisfied silently (e.g. a refresh token), so
18161832
// `reconnectAfterAuthRecovery()` has already run a complete
18171833
// `connect()` — handshake, server info, `connect` event and all.
18181834
// `connectPromise` is created once, outside this closure, so
@@ -1821,7 +1837,17 @@ export class InspectorClient extends InspectorClientEventTarget {
18211837
// circuit instead, and let the caller skip the post-connect block the
18221838
// nested connect already ran (dispatching a second `connect` event
18231839
// would re-trigger every list-state manager's refresh).
1840+
//
1841+
// Keyed off the leg rather than live status: an `onclose` landing
1842+
// between the nested connect and here would flip status off
1843+
// "connected" and fall through to the rejected `connectPromise`,
1844+
// reporting the stale handshake 401 as the reason the session died.
18241845
recoveredByNestedConnect = true;
1846+
if (this.status !== "connected") {
1847+
throw new Error(
1848+
"Connection closed during authorization recovery, after re-authorizing successfully",
1849+
);
1850+
}
18251851
return;
18261852
}
18271853
if (connectTimeoutMs > 0) {
@@ -5336,19 +5362,29 @@ export class InspectorClient extends InspectorClientEventTarget {
53365362
}
53375363

53385364
private async withDirectAuthRecovery<T>(
5339-
operation: () => Promise<T>,
5365+
operation: (attempt: number) => Promise<T>,
53405366
context?: { method?: string; toolName?: string },
53415367
attempt = 0,
53425368
): Promise<T> {
53435369
try {
5344-
return await operation();
5370+
// `attempt` is passed through so an operation can tell the first leg from
5371+
// the post-recovery retry leg — `connect()` needs that distinction, and
5372+
// live connection status is a racy proxy for it.
5373+
return await operation(attempt);
53455374
} catch (err) {
53465375
if (attempt >= 1 || !this.usesDirectAuthRecovery()) {
53475376
throw err;
53485377
}
53495378
if (!isAuthChallengeError(err)) {
53505379
throw err;
53515380
}
5381+
if (
5382+
this.authRecoveryDepth >= InspectorClient.MAX_NESTED_AUTH_RECOVERIES
5383+
) {
5384+
// Refreshed credentials are not satisfying the server: recovering again
5385+
// would just re-enter the nested connect() below. Surface the challenge.
5386+
throw err;
5387+
}
53525388
const challenge = parseAuthChallengeFromError(err, context);
53535389
/* v8 ignore next 3 -- defensive: parseAuthChallengeFromError shares isAuthChallengeError's checks, so it always returns a truthy challenge once that guard passes */
53545390
if (!challenge) {
@@ -5367,7 +5403,12 @@ export class InspectorClient extends InspectorClientEventTarget {
53675403
if (this.activeToolCallAbortController) {
53685404
this.activeToolCallAbortController = undefined;
53695405
}
5370-
await this.reconnectAfterAuthRecovery();
5406+
this.authRecoveryDepth += 1;
5407+
try {
5408+
await this.reconnectAfterAuthRecovery();
5409+
} finally {
5410+
this.authRecoveryDepth -= 1;
5411+
}
53715412
this.dispatchTypedEvent("authChallengeRecovered", { challenge });
53725413
return this.withDirectAuthRecovery(operation, context, attempt + 1);
53735414
}
@@ -5390,11 +5431,11 @@ export class InspectorClient extends InspectorClientEventTarget {
53905431
}
53915432

53925433
private async invokeMcpClient<T>(
5393-
operation: () => Promise<T>,
5434+
operation: (attempt: number) => Promise<T>,
53945435
context?: { method?: string; toolName?: string },
53955436
): Promise<T> {
53965437
if (!this.usesDirectAuthRecovery()) {
5397-
return operation();
5438+
return operation(0);
53985439
}
53995440
return this.withDirectAuthRecovery(operation, context);
54005441
}

0 commit comments

Comments
 (0)