Merge remote-tracking branch 'origin/v2/main' into v2/fix/2172-oidc-discovery-compat

Signed-off-by: cliffhall <cliff@futurescale.com>

# Conflicts:
#	README.md
#	core/mcp/inspectorClient.ts
#	test-servers/src/test-server-oauth.ts
This commit is contained in:
cliffhall 2026-08-28 10:10:57 -04:00
commit 2eeab05d00
9 changed files with 8524 additions and 1598 deletions

View file

@ -57,6 +57,7 @@ function createStorage(
clearServerMetadata: vi.fn(),
clearIdpSession: vi.fn(),
clearEnterpriseManagedResourceServers: vi.fn(),
takeRevocationSnapshot: vi.fn().mockResolvedValue({ byIssuer: {} }),
getCodeVerifier: vi.fn(),
getDiscoveryState: vi.fn().mockResolvedValue(undefined),
saveDiscoveryState: vi.fn(),

View file

@ -74,6 +74,7 @@ function createMemoryStorage(
saveScope: vi.fn(),
clear: vi.fn(),
clearEnterpriseManagedResourceServers: vi.fn(),
takeRevocationSnapshot: vi.fn().mockResolvedValue({ byIssuer: {} }),
} as unknown as OAuthStorage;
}

View file

@ -25,6 +25,7 @@ describe("idpSession", () => {
clearIdpSession: vi.fn(),
clear: vi.fn(),
clearEnterpriseManagedResourceServers: vi.fn(),
takeRevocationSnapshot: vi.fn().mockResolvedValue({ byIssuer: {} }),
} as unknown as OAuthStorage;
});

File diff suppressed because it is too large Load diff

View file

