Merge remote-tracking branch 'origin/v2/main' into v2/chore/milestone-merge-v2.3.0

Signed-off-by: cliffhall <cliff@futurescale.com>

# Conflicts:
#	package-lock.json
#	package.json
This commit is contained in:
cliffhall 2026-08-18 20:03:07 -04:00
commit 3719151081
12 changed files with 18171 additions and 2062 deletions

View file

@ -507,6 +507,9 @@ function renderApp(servers: Record<string, TuiServer>) {
async function mount(servers: Record<string, TuiServer>) {
const r = renderApp(servers);
await tick();
// The mount commit's effect flush can still be queued behind this tick, and
// this write is the one that absorbs the dropped first keypress.
await settleInputHandlers();
r.stdin.write("x");
await tick();
return r;
@ -532,6 +535,11 @@ const ENTER = "\r";
*/
async function press(r: RenderResult, keys: string[]) {
for (const k of keys) {
// Same hazard `waitUntil` guards against, at the other end: a caller can
// reach here on a turn that still has React's passive-effect flush queued
// (e.g. straight after a plain `tick`, or after an earlier key committed a
// render), so settle before every write rather than only after a poll.
await settleInputHandlers();
r.stdin.write(k);
await tick();
await tick();
@ -552,9 +560,29 @@ async function press(r: RenderResult, keys: string[]) {
*/
const POLL_TRIES = 100;
/**
* One check-phase turn, queued BEHIND React's already-scheduled passive-effect
* flush. A frame observed by a poll predicate is written during React's
* COMMIT, but ink re-arms its useInput listeners in the passive-effect flush
* React schedules (via setImmediate in Node) during that same commit. Node's
* event loop runs the timers phase before the check phase, so a 25ms poll
* tick can observe the new frame and let the test write the next keypress
* BEFORE that flush has run — the key is then dispatched to the previous
* commit's stale useInput closures (where e.g. pendingStepUp is still null)
* and silently swallowed (#1942). Yielding one setImmediate turn after the
* predicate passes sequences the next stdin write after the flush (FIFO
* within the check queue), so "frame visible" once again implies "input
* handlers armed".
*/
const settleInputHandlers = () =>
new Promise((resolve) => setImmediate(resolve));
async function waitUntil(predicate: () => boolean, tries = POLL_TRIES) {
for (let i = 0; i < tries; i++) {
if (predicate()) return;
if (predicate()) {
await settleInputHandlers();
return;
}
await tick();
}
}
@ -626,6 +654,23 @@ afterEach(() => {
while (mounted.length) mounted.pop()?.unmount();
});
// Pins the synchronization contract the OAuth step-up assertions depend on
// (#1942). The `setImmediate` sentinel below stands in for React's pending
// passive-effect flush — the turn where ink re-arms `useInput`. If `waitUntil`
// ever returns without yielding a check-phase turn, the sentinel has not run
// and this fails, instead of the regression resurfacing as a differently-named
// flaky OAuth test under coverage instrumentation.
describe("test helpers", () => {
it("waitUntil settles input handlers before resolving", async () => {
let flushed = false;
setImmediate(() => {
flushed = true;
});
await waitUntil(() => true);
expect(flushed).toBe(true);
});
});
describe("App (foundation)", () => {
it("renders the server list with the MCP Servers header", async () => {
const r = renderApp(stdioServer());
@ -661,6 +706,91 @@ describe("App (foundation)", () => {
expect(h.disconnect).toHaveBeenCalled();
});
it("surfaces a disconnect failure instead of floating the rejection", async () => {
// 'd' is a key handler, so it cannot await handleDisconnect — the handler
// has to own the failure itself or it escapes as an unhandled rejection
// and fails the whole run from somewhere else (#1959).
// The banner is deliberately independent of connection status: a rejected
// disconnect leaves the status "connected", so anything gated on
// `status === "error"` would never be seen.
h.ctrl.status = "connected";
h.disconnect.mockRejectedValue(new Error("discfail"));
const r = await mount(oneStdio());
r.stdin.write("d");
await expectFrame(r, "Disconnect failed: discfail");
});
it("owns a non-Error disconnect rejection too", async () => {
// The catch stringifies a non-Error rejection rather than reading
// `.message` off it; a throw here would escape the same way.
h.ctrl.status = "connected";
h.disconnect.mockRejectedValue("plainstring");
const r = await mount(oneStdio());
r.stdin.write("d");
await expectFrame(r, "Disconnect failed: plainstring");
});
it("clears a disconnect failure once a retry succeeds", async () => {
// A stale banner would keep reporting a failure the user has since fixed.
h.ctrl.status = "connected";
h.disconnect.mockRejectedValueOnce(new Error("discfail"));
const r = await mount(oneStdio());
r.stdin.write("d");
await expectFrame(r, "Disconnect failed: discfail");
r.stdin.write("d");
await waitUntil(() => !(r.lastFrame() ?? "").includes("Disconnect failed"));
expect(r.lastFrame() ?? "").not.toContain("Disconnect failed");
});
it("drops a disconnect rejection that lands after the user switched servers", async () => {
// The stale attempt is the one that usually rejects, so without an
// attempt token server alpha's failure would surface in beta's header.
h.ctrl.status = "connected";
let rejectDisconnect: (err: Error) => void = () => {};
h.disconnect.mockImplementationOnce(
() =>
new Promise<void>((_resolve, reject) => {
rejectDisconnect = reject;
}),
);
const r = await mount(stdioServer());
r.stdin.write("d"); // alpha's disconnect starts, and hangs
await tick();
await press(r, [DOWN]); // switch to beta
await expectFrame(r, "beta");
rejectDisconnect(new Error("stale-alpha-failure"));
// Give the rejection every chance to be published before asserting it
// wasn't — a bare tick would pass even with the guard removed.
await waitUntil(() =>
(r.lastFrame() ?? "").includes("stale-alpha-failure"),
);
expect(r.lastFrame() ?? "").not.toContain("stale-alpha-failure");
});
it("drops a stale disconnect rejection across an A → B → A round trip", async () => {
// The server-name check alone passes here: by the time the rejection
// lands, alpha is selected again. Only retiring the attempt token on
// every switch catches it.
h.ctrl.status = "connected";
let rejectDisconnect: (err: Error) => void = () => {};
h.disconnect.mockImplementationOnce(
() =>
new Promise<void>((_resolve, reject) => {
rejectDisconnect = reject;
}),
);
const r = await mount(stdioServer());
r.stdin.write("d"); // alpha's disconnect starts, and hangs
await tick();
await press(r, [DOWN]); // alpha -> beta
await expectFrame(r, "b.js");
await press(r, [UP]); // beta -> alpha again
await expectFrame(r, "s.js");
rejectDisconnect(new Error("round-trip-failure"));
await waitUntil(() => (r.lastFrame() ?? "").includes("round-trip-failure"));
expect(r.lastFrame() ?? "").not.toContain("round-trip-failure");
});
it("switches tabs via accelerator keys", async () => {
const r = await mount(stdioServer());
await press(r, ["t"]); // tools tab (server is auto-selected)

View file

@ -77,6 +77,73 @@ const renderAndSubmit = async (
};
describe("ResourceTestModal", () => {
// RFC 6570 keeps a required expression satisfied by any ONE of its names, so
// `{a,b}` cannot be expressed with ink-form's per-field `required` flag and
// its members are left optional there. Without the modal's own group check
// the TUI would submit blank -- dropping the expression and reading a
// different resource -- while the web panel blocks the same request (#1919).
describe("required-group validation", () => {
it("refuses to submit when no name in a required group has a value", async () => {
const read = vi.fn();
const { onClose, unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://{a,b}" }),
{ a: "", b: "" },
);
expect(read).not.toHaveBeenCalled();
expect(onClose).not.toHaveBeenCalled();
unmount();
});
it("blocks a required variable whose name collides with Object.prototype", async () => {
// `constructor` is a valid RFC 6570 varname, and the modal's own filter
// used to read `Object` (length 1) as a filled value. The *message* built
// from that filter came out naming no field; since frames render empty
// here (see the header note), that half is asserted on
// `unmetRequiredGroups` in the core suite. This asserts the gate.
const read = vi.fn();
const { onClose, unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://{constructor}" }),
{ constructor: "" },
);
expect(read).not.toHaveBeenCalled();
expect(onClose).not.toHaveBeenCalled();
unmount();
});
it("submits once any one name in the group has a value", async () => {
const read = vi.fn().mockResolvedValue({
result: { contents: [] },
expandedUri: "x://only-a",
});
const { unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://{a,b}" }),
{ a: "only-a", b: "" },
);
// The untouched field is dropped before the read: `""` is a *defined*
// RFC 6570 value that would expand to a valueless pair, and ink-form
// cannot distinguish "never touched" from "deliberately empty".
expect(read).toHaveBeenCalledWith("x://{a,b}", { a: "only-a" });
unmount();
});
it("does not block a template whose only expression is omittable", async () => {
const read = vi.fn().mockResolvedValue({
result: { contents: [] },
expandedUri: "x://events",
});
const { unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://events{?topic}" }),
{ topic: "" },
);
expect(read).toHaveBeenCalled();
unmount();
});
});
it("renders the form initially without invoking the client", async () => {
const read = vi.fn();
const api = render(

View file

@ -213,4 +213,173 @@ describe("schemaToForm", () => {
);
expect(form.sections[0]!.fields[0]).toMatchObject({ initialValue: "hi" });
});
// #2015 (the TUI twin of #1928): an argument declared with Zod's `.nullish()`
// has no top-level `type`/`enum` — they sit on the surviving `anyOf` branch —
// so before normalization every one of these degraded to a plain text field.
describe("nullable unions", () => {
it("renders a select for an anyOf string-enum|null argument", () => {
const form = schemaToForm(
{
properties: {
direction: {
anyOf: [
{ type: "string", enum: ["envio", "recebimento"] },
{ type: "null" },
],
},
},
},
"nullableEnum",
);
expect(form.sections[0]!.fields[0]).toMatchObject({
name: "direction",
type: "select",
options: [
{ label: "envio", value: "envio" },
{ label: "recebimento", value: "recebimento" },
],
});
});
it("maps the remaining nullable scalar branches to their typed fields", () => {
const form = schemaToForm(
{
properties: {
reference: { anyOf: [{ type: "string" }, { type: "null" }] },
quantity: {
anyOf: [
{ type: "integer", minimum: 1, maximum: 9 },
{ type: "null" },
],
},
ratio: { anyOf: [{ type: "number" }, { type: "null" }] },
express: { anyOf: [{ type: "boolean" }, { type: "null" }] },
},
},
"nullableScalars",
);
const fields = form.sections[0]!.fields;
expect(fields.map((f) => ({ name: f.name, type: f.type }))).toEqual([
{ name: "reference", type: "string" },
{ name: "quantity", type: "integer" },
{ name: "ratio", type: "float" },
{ name: "express", type: "boolean" },
]);
// The branch's own constraints are hoisted along with its type.
expect(fields[1]).toMatchObject({ min: 1, max: 9 });
});
it("renders a select for a nullable array-of-enum argument", () => {
const form = schemaToForm(
{
properties: {
tags: {
anyOf: [
{ type: "array", items: { enum: ["a", "b"] } },
{ type: "null" },
],
},
},
},
"nullableArrayEnum",
);
expect(form.sections[0]!.fields[0]).toMatchObject({
type: "select",
options: [
{ label: "a", value: "a" },
{ label: "b", value: "b" },
],
});
});
// With the null left in the list, the all-strings check would reject the
// enum and this would degrade to a plain text field.
it("renders a select for a type: [string, null] enum, null stripped", () => {
const form = schemaToForm(
{
properties: {
direction: {
type: ["string", "null"],
enum: ["envio", "recebimento", null],
},
},
},
"typeArrayNullableEnum",
);
expect(form.sections[0]!.fields[0]).toMatchObject({
type: "select",
options: [
{ label: "envio", value: "envio" },
{ label: "recebimento", value: "recebimento" },
],
});
});
it("collapses the type: [T, null] encoding too", () => {
const form = schemaToForm(
{
properties: {
note: { type: ["string", "null"] },
flag: { type: ["boolean", "null"] },
},
},
"typeArrayNull",
);
expect(
form.sections[0]!.fields.map((f) => ({ name: f.name, type: f.type })),
).toEqual([
{ name: "note", type: "string" },
{ name: "flag", type: "boolean" },
]);
});
// ink-form hands a select's stringified value straight back, so a numeric
// enum routed to a select would submit "1" for 1. The typed field loses the
// enum constraint but keeps the value's type — the safer loss.
it("routes a nullable numeric enum to its typed field, not a select", () => {
const form = schemaToForm(
{
properties: {
level: {
anyOf: [{ type: "integer", enum: [1, 2] }, { type: "null" }],
},
ratio: {
anyOf: [{ type: "number", enum: [0.5, 1.5] }, { type: "null" }],
},
},
},
"numericEnum",
);
expect(
form.sections[0]!.fields.map((f) => ({ name: f.name, type: f.type })),
).toEqual([
{ name: "level", type: "integer" },
{ name: "ratio", type: "float" },
]);
});
it("routes a plain numeric enum to its typed field too", () => {
const form = schemaToForm(
{ properties: { level: { type: "integer", enum: [1, 2] } } },
"plainNumericEnum",
);
expect(form.sections[0]!.fields[0]).toMatchObject({ type: "integer" });
});
it("leaves a union of two real types as a plain string field", () => {
const form = schemaToForm(
{
properties: {
mixed: { anyOf: [{ type: "string" }, { type: "number" }] },
},
},
"realUnion",
);
expect(form.sections[0]!.fields[0]).toMatchObject({
name: "mixed",
type: "string",
});
});
});
});

View file

@ -207,7 +207,9 @@ describe("tui tsup config", () => {
// the double cast is bridging a real structural gap, not hiding a mismatch.
// A hook the patch called but the stub lacks fails as undefined here rather
// than passing silently.
inkFormLabelPatch.setup(
// esbuild types `setup` as `void | Promise<void>`; await it so the
// assertions below can't run before an async setup has registered.
await inkFormLabelPatch.setup(
build as unknown as Parameters<typeof inkFormLabelPatch.setup>[0],
);

View file

@ -11,7 +11,38 @@ describe("uriTemplateToForm", () => {
expect(form.title).toBe("Read Resource: file");
const fields = form.sections[0]!.fields;
expect(fields.map((f) => f.name)).toEqual(["path", "name"]);
expect(fields[0]).toMatchObject({ type: "string", required: false });
// Simple `{path}` sits mid-URI, so omitting it would leave an empty path
// segment rather than a shorter URI -- it is mandatory, matching the web
// panel. Both clients read this from core's `requiredGroups`.
expect(fields[0]).toMatchObject({ type: "string", required: true });
});
it("names fields as the expander looks them up, not as the SDK parses them", () => {
// The SDK reports these as ";id" and "id:3"; submitting under those keys
// would make the expander find nothing and drop the expression (#1919).
expect(
uriTemplateToForm("x://a{;id}", "matrix").sections[0]!.fields.map(
(f) => f.name,
),
).toEqual(["id"]);
expect(
uriTemplateToForm("x://a/{id:3}", "prefix").sections[0]!.fields.map(
(f) => f.name,
),
).toEqual(["id"]);
});
it("leaves a shared required group optional rather than demanding every name", () => {
// `{a,b}` is satisfied by either name, and ink-form cannot say "any one
// of"; marking both required would refuse input the expander accepts.
const fields = uriTemplateToForm("x://{a,b}", "pair").sections[0]!.fields;
expect(fields.map((f) => f.name)).toEqual(["a", "b"]);
expect(fields.every((f) => f.required === false)).toBe(true);
});
it("marks an omittable variable optional", () => {
const fields = uriTemplateToForm("x://a{?topic}", "q").sections[0]!.fields;
expect(fields[0]).toMatchObject({ name: "topic", required: false });
});
it("returns an empty Template Variables section for a static URI", () => {
@ -33,3 +64,15 @@ describe("uriTemplateToForm", () => {
expect(form.sections[0]!.fields).toEqual([]);
});
});
describe("a name repeated inside one expression", () => {
it("is required, not treated as a shared group", () => {
// `{a,a}` is one requirement named twice. Before core deduplicated the
// group, `requiredGroups` returned ["a","a"], so this form's
// `length === 1` test left the field optional while ResourceTestModal's
// submit guard still refused a blank -- an un-submittable form.
const [field] = uriTemplateToForm("x://{a,a}", "T").sections[0].fields;
expect(field.name).toBe("a");
expect(field.required).toBe(true);
});
});

View file

@ -30,4 +30,19 @@ export default defineConfig([
"react-hooks/exhaustive-deps": "warn",
},
},
{
// Type-aware pass for `no-floating-promises` (#1959) — see the CLI config
// for the reasoning. Both tsconfig projects are listed because `src` and
// `__tests__` live in different ones.
files: ["**/*.{ts,tsx}"],
languageOptions: {
parserOptions: {
project: ["./tsconfig.json", "./tsconfig.test.json"],
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
"@typescript-eslint/no-floating-promises": "error",
},
},
]);

View file

@ -170,6 +170,17 @@ function App({
pendingStepUpRef.current = pendingStepUp;
}, [pendingStepUp]);
const [connectError, setConnectError] = useState<string | null>(null);
// Monotonic token for in-flight disconnects — see handleDisconnect.
const disconnectAttemptRef = useRef(0);
// A failed disconnect is deliberately NOT folded into `connectError`. That
// one is only rendered by InfoTab when the status is "error", which a
// rejected disconnect leaves untouched (the status stays "connected"), so
// the message would never be seen — and it feeds
// `connectError ?? inspectorLastError`, where a stale value would go on
// masking a later, real connection error. This renders in the header
// regardless of status and is cleared on the next connect/disconnect
// attempt and on a server switch.
const [disconnectError, setDisconnectError] = useState<string | null>(null);
const oauthInProgressRef = useRef(false);
const callbackServerRef = useRef<OAuthCallbackServer | null>(null);
const selectedServerRef = useRef<string | null>(null);
@ -434,6 +445,13 @@ function App({
useEffect(() => {
setOauthStatus("idle");
setOauthMessage(null);
// The header banner is server-scoped, so a failure from the server we just
// left must not be read as this one's. Clearing is not enough: a switch
// away and back (A → B → A) would leave both the attempt token and the
// server name matching again, so the stale rejection would land on the
// re-selected A. Retiring the token on every switch is what closes that.
disconnectAttemptRef.current++;
setDisconnectError(null);
const stepUp = pendingStepUpRef.current;
if (stepUp && selectedServer && stepUp.serverName !== selectedServer) {
setPendingStepUp(null);
@ -757,6 +775,10 @@ function App({
if (!selectedServer || !selectedInspectorClient || !selectedServerConfig) {
return;
}
// A connect attempt supersedes whatever the last disconnect reported —
// including one still in flight, which is what the counter bump retires.
disconnectAttemptRef.current++;
setDisconnectError(null);
const finishConnect = async () => {
await connectInspector();
@ -887,8 +909,31 @@ function App({
// Disconnect handler
const handleDisconnect = useCallback(async () => {
if (!selectedServer) return;
await disconnectInspector();
// InspectorClient will update status automatically, and data is preserved
// Claim this attempt before awaiting. A disconnect can still be in flight
// when the user switches servers or presses 'd' again, and it is the
// *stale* one that usually rejects — so the catch below must be able to
// tell "my failure" from "one that has since been superseded", or server
// A's error lands in server B's header. `handleConnect` bumps the same
// counter for the same reason.
const attempt = ++disconnectAttemptRef.current;
const attemptServer = selectedServer;
// Clear first, so a retry that succeeds leaves no stale message behind.
setDisconnectError(null);
try {
await disconnectInspector();
// InspectorClient will update status automatically, and data is preserved
} catch (err) {
// Nothing above this catches: the only caller is the key handler, which
// cannot await, so without this the rejection escapes unhandled. A
// superseded one is still owned here — just not published.
if (
disconnectAttemptRef.current !== attempt ||
selectedServerRef.current !== attemptServer
) {
return;
}
setDisconnectError(err instanceof Error ? err.message : String(err));
}
}, [selectedServer, disconnectInspector]);
const handleClearOAuth = useCallback(async () => {
@ -1428,12 +1473,15 @@ function App({
input.toLowerCase() === "c" &&
(inspectorStatus === "disconnected" || inspectorStatus === "error")
) {
handleConnect();
// Both handlers own their failures internally (each ends in a catch
// that surfaces the message), so there is nothing left for a key
// handler — which cannot await — to do with the promise.
void handleConnect();
} else if (
input.toLowerCase() === "d" &&
(inspectorStatus === "connected" || inspectorStatus === "connecting")
) {
handleDisconnect();
void handleDisconnect();
}
}
});
@ -1617,6 +1665,11 @@ function App({
<Text color="red">OAuth: {oauthMessage}</Text>
</Box>
)}
{disconnectError && (
<Box marginTop={1}>
<Text color="red">Disconnect failed: {disconnectError}</Text>
</Box>
)}
</Box>
</Box>

View file

@ -53,8 +53,10 @@ export function PromptsTab({
if (selectedPrompt.arguments && selectedPrompt.arguments.length > 0) {
onFetchPrompt(selectedPrompt);
} else {
// No arguments, fetch directly
(async () => {
// No arguments, fetch directly. The IIFE catches everything it can
// throw, so there is no rejection for this key handler — which
// cannot await — to own.
void (async () => {
try {
const invocation = await inspectorClient.getPrompt(
selectedPrompt.name,

View file

@ -5,6 +5,11 @@ import { InspectorClient } from "@inspector/core/mcp/index.js";
import { AuthRecoveryRequiredError } from "@inspector/core/auth/challenge.js";
import type { ReadResourceResult } from "@modelcontextprotocol/client";
import { uriTemplateToForm } from "../utils/uriTemplateToForm.js";
import {
definedValues,
requiredGroups,
unmetRequiredGroups,
} from "@inspector/core/mcp/uriTemplate.js";
import { ScrollView, type ScrollViewRef } from "ink-scroll-view";
// Helper to extract error message from various error types
@ -133,14 +138,45 @@ export function ResourceTestModal({
const handleFormSubmit = async (values: Record<string, string>) => {
if (!inspectorClient || !template) return;
// RFC 6570 keeps a required expression satisfied by any ONE of its names,
// so `{a,b}` cannot be expressed with ink-form's per-field `required` flag
// and its members are left optional there. Without this check the TUI would
// submit `{a,b}` completely blank -- dropping the expression and reading a
// different resource -- while the web panel blocks the same request (#1919).
// The message and the gate come from the SAME pass. Filtering the groups
// again here with a bare `values[name]` disagreed with the gate for a
// variable named `constructor` or `toString`: the inherited member read as
// filled, so the list came out empty and the error named no field at all.
const unmetGroups = unmetRequiredGroups(
requiredGroups(template.uriTemplate),
values,
);
if (unmetGroups.length > 0) {
const unmet = unmetGroups.map((names) => names.join(" or "));
setResult({
input: values,
output: null,
error: `Missing required template variable(s): ${unmet.join(", ")}`,
duration: 0,
uri: template.uriTemplate,
});
setState("results");
return;
}
setState("loading");
const startTime = Date.now();
try {
// Use InspectorClient's readResourceFromTemplate method which encapsulates template expansion and resource reading
// Blanks are dropped HERE, not in the expander: a key present with `""`
// is a defined RFC 6570 value that legitimately expands to `?topic=`,
// but ink-form hands back `""` for every field the user never touched,
// so this form cannot tell the two apart. The web panel does the same at
// its own boundary.
const invocation = await inspectorClient.readResourceFromTemplate(
template.uriTemplate,
values,
definedValues(values),
);
const duration = Date.now() - startTime;

View file

@ -186,7 +186,9 @@ export function ResourcesTab({
}
};
fetchContent();
// An effect body is synchronous, and fetchContent already catches
// everything it can throw, so there is no rejection left to own.
void fetchContent();
}, [shouldFetchResource, inspectorClient, onAuthRecoveryRequired]);
const listWidth = Math.floor(width * 0.4);

View file

@ -3,10 +3,19 @@
*/
import type { FormStructure, FormSection, FormField } from "ink-form";
import {
isStringEnum,
normalizeNullableUnion,
} from "@inspector/core/json/nullableUnion.js";
/** Minimal JSON Schema property shape used when building tool parameter forms */
interface JsonSchemaProperty {
type?: string;
/**
* An array here is the `["string", "null"]` nullable encoding, which
* {@link normalizeNullableUnion} collapses to a single name before the
* dispatch below reads it.
*/
type?: string | string[];
title?: string;
enum?: unknown[];
/** Non-standard legacy support: titles for enum values */
@ -15,6 +24,8 @@ interface JsonSchemaProperty {
minimum?: number;
maximum?: number;
default?: unknown;
/** Present on a nullable union; see {@link normalizeNullableUnion}. */
anyOf?: readonly unknown[];
}
/**
@ -68,9 +79,16 @@ export function schemaToForm(
// `properties` values are `unknown` (the SDK schema admits anything), so
// guard before treating a value as a schema object — a malformed server
// schema with e.g. `properties: { foo: null }` must not throw on `.title`.
const property = (
typeof prop === "object" && prop !== null ? prop : {}
) as JsonSchemaProperty;
// Flatten a nullable union (`anyOf: [X, {type:"null"}]`, `type: [X,"null"]`)
// before dispatching. Every branch below reads a single `type` string, and
// for an enum the `enum` keyword sits on the union's surviving branch — so
// without this an argument declared with Zod's `.nullish()` loses its
// select and degrades to a plain text field (#2015, the TUI twin of #1928).
const property = normalizeNullableUnion(
(typeof prop === "object" && prop !== null
? prop
: {}) as JsonSchemaProperty,
);
const baseField = {
name: key,
label: property.title || key,
@ -90,12 +108,17 @@ export function schemaToForm(
...baseField,
options: toSelectOptions(property.items.enum, property.items.enumNames),
} as FormField;
} else if (property.enum) {
// Single select
} else if (isStringEnum(property.enum)) {
// Single select. Gated on the members being strings because
// `toSelectOptions` stringifies them and ink-form hands the string
// straight back: a numeric `enum: [1, 2]` would submit `"1"` and violate
// the schema. A typed non-string enum falls through to its typed field
// below, which loses the enum constraint but keeps the value's type —
// the safer of the two losses.
field = {
type: "select",
...baseField,
options: toSelectOptions(property.enum, property.enumNames),
options: toSelectOptions(property.enum ?? [], property.enumNames),
} as FormField;
} else {
// Map JSON Schema types to ink-form types

View file

@ -4,32 +4,50 @@
import type { FormStructure, FormSection, FormField } from "ink-form";
import { UriTemplate } from "@modelcontextprotocol/client";
import {
requiredGroups,
templateVariables,
} from "@inspector/core/mcp/uriTemplate.js";
/**
* Converts a URI Template to ink-form structure
* Converts a URI Template to ink-form structure.
*
* Fields come from core's `templateVariables`, the same parser
* `InspectorClient.readResourceFromTemplate` expands through, so the key this
* form submits is the key the expander looks up. Using the SDK's
* `variableNames` here instead is not merely untidy -- it mangles the name:
* `{;id}` yields `";id"` and `{id:3}` yields `"id:3"`, so the form would submit
* `{ ";id": "7" }` while the expander looks for `id`, silently dropping the
* value and the whole expression with it (#1919).
*
* The SDK template is still constructed, but only to validate: core's parser is
* deliberately lenient (an unclosed `{` becomes literal text), so this is what
* still surfaces a malformed template as an empty form plus a logged error.
*/
export function uriTemplateToForm(
uriTemplate: string,
templateName: string,
): FormStructure {
const fields: FormField[] = [];
let fields: FormField[] = [];
try {
const template = new UriTemplate(uriTemplate);
/* v8 ignore next -- UriTemplate.variableNames is a getter that always
returns a string[]; the `|| []` fallback is an unreachable guard. */
const variableNames = template.variableNames || [];
for (const variableName of variableNames) {
const field: FormField = {
name: variableName,
label: variableName,
type: "string",
required: false, // URI template variables are typically optional
};
fields.push(field);
}
new UriTemplate(uriTemplate);
// Only a variable that is the *sole* member of a non-omittable expression
// is genuinely mandatory. RFC 6570 drops undefined names from a multi-name
// expression, so `{a,b}` needs only one of the two -- ink-form cannot
// express "any one of these", and marking both required would refuse input
// the expander accepts.
const mandatory = new Set(
requiredGroups(uriTemplate)
.filter((names) => names.length === 1)
.map(([name]) => name),
);
fields = templateVariables(uriTemplate).map(({ name }) => ({
name,
label: name,
type: "string",
required: mandatory.has(name),
}));
} catch (error) {
// If parsing fails, return empty form
console.error("Failed to parse URI template:", error);