inspector/core/mcp/modernTaskSchemas.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

132 lines
6.2 KiB
TypeScript

/**
* Modern (2026-07-28) task extension wire schemas — SEP-2663
* (`io.modelcontextprotocol/tasks`).
*
* SDK v2 removed all built-in tasks support: the `Task` / `GetTaskResultSchema`
* / `CreateTaskResultSchema` it still exports are the **deprecated 2025-11-25**
* vocabulary (`ttl` / `pollInterval`, blocking `tasks/result`, `tasks/list`).
* The redesigned extension is a different wire shape — `ttlMs` / `pollIntervalMs`,
* a polymorphic `DetailedTask` that inlines `result` / `error` / `inputRequests`
* by status, `tasks/get` polling, a new `tasks/update`, no `tasks/list`, and no
* blocking `tasks/result`. There is no SDK schema for it, so the Inspector drives
* modern `tasks/*` as raw requests with these explicit schemas (the "explicit-
* schema raw-request form" the SDK docs prescribe).
*
* Schemas are intentionally permissive (`looseObject`) so an unknown wire field
* (e.g. a future status-specific member) passes through rather than failing the
* parse — the Inspector is a debugging tool and should surface, not reject.
*/
import { z } from "zod/v4";
import type { InputRequests, Task } from "@modelcontextprotocol/client";
/** SEP-2133 extension identifier for the redesigned Tasks extension (SEP-2663). */
export const TASKS_EXTENSION_KEY = "io.modelcontextprotocol/tasks";
/** The modern protocol revision, used as the raw-request envelope's
* `protocolVersion` when the negotiated version isn't otherwise available. */
export const MODERN_PROTOCOL_VERSION = "2026-07-28";
/** The `_meta` value stamped on modern task-eligible requests to declare the
* client supports the tasks extension (per-request capability, SEP-2663). */
export const TASKS_EXTENSION_CLIENT_CAPABILITY = {
extensions: { [TASKS_EXTENSION_KEY]: {} },
} as const;
/**
* `_meta` key under which the transport-level rewriter stashes a modern task
* handle. SDK v2's codec rejects a `resultType: "task"` result outright (tasks
* were removed), so a task-creating `tools/call` response is rewritten to a
* benign `CallToolResult` carrying the real `DetailedTask` here, where the task
* poll driver reads it. See `MessageTrackingTransport`'s rewrite hook.
*/
export const MODERN_TASK_HANDLE_META =
"io.modelcontextprotocol/inspector/modernTaskHandle";
/** True when a decoded wire result is a modern `CreateTaskResult`
* (`resultType: "task"`) — the frame the SDK codec cannot handle. */
export function isModernCreateTaskResult(result: unknown): boolean {
return (
typeof result === "object" &&
result !== null &&
(result as { resultType?: unknown }).resultType === "task" &&
typeof (result as { taskId?: unknown }).taskId === "string"
);
}
const ModernTaskStatusSchema = z.enum([
"working",
"input_required",
"completed",
"failed",
"cancelled",
]);
/**
* `DetailedTask` (SEP-2663): the modern task shape returned by `tasks/get` and
* carried by a `CreateTaskResult`. Status-specific members (`result`, `error`,
* `inputRequests`) are optional here because a single loose schema stands in for
* the wire union `Working | InputRequired | Completed | Failed | Cancelled`.
*/
export const ModernDetailedTaskSchema = z.looseObject({
taskId: z.string(),
status: ModernTaskStatusSchema,
statusMessage: z.string().optional(),
createdAt: z.string(),
lastUpdatedAt: z.string(),
ttlMs: z.number().nullable().optional(),
pollIntervalMs: z.number().optional(),
/** Present on `completed`: the original request's result (e.g. CallToolResult). */
result: z.record(z.string(), z.unknown()).optional(),
/** Present on `failed`: the JSON-RPC error that ended the task. */
error: z.record(z.string(), z.unknown()).optional(),
/** Present on `input_required`: embedded server→client requests, keyed by id. */
inputRequests: z.record(z.string(), z.unknown()).optional(),
});
export type ModernDetailedTask = z.infer<typeof ModernDetailedTaskSchema>;
/** `GetTaskResult = Result & DetailedTask`. Same fields we need as the task itself. */
export const ModernGetTaskResultSchema = ModernDetailedTaskSchema;
/** `CreateTaskResult = Result & Task` (`resultType: "task"`). The seed task state. */
export const ModernCreateTaskResultSchema = ModernDetailedTaskSchema;
/** `UpdateTaskResult` — an empty acknowledgement (`resultType: "complete"`). */
export const ModernUpdateTaskResultSchema = z.looseObject({});
/** `CancelTaskResult` — modern cancel acks with an empty/loose result. */
export const ModernCancelTaskResultSchema = z.looseObject({});
/**
* Normalize a modern `DetailedTask` onto the internal (SDK 2025-11-25) `Task`
* shape the state store, events, and `TaskCard` consume: `ttlMs` → `ttl`,
* `pollIntervalMs` → `pollInterval`. The status-specific members
* (`result` / `error` / `inputRequests`) ride along structurally so the poll
* driver can read them; they are not part of the `Task` type but are harmless
* extra properties on the object (the card renders the full task JSON).
*/
export function normalizeModernTask(modern: ModernDetailedTask): Task {
const { ttlMs, pollIntervalMs, ...rest } = modern;
const normalized: Record<string, unknown> = { ...rest };
// The internal Task requires `ttl: number | null`; map the modern `ttlMs`
// (which is itself `number | null`) straight across, defaulting to null.
normalized.ttl = ttlMs ?? null;
if (pollIntervalMs != null) normalized.pollInterval = pollIntervalMs;
// The loose modern schema is a structural superset of the internal Task
// (taskId/status/statusMessage/createdAt/lastUpdatedAt present; ttl/pollInterval
// mapped above). No SDK schema relates the two nominal types, so a single
// narrowing cast bridges the structurally-identical shape.
return normalized as unknown as Task;
}
/** Read the embedded `inputRequests` map off a modern task, typed for
* {@link fulfilInputRequests}. The loose parse yields `unknown` values; the
* per-request `fulfilEmbeddedInputRequest` switch validates each by method. */
export function readInputRequests(
modern: ModernDetailedTask,
): InputRequests | undefined {
// Structural bridge: the loose record parse cannot express the InputRequests
// union, but fulfilEmbeddedInputRequest validates each entry by its `method`.
return modern.inputRequests as InputRequests | undefined;
}