feat: allow complex JSON values in request _meta

Closes #1910

`_meta` was typed `Record<string, string>` end to end in the Inspector —
on disk as a `{ key, value }[]` pair array, in the Server Settings form as
key/value rows, and in every request verb's per-call metadata parameter.
Nothing in the MCP spec restricts a `_meta` value to a string, and the SDK
models the field as a `z.looseObject`, so the restriction was ours alone.

Widen the whole path to `RequestMetadata` (`Record<string, JsonValue>`):

- Per-server default metadata is a JSON **object** on disk and in memory.
  The pre-#1910 pair array is still read (`normalizeStoredMetadata`) so an
  existing `mcp.json` keeps working; it is never written back, so a save
  migrates the entry.
- The Server Settings → Request Metadata section is a JSON editor
  (`JsonObjectInput`) instead of key/value rows — rows cannot express an
  object value. It keeps the typed text as the display source and emits
  only parsed JSON, the same draft split `SchemaJsonField` uses, so the box
  stays typeable; invalid text is flagged inline and not applied.
- The CLI stops flattening `--metadata` / `--tool-metadata` through
  `metaValueToString`. Those values were already JSON-parsed, so
  `trace={"id":"abc"}` used to reach the wire as the *string* `{"id":"abc"}`
  and now reaches it as an object.
- `servers/show` redaction replaces a sensitive key's whole value rather
  than a string, so a structured value cannot leak through its members.
- `progressTokenOf` narrows the reserved `progressToken` key back to
  `string | number` before it reaches the SDK; any other JSON still travels
  inside `_meta` but wires up no progress callback.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0177mPHAdECD18nLLCTwR5rh
Signed-off-by: cliffhall <cliff@futurescale.com>
This commit is contained in:
cliffhall 2026-08-23 12:23:40 -04:00
commit b33532c024
31 changed files with 1004 additions and 495 deletions

View file

