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
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:
parent
320daf2f67
commit
2259b1a3e1
5 changed files with 2483 additions and 132 deletions
|
|
@ -43,6 +43,12 @@ import {
|
|||
ListTasksRequestSchema,
|
||||
TaskStatusNotificationSchema,
|
||||
} from "@modelcontextprotocol/core";
|
||||
import {
|
||||
TASKS_EXTENSION_KEY,
|
||||
ModernTaskRuntime,
|
||||
createModernTaskTools,
|
||||
wireModernTaskHandlers,
|
||||
} from "./modern-tasks.js";
|
||||
|
||||
// Empty object JSON schema constant (from SDK's mcp.js)
|
||||
const EMPTY_OBJECT_JSON_SCHEMA = {
|
||||
|
|
@ -479,6 +485,21 @@ export interface ServerConfig {
|
|||
* Only used if tasks capability is enabled.
|
||||
*/
|
||||
taskStore?: InMemoryTaskStore;
|
||||
/**
|
||||
* Advertise the modern (2026-07-28) `io.modelcontextprotocol/tasks` extension
|
||||
* (SEP-2663) and wire its raw `tasks/get` / `tasks/update` / `tasks/cancel`
|
||||
* handlers plus the `modern_task` / `modern_input_task` tools. Distinct from
|
||||
* the legacy {@link ServerConfig.tasks} capability — meant to be paired with
|
||||
* `modern: true`. See `modern-tasks.ts`.
|
||||
*/
|
||||
tasksExtension?: boolean;
|
||||
/**
|
||||
* Shared modern task runtime. Created lazily on first `createMcpServer` call
|
||||
* and cached here so the stateless modern leg's per-request server instances
|
||||
* share one task store (a task created by a `tools/call` must be visible to a
|
||||
* later `tasks/get`). Do not set by hand.
|
||||
*/
|
||||
modernTaskRuntime?: ModernTaskRuntime;
|
||||
/**
|
||||
* OAuth 2.1 configuration for test server.
|
||||
* - **combined** (default): this server is both MCP resource and authorization server.
|
||||
|
|
@ -615,9 +636,13 @@ export function createMcpServer(config: ServerConfig): McpServer {
|
|||
cancel?: object;
|
||||
requests?: { tools?: { call?: object } };
|
||||
};
|
||||
extensions?: Record<string, object>;
|
||||
} = {};
|
||||
|
||||
if (config.tools !== undefined) {
|
||||
// The modern tasks extension (SEP-2663) needs the tools capability too (its
|
||||
// task-augmented tools list via `tools/list`), even when no `config.tools`
|
||||
// were supplied.
|
||||
if (config.tools !== undefined || config.tasksExtension) {
|
||||
capabilities.tools = {};
|
||||
}
|
||||
if (
|
||||
|
|
@ -651,6 +676,19 @@ export function createMcpServer(config: ServerConfig): McpServer {
|
|||
}
|
||||
}
|
||||
|
||||
// Modern tasks extension (SEP-2663): advertise it in server/discover and reuse
|
||||
// (or lazily create + cache) the shared runtime so the stateless modern leg's
|
||||
// per-request servers all answer against the same task store.
|
||||
const modernTaskRuntime = config.tasksExtension
|
||||
? (config.modernTaskRuntime ??= new ModernTaskRuntime())
|
||||
: undefined;
|
||||
if (config.tasksExtension) {
|
||||
capabilities.extensions = {
|
||||
...(capabilities.extensions ?? {}),
|
||||
[TASKS_EXTENSION_KEY]: {},
|
||||
};
|
||||
}
|
||||
|
||||
// Create the in-memory task store if tasks are enabled. SDK v2 has no built-in
|
||||
// task runtime, so the store is owned here and its methods answer the wire.
|
||||
const taskStore =
|
||||
|
|
@ -746,9 +784,15 @@ export function createMcpServer(config: ServerConfig): McpServer {
|
|||
// (returning a task handle), reproducing the deleted SDK task runtime.
|
||||
const taskTools = new Map<string, TaskToolDefinition>();
|
||||
|
||||
// Set up tools
|
||||
if (config.tools && config.tools.length > 0) {
|
||||
for (const tool of config.tools) {
|
||||
// Set up tools. The modern tasks extension contributes its task-augmented
|
||||
// tools (registered as ordinary tools so they surface in `tools/list`; their
|
||||
// `tools/call` is intercepted by `wireModernTaskHandlers` below).
|
||||
const effectiveTools: (ToolDefinition | TaskToolDefinition)[] = [
|
||||
...(config.tools ?? []),
|
||||
...(config.tasksExtension ? createModernTaskTools() : []),
|
||||
];
|
||||
if (effectiveTools.length > 0) {
|
||||
for (const tool of effectiveTools) {
|
||||
if (isTaskTool(tool)) {
|
||||
// Register the task tool as an ordinary tool so it surfaces in
|
||||
// `tools/list` with its input schema, `_meta`, and `execution` support.
|
||||
|
|
@ -1254,6 +1298,12 @@ export function createMcpServer(config: ServerConfig): McpServer {
|
|||
wireTaskHandlers(mcpServer, taskStore, taskTools);
|
||||
}
|
||||
|
||||
// Modern tasks extension (SEP-2663): raw tasks/get, tasks/update, tasks/cancel
|
||||
// (no tasks/list, no tasks/result) plus the CreateTaskResult tools/call seam.
|
||||
if (modernTaskRuntime) {
|
||||
wireModernTaskHandlers(mcpServer, modernTaskRuntime);
|
||||
}
|
||||
|
||||
return mcpServer;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -56,6 +56,10 @@ export interface ConfigFile {
|
|||
list?: boolean;
|
||||
cancel?: boolean;
|
||||
};
|
||||
/** Advertise the modern (SEP-2663) `io.modelcontextprotocol/tasks` extension
|
||||
* and wire its handlers + `modern_task` / `modern_input_task` tools. Pair with
|
||||
* `transport.modern`. */
|
||||
tasksExtension?: boolean;
|
||||
maxPageSize?: {
|
||||
tools?: number;
|
||||
resources?: number;
|
||||
|
|
|
|||
408
test-servers/src/modern-tasks.ts
Normal file
408
test-servers/src/modern-tasks.ts
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
/**
|
||||
* Modern (2026-07-28) Tasks extension server — SEP-2663
|
||||
* (`io.modelcontextprotocol/tasks`).
|
||||
*
|
||||
* SDK v2 removed all built-in tasks support, and the redesigned extension is a
|
||||
* different wire shape than the deleted 2025-11-25 runtime (`ttlMs`/`pollIntervalMs`,
|
||||
* a polymorphic `DetailedTask` inlining `result`/`error`/`inputRequests`,
|
||||
* `tasks/get` polling, a new `tasks/update`, no `tasks/list`, no blocking
|
||||
* `tasks/result`). This module wires a minimal, poll-driven modern task runtime
|
||||
* by hand so an Inspector connecting with **Protocol Era = Modern** can exercise
|
||||
* the full flow: a task-augmented `tools/call` returns a `CreateTaskResult`
|
||||
* (`resultType: "task"`); the client polls `tasks/get`; an `input_required` task
|
||||
* surfaces an embedded elicitation the client answers via `tasks/update`; and
|
||||
* the completed task inlines its `CallToolResult`.
|
||||
*
|
||||
* The runtime is a single shared `Map` so it survives across the stateless
|
||||
* modern leg's per-request server instances (each `createMcpHandler` request
|
||||
* builds a fresh `McpServer`, but they share one runtime via the config).
|
||||
*/
|
||||
|
||||
import * as z from "zod/v4";
|
||||
import type { RequestHandler } from "express";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { ToolDefinition } from "./composable-test-server.js";
|
||||
|
||||
/** SEP-2133 extension identifier for the redesigned Tasks extension. */
|
||||
export const TASKS_EXTENSION_KEY = "io.modelcontextprotocol/tasks";
|
||||
|
||||
/** Names of the modern task-augmented tools whose `tools/call` returns a task. */
|
||||
export const MODERN_TASK_TOOL_NAMES = new Set([
|
||||
"modern_task",
|
||||
"modern_input_task",
|
||||
// Never completes — stays `input_required` on every poll, so a client keeps
|
||||
// being re-prompted. Used to exercise the client's input-round cap.
|
||||
"modern_loop_task",
|
||||
]);
|
||||
|
||||
const DEFAULT_TTL_MS = 60_000;
|
||||
const DEFAULT_POLL_INTERVAL_MS = 500;
|
||||
/** `modern_task` reports `working` for this many `tasks/get` polls before completing. */
|
||||
const SIMPLE_WORKING_POLLS = 2;
|
||||
|
||||
type ModernTaskStatus =
|
||||
"working" | "input_required" | "completed" | "failed" | "cancelled";
|
||||
|
||||
interface ModernTaskEntry {
|
||||
taskId: string;
|
||||
kind: "simple" | "input" | "loop";
|
||||
status: ModernTaskStatus;
|
||||
createdAt: string;
|
||||
lastUpdatedAt: string;
|
||||
args: Record<string, unknown>;
|
||||
/** Remaining `working` polls for the simple task before it completes. */
|
||||
pollsRemaining: number;
|
||||
/** Set once the client answered the embedded elicitation via `tasks/update`. */
|
||||
inputSatisfied?: boolean;
|
||||
/** The `inputResponses` the client submitted, echoed back in the result. */
|
||||
inputResponses?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** The embedded elicitation an `input_required` modern task surfaces. Shaped as
|
||||
* a standalone `elicitation/create` request so the client's pending-request UI
|
||||
* (reused from the MRTR path) renders it and returns an `ElicitResult`. */
|
||||
function confirmInputRequests(): Record<string, unknown> {
|
||||
return {
|
||||
confirm: {
|
||||
method: "elicitation/create",
|
||||
params: {
|
||||
message: "Approve this task before it continues?",
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
approved: {
|
||||
type: "boolean",
|
||||
title: "Approved",
|
||||
description: "Whether to proceed with the task",
|
||||
},
|
||||
},
|
||||
required: ["approved"],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function newTaskId(): string {
|
||||
return (
|
||||
globalThis.crypto?.randomUUID?.() ??
|
||||
`task-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared, in-memory modern task runtime. One instance is created per modern
|
||||
* server config and reused across the stateless leg's per-request servers, so a
|
||||
* task created by one `tools/call` request is visible to a later `tasks/get`.
|
||||
*/
|
||||
export class ModernTaskRuntime {
|
||||
private tasks = new Map<string, ModernTaskEntry>();
|
||||
|
||||
/** Handle a task-augmented `tools/call`: durably create the task and return a
|
||||
* `CreateTaskResult` (`resultType: "task"`) seed. */
|
||||
createTask(
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const now = nowIso();
|
||||
const kind: ModernTaskEntry["kind"] =
|
||||
toolName === "modern_input_task"
|
||||
? "input"
|
||||
: toolName === "modern_loop_task"
|
||||
? "loop"
|
||||
: "simple";
|
||||
const entry: ModernTaskEntry = {
|
||||
taskId: newTaskId(),
|
||||
kind,
|
||||
status: "working",
|
||||
createdAt: now,
|
||||
lastUpdatedAt: now,
|
||||
args,
|
||||
pollsRemaining: SIMPLE_WORKING_POLLS,
|
||||
};
|
||||
this.tasks.set(entry.taskId, entry);
|
||||
return {
|
||||
resultType: "task",
|
||||
...this.project(entry),
|
||||
statusMessage: "The operation is now in progress.",
|
||||
};
|
||||
}
|
||||
|
||||
/** Serve `tasks/get`: advance the scripted lifecycle and return a
|
||||
* `DetailedTask` (`resultType: "complete"`). Throws on an unknown id. */
|
||||
getTask(taskId: string): Record<string, unknown> {
|
||||
const entry = this.requireTask(taskId);
|
||||
this.advance(entry);
|
||||
return { resultType: "complete", ...this.project(entry) };
|
||||
}
|
||||
|
||||
/** Serve `tasks/update`: record the answered `inputResponses` and ack empty. */
|
||||
updateTask(
|
||||
taskId: string,
|
||||
inputResponses: Record<string, unknown> | undefined,
|
||||
): Record<string, unknown> {
|
||||
const entry = this.requireTask(taskId);
|
||||
entry.inputSatisfied = true;
|
||||
if (inputResponses) entry.inputResponses = inputResponses;
|
||||
this.touch(entry);
|
||||
return { resultType: "complete" };
|
||||
}
|
||||
|
||||
/** Serve `tasks/cancel`: move the task to `cancelled` and ack empty. */
|
||||
cancelTask(taskId: string): Record<string, unknown> {
|
||||
const entry = this.requireTask(taskId);
|
||||
if (
|
||||
entry.status !== "completed" &&
|
||||
entry.status !== "failed" &&
|
||||
entry.status !== "cancelled"
|
||||
) {
|
||||
entry.status = "cancelled";
|
||||
this.touch(entry);
|
||||
}
|
||||
return { resultType: "complete" };
|
||||
}
|
||||
|
||||
private requireTask(taskId: string): ModernTaskEntry {
|
||||
const entry = this.tasks.get(taskId);
|
||||
if (!entry) throw new Error(`Unknown taskId: ${taskId}`);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private touch(entry: ModernTaskEntry): void {
|
||||
entry.lastUpdatedAt = nowIso();
|
||||
}
|
||||
|
||||
/** Move a task one step along its scripted lifecycle on each poll. */
|
||||
private advance(entry: ModernTaskEntry): void {
|
||||
if (
|
||||
entry.status === "completed" ||
|
||||
entry.status === "failed" ||
|
||||
entry.status === "cancelled"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (entry.kind === "simple") {
|
||||
if (entry.pollsRemaining > 0) {
|
||||
entry.pollsRemaining -= 1;
|
||||
} else {
|
||||
entry.status = "completed";
|
||||
}
|
||||
} else if (entry.kind === "loop") {
|
||||
// Never advances: stays input_required every poll (ignores tasks/update),
|
||||
// so a client is re-prompted indefinitely — exercises its round cap.
|
||||
entry.status = "input_required";
|
||||
} else {
|
||||
// input task: request input, then complete once the client has answered.
|
||||
entry.status = entry.inputSatisfied ? "completed" : "input_required";
|
||||
}
|
||||
this.touch(entry);
|
||||
}
|
||||
|
||||
/** Project the internal entry onto the wire `DetailedTask`, inlining the
|
||||
* status-specific member (`result` / `inputRequests`). */
|
||||
private project(entry: ModernTaskEntry): Record<string, unknown> {
|
||||
const base: Record<string, unknown> = {
|
||||
taskId: entry.taskId,
|
||||
status: entry.status,
|
||||
createdAt: entry.createdAt,
|
||||
lastUpdatedAt: entry.lastUpdatedAt,
|
||||
ttlMs: DEFAULT_TTL_MS,
|
||||
};
|
||||
// The simple task advertises a poll interval; the input task omits it so a
|
||||
// client falls back to its own default cadence (both paths exercised).
|
||||
if (entry.kind === "simple") {
|
||||
base.pollIntervalMs = DEFAULT_POLL_INTERVAL_MS;
|
||||
}
|
||||
if (entry.status === "input_required") {
|
||||
base.inputRequests = confirmInputRequests();
|
||||
}
|
||||
if (entry.status === "completed") {
|
||||
base.result = this.completedResult(entry);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
/** The `CallToolResult` a completed task inlines (SEP-2663: no `tasks/result`). */
|
||||
private completedResult(entry: ModernTaskEntry): Record<string, unknown> {
|
||||
const detail =
|
||||
entry.kind === "input"
|
||||
? `input=${JSON.stringify(entry.inputResponses ?? {})}`
|
||||
: `args=${JSON.stringify(entry.args ?? {})}`;
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Modern task ${entry.taskId} completed (${detail}).`,
|
||||
},
|
||||
],
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** The two plain tools whose `tools/call` the modern task handlers intercept.
|
||||
* Their handlers are placeholders — {@link wireModernTaskHandlers} routes these
|
||||
* names to the runtime before the SDK handler runs. */
|
||||
export function createModernTaskTools(): ToolDefinition[] {
|
||||
const placeholder: ToolDefinition["handler"] = async () => ({
|
||||
content: [
|
||||
{ type: "text" as const, text: "Task tool must be invoked as a task." },
|
||||
],
|
||||
isError: true,
|
||||
});
|
||||
return [
|
||||
{
|
||||
name: "modern_task",
|
||||
description:
|
||||
"Create a modern (SEP-2663) task that reports progress over a few polls then completes.",
|
||||
inputSchema: {
|
||||
message: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Text echoed back in the completed task result."),
|
||||
},
|
||||
handler: placeholder,
|
||||
},
|
||||
{
|
||||
name: "modern_input_task",
|
||||
description:
|
||||
"Create a modern task that pauses at input_required and completes after tasks/update.",
|
||||
inputSchema: {},
|
||||
handler: placeholder,
|
||||
},
|
||||
{
|
||||
name: "modern_loop_task",
|
||||
description:
|
||||
"Create a modern task that never completes — stays input_required every poll, so the client's round cap trips.",
|
||||
inputSchema: {},
|
||||
handler: placeholder,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
interface RawHandlerHost {
|
||||
_requestHandlers: Map<
|
||||
string,
|
||||
(request: unknown, ctx: unknown) => Promise<unknown>
|
||||
>;
|
||||
}
|
||||
|
||||
interface ToolsCallRequest {
|
||||
params: { name: string; arguments?: Record<string, unknown> };
|
||||
}
|
||||
|
||||
interface TaskMethodRequest {
|
||||
params: {
|
||||
taskId: string;
|
||||
inputResponses?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the modern task methods by hand onto an `McpServer`:
|
||||
* - override `tools/call` so a modern task tool returns a `CreateTaskResult`
|
||||
* (`resultType: "task"`) and durably creates the task; ordinary tools fall
|
||||
* through to the SDK handler;
|
||||
* - register raw `tasks/get` / `tasks/update` / `tasks/cancel` handlers backed
|
||||
* by the shared runtime. There is deliberately **no** `tasks/list` and **no**
|
||||
* `tasks/result` (SEP-2663 removed both).
|
||||
*
|
||||
* The `tools/call` override is installed into the private handler registry (not
|
||||
* via `setRequestHandler`) so the `CreateTaskResult` skips the `Server`'s
|
||||
* `tools/call` result-schema validation — the same seam the legacy task server
|
||||
* uses. This goes away when the SDK models the tasks extension natively.
|
||||
*/
|
||||
export function wireModernTaskHandlers(
|
||||
mcpServer: McpServer,
|
||||
runtime: ModernTaskRuntime,
|
||||
): void {
|
||||
const lowLevel = mcpServer.server;
|
||||
const registry = (lowLevel as unknown as RawHandlerHost)._requestHandlers;
|
||||
const sdkToolsCall = registry.get("tools/call");
|
||||
|
||||
registry.set("tools/call", async (request, ctx) => {
|
||||
const req = request as ToolsCallRequest;
|
||||
if (MODERN_TASK_TOOL_NAMES.has(req.params.name)) {
|
||||
return runtime.createTask(req.params.name, req.params.arguments ?? {});
|
||||
}
|
||||
if (!sdkToolsCall) {
|
||||
throw new Error("tools/call handler is not initialized");
|
||||
}
|
||||
return sdkToolsCall(request, ctx);
|
||||
});
|
||||
|
||||
registry.set("tasks/get", async (request) => {
|
||||
const req = request as TaskMethodRequest;
|
||||
return runtime.getTask(req.params.taskId);
|
||||
});
|
||||
|
||||
registry.set("tasks/update", async (request) => {
|
||||
const req = request as TaskMethodRequest;
|
||||
return runtime.updateTask(req.params.taskId, req.params.inputResponses);
|
||||
});
|
||||
|
||||
registry.set("tasks/cancel", async (request) => {
|
||||
const req = request as TaskMethodRequest;
|
||||
return runtime.cancelTask(req.params.taskId);
|
||||
});
|
||||
}
|
||||
|
||||
const MODERN_TASK_METHODS = new Set([
|
||||
"tasks/get",
|
||||
"tasks/update",
|
||||
"tasks/cancel",
|
||||
]);
|
||||
|
||||
interface TaskRpcBody {
|
||||
jsonrpc?: string;
|
||||
id?: unknown;
|
||||
method?: string;
|
||||
params?: { taskId?: string; inputResponses?: Record<string, unknown> };
|
||||
}
|
||||
|
||||
/**
|
||||
* Express middleware that answers modern `tasks/get` / `tasks/update` /
|
||||
* `tasks/cancel` POSTs DIRECTLY, before the SDK's `createMcpHandler` sees them.
|
||||
* SDK v2's modern leg era-gates inbound spec methods, so `tasks/*` (spec-method
|
||||
* names removed from the 2026-07-28 era) would be answered `-32601 Method not
|
||||
* found` by the handler — a conformant server can't serve the extension through
|
||||
* the SDK. Intercepting at the HTTP layer is how the test server serves the
|
||||
* extension anyway (mirrors the `specErrorInjector` seam). `tasks` task
|
||||
* creation still flows through `tools/call` (a modern method) inside the handler.
|
||||
*/
|
||||
export function createModernTaskInterceptor(
|
||||
getRuntime: () => ModernTaskRuntime,
|
||||
): RequestHandler {
|
||||
return (req, res, next) => {
|
||||
const body = req.body as TaskRpcBody | undefined;
|
||||
const method = body?.method;
|
||||
if (!method || !MODERN_TASK_METHODS.has(method)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const runtime = getRuntime();
|
||||
const id = body?.id ?? null;
|
||||
const taskId = body?.params?.taskId ?? "";
|
||||
try {
|
||||
let result: Record<string, unknown>;
|
||||
if (method === "tasks/get") {
|
||||
result = runtime.getTask(taskId);
|
||||
} else if (method === "tasks/update") {
|
||||
result = runtime.updateTask(taskId, body?.params?.inputResponses);
|
||||
} else {
|
||||
result = runtime.cancelTask(taskId);
|
||||
}
|
||||
res.json({ jsonrpc: "2.0", id, result });
|
||||
} catch (err) {
|
||||
res.json({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32602, message: (err as Error).message },
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -89,6 +89,7 @@ export function resolveConfig(config: ConfigFile): ServerConfig {
|
|||
listChanged: config.listChanged,
|
||||
subscriptions: config.subscriptions,
|
||||
tasks: config.tasks,
|
||||
tasksExtension: config.tasksExtension,
|
||||
maxPageSize: config.maxPageSize,
|
||||
serverType: isHttp
|
||||
? (transport.type as "sse" | "streamable-http")
|
||||
|
|
|
|||
|
|
@ -8,6 +8,10 @@ import type {
|
|||
McpHttpHandler,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import { createMcpServer } from "./test-server-fixtures.js";
|
||||
import {
|
||||
ModernTaskRuntime,
|
||||
createModernTaskInterceptor,
|
||||
} from "./modern-tasks.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
|
||||
import type { Request, Response } from "express";
|
||||
import express from "express";
|
||||
|
|
@ -365,6 +369,19 @@ export class TestServerHttp {
|
|||
? [specErrorInjector]
|
||||
: [];
|
||||
|
||||
// Modern tasks extension (SEP-2663): the SDK's modern leg era-gates inbound
|
||||
// `tasks/*` spec methods, so serve them from a middleware ahead of the SDK
|
||||
// handler, backed by the shared runtime (also used by the tools/call task
|
||||
// seam inside `createMcpServer`).
|
||||
if (this.config.tasksExtension) {
|
||||
this.configWithCallback.modernTaskRuntime ??= new ModernTaskRuntime();
|
||||
extraMiddleware.push(
|
||||
createModernTaskInterceptor(
|
||||
() => this.configWithCallback.modernTaskRuntime!,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
app.post("/mcp", ...mcpMiddleware, ...extraMiddleware, route);
|
||||
app.get("/mcp", ...mcpMiddleware, route);
|
||||
app.delete("/mcp", ...mcpMiddleware, route);
|
||||
|
|
|
|||
Loading…
Reference in a new issue