inspector/core/mcp/state/managedRequestorTasksState.ts
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

246 lines
9.9 KiB
TypeScript

/**
* ManagedRequestorTasksState: holds full requestor task list, syncs on
* tasksListChanged. Subscribes to taskStatusChange (server) and
* requestorTaskUpdated (client) to merge per-task updates.
*
* Ported from v1.5/main. v2 substitutes `InspectorClientProtocol` for the
* concrete `InspectorClient` since the runtime class is not yet ported.
*/
import type { InspectorClientProtocol } from "../inspectorClientProtocol.js";
import type { Task } from "@modelcontextprotocol/client";
import { isTerminalStatus } from "../types.js";
import type { InspectorClientEventMap } from "../inspectorClientEventTarget.js";
import {
TypedEventTarget,
type TypedEventGeneric,
} from "../typedEventTarget.js";
import { mergeTaskIntoList } from "./mergeTaskIntoList.js";
const MAX_PAGES = 100;
// Terminal task states — a task in one of these can no longer change, so
// "Clear Completed" targets exactly these.
const TERMINAL_STATUSES: ReadonlySet<Task["status"]> = new Set([
"completed",
"failed",
"cancelled",
]);
export interface ManagedRequestorTasksStateEventMap {
tasksChange: Task[];
}
/**
* State manager that keeps the full requestor task list in sync with the
* server. Subscribes to connect, tasksListChanged, statusChange,
* taskStatusChange (server), requestorTaskUpdated (client), and taskCancelled.
*/
export class ManagedRequestorTasksState extends TypedEventTarget<ManagedRequestorTasksStateEventMap> {
private tasks: Task[] = [];
private client: InspectorClientProtocol | null = null;
private unsubscribe: (() => void) | null = null;
// Task ids the user dismissed via clearCompleted(). Sticky for the session:
// these are filtered out of refresh() results and ignored by the live-merge
// handlers so a late status update (or a server that still lists the task)
// can't resurrect a cleared task. Reset on disconnect / destroy.
private dismissedTaskIds = new Set<string>();
// Task ids the user cancelled via the Cancel Task control. Cancellation is a
// deliberate terminal decision, so it is sticky: a status update that arrives
// afterwards — e.g. a server that completes the task anyway (cancellation is
// cooperative) or the in-flight tool call resolving with a result — must not
// flip a cancelled task back to "completed". Reset on disconnect / destroy.
private cancelledTaskIds = new Set<string>();
constructor(client: InspectorClientProtocol) {
super();
this.client = client;
const onConnect = (): void => {
void this.refresh();
};
const onTasksListChanged = (): void => {
void this.refresh();
};
const onStatusChange = (): void => {
if (isTerminalStatus(this.client?.getStatus())) {
this.tasks = [];
this.dismissedTaskIds.clear();
this.cancelledTaskIds.clear();
this.dispatchTypedEvent("tasksChange", []);
}
};
// A status update is ignored when the task was dismissed (clearCompleted)
// or when the user cancelled it and the update isn't itself "cancelled" —
// the deliberate cancel wins over a late completed/working update.
const shouldIgnoreUpdate = (taskId: string, status: Task["status"]): boolean =>
this.dismissedTaskIds.has(taskId) ||
(this.cancelledTaskIds.has(taskId) && status !== "cancelled");
const onTaskStatusChange = (
e: TypedEventGeneric<InspectorClientEventMap, "taskStatusChange">,
): void => {
const { taskId, task } = e.detail;
if (shouldIgnoreUpdate(taskId, task.status)) return;
this.tasks = mergeTaskIntoList(this.tasks, taskId, task);
this.dispatchTypedEvent("tasksChange", this.tasks);
};
const onRequestorTaskUpdated = (
e: TypedEventGeneric<InspectorClientEventMap, "requestorTaskUpdated">,
): void => {
const { taskId, task } = e.detail;
if (shouldIgnoreUpdate(taskId, task.status)) return;
this.tasks = mergeTaskIntoList(this.tasks, taskId, task);
this.dispatchTypedEvent("tasksChange", this.tasks);
};
const onTaskCancelled = (
e: TypedEventGeneric<InspectorClientEventMap, "taskCancelled">,
): void => {
const { taskId } = e.detail;
if (this.dismissedTaskIds.has(taskId)) return;
// Remember the cancel so a later status update can't un-cancel it.
this.cancelledTaskIds.add(taskId);
const idx = this.tasks.findIndex((t) => t.taskId === taskId);
if (idx >= 0) {
const next = [...this.tasks];
const prev = next[idx]!;
next[idx] = { ...prev, status: "cancelled" as const };
this.tasks = next;
this.dispatchTypedEvent("tasksChange", this.tasks);
}
};
this.client.addEventListener("connect", onConnect);
this.client.addEventListener("tasksListChanged", onTasksListChanged);
this.client.addEventListener("statusChange", onStatusChange);
this.client.addEventListener("taskStatusChange", onTaskStatusChange);
this.client.addEventListener(
"requestorTaskUpdated",
onRequestorTaskUpdated,
);
this.client.addEventListener("taskCancelled", onTaskCancelled);
this.unsubscribe = () => {
if (this.client) {
this.client.removeEventListener("connect", onConnect);
this.client.removeEventListener("tasksListChanged", onTasksListChanged);
this.client.removeEventListener("statusChange", onStatusChange);
this.client.removeEventListener("taskStatusChange", onTaskStatusChange);
this.client.removeEventListener(
"requestorTaskUpdated",
onRequestorTaskUpdated,
);
this.client.removeEventListener("taskCancelled", onTaskCancelled);
}
this.client = null;
};
}
getTasks(): Task[] {
return [...this.tasks];
}
async refresh(): Promise<Task[]> {
const client = this.client;
if (!client || client.getStatus() !== "connected") {
return this.getTasks();
}
// Modern era (SEP-2663): the `io.modelcontextprotocol/tasks` extension has
// NO `tasks/list` — task handles are durable and client-held, arriving via
// task-augmented tool calls (server-directed `CreateTaskResult`) or
// unsolicited handles. "Refresh" therefore re-polls the tasks already known
// to this store via `tasks/get`; a task the server has since dropped (TTL)
// simply keeps its last-seen state. Gate on the extension being negotiated.
if (client.isTasksExtensionNegotiated()) {
return this.refreshModern(client);
}
// Legacy era: gate on the server's `tasks` capability — calling tasks/list
// against a server that doesn't advertise it returns -32601 "Method not
// found", which then surfaces in the console for every connect against any
// server that doesn't implement task tracking. Empty list is the right
// semantics for "this server doesn't support tasks."
if (!client.getCapabilities()?.tasks) {
this.tasks = [];
this.dispatchTypedEvent("tasksChange", this.tasks);
return this.getTasks();
}
this.tasks = [];
let cursor: string | undefined;
let pageCount = 0;
do {
const result = await client.listRequestorTasks(cursor);
// Filter out tasks the user dismissed via clearCompleted() so a server
// that still lists them (or an in-flight refresh) can't resurrect them.
// For a user-cancelled task, keep it but pin its status to "cancelled":
// cancellation is cooperative, so a server that completes and re-lists it
// as "completed" must not un-stick the cancel on a manual Refresh — same
// guarantee the live-merge handlers give via `cancelledTaskIds`.
const page = result.tasks
.filter((t) => !this.dismissedTaskIds.has(t.taskId))
.map((t) =>
this.cancelledTaskIds.has(t.taskId)
? { ...t, status: "cancelled" as const }
: t,
);
this.tasks = cursor ? [...this.tasks, ...page] : page;
cursor = result.nextCursor;
pageCount++;
if (pageCount >= MAX_PAGES) {
throw new Error(
`Maximum pagination limit (${MAX_PAGES} pages) reached while listing requestor tasks`,
);
}
} while (cursor);
this.dispatchTypedEvent("tasksChange", this.tasks);
return this.getTasks();
}
/**
* Modern refresh: re-poll each currently-known (non-dismissed) task via
* `getRequestorTask` (`tasks/get`). Each poll dispatches `requestorTaskUpdated`,
* which the live-merge handler folds back into `this.tasks` — so the list
* updates in place. A poll that errors (e.g. the task expired and the server
* returns "unknown taskId") is swallowed so one dead handle can't abort the
* whole refresh. No known tasks ⇒ a no-op refresh (the correct "no server
* list" semantics).
*/
private async refreshModern(client: InspectorClientProtocol): Promise<Task[]> {
const ids = this.tasks
.map((t) => t.taskId)
.filter((id) => !this.dismissedTaskIds.has(id));
for (const id of ids) {
try {
await client.getRequestorTask(id);
} catch {
// Ignore a single failed poll (expired / unknown task); keep the rest.
}
}
return this.getTasks();
}
/**
* Drop terminal-state tasks (completed / failed / cancelled) from the list.
* Their ids are remembered in `dismissedTaskIds` so they stay gone for the
* rest of the session — a subsequent refresh() or live update won't bring
* them back. No-op (and no event) when there's nothing terminal to clear.
*/
clearCompleted(): void {
const remaining: Task[] = [];
let dismissedAny = false;
for (const task of this.tasks) {
if (TERMINAL_STATUSES.has(task.status)) {
this.dismissedTaskIds.add(task.taskId);
dismissedAny = true;
} else {
remaining.push(task);
}
}
if (!dismissedAny) return;
this.tasks = remaining;
this.dispatchTypedEvent("tasksChange", this.tasks);
}
destroy(): void {
this.unsubscribe?.();
this.unsubscribe = null;
this.tasks = [];
this.dismissedTaskIds.clear();
this.cancelledTaskIds.clear();
}
}