@ -1635,7 +1635,7 @@ const settingsWithRoots = (
): InspectorServerSettings => ({
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

View file

@ -384,7 +384,7 @@ async function replayProtocolRequest(
const EMPTY_SETTINGS: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: DEFAULT_TASK_TTL_MS,
@ -2466,13 +2466,9 @@ function App() {
const activeCimdUrl = getActiveCimdClientMetadataUrl(clientConfig);
// Flatten the persisted settings into the InspectorClient options shape.
// Empty / zero values stay unset so the SDK defaults apply.
const defaultMetadata = savedSettings?.metadata
? Object.fromEntries(
savedSettings.metadata
.filter((m) => m.key.trim() !== "")
.map((m) => [m.key, m.value]),
)
: undefined;
// Per-server default `_meta` is already a JSON object (#1910) — no
// pair-array flattening left to do; `{}` means "no defaults".
const defaultMetadata = savedSettings?.metadata;
const serverAuthorizationParams = savedSettings
? oauthAuthorizationParamsFromSettings(savedSettings)
: undefined;

View file

@ -0,0 +1,92 @@
import { useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, within } from "storybook/test";
import type { JsonObject } from "@inspector/core/json/jsonUtils.js";
import { JsonObjectInput } from "./JsonObjectInput";
/**
* The component is controlled, so every story drives it through a small
* stateful wrapper — otherwise the box would not accept a keystroke and the
* play functions could not exercise the draft behavior at all.
*/
function ControlledJsonObjectInput({ initial }: { initial: JsonObject }) {
const [value, setValue] = useState<JsonObject>(initial);
return (
<JsonObjectInput
label="Request metadata"
aria-label="Request metadata JSON"
value={value}
onChange={setValue}
/>
);
}
const meta: Meta<typeof ControlledJsonObjectInput> = {
title: "Elements/JsonObjectInput",
component: ControlledJsonObjectInput,
};
export default meta;
type Story = StoryObj<typeof ControlledJsonObjectInput>;
/** A structured payload renders as formatted JSON, nesting intact. */
export const Populated: Story = {
args: {
initial: {
tenant: "acme",
trace: { id: "abc123", sampled: true },
features: ["apps", "tasks"],
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const box = await canvas.findByLabelText("Request metadata JSON");
await expect(JSON.parse((box as HTMLTextAreaElement).value)).toEqual({
tenant: "acme",
trace: { id: "abc123", sampled: true },
features: ["apps", "tasks"],
});
},
};
/** An empty payload opens as `{}` and carries no error. */
export const Empty: Story = {
args: { initial: {} },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const box = await canvas.findByLabelText("Request metadata JSON");
await expect(box).toHaveValue("{}");
await expect(canvas.queryByText(/Not valid JSON/)).toBeNull();
},
};
/**
* Half-typed text is displayed as typed and flagged, rather than being
* re-escaped back into the box each keystroke (the #1928 failure this draft
* split exists to avoid).
*/
export const InvalidDraft: Story = {
args: { initial: {} },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const box = await canvas.findByLabelText("Request metadata JSON");
await userEvent.clear(box);
await userEvent.type(box, '{{"a":');
await expect(box).toHaveValue('{"a":');
await expect(await canvas.findByText(/Not valid JSON/)).toBeVisible();
},
};
/** Valid JSON that is not an object is rejected with its own message. */
export const NotAnObject: Story = {
args: { initial: {} },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const box = await canvas.findByLabelText("Request metadata JSON");
await userEvent.clear(box);
await userEvent.type(box, "[[1,2]");
await expect(
await canvas.findByText(/Must be a JSON object/),
).toBeVisible();
},
};

View file

@ -0,0 +1,172 @@
import { useState } from "react";
import { describe, it, expect, vi } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { JsonObject } from "@inspector/core/json/jsonUtils.js";
import { renderWithMantine } from "../../../test/renderWithMantine";
import { JsonObjectInput, parseObjectDraft } from "./JsonObjectInput";
const LABEL = "Payload JSON";
/** Controlled harness: the component never owns the value, only the draft. */
function Harness({
initial,
onChange,
}: {
initial: JsonObject;
onChange?: (v: JsonObject) => void;
}) {
const [value, setValue] = useState<JsonObject>(initial);
return (
<>
<JsonObjectInput
aria-label={LABEL}
value={value}
onChange={(next) => {
setValue(next);
onChange?.(next);
}}
/>
<output data-testid="emitted">{JSON.stringify(value)}</output>
</>
);
}
function box() {
return screen.getByLabelText(LABEL) as HTMLTextAreaElement;
}
describe("parseObjectDraft", () => {
it("reads empty text as the empty object rather than an error", () => {
expect(parseObjectDraft("")).toEqual({ ok: true, value: {} });
expect(parseObjectDraft(" \n ")).toEqual({ ok: true, value: {} });
});
it("accepts a JSON object with values of any JSON type", () => {
const result = parseObjectDraft(
'{"s":"a","n":1,"b":true,"z":null,"arr":[1,{"k":2}],"o":{"deep":{"er":1}}}',
);
expect(result).toEqual({
ok: true,
value: {
s: "a",
n: 1,
b: true,
z: null,
arr: [1, { k: 2 }],
o: { deep: { er: 1 } },
},
});
});
it("rejects text that is not JSON", () => {
expect(parseObjectDraft('{"a":')).toEqual({
ok: false,
error: "Not valid JSON — changes are not applied",
});
});
it.each([
["an array", "[1,2]"],
["a string", '"hello"'],
["a number", "42"],
["null", "null"],
])("rejects valid JSON that is not an object: %s", (_label, text) => {
const result = parseObjectDraft(text);
expect(result.ok).toBe(false);
expect(result.ok === false && result.error).toMatch(
/Must be a JSON object/,
);
});
});
describe("JsonObjectInput", () => {
it("opens with the value serialized two-space, nesting intact", () => {
renderWithMantine(<Harness initial={{ a: { b: [1, 2] } }} />);
expect(box().value).toBe(
'{\n "a": {\n "b": [\n 1,\n 2\n ]\n }\n}',
);
});
it("emits the parsed object — a structured value stays structured", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderWithMantine(<Harness initial={{}} onChange={onChange} />);
await user.clear(box());
await user.type(box(), '{{"trace":{{"id":"x"},"n":3}');
expect(onChange).toHaveBeenLastCalledWith({ trace: { id: "x" }, n: 3 });
});
it("shows the text as typed while it is invalid and does not emit", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderWithMantine(<Harness initial={{ keep: "me" }} onChange={onChange} />);
// Append a stray character rather than clearing: clearing is itself a
// valid edit (it means `{}`) and would emit, which is not what is under
// test here.
await user.click(box());
await user.keyboard("{End}x");
// Displayed verbatim — not re-escaped back through JSON.stringify.
expect(box().value.endsWith("}x")).toBe(true);
expect(
screen.getByText("Not valid JSON — changes are not applied"),
).toBeInTheDocument();
// Nothing emitted, so the caller still holds the last valid object.
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByTestId("emitted").textContent).toBe('{"keep":"me"}');
});
it("flags valid JSON that is not an object without emitting", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderWithMantine(<Harness initial={{ keep: "me" }} onChange={onChange} />);
await user.clear(box());
// The clear is a legitimate edit to `{}`; only what follows is under test.
expect(onChange).toHaveBeenLastCalledWith({});
onChange.mockClear();
await user.type(box(), "[[1]");
expect(screen.getByText(/Must be a JSON object/)).toBeInTheDocument();
expect(onChange).not.toHaveBeenCalled();
});
it("treats a cleared box as the empty object", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderWithMantine(<Harness initial={{ a: 1 }} onChange={onChange} />);
await user.clear(box());
expect(onChange).toHaveBeenLastCalledWith({});
expect(screen.queryByText(/Not valid JSON/)).toBeNull();
});
it("re-syncs when the parent's value diverges from the draft", async () => {
// An external reset (switching servers, a reloaded catalog) must reach the
// box; an in-progress edit must not be overwritten by the value it emitted.
function Externally() {
const [value, setValue] = useState<JsonObject>({ a: 1 });
return (
<>
<JsonObjectInput
aria-label={LABEL}
value={value}
onChange={setValue}
/>
<button onClick={() => setValue({ b: 2 })}>reset</button>
</>
);
}
const user = userEvent.setup();
renderWithMantine(<Externally />);
await user.click(screen.getByRole("button", { name: "reset" }));
expect(JSON.parse(box().value)).toEqual({ b: 2 });
});
it("leaves an in-progress edit alone when the parent echoes it back", async () => {
const user = userEvent.setup();
renderWithMantine(<Harness initial={{}} />);
await user.clear(box());
// Typed without the closing brace auto-pair: the text is what the user has
// so far, and the echo of the parsed value must not reformat it mid-edit.
await user.type(box(), '{{"a":1}');
expect(box().value).toBe('{"a":1}');
});
});

