Tasks: io.modelcontextprotocol/tasks extension on modern servers (era fork) (#1731)
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: 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>
This commit is contained in:
Cliff Hall 2026-07-21 19:17:04 -04:00 • committed by GitHub
commit 2259b1a3e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
42 changed files with 2483 additions and 132 deletions

View file

@ -33,6 +33,9 @@ inspector/
│ ├── json/ # JSON utilities and parameter/argument conversion
│ ├── logging/ # Silent pino logger singleton
│ ├── mcp/ # InspectorClient runtime + state stores
│ │ # (modernTaskSchemas.ts: SEP-2663 modern Tasks
│ │ # extension wire schemas + normalize/handle helpers,
│ │ # used by the raw-wire tasks/* channel — #1631)
│ │ ├── import/ # Config import strategies (#1348): client-config parsers
│ │ │ # (Claude Desktop/Cursor/Cline/VS Code), registry
│ │ │ # server.json parser, strategy registry + well-known
@ -45,7 +48,9 @@ inspector/
│ ├── react/ # React hooks over the state stores
│ └── storage/ # File I/O helpers (store-io.ts) used by OAuth persist backends
├── test-servers/ # Composable MCP test servers + fixtures used by integration tests.
│ ├── src/ # TypeScript sources.
│ ├── src/ # TypeScript sources. (modern-tasks.ts: SEP-2663 modern
│ │ # Tasks extension runtime + tasks/* Express interceptor
│ │ # + modern_task/modern_input_task tools — #1631)
│ ├── build/ # Built JS (gitignored). Produced by `npm run test-servers:build`
│ │ # so integration tests can spawn the stdio server as a real
│ │ # subprocess via `node test-servers/build/test-server-stdio.js`.

View file

@ -120,6 +120,8 @@ A streamable-HTTP server can also serve the **modern (2026-07-28) protocol era**
`test-servers/configs/subscriptions-legacy-http.json` and `test-servers/configs/subscriptions-modern-http.json` are the **resource-subscription era-fork showcase** (#1630). Both serve three `numbered_resources` with `subscriptions: true`; the legacy one also serves an `update_resource` tool, and the modern one sets `transport.modern: true`. Connect to the **legacy** server, open a resource in the **Resources** tab and click **Subscribe** — the client sends `resources/subscribe` (Network/Protocol view) and the Subscriptions section lists the URI with no stream chrome; call `update_resource` with that URI and the server updates the content and emits `notifications/resources/updated`, stamping the subscribed tile's last-updated time. Connect to the **modern** server with **Protocol Era = Modern** and the same Subscribe instead sends **`subscriptions/listen`** (its filter carries `resourceSubscriptions` + the `resourcesListChanged` opt-in) and resolves on `notifications/subscriptions/acknowledged`; the Subscriptions section then shows the stream-status badge (`Connecting…` → `Listening`) in its header, and if the long-lived stream drops it reconnects by re-listing. The modern config deliberately **omits** `update_resource`: the SDK's modern leg is stateless/per-request (`createMcpHandler(() => createMcpServer(config))`), so the tool would run against a throwaway server instance — the content change wouldn't persist for the next `resources/read`, and its `resources/updated` wouldn't reach the (separate) listen stream — which is more confusing than useful. The live update-notification round-trip is therefore demonstrated on the legacy (stateful-session) server; the modern server is for the subscribe/listen/badge behavior. (The Inspector's *receive* path is era-transparent, so a real stateful modern server that routes `resources/updated` onto the listen stream drives the subscribed tile the same way.)
`test-servers/configs/tasks-legacy-http.json` and `test-servers/configs/tasks-modern-http.json` are the **Tasks era-fork showcase** (#1631). The legacy server advertises `capabilities.tasks` (`tasks: { list, cancel }`) with the `simple_task` / `progress_task` / `elicitation_task` presets — connect to it, run one of those tools with **Run as task** on, and the **Tasks** tab lists it (populated via `tasks/list`), polls `tasks/get`, fetches the payload with the blocking `tasks/result`, and cancels with `tasks/cancel`. The modern server sets `transport.modern: true` and `tasksExtension: true`, advertising the `io.modelcontextprotocol/tasks` extension (SEP-2663) and serving the `modern_task` / `modern_input_task` tools. Connect with **Protocol Era = Modern**: the **Tasks** tab is now gated on the negotiated extension (not `capabilities.tasks`). Run `modern_task` as a task — the `tools/call` returns a `CreateTaskResult` (`resultType: "task"`, visible in the Protocol/Network tabs), the client polls **`tasks/get`** (no `tasks/list`), and the completed task inlines its result (no blocking `tasks/result`). Run `modern_input_task` and the task moves to `input_required`, surfacing an embedded elicitation through the pending-request modal; answering it sends **`tasks/update`** with the `inputResponses`, and the next poll completes. SDK v2 removed all tasks support **and** era-gates the `tasks/*` spec methods out of the modern era on both sides — so the Inspector drives the extension itself (the `resultType: "task"` frame is rewritten at the transport into a `CallToolResult` carrying the handle; `tasks/get`/`update`/`cancel` ride a raw-wire request channel with the full modern envelope), and the test server serves `tasks/*` from an Express interceptor ahead of the SDK handler (the SDK's modern leg would answer them `-32601`). The Tasks tab's **Refresh** re-polls the handles already known to the client (modern has no server-side task list).
## Building
```bash

View file

@ -64,6 +64,14 @@ vi.mock("@inspector/core/mcp/index.js", async (importOriginal) => {
.fn()
.mockResolvedValue({ success: true, result: { acts: [] } });
cancelRequestorTask = vi.fn().mockResolvedValue(undefined);
isTasksExtensionNegotiated = vi.fn().mockReturnValue(false);
getRequestorTask = vi.fn().mockResolvedValue({
taskId: "t",
status: "working",
ttl: null,
createdAt: "",
lastUpdatedAt: "",
});
cancelToolCall = vi.fn().mockReturnValue(true);
getPrompt = vi.fn().mockResolvedValue({ result: { messages: [] } });
readResource = vi
@ -1107,6 +1115,55 @@ describe("App task wiring", () => {
expect(client.cancelRequestorTask).toHaveBeenCalledWith("task-42");
});
it("Cancel on a task-input-required elicitation cancels the task, not answers it (#1631)", async () => {
// The user-facing half of the cancelable-loop fix: clicking Cancel on a
// MODERN task's input_required modal must cancel the underlying task (so the
// poll unblocks) rather than send an { action: "cancel" } answer that a
// non-advancing server would just re-prompt on.
const user = userEvent.setup();
renderWithMantine(<App />);
await user.click(screen.getByText("connect"));
await waitFor(() => expect(clientInstances).toHaveLength(1));
const client = clientInstances[0] as unknown as {
cancelRequestorTask: ReturnType<typeof vi.fn>;
};
const respond = vi.fn().mockResolvedValue(undefined);
const elicitation = {
id: "elicitation-1",
origin: "task-input-required",
taskId: "task-77",
request: {
params: {
message: "Approve this task before it continues?",
requestedSchema: {
type: "object",
properties: { approved: { type: "boolean", title: "Approved" } },
},
},
},
respond,
};
act(() => {
clientInstances[0].dispatchEvent(
new CustomEvent("pendingElicitationsChange", { detail: [elicitation] }),
);
});
await waitFor(() =>
expect(
screen.getByText(/Approve this task before it continues/),
).toBeInTheDocument(),
);
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(client.cancelRequestorTask).toHaveBeenCalledWith("task-77");
// The task is cancelled instead of answering the request.
expect(respond).not.toHaveBeenCalled();
});
it("does not re-cancel on a rapid second Cancel click", async () => {
const user = userEvent.setup();
renderWithMantine(<App />);

View file

@ -2823,8 +2823,16 @@ function App() {
// error). The created task shows up on the Tasks screen via the
// `requestorTaskUpdated` events callToolStream dispatches, and its live
// status/progress surface as toasts + progress bar.
// Legacy servers advertise task tool calls via
// `tasks.requests.tools.call`. Modern servers (SEP-2663) instead negotiate
// the `io.modelcontextprotocol/tasks` extension and are server-directed:
// task creation is decided per-request by the server, so declaring the
// extension on the call (which the task path does) is what makes a returned
// task handle legal ("unsolicited handles"). Either era routes the flagged
// call through the streaming task pipeline.
const serverSupportsTaskToolCalls =
!!capabilities?.tasks?.requests?.tools?.call;
!!capabilities?.tasks?.requests?.tools?.call ||
inspectorClient.isTasksExtensionNegotiated();
const asTask =
serverSupportsTaskToolCalls &&
(runAsTask || tool.execution?.taskSupport === "required");
@ -3999,9 +4007,25 @@ function App() {
const onElicitationRespond = useCallback(
(result: ElicitResult) => {
void pendingElicitations[0]?.respond(result);
const pending = pendingElicitations[0];
if (!pending) return;
// "Cancel" on a MODERN task's input_required request means "give up on the
// task" — not "send a cancel answer" (which a non-advancing server would
// just re-prompt on). Cancel the underlying task instead; that aborts the
// pending request, closes this modal, and lets the poll settle as
// cancelled (#1631). Submit/Decline still answer the task normally.
if (
result.action === "cancel" &&
pending.origin === "task-input-required" &&
pending.taskId &&
inspectorClient
) {
void inspectorClient.cancelRequestorTask(pending.taskId);
return;
}
void pending.respond(result);
},
[pendingElicitations],
[pendingElicitations, inspectorClient],
);
const handleStepUpAuthorize = async () => {
@ -4256,7 +4280,8 @@ function App() {
highlightedServerIds={highlightedServerIds}
onClearHighlight={clearHighlight}
serverSupportsTaskToolCalls={
!!capabilities?.tasks?.requests?.tools?.call
!!capabilities?.tasks?.requests?.tools?.call ||
(inspectorClient?.isTasksExtensionNegotiated() ?? false)
}
onToolsUiChange={onToolsUiChange}
onCallTool={(name, args, runAsTask) => {

View file

@ -13,6 +13,10 @@ export const InputRequired: Story = {
args: { origin: "input-required" },
};
export const TaskInputRequired: Story = {
args: { origin: "task-input-required" },
};
export const ServerRequest: Story = {
args: { origin: "server-request" },
};

View file

@ -9,6 +9,16 @@ describe("MrtrOriginNote", () => {
expect(screen.getByText(/sent back as a retry/i)).toBeInTheDocument();
});
it("renders the tasks/update note for a modern task input-required round (#1631)", () => {
renderWithMantine(<MrtrOriginNote origin="task-input-required" />);
expect(screen.getByText("input_required")).toBeInTheDocument();
expect(
screen.getByText(/submitted via a tasks\/update request/i),
).toBeInTheDocument();
// The task note must NOT claim the answer is a retry (that's the MRTR case).
expect(screen.queryByText(/sent back as a retry/i)).not.toBeInTheDocument();
});
it("renders nothing for a legacy server request", () => {
renderWithMantine(<MrtrOriginNote origin="server-request" />);
expect(screen.queryByText("input_required")).not.toBeInTheDocument();

View file

@ -6,7 +6,8 @@ export interface MrtrOriginNoteProps {
* How the pending request reached the Inspector. `"server-request"` (the
* default) is a legacy server→client request and renders nothing, keeping the
* panel visually identical to its pre-MRTR form. `"input-required"` is a
* modern (2026-07-28) MRTR round and renders the era-accurate note.
* modern (2026-07-28) MRTR round and `"task-input-required"` is a modern task
* (SEP-2663) round — each renders its own era-accurate note.
*/
origin?: PendingRequestOrigin;
}
@ -22,27 +23,37 @@ const NoteText = Text.withProps({
c: "dimmed",
});
// The two modern origins differ in HOW the answer is delivered: an MRTR round
// retries the original call with the answer (SEP-2322); a task round submits it
// via a separate `tasks/update` request (SEP-2663). The note is accurate to each
// so a user debugging the wire isn't told to expect the wrong follow-up frame.
const NOTE_BY_ORIGIN: Partial<Record<PendingRequestOrigin, string>> = {
"input-required":
"The server returned input_required; your answer is sent back as a retry of the original request (MRTR).",
"task-input-required":
"This task reached input_required; your answer is submitted via a tasks/update request (SEP-2663), not a retry.",
};
/**
* Era-accurate note for a pending sampling/elicitation request. On a modern
* MRTR round (`origin: "input-required"`, SEP-2322) the request was embedded in
* a tool-call/prompt/resource `input_required` result rather than sent as a
* server→client JSON-RPC request, and the user's answer is echoed back to the
* server as a retry of the original call. Legacy requests
* (`origin: "server-request"`) render nothing so their panels are unchanged.
* Era-accurate note for a pending sampling/elicitation request. A modern MRTR
* round (`origin: "input-required"`, SEP-2322) embeds the request in a
* tool-call/prompt/resource `input_required` result and retries the original
* call with the answer; a modern task round (`origin: "task-input-required"`,
* SEP-2663) surfaces it from the task's `inputRequests` and submits the answer
* via `tasks/update`. Legacy requests (`origin: "server-request"`) render
* nothing so their panels are unchanged.
*/
export function MrtrOriginNote({
origin = "server-request",
}: MrtrOriginNoteProps) {
if (origin !== "input-required") return null;
const note = NOTE_BY_ORIGIN[origin];
if (!note) return null;
return (
<NoteRow>
<Badge variant="outline" color="blue">
input_required
</Badge>
<NoteText>
The server returned input_required; your answer is sent back as a retry
of the original request (MRTR).
</NoteText>
<NoteText>{note}</NoteText>
</NoteRow>
);
}

View file

@ -90,3 +90,10 @@ export const Cancelled: Story = {
export const Collapsed: Story = {
args: { task: workingTask, isListExpanded: false },
};
// Compact monitoring-sidebar variant: the task id moves to its own line below
// the header so the status badge and Cancel Task control stay on the first row
// in the narrow column (#1631).
export const Embedded: Story = {
args: { task: workingTask, embedded: true },
};

View file

@ -51,6 +51,25 @@ describe("TaskCard", () => {
expect(screen.getByText("300000ms")).toBeInTheDocument();
});
it("still renders the task id (on its own line) in the embedded variant (#1631)", () => {
// The embedded sidebar moves the id out of the header so the badge/Cancel
// don't wrap, but the id must remain visible (not removed entirely).
renderWithMantine(
<TaskCard
task={workingTask}
isListExpanded={false}
onCancel={vi.fn()}
embedded
/>,
);
expect(screen.getByText("ID: task-working-1")).toBeInTheDocument();
// The status badge and Cancel Task control are still present on the header.
expect(screen.getByText("working")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Cancel Task" }),
).toBeInTheDocument();
});
it("renders the Cancel Task button when status is working", () => {
renderWithMantine(
<TaskCard task={workingTask} isListExpanded={false} onCancel={vi.fn()} />,

View file

@ -24,6 +24,13 @@ export interface TaskCardProps {
progress?: TaskProgress;
isListExpanded: boolean;
onCancel: () => void;
/**
* Compact variant for the narrow monitoring sidebar. Moves the long task ID
* out of the header onto its own line below it (truncated) so the header
* doesn't wrap the status badge / Cancel Task control onto a second row. The
* full-width Tasks screen keeps the ID inline in the header.
*/
embedded?: boolean;
}
const TaskContainer = Card.withProps({
@ -80,6 +87,9 @@ const HeaderLeftGroup = Group.withProps({
const HeaderRightGroup = Group.withProps({
gap: "xs",
// Keep the Cancel Task control and the status badge together on the header's
// first row rather than letting the badge wrap beneath the button.
wrap: "nowrap",
});
const SectionTitle = Text.withProps({
@ -100,6 +110,7 @@ export function TaskCard({
progress,
isListExpanded,
onCancel,
embedded = false,
}: TaskCardProps) {
const { taskId, status, ttl, createdAt, lastUpdatedAt, statusMessage } = task;
const [isExpanded, setIsExpanded] = useState(isListExpanded);
@ -115,7 +126,11 @@ export function TaskCard({
<HeaderRow>
<HeaderLeftGroup>
<SectionTitle>Task Details</SectionTitle>
<TaskIdText>{formatTaskId(taskId)}</TaskIdText>
{/* Full-width screen: the id sits inline after the title. In the
narrow embedded sidebar it moves to its own line below (see
below) so it can't push the status badge / Cancel Task onto a
second row. */}
{!embedded && <TaskIdText>{formatTaskId(taskId)}</TaskIdText>}
</HeaderLeftGroup>
<HeaderRightGroup>
{isActive && (
@ -125,6 +140,10 @@ export function TaskCard({
</HeaderRightGroup>
</HeaderRow>
{embedded && (
<TaskIdText truncate="end">{formatTaskId(taskId)}</TaskIdText>
)}
<SummaryRow>
<DetailRow>
<Stack gap={2}>

View file

@ -135,6 +135,7 @@ export function TaskListPanel({
progress={progressByTaskId?.[task.taskId]}
isListExpanded={!compact}
onCancel={() => onCancel(task.taskId)}
embedded={embedded}
/>
))}
</>
@ -157,6 +158,7 @@ export function TaskListPanel({
progress={progressByTaskId?.[task.taskId]}
isListExpanded={!compact}
onCancel={() => onCancel(task.taskId)}
embedded={embedded}
/>
))}
</>

View file

@ -325,6 +325,42 @@ describe("ToolDetailPanel", () => {
expect(screen.queryByLabelText("Run as task")).not.toBeInTheDocument();
});
it("shows the toggle for a task-forbidden tool on a modern connection (#1631)", () => {
// On modern (SEP-2663) task creation is server-directed, so any tool can
// become a task — the toggle is offered regardless of per-tool taskSupport.
renderWithMantine(
<ToolDetailPanel
{...baseProps}
tool={toolWithSupport("forbidden")}
serverSupportsTaskToolCalls={true}
modernTasks={true}
runAsTask={false}
/>,
);
const toggle = screen.getByLabelText("Run as task");
expect(toggle).not.toBeChecked();
expect(toggle).not.toBeDisabled();
});
it("routes the user's runAsTask choice on a modern connection (#1631)", async () => {
const user = userEvent.setup();
const onExecute = vi.fn();
renderWithMantine(
<ToolDetailPanel
{...baseProps}
tool={toolWithSupport("forbidden")}
serverSupportsTaskToolCalls={true}
modernTasks={true}
runAsTask={true}
onExecute={onExecute}
/>,
);
// The toggle is checked (user's choice), and executing forwards true.
expect(screen.getByLabelText("Run as task")).toBeChecked();
await user.click(screen.getByRole("button", { name: "Execute Tool" }));
expect(onExecute).toHaveBeenCalledWith(true);
});
it("shows an unchecked, enabled toggle for an optional tool (off by default)", () => {
renderWithMantine(
<ToolDetailPanel

View file

@ -35,7 +35,15 @@ export interface ToolDetailPanelProps {
progress?: ToolProgress;
/** Whether the connected server advertises task-augmented tool calls. */
serverSupportsTaskToolCalls: boolean;
/** User's "Run as task" preference (only meaningful for `optional` tools). */
/**
* Modern (2026-07-28) connection with the `io.modelcontextprotocol/tasks`
* extension negotiated (SEP-2663). Task creation is server-directed there, so
* "Run as task" is offered for ANY tool (not just ones declaring per-tool
* `taskSupport`, which is the legacy mechanism). Defaults to false (legacy).
*/
modernTasks?: boolean;
/** User's "Run as task" preference (meaningful for `optional` tools and, on
* modern connections, any tool). */
runAsTask: boolean;
onRunAsTaskChange: (value: boolean) => void;
onFormChange: (values: Record<string, unknown>) => void;
@ -154,6 +162,7 @@ export function ToolDetailPanel({
isExecuting,
progress,
serverSupportsTaskToolCalls,
modernTasks = false,
runAsTask,
onRunAsTaskChange,
onFormChange,
@ -180,20 +189,28 @@ export function ToolDetailPanel({
// single expandable control (aria-expanded + aria-controls).
const descriptionRegionId = useId();
// Show the toggle only when the server supports task tool calls and the tool
// doesn't forbid them. `required` tools are forced on (checked + disabled);
// `optional` tools follow the user's `runAsTask` choice.
// Show the toggle when the server supports task tool calls and either the
// connection is modern (task creation is server-directed there, so any tool
// may become a task) or the tool doesn't forbid per-tool task support
// (legacy). `required` tools are forced on (checked + disabled); `optional`
// and (on modern) any tool follow the user's `runAsTask` choice.
//
// NOTE: on modern, a per-tool `taskSupport: "forbidden"` is DELIBERATELY
// ignored. Under SEP-2663 task creation is decided by the server per request,
// not declared per tool, so `taskSupport` (a legacy 2025-11-25 concept) does
// not gate the affordance — the server may return a task for any call. The
// toggle just declares intent to poll a returned handle.
const taskSupport = getTaskSupport(tool);
const showRunAsTask =
serverSupportsTaskToolCalls && taskSupport !== "forbidden";
// Gate the effective decision on `showRunAsTask` (which includes
// `serverSupportsTaskToolCalls`): a stale `runAsTask`/`required` value must
// not route through callToolStream when the toggle is hidden because the
// server doesn't advertise task tool calls. Per spec, a tool's taskSupport is
// only considered when the server advertises `tasks.requests.tools.call`.
serverSupportsTaskToolCalls && (modernTasks || taskSupport !== "forbidden");
// Gate the effective decision on `showRunAsTask`: a stale `runAsTask`/`required`
// value must not route through callToolStream when the toggle is hidden. On
// legacy, a tool's taskSupport is only considered when the server advertises
// `tasks.requests.tools.call`; on modern, the user's choice governs any tool.
const effectiveRunAsTask =
showRunAsTask &&
(taskSupport === "required" || (taskSupport === "optional" && runAsTask));
(taskSupport === "required" ||
((taskSupport === "optional" || modernTasks) && runAsTask));
return (
<PanelStack>

View file

@ -43,6 +43,9 @@ export interface ToolsScreenProps {
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). */
@ -133,6 +136,7 @@ export function ToolsScreen({
ui,
listChanged,
serverSupportsTaskToolCalls,
modernTasks = false,
onUiChange,
onRefreshList,
pagination,
@ -216,6 +220,7 @@ export function ToolsScreen({
isExecuting={isExecuting}
progress={callState?.progress}
serverSupportsTaskToolCalls={serverSupportsTaskToolCalls}
modernTasks={modernTasks}
runAsTask={ui.runAsTask}
onRunAsTaskChange={(value) =>
onUiChange({ ...ui, runAsTask: value })

View file

@ -38,6 +38,7 @@ import type {
} from "@inspector/core/mcp/types.js";
import { isTerminalStatus } from "@inspector/core/mcp/types.js";
import { isAppTool } from "@inspector/core/mcp/apps.js";
import { TASKS_EXTENSION_KEY } from "@inspector/core/mcp/modernTaskSchemas.js";
import { ViewHeader } from "../../groups/ViewHeader/ViewHeader";
import { VersionBadge } from "../../elements/VersionBadge/VersionBadge";
import { CopyrightBadge } from "../../elements/CopyrightBadge/CopyrightBadge";
@ -807,8 +808,11 @@ export function InspectorView({
// Logs → capabilities.logging
// Prompts → capabilities.prompts
// Resources → capabilities.resources
// Tasks → capabilities.tasks (the "run as task" affordance on the
// Tools screen separately keys off tasks.requests.tools.call)
// Tasks → capabilities.tasks (legacy) OR the
// io.modelcontextprotocol/tasks extension (modern, SEP-2663).
// The "run as task" affordance on the Tools screen separately
// keys off tasks.requests.tools.call (legacy) / the negotiated
// extension (modern).
// Apps → capabilities.tools (MCP Apps build on tools) AND at least one
// app tool — Apps is a filtered view of tools, not its own
// capability, so it keeps the content check; when app tools
@ -830,7 +834,12 @@ export function InspectorView({
const hasApps = hasTools && appTools.length > 0;
const hasPrompts = capabilities?.prompts !== undefined;
const hasResources = capabilities?.resources !== undefined;
const hasTasks = capabilities?.tasks !== undefined;
// Legacy servers gate Tasks on `capabilities.tasks`; modern servers
// (SEP-2663) advertise the `io.modelcontextprotocol/tasks` extension in
// `server/discover` instead, so gate on either being present.
const hasTasks =
capabilities?.tasks !== undefined ||
capabilities?.extensions?.[TASKS_EXTENSION_KEY] !== undefined;
const hasLogging = capabilities?.logging !== undefined;
return ALL_TABS.filter((t) => {
if (t === NETWORK_TAB && isStdio) return false;
@ -1314,6 +1323,12 @@ export function InspectorView({
ui={toolsUi}
listChanged={toolsListChanged}
serverSupportsTaskToolCalls={serverSupportsTaskToolCalls}
modernTasks={
protocolEra === "modern" &&
initializeResult?.capabilities?.extensions?.[
TASKS_EXTENSION_KEY
] !== undefined
}
onUiChange={onToolsUiChange}
onRefreshList={onRefreshTools}
pagination={toolsPagination}

View file

@ -0,0 +1,159 @@
import { describe, it, expect, vi } from "vitest";
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
import { ModernGetTaskResultSchema } from "@inspector/core/mcp/modernTaskSchemas.js";
/**
* Unit coverage for the raw-wire request channel (#1631) that drives the modern
* tasks/* methods the SDK v2 era gate refuses to send. Exercised directly (with
* a fake transport) so the defensive branches — transport-null guard, send
* rejection, timeout, error response, and disconnect cleanup — are deterministic
* rather than dependent on server timing.
*/
describe("InspectorClient raw-wire channel (#1631)", () => {
function makeClient(): InspectorClient {
return new InspectorClient(
{ type: "stdio", command: "noop", args: [] },
// environment.transport is only used on connect(); these tests never
// connect, they poke the private raw-wire methods directly.
{ environment: { transport: () => ({}) as never } },
);
}
interface RawWireInternals {
transport: { send: (m: unknown) => Promise<void> } | null;
requestTimeout?: number;
rawWireRequest: (
method: string,
params: Record<string, unknown>,
schema: { parse: (v: unknown) => unknown },
) => Promise<unknown>;
consumeRawWireResponse: (message: unknown) => boolean;
rejectPendingRawWireRequests: (reason: string) => void;
}
function internals(client: InspectorClient): RawWireInternals {
return client as unknown as RawWireInternals;
}
it("throws when there is no transport", async () => {
const client = makeClient();
internals(client).transport = null;
await expect(
internals(client).rawWireRequest(
"tasks/get",
{},
ModernGetTaskResultSchema,
),
).rejects.toThrow(/not connected/i);
});
it("resolves when a matching response is consumed", async () => {
const client = makeClient();
let sent: { id: string } | undefined;
internals(client).transport = {
send: vi.fn(async (m: unknown) => {
sent = m as { id: string };
}),
};
const promise = internals(client).rawWireRequest(
"tasks/get",
{ taskId: "x" },
ModernGetTaskResultSchema,
);
// Let the send microtask register the pending entry.
await Promise.resolve();
expect(sent?.id).toMatch(/^inspector-ext-/);
const consumed = internals(client).consumeRawWireResponse({
id: sent!.id,
result: {
taskId: "x",
status: "completed",
createdAt: "a",
lastUpdatedAt: "b",
ttlMs: null,
result: { content: [] },
},
});
expect(consumed).toBe(true);
const result = (await promise) as { taskId: string };
expect(result.taskId).toBe("x");
});
it("ignores a response id it does not own", () => {
const client = makeClient();
expect(
internals(client).consumeRawWireResponse({ id: 42, result: {} }),
).toBe(false);
});
it("rejects when the response is an error", async () => {
const client = makeClient();
let sent: { id: string } | undefined;
internals(client).transport = {
send: vi.fn(async (m: unknown) => {
sent = m as { id: string };
}),
};
const promise = internals(client).rawWireRequest(
"tasks/cancel",
{ taskId: "x" },
ModernGetTaskResultSchema,
);
await Promise.resolve();
internals(client).consumeRawWireResponse({
id: sent!.id,
error: { code: -32602, message: "Unknown taskId" },
});
await expect(promise).rejects.toThrow(/Unknown taskId/);
});
it("rejects when the transport send fails", async () => {
const client = makeClient();
internals(client).transport = {
send: vi.fn().mockRejectedValue(new Error("socket closed")),
};
await expect(
internals(client).rawWireRequest(
"tasks/get",
{},
ModernGetTaskResultSchema,
),
).rejects.toThrow(/socket closed/);
});
it("rejects on timeout when no response arrives", async () => {
vi.useFakeTimers();
try {
const client = makeClient();
internals(client).requestTimeout = 10;
internals(client).transport = {
send: vi.fn().mockResolvedValue(undefined),
};
const promise = internals(client).rawWireRequest(
"tasks/get",
{},
ModernGetTaskResultSchema,
);
const assertion = expect(promise).rejects.toThrow(/timed out/);
await vi.advanceTimersByTimeAsync(20);
await assertion;
} finally {
vi.useRealTimers();
}
});
it("rejects all pending requests on teardown", async () => {
const client = makeClient();
internals(client).transport = {
send: vi.fn().mockResolvedValue(undefined),
};
const promise = internals(client).rawWireRequest(
"tasks/get",
{},
ModernGetTaskResultSchema,
);
await Promise.resolve();
internals(client).rejectPendingRawWireRequests("Disconnected");
await expect(promise).rejects.toThrow(/Disconnected/);
});
});

View file

@ -0,0 +1,136 @@
import { describe, it, expect } from "vitest";
import {
TASKS_EXTENSION_KEY,
MODERN_PROTOCOL_VERSION,
MODERN_TASK_HANDLE_META,
TASKS_EXTENSION_CLIENT_CAPABILITY,
ModernDetailedTaskSchema,
ModernGetTaskResultSchema,
ModernUpdateTaskResultSchema,
ModernCancelTaskResultSchema,
normalizeModernTask,
readInputRequests,
isModernCreateTaskResult,
} from "@inspector/core/mcp/modernTaskSchemas.js";
describe("modernTaskSchemas (#1631)", () => {
const baseTask = {
taskId: "abc",
status: "working" as const,
createdAt: "2026-07-20T00:00:00Z",
lastUpdatedAt: "2026-07-20T00:00:01Z",
};
describe("constants", () => {
it("exposes the SEP-2663 identifiers", () => {
expect(TASKS_EXTENSION_KEY).toBe("io.modelcontextprotocol/tasks");
expect(MODERN_PROTOCOL_VERSION).toBe("2026-07-28");
expect(MODERN_TASK_HANDLE_META).toContain("modernTaskHandle");
expect(
TASKS_EXTENSION_CLIENT_CAPABILITY.extensions[TASKS_EXTENSION_KEY],
).toEqual({});
});
});
describe("ModernDetailedTaskSchema", () => {
it("parses a working task and passes unknown fields through (loose)", () => {
const parsed = ModernDetailedTaskSchema.parse({
...baseTask,
ttlMs: 60000,
pollIntervalMs: 500,
somethingNew: "kept",
});
expect(parsed.taskId).toBe("abc");
expect((parsed as Record<string, unknown>).somethingNew).toBe("kept");
});
it("accepts a null ttlMs and inline result/error/inputRequests", () => {
const completed = ModernGetTaskResultSchema.parse({
...baseTask,
status: "completed",
ttlMs: null,
result: { content: [{ type: "text", text: "done" }] },
});
expect(completed.result).toBeDefined();
const failed = ModernDetailedTaskSchema.parse({
...baseTask,
status: "failed",
error: { code: -1, message: "boom" },
});
expect(failed.error).toBeDefined();
});
it("rejects a task missing required identity fields", () => {
expect(() =>
ModernDetailedTaskSchema.parse({ status: "working" }),
).toThrow();
});
it("accepts empty update/cancel acks", () => {
expect(ModernUpdateTaskResultSchema.parse({})).toEqual({});
expect(
ModernCancelTaskResultSchema.parse({ resultType: "complete" }),
).toBeDefined();
});
});
describe("normalizeModernTask", () => {
it("maps ttlMs → ttl and pollIntervalMs → pollInterval", () => {
const task = normalizeModernTask({
...baseTask,
ttlMs: 60000,
pollIntervalMs: 250,
});
expect(task.ttl).toBe(60000);
expect((task as { pollInterval?: number }).pollInterval).toBe(250);
});
it("defaults ttl to null and omits pollInterval when absent", () => {
const task = normalizeModernTask({ ...baseTask });
expect(task.ttl).toBeNull();
expect((task as { pollInterval?: number }).pollInterval).toBeUndefined();
});
it("carries the status-specific members structurally", () => {
const task = normalizeModernTask({
...baseTask,
status: "completed",
ttlMs: null,
result: { content: [] },
});
expect((task as { result?: unknown }).result).toEqual({ content: [] });
});
});
describe("readInputRequests", () => {
it("returns the inputRequests map when present", () => {
const requests = { confirm: { method: "elicitation/create" } };
const out = readInputRequests({
...baseTask,
status: "input_required",
inputRequests: requests,
});
expect(out).toBe(requests);
});
it("returns undefined when absent", () => {
expect(readInputRequests({ ...baseTask })).toBeUndefined();
});
});
describe("isModernCreateTaskResult", () => {
it("is true only for a resultType:task frame with a taskId", () => {
expect(
isModernCreateTaskResult({ resultType: "task", taskId: "x" }),
).toBe(true);
});
it("is false for complete results, non-objects, and missing taskId", () => {
expect(isModernCreateTaskResult({ resultType: "complete" })).toBe(false);
expect(isModernCreateTaskResult({ resultType: "task" })).toBe(false);
expect(isModernCreateTaskResult({ content: [] })).toBe(false);
expect(isModernCreateTaskResult(null)).toBe(false);
expect(isModernCreateTaskResult("task")).toBe(false);
});
});
});

View file

@ -210,6 +210,68 @@ describe("ManagedRequestorTasksState", () => {
expect(next[0]!.status).toBe("cancelled");
});
it("keeps a cancelled task cancelled when a later completed update arrives (#1631)", async () => {
// Cancellation is a deliberate terminal decision: a server that completes the
// task anyway (cooperative cancel) or the in-flight call resolving must not
// flip it back to completed.
client.setStatus("connected");
client.queueTaskPages({ tasks: [task("t1", "working")] });
await state.refresh();
client.dispatchTypedEvent("taskCancelled", { taskId: "t1" });
expect(state.getTasks()[0]!.status).toBe("cancelled");
// A late server notification and a client-origin update, both "completed":
let changed = false;
state.addEventListener("tasksChange", () => {
changed = true;
});
client.dispatchTypedEvent("taskStatusChange", {
taskId: "t1",
task: task("t1", "completed"),
});
client.dispatchTypedEvent("requestorTaskUpdated", {
taskId: "t1",
task: task("t1", "completed"),
});
expect(changed).toBe(false);
expect(state.getTasks()[0]!.status).toBe("cancelled");
});
it("still applies a subsequent cancelled update for a cancelled task", async () => {
client.setStatus("connected");
client.queueTaskPages({ tasks: [task("t1", "working")] });
await state.refresh();
client.dispatchTypedEvent("taskCancelled", { taskId: "t1" });
// A cancelled-status update is not blocked (it agrees with the sticky state).
const changePromise = waitForChange(state);
client.dispatchTypedEvent("taskStatusChange", {
taskId: "t1",
task: { ...task("t1", "cancelled"), statusMessage: "stopped" },
});
const next = await changePromise;
expect(next[0]!.status).toBe("cancelled");
expect(next[0]!.statusMessage).toBe("stopped");
});
it("keeps a cancelled task cancelled across a legacy refresh that re-lists it completed (#1631)", async () => {
// A cooperative-cancel server may complete the task anyway and still return
// it as "completed" from tasks/list. A manual Refresh must not un-stick the
// user's cancel — the legacy refresh path pins it to "cancelled" too.
client.setStatus("connected");
client.queueTaskPages({ tasks: [task("t1", "working")] });
await state.refresh();
client.dispatchTypedEvent("taskCancelled", { taskId: "t1" });
expect(state.getTasks()[0]!.status).toBe("cancelled");
// Server now lists the same task as completed; refresh must keep it cancelled.
client.queueTaskPages({ tasks: [task("t1", "completed")] });
await state.refresh();
expect(state.getTasks()[0]!.status).toBe("cancelled");
});
it("taskCancelled is a no-op when the task is unknown", async () => {
client.setStatus("connected");
client.queueTaskPages({ tasks: [task("t1")] });

View file

@ -903,9 +903,10 @@ describe("InspectorClient coverage backfill", () => {
});
describe("constructor capability branches and createReceiverTask options", () => {
it("constructs with no advertised capabilities (clientOptions undefined branch)", async () => {
// sample:false + elicit:false + no roots + no receiverTasks → the
// capabilities object is empty, so clientOptions is passed as undefined.
it("advertises only the tasks extension when no other capabilities are set", async () => {
// sample:false + elicit:false + no roots + no receiverTasks → the only
// advertised capability is the always-on Tasks extension (#1631), so
// `capabilities` is non-empty and is always attached.
client = new InspectorClient(
{
type: "stdio",
@ -919,7 +920,10 @@ describe("InspectorClient coverage backfill", () => {
},
);
const caps = client.getClientCapabilities();
expect(Object.keys(caps)).toHaveLength(0);
expect(caps.sampling).toBeUndefined();
expect(caps.elicitation).toBeUndefined();
expect(caps.roots).toBeUndefined();
expect(caps.extensions?.["io.modelcontextprotocol/tasks"]).toBeDefined();
await client.connect();
expect(client.getStatus()).toBe("connected");
});

View file

@ -0,0 +1,380 @@
import { describe, it, expect, afterEach, afterAll } from "vitest";
import * as z from "zod/v4";
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
import { createTransportNode } from "@inspector/core/mcp/node/transport.js";
import { eraToVersionNegotiation } from "@inspector/core/mcp/types.js";
import { ManagedRequestorTasksState } from "@inspector/core/mcp/state/managedRequestorTasksState.js";
import {
createTestServerHttp,
type TestServerHttp,
createTestServerInfo,
} from "@modelcontextprotocol/inspector-test-server";
import type { ServerConfig } from "@modelcontextprotocol/inspector-test-server";
import { getTaskServerConfig } from "@modelcontextprotocol/inspector-test-server";
import type { ContentBlock } from "@modelcontextprotocol/client";
import type { MessageEntry } from "@inspector/core/mcp/types.js";
/**
* Live coverage of the Tasks era fork (#1631). Modern (2026-07-28) servers serve
* the `io.modelcontextprotocol/tasks` extension (SEP-2663): a task-augmented
* `tools/call` returns a `CreateTaskResult`, the client polls `tasks/get`
* (no `tasks/list`, no blocking `tasks/result`), an `input_required` task
* surfaces an embedded elicitation answered via `tasks/update`, and a completed
* task inlines its result. Legacy servers keep the `capabilities.tasks` /
* `tasks/list` flow. Both are driven against a real server over a real transport.
*/
describe("tasks era fork (#1631)", () => {
let client: InspectorClient | null = null;
// One server per era, shared across the block's tests (started lazily, stopped
// in afterAll). Starting a fresh Express server per test made connection
// negotiation flaky under the heavy concurrent coverage run; task ids are
// unique per create so sharing state is harmless.
let modernServer: TestServerHttp | null = null;
let legacyServer: TestServerHttp | null = null;
afterEach(async () => {
if (client) {
try {
await client.disconnect();
} catch {
// ignore
}
client = null;
}
});
afterAll(async () => {
for (const s of [modernServer, legacyServer]) {
if (s) {
try {
await s.stop();
} catch {
// ignore
}
}
}
modernServer = null;
legacyServer = null;
});
async function startModernTasksServer(): Promise<TestServerHttp> {
if (modernServer) return modernServer;
const started = createTestServerHttp({
serverInfo: createTestServerInfo("tasks-modern-test", "1.0.0"),
tasksExtension: true,
// A plain tool alongside the task tools, so a modern tools/call that does
// NOT create a task exercises the synchronous-result path.
tools: [
{
name: "plain_echo",
description: "Echo the message without creating a task",
inputSchema: { message: z.string().optional() },
handler: async (args: Record<string, unknown>) => ({
content: [
{ type: "text" as const, text: `echo:${args.message ?? ""}` },
],
}),
},
],
modern: {},
});
await started.start();
modernServer = started;
return started;
}
async function startLegacyTasksServer(): Promise<TestServerHttp> {
if (legacyServer) return legacyServer;
const config = getTaskServerConfig() as ServerConfig;
const started = createTestServerHttp({
...config,
serverInfo: createTestServerInfo("tasks-legacy-test", "1.0.0"),
});
await started.start();
legacyServer = started;
return started;
}
async function connect(
url: string,
era: "legacy" | "modern",
): Promise<{ connected: InspectorClient; messages: MessageEntry[] }> {
const connected = new InspectorClient(
{ type: "streamable-http", url },
{
environment: { transport: createTransportNode },
versionNegotiation: eraToVersionNegotiation(era),
},
);
const messages: MessageEntry[] = [];
connected.addEventListener("message", (event) => {
messages.push(event.detail);
});
await connected.connect();
client = connected;
return { connected, messages };
}
function methodsSent(messages: MessageEntry[]): string[] {
return messages
.filter((m) => m.direction === "request")
.map((m) => ("method" in m.message ? m.message.method : ""))
.filter(Boolean);
}
function firstText(content: ContentBlock[] | undefined): string {
const block = content?.[0];
return block && "text" in block ? block.text : "";
}
describe("modern era", () => {
it("negotiates the tasks extension and gates on it", async () => {
const started = await startModernTasksServer();
const { connected } = await connect(started.url, "modern");
expect(connected.getProtocolEra()).toBe("modern");
expect(connected.isTasksExtensionNegotiated()).toBe(true);
expect(
connected.getCapabilities()?.extensions?.[
"io.modelcontextprotocol/tasks"
],
).toBeDefined();
});
it("creates a task, polls tasks/get (no tasks/list or tasks/result), and inlines the completed result", async () => {
const started = await startModernTasksServer();
const { connected, messages } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "modern_task");
expect(tool).toBeDefined();
messages.length = 0;
const invocation = await connected.callToolStream(tool!, {
message: "hi",
});
expect(invocation.success).toBe(true);
expect(firstText(invocation.result?.content as ContentBlock[])).toContain(
"completed",
);
const methods = methodsSent(messages);
expect(methods).toContain("tasks/get");
expect(methods).not.toContain("tasks/list");
expect(methods).not.toContain("tasks/result");
// Every task-eligible request declares the extension per-request (SEP-2663).
const call = messages.find(
(m) =>
m.direction === "request" &&
"method" in m.message &&
m.message.method === "tools/call",
);
const meta = (
call?.message as { params?: { _meta?: Record<string, unknown> } }
).params?._meta;
expect(
(
meta?.["io.modelcontextprotocol/clientCapabilities"] as {
extensions?: Record<string, unknown>;
}
)?.extensions,
).toHaveProperty("io.modelcontextprotocol/tasks");
});
it("answers an input_required task via tasks/update, then completes", async () => {
const started = await startModernTasksServer();
const { connected, messages } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "modern_input_task");
expect(tool).toBeDefined();
let pausedAtPendingUi = false;
connected.addEventListener("newPendingElicitation", (event) => {
pausedAtPendingUi = true;
// The task round is tagged distinctly from an MRTR round so the UI can
// show the accurate "answer via tasks/update" note (#1631 follow-up).
expect(event.detail.origin).toBe("task-input-required");
void event.detail.respond({
action: "accept",
content: { approved: true },
});
});
messages.length = 0;
const invocation = await connected.callToolStream(tool!, {});
expect(invocation.success).toBe(true);
expect(pausedAtPendingUi).toBe(true);
expect(firstText(invocation.result?.content as ContentBlock[])).toContain(
"approved",
);
const methods = methodsSent(messages);
expect(methods).toContain("tasks/update");
});
it("auto-polls an unsolicited task handle on the ordinary callTool path (#1631 follow-up)", async () => {
const started = await startModernTasksServer();
const { connected, messages } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "modern_task")!;
// The ordinary (non-run-as-task) path: the server answers with a task
// handle; callTool must poll it to termination and resolve to the task's
// final inline result — NOT the transport's "task created" placeholder.
const taskUpdates: string[] = [];
connected.addEventListener("requestorTaskUpdated", (event) => {
taskUpdates.push(event.detail.taskId);
});
messages.length = 0;
const invocation = await connected.callTool(tool, {
message: "unsolicited",
});
expect(invocation.success).toBe(true);
expect(firstText(invocation.result?.content as ContentBlock[])).toContain(
"completed",
);
expect(taskUpdates.length).toBeGreaterThan(0);
expect(methodsSent(messages)).toContain("tasks/get");
});
it("answers an input_required unsolicited handle via tasks/update on the ordinary path (#1631 follow-up)", async () => {
const started = await startModernTasksServer();
const { connected, messages } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "modern_input_task")!;
connected.addEventListener("newPendingElicitation", (event) => {
expect(event.detail.origin).toBe("task-input-required");
void event.detail.respond({
action: "accept",
content: { approved: true },
});
});
messages.length = 0;
const invocation = await connected.callTool(tool, {});
expect(invocation.success).toBe(true);
expect(firstText(invocation.result?.content as ContentBlock[])).toContain(
"approved",
);
expect(methodsSent(messages)).toContain("tasks/update");
});
it("bounds a never-completing input_required task with the round cap (#1631 review)", async () => {
const started = await startModernTasksServer();
const { connected } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "modern_loop_task")!;
// The server never advances past input_required, so the client re-prompts
// each poll; auto-answer, and the round cap must eventually abort instead
// of looping forever.
connected.addEventListener("newPendingElicitation", (event) => {
void event.detail.respond({
action: "accept",
content: { approved: true },
});
});
await expect(connected.callToolStream(tool, {})).rejects.toThrow(
/exceeded \d+ input_required rounds/,
);
});
it("cancels a task paused at input_required — aborts the pending elicitation and unblocks the poll (#1631)", async () => {
const started = await startModernTasksServer();
const { connected, messages } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
// A never-completing task: without the cancel-aborts-input fix, cancelling
// wouldn't unblock the poll — the modal would re-prompt forever.
const tool = tools.find((t) => t.name === "modern_loop_task")!;
let capturedTaskId: string | undefined;
let cancelledEventTaskId: string | undefined;
let cancelPromise: Promise<void> | undefined;
connected.addEventListener("requestorTaskUpdated", (event) => {
capturedTaskId = event.detail.taskId;
});
connected.addEventListener("taskCancelled", (event) => {
cancelledEventTaskId = event.detail.taskId;
});
connected.addEventListener("newPendingElicitation", () => {
// Cancel the underlying task instead of answering — this must abort the
// pending elicitation (close the modal) and let the poll settle.
if (capturedTaskId && !cancelPromise) {
cancelPromise = connected
.cancelRequestorTask(capturedTaskId)
.catch(() => {});
}
});
messages.length = 0;
// The poll must unblock and the call settle (reject) — not hang or loop.
await expect(connected.callToolStream(tool, {})).rejects.toThrow();
// Let tasks/cancel finish (it dispatches taskCancelled on completion).
await cancelPromise;
expect(methodsSent(messages)).toContain("tasks/cancel");
expect(cancelledEventTaskId).toBe(capturedTaskId);
// The pending elicitation was aborted, not left dangling behind a modal.
expect(connected.getPendingElicitations()).toHaveLength(0);
});
it("passes a synchronous (non-task) tool result straight through", async () => {
const started = await startModernTasksServer();
const { connected } = await connect(started.url, "modern");
const { tools } = await connected.listTools();
const plain = tools.find((t) => t.name === "plain_echo");
expect(plain).toBeDefined();
const invocation = await connected.callToolStream(plain!, {
message: "hi",
});
expect(invocation.success).toBe(true);
expect(firstText(invocation.result?.content as ContentBlock[])).toContain(
"echo:hi",
);
});
it("rejects a tasks/get for an unknown task id (raw-wire error path)", async () => {
const started = await startModernTasksServer();
const { connected } = await connect(started.url, "modern");
await expect(
connected.getRequestorTask("does-not-exist"),
).rejects.toThrow();
});
it("modern store refresh re-polls known tasks (no tasks/list)", async () => {
const started = await startModernTasksServer();
const { connected, messages } = await connect(started.url, "modern");
const store = new ManagedRequestorTasksState(connected);
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "modern_task")!;
// Running the task seeds the store via requestorTaskUpdated events.
await connected.callToolStream(tool, { message: "x" });
expect(store.getTasks().length).toBeGreaterThan(0);
messages.length = 0;
await store.refresh();
const methods = methodsSent(messages);
// Refresh re-polls with tasks/get; it never calls tasks/list on modern.
expect(methods).not.toContain("tasks/list");
store.destroy();
});
});
describe("legacy era", () => {
it("does not negotiate the extension and keeps the tasks/list flow", async () => {
const started = await startLegacyTasksServer();
const { connected, messages } = await connect(started.url, "legacy");
expect(connected.isTasksExtensionNegotiated()).toBe(false);
expect(connected.getCapabilities()?.tasks).toBeDefined();
const store = new ManagedRequestorTasksState(connected);
messages.length = 0;
await store.refresh();
expect(methodsSent(messages)).toContain("tasks/list");
store.destroy();
});
});
});

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