Skip to content

Commit fc0395e

Browse files
cliffhallclaude
andcommitted
fix(core): resolve connect() when auth recovery is satisfied silently
Review findings on #1809: - connect() built its handshake promise once, outside the runConnect closure withDirectAuthRecovery retries. On a "satisfied" outcome the recovery runs a complete nested connect() via reconnectAfterAuthRecovery(), so the retry leg re-awaited the already-rejected promise and rejected a connect() whose client was in fact connected. Short-circuit the retry when already connected, and skip the post-connect block the nested connect already ran (a duplicate `connect` event re-triggers every list-state manager's refresh). - Document the accepted 403 side effect of enabling interceptAuthChallenges with no stored tokens, and why every `{ pin }` counts as probing. - Replace the private-method double cast in the era-probe test with an observable assertion on the transport options, and split the non-auth failure case per era instead of a message alternation that passed either way. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016S7h83UKNQ7kvSiFDNksCt
1 parent 66cd6ce commit fc0395e

3 files changed

Lines changed: 261 additions & 51 deletions

File tree

‎clients/web/src/test/core/mcp/inspectorClient-era-probe-auth.test.ts‎

Lines changed: 94 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,44 @@
1-
import { describe, it, expect } from "vitest";
1+
import { describe, it, expect, vi } from "vitest";
22
import {
33
AuthChallengeError,
44
AuthRecoveryRequiredError,
55
} from "@inspector/core/auth/challenge.js";
66
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
77
import { eraToVersionNegotiation } from "@inspector/core/mcp/types.js";
8+
import type { CreateTransportOptions } from "@inspector/core/mcp/types.js";
9+
import { BrowserOAuthStorage } from "@inspector/core/auth/browser/storage.js";
810
import type { JSONRPCMessage, Transport } from "@modelcontextprotocol/client";
911

