@noodleseed/assistant 1.22.0 → 1.23.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/README.md +43 -8
- package/dist/app-view-element-1i_w6FDf.d.cts +40 -0
- package/dist/app-view-element-7ZQZLYbL.d.ts +40 -0
- package/dist/app-view.cjs +18666 -0
- package/dist/app-view.cjs.map +1 -0
- package/dist/app-view.d.cts +9 -0
- package/dist/app-view.d.ts +9 -0
- package/dist/app-view.js +15 -0
- package/dist/app-view.js.map +1 -0
- package/dist/chunk-5NBHHNI3.js +180 -0
- package/dist/chunk-5NBHHNI3.js.map +1 -0
- package/dist/{chunk-ZPZHPXIQ.js → chunk-IBDP6PXQ.js} +9 -3882
- package/dist/chunk-IBDP6PXQ.js.map +1 -0
- package/dist/chunk-P223CYPO.js +3880 -0
- package/dist/chunk-P223CYPO.js.map +1 -0
- package/dist/{chunk-6TT3R555.js → chunk-X7UQDIGS.js} +784 -4040
- package/dist/chunk-X7UQDIGS.js.map +1 -0
- package/dist/chunk-XKTUXFGX.js +3323 -0
- package/dist/chunk-XKTUXFGX.js.map +1 -0
- package/dist/{client-BkJlpN5N.d.ts → client-Bp_VKpMg.d.ts} +1 -1
- package/dist/{client-BZ7xPwfW.d.cts → client-uo57Swlm.d.cts} +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +2 -1
- package/dist/embed.global.js +87 -73
- package/dist/index.cjs +71 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/react/client.d.cts +1 -1
- package/dist/react/client.d.ts +1 -1
- package/dist/react/client.js +2 -1
- package/dist/react/client.js.map +1 -1
- package/dist/react.cjs +259 -47
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +7 -8
- package/dist/react.d.ts +7 -8
- package/dist/react.js +31 -41
- package/dist/react.js.map +1 -1
- package/package.json +16 -2
- package/dist/chunk-6TT3R555.js.map +0 -1
- package/dist/chunk-ZPZHPXIQ.js.map +0 -1
|
@@ -0,0 +1,3323 @@
|
|
|
1
|
+
import {
|
|
2
|
+
_enum,
|
|
3
|
+
_null,
|
|
4
|
+
array,
|
|
5
|
+
boolean,
|
|
6
|
+
custom,
|
|
7
|
+
discriminatedUnion,
|
|
8
|
+
external_exports,
|
|
9
|
+
intersection,
|
|
10
|
+
iso_exports,
|
|
11
|
+
literal,
|
|
12
|
+
looseObject,
|
|
13
|
+
number,
|
|
14
|
+
object,
|
|
15
|
+
optional,
|
|
16
|
+
preprocess,
|
|
17
|
+
record,
|
|
18
|
+
safeParse,
|
|
19
|
+
string,
|
|
20
|
+
union,
|
|
21
|
+
unknown
|
|
22
|
+
} from "./chunk-3YYTUJPJ.js";
|
|
23
|
+
import {
|
|
24
|
+
__require
|
|
25
|
+
} from "./chunk-5FUTL2UF.js";
|
|
26
|
+
|
|
27
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
|
|
28
|
+
var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
|
|
29
|
+
var JSONRPC_VERSION = "2.0";
|
|
30
|
+
var AssertObjectSchema = custom((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function"));
|
|
31
|
+
var ProgressTokenSchema = union([string(), number().int()]);
|
|
32
|
+
var CursorSchema = string();
|
|
33
|
+
var TaskCreationParamsSchema = looseObject({
|
|
34
|
+
/**
|
|
35
|
+
* Requested duration in milliseconds to retain task from creation.
|
|
36
|
+
*/
|
|
37
|
+
ttl: number().optional(),
|
|
38
|
+
/**
|
|
39
|
+
* Time in milliseconds to wait between task status requests.
|
|
40
|
+
*/
|
|
41
|
+
pollInterval: number().optional()
|
|
42
|
+
});
|
|
43
|
+
var TaskMetadataSchema = object({
|
|
44
|
+
ttl: number().optional()
|
|
45
|
+
});
|
|
46
|
+
var RelatedTaskMetadataSchema = object({
|
|
47
|
+
taskId: string()
|
|
48
|
+
});
|
|
49
|
+
var RequestMetaSchema = looseObject({
|
|
50
|
+
/**
|
|
51
|
+
* If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
|
|
52
|
+
*/
|
|
53
|
+
progressToken: ProgressTokenSchema.optional(),
|
|
54
|
+
/**
|
|
55
|
+
* If specified, this request is related to the provided task.
|
|
56
|
+
*/
|
|
57
|
+
[RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
|
|
58
|
+
});
|
|
59
|
+
var BaseRequestParamsSchema = object({
|
|
60
|
+
/**
|
|
61
|
+
* See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
|
|
62
|
+
*/
|
|
63
|
+
_meta: RequestMetaSchema.optional()
|
|
64
|
+
});
|
|
65
|
+
var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
66
|
+
/**
|
|
67
|
+
* If specified, the caller is requesting task-augmented execution for this request.
|
|
68
|
+
* The request will return a CreateTaskResult immediately, and the actual result can be
|
|
69
|
+
* retrieved later via tasks/result.
|
|
70
|
+
*
|
|
71
|
+
* Task augmentation is subject to capability negotiation - receivers MUST declare support
|
|
72
|
+
* for task augmentation of specific request types in their capabilities.
|
|
73
|
+
*/
|
|
74
|
+
task: TaskMetadataSchema.optional()
|
|
75
|
+
});
|
|
76
|
+
var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
|
|
77
|
+
var RequestSchema = object({
|
|
78
|
+
method: string(),
|
|
79
|
+
params: BaseRequestParamsSchema.loose().optional()
|
|
80
|
+
});
|
|
81
|
+
var NotificationsParamsSchema = object({
|
|
82
|
+
/**
|
|
83
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
84
|
+
* for notes on _meta usage.
|
|
85
|
+
*/
|
|
86
|
+
_meta: RequestMetaSchema.optional()
|
|
87
|
+
});
|
|
88
|
+
var NotificationSchema = object({
|
|
89
|
+
method: string(),
|
|
90
|
+
params: NotificationsParamsSchema.loose().optional()
|
|
91
|
+
});
|
|
92
|
+
var ResultSchema = looseObject({
|
|
93
|
+
/**
|
|
94
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
95
|
+
* for notes on _meta usage.
|
|
96
|
+
*/
|
|
97
|
+
_meta: RequestMetaSchema.optional()
|
|
98
|
+
});
|
|
99
|
+
var RequestIdSchema = union([string(), number().int()]);
|
|
100
|
+
var JSONRPCRequestSchema = object({
|
|
101
|
+
jsonrpc: literal(JSONRPC_VERSION),
|
|
102
|
+
id: RequestIdSchema,
|
|
103
|
+
...RequestSchema.shape
|
|
104
|
+
}).strict();
|
|
105
|
+
var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
|
|
106
|
+
var JSONRPCNotificationSchema = object({
|
|
107
|
+
jsonrpc: literal(JSONRPC_VERSION),
|
|
108
|
+
...NotificationSchema.shape
|
|
109
|
+
}).strict();
|
|
110
|
+
var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
|
|
111
|
+
var JSONRPCResultResponseSchema = object({
|
|
112
|
+
jsonrpc: literal(JSONRPC_VERSION),
|
|
113
|
+
id: RequestIdSchema,
|
|
114
|
+
result: ResultSchema
|
|
115
|
+
}).strict();
|
|
116
|
+
var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
|
|
117
|
+
var ErrorCode;
|
|
118
|
+
(function(ErrorCode2) {
|
|
119
|
+
ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
|
|
120
|
+
ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
|
|
121
|
+
ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
|
|
122
|
+
ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
|
|
123
|
+
ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
|
|
124
|
+
ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
|
|
125
|
+
ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
|
|
126
|
+
ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
|
|
127
|
+
})(ErrorCode || (ErrorCode = {}));
|
|
128
|
+
var JSONRPCErrorResponseSchema = object({
|
|
129
|
+
jsonrpc: literal(JSONRPC_VERSION),
|
|
130
|
+
id: RequestIdSchema.optional(),
|
|
131
|
+
error: object({
|
|
132
|
+
/**
|
|
133
|
+
* The error type that occurred.
|
|
134
|
+
*/
|
|
135
|
+
code: number().int(),
|
|
136
|
+
/**
|
|
137
|
+
* A short description of the error. The message SHOULD be limited to a concise single sentence.
|
|
138
|
+
*/
|
|
139
|
+
message: string(),
|
|
140
|
+
/**
|
|
141
|
+
* Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
|
|
142
|
+
*/
|
|
143
|
+
data: unknown().optional()
|
|
144
|
+
})
|
|
145
|
+
}).strict();
|
|
146
|
+
var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
|
|
147
|
+
var JSONRPCMessageSchema = union([
|
|
148
|
+
JSONRPCRequestSchema,
|
|
149
|
+
JSONRPCNotificationSchema,
|
|
150
|
+
JSONRPCResultResponseSchema,
|
|
151
|
+
JSONRPCErrorResponseSchema
|
|
152
|
+
]);
|
|
153
|
+
var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
|
|
154
|
+
var EmptyResultSchema = ResultSchema.strict();
|
|
155
|
+
var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
156
|
+
/**
|
|
157
|
+
* The ID of the request to cancel.
|
|
158
|
+
*
|
|
159
|
+
* This MUST correspond to the ID of a request previously issued in the same direction.
|
|
160
|
+
*/
|
|
161
|
+
requestId: RequestIdSchema.optional(),
|
|
162
|
+
/**
|
|
163
|
+
* An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
|
|
164
|
+
*/
|
|
165
|
+
reason: string().optional()
|
|
166
|
+
});
|
|
167
|
+
var CancelledNotificationSchema = NotificationSchema.extend({
|
|
168
|
+
method: literal("notifications/cancelled"),
|
|
169
|
+
params: CancelledNotificationParamsSchema
|
|
170
|
+
});
|
|
171
|
+
var IconSchema = object({
|
|
172
|
+
/**
|
|
173
|
+
* URL or data URI for the icon.
|
|
174
|
+
*/
|
|
175
|
+
src: string(),
|
|
176
|
+
/**
|
|
177
|
+
* Optional MIME type for the icon.
|
|
178
|
+
*/
|
|
179
|
+
mimeType: string().optional(),
|
|
180
|
+
/**
|
|
181
|
+
* Optional array of strings that specify sizes at which the icon can be used.
|
|
182
|
+
* Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
|
|
183
|
+
*
|
|
184
|
+
* If not provided, the client should assume that the icon can be used at any size.
|
|
185
|
+
*/
|
|
186
|
+
sizes: array(string()).optional(),
|
|
187
|
+
/**
|
|
188
|
+
* Optional specifier for the theme this icon is designed for. `light` indicates
|
|
189
|
+
* the icon is designed to be used with a light background, and `dark` indicates
|
|
190
|
+
* the icon is designed to be used with a dark background.
|
|
191
|
+
*
|
|
192
|
+
* If not provided, the client should assume the icon can be used with any theme.
|
|
193
|
+
*/
|
|
194
|
+
theme: _enum(["light", "dark"]).optional()
|
|
195
|
+
});
|
|
196
|
+
var IconsSchema = object({
|
|
197
|
+
/**
|
|
198
|
+
* Optional set of sized icons that the client can display in a user interface.
|
|
199
|
+
*
|
|
200
|
+
* Clients that support rendering icons MUST support at least the following MIME types:
|
|
201
|
+
* - `image/png` - PNG images (safe, universal compatibility)
|
|
202
|
+
* - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
|
|
203
|
+
*
|
|
204
|
+
* Clients that support rendering icons SHOULD also support:
|
|
205
|
+
* - `image/svg+xml` - SVG images (scalable but requires security precautions)
|
|
206
|
+
* - `image/webp` - WebP images (modern, efficient format)
|
|
207
|
+
*/
|
|
208
|
+
icons: array(IconSchema).optional()
|
|
209
|
+
});
|
|
210
|
+
var BaseMetadataSchema = object({
|
|
211
|
+
/** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
|
|
212
|
+
name: string(),
|
|
213
|
+
/**
|
|
214
|
+
* Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
|
|
215
|
+
* even by those unfamiliar with domain-specific terminology.
|
|
216
|
+
*
|
|
217
|
+
* If not provided, the name should be used for display (except for Tool,
|
|
218
|
+
* where `annotations.title` should be given precedence over using `name`,
|
|
219
|
+
* if present).
|
|
220
|
+
*/
|
|
221
|
+
title: string().optional()
|
|
222
|
+
});
|
|
223
|
+
var ImplementationSchema = BaseMetadataSchema.extend({
|
|
224
|
+
...BaseMetadataSchema.shape,
|
|
225
|
+
...IconsSchema.shape,
|
|
226
|
+
version: string(),
|
|
227
|
+
/**
|
|
228
|
+
* An optional URL of the website for this implementation.
|
|
229
|
+
*/
|
|
230
|
+
websiteUrl: string().optional(),
|
|
231
|
+
/**
|
|
232
|
+
* An optional human-readable description of what this implementation does.
|
|
233
|
+
*
|
|
234
|
+
* This can be used by clients or servers to provide context about their purpose
|
|
235
|
+
* and capabilities. For example, a server might describe the types of resources
|
|
236
|
+
* or tools it provides, while a client might describe its intended use case.
|
|
237
|
+
*/
|
|
238
|
+
description: string().optional()
|
|
239
|
+
});
|
|
240
|
+
var FormElicitationCapabilitySchema = intersection(object({
|
|
241
|
+
applyDefaults: boolean().optional()
|
|
242
|
+
}), record(string(), unknown()));
|
|
243
|
+
var ElicitationCapabilitySchema = preprocess((value) => {
|
|
244
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
245
|
+
if (Object.keys(value).length === 0) {
|
|
246
|
+
return { form: {} };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return value;
|
|
250
|
+
}, intersection(object({
|
|
251
|
+
form: FormElicitationCapabilitySchema.optional(),
|
|
252
|
+
url: AssertObjectSchema.optional()
|
|
253
|
+
}), record(string(), unknown()).optional()));
|
|
254
|
+
var ClientTasksCapabilitySchema = looseObject({
|
|
255
|
+
/**
|
|
256
|
+
* Present if the client supports listing tasks.
|
|
257
|
+
*/
|
|
258
|
+
list: AssertObjectSchema.optional(),
|
|
259
|
+
/**
|
|
260
|
+
* Present if the client supports cancelling tasks.
|
|
261
|
+
*/
|
|
262
|
+
cancel: AssertObjectSchema.optional(),
|
|
263
|
+
/**
|
|
264
|
+
* Capabilities for task creation on specific request types.
|
|
265
|
+
*/
|
|
266
|
+
requests: looseObject({
|
|
267
|
+
/**
|
|
268
|
+
* Task support for sampling requests.
|
|
269
|
+
*/
|
|
270
|
+
sampling: looseObject({
|
|
271
|
+
createMessage: AssertObjectSchema.optional()
|
|
272
|
+
}).optional(),
|
|
273
|
+
/**
|
|
274
|
+
* Task support for elicitation requests.
|
|
275
|
+
*/
|
|
276
|
+
elicitation: looseObject({
|
|
277
|
+
create: AssertObjectSchema.optional()
|
|
278
|
+
}).optional()
|
|
279
|
+
}).optional()
|
|
280
|
+
});
|
|
281
|
+
var ServerTasksCapabilitySchema = looseObject({
|
|
282
|
+
/**
|
|
283
|
+
* Present if the server supports listing tasks.
|
|
284
|
+
*/
|
|
285
|
+
list: AssertObjectSchema.optional(),
|
|
286
|
+
/**
|
|
287
|
+
* Present if the server supports cancelling tasks.
|
|
288
|
+
*/
|
|
289
|
+
cancel: AssertObjectSchema.optional(),
|
|
290
|
+
/**
|
|
291
|
+
* Capabilities for task creation on specific request types.
|
|
292
|
+
*/
|
|
293
|
+
requests: looseObject({
|
|
294
|
+
/**
|
|
295
|
+
* Task support for tool requests.
|
|
296
|
+
*/
|
|
297
|
+
tools: looseObject({
|
|
298
|
+
call: AssertObjectSchema.optional()
|
|
299
|
+
}).optional()
|
|
300
|
+
}).optional()
|
|
301
|
+
});
|
|
302
|
+
var ClientCapabilitiesSchema = object({
|
|
303
|
+
/**
|
|
304
|
+
* Experimental, non-standard capabilities that the client supports.
|
|
305
|
+
*/
|
|
306
|
+
experimental: record(string(), AssertObjectSchema).optional(),
|
|
307
|
+
/**
|
|
308
|
+
* Present if the client supports sampling from an LLM.
|
|
309
|
+
*/
|
|
310
|
+
sampling: object({
|
|
311
|
+
/**
|
|
312
|
+
* Present if the client supports context inclusion via includeContext parameter.
|
|
313
|
+
* If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
|
|
314
|
+
*/
|
|
315
|
+
context: AssertObjectSchema.optional(),
|
|
316
|
+
/**
|
|
317
|
+
* Present if the client supports tool use via tools and toolChoice parameters.
|
|
318
|
+
*/
|
|
319
|
+
tools: AssertObjectSchema.optional()
|
|
320
|
+
}).optional(),
|
|
321
|
+
/**
|
|
322
|
+
* Present if the client supports eliciting user input.
|
|
323
|
+
*/
|
|
324
|
+
elicitation: ElicitationCapabilitySchema.optional(),
|
|
325
|
+
/**
|
|
326
|
+
* Present if the client supports listing roots.
|
|
327
|
+
*/
|
|
328
|
+
roots: object({
|
|
329
|
+
/**
|
|
330
|
+
* Whether the client supports issuing notifications for changes to the roots list.
|
|
331
|
+
*/
|
|
332
|
+
listChanged: boolean().optional()
|
|
333
|
+
}).optional(),
|
|
334
|
+
/**
|
|
335
|
+
* Present if the client supports task creation.
|
|
336
|
+
*/
|
|
337
|
+
tasks: ClientTasksCapabilitySchema.optional(),
|
|
338
|
+
/**
|
|
339
|
+
* Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).
|
|
340
|
+
*/
|
|
341
|
+
extensions: record(string(), AssertObjectSchema).optional()
|
|
342
|
+
});
|
|
343
|
+
var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
344
|
+
/**
|
|
345
|
+
* The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
|
|
346
|
+
*/
|
|
347
|
+
protocolVersion: string(),
|
|
348
|
+
capabilities: ClientCapabilitiesSchema,
|
|
349
|
+
clientInfo: ImplementationSchema
|
|
350
|
+
});
|
|
351
|
+
var InitializeRequestSchema = RequestSchema.extend({
|
|
352
|
+
method: literal("initialize"),
|
|
353
|
+
params: InitializeRequestParamsSchema
|
|
354
|
+
});
|
|
355
|
+
var ServerCapabilitiesSchema = object({
|
|
356
|
+
/**
|
|
357
|
+
* Experimental, non-standard capabilities that the server supports.
|
|
358
|
+
*/
|
|
359
|
+
experimental: record(string(), AssertObjectSchema).optional(),
|
|
360
|
+
/**
|
|
361
|
+
* Present if the server supports sending log messages to the client.
|
|
362
|
+
*/
|
|
363
|
+
logging: AssertObjectSchema.optional(),
|
|
364
|
+
/**
|
|
365
|
+
* Present if the server supports sending completions to the client.
|
|
366
|
+
*/
|
|
367
|
+
completions: AssertObjectSchema.optional(),
|
|
368
|
+
/**
|
|
369
|
+
* Present if the server offers any prompt templates.
|
|
370
|
+
*/
|
|
371
|
+
prompts: object({
|
|
372
|
+
/**
|
|
373
|
+
* Whether this server supports issuing notifications for changes to the prompt list.
|
|
374
|
+
*/
|
|
375
|
+
listChanged: boolean().optional()
|
|
376
|
+
}).optional(),
|
|
377
|
+
/**
|
|
378
|
+
* Present if the server offers any resources to read.
|
|
379
|
+
*/
|
|
380
|
+
resources: object({
|
|
381
|
+
/**
|
|
382
|
+
* Whether this server supports clients subscribing to resource updates.
|
|
383
|
+
*/
|
|
384
|
+
subscribe: boolean().optional(),
|
|
385
|
+
/**
|
|
386
|
+
* Whether this server supports issuing notifications for changes to the resource list.
|
|
387
|
+
*/
|
|
388
|
+
listChanged: boolean().optional()
|
|
389
|
+
}).optional(),
|
|
390
|
+
/**
|
|
391
|
+
* Present if the server offers any tools to call.
|
|
392
|
+
*/
|
|
393
|
+
tools: object({
|
|
394
|
+
/**
|
|
395
|
+
* Whether this server supports issuing notifications for changes to the tool list.
|
|
396
|
+
*/
|
|
397
|
+
listChanged: boolean().optional()
|
|
398
|
+
}).optional(),
|
|
399
|
+
/**
|
|
400
|
+
* Present if the server supports task creation.
|
|
401
|
+
*/
|
|
402
|
+
tasks: ServerTasksCapabilitySchema.optional(),
|
|
403
|
+
/**
|
|
404
|
+
* Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).
|
|
405
|
+
*/
|
|
406
|
+
extensions: record(string(), AssertObjectSchema).optional()
|
|
407
|
+
});
|
|
408
|
+
var InitializeResultSchema = ResultSchema.extend({
|
|
409
|
+
/**
|
|
410
|
+
* The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
|
|
411
|
+
*/
|
|
412
|
+
protocolVersion: string(),
|
|
413
|
+
capabilities: ServerCapabilitiesSchema,
|
|
414
|
+
serverInfo: ImplementationSchema,
|
|
415
|
+
/**
|
|
416
|
+
* Instructions describing how to use the server and its features.
|
|
417
|
+
*
|
|
418
|
+
* This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
|
|
419
|
+
*/
|
|
420
|
+
instructions: string().optional()
|
|
421
|
+
});
|
|
422
|
+
var InitializedNotificationSchema = NotificationSchema.extend({
|
|
423
|
+
method: literal("notifications/initialized"),
|
|
424
|
+
params: NotificationsParamsSchema.optional()
|
|
425
|
+
});
|
|
426
|
+
var PingRequestSchema = RequestSchema.extend({
|
|
427
|
+
method: literal("ping"),
|
|
428
|
+
params: BaseRequestParamsSchema.optional()
|
|
429
|
+
});
|
|
430
|
+
var ProgressSchema = object({
|
|
431
|
+
/**
|
|
432
|
+
* The progress thus far. This should increase every time progress is made, even if the total is unknown.
|
|
433
|
+
*/
|
|
434
|
+
progress: number(),
|
|
435
|
+
/**
|
|
436
|
+
* Total number of items to process (or total progress required), if known.
|
|
437
|
+
*/
|
|
438
|
+
total: optional(number()),
|
|
439
|
+
/**
|
|
440
|
+
* An optional message describing the current progress.
|
|
441
|
+
*/
|
|
442
|
+
message: optional(string())
|
|
443
|
+
});
|
|
444
|
+
var ProgressNotificationParamsSchema = object({
|
|
445
|
+
...NotificationsParamsSchema.shape,
|
|
446
|
+
...ProgressSchema.shape,
|
|
447
|
+
/**
|
|
448
|
+
* The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
|
|
449
|
+
*/
|
|
450
|
+
progressToken: ProgressTokenSchema
|
|
451
|
+
});
|
|
452
|
+
var ProgressNotificationSchema = NotificationSchema.extend({
|
|
453
|
+
method: literal("notifications/progress"),
|
|
454
|
+
params: ProgressNotificationParamsSchema
|
|
455
|
+
});
|
|
456
|
+
var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
457
|
+
/**
|
|
458
|
+
* An opaque token representing the current pagination position.
|
|
459
|
+
* If provided, the server should return results starting after this cursor.
|
|
460
|
+
*/
|
|
461
|
+
cursor: CursorSchema.optional()
|
|
462
|
+
});
|
|
463
|
+
var PaginatedRequestSchema = RequestSchema.extend({
|
|
464
|
+
params: PaginatedRequestParamsSchema.optional()
|
|
465
|
+
});
|
|
466
|
+
var PaginatedResultSchema = ResultSchema.extend({
|
|
467
|
+
/**
|
|
468
|
+
* An opaque token representing the pagination position after the last returned result.
|
|
469
|
+
* If present, there may be more results available.
|
|
470
|
+
*/
|
|
471
|
+
nextCursor: CursorSchema.optional()
|
|
472
|
+
});
|
|
473
|
+
var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
|
|
474
|
+
var TaskSchema = object({
|
|
475
|
+
taskId: string(),
|
|
476
|
+
status: TaskStatusSchema,
|
|
477
|
+
/**
|
|
478
|
+
* Time in milliseconds to keep task results available after completion.
|
|
479
|
+
* If null, the task has unlimited lifetime until manually cleaned up.
|
|
480
|
+
*/
|
|
481
|
+
ttl: union([number(), _null()]),
|
|
482
|
+
/**
|
|
483
|
+
* ISO 8601 timestamp when the task was created.
|
|
484
|
+
*/
|
|
485
|
+
createdAt: string(),
|
|
486
|
+
/**
|
|
487
|
+
* ISO 8601 timestamp when the task was last updated.
|
|
488
|
+
*/
|
|
489
|
+
lastUpdatedAt: string(),
|
|
490
|
+
pollInterval: optional(number()),
|
|
491
|
+
/**
|
|
492
|
+
* Optional diagnostic message for failed tasks or other status information.
|
|
493
|
+
*/
|
|
494
|
+
statusMessage: optional(string())
|
|
495
|
+
});
|
|
496
|
+
var CreateTaskResultSchema = ResultSchema.extend({
|
|
497
|
+
task: TaskSchema
|
|
498
|
+
});
|
|
499
|
+
var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
|
|
500
|
+
var TaskStatusNotificationSchema = NotificationSchema.extend({
|
|
501
|
+
method: literal("notifications/tasks/status"),
|
|
502
|
+
params: TaskStatusNotificationParamsSchema
|
|
503
|
+
});
|
|
504
|
+
var GetTaskRequestSchema = RequestSchema.extend({
|
|
505
|
+
method: literal("tasks/get"),
|
|
506
|
+
params: BaseRequestParamsSchema.extend({
|
|
507
|
+
taskId: string()
|
|
508
|
+
})
|
|
509
|
+
});
|
|
510
|
+
var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
511
|
+
var GetTaskPayloadRequestSchema = RequestSchema.extend({
|
|
512
|
+
method: literal("tasks/result"),
|
|
513
|
+
params: BaseRequestParamsSchema.extend({
|
|
514
|
+
taskId: string()
|
|
515
|
+
})
|
|
516
|
+
});
|
|
517
|
+
var GetTaskPayloadResultSchema = ResultSchema.loose();
|
|
518
|
+
var ListTasksRequestSchema = PaginatedRequestSchema.extend({
|
|
519
|
+
method: literal("tasks/list")
|
|
520
|
+
});
|
|
521
|
+
var ListTasksResultSchema = PaginatedResultSchema.extend({
|
|
522
|
+
tasks: array(TaskSchema)
|
|
523
|
+
});
|
|
524
|
+
var CancelTaskRequestSchema = RequestSchema.extend({
|
|
525
|
+
method: literal("tasks/cancel"),
|
|
526
|
+
params: BaseRequestParamsSchema.extend({
|
|
527
|
+
taskId: string()
|
|
528
|
+
})
|
|
529
|
+
});
|
|
530
|
+
var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
531
|
+
var ResourceContentsSchema = object({
|
|
532
|
+
/**
|
|
533
|
+
* The URI of this resource.
|
|
534
|
+
*/
|
|
535
|
+
uri: string(),
|
|
536
|
+
/**
|
|
537
|
+
* The MIME type of this resource, if known.
|
|
538
|
+
*/
|
|
539
|
+
mimeType: optional(string()),
|
|
540
|
+
/**
|
|
541
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
542
|
+
* for notes on _meta usage.
|
|
543
|
+
*/
|
|
544
|
+
_meta: record(string(), unknown()).optional()
|
|
545
|
+
});
|
|
546
|
+
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
547
|
+
/**
|
|
548
|
+
* The text of the item. This must only be set if the item can actually be represented as text (not binary data).
|
|
549
|
+
*/
|
|
550
|
+
text: string()
|
|
551
|
+
});
|
|
552
|
+
var Base64Schema = string().refine((val) => {
|
|
553
|
+
try {
|
|
554
|
+
atob(val);
|
|
555
|
+
return true;
|
|
556
|
+
} catch {
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
559
|
+
}, { message: "Invalid Base64 string" });
|
|
560
|
+
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
561
|
+
/**
|
|
562
|
+
* A base64-encoded string representing the binary data of the item.
|
|
563
|
+
*/
|
|
564
|
+
blob: Base64Schema
|
|
565
|
+
});
|
|
566
|
+
var RoleSchema = _enum(["user", "assistant"]);
|
|
567
|
+
var AnnotationsSchema = object({
|
|
568
|
+
/**
|
|
569
|
+
* Intended audience(s) for the resource.
|
|
570
|
+
*/
|
|
571
|
+
audience: array(RoleSchema).optional(),
|
|
572
|
+
/**
|
|
573
|
+
* Importance hint for the resource, from 0 (least) to 1 (most).
|
|
574
|
+
*/
|
|
575
|
+
priority: number().min(0).max(1).optional(),
|
|
576
|
+
/**
|
|
577
|
+
* ISO 8601 timestamp for the most recent modification.
|
|
578
|
+
*/
|
|
579
|
+
lastModified: iso_exports.datetime({ offset: true }).optional()
|
|
580
|
+
});
|
|
581
|
+
var ResourceSchema = object({
|
|
582
|
+
...BaseMetadataSchema.shape,
|
|
583
|
+
...IconsSchema.shape,
|
|
584
|
+
/**
|
|
585
|
+
* The URI of this resource.
|
|
586
|
+
*/
|
|
587
|
+
uri: string(),
|
|
588
|
+
/**
|
|
589
|
+
* A description of what this resource represents.
|
|
590
|
+
*
|
|
591
|
+
* This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
|
|
592
|
+
*/
|
|
593
|
+
description: optional(string()),
|
|
594
|
+
/**
|
|
595
|
+
* The MIME type of this resource, if known.
|
|
596
|
+
*/
|
|
597
|
+
mimeType: optional(string()),
|
|
598
|
+
/**
|
|
599
|
+
* The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.
|
|
600
|
+
*
|
|
601
|
+
* This can be used by Hosts to display file sizes and estimate context window usage.
|
|
602
|
+
*/
|
|
603
|
+
size: optional(number()),
|
|
604
|
+
/**
|
|
605
|
+
* Optional annotations for the client.
|
|
606
|
+
*/
|
|
607
|
+
annotations: AnnotationsSchema.optional(),
|
|
608
|
+
/**
|
|
609
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
610
|
+
* for notes on _meta usage.
|
|
611
|
+
*/
|
|
612
|
+
_meta: optional(looseObject({}))
|
|
613
|
+
});
|
|
614
|
+
var ResourceTemplateSchema = object({
|
|
615
|
+
...BaseMetadataSchema.shape,
|
|
616
|
+
...IconsSchema.shape,
|
|
617
|
+
/**
|
|
618
|
+
* A URI template (according to RFC 6570) that can be used to construct resource URIs.
|
|
619
|
+
*/
|
|
620
|
+
uriTemplate: string(),
|
|
621
|
+
/**
|
|
622
|
+
* A description of what this template is for.
|
|
623
|
+
*
|
|
624
|
+
* This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
|
|
625
|
+
*/
|
|
626
|
+
description: optional(string()),
|
|
627
|
+
/**
|
|
628
|
+
* The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
|
|
629
|
+
*/
|
|
630
|
+
mimeType: optional(string()),
|
|
631
|
+
/**
|
|
632
|
+
* Optional annotations for the client.
|
|
633
|
+
*/
|
|
634
|
+
annotations: AnnotationsSchema.optional(),
|
|
635
|
+
/**
|
|
636
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
637
|
+
* for notes on _meta usage.
|
|
638
|
+
*/
|
|
639
|
+
_meta: optional(looseObject({}))
|
|
640
|
+
});
|
|
641
|
+
var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
|
|
642
|
+
method: literal("resources/list")
|
|
643
|
+
});
|
|
644
|
+
var ListResourcesResultSchema = PaginatedResultSchema.extend({
|
|
645
|
+
resources: array(ResourceSchema)
|
|
646
|
+
});
|
|
647
|
+
var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
|
|
648
|
+
method: literal("resources/templates/list")
|
|
649
|
+
});
|
|
650
|
+
var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
|
|
651
|
+
resourceTemplates: array(ResourceTemplateSchema)
|
|
652
|
+
});
|
|
653
|
+
var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
654
|
+
/**
|
|
655
|
+
* The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
|
|
656
|
+
*
|
|
657
|
+
* @format uri
|
|
658
|
+
*/
|
|
659
|
+
uri: string()
|
|
660
|
+
});
|
|
661
|
+
var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
|
|
662
|
+
var ReadResourceRequestSchema = RequestSchema.extend({
|
|
663
|
+
method: literal("resources/read"),
|
|
664
|
+
params: ReadResourceRequestParamsSchema
|
|
665
|
+
});
|
|
666
|
+
var ReadResourceResultSchema = ResultSchema.extend({
|
|
667
|
+
contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
|
|
668
|
+
});
|
|
669
|
+
var ResourceListChangedNotificationSchema = NotificationSchema.extend({
|
|
670
|
+
method: literal("notifications/resources/list_changed"),
|
|
671
|
+
params: NotificationsParamsSchema.optional()
|
|
672
|
+
});
|
|
673
|
+
var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
|
|
674
|
+
var SubscribeRequestSchema = RequestSchema.extend({
|
|
675
|
+
method: literal("resources/subscribe"),
|
|
676
|
+
params: SubscribeRequestParamsSchema
|
|
677
|
+
});
|
|
678
|
+
var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
|
|
679
|
+
var UnsubscribeRequestSchema = RequestSchema.extend({
|
|
680
|
+
method: literal("resources/unsubscribe"),
|
|
681
|
+
params: UnsubscribeRequestParamsSchema
|
|
682
|
+
});
|
|
683
|
+
var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
684
|
+
/**
|
|
685
|
+
* The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
|
|
686
|
+
*/
|
|
687
|
+
uri: string()
|
|
688
|
+
});
|
|
689
|
+
var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
|
|
690
|
+
method: literal("notifications/resources/updated"),
|
|
691
|
+
params: ResourceUpdatedNotificationParamsSchema
|
|
692
|
+
});
|
|
693
|
+
var PromptArgumentSchema = object({
|
|
694
|
+
/**
|
|
695
|
+
* The name of the argument.
|
|
696
|
+
*/
|
|
697
|
+
name: string(),
|
|
698
|
+
/**
|
|
699
|
+
* A human-readable description of the argument.
|
|
700
|
+
*/
|
|
701
|
+
description: optional(string()),
|
|
702
|
+
/**
|
|
703
|
+
* Whether this argument must be provided.
|
|
704
|
+
*/
|
|
705
|
+
required: optional(boolean())
|
|
706
|
+
});
|
|
707
|
+
var PromptSchema = object({
|
|
708
|
+
...BaseMetadataSchema.shape,
|
|
709
|
+
...IconsSchema.shape,
|
|
710
|
+
/**
|
|
711
|
+
* An optional description of what this prompt provides
|
|
712
|
+
*/
|
|
713
|
+
description: optional(string()),
|
|
714
|
+
/**
|
|
715
|
+
* A list of arguments to use for templating the prompt.
|
|
716
|
+
*/
|
|
717
|
+
arguments: optional(array(PromptArgumentSchema)),
|
|
718
|
+
/**
|
|
719
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
720
|
+
* for notes on _meta usage.
|
|
721
|
+
*/
|
|
722
|
+
_meta: optional(looseObject({}))
|
|
723
|
+
});
|
|
724
|
+
var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
|
|
725
|
+
method: literal("prompts/list")
|
|
726
|
+
});
|
|
727
|
+
var ListPromptsResultSchema = PaginatedResultSchema.extend({
|
|
728
|
+
prompts: array(PromptSchema)
|
|
729
|
+
});
|
|
730
|
+
var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
731
|
+
/**
|
|
732
|
+
* The name of the prompt or prompt template.
|
|
733
|
+
*/
|
|
734
|
+
name: string(),
|
|
735
|
+
/**
|
|
736
|
+
* Arguments to use for templating the prompt.
|
|
737
|
+
*/
|
|
738
|
+
arguments: record(string(), string()).optional()
|
|
739
|
+
});
|
|
740
|
+
var GetPromptRequestSchema = RequestSchema.extend({
|
|
741
|
+
method: literal("prompts/get"),
|
|
742
|
+
params: GetPromptRequestParamsSchema
|
|
743
|
+
});
|
|
744
|
+
var TextContentSchema = object({
|
|
745
|
+
type: literal("text"),
|
|
746
|
+
/**
|
|
747
|
+
* The text content of the message.
|
|
748
|
+
*/
|
|
749
|
+
text: string(),
|
|
750
|
+
/**
|
|
751
|
+
* Optional annotations for the client.
|
|
752
|
+
*/
|
|
753
|
+
annotations: AnnotationsSchema.optional(),
|
|
754
|
+
/**
|
|
755
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
756
|
+
* for notes on _meta usage.
|
|
757
|
+
*/
|
|
758
|
+
_meta: record(string(), unknown()).optional()
|
|
759
|
+
});
|
|
760
|
+
var ImageContentSchema = object({
|
|
761
|
+
type: literal("image"),
|
|
762
|
+
/**
|
|
763
|
+
* The base64-encoded image data.
|
|
764
|
+
*/
|
|
765
|
+
data: Base64Schema,
|
|
766
|
+
/**
|
|
767
|
+
* The MIME type of the image. Different providers may support different image types.
|
|
768
|
+
*/
|
|
769
|
+
mimeType: string(),
|
|
770
|
+
/**
|
|
771
|
+
* Optional annotations for the client.
|
|
772
|
+
*/
|
|
773
|
+
annotations: AnnotationsSchema.optional(),
|
|
774
|
+
/**
|
|
775
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
776
|
+
* for notes on _meta usage.
|
|
777
|
+
*/
|
|
778
|
+
_meta: record(string(), unknown()).optional()
|
|
779
|
+
});
|
|
780
|
+
var AudioContentSchema = object({
|
|
781
|
+
type: literal("audio"),
|
|
782
|
+
/**
|
|
783
|
+
* The base64-encoded audio data.
|
|
784
|
+
*/
|
|
785
|
+
data: Base64Schema,
|
|
786
|
+
/**
|
|
787
|
+
* The MIME type of the audio. Different providers may support different audio types.
|
|
788
|
+
*/
|
|
789
|
+
mimeType: string(),
|
|
790
|
+
/**
|
|
791
|
+
* Optional annotations for the client.
|
|
792
|
+
*/
|
|
793
|
+
annotations: AnnotationsSchema.optional(),
|
|
794
|
+
/**
|
|
795
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
796
|
+
* for notes on _meta usage.
|
|
797
|
+
*/
|
|
798
|
+
_meta: record(string(), unknown()).optional()
|
|
799
|
+
});
|
|
800
|
+
var ToolUseContentSchema = object({
|
|
801
|
+
type: literal("tool_use"),
|
|
802
|
+
/**
|
|
803
|
+
* The name of the tool to invoke.
|
|
804
|
+
* Must match a tool name from the request's tools array.
|
|
805
|
+
*/
|
|
806
|
+
name: string(),
|
|
807
|
+
/**
|
|
808
|
+
* Unique identifier for this tool call.
|
|
809
|
+
* Used to correlate with ToolResultContent in subsequent messages.
|
|
810
|
+
*/
|
|
811
|
+
id: string(),
|
|
812
|
+
/**
|
|
813
|
+
* Arguments to pass to the tool.
|
|
814
|
+
* Must conform to the tool's inputSchema.
|
|
815
|
+
*/
|
|
816
|
+
input: record(string(), unknown()),
|
|
817
|
+
/**
|
|
818
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
819
|
+
* for notes on _meta usage.
|
|
820
|
+
*/
|
|
821
|
+
_meta: record(string(), unknown()).optional()
|
|
822
|
+
});
|
|
823
|
+
var EmbeddedResourceSchema = object({
|
|
824
|
+
type: literal("resource"),
|
|
825
|
+
resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
|
|
826
|
+
/**
|
|
827
|
+
* Optional annotations for the client.
|
|
828
|
+
*/
|
|
829
|
+
annotations: AnnotationsSchema.optional(),
|
|
830
|
+
/**
|
|
831
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
832
|
+
* for notes on _meta usage.
|
|
833
|
+
*/
|
|
834
|
+
_meta: record(string(), unknown()).optional()
|
|
835
|
+
});
|
|
836
|
+
var ResourceLinkSchema = ResourceSchema.extend({
|
|
837
|
+
type: literal("resource_link")
|
|
838
|
+
});
|
|
839
|
+
var ContentBlockSchema = union([
|
|
840
|
+
TextContentSchema,
|
|
841
|
+
ImageContentSchema,
|
|
842
|
+
AudioContentSchema,
|
|
843
|
+
ResourceLinkSchema,
|
|
844
|
+
EmbeddedResourceSchema
|
|
845
|
+
]);
|
|
846
|
+
var PromptMessageSchema = object({
|
|
847
|
+
role: RoleSchema,
|
|
848
|
+
content: ContentBlockSchema
|
|
849
|
+
});
|
|
850
|
+
var GetPromptResultSchema = ResultSchema.extend({
|
|
851
|
+
/**
|
|
852
|
+
* An optional description for the prompt.
|
|
853
|
+
*/
|
|
854
|
+
description: string().optional(),
|
|
855
|
+
messages: array(PromptMessageSchema)
|
|
856
|
+
});
|
|
857
|
+
var PromptListChangedNotificationSchema = NotificationSchema.extend({
|
|
858
|
+
method: literal("notifications/prompts/list_changed"),
|
|
859
|
+
params: NotificationsParamsSchema.optional()
|
|
860
|
+
});
|
|
861
|
+
var ToolAnnotationsSchema = object({
|
|
862
|
+
/**
|
|
863
|
+
* A human-readable title for the tool.
|
|
864
|
+
*/
|
|
865
|
+
title: string().optional(),
|
|
866
|
+
/**
|
|
867
|
+
* If true, the tool does not modify its environment.
|
|
868
|
+
*
|
|
869
|
+
* Default: false
|
|
870
|
+
*/
|
|
871
|
+
readOnlyHint: boolean().optional(),
|
|
872
|
+
/**
|
|
873
|
+
* If true, the tool may perform destructive updates to its environment.
|
|
874
|
+
* If false, the tool performs only additive updates.
|
|
875
|
+
*
|
|
876
|
+
* (This property is meaningful only when `readOnlyHint == false`)
|
|
877
|
+
*
|
|
878
|
+
* Default: true
|
|
879
|
+
*/
|
|
880
|
+
destructiveHint: boolean().optional(),
|
|
881
|
+
/**
|
|
882
|
+
* If true, calling the tool repeatedly with the same arguments
|
|
883
|
+
* will have no additional effect on the its environment.
|
|
884
|
+
*
|
|
885
|
+
* (This property is meaningful only when `readOnlyHint == false`)
|
|
886
|
+
*
|
|
887
|
+
* Default: false
|
|
888
|
+
*/
|
|
889
|
+
idempotentHint: boolean().optional(),
|
|
890
|
+
/**
|
|
891
|
+
* If true, this tool may interact with an "open world" of external
|
|
892
|
+
* entities. If false, the tool's domain of interaction is closed.
|
|
893
|
+
* For example, the world of a web search tool is open, whereas that
|
|
894
|
+
* of a memory tool is not.
|
|
895
|
+
*
|
|
896
|
+
* Default: true
|
|
897
|
+
*/
|
|
898
|
+
openWorldHint: boolean().optional()
|
|
899
|
+
});
|
|
900
|
+
var ToolExecutionSchema = object({
|
|
901
|
+
/**
|
|
902
|
+
* Indicates the tool's preference for task-augmented execution.
|
|
903
|
+
* - "required": Clients MUST invoke the tool as a task
|
|
904
|
+
* - "optional": Clients MAY invoke the tool as a task or normal request
|
|
905
|
+
* - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
|
|
906
|
+
*
|
|
907
|
+
* If not present, defaults to "forbidden".
|
|
908
|
+
*/
|
|
909
|
+
taskSupport: _enum(["required", "optional", "forbidden"]).optional()
|
|
910
|
+
});
|
|
911
|
+
var ToolSchema = object({
|
|
912
|
+
...BaseMetadataSchema.shape,
|
|
913
|
+
...IconsSchema.shape,
|
|
914
|
+
/**
|
|
915
|
+
* A human-readable description of the tool.
|
|
916
|
+
*/
|
|
917
|
+
description: string().optional(),
|
|
918
|
+
/**
|
|
919
|
+
* A JSON Schema 2020-12 object defining the expected parameters for the tool.
|
|
920
|
+
* Must have type: 'object' at the root level per MCP spec.
|
|
921
|
+
*/
|
|
922
|
+
inputSchema: object({
|
|
923
|
+
type: literal("object"),
|
|
924
|
+
properties: record(string(), AssertObjectSchema).optional(),
|
|
925
|
+
required: array(string()).optional()
|
|
926
|
+
}).catchall(unknown()),
|
|
927
|
+
/**
|
|
928
|
+
* An optional JSON Schema 2020-12 object defining the structure of the tool's output
|
|
929
|
+
* returned in the structuredContent field of a CallToolResult.
|
|
930
|
+
* Must have type: 'object' at the root level per MCP spec.
|
|
931
|
+
*/
|
|
932
|
+
outputSchema: object({
|
|
933
|
+
type: literal("object"),
|
|
934
|
+
properties: record(string(), AssertObjectSchema).optional(),
|
|
935
|
+
required: array(string()).optional()
|
|
936
|
+
}).catchall(unknown()).optional(),
|
|
937
|
+
/**
|
|
938
|
+
* Optional additional tool information.
|
|
939
|
+
*/
|
|
940
|
+
annotations: ToolAnnotationsSchema.optional(),
|
|
941
|
+
/**
|
|
942
|
+
* Execution-related properties for this tool.
|
|
943
|
+
*/
|
|
944
|
+
execution: ToolExecutionSchema.optional(),
|
|
945
|
+
/**
|
|
946
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
947
|
+
* for notes on _meta usage.
|
|
948
|
+
*/
|
|
949
|
+
_meta: record(string(), unknown()).optional()
|
|
950
|
+
});
|
|
951
|
+
var ListToolsRequestSchema = PaginatedRequestSchema.extend({
|
|
952
|
+
method: literal("tools/list")
|
|
953
|
+
});
|
|
954
|
+
var ListToolsResultSchema = PaginatedResultSchema.extend({
|
|
955
|
+
tools: array(ToolSchema)
|
|
956
|
+
});
|
|
957
|
+
var CallToolResultSchema = ResultSchema.extend({
|
|
958
|
+
/**
|
|
959
|
+
* A list of content objects that represent the result of the tool call.
|
|
960
|
+
*
|
|
961
|
+
* If the Tool does not define an outputSchema, this field MUST be present in the result.
|
|
962
|
+
* For backwards compatibility, this field is always present, but it may be empty.
|
|
963
|
+
*/
|
|
964
|
+
content: array(ContentBlockSchema).default([]),
|
|
965
|
+
/**
|
|
966
|
+
* An object containing structured tool output.
|
|
967
|
+
*
|
|
968
|
+
* If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
|
|
969
|
+
*/
|
|
970
|
+
structuredContent: record(string(), unknown()).optional(),
|
|
971
|
+
/**
|
|
972
|
+
* Whether the tool call ended in an error.
|
|
973
|
+
*
|
|
974
|
+
* If not set, this is assumed to be false (the call was successful).
|
|
975
|
+
*
|
|
976
|
+
* Any errors that originate from the tool SHOULD be reported inside the result
|
|
977
|
+
* object, with `isError` set to true, _not_ as an MCP protocol-level error
|
|
978
|
+
* response. Otherwise, the LLM would not be able to see that an error occurred
|
|
979
|
+
* and self-correct.
|
|
980
|
+
*
|
|
981
|
+
* However, any errors in _finding_ the tool, an error indicating that the
|
|
982
|
+
* server does not support tool calls, or any other exceptional conditions,
|
|
983
|
+
* should be reported as an MCP error response.
|
|
984
|
+
*/
|
|
985
|
+
isError: boolean().optional()
|
|
986
|
+
});
|
|
987
|
+
var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
|
|
988
|
+
toolResult: unknown()
|
|
989
|
+
}));
|
|
990
|
+
var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
991
|
+
/**
|
|
992
|
+
* The name of the tool to call.
|
|
993
|
+
*/
|
|
994
|
+
name: string(),
|
|
995
|
+
/**
|
|
996
|
+
* Arguments to pass to the tool.
|
|
997
|
+
*/
|
|
998
|
+
arguments: record(string(), unknown()).optional()
|
|
999
|
+
});
|
|
1000
|
+
var CallToolRequestSchema = RequestSchema.extend({
|
|
1001
|
+
method: literal("tools/call"),
|
|
1002
|
+
params: CallToolRequestParamsSchema
|
|
1003
|
+
});
|
|
1004
|
+
var ToolListChangedNotificationSchema = NotificationSchema.extend({
|
|
1005
|
+
method: literal("notifications/tools/list_changed"),
|
|
1006
|
+
params: NotificationsParamsSchema.optional()
|
|
1007
|
+
});
|
|
1008
|
+
var ListChangedOptionsBaseSchema = object({
|
|
1009
|
+
/**
|
|
1010
|
+
* If true, the list will be refreshed automatically when a list changed notification is received.
|
|
1011
|
+
* The callback will be called with the updated list.
|
|
1012
|
+
*
|
|
1013
|
+
* If false, the callback will be called with null items, allowing manual refresh.
|
|
1014
|
+
*
|
|
1015
|
+
* @default true
|
|
1016
|
+
*/
|
|
1017
|
+
autoRefresh: boolean().default(true),
|
|
1018
|
+
/**
|
|
1019
|
+
* Debounce time in milliseconds for list changed notification processing.
|
|
1020
|
+
*
|
|
1021
|
+
* Multiple notifications received within this timeframe will only trigger one refresh.
|
|
1022
|
+
* Set to 0 to disable debouncing.
|
|
1023
|
+
*
|
|
1024
|
+
* @default 300
|
|
1025
|
+
*/
|
|
1026
|
+
debounceMs: number().int().nonnegative().default(300)
|
|
1027
|
+
});
|
|
1028
|
+
var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
|
|
1029
|
+
var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
1030
|
+
/**
|
|
1031
|
+
* The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
|
|
1032
|
+
*/
|
|
1033
|
+
level: LoggingLevelSchema
|
|
1034
|
+
});
|
|
1035
|
+
var SetLevelRequestSchema = RequestSchema.extend({
|
|
1036
|
+
method: literal("logging/setLevel"),
|
|
1037
|
+
params: SetLevelRequestParamsSchema
|
|
1038
|
+
});
|
|
1039
|
+
var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
1040
|
+
/**
|
|
1041
|
+
* The severity of this log message.
|
|
1042
|
+
*/
|
|
1043
|
+
level: LoggingLevelSchema,
|
|
1044
|
+
/**
|
|
1045
|
+
* An optional name of the logger issuing this message.
|
|
1046
|
+
*/
|
|
1047
|
+
logger: string().optional(),
|
|
1048
|
+
/**
|
|
1049
|
+
* The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
|
|
1050
|
+
*/
|
|
1051
|
+
data: unknown()
|
|
1052
|
+
});
|
|
1053
|
+
var LoggingMessageNotificationSchema = NotificationSchema.extend({
|
|
1054
|
+
method: literal("notifications/message"),
|
|
1055
|
+
params: LoggingMessageNotificationParamsSchema
|
|
1056
|
+
});
|
|
1057
|
+
var ModelHintSchema = object({
|
|
1058
|
+
/**
|
|
1059
|
+
* A hint for a model name.
|
|
1060
|
+
*/
|
|
1061
|
+
name: string().optional()
|
|
1062
|
+
});
|
|
1063
|
+
var ModelPreferencesSchema = object({
|
|
1064
|
+
/**
|
|
1065
|
+
* Optional hints to use for model selection.
|
|
1066
|
+
*/
|
|
1067
|
+
hints: array(ModelHintSchema).optional(),
|
|
1068
|
+
/**
|
|
1069
|
+
* How much to prioritize cost when selecting a model.
|
|
1070
|
+
*/
|
|
1071
|
+
costPriority: number().min(0).max(1).optional(),
|
|
1072
|
+
/**
|
|
1073
|
+
* How much to prioritize sampling speed (latency) when selecting a model.
|
|
1074
|
+
*/
|
|
1075
|
+
speedPriority: number().min(0).max(1).optional(),
|
|
1076
|
+
/**
|
|
1077
|
+
* How much to prioritize intelligence and capabilities when selecting a model.
|
|
1078
|
+
*/
|
|
1079
|
+
intelligencePriority: number().min(0).max(1).optional()
|
|
1080
|
+
});
|
|
1081
|
+
var ToolChoiceSchema = object({
|
|
1082
|
+
/**
|
|
1083
|
+
* Controls when tools are used:
|
|
1084
|
+
* - "auto": Model decides whether to use tools (default)
|
|
1085
|
+
* - "required": Model MUST use at least one tool before completing
|
|
1086
|
+
* - "none": Model MUST NOT use any tools
|
|
1087
|
+
*/
|
|
1088
|
+
mode: _enum(["auto", "required", "none"]).optional()
|
|
1089
|
+
});
|
|
1090
|
+
var ToolResultContentSchema = object({
|
|
1091
|
+
type: literal("tool_result"),
|
|
1092
|
+
toolUseId: string().describe("The unique identifier for the corresponding tool call."),
|
|
1093
|
+
content: array(ContentBlockSchema).default([]),
|
|
1094
|
+
structuredContent: object({}).loose().optional(),
|
|
1095
|
+
isError: boolean().optional(),
|
|
1096
|
+
/**
|
|
1097
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
1098
|
+
* for notes on _meta usage.
|
|
1099
|
+
*/
|
|
1100
|
+
_meta: record(string(), unknown()).optional()
|
|
1101
|
+
});
|
|
1102
|
+
var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
|
|
1103
|
+
var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
|
|
1104
|
+
TextContentSchema,
|
|
1105
|
+
ImageContentSchema,
|
|
1106
|
+
AudioContentSchema,
|
|
1107
|
+
ToolUseContentSchema,
|
|
1108
|
+
ToolResultContentSchema
|
|
1109
|
+
]);
|
|
1110
|
+
var SamplingMessageSchema = object({
|
|
1111
|
+
role: RoleSchema,
|
|
1112
|
+
content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
|
|
1113
|
+
/**
|
|
1114
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
1115
|
+
* for notes on _meta usage.
|
|
1116
|
+
*/
|
|
1117
|
+
_meta: record(string(), unknown()).optional()
|
|
1118
|
+
});
|
|
1119
|
+
var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1120
|
+
messages: array(SamplingMessageSchema),
|
|
1121
|
+
/**
|
|
1122
|
+
* The server's preferences for which model to select. The client MAY modify or omit this request.
|
|
1123
|
+
*/
|
|
1124
|
+
modelPreferences: ModelPreferencesSchema.optional(),
|
|
1125
|
+
/**
|
|
1126
|
+
* An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
|
|
1127
|
+
*/
|
|
1128
|
+
systemPrompt: string().optional(),
|
|
1129
|
+
/**
|
|
1130
|
+
* A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
|
|
1131
|
+
* The client MAY ignore this request.
|
|
1132
|
+
*
|
|
1133
|
+
* Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
|
|
1134
|
+
* declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
|
|
1135
|
+
*/
|
|
1136
|
+
includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
|
|
1137
|
+
temperature: number().optional(),
|
|
1138
|
+
/**
|
|
1139
|
+
* The requested maximum number of tokens to sample (to prevent runaway completions).
|
|
1140
|
+
*
|
|
1141
|
+
* The client MAY choose to sample fewer tokens than the requested maximum.
|
|
1142
|
+
*/
|
|
1143
|
+
maxTokens: number().int(),
|
|
1144
|
+
stopSequences: array(string()).optional(),
|
|
1145
|
+
/**
|
|
1146
|
+
* Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
|
|
1147
|
+
*/
|
|
1148
|
+
metadata: AssertObjectSchema.optional(),
|
|
1149
|
+
/**
|
|
1150
|
+
* Tools that the model may use during generation.
|
|
1151
|
+
* The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
|
|
1152
|
+
*/
|
|
1153
|
+
tools: array(ToolSchema).optional(),
|
|
1154
|
+
/**
|
|
1155
|
+
* Controls how the model uses tools.
|
|
1156
|
+
* The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
|
|
1157
|
+
* Default is `{ mode: "auto" }`.
|
|
1158
|
+
*/
|
|
1159
|
+
toolChoice: ToolChoiceSchema.optional()
|
|
1160
|
+
});
|
|
1161
|
+
var CreateMessageRequestSchema = RequestSchema.extend({
|
|
1162
|
+
method: literal("sampling/createMessage"),
|
|
1163
|
+
params: CreateMessageRequestParamsSchema
|
|
1164
|
+
});
|
|
1165
|
+
var CreateMessageResultSchema = ResultSchema.extend({
|
|
1166
|
+
/**
|
|
1167
|
+
* The name of the model that generated the message.
|
|
1168
|
+
*/
|
|
1169
|
+
model: string(),
|
|
1170
|
+
/**
|
|
1171
|
+
* The reason why sampling stopped, if known.
|
|
1172
|
+
*
|
|
1173
|
+
* Standard values:
|
|
1174
|
+
* - "endTurn": Natural end of the assistant's turn
|
|
1175
|
+
* - "stopSequence": A stop sequence was encountered
|
|
1176
|
+
* - "maxTokens": Maximum token limit was reached
|
|
1177
|
+
*
|
|
1178
|
+
* This field is an open string to allow for provider-specific stop reasons.
|
|
1179
|
+
*/
|
|
1180
|
+
stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string())),
|
|
1181
|
+
role: RoleSchema,
|
|
1182
|
+
/**
|
|
1183
|
+
* Response content. Single content block (text, image, or audio).
|
|
1184
|
+
*/
|
|
1185
|
+
content: SamplingContentSchema
|
|
1186
|
+
});
|
|
1187
|
+
var CreateMessageResultWithToolsSchema = ResultSchema.extend({
|
|
1188
|
+
/**
|
|
1189
|
+
* The name of the model that generated the message.
|
|
1190
|
+
*/
|
|
1191
|
+
model: string(),
|
|
1192
|
+
/**
|
|
1193
|
+
* The reason why sampling stopped, if known.
|
|
1194
|
+
*
|
|
1195
|
+
* Standard values:
|
|
1196
|
+
* - "endTurn": Natural end of the assistant's turn
|
|
1197
|
+
* - "stopSequence": A stop sequence was encountered
|
|
1198
|
+
* - "maxTokens": Maximum token limit was reached
|
|
1199
|
+
* - "toolUse": The model wants to use one or more tools
|
|
1200
|
+
*
|
|
1201
|
+
* This field is an open string to allow for provider-specific stop reasons.
|
|
1202
|
+
*/
|
|
1203
|
+
stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string())),
|
|
1204
|
+
role: RoleSchema,
|
|
1205
|
+
/**
|
|
1206
|
+
* Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
|
|
1207
|
+
*/
|
|
1208
|
+
content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
|
|
1209
|
+
});
|
|
1210
|
+
var BooleanSchemaSchema = object({
|
|
1211
|
+
type: literal("boolean"),
|
|
1212
|
+
title: string().optional(),
|
|
1213
|
+
description: string().optional(),
|
|
1214
|
+
default: boolean().optional()
|
|
1215
|
+
});
|
|
1216
|
+
var StringSchemaSchema = object({
|
|
1217
|
+
type: literal("string"),
|
|
1218
|
+
title: string().optional(),
|
|
1219
|
+
description: string().optional(),
|
|
1220
|
+
minLength: number().optional(),
|
|
1221
|
+
maxLength: number().optional(),
|
|
1222
|
+
format: _enum(["email", "uri", "date", "date-time"]).optional(),
|
|
1223
|
+
default: string().optional()
|
|
1224
|
+
});
|
|
1225
|
+
var NumberSchemaSchema = object({
|
|
1226
|
+
type: _enum(["number", "integer"]),
|
|
1227
|
+
title: string().optional(),
|
|
1228
|
+
description: string().optional(),
|
|
1229
|
+
minimum: number().optional(),
|
|
1230
|
+
maximum: number().optional(),
|
|
1231
|
+
default: number().optional()
|
|
1232
|
+
});
|
|
1233
|
+
var UntitledSingleSelectEnumSchemaSchema = object({
|
|
1234
|
+
type: literal("string"),
|
|
1235
|
+
title: string().optional(),
|
|
1236
|
+
description: string().optional(),
|
|
1237
|
+
enum: array(string()),
|
|
1238
|
+
default: string().optional()
|
|
1239
|
+
});
|
|
1240
|
+
var TitledSingleSelectEnumSchemaSchema = object({
|
|
1241
|
+
type: literal("string"),
|
|
1242
|
+
title: string().optional(),
|
|
1243
|
+
description: string().optional(),
|
|
1244
|
+
oneOf: array(object({
|
|
1245
|
+
const: string(),
|
|
1246
|
+
title: string()
|
|
1247
|
+
})),
|
|
1248
|
+
default: string().optional()
|
|
1249
|
+
});
|
|
1250
|
+
var LegacyTitledEnumSchemaSchema = object({
|
|
1251
|
+
type: literal("string"),
|
|
1252
|
+
title: string().optional(),
|
|
1253
|
+
description: string().optional(),
|
|
1254
|
+
enum: array(string()),
|
|
1255
|
+
enumNames: array(string()).optional(),
|
|
1256
|
+
default: string().optional()
|
|
1257
|
+
});
|
|
1258
|
+
var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
|
|
1259
|
+
var UntitledMultiSelectEnumSchemaSchema = object({
|
|
1260
|
+
type: literal("array"),
|
|
1261
|
+
title: string().optional(),
|
|
1262
|
+
description: string().optional(),
|
|
1263
|
+
minItems: number().optional(),
|
|
1264
|
+
maxItems: number().optional(),
|
|
1265
|
+
items: object({
|
|
1266
|
+
type: literal("string"),
|
|
1267
|
+
enum: array(string())
|
|
1268
|
+
}),
|
|
1269
|
+
default: array(string()).optional()
|
|
1270
|
+
});
|
|
1271
|
+
var TitledMultiSelectEnumSchemaSchema = object({
|
|
1272
|
+
type: literal("array"),
|
|
1273
|
+
title: string().optional(),
|
|
1274
|
+
description: string().optional(),
|
|
1275
|
+
minItems: number().optional(),
|
|
1276
|
+
maxItems: number().optional(),
|
|
1277
|
+
items: object({
|
|
1278
|
+
anyOf: array(object({
|
|
1279
|
+
const: string(),
|
|
1280
|
+
title: string()
|
|
1281
|
+
}))
|
|
1282
|
+
}),
|
|
1283
|
+
default: array(string()).optional()
|
|
1284
|
+
});
|
|
1285
|
+
var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
|
|
1286
|
+
var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
|
|
1287
|
+
var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
|
|
1288
|
+
var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1289
|
+
/**
|
|
1290
|
+
* The elicitation mode.
|
|
1291
|
+
*
|
|
1292
|
+
* Optional for backward compatibility. Clients MUST treat missing mode as "form".
|
|
1293
|
+
*/
|
|
1294
|
+
mode: literal("form").optional(),
|
|
1295
|
+
/**
|
|
1296
|
+
* The message to present to the user describing what information is being requested.
|
|
1297
|
+
*/
|
|
1298
|
+
message: string(),
|
|
1299
|
+
/**
|
|
1300
|
+
* A restricted subset of JSON Schema.
|
|
1301
|
+
* Only top-level properties are allowed, without nesting.
|
|
1302
|
+
*/
|
|
1303
|
+
requestedSchema: object({
|
|
1304
|
+
type: literal("object"),
|
|
1305
|
+
properties: record(string(), PrimitiveSchemaDefinitionSchema),
|
|
1306
|
+
required: array(string()).optional()
|
|
1307
|
+
})
|
|
1308
|
+
});
|
|
1309
|
+
var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1310
|
+
/**
|
|
1311
|
+
* The elicitation mode.
|
|
1312
|
+
*/
|
|
1313
|
+
mode: literal("url"),
|
|
1314
|
+
/**
|
|
1315
|
+
* The message to present to the user explaining why the interaction is needed.
|
|
1316
|
+
*/
|
|
1317
|
+
message: string(),
|
|
1318
|
+
/**
|
|
1319
|
+
* The ID of the elicitation, which must be unique within the context of the server.
|
|
1320
|
+
* The client MUST treat this ID as an opaque value.
|
|
1321
|
+
*/
|
|
1322
|
+
elicitationId: string(),
|
|
1323
|
+
/**
|
|
1324
|
+
* The URL that the user should navigate to.
|
|
1325
|
+
*/
|
|
1326
|
+
url: string().url()
|
|
1327
|
+
});
|
|
1328
|
+
var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
|
|
1329
|
+
var ElicitRequestSchema = RequestSchema.extend({
|
|
1330
|
+
method: literal("elicitation/create"),
|
|
1331
|
+
params: ElicitRequestParamsSchema
|
|
1332
|
+
});
|
|
1333
|
+
var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
1334
|
+
/**
|
|
1335
|
+
* The ID of the elicitation that completed.
|
|
1336
|
+
*/
|
|
1337
|
+
elicitationId: string()
|
|
1338
|
+
});
|
|
1339
|
+
var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
|
|
1340
|
+
method: literal("notifications/elicitation/complete"),
|
|
1341
|
+
params: ElicitationCompleteNotificationParamsSchema
|
|
1342
|
+
});
|
|
1343
|
+
var ElicitResultSchema = ResultSchema.extend({
|
|
1344
|
+
/**
|
|
1345
|
+
* The user action in response to the elicitation.
|
|
1346
|
+
* - "accept": User submitted the form/confirmed the action
|
|
1347
|
+
* - "decline": User explicitly decline the action
|
|
1348
|
+
* - "cancel": User dismissed without making an explicit choice
|
|
1349
|
+
*/
|
|
1350
|
+
action: _enum(["accept", "decline", "cancel"]),
|
|
1351
|
+
/**
|
|
1352
|
+
* The submitted form data, only present when action is "accept".
|
|
1353
|
+
* Contains values matching the requested schema.
|
|
1354
|
+
* Per MCP spec, content is "typically omitted" for decline/cancel actions.
|
|
1355
|
+
* We normalize null to undefined for leniency while maintaining type compatibility.
|
|
1356
|
+
*/
|
|
1357
|
+
content: preprocess((val) => val === null ? void 0 : val, record(string(), union([string(), number(), boolean(), array(string())])).optional())
|
|
1358
|
+
});
|
|
1359
|
+
var ResourceTemplateReferenceSchema = object({
|
|
1360
|
+
type: literal("ref/resource"),
|
|
1361
|
+
/**
|
|
1362
|
+
* The URI or URI template of the resource.
|
|
1363
|
+
*/
|
|
1364
|
+
uri: string()
|
|
1365
|
+
});
|
|
1366
|
+
var PromptReferenceSchema = object({
|
|
1367
|
+
type: literal("ref/prompt"),
|
|
1368
|
+
/**
|
|
1369
|
+
* The name of the prompt or prompt template
|
|
1370
|
+
*/
|
|
1371
|
+
name: string()
|
|
1372
|
+
});
|
|
1373
|
+
var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
1374
|
+
ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
|
|
1375
|
+
/**
|
|
1376
|
+
* The argument's information
|
|
1377
|
+
*/
|
|
1378
|
+
argument: object({
|
|
1379
|
+
/**
|
|
1380
|
+
* The name of the argument
|
|
1381
|
+
*/
|
|
1382
|
+
name: string(),
|
|
1383
|
+
/**
|
|
1384
|
+
* The value of the argument to use for completion matching.
|
|
1385
|
+
*/
|
|
1386
|
+
value: string()
|
|
1387
|
+
}),
|
|
1388
|
+
context: object({
|
|
1389
|
+
/**
|
|
1390
|
+
* Previously-resolved variables in a URI template or prompt.
|
|
1391
|
+
*/
|
|
1392
|
+
arguments: record(string(), string()).optional()
|
|
1393
|
+
}).optional()
|
|
1394
|
+
});
|
|
1395
|
+
var CompleteRequestSchema = RequestSchema.extend({
|
|
1396
|
+
method: literal("completion/complete"),
|
|
1397
|
+
params: CompleteRequestParamsSchema
|
|
1398
|
+
});
|
|
1399
|
+
var CompleteResultSchema = ResultSchema.extend({
|
|
1400
|
+
completion: looseObject({
|
|
1401
|
+
/**
|
|
1402
|
+
* An array of completion values. Must not exceed 100 items.
|
|
1403
|
+
*/
|
|
1404
|
+
values: array(string()).max(100),
|
|
1405
|
+
/**
|
|
1406
|
+
* The total number of completion options available. This can exceed the number of values actually sent in the response.
|
|
1407
|
+
*/
|
|
1408
|
+
total: optional(number().int()),
|
|
1409
|
+
/**
|
|
1410
|
+
* Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
|
|
1411
|
+
*/
|
|
1412
|
+
hasMore: optional(boolean())
|
|
1413
|
+
})
|
|
1414
|
+
});
|
|
1415
|
+
var RootSchema = object({
|
|
1416
|
+
/**
|
|
1417
|
+
* The URI identifying the root. This *must* start with file:// for now.
|
|
1418
|
+
*/
|
|
1419
|
+
uri: string().startsWith("file://"),
|
|
1420
|
+
/**
|
|
1421
|
+
* An optional name for the root.
|
|
1422
|
+
*/
|
|
1423
|
+
name: string().optional(),
|
|
1424
|
+
/**
|
|
1425
|
+
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
1426
|
+
* for notes on _meta usage.
|
|
1427
|
+
*/
|
|
1428
|
+
_meta: record(string(), unknown()).optional()
|
|
1429
|
+
});
|
|
1430
|
+
var ListRootsRequestSchema = RequestSchema.extend({
|
|
1431
|
+
method: literal("roots/list"),
|
|
1432
|
+
params: BaseRequestParamsSchema.optional()
|
|
1433
|
+
});
|
|
1434
|
+
var ListRootsResultSchema = ResultSchema.extend({
|
|
1435
|
+
roots: array(RootSchema)
|
|
1436
|
+
});
|
|
1437
|
+
var RootsListChangedNotificationSchema = NotificationSchema.extend({
|
|
1438
|
+
method: literal("notifications/roots/list_changed"),
|
|
1439
|
+
params: NotificationsParamsSchema.optional()
|
|
1440
|
+
});
|
|
1441
|
+
var ClientRequestSchema = union([
|
|
1442
|
+
PingRequestSchema,
|
|
1443
|
+
InitializeRequestSchema,
|
|
1444
|
+
CompleteRequestSchema,
|
|
1445
|
+
SetLevelRequestSchema,
|
|
1446
|
+
GetPromptRequestSchema,
|
|
1447
|
+
ListPromptsRequestSchema,
|
|
1448
|
+
ListResourcesRequestSchema,
|
|
1449
|
+
ListResourceTemplatesRequestSchema,
|
|
1450
|
+
ReadResourceRequestSchema,
|
|
1451
|
+
SubscribeRequestSchema,
|
|
1452
|
+
UnsubscribeRequestSchema,
|
|
1453
|
+
CallToolRequestSchema,
|
|
1454
|
+
ListToolsRequestSchema,
|
|
1455
|
+
GetTaskRequestSchema,
|
|
1456
|
+
GetTaskPayloadRequestSchema,
|
|
1457
|
+
ListTasksRequestSchema,
|
|
1458
|
+
CancelTaskRequestSchema
|
|
1459
|
+
]);
|
|
1460
|
+
var ClientNotificationSchema = union([
|
|
1461
|
+
CancelledNotificationSchema,
|
|
1462
|
+
ProgressNotificationSchema,
|
|
1463
|
+
InitializedNotificationSchema,
|
|
1464
|
+
RootsListChangedNotificationSchema,
|
|
1465
|
+
TaskStatusNotificationSchema
|
|
1466
|
+
]);
|
|
1467
|
+
var ClientResultSchema = union([
|
|
1468
|
+
EmptyResultSchema,
|
|
1469
|
+
CreateMessageResultSchema,
|
|
1470
|
+
CreateMessageResultWithToolsSchema,
|
|
1471
|
+
ElicitResultSchema,
|
|
1472
|
+
ListRootsResultSchema,
|
|
1473
|
+
GetTaskResultSchema,
|
|
1474
|
+
ListTasksResultSchema,
|
|
1475
|
+
CreateTaskResultSchema
|
|
1476
|
+
]);
|
|
1477
|
+
var ServerRequestSchema = union([
|
|
1478
|
+
PingRequestSchema,
|
|
1479
|
+
CreateMessageRequestSchema,
|
|
1480
|
+
ElicitRequestSchema,
|
|
1481
|
+
ListRootsRequestSchema,
|
|
1482
|
+
GetTaskRequestSchema,
|
|
1483
|
+
GetTaskPayloadRequestSchema,
|
|
1484
|
+
ListTasksRequestSchema,
|
|
1485
|
+
CancelTaskRequestSchema
|
|
1486
|
+
]);
|
|
1487
|
+
var ServerNotificationSchema = union([
|
|
1488
|
+
CancelledNotificationSchema,
|
|
1489
|
+
ProgressNotificationSchema,
|
|
1490
|
+
LoggingMessageNotificationSchema,
|
|
1491
|
+
ResourceUpdatedNotificationSchema,
|
|
1492
|
+
ResourceListChangedNotificationSchema,
|
|
1493
|
+
ToolListChangedNotificationSchema,
|
|
1494
|
+
PromptListChangedNotificationSchema,
|
|
1495
|
+
TaskStatusNotificationSchema,
|
|
1496
|
+
ElicitationCompleteNotificationSchema
|
|
1497
|
+
]);
|
|
1498
|
+
var ServerResultSchema = union([
|
|
1499
|
+
EmptyResultSchema,
|
|
1500
|
+
InitializeResultSchema,
|
|
1501
|
+
CompleteResultSchema,
|
|
1502
|
+
GetPromptResultSchema,
|
|
1503
|
+
ListPromptsResultSchema,
|
|
1504
|
+
ListResourcesResultSchema,
|
|
1505
|
+
ListResourceTemplatesResultSchema,
|
|
1506
|
+
ReadResourceResultSchema,
|
|
1507
|
+
CallToolResultSchema,
|
|
1508
|
+
ListToolsResultSchema,
|
|
1509
|
+
GetTaskResultSchema,
|
|
1510
|
+
ListTasksResultSchema,
|
|
1511
|
+
CreateTaskResultSchema
|
|
1512
|
+
]);
|
|
1513
|
+
var McpError = class _McpError extends Error {
|
|
1514
|
+
constructor(code, message, data) {
|
|
1515
|
+
super(`MCP error ${code}: ${message}`);
|
|
1516
|
+
this.code = code;
|
|
1517
|
+
this.data = data;
|
|
1518
|
+
this.name = "McpError";
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* Factory method to create the appropriate error type based on the error code and data
|
|
1522
|
+
*/
|
|
1523
|
+
static fromError(code, message, data) {
|
|
1524
|
+
if (code === ErrorCode.UrlElicitationRequired && data) {
|
|
1525
|
+
const errorData = data;
|
|
1526
|
+
if (errorData.elicitations) {
|
|
1527
|
+
return new UrlElicitationRequiredError(errorData.elicitations, message);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
return new _McpError(code, message, data);
|
|
1531
|
+
}
|
|
1532
|
+
};
|
|
1533
|
+
var UrlElicitationRequiredError = class extends McpError {
|
|
1534
|
+
constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
|
|
1535
|
+
super(ErrorCode.UrlElicitationRequired, message, {
|
|
1536
|
+
elicitations
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
get elicitations() {
|
|
1540
|
+
return this.data?.elicitations ?? [];
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
|
|
1544
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
|
|
1545
|
+
function isZ4Schema(s2) {
|
|
1546
|
+
const schema = s2;
|
|
1547
|
+
return !!schema._zod;
|
|
1548
|
+
}
|
|
1549
|
+
function safeParse2(schema, data) {
|
|
1550
|
+
if (isZ4Schema(schema)) {
|
|
1551
|
+
const result2 = safeParse(schema, data);
|
|
1552
|
+
return result2;
|
|
1553
|
+
}
|
|
1554
|
+
const v3Schema = schema;
|
|
1555
|
+
const result = v3Schema.safeParse(data);
|
|
1556
|
+
return result;
|
|
1557
|
+
}
|
|
1558
|
+
function getObjectShape(schema) {
|
|
1559
|
+
if (!schema)
|
|
1560
|
+
return void 0;
|
|
1561
|
+
let rawShape;
|
|
1562
|
+
if (isZ4Schema(schema)) {
|
|
1563
|
+
const v4Schema = schema;
|
|
1564
|
+
rawShape = v4Schema._zod?.def?.shape;
|
|
1565
|
+
} else {
|
|
1566
|
+
const v3Schema = schema;
|
|
1567
|
+
rawShape = v3Schema.shape;
|
|
1568
|
+
}
|
|
1569
|
+
if (!rawShape)
|
|
1570
|
+
return void 0;
|
|
1571
|
+
if (typeof rawShape === "function") {
|
|
1572
|
+
try {
|
|
1573
|
+
return rawShape();
|
|
1574
|
+
} catch {
|
|
1575
|
+
return void 0;
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
return rawShape;
|
|
1579
|
+
}
|
|
1580
|
+
function getLiteralValue(schema) {
|
|
1581
|
+
if (isZ4Schema(schema)) {
|
|
1582
|
+
const v4Schema = schema;
|
|
1583
|
+
const def2 = v4Schema._zod?.def;
|
|
1584
|
+
if (def2) {
|
|
1585
|
+
if (def2.value !== void 0)
|
|
1586
|
+
return def2.value;
|
|
1587
|
+
if (Array.isArray(def2.values) && def2.values.length > 0) {
|
|
1588
|
+
return def2.values[0];
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
const v3Schema = schema;
|
|
1593
|
+
const def = v3Schema._def;
|
|
1594
|
+
if (def) {
|
|
1595
|
+
if (def.value !== void 0)
|
|
1596
|
+
return def.value;
|
|
1597
|
+
if (Array.isArray(def.values) && def.values.length > 0) {
|
|
1598
|
+
return def.values[0];
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
const directValue = schema.value;
|
|
1602
|
+
if (directValue !== void 0)
|
|
1603
|
+
return directValue;
|
|
1604
|
+
return void 0;
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
|
|
1608
|
+
function isTerminal(status) {
|
|
1609
|
+
return status === "completed" || status === "failed" || status === "cancelled";
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
|
|
1613
|
+
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
|
|
1614
|
+
|
|
1615
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
|
|
1616
|
+
function getMethodLiteral(schema) {
|
|
1617
|
+
const shape = getObjectShape(schema);
|
|
1618
|
+
const methodSchema = shape?.method;
|
|
1619
|
+
if (!methodSchema) {
|
|
1620
|
+
throw new Error("Schema is missing a method literal");
|
|
1621
|
+
}
|
|
1622
|
+
const value = getLiteralValue(methodSchema);
|
|
1623
|
+
if (typeof value !== "string") {
|
|
1624
|
+
throw new Error("Schema method literal must be a string");
|
|
1625
|
+
}
|
|
1626
|
+
return value;
|
|
1627
|
+
}
|
|
1628
|
+
function parseWithCompat(schema, data) {
|
|
1629
|
+
const result = safeParse2(schema, data);
|
|
1630
|
+
if (!result.success) {
|
|
1631
|
+
throw result.error;
|
|
1632
|
+
}
|
|
1633
|
+
return result.data;
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
|
|
1637
|
+
var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
|
|
1638
|
+
var Protocol = class {
|
|
1639
|
+
constructor(_options) {
|
|
1640
|
+
this._options = _options;
|
|
1641
|
+
this._requestMessageId = 0;
|
|
1642
|
+
this._requestHandlers = /* @__PURE__ */ new Map();
|
|
1643
|
+
this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
|
|
1644
|
+
this._notificationHandlers = /* @__PURE__ */ new Map();
|
|
1645
|
+
this._responseHandlers = /* @__PURE__ */ new Map();
|
|
1646
|
+
this._progressHandlers = /* @__PURE__ */ new Map();
|
|
1647
|
+
this._timeoutInfo = /* @__PURE__ */ new Map();
|
|
1648
|
+
this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
|
|
1649
|
+
this._taskProgressTokens = /* @__PURE__ */ new Map();
|
|
1650
|
+
this._requestResolvers = /* @__PURE__ */ new Map();
|
|
1651
|
+
this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
|
|
1652
|
+
this._oncancel(notification);
|
|
1653
|
+
});
|
|
1654
|
+
this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
|
|
1655
|
+
this._onprogress(notification);
|
|
1656
|
+
});
|
|
1657
|
+
this.setRequestHandler(
|
|
1658
|
+
PingRequestSchema,
|
|
1659
|
+
// Automatic pong by default.
|
|
1660
|
+
(_request) => ({})
|
|
1661
|
+
);
|
|
1662
|
+
this._taskStore = _options?.taskStore;
|
|
1663
|
+
this._taskMessageQueue = _options?.taskMessageQueue;
|
|
1664
|
+
if (this._taskStore) {
|
|
1665
|
+
this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
|
|
1666
|
+
const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
|
|
1667
|
+
if (!task) {
|
|
1668
|
+
throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
|
|
1669
|
+
}
|
|
1670
|
+
return {
|
|
1671
|
+
...task
|
|
1672
|
+
};
|
|
1673
|
+
});
|
|
1674
|
+
this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
|
|
1675
|
+
const handleTaskResult = async () => {
|
|
1676
|
+
const taskId = request.params.taskId;
|
|
1677
|
+
if (this._taskMessageQueue) {
|
|
1678
|
+
let queuedMessage;
|
|
1679
|
+
while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
|
|
1680
|
+
if (queuedMessage.type === "response" || queuedMessage.type === "error") {
|
|
1681
|
+
const message = queuedMessage.message;
|
|
1682
|
+
const requestId = message.id;
|
|
1683
|
+
const resolver = this._requestResolvers.get(requestId);
|
|
1684
|
+
if (resolver) {
|
|
1685
|
+
this._requestResolvers.delete(requestId);
|
|
1686
|
+
if (queuedMessage.type === "response") {
|
|
1687
|
+
resolver(message);
|
|
1688
|
+
} else {
|
|
1689
|
+
const errorMessage = message;
|
|
1690
|
+
const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
|
|
1691
|
+
resolver(error);
|
|
1692
|
+
}
|
|
1693
|
+
} else {
|
|
1694
|
+
const messageType = queuedMessage.type === "response" ? "Response" : "Error";
|
|
1695
|
+
this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
|
|
1696
|
+
}
|
|
1697
|
+
continue;
|
|
1698
|
+
}
|
|
1699
|
+
await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
const task = await this._taskStore.getTask(taskId, extra.sessionId);
|
|
1703
|
+
if (!task) {
|
|
1704
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
1705
|
+
}
|
|
1706
|
+
if (!isTerminal(task.status)) {
|
|
1707
|
+
await this._waitForTaskUpdate(taskId, extra.signal);
|
|
1708
|
+
return await handleTaskResult();
|
|
1709
|
+
}
|
|
1710
|
+
if (isTerminal(task.status)) {
|
|
1711
|
+
const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
|
|
1712
|
+
this._clearTaskQueue(taskId);
|
|
1713
|
+
return {
|
|
1714
|
+
...result,
|
|
1715
|
+
_meta: {
|
|
1716
|
+
...result._meta,
|
|
1717
|
+
[RELATED_TASK_META_KEY]: {
|
|
1718
|
+
taskId
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
return await handleTaskResult();
|
|
1724
|
+
};
|
|
1725
|
+
return await handleTaskResult();
|
|
1726
|
+
});
|
|
1727
|
+
this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
|
|
1728
|
+
try {
|
|
1729
|
+
const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
|
|
1730
|
+
return {
|
|
1731
|
+
tasks,
|
|
1732
|
+
nextCursor,
|
|
1733
|
+
_meta: {}
|
|
1734
|
+
};
|
|
1735
|
+
} catch (error) {
|
|
1736
|
+
throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
|
|
1737
|
+
}
|
|
1738
|
+
});
|
|
1739
|
+
this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
|
|
1740
|
+
try {
|
|
1741
|
+
const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
|
|
1742
|
+
if (!task) {
|
|
1743
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
|
|
1744
|
+
}
|
|
1745
|
+
if (isTerminal(task.status)) {
|
|
1746
|
+
throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
|
|
1747
|
+
}
|
|
1748
|
+
await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
|
|
1749
|
+
this._clearTaskQueue(request.params.taskId);
|
|
1750
|
+
const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
|
|
1751
|
+
if (!cancelledTask) {
|
|
1752
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
|
|
1753
|
+
}
|
|
1754
|
+
return {
|
|
1755
|
+
_meta: {},
|
|
1756
|
+
...cancelledTask
|
|
1757
|
+
};
|
|
1758
|
+
} catch (error) {
|
|
1759
|
+
if (error instanceof McpError) {
|
|
1760
|
+
throw error;
|
|
1761
|
+
}
|
|
1762
|
+
throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
|
|
1763
|
+
}
|
|
1764
|
+
});
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
async _oncancel(notification) {
|
|
1768
|
+
if (!notification.params.requestId) {
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
|
|
1772
|
+
controller?.abort(notification.params.reason);
|
|
1773
|
+
}
|
|
1774
|
+
_setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
|
|
1775
|
+
this._timeoutInfo.set(messageId, {
|
|
1776
|
+
timeoutId: setTimeout(onTimeout, timeout),
|
|
1777
|
+
startTime: Date.now(),
|
|
1778
|
+
timeout,
|
|
1779
|
+
maxTotalTimeout,
|
|
1780
|
+
resetTimeoutOnProgress,
|
|
1781
|
+
onTimeout
|
|
1782
|
+
});
|
|
1783
|
+
}
|
|
1784
|
+
_resetTimeout(messageId) {
|
|
1785
|
+
const info = this._timeoutInfo.get(messageId);
|
|
1786
|
+
if (!info)
|
|
1787
|
+
return false;
|
|
1788
|
+
const totalElapsed = Date.now() - info.startTime;
|
|
1789
|
+
if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
|
|
1790
|
+
this._timeoutInfo.delete(messageId);
|
|
1791
|
+
throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
|
|
1792
|
+
maxTotalTimeout: info.maxTotalTimeout,
|
|
1793
|
+
totalElapsed
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
clearTimeout(info.timeoutId);
|
|
1797
|
+
info.timeoutId = setTimeout(info.onTimeout, info.timeout);
|
|
1798
|
+
return true;
|
|
1799
|
+
}
|
|
1800
|
+
_cleanupTimeout(messageId) {
|
|
1801
|
+
const info = this._timeoutInfo.get(messageId);
|
|
1802
|
+
if (info) {
|
|
1803
|
+
clearTimeout(info.timeoutId);
|
|
1804
|
+
this._timeoutInfo.delete(messageId);
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
/**
|
|
1808
|
+
* Attaches to the given transport, starts it, and starts listening for messages.
|
|
1809
|
+
*
|
|
1810
|
+
* The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
|
|
1811
|
+
*/
|
|
1812
|
+
async connect(transport) {
|
|
1813
|
+
if (this._transport) {
|
|
1814
|
+
throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");
|
|
1815
|
+
}
|
|
1816
|
+
this._transport = transport;
|
|
1817
|
+
const _onclose = this.transport?.onclose;
|
|
1818
|
+
this._transport.onclose = () => {
|
|
1819
|
+
_onclose?.();
|
|
1820
|
+
this._onclose();
|
|
1821
|
+
};
|
|
1822
|
+
const _onerror = this.transport?.onerror;
|
|
1823
|
+
this._transport.onerror = (error) => {
|
|
1824
|
+
_onerror?.(error);
|
|
1825
|
+
this._onerror(error);
|
|
1826
|
+
};
|
|
1827
|
+
const _onmessage = this._transport?.onmessage;
|
|
1828
|
+
this._transport.onmessage = (message, extra) => {
|
|
1829
|
+
_onmessage?.(message, extra);
|
|
1830
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
|
|
1831
|
+
this._onresponse(message);
|
|
1832
|
+
} else if (isJSONRPCRequest(message)) {
|
|
1833
|
+
this._onrequest(message, extra);
|
|
1834
|
+
} else if (isJSONRPCNotification(message)) {
|
|
1835
|
+
this._onnotification(message);
|
|
1836
|
+
} else {
|
|
1837
|
+
this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
await this._transport.start();
|
|
1841
|
+
}
|
|
1842
|
+
_onclose() {
|
|
1843
|
+
const responseHandlers = this._responseHandlers;
|
|
1844
|
+
this._responseHandlers = /* @__PURE__ */ new Map();
|
|
1845
|
+
this._progressHandlers.clear();
|
|
1846
|
+
this._taskProgressTokens.clear();
|
|
1847
|
+
this._pendingDebouncedNotifications.clear();
|
|
1848
|
+
for (const info of this._timeoutInfo.values()) {
|
|
1849
|
+
clearTimeout(info.timeoutId);
|
|
1850
|
+
}
|
|
1851
|
+
this._timeoutInfo.clear();
|
|
1852
|
+
for (const controller of this._requestHandlerAbortControllers.values()) {
|
|
1853
|
+
controller.abort();
|
|
1854
|
+
}
|
|
1855
|
+
this._requestHandlerAbortControllers.clear();
|
|
1856
|
+
const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
|
|
1857
|
+
this._transport = void 0;
|
|
1858
|
+
this.onclose?.();
|
|
1859
|
+
for (const handler of responseHandlers.values()) {
|
|
1860
|
+
handler(error);
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
_onerror(error) {
|
|
1864
|
+
this.onerror?.(error);
|
|
1865
|
+
}
|
|
1866
|
+
_onnotification(notification) {
|
|
1867
|
+
const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
|
|
1868
|
+
if (handler === void 0) {
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
|
|
1872
|
+
}
|
|
1873
|
+
_onrequest(request, extra) {
|
|
1874
|
+
const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
|
|
1875
|
+
const capturedTransport = this._transport;
|
|
1876
|
+
const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
|
|
1877
|
+
if (handler === void 0) {
|
|
1878
|
+
const errorResponse = {
|
|
1879
|
+
jsonrpc: "2.0",
|
|
1880
|
+
id: request.id,
|
|
1881
|
+
error: {
|
|
1882
|
+
code: ErrorCode.MethodNotFound,
|
|
1883
|
+
message: "Method not found"
|
|
1884
|
+
}
|
|
1885
|
+
};
|
|
1886
|
+
if (relatedTaskId && this._taskMessageQueue) {
|
|
1887
|
+
this._enqueueTaskMessage(relatedTaskId, {
|
|
1888
|
+
type: "error",
|
|
1889
|
+
message: errorResponse,
|
|
1890
|
+
timestamp: Date.now()
|
|
1891
|
+
}, capturedTransport?.sessionId).catch((error) => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
|
|
1892
|
+
} else {
|
|
1893
|
+
capturedTransport?.send(errorResponse).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
|
|
1894
|
+
}
|
|
1895
|
+
return;
|
|
1896
|
+
}
|
|
1897
|
+
const abortController = new AbortController();
|
|
1898
|
+
this._requestHandlerAbortControllers.set(request.id, abortController);
|
|
1899
|
+
const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
|
|
1900
|
+
const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
|
|
1901
|
+
const fullExtra = {
|
|
1902
|
+
signal: abortController.signal,
|
|
1903
|
+
sessionId: capturedTransport?.sessionId,
|
|
1904
|
+
_meta: request.params?._meta,
|
|
1905
|
+
sendNotification: async (notification) => {
|
|
1906
|
+
if (abortController.signal.aborted)
|
|
1907
|
+
return;
|
|
1908
|
+
const notificationOptions = { relatedRequestId: request.id };
|
|
1909
|
+
if (relatedTaskId) {
|
|
1910
|
+
notificationOptions.relatedTask = { taskId: relatedTaskId };
|
|
1911
|
+
}
|
|
1912
|
+
await this.notification(notification, notificationOptions);
|
|
1913
|
+
},
|
|
1914
|
+
sendRequest: async (r2, resultSchema, options) => {
|
|
1915
|
+
if (abortController.signal.aborted) {
|
|
1916
|
+
throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
|
|
1917
|
+
}
|
|
1918
|
+
const requestOptions = { ...options, relatedRequestId: request.id };
|
|
1919
|
+
if (relatedTaskId && !requestOptions.relatedTask) {
|
|
1920
|
+
requestOptions.relatedTask = { taskId: relatedTaskId };
|
|
1921
|
+
}
|
|
1922
|
+
const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
|
|
1923
|
+
if (effectiveTaskId && taskStore) {
|
|
1924
|
+
await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
|
|
1925
|
+
}
|
|
1926
|
+
return await this.request(r2, resultSchema, requestOptions);
|
|
1927
|
+
},
|
|
1928
|
+
authInfo: extra?.authInfo,
|
|
1929
|
+
requestId: request.id,
|
|
1930
|
+
requestInfo: extra?.requestInfo,
|
|
1931
|
+
taskId: relatedTaskId,
|
|
1932
|
+
taskStore,
|
|
1933
|
+
taskRequestedTtl: taskCreationParams?.ttl,
|
|
1934
|
+
closeSSEStream: extra?.closeSSEStream,
|
|
1935
|
+
closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
|
|
1936
|
+
};
|
|
1937
|
+
Promise.resolve().then(() => {
|
|
1938
|
+
if (taskCreationParams) {
|
|
1939
|
+
this.assertTaskHandlerCapability(request.method);
|
|
1940
|
+
}
|
|
1941
|
+
}).then(() => handler(request, fullExtra)).then(async (result) => {
|
|
1942
|
+
if (abortController.signal.aborted) {
|
|
1943
|
+
return;
|
|
1944
|
+
}
|
|
1945
|
+
const response = {
|
|
1946
|
+
result,
|
|
1947
|
+
jsonrpc: "2.0",
|
|
1948
|
+
id: request.id
|
|
1949
|
+
};
|
|
1950
|
+
if (relatedTaskId && this._taskMessageQueue) {
|
|
1951
|
+
await this._enqueueTaskMessage(relatedTaskId, {
|
|
1952
|
+
type: "response",
|
|
1953
|
+
message: response,
|
|
1954
|
+
timestamp: Date.now()
|
|
1955
|
+
}, capturedTransport?.sessionId);
|
|
1956
|
+
} else {
|
|
1957
|
+
await capturedTransport?.send(response);
|
|
1958
|
+
}
|
|
1959
|
+
}, async (error) => {
|
|
1960
|
+
if (abortController.signal.aborted) {
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
const errorResponse = {
|
|
1964
|
+
jsonrpc: "2.0",
|
|
1965
|
+
id: request.id,
|
|
1966
|
+
error: {
|
|
1967
|
+
code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
|
|
1968
|
+
message: error.message ?? "Internal error",
|
|
1969
|
+
...error["data"] !== void 0 && { data: error["data"] }
|
|
1970
|
+
}
|
|
1971
|
+
};
|
|
1972
|
+
if (relatedTaskId && this._taskMessageQueue) {
|
|
1973
|
+
await this._enqueueTaskMessage(relatedTaskId, {
|
|
1974
|
+
type: "error",
|
|
1975
|
+
message: errorResponse,
|
|
1976
|
+
timestamp: Date.now()
|
|
1977
|
+
}, capturedTransport?.sessionId);
|
|
1978
|
+
} else {
|
|
1979
|
+
await capturedTransport?.send(errorResponse);
|
|
1980
|
+
}
|
|
1981
|
+
}).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
|
|
1982
|
+
if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
|
|
1983
|
+
this._requestHandlerAbortControllers.delete(request.id);
|
|
1984
|
+
}
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
_onprogress(notification) {
|
|
1988
|
+
const { progressToken, ...params } = notification.params;
|
|
1989
|
+
const messageId = Number(progressToken);
|
|
1990
|
+
const handler = this._progressHandlers.get(messageId);
|
|
1991
|
+
if (!handler) {
|
|
1992
|
+
this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
|
|
1993
|
+
return;
|
|
1994
|
+
}
|
|
1995
|
+
const responseHandler = this._responseHandlers.get(messageId);
|
|
1996
|
+
const timeoutInfo = this._timeoutInfo.get(messageId);
|
|
1997
|
+
if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
|
|
1998
|
+
try {
|
|
1999
|
+
this._resetTimeout(messageId);
|
|
2000
|
+
} catch (error) {
|
|
2001
|
+
this._responseHandlers.delete(messageId);
|
|
2002
|
+
this._progressHandlers.delete(messageId);
|
|
2003
|
+
this._cleanupTimeout(messageId);
|
|
2004
|
+
responseHandler(error);
|
|
2005
|
+
return;
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
handler(params);
|
|
2009
|
+
}
|
|
2010
|
+
_onresponse(response) {
|
|
2011
|
+
const messageId = Number(response.id);
|
|
2012
|
+
const resolver = this._requestResolvers.get(messageId);
|
|
2013
|
+
if (resolver) {
|
|
2014
|
+
this._requestResolvers.delete(messageId);
|
|
2015
|
+
if (isJSONRPCResultResponse(response)) {
|
|
2016
|
+
resolver(response);
|
|
2017
|
+
} else {
|
|
2018
|
+
const error = new McpError(response.error.code, response.error.message, response.error.data);
|
|
2019
|
+
resolver(error);
|
|
2020
|
+
}
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
const handler = this._responseHandlers.get(messageId);
|
|
2024
|
+
if (handler === void 0) {
|
|
2025
|
+
this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
this._responseHandlers.delete(messageId);
|
|
2029
|
+
this._cleanupTimeout(messageId);
|
|
2030
|
+
let isTaskResponse = false;
|
|
2031
|
+
if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
|
|
2032
|
+
const result = response.result;
|
|
2033
|
+
if (result.task && typeof result.task === "object") {
|
|
2034
|
+
const task = result.task;
|
|
2035
|
+
if (typeof task.taskId === "string") {
|
|
2036
|
+
isTaskResponse = true;
|
|
2037
|
+
this._taskProgressTokens.set(task.taskId, messageId);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
if (!isTaskResponse) {
|
|
2042
|
+
this._progressHandlers.delete(messageId);
|
|
2043
|
+
}
|
|
2044
|
+
if (isJSONRPCResultResponse(response)) {
|
|
2045
|
+
handler(response);
|
|
2046
|
+
} else {
|
|
2047
|
+
const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
|
|
2048
|
+
handler(error);
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
get transport() {
|
|
2052
|
+
return this._transport;
|
|
2053
|
+
}
|
|
2054
|
+
/**
|
|
2055
|
+
* Closes the connection.
|
|
2056
|
+
*/
|
|
2057
|
+
async close() {
|
|
2058
|
+
await this._transport?.close();
|
|
2059
|
+
}
|
|
2060
|
+
/**
|
|
2061
|
+
* Sends a request and returns an AsyncGenerator that yields response messages.
|
|
2062
|
+
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
2063
|
+
*
|
|
2064
|
+
* @example
|
|
2065
|
+
* ```typescript
|
|
2066
|
+
* const stream = protocol.requestStream(request, resultSchema, options);
|
|
2067
|
+
* for await (const message of stream) {
|
|
2068
|
+
* switch (message.type) {
|
|
2069
|
+
* case 'taskCreated':
|
|
2070
|
+
* console.log('Task created:', message.task.taskId);
|
|
2071
|
+
* break;
|
|
2072
|
+
* case 'taskStatus':
|
|
2073
|
+
* console.log('Task status:', message.task.status);
|
|
2074
|
+
* break;
|
|
2075
|
+
* case 'result':
|
|
2076
|
+
* console.log('Final result:', message.result);
|
|
2077
|
+
* break;
|
|
2078
|
+
* case 'error':
|
|
2079
|
+
* console.error('Error:', message.error);
|
|
2080
|
+
* break;
|
|
2081
|
+
* }
|
|
2082
|
+
* }
|
|
2083
|
+
* ```
|
|
2084
|
+
*
|
|
2085
|
+
* @experimental Use `client.experimental.tasks.requestStream()` to access this method.
|
|
2086
|
+
*/
|
|
2087
|
+
async *requestStream(request, resultSchema, options) {
|
|
2088
|
+
const { task } = options ?? {};
|
|
2089
|
+
if (!task) {
|
|
2090
|
+
try {
|
|
2091
|
+
const result = await this.request(request, resultSchema, options);
|
|
2092
|
+
yield { type: "result", result };
|
|
2093
|
+
} catch (error) {
|
|
2094
|
+
yield {
|
|
2095
|
+
type: "error",
|
|
2096
|
+
error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
let taskId;
|
|
2102
|
+
try {
|
|
2103
|
+
const createResult = await this.request(request, CreateTaskResultSchema, options);
|
|
2104
|
+
if (createResult.task) {
|
|
2105
|
+
taskId = createResult.task.taskId;
|
|
2106
|
+
yield { type: "taskCreated", task: createResult.task };
|
|
2107
|
+
} else {
|
|
2108
|
+
throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
|
|
2109
|
+
}
|
|
2110
|
+
while (true) {
|
|
2111
|
+
const task2 = await this.getTask({ taskId }, options);
|
|
2112
|
+
yield { type: "taskStatus", task: task2 };
|
|
2113
|
+
if (isTerminal(task2.status)) {
|
|
2114
|
+
if (task2.status === "completed") {
|
|
2115
|
+
const result = await this.getTaskResult({ taskId }, resultSchema, options);
|
|
2116
|
+
yield { type: "result", result };
|
|
2117
|
+
} else if (task2.status === "failed") {
|
|
2118
|
+
yield {
|
|
2119
|
+
type: "error",
|
|
2120
|
+
error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
|
|
2121
|
+
};
|
|
2122
|
+
} else if (task2.status === "cancelled") {
|
|
2123
|
+
yield {
|
|
2124
|
+
type: "error",
|
|
2125
|
+
error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
|
|
2126
|
+
};
|
|
2127
|
+
}
|
|
2128
|
+
return;
|
|
2129
|
+
}
|
|
2130
|
+
if (task2.status === "input_required") {
|
|
2131
|
+
const result = await this.getTaskResult({ taskId }, resultSchema, options);
|
|
2132
|
+
yield { type: "result", result };
|
|
2133
|
+
return;
|
|
2134
|
+
}
|
|
2135
|
+
const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
|
|
2136
|
+
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
|
2137
|
+
options?.signal?.throwIfAborted();
|
|
2138
|
+
}
|
|
2139
|
+
} catch (error) {
|
|
2140
|
+
yield {
|
|
2141
|
+
type: "error",
|
|
2142
|
+
error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Sends a request and waits for a response.
|
|
2148
|
+
*
|
|
2149
|
+
* Do not use this method to emit notifications! Use notification() instead.
|
|
2150
|
+
*/
|
|
2151
|
+
request(request, resultSchema, options) {
|
|
2152
|
+
const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
|
|
2153
|
+
return new Promise((resolve, reject) => {
|
|
2154
|
+
const earlyReject = (error) => {
|
|
2155
|
+
reject(error);
|
|
2156
|
+
};
|
|
2157
|
+
if (!this._transport) {
|
|
2158
|
+
earlyReject(new Error("Not connected"));
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
if (this._options?.enforceStrictCapabilities === true) {
|
|
2162
|
+
try {
|
|
2163
|
+
this.assertCapabilityForMethod(request.method);
|
|
2164
|
+
if (task) {
|
|
2165
|
+
this.assertTaskCapability(request.method);
|
|
2166
|
+
}
|
|
2167
|
+
} catch (e2) {
|
|
2168
|
+
earlyReject(e2);
|
|
2169
|
+
return;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
options?.signal?.throwIfAborted();
|
|
2173
|
+
const messageId = this._requestMessageId++;
|
|
2174
|
+
const jsonrpcRequest = {
|
|
2175
|
+
...request,
|
|
2176
|
+
jsonrpc: "2.0",
|
|
2177
|
+
id: messageId
|
|
2178
|
+
};
|
|
2179
|
+
if (options?.onprogress) {
|
|
2180
|
+
this._progressHandlers.set(messageId, options.onprogress);
|
|
2181
|
+
jsonrpcRequest.params = {
|
|
2182
|
+
...request.params,
|
|
2183
|
+
_meta: {
|
|
2184
|
+
...request.params?._meta || {},
|
|
2185
|
+
progressToken: messageId
|
|
2186
|
+
}
|
|
2187
|
+
};
|
|
2188
|
+
}
|
|
2189
|
+
if (task) {
|
|
2190
|
+
jsonrpcRequest.params = {
|
|
2191
|
+
...jsonrpcRequest.params,
|
|
2192
|
+
task
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
if (relatedTask) {
|
|
2196
|
+
jsonrpcRequest.params = {
|
|
2197
|
+
...jsonrpcRequest.params,
|
|
2198
|
+
_meta: {
|
|
2199
|
+
...jsonrpcRequest.params?._meta || {},
|
|
2200
|
+
[RELATED_TASK_META_KEY]: relatedTask
|
|
2201
|
+
}
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
const cancel = (reason) => {
|
|
2205
|
+
this._responseHandlers.delete(messageId);
|
|
2206
|
+
this._progressHandlers.delete(messageId);
|
|
2207
|
+
this._cleanupTimeout(messageId);
|
|
2208
|
+
this._transport?.send({
|
|
2209
|
+
jsonrpc: "2.0",
|
|
2210
|
+
method: "notifications/cancelled",
|
|
2211
|
+
params: {
|
|
2212
|
+
requestId: messageId,
|
|
2213
|
+
reason: String(reason)
|
|
2214
|
+
}
|
|
2215
|
+
}, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => this._onerror(new Error(`Failed to send cancellation: ${error2}`)));
|
|
2216
|
+
const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
|
|
2217
|
+
reject(error);
|
|
2218
|
+
};
|
|
2219
|
+
this._responseHandlers.set(messageId, (response) => {
|
|
2220
|
+
if (options?.signal?.aborted) {
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (response instanceof Error) {
|
|
2224
|
+
return reject(response);
|
|
2225
|
+
}
|
|
2226
|
+
try {
|
|
2227
|
+
const parseResult = safeParse2(resultSchema, response.result);
|
|
2228
|
+
if (!parseResult.success) {
|
|
2229
|
+
reject(parseResult.error);
|
|
2230
|
+
} else {
|
|
2231
|
+
resolve(parseResult.data);
|
|
2232
|
+
}
|
|
2233
|
+
} catch (error) {
|
|
2234
|
+
reject(error);
|
|
2235
|
+
}
|
|
2236
|
+
});
|
|
2237
|
+
options?.signal?.addEventListener("abort", () => {
|
|
2238
|
+
cancel(options?.signal?.reason);
|
|
2239
|
+
});
|
|
2240
|
+
const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
|
|
2241
|
+
const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
|
|
2242
|
+
this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
|
|
2243
|
+
const relatedTaskId = relatedTask?.taskId;
|
|
2244
|
+
if (relatedTaskId) {
|
|
2245
|
+
const responseResolver = (response) => {
|
|
2246
|
+
const handler = this._responseHandlers.get(messageId);
|
|
2247
|
+
if (handler) {
|
|
2248
|
+
handler(response);
|
|
2249
|
+
} else {
|
|
2250
|
+
this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
|
|
2251
|
+
}
|
|
2252
|
+
};
|
|
2253
|
+
this._requestResolvers.set(messageId, responseResolver);
|
|
2254
|
+
this._enqueueTaskMessage(relatedTaskId, {
|
|
2255
|
+
type: "request",
|
|
2256
|
+
message: jsonrpcRequest,
|
|
2257
|
+
timestamp: Date.now()
|
|
2258
|
+
}).catch((error) => {
|
|
2259
|
+
this._cleanupTimeout(messageId);
|
|
2260
|
+
reject(error);
|
|
2261
|
+
});
|
|
2262
|
+
} else {
|
|
2263
|
+
this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
|
|
2264
|
+
this._cleanupTimeout(messageId);
|
|
2265
|
+
reject(error);
|
|
2266
|
+
});
|
|
2267
|
+
}
|
|
2268
|
+
});
|
|
2269
|
+
}
|
|
2270
|
+
/**
|
|
2271
|
+
* Gets the current status of a task.
|
|
2272
|
+
*
|
|
2273
|
+
* @experimental Use `client.experimental.tasks.getTask()` to access this method.
|
|
2274
|
+
*/
|
|
2275
|
+
async getTask(params, options) {
|
|
2276
|
+
return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* Retrieves the result of a completed task.
|
|
2280
|
+
*
|
|
2281
|
+
* @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
|
|
2282
|
+
*/
|
|
2283
|
+
async getTaskResult(params, resultSchema, options) {
|
|
2284
|
+
return this.request({ method: "tasks/result", params }, resultSchema, options);
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Lists tasks, optionally starting from a pagination cursor.
|
|
2288
|
+
*
|
|
2289
|
+
* @experimental Use `client.experimental.tasks.listTasks()` to access this method.
|
|
2290
|
+
*/
|
|
2291
|
+
async listTasks(params, options) {
|
|
2292
|
+
return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
|
|
2293
|
+
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Cancels a specific task.
|
|
2296
|
+
*
|
|
2297
|
+
* @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
|
|
2298
|
+
*/
|
|
2299
|
+
async cancelTask(params, options) {
|
|
2300
|
+
return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Emits a notification, which is a one-way message that does not expect a response.
|
|
2304
|
+
*/
|
|
2305
|
+
async notification(notification, options) {
|
|
2306
|
+
if (!this._transport) {
|
|
2307
|
+
throw new Error("Not connected");
|
|
2308
|
+
}
|
|
2309
|
+
this.assertNotificationCapability(notification.method);
|
|
2310
|
+
const relatedTaskId = options?.relatedTask?.taskId;
|
|
2311
|
+
if (relatedTaskId) {
|
|
2312
|
+
const jsonrpcNotification2 = {
|
|
2313
|
+
...notification,
|
|
2314
|
+
jsonrpc: "2.0",
|
|
2315
|
+
params: {
|
|
2316
|
+
...notification.params,
|
|
2317
|
+
_meta: {
|
|
2318
|
+
...notification.params?._meta || {},
|
|
2319
|
+
[RELATED_TASK_META_KEY]: options.relatedTask
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
};
|
|
2323
|
+
await this._enqueueTaskMessage(relatedTaskId, {
|
|
2324
|
+
type: "notification",
|
|
2325
|
+
message: jsonrpcNotification2,
|
|
2326
|
+
timestamp: Date.now()
|
|
2327
|
+
});
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2330
|
+
const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
|
|
2331
|
+
const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
|
|
2332
|
+
if (canDebounce) {
|
|
2333
|
+
if (this._pendingDebouncedNotifications.has(notification.method)) {
|
|
2334
|
+
return;
|
|
2335
|
+
}
|
|
2336
|
+
this._pendingDebouncedNotifications.add(notification.method);
|
|
2337
|
+
Promise.resolve().then(() => {
|
|
2338
|
+
this._pendingDebouncedNotifications.delete(notification.method);
|
|
2339
|
+
if (!this._transport) {
|
|
2340
|
+
return;
|
|
2341
|
+
}
|
|
2342
|
+
let jsonrpcNotification2 = {
|
|
2343
|
+
...notification,
|
|
2344
|
+
jsonrpc: "2.0"
|
|
2345
|
+
};
|
|
2346
|
+
if (options?.relatedTask) {
|
|
2347
|
+
jsonrpcNotification2 = {
|
|
2348
|
+
...jsonrpcNotification2,
|
|
2349
|
+
params: {
|
|
2350
|
+
...jsonrpcNotification2.params,
|
|
2351
|
+
_meta: {
|
|
2352
|
+
...jsonrpcNotification2.params?._meta || {},
|
|
2353
|
+
[RELATED_TASK_META_KEY]: options.relatedTask
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
};
|
|
2357
|
+
}
|
|
2358
|
+
this._transport?.send(jsonrpcNotification2, options).catch((error) => this._onerror(error));
|
|
2359
|
+
});
|
|
2360
|
+
return;
|
|
2361
|
+
}
|
|
2362
|
+
let jsonrpcNotification = {
|
|
2363
|
+
...notification,
|
|
2364
|
+
jsonrpc: "2.0"
|
|
2365
|
+
};
|
|
2366
|
+
if (options?.relatedTask) {
|
|
2367
|
+
jsonrpcNotification = {
|
|
2368
|
+
...jsonrpcNotification,
|
|
2369
|
+
params: {
|
|
2370
|
+
...jsonrpcNotification.params,
|
|
2371
|
+
_meta: {
|
|
2372
|
+
...jsonrpcNotification.params?._meta || {},
|
|
2373
|
+
[RELATED_TASK_META_KEY]: options.relatedTask
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
};
|
|
2377
|
+
}
|
|
2378
|
+
await this._transport.send(jsonrpcNotification, options);
|
|
2379
|
+
}
|
|
2380
|
+
/**
|
|
2381
|
+
* Registers a handler to invoke when this protocol object receives a request with the given method.
|
|
2382
|
+
*
|
|
2383
|
+
* Note that this will replace any previous request handler for the same method.
|
|
2384
|
+
*/
|
|
2385
|
+
setRequestHandler(requestSchema, handler) {
|
|
2386
|
+
const method = getMethodLiteral(requestSchema);
|
|
2387
|
+
this.assertRequestHandlerCapability(method);
|
|
2388
|
+
this._requestHandlers.set(method, (request, extra) => {
|
|
2389
|
+
const parsed = parseWithCompat(requestSchema, request);
|
|
2390
|
+
return Promise.resolve(handler(parsed, extra));
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* Removes the request handler for the given method.
|
|
2395
|
+
*/
|
|
2396
|
+
removeRequestHandler(method) {
|
|
2397
|
+
this._requestHandlers.delete(method);
|
|
2398
|
+
}
|
|
2399
|
+
/**
|
|
2400
|
+
* Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
|
|
2401
|
+
*/
|
|
2402
|
+
assertCanSetRequestHandler(method) {
|
|
2403
|
+
if (this._requestHandlers.has(method)) {
|
|
2404
|
+
throw new Error(`A request handler for ${method} already exists, which would be overridden`);
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* Registers a handler to invoke when this protocol object receives a notification with the given method.
|
|
2409
|
+
*
|
|
2410
|
+
* Note that this will replace any previous notification handler for the same method.
|
|
2411
|
+
*/
|
|
2412
|
+
setNotificationHandler(notificationSchema, handler) {
|
|
2413
|
+
const method = getMethodLiteral(notificationSchema);
|
|
2414
|
+
this._notificationHandlers.set(method, (notification) => {
|
|
2415
|
+
const parsed = parseWithCompat(notificationSchema, notification);
|
|
2416
|
+
return Promise.resolve(handler(parsed));
|
|
2417
|
+
});
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* Removes the notification handler for the given method.
|
|
2421
|
+
*/
|
|
2422
|
+
removeNotificationHandler(method) {
|
|
2423
|
+
this._notificationHandlers.delete(method);
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* Cleans up the progress handler associated with a task.
|
|
2427
|
+
* This should be called when a task reaches a terminal status.
|
|
2428
|
+
*/
|
|
2429
|
+
_cleanupTaskProgressHandler(taskId) {
|
|
2430
|
+
const progressToken = this._taskProgressTokens.get(taskId);
|
|
2431
|
+
if (progressToken !== void 0) {
|
|
2432
|
+
this._progressHandlers.delete(progressToken);
|
|
2433
|
+
this._taskProgressTokens.delete(taskId);
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
/**
|
|
2437
|
+
* Enqueues a task-related message for side-channel delivery via tasks/result.
|
|
2438
|
+
* @param taskId The task ID to associate the message with
|
|
2439
|
+
* @param message The message to enqueue
|
|
2440
|
+
* @param sessionId Optional session ID for binding the operation to a specific session
|
|
2441
|
+
* @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
|
|
2442
|
+
*
|
|
2443
|
+
* Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
|
|
2444
|
+
* the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
|
|
2445
|
+
* simply propagates the error.
|
|
2446
|
+
*/
|
|
2447
|
+
async _enqueueTaskMessage(taskId, message, sessionId) {
|
|
2448
|
+
if (!this._taskStore || !this._taskMessageQueue) {
|
|
2449
|
+
throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
|
|
2450
|
+
}
|
|
2451
|
+
const maxQueueSize = this._options?.maxTaskQueueSize;
|
|
2452
|
+
await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
|
|
2453
|
+
}
|
|
2454
|
+
/**
|
|
2455
|
+
* Clears the message queue for a task and rejects any pending request resolvers.
|
|
2456
|
+
* @param taskId The task ID whose queue should be cleared
|
|
2457
|
+
* @param sessionId Optional session ID for binding the operation to a specific session
|
|
2458
|
+
*/
|
|
2459
|
+
async _clearTaskQueue(taskId, sessionId) {
|
|
2460
|
+
if (this._taskMessageQueue) {
|
|
2461
|
+
const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
|
|
2462
|
+
for (const message of messages) {
|
|
2463
|
+
if (message.type === "request" && isJSONRPCRequest(message.message)) {
|
|
2464
|
+
const requestId = message.message.id;
|
|
2465
|
+
const resolver = this._requestResolvers.get(requestId);
|
|
2466
|
+
if (resolver) {
|
|
2467
|
+
resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
|
|
2468
|
+
this._requestResolvers.delete(requestId);
|
|
2469
|
+
} else {
|
|
2470
|
+
this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
/**
|
|
2477
|
+
* Waits for a task update (new messages or status change) with abort signal support.
|
|
2478
|
+
* Uses polling to check for updates at the task's configured poll interval.
|
|
2479
|
+
* @param taskId The task ID to wait for
|
|
2480
|
+
* @param signal Abort signal to cancel the wait
|
|
2481
|
+
* @returns Promise that resolves when an update occurs or rejects if aborted
|
|
2482
|
+
*/
|
|
2483
|
+
async _waitForTaskUpdate(taskId, signal) {
|
|
2484
|
+
let interval = this._options?.defaultTaskPollInterval ?? 1e3;
|
|
2485
|
+
try {
|
|
2486
|
+
const task = await this._taskStore?.getTask(taskId);
|
|
2487
|
+
if (task?.pollInterval) {
|
|
2488
|
+
interval = task.pollInterval;
|
|
2489
|
+
}
|
|
2490
|
+
} catch {
|
|
2491
|
+
}
|
|
2492
|
+
return new Promise((resolve, reject) => {
|
|
2493
|
+
if (signal.aborted) {
|
|
2494
|
+
reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
2495
|
+
return;
|
|
2496
|
+
}
|
|
2497
|
+
const timeoutId = setTimeout(resolve, interval);
|
|
2498
|
+
signal.addEventListener("abort", () => {
|
|
2499
|
+
clearTimeout(timeoutId);
|
|
2500
|
+
reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
2501
|
+
}, { once: true });
|
|
2502
|
+
});
|
|
2503
|
+
}
|
|
2504
|
+
requestTaskStore(request, sessionId) {
|
|
2505
|
+
const taskStore = this._taskStore;
|
|
2506
|
+
if (!taskStore) {
|
|
2507
|
+
throw new Error("No task store configured");
|
|
2508
|
+
}
|
|
2509
|
+
return {
|
|
2510
|
+
createTask: async (taskParams) => {
|
|
2511
|
+
if (!request) {
|
|
2512
|
+
throw new Error("No request provided");
|
|
2513
|
+
}
|
|
2514
|
+
return await taskStore.createTask(taskParams, request.id, {
|
|
2515
|
+
method: request.method,
|
|
2516
|
+
params: request.params
|
|
2517
|
+
}, sessionId);
|
|
2518
|
+
},
|
|
2519
|
+
getTask: async (taskId) => {
|
|
2520
|
+
const task = await taskStore.getTask(taskId, sessionId);
|
|
2521
|
+
if (!task) {
|
|
2522
|
+
throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
|
|
2523
|
+
}
|
|
2524
|
+
return task;
|
|
2525
|
+
},
|
|
2526
|
+
storeTaskResult: async (taskId, status, result) => {
|
|
2527
|
+
await taskStore.storeTaskResult(taskId, status, result, sessionId);
|
|
2528
|
+
const task = await taskStore.getTask(taskId, sessionId);
|
|
2529
|
+
if (task) {
|
|
2530
|
+
const notification = TaskStatusNotificationSchema.parse({
|
|
2531
|
+
method: "notifications/tasks/status",
|
|
2532
|
+
params: task
|
|
2533
|
+
});
|
|
2534
|
+
await this.notification(notification);
|
|
2535
|
+
if (isTerminal(task.status)) {
|
|
2536
|
+
this._cleanupTaskProgressHandler(taskId);
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
},
|
|
2540
|
+
getTaskResult: (taskId) => {
|
|
2541
|
+
return taskStore.getTaskResult(taskId, sessionId);
|
|
2542
|
+
},
|
|
2543
|
+
updateTaskStatus: async (taskId, status, statusMessage) => {
|
|
2544
|
+
const task = await taskStore.getTask(taskId, sessionId);
|
|
2545
|
+
if (!task) {
|
|
2546
|
+
throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
|
|
2547
|
+
}
|
|
2548
|
+
if (isTerminal(task.status)) {
|
|
2549
|
+
throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
|
|
2550
|
+
}
|
|
2551
|
+
await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
|
|
2552
|
+
const updatedTask = await taskStore.getTask(taskId, sessionId);
|
|
2553
|
+
if (updatedTask) {
|
|
2554
|
+
const notification = TaskStatusNotificationSchema.parse({
|
|
2555
|
+
method: "notifications/tasks/status",
|
|
2556
|
+
params: updatedTask
|
|
2557
|
+
});
|
|
2558
|
+
await this.notification(notification);
|
|
2559
|
+
if (isTerminal(updatedTask.status)) {
|
|
2560
|
+
this._cleanupTaskProgressHandler(taskId);
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
},
|
|
2564
|
+
listTasks: (cursor) => {
|
|
2565
|
+
return taskStore.listTasks(cursor, sessionId);
|
|
2566
|
+
}
|
|
2567
|
+
};
|
|
2568
|
+
}
|
|
2569
|
+
};
|
|
2570
|
+
|
|
2571
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+ext-apps@1.7.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__react-_bc4d5adeaec14d46b9a46bfff8177b13/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.js
|
|
2572
|
+
var ZQ = ((X) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(X, { get: (Y, Z) => (typeof __require < "u" ? __require : Y)[Z] }) : X)(function(X) {
|
|
2573
|
+
if (typeof __require < "u") return __require.apply(this, arguments);
|
|
2574
|
+
throw Error('Dynamic require of "' + X + '" is not supported');
|
|
2575
|
+
});
|
|
2576
|
+
var _ = class extends Protocol {
|
|
2577
|
+
_registeredMethods = /* @__PURE__ */ new Set();
|
|
2578
|
+
_eventSlots = /* @__PURE__ */ new Map();
|
|
2579
|
+
onEventDispatch(X, Y) {
|
|
2580
|
+
}
|
|
2581
|
+
_ensureEventSlot(X) {
|
|
2582
|
+
let Y = this._eventSlots.get(X);
|
|
2583
|
+
if (!Y) {
|
|
2584
|
+
let Z = this.eventSchemas[X];
|
|
2585
|
+
if (!Z) throw Error(`Unknown event: ${String(X)}`);
|
|
2586
|
+
Y = { listeners: [] }, this._eventSlots.set(X, Y);
|
|
2587
|
+
let $ = Z.shape.method.value;
|
|
2588
|
+
this._registeredMethods.add($);
|
|
2589
|
+
let J = Y;
|
|
2590
|
+
super.setNotificationHandler(Z, (K) => {
|
|
2591
|
+
let D = K.params;
|
|
2592
|
+
this.onEventDispatch(X, D), J.onHandler?.(D);
|
|
2593
|
+
for (let G of [...J.listeners]) G(D);
|
|
2594
|
+
});
|
|
2595
|
+
}
|
|
2596
|
+
return Y;
|
|
2597
|
+
}
|
|
2598
|
+
setEventHandler(X, Y) {
|
|
2599
|
+
let Z = this._ensureEventSlot(X);
|
|
2600
|
+
if (Z.onHandler && Y) console.warn(`[MCP Apps] on${String(X)} handler replaced. Use addEventListener("${String(X)}", \u2026) to add multiple listeners without replacing.`);
|
|
2601
|
+
Z.onHandler = Y;
|
|
2602
|
+
}
|
|
2603
|
+
getEventHandler(X) {
|
|
2604
|
+
return this._eventSlots.get(X)?.onHandler;
|
|
2605
|
+
}
|
|
2606
|
+
addEventListener(X, Y) {
|
|
2607
|
+
this._ensureEventSlot(X).listeners.push(Y);
|
|
2608
|
+
}
|
|
2609
|
+
removeEventListener(X, Y) {
|
|
2610
|
+
let Z = this._eventSlots.get(X);
|
|
2611
|
+
if (!Z) return;
|
|
2612
|
+
let $ = Z.listeners.indexOf(Y);
|
|
2613
|
+
if ($ !== -1) Z.listeners.splice($, 1);
|
|
2614
|
+
}
|
|
2615
|
+
setRequestHandler = (X, Y) => {
|
|
2616
|
+
this._assertMethodNotRegistered(X, "setRequestHandler"), super.setRequestHandler(X, Y);
|
|
2617
|
+
};
|
|
2618
|
+
setNotificationHandler = (X, Y) => {
|
|
2619
|
+
this._assertMethodNotRegistered(X, "setNotificationHandler"), super.setNotificationHandler(X, Y);
|
|
2620
|
+
};
|
|
2621
|
+
warnIfRequestHandlerReplaced(X, Y, Z) {
|
|
2622
|
+
if (Y && Z) console.warn(`[MCP Apps] ${X} handler replaced. Previous handler will no longer be called.`);
|
|
2623
|
+
}
|
|
2624
|
+
replaceRequestHandler = (X, Y) => {
|
|
2625
|
+
let Z = X.shape.method.value;
|
|
2626
|
+
this._registeredMethods.add(Z), super.setRequestHandler(X, Y);
|
|
2627
|
+
};
|
|
2628
|
+
_assertMethodNotRegistered(X, Y) {
|
|
2629
|
+
let Z = X.shape.method.value;
|
|
2630
|
+
if (this._registeredMethods.has(Z)) throw Error(`Handler for "${Z}" already registered (via ${Y}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);
|
|
2631
|
+
this._registeredMethods.add(Z);
|
|
2632
|
+
}
|
|
2633
|
+
};
|
|
2634
|
+
var j = "2026-01-26";
|
|
2635
|
+
var V = "ui/notifications/tool-input-partial";
|
|
2636
|
+
var r = external_exports.union([external_exports.literal("light"), external_exports.literal("dark")]).describe("Color theme preference for the host environment.");
|
|
2637
|
+
var B = external_exports.union([external_exports.literal("inline"), external_exports.literal("fullscreen"), external_exports.literal("pip")]).describe("Display mode for UI presentation.");
|
|
2638
|
+
var HQ = external_exports.union([external_exports.literal("--color-background-primary"), external_exports.literal("--color-background-secondary"), external_exports.literal("--color-background-tertiary"), external_exports.literal("--color-background-inverse"), external_exports.literal("--color-background-ghost"), external_exports.literal("--color-background-info"), external_exports.literal("--color-background-danger"), external_exports.literal("--color-background-success"), external_exports.literal("--color-background-warning"), external_exports.literal("--color-background-disabled"), external_exports.literal("--color-text-primary"), external_exports.literal("--color-text-secondary"), external_exports.literal("--color-text-tertiary"), external_exports.literal("--color-text-inverse"), external_exports.literal("--color-text-ghost"), external_exports.literal("--color-text-info"), external_exports.literal("--color-text-danger"), external_exports.literal("--color-text-success"), external_exports.literal("--color-text-warning"), external_exports.literal("--color-text-disabled"), external_exports.literal("--color-border-primary"), external_exports.literal("--color-border-secondary"), external_exports.literal("--color-border-tertiary"), external_exports.literal("--color-border-inverse"), external_exports.literal("--color-border-ghost"), external_exports.literal("--color-border-info"), external_exports.literal("--color-border-danger"), external_exports.literal("--color-border-success"), external_exports.literal("--color-border-warning"), external_exports.literal("--color-border-disabled"), external_exports.literal("--color-ring-primary"), external_exports.literal("--color-ring-secondary"), external_exports.literal("--color-ring-inverse"), external_exports.literal("--color-ring-info"), external_exports.literal("--color-ring-danger"), external_exports.literal("--color-ring-success"), external_exports.literal("--color-ring-warning"), external_exports.literal("--font-sans"), external_exports.literal("--font-mono"), external_exports.literal("--font-weight-normal"), external_exports.literal("--font-weight-medium"), external_exports.literal("--font-weight-semibold"), external_exports.literal("--font-weight-bold"), external_exports.literal("--font-text-xs-size"), external_exports.literal("--font-text-sm-size"), external_exports.literal("--font-text-md-size"), external_exports.literal("--font-text-lg-size"), external_exports.literal("--font-heading-xs-size"), external_exports.literal("--font-heading-sm-size"), external_exports.literal("--font-heading-md-size"), external_exports.literal("--font-heading-lg-size"), external_exports.literal("--font-heading-xl-size"), external_exports.literal("--font-heading-2xl-size"), external_exports.literal("--font-heading-3xl-size"), external_exports.literal("--font-text-xs-line-height"), external_exports.literal("--font-text-sm-line-height"), external_exports.literal("--font-text-md-line-height"), external_exports.literal("--font-text-lg-line-height"), external_exports.literal("--font-heading-xs-line-height"), external_exports.literal("--font-heading-sm-line-height"), external_exports.literal("--font-heading-md-line-height"), external_exports.literal("--font-heading-lg-line-height"), external_exports.literal("--font-heading-xl-line-height"), external_exports.literal("--font-heading-2xl-line-height"), external_exports.literal("--font-heading-3xl-line-height"), external_exports.literal("--border-radius-xs"), external_exports.literal("--border-radius-sm"), external_exports.literal("--border-radius-md"), external_exports.literal("--border-radius-lg"), external_exports.literal("--border-radius-xl"), external_exports.literal("--border-radius-full"), external_exports.literal("--border-width-regular"), external_exports.literal("--shadow-hairline"), external_exports.literal("--shadow-sm"), external_exports.literal("--shadow-md"), external_exports.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming.");
|
|
2639
|
+
var RQ = external_exports.record(HQ.describe(`Style variables for theming MCP apps.
|
|
2640
|
+
|
|
2641
|
+
Individual style keys are optional - hosts may provide any subset of these values.
|
|
2642
|
+
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
2643
|
+
|
|
2644
|
+
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
2645
|
+
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), external_exports.union([external_exports.string(), external_exports.undefined()]).describe(`Style variables for theming MCP apps.
|
|
2646
|
+
|
|
2647
|
+
Individual style keys are optional - hosts may provide any subset of these values.
|
|
2648
|
+
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
2649
|
+
|
|
2650
|
+
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
2651
|
+
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.
|
|
2652
|
+
|
|
2653
|
+
Individual style keys are optional - hosts may provide any subset of these values.
|
|
2654
|
+
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
2655
|
+
|
|
2656
|
+
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
2657
|
+
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);
|
|
2658
|
+
var L = external_exports.object({ method: external_exports.literal("ui/open-link"), params: external_exports.object({ url: external_exports.string().describe("URL to open in the host's browser") }) });
|
|
2659
|
+
var P = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).") }).passthrough();
|
|
2660
|
+
var A = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).") }).passthrough();
|
|
2661
|
+
var U = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the host rejected or failed to deliver the message.") }).passthrough();
|
|
2662
|
+
var w = external_exports.object({ method: external_exports.literal("ui/notifications/sandbox-proxy-ready"), params: external_exports.object({}) });
|
|
2663
|
+
var O = external_exports.object({ connectDomains: external_exports.array(external_exports.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
|
|
2664
|
+
|
|
2665
|
+
- Maps to CSP \`connect-src\` directive
|
|
2666
|
+
- Empty or omitted \u2192 no network connections (secure default)`), resourceDomains: external_exports.array(external_exports.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"), frameDomains: external_exports.array(external_exports.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"), baseUriDomains: external_exports.array(external_exports.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)") });
|
|
2667
|
+
var z = external_exports.object({ camera: external_exports.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."), microphone: external_exports.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."), geolocation: external_exports.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."), clipboardWrite: external_exports.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.") });
|
|
2668
|
+
var H = external_exports.object({ method: external_exports.literal("ui/notifications/size-changed"), params: external_exports.object({ width: external_exports.number().optional().describe("New width in pixels."), height: external_exports.number().optional().describe("New height in pixels.") }) });
|
|
2669
|
+
var R = external_exports.object({ method: external_exports.literal("ui/notifications/tool-input"), params: external_exports.object({ arguments: external_exports.record(external_exports.string(), external_exports.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.") }) });
|
|
2670
|
+
var T = external_exports.object({ method: external_exports.literal("ui/notifications/tool-input-partial"), params: external_exports.object({ arguments: external_exports.record(external_exports.string(), external_exports.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).") }) });
|
|
2671
|
+
var M = external_exports.object({ method: external_exports.literal("ui/notifications/tool-cancelled"), params: external_exports.object({ reason: external_exports.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").') }) });
|
|
2672
|
+
var o = external_exports.object({ fonts: external_exports.string().optional() });
|
|
2673
|
+
var s = external_exports.object({ variables: RQ.optional().describe("CSS variables for theming the app."), css: o.optional().describe("CSS blocks that apps can inject.") });
|
|
2674
|
+
var C = external_exports.object({ method: external_exports.literal("ui/resource-teardown"), params: external_exports.object({}) });
|
|
2675
|
+
var S = external_exports.record(external_exports.string(), external_exports.unknown());
|
|
2676
|
+
var F = external_exports.object({ text: external_exports.object({}).optional().describe("Host supports text content blocks."), image: external_exports.object({}).optional().describe("Host supports image content blocks."), audio: external_exports.object({}).optional().describe("Host supports audio content blocks."), resource: external_exports.object({}).optional().describe("Host supports resource content blocks."), resourceLink: external_exports.object({}).optional().describe("Host supports resource link content blocks."), structuredContent: external_exports.object({}).optional().describe("Host supports structured content.") });
|
|
2677
|
+
var q = external_exports.object({ method: external_exports.literal("ui/notifications/request-teardown"), params: external_exports.object({}).optional() });
|
|
2678
|
+
var t = external_exports.object({ experimental: external_exports.object({}).optional().describe("Experimental features (structure TBD)."), openLinks: external_exports.object({}).optional().describe("Host supports opening external URLs."), downloadFile: external_exports.object({}).optional().describe("Host supports file downloads via ui/download-file."), serverTools: external_exports.object({ listChanged: external_exports.boolean().optional().describe("Host supports tools/list_changed notifications.") }).optional().describe("Host can proxy tool calls to the MCP server."), serverResources: external_exports.object({ listChanged: external_exports.boolean().optional().describe("Host supports resources/list_changed notifications.") }).optional().describe("Host can proxy resource reads to the MCP server."), logging: external_exports.object({}).optional().describe("Host accepts log messages."), sandbox: external_exports.object({ permissions: z.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."), csp: O.optional().describe("CSP domains approved by the host.") }).optional().describe("Sandbox configuration applied by the host."), updateModelContext: F.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."), message: F.optional().describe("Host supports receiving content messages (ui/message) from the view."), sampling: external_exports.object({ tools: external_exports.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.") }).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.") });
|
|
2679
|
+
var a = external_exports.object({ experimental: external_exports.object({}).optional().describe("Experimental features (structure TBD)."), tools: external_exports.object({ listChanged: external_exports.boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."), availableDisplayModes: external_exports.array(B).optional().describe("Display modes the app supports.") });
|
|
2680
|
+
var y = external_exports.object({ method: external_exports.literal("ui/notifications/initialized"), params: external_exports.object({}).optional() });
|
|
2681
|
+
var TQ = external_exports.object({ csp: O.optional().describe("Content Security Policy configuration for UI resources."), permissions: z.optional().describe("Sandbox permissions requested by the UI resource."), domain: external_exports.string().optional().describe(`Dedicated origin for view sandbox.
|
|
2682
|
+
|
|
2683
|
+
Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
|
|
2684
|
+
|
|
2685
|
+
**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:
|
|
2686
|
+
- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
|
|
2687
|
+
- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
|
|
2688
|
+
|
|
2689
|
+
If omitted, host uses default sandbox origin (typically per-conversation).`), prefersBorder: external_exports.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
|
|
2690
|
+
|
|
2691
|
+
Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.
|
|
2692
|
+
|
|
2693
|
+
- \`true\`: request visible border + background
|
|
2694
|
+
- \`false\`: request no visible border + background
|
|
2695
|
+
- omitted: host decides border`) });
|
|
2696
|
+
var I = external_exports.object({ method: external_exports.literal("ui/request-display-mode"), params: external_exports.object({ mode: B.describe("The display mode being requested.") }) });
|
|
2697
|
+
var g = external_exports.object({ mode: B.describe("The display mode that was actually set. May differ from requested if not supported.") }).passthrough();
|
|
2698
|
+
var e = external_exports.union([external_exports.literal("model"), external_exports.literal("app")]).describe("Tool visibility scope - who can access the tool.");
|
|
2699
|
+
var MQ = external_exports.object({ resourceUri: external_exports.string().optional(), visibility: external_exports.array(e).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
2700
|
+
- "model": Tool visible to and callable by the agent
|
|
2701
|
+
- "app": Tool callable by the app from this server only`), csp: external_exports.never().optional(), permissions: external_exports.never().optional() });
|
|
2702
|
+
var OX = external_exports.object({ mimeTypes: external_exports.array(external_exports.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.') });
|
|
2703
|
+
var f = external_exports.object({ method: external_exports.literal("ui/download-file"), params: external_exports.object({ contents: external_exports.array(external_exports.union([EmbeddedResourceSchema, ResourceLinkSchema])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.") }) });
|
|
2704
|
+
var k = external_exports.object({ method: external_exports.literal("ui/message"), params: external_exports.object({ role: external_exports.literal("user").describe('Message role, currently only "user" is supported.'), content: external_exports.array(ContentBlockSchema).describe("Message content blocks (text, image, etc.).") }) });
|
|
2705
|
+
var CQ = external_exports.object({ method: external_exports.literal("ui/notifications/sandbox-resource-ready"), params: external_exports.object({ html: external_exports.string().describe("HTML content to load into the inner iframe."), sandbox: external_exports.string().optional().describe("Optional override for the inner iframe's sandbox attribute."), csp: O.optional().describe("CSP configuration from resource metadata."), permissions: z.optional().describe("Sandbox permissions from resource metadata.") }) });
|
|
2706
|
+
var v = external_exports.object({ method: external_exports.literal("ui/notifications/tool-result"), params: CallToolResultSchema.describe("Standard MCP tool execution result.") });
|
|
2707
|
+
var x = external_exports.object({ toolInfo: external_exports.object({ id: RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."), tool: ToolSchema.describe("Tool definition including name, inputSchema, etc.") }).optional().describe("Metadata of the tool call that instantiated this App."), theme: r.optional().describe("Current color theme preference."), styles: s.optional().describe("Style configuration for theming the app."), displayMode: B.optional().describe("How the UI is currently displayed."), availableDisplayModes: external_exports.array(B).optional().describe("Display modes the host supports."), containerDimensions: external_exports.union([external_exports.object({ height: external_exports.number().describe("Fixed container height in pixels.") }), external_exports.object({ maxHeight: external_exports.union([external_exports.number(), external_exports.undefined()]).optional().describe("Maximum container height in pixels.") })]).and(external_exports.union([external_exports.object({ width: external_exports.number().describe("Fixed container width in pixels.") }), external_exports.object({ maxWidth: external_exports.union([external_exports.number(), external_exports.undefined()]).optional().describe("Maximum container width in pixels.") })])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
2708
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`), locale: external_exports.string().optional().describe("User's language and region preference in BCP 47 format."), timeZone: external_exports.string().optional().describe("User's timezone in IANA format."), userAgent: external_exports.string().optional().describe("Host application identifier."), platform: external_exports.union([external_exports.literal("web"), external_exports.literal("desktop"), external_exports.literal("mobile")]).optional().describe("Platform type for responsive design decisions."), deviceCapabilities: external_exports.object({ touch: external_exports.boolean().optional().describe("Whether the device supports touch input."), hover: external_exports.boolean().optional().describe("Whether the device supports hover interactions.") }).optional().describe("Device input capabilities."), safeAreaInsets: external_exports.object({ top: external_exports.number().describe("Top safe area inset in pixels."), right: external_exports.number().describe("Right safe area inset in pixels."), bottom: external_exports.number().describe("Bottom safe area inset in pixels."), left: external_exports.number().describe("Left safe area inset in pixels.") }).optional().describe("Mobile safe area boundaries in pixels.") }).passthrough();
|
|
2709
|
+
var b = external_exports.object({ method: external_exports.literal("ui/notifications/host-context-changed"), params: x.describe("Partial context update containing only changed fields.") });
|
|
2710
|
+
var d = external_exports.object({ method: external_exports.literal("ui/update-model-context"), params: external_exports.object({ content: external_exports.array(ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."), structuredContent: external_exports.record(external_exports.string(), external_exports.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.") }) });
|
|
2711
|
+
var u = external_exports.object({ method: external_exports.literal("ui/initialize"), params: external_exports.object({ appInfo: ImplementationSchema.describe("App identification (name and version)."), appCapabilities: a.describe("Features and capabilities this app provides."), protocolVersion: external_exports.string().describe("Protocol version this app supports.") }) });
|
|
2712
|
+
var h = external_exports.object({ protocolVersion: external_exports.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'), hostInfo: ImplementationSchema.describe("Host application identification and version."), hostCapabilities: t.describe("Features and capabilities provided by the host."), hostContext: x.describe("Rich context about the host environment.") }).passthrough();
|
|
2713
|
+
var E = class {
|
|
2714
|
+
eventTarget;
|
|
2715
|
+
eventSource;
|
|
2716
|
+
messageListener;
|
|
2717
|
+
constructor(X = window.parent, Y) {
|
|
2718
|
+
this.eventTarget = X;
|
|
2719
|
+
this.eventSource = Y;
|
|
2720
|
+
this.messageListener = (Z) => {
|
|
2721
|
+
if (Y && Z.source !== this.eventSource) {
|
|
2722
|
+
console.debug("Ignoring message from unknown source", Z);
|
|
2723
|
+
return;
|
|
2724
|
+
}
|
|
2725
|
+
let $ = JSONRPCMessageSchema.safeParse(Z.data);
|
|
2726
|
+
if ($.success) console.debug("Parsed message", $.data), this.onmessage?.($.data);
|
|
2727
|
+
else if (Z.data?.jsonrpc !== "2.0") console.debug("Ignoring non-JSON-RPC message", $.error.message, Z);
|
|
2728
|
+
else console.error("Failed to parse message", $.error.message, Z), this.onerror?.(Error("Invalid JSON-RPC message received: " + $.error.message));
|
|
2729
|
+
};
|
|
2730
|
+
}
|
|
2731
|
+
async start() {
|
|
2732
|
+
window.addEventListener("message", this.messageListener);
|
|
2733
|
+
}
|
|
2734
|
+
async send(X, Y) {
|
|
2735
|
+
if (X.method !== V) console.debug("Sending message", X);
|
|
2736
|
+
this.eventTarget.postMessage(X, "*");
|
|
2737
|
+
}
|
|
2738
|
+
async close() {
|
|
2739
|
+
window.removeEventListener("message", this.messageListener), this.onclose?.();
|
|
2740
|
+
}
|
|
2741
|
+
onclose;
|
|
2742
|
+
onerror;
|
|
2743
|
+
onmessage;
|
|
2744
|
+
sessionId;
|
|
2745
|
+
setProtocolVersion;
|
|
2746
|
+
};
|
|
2747
|
+
var KX = [j];
|
|
2748
|
+
var DX = class extends _ {
|
|
2749
|
+
_client;
|
|
2750
|
+
_hostInfo;
|
|
2751
|
+
_capabilities;
|
|
2752
|
+
_appCapabilities;
|
|
2753
|
+
_hostContext = {};
|
|
2754
|
+
_appInfo;
|
|
2755
|
+
_initializedReceived = false;
|
|
2756
|
+
_baseReplaceRequestHandler = this.replaceRequestHandler;
|
|
2757
|
+
replaceRequestHandler = (X, Y) => {
|
|
2758
|
+
this._baseReplaceRequestHandler(X, (Z, $) => {
|
|
2759
|
+
if (!this._initializedReceived) console.warn(`[ext-apps] AppBridge received '${Z.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);
|
|
2760
|
+
return Y(Z, $);
|
|
2761
|
+
});
|
|
2762
|
+
};
|
|
2763
|
+
eventSchemas = { sizechange: H, sandboxready: w, initialized: y, requestteardown: q, loggingmessage: LoggingMessageNotificationSchema };
|
|
2764
|
+
constructor(X, Y, Z, $) {
|
|
2765
|
+
super($);
|
|
2766
|
+
this._client = X;
|
|
2767
|
+
this._hostInfo = Y;
|
|
2768
|
+
this._capabilities = Z;
|
|
2769
|
+
this.addEventListener("initialized", () => {
|
|
2770
|
+
this._initializedReceived = true;
|
|
2771
|
+
}), this._hostContext = $?.hostContext || {}, this.setRequestHandler(u, (J) => this._oninitialize(J)), this.setRequestHandler(PingRequestSchema, (J, K) => {
|
|
2772
|
+
return this.onping?.(J.params, K), {};
|
|
2773
|
+
}), this.replaceRequestHandler(I, (J) => {
|
|
2774
|
+
return { mode: this._hostContext.displayMode ?? "inline" };
|
|
2775
|
+
});
|
|
2776
|
+
}
|
|
2777
|
+
getAppCapabilities() {
|
|
2778
|
+
return this._appCapabilities;
|
|
2779
|
+
}
|
|
2780
|
+
getAppVersion() {
|
|
2781
|
+
return this._appInfo;
|
|
2782
|
+
}
|
|
2783
|
+
onping;
|
|
2784
|
+
get onsizechange() {
|
|
2785
|
+
return this.getEventHandler("sizechange");
|
|
2786
|
+
}
|
|
2787
|
+
set onsizechange(X) {
|
|
2788
|
+
this.setEventHandler("sizechange", X);
|
|
2789
|
+
}
|
|
2790
|
+
get onsandboxready() {
|
|
2791
|
+
return this.getEventHandler("sandboxready");
|
|
2792
|
+
}
|
|
2793
|
+
set onsandboxready(X) {
|
|
2794
|
+
this.setEventHandler("sandboxready", X);
|
|
2795
|
+
}
|
|
2796
|
+
get oninitialized() {
|
|
2797
|
+
return this.getEventHandler("initialized");
|
|
2798
|
+
}
|
|
2799
|
+
set oninitialized(X) {
|
|
2800
|
+
this.setEventHandler("initialized", X);
|
|
2801
|
+
}
|
|
2802
|
+
_onmessage;
|
|
2803
|
+
get onmessage() {
|
|
2804
|
+
return this._onmessage;
|
|
2805
|
+
}
|
|
2806
|
+
set onmessage(X) {
|
|
2807
|
+
this.warnIfRequestHandlerReplaced("onmessage", this._onmessage, X), this._onmessage = X, this.replaceRequestHandler(k, async (Y, Z) => {
|
|
2808
|
+
if (!this._onmessage) throw Error("No onmessage handler set");
|
|
2809
|
+
return this._onmessage(Y.params, Z);
|
|
2810
|
+
});
|
|
2811
|
+
}
|
|
2812
|
+
_onopenlink;
|
|
2813
|
+
get onopenlink() {
|
|
2814
|
+
return this._onopenlink;
|
|
2815
|
+
}
|
|
2816
|
+
set onopenlink(X) {
|
|
2817
|
+
this.warnIfRequestHandlerReplaced("onopenlink", this._onopenlink, X), this._onopenlink = X, this.replaceRequestHandler(L, async (Y, Z) => {
|
|
2818
|
+
if (!this._onopenlink) throw Error("No onopenlink handler set");
|
|
2819
|
+
return this._onopenlink(Y.params, Z);
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
_ondownloadfile;
|
|
2823
|
+
get ondownloadfile() {
|
|
2824
|
+
return this._ondownloadfile;
|
|
2825
|
+
}
|
|
2826
|
+
set ondownloadfile(X) {
|
|
2827
|
+
this.warnIfRequestHandlerReplaced("ondownloadfile", this._ondownloadfile, X), this._ondownloadfile = X, this.replaceRequestHandler(f, async (Y, Z) => {
|
|
2828
|
+
if (!this._ondownloadfile) throw Error("No ondownloadfile handler set");
|
|
2829
|
+
return this._ondownloadfile(Y.params, Z);
|
|
2830
|
+
});
|
|
2831
|
+
}
|
|
2832
|
+
get onrequestteardown() {
|
|
2833
|
+
return this.getEventHandler("requestteardown");
|
|
2834
|
+
}
|
|
2835
|
+
set onrequestteardown(X) {
|
|
2836
|
+
this.setEventHandler("requestteardown", X);
|
|
2837
|
+
}
|
|
2838
|
+
_onrequestdisplaymode;
|
|
2839
|
+
get onrequestdisplaymode() {
|
|
2840
|
+
return this._onrequestdisplaymode;
|
|
2841
|
+
}
|
|
2842
|
+
set onrequestdisplaymode(X) {
|
|
2843
|
+
this.warnIfRequestHandlerReplaced("onrequestdisplaymode", this._onrequestdisplaymode, X), this._onrequestdisplaymode = X, this.replaceRequestHandler(I, async (Y, Z) => {
|
|
2844
|
+
if (!this._onrequestdisplaymode) throw Error("No onrequestdisplaymode handler set");
|
|
2845
|
+
return this._onrequestdisplaymode(Y.params, Z);
|
|
2846
|
+
});
|
|
2847
|
+
}
|
|
2848
|
+
get onloggingmessage() {
|
|
2849
|
+
return this.getEventHandler("loggingmessage");
|
|
2850
|
+
}
|
|
2851
|
+
set onloggingmessage(X) {
|
|
2852
|
+
this.setEventHandler("loggingmessage", X);
|
|
2853
|
+
}
|
|
2854
|
+
_onupdatemodelcontext;
|
|
2855
|
+
get onupdatemodelcontext() {
|
|
2856
|
+
return this._onupdatemodelcontext;
|
|
2857
|
+
}
|
|
2858
|
+
set onupdatemodelcontext(X) {
|
|
2859
|
+
this.warnIfRequestHandlerReplaced("onupdatemodelcontext", this._onupdatemodelcontext, X), this._onupdatemodelcontext = X, this.replaceRequestHandler(d, async (Y, Z) => {
|
|
2860
|
+
if (!this._onupdatemodelcontext) throw Error("No onupdatemodelcontext handler set");
|
|
2861
|
+
return this._onupdatemodelcontext(Y.params, Z);
|
|
2862
|
+
});
|
|
2863
|
+
}
|
|
2864
|
+
_oncalltool;
|
|
2865
|
+
get oncalltool() {
|
|
2866
|
+
return this._oncalltool;
|
|
2867
|
+
}
|
|
2868
|
+
set oncalltool(X) {
|
|
2869
|
+
this.warnIfRequestHandlerReplaced("oncalltool", this._oncalltool, X), this._oncalltool = X, this.replaceRequestHandler(CallToolRequestSchema, async (Y, Z) => {
|
|
2870
|
+
if (!this._oncalltool) throw Error("No oncalltool handler set");
|
|
2871
|
+
return this._oncalltool(Y.params, Z);
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
set oncreatesamplingmessage(X) {
|
|
2875
|
+
this.setRequestHandler(CreateMessageRequestSchema, async (Y, Z) => {
|
|
2876
|
+
return X(Y.params, Z);
|
|
2877
|
+
});
|
|
2878
|
+
}
|
|
2879
|
+
sendToolListChanged(X = {}) {
|
|
2880
|
+
return this.notification({ method: "notifications/tools/list_changed", params: X });
|
|
2881
|
+
}
|
|
2882
|
+
_onlistresources;
|
|
2883
|
+
get onlistresources() {
|
|
2884
|
+
return this._onlistresources;
|
|
2885
|
+
}
|
|
2886
|
+
set onlistresources(X) {
|
|
2887
|
+
this.warnIfRequestHandlerReplaced("onlistresources", this._onlistresources, X), this._onlistresources = X, this.replaceRequestHandler(ListResourcesRequestSchema, async (Y, Z) => {
|
|
2888
|
+
if (!this._onlistresources) throw Error("No onlistresources handler set");
|
|
2889
|
+
return this._onlistresources(Y.params, Z);
|
|
2890
|
+
});
|
|
2891
|
+
}
|
|
2892
|
+
_onlistresourcetemplates;
|
|
2893
|
+
get onlistresourcetemplates() {
|
|
2894
|
+
return this._onlistresourcetemplates;
|
|
2895
|
+
}
|
|
2896
|
+
set onlistresourcetemplates(X) {
|
|
2897
|
+
this.warnIfRequestHandlerReplaced("onlistresourcetemplates", this._onlistresourcetemplates, X), this._onlistresourcetemplates = X, this.replaceRequestHandler(ListResourceTemplatesRequestSchema, async (Y, Z) => {
|
|
2898
|
+
if (!this._onlistresourcetemplates) throw Error("No onlistresourcetemplates handler set");
|
|
2899
|
+
return this._onlistresourcetemplates(Y.params, Z);
|
|
2900
|
+
});
|
|
2901
|
+
}
|
|
2902
|
+
_onreadresource;
|
|
2903
|
+
get onreadresource() {
|
|
2904
|
+
return this._onreadresource;
|
|
2905
|
+
}
|
|
2906
|
+
set onreadresource(X) {
|
|
2907
|
+
this.warnIfRequestHandlerReplaced("onreadresource", this._onreadresource, X), this._onreadresource = X, this.replaceRequestHandler(ReadResourceRequestSchema, async (Y, Z) => {
|
|
2908
|
+
if (!this._onreadresource) throw Error("No onreadresource handler set");
|
|
2909
|
+
return this._onreadresource(Y.params, Z);
|
|
2910
|
+
});
|
|
2911
|
+
}
|
|
2912
|
+
sendResourceListChanged(X = {}) {
|
|
2913
|
+
return this.notification({ method: "notifications/resources/list_changed", params: X });
|
|
2914
|
+
}
|
|
2915
|
+
_onlistprompts;
|
|
2916
|
+
get onlistprompts() {
|
|
2917
|
+
return this._onlistprompts;
|
|
2918
|
+
}
|
|
2919
|
+
set onlistprompts(X) {
|
|
2920
|
+
this.warnIfRequestHandlerReplaced("onlistprompts", this._onlistprompts, X), this._onlistprompts = X, this.replaceRequestHandler(ListPromptsRequestSchema, async (Y, Z) => {
|
|
2921
|
+
if (!this._onlistprompts) throw Error("No onlistprompts handler set");
|
|
2922
|
+
return this._onlistprompts(Y.params, Z);
|
|
2923
|
+
});
|
|
2924
|
+
}
|
|
2925
|
+
sendPromptListChanged(X = {}) {
|
|
2926
|
+
return this.notification({ method: "notifications/prompts/list_changed", params: X });
|
|
2927
|
+
}
|
|
2928
|
+
assertCapabilityForMethod(X) {
|
|
2929
|
+
}
|
|
2930
|
+
assertRequestHandlerCapability(X) {
|
|
2931
|
+
}
|
|
2932
|
+
assertNotificationCapability(X) {
|
|
2933
|
+
}
|
|
2934
|
+
assertTaskCapability(X) {
|
|
2935
|
+
throw Error("Tasks are not supported in MCP Apps");
|
|
2936
|
+
}
|
|
2937
|
+
assertTaskHandlerCapability(X) {
|
|
2938
|
+
throw Error("Task handlers are not supported in MCP Apps");
|
|
2939
|
+
}
|
|
2940
|
+
getCapabilities() {
|
|
2941
|
+
return this._capabilities;
|
|
2942
|
+
}
|
|
2943
|
+
async _oninitialize(X) {
|
|
2944
|
+
let Y = X.params.protocolVersion;
|
|
2945
|
+
if (this._appInfo !== void 0) console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");
|
|
2946
|
+
return this._appCapabilities = X.params.appCapabilities, this._appInfo = X.params.appInfo, { protocolVersion: KX.includes(Y) ? Y : j, hostCapabilities: this.getCapabilities(), hostInfo: this._hostInfo, hostContext: this._hostContext };
|
|
2947
|
+
}
|
|
2948
|
+
setHostContext(X) {
|
|
2949
|
+
let Y = {}, Z = false;
|
|
2950
|
+
for (let $ of Object.keys(X)) {
|
|
2951
|
+
let J = this._hostContext[$], K = X[$];
|
|
2952
|
+
if (GX(J, K)) continue;
|
|
2953
|
+
Y[$] = K, Z = true;
|
|
2954
|
+
}
|
|
2955
|
+
if (Z) this._hostContext = X, this.sendHostContextChange(Y);
|
|
2956
|
+
}
|
|
2957
|
+
sendHostContextChange(X) {
|
|
2958
|
+
return this.notification({ method: "ui/notifications/host-context-changed", params: X });
|
|
2959
|
+
}
|
|
2960
|
+
sendToolInput(X) {
|
|
2961
|
+
return this.notification({ method: "ui/notifications/tool-input", params: X });
|
|
2962
|
+
}
|
|
2963
|
+
sendToolInputPartial(X) {
|
|
2964
|
+
return this.notification({ method: "ui/notifications/tool-input-partial", params: X });
|
|
2965
|
+
}
|
|
2966
|
+
sendToolResult(X) {
|
|
2967
|
+
return this.notification({ method: "ui/notifications/tool-result", params: X });
|
|
2968
|
+
}
|
|
2969
|
+
sendToolCancelled(X) {
|
|
2970
|
+
return this.notification({ method: "ui/notifications/tool-cancelled", params: X });
|
|
2971
|
+
}
|
|
2972
|
+
sendSandboxResourceReady(X) {
|
|
2973
|
+
return this.notification({ method: "ui/notifications/sandbox-resource-ready", params: X });
|
|
2974
|
+
}
|
|
2975
|
+
teardownResource(X, Y) {
|
|
2976
|
+
return this.request({ method: "ui/resource-teardown", params: X }, S, Y);
|
|
2977
|
+
}
|
|
2978
|
+
sendResourceTeardown = this.teardownResource;
|
|
2979
|
+
callTool(X, Y) {
|
|
2980
|
+
return this.request({ method: "tools/call", params: X }, CallToolResultSchema, Y);
|
|
2981
|
+
}
|
|
2982
|
+
listTools(X, Y) {
|
|
2983
|
+
return this.request({ method: "tools/list", params: X }, ListToolsResultSchema, Y);
|
|
2984
|
+
}
|
|
2985
|
+
async connect(X) {
|
|
2986
|
+
if (this.transport) throw Error("AppBridge is already connected. Call close() before connecting again.");
|
|
2987
|
+
if (this._initializedReceived = false, this._client) {
|
|
2988
|
+
let Y = this._client.getServerCapabilities();
|
|
2989
|
+
if (!Y) throw Error("Client server capabilities not available");
|
|
2990
|
+
if (Y.tools) {
|
|
2991
|
+
if (this.oncalltool = async (Z, $) => {
|
|
2992
|
+
return this._client.request({ method: "tools/call", params: Z }, CallToolResultSchema, { signal: $.signal });
|
|
2993
|
+
}, Y.tools.listChanged) this._client.setNotificationHandler(ToolListChangedNotificationSchema, (Z) => this.sendToolListChanged(Z.params));
|
|
2994
|
+
}
|
|
2995
|
+
if (Y.resources) {
|
|
2996
|
+
if (this.onlistresources = async (Z, $) => {
|
|
2997
|
+
return this._client.request({ method: "resources/list", params: Z }, ListResourcesResultSchema, { signal: $.signal });
|
|
2998
|
+
}, this.onlistresourcetemplates = async (Z, $) => {
|
|
2999
|
+
return this._client.request({ method: "resources/templates/list", params: Z }, ListResourceTemplatesResultSchema, { signal: $.signal });
|
|
3000
|
+
}, this.onreadresource = async (Z, $) => {
|
|
3001
|
+
return this._client.request({ method: "resources/read", params: Z }, ReadResourceResultSchema, { signal: $.signal });
|
|
3002
|
+
}, Y.resources.listChanged) this._client.setNotificationHandler(ResourceListChangedNotificationSchema, (Z) => this.sendResourceListChanged(Z.params));
|
|
3003
|
+
}
|
|
3004
|
+
if (Y.prompts) {
|
|
3005
|
+
if (this.onlistprompts = async (Z, $) => {
|
|
3006
|
+
return this._client.request({ method: "prompts/list", params: Z }, ListPromptsResultSchema, { signal: $.signal });
|
|
3007
|
+
}, Y.prompts.listChanged) this._client.setNotificationHandler(PromptListChangedNotificationSchema, (Z) => this.sendPromptListChanged(Z.params));
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
return super.connect(X);
|
|
3011
|
+
}
|
|
3012
|
+
};
|
|
3013
|
+
function GX(X, Y) {
|
|
3014
|
+
return JSON.stringify(X) === JSON.stringify(Y);
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
// src/app-host.ts
|
|
3018
|
+
var PROXY_DOCUMENT = `<!doctype html><meta charset="utf-8"><style>html,body,iframe{border:0;margin:0;width:100%;height:100%;overflow:hidden}body{background:transparent}</style><script>
|
|
3019
|
+
let inner;
|
|
3020
|
+
const ready={jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-ready',params:{}};
|
|
3021
|
+
// Re-announce until the host acknowledges with the resource: when this document is hosted
|
|
3022
|
+
// cross-origin, the first announcement can arrive before the host's load handler is listening.
|
|
3023
|
+
const announce=setInterval(()=>parent.postMessage(ready,'*'),120);
|
|
3024
|
+
setTimeout(()=>clearInterval(announce),15000);
|
|
3025
|
+
addEventListener('message',(event)=>{
|
|
3026
|
+
if(event.source===parent){
|
|
3027
|
+
const message=event.data;
|
|
3028
|
+
if(message?.method==='ui/notifications/sandbox-resource-ready'){
|
|
3029
|
+
clearInterval(announce);
|
|
3030
|
+
if(inner)return;
|
|
3031
|
+
inner=document.createElement('iframe');
|
|
3032
|
+
inner.setAttribute('sandbox',message.params?.sandbox||'allow-scripts');
|
|
3033
|
+
inner.setAttribute('referrerpolicy','no-referrer');
|
|
3034
|
+
inner.srcdoc=String(message.params?.html||'');
|
|
3035
|
+
document.body.replaceChildren(inner);
|
|
3036
|
+
return;
|
|
3037
|
+
}
|
|
3038
|
+
inner?.contentWindow?.postMessage(message,'*');
|
|
3039
|
+
} else if(inner && event.source===inner.contentWindow) {
|
|
3040
|
+
parent.postMessage(event.data,'*');
|
|
3041
|
+
}
|
|
3042
|
+
});
|
|
3043
|
+
parent.postMessage(ready,'*');
|
|
3044
|
+
</script>`;
|
|
3045
|
+
function isAllowedAppLink(value, allowedDomains, baseUrl) {
|
|
3046
|
+
try {
|
|
3047
|
+
const parsed = new URL(value, baseUrl);
|
|
3048
|
+
if (parsed.protocol !== "https:") return void 0;
|
|
3049
|
+
const allowed = allowedDomains.some((candidate) => {
|
|
3050
|
+
try {
|
|
3051
|
+
return new URL(candidate).origin === parsed.origin;
|
|
3052
|
+
} catch {
|
|
3053
|
+
return false;
|
|
3054
|
+
}
|
|
3055
|
+
});
|
|
3056
|
+
return allowed ? parsed.href : void 0;
|
|
3057
|
+
} catch {
|
|
3058
|
+
return void 0;
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
function createAssistantAppHostContext(theme, allowFullscreen = false, displayMode = "inline") {
|
|
3062
|
+
return {
|
|
3063
|
+
theme,
|
|
3064
|
+
displayMode: allowFullscreen && displayMode === "fullscreen" ? "fullscreen" : "inline",
|
|
3065
|
+
availableDisplayModes: allowFullscreen ? ["inline", "fullscreen"] : ["inline"],
|
|
3066
|
+
platform: "web"
|
|
3067
|
+
};
|
|
3068
|
+
}
|
|
3069
|
+
var APP_RENDER_TIMEOUT_MS = 1e4;
|
|
3070
|
+
var APP_TEARDOWN_TIMEOUT_MS = 1e3;
|
|
3071
|
+
var mountedApps = /* @__PURE__ */ new WeakMap();
|
|
3072
|
+
function resolveSandboxUrl(value) {
|
|
3073
|
+
if (!value) return void 0;
|
|
3074
|
+
try {
|
|
3075
|
+
const parsed = new URL(value);
|
|
3076
|
+
return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.href : void 0;
|
|
3077
|
+
} catch {
|
|
3078
|
+
return void 0;
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
function mountAssistantApp(detail, actions, options = {}) {
|
|
3082
|
+
if (!detail.html) return void 0;
|
|
3083
|
+
const card = document.createElement("section");
|
|
3084
|
+
card.className = "noodle-app-card";
|
|
3085
|
+
if (detail.title) {
|
|
3086
|
+
const title = document.createElement("div");
|
|
3087
|
+
title.className = "noodle-app-title";
|
|
3088
|
+
title.textContent = detail.title;
|
|
3089
|
+
card.append(title);
|
|
3090
|
+
}
|
|
3091
|
+
const exitFullscreen = document.createElement("button");
|
|
3092
|
+
exitFullscreen.className = "noodle-app-fullscreen-exit";
|
|
3093
|
+
exitFullscreen.type = "button";
|
|
3094
|
+
exitFullscreen.setAttribute("aria-label", "Exit fullscreen");
|
|
3095
|
+
exitFullscreen.title = "Exit fullscreen";
|
|
3096
|
+
exitFullscreen.hidden = true;
|
|
3097
|
+
card.append(exitFullscreen);
|
|
3098
|
+
const frame = document.createElement("iframe");
|
|
3099
|
+
frame.className = "noodle-app-frame";
|
|
3100
|
+
frame.title = detail.title ?? detail.tool;
|
|
3101
|
+
frame.setAttribute("sandbox", "allow-scripts");
|
|
3102
|
+
frame.setAttribute("referrerpolicy", "no-referrer");
|
|
3103
|
+
const sandboxUrl = resolveSandboxUrl(options.sandboxUrl);
|
|
3104
|
+
if (sandboxUrl) frame.src = sandboxUrl;
|
|
3105
|
+
else frame.srcdoc = PROXY_DOCUMENT;
|
|
3106
|
+
card.append(frame);
|
|
3107
|
+
let mountedBridge;
|
|
3108
|
+
let mountedTransport;
|
|
3109
|
+
let destroyed = false;
|
|
3110
|
+
let initialized = false;
|
|
3111
|
+
let currentTheme = actions.theme;
|
|
3112
|
+
let displayMode = "inline";
|
|
3113
|
+
let hostContext = createAssistantAppHostContext(
|
|
3114
|
+
currentTheme,
|
|
3115
|
+
options.allowFullscreen === true,
|
|
3116
|
+
displayMode
|
|
3117
|
+
);
|
|
3118
|
+
let destroyPromise;
|
|
3119
|
+
const applyDisplayMode = (requestedMode) => {
|
|
3120
|
+
displayMode = requestedMode === "fullscreen" && options.allowFullscreen === true ? "fullscreen" : "inline";
|
|
3121
|
+
card.toggleAttribute("data-fullscreen", displayMode === "fullscreen");
|
|
3122
|
+
exitFullscreen.hidden = displayMode !== "fullscreen";
|
|
3123
|
+
hostContext = createAssistantAppHostContext(
|
|
3124
|
+
currentTheme,
|
|
3125
|
+
options.allowFullscreen === true,
|
|
3126
|
+
displayMode
|
|
3127
|
+
);
|
|
3128
|
+
if (initialized) mountedBridge?.setHostContext(hostContext);
|
|
3129
|
+
return displayMode;
|
|
3130
|
+
};
|
|
3131
|
+
exitFullscreen.addEventListener("click", () => {
|
|
3132
|
+
if (destroyed) return;
|
|
3133
|
+
applyDisplayMode("inline");
|
|
3134
|
+
frame.focus();
|
|
3135
|
+
});
|
|
3136
|
+
const renderTimer = setTimeout(() => {
|
|
3137
|
+
if (initialized || !frame.isConnected) return;
|
|
3138
|
+
const note = document.createElement("div");
|
|
3139
|
+
note.className = "noodle-app-fallback";
|
|
3140
|
+
note.textContent = "This app view could not be displayed.";
|
|
3141
|
+
frame.replaceWith(note);
|
|
3142
|
+
options.onRenderFailure?.({ code: "view_render_timeout", retryable: false });
|
|
3143
|
+
}, APP_RENDER_TIMEOUT_MS);
|
|
3144
|
+
frame.addEventListener(
|
|
3145
|
+
"load",
|
|
3146
|
+
() => {
|
|
3147
|
+
if (destroyed) return;
|
|
3148
|
+
const target = frame.contentWindow;
|
|
3149
|
+
if (!target) return;
|
|
3150
|
+
const bridge = new DX(
|
|
3151
|
+
null,
|
|
3152
|
+
{ name: "Noodle Seed Embedded Assistant", version: "1.0.0" },
|
|
3153
|
+
{
|
|
3154
|
+
openLinks: {},
|
|
3155
|
+
serverTools: {},
|
|
3156
|
+
serverResources: {},
|
|
3157
|
+
updateModelContext: { text: {}, structuredContent: {} },
|
|
3158
|
+
message: { text: {} }
|
|
3159
|
+
},
|
|
3160
|
+
{
|
|
3161
|
+
hostContext
|
|
3162
|
+
}
|
|
3163
|
+
);
|
|
3164
|
+
mountedBridge = bridge;
|
|
3165
|
+
bridge.onsandboxready = () => {
|
|
3166
|
+
if (destroyed) return;
|
|
3167
|
+
const current = options.getDetail?.() ?? detail;
|
|
3168
|
+
void bridge.sendSandboxResourceReady({
|
|
3169
|
+
html: current.html,
|
|
3170
|
+
sandbox: "allow-scripts",
|
|
3171
|
+
...current.resourceMeta ?? {}
|
|
3172
|
+
});
|
|
3173
|
+
};
|
|
3174
|
+
bridge.onsizechange = ({ height }) => {
|
|
3175
|
+
if (destroyed) return;
|
|
3176
|
+
if (typeof height === "number" && Number.isFinite(height)) {
|
|
3177
|
+
frame.style.height = `${Math.min(1200, Math.max(120, Math.ceil(height)))}px`;
|
|
3178
|
+
}
|
|
3179
|
+
};
|
|
3180
|
+
bridge.onmessage = async ({ content }) => {
|
|
3181
|
+
if (destroyed) return {};
|
|
3182
|
+
const text = content.flatMap(
|
|
3183
|
+
(part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []
|
|
3184
|
+
).join("\n").trim();
|
|
3185
|
+
if (text) await actions.sendMessage(text);
|
|
3186
|
+
return {};
|
|
3187
|
+
};
|
|
3188
|
+
bridge.onupdatemodelcontext = async (update) => {
|
|
3189
|
+
if (destroyed) return {};
|
|
3190
|
+
actions.updateModelContext(update);
|
|
3191
|
+
return {};
|
|
3192
|
+
};
|
|
3193
|
+
bridge.onrequestteardown = () => {
|
|
3194
|
+
if (destroyed) return;
|
|
3195
|
+
options.onTeardownRequest?.();
|
|
3196
|
+
void destroy();
|
|
3197
|
+
};
|
|
3198
|
+
bridge.onopenlink = async ({ url }) => {
|
|
3199
|
+
if (destroyed) return { isError: true };
|
|
3200
|
+
const current = options.getDetail?.() ?? detail;
|
|
3201
|
+
const allowed = isAllowedAppLink(
|
|
3202
|
+
url,
|
|
3203
|
+
current.allowedOpenDomains ?? [],
|
|
3204
|
+
globalThis.location?.href ?? "https://invalid.example"
|
|
3205
|
+
);
|
|
3206
|
+
if (!allowed) return { isError: true };
|
|
3207
|
+
globalThis.open?.(allowed, "_blank", "noopener,noreferrer");
|
|
3208
|
+
return {};
|
|
3209
|
+
};
|
|
3210
|
+
bridge.onrequestdisplaymode = async ({ mode }) => {
|
|
3211
|
+
if (destroyed) return { mode: displayMode };
|
|
3212
|
+
return { mode: applyDisplayMode(mode) };
|
|
3213
|
+
};
|
|
3214
|
+
bridge.oncalltool = async (params) => {
|
|
3215
|
+
if (destroyed) {
|
|
3216
|
+
return {
|
|
3217
|
+
content: [{ type: "text", text: "App view is closing." }],
|
|
3218
|
+
isError: true
|
|
3219
|
+
};
|
|
3220
|
+
}
|
|
3221
|
+
return await actions.client.requestApp("tools/call", params);
|
|
3222
|
+
};
|
|
3223
|
+
bridge.onlistresources = async (params) => {
|
|
3224
|
+
if (destroyed) {
|
|
3225
|
+
return { resources: [] };
|
|
3226
|
+
}
|
|
3227
|
+
return await actions.client.requestApp("resources/list", params ?? {});
|
|
3228
|
+
};
|
|
3229
|
+
bridge.onreadresource = async (params) => {
|
|
3230
|
+
if (destroyed) {
|
|
3231
|
+
return { contents: [] };
|
|
3232
|
+
}
|
|
3233
|
+
return await actions.client.requestApp("resources/read", params);
|
|
3234
|
+
};
|
|
3235
|
+
bridge.oninitialized = () => {
|
|
3236
|
+
if (destroyed) return;
|
|
3237
|
+
initialized = true;
|
|
3238
|
+
clearTimeout(renderTimer);
|
|
3239
|
+
bridge.setHostContext(hostContext);
|
|
3240
|
+
const current = options.getDetail?.() ?? detail;
|
|
3241
|
+
void bridge.sendToolInput({ arguments: current.arguments ?? {} });
|
|
3242
|
+
void bridge.sendToolResult({
|
|
3243
|
+
content: [{ type: "text", text: JSON.stringify(current.result) }],
|
|
3244
|
+
...typeof current.result === "object" && current.result !== null && !Array.isArray(current.result) ? { structuredContent: current.result } : {}
|
|
3245
|
+
});
|
|
3246
|
+
};
|
|
3247
|
+
const transport = new E(target, target);
|
|
3248
|
+
mountedTransport = transport;
|
|
3249
|
+
void bridge.connect(transport).catch(() => {
|
|
3250
|
+
void destroy();
|
|
3251
|
+
});
|
|
3252
|
+
},
|
|
3253
|
+
{ once: true }
|
|
3254
|
+
);
|
|
3255
|
+
const updateTheme = (theme) => {
|
|
3256
|
+
if (destroyed) return;
|
|
3257
|
+
currentTheme = theme;
|
|
3258
|
+
hostContext = createAssistantAppHostContext(
|
|
3259
|
+
currentTheme,
|
|
3260
|
+
options.allowFullscreen === true,
|
|
3261
|
+
displayMode
|
|
3262
|
+
);
|
|
3263
|
+
if (initialized) mountedBridge?.setHostContext(hostContext);
|
|
3264
|
+
};
|
|
3265
|
+
const destroy = () => {
|
|
3266
|
+
if (destroyPromise) return destroyPromise;
|
|
3267
|
+
destroyed = true;
|
|
3268
|
+
clearTimeout(renderTimer);
|
|
3269
|
+
destroyPromise = (async () => {
|
|
3270
|
+
try {
|
|
3271
|
+
if (initialized) {
|
|
3272
|
+
await mountedBridge?.teardownResource({}, { timeout: APP_TEARDOWN_TIMEOUT_MS });
|
|
3273
|
+
}
|
|
3274
|
+
} catch {
|
|
3275
|
+
}
|
|
3276
|
+
await mountedTransport?.close().catch(() => {
|
|
3277
|
+
});
|
|
3278
|
+
card.remove();
|
|
3279
|
+
mountedApps.delete(card);
|
|
3280
|
+
})();
|
|
3281
|
+
return destroyPromise;
|
|
3282
|
+
};
|
|
3283
|
+
mountedApps.set(card, { destroy, updateTheme });
|
|
3284
|
+
return card;
|
|
3285
|
+
}
|
|
3286
|
+
function updateAssistantAppTheme(card, theme) {
|
|
3287
|
+
mountedApps.get(card)?.updateTheme(theme);
|
|
3288
|
+
}
|
|
3289
|
+
function unmountAssistantApp(card) {
|
|
3290
|
+
return mountedApps.get(card)?.destroy() ?? Promise.resolve();
|
|
3291
|
+
}
|
|
3292
|
+
|
|
3293
|
+
// src/app-view-styles.ts
|
|
3294
|
+
var ASSISTANT_APP_VIEW_CSS = `
|
|
3295
|
+
.noodle-app-card { position: relative; display: grid; gap: 8px; width: 100%; margin: 4px 0 16px; overflow: hidden; color: var(--ns-assistant-app-text, inherit); border: 1px solid var(--ns-assistant-app-border, var(--ns-assistant-divider, var(--ns-assistant-default-divider, var(--ns-app-view-border, #d1d5db)))); border-radius: var(--ns-assistant-card-radius, var(--ns-assistant-default-card-radius, 12px)); background: var(--ns-assistant-app, var(--ns-assistant-elevated, var(--ns-assistant-default-elevated, var(--ns-app-view-surface, #fff)))); }
|
|
3296
|
+
.noodle-app-title { padding: 10px 12px 0; font-size: .86em; font-weight: 650; }
|
|
3297
|
+
.noodle-app-fullscreen-exit { position: absolute; top: max(12px, env(safe-area-inset-top)); right: max(12px, env(safe-area-inset-right)); z-index: 1; display: grid; place-items: center; width: 44px; height: 44px; padding: 0; color: var(--ns-assistant-muted-text, var(--ns-assistant-default-muted-text, var(--ns-app-view-muted, #6b7280))); border: 1px solid var(--ns-assistant-secondary-button-border, var(--ns-assistant-divider, var(--ns-assistant-default-divider, var(--ns-app-view-border, #d1d5db)))); border-radius: 999px; background: var(--ns-assistant-secondary-button, var(--ns-assistant-elevated, var(--ns-assistant-default-elevated, var(--ns-app-view-surface, #fff)))); box-shadow: 0 6px 20px rgba(0,0,0,.14); cursor: pointer; font: inherit; transition: color .15s ease, background .15s ease, transform .15s ease; }
|
|
3298
|
+
.noodle-app-fullscreen-exit[hidden] { display: none; }
|
|
3299
|
+
.noodle-app-fullscreen-exit::before { content: ''; width: 18px; height: 18px; background: currentColor; -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='m6 6 12 12M18 6 6 18' fill='none' stroke='black' stroke-width='2' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat; mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='m6 6 12 12M18 6 6 18' fill='none' stroke='black' stroke-width='2' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat; }
|
|
3300
|
+
.noodle-app-fullscreen-exit:hover { color: var(--ns-assistant-text, var(--ns-assistant-default-text, inherit)); background: var(--ns-assistant-hover, var(--ns-assistant-elevated, var(--ns-assistant-default-elevated, var(--ns-app-view-surface, #fff)))); }
|
|
3301
|
+
.noodle-app-fullscreen-exit:focus-visible { outline: 3px solid var(--ns-assistant-focus, var(--ns-assistant-default-focus, #2563eb)); outline-offset: 2px; }
|
|
3302
|
+
.noodle-app-fullscreen-exit:active { transform: scale(.96); }
|
|
3303
|
+
.noodle-app-frame { display: block; width: 100%; min-height: 120px; border: 0; background: transparent; }
|
|
3304
|
+
.noodle-app-fallback { padding: 14px 16px; font-size: 13px; color: var(--ns-assistant-muted, var(--ns-assistant-default-muted, var(--ns-app-view-muted, #6b7280))); }
|
|
3305
|
+
.noodle-app-card[data-fullscreen] { position: fixed; inset: 0; z-index: 2; margin: 0; border-radius: 0; background: var(--ns-assistant-panel, var(--ns-assistant-default-panel, var(--ns-app-view-surface, #fff))); }
|
|
3306
|
+
.noodle-app-card[data-fullscreen] .noodle-app-frame { height: 100% !important; }
|
|
3307
|
+
`;
|
|
3308
|
+
var ASSISTANT_APP_VIEW_STYLES = `<style>
|
|
3309
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
3310
|
+
:host { --ns-app-view-surface: #fff; --ns-app-view-border: #d1d5db; --ns-app-view-muted: #6b7280; display: block; min-width: 0; color: #111827; color-scheme: light; font: inherit; }
|
|
3311
|
+
:host([data-theme="dark"]) { --ns-app-view-surface: #17191f; --ns-app-view-border: #343741; --ns-app-view-muted: #a7adb8; color: #f3f4f6; color-scheme: dark; }
|
|
3312
|
+
:host([hidden]) { display: none; }
|
|
3313
|
+
${ASSISTANT_APP_VIEW_CSS}
|
|
3314
|
+
</style>`;
|
|
3315
|
+
|
|
3316
|
+
export {
|
|
3317
|
+
mountAssistantApp,
|
|
3318
|
+
updateAssistantAppTheme,
|
|
3319
|
+
unmountAssistantApp,
|
|
3320
|
+
ASSISTANT_APP_VIEW_CSS,
|
|
3321
|
+
ASSISTANT_APP_VIEW_STYLES
|
|
3322
|
+
};
|
|
3323
|
+
//# sourceMappingURL=chunk-XKTUXFGX.js.map
|