keryx 0.48.1 → 0.49.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.
- package/classes/Action.ts +93 -0
- package/config/server/mcp.ts +9 -0
- package/index.ts +7 -1
- package/initializers/mcp.ts +5 -0
- package/lua/update-mcp-task.lua +19 -0
- package/package.json +1 -1
- package/servers/web.ts +17 -8
- package/util/mcpServer.ts +242 -133
- package/util/mcpTasks.ts +599 -0
- package/util/mcpToolResult.ts +101 -0
- package/util/webRouting.ts +32 -13
package/util/mcpTasks.ts
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type CreateTaskOptions,
|
|
3
|
+
isTerminal,
|
|
4
|
+
type TaskStore,
|
|
5
|
+
} from "@modelcontextprotocol/sdk/experimental/tasks";
|
|
6
|
+
import {
|
|
7
|
+
type CallToolResult,
|
|
8
|
+
ErrorCode,
|
|
9
|
+
McpError,
|
|
10
|
+
type Request,
|
|
11
|
+
type RequestId,
|
|
12
|
+
type Task,
|
|
13
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
14
|
+
import { createHash, randomUUID } from "crypto";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
import { api, logger } from "../api";
|
|
17
|
+
import type { Action, McpTaskState, McpTaskStatus } from "../classes/Action";
|
|
18
|
+
import { CONNECTION_TYPE, Connection } from "../classes/Connection";
|
|
19
|
+
import { config } from "../config";
|
|
20
|
+
import type { McpSessionAuth } from "./mcpServer";
|
|
21
|
+
import { toCallToolResult, toolErrorResult } from "./mcpToolResult";
|
|
22
|
+
|
|
23
|
+
const UPDATE_MCP_TASK_LUA = await Bun.file(
|
|
24
|
+
join(import.meta.dir, "..", "lua", "update-mcp-task.lua"),
|
|
25
|
+
).text();
|
|
26
|
+
|
|
27
|
+
/** How many tasks one `tasks/list` page holds. */
|
|
28
|
+
export const MCP_TASK_LIST_PAGE_SIZE = 50;
|
|
29
|
+
|
|
30
|
+
/** How many times a task write re-reads and retries after losing a race. */
|
|
31
|
+
const MAX_UPDATE_ATTEMPTS = 5;
|
|
32
|
+
|
|
33
|
+
/** Redis key for one task record. */
|
|
34
|
+
export function mcpTaskKey(taskId: string): string {
|
|
35
|
+
return `mcp:task:${taskId}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Redis key for an owner's task index (a sorted set of task ids by creation time). */
|
|
39
|
+
function mcpTaskIndexKey(ownerKey: string): string {
|
|
40
|
+
return `mcp:tasks:${ownerKey}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Who a task belongs to. Tasks are bound to the authenticated principal — the
|
|
45
|
+
* OAuth client **and** the user — rather than to the `Mcp-Session-Id`, so a
|
|
46
|
+
* client that reconnects (a new session, possibly on another node) still sees
|
|
47
|
+
* its tasks, and nobody else ever does. An anonymous session has no principal,
|
|
48
|
+
* so its tasks are bound to the session itself.
|
|
49
|
+
*/
|
|
50
|
+
export type McpTaskOwner = {
|
|
51
|
+
/** Opaque, stable key for the principal (a hash; safe in a Redis key). */
|
|
52
|
+
key: string;
|
|
53
|
+
/** The session's auth context, used to act as the owner on later checks. */
|
|
54
|
+
auth: McpSessionAuth;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Derive the {@link McpTaskOwner} for a session's auth context.
|
|
59
|
+
*
|
|
60
|
+
* @param auth - The session's captured auth context.
|
|
61
|
+
* @param anonymous - Whether the session is anonymous.
|
|
62
|
+
* @param sessionId - The session id; the binding for anonymous sessions.
|
|
63
|
+
* @returns The owner, or `undefined` for an anonymous session with no id yet.
|
|
64
|
+
*/
|
|
65
|
+
export function mcpTaskOwnerFor(
|
|
66
|
+
auth: McpSessionAuth,
|
|
67
|
+
anonymous: boolean,
|
|
68
|
+
sessionId: string | undefined,
|
|
69
|
+
): McpTaskOwner | undefined {
|
|
70
|
+
let principal: string;
|
|
71
|
+
if (anonymous) {
|
|
72
|
+
if (!sessionId) return undefined;
|
|
73
|
+
principal = JSON.stringify(["session", sessionId]);
|
|
74
|
+
} else {
|
|
75
|
+
principal = JSON.stringify([
|
|
76
|
+
"client",
|
|
77
|
+
auth.clientId,
|
|
78
|
+
auth.userId == null ? null : String(auth.userId),
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
key: createHash("sha256").update(principal).digest("hex"),
|
|
83
|
+
auth,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A task as persisted in Redis. */
|
|
88
|
+
type McpTaskRecord = {
|
|
89
|
+
/** The MCP task object served by `tasks/get` and `tasks/list`. */
|
|
90
|
+
task: Task;
|
|
91
|
+
/** {@link McpTaskOwner.key} of the principal that created it. */
|
|
92
|
+
owner: string;
|
|
93
|
+
/** Name of the action the task runs. */
|
|
94
|
+
action: string;
|
|
95
|
+
/** A durable task's handle: what the action returned when the task was created. */
|
|
96
|
+
handle?: unknown;
|
|
97
|
+
/** The `tasks/result` payload, once the task is terminal. */
|
|
98
|
+
result?: CallToolResult;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Background runs of managed tasks still in flight on this node. */
|
|
102
|
+
const inFlight = new Set<Promise<void>>();
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Wait for every managed task still running in the background on this node to
|
|
106
|
+
* record its result. Called when the MCP initializer stops, so a shutdown does
|
|
107
|
+
* not strand a task as `working` when its result was moments away.
|
|
108
|
+
*/
|
|
109
|
+
export async function settleMcpTasks(): Promise<void> {
|
|
110
|
+
while (inFlight.size > 0) await Promise.allSettled([...inFlight]);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Build a connection that acts as a task's owner, for a durable task's
|
|
115
|
+
* `status` / `cancel` callbacks. Like the channel-authorization probe, its
|
|
116
|
+
* session lives in memory only, so polling a task writes no session to Redis.
|
|
117
|
+
*
|
|
118
|
+
* @param auth - The owner's auth context.
|
|
119
|
+
*/
|
|
120
|
+
function createOwnerConnection(auth: McpSessionAuth): Connection {
|
|
121
|
+
const connection = new Connection(
|
|
122
|
+
CONNECTION_TYPE.MCP,
|
|
123
|
+
auth.ip ?? "unknown",
|
|
124
|
+
randomUUID(),
|
|
125
|
+
);
|
|
126
|
+
connection.session = {
|
|
127
|
+
id: connection.sessionId,
|
|
128
|
+
cookieName: config.session.cookieName,
|
|
129
|
+
createdAt: Date.now(),
|
|
130
|
+
data: auth.userId != null ? { userId: auth.userId } : {},
|
|
131
|
+
};
|
|
132
|
+
connection.sessionLoaded = true;
|
|
133
|
+
return connection;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The `tasks/result` payload for a task cancelled before it produced one. */
|
|
137
|
+
function cancelledResult(statusMessage?: string): CallToolResult {
|
|
138
|
+
return toolErrorResult({
|
|
139
|
+
message: statusMessage ?? "Task was cancelled.",
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Whether a request asked for task-augmented execution (`params.task` set).
|
|
145
|
+
* Not the SDK's `isTaskAugmentedRequestParams`: `task` is optional in the
|
|
146
|
+
* schema it validates against, so it is true of every request.
|
|
147
|
+
*/
|
|
148
|
+
function asksForTask(request: Request): boolean {
|
|
149
|
+
const task = (request.params as { task?: unknown } | undefined)?.task;
|
|
150
|
+
return task !== null && typeof task === "object";
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The status a finished run's result implies. */
|
|
154
|
+
function statusOf(result: CallToolResult): "completed" | "failed" {
|
|
155
|
+
return result.isError ? "failed" : "completed";
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function findAction(name: string): Action | undefined {
|
|
159
|
+
return api.actions.actions.find((a: Action) => a.name === name);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The `TaskStore` behind MCP Tasks — one per `McpServer` (that is, per
|
|
164
|
+
* session), backed by Redis so a task can be read from any node and outlive the
|
|
165
|
+
* session that created it.
|
|
166
|
+
*
|
|
167
|
+
* The SDK answers `tasks/get`, `tasks/result`, `tasks/list`, and `tasks/cancel`
|
|
168
|
+
* from this store, passing at most the session id. Every read is therefore
|
|
169
|
+
* scoped to the session's **owner** (resolved fresh on each call, so a session
|
|
170
|
+
* that signs in mid-way is re-scoped), and a task owned by anybody else reads
|
|
171
|
+
* exactly like an unknown id.
|
|
172
|
+
*
|
|
173
|
+
* Two task kinds share the store (see `McpTaskConfig`): a **managed** task's
|
|
174
|
+
* result is written by its background run; a **durable** task's state is
|
|
175
|
+
* pulled from the action's `status` callback whenever a non-terminal task is
|
|
176
|
+
* read. Every write is a compare-and-set, so a terminal status is final.
|
|
177
|
+
*/
|
|
178
|
+
export class McpTaskStore implements TaskStore {
|
|
179
|
+
/** Tasks minted by `createTask` and not yet claimed by the tool handler. */
|
|
180
|
+
private minted = new Map<string, { task: Task; inline: boolean }>();
|
|
181
|
+
/** Results of plain (non-task) calls to `optional` tools; never persisted. */
|
|
182
|
+
private inline = new Map<string, { task: Task; result: CallToolResult }>();
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* @param resolveOwner - Returns the session's current owner, or `undefined`
|
|
186
|
+
* if it has none (no auth context): every read then fails closed.
|
|
187
|
+
*/
|
|
188
|
+
constructor(private readonly resolveOwner: () => McpTaskOwner | undefined) {}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Mint a task id for a `tools/call`. Nothing is persisted yet: the tool
|
|
192
|
+
* handler {@link claim}s the task and then either finishes it inline or
|
|
193
|
+
* {@link save}s it. This is also where a plain call to an `optional` tool is
|
|
194
|
+
* told apart from a task-augmented one — the SDK routes both through task
|
|
195
|
+
* creation, and only the original request says which it was.
|
|
196
|
+
*
|
|
197
|
+
* @param taskParams - The client's requested `ttl` (ms) and our poll interval.
|
|
198
|
+
* @param _requestId - The JSON-RPC request id (unused).
|
|
199
|
+
* @param request - The original `tools/call` request.
|
|
200
|
+
*/
|
|
201
|
+
async createTask(
|
|
202
|
+
taskParams: CreateTaskOptions,
|
|
203
|
+
_requestId: RequestId,
|
|
204
|
+
request: Request,
|
|
205
|
+
): Promise<Task> {
|
|
206
|
+
const now = new Date().toISOString();
|
|
207
|
+
const maxTtl = config.server.mcp.taskMaxTtl * 1000;
|
|
208
|
+
const requested = taskParams.ttl ?? config.server.mcp.taskTtl * 1000;
|
|
209
|
+
const task: Task = {
|
|
210
|
+
taskId: randomUUID(),
|
|
211
|
+
status: "working",
|
|
212
|
+
ttl: Math.max(1000, Math.min(requested, maxTtl)),
|
|
213
|
+
createdAt: now,
|
|
214
|
+
lastUpdatedAt: now,
|
|
215
|
+
pollInterval:
|
|
216
|
+
taskParams.pollInterval ?? config.server.mcp.taskPollInterval,
|
|
217
|
+
};
|
|
218
|
+
this.minted.set(task.taskId, {
|
|
219
|
+
task,
|
|
220
|
+
inline: !asksForTask(request),
|
|
221
|
+
});
|
|
222
|
+
return task;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Take a task minted by {@link createTask} for the current call.
|
|
227
|
+
*
|
|
228
|
+
* @param taskId - The id `createTask` returned.
|
|
229
|
+
* @returns The task, and whether the call was a plain (non-task) call that
|
|
230
|
+
* must be answered inline.
|
|
231
|
+
*/
|
|
232
|
+
claim(taskId: string): { task: Task; inline: boolean } {
|
|
233
|
+
const minted = this.minted.get(taskId);
|
|
234
|
+
if (!minted) {
|
|
235
|
+
throw new McpError(ErrorCode.InternalError, `Unknown task ${taskId}`);
|
|
236
|
+
}
|
|
237
|
+
this.minted.delete(taskId);
|
|
238
|
+
return minted;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Finish a plain call to an `optional` tool. The SDK still polls the task it
|
|
243
|
+
* made for the call, so hand it a terminal task whose result is held in
|
|
244
|
+
* memory until the SDK collects it — immediately, in the same request.
|
|
245
|
+
*
|
|
246
|
+
* @param task - The claimed task.
|
|
247
|
+
* @param result - The tool result to return to the caller.
|
|
248
|
+
* @returns The terminal task.
|
|
249
|
+
*/
|
|
250
|
+
finishInline(task: Task, result: CallToolResult): Task {
|
|
251
|
+
const finished: Task = { ...task, status: statusOf(result) };
|
|
252
|
+
this.inline.set(task.taskId, { task: finished, result });
|
|
253
|
+
return finished;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Persist a new task for the session's owner and add it to the owner's index.
|
|
258
|
+
*
|
|
259
|
+
* @param task - The claimed task, with the status it starts in.
|
|
260
|
+
* @param action - The action the task runs.
|
|
261
|
+
* @param fields - A durable task's `handle`, or a `result` if it is already terminal.
|
|
262
|
+
* @returns The persisted task.
|
|
263
|
+
* @throws {McpError} If the session has no owner to bind the task to.
|
|
264
|
+
*/
|
|
265
|
+
async save(
|
|
266
|
+
task: Task,
|
|
267
|
+
action: Action,
|
|
268
|
+
fields: { handle?: unknown; result?: CallToolResult } = {},
|
|
269
|
+
): Promise<Task> {
|
|
270
|
+
const owner = this.resolveOwner();
|
|
271
|
+
if (!owner) {
|
|
272
|
+
throw new McpError(
|
|
273
|
+
ErrorCode.InvalidRequest,
|
|
274
|
+
"This session cannot create tasks.",
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
const record: McpTaskRecord = {
|
|
278
|
+
task,
|
|
279
|
+
owner: owner.key,
|
|
280
|
+
action: action.name,
|
|
281
|
+
...fields,
|
|
282
|
+
};
|
|
283
|
+
const indexKey = mcpTaskIndexKey(owner.key);
|
|
284
|
+
await api.redis.redis
|
|
285
|
+
.multi()
|
|
286
|
+
.set(mcpTaskKey(task.taskId), JSON.stringify(record), "PX", task.ttl ?? 0)
|
|
287
|
+
.zadd(indexKey, Date.parse(task.createdAt), task.taskId)
|
|
288
|
+
.pexpire(indexKey, config.server.mcp.taskMaxTtl * 1000)
|
|
289
|
+
.exec();
|
|
290
|
+
return task;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Track a managed task's background run on this node, recording its result
|
|
295
|
+
* when it settles. A run that throws records a failure rather than leaving the
|
|
296
|
+
* task `working` until it expires.
|
|
297
|
+
*
|
|
298
|
+
* @param taskId - The task the run belongs to.
|
|
299
|
+
* @param run - Runs the action and renders its tool result.
|
|
300
|
+
*/
|
|
301
|
+
runInBackground(taskId: string, run: () => Promise<CallToolResult>): void {
|
|
302
|
+
const settled = (async () => {
|
|
303
|
+
let result: CallToolResult;
|
|
304
|
+
try {
|
|
305
|
+
result = await run();
|
|
306
|
+
} catch (error) {
|
|
307
|
+
result = toolErrorResult({
|
|
308
|
+
message: error instanceof Error ? error.message : String(error),
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
await this.finish(taskId, result);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
logger.error(`Failed to record result of MCP task ${taskId}: ${error}`);
|
|
315
|
+
}
|
|
316
|
+
})();
|
|
317
|
+
inFlight.add(settled);
|
|
318
|
+
settled.finally(() => inFlight.delete(settled));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Record a terminal result unless the task is already terminal (e.g. it was
|
|
323
|
+
* cancelled while running, in which case the result is discarded). Reads the
|
|
324
|
+
* record without an owner check: the background run is the owner's own call.
|
|
325
|
+
*/
|
|
326
|
+
private async finish(taskId: string, result: CallToolResult): Promise<void> {
|
|
327
|
+
await this.update(taskId, undefined, (record) => ({
|
|
328
|
+
...record,
|
|
329
|
+
task: this.advance(record.task, statusOf(result)),
|
|
330
|
+
result,
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Read a task for `tasks/get` (and while `tasks/result` waits). A durable
|
|
336
|
+
* task that is not yet terminal is refreshed from its action's `status`
|
|
337
|
+
* callback first.
|
|
338
|
+
*
|
|
339
|
+
* @param taskId - The task id.
|
|
340
|
+
* @returns The task, or `null` if it is unknown, expired, or not this owner's.
|
|
341
|
+
*/
|
|
342
|
+
async getTask(taskId: string): Promise<Task | null> {
|
|
343
|
+
const inline = this.inline.get(taskId);
|
|
344
|
+
if (inline) return inline.task;
|
|
345
|
+
|
|
346
|
+
const owner = this.resolveOwner();
|
|
347
|
+
if (!owner) return null;
|
|
348
|
+
const record = await this.read(taskId, owner);
|
|
349
|
+
if (!record) return null;
|
|
350
|
+
if (isTerminal(record.task.status)) return record.task;
|
|
351
|
+
|
|
352
|
+
const action = findAction(record.action);
|
|
353
|
+
const status = action?.mcp?.task?.status;
|
|
354
|
+
if (!action || !status) return record.task;
|
|
355
|
+
|
|
356
|
+
let state: McpTaskState;
|
|
357
|
+
const connection = createOwnerConnection(owner.auth);
|
|
358
|
+
try {
|
|
359
|
+
state = await status(record.handle, connection);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
logger.warn(
|
|
362
|
+
`MCP task ${taskId} (${record.action}) status check failed: ${error}`,
|
|
363
|
+
);
|
|
364
|
+
return record.task;
|
|
365
|
+
} finally {
|
|
366
|
+
connection.destroy();
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (
|
|
370
|
+
state.status === record.task.status &&
|
|
371
|
+
state.statusMessage === record.task.statusMessage
|
|
372
|
+
) {
|
|
373
|
+
return record.task;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
let result: CallToolResult | undefined;
|
|
377
|
+
if (state.status === "cancelled") {
|
|
378
|
+
result = cancelledResult(state.statusMessage);
|
|
379
|
+
} else if (state.status === "completed" || state.status === "failed") {
|
|
380
|
+
result = await toCallToolResult(
|
|
381
|
+
action,
|
|
382
|
+
state.result !== undefined ? state.result : record.handle,
|
|
383
|
+
);
|
|
384
|
+
if (state.status === "failed") result = { ...result, isError: true };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const updated = await this.update(taskId, owner, (current) => ({
|
|
388
|
+
...current,
|
|
389
|
+
task: this.advance(current.task, state.status, state.statusMessage),
|
|
390
|
+
...(result ? { result } : {}),
|
|
391
|
+
}));
|
|
392
|
+
return updated?.task ?? null;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* The `tasks/result` payload of a terminal task. The SDK only asks once the
|
|
397
|
+
* task is terminal.
|
|
398
|
+
*
|
|
399
|
+
* @param taskId - The task id.
|
|
400
|
+
* @throws {McpError} If the task is unknown, not this owner's, or not finished.
|
|
401
|
+
*/
|
|
402
|
+
async getTaskResult(taskId: string): Promise<CallToolResult> {
|
|
403
|
+
const inline = this.inline.get(taskId);
|
|
404
|
+
if (inline) {
|
|
405
|
+
this.inline.delete(taskId);
|
|
406
|
+
return inline.result;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const owner = this.resolveOwner();
|
|
410
|
+
const record = owner ? await this.read(taskId, owner) : null;
|
|
411
|
+
if (!record) {
|
|
412
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
413
|
+
}
|
|
414
|
+
if (record.result) return record.result;
|
|
415
|
+
if (record.task.status === "cancelled") {
|
|
416
|
+
return cancelledResult(record.task.statusMessage);
|
|
417
|
+
}
|
|
418
|
+
throw new McpError(
|
|
419
|
+
ErrorCode.InvalidParams,
|
|
420
|
+
`Task ${taskId} has no result yet (status: ${record.task.status})`,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Store a task's final result. Part of the SDK's `TaskStore` contract;
|
|
426
|
+
* Keryx's own tool handlers record results through {@link runInBackground}.
|
|
427
|
+
*/
|
|
428
|
+
async storeTaskResult(
|
|
429
|
+
taskId: string,
|
|
430
|
+
status: "completed" | "failed",
|
|
431
|
+
result: CallToolResult,
|
|
432
|
+
): Promise<void> {
|
|
433
|
+
const owner = this.resolveOwner();
|
|
434
|
+
if (!owner) return;
|
|
435
|
+
await this.update(taskId, owner, (record) => ({
|
|
436
|
+
...record,
|
|
437
|
+
task: this.advance(record.task, status),
|
|
438
|
+
result,
|
|
439
|
+
}));
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Change a task's status. The SDK calls this for `tasks/cancel` (after
|
|
444
|
+
* checking the task is not terminal), which is where a durable task's
|
|
445
|
+
* `cancel` callback runs — before the task is marked, so a callback that
|
|
446
|
+
* throws leaves the task running and the client sees the error.
|
|
447
|
+
*
|
|
448
|
+
* @param taskId - The task id.
|
|
449
|
+
* @param status - The new status.
|
|
450
|
+
* @param statusMessage - Optional detail for the client.
|
|
451
|
+
* @throws {McpError} If the task is unknown or not this owner's, or the
|
|
452
|
+
* action's `cancel` callback refused.
|
|
453
|
+
*/
|
|
454
|
+
async updateTaskStatus(
|
|
455
|
+
taskId: string,
|
|
456
|
+
status: McpTaskStatus,
|
|
457
|
+
statusMessage?: string,
|
|
458
|
+
): Promise<void> {
|
|
459
|
+
const owner = this.resolveOwner();
|
|
460
|
+
const record = owner ? await this.read(taskId, owner) : null;
|
|
461
|
+
if (!owner || !record) {
|
|
462
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
463
|
+
}
|
|
464
|
+
if (isTerminal(record.task.status)) return;
|
|
465
|
+
|
|
466
|
+
if (status === "cancelled") {
|
|
467
|
+
const cancel = findAction(record.action)?.mcp?.task?.cancel;
|
|
468
|
+
if (cancel) {
|
|
469
|
+
const connection = createOwnerConnection(owner.auth);
|
|
470
|
+
try {
|
|
471
|
+
await cancel(record.handle, connection);
|
|
472
|
+
} catch (error) {
|
|
473
|
+
throw new McpError(
|
|
474
|
+
ErrorCode.InvalidRequest,
|
|
475
|
+
`Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`,
|
|
476
|
+
);
|
|
477
|
+
} finally {
|
|
478
|
+
connection.destroy();
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
await this.update(taskId, owner, (current) => ({
|
|
484
|
+
...current,
|
|
485
|
+
task: this.advance(current.task, status, statusMessage),
|
|
486
|
+
...(status === "cancelled"
|
|
487
|
+
? { result: cancelledResult(statusMessage) }
|
|
488
|
+
: {}),
|
|
489
|
+
}));
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* List the owner's tasks, newest first, with their last recorded status
|
|
494
|
+
* (`tasks/get` is what refreshes a durable task). Expired entries are pruned
|
|
495
|
+
* from the index as they are found.
|
|
496
|
+
*
|
|
497
|
+
* @param cursor - The `nextCursor` of the previous page, if any.
|
|
498
|
+
* @throws {Error} If `cursor` is not one this store issued.
|
|
499
|
+
*/
|
|
500
|
+
async listTasks(
|
|
501
|
+
cursor?: string,
|
|
502
|
+
): Promise<{ tasks: Task[]; nextCursor?: string }> {
|
|
503
|
+
const owner = this.resolveOwner();
|
|
504
|
+
if (!owner) return { tasks: [] };
|
|
505
|
+
const offset = cursor === undefined ? 0 : Number(cursor);
|
|
506
|
+
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
507
|
+
throw new Error(`Invalid cursor: ${cursor}`);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const indexKey = mcpTaskIndexKey(owner.key);
|
|
511
|
+
const ids = await api.redis.redis.zrevrange(
|
|
512
|
+
indexKey,
|
|
513
|
+
offset,
|
|
514
|
+
offset + MCP_TASK_LIST_PAGE_SIZE - 1,
|
|
515
|
+
);
|
|
516
|
+
if (ids.length === 0) return { tasks: [] };
|
|
517
|
+
|
|
518
|
+
const raws = await api.redis.redis.mget(ids.map(mcpTaskKey));
|
|
519
|
+
const tasks: Task[] = [];
|
|
520
|
+
const expired: string[] = [];
|
|
521
|
+
raws.forEach((raw, i) => {
|
|
522
|
+
const record = raw ? (JSON.parse(raw) as McpTaskRecord) : null;
|
|
523
|
+
if (record && record.owner === owner.key) tasks.push(record.task);
|
|
524
|
+
else expired.push(ids[i]);
|
|
525
|
+
});
|
|
526
|
+
if (expired.length > 0) await api.redis.redis.zrem(indexKey, ...expired);
|
|
527
|
+
|
|
528
|
+
// Pruned entries shift everything after them up, so the next page starts
|
|
529
|
+
// that much earlier.
|
|
530
|
+
return ids.length === MCP_TASK_LIST_PAGE_SIZE
|
|
531
|
+
? { tasks, nextCursor: String(offset + ids.length - expired.length) }
|
|
532
|
+
: { tasks };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** The task after a status change, stamped with the time of the change. */
|
|
536
|
+
private advance(
|
|
537
|
+
task: Task,
|
|
538
|
+
status: McpTaskStatus,
|
|
539
|
+
statusMessage?: string,
|
|
540
|
+
): Task {
|
|
541
|
+
const next: Task = {
|
|
542
|
+
...task,
|
|
543
|
+
status,
|
|
544
|
+
lastUpdatedAt: new Date().toISOString(),
|
|
545
|
+
};
|
|
546
|
+
if (statusMessage !== undefined) next.statusMessage = statusMessage;
|
|
547
|
+
else delete next.statusMessage;
|
|
548
|
+
return next;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Read a record, or `null` if it is missing or belongs to someone else. */
|
|
552
|
+
private async read(
|
|
553
|
+
taskId: string,
|
|
554
|
+
owner: McpTaskOwner,
|
|
555
|
+
): Promise<McpTaskRecord | null> {
|
|
556
|
+
const raw = await api.redis.redis.get(mcpTaskKey(taskId));
|
|
557
|
+
if (!raw) return null;
|
|
558
|
+
const record = JSON.parse(raw) as McpTaskRecord;
|
|
559
|
+
return record.owner === owner.key ? record : null;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Compare-and-set a record, retrying on a lost race. A record that is
|
|
564
|
+
* already terminal is never rewritten.
|
|
565
|
+
*
|
|
566
|
+
* @param taskId - The task id.
|
|
567
|
+
* @param owner - Restrict to this owner's record; `undefined` skips the check
|
|
568
|
+
* (only for a background run writing its own task).
|
|
569
|
+
* @param mutate - Builds the new record from the current one.
|
|
570
|
+
* @returns The record as written, the terminal record if it already was, or
|
|
571
|
+
* `null` if the task is gone.
|
|
572
|
+
*/
|
|
573
|
+
private async update(
|
|
574
|
+
taskId: string,
|
|
575
|
+
owner: McpTaskOwner | undefined,
|
|
576
|
+
mutate: (record: McpTaskRecord) => McpTaskRecord,
|
|
577
|
+
): Promise<McpTaskRecord | null> {
|
|
578
|
+
for (let attempt = 0; attempt < MAX_UPDATE_ATTEMPTS; attempt++) {
|
|
579
|
+
const raw = await api.redis.redis.get(mcpTaskKey(taskId));
|
|
580
|
+
if (!raw) return null;
|
|
581
|
+
const record = JSON.parse(raw) as McpTaskRecord;
|
|
582
|
+
if (owner && record.owner !== owner.key) return null;
|
|
583
|
+
if (isTerminal(record.task.status)) return record;
|
|
584
|
+
const next = mutate(record);
|
|
585
|
+
const written = await api.redis.redis.eval(
|
|
586
|
+
UPDATE_MCP_TASK_LUA,
|
|
587
|
+
1,
|
|
588
|
+
mcpTaskKey(taskId),
|
|
589
|
+
raw,
|
|
590
|
+
JSON.stringify(next),
|
|
591
|
+
);
|
|
592
|
+
if (written === 1) return next;
|
|
593
|
+
}
|
|
594
|
+
throw new McpError(
|
|
595
|
+
ErrorCode.InternalError,
|
|
596
|
+
`Task ${taskId} is being updated concurrently; try again.`,
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
import type { Action } from "../classes/Action";
|
|
3
|
+
import { MCP_RESPONSE_FORMAT } from "../classes/Action";
|
|
4
|
+
import { StreamingResponse } from "../classes/StreamingResponse";
|
|
5
|
+
import { UIResponse } from "../classes/UIResponse";
|
|
6
|
+
import { config } from "../config";
|
|
7
|
+
import { toMarkdown } from "./toMarkdown";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The `CallToolResult` for a failed action. Errors are always JSON, whatever the
|
|
11
|
+
* action's `mcp.responseFormat`, so an agent can parse them reliably.
|
|
12
|
+
*
|
|
13
|
+
* @param error - The error's message and, when known, its `ErrorType`.
|
|
14
|
+
*/
|
|
15
|
+
export function toolErrorResult(error: {
|
|
16
|
+
message: string;
|
|
17
|
+
type?: string;
|
|
18
|
+
}): CallToolResult {
|
|
19
|
+
return {
|
|
20
|
+
content: [
|
|
21
|
+
{
|
|
22
|
+
type: "text" as const,
|
|
23
|
+
text: JSON.stringify({ error: error.message, type: error.type }),
|
|
24
|
+
},
|
|
25
|
+
],
|
|
26
|
+
isError: true,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Render an action's response as an MCP `CallToolResult`. This is the single
|
|
32
|
+
* rendering used for a plain `tools/call` and for a task's `tasks/result`, so a
|
|
33
|
+
* client sees the same shape either way.
|
|
34
|
+
*
|
|
35
|
+
* - A {@link StreamingResponse} is drained into one text block; each chunk is
|
|
36
|
+
* also handed to `onChunk` (a plain call forwards it as a logging message).
|
|
37
|
+
* - A {@link UIResponse} carries its text and its `structuredContent`.
|
|
38
|
+
* - Anything else is JSON (or markdown, per `mcp.responseFormat`), and a plain
|
|
39
|
+
* object is promoted to `structuredContent` so MCP Apps can bind to it.
|
|
40
|
+
*
|
|
41
|
+
* @param action - The action that produced the response; its `mcp.responseFormat` applies.
|
|
42
|
+
* @param response - What the action returned.
|
|
43
|
+
* @param onChunk - Optional observer for each chunk of a streaming response.
|
|
44
|
+
*/
|
|
45
|
+
export async function toCallToolResult(
|
|
46
|
+
action: Action,
|
|
47
|
+
response: unknown,
|
|
48
|
+
onChunk?: (chunk: string) => void,
|
|
49
|
+
): Promise<CallToolResult> {
|
|
50
|
+
if (response instanceof StreamingResponse) {
|
|
51
|
+
const reader = response.stream.getReader();
|
|
52
|
+
const decoder = new TextDecoder();
|
|
53
|
+
let accumulated = "";
|
|
54
|
+
try {
|
|
55
|
+
while (true) {
|
|
56
|
+
const { done, value } = await reader.read();
|
|
57
|
+
if (done) break;
|
|
58
|
+
const chunk = decoder.decode(value);
|
|
59
|
+
accumulated += chunk;
|
|
60
|
+
onChunk?.(chunk);
|
|
61
|
+
}
|
|
62
|
+
} finally {
|
|
63
|
+
response.onClose?.();
|
|
64
|
+
}
|
|
65
|
+
return { content: [{ type: "text" as const, text: accumulated }] };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// MCP App responses carry both a text block (added to model context)
|
|
69
|
+
// and structuredContent (delivered to the app UI for rendering).
|
|
70
|
+
// ext-apps hosts render the UI from the tool's `_meta.ui.resourceUri`
|
|
71
|
+
// and the separate `ui://` resource — the content array stays text-only.
|
|
72
|
+
if (response instanceof UIResponse) {
|
|
73
|
+
return {
|
|
74
|
+
content: [{ type: "text" as const, text: response.text }],
|
|
75
|
+
structuredContent: response.structuredContent,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const format = action.mcp?.responseFormat ?? MCP_RESPONSE_FORMAT.JSON;
|
|
80
|
+
const text =
|
|
81
|
+
format === MCP_RESPONSE_FORMAT.MARKDOWN
|
|
82
|
+
? toMarkdown(response, {
|
|
83
|
+
maxDepth: config.server.mcp.markdownDepthLimit,
|
|
84
|
+
})
|
|
85
|
+
: JSON.stringify(response);
|
|
86
|
+
|
|
87
|
+
// Promote plain object responses to structuredContent so MCP Apps can
|
|
88
|
+
// bind without JSON.parse (same shape UIResponse already provides).
|
|
89
|
+
const structuredContent =
|
|
90
|
+
format === MCP_RESPONSE_FORMAT.JSON &&
|
|
91
|
+
response !== null &&
|
|
92
|
+
typeof response === "object" &&
|
|
93
|
+
!Array.isArray(response)
|
|
94
|
+
? (response as Record<string, unknown>)
|
|
95
|
+
: undefined;
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
content: [{ type: "text" as const, text }],
|
|
99
|
+
...(structuredContent ? { structuredContent } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|