@lushly-dev/afd-server 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +178 -48
  2. package/dist/app-call-registry.d.ts +31 -0
  3. package/dist/app-call-registry.d.ts.map +1 -0
  4. package/dist/app-call-registry.js +56 -0
  5. package/dist/app-call-registry.js.map +1 -0
  6. package/dist/approval-admission.d.ts +93 -0
  7. package/dist/approval-admission.d.ts.map +1 -0
  8. package/dist/approval-admission.js +165 -0
  9. package/dist/approval-admission.js.map +1 -0
  10. package/dist/approval-crypto.d.ts +22 -16
  11. package/dist/approval-crypto.d.ts.map +1 -1
  12. package/dist/approval-crypto.js +41 -66
  13. package/dist/approval-crypto.js.map +1 -1
  14. package/dist/approval-process-state.d.ts +20 -0
  15. package/dist/approval-process-state.d.ts.map +1 -0
  16. package/dist/approval-process-state.js +28 -0
  17. package/dist/approval-process-state.js.map +1 -0
  18. package/dist/approval-relay.d.ts +171 -8
  19. package/dist/approval-relay.d.ts.map +1 -1
  20. package/dist/approval-relay.js +42 -3
  21. package/dist/approval-relay.js.map +1 -1
  22. package/dist/approval-up-front.d.ts +40 -0
  23. package/dist/approval-up-front.d.ts.map +1 -0
  24. package/dist/approval-up-front.js +365 -0
  25. package/dist/approval-up-front.js.map +1 -0
  26. package/dist/approval.d.ts +17 -12
  27. package/dist/approval.d.ts.map +1 -1
  28. package/dist/approval.js +178 -41
  29. package/dist/approval.js.map +1 -1
  30. package/dist/approver.d.ts +84 -0
  31. package/dist/approver.d.ts.map +1 -0
  32. package/dist/approver.js +107 -0
  33. package/dist/approver.js.map +1 -0
  34. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  35. package/dist/bootstrap/afd-docs.js +4 -0
  36. package/dist/bootstrap/afd-docs.js.map +1 -1
  37. package/dist/bootstrap/afd-help.d.ts +2 -1
  38. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  39. package/dist/bootstrap/afd-help.js +17 -4
  40. package/dist/bootstrap/afd-help.js.map +1 -1
  41. package/dist/bootstrap/described-command.d.ts +2 -1
  42. package/dist/bootstrap/described-command.d.ts.map +1 -1
  43. package/dist/bootstrap/described-command.js.map +1 -1
  44. package/dist/command-timeout.d.ts +17 -0
  45. package/dist/command-timeout.d.ts.map +1 -0
  46. package/dist/command-timeout.js +92 -0
  47. package/dist/command-timeout.js.map +1 -0
  48. package/dist/context-fields.d.ts.map +1 -1
  49. package/dist/context-fields.js +9 -9
  50. package/dist/context-fields.js.map +1 -1
  51. package/dist/define-core.d.ts +27 -1
  52. package/dist/define-core.d.ts.map +1 -1
  53. package/dist/define-core.js +8 -1
  54. package/dist/define-core.js.map +1 -1
  55. package/dist/define.d.ts +3 -2
  56. package/dist/define.d.ts.map +1 -1
  57. package/dist/define.js +1 -1
  58. package/dist/define.js.map +1 -1
  59. package/dist/direct-registry.d.ts +27 -3
  60. package/dist/direct-registry.d.ts.map +1 -1
  61. package/dist/direct-registry.js +41 -6
  62. package/dist/direct-registry.js.map +1 -1
  63. package/dist/direct-tool-surface.d.ts +1 -1
  64. package/dist/direct-tool-surface.d.ts.map +1 -1
  65. package/dist/direct-tool-surface.js +14 -4
  66. package/dist/direct-tool-surface.js.map +1 -1
  67. package/dist/direct.d.ts +3 -1
  68. package/dist/direct.d.ts.map +1 -1
  69. package/dist/direct.js +2 -1
  70. package/dist/direct.js.map +1 -1
  71. package/dist/elicitation-state.d.ts +5 -1
  72. package/dist/elicitation-state.d.ts.map +1 -1
  73. package/dist/elicitation-state.js +4 -1
  74. package/dist/elicitation-state.js.map +1 -1
  75. package/dist/execution.d.ts +17 -0
  76. package/dist/execution.d.ts.map +1 -1
  77. package/dist/execution.js +78 -7
  78. package/dist/execution.js.map +1 -1
  79. package/dist/http-handler.d.ts +20 -2
  80. package/dist/http-handler.d.ts.map +1 -1
  81. package/dist/http-handler.js +139 -16
  82. package/dist/http-handler.js.map +1 -1
  83. package/dist/http-security.d.ts +14 -1
  84. package/dist/http-security.d.ts.map +1 -1
  85. package/dist/http-security.js +79 -17
  86. package/dist/http-security.js.map +1 -1
  87. package/dist/http-sessions.d.ts +35 -5
  88. package/dist/http-sessions.d.ts.map +1 -1
  89. package/dist/http-sessions.js +42 -10
  90. package/dist/http-sessions.js.map +1 -1
  91. package/dist/index.d.ts +13 -6
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +11 -4
  94. package/dist/index.js.map +1 -1
  95. package/dist/instance-state.d.ts +46 -0
  96. package/dist/instance-state.d.ts.map +1 -0
  97. package/dist/instance-state.js +91 -0
  98. package/dist/instance-state.js.map +1 -0
  99. package/dist/journal-replay.d.ts.map +1 -1
  100. package/dist/journal-replay.js +41 -3
  101. package/dist/journal-replay.js.map +1 -1
  102. package/dist/journal.d.ts +10 -1
  103. package/dist/journal.d.ts.map +1 -1
  104. package/dist/journal.js +95 -10
  105. package/dist/journal.js.map +1 -1
  106. package/dist/json-rpc.d.ts +3 -2
  107. package/dist/json-rpc.d.ts.map +1 -1
  108. package/dist/json-rpc.js +5 -3
  109. package/dist/json-rpc.js.map +1 -1
  110. package/dist/lazy-tools.d.ts +16 -1
  111. package/dist/lazy-tools.d.ts.map +1 -1
  112. package/dist/lazy-tools.js +13 -2
  113. package/dist/lazy-tools.js.map +1 -1
  114. package/dist/mcp-auth-bearer.d.ts +2 -0
  115. package/dist/mcp-auth-bearer.d.ts.map +1 -1
  116. package/dist/mcp-auth-bearer.js +1 -1
  117. package/dist/mcp-auth-bearer.js.map +1 -1
  118. package/dist/mcp-auth-dispatch.d.ts +38 -0
  119. package/dist/mcp-auth-dispatch.d.ts.map +1 -0
  120. package/dist/mcp-auth-dispatch.js +113 -0
  121. package/dist/mcp-auth-dispatch.js.map +1 -0
  122. package/dist/mcp-auth-jwt.d.ts +3 -2
  123. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  124. package/dist/mcp-auth-jwt.js.map +1 -1
  125. package/dist/mcp-auth-resource.d.ts +6 -2
  126. package/dist/mcp-auth-resource.d.ts.map +1 -1
  127. package/dist/mcp-auth-resource.js +6 -5
  128. package/dist/mcp-auth-resource.js.map +1 -1
  129. package/dist/mcp-auth-scopes.d.ts +84 -0
  130. package/dist/mcp-auth-scopes.d.ts.map +1 -0
  131. package/dist/mcp-auth-scopes.js +125 -0
  132. package/dist/mcp-auth-scopes.js.map +1 -0
  133. package/dist/mcp-auth-view.d.ts +50 -0
  134. package/dist/mcp-auth-view.d.ts.map +1 -0
  135. package/dist/mcp-auth-view.js +166 -0
  136. package/dist/mcp-auth-view.js.map +1 -0
  137. package/dist/mcp-auth.d.ts +79 -3
  138. package/dist/mcp-auth.d.ts.map +1 -1
  139. package/dist/mcp-auth.js +206 -20
  140. package/dist/mcp-auth.js.map +1 -1
  141. package/dist/mcp-modern.d.ts +12 -1
  142. package/dist/mcp-modern.d.ts.map +1 -1
  143. package/dist/mcp-modern.js +210 -29
  144. package/dist/mcp-modern.js.map +1 -1
  145. package/dist/meta-argument.d.ts +8 -8
  146. package/dist/meta-argument.d.ts.map +1 -1
  147. package/dist/meta-argument.js +17 -10
  148. package/dist/meta-argument.js.map +1 -1
  149. package/dist/meta-tools.js +1 -1
  150. package/dist/meta-tools.js.map +1 -1
  151. package/dist/middleware.d.ts.map +1 -1
  152. package/dist/middleware.js +16 -6
  153. package/dist/middleware.js.map +1 -1
  154. package/dist/output-budget.d.ts +77 -0
  155. package/dist/output-budget.d.ts.map +1 -0
  156. package/dist/output-budget.js +200 -0
  157. package/dist/output-budget.js.map +1 -0
  158. package/dist/resources.d.ts +35 -10
  159. package/dist/resources.d.ts.map +1 -1
  160. package/dist/resources.js +59 -18
  161. package/dist/resources.js.map +1 -1
  162. package/dist/scope-view.d.ts +59 -0
  163. package/dist/scope-view.d.ts.map +1 -0
  164. package/dist/scope-view.js +44 -0
  165. package/dist/scope-view.js.map +1 -0
  166. package/dist/server-types.d.ts +157 -25
  167. package/dist/server-types.d.ts.map +1 -1
  168. package/dist/server-types.js.map +1 -1
  169. package/dist/server.d.ts.map +1 -1
  170. package/dist/server.js +162 -20
  171. package/dist/server.js.map +1 -1
  172. package/dist/skills.d.ts.map +1 -1
  173. package/dist/skills.js +99 -3
  174. package/dist/skills.js.map +1 -1
  175. package/dist/task-dispatch.d.ts +34 -0
  176. package/dist/task-dispatch.d.ts.map +1 -0
  177. package/dist/task-dispatch.js +26 -0
  178. package/dist/task-dispatch.js.map +1 -0
  179. package/dist/tasks-runtime.d.ts +113 -0
  180. package/dist/tasks-runtime.d.ts.map +1 -0
  181. package/dist/tasks-runtime.js +687 -0
  182. package/dist/tasks-runtime.js.map +1 -0
  183. package/dist/tasks.d.ts +210 -0
  184. package/dist/tasks.d.ts.map +1 -0
  185. package/dist/tasks.js +289 -0
  186. package/dist/tasks.js.map +1 -0
  187. package/dist/tool-router.d.ts +4 -0
  188. package/dist/tool-router.d.ts.map +1 -1
  189. package/dist/tool-router.js +103 -26
  190. package/dist/tool-router.js.map +1 -1
  191. package/dist/tools.d.ts.map +1 -1
  192. package/dist/tools.js +11 -18
  193. package/dist/tools.js.map +1 -1
  194. package/dist/up-front-steps.d.ts +27 -0
  195. package/dist/up-front-steps.d.ts.map +1 -0
  196. package/dist/up-front-steps.js +110 -0
  197. package/dist/up-front-steps.js.map +1 -0
  198. package/dist/validation.d.ts +24 -3
  199. package/dist/validation.d.ts.map +1 -1
  200. package/dist/validation.js +56 -6
  201. package/dist/validation.js.map +1 -1
  202. package/dist/verified-credentials.d.ts +13 -5
  203. package/dist/verified-credentials.d.ts.map +1 -1
  204. package/dist/verified-credentials.js +43 -10
  205. package/dist/verified-credentials.js.map +1 -1
  206. package/package.json +7 -7
