inspector/clients/web/src/components/screens/ToolsScreen/ToolsScreen.tsx
Cliff Hall 2259b1a3e1
Some checks failed
Run install, format, lint, build, and test on every push / build (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish-github-container-registry (push) Has been cancelled
Tasks: io.modelcontextprotocol/tasks extension on modern servers (era fork) (#1731)
* Tasks: modern io.modelcontextprotocol/tasks extension (era fork core)

Core + test-server implementation of the SEP-2663 tasks extension for modern
(2026-07-28) connections, forked from the legacy 2025-11-25 tasks path.

SDK v2 removed all tasks support AND era-gates the tasks/* spec methods out of
the modern era on both the client (outbound) and server (inbound) sides, and its
codec rejects a resultType:"task" result outright. So the Inspector drives the
extension itself: task creation rides tools/call (a modern method) with the
resultType:"task" frame rewritten at the transport to a CallToolResult carrying
the handle in _meta; tasks/get/update/cancel go over a raw-wire request channel
that bypasses the era gate (full modern envelope, string ids, consumed by the
transport). input_required tasks reuse the existing pending-request modal via
fulfilInputRequests, answered with tasks/update. No tasks/list, no tasks/result.

Tab + run-as-task gate on the negotiated extension; the managed task store's
refresh re-polls known handles on modern (no server list). Test server serves
the extension via an Express interceptor (SDK can't) + a shared poll-driven
runtime. Full integration coverage of both eras.

Refs #1631

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Tasks modern era: tests + coverage (raw-wire, schemas, era integration)

Adds unit coverage for modernTaskSchemas and the raw-wire request channel
(transport-null guard, send failure, timeout, error response, teardown), plus
end-to-end era integration tests (create/poll/input-required/update/cancel,
synchronous passthrough, unknown-id error, modern store re-poll). Fixes the App
and constructor-capabilities tests for the always-on tasks extension.

Refs #1631

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Tasks modern era: docs + share test servers per era to de-flake coverage

Document the tasks era-fork test configs in README and the new core/test-server
files in AGENTS.md. Share one modern + one legacy test server across the era
integration block (started lazily, stopped in afterAll) — starting a fresh
Express server per test made connection negotiation flaky under the heavy
concurrent coverage run.

Refs #1631

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Restore pr-screenshots deleted inadvertently

The logging/subscriptions PR screenshots + README were staged-deleted in the
working tree before this branch; restore them from v2/main so this PR doesn't
remove other PRs' artifacts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Tasks modern era: offer Run-as-task for any tool + PR screenshots

On modern (SEP-2663) task creation is server-directed — the client declares the
extension once and any tool may return a task — so the Tools screen now offers
'Run as task' for every tool on a modern connection (threaded via a modernTasks
prop through InspectorView → ToolsScreen → ToolDetailPanel), rather than gating
on the legacy per-tool taskSupport. Verified end-to-end in the web UI (remote
proxy): create → poll tasks/get → input_required elicitation → tasks/update →
inline result, plus the unchanged legacy tasks/list/result flow. Adds proof
screenshots.

Refs #1631

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Tasks modern era: address two follow-ups (task-input note + ordinary-path auto-poll)

1. The pending-request note now distinguishes a modern task round from an MRTR
   round: a new 'task-input-required' PendingRequestOrigin threads through
   fulfilInputRequests → the pending-request modal → MrtrOriginNote, which shows
   'submitted via a tasks/update request (SEP-2663), not a retry' instead of the
   MRTR retry copy.

2. The ordinary (non-run-as-task) modern callTool path now auto-polls an
   unsolicited task handle: attemptToolCall detects the rewritten handle in the
   result _meta and drives it to termination (get → input_required/update →
   inline result), dispatching task events so the Tasks tab + toasts track it and
   the tool result resolves to the task's final result. The poll loop is shared
   with the streaming path via extracted helpers (submitModernTaskInput /
   modernTaskTerminalOutcome / modernTaskPollInterval).

Refs #1631

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Tasks modern era: address review (negotiated envelope version, input-round cap, clarifying comment) + fresh smoke screenshots

Review of #1731:
1. withModernTaskEnvelope now stamps the NEGOTIATED protocol version
   (getProtocolVersion() ?? MODERN_PROTOCOL_VERSION) so the envelope matches the
   MCP-Protocol-Version header instead of a hardcoded constant.
2. A never-completing input_required task is now bounded by MRTR_MAX_ROUNDS in the
   shared submitModernTaskInput (threaded through both poll loops), so a
   non-conformant server can't re-prompt the user forever. New modern_loop_task
   test-server tool + integration test cover the cap.
3. ToolDetailPanel: comment clarifying that per-tool taskSupport:"forbidden" is
   deliberately ignored on modern (task creation is server-directed under SEP-2663).

(The abort-during-poll observation is addressed in the PR reply: the cancel path
uses tasks/cancel and disconnect rejects the in-flight raw request, so the poll
stops; matches legacy.)

Fresh web-UI smoke screenshots (modern connected, task completed, input_required
with the corrected tasks/update note, input completed).

Refs #1631

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Tasks modern era: fix uncancelable input-required loop + sticky cancel

Two bug fixes reported during manual testing of the tasks era-fork (#1631):

1. A modern task paused at `input_required` (e.g. `modern_loop_task`, which
   never advances) could not be cancelled: the poll loop blocked on the
   pending-request modal, so `cancelRequestorTask` sent `tasks/cancel` but the
   modal kept re-prompting. Now each modern poll loop registers a per-task
   AbortController (`registerTaskInputAbort`), `cancelRequestorTask` aborts it
   to reject the pending elicitation and unblock the poll, and the embedded
   input requests are tagged with their owning task id
   (`RELATED_TASK_META_KEY`) so the pending-request UI's Cancel action cancels
   the TASK rather than sending a "cancel" answer the server would re-prompt on.

2. On the legacy server, cancelling a task briefly showed CANCELLED then
   flipped to COMPLETED when the in-flight tool call resolved. Cancellation is
   a deliberate terminal decision, so `ManagedRequestorTasksState` now remembers
   cancelled task ids and ignores any later non-cancelled status update.

Also: move the compact task id onto its own line in the embedded monitoring
sidebar so the status badge / Cancel Task control don't wrap; DRY the duplicated
task poll-interval logic into a shared `taskPollInterval` helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Refresh tasks PR screenshots + capture both bug-fix scenarios

Recapture the five tasks flow screenshots against the current build and add
two demonstrating the post-review fixes: modern_loop_task cancelled from the
pending-request modal (uncancelable-loop fix) and a legacy task staying
CANCELLED after the in-flight call resolves (sticky-cancel fix).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Address re-review: sticky cancel on legacy refresh + App cancel-routing test

Re-review of the cancelable-loop / sticky-cancel fix raised two non-blocking
hardening items:

1. The legacy tasks/list refresh() rebuilt the list from the server, honoring
   only dismissedTaskIds — so a cooperative-cancel server that re-lists a
   user-cancelled task as completed could un-stick the cancel on a manual
   Refresh. The refresh path now pins a cancelledTaskIds task to "cancelled"
   (keeping it visible-as-cancelled, matching the live-merge handlers) rather
   than dropping it. Covered by a new state test.

2. Added an App.test.tsx case locking in the user-facing half of the fix: Cancel
   on a task-input-required elicitation calls cancelRequestorTask (not respond).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 19:17:04 -04:00

247 lines
9.2 KiB
TypeScript

import { Card, Flex, Stack, Text } from "@mantine/core";
import type {
CallToolResult,
ReadResourceResult,
Tool,
} from "@modelcontextprotocol/client";
import { ToolControls } from "../../groups/ToolControls/ToolControls";
import type { ListPaginationControlsProps } from "../../elements/ListPaginationControls/ListPaginationControls";
import {
ToolDetailPanel,
type ToolProgress,
} from "../../groups/ToolDetailPanel/ToolDetailPanel";
import { ToolResultPanel } from "../../groups/ToolResultPanel/ToolResultPanel";
import { resultHasResourceLinks } from "../../groups/ToolResultPanel/toolResultUtils";
import { collectSchemaDefaults, toFormSchema } from "../../../utils/jsonUtils";
export interface ToolCallState {
status: "idle" | "pending" | "ok" | "error";
result?: CallToolResult;
error?: string;
progress?: ToolProgress;
}
// Selection, form values, and sidebar search — controlled by the parent (App)
// as one object so they persist across tab navigation within a live session;
// the screen unmounts on tab switch, so local state would be lost (#1414/#1417).
export interface ToolsUiState {
selectedToolName?: string;
formValues: Record<string, unknown>;
search: string;
// Screen-level "Run as task" toggle, shared across tools (not per-tool):
// selecting a different tool keeps the current value. Persists across tab
// navigation like the rest of the UI state, and is only honored for the
// selected tool when its `execution.taskSupport` is "optional" (a "required"
// tool is always run as a task, "forbidden" never) — see ToolDetailPanel.
runAsTask: boolean;
}
export interface ToolsScreenProps {
tools: Tool[];
callState?: ToolCallState;
ui: ToolsUiState;
listChanged: boolean;
/** Whether the connected server advertises task-augmented tool calls. */
serverSupportsTaskToolCalls: boolean;
/** Modern (SEP-2663) tasks extension negotiated — "Run as task" is offered
* for any tool (server-directed task creation). */
modernTasks?: boolean;
onUiChange: (next: ToolsUiState) => void;
onRefreshList: () => void;
/** Pagination controls rendered in the sidebar (#1721). */
pagination: ListPaginationControlsProps;
onCallTool: (
name: string,
args: Record<string, unknown>,
runAsTask?: boolean,
) => void;
onCancelCall?: () => void;
onClearResult?: () => void;
/**
* Read-on-demand handler for `resource_link` blocks in a tool result.
* Passed through to the result panel so links can inline their contents.
*/
onReadResource?: (uri: string) => Promise<ReadResourceResult>;
}
// 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(100dvh - var(--app-shell-header-height, 0px) - var(--app-shell-footer-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(100dvh - var(--app-shell-header-height, 0px) - var(--app-shell-footer-height, 0px))",
gap: "md",
p: "xl",
});
const Sidebar = Stack.withProps({
// Widened from 340 to comfortably fit the pagination controls
// (Load-next-page button + status) without cramping list entries (#1721).
w: 360,
flex: "0 0 auto",
});
// `sidebar` variant makes the card a full-height flex column capped at the
// screen height, so ToolControls' list fills the card and scrolls internally
// once it overflows (matching the Resources sidebar). (#1417)
const SidebarCard = Card.withProps({
withBorder: true,
padding: "lg",
variant: "sidebar",
});
// 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",
});
// Full-height card for the empty placeholder (used with `flex={1}`) so it fills
// the screen height like the Prompts/Resources placeholders, rather than
// shrinking to its text. The result/detail states keep the content-sized
// `ContentCard` (their inner ScrollArea handles overflow).
const DetailCard = Card.withProps({
withBorder: true,
padding: "lg",
});
const EmptyState = Text.withProps({
c: "dimmed",
ta: "center",
py: "xl",
});
export function ToolsScreen({
tools,
callState,
ui,
listChanged,
serverSupportsTaskToolCalls,
modernTasks = false,
onUiChange,
onRefreshList,
pagination,
onCallTool,
onCancelCall,
onClearResult,
onReadResource,
}: ToolsScreenProps) {
const { selectedToolName, formValues, search } = ui;
const selectedTool = selectedToolName
? tools.find((t) => t.name === selectedToolName)
: undefined;
const isExecuting = callState?.status === "pending";
return (
<ScreenLayout>
<Sidebar>
<SidebarCard>
<ToolControls
tools={tools}
selectedName={selectedToolName}
searchText={search}
listChanged={listChanged}
onRefreshList={onRefreshList}
pagination={pagination}
onSearchChange={(value) => onUiChange({ ...ui, search: value })}
onSelectTool={(name) => {
// 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);
// `name` always comes from the rendered tools list (ToolControls
// only emits names it was given), so the lookup never misses; the
// empty-object fallback is an unreachable defensive default.
let formValues: Record<string, unknown> = {};
/* v8 ignore next -- unreachable: onSelectTool always names a tool in the list */
if (tool)
formValues = collectSchemaDefaults(
toFormSchema(tool.inputSchema) ?? {},
);
onUiChange({
...ui,
selectedToolName: name,
formValues,
});
}}
/>
</SidebarCard>
</Sidebar>
{callState?.result ? (
// Results replace the input form while present, and the panel's top-left
// X dismisses them back to the form (#1661) — the Prompts screen pattern.
// `formValues` live in the lifted UI state, so the form is restored
// intact for a re-run. A call in flight sets a `pending` state with no
// `result` (App.tsx), so the executing form (progress + cancel) shows
// until the result lands.
<ContentPane mah={SCROLL_MAX_HEIGHT}>
{/* Fill the pane's full height only when the result renders a
"Resource Links" box, so that box can expand into the available
space and scroll within. Plain text/image/error results keep the
content-sized card (matching the input-form state) instead of
reserving a tall empty card. */}
<ContentCard
flex={resultHasResourceLinks(callState.result) ? 1 : undefined}
>
<ToolResultPanel
result={callState.result}
onClear={() => onClearResult?.()}
onReadResource={onReadResource}
/>
</ContentCard>
</ContentPane>
) : selectedTool ? (
<ContentPane mah={SCROLL_MAX_HEIGHT}>
<ContentCard>
<ToolDetailPanel
tool={selectedTool}
formValues={formValues}
isExecuting={isExecuting}
progress={callState?.progress}
serverSupportsTaskToolCalls={serverSupportsTaskToolCalls}
modernTasks={modernTasks}
runAsTask={ui.runAsTask}
onRunAsTaskChange={(value) =>
onUiChange({ ...ui, runAsTask: value })
}
onFormChange={(values) =>
onUiChange({ ...ui, formValues: values })
}
onExecute={(runAsTask) =>
onCallTool(selectedTool.name, formValues, runAsTask)
}
onCancel={() => onCancelCall?.()}
/>
</ContentCard>
</ContentPane>
) : (
// Empty placeholder fills the full screen height (like Prompts/Resources)
// rather than shrinking to its text.
<DetailCard flex={1}>
<EmptyState>Select a tool to view details</EmptyState>
</DetailCard>
)}
</ScreenLayout>
);
}