feat(web): render pending sampling/elicitation requests (#1407) (#1411)

* feat(web): render pending sampling/elicitation requests (#1407)

Server-initiated sampling and elicitation requests never reached the v2
web UI: the InspectorClient queued them and returned a Promise that only
resolved on a user response, but nothing subscribed to the pending-change
events or rendered the (already-built) request components. A tool that
triggered one spun the Execute button forever.

Wire the queues to the UI:
- Add usePendingClientRequests() (core/react) subscribing to
  pendingSamplesChange / pendingElicitationsChange and returning the live
  arrays. Expose getPendingSamples() / getPendingElicitations() on
  InspectorClientProtocol (and the test fake) so hooks can read them.
- Add PendingClientRequestModal, an App-level modal that surfaces one
  queued request at a time (sampling-first) via the existing
  SamplingRequestPanel / ElicitationFormPanel / ElicitationUrlPanel. It is
  non-dismissable so the blocked call only resolves via an explicit action.
- Wire it in App.tsx: responding/rejecting resolves the client's handler
  Promise, which unblocks the originating call and clears the spinner.

Also fold in two issues surfaced while verifying:
- SchemaForm rendered an `array` + `items.enum` (multi-select enum) as a
  JSON textarea because only `items.anyOf` had a branch; add a MultiSelect
  branch with enumNames label support.
- ToolsScreen's result lives in App and outlived the screen's local
  selection (reset on tab-switch unmount), leaving a result with no
  selected tool. Clear the result on unmount for a clean slate on return.
  Prompts/Resources gate their preview on selection, so they are unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(elicitation): support explicit decline; honest queue label; review polish

Address @claude review on #1411:
- Add an explicit "Decline" action to ElicitationFormPanel so the spec's
  decline (refusal) is distinguishable from cancel (dismissal); the JSDoc
  claimed accept/decline/cancel but only accept/cancel were wired. Wire the
  modal body to emit { action: "decline" }.
- Replace the misleading "1 of N" queue label (the leading 1 never changed
  since the modal always shows the head) with an "N pending" hint, hidden when
  nothing else is queued.
- Make the dead useMemo honest: derive the head request inside the memo from
  the source arrays so it actually caches (the inline activeElicitation had a
  fresh identity every render).
- Document the URL elicitation accept-on-open semantic with a comment pointing
  at the follow-up (#1415).
- Add an App-level round-trip test driving pendingSamplesChange end-to-end
  (modal opens, respond() fires, empty event closes it).

Follow-ups filed: #1415 (URL two-step completion flow), #1416 (form required-
field submit gate + double-submit guard).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(elicitation): include untouched schema defaults in submitted content

The schema form displays a field's default via resolveValue(), but onChange
only writes a field into `values` once the user edits it. So an elicitation
submitted with default-only fields left untouched dropped them entirely —
v2 sent just the manually-edited fields while v1 sent defaults too (reported
with the everything server: firstLine/integer/number/enum defaults missing).

Add collectSchemaDefaults() to jsonUtils (recurses nested objects, omits
fields with no default) and seed ElicitationFormModalBody's values state with
it via a lazy initializer. The modal body is keyed by request id, so it
re-seeds per request; user edits still override seeded defaults via the
existing onChange merge.

Tests: collectSchemaDefaults unit tests (field types, nested, empty) in
jsonUtils.test; a modal test asserting an untouched-default form still submits
its defaults in content.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(forms): seed schema defaults for tool-call and app-launch forms too

Extend the elicitation defaults fix (collectSchemaDefaults) to the other two
SchemaForm consumers that own form state and submit it: ToolsScreen (tool
execute args) and AppsScreen (app launch args). Both reset formValues to {} on
selection, so default-only fields the user never edited were dropped from the
submitted args — same root cause as the elicitation modal.

Seed formValues from the selected tool/app inputSchema defaults on select.
User edits still override via the existing onFormChange merge.

(InlineElicitationRequest has no consumers wired up, so it's left as-is.)

Tests: ToolsScreen sends a tool's default on Execute without editing;
AppsScreen sends an app's default on Open App without editing.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(elicitation): gate form submit on required fields; guard double-submit (#1416)

Fold the #1416 hardening into this PR:

- Gate the elicitation form's Submit button on required fields. Promote the
  hasMissingRequiredFields helper out of AppDetailPanel into jsonUtils (shared)
  and use it in ElicitationFormPanel so Submit is disabled until every required
  field has a value.
- Guard against double-submit. Add an optional `busy` prop to the sampling,
  elicitation-form, and elicitation-url panels that disables their responding
  actions. PendingClientRequestModal's bodies use a new ref-guarded
  useRespondOnce() hook: the first action dispatches and locks the panel; later
  clicks no-op. This stops a fast double-click from calling respond()/reject()
  twice (which throws and produced an unhandled rejection). Copy URL stays
  enabled — it doesn't resolve the request.

Tests: hasMissingRequiredFields unit tests; ElicitationFormPanel submit-gate
and busy-lock tests; a modal double-click-resolves-once test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(tools): cap detail/result panels at viewport and scroll internally

The Tools screen's detail and result columns sized to their content and bled
past the bottom of the viewport on long output (e.g. the env dump or a long
elicitation result). Cap each column at the screen's available height and let
its panel scroll internally instead.

- ToolsScreen: drop `align: flex-start` and wrap each column in a stretched
  `ContentPane` (Flex column, capped by `mah` = viewport − header − xl*2). The
  pane's definite height is what lets the card's inner ScrollArea know how far
  to shrink — a bare `mah` on the card does not (the card sizes to content, so
  the scroll region renders full-height and overflow:hidden just clips it,
  unreachable). Mirrors the proven Prompts/Resources preview panes.
- ToolResultPanel: pinned header + inner ScrollArea (flex 0 1 auto, mih 0).
- ToolDetailPanel: pinned title/annotations header, scrolling body
  (description + form + progress), pinned Execute footer.

Audited the other screens: Prompts/Resources already use this pattern,
ServerList and the four list panels (Logging/Network/History/Tasks) already cap
via ScrollArea.Autosize. Only AppsScreen's app-input form had the same gap —
fixed it the same way: AppDetailPanel now scrolls internally and the card uses
variant="preview" so the running app's iframe and a long form both stay within
the viewport.

Verified in-browser against the everything server: the get-env result now
stops at the viewport bottom with margin and scrolls within the card
(clientHeight 502 vs scrollHeight 1931), header pinned.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(remote): use sync pino destinations in logging tests to fix teardown race

CI flaked with an uncaught `ENOENT: ... /tmp/inspector-log-unknown-level-*/app.log`
that failed an unrelated later test. The remote-logging integration tests create
`pino.destination(logFile)` loggers (async sonic-boom streams) and rmSync the temp
dir in finally/afterEach without closing the stream — a buffered background flush
then fires after the dir is gone and throws an uncaught error, which Vitest counts
as a run failure even though all tests pass.

Make those destinations `sync: true` so the write lands during the request instead
of on a later flush, removing the race. Test-only; unrelated to this PR's feature
work but it was blocking the PR's CI.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cliff Hall 2026-06-02 17:52:20 -04:00 • committed by GitHub
commit 8f6a2e0f78
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 1678 additions and 147 deletions

View file

@ -32,6 +32,8 @@ vi.mock("@inspector/core/mcp/index.js", () => {
.mockResolvedValue({ result: { contents: [] }, timestamp: 1 });
setLoggingLevel = vi.fn().mockResolvedValue(undefined);
getOAuthState = vi.fn().mockReturnValue(undefined);
getPendingSamples = vi.fn().mockReturnValue([]);
getPendingElicitations = vi.fn().mockReturnValue([]);
}
const instances: FakeInspectorClient[] = [];
return {
@ -255,3 +257,58 @@ describe("App session-scoped state reset on disconnect", () => {
expect(screen.getByTestId("log-level")).toHaveTextContent("info");
});
});
describe("App pending server-initiated request modal", () => {
beforeEach(() => {
clientInstances.length = 0;
});
it("opens the modal on a pending sample, resolves it, and closes", async () => {
const user = userEvent.setup();
renderWithMantine(<App />);
await user.click(screen.getByText("connect"));
await waitFor(() => expect(clientInstances).toHaveLength(1));
// The usePendingClientRequests hook subscribes to the live client's
// `pendingSamplesChange` event; firing it drives the App-owned modal that
// InspectorView does not render. Mirrors how the client enqueues a
// server-initiated sampling request mid tool-call.
const respond = vi.fn().mockResolvedValue(undefined);
const sample = {
id: "sample-1",
request: {
params: {
messages: [{ role: "user", content: { type: "text", text: "Hi" } }],
maxTokens: 256,
},
},
respond,
reject: vi.fn(),
};
act(() => {
clientInstances[0].dispatchEvent(
new CustomEvent("pendingSamplesChange", { detail: [sample] }),
);
});
await waitFor(() =>
expect(screen.getByText("Sampling Request")).toBeInTheDocument(),
);
// Resolving via the modal calls the queued request's respond() — this is
// what unblocks the originating call (the "spinner clears" criterion).
await user.click(screen.getByRole("button", { name: "Auto-respond" }));
expect(respond).toHaveBeenCalledTimes(1);
// The client clearing its queue (empty event) closes the modal.
act(() => {
clientInstances[0].dispatchEvent(
new CustomEvent("pendingSamplesChange", { detail: [] }),
);
});
await waitFor(() =>
expect(screen.queryByText("Sampling Request")).not.toBeInTheDocument(),
);
});
});

View file

@ -8,6 +8,8 @@ import {
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import type {
CreateMessageResult,
ElicitResult,
InitializeResult,
LoggingLevel,
LoggingMessageNotification,
@ -55,6 +57,7 @@ import { useResourceSubscriptions } from "@inspector/core/react/useResourceSubsc
import { useMessageLog } from "@inspector/core/react/useMessageLog.js";
import { useFetchRequestLog } from "@inspector/core/react/useFetchRequestLog.js";
import { useSandboxUrl } from "@inspector/core/react/useSandboxUrl.js";
import { usePendingClientRequests } from "@inspector/core/react/usePendingClientRequests.js";
import { InspectorView } from "./components/views/InspectorView/InspectorView";
import type { ToolCallState } from "./components/screens/ToolsScreen/ToolsScreen";
import type { GetPromptState } from "./components/screens/PromptsScreen/PromptsScreen";
@ -71,6 +74,10 @@ import { ConnectionInfoModal } from "./components/groups/ConnectionInfoModal/Con
import { OutputValidationModal } from "./components/groups/OutputValidationModal/OutputValidationModal";
import type { OAuthDetails } from "./components/groups/ConnectionInfoContent/ConnectionInfoContent";
import { ServerRemoveConfirmModal } from "./components/groups/ServerRemoveConfirmModal/ServerRemoveConfirmModal";
import {
PendingClientRequestModal,
type PendingClientRequestContent,
} from "./components/groups/PendingClientRequestModal/PendingClientRequestModal";
import { buildExportFilename, downloadJsonFile } from "./lib/downloadFile";
import { createWebEnvironment } from "./lib/environmentFactory";
import {
@ -353,6 +360,10 @@ function App() {
);
const { messages } = useMessageLog(messageLogState);
const { fetchRequests } = useFetchRequestLog(fetchRequestLogState);
// Server-initiated sampling / elicitation requests. These arrive while a call
// (e.g. a tool execution) is in flight and block it until the user responds.
const { pendingSamples, pendingElicitations } =
usePendingClientRequests(inspectorClient);
// Capture observed handshake latency at the connecting → connected edge.
// Reset when the status leaves "connected" so the next connect starts
@ -1328,6 +1339,71 @@ function App() {
return { ...readResourceState, isSubscribed };
}, [readResourceState, subscriptions]);
// Surface one pending server-initiated request at a time in the modal,
// sampling-first. Responding (below) removes it from the client's queue,
// which re-renders this with the next request or closes the modal.
const totalPendingRequests =
pendingSamples.length + pendingElicitations.length;
// Derive the head request inside the memo (depending on the source arrays)
// so the memo actually caches — an inline `activeElicitation` would have a
// fresh identity every render and defeat it.
const pendingRequestContent =
useMemo<PendingClientRequestContent | null>(() => {
const activeSample = pendingSamples[0];
if (activeSample) {
return {
kind: "sampling",
id: activeSample.id,
request: activeSample.request.params,
};
}
const activeElicitation = pendingElicitations[0];
if (activeElicitation) {
const params = activeElicitation.request.params;
if ("url" in params) {
return {
kind: "elicitation-url",
id: activeElicitation.id,
message: params.message,
url: params.url,
};
}
return {
kind: "elicitation-form",
id: activeElicitation.id,
request: params,
};
}
return null;
}, [pendingSamples, pendingElicitations]);
// A remaining-count hint shown only when more than the displayed head is
// queued. The modal always shows the head, so a "1 of N" position would be
// misleading — the leading "1" never changes.
const queueLabel =
totalPendingRequests > 1 ? `${totalPendingRequests} pending` : "";
const onSamplingRespond = useCallback(
(result: CreateMessageResult) => {
void pendingSamples[0]?.respond(result);
},
[pendingSamples],
);
const onSamplingReject = useCallback(() => {
void pendingSamples[0]?.reject(
new Error("Sampling request rejected by user."),
);
}, [pendingSamples]);
const onElicitationRespond = useCallback(
(result: ElicitResult) => {
void pendingElicitations[0]?.respond(result);
},
[pendingElicitations],
);
return (
<>
<InspectorView
@ -1445,6 +1521,14 @@ function App() {
message={outputValidationDetails?.message}
onClose={() => setOutputValidationDetails(null)}
/>
<PendingClientRequestModal
request={pendingRequestContent}
serverName={activeServer?.name ?? "this server"}
queuePosition={queueLabel}
onSamplingRespond={onSamplingRespond}
onSamplingReject={onSamplingReject}
onElicitationRespond={onElicitationRespond}
/>
</>
);
}

View file

@ -1,8 +1,9 @@
import { Button, Divider, Stack, Text } from "@mantine/core";
import { Button, Divider, ScrollArea, Stack, Text } from "@mantine/core";
import { MdPlayArrow } from "react-icons/md";
import type { Tool } from "@modelcontextprotocol/sdk/types.js";
import { SchemaForm } from "../SchemaForm/SchemaForm";
import { hasInputFields } from "../../../utils/toolUtils";
import { hasMissingRequiredFields } from "../../../utils/jsonUtils";
export interface AppDetailPanelProps {
tool: Tool;
@ -17,16 +18,22 @@ const DescriptionText = Text.withProps({
c: "dimmed",
});
function hasMissingRequiredFields(
schema: Tool["inputSchema"],
values: Record<string, unknown>,
): boolean {
const required = schema.required ?? [];
return required.some((field) => {
const value = values[field];
return value === undefined || value === null || value === "";
});
}
// Fills the available height inside AppsScreen's full-height card and scrolls
// the form (description + fields + Open App) when it would overflow, instead of
// bleeding past the viewport. `mih: 0` lets it shrink within the flex parent;
// standalone (no flex parent) it just sizes to content.
const PanelScroll = ScrollArea.withProps({
flex: 1,
mih: 0,
type: "auto",
scrollbars: "y",
offsetScrollbars: true,
});
const PanelStack = Stack.withProps({
gap: "md",
miw: 0,
});
export function AppDetailPanel({
tool,
@ -41,31 +48,33 @@ export function AppDetailPanel({
const hasFields = hasInputFields(tool);
return (
<Stack gap="md" miw={0}>
{description && <DescriptionText>{description}</DescriptionText>}
<PanelScroll>
<PanelStack>
{description && <DescriptionText>{description}</DescriptionText>}
{hasFields && <Divider />}
{hasFields && <Divider />}
{/* Form stays editable while validation fails so users can finish
filling required fields. The disabled-when-incomplete gate is on
the Open App button below, not on the form itself. */}
<SchemaForm
schema={inputSchema}
values={formValues}
onChange={onFormChange}
disabled={isOpening}
/>
{/* Form stays editable while validation fails so users can finish
filling required fields. The disabled-when-incomplete gate is on
the Open App button below, not on the form itself. */}
<SchemaForm
schema={inputSchema}
values={formValues}
onChange={onFormChange}
disabled={isOpening}
/>
<Button
size="md"
fullWidth
leftSection={<MdPlayArrow aria-hidden size={18} />}
onClick={onOpenApp}
disabled={disabled}
loading={isOpening}
>
Open App
</Button>
</Stack>
<Button
size="md"
fullWidth
leftSection={<MdPlayArrow aria-hidden size={18} />}
onClick={onOpenApp}
disabled={disabled}
loading={isOpening}
>
Open App
</Button>
</PanelStack>
</PanelScroll>
);
}

View file

@ -9,6 +9,7 @@ const meta: Meta<typeof ElicitationFormPanel> = {
args: {
onChange: fn(),
onSubmit: fn(),
onDecline: fn(),
onCancel: fn(),
serverName: "postgres-server",
values: {},

View file

@ -15,12 +15,22 @@ const dbRequest: ElicitRequestFormParams = {
},
};
const requiredRequest: ElicitRequestFormParams = {
message: "Please provide your name.",
requestedSchema: {
type: "object" as const,
properties: { name: { type: "string" as const, title: "Name" } },
required: ["name"],
},
};
const baseProps = {
request: dbRequest,
serverName: "postgres-server",
values: {},
onChange: vi.fn(),
onSubmit: vi.fn(),
onDecline: vi.fn(),
onCancel: vi.fn(),
};
@ -44,9 +54,10 @@ describe("ElicitationFormPanel", () => {
expect(screen.getByLabelText("Port")).toBeInTheDocument();
});
it("renders Submit and Cancel buttons", () => {
it("renders Submit, Decline, and Cancel buttons", () => {
renderWithMantine(<ElicitationFormPanel {...baseProps} />);
expect(screen.getByRole("button", { name: "Submit" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Decline" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument();
});
@ -60,6 +71,16 @@ describe("ElicitationFormPanel", () => {
expect(onSubmit).toHaveBeenCalledTimes(1);
});
it("invokes onDecline when Decline is clicked", async () => {
const user = userEvent.setup();
const onDecline = vi.fn();
renderWithMantine(
<ElicitationFormPanel {...baseProps} onDecline={onDecline} />,
);
await user.click(screen.getByRole("button", { name: "Decline" }));
expect(onDecline).toHaveBeenCalledTimes(1);
});
it("invokes onCancel when Cancel is clicked", async () => {
const user = userEvent.setup();
const onCancel = vi.fn();
@ -70,6 +91,32 @@ describe("ElicitationFormPanel", () => {
expect(onCancel).toHaveBeenCalledTimes(1);
});
it("disables Submit until required fields are filled", () => {
const { rerender } = renderWithMantine(
<ElicitationFormPanel
{...baseProps}
request={requiredRequest}
values={{}}
/>,
);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
rerender(
<ElicitationFormPanel
{...baseProps}
request={requiredRequest}
values={{ name: "Ada" }}
/>,
);
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
});
it("locks all actions when busy", () => {
renderWithMantine(<ElicitationFormPanel {...baseProps} busy />);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Decline" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();
});
it("invokes onChange when a schema field is updated", async () => {
const user = userEvent.setup();
const onChange = vi.fn();

View file

@ -1,6 +1,9 @@
import { Alert, Button, Divider, Group, Stack, Text } from "@mantine/core";
import type { ElicitRequestFormParams } from "@modelcontextprotocol/sdk/types.js";
import type { JsonSchemaType } from "../../../utils/jsonUtils";
import {
hasMissingRequiredFields,
type JsonSchemaType,
} from "../../../utils/jsonUtils";
import { SchemaForm } from "../SchemaForm/SchemaForm";
export interface ElicitationFormPanelProps {
@ -9,7 +12,15 @@ export interface ElicitationFormPanelProps {
values: Record<string, unknown>;
onChange: (values: Record<string, unknown>) => void;
onSubmit: () => void;
/** Explicit refusal to provide the data (maps to the spec's `decline`). */
onDecline: () => void;
/** Dismissal without an explicit choice (maps to the spec's `cancel`). */
onCancel: () => void;
/**
* A response has been dispatched; lock the actions so a second click can't
* resolve the request twice (the underlying handler throws if called again).
*/
busy?: boolean;
}
const QuotedMessage = Text.withProps({
@ -31,25 +42,36 @@ export function ElicitationFormPanel({
values,
onChange,
onSubmit,
onDecline,
onCancel,
busy = false,
}: ElicitationFormPanelProps) {
const requestedSchema = request.requestedSchema as JsonSchemaType;
const submitDisabled =
busy || hasMissingRequiredFields(requestedSchema, values);
return (
<Stack gap="md">
<QuotedMessage>{formatQuoted(request.message)}</QuotedMessage>
<Divider />
<SchemaForm
schema={request.requestedSchema as JsonSchemaType}
schema={requestedSchema}
values={values}
onChange={onChange}
disabled={busy}
/>
<Alert color="yellow" title="Warning">
{formatWarning(serverName)}
</Alert>
<Group justify="flex-end">
<Button variant="light" onClick={onCancel}>
<Button variant="light" onClick={onCancel} disabled={busy}>
Cancel
</Button>
<Button onClick={onSubmit}>Submit</Button>
<Button variant="light" color="red" onClick={onDecline} disabled={busy}>
Decline
</Button>
<Button onClick={onSubmit} disabled={submitDisabled}>
Submit
</Button>
</Group>
</Stack>
);

View file

@ -17,6 +17,12 @@ export interface ElicitationUrlPanelProps {
onCopyUrl: () => void;
onOpenInBrowser: () => void;
onCancel: () => void;
/**
* A response has been dispatched; lock the responding actions so a second
* click can't resolve the request twice (the handler throws if called
* again). Copy URL stays enabled — it doesn't resolve the request.
*/
busy?: boolean;
}
const ItalicMessage = Text.withProps({
@ -51,6 +57,7 @@ export function ElicitationUrlPanel({
onCopyUrl,
onOpenInBrowser,
onCancel,
busy = false,
}: ElicitationUrlPanelProps) {
return (
<Stack gap="md">
@ -62,7 +69,7 @@ export function ElicitationUrlPanel({
<Button variant="light" onClick={onCopyUrl}>
Copy URL
</Button>
<Button variant="light" onClick={onOpenInBrowser}>
<Button variant="light" onClick={onOpenInBrowser} disabled={busy}>
Open in Browser
</Button>
</Group>
@ -78,7 +85,7 @@ export function ElicitationUrlPanel({
This will open an external URL. Verify the domain before proceeding.
</Alert>
<Group justify="flex-end">
<Button variant="light" onClick={onCancel}>
<Button variant="light" onClick={onCancel} disabled={busy}>
Cancel
</Button>
</Group>

View file

@ -0,0 +1,117 @@
import { AppShell } from "@mantine/core";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, fn, userEvent, within } from "storybook/test";
import type {
CreateMessageRequestParams,
ElicitRequestFormParams,
} from "@modelcontextprotocol/sdk/types.js";
import {
PendingClientRequestModal,
type PendingClientRequestModalProps,
} from "./PendingClientRequestModal";
const samplingRequest: CreateMessageRequestParams = {
messages: [
{
role: "user",
content: {
type: "text",
text: "Summarize the latest changes in this repository.",
},
},
],
maxTokens: 1024,
};
const formRequest: ElicitRequestFormParams = {
message: "Please provide your database connection details.",
requestedSchema: {
type: "object",
properties: {
host: { type: "string", title: "Host" },
port: { type: "string", title: "Port" },
},
},
};
function InteractiveRender(args: PendingClientRequestModalProps) {
return (
<AppShell>
<AppShell.Main>
<PendingClientRequestModal {...args} />
</AppShell.Main>
</AppShell>
);
}
const meta: Meta<typeof PendingClientRequestModal> = {
title: "Groups/PendingClientRequestModal",
component: PendingClientRequestModal,
parameters: { layout: "fullscreen" },
render: InteractiveRender,
args: {
serverName: "Everything Server",
queuePosition: "1 of 1",
onSamplingRespond: fn(),
onSamplingReject: fn(),
onElicitationRespond: fn(),
},
};
export default meta;
type Story = StoryObj<typeof PendingClientRequestModal>;
export const Sampling: Story = {
args: {
request: { kind: "sampling", id: "sampling-1", request: samplingRequest },
},
play: async ({ canvasElement, args }) => {
const body = within(canvasElement.ownerDocument.body);
await body.findByText("Sampling Request");
expect(
body.getByText("The server is requesting an LLM completion."),
).toBeInTheDocument();
await userEvent.click(body.getByRole("button", { name: "Auto-respond" }));
expect(args.onSamplingRespond).toHaveBeenCalled();
},
};
export const ElicitationForm: Story = {
args: {
request: {
kind: "elicitation-form",
id: "elicitation-1",
request: formRequest,
},
},
play: async ({ canvasElement, args }) => {
const body = within(canvasElement.ownerDocument.body);
await body.findByText("Elicitation Request");
expect(
body.getByText(/Please provide your database connection details/),
).toBeInTheDocument();
await userEvent.click(body.getByRole("button", { name: "Submit" }));
expect(args.onElicitationRespond).toHaveBeenCalledWith({
action: "accept",
content: {},
});
},
};
export const ElicitationUrl: Story = {
args: {
request: {
kind: "elicitation-url",
id: "elicitation-2",
message: "Authorize access in your browser to continue.",
url: "https://example.com/authorize?token=abc123",
},
},
play: async ({ canvasElement }) => {
const body = within(canvasElement.ownerDocument.body);
await body.findByText("Elicitation Request");
expect(
body.getByText("https://example.com/authorize?token=abc123"),
).toBeInTheDocument();
},
};

View file

@ -0,0 +1,259 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import userEvent from "@testing-library/user-event";
import type {
CreateMessageRequestParams,
ElicitRequestFormParams,
} from "@modelcontextprotocol/sdk/types.js";
import { renderWithMantine, screen } from "../../../test/renderWithMantine";
import {
PendingClientRequestModal,
type PendingClientRequestContent,
} from "./PendingClientRequestModal";
const samplingRequest: CreateMessageRequestParams = {
messages: [
{
role: "user",
content: { type: "text", text: "What is the capital of France?" },
},
],
maxTokens: 1024,
};
const formRequest: ElicitRequestFormParams = {
message: "Please provide your name.",
requestedSchema: {
type: "object",
properties: { name: { type: "string", title: "Name" } },
},
};
const samplingContent: PendingClientRequestContent = {
kind: "sampling",
id: "sampling-1",
request: samplingRequest,
};
const formContent: PendingClientRequestContent = {
kind: "elicitation-form",
id: "elicitation-1",
request: formRequest,
};
const urlContent: PendingClientRequestContent = {
kind: "elicitation-url",
id: "elicitation-2",
message: "Authorize access in your browser.",
url: "https://example.com/authorize",
};
const baseProps = {
serverName: "Everything Server",
queuePosition: "1 of 1",
onSamplingRespond: vi.fn(),
onSamplingReject: vi.fn(),
onElicitationRespond: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
});
describe("PendingClientRequestModal", () => {
it("renders nothing when there is no active request", () => {
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={null} />,
);
expect(screen.queryByText("Sampling Request")).not.toBeInTheDocument();
expect(screen.queryByText("Elicitation Request")).not.toBeInTheDocument();
});
it("renders the sampling title, queue position, and panel", () => {
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={samplingContent} />,
);
expect(screen.getByText("Sampling Request")).toBeInTheDocument();
expect(screen.getByText("1 of 1")).toBeInTheDocument();
expect(
screen.getByText("The server is requesting an LLM completion."),
).toBeInTheDocument();
});
it("auto-responds with a stub sampling result", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={samplingContent} />,
);
await user.click(screen.getByRole("button", { name: "Auto-respond" }));
expect(baseProps.onSamplingRespond).toHaveBeenCalledWith({
model: "stub-model",
stopReason: "endTurn",
role: "assistant",
content: { type: "text", text: "" },
});
});
it("sends the edited sampling draft", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={samplingContent} />,
);
const textarea = screen
.getAllByRole("textbox")
.find((el) => el.tagName === "TEXTAREA") as HTMLTextAreaElement;
await user.type(textarea, "Paris");
await user.click(screen.getByRole("button", { name: "Send Response" }));
expect(baseProps.onSamplingRespond).toHaveBeenCalledWith(
expect.objectContaining({
content: { type: "text", text: "Paris" },
}),
);
});
it("rejects the sampling request", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={samplingContent} />,
);
await user.click(screen.getByRole("button", { name: "Reject" }));
expect(baseProps.onSamplingReject).toHaveBeenCalledTimes(1);
});
it("resolves a request only once when the action is double-clicked", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={samplingContent} />,
);
const autoRespond = screen.getByRole("button", { name: "Auto-respond" });
await user.click(autoRespond);
// After the first dispatch the actions lock (busy); a second click no-ops.
await user.click(autoRespond);
expect(baseProps.onSamplingRespond).toHaveBeenCalledTimes(1);
expect(
screen.getByRole("button", { name: "Send Response" }),
).toBeDisabled();
expect(screen.getByRole("button", { name: "Reject" })).toBeDisabled();
});
it("renders the elicitation form with the server name warning", () => {
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={formContent} />,
);
expect(screen.getByText("Elicitation Request")).toBeInTheDocument();
expect(screen.getByText(/Please provide your name/)).toBeInTheDocument();
expect(screen.getByText(/Everything Server/)).toBeInTheDocument();
});
it("accepts a form elicitation on submit", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={formContent} />,
);
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(baseProps.onElicitationRespond).toHaveBeenCalledWith({
action: "accept",
content: {},
});
});
it("includes untouched schema defaults in the submitted content", async () => {
const user = userEvent.setup();
const formWithDefaults: PendingClientRequestContent = {
kind: "elicitation-form",
id: "elicitation-defaults",
request: {
message: "Confirm your preferences.",
requestedSchema: {
type: "object",
properties: {
firstLine: {
type: "string",
title: "First line",
default: "It was a dark and stormy night.",
},
integer: { type: "integer", title: "Integer", default: 42 },
name: { type: "string", title: "Name" },
},
},
},
};
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={formWithDefaults} />,
);
// Submit without touching any field: the default-only fields must still be
// sent (the v1-parity bug this guards against dropped them).
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(baseProps.onElicitationRespond).toHaveBeenCalledWith({
action: "accept",
content: {
firstLine: "It was a dark and stormy night.",
integer: 42,
},
});
});
it("declines a form elicitation", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={formContent} />,
);
await user.click(screen.getByRole("button", { name: "Decline" }));
expect(baseProps.onElicitationRespond).toHaveBeenCalledWith({
action: "decline",
});
});
it("cancels a form elicitation", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={formContent} />,
);
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(baseProps.onElicitationRespond).toHaveBeenCalledWith({
action: "cancel",
});
});
it("opens the URL and accepts a URL elicitation", async () => {
const user = userEvent.setup();
const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={urlContent} />,
);
await user.click(screen.getByRole("button", { name: "Open in Browser" }));
expect(openSpy).toHaveBeenCalledWith(
"https://example.com/authorize",
"_blank",
"noopener,noreferrer",
);
expect(baseProps.onElicitationRespond).toHaveBeenCalledWith({
action: "accept",
});
openSpy.mockRestore();
});
it("copies the URL to the clipboard", async () => {
const user = userEvent.setup();
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, "clipboard", {
value: { writeText },
configurable: true,
});
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={urlContent} />,
);
await user.click(screen.getByRole("button", { name: "Copy URL" }));
expect(writeText).toHaveBeenCalledWith("https://example.com/authorize");
});
it("cancels a URL elicitation", async () => {
const user = userEvent.setup();
renderWithMantine(
<PendingClientRequestModal {...baseProps} request={urlContent} />,
);
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(baseProps.onElicitationRespond).toHaveBeenCalledWith({
action: "cancel",
});
});
});

View file

@ -0,0 +1,259 @@
import { useRef, useState } from "react";
import { Group, Modal, Text } from "@mantine/core";
import type {
CreateMessageRequestParams,
CreateMessageResult,
ElicitRequestFormParams,
ElicitResult,
} from "@modelcontextprotocol/sdk/types.js";
import { SamplingRequestPanel } from "../SamplingRequestPanel/SamplingRequestPanel";
import { ElicitationFormPanel } from "../ElicitationFormPanel/ElicitationFormPanel";
import { ElicitationUrlPanel } from "../ElicitationUrlPanel/ElicitationUrlPanel";
import {
collectSchemaDefaults,
type JsonSchemaType,
} from "../../../utils/jsonUtils";
/**
* The server-initiated request currently shown in the modal. `id` is the
* client-side request id; it keys the modal body so per-request draft state
* resets when the active request changes.
*/
export type PendingClientRequestContent =
| { kind: "sampling"; id: string; request: CreateMessageRequestParams }
| { kind: "elicitation-form"; id: string; request: ElicitRequestFormParams }
| { kind: "elicitation-url"; id: string; message: string; url: string };
export interface PendingClientRequestModalProps {
/** The active request to display, or null when nothing is pending. */
request: PendingClientRequestContent | null;
/** Display name of the connected server (shown in elicitation warnings). */
serverName: string;
/**
* Count label for the still-pending requests, e.g. "3 pending". The modal
* always shows the head of the queue, so this is a remaining-count hint, not
* a navigable position. Empty string hides the label (nothing else queued).
*/
queuePosition: string;
/** Resolve a sampling request with the given (drafted or auto) result. */
onSamplingRespond: (result: CreateMessageResult) => void;
/** Reject the active sampling request. */
onSamplingReject: () => void;
/** Resolve an elicitation request (accept/decline/cancel). */
onElicitationRespond: (result: ElicitResult) => void;
}
const TitleRow = Group.withProps({
justify: "space-between",
gap: "md",
w: "100%",
wrap: "nowrap",
});
const TitleText = Text.withProps({ fw: 600 });
const QueueLabel = Text.withProps({ size: "xs", c: "dimmed" });
/**
* The stub result pre-filled into a sampling draft. "Auto-respond" sends this
* as-is; "Send Response" sends whatever the user edited it into.
*/
function createDefaultSamplingResult(): CreateMessageResult {
return {
model: "stub-model",
stopReason: "endTurn",
role: "assistant",
content: { type: "text", text: "" },
};
}
function titleFor(content: PendingClientRequestContent): string {
return content.kind === "sampling"
? "Sampling Request"
: "Elicitation Request";
}
// Empty handler — the modal is intentionally non-dismissable; the request is
// only resolved via an explicit action button so the blocked call never hangs
// on an accidental dismissal.
function ignoreClose(): void {}
/**
* Returns a `responded` flag and a `once()` wrapper. The first invocation of
* any wrapped callback flips `responded` (to lock the panel's actions) and
* runs it; later invocations no-op. The ref makes the guard synchronous so a
* fast double-click can't resolve the request twice before the modal unmounts
* — respond()/reject() throw if called again. Reset per request via the body's
* `key`.
*/
function useRespondOnce(): {
responded: boolean;
once: (fn: () => void) => () => void;
} {
const [responded, setResponded] = useState(false);
const respondedRef = useRef(false);
const once = (fn: () => void) => () => {
if (respondedRef.current) return;
respondedRef.current = true;
setResponded(true);
fn();
};
return { responded, once };
}
function SamplingModalBody({
request,
onRespond,
onReject,
}: {
request: CreateMessageRequestParams;
onRespond: (result: CreateMessageResult) => void;
onReject: () => void;
}) {
const [draftResult, setDraftResult] = useState<CreateMessageResult>(
createDefaultSamplingResult,
);
const { responded, once } = useRespondOnce();
return (
<SamplingRequestPanel
request={request}
draftResult={draftResult}
onResultChange={setDraftResult}
onAutoRespond={once(() => onRespond(createDefaultSamplingResult()))}
onSend={once(() => onRespond(draftResult))}
onReject={once(onReject)}
busy={responded}
/>
);
}
function ElicitationFormModalBody({
request,
serverName,
onRespond,
}: {
request: ElicitRequestFormParams;
serverName: string;
onRespond: (result: ElicitResult) => void;
}) {
// Seed with the schema's defaults so default-only fields the user never
// touches are still included on submit (the form shows them via
// resolveValue, but onChange only writes edited fields). The modal body is
// keyed by request id, so this lazy initializer re-runs per request.
const [values, setValues] = useState<Record<string, unknown>>(() =>
collectSchemaDefaults(request.requestedSchema as JsonSchemaType),
);
const { responded, once } = useRespondOnce();
return (
<ElicitationFormPanel
request={request}
serverName={serverName}
values={values}
onChange={setValues}
onSubmit={once(() =>
onRespond({
action: "accept",
content: values as ElicitResult["content"],
}),
)}
onDecline={once(() => onRespond({ action: "decline" }))}
onCancel={once(() => onRespond({ action: "cancel" }))}
busy={responded}
/>
);
}
function ElicitationUrlModalBody({
id,
message,
url,
onRespond,
}: {
id: string;
message: string;
url: string;
onRespond: (result: ElicitResult) => void;
}) {
const { responded, once } = useRespondOnce();
return (
<ElicitationUrlPanel
message={message}
url={url}
requestId={id}
isWaiting={false}
onCopyUrl={() => {
void navigator.clipboard?.writeText(url);
}}
onOpenInBrowser={once(() => {
window.open(url, "_blank", "noopener,noreferrer");
// Accept-on-open: the inspector can't observe completion of an external
// flow, so opening the URL is treated as acceptance. This is optimistic
// — the user could close the tab without finishing. A proper two-step
// "open, then confirm completion" flow (using ElicitationUrlPanel's
// isWaiting state) is tracked as a follow-up; see #1415.
onRespond({ action: "accept" });
})}
onCancel={once(() => onRespond({ action: "cancel" }))}
busy={responded}
/>
);
}
/**
* App-level modal that surfaces a server-initiated sampling/elicitation request
* while a call (e.g. a tool execution) is in flight. Responding resolves the
* client's handler Promise, which unblocks the originating call.
*/
export function PendingClientRequestModal({
request,
serverName,
queuePosition,
onSamplingRespond,
onSamplingReject,
onElicitationRespond,
}: PendingClientRequestModalProps) {
return (
<Modal
opened={request !== null}
onClose={ignoreClose}
withCloseButton={false}
closeOnClickOutside={false}
closeOnEscape={false}
size="lg"
title={
request && (
<TitleRow>
<TitleText>{titleFor(request)}</TitleText>
{queuePosition && <QueueLabel>{queuePosition}</QueueLabel>}
</TitleRow>
)
}
>
{request?.kind === "sampling" && (
<SamplingModalBody
key={request.id}
request={request.request}
onRespond={onSamplingRespond}
onReject={onSamplingReject}
/>
)}
{request?.kind === "elicitation-form" && (
<ElicitationFormModalBody
key={request.id}
request={request.request}
serverName={serverName}
onRespond={onElicitationRespond}
/>
)}
{request?.kind === "elicitation-url" && (
<ElicitationUrlModalBody
key={request.id}
id={request.id}
message={request.message}
url={request.url}
onRespond={onElicitationRespond}
/>
)}
</Modal>
);
}

View file

@ -24,6 +24,11 @@ export interface SamplingRequestPanelProps {
onAutoRespond: () => void;
onSend: () => void;
onReject: () => void;
/**
* A response has been dispatched; lock the actions so a second click can't
* resolve the request twice (the underlying handler throws if called again).
*/
busy?: boolean;
}
function formatPriority(value: number): string {
@ -62,6 +67,7 @@ export function SamplingRequestPanel({
onAutoRespond,
onSend,
onReject,
busy = false,
}: SamplingRequestPanelProps) {
const {
messages,
@ -173,11 +179,15 @@ export function SamplingRequestPanel({
/>
</Group>
<Group justify="flex-end">
<Button variant="light" onClick={onAutoRespond}>
<Button variant="light" onClick={onAutoRespond} disabled={busy}>
Auto-respond
</Button>
<RejectButton onClick={onReject}>Reject</RejectButton>
<Button onClick={onSend}>Send Response</Button>
<RejectButton onClick={onReject} disabled={busy}>
Reject
</RejectButton>
<Button onClick={onSend} disabled={busy}>
Send Response
</Button>
</Group>
</Stack>
);

View file

@ -190,6 +190,66 @@ describe("SchemaForm", () => {
expect(onChange).toHaveBeenCalledWith({ tags: ["a"] });
});
it("renders a MultiSelect for an array of enum items and invokes onChange when an option is selected", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const schema: JsonSchemaType = {
type: "object",
properties: {
instruments: {
type: "array",
description: "Choose your favorite instruments",
items: {
type: "string",
enum: ["Guitar", "Piano", "Drums"],
},
},
},
};
renderWithMantine(
<SchemaForm schema={schema} values={{}} onChange={onChange} />,
);
// Falls back to the field name as label when no title is supplied.
await user.click(screen.getByRole("textbox", { name: "instruments" }));
const option = await screen.findByRole("option", {
name: "Guitar",
hidden: true,
});
await user.click(option);
expect(onChange).toHaveBeenCalledWith({ instruments: ["Guitar"] });
});
it("uses enumNames for enum-array option labels and the raw value on change", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const schema: JsonSchemaType = {
type: "object",
properties: {
sizes: {
type: "array",
title: "Sizes",
items: {
type: "string",
enum: ["s", "m", "l"],
enumNames: ["Small", "Medium", "Large"],
},
},
},
};
renderWithMantine(
<SchemaForm schema={schema} values={{}} onChange={onChange} />,
);
await user.click(screen.getByRole("textbox", { name: "Sizes" }));
// The option shows the enumNames label...
const option = await screen.findByRole("option", {
name: "Medium",
hidden: true,
});
await user.click(option);
// ...but the value persisted is the raw enum value.
expect(onChange).toHaveBeenCalledWith({ sizes: ["m"] });
});
it("renders nested object fields recursively", () => {
const onChange = vi.fn();
const schema: JsonSchemaType = {

View file

@ -155,6 +155,31 @@ export function SchemaForm({
);
}
// array of enum values (multi-select)
if (fieldSchema.type === "array" && fieldSchema.items?.enum) {
const itemEnum = fieldSchema.items.enum;
const itemEnumNames = fieldSchema.items.enumNames;
const data =
itemEnumNames && itemEnumNames.length === itemEnum.length
? itemEnum.map((value, index) => ({
value,
label: itemEnumNames[index],
}))
: itemEnum;
return (
<MultiSelect
key={fieldName}
label={label}
description={description}
withAsterisk={isRequired}
disabled={disabled}
data={data}
value={(rawValue as string[]) ?? []}
onChange={(val) => handleFieldChange(fieldName, val)}
/>
);
}
// array with items having anyOf
if (fieldSchema.type === "array" && fieldSchema.items?.anyOf) {
const data = fieldSchema.items.anyOf.map((item) => ({

View file

@ -1,4 +1,12 @@
import { Button, Divider, Group, Image, Stack, Text } from "@mantine/core";
import {
Button,
Divider,
Group,
Image,
ScrollArea,
Stack,
Text,
} from "@mantine/core";
import type {
ProgressNotification,
Tool,
@ -24,6 +32,40 @@ export interface ToolDetailPanelProps {
onCancel: () => void;
}
// Outer column: title/annotations pin at top, the Execute footer pins at the
// bottom, and the middle (description + form + progress) scrolls when the
// enclosing card hits its `mah`. `mih: 0` lets the flex children shrink.
const PanelStack = Stack.withProps({
gap: "md",
miw: 0,
mih: 0,
});
const PinnedHeader = Stack.withProps({
gap: "md",
flex: "0 0 auto",
});
// `0 1 auto` + `mih: 0`: shrinks to the available space and scrolls; a short
// form doesn't reserve extra height, keeping Execute snug below it.
const BodyScroll = ScrollArea.withProps({
flex: "0 1 auto",
miw: 0,
mih: 0,
type: "auto",
scrollbars: "y",
offsetScrollbars: true,
});
const BodyStack = Stack.withProps({
gap: "md",
});
const FooterRow = Group.withProps({
justify: "flex-end",
flex: "0 0 auto",
});
const TitleRow = Group.withProps({
gap: "sm",
wrap: "nowrap",
@ -76,42 +118,48 @@ export function ToolDetailPanel({
const iconSrc = icons?.[0]?.src;
return (
<Stack gap="md" miw={0}>
<TitleRow>
{iconSrc && <ToolIcon src={iconSrc} alt="" />}
<ToolTitle>{resolveDisplayLabel(name, title)}</ToolTitle>
</TitleRow>
{hasAnyAnnotation(annotations) && annotations && (
<Group gap="xs">
{annotations.readOnlyHint && (
<AnnotationBadge facet="readOnlyHint" value={true} />
)}
{annotations.destructiveHint && (
<AnnotationBadge facet="destructiveHint" value={true} />
)}
{annotations.idempotentHint && (
<AnnotationBadge facet="idempotentHint" value={true} />
)}
{annotations.openWorldHint && (
<AnnotationBadge facet="openWorldHint" value={true} />
)}
</Group>
)}
<PanelStack>
<PinnedHeader>
<TitleRow>
{iconSrc && <ToolIcon src={iconSrc} alt="" />}
<ToolTitle>{resolveDisplayLabel(name, title)}</ToolTitle>
</TitleRow>
{hasAnyAnnotation(annotations) && annotations && (
<Group gap="xs">
{annotations.readOnlyHint && (
<AnnotationBadge facet="readOnlyHint" value={true} />
)}
{annotations.destructiveHint && (
<AnnotationBadge facet="destructiveHint" value={true} />
)}
{annotations.idempotentHint && (
<AnnotationBadge facet="idempotentHint" value={true} />
)}
{annotations.openWorldHint && (
<AnnotationBadge facet="openWorldHint" value={true} />
)}
</Group>
)}
</PinnedHeader>
{description && <DescriptionText>{description}</DescriptionText>}
<BodyScroll>
<BodyStack>
{description && <DescriptionText>{description}</DescriptionText>}
<Divider />
<Divider />
<SchemaForm
schema={inputSchema}
values={formValues}
onChange={onFormChange}
disabled={isExecuting}
/>
<SchemaForm
schema={inputSchema}
values={formValues}
onChange={onFormChange}
disabled={isExecuting}
/>
{progress && <ProgressDisplay params={progress} />}
{progress && <ProgressDisplay params={progress} />}
</BodyStack>
</BodyScroll>
<Group justify="flex-end">
<FooterRow>
{isExecuting && <CancelButton onClick={onCancel}>Cancel</CancelButton>}
<Button
size="md"
@ -121,7 +169,7 @@ export function ToolDetailPanel({
>
Execute Tool
</Button>
</Group>
</Stack>
</FooterRow>
</PanelStack>
);
}

View file

@ -1,4 +1,12 @@
import { Alert, Button, Group, Stack, Text, Title } from "@mantine/core";
import {
Alert,
Button,
Group,
ScrollArea,
Stack,
Text,
Title,
} from "@mantine/core";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { ContentViewer } from "../../elements/ContentViewer/ContentViewer";
@ -12,33 +20,64 @@ const ClearButton = Button.withProps({
size: "sm",
});
// Outer column: the header pins (`flex: 0 0 auto`) and the scroll region
// absorbs overflow when the enclosing card hits its `mah`. `mih: 0` lets the
// flex children shrink below their content's intrinsic height.
const PanelStack = Stack.withProps({
gap: "md",
miw: 0,
mih: 0,
});
const HeaderRow = Group.withProps({
justify: "space-between",
flex: "0 0 auto",
});
// `0 1 auto` + `mih: 0` lets the scroll region shrink (never grow) so a short
// result doesn't reserve height while a long one scrolls within the card cap.
const ResultScroll = ScrollArea.withProps({
flex: "0 1 auto",
miw: 0,
mih: 0,
type: "auto",
scrollbars: "y",
offsetScrollbars: true,
});
const ResultStack = Stack.withProps({
gap: "md",
});
export function ToolResultPanel({ result, onClear }: ToolResultPanelProps) {
return (
<Stack>
<Group justify="space-between">
<PanelStack>
<HeaderRow>
<Title order={4}>Results</Title>
<ClearButton onClick={onClear}>Clear</ClearButton>
</Group>
{result.isError ? (
<Alert color="red" variant="light" title="Tool Error">
{result.content
.filter((b) => b.type === "text")
.map((b) => b.text)
.join("\n")}
</Alert>
) : result.content.length === 0 ? (
<Text c="dimmed">No results yet</Text>
) : (
<>
{result.content.map((block, index) => (
<ContentViewer
key={index}
block={block}
copyable={block.type === "text"}
/>
))}
</>
)}
</Stack>
</HeaderRow>
<ResultScroll>
<ResultStack>
{result.isError ? (
<Alert color="red" variant="light" title="Tool Error">
{result.content
.filter((b) => b.type === "text")
.map((b) => b.text)
.join("\n")}
</Alert>
) : result.content.length === 0 ? (
<Text c="dimmed">No results yet</Text>
) : (
result.content.map((block, index) => (
<ContentViewer
key={index}
block={block}
copyable={block.type === "text"}
/>
))
)}
</ResultStack>
</ResultScroll>
</PanelStack>
);
}

View file

@ -40,7 +40,7 @@ const cohortApp: Tool = {
description: "Cohort retention",
inputSchema: {
type: "object",
properties: { metric: { type: "string" } },
properties: { metric: { type: "string", default: "retention" } },
},
_meta: { ui: { resourceUri: "ui://apps/cohorts" } },
};
@ -170,6 +170,16 @@ describe("AppsScreen", () => {
expect(screen.getByTitle("Weather Widget")).toBeInTheDocument();
});
it("seeds schema defaults so untouched fields are sent on Open App", async () => {
const user = userEvent.setup();
const onOpenApp = vi.fn();
renderWithMantine(<AppsScreen {...buildProps({ onOpenApp })} />);
await user.click(screen.getByText("Cohort Data"));
// Open without editing the metric field: its default must still be sent.
await user.click(screen.getByRole("button", { name: /Open App/ }));
expect(onOpenApp).toHaveBeenCalledWith("cohorts", { metric: "retention" });
});
it("returns to the input form when 'Back to Input' is clicked", async () => {
const user = userEvent.setup();
renderWithMantine(<AppsScreen {...buildProps()} />);

View file

@ -25,6 +25,7 @@ import {
import { AppDetailPanel } from "../../groups/AppDetailPanel/AppDetailPanel";
import { AppControls } from "../../groups/AppControls/AppControls";
import { hasInputFields, resolveDisplayLabel } from "../../../utils/toolUtils";
import { collectSchemaDefaults } from "../../../utils/jsonUtils";
export interface AppsScreenProps {
tools: Tool[];
@ -64,9 +65,13 @@ const SidebarCard = Card.withProps({
padding: "lg",
});
// `variant="preview"` (overflow: hidden) keeps the full-height card from
// bleeding past the viewport: the running app's iframe fills it, and the
// app-input form scrolls internally (see AppDetailPanel's PanelScroll).
const ContentCard = Card.withProps({
withBorder: true,
padding: "lg",
variant: "preview",
});
const EmptyState = Text.withProps({
@ -149,7 +154,9 @@ export function AppsScreen({
const next = tools.find((t) => t.name === name);
if (!next) return;
setSelectedAppName(name);
setFormValues({});
// Seed schema defaults so default-only fields are sent on Open App (parity
// with the form's resolveValue display, which onChange doesn't capture).
setFormValues(collectSchemaDefaults(next.inputSchema));
setMaximized(false);
onSelectApp(name);
// No-input apps auto-launch on selection so the user lands directly in

View file

@ -248,6 +248,7 @@ export const WithElicitationModal: Story = {
values={{}}
onChange={fn()}
onSubmit={fn()}
onDecline={fn()}
onCancel={fn()}
/>
</Modal>

View file

@ -7,6 +7,13 @@ import { ToolsScreen } from "./ToolsScreen";
const tools: Tool[] = [
{ name: "alpha", inputSchema: { type: "object" } },
{ name: "beta", inputSchema: { type: "object" } },
{
name: "gamma",
inputSchema: {
type: "object",
properties: { mode: { type: "string", default: "fast" } },
},
},
];
const baseProps = {
@ -56,6 +63,16 @@ describe("ToolsScreen", () => {
expect(onCallTool).toHaveBeenCalledWith("alpha", {});
});
it("seeds schema defaults so untouched fields are sent on Execute", async () => {
const user = userEvent.setup();
const onCallTool = vi.fn();
renderWithMantine(<ToolsScreen {...baseProps} onCallTool={onCallTool} />);
await user.click(screen.getByText("gamma"));
// Execute without editing the form: the default must still be sent.
await user.click(screen.getByRole("button", { name: /Execute/ }));
expect(onCallTool).toHaveBeenCalledWith("gamma", { mode: "fast" });
});
it("invokes onClearResult when Clear is clicked on the result panel", async () => {
const user = userEvent.setup();
const onClearResult = vi.fn();
@ -73,6 +90,23 @@ describe("ToolsScreen", () => {
expect(onClearResult).toHaveBeenCalledTimes(1);
});
it("clears the persisted result when the screen unmounts", () => {
const onClearResult = vi.fn();
const { unmount } = renderWithMantine(
<ToolsScreen
{...baseProps}
onClearResult={onClearResult}
callState={{
status: "ok",
result: { content: [{ type: "text", text: "ok" }] },
}}
/>,
);
expect(onClearResult).not.toHaveBeenCalled();
unmount();
expect(onClearResult).toHaveBeenCalledTimes(1);
});
it("treats pending callState as executing", async () => {
const user = userEvent.setup();
renderWithMantine(

View file

@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useRef, useState } from "react";
import { Card, Flex, Stack, Text } from "@mantine/core";
import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
import { ToolControls } from "../../groups/ToolControls/ToolControls";
@ -7,6 +7,7 @@ import {
type ToolProgress,
} from "../../groups/ToolDetailPanel/ToolDetailPanel";
import { ToolResultPanel } from "../../groups/ToolResultPanel/ToolResultPanel";
import { collectSchemaDefaults } from "../../../utils/jsonUtils";
export interface ToolCallState {
status: "idle" | "pending" | "ok" | "error";
@ -25,12 +26,21 @@ export interface ToolsScreenProps {
onClearResult?: () => void;
}
// Caps the detail/result columns at the screen's available height: full
// viewport minus the app-shell header and the screen's top+bottom xl padding,
// leaving the bottom margin the overflow used to eat.
const SCROLL_MAX_HEIGHT =
"calc(100vh - var(--app-shell-header-height, 0px) - var(--mantine-spacing-xl) * 2)";
// No `align` override: children stretch to the row's full height, giving each
// column pane a definite height. That definite height is what lets a column's
// inner ScrollArea know how much it can shrink into (a bare `mah` doesn't —
// see the Prompts/Resources preview panes this mirrors).
const ScreenLayout = Flex.withProps({
variant: "screen",
h: "calc(100vh - var(--app-shell-header-height, 0px))",
gap: "md",
p: "xl",
align: "flex-start",
});
const Sidebar = Stack.withProps({
@ -43,9 +53,22 @@ const SidebarCard = Card.withProps({
padding: "lg",
});
// Column wrapper: stretches to the screen's available height (capped by the
// consumer-set `mah`) so the card inside has a definite height to shrink into.
const ContentPane = Flex.withProps({
flex: 1,
miw: 0,
direction: "column",
align: "stretch",
});
// Detail/result column card: `variant="preview"` (overflow: hidden) lets the
// panel's inner ScrollArea take over scrolling instead of the card bleeding
// past the viewport. Sizes to content when short, caps at the pane when tall.
const ContentCard = Card.withProps({
withBorder: true,
padding: "lg",
variant: "preview",
});
const EmptyState = Text.withProps({
@ -72,6 +95,22 @@ export function ToolsScreen({
: undefined;
const isExecuting = callState?.status === "pending";
// The result lives in App so it survives pending → ok/error without
// remounting the screen. But the screen's selection is local and resets when
// the screen unmounts on tab switch — leaving the Results panel showing a
// result with no selected tool. Clear the result on unmount so returning to
// the screen starts from a clean slate. A ref keeps the latest handler so the
// effect can stay mount/unmount-only without re-running mid-session.
const onClearResultRef = useRef(onClearResult);
useEffect(() => {
onClearResultRef.current = onClearResult;
}, [onClearResult]);
useEffect(() => {
return () => {
onClearResultRef.current?.();
};
}, []);
return (
<ScreenLayout>
<Sidebar>
@ -82,39 +121,50 @@ export function ToolsScreen({
listChanged={listChanged}
onRefreshList={onRefreshList}
onSelectTool={(name) => {
setFormValues({});
// Seed the form with the tool's schema defaults so default-only
// fields the user never edits are still sent on execute (the
// form shows defaults via resolveValue, but onChange only writes
// edited fields).
const tool = tools.find((t) => t.name === name);
setFormValues(
tool ? collectSchemaDefaults(tool.inputSchema) : {},
);
setSelectedToolName(name);
}}
/>
</SidebarCard>
</Sidebar>
<ContentCard flex={1}>
{selectedTool ? (
<ToolDetailPanel
tool={selectedTool}
formValues={formValues}
isExecuting={isExecuting}
progress={callState?.progress}
onFormChange={setFormValues}
onExecute={() => onCallTool(selectedTool.name, formValues)}
onCancel={() => onCancelCall?.()}
/>
) : (
<EmptyState>Select a tool to view details</EmptyState>
)}
</ContentCard>
<ContentPane mah={SCROLL_MAX_HEIGHT}>
<ContentCard>
{selectedTool ? (
<ToolDetailPanel
tool={selectedTool}
formValues={formValues}
isExecuting={isExecuting}
progress={callState?.progress}
onFormChange={setFormValues}
onExecute={() => onCallTool(selectedTool.name, formValues)}
onCancel={() => onCancelCall?.()}
/>
) : (
<EmptyState>Select a tool to view details</EmptyState>
)}
</ContentCard>
</ContentPane>
<ContentCard flex={1}>
{callState?.result ? (
<ToolResultPanel
result={callState.result}
onClear={() => onClearResult?.()}
/>
) : (
<EmptyState>Results will appear here</EmptyState>
)}
</ContentCard>
<ContentPane mah={SCROLL_MAX_HEIGHT}>
<ContentCard>
{callState?.result ? (
<ToolResultPanel
result={callState.result}
onClear={() => onClearResult?.()}
/>
) : (
<EmptyState>Results will appear here</EmptyState>
)}
</ContentCard>
</ContentPane>
</ScreenLayout>
);
}

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