View file

@ -0,0 +1,113 @@
import { useState } from "react";
import { JsonInput } from "@mantine/core";
import type { JsonObject } from "@inspector/core/json/jsonUtils.js";
import { useValueChange } from "../../../hooks/useValueChange";
const ObjectJsonInput = JsonInput.withProps({
formatOnBlur: true,
autosize: true,
minRows: 4,
spellCheck: false,
});
/** Two-space canonical form — the same shape the catalog file is written in. */
function serialize(value: JsonObject): string {
return JSON.stringify(value, null, 2);
}
/** A plain JSON object, i.e. not an array and not a scalar. */
function isJsonObject(value: unknown): value is JsonObject {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/**
* What a draft's text currently means: the object to emit, or why it can't be.
*
* Empty text is the object `{}` rather than an error — clearing the box is how
* "send no metadata" is spelled, and an empty editor showing a red error would
* read as broken.
*/
type DraftState =
| { ok: true; value: JsonObject }
| { ok: false; error: string };
export function parseObjectDraft(text: string): DraftState {
if (text.trim() === "") return { ok: true, value: {} };
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return { ok: false, error: "Not valid JSON — changes are not applied" };
}
if (!isJsonObject(parsed)) {
return {
ok: false,
error: "Must be a JSON object (`{ … }`) — changes are not applied",
};
}
return { ok: true, value: parsed };
}
export interface JsonObjectInputProps {
value: JsonObject;
onChange: (value: JsonObject) => void;
label?: string;
description?: string;
placeholder?: string;
"aria-label"?: string;
"data-testid"?: string;
}
/**
* A JSON-object editor: the user types JSON, the parent receives the parsed
* object.
*
* This is the editor for payloads whose *values* may be any JSON, which is why
* it exists beside the key/value row editors used for headers and env. `_meta`
* is the case that forced it (#1910) — nothing in the MCP spec restricts a
* `_meta` value to a string, so a `{ key, value }` row editor cannot express
* what the protocol allows.
*
* The text the user is typing is the source of truth for what is *displayed*;
* the parent only ever sees a parsed object. That split is what makes the box
* typeable: driving it off the parent's value and stringifying on every render
* re-escapes half-typed text once per keystroke, which is the #1928 symptom.
* `SchemaJsonField` in `SchemaForm.tsx` carries the same split for the same
* reason — see the long comment there.
*
* While the text is invalid the parent is **not** told, so the last valid
* object stands. The alternative — emitting `{}` — would silently discard a
* user's configured metadata the moment they typed a stray character, and this
* form has no Save button to gate instead: `onChange` writes straight through.
* The state is not silent, though; the field says so on itself via `error`.
*/
export function JsonObjectInput({
value,
onChange,
...inputProps
}: JsonObjectInputProps) {
const [draft, setDraft] = useState(() => serialize(value));
// Re-sync only when the parent's value genuinely diverges from what the draft
// parses to, so an external reset (switching servers, a reloaded catalog)
// reaches the box while an in-progress edit is left alone. Compared through
// canonical JSON because the parent hands back a fresh object each time.
const parsed = parseObjectDraft(draft);
const draftJson = parsed.ok ? serialize(parsed.value) : null;
useValueChange(serialize(value), (next) => {
if (next !== draftJson) setDraft(next);
});
return (
<ObjectJsonInput
{...inputProps}
value={draft}
error={parsed.ok ? undefined : parsed.error}
onChange={(text) => {
setDraft(text);
const result = parseObjectDraft(text);
if (result.ok) onChange(result.value);
}}
/>
);
}

View file

