fix: surface list-fetch failures instead of swallowing them

A list load that failed — a transport error, or a result the SDK's era
codec rejects as invalid — reported nothing. The connect-time refresh is
fired with no caller to await it (`void this.refresh()`), so its rejection
became an unhandled rejection: the header said "Connected", the panel
rendered an empty list indistinguishable from a server that has none, and
the failed exchange showed in the Protocol panel as a clean success.

Two surfaces now tell the truth:

- ManagedListState records the failure as observable state (`getError` +
  an `errorChange` event) and still re-throws, so App's auth-recovery
  wrapper keeps working. The four `useManaged*` hooks expose it via a
  shared `useManagedListError`, and the Tools/Prompts/Resources sidebars
  render a `ListLoadError` alert with the reason and a Retry.
- A response the client refused is attributed back to its Protocol entry
  (`markResponseRejected` → `responseRejected` → `MessageEntry.clientError`),
  which now renders an Error status and a "Rejected by the Inspector"
  alert rather than the green resultType badge alone. The SDK gives no
  request id with a decode failure, so the id is recovered by correlation;
  see the comment on `markResponseRejected` for why that is exact.

Also stops `listAllTools` from dropping a failing excluded-tools walk on
the floor — it stays non-fatal but is logged.

Closes #1953

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SW1p8E2uiyyLx4RKwrwSrt
This commit is contained in:
cliffhall 2026-08-08 16:48:48 -04:00
commit f201032137
6 changed files with 1080 additions and 48 deletions

View file