12+
/**
13+
* Minimal transport whose `send` rejects — which is what the probe's
14+
* `server/discover` exchange hits. The remote path rejects with
15+
* `AuthRecoveryRequiredError` (after the backend intercepted the 401 and
16+
* `handleAuthChallenge` returned `interactive`); a direct transport with
17+
* challenge interception rejects with `AuthChallengeError`.
18+
*/
19+
class RejectingTransport implements Transport {
20+
onclose?: () => void;
21+
onerror?: (error: Error) => void;
22+
onmessage?: (message: JSONRPCMessage) => void;
23+
24+
private readonly rejection: Error;
25+
26+
// A parameter property would trip `erasableSyntaxOnly`.
27+
constructor(rejection: Error) {
28+
this.rejection = rejection;
29+
}
30+
31+
async start(): Promise<void> {}
32+
33+
async send(): Promise<void> {
34+
throw this.rejection;
35+
}
36+
37+
async close(): Promise<void> {
38+
this.onclose?.();
39+
}
40+
}
41+
1042
/**
1143
* Connecting with `protocolEra: "auto" | "modern"` sends the SDK's
1244
* `server/discover` negotiation probe first, and the probe's classifier reports
@@ -21,36 +53,6 @@ import type { JSONRPCMessage, Transport } from "@modelcontextprotocol/client";
2153
* `src/test/integration/mcp/inspectorClient-modern-era-oauth.test.ts`.
2254
*/
2355
describe("InspectorClient connect() era-probe auth unwrapping (#1805)", () => {
24-
/**
25-
* Minimal transport whose `send` rejects — which is what the probe's
26-
* `server/discover` exchange hits. The remote path rejects with
27-
* `AuthRecoveryRequiredError` (after the backend intercepted the 401 and
28-
* `handleAuthChallenge` returned `interactive`); a direct transport with
29-
* challenge interception rejects with `AuthChallengeError`.
30-
*/
31-
class RejectingTransport implements Transport {
32-
onclose?: () => void;
33-
onerror?: (error: Error) => void;
34-
onmessage?: (message: JSONRPCMessage) => void;
35-
36-
private readonly rejection: Error;
37-
38-
// A parameter property would trip `erasableSyntaxOnly`.
39-
constructor(rejection: Error) {
40-
this.rejection = rejection;
41-
}
42-
43-
async start(): Promise<void> {}
44-
45-
async send(): Promise<void> {
46-
throw this.rejection;
47-
}
48-
49-
async close(): Promise<void> {
50-
this.onclose?.();
51-
}
52-
}
53-
5456
function makeClient(
5557
rejection: Error,
5658
era: "legacy" | "auto" | "modern",
@@ -94,10 +96,21 @@ describe("InspectorClient connect() era-probe auth unwrapping (#1805)", () => {
9496
it(`leaves a non-auth probe failure untouched on the "${era}" era`, async () => {
9597
const client = makeClient(new Error("ECONNREFUSED"), era);
9698

97-
// No auth error in the chain: the SDK's typed negotiation error stands, so
98-
// callers still report a plain connection failure.
99-
await expect(client.connect()).rejects.toThrow(
100-
/Version negotiation|ECONNREFUSED/,
99+
// No auth error in the chain, so nothing is unwrapped: whatever the SDK
100+
// produced reaches the caller as a plain connection failure. Pin that it
101+
// is *not* an auth error rather than matching a message alternation
102+
// (which would pass on either branch and assert nothing) — "auto" falls
103+
// back to the legacy handshake and rejects with the raw error, while
104+
// "modern" pins and rejects with the wrapped negotiation error.
105+
const error = await client.connect().then(
106+
() => undefined,
107+
(err: unknown) => err,
108+
);
109+
expect(error).toBeInstanceOf(Error);
110+
expect(error).not.toBeInstanceOf(AuthChallengeError);
111+
expect(error).not.toBeInstanceOf(AuthRecoveryRequiredError);
112+
expect((error as Error).message).toMatch(
113+
era === "auto" ? /ECONNREFUSED/ : /Version negotiation/,
101114
);
102115
});
103116
}
@@ -112,32 +125,64 @@ describe("InspectorClient connect() era-probe auth unwrapping (#1805)", () => {
112125
});
113126
});
114127

115-
describe("InspectorClient probesProtocolEra (#1805)", () => {
116-
function probesFor(
128+
/**
129+
* The workaround half of #1805: with no stored tokens there is no authProvider,
130+
* so the direct path only intercepts the probe's 401 — turning it into a typed
131+
* `AuthChallengeError` that survives as `data.cause` — when the era actually
132+
* probes. Asserted through the transport options the factory receives (the
133+
* load-bearing effect) rather than the private predicate behind it.
134+
*/
135+
describe("InspectorClient era-scoped interceptAuthChallenges (#1805)", () => {
136+
async function interceptFlagFor(
117137
versionNegotiation:
118138
| { mode?: "legacy" | "auto" | { pin: string } }
119139
| undefined,
120-
): boolean {
140+
): Promise<boolean | undefined> {
141+
let seen: CreateTransportOptions | undefined;
121142
const client = new InspectorClient(
122143
{ type: "streamable-http", url: "https://mcp.example/mcp" },
123144
{
124-
environment: { transport: () => ({}) as never },
145+
environment: {
146+
transport: (_config, options) => {
147+
seen = options;
148+
return {
149+
transport: new RejectingTransport(new Error("ECONNREFUSED")),
150+
};
151+
},
152+
// Real but empty storage (sessionStorage under happy-dom) plus the
153+
// other two components an OAuthManager requires. No stored tokens, so
154+
// `isOAuthAuthorized()` is false and no authProvider is attached —
155+
// the case this clause exists for.
156+
oauth: {
157+
storage: new BrowserOAuthStorage(),
158+
navigation: { navigateToAuthorization: vi.fn() },
159+
redirectUrlProvider: {
160+
getRedirectUrl: () => "http://localhost/callback",
161+
},
162+
},
163+
},
164+
oauth: { clientId: "era-probe-test" },
165+
directAuthRecovery: true,
125166
...(versionNegotiation ? { versionNegotiation } : {}),
126167
},
127168
);
128-
return (
129-
client as unknown as { probesProtocolEra: () => boolean }
130-
).probesProtocolEra();
169+
170+
await client.connect().catch(() => {});
171+
return seen?.interceptAuthChallenges;
131172
}
132173

133-
it("is true for the probing eras and false for legacy", () => {
134-
expect(probesFor(eraToVersionNegotiation("auto"))).toBe(true);
135-
expect(probesFor(eraToVersionNegotiation("modern"))).toBe(true);
136-
expect(probesFor(eraToVersionNegotiation("legacy"))).toBe(false);
174+
it("is enabled for the probing eras and left off for legacy", async () => {
175+
expect(await interceptFlagFor(eraToVersionNegotiation("auto"))).toBe(true);
176+
expect(await interceptFlagFor(eraToVersionNegotiation("modern"))).toBe(
177+
true,
178+
);
179+
expect(
180+
await interceptFlagFor(eraToVersionNegotiation("legacy")),
181+
).toBeFalsy();
137182
});
138183

139-
it("treats an absent mode and an absent option as legacy (the SDK default)", () => {
140-
expect(probesFor({})).toBe(false);
141-
expect(probesFor(undefined)).toBe(false);
184+
it("treats an absent mode and an absent option as legacy (the SDK default)", async () => {
185+
expect(await interceptFlagFor({})).toBeFalsy();
186+
expect(await interceptFlagFor(undefined)).toBeFalsy();
142187
});
143188
});
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { describe, it, expect, vi } from "vitest";
2+
import { AuthChallengeError } from "@inspector/core/auth/challenge.js";
3+
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
4+
import { BrowserOAuthStorage } from "@inspector/core/auth/browser/storage.js";
5+
import type { JSONRPCMessage, Transport } from "@modelcontextprotocol/client";
6+
7+
/**
8+
* The three environment components an OAuthManager needs to exist. Storage is
9+
* real but empty (sessionStorage under happy-dom), so there are no tokens and
10+
* no authProvider is attached — the connect path this covers.
11+
*/
12+
function oauthEnvironment() {
13+
return {
14+
storage: new BrowserOAuthStorage(),
15+
navigation: { navigateToAuthorization: vi.fn() },
16+
redirectUrlProvider: {
17+
getRedirectUrl: () => "http://localhost/callback",
18+
},
19+
};
20+
}
21+
22+
/**
23+
* A connect-time auth challenge that recovery satisfies *silently* (a refresh
24+
* token, say) must leave `connect()` resolved, not rejected.
25+
*
26+
* `connect()` builds its handshake promise once, outside the `runConnect`
27+
* closure that `withDirectAuthRecovery` retries. On a `satisfied` outcome
28+
* recovery calls `reconnectAfterAuthRecovery()`, which runs a complete nested
29+
* `connect()` — so by the time the retry leg runs, the client is connected and
30+
* the original promise is still rejected. Re-awaiting it rethrew that first
31+
* error and rejected a `connect()` whose client was in fact connected (found in
32+
* review of #1809; reachable on the legacy era before #1805 and on auto/modern
33+
* after it, since a probe 401 now arrives as a typed challenge).
34+
*/
35+
describe("InspectorClient connect() after a silently satisfied auth challenge", () => {
36+
/** Answers `initialize`, so a connect over it completes the handshake. */
37+
class HandshakingTransport implements Transport {
38+
onclose?: () => void;
39+
onerror?: (error: Error) => void;
40+
onmessage?: (message: JSONRPCMessage) => void;
41+
42+
async start(): Promise<void> {}
43+
async close(): Promise<void> {
44+
this.onclose?.();
45+
}
46+
47+
async send(message: JSONRPCMessage): Promise<void> {
48+
if (
49+
"method" in message &&
50+
message.method === "initialize" &&
51+
"id" in message
52+
) {
53+
const params = message.params as { protocolVersion: string };
54+
this.onmessage?.({
55+
jsonrpc: "2.0",
56+
id: message.id,
57+
result: {
58+
protocolVersion: params.protocolVersion,
59+
capabilities: {},
60+
serverInfo: { name: "recovered-server", version: "1.0.0" },
61+
},
62+
});
63+
}
64+
}
65+
}
66+
67+
/** Rejects the handshake with the challenge recovery will satisfy. */
68+
class ChallengingTransport implements Transport {
69+
onclose?: () => void;
70+
onerror?: (error: Error) => void;
71+
onmessage?: (message: JSONRPCMessage) => void;
72+
73+
async start(): Promise<void> {}
74+
async close(): Promise<void> {
75+
this.onclose?.();
76+
}
77+
78+
async send(): Promise<void> {
79+
throw new AuthChallengeError({ reason: "token_expired" }, 401);
80+
}
81+
}
82+
83+
it("resolves, reports connected, and dispatches exactly one connect event", async () => {
84+
let transportsCreated = 0;
85+
const client = new InspectorClient(
86+
{ type: "streamable-http", url: "https://mcp.example/mcp" },
87+
{
88+
environment: {
89+
transport: () => {
90+
transportsCreated += 1;
91+
// First connect challenges; the reconnect underneath the satisfied
92+
// recovery gets a transport that completes the handshake.
93+
return {
94+
transport:
95+
transportsCreated === 1
96+
? new ChallengingTransport()
97+
: new HandshakingTransport(),
98+
};
99+
},
100+
oauth: oauthEnvironment(),
101+
},
102+
oauth: { clientId: "satisfied-recovery-test" },
103+
directAuthRecovery: true,
104+
},
105+
);
106+
107+
// Recovery succeeds without user interaction — the case that ends in the
108+
// retry leg rather than an AuthRecoveryRequiredError.
109+
vi.spyOn(client, "handleAuthChallenge").mockResolvedValue({
110+
kind: "satisfied",
111+
});
112+
113+
let connectEvents = 0;
114+
client.addEventListener("connect", () => {
115+
connectEvents += 1;
116+
});
117+
118+
await expect(client.connect()).resolves.toBeUndefined();
119+
expect(client.getStatus()).toBe("connected");
120+
expect(transportsCreated).toBe(2);
121+
// The nested connect() already ran the post-connect block; the outer call
122+
// must not run it a second time (a duplicate `connect` re-triggers every
123+
// list-state manager's refresh).
124+
expect(connectEvents).toBe(1);
125+
126+
await client.disconnect();
127+
});
128+
});

‎core/mcp/inspectorClient.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1725,6 +1725,14 @@ export class InspectorClient extends InspectorClientEventTarget {
17251725
// auth-required. `findNestedAuthError` is the permanent fix; the
17261726
// `|| this.probesProtocolEra()` clause below exists only to compensate
17271727
// for that upstream gap and should be deleted with it.
1728+
//
1729+
// Known, accepted side effect of turning intercept on with no stored
1730+
// tokens: `parseAuthChallengeFromResponse` treats 403 as a challenge
1731+
// too, so a probe answered 403 for a *non-auth* reason (a gateway
1732+
// rejecting the unknown `server/discover` method, say) now starts OAuth
1733+
// discovery instead of letting "auto" fall back to the legacy
1734+
// `initialize`. The outcome is a surfaced `oauthError`, not a hang, and
1735+
// it goes away with this clause.
17281736
(transportOptions.authProvider || this.probesProtocolEra())
17291737
) {
17301738
transportOptions.interceptAuthChallenges = true;
@@ -1798,7 +1806,24 @@ export class InspectorClient extends InspectorClientEventTarget {
17981806
.catch((err: unknown) => {
17991807
throw findNestedAuthError(err) ?? err;
18001808
});
1809+
// Set when a satisfied auth recovery already completed a full connect()
1810+
// underneath us — see the short-circuit in `runConnect`.
1811+
let recoveredByNestedConnect = false;
18011812
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
1816+
// `reconnectAfterAuthRecovery()` has already run a complete
1817+
// `connect()` — handshake, server info, `connect` event and all.
1818+
// `connectPromise` is created once, outside this closure, so
1819+
// re-awaiting it here would rethrow the *original* rejection and
1820+
// reject a `connect()` whose client is in fact connected. Short-
1821+
// circuit instead, and let the caller skip the post-connect block the
1822+
// nested connect already ran (dispatching a second `connect` event
1823+
// would re-trigger every list-state manager's refresh).
1824+
recoveredByNestedConnect = true;
1825+
return;
1826+
}
18021827
if (connectTimeoutMs > 0) {
18031828
connectPromise.catch(() => {});
18041829
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -1831,6 +1856,10 @@ export class InspectorClient extends InspectorClientEventTarget {
18311856
}
18321857
throw err;
18331858
}
1859+
if (recoveredByNestedConnect) {
1860+
// The nested connect() from the auth recovery did all of the below.
1861+
return;
1862+
}
18341863
this.status = "connected";
18351864
this.dispatchTypedEvent("statusChange", this.status);
18361865

@@ -5290,8 +5319,16 @@ export class InspectorClient extends InspectorClientEventTarget {
52905319

52915320
/**
52925321
* True when connect() sends the SDK's `server/discover` negotiation probe —
5293-
* i.e. `protocolEra` is "auto" or "modern" (`{ pin }`). Legacy is the default
5294-
* for an absent `mode`, matching the SDK.
5322+
* i.e. `protocolEra` is "auto", or "modern" (`{ pin: MODERN_PROTOCOL_VERSION }`).
5323+
* Legacy is the default for an absent `mode`, matching the SDK.
5324+
*
5325+
* `versionNegotiation` is a public option, so a caller can pin a revision the
5326+
* repo's own {@link eraToVersionNegotiation} never produces (it only ever
5327+
* pins {@link MODERN_PROTOCOL_VERSION}). That is still "probing" and
5328+
* deliberately reports true: per the SDK, *any* `{ pin }` sends the
5329+
* connect-time `server/discover` — "the connect-time `server/discover` must
5330+
* offer it. No fallback" — so the pinned revision doesn't change whether the
5331+
* probe (and hence the buried-401 problem) happens. Only "legacy" skips it.
52955332
*/
52965333
private probesProtocolEra(): boolean {
52975334
const mode = this.versionNegotiation.mode;

0 commit comments

Comments
 (0)