inspector/core/mcp/inspectorClientProtocol.ts
cliffhall f201032137 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
2026-08-08 16:48:48 -04:00

183 lines
7.1 KiB
TypeScript

/**
* InspectorClientProtocol: the minimal surface that state managers (core/mcp/state/)
* and React hooks (core/react/) consume.
*
* v1.5 has a single concrete `InspectorClient` class (~2k LOC) bundling the transport,
* SDK client, OAuth flow, pending-request queues, and fetch tracking. Porting the full
* class requires first porting the auth subsystem (core/auth/, ~12 files) — that's
* deferred to a follow-up issue.
*
* This interface captures just what the state+hooks layer needs to function,
* so the layer is decoupled from how (or whether) the runtime is wired up.
* The real `InspectorClient` will implement this interface in the follow-up port.
*/
import type {
ConnectionStatus,
InspectorServerSettings,
ResourceReadInvocation,
ResourceTemplateReadInvocation,
PromptGetInvocation,
ToolCallInvocation,
ResourceSubscriptionStreamState,
ExcludedTool,
} from "./types.js";
import type {
CacheMode,
ClientCapabilities,
DiscoverResult,
Implementation,
LoggingLevel,
Prompt,
ProtocolEra,
Resource,
ResourceTemplateType as ResourceTemplate,
ServerCapabilities,
Task,
Tool,
} from "@modelcontextprotocol/client";
import type { JsonValue } from "../json/jsonUtils.js";
import type { InspectorClientEventTarget } from "./inspectorClientEventTarget.js";
import type { SamplingCreateMessage } from "./samplingCreateMessage.js";
import type { ElicitationCreateMessage } from "./elicitationCreateMessage.js";
/**
* Opaque type representing the AppRendererClient surface used by @mcp-ui.
* v1.5 aliases this to the SDK `Client` type; v2 leaves it opaque until the
* real InspectorClient (or a focused App-renderer port) lands.
*/
export type AppRendererClient = unknown;
/**
* The contract every state manager and hook depends on. Anything that holds
* a reference to "an Inspector client" — including tests and fixtures —
* should depend on this protocol rather than the concrete class.
*/
export interface InspectorClientProtocol extends InspectorClientEventTarget {
// Connection state accessors
getStatus(): ConnectionStatus;
getCapabilities(): ServerCapabilities | undefined;
getClientCapabilities(): ClientCapabilities;
getServerInfo(): Implementation | undefined;
getInstructions(): string | undefined;
getProtocolVersion(): string | undefined;
getProtocolEra(): ProtocolEra | undefined;
/** Tools excluded from `tools/list` for invalid `x-mcp-header` annotations
* (SEP-2243); empty on legacy/stdio connections (#1632). */
getExcludedTools(): ExcludedTool[];
getResourceSubscriptionStreamState(): ResourceSubscriptionStreamState;
getDiscoverResult(): DiscoverResult | undefined;
getServerSettings(): InspectorServerSettings | undefined;
setServerSettings(settings: InspectorServerSettings): void;
getAppRendererClient(): AppRendererClient | null;
// Connection control
connect(): Promise<void>;
disconnect(safeDisconnectTimeout?: number): Promise<void>;
// Paginated list methods used by managed/paged state stores
listTools(
cursor?: string,
metadata?: Record<string, string>,
): Promise<{ tools: Tool[]; nextCursor?: string }>;
listPrompts(
cursor?: string,
metadata?: Record<string, string>,
): Promise<{ prompts: Prompt[]; nextCursor?: string }>;
listResources(
cursor?: string,
metadata?: Record<string, string>,
): Promise<{ resources: Resource[]; nextCursor?: string }>;
listResourceTemplates(
cursor?: string,
metadata?: Record<string, string>,
): Promise<{ resourceTemplates: ResourceTemplate[]; nextCursor?: string }>;
listRequestorTasks(
cursor?: string,
): Promise<{ tasks: Task[]; nextCursor?: string }>;
/** Poll one requestor task's current status (era-aware: modern `DetailedTask`
* via `tasks/get`, or the legacy flattened task). Dispatches
* `requestorTaskUpdated`. Used by the modern task store's refresh (no
* `tasks/list`). */
getRequestorTask(taskId: string): Promise<Task>;
/** True when a modern (2026-07-28) connection negotiated the
* `io.modelcontextprotocol/tasks` extension (SEP-2663). Gates the Tasks tab
* and the modern task store's poll-based refresh. */
isTasksExtensionNegotiated(): boolean;
/**
* Mark the response that most recently answered `method` as rejected by the
* client, so its Protocol entry shows the reason instead of rendering as a
* clean success (#1953). Optional so existing test doubles satisfy the
* interface without implementing it; see `InspectorClient` for how the id is
* correlated and why that correlation is exact.
*/
markResponseRejected?(method: string, reason: string): void;
// Aggregate (all-page) list methods used by the managed state stores on
// refresh. Unlike the single-page methods above, these route through the
// SDK's cache-aware high-level verbs so `cacheMode` ('use' | 'refresh' |
// 'bypass') is honored — a manual refresh forces a cache-bypassing round trip
// on modern servers that send `ttlMs` hints. Options are optional; omitting
// `cacheMode` uses the SDK default ('use').
listAllTools(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
}): Promise<{ tools: Tool[] }>;
listAllPrompts(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
}): Promise<{ prompts: Prompt[] }>;
listAllResources(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
}): Promise<{ resources: Resource[] }>;
listAllResourceTemplates(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
}): Promise<{ resourceTemplates: ResourceTemplate[] }>;
// Invocation methods used by paged result panels
callTool(
tool: Tool,
args: Record<string, JsonValue>,
generalMetadata?: Record<string, string>,
toolSpecificMetadata?: Record<string, string>,
): Promise<ToolCallInvocation>;
readResource(
uri: string,
metadata?: Record<string, string>,
): Promise<ResourceReadInvocation>;
readResourceFromTemplate(
uriTemplate: string,
params: Record<string, string>,
metadata?: Record<string, string>,
): Promise<ResourceTemplateReadInvocation>;
getPrompt(
name: string,
params?: Record<string, string>,
metadata?: Record<string, string>,
): Promise<PromptGetInvocation>;
// Misc surface required by hooks/state
setLoggingLevel(level: LoggingLevel): Promise<void>;
getSessionId(): string | undefined;
// Server-initiated request queues. Each entry exposes `respond()` / `reject()`
// (and `remove()`), which resolve the handler Promise that left the originating
// call (e.g. a tool execution) in flight. The `pendingSamplesChange` /
// `pendingElicitationsChange` events fire whenever these arrays mutate.
getPendingSamples(): SamplingCreateMessage[];
getPendingElicitations(): ElicitationCreateMessage[];
// Completions (resource templates / prompt arguments)
getCompletions(
ref:
| { type: "ref/resource"; uri: string }
| { type: "ref/prompt"; name: string },
argumentName: string,
argumentValue: string,
context?: Record<string, string>,
metadata?: Record<string, string>,
): Promise<{ values: string[]; total?: number; hasMore?: boolean }>;
}