@ -10,7 +10,7 @@ import {
const defaultSettings: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -57,34 +57,9 @@ function InteractiveRender(args: ServerSettingsFormProps) {
},
});
}}
onAddMetadata={() => {
args.onAddMetadata();
updateArgs({
settings: {
...args.settings,
metadata: [...args.settings.metadata, { key: "", value: "" }],
},
});
}}
onRemoveMetadata={(index) => {
args.onRemoveMetadata(index);
updateArgs({
settings: {
...args.settings,
metadata: args.settings.metadata.filter((_, i) => i !== index),
},
});
}}
onMetadataChange={(index, key, value) => {
args.onMetadataChange(index, key, value);
updateArgs({
settings: {
...args.settings,
metadata: args.settings.metadata.map((m, i) =>
i === index ? { key, value } : m,
),
},
});
onMetadataChange={(metadata) => {
args.onMetadataChange(metadata);
updateArgs({ settings: { ...args.settings, metadata } });
}}
onAddEnv={() => {
args.onAddEnv();
@ -197,8 +172,6 @@ const meta: Meta<typeof ServerSettingsForm> = {
onRemoveEnv: fn(),
onEnvChange: fn(),
onCwdChange: fn(),
onAddMetadata: fn(),
onRemoveMetadata: fn(),
onMetadataChange: fn(),
onTimeoutChange: fn(),
onAutoRefreshChange: fn(),
@ -278,10 +251,13 @@ export const AllConfigured: Story = {
{ key: "X-Request-Id", value: "req-456" },
],
env: [],
metadata: [
{ key: "userId", value: "user-789" },
{ key: "sessionId", value: "session-012" },
],
metadata: {
userId: "user-789",
sessionId: "session-012",
// A structured value — the case a `{ key, value }` row editor could
// not express (#1910).
client: { name: "inspector", features: ["apps", "tasks"], retries: 3 },
},
connectionTimeout: 15000,
requestTimeout: 45000,
taskTtl: 45000,

View file

@ -22,7 +22,7 @@ function clearButtonFor(input: HTMLElement): HTMLElement {
const emptySettings: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -33,7 +33,7 @@ const emptySettings: InspectorServerSettings = {
const populatedSettings: InspectorServerSettings = {
headers: [{ key: "Authorization", value: "Bearer abc" }],
env: [],
metadata: [{ key: "userId", value: "u-1" }],
metadata: { userId: "u-1", tenant: { id: 7, tags: ["a"] } },
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -63,8 +63,6 @@ const baseHandlers = {
onRemoveEnv: vi.fn(),
onEnvChange: vi.fn(),
onCwdChange: vi.fn(),
onAddMetadata: vi.fn(),
onRemoveMetadata: vi.fn(),
onMetadataChange: vi.fn(),
onTimeoutChange: vi.fn(),
onAutoRefreshChange: vi.fn(),
@ -239,7 +237,7 @@ describe("ServerSettingsForm", () => {
expect(screen.getByText("Log Level per Request")).toBeInTheDocument();
});
it("shows empty hints for headers and metadata when no entries exist", () => {
it("shows the empty hint for headers, and an empty JSON object for metadata", () => {
renderWithMantine(
<ServerSettingsForm
{...baseHandlers}
@ -250,9 +248,9 @@ describe("ServerSettingsForm", () => {
expect(
screen.getByText("No custom headers configured"),
).toBeInTheDocument();
expect(
screen.getByText("No request metadata configured"),
).toBeInTheDocument();
// Metadata has no rows to be absent — the editor is always present, and
// "none configured" is spelled `{}` in the box itself.
expect(screen.getByLabelText("Request metadata JSON")).toHaveValue("{}");
});
it("invokes onAddHeader when + Add Header is clicked", async () => {
@ -270,21 +268,6 @@ describe("ServerSettingsForm", () => {
expect(onAddHeader).toHaveBeenCalledTimes(1);
});
it("invokes onAddMetadata when + Add Metadata is clicked", async () => {
const user = userEvent.setup();
const onAddMetadata = vi.fn();
renderWithMantine(
<ServerSettingsForm
{...baseHandlers}
onAddMetadata={onAddMetadata}
settings={emptySettings}
expandedSections={["metadata"]}
/>,
);
await user.click(screen.getByRole("button", { name: "+ Add Metadata" }));
expect(onAddMetadata).toHaveBeenCalledTimes(1);
});
it("invokes onHeaderChange when typing in header value input", async () => {
const user = userEvent.setup();
const onHeaderChange = vi.fn();
@ -340,29 +323,38 @@ describe("ServerSettingsForm", () => {
expect(onRemoveHeader).toHaveBeenCalledWith(0);
});
it("invokes onMetadataChange and onRemoveMetadata for metadata rows", async () => {
const user = userEvent.setup();
const onMetadataChange = vi.fn();
const onRemoveMetadata = vi.fn();
it("renders the configured metadata as formatted JSON, nested values included", () => {
renderWithMantine(
<ServerSettingsForm
{...baseHandlers}
onMetadataChange={onMetadataChange}
onRemoveMetadata={onRemoveMetadata}
settings={populatedSettings}
expandedSections={["metadata"]}
/>,
);
const valueInput = screen.getByDisplayValue("u-1");
await user.type(valueInput, "Z");
expect(onMetadataChange).toHaveBeenCalled();
const editor = screen.getByLabelText("Request metadata JSON");
// The point of #1910: a nested object survives into the editor instead of
// being flattened into a `{ key, value }` string row.
expect(JSON.parse((editor as HTMLTextAreaElement).value)).toEqual({
userId: "u-1",
tenant: { id: 7, tags: ["a"] },
});
});
await user.click(
screen.getByRole("button", {
name: "Remove metadata entry, userId, row 1",
}),
it("reports the whole edited object through onMetadataChange", async () => {
const user = userEvent.setup();
const onMetadataChange = vi.fn();
renderWithMantine(
<ServerSettingsForm
{...baseHandlers}
onMetadataChange={onMetadataChange}
settings={emptySettings}
expandedSections={["metadata"]}
/>,
);
expect(onRemoveMetadata).toHaveBeenCalledWith(0);
const editor = screen.getByLabelText("Request metadata JSON");
await user.clear(editor);
await user.type(editor, '{{"n":[[1,2]}');
expect(onMetadataChange).toHaveBeenLastCalledWith({ n: [1, 2] });
});
it("invokes onTimeoutChange when typing in connection timeout", async () => {
@ -1470,23 +1462,6 @@ describe("ServerSettingsForm", () => {
expect(onClearStoredOAuth).toHaveBeenCalledTimes(1);
});
it("clears a metadata value via its Clear button (onMetadataChange with empty value)", async () => {
const user = userEvent.setup();
const onMetadataChange = vi.fn();
renderWithMantine(
<ServerSettingsForm
{...baseHandlers}
onMetadataChange={onMetadataChange}
settings={populatedSettings}
expandedSections={["metadata"]}
/>,
);
// populatedSettings has one metadata { key: "userId", value: "u-1" }
const valueInput = screen.getByDisplayValue("u-1");
await user.click(clearButtonFor(valueInput));
expect(onMetadataChange).toHaveBeenCalledWith(0, "userId", "");
});
it("omits the Clear buttons for an empty header key/value row", () => {
// A row whose key and value are both empty renders no Clear button in
// either field (the null branch of `item.key ?` / `item.value ?`).

View file

@ -4,6 +4,7 @@ import {
Alert,
Button,
Checkbox,
Code,
Flex,
Group,
NumberInput,
@ -13,11 +14,13 @@ import {
TextInput,
} from "@mantine/core";
import { ClearButton } from "../../elements/ClearButton/ClearButton";
import { JsonObjectInput } from "../../elements/JsonObjectInput/JsonObjectInput";
import type { ProtocolEra } from "@modelcontextprotocol/client";
import type {
InspectorServerSettings,
ModernLogLevel,
OAuthSettings,
RequestMetadata,
ServerProtocolEra,
ServerType,
} from "@inspector/core/mcp/types.js";
@ -78,9 +81,12 @@ export interface ServerSettingsFormProps {
onRemoveEnv: (index: number) => void;
onEnvChange: (index: number, key: string, value: string) => void;
onCwdChange: (value: string) => void;
onAddMetadata: () => void;
onRemoveMetadata: (index: number) => void;
onMetadataChange: (index: number, key: string, value: string) => void;
/**
* Replace the whole default-`_meta` payload. Not the `(index, key, value)`
* row callback the header/env editors use — metadata is edited as a JSON
* object, since a `_meta` value may be any JSON (#1910).
*/
onMetadataChange: (metadata: RequestMetadata) => void;
onTimeoutChange: (
field: "connectionTimeout" | "requestTimeout" | "taskTtl",
value: number,
@ -434,8 +440,6 @@ export function ServerSettingsForm({
onRemoveEnv,
onEnvChange,
onCwdChange,
onAddMetadata,
onRemoveMetadata,
onMetadataChange,
onTimeoutChange,
onAutoRefreshChange,
@ -724,22 +728,18 @@ export function ServerSettingsForm({
<Accordion.Control>Request Metadata</Accordion.Control>
<Accordion.Panel>
<Stack gap="md">
<Group justify="space-between">
<HintText>
Metadata sent with every MCP request (included in _meta field)
</HintText>
<AddButton onClick={onAddMetadata}>+ Add Metadata</AddButton>
</Group>
{settings.metadata.length === 0 ? (
<EmptyHint>No request metadata configured</EmptyHint>
) : (
<KeyValueRows
items={settings.metadata}
entityLabel="metadata entry"
onChange={onMetadataChange}
onRemove={onRemoveMetadata}
/>
)}
<HintText>
Metadata merged into the `_meta` field of every MCP request to
this server, as a JSON object. Values may be any JSON — objects,
arrays, numbers, booleans, `null` — not just strings. Leave it as{" "}
<Code>{"{}"}</Code> to send none.
</HintText>
<JsonObjectInput
aria-label="Request metadata JSON"
placeholder={'{\n "example": { "nested": true }\n}'}
value={settings.metadata}
onChange={onMetadataChange}
/>
</Stack>
</Accordion.Panel>
</Accordion.Item>

View file

@ -14,7 +14,7 @@ const initialSettings: InspectorServerSettings = {
{ key: "X-Request-Id", value: "req-456" },
],
env: [],
metadata: [{ key: "userId", value: "user-789" }],
metadata: { userId: "user-789", client: { name: "inspector" } },
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -74,7 +74,7 @@ export const EmptySettings: Story = {
settings: {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -96,7 +96,7 @@ export const StdioServer: Story = {
{ key: "API_KEY", value: "abc-123" },
{ key: "LOG_LEVEL", value: "debug" },
],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

View file

@ -7,7 +7,7 @@ import { ServerSettingsModal } from "./ServerSettingsModal";
const initialSettings: InspectorServerSettings = {
headers: [{ key: "Authorization", value: "Bearer abc" }],
env: [],
metadata: [{ key: "userId", value: "u-1" }],
metadata: { userId: "u-1" },
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -21,7 +21,7 @@ const initialSettings: InspectorServerSettings = {
const emptySettings: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 30000,
requestTimeout: 60000,
taskTtl: 60000,
@ -310,76 +310,6 @@ describe("ServerSettingsModal", () => {
expect(lastCall.headers[0].value).toContain("Bearer abc");
});
it("calls onSettingsChange when adding metadata after expanding the section", async () => {
const user = userEvent.setup();
const onSettingsChange = vi.fn();
renderWithMantine(
<ServerSettingsModal
opened
settings={emptySettings}
serverType="streamable-http"
isStdio={false}
onClose={vi.fn()}
onSettingsChange={onSettingsChange}
/>,
);
await user.click(screen.getByRole("button", { name: "Request Metadata" }));
await user.click(screen.getByRole("button", { name: "+ Add Metadata" }));
expect(onSettingsChange).toHaveBeenCalledWith({
...emptySettings,
metadata: [{ key: "", value: "" }],
});
});
it("calls onSettingsChange when removing metadata", async () => {
const user = userEvent.setup();
const onSettingsChange = vi.fn();
renderWithMantine(
<ServerSettingsModal
opened
settings={initialSettings}
serverType="streamable-http"
isStdio={false}
onClose={vi.fn()}
onSettingsChange={onSettingsChange}
/>,
);
await user.click(screen.getByRole("button", { name: "Request Metadata" }));
// Both the header and metadata rows have a remove button; each is named
// for the row it belongs to, so no positional guess is needed.
await user.click(
screen.getByRole("button", {
name: "Remove metadata entry, userId, row 1",
}),
);
expect(onSettingsChange).toHaveBeenCalledWith({
...initialSettings,
metadata: [],
});
});
it("calls onSettingsChange when typing in metadata key/value", async () => {
const user = userEvent.setup();
const onSettingsChange = vi.fn();
renderWithMantine(
<ServerSettingsModal
opened
settings={initialSettings}
serverType="streamable-http"
isStdio={false}
onClose={vi.fn()}
onSettingsChange={onSettingsChange}
/>,
);
await user.click(screen.getByRole("button", { name: "Request Metadata" }));
const valueInput = screen.getByDisplayValue("u-1");
await user.type(valueInput, "9");
expect(onSettingsChange).toHaveBeenCalled();
const lastCall =
onSettingsChange.mock.calls[onSettingsChange.mock.calls.length - 1][0];
expect(lastCall.metadata[0].key).toBe("userId");
});
it("calls onSettingsChange when changing timeouts", async () => {
const user = userEvent.setup();
const onSettingsChange = vi.fn();
@ -703,20 +633,13 @@ describe("ServerSettingsModal", () => {
expect(lastCall.headers[1]).toEqual({ key: "B", value: "2" });
});
it("preserves sibling rows when editing one of several metadata entries", async () => {
it("replaces the whole metadata object when the JSON editor changes", async () => {
const user = userEvent.setup();
const onSettingsChange = vi.fn();
const twoMeta: InspectorServerSettings = {
...emptySettings,
metadata: [
{ key: "m1", value: "v1" },
{ key: "m2", value: "v2" },
],
};
renderWithMantine(
<ServerSettingsModal
opened
settings={twoMeta}
settings={emptySettings}
serverType="streamable-http"
isStdio={false}
onClose={vi.fn()}
@ -724,9 +647,15 @@ describe("ServerSettingsModal", () => {
/>,
);
await user.click(screen.getByRole("button", { name: "Request Metadata" }));
await user.type(screen.getByDisplayValue("v1"), "x");
const editor = screen.getByLabelText("Request metadata JSON");
await user.clear(editor);
await user.type(editor, '{{"trace":{{"id":"abc"}}}');
const lastCall = onSettingsChange.mock.calls.at(-1)?.[0];
expect(lastCall.metadata[1]).toEqual({ key: "m2", value: "v2" });
// The nested object arrives as an object, not a stringified one — the
// whole point of #1910.
expect(lastCall.metadata).toEqual({ trace: { id: "abc" } });
// Every other setting is carried through untouched.
expect(lastCall.headers).toEqual(emptySettings.headers);
});
it("preserves sibling rows when editing one of several roots", async () => {

View file

@ -5,6 +5,7 @@ import type {
InspectorServerSettings,
ModernLogLevel,
OAuthSettings,
RequestMetadata,
ServerProtocolEra,
ServerType,
} from "@inspector/core/mcp/types.js";
@ -155,24 +156,7 @@ export function ServerSettingsModal({
onSettingsChange({ ...settings, cwd: value });
}
function handleAddMetadata() {
onSettingsChange({
...settings,
metadata: [...settings.metadata, { key: "", value: "" }],
});
}
function handleRemoveMetadata(index: number) {
onSettingsChange({
...settings,
metadata: settings.metadata.filter((_, i) => i !== index),
});
}
function handleMetadataChange(index: number, key: string, value: string) {
const metadata = settings.metadata.map((m, i) =>
i === index ? { key, value } : m,
);
function handleMetadataChange(metadata: RequestMetadata) {
onSettingsChange({ ...settings, metadata });
}
@ -303,8 +287,6 @@ export function ServerSettingsModal({
onRemoveEnv={handleRemoveEnv}
onEnvChange={handleEnvChange}
onCwdChange={handleCwdChange}
onAddMetadata={handleAddMetadata}
onRemoveMetadata={handleRemoveMetadata}
onMetadataChange={handleMetadataChange}
onTimeoutChange={handleTimeoutChange}
onAutoRefreshChange={handleAutoRefreshChange}

View file

@ -76,7 +76,7 @@ describe("runner client auth options", () => {
taskTtl: 60000,
maxFetchRequests: 10,
autoRefreshOnListChanged: false,
metadata: [],
metadata: {},
headers: [],
env: [],
roots: [],
@ -99,7 +99,7 @@ describe("runner client auth options", () => {
taskTtl: 60000,
maxFetchRequests: 10,
autoRefreshOnListChanged: false,
metadata: [],
metadata: {},
headers: [],
env: [],
roots: [],
@ -116,7 +116,7 @@ describe("runner client auth options", () => {
taskTtl: 60000,
maxFetchRequests: 10,
autoRefreshOnListChanged: false,
metadata: [],
metadata: {},
headers: [],
env: [],
roots: [],
@ -135,7 +135,7 @@ describe("runner client auth options", () => {
taskTtl: 60000,
maxFetchRequests: 10,
autoRefreshOnListChanged: false,
metadata: [],
metadata: {},
headers: [],
env: [],
roots: [],
@ -156,7 +156,7 @@ describe("runner client auth options", () => {
taskTtl: 60000,
maxFetchRequests: 10,
autoRefreshOnListChanged: false,
metadata: [],
metadata: {},
headers: [],
env: [],
roots: [],
@ -187,7 +187,7 @@ describe("runner client auth options", () => {
taskTtl: 60000,
maxFetchRequests: 10,
autoRefreshOnListChanged: false,
metadata: [],
metadata: {},
headers: [],
env: [],
roots: [],

View file

@ -854,7 +854,7 @@ describe("InspectorClient peer-handler timing (#1797)", () => {
serverSettings: {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,

View file

@ -30,7 +30,7 @@ describe("headersToServerSettings", () => {
expect(settings?.headers).toEqual([
{ key: "Authorization", value: "Bearer t" },
]);
expect(settings?.metadata).toEqual([]);
expect(settings?.metadata).toEqual({});
expect(settings?.roots).toEqual([]);
});
});

View file

@ -361,7 +361,7 @@ describe("RemoteClientTransport", () => {
const settings = {
headers: [{ key: "X-Tenant", value: "acme" }],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,

View file

@ -11,6 +11,7 @@ import {
mcpConfigToServerEntries,
mergeSecretsIntoStored,
normalizeServerType,
normalizeStoredMetadata,
oauthAuthorizationParamsFromSettings,
oauthEndpointOverridesFromSettings,
serverEntriesToMcpConfig,
@ -240,7 +241,7 @@ describe("serverEntriesToMcpConfig", () => {
});
it("round-trips a populated set of Inspector-extension fields (post-#1358 flat shape)", () => {
// Disk shape: top-level `headers` (Record), `metadata` (pair-array),
// Disk shape: top-level `headers` (Record), `metadata` (JSON object),
// numeric timeouts, nested `oauth`. Round-trip must preserve the on-
// disk shape byte-equivalent so a hand-edited file is stable.
const original: MCPConfig = {
@ -249,7 +250,7 @@ describe("serverEntriesToMcpConfig", () => {
type: "streamable-http",
url: "https://x.test/mcp",
headers: { Authorization: "Bearer xyz" },
metadata: [{ key: "tenant", value: "acme" }],
metadata: { tenant: "acme", limits: { rps: 10 } },
connectionTimeout: 30000,
requestTimeout: 60000,
oauth: {
@ -581,7 +582,7 @@ describe("serverEntriesToMcpConfig", () => {
headers: [{ key: "X-Tenant", value: "acme" }],
// Non-stdio server → empty env mirror in memory (for the form)
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
// Absent taskTtl on disk → product default in memory (for the form)
@ -663,7 +664,7 @@ describe("serverEntriesToMcpConfig", () => {
{ key: " ", value: "whitespace" },
],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,
@ -690,7 +691,7 @@ describe("serverEntriesToMcpConfig", () => {
settings: {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,
@ -719,7 +720,7 @@ describe("serverEntriesToMcpConfig", () => {
settings: {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,
@ -758,7 +759,7 @@ describe("serverEntriesToMcpConfig", () => {
settings: {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,
@ -785,7 +786,7 @@ describe("serverEntriesToMcpConfig", () => {
settings: {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 0,
@ -1163,7 +1164,7 @@ describe("enterpriseManaged oauth settings", () => {
const stored = inspectorSettingsToStoredFields({
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,
@ -1180,7 +1181,7 @@ describe("enterpriseManaged oauth settings", () => {
const stored = inspectorSettingsToStoredFields({
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,
@ -1196,7 +1197,7 @@ describe("oauthOnInsufficientScope (SEP-2350)", () => {
const baseSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,
@ -1374,6 +1375,109 @@ describe("oauthOnInsufficientScope (SEP-2350)", () => {
});
});
describe("normalizeStoredMetadata (#1910)", () => {
let warn: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
warn = vi.spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(() => {
warn.mockRestore();
});
it("passes an object through, values of any JSON type intact", () => {
const meta = {
s: "a",
n: 1,
b: false,
z: null,
arr: [1, { k: 2 }],
o: { deep: true },
};
expect(normalizeStoredMetadata(meta)).toEqual(meta);
});
it("copies rather than aliasing the stored object", () => {
// The settings object is edited in place by the form; sharing the
// reference with the parsed catalog would mutate it behind the caller.
const meta = { a: 1 };
const out = normalizeStoredMetadata(meta);
out.b = 2;
expect(meta).toEqual({ a: 1 });
});
it("reads the pre-#1910 pair array so an existing mcp.json keeps working", () => {
expect(
normalizeStoredMetadata([
{ key: "tenant", value: "acme" },
{ key: "n", value: 3 },
]),
).toEqual({ tenant: "acme", n: 3 });
});
it("skips a blank-key legacy pair", () => {
expect(
normalizeStoredMetadata([
{ key: "", value: "orphan" },
{ key: " ", value: "orphan" },
{ key: "kept", value: "yes" },
]),
).toEqual({ kept: "yes" });
});
it("reads a legacy pair with no value as an empty string", () => {
expect(normalizeStoredMetadata([{ key: "k" }])).toEqual({ k: "" });
});
it("drops a malformed legacy entry with a warning, keeping its siblings", () => {
expect(
normalizeStoredMetadata([
"nope",
null,
{ value: "no key" },
{ key: "kept", value: 1 },
]),
).toEqual({ kept: 1 });
expect(warn).toHaveBeenCalledTimes(3);
});
it.each([
["undefined", undefined],
["null", null],
])("reads %s as the empty object without warning", (_label, input) => {
expect(normalizeStoredMetadata(input)).toEqual({});
expect(warn).not.toHaveBeenCalled();
});
it.each([
["a string", "oops"],
["a number", 7],
["a boolean", true],
])("drops %s with a warning", (_label, input) => {
expect(normalizeStoredMetadata(input)).toEqual({});
expect(warn).toHaveBeenCalledTimes(1);
});
it("migrates a legacy file to the object shape on the next write", () => {
// Read side accepts the pair array; write side emits only the object, so
// one round-trip is the migration.
const entries = mcpConfigToServerEntries({
mcpServers: {
legacy: {
type: "streamable-http",
url: "https://x.test/mcp",
metadata: [{ key: "tenant", value: "acme" }] as unknown as Record<
string,
never
>,
},
},
});
expect(entries[0]?.settings?.metadata).toEqual({ tenant: "acme" });
const round = serverEntriesToMcpConfig(entries);
expect(round.mcpServers.legacy?.metadata).toEqual({ tenant: "acme" });
});
});
describe("envRecordToPairs / envPairsToRecord", () => {
it("envRecordToPairs preserves key insertion order", () => {
expect(envRecordToPairs({ B: "2", A: "1" })).toEqual([
@ -1469,7 +1573,7 @@ describe("stdio env / cwd mirroring", () => {
headers: [],
env: [{ key: "API_KEY", value: "secret" }],
cwd: "/srv/app",
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

View file

@ -13,7 +13,7 @@ function prompt(name: string): Prompt {
const AUTO_REFRESH_SETTINGS: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

View file

@ -13,7 +13,7 @@ function template(name: string): ResourceTemplate {
const AUTO_REFRESH_SETTINGS: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

View file

@ -13,7 +13,7 @@ function resource(uri: string): Resource {
const AUTO_REFRESH_SETTINGS: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

View file

@ -13,7 +13,7 @@ function tool(name: string): Tool {
const AUTO_REFRESH_SETTINGS: InspectorServerSettings = {
headers: [],
env: [],
metadata: [],
metadata: {},
connectionTimeout: 0,
requestTimeout: 0,
taskTtl: 60000,

Some files were not shown because too many files have changed in this diff Show more