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
3 changed files with 1004 additions and 495 deletions

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);
}}
/>
);
}