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/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 = {
|
package/config/server/mcp.ts
CHANGED
|
@@ -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 {
|
|
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,
|
package/initializers/mcp.ts
CHANGED
|
@@ -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
package/servers/web.ts
CHANGED
|
@@ -673,14 +673,23 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
673
673
|
rawBody,
|
|
674
674
|
});
|
|
675
675
|
} catch (e) {
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
)
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
676
|
+
// An oversized or unparseable body is the client's fault: answer it with
|
|
677
|
+
// the JSON error envelope (and CORS headers) rather than letting it
|
|
678
|
+
// escape to Bun's default 500 handler, and never leak the connection.
|
|
679
|
+
connection.destroy();
|
|
680
|
+
const error =
|
|
681
|
+
e instanceof TypedError
|
|
682
|
+
? e
|
|
683
|
+
: new TypedError({
|
|
684
|
+
message: `cannot parse request body: ${e}`,
|
|
685
|
+
type: ErrorType.CONNECTION_ACTION_PARAM_VALIDATION,
|
|
686
|
+
cause: e,
|
|
687
|
+
});
|
|
688
|
+
const status = error.message.startsWith("Payload Too Large") ? 413 : 400;
|
|
689
|
+
return {
|
|
690
|
+
response: buildError(connection, error, status, requestOrigin),
|
|
691
|
+
actionName: actionName ?? undefined,
|
|
692
|
+
};
|
|
684
693
|
}
|
|
685
694
|
|
|
686
695
|
const { response, error } = await connection.act(
|
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 {
|
|
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
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
785
|
-
|
|
786
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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);
|