@@ -0,0 +1,687 @@
1
+ /**
2
+ * @fileoverview MCP Tasks runtime: creation, background execution, cancellation, deadlines and
3
+ * `tasks/get`, `tasks/update`, `tasks/cancel` handlers (`spec/command-metadata.md`, "Tasks";
4
+ * SEP-2663).
5
+ */
6
+ import { randomBytes } from 'node:crypto';
7
+ import { ErrorCodes, failure, systemClock, truncateName } from '@lushly-dev/afd-core';
8
+ import { CLIENT_CAPABILITIES_META_KEY, ProtocolError, ProtocolErrorCode, } from '@modelcontextprotocol/server';
9
+ import { z } from 'zod';
10
+ import { bindContextState, resolveContextState } from './context-scope.js';
11
+ import { JsonRpcError } from './json-rpc.js';
12
+ import { bindOutputBudgetAsk, OUTPUT_BUDGET_ASK } from './output-budget.js';
13
+ import { principalBinding } from './principal-binding.js';
14
+ import { bindScopeView, scopeViewOf } from './scope-view.js';
15
+ import { InMemoryTaskStore, isTaskExpired, isTerminalTaskStatus, resolveTaskOptions, TASKS_EXTENSION_ID, TaskStoreError, taskOwnerMatches, taskTtlFor, } from './tasks.js';
16
+ import { resultContent } from './tool-router.js';
17
+ import { cloneVerifiedCredentials, unbrandVerifiedCredentials } from './verified-credentials.js';
18
+ /**
19
+ * Thrown by the task dispatch inside `tools/call` so the patched `Server._wrapHandler` returns a
20
+ * `CreateTaskResult` without running the SDK's `CallToolResultSchema` check over it.
21
+ */
22
+ export class CreateTaskSignal {
23
+ result;
24
+ constructor(result) {
25
+ this.result = result;
26
+ }
27
+ }
28
+ /**
29
+ * Patch `server._wrapHandler` so a {@link CreateTaskSignal} thrown from `tools/call` returns its
30
+ * `CreateTaskResult` straight to `Protocol._onrequest` (preserving request validation, input
31
+ * required handling and response encoding).
32
+ */
33
+ export function patchToolsCallForTasks(server) {
34
+ const sdk = server;
35
+ const originalWrap = sdk._wrapHandler.bind(server);
36
+ sdk._wrapHandler = (method, handler) => {
37
+ if (method !== 'tools/call')
38
+ return originalWrap(method, handler);
39
+ const wrapped = originalWrap(method, handler);
40
+ return async (request, extra) => {
41
+ try {
42
+ return await wrapped(request, extra);
43
+ }
44
+ catch (error) {
45
+ if (error instanceof CreateTaskSignal)
46
+ return error.result;
47
+ throw error;
48
+ }
49
+ };
50
+ };
51
+ }
52
+ // ═══════════════════════════════════════════════════════════════════════════════
53
+ // IDS & WIRE HELPERS
54
+ // ═══════════════════════════════════════════════════════════════════════════════
55
+ const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567';
56
+ const TASK_ID_LENGTH = 26;
57
+ const TASK_ID_RE = /^[a-z2-7]{26}$/;
58
+ const MAX_TIMEOUT_MS = 2_147_483_647;
59
+ const utf8 = new TextEncoder();
60
+ /** Generate a 128-bit cryptographic random task id in unpadded lowercase RFC 4648 base32. */
61
+ export function newTaskId() {
62
+ const bytes = randomBytes(16);
63
+ let id = '';
64
+ let buffer = 0;
65
+ let bits = 0;
66
+ for (const byte of bytes) {
67
+ buffer = (buffer << 8) | byte;
68
+ bits += 8;
69
+ while (bits >= 5) {
70
+ bits -= 5;
71
+ id += BASE32[(buffer >>> bits) & 31];
72
+ }
73
+ }
74
+ if (bits > 0) {
75
+ id += BASE32[(buffer << (5 - bits)) & 31];
76
+ }
77
+ return id;
78
+ }
79
+ /** Whether `id` could be a task id issued by this server. */
80
+ export function isTaskId(id) {
81
+ return id.length === TASK_ID_LENGTH && TASK_ID_RE.test(id);
82
+ }
83
+ function isoTimestamp(ms) {
84
+ return new Date(ms).toISOString();
85
+ }
86
+ function wireCreateTask(record) {
87
+ return {
88
+ resultType: 'task',
89
+ taskId: record.id,
90
+ status: 'working',
91
+ ...(record.statusMessage !== undefined && { statusMessage: record.statusMessage }),
92
+ createdAt: isoTimestamp(record.createdAt),
93
+ lastUpdatedAt: isoTimestamp(record.lastUpdatedAt),
94
+ ttlMs: record.ttlMs,
95
+ pollIntervalMs: record.pollIntervalMs,
96
+ };
97
+ }
98
+ function wireDetailedTask(record) {
99
+ const base = {
100
+ taskId: record.id,
101
+ status: record.status,
102
+ ...(record.statusMessage !== undefined && { statusMessage: record.statusMessage }),
103
+ createdAt: isoTimestamp(record.createdAt),
104
+ lastUpdatedAt: isoTimestamp(record.lastUpdatedAt),
105
+ ttlMs: record.ttlMs,
106
+ pollIntervalMs: record.pollIntervalMs,
107
+ };
108
+ if (record.status === 'completed') {
109
+ base.result = record.result ?? { content: [], isError: false };
110
+ }
111
+ else if (record.status === 'failed') {
112
+ base.error = record.error ?? internalErrorObject();
113
+ }
114
+ return base;
115
+ }
116
+ function isRecord(value) {
117
+ return !!value && typeof value === 'object' && !Array.isArray(value);
118
+ }
119
+ /**
120
+ * Whether `ctx` is an MCP 2026-07-28 request whose envelope client capabilities declare the Tasks
121
+ * extension. A 2025-era request never does.
122
+ */
123
+ export function requestDeclaresTasks(era, ctx) {
124
+ if (era !== 'modern')
125
+ return false;
126
+ const envelope = ctx.mcpReq.envelope;
127
+ const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
128
+ if (!isRecord(capabilities))
129
+ return false;
130
+ const extensions = capabilities.extensions;
131
+ if (!isRecord(extensions))
132
+ return false;
133
+ return isRecord(extensions[TASKS_EXTENSION_ID]);
134
+ }
135
+ function missingTasksCapability() {
136
+ return new ProtocolError(ProtocolErrorCode.MissingRequiredClientCapability, `Client does not declare required capability: ${TASKS_EXTENSION_ID}`, {
137
+ requiredCapabilities: {
138
+ extensions: { [TASKS_EXTENSION_ID]: {} },
139
+ },
140
+ });
141
+ }
142
+ function taskNotFound() {
143
+ return new ProtocolError(ProtocolErrorCode.InvalidParams, 'Task not found');
144
+ }
145
+ function internalRpcError() {
146
+ return new ProtocolError(ProtocolErrorCode.InternalError, 'Internal error');
147
+ }
148
+ function internalErrorObject() {
149
+ return { code: -32603, message: 'Internal error' };
150
+ }
151
+ function taskLimitError() {
152
+ return {
153
+ code: ErrorCodes.RATE_LIMITED,
154
+ message: 'The task could not start: a task limit was reached, so nothing ran',
155
+ suggestion: 'Wait for one of your tasks to finish or expire, then call again.',
156
+ retryable: true,
157
+ };
158
+ }
159
+ function compositeTaskError(tool, commandName) {
160
+ return {
161
+ code: tool === 'afd-batch' ? 'INVALID_BATCH_REQUEST' : 'INVALID_PIPELINE_REQUEST',
162
+ message: `Command '${truncateName(commandName)}' requires MCP Tasks and cannot run inside ${tool}`,
163
+ suggestion: `Call '${truncateName(commandName)}' directly or through afd-call on an MCP 2026-07-28 client declaring ${TASKS_EXTENSION_ID}`,
164
+ retryable: false,
165
+ };
166
+ }
167
+ function unidentifiedCallersError(command) {
168
+ return {
169
+ code: ErrorCodes.UNAUTHORIZED,
170
+ message: `Command '${truncateName(command)}' runs only as a task, and this server cannot tell its callers apart, so it starts no task`,
171
+ suggestion: "Nothing ran. The server's operator must configure authorization, or declare that the server's context hook identifies every caller; calling again will not help until then.",
172
+ retryable: false,
173
+ };
174
+ }
175
+ function createRunningTask() {
176
+ const controller = new AbortController();
177
+ const running = {
178
+ controller,
179
+ reason: undefined,
180
+ stop(reason) {
181
+ if (running.reason === undefined) {
182
+ running.reason = reason;
183
+ }
184
+ if (!controller.signal.aborted) {
185
+ controller.abort();
186
+ }
187
+ },
188
+ };
189
+ return running;
190
+ }
191
+ /** What deadline is due at `nowMs`: token expiry first, then TTL. */
192
+ export function dueTaskStop(tokenDeadlineMs, ttlDeadlineMs, nowMs) {
193
+ if (tokenDeadlineMs !== undefined && nowMs >= tokenDeadlineMs)
194
+ return 'token-expired';
195
+ if (nowMs >= ttlDeadlineMs)
196
+ return 'ttl-ended';
197
+ return undefined;
198
+ }
199
+ /** Build `TASK_TOKEN_EXPIRED`, retryable unless a mutation may have started. */
200
+ export function tokenExpiredError(stage, mutation) {
201
+ let message;
202
+ let suggestion;
203
+ if (stage === 'not-started') {
204
+ message = 'The task did not start: the access token that started it had expired';
205
+ suggestion = 'Nothing ran. Obtain a new access token and start the task again.';
206
+ }
207
+ else if (stage === 'running') {
208
+ message = 'The task stopped because the access token that started it expired';
209
+ suggestion = mutation
210
+ ? 'The command may have made part of its change before it stopped: check its effect, then start it again with a new access token if it is still needed.'
211
+ : 'Obtain a new access token and start the task again.';
212
+ }
213
+ else {
214
+ message =
215
+ 'The task finished after the access token that started it expired, so its result is not delivered';
216
+ suggestion = mutation
217
+ ? 'The command ran to the end and made its change: check its effect before starting it again with a new access token.'
218
+ : 'Obtain a new access token and start the task again.';
219
+ }
220
+ return {
221
+ code: ErrorCodes.TASK_TOKEN_EXPIRED,
222
+ message,
223
+ suggestion,
224
+ retryable: stage === 'not-started' || !mutation,
225
+ };
226
+ }
227
+ function completionChange(result, maxResultBytes, at) {
228
+ const toolResult = resultContent(result, !result.success);
229
+ let serialized;
230
+ try {
231
+ serialized = JSON.stringify(toolResult);
232
+ }
233
+ catch {
234
+ return { kind: 'failed', error: internalErrorObject(), at };
235
+ }
236
+ const size = utf8.encode(serialized).byteLength;
237
+ if (size <= maxResultBytes) {
238
+ return { kind: 'completed', result: toolResult, at };
239
+ }
240
+ const tooLarge = {
241
+ code: ErrorCodes.INTERNAL_ERROR,
242
+ message: 'The command ran, but its result is larger than this server keeps for a task',
243
+ suggestion: 'The command ran: check its effect before running it again. For a read, ask for less (narrow the request or set an output budget).',
244
+ details: { limitBytes: maxResultBytes, actualBytes: size },
245
+ retryable: false,
246
+ };
247
+ return { kind: 'completed', result: resultContent(failure(tooLarge), true), at };
248
+ }
249
+ /** Copy string-keyed properties and only the safe symbols (`scopeView`, `contextState`). */
250
+ function cloneTaskContext(context, signal, reportProgress) {
251
+ const copy = {};
252
+ for (const key of Object.keys(context)) {
253
+ copy[key] = context[key];
254
+ }
255
+ // MCP Tasks are bounded by their own TTL (default 5 min) and cancellation signal rather than
256
+ // the inline server defaultTimeoutMs; keep an explicit per-request timeout if the hook set one.
257
+ if (copy.timeout === undefined) {
258
+ copy.timeout = 0;
259
+ }
260
+ let taskContext = {
261
+ ...copy,
262
+ signal,
263
+ reportProgress,
264
+ };
265
+ const view = scopeViewOf(context);
266
+ if (view)
267
+ taskContext = bindScopeView(taskContext, view);
268
+ const state = resolveContextState(context, undefined);
269
+ if (state !== undefined)
270
+ taskContext = bindContextState(taskContext, state);
271
+ if (Object.hasOwn(context, OUTPUT_BUDGET_ASK)) {
272
+ taskContext = bindOutputBudgetAsk(taskContext, context[OUTPUT_BUDGET_ASK]);
273
+ }
274
+ return taskContext;
275
+ }
276
+ const taskIdParamsSchema = z.object({ taskId: z.string() });
277
+ const updateTaskParamsSchema = z.object({
278
+ taskId: z.string(),
279
+ inputResponses: z.record(z.string(), z.unknown()).optional(),
280
+ });
281
+ export class TaskRuntime {
282
+ store;
283
+ options;
284
+ servesTasks;
285
+ clock;
286
+ hasAuth;
287
+ hasContextHook;
288
+ actor;
289
+ executeCommand;
290
+ running = new Map();
291
+ constructor(deps) {
292
+ this.store = deps.store ?? new InMemoryTaskStore();
293
+ this.options = resolveTaskOptions(deps.options);
294
+ this.clock = deps.clock ?? systemClock;
295
+ this.hasAuth = deps.hasAuth;
296
+ this.hasContextHook = deps.hasContextHook;
297
+ this.actor = deps.actor;
298
+ this.executeCommand = deps.executeCommand;
299
+ this.servesTasks = deps.commands.some((cmd) => cmd.task === 'optional' || cmd.task === 'required');
300
+ }
301
+ get hookIdentifiesCallers() {
302
+ return this.options.callersIdentifiedByHook && this.hasContextHook;
303
+ }
304
+ /** Whether HTTP configuration identifies callers well enough to serve MCP Tasks. */
305
+ get identifiesHttpCallers() {
306
+ return this.hasAuth || this.hookIdentifiesCallers;
307
+ }
308
+ /** Whether this server declares the Tasks extension on this transport (`isHttp`). */
309
+ declaresTasksTo(isHttp) {
310
+ return this.servesTasks && (!isHttp || this.identifiesHttpCallers);
311
+ }
312
+ /** Whether a task may be created for a request on this transport with `credentials`. */
313
+ identifiesCaller(isHttp, credentials) {
314
+ return !isHttp || (this.hasAuth && credentials !== undefined) || this.hookIdentifiesCallers;
315
+ }
316
+ /** Build the {@link TaskDispatch} for one modern/stdio `tools/call`. */
317
+ dispatchFor(era, isHttp, ctx, credentials) {
318
+ return {
319
+ dispatch: async (command, input, context) => {
320
+ if (command.task !== 'optional' && command.task !== 'required')
321
+ return undefined;
322
+ if (!this.identifiesCaller(isHttp, credentials)) {
323
+ if (command.task === 'required') {
324
+ return resultContent(failure(unidentifiedCallersError(command.name)), true);
325
+ }
326
+ return undefined;
327
+ }
328
+ if (!requestDeclaresTasks(era, ctx)) {
329
+ if (command.task === 'required')
330
+ throw missingTasksCapability();
331
+ return undefined;
332
+ }
333
+ return this.startTask(command, input, context);
334
+ },
335
+ refuseComposite: compositeTaskError,
336
+ };
337
+ }
338
+ /** Build the {@link TaskDispatch} for the 2025-era `/message` HTTP lane. */
339
+ legacyHttpDispatchFor(credentials) {
340
+ return {
341
+ dispatch: async (command) => {
342
+ if (command.task !== 'required')
343
+ return undefined;
344
+ if (!this.identifiesCaller(true, credentials)) {
345
+ return resultContent(failure(unidentifiedCallersError(command.name)), true);
346
+ }
347
+ throw new JsonRpcError(ProtocolErrorCode.MissingRequiredClientCapability, `Client does not declare required capability: ${TASKS_EXTENSION_ID}`, `Call '${truncateName(command.name)}' over MCP 2026-07-28 declaring the ${TASKS_EXTENSION_ID} extension`, { requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } } });
348
+ },
349
+ refuseComposite: compositeTaskError,
350
+ };
351
+ }
352
+ /** Abort all locally running tasks without overwriting shared store state (server stop/dispose). */
353
+ dispose() {
354
+ for (const running of this.running.values()) {
355
+ running.stop('lost');
356
+ }
357
+ this.running.clear();
358
+ }
359
+ /** Install `tasks/get`, `tasks/update` and `tasks/cancel` handlers on `server`. */
360
+ installHandlers(server, opts) {
361
+ if (!this.declaresTasksTo(opts.isHttp))
362
+ return;
363
+ const resolveCaller = async (ctx) => {
364
+ if (!requestDeclaresTasks(opts.era, ctx)) {
365
+ throw missingTasksCapability();
366
+ }
367
+ const view = opts.requestView?.();
368
+ const reqDecision = view?.decideRequest();
369
+ if (view && reqDecision && reqDecision !== 'proceed') {
370
+ const error = view.insufficientScope(reqDecision.forbidden);
371
+ throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
372
+ code: error.code,
373
+ suggestion: error.suggestion,
374
+ scopes: reqDecision.forbidden,
375
+ });
376
+ }
377
+ let values;
378
+ try {
379
+ values = opts.requestValues ? await opts.requestValues() : {};
380
+ }
381
+ catch (error) {
382
+ throw opts.internalError(error);
383
+ }
384
+ const actor = (values.actor ?? this.actor);
385
+ const credentials = (view?.credentials ?? values.credentials);
386
+ let owner;
387
+ try {
388
+ owner = principalBinding(actor, credentials);
389
+ }
390
+ catch {
391
+ throw internalRpcError();
392
+ }
393
+ return { owner, view };
394
+ };
395
+ const findTask = async (caller, taskId, needsCommand) => {
396
+ if (!isTaskId(taskId))
397
+ throw taskNotFound();
398
+ let record;
399
+ try {
400
+ record = await this.store.get(taskId, caller.owner);
401
+ }
402
+ catch {
403
+ throw internalRpcError();
404
+ }
405
+ const now = this.clock.now();
406
+ if (!record ||
407
+ record.id !== taskId ||
408
+ !taskOwnerMatches(record.owner, caller.owner) ||
409
+ isTaskExpired(record, now)) {
410
+ throw taskNotFound();
411
+ }
412
+ if (caller.view && !caller.view.known(record.command)) {
413
+ throw taskNotFound();
414
+ }
415
+ if (needsCommand && caller.view) {
416
+ const decision = caller.view.decideTask(record.command);
417
+ if (decision !== 'proceed') {
418
+ const error = caller.view.insufficientScope(decision.forbidden);
419
+ throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
420
+ code: error.code,
421
+ suggestion: error.suggestion,
422
+ scopes: decision.forbidden,
423
+ });
424
+ }
425
+ }
426
+ return record;
427
+ };
428
+ server.setRequestHandler('tasks/get', { params: taskIdParamsSchema }, async (params, ctx) => {
429
+ const caller = await resolveCaller(ctx);
430
+ const record = await findTask(caller, params.taskId, true);
431
+ return wireDetailedTask(record);
432
+ });
433
+ server.setRequestHandler('tasks/update', { params: updateTaskParamsSchema }, async (params, ctx) => {
434
+ const caller = await resolveCaller(ctx);
435
+ await findTask(caller, params.taskId, true);
436
+ return {};
437
+ });
438
+ server.setRequestHandler('tasks/cancel', { params: taskIdParamsSchema }, async (params, ctx) => {
439
+ const caller = await resolveCaller(ctx);
440
+ const record = await findTask(caller, params.taskId, false);
441
+ if (isTerminalTaskStatus(record.status)) {
442
+ this.running.get(record.id)?.stop('lost');
443
+ return {};
444
+ }
445
+ try {
446
+ await this.store.update(record.id, caller.owner, { kind: 'cancel-requested' });
447
+ }
448
+ catch {
449
+ throw internalRpcError();
450
+ }
451
+ this.running.get(record.id)?.stop('cancelled');
452
+ return {};
453
+ });
454
+ }
455
+ async startTask(command, input, context) {
456
+ const actor = (context.actor ?? this.actor);
457
+ const credentials = context.credentials;
458
+ let owner;
459
+ try {
460
+ owner = principalBinding(actor, credentials);
461
+ }
462
+ catch {
463
+ throw internalRpcError();
464
+ }
465
+ const id = newTaskId();
466
+ const now = this.clock.now();
467
+ await this.store.expire(now).catch(() => { });
468
+ const expiresAtSeconds = typeof credentials?.expiresAt === 'number' ? credentials.expiresAt : undefined;
469
+ const ttlMs = taskTtlFor(this.options, now, expiresAtSeconds);
470
+ const record = {
471
+ id,
472
+ owner,
473
+ command: command.name,
474
+ status: 'working',
475
+ createdAt: now,
476
+ lastUpdatedAt: now,
477
+ ttlMs,
478
+ pollIntervalMs: this.options.pollIntervalMs,
479
+ cancelRequested: false,
480
+ };
481
+ if (this.running.size >= this.options.maxRunning) {
482
+ return resultContent(failure(taskLimitError()), true);
483
+ }
484
+ const running = createRunningTask();
485
+ this.running.set(id, running);
486
+ try {
487
+ await this.store.create(record, { command, input, context });
488
+ }
489
+ catch (error) {
490
+ this.running.delete(id);
491
+ if (error instanceof TaskStoreError &&
492
+ (error.kind === 'owner-limit' || error.kind === 'total-limit')) {
493
+ return resultContent(failure(taskLimitError()), true);
494
+ }
495
+ return resultContent(failure({
496
+ code: ErrorCodes.INTERNAL_ERROR,
497
+ message: 'The task could not be recorded, so nothing ran',
498
+ suggestion: 'Retry later.',
499
+ retryable: true,
500
+ }), true);
501
+ }
502
+ let latestProgress;
503
+ let hasProgress = false;
504
+ const verifiedCredentials = context.credentials && typeof context.credentials === 'object'
505
+ ? cloneVerifiedCredentials(context.credentials)
506
+ : undefined;
507
+ const taskContext = cloneTaskContext(verifiedCredentials ? { ...context, credentials: verifiedCredentials } : context, running.controller.signal, (message) => {
508
+ if (typeof message === 'string') {
509
+ latestProgress = message;
510
+ hasProgress = true;
511
+ }
512
+ });
513
+ const takeProgress = () => {
514
+ if (!hasProgress)
515
+ return undefined;
516
+ hasProgress = false;
517
+ const msg = latestProgress;
518
+ latestProgress = undefined;
519
+ return msg;
520
+ };
521
+ const tokenDeadlineMs = expiresAtSeconds !== undefined ? expiresAtSeconds * 1000 : undefined;
522
+ const ttlDeadlineMs = record.createdAt + record.ttlMs;
523
+ void this.runTask({
524
+ id,
525
+ owner,
526
+ commandName: command.name,
527
+ mutation: command.mutation === true,
528
+ input,
529
+ context: taskContext,
530
+ running,
531
+ takeProgress,
532
+ tokenDeadlineMs,
533
+ ttlDeadlineMs,
534
+ verifiedCredentials,
535
+ });
536
+ throw new CreateTaskSignal(wireCreateTask(record));
537
+ }
538
+ async runTask(job) {
539
+ let outcome;
540
+ try {
541
+ outcome = await this.driveTask(job);
542
+ }
543
+ catch {
544
+ outcome = { kind: 'internal' };
545
+ }
546
+ finally {
547
+ this.running.delete(job.id);
548
+ if (job.verifiedCredentials) {
549
+ unbrandVerifiedCredentials(job.verifiedCredentials);
550
+ }
551
+ }
552
+ const now = this.clock.now();
553
+ let change;
554
+ if (outcome.kind === 'finished') {
555
+ change = completionChange(outcome.result, this.options.maxResultBytes, now);
556
+ }
557
+ else if (outcome.kind === 'internal') {
558
+ change = { kind: 'failed', error: internalErrorObject(), at: now };
559
+ }
560
+ else if (outcome.stop === 'cancelled') {
561
+ change = { kind: 'cancelled', at: now };
562
+ }
563
+ else if (outcome.stop === 'token-expired') {
564
+ change = completionChange(failure(tokenExpiredError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now);
565
+ }
566
+ else if (outcome.stop === 'ttl-ended') {
567
+ await this.store.expire(now).catch(() => { });
568
+ return;
569
+ }
570
+ else {
571
+ // 'lost': another process or server shutdown ended it; write nothing.
572
+ return;
573
+ }
574
+ for (let attempt = 0; attempt < 3; attempt++) {
575
+ try {
576
+ await this.store.update(job.id, job.owner, change);
577
+ break;
578
+ }
579
+ catch {
580
+ if (attempt < 2) {
581
+ await new Promise((resolve) => setTimeout(resolve, Math.min(this.options.checkIntervalMs, MAX_TIMEOUT_MS)));
582
+ }
583
+ }
584
+ }
585
+ }
586
+ async driveTask(job) {
587
+ const initialStop = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now()) ?? job.running.reason;
588
+ if (initialStop !== undefined) {
589
+ return { kind: 'stopped', stop: initialStop, stage: 'not-started' };
590
+ }
591
+ let execSettled = false;
592
+ let execResult;
593
+ let execFailed = false;
594
+ const execPromise = Promise.resolve()
595
+ .then(() => this.executeCommand(job.commandName, job.input, job.context))
596
+ .then((result) => {
597
+ execSettled = true;
598
+ execResult = result;
599
+ return 'exec';
600
+ }, () => {
601
+ execSettled = true;
602
+ execFailed = true;
603
+ return 'exec';
604
+ });
605
+ const stoppedPromise = new Promise((resolve) => {
606
+ if (job.running.controller.signal.aborted) {
607
+ resolve('stopped');
608
+ }
609
+ else {
610
+ job.running.controller.signal.addEventListener('abort', () => resolve('stopped'), {
611
+ once: true,
612
+ });
613
+ }
614
+ });
615
+ const stopReason = () => job.running.reason;
616
+ for (;;) {
617
+ if (stopReason() === 'lost') {
618
+ return { kind: 'stopped', stop: 'lost', stage: 'running' };
619
+ }
620
+ if (execSettled) {
621
+ if (execFailed || !execResult)
622
+ return { kind: 'internal' };
623
+ const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now());
624
+ return due !== undefined
625
+ ? { kind: 'stopped', stop: due, stage: 'finished' }
626
+ : { kind: 'finished', result: execResult };
627
+ }
628
+ const now = this.clock.now();
629
+ const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, now);
630
+ if (due !== undefined) {
631
+ job.running.stop(due);
632
+ }
633
+ if (stopReason() === undefined) {
634
+ const message = job.takeProgress();
635
+ if (message !== undefined) {
636
+ await this.store
637
+ .update(job.id, job.owner, { kind: 'progress', message, at: now })
638
+ .catch(() => { });
639
+ }
640
+ if (this.store.heartbeat) {
641
+ await this.store.heartbeat(job.id, job.owner, now).catch(() => { });
642
+ }
643
+ try {
644
+ const current = await this.store.get(job.id, job.owner);
645
+ if (!current || isTaskExpired(current, now)) {
646
+ job.running.stop('ttl-ended');
647
+ }
648
+ else if (isTerminalTaskStatus(current.status)) {
649
+ job.running.stop('lost');
650
+ }
651
+ else if (current.cancelRequested) {
652
+ job.running.stop('cancelled');
653
+ }
654
+ }
655
+ catch {
656
+ // Transient store read failure: try again on the next check.
657
+ }
658
+ }
659
+ const reason = stopReason();
660
+ if (reason === 'lost' || reason === 'ttl-ended') {
661
+ return { kind: 'stopped', stop: reason, stage: 'running' };
662
+ }
663
+ if (execSettled)
664
+ continue;
665
+ if (reason !== undefined) {
666
+ return { kind: 'stopped', stop: reason, stage: 'running' };
667
+ }
668
+ const nearest = job.tokenDeadlineMs !== undefined
669
+ ? Math.min(job.tokenDeadlineMs, job.ttlDeadlineMs)
670
+ : job.ttlDeadlineMs;
671
+ const until = Math.max(1, nearest - now);
672
+ const waitMs = Math.min(this.options.checkIntervalMs, until, MAX_TIMEOUT_MS);
673
+ let timer;
674
+ const tickPromise = new Promise((resolve) => {
675
+ timer = setTimeout(() => resolve('tick'), waitMs);
676
+ });
677
+ try {
678
+ await Promise.race([execPromise, stoppedPromise, tickPromise]);
679
+ }
680
+ finally {
681
+ if (timer !== undefined)
682
+ clearTimeout(timer);
683
+ }
684
+ }
685
+ }
686
+ }
687
+ //# sourceMappingURL=tasks-runtime.js.map