@ -358,6 +358,67 @@ describe("BrowserOAuthStorage", () => {
});
});
// #2144 — the atomic take-and-clear. Split reads followed by a separate clear
// are a check-then-act: each await yields, and an OAuth completion landing in
// one of those gaps saves a grant the clear then destroys.
describe("takeRevocationSnapshot", () => {
it("returns every slot and clears the server in one step", async () => {
await storage.saveTokens(
testServerUrl,
{ access_token: "a", token_type: "Bearer" },
{ issuer: "https://as-a.example.com" },
);
await storage.savePreregisteredClientInformation(testServerUrl, {
client_id: "static-cid",
});
await storage.saveServerMetadata(testServerUrl, {
issuer: "https://as-a.example.com",
authorization_endpoint: "https://as-a.example.com/authorize",
token_endpoint: "https://as-a.example.com/token",
response_types_supported: ["code"],
});
const snapshot = await storage.takeRevocationSnapshot(testServerUrl);
expect(
snapshot.byIssuer["https://as-a.example.com"]?.tokens,
).toMatchObject({ access_token: "a" });
expect(snapshot.preregisteredClientInformation).toMatchObject({
client_id: "static-cid",
});
expect(snapshot.serverMetadata).toMatchObject({
issuer: "https://as-a.example.com",
});
// Cleared in the same step.
expect(await storage.getTokens(testServerUrl)).toBeUndefined();
expect(await storage.getServerMetadata(testServerUrl)).toBeNull();
expect(
(await storage.takeRevocationSnapshot(testServerUrl)).byIssuer,
).toEqual({});
});
it("returns the legacy unkeyed slot too", async () => {
await storage.saveTokens(testServerUrl, {
access_token: "legacy",
token_type: "Bearer",
});
const snapshot = await storage.takeRevocationSnapshot(testServerUrl);
expect(snapshot.legacyTokens).toMatchObject({ access_token: "legacy" });
expect(snapshot.byIssuer).toEqual({});
});
it("is empty for a server with no state", async () => {
const snapshot = await storage.takeRevocationSnapshot(
"https://unknown.example/mcp",
);
expect(snapshot.byIssuer).toEqual({});
expect(snapshot.legacyTokens).toBeUndefined();
expect(snapshot.serverMetadata).toBeUndefined();
});
});
describe("clearServerState", () => {
it("should clear all state for a server", async () => {
const clientInfo: OAuthClientInformation = {

View file

@ -12,6 +12,8 @@ class FakeTransport implements Transport {
sessionId?: string;
// Optional on the SDK Transport interface; stdio omits it, HTTP defines it.
setProtocolVersion?: (version: string) => void;
// Optional too: Streamable HTTP advertises it, stdio and SSE say nothing.
hasPerRequestStream?: boolean;
async start(): Promise<void> {}
async send(message: JSONRPCMessage): Promise<void> {
this.sent.push(message);
@ -272,4 +274,19 @@ describe("MessageTrackingTransport.setProtocolVersion", () => {
expect(() => tracked.setProtocolVersion("2025-06-18")).not.toThrow();
expect(tracked.protocolVersion).toBe("2025-06-18");
});
// #2140: the SDK reads `hasPerRequestStream` off the transport it was handed
// — always this wrapper — to choose between aborting a request's own stream
// and POSTing `notifications/cancelled`. A wrapper that answers for the base
// transport instead of forwarding its answer breaks Cancel on every client.
it("forwards the base transport's per-request-stream capability", () => {
const { tracked, base } = makeTracked();
expect(tracked.hasPerRequestStream).toBeUndefined();
base.hasPerRequestStream = true;
expect(tracked.hasPerRequestStream).toBe(true);
base.hasPerRequestStream = false;
expect(tracked.hasPerRequestStream).toBe(false);
});
});

View file

@ -67,6 +67,7 @@ function createMockParams(
saveIdpSession: vi.fn().mockResolvedValue(undefined),
clearIdpSession: vi.fn(),
clearEnterpriseManagedResourceServers: vi.fn(),
takeRevocationSnapshot: vi.fn().mockResolvedValue({ byIssuer: {} }),
getDiscoveryState: vi.fn().mockResolvedValue(undefined),
saveDiscoveryState: vi.fn().mockResolvedValue(undefined),
clearDiscoveryState: vi.fn().mockResolvedValue(undefined),
@ -186,17 +187,128 @@ describe("OAuthManager", () => {
});
describe("clearOAuthTokens", () => {
it("calls storage.clear(serverUrl) when storage is configured", async () => {
/**
* The take-and-clear is ONE atomic storage step now, so `clear` is no
* longer called separately — these assert on `takeRevocationSnapshot`.
*/
function stubSnapshot(
storage: OAuthManagerConfig["storage"],
revocable = true,
): void {
vi.mocked(storage!.takeRevocationSnapshot).mockResolvedValue({
byIssuer: revocable
? {
"https://as.example.com": {
tokens: {
access_token: "a",
token_type: "Bearer",
refresh_token: "r",
},
},
}
: {},
serverMetadata: {
issuer: "https://as.example.com",
authorization_endpoint: "https://as.example.com/authorize",
token_endpoint: "https://as.example.com/token",
revocation_endpoint: "https://as.example.com/revoke",
response_types_supported: ["code"],
},
});
}
it("takes and clears the server's state when storage is configured", async () => {
const params = createMockParams();
const manager = new OAuthManager(params);
await manager.clearOAuthTokens();
expect(params.initialConfig.storage!.clear).toHaveBeenCalledWith(
SERVER_URL,
);
expect(
params.initialConfig.storage!.takeRevocationSnapshot,
).toHaveBeenCalledWith(SERVER_URL);
expect(manager.getOAuthFlowState()).toBeUndefined();
expect(manager.getOAuthFlowStep()).toBeUndefined();
});
// #2144 — the ordering is the contract. The request is built from state the
// clear destroys, so the take must come first; but the two are ONE step, so
// nothing can save a fresh grant between them, and the network wait happens
// after the state is already gone.
it("clears local state before waiting on the revocation request", async () => {
const params = createMockParams();
const storage = params.initialConfig.storage!;
const order: string[] = [];
vi.mocked(storage.takeRevocationSnapshot).mockImplementation(async () => {
order.push("clear");
return {
byIssuer: {
"https://as.example.com": {
tokens: {
access_token: "a",
token_type: "Bearer",
refresh_token: "r",
},
},
},
serverMetadata: {
issuer: "https://as.example.com",
authorization_endpoint: "https://as.example.com/authorize",
token_endpoint: "https://as.example.com/token",
revocation_endpoint: "https://as.example.com/revoke",
response_types_supported: ["code"],
},
};
});
const fetchFn = vi.fn<typeof fetch>(async () => {
order.push("revoke");
return new Response(null, { status: 200 });
});
const manager = new OAuthManager({
...params,
effectiveAuthFetch: fetchFn,
});
await expect(manager.clearOAuthTokens()).resolves.toMatchObject({
status: "revoked",
tokenTypeHint: "refresh_token",
});
expect(order).toEqual(["clear", "revoke"]);
});
it("clears local state even when the revocation request fails", async () => {
const params = createMockParams();
const storage = params.initialConfig.storage!;
stubSnapshot(storage);
const manager = new OAuthManager({
...params,
effectiveAuthFetch: vi.fn<typeof fetch>(async () => {
throw new Error("unreachable");
}),
});
await expect(manager.clearOAuthTokens()).resolves.toMatchObject({
status: "failed",
});
expect(storage.takeRevocationSnapshot).toHaveBeenCalledWith(SERVER_URL);
});
it("skips the request when revocation is turned off", async () => {
const params = createMockParams();
const storage = params.initialConfig.storage!;
stubSnapshot(storage);
const fetchFn = vi.fn<typeof fetch>();
const manager = new OAuthManager({
...params,
effectiveAuthFetch: fetchFn,
});
await expect(
manager.clearOAuthTokens({ revoke: false }),
).resolves.toEqual({ status: "skipped", reason: "disabled" });
expect(fetchFn).not.toHaveBeenCalled();
// Still cleared — that is what the caller asked for; the request is the
// optional part.
expect(storage.takeRevocationSnapshot).toHaveBeenCalledWith(SERVER_URL);
});
it("no-ops when storage is not configured", async () => {
const params = createMockParams({
initialConfig: {
@ -207,7 +319,10 @@ describe("OAuthManager", () => {
} as OAuthManagerConfig,
});
const manager = new OAuthManager(params);
await manager.clearOAuthTokens();
await expect(manager.clearOAuthTokens()).resolves.toEqual({
status: "skipped",
reason: "no_tokens",
});
expect(params.getServerUrl).not.toHaveBeenCalled();
});
});

View file

@ -569,4 +569,121 @@ describe("RemoteClientTransport", () => {
await transport.close();
});
// #2140: the Cancel button's wire signal is chosen by the SDK from the
// transport's `hasPerRequestStream`. The real upstream transport lives on the
// backend, so this transport answers for it — and must answer per server
// type, since only Streamable HTTP gives a request a stream of its own to
// close.
describe("per-request-stream cancellation (#2140)", () => {
it("advertises hasPerRequestStream only for streamable-http", () => {
const forType = (c: MCPServerConfig) =>
new RemoteClientTransport(
{ baseUrl, fetchFn: vi.fn<typeof fetch>() },
c,
).hasPerRequestStream;
expect(
forType({ type: "streamable-http", url: "http://server.example/mcp" }),
).toBe(true);
// stdio and SSE multiplex every request over one shared channel, so
// aborting anything would cancel the whole session rather than the call.
// The SDK must keep sending `notifications/cancelled` for them.
expect(forType(config)).toBe(false);
expect(forType({ type: "sse", url: "http://server.example/sse" })).toBe(
false,
);
});
it("applies the SDK's requestSignal to the browser-to-backend send fetch", async () => {
const seenInits: (RequestInit | undefined)[] = [];
let sse = createPushableSseStream();
const fetchFn = vi
.fn<typeof fetch>()
.mockImplementation(async (input, init) => {
const url = String(input);
if (url.endsWith("/api/mcp/connect")) {
return new Response(JSON.stringify({ sessionId: "abc" }), {
status: 200,
});
}
if (url.includes("/api/mcp/events")) {
sse = createPushableSseStream();
return sse.response;
}
if (url.endsWith("/api/mcp/send")) {
seenInits.push(init);
return new Response(JSON.stringify({ ok: true }), { status: 200 });
}
return new Response("not found", { status: 404 });
});
const transport = new RemoteClientTransport({ baseUrl, fetchFn }, config);
await transport.start();
const controller = new AbortController();
await transport.send(
{ jsonrpc: "2.0", method: "notifications/initialized" },
{ requestSignal: controller.signal },
);
expect(seenInits[0]?.signal).toBe(controller.signal);
// No signal supplied (stdio/SSE, where the SDK never creates one) must
// leave the fetch unaborted rather than passing `undefined` through as a
// deliberate value.
await transport.send({
jsonrpc: "2.0",
method: "notifications/roots/list_changed",
});
expect(seenInits[1]).not.toHaveProperty("signal");
await transport.close();
});
it("aborting the requestSignal rejects the in-flight send", async () => {
let sse = createPushableSseStream();
const fetchFn = vi
.fn<typeof fetch>()
.mockImplementation(async (input, init) => {
const url = String(input);
if (url.endsWith("/api/mcp/connect")) {
return new Response(JSON.stringify({ sessionId: "abc" }), {
status: 200,
});
}
if (url.includes("/api/mcp/events")) {
sse = createPushableSseStream();
return sse.response;
}
if (url.endsWith("/api/mcp/send")) {
// The backend holds this route open for the whole call, so model it
// as a fetch that only settles when the caller aborts.
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () =>
reject(new DOMException("Aborted", "AbortError")),
);
});
}
return new Response("not found", { status: 404 });
});
const transport = new RemoteClientTransport({ baseUrl, fetchFn }, config);
await transport.start();
const controller = new AbortController();
const sent = transport.send(
{ jsonrpc: "2.0", id: 7, method: "tools/call" },
{ requestSignal: controller.signal },
);
controller.abort();
// The backend never answers an aborted send, so the rejection has to come
// from the fetch itself. `postSend` already cancels the SSE response wait
// it registered for this id on that path (its catch does, unchanged by
// #2140) — so the send surfaces the abort rather than the wait's timeout.
await expect(sent).rejects.toThrow(/Aborted/);
await transport.close();
});
});
});

View file

@ -1261,6 +1261,73 @@ describe("oauth.requestRefreshToken (#2068)", () => {
});
});
// #2144 — same inverted-default shape as `requestRefreshToken` above: on by
// default, and only the opt-out is written, so an entry that never touched the
// switch keeps a byte-stable round-trip.
describe("oauthRevokeOnClear (RFC 7009)", () => {
const baseSettings = {
headers: [],
env: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,
maxFetchRequests: 1000,
roots: [],
};
it("lifts an explicit false to settings.oauthRevokeOnClear", () => {
expect(
storedFieldsToInspectorSettings({
oauth: { clientId: "cid", revokeOnClear: false },
})?.oauthRevokeOnClear,
).toBe(false);
});
it("leaves the setting unset when the field is absent (default: on)", () => {
expect(
storedFieldsToInspectorSettings({ oauth: { clientId: "cid" } })
?.oauthRevokeOnClear,
).toBeUndefined();
});
it("leaves the setting unset for an explicit true, which means the default", () => {
expect(
storedFieldsToInspectorSettings({
oauth: { clientId: "cid", revokeOnClear: true },
})?.oauthRevokeOnClear,
).toBeUndefined();
});
it("persists the opt-out under oauth on disk", () => {
expect(
inspectorSettingsToStoredFields({
...baseSettings,
oauthRevokeOnClear: false,
}).oauth?.revokeOnClear,
).toBe(false);
});
it("writes nothing when the setting is on", () => {
expect(
inspectorSettingsToStoredFields({
...baseSettings,
oauthRevokeOnClear: true,
}).oauth,
).toBeUndefined();
});
it("round-trips the opt-out", () => {
const stored = inspectorSettingsToStoredFields({
...baseSettings,
oauthRevokeOnClear: false,
});
expect(storedFieldsToInspectorSettings(stored)?.oauthRevokeOnClear).toBe(
false,
);
});
});
describe("oauthOnInsufficientScope (SEP-2350)", () => {
const baseSettings = {
headers: [],