keryx 0.48.2 → 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 CHANGED
@@ -75,6 +75,94 @@ export type McpUiConfig = {
75
75
  domain?: string;
76
76
  };
77
77
 
78
+ /**
79
+ * The lifecycle states of an MCP task (MCP `2025-11-25`). `completed`, `failed`,
80
+ * and `cancelled` are terminal: once a task reaches one it never changes again.
81
+ */
82
+ export type McpTaskStatus =
83
+ | "working"
84
+ | "input_required"
85
+ | "completed"
86
+ | "failed"
87
+ | "cancelled";
88
+
89
+ /**
90
+ * What an action's {@link McpTaskConfig.status} callback reports about a durable
91
+ * task. Keryx stores it and answers `tasks/get` from it.
92
+ */
93
+ export type McpTaskState = {
94
+ /** The task's current status. A terminal status is final. */
95
+ status: McpTaskStatus;
96
+ /** Optional human-readable detail, surfaced to the client as `statusMessage`. */
97
+ statusMessage?: string;
98
+ /**
99
+ * For a terminal status, the value `tasks/result` delivers. It is rendered
100
+ * exactly like an action response (honoring `mcp.responseFormat`), and a
101
+ * `failed` result is flagged `isError`. Defaults to the action's original
102
+ * response when omitted.
103
+ */
104
+ result?: unknown;
105
+ };
106
+
107
+ /**
108
+ * Publishes an MCP tool as **task-capable** (MCP Tasks, `2025-11-25`). A client
109
+ * can then call the tool with `task: { ttl }`, get a task id back immediately,
110
+ * and check on it later with `tasks/get`, `tasks/result`, `tasks/list`, and
111
+ * `tasks/cancel` — from the same session or a later one, on any node.
112
+ *
113
+ * There are two kinds of task:
114
+ *
115
+ * - **Managed** (no `status`): Keryx runs the action in the background, and the
116
+ * task ends when `run()` does. Use it for an action that is merely slow.
117
+ * - **Durable** (`status` set): `run()` starts work that lives in your own
118
+ * storage (a job row, a workflow execution) and returns a handle to it. The
119
+ * task stays `working` until `status(handle)` reports a terminal state, so it
120
+ * can outlive the request, the session, and the node that created it.
121
+ *
122
+ * @see {@link https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks}
123
+ */
124
+ export type McpTaskConfig = {
125
+ /**
126
+ * `"optional"`: a plain `tools/call` still runs the action and returns its
127
+ * response directly, exactly as without `task`; only a call that asks for a
128
+ * task gets one. `"required"`: the tool may only be called as a task.
129
+ */
130
+ support: "optional" | "required";
131
+ /**
132
+ * Suggested interval (ms) between a client's `tasks/get` polls. Also how
133
+ * often a blocked `tasks/result` re-checks. Defaults to
134
+ * `config.server.mcp.taskPollInterval`.
135
+ */
136
+ pollInterval?: number;
137
+ /**
138
+ * Makes the task **durable**: report its state from your own storage. Called
139
+ * on `tasks/get` (and while `tasks/result` waits) for as long as the task is
140
+ * non-terminal, never after.
141
+ *
142
+ * @param response - What the action's `run()` returned when the task was
143
+ * created — the handle to your work.
144
+ * @param connection - An MCP connection authenticated as the task's owner,
145
+ * so `connection.act(...)` runs the target action's middleware as that user.
146
+ * @returns The task's current state. A thrown error is logged and the task
147
+ * keeps its last known state, so a transient failure doesn't end it.
148
+ */
149
+ status?: (
150
+ response: any,
151
+ connection: Connection,
152
+ ) => Promise<McpTaskState> | McpTaskState;
153
+ /**
154
+ * Called on `tasks/cancel` for a non-terminal **durable** task, before it is
155
+ * marked `cancelled`. Throw to refuse: the client gets an error and the task
156
+ * keeps running. Without it, cancelling a durable task only stops tracking
157
+ * it. A managed task's background run is never interrupted; its result is
158
+ * discarded.
159
+ *
160
+ * @param response - What the action's `run()` returned when the task was created.
161
+ * @param connection - An MCP connection authenticated as the task's owner.
162
+ */
163
+ cancel?: (response: any, connection: Connection) => Promise<void> | void;
164
+ };
165
+
78
166
  export enum HTTP_METHOD {
79
167
  GET = "GET",
80
168
  POST = "POST",
@@ -145,6 +233,11 @@ export type McpActionConfig = {
145
233
  * `MCP_RESPONSE_FORMAT.MARKDOWN` returns a human-readable markdown rendering via `toMarkdown()`.
146
234
  */
147
235
  responseFormat?: MCP_RESPONSE_FORMAT;
236
+ /**
237
+ * Make the tool task-capable (MCP Tasks), so a client can start it and check
238
+ * on it later instead of holding one request open. See {@link McpTaskConfig}.
239
+ */
240
+ task?: McpTaskConfig;
148
241
  };
149
242
 
150
243
  export type ActionConstructorInputs = {
@@ -72,4 +72,13 @@ export const configServerMcp = {
72
72
  "MCP_ANONYMOUS_SESSION_TTL",
73
73
  60 * 60,
74
74
  ),
75
+ // MCP Tasks (`mcp.task`): how long a task record lives in Redis (seconds)
76
+ // when the client asks for no particular `ttl`, and the ceiling on the `ttl`
77
+ // a client may ask for. A task is forgotten once its TTL lapses, whatever its
78
+ // status — a durable task's own work carries on; only tracking stops.
79
+ taskTtl: await loadFromEnvIfSet("MCP_TASK_TTL", 60 * 60),
80
+ taskMaxTtl: await loadFromEnvIfSet("MCP_TASK_MAX_TTL", 60 * 60 * 24),
81
+ // Suggested gap (ms) between a client's `tasks/get` polls, unless the action
82
+ // sets `mcp.task.pollInterval`.
83
+ taskPollInterval: await loadFromEnvIfSet("MCP_TASK_POLL_INTERVAL", 1000),
75
84
  };
package/index.ts CHANGED
@@ -19,7 +19,13 @@ import "./initializers/signals";
19
19
  import "./initializers/swagger";
20
20
 
21
21
  export * from "./api";
22
- export type { ActionMiddleware, McpUiConfig } from "./classes/Action";
22
+ export type {
23
+ ActionMiddleware,
24
+ McpTaskConfig,
25
+ McpTaskState,
26
+ McpTaskStatus,
27
+ McpUiConfig,
28
+ } from "./classes/Action";
23
29
  export {
24
30
  HTTP_METHOD,
25
31
  MCP_APP_MIME_TYPE,
@@ -48,6 +48,7 @@ import {
48
48
  validateJsonRpcPayload,
49
49
  writeMcpSessionRecord,
50
50
  } from "../util/mcpServer";
51
+ import { settleMcpTasks } from "../util/mcpTasks";
51
52
  import type { PubSubMessage } from "./pubsub";
52
53
 
53
54
  type McpHandleRequest = (req: Request, ip: string) => Promise<Response>;
@@ -606,6 +607,10 @@ export class McpInitializer extends Initializer {
606
607
  async stop() {
607
608
  if (!config.server.mcp.enabled) return;
608
609
 
610
+ // Let managed MCP tasks running in the background record their results
611
+ // while Redis is still up, rather than leaving them `working` until expiry.
612
+ await settleMcpTasks();
613
+
609
614
  // Close all transports
610
615
  for (const { transport } of api.mcp.transports.values()) {
611
616
  try {
@@ -0,0 +1,19 @@
1
+ -- Compare-and-set one MCP task record, keeping its remaining TTL:
2
+ -- KEYS[1] = task key (mcp:task:{taskId})
3
+ -- ARGV[1] = the record exactly as the caller read it
4
+ -- ARGV[2] = the record to write
5
+ -- Returns 1 if written, 0 if the record changed (or expired) since it was read.
6
+ -- The caller re-reads and retries, so a status that went terminal in between —
7
+ -- a cancel racing a background run's result — is never overwritten.
8
+
9
+ local current = redis.call('GET', KEYS[1])
10
+ if current ~= ARGV[1] then return 0 end
11
+ -- PTTL is -1 only for a key with no expiry. A key at its last millisecond
12
+ -- reads 0, and must keep an expiry rather than lose it.
13
+ local ttl = redis.call('PTTL', KEYS[1])
14
+ if ttl == -1 then
15
+ redis.call('SET', KEYS[1], ARGV[2])
16
+ else
17
+ redis.call('SET', KEYS[1], ARGV[2], 'PX', math.max(ttl, 1))
18
+ end
19
+ return 1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.48.2",
3
+ "version": "0.49.0",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/util/mcpServer.ts CHANGED
@@ -3,12 +3,18 @@ import {
3
3
  ResourceTemplate,
4
4
  } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
6
- import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
6
+ import type {
7
+ RequestHandlerExtra,
8
+ RequestTaskStore,
9
+ } from "@modelcontextprotocol/sdk/shared/protocol.js";
7
10
  import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js";
8
11
  import {
12
+ type CallToolResult,
9
13
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
14
+ ErrorCode,
10
15
  JSONRPCMessageSchema,
11
16
  ListResourceTemplatesRequestSchema,
17
+ McpError,
12
18
  type ServerNotification,
13
19
  type ServerRequest,
14
20
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -17,18 +23,17 @@ import {
17
23
  import { randomUUID } from "crypto";
18
24
  import * as z4mini from "zod/v4-mini";
19
25
  import { api, logger } from "../api";
20
- import type { Action, McpUiConfig } from "../classes/Action";
21
- import { MCP_APP_MIME_TYPE, MCP_RESPONSE_FORMAT } from "../classes/Action";
26
+ import type { Action, McpTaskConfig, McpUiConfig } from "../classes/Action";
27
+ import { MCP_APP_MIME_TYPE } from "../classes/Action";
22
28
  import { CONNECTION_TYPE, Connection } from "../classes/Connection";
23
29
  import { McpUrlElicitationRequiredError } from "../classes/McpUrlElicitationRequiredError";
24
- import { StreamingResponse } from "../classes/StreamingResponse";
25
30
  import { ErrorType, TypedError } from "../classes/TypedError";
26
- import { UIResponse } from "../classes/UIResponse";
27
31
  import { config } from "../config";
28
32
  import pkg from "../package.json";
29
33
  import { appendHeaders } from "../util/http";
30
34
  import { getResolvedMcpAppHtml } from "../util/mcpAppBundler";
31
- import { toMarkdown } from "../util/toMarkdown";
35
+ import { McpTaskStore, mcpTaskOwnerFor } from "../util/mcpTasks";
36
+ import { toCallToolResult, toolErrorResult } from "../util/mcpToolResult";
32
37
 
33
38
  /**
34
39
  * Convert a Keryx action name to a valid MCP tool name.
@@ -777,23 +782,56 @@ export function createMcpServer(
777
782
  // `initialize` (spec 2026-01-26, SEP-1724). Only declared when at least one
778
783
  // action ships a UI, keeping the capability surface minimal.
779
784
  const hasUiActions = api.actions.actions.some((a: Action) => a.mcp?.ui);
780
- const mcpServer = new McpServer(
785
+ // Advertise MCP Tasks (spec 2025-11-25) only when some tool is task-capable.
786
+ // The SDK answers `tasks/*` from the store; it is per-session because every
787
+ // read is scoped to the session's owner (see McpTaskStore).
788
+ const hasTaskActions = api.actions.actions.some(
789
+ (a: Action) => isMcpTool(a) && a.mcp?.task,
790
+ );
791
+ let mcpServer: McpServer | undefined;
792
+ const taskStore = hasTaskActions
793
+ ? new McpTaskStore(() => {
794
+ const auth = mcpServer && api.mcp.mcpServerAuth.get(mcpServer);
795
+ if (!auth) return undefined;
796
+ return mcpTaskOwnerFor(
797
+ auth,
798
+ auth.clientId === ANONYMOUS_MCP_CLIENT_ID,
799
+ mcpServer?.server.transport?.sessionId,
800
+ );
801
+ })
802
+ : undefined;
803
+ mcpServer = new McpServer(
781
804
  { name: pkg.name, version: pkg.version },
782
805
  {
783
806
  instructions: config.server.mcp.instructions,
784
- ...(hasUiActions
785
- ? {
786
- capabilities: {
807
+ capabilities: {
808
+ ...(hasUiActions
809
+ ? {
787
810
  extensions: {
788
811
  [UI_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME_TYPE] },
789
812
  },
790
- },
813
+ }
814
+ : {}),
815
+ ...(taskStore
816
+ ? {
817
+ tasks: {
818
+ list: {},
819
+ cancel: {},
820
+ requests: { tools: { call: {} } },
821
+ },
822
+ }
823
+ : {}),
824
+ },
825
+ ...(taskStore
826
+ ? {
827
+ taskStore,
828
+ defaultTaskPollInterval: config.server.mcp.taskPollInterval,
791
829
  }
792
830
  : {}),
793
831
  },
794
832
  );
795
833
 
796
- registerTools(mcpServer, anonymous);
834
+ registerTools(mcpServer, anonymous, taskStore);
797
835
  registerResources(mcpServer, anonymous);
798
836
  registerUiResources(mcpServer, anonymous);
799
837
  registerPrompts(mcpServer, anonymous);
@@ -830,7 +868,180 @@ function buildUiMeta(ui: McpUiConfig): Record<string, unknown> {
830
868
  return meta;
831
869
  }
832
870
 
833
- function registerTools(mcpServer: McpServer, anonymous: boolean) {
871
+ /** Extra the SDK hands a tool handler (task handlers get a `taskStore` too). */
872
+ type ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;
873
+
874
+ /**
875
+ * Run an action for a tool call and render its result. Shared by plain tool
876
+ * calls, inline calls to `optional` task tools, and task runs.
877
+ *
878
+ * @param action - The action to run.
879
+ * @param args - The tool call's arguments.
880
+ * @param extra - The SDK's handler extra (auth, session id, abort signal).
881
+ * @param mcpServer - The session's server. Pass it for a call answered in the
882
+ * request, so the action can elicit and stream log messages; omit it for a
883
+ * task's background run, which has no live request to talk back over.
884
+ * @throws {UrlElicitationRequiredError} When the action needs the user to visit a URL first.
885
+ */
886
+ async function runToolCall(
887
+ action: Action,
888
+ args: Record<string, unknown> | undefined,
889
+ extra: ToolExtra,
890
+ mcpServer?: McpServer,
891
+ ): Promise<CallToolResult> {
892
+ const { response, error } = await actForToolCall(
893
+ action,
894
+ args,
895
+ extra,
896
+ mcpServer,
897
+ );
898
+ if (error) return toolErrorResult(error);
899
+ // Forward streamed chunks as logging messages for real-time visibility.
900
+ return toCallToolResult(
901
+ action,
902
+ response,
903
+ mcpServer
904
+ ? (chunk) => {
905
+ mcpServer.server
906
+ .sendLoggingMessage({ level: "info", data: chunk })
907
+ .catch(() => {
908
+ // Logging message delivery is best-effort
909
+ });
910
+ }
911
+ : undefined,
912
+ );
913
+ }
914
+
915
+ /**
916
+ * Run an action for a tool call as the caller, without rendering the result.
917
+ * The one place a tool call's connection is built, so a durable task's start
918
+ * gets the same elicitation support as a plain call.
919
+ *
920
+ * @param action - The action to run.
921
+ * @param args - The tool call's arguments.
922
+ * @param extra - The SDK's handler extra (auth, session id, abort signal).
923
+ * @param mcpServer - The session's server, for a call answered in the request
924
+ * (enables elicitation); omit it for a task's background run.
925
+ * @returns The action's response, or the error it failed with.
926
+ * @throws {UrlElicitationRequiredError} When the action needs the user to visit a URL first.
927
+ */
928
+ async function actForToolCall(
929
+ action: Action,
930
+ args: Record<string, unknown> | undefined,
931
+ extra: ToolExtra,
932
+ mcpServer?: McpServer,
933
+ ): Promise<{ response: unknown; error?: TypedError }> {
934
+ const connection = await createMcpConnection(
935
+ mcpServer
936
+ ? extra
937
+ : { authInfo: extra.authInfo, sessionId: extra.sessionId },
938
+ mcpServer,
939
+ );
940
+ try {
941
+ const { response, error } = await connection.act(
942
+ action.name,
943
+ args && typeof args === "object" ? args : {},
944
+ "",
945
+ extra.sessionId || "",
946
+ );
947
+ if (error instanceof McpUrlElicitationRequiredError) {
948
+ throw new UrlElicitationRequiredError(error.elicitations, error.message);
949
+ }
950
+ return { response, error };
951
+ } finally {
952
+ connection.destroy();
953
+ }
954
+ }
955
+
956
+ /**
957
+ * The handlers for a task-capable tool (`mcp.task`). The SDK routes every call
958
+ * of such a tool — task-augmented or not — through `createTask`.
959
+ *
960
+ * - A **plain call** to an `optional` tool runs the action right here and is
961
+ * answered with its result, exactly like a tool without `mcp.task`.
962
+ * - A **durable** task runs the action now, in the request (so it can still
963
+ * elicit); its response is the handle that the action's `status` callback is
964
+ * asked about from then on. A failing action ends the task as `failed`
965
+ * immediately; one that needs a URL elicitation fails the call instead, so
966
+ * the client can send the user there and retry.
967
+ * - A **managed** task is saved as `working` and the action runs in the
968
+ * background on this node, its result recorded when it settles.
969
+ */
970
+ function buildToolTaskHandler(
971
+ action: Action,
972
+ taskConfig: McpTaskConfig,
973
+ mcpServer: McpServer,
974
+ taskStore: McpTaskStore,
975
+ ) {
976
+ return {
977
+ createTask: async (
978
+ args: Record<string, unknown> | undefined,
979
+ extra: ToolExtra & { taskStore: RequestTaskStore },
980
+ ) => {
981
+ // Anonymous sessions may only call public tools. The HTTP layer already
982
+ // answers such a call with a 401 challenge; this is the backstop.
983
+ if (!isMcpAccessAllowed(action, extra.authInfo)) {
984
+ throw new McpError(
985
+ ErrorCode.InvalidRequest,
986
+ mcpAuthenticationRequiredError(action).message,
987
+ );
988
+ }
989
+
990
+ const minted = await extra.taskStore.createTask({
991
+ ttl: extra.taskRequestedTtl,
992
+ pollInterval: taskConfig.pollInterval,
993
+ });
994
+ const { task, inline } = taskStore.claim(minted.taskId);
995
+
996
+ if (inline) {
997
+ const result = await runToolCall(action, args, extra, mcpServer);
998
+ return { task: taskStore.finishInline(task, result) };
999
+ }
1000
+
1001
+ if (taskConfig.status) {
1002
+ // Started in the request, so the action can still elicit.
1003
+ const { response, error } = await actForToolCall(
1004
+ action,
1005
+ args,
1006
+ extra,
1007
+ mcpServer,
1008
+ );
1009
+ if (error) {
1010
+ return {
1011
+ task: await taskStore.save(
1012
+ { ...task, status: "failed", statusMessage: error.message },
1013
+ action,
1014
+ { result: toolErrorResult(error) },
1015
+ ),
1016
+ };
1017
+ }
1018
+ return {
1019
+ task: await taskStore.save(task, action, { handle: response }),
1020
+ };
1021
+ }
1022
+
1023
+ const saved = await taskStore.save(task, action);
1024
+ taskStore.runInBackground(task.taskId, () =>
1025
+ runToolCall(action, args, extra),
1026
+ );
1027
+ return { task: saved };
1028
+ },
1029
+ getTask: async (
1030
+ _args: Record<string, unknown> | undefined,
1031
+ extra: ToolExtra & { taskId: string; taskStore: RequestTaskStore },
1032
+ ) => extra.taskStore.getTask(extra.taskId),
1033
+ getTaskResult: async (
1034
+ _args: Record<string, unknown> | undefined,
1035
+ extra: ToolExtra & { taskId: string; taskStore: RequestTaskStore },
1036
+ ) => (await extra.taskStore.getTaskResult(extra.taskId)) as CallToolResult,
1037
+ };
1038
+ }
1039
+
1040
+ function registerTools(
1041
+ mcpServer: McpServer,
1042
+ anonymous: boolean,
1043
+ taskStore: McpTaskStore | undefined,
1044
+ ) {
834
1045
  const registered = new Set<string>();
835
1046
  for (const action of api.actions.actions) {
836
1047
  // Tools are opt-in: register only actions that explicitly set `mcp.tool =
@@ -861,133 +1072,31 @@ function registerTools(mcpServer: McpServer, anonymous: boolean) {
861
1072
  toolConfig._meta = { ui: { resourceUri: uiResourceUri(action) } };
862
1073
  }
863
1074
 
1075
+ const taskConfig = action.mcp?.task;
1076
+ if (taskConfig && taskStore) {
1077
+ const tool = mcpServer.experimental.tasks.registerToolTask(
1078
+ toolName,
1079
+ {
1080
+ ...toolConfig,
1081
+ inputSchema: toolConfig.inputSchema,
1082
+ execution: { taskSupport: taskConfig.support },
1083
+ },
1084
+ buildToolTaskHandler(action, taskConfig, mcpServer, taskStore),
1085
+ );
1086
+ gateForAnonymous(mcpServer, action, tool, anonymous);
1087
+ continue;
1088
+ }
1089
+
864
1090
  const tool = mcpServer.registerTool(
865
1091
  toolName,
866
1092
  toolConfig,
867
- async (
868
- args: Record<string, unknown>,
869
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>,
870
- ) => {
1093
+ async (args: Record<string, unknown>, extra: ToolExtra) => {
871
1094
  // Anonymous sessions may only call public tools. The HTTP layer already
872
1095
  // answers such a call with a 401 challenge; this is the backstop.
873
1096
  if (!isMcpAccessAllowed(action, extra.authInfo)) {
874
- const denied = mcpAuthenticationRequiredError(action);
875
- return {
876
- content: [
877
- {
878
- type: "text" as const,
879
- text: JSON.stringify({
880
- error: denied.message,
881
- type: denied.type,
882
- }),
883
- },
884
- ],
885
- isError: true,
886
- };
887
- }
888
-
889
- const mcpSessionId = extra.sessionId || "";
890
- const connection = await createMcpConnection(extra, mcpServer);
891
-
892
- try {
893
- const params =
894
- args && typeof args === "object"
895
- ? (args as Record<string, unknown>)
896
- : {};
897
-
898
- const { response, error } = await connection.act(
899
- action.name,
900
- params,
901
- "",
902
- mcpSessionId,
903
- );
904
-
905
- if (error) {
906
- if (error instanceof McpUrlElicitationRequiredError) {
907
- throw new UrlElicitationRequiredError(
908
- error.elicitations,
909
- error.message,
910
- );
911
- }
912
- return {
913
- content: [
914
- {
915
- type: "text" as const,
916
- text: JSON.stringify({
917
- error: error.message,
918
- type: error.type,
919
- }),
920
- },
921
- ],
922
- isError: true,
923
- };
924
- }
925
-
926
- // For streaming responses, consume the stream and accumulate into a single result.
927
- // Send incremental chunks as MCP logging messages for real-time visibility.
928
- if (response instanceof StreamingResponse) {
929
- const reader = response.stream.getReader();
930
- const decoder = new TextDecoder();
931
- let accumulated = "";
932
- try {
933
- while (true) {
934
- const { done, value } = await reader.read();
935
- if (done) break;
936
- const chunk = decoder.decode(value);
937
- accumulated += chunk;
938
- try {
939
- mcpServer.server.sendLoggingMessage({
940
- level: "info",
941
- data: chunk,
942
- });
943
- } catch (_e) {
944
- // Logging message delivery is best-effort
945
- }
946
- }
947
- } finally {
948
- response.onClose?.();
949
- }
950
- return {
951
- content: [{ type: "text" as const, text: accumulated }],
952
- };
953
- }
954
-
955
- // MCP App responses carry both a text block (added to model context)
956
- // and structuredContent (delivered to the app UI for rendering).
957
- // ext-apps hosts render the UI from the tool's `_meta.ui.resourceUri`
958
- // and the separate `ui://` resource — the content array stays text-only.
959
- if (response instanceof UIResponse) {
960
- return {
961
- content: [{ type: "text" as const, text: response.text }],
962
- structuredContent: response.structuredContent,
963
- };
964
- }
965
-
966
- const format = action.mcp?.responseFormat ?? MCP_RESPONSE_FORMAT.JSON;
967
- const text =
968
- format === MCP_RESPONSE_FORMAT.MARKDOWN
969
- ? toMarkdown(response, {
970
- maxDepth: config.server.mcp.markdownDepthLimit,
971
- })
972
- : JSON.stringify(response);
973
-
974
- // Promote plain object responses to structuredContent so MCP Apps can
975
- // bind without JSON.parse (same shape UIResponse already provides).
976
- const structuredContent =
977
- format === MCP_RESPONSE_FORMAT.JSON &&
978
- response !== null &&
979
- typeof response === "object" &&
980
- !Array.isArray(response)
981
- ? (response as Record<string, unknown>)
982
- : undefined;
983
-
984
- return {
985
- content: [{ type: "text" as const, text }],
986
- ...(structuredContent ? { structuredContent } : {}),
987
- };
988
- } finally {
989
- connection.destroy();
1097
+ return toolErrorResult(mcpAuthenticationRequiredError(action));
990
1098
  }
1099
+ return runToolCall(action, args, extra, mcpServer);
991
1100
  },
992
1101
  );
993
1102
  gateForAnonymous(mcpServer, action, tool, anonymous);
@@ -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
+ }