inspector/core/react/useInspectorClient.ts
Cliff Hall e026051b47
Some checks failed
Run install, format, lint, build, and test on every push / build (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish-github-container-registry (push) Has been cancelled
Era-aware connection model & capability gating (#1626) (#1697)
* Era-aware connection model & capability gating (#1626)

Make protocol era (SEP §7.8) a first-class, per-server connection dimension,
orthogonal to the transport type, and drive the SDK Client's versionNegotiation
from it.

Config
- Add `ServerProtocolEra` ("legacy" | "auto" | "modern"), `DEFAULT_PROTOCOL_ERA`
  (legacy, per the SDK's don't-auto-probe guidance), `MODERN_PROTOCOL_VERSION`,
  and `eraToVersionNegotiation()` in core/mcp/types.ts.
- Persist `protocolEra` on `StoredMCPServer` / `InspectorServerSettings`,
  round-tripping through serverList.ts (omitting the default on disk) and the
  `/api/servers` read + write validators.

InspectorClient / state
- Thread `versionNegotiation` through `InspectorClientOptions` (default legacy),
  replacing the hardcoded pin. After connect, read `getProtocolEra()` /
  `getDiscoverResult()` / `getNegotiatedProtocolVersion()`, expose them via
  getters, dispatch `protocolEraChange` / `discoverResultChange`, and clear on
  disconnect. `useInspectorClient` surfaces `protocolEra` / `discoverResult`.

Web UI
- ServerSettingsForm: a Protocol Era selector bound to the per-server setting.
- ConnectionInfoContent: era-aware — Era badge, Session ("Sessionless" on
  modern), and a Discovery section (supported versions + extensions) from the
  `server/discover` result.

CLI/TUI also map the mcp.json `protocolEra` into versionNegotiation so the field
applies uniformly. Version negotiation stays fully client-side; modern connect
works over the existing remote tunnel and disconnect is sessionless (the SDK
skips DELETE when there is no session id). Mcp-* header fidelity is left to the
History/Network card.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Address @claude review: era docstrings, era validation, stdio session label, AGENTS.md rule

- Fix stale docstrings/comments in inspectorClient.ts, useInspectorClient.ts,
  inspectorClientEventTarget.ts, and ConnectionInfoContent.tsx: getProtocolEra()
  returns "legacy" (not undefined) on a plain legacy connect; it is undefined
  only when not connected.
- Validate protocolEra at the storedFieldsToInspectorSettings read boundary
  (new shared isProtocolEra guard) so a hand-edited mcp.json read directly by
  the CLI/TUI drops an unknown era instead of passing it to
  eraToVersionNegotiation. Keeps the exhaustive switch intact.
- ConnectionInfoContent: the Session row is HTTP-only — show "N/A (stdio)" for
  stdio instead of the misleading "Session-based".
- AGENTS.md: add a rule against unjustified `as unknown as` double casts, and
  drop the one such cast introduced in the serverList test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Address re-review: dedupe isProtocolEra guard in remote server

Replace the local isProtocolEra in remote/node/server.ts with the shared guard
now exported from serverList.ts (already imported here), so the era literal set
lives in one place and can't drift.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 23:39:29 -04:00

229 lines
8.4 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
import type { InspectorClientProtocol } from "../mcp/inspectorClientProtocol.js";
import type { AppRendererClient } from "../mcp/inspectorClientProtocol.js";
import type { TypedEvent } from "../mcp/inspectorClientEventTarget.js";
import type { ConnectionStatus } from "../mcp/types.js";
import type {
ClientCapabilities,
ServerCapabilities,
Implementation,
ProtocolEra,
DiscoverResult,
} from "@modelcontextprotocol/client";
// Module-scope frozen object so the `?? EMPTY_CLIENT_CAPABILITIES`
// fallback below doesn't return a fresh literal on every render —
// downstream `useMemo`/`useEffect` deps that key on `clientCapabilities`
// would otherwise invalidate every tick when no client is attached.
const EMPTY_CLIENT_CAPABILITIES: ClientCapabilities = Object.freeze({});
export interface UseInspectorClientResult {
status: ConnectionStatus;
capabilities?: ServerCapabilities;
clientCapabilities: ClientCapabilities;
serverInfo?: Implementation;
instructions?: string;
protocolVersion?: string;
/**
* Protocol era negotiated with the server (SEP §7.8): `"legacy"` for the
* 2025-11-25 initialize handshake, `"modern"` for the 2026-era sessionless
* model. Populated for every era once connected (a plain legacy connect
* reports `"legacy"`); undefined only when not connected. (#1626)
*/
protocolEra?: ProtocolEra;
/**
* The `server/discover` result on a probed/pinned connect — server identity,
* capabilities, and supported versions learned without an initialize
* handshake. Undefined on a legacy connect. (#1626)
*/
discoverResult?: DiscoverResult;
/**
* Message from the most recent mid-session transport failure (the client's
* `error` event — stdio crash, SSE drop, HTTP 5xx). Stays set until the next
* connection attempt (`status` → `"connecting"`) clears it, so consumers can
* render it without subscribing to the event directly. Handshake failures do
* NOT populate this — they reject the `connect()` promise instead.
*/
lastError?: string;
appRendererClient: AppRendererClient | null;
connect: () => Promise<void>;
disconnect: () => Promise<void>;
}
/**
* React hook that subscribes to InspectorClient events and provides reactive
* connection state. Log lists (message / stderr / fetch) live in dedicated
* state managers consumed via useMessageLog / useStderrLog / useFetchRequestLog.
*
* Note: `appRendererClient` is read lazily from the client on every render
* and is NOT subscribed. It changes once at connect time and is not expected
* to change again during a session, so callers will see the current value
* on any rerender triggered by status / capabilities / serverInfo / instructions.
* If a future use case requires autonomous updates when the renderer attaches,
* add an `appRendererClientChange` event to `InspectorClientEventMap` and
* subscribe here.
*/
export function useInspectorClient(
inspectorClient: InspectorClientProtocol | null,
): UseInspectorClientResult {
const [status, setStatus] = useState<ConnectionStatus>(
inspectorClient?.getStatus() ?? "disconnected",
);
const [capabilities, setCapabilities] = useState<
ServerCapabilities | undefined
>(inspectorClient?.getCapabilities());
const [serverInfo, setServerInfo] = useState<Implementation | undefined>(
inspectorClient?.getServerInfo(),
);
const [instructions, setInstructions] = useState<string | undefined>(
inspectorClient?.getInstructions(),
);
const [protocolVersion, setProtocolVersion] = useState<string | undefined>(
inspectorClient?.getProtocolVersion(),
);
const [protocolEra, setProtocolEra] = useState<ProtocolEra | undefined>(
inspectorClient?.getProtocolEra(),
);
const [discoverResult, setDiscoverResult] = useState<
DiscoverResult | undefined
>(inspectorClient?.getDiscoverResult());
const [lastError, setLastError] = useState<string | undefined>(undefined);
useEffect(() => {
if (!inspectorClient) {
setStatus("disconnected");
setCapabilities(undefined);
setServerInfo(undefined);
setInstructions(undefined);
setProtocolVersion(undefined);
setProtocolEra(undefined);
setDiscoverResult(undefined);
setLastError(undefined);
return;
}
setStatus(inspectorClient.getStatus());
setCapabilities(inspectorClient.getCapabilities());
setServerInfo(inspectorClient.getServerInfo());
setInstructions(inspectorClient.getInstructions());
setProtocolVersion(inspectorClient.getProtocolVersion());
setProtocolEra(inspectorClient.getProtocolEra());
setDiscoverResult(inspectorClient.getDiscoverResult());
setLastError(undefined);
const onStatusChange = (event: TypedEvent<"statusChange">) => {
setStatus(event.detail);
// A fresh connection attempt clears any stale error from the prior
// session so the UI doesn't keep showing why the last transport died.
if (event.detail === "connecting") {
setLastError(undefined);
}
};
const onError = (event: TypedEvent<"error">) => {
setLastError(event.detail.message);
};
const onCapabilitiesChange = (event: TypedEvent<"capabilitiesChange">) => {
setCapabilities(event.detail);
};
const onServerInfoChange = (event: TypedEvent<"serverInfoChange">) => {
setServerInfo(event.detail);
};
const onInstructionsChange = (event: TypedEvent<"instructionsChange">) => {
setInstructions(event.detail);
};
const onProtocolVersionChange = (
event: TypedEvent<"protocolVersionChange">,
) => {
setProtocolVersion(event.detail);
};
const onProtocolEraChange = (event: TypedEvent<"protocolEraChange">) => {
setProtocolEra(event.detail);
};
const onDiscoverResultChange = (
event: TypedEvent<"discoverResultChange">,
) => {
setDiscoverResult(event.detail);
};
inspectorClient.addEventListener("statusChange", onStatusChange);
inspectorClient.addEventListener("error", onError);
inspectorClient.addEventListener(
"capabilitiesChange",
onCapabilitiesChange,
);
inspectorClient.addEventListener("serverInfoChange", onServerInfoChange);
inspectorClient.addEventListener(
"instructionsChange",
onInstructionsChange,
);
inspectorClient.addEventListener(
"protocolVersionChange",
onProtocolVersionChange,
);
inspectorClient.addEventListener("protocolEraChange", onProtocolEraChange);
inspectorClient.addEventListener(
"discoverResultChange",
onDiscoverResultChange,
);
return () => {
inspectorClient.removeEventListener("statusChange", onStatusChange);
inspectorClient.removeEventListener("error", onError);
inspectorClient.removeEventListener(
"capabilitiesChange",
onCapabilitiesChange,
);
inspectorClient.removeEventListener(
"serverInfoChange",
onServerInfoChange,
);
inspectorClient.removeEventListener(
"instructionsChange",
onInstructionsChange,
);
inspectorClient.removeEventListener(
"protocolVersionChange",
onProtocolVersionChange,
);
inspectorClient.removeEventListener(
"protocolEraChange",
onProtocolEraChange,
);
inspectorClient.removeEventListener(
"discoverResultChange",
onDiscoverResultChange,
);
};
}, [inspectorClient]);
const connect = useCallback(async () => {
if (!inspectorClient) return;
await inspectorClient.connect();
}, [inspectorClient]);
const disconnect = useCallback(async () => {
if (!inspectorClient) return;
await inspectorClient.disconnect();
}, [inspectorClient]);
return {
status,
capabilities,
// Read lazily on every render rather than subscribed: client capabilities
// are built once in InspectorClient's constructor (from `sample`, `elicit`,
// `roots`, `receiverTasks`) and never mutate during a session, so there's
// no event to subscribe to. The module-scope frozen empty object is the
// stable fallback when no client is attached.
clientCapabilities:
inspectorClient?.getClientCapabilities() ?? EMPTY_CLIENT_CAPABILITIES,
serverInfo,
instructions,
protocolVersion,
protocolEra,
discoverResult,
lastError,
appRendererClient: inspectorClient?.getAppRendererClient() ?? null,
connect,
disconnect,
};
}