@ -29,12 +29,29 @@ import { TypedEventTarget } from "../typedEventTarget.js";
*/
export const DEFAULT_LIST_CHANGED_DEBOUNCE_MS = 250;
/** Every managed-list event map carries the list-changed indicator event. */
/**
* Every managed-list event map carries the list-changed indicator event and the
* last-fetch error (#1953).
*/
export interface ManagedListEventMap {
/**
* Fires when the "list changed since last refresh" flag flips. True when
* this list's `list_changed` notification arrives (auto-refresh off), false
* once the user refreshes or the connection drops. Drives the sidebar
* list-changed indicator (#1402).
*/
listChangedChange: boolean;
/** The last fetch's failure, or `null` once a fetch succeeds. */
errorChange: Error | null;
}
export interface ManagedListConfig<T, M extends ManagedListEventMap> {
/**
* The JSON-RPC method this list pages (e.g. "tools/list"). Used to attribute
* a failed load back to its Protocol entry — see
* `InspectorClientProtocol.markResponseRejected` (#1953).
*/
listMethod: string;
/** The `*Change` event this manager dispatches (e.g. "toolsChange"). */
changeEvent: keyof M;
/** The client notification that signals the list changed. */
@ -81,6 +98,11 @@ export abstract class ManagedListState<
private unsubscribe: (() => void) | null = null;
private _metadata: Record<string, string> | undefined = undefined;
private listChanged = false;
// The last fetch's failure, kept as observable state so a load that fails
// (a transport error, or a result the SDK codec rejects as invalid) is
// rendered by the list panel instead of vanishing into an unhandled
// rejection — which read as "this server has no tools" (#1953).
private error: Error | null = null;
private readonly config: ManagedListConfig<T, M>;
// Debounce a burst of `list_changed` notifications into a single
// refresh (or one indicator light) once it settles.
@ -112,7 +134,11 @@ export abstract class ManagedListState<
) {
return;
}
void this.refresh();
// The connect-time load has no caller to await it, so its rejection is
// caught here rather than left to become an unhandled rejection. This is
// not a swallow: `refresh` has already recorded the failure via
// `setError`, and the list panel renders it (#1953).
void this.refresh().catch(() => {});
};
const onListChanged = (): void => {
// Debounce: collapse a burst of notifications into one settled action
@ -133,6 +159,9 @@ export abstract class ManagedListState<
this.items = [];
this.dispatchChange();
this.setListChanged(false);
// A disconnect ends the session the error belonged to — a stale
// "couldn't load tools" must not outlive it into the next connect.
this.setError(null);
}
};
this.client.addEventListener("connect", onConnect);
@ -187,8 +216,10 @@ export abstract class ManagedListState<
if (!skipAggregate && settings?.autoRefreshOnListChanged) {
// A `list_changed` means the prior list is stale, so bypass any
// cached entry (`cacheMode: "refresh"`) and re-store the fresh
// aggregate.
await this.refresh(undefined, "refresh");
// aggregate. Like the connect-time load this has no caller to await
// it, so a failure is caught here — already recorded by `setError`
// and rendered by the panel (#1953).
await this.refresh(undefined, "refresh").catch(() => {});
} else if (this.config.supportsIndicator) {
this.setListChanged(true);
}
@ -236,6 +267,20 @@ export abstract class ManagedListState<
this.emit("listChangedChange", value);
}
/** The last fetch's failure, or `null` when the last fetch succeeded. */
getError(): Error | null {
return this.error;
}
// Compared by identity rather than message: two distinct failures with the
// same text are still two events, and a re-render on a repeat failure is
// cheap next to silently coalescing them.
private setError(value: Error | null): void {
if (this.error === value) return;
this.error = value;
this.emit("errorChange", value);
}
setMetadata(metadata?: Record<string, string>): void {
this._metadata = metadata;
}
@ -245,12 +290,34 @@ export abstract class ManagedListState<
* this fetch: `undefined` (the connect-time load) uses the default `'use'`;
* a user-initiated or auto refresh passes `'refresh'` to force a
* cache-bypassing round trip and re-store the fresh aggregate.
*
* A failure is recorded as observable state (`getError`) AND re-thrown: the
* state drives the panel's error rendering, while the rejection is what the
* caller's auth-recovery wrapper keys off to detect a 401 and start a
* re-authorization. Callers with nobody to await them (the connect-time load,
* the `list_changed` auto-refresh) catch it explicitly (#1953).
*/
async refresh(
metadata?: Record<string, string>,
cacheMode?: CacheMode,
): Promise<T[]> {
const next = await this.fetchItems(metadata, cacheMode);
let next: T[] | null;
try {
next = await this.fetchItems(metadata, cacheMode);
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
this.setError(error);
// Attribute the failure to the response it came from, so the Protocol
// entry stops rendering a rejected result as a clean success (#1953).
// Must happen in this catch, while the correlation window the client
// documents is still valid.
this.client?.markResponseRejected?.(
this.config.listMethod,
error.message,
);
throw err;
}
this.setError(null);
// `null` means not connected — leave the current list untouched.
if (next === null) return this.getItems();
this.applyItems(next);

View file

@ -8,17 +8,11 @@ import type { Prompt } from "@modelcontextprotocol/client";
import {
ManagedListState,
DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
type ManagedListEventMap,
} from "./managedListState.js";
export interface ManagedPromptsStateEventMap {
export interface ManagedPromptsStateEventMap extends ManagedListEventMap {
promptsChange: Prompt[];
/**
* Fires when the "list changed since last refresh" flag flips. True when a
* `prompts/list_changed` arrives (auto-refresh off), false once the user
* refreshes or the connection drops. Drives the sidebar list-changed
* indicator (#1402).
*/
listChangedChange: boolean;
}
export class ManagedPromptsState extends ManagedListState<
@ -30,6 +24,7 @@ export class ManagedPromptsState extends ManagedListState<
debounceMs = DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
) {
super(client, {
listMethod: "prompts/list",
changeEvent: "promptsChange",
listChangedEvent: "promptsListChanged",
capabilityKey: "prompts",

View file

@ -15,15 +15,11 @@ import type { ResourceTemplateType as ResourceTemplate } from "@modelcontextprot
import {
ManagedListState,
DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
type ManagedListEventMap,
} from "./managedListState.js";
export interface ManagedResourceTemplatesStateEventMap {
export interface ManagedResourceTemplatesStateEventMap extends ManagedListEventMap {
resourceTemplatesChange: ResourceTemplate[];
/**
* Carried only to satisfy the ManagedListState base; templates have no
* indicator, so this never fires.
*/
listChangedChange: boolean;
}
export class ManagedResourceTemplatesState extends ManagedListState<
@ -35,6 +31,7 @@ export class ManagedResourceTemplatesState extends ManagedListState<
debounceMs = DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
) {
super(client, {
listMethod: "resources/templates/list",
changeEvent: "resourceTemplatesChange",
listChangedEvent: "resourceTemplatesListChanged",
// Templates are gated on the broader `resources` capability.

View file

@ -8,17 +8,11 @@ import type { Resource } from "@modelcontextprotocol/client";
import {
ManagedListState,
DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
type ManagedListEventMap,
} from "./managedListState.js";
export interface ManagedResourcesStateEventMap {
export interface ManagedResourcesStateEventMap extends ManagedListEventMap {
resourcesChange: Resource[];
/**
* Fires when the "list changed since last refresh" flag flips. True when a
* `resources/list_changed` arrives (auto-refresh off), false once the user
* refreshes or the connection drops. Drives the list-changed indicator
* (#1402).
*/
listChangedChange: boolean;
}
export class ManagedResourcesState extends ManagedListState<
@ -30,6 +24,7 @@ export class ManagedResourcesState extends ManagedListState<
debounceMs = DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
) {
super(client, {
listMethod: "resources/list",
changeEvent: "resourcesChange",
listChangedEvent: "resourcesListChanged",
capabilityKey: "resources",

View file

@ -8,17 +8,11 @@ import type { Tool } from "@modelcontextprotocol/client";
import {
ManagedListState,
DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
type ManagedListEventMap,
} from "./managedListState.js";
export interface ManagedToolsStateEventMap {
export interface ManagedToolsStateEventMap extends ManagedListEventMap {
toolsChange: Tool[];
/**
* Fires when the "list changed since last refresh" flag flips. True when a
* `tools/list_changed` arrives (auto-refresh off), false once the user
* refreshes or the connection drops. Drives the sidebar list-changed
* indicator (#1402).
*/
listChangedChange: boolean;
}
export class ManagedToolsState extends ManagedListState<
@ -30,6 +24,7 @@ export class ManagedToolsState extends ManagedListState<
debounceMs = DEFAULT_LIST_CHANGED_DEBOUNCE_MS,
) {
super(client, {
listMethod: "tools/list",
changeEvent: "toolsChange",
listChangedEvent: "toolsListChanged",
capabilityKey: "tools",

View file

@ -98,6 +98,31 @@ export class MessageLogState extends TypedEventTarget<MessageLogStateEventMap> {
pushEntry(entry);
};
// A response the client rejected after the fact (the wire frame was valid
// JSON-RPC, but the SDK codec refused the result). Annotate the entry that
// carries that JSON-RPC id so it stops rendering as a clean success — the
// request entry when the response was folded into it, otherwise the
// standalone response entry. Searched newest-first: ids are unique within
// a session, and the failing exchange is by construction a recent one.
const onResponseRejected = (
event: TypedEventGeneric<InspectorClientEventMap, "responseRejected">,
): void => {
const { id, reason } = event.detail;
for (let i = this.messages.length - 1; i >= 0; i--) {
const entry = this.messages[i]!;
const entryId = (entry.message as { id?: string | number }).id;
if (entryId !== id) continue;
if (entry.direction === "notification") continue;
// A request entry with no response yet isn't the one being rejected —
// keep looking for the standalone response frame.
if (entry.direction === "request" && !entry.response) continue;
entry.clientError = reason;
this.dispatchTypedEvent("message", entry);
this.dispatchTypedEvent("messagesChange", this.getMessages());
return;
}
};
const onStatusChange = (): void => {
if (isTerminalStatus(this.client?.getStatus())) {
this.messages = [];
@ -106,10 +131,12 @@ export class MessageLogState extends TypedEventTarget<MessageLogStateEventMap> {
}
};
this.client.addEventListener("message", onMessage);
this.client.addEventListener("responseRejected", onResponseRejected);
this.client.addEventListener("statusChange", onStatusChange);
this.unsubscribe = () => {
if (this.client) {
this.client.removeEventListener("message", onMessage);
this.client.removeEventListener("responseRejected", onResponseRejected);
this.client.removeEventListener("statusChange", onStatusChange);
}
this.client = null;