inspector/clients/web/src/components/elements/JsonObjectInput/JsonObjectInput.test.tsx
cliffhall b33532c024 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>
2026-08-23 12:23:40 -04:00

172 lines
5.9 KiB
TypeScript

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