Merge branch 'v2/main' into v2/fix/2067-proxy-undici

One conflict, in `clients/tui/__tests__/App.test.tsx`: both sides added an
`opts` capture to the test harness's `FakeClient` for different fields —
`defaultMetadata` on v2/main (#1910), `environment.fetch` here (#2067) — so the
resolution is the union of the two, keeping both rationales and both tests.

Everything else auto-merged. `npm run ci` passes on the result.

Signed-off-by: cliffhall <cliff@futurescale.com>
This commit is contained in:
cliffhall 2026-08-23 23:34:07 -04:00
commit 531cf84e60
17 changed files with 3739 additions and 691 deletions

View file

@ -14,6 +14,63 @@ export type JsonValue =
export type JsonObject = { [key: string]: JsonValue };
/**
* A JSON value that survives serialization unchanged — {@link JsonValue}
* without `undefined`.
*
* `JsonValue` admits `undefined` because it is also used for *arguments*, where
* it usefully means "this field was not supplied". That meaning does not carry
* to a payload the Inspector promises to transmit verbatim: `JSON.stringify`
* drops an `undefined` object member entirely and rewrites an `undefined` array
* element to `null`, so a value the type accepted is not the value that arrives.
*
* Used for `_meta` (#1910), whose whole contract is that any JSON the user
* writes reaches the wire as written.
*/
export type StrictJsonValue =
| string
| number
| boolean
| null
| StrictJsonValue[]
| { [key: string]: StrictJsonValue };
export type StrictJsonObject = { [key: string]: StrictJsonValue };
/**
* Whether a value is JSON that survives `JSON.stringify` unchanged.
*
* {@link StrictJsonValue} is the *type*-level half of this and cannot express
* the rest: TypeScript has one `number`, but JSON has no encoding for `NaN` or
* `±Infinity`, so `JSON.stringify` rewrites them to `null`.
*
* That is reachable from ordinary input, not just from a careless caller —
* `JSON.parse("1e400")` returns `Infinity` on overflow, so text a user typed
* parses successfully, satisfies the type, and then reaches the wire as `null`
* while the editor still shows what they wrote. Checking at the boundary is the
* only place the distinction exists.
*/
export function isSerializableJson(value: unknown): value is StrictJsonValue {
if (value === null) return true;
switch (typeof value) {
case "string":
case "boolean":
return true;
case "number":
// Rejects NaN and ±Infinity; every other number round-trips.
return Number.isFinite(value);
case "object":
return Array.isArray(value)
? value.every(isSerializableJson)
: Object.values(value as Record<string, unknown>).every(
isSerializableJson,
);
default:
// `undefined`, functions, symbols and bigints are not JSON at all.
return false;
}
}
/**
* Widen a typed object to a generic string-keyed record so its keys can be
* iterated or read/written generically. Many of the project's config/SDK types

View file

@ -36,6 +36,7 @@ import type {
ResourceSubscriptionStreamState,
ToolCallInvocation,
ExcludedTool,
RequestMetadata,
} from "../types.js";
import { INACTIVE_SUBSCRIPTION_STREAM_STATE } from "../types.js";
import type { MalformedListItem } from "../listSalvage.js";
@ -145,25 +146,25 @@ export class FakeInspectorClient
listAllTools = vi.fn(
async (_options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}) => ({ tools: drainPages(this.toolPages, "tools") }),
);
listAllPrompts = vi.fn(
async (_options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}) => ({ prompts: drainPages(this.promptPages, "prompts") }),
);
listAllResources = vi.fn(
async (_options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}) => ({ resources: drainPages(this.resourcePages, "resources") }),
);
listAllResourceTemplates = vi.fn(
async (_options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}) => ({
resourceTemplates: drainPages(
this.resourceTemplatePages,
@ -224,7 +225,7 @@ export class FakeInspectorClient
_argumentName: string,
_argumentValue: string,
_context?: Record<string, string>,
_metadata?: Record<string, string>,
_metadata?: RequestMetadata,
): Promise<{ values: string[]; total?: number; hasMore?: boolean }> => ({
values: [],
}),

View file

@ -1,4 +1,10 @@
import { Client } from "@modelcontextprotocol/client";
// The protocol's own schemas for the reserved `_meta` members, so the client
// validates against the SDK rather than a restatement of it that can drift.
import {
ProgressTokenSchema,
RequestMetaSchema,
} from "@modelcontextprotocol/core";
import type {
MCPServerConfig,
StderrLogEntry,
@ -17,6 +23,7 @@ import type {
PendingRequestOrigin,
ResourceSubscriptionStreamState,
ExcludedTool,
RequestMetadata,
} from "./types.js";
import {
scanXMcpHeaderDeclarations,
@ -356,8 +363,8 @@ function notificationMethodFromSchema(schema: unknown): string | undefined {
interface ToolCallRequest {
tool: Tool;
args: Record<string, JsonValue>;
generalMetadata?: Record<string, string>;
toolSpecificMetadata?: Record<string, string>;
generalMetadata?: RequestMetadata;
toolSpecificMetadata?: RequestMetadata;
taskOptions?: { ttl?: number };
options?: { skipOutputValidation?: boolean };
}
@ -368,6 +375,69 @@ interface ToolCallRequest {
// server can't spin a tight zero-delay loop; a successful acknowledgement resets
// the count, and past the cap we give up (mark the stream ended) rather than
// retry a persistently-failing re-list forever.
/**
* A one-word name for a JSON value's type, for diagnostics that must not
* disclose the value itself.
*/
function describeJsonType(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
/**
* Whether a `_meta.progressToken` value is one the protocol allows.
*
* Delegates to the SDK's own `ProgressTokenSchema` rather than restating it.
* A hand-rolled check drifts: this was `Number.isInteger` until review pointed
* out that zod 4's `.int()` rejects anything past `Number.MAX_SAFE_INTEGER`,
* so an unsafe integer passed here and was rejected by the server instead.
*/
function isProgressToken(value: unknown): value is ProgressToken {
return ProgressTokenSchema.safeParse(value).success;
}
/**
* Drop the reserved `_meta` members whose value the protocol will not accept.
*
* Most of `_meta` is arbitrary JSON (#1910), but a few keys are **reserved**
* and carry their own schema — `progressToken` (a string or a safe integer;
* zod's `.int()` rejects anything past `Number.MAX_SAFE_INTEGER`) and
* `io.modelcontextprotocol/related-task` (`{ taskId: string }`) in the pinned
* SDK. Before the widening every value was a string, so only `progressToken`
* could even be wrong; now any of them can, and one bad reserved member makes a
* conforming server reject the **whole request** rather than ignore the key.
*
* Validated with the SDK's `RequestMetaSchema` instead of a hand-maintained
* list, which is the point: the schema is loose, so unknown keys pass through
* untouched, and a member the SDK constrains in a later release is covered here
* without anyone remembering to add it. Zod reports the offending top-level key
* as `issue.path[0]`, so only that member is removed — siblings survive, and
* the request stays well-formed because every reserved member is optional.
*/
function dropInvalidReservedMeta(
meta: RequestMetadata,
logger: InspectorLogger,
): RequestMetadata {
const result = RequestMetaSchema.safeParse(meta);
if (result.success) return meta;
const cleaned = { ...meta };
for (const issue of result.error.issues) {
const key = issue.path[0];
if (typeof key !== "string" || !(key in cleaned)) continue;
// The key and the reason, never the value: `_meta` can carry credentials,
// and this logger is persisted by real clients (the TUI writes it to
// `~/.mcp-inspector/auth.log`).
logger.warn(
{ key, received: describeJsonType(cleaned[key]) },
"Dropping reserved `_meta` member — it does not match the protocol schema.",
);
delete cleaned[key];
}
return cleaned;
}
const MODERN_RECONNECT_BASE_MS = 500;
const MODERN_RECONNECT_MAX_MS = 15_000;
const MODERN_RECONNECT_MAX_ATTEMPTS = 8;
@ -420,7 +490,7 @@ export class InspectorClient extends InspectorClientEventTarget {
private progress: boolean;
private resetTimeoutOnProgress: boolean;
private requestTimeout: number | undefined;
private defaultMetadata: Record<string, string> | undefined;
private defaultMetadata: RequestMetadata | undefined;
private serverSettings: InspectorServerSettings | undefined;
private versionNegotiation: VersionNegotiationOptions;
private status: ConnectionStatus = "disconnected";
@ -1035,8 +1105,8 @@ export class InspectorClient extends InspectorClientEventTarget {
* injecting an empty `_meta` field.
*/
private mergeMeta(
callMetadata?: Record<string, string>,
): Record<string, string> | undefined {
callMetadata?: RequestMetadata,
): RequestMetadata | undefined {
const defaults = this.defaultMetadata;
// Modern-era per-request log level (#1629): stamp the opt-in `_meta` key on
// every request so the server emits `notifications/message` on this
@ -1052,7 +1122,29 @@ export class InspectorClient extends InspectorClientEventTarget {
...(logMeta ?? {}),
...(callMetadata ?? {}),
};
return Object.keys(merged).length > 0 ? merged : undefined;
// Reserved members carry their own schemas even though the rest of `_meta`
// is arbitrary JSON, and one bad reserved value makes a conforming server
// reject the whole request. See `dropInvalidReservedMeta`.
const sanitized = dropInvalidReservedMeta(merged, this.logger);
return Object.keys(sanitized).length > 0 ? sanitized : undefined;
}
/**
* The `progressToken` a caller stamped on its request metadata, when it is
* one the SDK will accept.
*
* This governs only **callback correlation** — whether the client wires up an
* `onprogress` for the request. Keeping an invalid value off the **wire** is
* a separate concern handled in {@link mergeMeta}, which deletes the member
* from the outgoing `_meta` so a conforming server is never sent something
* `ProgressTokenSchema` rejects. The two use the same {@link isProgressToken}
* predicate, so they cannot disagree about what counts as valid.
*/
private progressTokenOf(
metadata: RequestMetadata | undefined,
): ProgressToken | undefined {
const token = metadata?.progressToken;
return isProgressToken(token) ? token : undefined;
}
private getRequestOptions(
@ -1110,8 +1202,8 @@ export class InspectorClient extends InspectorClientEventTarget {
* so the merge/omit branch is defined once.
*/
private aggregateListParams(
metadata?: Record<string, string>,
): { _meta: Record<string, string> } | undefined {
metadata?: RequestMetadata,
): { _meta: RequestMetadata } | undefined {
const effectiveMeta = this.mergeMeta(metadata);
return effectiveMeta ? { _meta: effectiveMeta } : undefined;
}
@ -3405,7 +3497,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listTools(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ tools: Tool[]; nextCursor?: string }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -3423,7 +3515,7 @@ export class InspectorClient extends InspectorClientEventTarget {
this.client!.request(
{ method: "tools/list", params },
ListToolsResultSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
);
const tools = [...(response.tools || [])];
@ -3444,7 +3536,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listAllTools(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ tools: Tool[] }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -3596,7 +3688,7 @@ export class InspectorClient extends InspectorClientEventTarget {
* from it so every field except the entries is still validated. */
resultSchema: z.ZodObject;
aggregate: () => Promise<T[]>;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
/**
* Filter applied to SALVAGED entries only, to reproduce a filter the SDK's
* strict aggregate applies for us. Without it the fallback would return a
@ -3674,7 +3766,7 @@ export class InspectorClient extends InspectorClientEventTarget {
itemsKey: string;
itemSchema: z.ZodType<T>;
resultSchema: z.ZodObject;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
err: unknown;
}): Promise<T[]> {
const pageSchema = lenientListPageSchema(resultSchema, itemsKey);
@ -3725,7 +3817,7 @@ export class InspectorClient extends InspectorClientEventTarget {
: this.client!.request(
{ method, params },
pageSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
{ method },
);
@ -3811,7 +3903,7 @@ export class InspectorClient extends InspectorClientEventTarget {
* stops the walk (non-converging-server guard, mirroring the SDK).
*/
async refreshExcludedTools(
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<ExcludedTool[]> {
const excluded: ExcludedTool[] = [];
// Gated to connections that actually exclude; otherwise this is a pure
@ -3881,7 +3973,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
private async listToolsForScan(
cursor: string | undefined,
metadata: Record<string, string> | undefined,
metadata: RequestMetadata | undefined,
): Promise<{
tools: Tool[];
nextCursor?: string;
@ -3924,7 +4016,7 @@ export class InspectorClient extends InspectorClientEventTarget {
: this.client!.request(
{ method: "tools/list", params },
pageSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
{ method: "tools/list" },
);
@ -4016,8 +4108,8 @@ export class InspectorClient extends InspectorClientEventTarget {
async callTool(
tool: Tool,
args: Record<string, JsonValue>,
generalMetadata?: Record<string, string>,
toolSpecificMetadata?: Record<string, string>,
generalMetadata?: RequestMetadata,
toolSpecificMetadata?: RequestMetadata,
taskOptions?: { ttl?: number },
options?: { skipOutputValidation?: boolean },
): Promise<ToolCallInvocation> {
@ -4245,7 +4337,7 @@ export class InspectorClient extends InspectorClientEventTarget {
const convertedArgs = this.convertStringToolArgs(tool, args);
// Merge general metadata with tool-specific metadata; tool-specific wins.
const callMetadata: Record<string, string> | undefined =
const callMetadata: RequestMetadata | undefined =
generalMetadata || toolSpecificMetadata
? { ...(generalMetadata || {}), ...(toolSpecificMetadata || {}) }
: undefined;
@ -4258,7 +4350,7 @@ export class InspectorClient extends InspectorClientEventTarget {
const callParams: {
name: string;
arguments: Record<string, JsonValue>;
_meta?: Record<string, string>;
_meta?: RequestMetadata;
task?: { ttl: number };
} = {
name: tool.name,
@ -4270,7 +4362,7 @@ export class InspectorClient extends InspectorClientEventTarget {
}
const requestOptions = this.getRequestOptions(
metadata?.progressToken,
this.progressTokenOf(metadata),
signal,
);
this.applyMirroredParamHeaders(tool, convertedArgs, requestOptions);
@ -4360,11 +4452,11 @@ export class InspectorClient extends InspectorClientEventTarget {
private dispatchFailedToolCall(
tool: Tool,
args: Record<string, JsonValue>,
generalMetadata: Record<string, string> | undefined,
toolSpecificMetadata: Record<string, string> | undefined,
generalMetadata: RequestMetadata | undefined,
toolSpecificMetadata: RequestMetadata | undefined,
errorMessage: string,
): void {
const callMetadata: Record<string, string> | undefined =
const callMetadata: RequestMetadata | undefined =
generalMetadata || toolSpecificMetadata
? { ...(generalMetadata || {}), ...(toolSpecificMetadata || {}) }
: undefined;
@ -4848,8 +4940,8 @@ export class InspectorClient extends InspectorClientEventTarget {
async callToolStream(
tool: Tool,
args: Record<string, JsonValue>,
generalMetadata?: Record<string, string>,
toolSpecificMetadata?: Record<string, string>,
generalMetadata?: RequestMetadata,
toolSpecificMetadata?: RequestMetadata,
taskOptions?: { ttl?: number },
): Promise<ToolCallInvocation> {
if (!this.client) {
@ -4859,7 +4951,7 @@ export class InspectorClient extends InspectorClientEventTarget {
const convertedArgs = this.convertStringToolArgs(tool, args);
// Merge general metadata with tool-specific metadata; tool-specific wins.
const callMetadata: Record<string, string> | undefined =
const callMetadata: RequestMetadata | undefined =
generalMetadata || toolSpecificMetadata
? { ...(generalMetadata || {}), ...(toolSpecificMetadata || {}) }
: undefined;
@ -4895,7 +4987,9 @@ export class InspectorClient extends InspectorClientEventTarget {
// attach one here either — doing so would request a progress token (and
// emit requestorTaskProgress) for task calls only, bypassing the toggle
// that governs every other call path.
const requestOptions = this.getRequestOptions(metadata?.progressToken);
const requestOptions = this.getRequestOptions(
this.progressTokenOf(metadata),
);
// The task-augmented `tools/call` needs the same SEP-2243 mirroring as the
// plain one — a strict modern server rejects it with -32020 otherwise.
this.applyMirroredParamHeaders(tool, convertedArgs, requestOptions);
@ -5056,7 +5150,7 @@ export class InspectorClient extends InspectorClientEventTarget {
return invocation;
} catch (error) {
// Merge general metadata with tool-specific metadata for error case
const callMetadata: Record<string, string> | undefined =
const callMetadata: RequestMetadata | undefined =
generalMetadata || toolSpecificMetadata
? { ...(generalMetadata || {}), ...(toolSpecificMetadata || {}) }
: undefined;
@ -5086,7 +5180,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listResources(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ resources: Resource[]; nextCursor?: string }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5100,7 +5194,7 @@ export class InspectorClient extends InspectorClientEventTarget {
this.client!.request(
{ method: "resources/list", params },
ListResourcesResultSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
);
return {
@ -5117,7 +5211,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listAllResources(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ resources: Resource[] }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5148,7 +5242,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async readResource(
uri: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<ResourceReadInvocation> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5167,7 +5261,7 @@ export class InspectorClient extends InspectorClientEventTarget {
"resources/read",
params,
ReadResourceResultSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
{ method: "resources/read" },
);
@ -5198,7 +5292,7 @@ export class InspectorClient extends InspectorClientEventTarget {
async readResourceFromTemplate(
uriTemplate: string,
params: Record<string, string>,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<ResourceTemplateReadInvocation> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5260,7 +5354,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listResourceTemplates(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ resourceTemplates: ResourceTemplate[]; nextCursor?: string }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5275,7 +5369,7 @@ export class InspectorClient extends InspectorClientEventTarget {
this.client!.request(
{ method: "resources/templates/list", params },
ListResourceTemplatesResultSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
{ method: "resources/templates/list" },
);
@ -5293,7 +5387,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listAllResourceTemplates(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ resourceTemplates: ResourceTemplate[] }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5324,7 +5418,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listPrompts(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ prompts: Prompt[]; nextCursor?: string }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5338,7 +5432,7 @@ export class InspectorClient extends InspectorClientEventTarget {
this.client!.request(
{ method: "prompts/list", params },
ListPromptsResultSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
);
return {
@ -5355,7 +5449,7 @@ export class InspectorClient extends InspectorClientEventTarget {
*/
async listAllPrompts(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ prompts: Prompt[] }> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5388,7 +5482,7 @@ export class InspectorClient extends InspectorClientEventTarget {
async getPrompt(
name: string,
args?: Record<string, JsonValue>,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<PromptGetInvocation> {
if (!this.client) {
throw new Error("Client is not connected");
@ -5412,7 +5506,7 @@ export class InspectorClient extends InspectorClientEventTarget {
"prompts/get",
params,
GetPromptResultSchema,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
{ method: "prompts/get", toolName: name },
);
@ -5451,7 +5545,7 @@ export class InspectorClient extends InspectorClientEventTarget {
argumentName: string,
argumentValue: string,
context?: Record<string, string>,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ values: string[]; total?: number; hasMore?: boolean }> {
if (!this.client) {
return { values: [] };
@ -5473,7 +5567,7 @@ export class InspectorClient extends InspectorClientEventTarget {
() =>
this.client!.complete(
params,
this.getRequestOptions(metadata?.progressToken),
this.getRequestOptions(this.progressTokenOf(metadata)),
),
{
method: "completion/complete",

View file

@ -25,6 +25,7 @@ import type {
ResourceTemplateReadInvocation,
ResourceSubscriptionStreamState,
ExcludedTool,
RequestMetadata,
} from "./types.js";
import type { MalformedListItem } from "./listSalvage.js";
import type {
@ -112,7 +113,7 @@ export interface InspectorClientEventMap {
timestamp: Date;
success: boolean;
error?: string;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
/** Non-fatal outputSchema mismatch detected on the skipOutputValidation path. */
outputValidationError?: string;
};

View file

@ -21,6 +21,7 @@ import type {
ToolCallInvocation,
ResourceSubscriptionStreamState,
ExcludedTool,
RequestMetadata,
} from "./types.js";
import type {
CacheMode,
@ -82,19 +83,19 @@ export interface InspectorClientProtocol extends InspectorClientEventTarget {
// Paginated list methods used by managed/paged state stores
listTools(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ tools: Tool[]; nextCursor?: string }>;
listPrompts(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ prompts: Prompt[]; nextCursor?: string }>;
listResources(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ resources: Resource[]; nextCursor?: string }>;
listResourceTemplates(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ resourceTemplates: ResourceTemplate[]; nextCursor?: string }>;
listRequestorTasks(
cursor?: string,
@ -126,41 +127,41 @@ export interface InspectorClientProtocol extends InspectorClientEventTarget {
// `cacheMode` uses the SDK default ('use').
listAllTools(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ tools: Tool[] }>;
listAllPrompts(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ prompts: Prompt[] }>;
listAllResources(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): Promise<{ resources: Resource[] }>;
listAllResourceTemplates(options?: {
cacheMode?: CacheMode;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}): 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>,
generalMetadata?: RequestMetadata,
toolSpecificMetadata?: RequestMetadata,
): Promise<ToolCallInvocation>;
readResource(
uri: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<ResourceReadInvocation>;
readResourceFromTemplate(
uriTemplate: string,
params: Record<string, string>,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<ResourceTemplateReadInvocation>;
getPrompt(
name: string,
params?: Record<string, string>,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<PromptGetInvocation>;
// Misc surface required by hooks/state
@ -182,6 +183,6 @@ export interface InspectorClientProtocol extends InspectorClientEventTarget {
argumentName: string,
argumentValue: string,
context?: Record<string, string>,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<{ values: string[]; total?: number; hasMore?: boolean }>;
}

View file

@ -49,7 +49,7 @@ export function headersToServerSettings(
return {
headers: Object.entries(headers).map(([key, value]) => ({ key, value })),
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: DEFAULT_TASK_TTL_MS,

View file

@ -42,6 +42,7 @@ import {
} from "../../types.js";
import type {
InspectorServerSettings,
RequestMetadata,
MCPConfig,
MCPServerConfig,
StdioServerConfig,
@ -1220,6 +1221,20 @@ export function createRemoteApp(
// credentials are intentionally lost on first read (hard cutover per
// #1358 decision 4). Users re-enter via the form or hand-edit into the
// flat shape.
// The *container* `_meta` requires — a plain JSON object.
//
// Value-level validity is deliberately not checked here. Values are
// arbitrary JSON (#1910), and the one class that survives `JSON.parse` yet
// cannot be sent — a non-finite number, from a literal like `1e400` in a
// hand-edited catalog — is filtered **per key** by
// `normalizeStoredMetadata`, which every read routes through. Rejecting the
// whole field here instead would cost a user every other key they had
// configured, for one bad value.
//
// Note the wire cannot carry the bad case at all: a client's own
// `JSON.stringify` turns `Infinity` into `null` before the request is sent.
const isJsonObject = (v: unknown): v is RequestMetadata =>
v !== null && typeof v === "object" && !Array.isArray(v);
const isStringRecord = (v: unknown): v is Record<string, string> => {
if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
for (const val of Object.values(v as Record<string, unknown>)) {
@ -1332,10 +1347,18 @@ export function createRemoteApp(
);
delete valObj.headers;
}
if ("metadata" in valObj && !isKvArray(valObj.metadata)) {
// A JSON object post-#1910; the pre-#1910 `{ key, value }[]` pair array
// is still accepted so an existing file keeps working (it is normalized
// by `normalizeStoredMetadata` on the way into the settings shape, and
// rewritten as an object on the next save).
if (
"metadata" in valObj &&
!isJsonObject(valObj.metadata) &&
!isKvArray(valObj.metadata)
) {
logWarn(
{ route: "/api/servers", id, droppedKey: "metadata" },
"Dropping malformed `metadata` field — expected `Array<{ key: string, value: string }>`.",
"Dropping malformed `metadata` field — expected a JSON object.",
);
delete valObj.metadata;
}
@ -1564,10 +1587,14 @@ export function createRemoteApp(
error: "settings.headers must be an array of { key, value }",
};
}
if (!isKvArray(obj.metadata)) {
// `_meta` takes any JSON, so metadata crosses the wire as a plain JSON
// object rather than the `{ key, value }` rows headers/env still use
// (#1910). Only the container is checked — the values are arbitrary JSON
// by design, and anything that survived `c.req.json()` already is.
if (!isJsonObject(obj.metadata)) {
return {
ok: false,
error: "settings.metadata must be an array of { key, value }",
error: "settings.metadata must be a JSON object",
};
}
// env is optional on the wire (older clients / non-stdio servers won't send
@ -1743,7 +1770,7 @@ export function createRemoteApp(
// Absent → empty list, matching the read side. The write-through drops
// empty-key rows and clears `config.env` when the list is empty.
env: isKvArray(obj.env) ? obj.env : [],
metadata: obj.metadata as { key: string; value: string }[],
metadata: obj.metadata as RequestMetadata,
connectionTimeout: obj.connectionTimeout as number,
requestTimeout: obj.requestTimeout as number,
// Absent → product default, matching the read side

View file

@ -15,6 +15,7 @@ import {
import type { Root } from "@modelcontextprotocol/client";
import type {
InspectorServerSettings,
RequestMetadata,
MCPConfig,
MCPServerConfig,
ServerEntry,
@ -28,6 +29,8 @@ import {
envSecretField,
} from "../auth/secret-fields.js";
import { toRecord } from "../json/jsonUtils.js";
import type { JsonValue } from "../json/jsonUtils.js";
import { isSerializableJson } from "../json/jsonUtils.js";
// The full set of valid `type` discriminator values, used to reject anything
// else read off disk so unknown strings can't propagate to narrowing sites.
@ -194,6 +197,130 @@ export function envPairsToRecord(
return out;
}
/**
* Read a server's `metadata` off disk into the in-memory `RequestMetadata`
* object, accepting both the current object shape and the pre-#1910
* `{ key, value }[]` pair array.
*
* The pair array is the shape every `mcp.json` written before #1910 carries, so
* dropping it would silently stop sending a user's configured `_meta` on the
* first read of an existing file. It is read here and never written back:
* `inspectorSettingsToStoredFields` emits only the object form, so the file is
* migrated the next time the entry is saved.
*
* Anything else — a string, a number, an array of non-pairs — is not metadata
* the Inspector can send, so it is dropped with a warning rather than half-
* interpreted, following `cleanRoots` / `cleanAuthorizationParams` above. A
* pair whose key is blank is skipped for the same reason the write side omits
* it: `_meta` has no meaningful empty key.
*/
export function normalizeStoredMetadata(
metadata: StoredMCPServer["metadata"] | unknown,
): RequestMetadata {
if (metadata === undefined || metadata === null) return {};
if (Array.isArray(metadata)) {
const out: RequestMetadata = {};
for (const entry of metadata) {
if (
typeof entry !== "object" ||
entry === null ||
typeof (entry as { key?: unknown }).key !== "string"
) {
// Structural message only — never the entry. A malformed legacy row
// still holds whatever the user put in it, which for `_meta` can be a
// credential, and this goes to the console of every client that reads
// the catalog.
console.warn(
"Ignoring malformed legacy metadata entry (expected `{ key, value }`).",
);
continue;
}
const { key, value } = entry as { key: string; value?: JsonValue };
if (key.trim() === "") continue;
// `??`, not `||`: `null` is a legal `_meta` value and must survive the
// migration as `null`. Only a genuinely absent `value` becomes `""`.
const resolved = value === undefined ? "" : value;
if (!keepSerializable(key, resolved)) continue;
defineMetadataKey(out, key, resolved);
}
return out;
}
if (typeof metadata === "object") {
// A hand-edited catalog reaches this untouched by any editor, so it is a
// real source of values that parse but cannot be sent — `1e400` becomes
// `Infinity`, which the next serialization writes as `null`. Same
// invariant the web editor and the CLI enforce, applied per key so one bad
// value does not cost the rest.
const out: RequestMetadata = {};
for (const [key, value] of Object.entries(metadata as RequestMetadata)) {
if (keepSerializable(key, value)) defineMetadataKey(out, key, value);
}
return out;
}
console.warn(
`Ignoring malformed \`metadata\` (expected a JSON object, got ${describeJsonType(metadata)}).`,
);
return {};
}
/**
* Store a metadata key as an **own** property.
*
* `out[key] = value` invokes the prototype setter for the key `"__proto__"`,
* so the entry vanishes on reload and — for an object value — the returned
* metadata is given a caller-controlled prototype. `_meta` keys come from a
* file a user (or something that wrote that file) controls, so `"__proto__"`
* is a key that can genuinely arrive.
*
* Both branches of `normalizeStoredMetadata` go through this rather than each
* spelling it out. The object branch was originally a spread — safe, because
* spread defines rather than sets — and rewriting it into a per-key loop for
* value filtering silently reintroduced the hazard the legacy branch had
* already fixed. One mechanism is what stops that recurring.
*/
function defineMetadataKey(
out: RequestMetadata,
key: string,
value: JsonValue,
): void {
Object.defineProperty(out, key, {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
/**
* Whether a metadata value can be sent as written, warning by key when it
* cannot.
*
* Names the key and the offending type, never the value: `_meta` carries
* whatever the user configured, credentials included, and these warnings reach
* ordinary console output.
*/
function keepSerializable(key: string, value: unknown): boolean {
if (isSerializableJson(value)) return true;
console.warn(
`Ignoring metadata key "${key}" — its value is not JSON that can be sent ` +
`(got ${describeJsonType(value)}; note \`1e400\` parses to Infinity).`,
);
return false;
}
/** A one-word type name for a diagnostic that must not disclose the value. */
function describeJsonType(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
if (typeof value === "number" && !Number.isFinite(value)) {
return Number.isNaN(value) ? "NaN" : "a non-finite number";
}
return typeof value;
}
/**
* Validate a server's `oauth.authorizationParams` as it comes off disk, or
* `undefined` when there is nothing usable. (#2018)
@ -349,7 +476,7 @@ export function storedFieldsToInspectorSettings(
const settings: InspectorServerSettings = {
headers: headersPairs,
env: envRecordToPairs(stored.env),
metadata: stored.metadata ?? [],
metadata: normalizeStoredMetadata(stored.metadata),
connectionTimeout: stored.connectionTimeout ?? 0,
requestTimeout: stored.requestTimeout ?? 0,
// Unlike the timeouts (0 = "SDK default"), task TTL has a concrete product
@ -458,9 +585,11 @@ export function inspectorSettingsToStoredFields(
out.headers = headersRecord;
}
const metadataFiltered = settings.metadata.filter((m) => m.key.trim() !== "");
if (metadataFiltered.length > 0) {
out.metadata = metadataFiltered;
// Blank-key entries can't exist in the object form (an object has no blank
// key the user can leave mid-edit, the way a `{key,value}` row could), so
// there is nothing to filter — only the empty-object case to omit.
if (Object.keys(settings.metadata).length > 0) {
out.metadata = settings.metadata;
}
if (settings.connectionTimeout > 0) {

View file

@ -19,6 +19,7 @@ import type {
} from "@modelcontextprotocol/client";
import { isClientDecodeRejection } from "../listSalvage.js";
import { isTerminalStatus } from "../types.js";
import type { RequestMetadata } from "../types.js";
import { TypedEventTarget } from "../typedEventTarget.js";
/**
@ -67,7 +68,7 @@ export interface ManagedListConfig<T, M extends ManagedListEventMap> {
fetchAll: (
client: InspectorClientProtocol,
cacheMode: CacheMode | undefined,
metadata: Record<string, string> | undefined,
metadata: RequestMetadata | undefined,
) => Promise<T[]>;
/**
* Whether this list drives a list-changed indicator. When true, a
@ -97,7 +98,7 @@ export abstract class ManagedListState<
protected items: T[] = [];
protected client: InspectorClientProtocol | null = null;
private unsubscribe: (() => void) | null = null;
private _metadata: Record<string, string> | undefined = undefined;
private _metadata: RequestMetadata | 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
@ -282,7 +283,7 @@ export abstract class ManagedListState<
this.emit("errorChange", value);
}
setMetadata(metadata?: Record<string, string>): void {
setMetadata(metadata?: RequestMetadata): void {
this._metadata = metadata;
}
@ -299,7 +300,7 @@ export abstract class ManagedListState<
* the `list_changed` auto-refresh) catch it explicitly (#1953).
*/
async refresh(
metadata?: Record<string, string>,
metadata?: RequestMetadata,
cacheMode?: CacheMode,
): Promise<T[]> {
let next: T[] | null;
@ -336,7 +337,7 @@ export abstract class ManagedListState<
* the console; empty list is the right semantics).
*/
private async fetchItems(
metadata: Record<string, string> | undefined,
metadata: RequestMetadata | undefined,
cacheMode: CacheMode | undefined,
): Promise<T[] | null> {
const client = this.client;

View file

@ -15,6 +15,7 @@
import type { InspectorClientProtocol } from "../inspectorClientProtocol.js";
import type { Prompt } from "@modelcontextprotocol/client";
import { isTerminalStatus } from "../types.js";
import type { RequestMetadata } from "../types.js";
import { TypedEventTarget } from "../typedEventTarget.js";
import type { PagePaginationState } from "./pagedToolsState.js";
@ -112,7 +113,7 @@ export class PagedPromptsState extends TypedEventTarget<PagedPromptsStateEventMa
async loadPage(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<LoadPageResult> {
const c = this.client;
if (!c || c.getStatus() !== "connected") {

View file

@ -14,6 +14,7 @@
import type { InspectorClientProtocol } from "../inspectorClientProtocol.js";
import type { ResourceTemplateType as ResourceTemplate } from "@modelcontextprotocol/client";
import { isTerminalStatus } from "../types.js";
import type { RequestMetadata } from "../types.js";
import { TypedEventTarget } from "../typedEventTarget.js";
export interface PagedResourceTemplatesStateEventMap {
@ -59,7 +60,7 @@ export class PagedResourceTemplatesState extends TypedEventTarget<PagedResourceT
async loadPage(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<LoadPageResult> {
const c = this.client;
if (!c || c.getStatus() !== "connected") {

View file

@ -16,6 +16,7 @@
import type { InspectorClientProtocol } from "../inspectorClientProtocol.js";
import type { Resource } from "@modelcontextprotocol/client";
import { isTerminalStatus } from "../types.js";
import type { RequestMetadata } from "../types.js";
import { TypedEventTarget } from "../typedEventTarget.js";
import type { PagePaginationState } from "./pagedToolsState.js";
@ -113,7 +114,7 @@ export class PagedResourcesState extends TypedEventTarget<PagedResourcesStateEve
async loadPage(
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<LoadPageResult> {
const c = this.client;
if (!c || c.getStatus() !== "connected") {

View file

@ -24,7 +24,11 @@ import type { OAuthClientProvider } from "@modelcontextprotocol/client";
import type { Transport } from "@modelcontextprotocol/client";
import type { InspectorLogger } from "../logging/logger.js";
import type { AppElicitationRenderer } from "./appElicitation.js";
import type { JsonValue } from "../json/jsonUtils.js";
import type {
JsonValue,
StrictJsonObject,
StrictJsonValue,
} from "../json/jsonUtils.js";
import type {
ClientConfig,
EnterpriseManagedAuthIdpConfig,
@ -99,11 +103,20 @@ export type StoredMCPServer = MCPServerConfig & {
*/
headers?: Record<string, string>;
/**
* Default `_meta` keys merged into every outgoing MCP request. Inspector-
* specific (no analog in the broader mcp.json ecosystem), so the pair-array
* shape is preserved on disk and in memory.
* Default `_meta` payload merged into every outgoing MCP request. Inspector-
* specific (no analog in the broader mcp.json ecosystem).
*
* A JSON object, so a value may be any JSON — object, array, number, boolean,
* `null` — not just a string (#1910). Nothing in the MCP spec restricts
* `_meta` to string values, and the SDK models it as a passthrough object;
* the string-pair restriction was the Inspector's own.
*
* The pre-#1910 on-disk shape was a `{ key, value }[]` pair array. It is
* still **read** (see `normalizeStoredMetadata` in `serverList.ts`) so an
* existing `mcp.json` keeps working, but it is never written back — a
* round-trip through the Inspector rewrites the field as an object.
*/
metadata?: { key: string; value: string }[];
metadata?: StrictJsonObject;
/**
* Protocol era to negotiate with this server (`"legacy" | "auto" | "modern"`),
* orthogonal to the transport `type`. Inspector-specific (no analog in the
@ -361,6 +374,24 @@ export interface ServerState {
stderrLogs: StderrLogEntry[];
}
/**
* A `_meta` payload: a JSON object whose values may be any JSON, not just
* strings (#1910).
*
* {@link StrictJsonValue}, not `JsonValue`: the latter admits `undefined`,
* which `JSON.stringify` drops from an object and turns into `null` inside an
* array — so a value the type accepted would not be the value that reaches the
* server, contradicting the one promise this payload makes.
*
* The MCP spec places no restriction on `_meta` value types and the SDK models
* the field as a passthrough object, so the Inspector must be able to send —
* and to record — nested objects, arrays, numbers, booleans and `null`. Used
* for both the per-server default payload (`InspectorServerSettings.metadata`,
* `InspectorClientOptions.defaultMetadata`) and the per-call metadata every
* request verb accepts.
*/
export type RequestMetadata = Record<string, StrictJsonValue>;
/**
* Represents a complete resource read invocation, including request parameters,
* response, and metadata.
@ -369,7 +400,7 @@ export interface ResourceReadInvocation {
result: ReadResourceResult;
timestamp: Date;
uri: string;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}
/**
@ -382,7 +413,7 @@ export interface ResourceTemplateReadInvocation {
result: ReadResourceResult;
timestamp: Date;
params: Record<string, string>;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}
/**
@ -394,7 +425,7 @@ export interface PromptGetInvocation {
timestamp: Date;
name: string;
params?: Record<string, string>;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
}
/**
@ -408,7 +439,7 @@ export interface ToolCallInvocation {
timestamp: Date;
success: boolean;
error?: string;
metadata?: Record<string, string>;
metadata?: RequestMetadata;
/**
* Set only on the `skipOutputValidation` path: present when the (delivered)
* result's structuredContent does NOT match the tool's declared outputSchema.
@ -689,7 +720,12 @@ export function eraToVersionNegotiation(
*/
export interface InspectorServerSettings {
headers: { key: string; value: string }[];
metadata: { key: string; value: string }[];
/**
* Default `_meta` payload for this server, edited as a JSON object rather
* than key/value rows so a value can be any JSON (#1910). Always present;
* `{}` means "send no default metadata".
*/
metadata: RequestMetadata;
/**
* Environment variables for stdio servers, edited as controlled key/value
* rows (mirrors `headers`). Only meaningful for stdio transports; non-stdio
@ -1080,7 +1116,7 @@ export interface InspectorClientOptions {
* site metadata wins on key collision. Set this from `InspectorServerSettings.metadata`
* so persisted server-wide metadata reaches the wire on the first request.
*/
defaultMetadata?: Record<string, string>;
defaultMetadata?: RequestMetadata;
/**
* Optional per-server runtime settings forwarded to the transport factory

View file

@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import type { InspectorClientProtocol } from "../mcp/inspectorClientProtocol.js";
import type { RequestMetadata } from "../mcp/types.js";
import type {
PagedPromptsState,
PagedPromptsStateEventMap,
@ -23,7 +24,7 @@ export interface UsePagedPromptsResult {
error: Error | null;
loadPage: (
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
) => Promise<LoadPageResult>;
clear: () => void;
}
@ -84,7 +85,7 @@ export function usePagedPrompts(
const loadPage = useCallback(
async (
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<LoadPageResult> => {
if (!pagedPromptsState || !client) {
return { prompts: [], nextCursor: undefined };

View file

@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import type { InspectorClientProtocol } from "../mcp/inspectorClientProtocol.js";
import type { RequestMetadata } from "../mcp/types.js";
import type {
PagedResourceTemplatesState,
PagedResourceTemplatesStateEventMap,
@ -12,7 +13,7 @@ export interface UsePagedResourceTemplatesResult {
resourceTemplates: ResourceTemplate[];
loadPage: (
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
) => Promise<LoadPageResult>;
clear: () => void;
}
@ -58,7 +59,7 @@ export function usePagedResourceTemplates(
const loadPage = useCallback(
async (
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<LoadPageResult> => {
if (!pagedResourceTemplatesState || !client) {
return { resourceTemplates: [], nextCursor: undefined };

View file

@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import type { InspectorClientProtocol } from "../mcp/inspectorClientProtocol.js";
import type { RequestMetadata } from "../mcp/types.js";
import type {
PagedResourcesState,
PagedResourcesStateEventMap,
@ -23,7 +24,7 @@ export interface UsePagedResourcesResult {
error: Error | null;
loadPage: (
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
) => Promise<LoadPageResult>;
clear: () => void;
}
@ -90,7 +91,7 @@ export function usePagedResources(
const loadPage = useCallback(
async (
cursor?: string,
metadata?: Record<string, string>,
metadata?: RequestMetadata,
): Promise<LoadPageResult> => {
if (!pagedResourcesState || !client) {
return { resources: [], nextCursor: undefined };

View file

@ -62,6 +62,25 @@ export interface UseServersResult {
importSource: (type: string) => Promise<ImportSourceResult>;
}
/**
* Thrown when a mutation's *write* landed but reading the list back
* afterwards failed — see `refreshAfterWrite`.
*
* Distinct from a rejected write because the two call for opposite handling
* in an optimistic caller. The pagination toggle in `App.tsx` reverts its
* optimistic override and rolls the live client back on a rejection, which is
* right for a failed PUT and wrong here: the setting *is* on disk, so the
* rollback would show the user a value that no longer matches it. Callers
* that update optimistically must branch on this; callers that only report
* (the modals) can treat it as any other error.
*/
export class ServerListReloadError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = "ServerListReloadError";
}
}
function buildHeaders(
authToken: string | undefined,
includeJsonBody: boolean,
@ -132,33 +151,78 @@ export function useServers(opts: UseServersOptions): UseServersResult {
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | undefined>(undefined);
// The list read itself, throwing on failure. Every refresh path goes
// through it; they differ only in what they do with a rejection.
const loadServers = useCallback(async (): Promise<ServerEntry[]> => {
const res = await doFetch(`${base}/api/servers`, {
method: "GET",
headers: buildHeaders(authToken, false),
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const body = (await res.json()) as MCPConfig;
return mcpConfigToServerEntries(body);
}, [base, authToken, doFetch]);
// Inner refresh that the public `refresh` and the SSE-triggered background
// refresh both share. `background` skips the loading-state toggle so
// consumers rendering a spinner or skeleton don't flash on every external
// mcp.json edit — the existing list stays on screen while the re-fetch
// resolves. `error` is still reset / set either way so a real error
// surfaces even from a background refresh.
//
// A failure is recorded in `error` and NOT rethrown: the two callers are
// the mount effect and the SSE loop, neither of which has anywhere to put
// a rejection. Post-write reloads use `refreshAfterWrite` instead.
const refreshInternal = useCallback(
async (background: boolean): Promise<void> => {
if (!background) setLoading(true);
setError(undefined);
try {
const res = await doFetch(`${base}/api/servers`, {
method: "GET",
headers: buildHeaders(authToken, false),
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const body = (await res.json()) as MCPConfig;
setServers(mcpConfigToServerEntries(body));
setServers(await loadServers());
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
if (!background) setLoading(false);
}
},
[base, authToken, doFetch],
[loadServers],
);
// Post-write reload, used by every mutator. Unlike `refreshInternal` it
// rethrows, because a mutator's caller learns that something went wrong
// only from a rejection — `ServerConfigModal` renders `submitError` for a
// thrown error and nothing else, so a successful POST followed by a failed
// GET closed the Add Server modal as though the whole thing had worked
// (#1914). The reported failure was silent for exactly this reason.
//
// The message says the write landed, because it did: only reading the list
// back failed. A bare "could not add server" would send the user straight
// into a retry that trips the duplicate-id check, which is the dead end the
// original report described.
//
// The rejection is a `ServerListReloadError` rather than a bare `Error` so
// an optimistic caller can tell it from a failed write and skip its
// rollback — reverting here would contradict what is actually on disk.
const refreshAfterWrite = useCallback(
async (verb: string): Promise<void> => {
setLoading(true);
setError(undefined);
try {
setServers(await loadServers());
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
setError(message);
throw new ServerListReloadError(
`The server was ${verb}, but the server list could not be reloaded: ${message}`,
{ cause: err },
);
} finally {
setLoading(false);
}
},
[loadServers],
);
const refresh = useCallback(
@ -241,9 +305,9 @@ export function useServers(opts: UseServersOptions): UseServersResult {
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
await refresh();
await refreshAfterWrite("added");
},
[base, authToken, doFetch, refresh],
[base, authToken, doFetch, refreshAfterWrite],
);
const importSource = useCallback(
@ -282,9 +346,9 @@ export function useServers(opts: UseServersOptions): UseServersResult {
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
await refresh();
await refreshAfterWrite("saved");
},
[base, authToken, doFetch, refresh],
[base, authToken, doFetch, refreshAfterWrite],
);
const updateServerSettings = useCallback(
@ -307,9 +371,9 @@ export function useServers(opts: UseServersOptions): UseServersResult {
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
await refresh();
await refreshAfterWrite("saved");
},
[base, authToken, doFetch, refresh],
[base, authToken, doFetch, refreshAfterWrite],
);
const removeServer = useCallback(
@ -324,9 +388,9 @@ export function useServers(opts: UseServersOptions): UseServersResult {
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
await refresh();
await refreshAfterWrite("removed");
},
[base, authToken, doFetch, refresh],
[base, authToken, doFetch, refreshAfterWrite],
);
const reorderServers = useCallback(