@modelcontextprotocol/server 2.0.0-alpha.3 → 2.0.0-alpha.4
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 +5 -2
- package/dist/{ajvProvider-Birb50r-.mjs → ajvProvider-BQMcjynJ.mjs} +952 -154
- package/dist/ajvProvider-BQMcjynJ.mjs.map +1 -0
- package/dist/{ajvProvider-DZ_siXcF.d.mts → ajvProvider-Dzgk80kq.d.mts} +58 -11
- package/dist/ajvProvider-Dzgk80kq.d.mts.map +1 -0
- package/dist/{cfWorkerProvider-BrJKpSFH.mjs → cfWorkerProvider-BDC2rVl3.mjs} +21 -5
- package/dist/cfWorkerProvider-BDC2rVl3.mjs.map +1 -0
- package/dist/{cfWorkerProvider-DUhk5Ewx.d.mts → cfWorkerProvider-DmvjVsvQ.d.mts} +13 -6
- package/dist/cfWorkerProvider-DmvjVsvQ.d.mts.map +1 -0
- package/dist/{transport-DMKhEchd.d.mts → createMcpHandler-Du3hjXvf.d.mts} +5283 -1559
- package/dist/createMcpHandler-Du3hjXvf.d.mts.map +1 -0
- package/dist/index.d.mts +167 -2015
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1238 -1281
- package/dist/index.mjs.map +1 -1
- package/dist/mcp-JttQJlI9.mjs +9998 -0
- package/dist/mcp-JttQJlI9.mjs.map +1 -0
- package/dist/shimsNode.d.mts +1 -1
- package/dist/shimsNode.mjs +1 -1
- package/dist/shimsWorkerd.d.mts +1 -1
- package/dist/shimsWorkerd.mjs +1 -1
- package/dist/stdio.d.mts +61 -3
- package/dist/stdio.d.mts.map +1 -1
- package/dist/stdio.mjs +457 -2
- package/dist/stdio.mjs.map +1 -1
- package/dist/types-DBYdVs-n.d.mts +1099 -0
- package/dist/types-DBYdVs-n.d.mts.map +1 -0
- package/dist/validators/ajv.d.mts +1 -1
- package/dist/validators/ajv.mjs +1 -1
- package/dist/validators/cfWorker.d.mts +1 -1
- package/dist/validators/cfWorker.mjs +1 -1
- package/package.json +3 -6
- package/dist/ajvProvider-Birb50r-.mjs.map +0 -1
- package/dist/ajvProvider-DZ_siXcF.d.mts.map +0 -1
- package/dist/cfWorkerProvider-BrJKpSFH.mjs.map +0 -1
- package/dist/cfWorkerProvider-DUhk5Ewx.d.mts.map +0 -1
- package/dist/src-Pa1iAvsj.mjs +0 -3386
- package/dist/src-Pa1iAvsj.mjs.map +0 -1
- package/dist/transport-DMKhEchd.d.mts.map +0 -1
- package/dist/types-R2RTIcjk.d.mts +0 -66
- package/dist/types-R2RTIcjk.d.mts.map +0 -1
package/dist/src-Pa1iAvsj.mjs
DELETED
|
@@ -1,3386 +0,0 @@
|
|
|
1
|
-
import { n as __exportAll } from "./chunk-BRhqBsOc.mjs";
|
|
2
|
-
import * as z from "zod/v4";
|
|
3
|
-
|
|
4
|
-
//#region ../core-internal/src/auth/errors.ts
|
|
5
|
-
/**
|
|
6
|
-
* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749}
|
|
7
|
-
* and extensions.
|
|
8
|
-
*/
|
|
9
|
-
let OAuthErrorCode = /* @__PURE__ */ function(OAuthErrorCode$1) {
|
|
10
|
-
/**
|
|
11
|
-
* The request is missing a required parameter, includes an invalid parameter value,
|
|
12
|
-
* includes a parameter more than once, or is otherwise malformed.
|
|
13
|
-
*/
|
|
14
|
-
OAuthErrorCode$1["InvalidRequest"] = "invalid_request";
|
|
15
|
-
/**
|
|
16
|
-
* Client authentication failed (e.g., unknown client, no client authentication included,
|
|
17
|
-
* or unsupported authentication method).
|
|
18
|
-
*/
|
|
19
|
-
OAuthErrorCode$1["InvalidClient"] = "invalid_client";
|
|
20
|
-
/**
|
|
21
|
-
* The provided authorization grant or refresh token is invalid, expired, revoked,
|
|
22
|
-
* does not match the redirection URI used in the authorization request, or was issued to another client.
|
|
23
|
-
*/
|
|
24
|
-
OAuthErrorCode$1["InvalidGrant"] = "invalid_grant";
|
|
25
|
-
/**
|
|
26
|
-
* The authenticated client is not authorized to use this authorization grant type.
|
|
27
|
-
*/
|
|
28
|
-
OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client";
|
|
29
|
-
/**
|
|
30
|
-
* The authorization grant type is not supported by the authorization server.
|
|
31
|
-
*/
|
|
32
|
-
OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type";
|
|
33
|
-
/**
|
|
34
|
-
* The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner.
|
|
35
|
-
*/
|
|
36
|
-
OAuthErrorCode$1["InvalidScope"] = "invalid_scope";
|
|
37
|
-
/**
|
|
38
|
-
* The resource owner or authorization server denied the request.
|
|
39
|
-
*/
|
|
40
|
-
OAuthErrorCode$1["AccessDenied"] = "access_denied";
|
|
41
|
-
/**
|
|
42
|
-
* The authorization server encountered an unexpected condition that prevented it from fulfilling the request.
|
|
43
|
-
*/
|
|
44
|
-
OAuthErrorCode$1["ServerError"] = "server_error";
|
|
45
|
-
/**
|
|
46
|
-
* The authorization server is currently unable to handle the request due to temporary overloading or maintenance.
|
|
47
|
-
*/
|
|
48
|
-
OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable";
|
|
49
|
-
/**
|
|
50
|
-
* The authorization server does not support obtaining an authorization code using this method.
|
|
51
|
-
*/
|
|
52
|
-
OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type";
|
|
53
|
-
/**
|
|
54
|
-
* The authorization server does not support the requested token type.
|
|
55
|
-
*/
|
|
56
|
-
OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type";
|
|
57
|
-
/**
|
|
58
|
-
* The access token provided is expired, revoked, malformed, or invalid for other reasons.
|
|
59
|
-
*/
|
|
60
|
-
OAuthErrorCode$1["InvalidToken"] = "invalid_token";
|
|
61
|
-
/**
|
|
62
|
-
* The HTTP method used is not allowed for this endpoint. (Custom, non-standard error)
|
|
63
|
-
*/
|
|
64
|
-
OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed";
|
|
65
|
-
/**
|
|
66
|
-
* Rate limit exceeded. (Custom, non-standard error based on RFC 6585)
|
|
67
|
-
*/
|
|
68
|
-
OAuthErrorCode$1["TooManyRequests"] = "too_many_requests";
|
|
69
|
-
/**
|
|
70
|
-
* The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591)
|
|
71
|
-
*/
|
|
72
|
-
OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata";
|
|
73
|
-
/**
|
|
74
|
-
* The request requires higher privileges than provided by the access token.
|
|
75
|
-
*/
|
|
76
|
-
OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope";
|
|
77
|
-
/**
|
|
78
|
-
* The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707)
|
|
79
|
-
*/
|
|
80
|
-
OAuthErrorCode$1["InvalidTarget"] = "invalid_target";
|
|
81
|
-
return OAuthErrorCode$1;
|
|
82
|
-
}({});
|
|
83
|
-
/**
|
|
84
|
-
* OAuth error class for all OAuth-related errors.
|
|
85
|
-
*/
|
|
86
|
-
var OAuthError = class OAuthError extends Error {
|
|
87
|
-
constructor(code, message, errorUri) {
|
|
88
|
-
super(message);
|
|
89
|
-
this.code = code;
|
|
90
|
-
this.errorUri = errorUri;
|
|
91
|
-
this.name = "OAuthError";
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Converts the error to a standard OAuth error response object.
|
|
95
|
-
*/
|
|
96
|
-
toResponseObject() {
|
|
97
|
-
const response = {
|
|
98
|
-
error: this.code,
|
|
99
|
-
error_description: this.message
|
|
100
|
-
};
|
|
101
|
-
if (this.errorUri) response.error_uri = this.errorUri;
|
|
102
|
-
return response;
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* Creates an {@linkcode OAuthError} from an OAuth error response.
|
|
106
|
-
*/
|
|
107
|
-
static fromResponse(response) {
|
|
108
|
-
return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri);
|
|
109
|
-
}
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
//#endregion
|
|
113
|
-
//#region ../core-internal/src/errors/sdkErrors.ts
|
|
114
|
-
/**
|
|
115
|
-
* Error codes for SDK errors (local errors that never cross the wire).
|
|
116
|
-
* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses
|
|
117
|
-
* descriptive string values for better developer experience.
|
|
118
|
-
*
|
|
119
|
-
* These errors are thrown locally by the SDK and are never serialized as
|
|
120
|
-
* JSON-RPC error responses.
|
|
121
|
-
*/
|
|
122
|
-
let SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) {
|
|
123
|
-
/** Transport is not connected */
|
|
124
|
-
SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED";
|
|
125
|
-
/** Transport is already connected */
|
|
126
|
-
SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED";
|
|
127
|
-
/** Protocol is not initialized */
|
|
128
|
-
SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED";
|
|
129
|
-
/** Required capability is not supported by the remote side */
|
|
130
|
-
SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED";
|
|
131
|
-
/** Request timed out waiting for response */
|
|
132
|
-
SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT";
|
|
133
|
-
/** Connection was closed */
|
|
134
|
-
SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED";
|
|
135
|
-
/** Failed to send message */
|
|
136
|
-
SdkErrorCode$1["SendFailed"] = "SEND_FAILED";
|
|
137
|
-
/** Response result failed local schema validation */
|
|
138
|
-
SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT";
|
|
139
|
-
SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED";
|
|
140
|
-
SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION";
|
|
141
|
-
SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN";
|
|
142
|
-
SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT";
|
|
143
|
-
SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM";
|
|
144
|
-
SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION";
|
|
145
|
-
return SdkErrorCode$1;
|
|
146
|
-
}({});
|
|
147
|
-
/**
|
|
148
|
-
* SDK errors are local errors that never cross the wire.
|
|
149
|
-
* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors
|
|
150
|
-
* that are serialized and sent as error responses.
|
|
151
|
-
*
|
|
152
|
-
* @example
|
|
153
|
-
* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage"
|
|
154
|
-
* try {
|
|
155
|
-
* // Throwing an SDK error
|
|
156
|
-
* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected');
|
|
157
|
-
* } catch (error) {
|
|
158
|
-
* // Checking error type by code
|
|
159
|
-
* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
|
|
160
|
-
* // Handle timeout
|
|
161
|
-
* }
|
|
162
|
-
* }
|
|
163
|
-
* ```
|
|
164
|
-
*/
|
|
165
|
-
var SdkError = class extends Error {
|
|
166
|
-
constructor(code, message, data) {
|
|
167
|
-
super(message);
|
|
168
|
-
this.code = code;
|
|
169
|
-
this.data = data;
|
|
170
|
-
this.name = "SdkError";
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
/**
|
|
174
|
-
* An {@linkcode SdkError} subclass for HTTP transport failures.
|
|
175
|
-
*
|
|
176
|
-
* Thrown by the streamable HTTP transport when the server responds with a
|
|
177
|
-
* non-OK status code. Narrows {@linkcode SdkError.data | data} to
|
|
178
|
-
* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status
|
|
179
|
-
* without unsafe casting.
|
|
180
|
-
*
|
|
181
|
-
* @example
|
|
182
|
-
* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage"
|
|
183
|
-
* if (error instanceof SdkHttpError) {
|
|
184
|
-
* console.log(error.status); // number
|
|
185
|
-
* console.log(error.statusText); // string | undefined
|
|
186
|
-
* }
|
|
187
|
-
* ```
|
|
188
|
-
*/
|
|
189
|
-
var SdkHttpError = class extends SdkError {
|
|
190
|
-
constructor(code, message, data) {
|
|
191
|
-
super(code, message, data);
|
|
192
|
-
this.name = "SdkHttpError";
|
|
193
|
-
}
|
|
194
|
-
get status() {
|
|
195
|
-
return this.data.status;
|
|
196
|
-
}
|
|
197
|
-
get statusText() {
|
|
198
|
-
return this.data.statusText;
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
|
|
202
|
-
//#endregion
|
|
203
|
-
//#region ../core-internal/src/shared/auth.ts
|
|
204
|
-
/**
|
|
205
|
-
* Reusable URL validation that disallows `javascript:` scheme
|
|
206
|
-
*/
|
|
207
|
-
const SafeUrlSchema = z.url().superRefine((val, ctx) => {
|
|
208
|
-
if (!URL.canParse(val)) {
|
|
209
|
-
ctx.addIssue({
|
|
210
|
-
code: z.ZodIssueCode.custom,
|
|
211
|
-
message: "URL must be parseable",
|
|
212
|
-
fatal: true
|
|
213
|
-
});
|
|
214
|
-
return z.NEVER;
|
|
215
|
-
}
|
|
216
|
-
}).refine((url) => {
|
|
217
|
-
const u = new URL(url);
|
|
218
|
-
return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
|
|
219
|
-
}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
|
|
220
|
-
/**
|
|
221
|
-
* RFC 9728 OAuth Protected Resource Metadata
|
|
222
|
-
*/
|
|
223
|
-
const OAuthProtectedResourceMetadataSchema = z.looseObject({
|
|
224
|
-
resource: z.string().url(),
|
|
225
|
-
authorization_servers: z.array(SafeUrlSchema).optional(),
|
|
226
|
-
jwks_uri: z.string().url().optional(),
|
|
227
|
-
scopes_supported: z.array(z.string()).optional(),
|
|
228
|
-
bearer_methods_supported: z.array(z.string()).optional(),
|
|
229
|
-
resource_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
230
|
-
resource_name: z.string().optional(),
|
|
231
|
-
resource_documentation: z.string().optional(),
|
|
232
|
-
resource_policy_uri: z.string().url().optional(),
|
|
233
|
-
resource_tos_uri: z.string().url().optional(),
|
|
234
|
-
tls_client_certificate_bound_access_tokens: z.boolean().optional(),
|
|
235
|
-
authorization_details_types_supported: z.array(z.string()).optional(),
|
|
236
|
-
dpop_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
237
|
-
dpop_bound_access_tokens_required: z.boolean().optional()
|
|
238
|
-
});
|
|
239
|
-
/**
|
|
240
|
-
* RFC 8414 OAuth 2.0 Authorization Server Metadata
|
|
241
|
-
*/
|
|
242
|
-
const OAuthMetadataSchema = z.looseObject({
|
|
243
|
-
issuer: z.string(),
|
|
244
|
-
authorization_endpoint: SafeUrlSchema,
|
|
245
|
-
token_endpoint: SafeUrlSchema,
|
|
246
|
-
registration_endpoint: SafeUrlSchema.optional(),
|
|
247
|
-
scopes_supported: z.array(z.string()).optional(),
|
|
248
|
-
response_types_supported: z.array(z.string()),
|
|
249
|
-
response_modes_supported: z.array(z.string()).optional(),
|
|
250
|
-
grant_types_supported: z.array(z.string()).optional(),
|
|
251
|
-
token_endpoint_auth_methods_supported: z.array(z.string()).optional(),
|
|
252
|
-
token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
253
|
-
service_documentation: SafeUrlSchema.optional(),
|
|
254
|
-
revocation_endpoint: SafeUrlSchema.optional(),
|
|
255
|
-
revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),
|
|
256
|
-
revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
257
|
-
introspection_endpoint: z.string().optional(),
|
|
258
|
-
introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),
|
|
259
|
-
introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
260
|
-
code_challenge_methods_supported: z.array(z.string()).optional(),
|
|
261
|
-
client_id_metadata_document_supported: z.boolean().optional()
|
|
262
|
-
});
|
|
263
|
-
/**
|
|
264
|
-
* OpenID Connect Discovery 1.0 Provider Metadata
|
|
265
|
-
*
|
|
266
|
-
* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
|
|
267
|
-
*/
|
|
268
|
-
const OpenIdProviderMetadataSchema = z.looseObject({
|
|
269
|
-
issuer: z.string(),
|
|
270
|
-
authorization_endpoint: SafeUrlSchema,
|
|
271
|
-
token_endpoint: SafeUrlSchema,
|
|
272
|
-
userinfo_endpoint: SafeUrlSchema.optional(),
|
|
273
|
-
jwks_uri: SafeUrlSchema,
|
|
274
|
-
registration_endpoint: SafeUrlSchema.optional(),
|
|
275
|
-
scopes_supported: z.array(z.string()).optional(),
|
|
276
|
-
response_types_supported: z.array(z.string()),
|
|
277
|
-
response_modes_supported: z.array(z.string()).optional(),
|
|
278
|
-
grant_types_supported: z.array(z.string()).optional(),
|
|
279
|
-
acr_values_supported: z.array(z.string()).optional(),
|
|
280
|
-
subject_types_supported: z.array(z.string()),
|
|
281
|
-
id_token_signing_alg_values_supported: z.array(z.string()),
|
|
282
|
-
id_token_encryption_alg_values_supported: z.array(z.string()).optional(),
|
|
283
|
-
id_token_encryption_enc_values_supported: z.array(z.string()).optional(),
|
|
284
|
-
userinfo_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
285
|
-
userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),
|
|
286
|
-
userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),
|
|
287
|
-
request_object_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
288
|
-
request_object_encryption_alg_values_supported: z.array(z.string()).optional(),
|
|
289
|
-
request_object_encryption_enc_values_supported: z.array(z.string()).optional(),
|
|
290
|
-
token_endpoint_auth_methods_supported: z.array(z.string()).optional(),
|
|
291
|
-
token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),
|
|
292
|
-
display_values_supported: z.array(z.string()).optional(),
|
|
293
|
-
claim_types_supported: z.array(z.string()).optional(),
|
|
294
|
-
claims_supported: z.array(z.string()).optional(),
|
|
295
|
-
service_documentation: z.string().optional(),
|
|
296
|
-
claims_locales_supported: z.array(z.string()).optional(),
|
|
297
|
-
ui_locales_supported: z.array(z.string()).optional(),
|
|
298
|
-
claims_parameter_supported: z.boolean().optional(),
|
|
299
|
-
request_parameter_supported: z.boolean().optional(),
|
|
300
|
-
request_uri_parameter_supported: z.boolean().optional(),
|
|
301
|
-
require_request_uri_registration: z.boolean().optional(),
|
|
302
|
-
op_policy_uri: SafeUrlSchema.optional(),
|
|
303
|
-
op_tos_uri: SafeUrlSchema.optional(),
|
|
304
|
-
client_id_metadata_document_supported: z.boolean().optional()
|
|
305
|
-
});
|
|
306
|
-
/**
|
|
307
|
-
* OpenID Connect Discovery metadata that may include OAuth 2.0 fields
|
|
308
|
-
* This schema represents the real-world scenario where OIDC providers
|
|
309
|
-
* return a mix of OpenID Connect and OAuth 2.0 metadata fields
|
|
310
|
-
*/
|
|
311
|
-
const OpenIdProviderDiscoveryMetadataSchema = z.object({
|
|
312
|
-
...OpenIdProviderMetadataSchema.shape,
|
|
313
|
-
...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape
|
|
314
|
-
});
|
|
315
|
-
/**
|
|
316
|
-
* OAuth 2.1 token response
|
|
317
|
-
*/
|
|
318
|
-
const OAuthTokensSchema = z.object({
|
|
319
|
-
access_token: z.string(),
|
|
320
|
-
id_token: z.string().optional(),
|
|
321
|
-
token_type: z.string(),
|
|
322
|
-
expires_in: z.coerce.number().optional(),
|
|
323
|
-
scope: z.string().optional(),
|
|
324
|
-
refresh_token: z.string().optional()
|
|
325
|
-
}).strip();
|
|
326
|
-
/**
|
|
327
|
-
* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens.
|
|
328
|
-
*
|
|
329
|
-
* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when
|
|
330
|
-
* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive,
|
|
331
|
-
* so strict checking rejects conformant IdPs.
|
|
332
|
-
*/
|
|
333
|
-
const IdJagTokenExchangeResponseSchema = z.object({
|
|
334
|
-
issued_token_type: z.literal("urn:ietf:params:oauth:token-type:id-jag"),
|
|
335
|
-
access_token: z.string(),
|
|
336
|
-
token_type: z.string().optional(),
|
|
337
|
-
expires_in: z.number().optional(),
|
|
338
|
-
scope: z.string().optional()
|
|
339
|
-
}).strip();
|
|
340
|
-
/**
|
|
341
|
-
* OAuth 2.1 error response
|
|
342
|
-
*/
|
|
343
|
-
const OAuthErrorResponseSchema = z.object({
|
|
344
|
-
error: z.string(),
|
|
345
|
-
error_description: z.string().optional(),
|
|
346
|
-
error_uri: z.string().optional()
|
|
347
|
-
});
|
|
348
|
-
/**
|
|
349
|
-
* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri`
|
|
350
|
-
*/
|
|
351
|
-
const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal("").transform(() => void 0));
|
|
352
|
-
/**
|
|
353
|
-
* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata
|
|
354
|
-
*/
|
|
355
|
-
const OAuthClientMetadataSchema = z.object({
|
|
356
|
-
redirect_uris: z.array(SafeUrlSchema),
|
|
357
|
-
token_endpoint_auth_method: z.string().optional(),
|
|
358
|
-
grant_types: z.array(z.string()).optional(),
|
|
359
|
-
response_types: z.array(z.string()).optional(),
|
|
360
|
-
client_name: z.string().optional(),
|
|
361
|
-
client_uri: SafeUrlSchema.optional(),
|
|
362
|
-
logo_uri: OptionalSafeUrlSchema,
|
|
363
|
-
scope: z.string().optional(),
|
|
364
|
-
contacts: z.array(z.string()).optional(),
|
|
365
|
-
tos_uri: OptionalSafeUrlSchema,
|
|
366
|
-
policy_uri: z.string().optional(),
|
|
367
|
-
jwks_uri: SafeUrlSchema.optional(),
|
|
368
|
-
jwks: z.any().optional(),
|
|
369
|
-
software_id: z.string().optional(),
|
|
370
|
-
software_version: z.string().optional(),
|
|
371
|
-
software_statement: z.string().optional()
|
|
372
|
-
}).strip();
|
|
373
|
-
/**
|
|
374
|
-
* RFC 7591 OAuth 2.0 Dynamic Client Registration client information
|
|
375
|
-
*/
|
|
376
|
-
const OAuthClientInformationSchema = z.object({
|
|
377
|
-
client_id: z.string(),
|
|
378
|
-
client_secret: z.string().optional(),
|
|
379
|
-
client_id_issued_at: z.number().optional(),
|
|
380
|
-
client_secret_expires_at: z.number().optional()
|
|
381
|
-
}).strip();
|
|
382
|
-
/**
|
|
383
|
-
* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)
|
|
384
|
-
*/
|
|
385
|
-
const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
|
|
386
|
-
/**
|
|
387
|
-
* RFC 7591 OAuth 2.0 Dynamic Client Registration error response
|
|
388
|
-
*/
|
|
389
|
-
const OAuthClientRegistrationErrorSchema = z.object({
|
|
390
|
-
error: z.string(),
|
|
391
|
-
error_description: z.string().optional()
|
|
392
|
-
}).strip();
|
|
393
|
-
/**
|
|
394
|
-
* RFC 7009 OAuth 2.0 Token Revocation request
|
|
395
|
-
*/
|
|
396
|
-
const OAuthTokenRevocationRequestSchema = z.object({
|
|
397
|
-
token: z.string(),
|
|
398
|
-
token_type_hint: z.string().optional()
|
|
399
|
-
}).strip();
|
|
400
|
-
|
|
401
|
-
//#endregion
|
|
402
|
-
//#region ../core-internal/src/shared/authUtils.ts
|
|
403
|
-
/**
|
|
404
|
-
* Utilities for handling OAuth resource URIs.
|
|
405
|
-
*/
|
|
406
|
-
/**
|
|
407
|
-
* Converts a server URL to a resource URL by removing the fragment.
|
|
408
|
-
* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2}
|
|
409
|
-
* states that resource URIs "MUST NOT include a fragment component".
|
|
410
|
-
* Keeps everything else unchanged (scheme, domain, port, path, query).
|
|
411
|
-
*/
|
|
412
|
-
function resourceUrlFromServerUrl(url) {
|
|
413
|
-
const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
|
|
414
|
-
resourceURL.hash = "";
|
|
415
|
-
return resourceURL;
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* Checks if a requested resource URL matches a configured resource URL.
|
|
419
|
-
* A requested resource matches if it has the same scheme, domain, port,
|
|
420
|
-
* and its path starts with the configured resource's path.
|
|
421
|
-
*
|
|
422
|
-
* @param options - The options object
|
|
423
|
-
* @param options.requestedResource - The resource URL being requested
|
|
424
|
-
* @param options.configuredResource - The resource URL that has been configured
|
|
425
|
-
* @returns true if the requested resource matches the configured resource, false otherwise
|
|
426
|
-
*/
|
|
427
|
-
function checkResourceAllowed({ requestedResource, configuredResource }) {
|
|
428
|
-
const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
|
|
429
|
-
const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
|
|
430
|
-
if (requested.origin !== configured.origin) return false;
|
|
431
|
-
if (requested.pathname.length < configured.pathname.length) return false;
|
|
432
|
-
const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
|
|
433
|
-
const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
|
|
434
|
-
return requestedPath.startsWith(configuredPath);
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
//#endregion
|
|
438
|
-
//#region ../core-internal/src/shared/metadataUtils.ts
|
|
439
|
-
/**
|
|
440
|
-
* Utilities for working with {@linkcode BaseMetadata} objects.
|
|
441
|
-
*/
|
|
442
|
-
/**
|
|
443
|
-
* Gets the display name for an object with {@linkcode BaseMetadata}.
|
|
444
|
-
* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name`
|
|
445
|
-
* For other objects: `title` → `name`
|
|
446
|
-
* This implements the spec requirement: "if no title is provided, name should be used for display purposes"
|
|
447
|
-
*/
|
|
448
|
-
function getDisplayName(metadata) {
|
|
449
|
-
if (metadata.title !== void 0 && metadata.title !== "") return metadata.title;
|
|
450
|
-
if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title;
|
|
451
|
-
return metadata.name;
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
//#endregion
|
|
455
|
-
//#region ../core-internal/src/types/constants.ts
|
|
456
|
-
const LATEST_PROTOCOL_VERSION = "2025-11-25";
|
|
457
|
-
const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26";
|
|
458
|
-
const SUPPORTED_PROTOCOL_VERSIONS = [
|
|
459
|
-
LATEST_PROTOCOL_VERSION,
|
|
460
|
-
"2025-06-18",
|
|
461
|
-
"2025-03-26",
|
|
462
|
-
"2024-11-05",
|
|
463
|
-
"2024-10-07"
|
|
464
|
-
];
|
|
465
|
-
const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
|
|
466
|
-
/**
|
|
467
|
-
* `_meta` key carrying the MCP protocol version governing a request.
|
|
468
|
-
*
|
|
469
|
-
* For the HTTP transport, the value must match the `MCP-Protocol-Version` header.
|
|
470
|
-
*/
|
|
471
|
-
const PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion";
|
|
472
|
-
/**
|
|
473
|
-
* `_meta` key identifying the client software making a request.
|
|
474
|
-
*/
|
|
475
|
-
const CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
476
|
-
/**
|
|
477
|
-
* `_meta` key carrying the client's capabilities for a request.
|
|
478
|
-
*
|
|
479
|
-
* Capabilities are declared per request rather than once at initialization;
|
|
480
|
-
* servers must not infer capabilities from prior requests.
|
|
481
|
-
*/
|
|
482
|
-
const CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities";
|
|
483
|
-
/**
|
|
484
|
-
* `_meta` key carrying the desired log level for a request.
|
|
485
|
-
*
|
|
486
|
-
* When absent, the server must not send `notifications/message` notifications
|
|
487
|
-
* for the request.
|
|
488
|
-
*
|
|
489
|
-
* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains
|
|
490
|
-
* in the specification for at least twelve months.
|
|
491
|
-
*/
|
|
492
|
-
const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel";
|
|
493
|
-
/**
|
|
494
|
-
* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414).
|
|
495
|
-
*
|
|
496
|
-
* When present, the value MUST follow the W3C `traceparent` header format,
|
|
497
|
-
* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`.
|
|
498
|
-
*
|
|
499
|
-
* @see https://www.w3.org/TR/trace-context/#traceparent-header
|
|
500
|
-
*/
|
|
501
|
-
const TRACEPARENT_META_KEY = "traceparent";
|
|
502
|
-
/**
|
|
503
|
-
* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414).
|
|
504
|
-
*
|
|
505
|
-
* When present, the value MUST follow the W3C `tracestate` header format,
|
|
506
|
-
* e.g. `vendor1=value1,vendor2=value2`.
|
|
507
|
-
*
|
|
508
|
-
* @see https://www.w3.org/TR/trace-context/#tracestate-header
|
|
509
|
-
*/
|
|
510
|
-
const TRACESTATE_META_KEY = "tracestate";
|
|
511
|
-
/**
|
|
512
|
-
* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414).
|
|
513
|
-
*
|
|
514
|
-
* When present, the value MUST follow the W3C Baggage header format,
|
|
515
|
-
* e.g. `userId=alice,serverRegion=us-east-1`.
|
|
516
|
-
*
|
|
517
|
-
* @see https://www.w3.org/TR/baggage/
|
|
518
|
-
*/
|
|
519
|
-
const BAGGAGE_META_KEY = "baggage";
|
|
520
|
-
const JSONRPC_VERSION = "2.0";
|
|
521
|
-
const PARSE_ERROR = -32700;
|
|
522
|
-
const INVALID_REQUEST = -32600;
|
|
523
|
-
const METHOD_NOT_FOUND = -32601;
|
|
524
|
-
const INVALID_PARAMS = -32602;
|
|
525
|
-
const INTERNAL_ERROR = -32603;
|
|
526
|
-
|
|
527
|
-
//#endregion
|
|
528
|
-
//#region ../core-internal/src/types/enums.ts
|
|
529
|
-
/**
|
|
530
|
-
* Error codes for protocol errors that cross the wire as JSON-RPC error responses.
|
|
531
|
-
* These follow the JSON-RPC specification and MCP-specific extensions.
|
|
532
|
-
*/
|
|
533
|
-
let ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) {
|
|
534
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError";
|
|
535
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest";
|
|
536
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound";
|
|
537
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams";
|
|
538
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError";
|
|
539
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound";
|
|
540
|
-
/**
|
|
541
|
-
* Processing the request requires a capability the client did not declare
|
|
542
|
-
* in the request's `clientCapabilities` (protocol revision 2026-07-28).
|
|
543
|
-
*/
|
|
544
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32003] = "MissingRequiredClientCapability";
|
|
545
|
-
/**
|
|
546
|
-
* The request's protocol version is unknown to the server or unsupported
|
|
547
|
-
* by it (protocol revision 2026-07-28).
|
|
548
|
-
*/
|
|
549
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32004] = "UnsupportedProtocolVersion";
|
|
550
|
-
ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
|
|
551
|
-
return ProtocolErrorCode$1;
|
|
552
|
-
}({});
|
|
553
|
-
|
|
554
|
-
//#endregion
|
|
555
|
-
//#region ../core-internal/src/types/errors.ts
|
|
556
|
-
/**
|
|
557
|
-
* Protocol errors are JSON-RPC errors that cross the wire as error responses.
|
|
558
|
-
* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum.
|
|
559
|
-
*/
|
|
560
|
-
var ProtocolError = class ProtocolError extends Error {
|
|
561
|
-
constructor(code, message, data) {
|
|
562
|
-
super(message);
|
|
563
|
-
this.code = code;
|
|
564
|
-
this.data = data;
|
|
565
|
-
this.name = "ProtocolError";
|
|
566
|
-
}
|
|
567
|
-
/**
|
|
568
|
-
* Factory method to create the appropriate error type based on the error code and data
|
|
569
|
-
*/
|
|
570
|
-
static fromError(code, message, data) {
|
|
571
|
-
if (code === ProtocolErrorCode.UrlElicitationRequired && data) {
|
|
572
|
-
const errorData = data;
|
|
573
|
-
if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message);
|
|
574
|
-
}
|
|
575
|
-
if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) {
|
|
576
|
-
const errorData = data;
|
|
577
|
-
if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new UnsupportedProtocolVersionError({
|
|
578
|
-
supported: errorData.supported,
|
|
579
|
-
requested: errorData.requested
|
|
580
|
-
}, message);
|
|
581
|
-
}
|
|
582
|
-
return new ProtocolError(code, message, data);
|
|
583
|
-
}
|
|
584
|
-
};
|
|
585
|
-
/**
|
|
586
|
-
* Specialized error type when a tool requires a URL mode elicitation.
|
|
587
|
-
* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.
|
|
588
|
-
*/
|
|
589
|
-
var UrlElicitationRequiredError = class extends ProtocolError {
|
|
590
|
-
constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
|
|
591
|
-
super(ProtocolErrorCode.UrlElicitationRequired, message, { elicitations });
|
|
592
|
-
}
|
|
593
|
-
get elicitations() {
|
|
594
|
-
return this.data?.elicitations ?? [];
|
|
595
|
-
}
|
|
596
|
-
};
|
|
597
|
-
/**
|
|
598
|
-
* Error type for the `-32004` UnsupportedProtocolVersion protocol error (protocol
|
|
599
|
-
* revision 2026-07-28): the request's protocol version is unknown to the server or
|
|
600
|
-
* unsupported by it.
|
|
601
|
-
*
|
|
602
|
-
* The error data lists the protocol versions the receiver supports (`supported`),
|
|
603
|
-
* so the sender can choose a mutually supported version and retry, and echoes the
|
|
604
|
-
* version that was requested (`requested`).
|
|
605
|
-
*/
|
|
606
|
-
var UnsupportedProtocolVersionError = class extends ProtocolError {
|
|
607
|
-
constructor(data, message = `Unsupported protocol version: ${data.requested}`) {
|
|
608
|
-
super(ProtocolErrorCode.UnsupportedProtocolVersion, message, data);
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Protocol versions the receiver supports.
|
|
612
|
-
*/
|
|
613
|
-
get supported() {
|
|
614
|
-
return this.data.supported;
|
|
615
|
-
}
|
|
616
|
-
/**
|
|
617
|
-
* The protocol version that was requested.
|
|
618
|
-
*/
|
|
619
|
-
get requested() {
|
|
620
|
-
return this.data.requested;
|
|
621
|
-
}
|
|
622
|
-
};
|
|
623
|
-
|
|
624
|
-
//#endregion
|
|
625
|
-
//#region ../core-internal/src/types/schemas.ts
|
|
626
|
-
var schemas_exports = /* @__PURE__ */ __exportAll({
|
|
627
|
-
AnnotationsSchema: () => AnnotationsSchema,
|
|
628
|
-
AudioContentSchema: () => AudioContentSchema,
|
|
629
|
-
BaseMetadataSchema: () => BaseMetadataSchema,
|
|
630
|
-
BaseRequestParamsSchema: () => BaseRequestParamsSchema,
|
|
631
|
-
BlobResourceContentsSchema: () => BlobResourceContentsSchema,
|
|
632
|
-
BooleanSchemaSchema: () => BooleanSchemaSchema,
|
|
633
|
-
CallToolRequestParamsSchema: () => CallToolRequestParamsSchema,
|
|
634
|
-
CallToolRequestSchema: () => CallToolRequestSchema,
|
|
635
|
-
CallToolResultSchema: () => CallToolResultSchema,
|
|
636
|
-
CancelTaskRequestSchema: () => CancelTaskRequestSchema,
|
|
637
|
-
CancelTaskResultSchema: () => CancelTaskResultSchema,
|
|
638
|
-
CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema,
|
|
639
|
-
CancelledNotificationSchema: () => CancelledNotificationSchema,
|
|
640
|
-
ClientCapabilitiesSchema: () => ClientCapabilitiesSchema,
|
|
641
|
-
ClientNotificationSchema: () => ClientNotificationSchema,
|
|
642
|
-
ClientRequestSchema: () => ClientRequestSchema,
|
|
643
|
-
ClientResultSchema: () => ClientResultSchema,
|
|
644
|
-
ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema,
|
|
645
|
-
CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema,
|
|
646
|
-
CompleteRequestParamsSchema: () => CompleteRequestParamsSchema,
|
|
647
|
-
CompleteRequestSchema: () => CompleteRequestSchema,
|
|
648
|
-
CompleteResultSchema: () => CompleteResultSchema,
|
|
649
|
-
ContentBlockSchema: () => ContentBlockSchema,
|
|
650
|
-
CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema,
|
|
651
|
-
CreateMessageRequestSchema: () => CreateMessageRequestSchema,
|
|
652
|
-
CreateMessageResultSchema: () => CreateMessageResultSchema,
|
|
653
|
-
CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema,
|
|
654
|
-
CreateTaskResultSchema: () => CreateTaskResultSchema,
|
|
655
|
-
CursorSchema: () => CursorSchema,
|
|
656
|
-
DiscoverRequestSchema: () => DiscoverRequestSchema,
|
|
657
|
-
DiscoverResultSchema: () => DiscoverResultSchema,
|
|
658
|
-
ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema,
|
|
659
|
-
ElicitRequestParamsSchema: () => ElicitRequestParamsSchema,
|
|
660
|
-
ElicitRequestSchema: () => ElicitRequestSchema,
|
|
661
|
-
ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema,
|
|
662
|
-
ElicitResultSchema: () => ElicitResultSchema,
|
|
663
|
-
ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema,
|
|
664
|
-
ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema,
|
|
665
|
-
EmbeddedResourceSchema: () => EmbeddedResourceSchema,
|
|
666
|
-
EmptyResultSchema: () => EmptyResultSchema,
|
|
667
|
-
EnumSchemaSchema: () => EnumSchemaSchema,
|
|
668
|
-
GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema,
|
|
669
|
-
GetPromptRequestSchema: () => GetPromptRequestSchema,
|
|
670
|
-
GetPromptResultSchema: () => GetPromptResultSchema,
|
|
671
|
-
GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema,
|
|
672
|
-
GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema,
|
|
673
|
-
GetTaskRequestSchema: () => GetTaskRequestSchema,
|
|
674
|
-
GetTaskResultSchema: () => GetTaskResultSchema,
|
|
675
|
-
IconSchema: () => IconSchema,
|
|
676
|
-
IconsSchema: () => IconsSchema,
|
|
677
|
-
ImageContentSchema: () => ImageContentSchema,
|
|
678
|
-
ImplementationSchema: () => ImplementationSchema,
|
|
679
|
-
InitializeRequestParamsSchema: () => InitializeRequestParamsSchema,
|
|
680
|
-
InitializeRequestSchema: () => InitializeRequestSchema,
|
|
681
|
-
InitializeResultSchema: () => InitializeResultSchema,
|
|
682
|
-
InitializedNotificationSchema: () => InitializedNotificationSchema,
|
|
683
|
-
JSONArraySchema: () => JSONArraySchema,
|
|
684
|
-
JSONObjectSchema: () => JSONObjectSchema,
|
|
685
|
-
JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema,
|
|
686
|
-
JSONRPCMessageSchema: () => JSONRPCMessageSchema,
|
|
687
|
-
JSONRPCNotificationSchema: () => JSONRPCNotificationSchema,
|
|
688
|
-
JSONRPCRequestSchema: () => JSONRPCRequestSchema,
|
|
689
|
-
JSONRPCResponseSchema: () => JSONRPCResponseSchema,
|
|
690
|
-
JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema,
|
|
691
|
-
JSONValueSchema: () => JSONValueSchema,
|
|
692
|
-
LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema,
|
|
693
|
-
ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema,
|
|
694
|
-
ListPromptsRequestSchema: () => ListPromptsRequestSchema,
|
|
695
|
-
ListPromptsResultSchema: () => ListPromptsResultSchema,
|
|
696
|
-
ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema,
|
|
697
|
-
ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema,
|
|
698
|
-
ListResourcesRequestSchema: () => ListResourcesRequestSchema,
|
|
699
|
-
ListResourcesResultSchema: () => ListResourcesResultSchema,
|
|
700
|
-
ListRootsRequestSchema: () => ListRootsRequestSchema,
|
|
701
|
-
ListRootsResultSchema: () => ListRootsResultSchema,
|
|
702
|
-
ListTasksRequestSchema: () => ListTasksRequestSchema,
|
|
703
|
-
ListTasksResultSchema: () => ListTasksResultSchema,
|
|
704
|
-
ListToolsRequestSchema: () => ListToolsRequestSchema,
|
|
705
|
-
ListToolsResultSchema: () => ListToolsResultSchema,
|
|
706
|
-
LoggingLevelSchema: () => LoggingLevelSchema,
|
|
707
|
-
LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema,
|
|
708
|
-
LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema,
|
|
709
|
-
ModelHintSchema: () => ModelHintSchema,
|
|
710
|
-
ModelPreferencesSchema: () => ModelPreferencesSchema,
|
|
711
|
-
MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema,
|
|
712
|
-
NotificationSchema: () => NotificationSchema,
|
|
713
|
-
NotificationsParamsSchema: () => NotificationsParamsSchema,
|
|
714
|
-
NumberSchemaSchema: () => NumberSchemaSchema,
|
|
715
|
-
PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema,
|
|
716
|
-
PaginatedRequestSchema: () => PaginatedRequestSchema,
|
|
717
|
-
PaginatedResultSchema: () => PaginatedResultSchema,
|
|
718
|
-
PingRequestSchema: () => PingRequestSchema,
|
|
719
|
-
PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema,
|
|
720
|
-
ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema,
|
|
721
|
-
ProgressNotificationSchema: () => ProgressNotificationSchema,
|
|
722
|
-
ProgressSchema: () => ProgressSchema,
|
|
723
|
-
ProgressTokenSchema: () => ProgressTokenSchema,
|
|
724
|
-
PromptArgumentSchema: () => PromptArgumentSchema,
|
|
725
|
-
PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema,
|
|
726
|
-
PromptMessageSchema: () => PromptMessageSchema,
|
|
727
|
-
PromptReferenceSchema: () => PromptReferenceSchema,
|
|
728
|
-
PromptSchema: () => PromptSchema,
|
|
729
|
-
ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema,
|
|
730
|
-
ReadResourceRequestSchema: () => ReadResourceRequestSchema,
|
|
731
|
-
ReadResourceResultSchema: () => ReadResourceResultSchema,
|
|
732
|
-
RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema,
|
|
733
|
-
RequestIdSchema: () => RequestIdSchema,
|
|
734
|
-
RequestMetaEnvelopeSchema: () => RequestMetaEnvelopeSchema,
|
|
735
|
-
RequestMetaSchema: () => RequestMetaSchema,
|
|
736
|
-
RequestSchema: () => RequestSchema,
|
|
737
|
-
ResourceContentsSchema: () => ResourceContentsSchema,
|
|
738
|
-
ResourceLinkSchema: () => ResourceLinkSchema,
|
|
739
|
-
ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema,
|
|
740
|
-
ResourceRequestParamsSchema: () => ResourceRequestParamsSchema,
|
|
741
|
-
ResourceSchema: () => ResourceSchema,
|
|
742
|
-
ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema,
|
|
743
|
-
ResourceTemplateSchema: () => ResourceTemplateSchema,
|
|
744
|
-
ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema,
|
|
745
|
-
ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema,
|
|
746
|
-
ResultSchema: () => ResultSchema,
|
|
747
|
-
RoleSchema: () => RoleSchema,
|
|
748
|
-
RootSchema: () => RootSchema,
|
|
749
|
-
RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema,
|
|
750
|
-
SamplingContentSchema: () => SamplingContentSchema,
|
|
751
|
-
SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema,
|
|
752
|
-
SamplingMessageSchema: () => SamplingMessageSchema,
|
|
753
|
-
ServerCapabilitiesSchema: () => ServerCapabilitiesSchema,
|
|
754
|
-
ServerNotificationSchema: () => ServerNotificationSchema,
|
|
755
|
-
ServerRequestSchema: () => ServerRequestSchema,
|
|
756
|
-
ServerResultSchema: () => ServerResultSchema,
|
|
757
|
-
ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema,
|
|
758
|
-
SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema,
|
|
759
|
-
SetLevelRequestSchema: () => SetLevelRequestSchema,
|
|
760
|
-
SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema,
|
|
761
|
-
StringSchemaSchema: () => StringSchemaSchema,
|
|
762
|
-
SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema,
|
|
763
|
-
SubscribeRequestSchema: () => SubscribeRequestSchema,
|
|
764
|
-
TaskAugmentedRequestParamsSchema: () => TaskAugmentedRequestParamsSchema,
|
|
765
|
-
TaskCreationParamsSchema: () => TaskCreationParamsSchema,
|
|
766
|
-
TaskMetadataSchema: () => TaskMetadataSchema,
|
|
767
|
-
TaskSchema: () => TaskSchema,
|
|
768
|
-
TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema,
|
|
769
|
-
TaskStatusNotificationSchema: () => TaskStatusNotificationSchema,
|
|
770
|
-
TaskStatusSchema: () => TaskStatusSchema,
|
|
771
|
-
TextContentSchema: () => TextContentSchema,
|
|
772
|
-
TextResourceContentsSchema: () => TextResourceContentsSchema,
|
|
773
|
-
TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema,
|
|
774
|
-
TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema,
|
|
775
|
-
ToolAnnotationsSchema: () => ToolAnnotationsSchema,
|
|
776
|
-
ToolChoiceSchema: () => ToolChoiceSchema,
|
|
777
|
-
ToolExecutionSchema: () => ToolExecutionSchema,
|
|
778
|
-
ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema,
|
|
779
|
-
ToolResultContentSchema: () => ToolResultContentSchema,
|
|
780
|
-
ToolSchema: () => ToolSchema,
|
|
781
|
-
ToolUseContentSchema: () => ToolUseContentSchema,
|
|
782
|
-
UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema,
|
|
783
|
-
UnsubscribeRequestSchema: () => UnsubscribeRequestSchema,
|
|
784
|
-
UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema,
|
|
785
|
-
UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema,
|
|
786
|
-
getNotificationSchema: () => getNotificationSchema,
|
|
787
|
-
getRequestSchema: () => getRequestSchema,
|
|
788
|
-
getResultSchema: () => getResultSchema
|
|
789
|
-
});
|
|
790
|
-
const JSONValueSchema = z.lazy(() => z.union([
|
|
791
|
-
z.string(),
|
|
792
|
-
z.number(),
|
|
793
|
-
z.boolean(),
|
|
794
|
-
z.null(),
|
|
795
|
-
z.record(z.string(), JSONValueSchema),
|
|
796
|
-
z.array(JSONValueSchema)
|
|
797
|
-
]));
|
|
798
|
-
const JSONObjectSchema = z.record(z.string(), JSONValueSchema);
|
|
799
|
-
const JSONArraySchema = z.array(JSONValueSchema);
|
|
800
|
-
/**
|
|
801
|
-
* A progress token, used to associate progress notifications with the original request.
|
|
802
|
-
*/
|
|
803
|
-
const ProgressTokenSchema = z.union([z.string(), z.number().int()]);
|
|
804
|
-
/**
|
|
805
|
-
* An opaque token used to represent a cursor for pagination.
|
|
806
|
-
*/
|
|
807
|
-
const CursorSchema = z.string();
|
|
808
|
-
/**
|
|
809
|
-
* Task creation parameters, used to ask that the server create a task to represent a request.
|
|
810
|
-
*/
|
|
811
|
-
const TaskCreationParamsSchema = z.looseObject({
|
|
812
|
-
ttl: z.number().optional(),
|
|
813
|
-
pollInterval: z.number().optional()
|
|
814
|
-
});
|
|
815
|
-
const TaskMetadataSchema = z.object({ ttl: z.number().optional() });
|
|
816
|
-
/**
|
|
817
|
-
* Metadata for associating messages with a task.
|
|
818
|
-
* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.
|
|
819
|
-
*/
|
|
820
|
-
const RelatedTaskMetadataSchema = z.object({ taskId: z.string() });
|
|
821
|
-
const RequestMetaSchema = z.looseObject({
|
|
822
|
-
progressToken: ProgressTokenSchema.optional(),
|
|
823
|
-
[RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
|
|
824
|
-
});
|
|
825
|
-
/**
|
|
826
|
-
* Common params for any request.
|
|
827
|
-
*/
|
|
828
|
-
const BaseRequestParamsSchema = z.object({ _meta: RequestMetaSchema.optional() });
|
|
829
|
-
/**
|
|
830
|
-
* Common params for any task-augmented request.
|
|
831
|
-
*/
|
|
832
|
-
const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() });
|
|
833
|
-
const RequestSchema = z.object({
|
|
834
|
-
method: z.string(),
|
|
835
|
-
params: BaseRequestParamsSchema.loose().optional()
|
|
836
|
-
});
|
|
837
|
-
const NotificationsParamsSchema = z.object({ _meta: RequestMetaSchema.optional() });
|
|
838
|
-
const NotificationSchema = z.object({
|
|
839
|
-
method: z.string(),
|
|
840
|
-
params: NotificationsParamsSchema.loose().optional()
|
|
841
|
-
});
|
|
842
|
-
const ResultSchema = z.looseObject({
|
|
843
|
-
_meta: RequestMetaSchema.optional(),
|
|
844
|
-
resultType: z.string().optional()
|
|
845
|
-
});
|
|
846
|
-
/**
|
|
847
|
-
* A uniquely identifying ID for a request in JSON-RPC.
|
|
848
|
-
*/
|
|
849
|
-
const RequestIdSchema = z.union([z.string(), z.number().int()]);
|
|
850
|
-
/**
|
|
851
|
-
* A request that expects a response.
|
|
852
|
-
*/
|
|
853
|
-
const JSONRPCRequestSchema = z.object({
|
|
854
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
855
|
-
id: RequestIdSchema,
|
|
856
|
-
...RequestSchema.shape
|
|
857
|
-
}).strict();
|
|
858
|
-
/**
|
|
859
|
-
* A notification which does not expect a response.
|
|
860
|
-
*/
|
|
861
|
-
const JSONRPCNotificationSchema = z.object({
|
|
862
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
863
|
-
...NotificationSchema.shape
|
|
864
|
-
}).strict();
|
|
865
|
-
/**
|
|
866
|
-
* A successful (non-error) response to a request.
|
|
867
|
-
*/
|
|
868
|
-
const JSONRPCResultResponseSchema = z.object({
|
|
869
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
870
|
-
id: RequestIdSchema,
|
|
871
|
-
result: ResultSchema
|
|
872
|
-
}).strict();
|
|
873
|
-
/**
|
|
874
|
-
* A response to a request that indicates an error occurred.
|
|
875
|
-
*/
|
|
876
|
-
const JSONRPCErrorResponseSchema = z.object({
|
|
877
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
878
|
-
id: RequestIdSchema.optional(),
|
|
879
|
-
error: z.object({
|
|
880
|
-
code: z.number().int(),
|
|
881
|
-
message: z.string(),
|
|
882
|
-
data: z.unknown().optional()
|
|
883
|
-
})
|
|
884
|
-
}).strict();
|
|
885
|
-
const JSONRPCMessageSchema = z.union([
|
|
886
|
-
JSONRPCRequestSchema,
|
|
887
|
-
JSONRPCNotificationSchema,
|
|
888
|
-
JSONRPCResultResponseSchema,
|
|
889
|
-
JSONRPCErrorResponseSchema
|
|
890
|
-
]);
|
|
891
|
-
const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
|
|
892
|
-
/**
|
|
893
|
-
* A response that indicates success but carries no data.
|
|
894
|
-
*/
|
|
895
|
-
const EmptyResultSchema = ResultSchema.strict();
|
|
896
|
-
const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
897
|
-
requestId: RequestIdSchema.optional(),
|
|
898
|
-
reason: z.string().optional()
|
|
899
|
-
});
|
|
900
|
-
/**
|
|
901
|
-
* This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
|
|
902
|
-
*
|
|
903
|
-
* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
|
|
904
|
-
*
|
|
905
|
-
* This notification indicates that the result will be unused, so any associated processing SHOULD cease.
|
|
906
|
-
*
|
|
907
|
-
* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request.
|
|
908
|
-
*/
|
|
909
|
-
const CancelledNotificationSchema = NotificationSchema.extend({
|
|
910
|
-
method: z.literal("notifications/cancelled"),
|
|
911
|
-
params: CancelledNotificationParamsSchema
|
|
912
|
-
});
|
|
913
|
-
/**
|
|
914
|
-
* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}.
|
|
915
|
-
*/
|
|
916
|
-
const IconSchema = z.object({
|
|
917
|
-
src: z.string(),
|
|
918
|
-
mimeType: z.string().optional(),
|
|
919
|
-
sizes: z.array(z.string()).optional(),
|
|
920
|
-
theme: z.enum(["light", "dark"]).optional()
|
|
921
|
-
});
|
|
922
|
-
/**
|
|
923
|
-
* Base schema to add `icons` property.
|
|
924
|
-
*
|
|
925
|
-
*/
|
|
926
|
-
const IconsSchema = z.object({ icons: z.array(IconSchema).optional() });
|
|
927
|
-
/**
|
|
928
|
-
* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}.
|
|
929
|
-
*/
|
|
930
|
-
const BaseMetadataSchema = z.object({
|
|
931
|
-
name: z.string(),
|
|
932
|
-
title: z.string().optional()
|
|
933
|
-
});
|
|
934
|
-
/**
|
|
935
|
-
* Describes the name and version of an MCP implementation.
|
|
936
|
-
*/
|
|
937
|
-
const ImplementationSchema = BaseMetadataSchema.extend({
|
|
938
|
-
...BaseMetadataSchema.shape,
|
|
939
|
-
...IconsSchema.shape,
|
|
940
|
-
version: z.string(),
|
|
941
|
-
websiteUrl: z.string().optional(),
|
|
942
|
-
description: z.string().optional()
|
|
943
|
-
});
|
|
944
|
-
const FormElicitationCapabilitySchema = z.intersection(z.object({ applyDefaults: z.boolean().optional() }), JSONObjectSchema);
|
|
945
|
-
const ElicitationCapabilitySchema = z.preprocess((value) => {
|
|
946
|
-
if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} };
|
|
947
|
-
return value;
|
|
948
|
-
}, z.intersection(z.object({
|
|
949
|
-
form: FormElicitationCapabilitySchema.optional(),
|
|
950
|
-
url: JSONObjectSchema.optional()
|
|
951
|
-
}), JSONObjectSchema.optional()));
|
|
952
|
-
/**
|
|
953
|
-
* Task capabilities for clients, indicating which request types support task creation.
|
|
954
|
-
*/
|
|
955
|
-
const ClientTasksCapabilitySchema = z.looseObject({
|
|
956
|
-
list: JSONObjectSchema.optional(),
|
|
957
|
-
cancel: JSONObjectSchema.optional(),
|
|
958
|
-
requests: z.looseObject({
|
|
959
|
-
sampling: z.looseObject({ createMessage: JSONObjectSchema.optional() }).optional(),
|
|
960
|
-
elicitation: z.looseObject({ create: JSONObjectSchema.optional() }).optional()
|
|
961
|
-
}).optional()
|
|
962
|
-
});
|
|
963
|
-
/**
|
|
964
|
-
* Task capabilities for servers, indicating which request types support task creation.
|
|
965
|
-
*/
|
|
966
|
-
const ServerTasksCapabilitySchema = z.looseObject({
|
|
967
|
-
list: JSONObjectSchema.optional(),
|
|
968
|
-
cancel: JSONObjectSchema.optional(),
|
|
969
|
-
requests: z.looseObject({ tools: z.looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional()
|
|
970
|
-
});
|
|
971
|
-
/**
|
|
972
|
-
* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
|
|
973
|
-
*/
|
|
974
|
-
const ClientCapabilitiesSchema = z.object({
|
|
975
|
-
experimental: z.record(z.string(), JSONObjectSchema).optional(),
|
|
976
|
-
sampling: z.object({
|
|
977
|
-
context: JSONObjectSchema.optional(),
|
|
978
|
-
tools: JSONObjectSchema.optional()
|
|
979
|
-
}).optional(),
|
|
980
|
-
elicitation: ElicitationCapabilitySchema.optional(),
|
|
981
|
-
roots: z.object({ listChanged: z.boolean().optional() }).optional(),
|
|
982
|
-
tasks: ClientTasksCapabilitySchema.optional(),
|
|
983
|
-
extensions: z.record(z.string(), JSONObjectSchema).optional()
|
|
984
|
-
});
|
|
985
|
-
const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
986
|
-
protocolVersion: z.string(),
|
|
987
|
-
capabilities: ClientCapabilitiesSchema,
|
|
988
|
-
clientInfo: ImplementationSchema
|
|
989
|
-
});
|
|
990
|
-
/**
|
|
991
|
-
* This request is sent from the client to the server when it first connects, asking it to begin initialization.
|
|
992
|
-
*/
|
|
993
|
-
const InitializeRequestSchema = RequestSchema.extend({
|
|
994
|
-
method: z.literal("initialize"),
|
|
995
|
-
params: InitializeRequestParamsSchema
|
|
996
|
-
});
|
|
997
|
-
/**
|
|
998
|
-
* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
|
|
999
|
-
*/
|
|
1000
|
-
const ServerCapabilitiesSchema = z.object({
|
|
1001
|
-
experimental: z.record(z.string(), JSONObjectSchema).optional(),
|
|
1002
|
-
logging: JSONObjectSchema.optional(),
|
|
1003
|
-
completions: JSONObjectSchema.optional(),
|
|
1004
|
-
prompts: z.object({ listChanged: z.boolean().optional() }).optional(),
|
|
1005
|
-
resources: z.object({
|
|
1006
|
-
subscribe: z.boolean().optional(),
|
|
1007
|
-
listChanged: z.boolean().optional()
|
|
1008
|
-
}).optional(),
|
|
1009
|
-
tools: z.object({ listChanged: z.boolean().optional() }).optional(),
|
|
1010
|
-
tasks: ServerTasksCapabilitySchema.optional(),
|
|
1011
|
-
extensions: z.record(z.string(), JSONObjectSchema).optional()
|
|
1012
|
-
});
|
|
1013
|
-
/**
|
|
1014
|
-
* After receiving an initialize request from the client, the server sends this response.
|
|
1015
|
-
*/
|
|
1016
|
-
const InitializeResultSchema = ResultSchema.extend({
|
|
1017
|
-
protocolVersion: z.string(),
|
|
1018
|
-
capabilities: ServerCapabilitiesSchema,
|
|
1019
|
-
serverInfo: ImplementationSchema,
|
|
1020
|
-
instructions: z.string().optional()
|
|
1021
|
-
});
|
|
1022
|
-
/**
|
|
1023
|
-
* This notification is sent from the client to the server after initialization has finished.
|
|
1024
|
-
*/
|
|
1025
|
-
const InitializedNotificationSchema = NotificationSchema.extend({
|
|
1026
|
-
method: z.literal("notifications/initialized"),
|
|
1027
|
-
params: NotificationsParamsSchema.optional()
|
|
1028
|
-
});
|
|
1029
|
-
/**
|
|
1030
|
-
* A request from the client asking the server to advertise its supported protocol
|
|
1031
|
-
* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers
|
|
1032
|
-
* MUST implement `server/discover`. Clients MAY call it but are not required to —
|
|
1033
|
-
* version negotiation can also happen inline via the per-request `_meta` envelope.
|
|
1034
|
-
*/
|
|
1035
|
-
const DiscoverRequestSchema = RequestSchema.extend({
|
|
1036
|
-
method: z.literal("server/discover"),
|
|
1037
|
-
params: BaseRequestParamsSchema.optional()
|
|
1038
|
-
});
|
|
1039
|
-
/**
|
|
1040
|
-
* The result returned by the server for a `server/discover` request.
|
|
1041
|
-
*/
|
|
1042
|
-
const DiscoverResultSchema = ResultSchema.extend({
|
|
1043
|
-
supportedVersions: z.array(z.string()),
|
|
1044
|
-
capabilities: ServerCapabilitiesSchema,
|
|
1045
|
-
serverInfo: ImplementationSchema,
|
|
1046
|
-
instructions: z.string().optional()
|
|
1047
|
-
});
|
|
1048
|
-
/**
|
|
1049
|
-
* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
|
|
1050
|
-
*/
|
|
1051
|
-
const PingRequestSchema = RequestSchema.extend({
|
|
1052
|
-
method: z.literal("ping"),
|
|
1053
|
-
params: BaseRequestParamsSchema.optional()
|
|
1054
|
-
});
|
|
1055
|
-
const ProgressSchema = z.object({
|
|
1056
|
-
progress: z.number(),
|
|
1057
|
-
total: z.optional(z.number()),
|
|
1058
|
-
message: z.optional(z.string())
|
|
1059
|
-
});
|
|
1060
|
-
const ProgressNotificationParamsSchema = z.object({
|
|
1061
|
-
...NotificationsParamsSchema.shape,
|
|
1062
|
-
...ProgressSchema.shape,
|
|
1063
|
-
progressToken: ProgressTokenSchema
|
|
1064
|
-
});
|
|
1065
|
-
/**
|
|
1066
|
-
* An out-of-band notification used to inform the receiver of a progress update for a long-running request.
|
|
1067
|
-
*
|
|
1068
|
-
* @category notifications/progress
|
|
1069
|
-
*/
|
|
1070
|
-
const ProgressNotificationSchema = NotificationSchema.extend({
|
|
1071
|
-
method: z.literal("notifications/progress"),
|
|
1072
|
-
params: ProgressNotificationParamsSchema
|
|
1073
|
-
});
|
|
1074
|
-
const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() });
|
|
1075
|
-
const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() });
|
|
1076
|
-
const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() });
|
|
1077
|
-
/**
|
|
1078
|
-
* The status of a task.
|
|
1079
|
-
* */
|
|
1080
|
-
const TaskStatusSchema = z.enum([
|
|
1081
|
-
"working",
|
|
1082
|
-
"input_required",
|
|
1083
|
-
"completed",
|
|
1084
|
-
"failed",
|
|
1085
|
-
"cancelled"
|
|
1086
|
-
]);
|
|
1087
|
-
/**
|
|
1088
|
-
* A pollable state object associated with a request.
|
|
1089
|
-
*/
|
|
1090
|
-
const TaskSchema = z.object({
|
|
1091
|
-
taskId: z.string(),
|
|
1092
|
-
status: TaskStatusSchema,
|
|
1093
|
-
ttl: z.union([z.number(), z.null()]),
|
|
1094
|
-
createdAt: z.string(),
|
|
1095
|
-
lastUpdatedAt: z.string(),
|
|
1096
|
-
pollInterval: z.optional(z.number()),
|
|
1097
|
-
statusMessage: z.optional(z.string())
|
|
1098
|
-
});
|
|
1099
|
-
/**
|
|
1100
|
-
* Result returned when a task is created, containing the task data wrapped in a `task` field.
|
|
1101
|
-
*/
|
|
1102
|
-
const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema });
|
|
1103
|
-
/**
|
|
1104
|
-
* Parameters for task status notification.
|
|
1105
|
-
*/
|
|
1106
|
-
const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
|
|
1107
|
-
/**
|
|
1108
|
-
* A notification sent when a task's status changes.
|
|
1109
|
-
*/
|
|
1110
|
-
const TaskStatusNotificationSchema = NotificationSchema.extend({
|
|
1111
|
-
method: z.literal("notifications/tasks/status"),
|
|
1112
|
-
params: TaskStatusNotificationParamsSchema
|
|
1113
|
-
});
|
|
1114
|
-
/**
|
|
1115
|
-
* A request to get the state of a specific task.
|
|
1116
|
-
*/
|
|
1117
|
-
const GetTaskRequestSchema = RequestSchema.extend({
|
|
1118
|
-
method: z.literal("tasks/get"),
|
|
1119
|
-
params: BaseRequestParamsSchema.extend({ taskId: z.string() })
|
|
1120
|
-
});
|
|
1121
|
-
/**
|
|
1122
|
-
* The response to a {@linkcode GetTaskRequest | tasks/get} request.
|
|
1123
|
-
*/
|
|
1124
|
-
const GetTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
1125
|
-
/**
|
|
1126
|
-
* A request to get the result of a specific task.
|
|
1127
|
-
*/
|
|
1128
|
-
const GetTaskPayloadRequestSchema = RequestSchema.extend({
|
|
1129
|
-
method: z.literal("tasks/result"),
|
|
1130
|
-
params: BaseRequestParamsSchema.extend({ taskId: z.string() })
|
|
1131
|
-
});
|
|
1132
|
-
/**
|
|
1133
|
-
* The response to a `tasks/result` request.
|
|
1134
|
-
* The structure matches the result type of the original request.
|
|
1135
|
-
* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure.
|
|
1136
|
-
*
|
|
1137
|
-
*/
|
|
1138
|
-
const GetTaskPayloadResultSchema = ResultSchema.loose();
|
|
1139
|
-
/**
|
|
1140
|
-
* A request to list tasks.
|
|
1141
|
-
*/
|
|
1142
|
-
const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: z.literal("tasks/list") });
|
|
1143
|
-
/**
|
|
1144
|
-
* The response to a {@linkcode ListTasksRequest | tasks/list} request.
|
|
1145
|
-
*/
|
|
1146
|
-
const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: z.array(TaskSchema) });
|
|
1147
|
-
/**
|
|
1148
|
-
* A request to cancel a specific task.
|
|
1149
|
-
*/
|
|
1150
|
-
const CancelTaskRequestSchema = RequestSchema.extend({
|
|
1151
|
-
method: z.literal("tasks/cancel"),
|
|
1152
|
-
params: BaseRequestParamsSchema.extend({ taskId: z.string() })
|
|
1153
|
-
});
|
|
1154
|
-
/**
|
|
1155
|
-
* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request.
|
|
1156
|
-
*/
|
|
1157
|
-
const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
1158
|
-
/**
|
|
1159
|
-
* The contents of a specific resource or sub-resource.
|
|
1160
|
-
*/
|
|
1161
|
-
const ResourceContentsSchema = z.object({
|
|
1162
|
-
uri: z.string(),
|
|
1163
|
-
mimeType: z.optional(z.string()),
|
|
1164
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1165
|
-
});
|
|
1166
|
-
const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: z.string() });
|
|
1167
|
-
/**
|
|
1168
|
-
* A Zod schema for validating Base64 strings that is more performant and
|
|
1169
|
-
* robust for very large inputs than the default regex-based check. It avoids
|
|
1170
|
-
* stack overflows by using the native `atob` function for validation.
|
|
1171
|
-
*/
|
|
1172
|
-
const Base64Schema = z.string().refine((val) => {
|
|
1173
|
-
try {
|
|
1174
|
-
atob(val);
|
|
1175
|
-
return true;
|
|
1176
|
-
} catch {
|
|
1177
|
-
return false;
|
|
1178
|
-
}
|
|
1179
|
-
}, { message: "Invalid Base64 string" });
|
|
1180
|
-
const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: Base64Schema });
|
|
1181
|
-
/**
|
|
1182
|
-
* The sender or recipient of messages and data in a conversation.
|
|
1183
|
-
*/
|
|
1184
|
-
const RoleSchema = z.enum(["user", "assistant"]);
|
|
1185
|
-
/**
|
|
1186
|
-
* Optional annotations providing clients additional context about a resource.
|
|
1187
|
-
*/
|
|
1188
|
-
const AnnotationsSchema = z.object({
|
|
1189
|
-
audience: z.array(RoleSchema).optional(),
|
|
1190
|
-
priority: z.number().min(0).max(1).optional(),
|
|
1191
|
-
lastModified: z.iso.datetime({ offset: true }).optional()
|
|
1192
|
-
});
|
|
1193
|
-
/**
|
|
1194
|
-
* A known resource that the server is capable of reading.
|
|
1195
|
-
*/
|
|
1196
|
-
const ResourceSchema = z.object({
|
|
1197
|
-
...BaseMetadataSchema.shape,
|
|
1198
|
-
...IconsSchema.shape,
|
|
1199
|
-
uri: z.string(),
|
|
1200
|
-
description: z.optional(z.string()),
|
|
1201
|
-
mimeType: z.optional(z.string()),
|
|
1202
|
-
size: z.optional(z.number()),
|
|
1203
|
-
annotations: AnnotationsSchema.optional(),
|
|
1204
|
-
_meta: z.optional(z.looseObject({}))
|
|
1205
|
-
});
|
|
1206
|
-
/**
|
|
1207
|
-
* A template description for resources available on the server.
|
|
1208
|
-
*/
|
|
1209
|
-
const ResourceTemplateSchema = z.object({
|
|
1210
|
-
...BaseMetadataSchema.shape,
|
|
1211
|
-
...IconsSchema.shape,
|
|
1212
|
-
uriTemplate: z.string(),
|
|
1213
|
-
description: z.optional(z.string()),
|
|
1214
|
-
mimeType: z.optional(z.string()),
|
|
1215
|
-
annotations: AnnotationsSchema.optional(),
|
|
1216
|
-
_meta: z.optional(z.looseObject({}))
|
|
1217
|
-
});
|
|
1218
|
-
/**
|
|
1219
|
-
* Sent from the client to request a list of resources the server has.
|
|
1220
|
-
*/
|
|
1221
|
-
const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: z.literal("resources/list") });
|
|
1222
|
-
/**
|
|
1223
|
-
* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client.
|
|
1224
|
-
*/
|
|
1225
|
-
const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: z.array(ResourceSchema) });
|
|
1226
|
-
/**
|
|
1227
|
-
* Sent from the client to request a list of resource templates the server has.
|
|
1228
|
-
*/
|
|
1229
|
-
const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: z.literal("resources/templates/list") });
|
|
1230
|
-
/**
|
|
1231
|
-
* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client.
|
|
1232
|
-
*/
|
|
1233
|
-
const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: z.array(ResourceTemplateSchema) });
|
|
1234
|
-
const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: z.string() });
|
|
1235
|
-
/**
|
|
1236
|
-
* Parameters for a {@linkcode ReadResourceRequest | resources/read} request.
|
|
1237
|
-
*/
|
|
1238
|
-
const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
|
|
1239
|
-
/**
|
|
1240
|
-
* Sent from the client to the server, to read a specific resource URI.
|
|
1241
|
-
*/
|
|
1242
|
-
const ReadResourceRequestSchema = RequestSchema.extend({
|
|
1243
|
-
method: z.literal("resources/read"),
|
|
1244
|
-
params: ReadResourceRequestParamsSchema
|
|
1245
|
-
});
|
|
1246
|
-
/**
|
|
1247
|
-
* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client.
|
|
1248
|
-
*/
|
|
1249
|
-
const ReadResourceResultSchema = ResultSchema.extend({ contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) });
|
|
1250
|
-
/**
|
|
1251
|
-
* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
|
|
1252
|
-
*/
|
|
1253
|
-
const ResourceListChangedNotificationSchema = NotificationSchema.extend({
|
|
1254
|
-
method: z.literal("notifications/resources/list_changed"),
|
|
1255
|
-
params: NotificationsParamsSchema.optional()
|
|
1256
|
-
});
|
|
1257
|
-
const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
|
|
1258
|
-
/**
|
|
1259
|
-
* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes.
|
|
1260
|
-
*/
|
|
1261
|
-
const SubscribeRequestSchema = RequestSchema.extend({
|
|
1262
|
-
method: z.literal("resources/subscribe"),
|
|
1263
|
-
params: SubscribeRequestParamsSchema
|
|
1264
|
-
});
|
|
1265
|
-
const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
|
|
1266
|
-
/**
|
|
1267
|
-
* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request.
|
|
1268
|
-
*/
|
|
1269
|
-
const UnsubscribeRequestSchema = RequestSchema.extend({
|
|
1270
|
-
method: z.literal("resources/unsubscribe"),
|
|
1271
|
-
params: UnsubscribeRequestParamsSchema
|
|
1272
|
-
});
|
|
1273
|
-
/**
|
|
1274
|
-
* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification.
|
|
1275
|
-
*/
|
|
1276
|
-
const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: z.string() });
|
|
1277
|
-
/**
|
|
1278
|
-
* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request.
|
|
1279
|
-
*/
|
|
1280
|
-
const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
|
|
1281
|
-
method: z.literal("notifications/resources/updated"),
|
|
1282
|
-
params: ResourceUpdatedNotificationParamsSchema
|
|
1283
|
-
});
|
|
1284
|
-
/**
|
|
1285
|
-
* Describes an argument that a prompt can accept.
|
|
1286
|
-
*/
|
|
1287
|
-
const PromptArgumentSchema = z.object({
|
|
1288
|
-
name: z.string(),
|
|
1289
|
-
description: z.optional(z.string()),
|
|
1290
|
-
required: z.optional(z.boolean())
|
|
1291
|
-
});
|
|
1292
|
-
/**
|
|
1293
|
-
* A prompt or prompt template that the server offers.
|
|
1294
|
-
*/
|
|
1295
|
-
const PromptSchema = z.object({
|
|
1296
|
-
...BaseMetadataSchema.shape,
|
|
1297
|
-
...IconsSchema.shape,
|
|
1298
|
-
description: z.optional(z.string()),
|
|
1299
|
-
arguments: z.optional(z.array(PromptArgumentSchema)),
|
|
1300
|
-
_meta: z.optional(z.looseObject({}))
|
|
1301
|
-
});
|
|
1302
|
-
/**
|
|
1303
|
-
* Sent from the client to request a list of prompts and prompt templates the server has.
|
|
1304
|
-
*/
|
|
1305
|
-
const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: z.literal("prompts/list") });
|
|
1306
|
-
/**
|
|
1307
|
-
* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client.
|
|
1308
|
-
*/
|
|
1309
|
-
const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: z.array(PromptSchema) });
|
|
1310
|
-
/**
|
|
1311
|
-
* Parameters for a {@linkcode GetPromptRequest | prompts/get} request.
|
|
1312
|
-
*/
|
|
1313
|
-
const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
1314
|
-
name: z.string(),
|
|
1315
|
-
arguments: z.record(z.string(), z.string()).optional()
|
|
1316
|
-
});
|
|
1317
|
-
/**
|
|
1318
|
-
* Used by the client to get a prompt provided by the server.
|
|
1319
|
-
*/
|
|
1320
|
-
const GetPromptRequestSchema = RequestSchema.extend({
|
|
1321
|
-
method: z.literal("prompts/get"),
|
|
1322
|
-
params: GetPromptRequestParamsSchema
|
|
1323
|
-
});
|
|
1324
|
-
/**
|
|
1325
|
-
* Text provided to or from an LLM.
|
|
1326
|
-
*/
|
|
1327
|
-
const TextContentSchema = z.object({
|
|
1328
|
-
type: z.literal("text"),
|
|
1329
|
-
text: z.string(),
|
|
1330
|
-
annotations: AnnotationsSchema.optional(),
|
|
1331
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1332
|
-
});
|
|
1333
|
-
/**
|
|
1334
|
-
* An image provided to or from an LLM.
|
|
1335
|
-
*/
|
|
1336
|
-
const ImageContentSchema = z.object({
|
|
1337
|
-
type: z.literal("image"),
|
|
1338
|
-
data: Base64Schema,
|
|
1339
|
-
mimeType: z.string(),
|
|
1340
|
-
annotations: AnnotationsSchema.optional(),
|
|
1341
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1342
|
-
});
|
|
1343
|
-
/**
|
|
1344
|
-
* Audio content provided to or from an LLM.
|
|
1345
|
-
*/
|
|
1346
|
-
const AudioContentSchema = z.object({
|
|
1347
|
-
type: z.literal("audio"),
|
|
1348
|
-
data: Base64Schema,
|
|
1349
|
-
mimeType: z.string(),
|
|
1350
|
-
annotations: AnnotationsSchema.optional(),
|
|
1351
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1352
|
-
});
|
|
1353
|
-
/**
|
|
1354
|
-
* A tool call request from an assistant (LLM).
|
|
1355
|
-
* Represents the assistant's request to use a tool.
|
|
1356
|
-
*/
|
|
1357
|
-
const ToolUseContentSchema = z.object({
|
|
1358
|
-
type: z.literal("tool_use"),
|
|
1359
|
-
name: z.string(),
|
|
1360
|
-
id: z.string(),
|
|
1361
|
-
input: z.record(z.string(), z.unknown()),
|
|
1362
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1363
|
-
});
|
|
1364
|
-
/**
|
|
1365
|
-
* The contents of a resource, embedded into a prompt or tool call result.
|
|
1366
|
-
*/
|
|
1367
|
-
const EmbeddedResourceSchema = z.object({
|
|
1368
|
-
type: z.literal("resource"),
|
|
1369
|
-
resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
|
|
1370
|
-
annotations: AnnotationsSchema.optional(),
|
|
1371
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1372
|
-
});
|
|
1373
|
-
/**
|
|
1374
|
-
* A resource that the server is capable of reading, included in a prompt or tool call result.
|
|
1375
|
-
*
|
|
1376
|
-
* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests.
|
|
1377
|
-
*/
|
|
1378
|
-
const ResourceLinkSchema = ResourceSchema.extend({ type: z.literal("resource_link") });
|
|
1379
|
-
/**
|
|
1380
|
-
* A content block that can be used in prompts and tool results.
|
|
1381
|
-
*/
|
|
1382
|
-
const ContentBlockSchema = z.union([
|
|
1383
|
-
TextContentSchema,
|
|
1384
|
-
ImageContentSchema,
|
|
1385
|
-
AudioContentSchema,
|
|
1386
|
-
ResourceLinkSchema,
|
|
1387
|
-
EmbeddedResourceSchema
|
|
1388
|
-
]);
|
|
1389
|
-
/**
|
|
1390
|
-
* Describes a message returned as part of a prompt.
|
|
1391
|
-
*/
|
|
1392
|
-
const PromptMessageSchema = z.object({
|
|
1393
|
-
role: RoleSchema,
|
|
1394
|
-
content: ContentBlockSchema
|
|
1395
|
-
});
|
|
1396
|
-
/**
|
|
1397
|
-
* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client.
|
|
1398
|
-
*/
|
|
1399
|
-
const GetPromptResultSchema = ResultSchema.extend({
|
|
1400
|
-
description: z.string().optional(),
|
|
1401
|
-
messages: z.array(PromptMessageSchema)
|
|
1402
|
-
});
|
|
1403
|
-
/**
|
|
1404
|
-
* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
|
|
1405
|
-
*/
|
|
1406
|
-
const PromptListChangedNotificationSchema = NotificationSchema.extend({
|
|
1407
|
-
method: z.literal("notifications/prompts/list_changed"),
|
|
1408
|
-
params: NotificationsParamsSchema.optional()
|
|
1409
|
-
});
|
|
1410
|
-
/**
|
|
1411
|
-
* Additional properties describing a `Tool` to clients.
|
|
1412
|
-
*
|
|
1413
|
-
* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**.
|
|
1414
|
-
* They are not guaranteed to provide a faithful description of
|
|
1415
|
-
* tool behavior (including descriptive properties like `title`).
|
|
1416
|
-
*
|
|
1417
|
-
* Clients should never make tool use decisions based on `ToolAnnotations`
|
|
1418
|
-
* received from untrusted servers.
|
|
1419
|
-
*/
|
|
1420
|
-
const ToolAnnotationsSchema = z.object({
|
|
1421
|
-
title: z.string().optional(),
|
|
1422
|
-
readOnlyHint: z.boolean().optional(),
|
|
1423
|
-
destructiveHint: z.boolean().optional(),
|
|
1424
|
-
idempotentHint: z.boolean().optional(),
|
|
1425
|
-
openWorldHint: z.boolean().optional()
|
|
1426
|
-
});
|
|
1427
|
-
/**
|
|
1428
|
-
* Execution-related properties for a tool.
|
|
1429
|
-
*/
|
|
1430
|
-
const ToolExecutionSchema = z.object({ taskSupport: z.enum([
|
|
1431
|
-
"required",
|
|
1432
|
-
"optional",
|
|
1433
|
-
"forbidden"
|
|
1434
|
-
]).optional() });
|
|
1435
|
-
/**
|
|
1436
|
-
* Definition for a tool the client can call.
|
|
1437
|
-
*/
|
|
1438
|
-
const ToolSchema = z.object({
|
|
1439
|
-
...BaseMetadataSchema.shape,
|
|
1440
|
-
...IconsSchema.shape,
|
|
1441
|
-
description: z.string().optional(),
|
|
1442
|
-
inputSchema: z.object({
|
|
1443
|
-
type: z.literal("object"),
|
|
1444
|
-
properties: z.record(z.string(), JSONValueSchema).optional(),
|
|
1445
|
-
required: z.array(z.string()).optional()
|
|
1446
|
-
}).catchall(z.unknown()),
|
|
1447
|
-
outputSchema: z.object({
|
|
1448
|
-
type: z.literal("object"),
|
|
1449
|
-
properties: z.record(z.string(), JSONValueSchema).optional(),
|
|
1450
|
-
required: z.array(z.string()).optional()
|
|
1451
|
-
}).catchall(z.unknown()).optional(),
|
|
1452
|
-
annotations: ToolAnnotationsSchema.optional(),
|
|
1453
|
-
execution: ToolExecutionSchema.optional(),
|
|
1454
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1455
|
-
});
|
|
1456
|
-
/**
|
|
1457
|
-
* Sent from the client to request a list of tools the server has.
|
|
1458
|
-
*/
|
|
1459
|
-
const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: z.literal("tools/list") });
|
|
1460
|
-
/**
|
|
1461
|
-
* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client.
|
|
1462
|
-
*/
|
|
1463
|
-
const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: z.array(ToolSchema) });
|
|
1464
|
-
/**
|
|
1465
|
-
* The server's response to a tool call.
|
|
1466
|
-
*/
|
|
1467
|
-
const CallToolResultSchema = ResultSchema.extend({
|
|
1468
|
-
content: z.array(ContentBlockSchema).default([]),
|
|
1469
|
-
structuredContent: z.record(z.string(), z.unknown()).optional(),
|
|
1470
|
-
isError: z.boolean().optional()
|
|
1471
|
-
});
|
|
1472
|
-
/**
|
|
1473
|
-
* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07.
|
|
1474
|
-
*/
|
|
1475
|
-
const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: z.unknown() }));
|
|
1476
|
-
/**
|
|
1477
|
-
* Parameters for a `tools/call` request.
|
|
1478
|
-
*/
|
|
1479
|
-
const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1480
|
-
name: z.string(),
|
|
1481
|
-
arguments: z.record(z.string(), z.unknown()).optional()
|
|
1482
|
-
});
|
|
1483
|
-
/**
|
|
1484
|
-
* Used by the client to invoke a tool provided by the server.
|
|
1485
|
-
*/
|
|
1486
|
-
const CallToolRequestSchema = RequestSchema.extend({
|
|
1487
|
-
method: z.literal("tools/call"),
|
|
1488
|
-
params: CallToolRequestParamsSchema
|
|
1489
|
-
});
|
|
1490
|
-
/**
|
|
1491
|
-
* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
|
|
1492
|
-
*/
|
|
1493
|
-
const ToolListChangedNotificationSchema = NotificationSchema.extend({
|
|
1494
|
-
method: z.literal("notifications/tools/list_changed"),
|
|
1495
|
-
params: NotificationsParamsSchema.optional()
|
|
1496
|
-
});
|
|
1497
|
-
/**
|
|
1498
|
-
* Base schema for list changed subscription options (without callback).
|
|
1499
|
-
* Used internally for Zod validation of `autoRefresh` and `debounceMs`.
|
|
1500
|
-
*/
|
|
1501
|
-
const ListChangedOptionsBaseSchema = z.object({
|
|
1502
|
-
autoRefresh: z.boolean().default(true),
|
|
1503
|
-
debounceMs: z.number().int().nonnegative().default(300)
|
|
1504
|
-
});
|
|
1505
|
-
/**
|
|
1506
|
-
* The severity of a log message.
|
|
1507
|
-
*/
|
|
1508
|
-
const LoggingLevelSchema = z.enum([
|
|
1509
|
-
"debug",
|
|
1510
|
-
"info",
|
|
1511
|
-
"notice",
|
|
1512
|
-
"warning",
|
|
1513
|
-
"error",
|
|
1514
|
-
"critical",
|
|
1515
|
-
"alert",
|
|
1516
|
-
"emergency"
|
|
1517
|
-
]);
|
|
1518
|
-
/**
|
|
1519
|
-
* Parameters for a `logging/setLevel` request.
|
|
1520
|
-
*/
|
|
1521
|
-
const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema });
|
|
1522
|
-
/**
|
|
1523
|
-
* A request from the client to the server, to enable or adjust logging.
|
|
1524
|
-
*/
|
|
1525
|
-
const SetLevelRequestSchema = RequestSchema.extend({
|
|
1526
|
-
method: z.literal("logging/setLevel"),
|
|
1527
|
-
params: SetLevelRequestParamsSchema
|
|
1528
|
-
});
|
|
1529
|
-
/**
|
|
1530
|
-
* Parameters for a `notifications/message` notification.
|
|
1531
|
-
*/
|
|
1532
|
-
const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
1533
|
-
level: LoggingLevelSchema,
|
|
1534
|
-
logger: z.string().optional(),
|
|
1535
|
-
data: z.unknown()
|
|
1536
|
-
});
|
|
1537
|
-
/**
|
|
1538
|
-
* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically.
|
|
1539
|
-
*/
|
|
1540
|
-
const LoggingMessageNotificationSchema = NotificationSchema.extend({
|
|
1541
|
-
method: z.literal("notifications/message"),
|
|
1542
|
-
params: LoggingMessageNotificationParamsSchema
|
|
1543
|
-
});
|
|
1544
|
-
/**
|
|
1545
|
-
* The per-request `_meta` envelope carried by every request under protocol revision
|
|
1546
|
-
* 2026-07-28: the protocol version governing the request, the client implementation
|
|
1547
|
-
* info, and the client's capabilities — declared per request rather than once at
|
|
1548
|
-
* initialization — plus the optional log-level opt-in.
|
|
1549
|
-
*
|
|
1550
|
-
* This schema models the complete envelope on its own. The base request schemas
|
|
1551
|
-
* ({@linkcode RequestMetaSchema}) deliberately stay lenient so the same wire schemas
|
|
1552
|
-
* parse requests from earlier protocol revisions (no envelope) as well; envelope
|
|
1553
|
-
* requiredness is enforced per request at dispatch time, not here.
|
|
1554
|
-
*/
|
|
1555
|
-
const RequestMetaEnvelopeSchema = z.looseObject({
|
|
1556
|
-
progressToken: ProgressTokenSchema.optional(),
|
|
1557
|
-
[PROTOCOL_VERSION_META_KEY]: z.string(),
|
|
1558
|
-
[CLIENT_INFO_META_KEY]: ImplementationSchema,
|
|
1559
|
-
[CLIENT_CAPABILITIES_META_KEY]: ClientCapabilitiesSchema,
|
|
1560
|
-
[LOG_LEVEL_META_KEY]: LoggingLevelSchema.optional()
|
|
1561
|
-
});
|
|
1562
|
-
/**
|
|
1563
|
-
* Hints to use for model selection.
|
|
1564
|
-
*/
|
|
1565
|
-
const ModelHintSchema = z.object({ name: z.string().optional() });
|
|
1566
|
-
/**
|
|
1567
|
-
* The server's preferences for model selection, requested of the client during sampling.
|
|
1568
|
-
*/
|
|
1569
|
-
const ModelPreferencesSchema = z.object({
|
|
1570
|
-
hints: z.array(ModelHintSchema).optional(),
|
|
1571
|
-
costPriority: z.number().min(0).max(1).optional(),
|
|
1572
|
-
speedPriority: z.number().min(0).max(1).optional(),
|
|
1573
|
-
intelligencePriority: z.number().min(0).max(1).optional()
|
|
1574
|
-
});
|
|
1575
|
-
/**
|
|
1576
|
-
* Controls tool usage behavior in sampling requests.
|
|
1577
|
-
*/
|
|
1578
|
-
const ToolChoiceSchema = z.object({ mode: z.enum([
|
|
1579
|
-
"auto",
|
|
1580
|
-
"required",
|
|
1581
|
-
"none"
|
|
1582
|
-
]).optional() });
|
|
1583
|
-
/**
|
|
1584
|
-
* The result of a tool execution, provided by the user (server).
|
|
1585
|
-
* Represents the outcome of invoking a tool requested via `ToolUseContent`.
|
|
1586
|
-
*/
|
|
1587
|
-
const ToolResultContentSchema = z.object({
|
|
1588
|
-
type: z.literal("tool_result"),
|
|
1589
|
-
toolUseId: z.string().describe("The unique identifier for the corresponding tool call."),
|
|
1590
|
-
content: z.array(ContentBlockSchema).default([]),
|
|
1591
|
-
structuredContent: z.object({}).loose().optional(),
|
|
1592
|
-
isError: z.boolean().optional(),
|
|
1593
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1594
|
-
});
|
|
1595
|
-
/**
|
|
1596
|
-
* Basic content types for sampling responses (without tool use).
|
|
1597
|
-
* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used.
|
|
1598
|
-
*/
|
|
1599
|
-
const SamplingContentSchema = z.discriminatedUnion("type", [
|
|
1600
|
-
TextContentSchema,
|
|
1601
|
-
ImageContentSchema,
|
|
1602
|
-
AudioContentSchema
|
|
1603
|
-
]);
|
|
1604
|
-
/**
|
|
1605
|
-
* Content block types allowed in sampling messages.
|
|
1606
|
-
* This includes text, image, audio, tool use requests, and tool results.
|
|
1607
|
-
*/
|
|
1608
|
-
const SamplingMessageContentBlockSchema = z.discriminatedUnion("type", [
|
|
1609
|
-
TextContentSchema,
|
|
1610
|
-
ImageContentSchema,
|
|
1611
|
-
AudioContentSchema,
|
|
1612
|
-
ToolUseContentSchema,
|
|
1613
|
-
ToolResultContentSchema
|
|
1614
|
-
]);
|
|
1615
|
-
/**
|
|
1616
|
-
* Describes a message issued to or received from an LLM API.
|
|
1617
|
-
*/
|
|
1618
|
-
const SamplingMessageSchema = z.object({
|
|
1619
|
-
role: RoleSchema,
|
|
1620
|
-
content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),
|
|
1621
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1622
|
-
});
|
|
1623
|
-
/**
|
|
1624
|
-
* Parameters for a `sampling/createMessage` request.
|
|
1625
|
-
*/
|
|
1626
|
-
const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1627
|
-
messages: z.array(SamplingMessageSchema),
|
|
1628
|
-
modelPreferences: ModelPreferencesSchema.optional(),
|
|
1629
|
-
systemPrompt: z.string().optional(),
|
|
1630
|
-
includeContext: z.enum([
|
|
1631
|
-
"none",
|
|
1632
|
-
"thisServer",
|
|
1633
|
-
"allServers"
|
|
1634
|
-
]).optional(),
|
|
1635
|
-
temperature: z.number().optional(),
|
|
1636
|
-
maxTokens: z.number().int(),
|
|
1637
|
-
stopSequences: z.array(z.string()).optional(),
|
|
1638
|
-
metadata: JSONObjectSchema.optional(),
|
|
1639
|
-
tools: z.array(ToolSchema).optional(),
|
|
1640
|
-
toolChoice: ToolChoiceSchema.optional()
|
|
1641
|
-
});
|
|
1642
|
-
/**
|
|
1643
|
-
* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
|
|
1644
|
-
*/
|
|
1645
|
-
const CreateMessageRequestSchema = RequestSchema.extend({
|
|
1646
|
-
method: z.literal("sampling/createMessage"),
|
|
1647
|
-
params: CreateMessageRequestParamsSchema
|
|
1648
|
-
});
|
|
1649
|
-
/**
|
|
1650
|
-
* The client's response to a `sampling/create_message` request from the server.
|
|
1651
|
-
* This is the backwards-compatible version that returns single content (no arrays).
|
|
1652
|
-
* Used when the request does not include tools.
|
|
1653
|
-
*/
|
|
1654
|
-
const CreateMessageResultSchema = ResultSchema.extend({
|
|
1655
|
-
model: z.string(),
|
|
1656
|
-
stopReason: z.optional(z.enum([
|
|
1657
|
-
"endTurn",
|
|
1658
|
-
"stopSequence",
|
|
1659
|
-
"maxTokens"
|
|
1660
|
-
]).or(z.string())),
|
|
1661
|
-
role: RoleSchema,
|
|
1662
|
-
content: SamplingContentSchema
|
|
1663
|
-
});
|
|
1664
|
-
/**
|
|
1665
|
-
* The client's response to a `sampling/create_message` request when tools were provided.
|
|
1666
|
-
* This version supports array content for tool use flows.
|
|
1667
|
-
*/
|
|
1668
|
-
const CreateMessageResultWithToolsSchema = ResultSchema.extend({
|
|
1669
|
-
model: z.string(),
|
|
1670
|
-
stopReason: z.optional(z.enum([
|
|
1671
|
-
"endTurn",
|
|
1672
|
-
"stopSequence",
|
|
1673
|
-
"maxTokens",
|
|
1674
|
-
"toolUse"
|
|
1675
|
-
]).or(z.string())),
|
|
1676
|
-
role: RoleSchema,
|
|
1677
|
-
content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])
|
|
1678
|
-
});
|
|
1679
|
-
/**
|
|
1680
|
-
* Primitive schema definition for boolean fields.
|
|
1681
|
-
*/
|
|
1682
|
-
const BooleanSchemaSchema = z.object({
|
|
1683
|
-
type: z.literal("boolean"),
|
|
1684
|
-
title: z.string().optional(),
|
|
1685
|
-
description: z.string().optional(),
|
|
1686
|
-
default: z.boolean().optional()
|
|
1687
|
-
});
|
|
1688
|
-
/**
|
|
1689
|
-
* Primitive schema definition for string fields.
|
|
1690
|
-
*/
|
|
1691
|
-
const StringSchemaSchema = z.object({
|
|
1692
|
-
type: z.literal("string"),
|
|
1693
|
-
title: z.string().optional(),
|
|
1694
|
-
description: z.string().optional(),
|
|
1695
|
-
minLength: z.number().optional(),
|
|
1696
|
-
maxLength: z.number().optional(),
|
|
1697
|
-
format: z.enum([
|
|
1698
|
-
"email",
|
|
1699
|
-
"uri",
|
|
1700
|
-
"date",
|
|
1701
|
-
"date-time"
|
|
1702
|
-
]).optional(),
|
|
1703
|
-
default: z.string().optional()
|
|
1704
|
-
});
|
|
1705
|
-
/**
|
|
1706
|
-
* Primitive schema definition for number fields.
|
|
1707
|
-
*/
|
|
1708
|
-
const NumberSchemaSchema = z.object({
|
|
1709
|
-
type: z.enum(["number", "integer"]),
|
|
1710
|
-
title: z.string().optional(),
|
|
1711
|
-
description: z.string().optional(),
|
|
1712
|
-
minimum: z.number().optional(),
|
|
1713
|
-
maximum: z.number().optional(),
|
|
1714
|
-
default: z.number().optional()
|
|
1715
|
-
});
|
|
1716
|
-
/**
|
|
1717
|
-
* Schema for single-selection enumeration without display titles for options.
|
|
1718
|
-
*/
|
|
1719
|
-
const UntitledSingleSelectEnumSchemaSchema = z.object({
|
|
1720
|
-
type: z.literal("string"),
|
|
1721
|
-
title: z.string().optional(),
|
|
1722
|
-
description: z.string().optional(),
|
|
1723
|
-
enum: z.array(z.string()),
|
|
1724
|
-
default: z.string().optional()
|
|
1725
|
-
});
|
|
1726
|
-
/**
|
|
1727
|
-
* Schema for single-selection enumeration with display titles for each option.
|
|
1728
|
-
*/
|
|
1729
|
-
const TitledSingleSelectEnumSchemaSchema = z.object({
|
|
1730
|
-
type: z.literal("string"),
|
|
1731
|
-
title: z.string().optional(),
|
|
1732
|
-
description: z.string().optional(),
|
|
1733
|
-
oneOf: z.array(z.object({
|
|
1734
|
-
const: z.string(),
|
|
1735
|
-
title: z.string()
|
|
1736
|
-
})),
|
|
1737
|
-
default: z.string().optional()
|
|
1738
|
-
});
|
|
1739
|
-
/**
|
|
1740
|
-
* Use {@linkcode TitledSingleSelectEnumSchema} instead.
|
|
1741
|
-
* This interface will be removed in a future version.
|
|
1742
|
-
*/
|
|
1743
|
-
const LegacyTitledEnumSchemaSchema = z.object({
|
|
1744
|
-
type: z.literal("string"),
|
|
1745
|
-
title: z.string().optional(),
|
|
1746
|
-
description: z.string().optional(),
|
|
1747
|
-
enum: z.array(z.string()),
|
|
1748
|
-
enumNames: z.array(z.string()).optional(),
|
|
1749
|
-
default: z.string().optional()
|
|
1750
|
-
});
|
|
1751
|
-
const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
|
|
1752
|
-
/**
|
|
1753
|
-
* Schema for multiple-selection enumeration without display titles for options.
|
|
1754
|
-
*/
|
|
1755
|
-
const UntitledMultiSelectEnumSchemaSchema = z.object({
|
|
1756
|
-
type: z.literal("array"),
|
|
1757
|
-
title: z.string().optional(),
|
|
1758
|
-
description: z.string().optional(),
|
|
1759
|
-
minItems: z.number().optional(),
|
|
1760
|
-
maxItems: z.number().optional(),
|
|
1761
|
-
items: z.object({
|
|
1762
|
-
type: z.literal("string"),
|
|
1763
|
-
enum: z.array(z.string())
|
|
1764
|
-
}),
|
|
1765
|
-
default: z.array(z.string()).optional()
|
|
1766
|
-
});
|
|
1767
|
-
/**
|
|
1768
|
-
* Schema for multiple-selection enumeration with display titles for each option.
|
|
1769
|
-
*/
|
|
1770
|
-
const TitledMultiSelectEnumSchemaSchema = z.object({
|
|
1771
|
-
type: z.literal("array"),
|
|
1772
|
-
title: z.string().optional(),
|
|
1773
|
-
description: z.string().optional(),
|
|
1774
|
-
minItems: z.number().optional(),
|
|
1775
|
-
maxItems: z.number().optional(),
|
|
1776
|
-
items: z.object({ anyOf: z.array(z.object({
|
|
1777
|
-
const: z.string(),
|
|
1778
|
-
title: z.string()
|
|
1779
|
-
})) }),
|
|
1780
|
-
default: z.array(z.string()).optional()
|
|
1781
|
-
});
|
|
1782
|
-
/**
|
|
1783
|
-
* Combined schema for multiple-selection enumeration
|
|
1784
|
-
*/
|
|
1785
|
-
const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
|
|
1786
|
-
/**
|
|
1787
|
-
* Primitive schema definition for enum fields.
|
|
1788
|
-
*/
|
|
1789
|
-
const EnumSchemaSchema = z.union([
|
|
1790
|
-
LegacyTitledEnumSchemaSchema,
|
|
1791
|
-
SingleSelectEnumSchemaSchema,
|
|
1792
|
-
MultiSelectEnumSchemaSchema
|
|
1793
|
-
]);
|
|
1794
|
-
/**
|
|
1795
|
-
* Union of all primitive schema definitions.
|
|
1796
|
-
*/
|
|
1797
|
-
const PrimitiveSchemaDefinitionSchema = z.union([
|
|
1798
|
-
EnumSchemaSchema,
|
|
1799
|
-
BooleanSchemaSchema,
|
|
1800
|
-
StringSchemaSchema,
|
|
1801
|
-
NumberSchemaSchema
|
|
1802
|
-
]);
|
|
1803
|
-
/**
|
|
1804
|
-
* Parameters for an `elicitation/create` request for form-based elicitation.
|
|
1805
|
-
*/
|
|
1806
|
-
const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1807
|
-
mode: z.literal("form").optional(),
|
|
1808
|
-
message: z.string(),
|
|
1809
|
-
requestedSchema: z.object({
|
|
1810
|
-
type: z.literal("object"),
|
|
1811
|
-
properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),
|
|
1812
|
-
required: z.array(z.string()).optional()
|
|
1813
|
-
}).catchall(z.unknown())
|
|
1814
|
-
});
|
|
1815
|
-
/**
|
|
1816
|
-
* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation.
|
|
1817
|
-
*/
|
|
1818
|
-
const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
1819
|
-
mode: z.literal("url"),
|
|
1820
|
-
message: z.string(),
|
|
1821
|
-
elicitationId: z.string(),
|
|
1822
|
-
url: z.string().url()
|
|
1823
|
-
});
|
|
1824
|
-
/**
|
|
1825
|
-
* The parameters for a request to elicit additional information from the user via the client.
|
|
1826
|
-
*/
|
|
1827
|
-
const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
|
|
1828
|
-
/**
|
|
1829
|
-
* A request from the server to elicit user input via the client.
|
|
1830
|
-
* The client should present the message and form fields to the user (form mode)
|
|
1831
|
-
* or navigate to a URL (URL mode).
|
|
1832
|
-
*/
|
|
1833
|
-
const ElicitRequestSchema = RequestSchema.extend({
|
|
1834
|
-
method: z.literal("elicitation/create"),
|
|
1835
|
-
params: ElicitRequestParamsSchema
|
|
1836
|
-
});
|
|
1837
|
-
/**
|
|
1838
|
-
* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification.
|
|
1839
|
-
*
|
|
1840
|
-
* @category notifications/elicitation/complete
|
|
1841
|
-
*/
|
|
1842
|
-
const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: z.string() });
|
|
1843
|
-
/**
|
|
1844
|
-
* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.
|
|
1845
|
-
*
|
|
1846
|
-
* @category notifications/elicitation/complete
|
|
1847
|
-
*/
|
|
1848
|
-
const ElicitationCompleteNotificationSchema = NotificationSchema.extend({
|
|
1849
|
-
method: z.literal("notifications/elicitation/complete"),
|
|
1850
|
-
params: ElicitationCompleteNotificationParamsSchema
|
|
1851
|
-
});
|
|
1852
|
-
/**
|
|
1853
|
-
* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server.
|
|
1854
|
-
*/
|
|
1855
|
-
const ElicitResultSchema = ResultSchema.extend({
|
|
1856
|
-
action: z.enum([
|
|
1857
|
-
"accept",
|
|
1858
|
-
"decline",
|
|
1859
|
-
"cancel"
|
|
1860
|
-
]),
|
|
1861
|
-
content: z.preprocess((val) => val === null ? void 0 : val, z.record(z.string(), z.union([
|
|
1862
|
-
z.string(),
|
|
1863
|
-
z.number(),
|
|
1864
|
-
z.boolean(),
|
|
1865
|
-
z.array(z.string())
|
|
1866
|
-
])).optional())
|
|
1867
|
-
});
|
|
1868
|
-
/**
|
|
1869
|
-
* A reference to a resource or resource template definition.
|
|
1870
|
-
*/
|
|
1871
|
-
const ResourceTemplateReferenceSchema = z.object({
|
|
1872
|
-
type: z.literal("ref/resource"),
|
|
1873
|
-
uri: z.string()
|
|
1874
|
-
});
|
|
1875
|
-
/**
|
|
1876
|
-
* Identifies a prompt.
|
|
1877
|
-
*/
|
|
1878
|
-
const PromptReferenceSchema = z.object({
|
|
1879
|
-
type: z.literal("ref/prompt"),
|
|
1880
|
-
name: z.string()
|
|
1881
|
-
});
|
|
1882
|
-
/**
|
|
1883
|
-
* Parameters for a {@linkcode CompleteRequest | completion/complete} request.
|
|
1884
|
-
*/
|
|
1885
|
-
const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
1886
|
-
ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
|
|
1887
|
-
argument: z.object({
|
|
1888
|
-
name: z.string(),
|
|
1889
|
-
value: z.string()
|
|
1890
|
-
}),
|
|
1891
|
-
context: z.object({ arguments: z.record(z.string(), z.string()).optional() }).optional()
|
|
1892
|
-
});
|
|
1893
|
-
/**
|
|
1894
|
-
* A request from the client to the server, to ask for completion options.
|
|
1895
|
-
*/
|
|
1896
|
-
const CompleteRequestSchema = RequestSchema.extend({
|
|
1897
|
-
method: z.literal("completion/complete"),
|
|
1898
|
-
params: CompleteRequestParamsSchema
|
|
1899
|
-
});
|
|
1900
|
-
/**
|
|
1901
|
-
* The server's response to a {@linkcode CompleteRequest | completion/complete} request
|
|
1902
|
-
*/
|
|
1903
|
-
const CompleteResultSchema = ResultSchema.extend({ completion: z.looseObject({
|
|
1904
|
-
values: z.array(z.string()).max(100),
|
|
1905
|
-
total: z.optional(z.number().int()),
|
|
1906
|
-
hasMore: z.optional(z.boolean())
|
|
1907
|
-
}) });
|
|
1908
|
-
/**
|
|
1909
|
-
* Represents a root directory or file that the server can operate on.
|
|
1910
|
-
*/
|
|
1911
|
-
const RootSchema = z.object({
|
|
1912
|
-
uri: z.string().startsWith("file://"),
|
|
1913
|
-
name: z.string().optional(),
|
|
1914
|
-
_meta: z.record(z.string(), z.unknown()).optional()
|
|
1915
|
-
});
|
|
1916
|
-
/**
|
|
1917
|
-
* Sent from the server to request a list of root URIs from the client.
|
|
1918
|
-
*/
|
|
1919
|
-
const ListRootsRequestSchema = RequestSchema.extend({
|
|
1920
|
-
method: z.literal("roots/list"),
|
|
1921
|
-
params: BaseRequestParamsSchema.optional()
|
|
1922
|
-
});
|
|
1923
|
-
/**
|
|
1924
|
-
* The client's response to a `roots/list` request from the server.
|
|
1925
|
-
*/
|
|
1926
|
-
const ListRootsResultSchema = ResultSchema.extend({ roots: z.array(RootSchema) });
|
|
1927
|
-
/**
|
|
1928
|
-
* A notification from the client to the server, informing it that the list of roots has changed.
|
|
1929
|
-
*/
|
|
1930
|
-
const RootsListChangedNotificationSchema = NotificationSchema.extend({
|
|
1931
|
-
method: z.literal("notifications/roots/list_changed"),
|
|
1932
|
-
params: NotificationsParamsSchema.optional()
|
|
1933
|
-
});
|
|
1934
|
-
const ClientRequestSchema = z.union([
|
|
1935
|
-
PingRequestSchema,
|
|
1936
|
-
InitializeRequestSchema,
|
|
1937
|
-
CompleteRequestSchema,
|
|
1938
|
-
SetLevelRequestSchema,
|
|
1939
|
-
GetPromptRequestSchema,
|
|
1940
|
-
ListPromptsRequestSchema,
|
|
1941
|
-
ListResourcesRequestSchema,
|
|
1942
|
-
ListResourceTemplatesRequestSchema,
|
|
1943
|
-
ReadResourceRequestSchema,
|
|
1944
|
-
SubscribeRequestSchema,
|
|
1945
|
-
UnsubscribeRequestSchema,
|
|
1946
|
-
CallToolRequestSchema,
|
|
1947
|
-
ListToolsRequestSchema,
|
|
1948
|
-
GetTaskRequestSchema,
|
|
1949
|
-
GetTaskPayloadRequestSchema,
|
|
1950
|
-
ListTasksRequestSchema,
|
|
1951
|
-
CancelTaskRequestSchema
|
|
1952
|
-
]);
|
|
1953
|
-
const ClientNotificationSchema = z.union([
|
|
1954
|
-
CancelledNotificationSchema,
|
|
1955
|
-
ProgressNotificationSchema,
|
|
1956
|
-
InitializedNotificationSchema,
|
|
1957
|
-
RootsListChangedNotificationSchema,
|
|
1958
|
-
TaskStatusNotificationSchema
|
|
1959
|
-
]);
|
|
1960
|
-
const ClientResultSchema = z.union([
|
|
1961
|
-
EmptyResultSchema,
|
|
1962
|
-
CreateMessageResultSchema,
|
|
1963
|
-
CreateMessageResultWithToolsSchema,
|
|
1964
|
-
ElicitResultSchema,
|
|
1965
|
-
ListRootsResultSchema,
|
|
1966
|
-
GetTaskResultSchema,
|
|
1967
|
-
ListTasksResultSchema,
|
|
1968
|
-
CreateTaskResultSchema
|
|
1969
|
-
]);
|
|
1970
|
-
const ServerRequestSchema = z.union([
|
|
1971
|
-
PingRequestSchema,
|
|
1972
|
-
CreateMessageRequestSchema,
|
|
1973
|
-
ElicitRequestSchema,
|
|
1974
|
-
ListRootsRequestSchema,
|
|
1975
|
-
GetTaskRequestSchema,
|
|
1976
|
-
GetTaskPayloadRequestSchema,
|
|
1977
|
-
ListTasksRequestSchema,
|
|
1978
|
-
CancelTaskRequestSchema
|
|
1979
|
-
]);
|
|
1980
|
-
const ServerNotificationSchema = z.union([
|
|
1981
|
-
CancelledNotificationSchema,
|
|
1982
|
-
ProgressNotificationSchema,
|
|
1983
|
-
LoggingMessageNotificationSchema,
|
|
1984
|
-
ResourceUpdatedNotificationSchema,
|
|
1985
|
-
ResourceListChangedNotificationSchema,
|
|
1986
|
-
ToolListChangedNotificationSchema,
|
|
1987
|
-
PromptListChangedNotificationSchema,
|
|
1988
|
-
TaskStatusNotificationSchema,
|
|
1989
|
-
ElicitationCompleteNotificationSchema
|
|
1990
|
-
]);
|
|
1991
|
-
const ServerResultSchema = z.union([
|
|
1992
|
-
EmptyResultSchema,
|
|
1993
|
-
InitializeResultSchema,
|
|
1994
|
-
CompleteResultSchema,
|
|
1995
|
-
GetPromptResultSchema,
|
|
1996
|
-
ListPromptsResultSchema,
|
|
1997
|
-
ListResourcesResultSchema,
|
|
1998
|
-
ListResourceTemplatesResultSchema,
|
|
1999
|
-
ReadResourceResultSchema,
|
|
2000
|
-
CallToolResultSchema,
|
|
2001
|
-
ListToolsResultSchema,
|
|
2002
|
-
GetTaskResultSchema,
|
|
2003
|
-
ListTasksResultSchema,
|
|
2004
|
-
CreateTaskResultSchema
|
|
2005
|
-
]);
|
|
2006
|
-
const resultSchemas = {
|
|
2007
|
-
ping: EmptyResultSchema,
|
|
2008
|
-
initialize: InitializeResultSchema,
|
|
2009
|
-
"completion/complete": CompleteResultSchema,
|
|
2010
|
-
"logging/setLevel": EmptyResultSchema,
|
|
2011
|
-
"prompts/get": GetPromptResultSchema,
|
|
2012
|
-
"prompts/list": ListPromptsResultSchema,
|
|
2013
|
-
"resources/list": ListResourcesResultSchema,
|
|
2014
|
-
"resources/templates/list": ListResourceTemplatesResultSchema,
|
|
2015
|
-
"resources/read": ReadResourceResultSchema,
|
|
2016
|
-
"resources/subscribe": EmptyResultSchema,
|
|
2017
|
-
"resources/unsubscribe": EmptyResultSchema,
|
|
2018
|
-
"tools/call": z.union([CallToolResultSchema, CreateTaskResultSchema]),
|
|
2019
|
-
"tools/list": ListToolsResultSchema,
|
|
2020
|
-
"sampling/createMessage": z.union([CreateMessageResultWithToolsSchema, CreateTaskResultSchema]),
|
|
2021
|
-
"elicitation/create": z.union([ElicitResultSchema, CreateTaskResultSchema]),
|
|
2022
|
-
"roots/list": ListRootsResultSchema,
|
|
2023
|
-
"tasks/get": GetTaskResultSchema,
|
|
2024
|
-
"tasks/result": ResultSchema,
|
|
2025
|
-
"tasks/list": ListTasksResultSchema,
|
|
2026
|
-
"tasks/cancel": CancelTaskResultSchema
|
|
2027
|
-
};
|
|
2028
|
-
function getResultSchema(method) {
|
|
2029
|
-
return resultSchemas[method];
|
|
2030
|
-
}
|
|
2031
|
-
function buildSchemaMap(schemas) {
|
|
2032
|
-
const map = {};
|
|
2033
|
-
for (const schema of schemas) {
|
|
2034
|
-
const method = schema.shape.method.value;
|
|
2035
|
-
map[method] = schema;
|
|
2036
|
-
}
|
|
2037
|
-
return map;
|
|
2038
|
-
}
|
|
2039
|
-
const requestSchemas = buildSchemaMap([...ClientRequestSchema.options, ...ServerRequestSchema.options]);
|
|
2040
|
-
const notificationSchemas = buildSchemaMap([...ClientNotificationSchema.options, ...ServerNotificationSchema.options]);
|
|
2041
|
-
function getRequestSchema(method) {
|
|
2042
|
-
return requestSchemas[method];
|
|
2043
|
-
}
|
|
2044
|
-
function getNotificationSchema(method) {
|
|
2045
|
-
return notificationSchemas[method];
|
|
2046
|
-
}
|
|
2047
|
-
|
|
2048
|
-
//#endregion
|
|
2049
|
-
//#region ../core-internal/src/types/guards.ts
|
|
2050
|
-
/**
|
|
2051
|
-
* Validates and parses an unknown value as a JSON-RPC message.
|
|
2052
|
-
*
|
|
2053
|
-
* Use this to validate incoming messages in custom transport implementations.
|
|
2054
|
-
* Throws if the value does not conform to the JSON-RPC message schema.
|
|
2055
|
-
*
|
|
2056
|
-
* @param value - The value to validate (typically a parsed JSON object).
|
|
2057
|
-
* @returns The validated {@linkcode JSONRPCMessage}.
|
|
2058
|
-
* @throws If validation fails.
|
|
2059
|
-
*/
|
|
2060
|
-
function parseJSONRPCMessage(value) {
|
|
2061
|
-
return JSONRPCMessageSchema.parse(value);
|
|
2062
|
-
}
|
|
2063
|
-
const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
|
|
2064
|
-
const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
|
|
2065
|
-
/**
|
|
2066
|
-
* Checks if a value is a valid {@linkcode JSONRPCResultResponse}.
|
|
2067
|
-
* @param value - The value to check.
|
|
2068
|
-
*
|
|
2069
|
-
* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise.
|
|
2070
|
-
*/
|
|
2071
|
-
const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
|
|
2072
|
-
/**
|
|
2073
|
-
* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}.
|
|
2074
|
-
* @param value - The value to check.
|
|
2075
|
-
*
|
|
2076
|
-
* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise.
|
|
2077
|
-
*/
|
|
2078
|
-
const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
|
|
2079
|
-
/**
|
|
2080
|
-
* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response).
|
|
2081
|
-
* @param value - The value to check.
|
|
2082
|
-
*
|
|
2083
|
-
* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise.
|
|
2084
|
-
*/
|
|
2085
|
-
const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
|
|
2086
|
-
/**
|
|
2087
|
-
* Checks if a value is a valid {@linkcode CallToolResult}.
|
|
2088
|
-
* @param value - The value to check.
|
|
2089
|
-
*
|
|
2090
|
-
* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise.
|
|
2091
|
-
*/
|
|
2092
|
-
const isCallToolResult = (value) => {
|
|
2093
|
-
if (typeof value !== "object" || value === null || !("content" in value)) return false;
|
|
2094
|
-
return CallToolResultSchema.safeParse(value).success;
|
|
2095
|
-
};
|
|
2096
|
-
/**
|
|
2097
|
-
* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}.
|
|
2098
|
-
* @param value - The value to check.
|
|
2099
|
-
*
|
|
2100
|
-
* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise.
|
|
2101
|
-
*/
|
|
2102
|
-
const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
|
|
2103
|
-
const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;
|
|
2104
|
-
const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
|
|
2105
|
-
function assertCompleteRequestPrompt(request) {
|
|
2106
|
-
if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);
|
|
2107
|
-
}
|
|
2108
|
-
function assertCompleteRequestResourceTemplate(request) {
|
|
2109
|
-
if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
|
|
2110
|
-
}
|
|
2111
|
-
|
|
2112
|
-
//#endregion
|
|
2113
|
-
//#region ../core-internal/src/types/specTypeSchema.ts
|
|
2114
|
-
/**
|
|
2115
|
-
* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`.
|
|
2116
|
-
*
|
|
2117
|
-
* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no
|
|
2118
|
-
* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`,
|
|
2119
|
-
* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`).
|
|
2120
|
-
* Keeping the list explicit means new public spec types must be added here deliberately, and
|
|
2121
|
-
* internals never leak into `SpecTypeName`.
|
|
2122
|
-
*
|
|
2123
|
-
* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType`
|
|
2124
|
-
* (the bare name collides with the server package's `ResourceTemplate` class), so
|
|
2125
|
-
* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to
|
|
2126
|
-
* a type literally named `ResourceTemplate`.
|
|
2127
|
-
*/
|
|
2128
|
-
const SPEC_SCHEMA_KEYS = [
|
|
2129
|
-
"AnnotationsSchema",
|
|
2130
|
-
"AudioContentSchema",
|
|
2131
|
-
"BaseMetadataSchema",
|
|
2132
|
-
"BlobResourceContentsSchema",
|
|
2133
|
-
"BooleanSchemaSchema",
|
|
2134
|
-
"CallToolRequestSchema",
|
|
2135
|
-
"CallToolRequestParamsSchema",
|
|
2136
|
-
"CallToolResultSchema",
|
|
2137
|
-
"CancelledNotificationSchema",
|
|
2138
|
-
"CancelledNotificationParamsSchema",
|
|
2139
|
-
"CancelTaskRequestSchema",
|
|
2140
|
-
"CancelTaskResultSchema",
|
|
2141
|
-
"ClientCapabilitiesSchema",
|
|
2142
|
-
"ClientNotificationSchema",
|
|
2143
|
-
"ClientRequestSchema",
|
|
2144
|
-
"ClientResultSchema",
|
|
2145
|
-
"CompatibilityCallToolResultSchema",
|
|
2146
|
-
"CompleteRequestSchema",
|
|
2147
|
-
"CompleteRequestParamsSchema",
|
|
2148
|
-
"CompleteResultSchema",
|
|
2149
|
-
"ContentBlockSchema",
|
|
2150
|
-
"CreateMessageRequestSchema",
|
|
2151
|
-
"CreateMessageRequestParamsSchema",
|
|
2152
|
-
"CreateMessageResultSchema",
|
|
2153
|
-
"CreateMessageResultWithToolsSchema",
|
|
2154
|
-
"CreateTaskResultSchema",
|
|
2155
|
-
"CursorSchema",
|
|
2156
|
-
"DiscoverRequestSchema",
|
|
2157
|
-
"DiscoverResultSchema",
|
|
2158
|
-
"ElicitationCompleteNotificationSchema",
|
|
2159
|
-
"ElicitationCompleteNotificationParamsSchema",
|
|
2160
|
-
"ElicitRequestSchema",
|
|
2161
|
-
"ElicitRequestFormParamsSchema",
|
|
2162
|
-
"ElicitRequestParamsSchema",
|
|
2163
|
-
"ElicitRequestURLParamsSchema",
|
|
2164
|
-
"ElicitResultSchema",
|
|
2165
|
-
"EmbeddedResourceSchema",
|
|
2166
|
-
"EmptyResultSchema",
|
|
2167
|
-
"EnumSchemaSchema",
|
|
2168
|
-
"GetPromptRequestSchema",
|
|
2169
|
-
"GetPromptRequestParamsSchema",
|
|
2170
|
-
"GetPromptResultSchema",
|
|
2171
|
-
"GetTaskPayloadRequestSchema",
|
|
2172
|
-
"GetTaskPayloadResultSchema",
|
|
2173
|
-
"GetTaskRequestSchema",
|
|
2174
|
-
"GetTaskResultSchema",
|
|
2175
|
-
"IconSchema",
|
|
2176
|
-
"IconsSchema",
|
|
2177
|
-
"ImageContentSchema",
|
|
2178
|
-
"ImplementationSchema",
|
|
2179
|
-
"InitializedNotificationSchema",
|
|
2180
|
-
"InitializeRequestSchema",
|
|
2181
|
-
"InitializeRequestParamsSchema",
|
|
2182
|
-
"InitializeResultSchema",
|
|
2183
|
-
"JSONArraySchema",
|
|
2184
|
-
"JSONObjectSchema",
|
|
2185
|
-
"JSONRPCErrorResponseSchema",
|
|
2186
|
-
"JSONRPCMessageSchema",
|
|
2187
|
-
"JSONRPCNotificationSchema",
|
|
2188
|
-
"JSONRPCRequestSchema",
|
|
2189
|
-
"JSONRPCResponseSchema",
|
|
2190
|
-
"JSONRPCResultResponseSchema",
|
|
2191
|
-
"JSONValueSchema",
|
|
2192
|
-
"LegacyTitledEnumSchemaSchema",
|
|
2193
|
-
"ListPromptsRequestSchema",
|
|
2194
|
-
"ListPromptsResultSchema",
|
|
2195
|
-
"ListResourcesRequestSchema",
|
|
2196
|
-
"ListResourcesResultSchema",
|
|
2197
|
-
"ListResourceTemplatesRequestSchema",
|
|
2198
|
-
"ListResourceTemplatesResultSchema",
|
|
2199
|
-
"ListRootsRequestSchema",
|
|
2200
|
-
"ListRootsResultSchema",
|
|
2201
|
-
"ListTasksRequestSchema",
|
|
2202
|
-
"ListTasksResultSchema",
|
|
2203
|
-
"ListToolsRequestSchema",
|
|
2204
|
-
"ListToolsResultSchema",
|
|
2205
|
-
"LoggingLevelSchema",
|
|
2206
|
-
"LoggingMessageNotificationSchema",
|
|
2207
|
-
"LoggingMessageNotificationParamsSchema",
|
|
2208
|
-
"ModelHintSchema",
|
|
2209
|
-
"ModelPreferencesSchema",
|
|
2210
|
-
"MultiSelectEnumSchemaSchema",
|
|
2211
|
-
"NotificationSchema",
|
|
2212
|
-
"NumberSchemaSchema",
|
|
2213
|
-
"PaginatedRequestSchema",
|
|
2214
|
-
"PaginatedRequestParamsSchema",
|
|
2215
|
-
"PaginatedResultSchema",
|
|
2216
|
-
"PingRequestSchema",
|
|
2217
|
-
"PrimitiveSchemaDefinitionSchema",
|
|
2218
|
-
"ProgressSchema",
|
|
2219
|
-
"ProgressNotificationSchema",
|
|
2220
|
-
"ProgressNotificationParamsSchema",
|
|
2221
|
-
"ProgressTokenSchema",
|
|
2222
|
-
"PromptSchema",
|
|
2223
|
-
"PromptArgumentSchema",
|
|
2224
|
-
"PromptListChangedNotificationSchema",
|
|
2225
|
-
"PromptMessageSchema",
|
|
2226
|
-
"PromptReferenceSchema",
|
|
2227
|
-
"ReadResourceRequestSchema",
|
|
2228
|
-
"ReadResourceRequestParamsSchema",
|
|
2229
|
-
"ReadResourceResultSchema",
|
|
2230
|
-
"RelatedTaskMetadataSchema",
|
|
2231
|
-
"RequestSchema",
|
|
2232
|
-
"RequestIdSchema",
|
|
2233
|
-
"RequestMetaEnvelopeSchema",
|
|
2234
|
-
"RequestMetaSchema",
|
|
2235
|
-
"ResourceSchema",
|
|
2236
|
-
"ResourceContentsSchema",
|
|
2237
|
-
"ResourceLinkSchema",
|
|
2238
|
-
"ResourceListChangedNotificationSchema",
|
|
2239
|
-
"ResourceRequestParamsSchema",
|
|
2240
|
-
"ResourceTemplateSchema",
|
|
2241
|
-
"ResourceTemplateReferenceSchema",
|
|
2242
|
-
"ResourceUpdatedNotificationSchema",
|
|
2243
|
-
"ResourceUpdatedNotificationParamsSchema",
|
|
2244
|
-
"ResultSchema",
|
|
2245
|
-
"RoleSchema",
|
|
2246
|
-
"RootSchema",
|
|
2247
|
-
"RootsListChangedNotificationSchema",
|
|
2248
|
-
"SamplingContentSchema",
|
|
2249
|
-
"SamplingMessageSchema",
|
|
2250
|
-
"SamplingMessageContentBlockSchema",
|
|
2251
|
-
"ServerCapabilitiesSchema",
|
|
2252
|
-
"ServerNotificationSchema",
|
|
2253
|
-
"ServerRequestSchema",
|
|
2254
|
-
"ServerResultSchema",
|
|
2255
|
-
"SetLevelRequestSchema",
|
|
2256
|
-
"SetLevelRequestParamsSchema",
|
|
2257
|
-
"SingleSelectEnumSchemaSchema",
|
|
2258
|
-
"StringSchemaSchema",
|
|
2259
|
-
"SubscribeRequestSchema",
|
|
2260
|
-
"SubscribeRequestParamsSchema",
|
|
2261
|
-
"TaskSchema",
|
|
2262
|
-
"TaskAugmentedRequestParamsSchema",
|
|
2263
|
-
"TaskCreationParamsSchema",
|
|
2264
|
-
"TaskMetadataSchema",
|
|
2265
|
-
"TaskStatusSchema",
|
|
2266
|
-
"TaskStatusNotificationSchema",
|
|
2267
|
-
"TaskStatusNotificationParamsSchema",
|
|
2268
|
-
"TextContentSchema",
|
|
2269
|
-
"TextResourceContentsSchema",
|
|
2270
|
-
"TitledMultiSelectEnumSchemaSchema",
|
|
2271
|
-
"TitledSingleSelectEnumSchemaSchema",
|
|
2272
|
-
"ToolSchema",
|
|
2273
|
-
"ToolAnnotationsSchema",
|
|
2274
|
-
"ToolChoiceSchema",
|
|
2275
|
-
"ToolExecutionSchema",
|
|
2276
|
-
"ToolListChangedNotificationSchema",
|
|
2277
|
-
"ToolResultContentSchema",
|
|
2278
|
-
"ToolUseContentSchema",
|
|
2279
|
-
"UnsubscribeRequestSchema",
|
|
2280
|
-
"UnsubscribeRequestParamsSchema",
|
|
2281
|
-
"UntitledMultiSelectEnumSchemaSchema",
|
|
2282
|
-
"UntitledSingleSelectEnumSchemaSchema"
|
|
2283
|
-
];
|
|
2284
|
-
const authSchemas = {
|
|
2285
|
-
IdJagTokenExchangeResponseSchema,
|
|
2286
|
-
OAuthClientInformationFullSchema,
|
|
2287
|
-
OAuthClientInformationSchema,
|
|
2288
|
-
OAuthClientMetadataSchema,
|
|
2289
|
-
OAuthClientRegistrationErrorSchema,
|
|
2290
|
-
OAuthErrorResponseSchema,
|
|
2291
|
-
OAuthMetadataSchema,
|
|
2292
|
-
OAuthProtectedResourceMetadataSchema,
|
|
2293
|
-
OAuthTokenRevocationRequestSchema,
|
|
2294
|
-
OAuthTokensSchema,
|
|
2295
|
-
OpenIdProviderDiscoveryMetadataSchema,
|
|
2296
|
-
OpenIdProviderMetadataSchema
|
|
2297
|
-
};
|
|
2298
|
-
const _specTypeSchemas = {};
|
|
2299
|
-
const _isSpecType = {};
|
|
2300
|
-
function register(key, schema) {
|
|
2301
|
-
const name = key.slice(0, -6);
|
|
2302
|
-
_specTypeSchemas[name] = schema;
|
|
2303
|
-
_isSpecType[name] = (v) => schema.safeParse(v).success;
|
|
2304
|
-
}
|
|
2305
|
-
for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]);
|
|
2306
|
-
for (const [key, schema] of Object.entries(authSchemas)) register(key, schema);
|
|
2307
|
-
/**
|
|
2308
|
-
* Runtime validators for every MCP spec type, keyed by type name.
|
|
2309
|
-
*
|
|
2310
|
-
* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for
|
|
2311
|
-
* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from
|
|
2312
|
-
* storage that should be a `Tool`.
|
|
2313
|
-
*
|
|
2314
|
-
* Each entry implements the Standard Schema interface, so it composes with any
|
|
2315
|
-
* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead.
|
|
2316
|
-
*
|
|
2317
|
-
* @example
|
|
2318
|
-
* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage"
|
|
2319
|
-
* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted);
|
|
2320
|
-
* if (result.issues === undefined) {
|
|
2321
|
-
* // result.value is CallToolResult
|
|
2322
|
-
* }
|
|
2323
|
-
* ```
|
|
2324
|
-
*/
|
|
2325
|
-
const specTypeSchemas = Object.freeze(_specTypeSchemas);
|
|
2326
|
-
/**
|
|
2327
|
-
* Type predicates for every MCP spec type, keyed by type name.
|
|
2328
|
-
*
|
|
2329
|
-
* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and
|
|
2330
|
-
* transforms are applied), and narrows to that input type. For schemas with `.default()` or
|
|
2331
|
-
* `.preprocess()`, this may accept values that do not structurally match the named output type;
|
|
2332
|
-
* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use
|
|
2333
|
-
* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value.
|
|
2334
|
-
*
|
|
2335
|
-
* Each guard is a standalone function, so it can be passed directly as a callback.
|
|
2336
|
-
*
|
|
2337
|
-
* @example
|
|
2338
|
-
* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage"
|
|
2339
|
-
* if (isSpecType.ContentBlock(value)) {
|
|
2340
|
-
* // value is ContentBlock
|
|
2341
|
-
* }
|
|
2342
|
-
*
|
|
2343
|
-
* const blocks = mixed.filter(isSpecType.ContentBlock);
|
|
2344
|
-
* ```
|
|
2345
|
-
*/
|
|
2346
|
-
const isSpecType = Object.freeze(_isSpecType);
|
|
2347
|
-
|
|
2348
|
-
//#endregion
|
|
2349
|
-
//#region ../core-internal/src/util/standardSchema.ts
|
|
2350
|
-
/**
|
|
2351
|
-
* Standard Schema utilities for user-provided schemas.
|
|
2352
|
-
* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations.
|
|
2353
|
-
* @see https://standardschema.dev
|
|
2354
|
-
*/
|
|
2355
|
-
function isStandardSchema(schema) {
|
|
2356
|
-
if (schema == null) return false;
|
|
2357
|
-
const schemaType = typeof schema;
|
|
2358
|
-
if (schemaType !== "object" && schemaType !== "function") return false;
|
|
2359
|
-
if (!("~standard" in schema)) return false;
|
|
2360
|
-
return typeof schema["~standard"]?.validate === "function";
|
|
2361
|
-
}
|
|
2362
|
-
let warnedZodFallback = false;
|
|
2363
|
-
/**
|
|
2364
|
-
* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema.
|
|
2365
|
-
*
|
|
2366
|
-
* MCP requires `type: "object"` at the root of tool inputSchema/outputSchema and
|
|
2367
|
-
* prompt argument schemas. Zod's discriminated unions emit `{oneOf: [...]}` without
|
|
2368
|
-
* a top-level `type`, so this function defaults `type` to `"object"` when absent.
|
|
2369
|
-
*
|
|
2370
|
-
* Throws if the schema has an explicit non-object `type` (e.g. `z.string()`),
|
|
2371
|
-
* since that cannot satisfy the MCP spec.
|
|
2372
|
-
*/
|
|
2373
|
-
function standardSchemaToJsonSchema(schema, io = "input") {
|
|
2374
|
-
const std = schema["~standard"];
|
|
2375
|
-
let result;
|
|
2376
|
-
if (std.jsonSchema) result = std.jsonSchema[io]({ target: "draft-2020-12" });
|
|
2377
|
-
else if (std.vendor === "zod") {
|
|
2378
|
-
if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");
|
|
2379
|
-
if (!warnedZodFallback) {
|
|
2380
|
-
warnedZodFallback = true;
|
|
2381
|
-
console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");
|
|
2382
|
-
}
|
|
2383
|
-
result = z.toJSONSchema(schema, {
|
|
2384
|
-
target: "draft-2020-12",
|
|
2385
|
-
io
|
|
2386
|
-
});
|
|
2387
|
-
} else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);
|
|
2388
|
-
if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`);
|
|
2389
|
-
return {
|
|
2390
|
-
type: "object",
|
|
2391
|
-
...result
|
|
2392
|
-
};
|
|
2393
|
-
}
|
|
2394
|
-
function formatIssue(issue) {
|
|
2395
|
-
if (!issue.path?.length) return issue.message;
|
|
2396
|
-
return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`;
|
|
2397
|
-
}
|
|
2398
|
-
async function validateStandardSchema(schema, data) {
|
|
2399
|
-
const result = await schema["~standard"].validate(data);
|
|
2400
|
-
if (result.issues && result.issues.length > 0) return {
|
|
2401
|
-
success: false,
|
|
2402
|
-
error: result.issues.map((i) => formatIssue(i)).join(", ")
|
|
2403
|
-
};
|
|
2404
|
-
return {
|
|
2405
|
-
success: true,
|
|
2406
|
-
data: result.value
|
|
2407
|
-
};
|
|
2408
|
-
}
|
|
2409
|
-
function promptArgumentsFromStandardSchema(schema) {
|
|
2410
|
-
const jsonSchema = standardSchemaToJsonSchema(schema, "input");
|
|
2411
|
-
const properties = jsonSchema.properties || {};
|
|
2412
|
-
const required = jsonSchema.required || [];
|
|
2413
|
-
return Object.entries(properties).map(([name, prop]) => ({
|
|
2414
|
-
name,
|
|
2415
|
-
description: prop?.description,
|
|
2416
|
-
required: required.includes(name)
|
|
2417
|
-
}));
|
|
2418
|
-
}
|
|
2419
|
-
|
|
2420
|
-
//#endregion
|
|
2421
|
-
//#region ../core-internal/src/shared/protocol.ts
|
|
2422
|
-
/**
|
|
2423
|
-
* The default request timeout, in milliseconds.
|
|
2424
|
-
*/
|
|
2425
|
-
const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
|
|
2426
|
-
/**
|
|
2427
|
-
* Implements MCP protocol framing on top of a pluggable transport, including
|
|
2428
|
-
* features like request/response linking, notifications, and progress.
|
|
2429
|
-
*
|
|
2430
|
-
* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific
|
|
2431
|
-
* implementations most code should use.
|
|
2432
|
-
*/
|
|
2433
|
-
var Protocol = class {
|
|
2434
|
-
_transport;
|
|
2435
|
-
_requestMessageId = 0;
|
|
2436
|
-
_requestHandlers = /* @__PURE__ */ new Map();
|
|
2437
|
-
_requestHandlerAbortControllers = /* @__PURE__ */ new Map();
|
|
2438
|
-
_notificationHandlers = /* @__PURE__ */ new Map();
|
|
2439
|
-
_responseHandlers = /* @__PURE__ */ new Map();
|
|
2440
|
-
_progressHandlers = /* @__PURE__ */ new Map();
|
|
2441
|
-
_timeoutInfo = /* @__PURE__ */ new Map();
|
|
2442
|
-
_pendingDebouncedNotifications = /* @__PURE__ */ new Set();
|
|
2443
|
-
_supportedProtocolVersions;
|
|
2444
|
-
/**
|
|
2445
|
-
* Callback for when the connection is closed for any reason.
|
|
2446
|
-
*
|
|
2447
|
-
* This is invoked when {@linkcode Protocol.close | close()} is called as well.
|
|
2448
|
-
*/
|
|
2449
|
-
onclose;
|
|
2450
|
-
/**
|
|
2451
|
-
* Callback for when an error occurs.
|
|
2452
|
-
*
|
|
2453
|
-
* Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.
|
|
2454
|
-
*/
|
|
2455
|
-
onerror;
|
|
2456
|
-
/**
|
|
2457
|
-
* A handler to invoke for any request types that do not have their own handler installed.
|
|
2458
|
-
*/
|
|
2459
|
-
fallbackRequestHandler;
|
|
2460
|
-
/**
|
|
2461
|
-
* A handler to invoke for any notification types that do not have their own handler installed.
|
|
2462
|
-
*/
|
|
2463
|
-
fallbackNotificationHandler;
|
|
2464
|
-
constructor(_options) {
|
|
2465
|
-
this._options = _options;
|
|
2466
|
-
this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS;
|
|
2467
|
-
this.setNotificationHandler("notifications/cancelled", (notification) => {
|
|
2468
|
-
this._oncancel(notification);
|
|
2469
|
-
});
|
|
2470
|
-
this.setNotificationHandler("notifications/progress", (notification) => {
|
|
2471
|
-
this._onprogress(notification);
|
|
2472
|
-
});
|
|
2473
|
-
this.setRequestHandler("ping", (_request) => ({}));
|
|
2474
|
-
}
|
|
2475
|
-
async _oncancel(notification) {
|
|
2476
|
-
if (!notification.params.requestId) return;
|
|
2477
|
-
this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason);
|
|
2478
|
-
}
|
|
2479
|
-
_setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
|
|
2480
|
-
this._timeoutInfo.set(messageId, {
|
|
2481
|
-
timeoutId: setTimeout(onTimeout, timeout),
|
|
2482
|
-
startTime: Date.now(),
|
|
2483
|
-
timeout,
|
|
2484
|
-
maxTotalTimeout,
|
|
2485
|
-
resetTimeoutOnProgress,
|
|
2486
|
-
onTimeout
|
|
2487
|
-
});
|
|
2488
|
-
}
|
|
2489
|
-
_resetTimeout(messageId) {
|
|
2490
|
-
const info = this._timeoutInfo.get(messageId);
|
|
2491
|
-
if (!info) return false;
|
|
2492
|
-
const totalElapsed = Date.now() - info.startTime;
|
|
2493
|
-
if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
|
|
2494
|
-
this._timeoutInfo.delete(messageId);
|
|
2495
|
-
throw new SdkError(SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
|
|
2496
|
-
maxTotalTimeout: info.maxTotalTimeout,
|
|
2497
|
-
totalElapsed
|
|
2498
|
-
});
|
|
2499
|
-
}
|
|
2500
|
-
clearTimeout(info.timeoutId);
|
|
2501
|
-
info.timeoutId = setTimeout(info.onTimeout, info.timeout);
|
|
2502
|
-
return true;
|
|
2503
|
-
}
|
|
2504
|
-
_cleanupTimeout(messageId) {
|
|
2505
|
-
const info = this._timeoutInfo.get(messageId);
|
|
2506
|
-
if (info) {
|
|
2507
|
-
clearTimeout(info.timeoutId);
|
|
2508
|
-
this._timeoutInfo.delete(messageId);
|
|
2509
|
-
}
|
|
2510
|
-
}
|
|
2511
|
-
/**
|
|
2512
|
-
* Attaches to the given transport, starts it, and starts listening for messages.
|
|
2513
|
-
*
|
|
2514
|
-
* The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.
|
|
2515
|
-
*/
|
|
2516
|
-
async connect(transport) {
|
|
2517
|
-
this._transport = transport;
|
|
2518
|
-
const _onclose = this.transport?.onclose;
|
|
2519
|
-
this._transport.onclose = () => {
|
|
2520
|
-
try {
|
|
2521
|
-
_onclose?.();
|
|
2522
|
-
} finally {
|
|
2523
|
-
this._onclose();
|
|
2524
|
-
}
|
|
2525
|
-
};
|
|
2526
|
-
const _onerror = this.transport?.onerror;
|
|
2527
|
-
this._transport.onerror = (error) => {
|
|
2528
|
-
_onerror?.(error);
|
|
2529
|
-
this._onerror(error);
|
|
2530
|
-
};
|
|
2531
|
-
const _onmessage = this._transport?.onmessage;
|
|
2532
|
-
this._transport.onmessage = (message, extra) => {
|
|
2533
|
-
_onmessage?.(message, extra);
|
|
2534
|
-
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) this._onresponse(message);
|
|
2535
|
-
else if (isJSONRPCRequest(message)) this._onrequest(message, extra);
|
|
2536
|
-
else if (isJSONRPCNotification(message)) this._onnotification(message);
|
|
2537
|
-
else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`));
|
|
2538
|
-
};
|
|
2539
|
-
transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions);
|
|
2540
|
-
await this._transport.start();
|
|
2541
|
-
}
|
|
2542
|
-
_onclose() {
|
|
2543
|
-
const responseHandlers = this._responseHandlers;
|
|
2544
|
-
this._responseHandlers = /* @__PURE__ */ new Map();
|
|
2545
|
-
this._progressHandlers.clear();
|
|
2546
|
-
this._pendingDebouncedNotifications.clear();
|
|
2547
|
-
for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId);
|
|
2548
|
-
this._timeoutInfo.clear();
|
|
2549
|
-
const requestHandlerAbortControllers = this._requestHandlerAbortControllers;
|
|
2550
|
-
this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
|
|
2551
|
-
const error = new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed");
|
|
2552
|
-
this._transport = void 0;
|
|
2553
|
-
try {
|
|
2554
|
-
this.onclose?.();
|
|
2555
|
-
} finally {
|
|
2556
|
-
for (const handler of responseHandlers.values()) handler(error);
|
|
2557
|
-
for (const controller of requestHandlerAbortControllers.values()) controller.abort(error);
|
|
2558
|
-
}
|
|
2559
|
-
}
|
|
2560
|
-
_onerror(error) {
|
|
2561
|
-
this.onerror?.(error);
|
|
2562
|
-
}
|
|
2563
|
-
_onnotification(notification) {
|
|
2564
|
-
const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
|
|
2565
|
-
if (handler === void 0) return;
|
|
2566
|
-
Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`)));
|
|
2567
|
-
}
|
|
2568
|
-
_onrequest(request, extra) {
|
|
2569
|
-
const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
|
|
2570
|
-
const capturedTransport = this._transport;
|
|
2571
|
-
const sendNotification = (notification, options) => this.notification(notification, {
|
|
2572
|
-
...options,
|
|
2573
|
-
relatedRequestId: request.id
|
|
2574
|
-
});
|
|
2575
|
-
const sendRequest = (r, resultSchema, options) => this._requestWithSchema(r, resultSchema, {
|
|
2576
|
-
...options,
|
|
2577
|
-
relatedRequestId: request.id
|
|
2578
|
-
});
|
|
2579
|
-
if (handler === void 0) {
|
|
2580
|
-
const errorResponse = {
|
|
2581
|
-
jsonrpc: "2.0",
|
|
2582
|
-
id: request.id,
|
|
2583
|
-
error: {
|
|
2584
|
-
code: ProtocolErrorCode.MethodNotFound,
|
|
2585
|
-
message: "Method not found"
|
|
2586
|
-
}
|
|
2587
|
-
};
|
|
2588
|
-
capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`)));
|
|
2589
|
-
return;
|
|
2590
|
-
}
|
|
2591
|
-
const abortController = new AbortController();
|
|
2592
|
-
this._requestHandlerAbortControllers.set(request.id, abortController);
|
|
2593
|
-
const baseCtx = {
|
|
2594
|
-
sessionId: capturedTransport?.sessionId,
|
|
2595
|
-
mcpReq: {
|
|
2596
|
-
id: request.id,
|
|
2597
|
-
method: request.method,
|
|
2598
|
-
_meta: request.params?._meta,
|
|
2599
|
-
signal: abortController.signal,
|
|
2600
|
-
send: ((r, schemaOrOptions, maybeOptions) => {
|
|
2601
|
-
if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions);
|
|
2602
|
-
const resultSchema = getResultSchema(r.method);
|
|
2603
|
-
if (!resultSchema) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);
|
|
2604
|
-
return sendRequest(r, resultSchema, schemaOrOptions);
|
|
2605
|
-
}),
|
|
2606
|
-
notify: sendNotification
|
|
2607
|
-
},
|
|
2608
|
-
http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0
|
|
2609
|
-
};
|
|
2610
|
-
const ctx = this.buildContext(baseCtx, extra);
|
|
2611
|
-
Promise.resolve().then(() => handler(request, ctx)).then(async (result) => {
|
|
2612
|
-
if (abortController.signal.aborted) return;
|
|
2613
|
-
const response = {
|
|
2614
|
-
result,
|
|
2615
|
-
jsonrpc: "2.0",
|
|
2616
|
-
id: request.id
|
|
2617
|
-
};
|
|
2618
|
-
await capturedTransport?.send(response);
|
|
2619
|
-
}, async (error) => {
|
|
2620
|
-
if (abortController.signal.aborted) return;
|
|
2621
|
-
const errorResponse = {
|
|
2622
|
-
jsonrpc: "2.0",
|
|
2623
|
-
id: request.id,
|
|
2624
|
-
error: {
|
|
2625
|
-
code: Number.isSafeInteger(error["code"]) ? error["code"] : ProtocolErrorCode.InternalError,
|
|
2626
|
-
message: error.message ?? "Internal error",
|
|
2627
|
-
...error["data"] !== void 0 && { data: error["data"] }
|
|
2628
|
-
}
|
|
2629
|
-
};
|
|
2630
|
-
await capturedTransport?.send(errorResponse);
|
|
2631
|
-
}).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => {
|
|
2632
|
-
if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id);
|
|
2633
|
-
});
|
|
2634
|
-
}
|
|
2635
|
-
_onprogress(notification) {
|
|
2636
|
-
const { progressToken, ...params } = notification.params;
|
|
2637
|
-
const messageId = Number(progressToken);
|
|
2638
|
-
const handler = this._progressHandlers.get(messageId);
|
|
2639
|
-
if (!handler) {
|
|
2640
|
-
this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
|
|
2641
|
-
return;
|
|
2642
|
-
}
|
|
2643
|
-
const responseHandler = this._responseHandlers.get(messageId);
|
|
2644
|
-
const timeoutInfo = this._timeoutInfo.get(messageId);
|
|
2645
|
-
if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try {
|
|
2646
|
-
this._resetTimeout(messageId);
|
|
2647
|
-
} catch (error) {
|
|
2648
|
-
this._responseHandlers.delete(messageId);
|
|
2649
|
-
this._progressHandlers.delete(messageId);
|
|
2650
|
-
this._cleanupTimeout(messageId);
|
|
2651
|
-
responseHandler(error);
|
|
2652
|
-
return;
|
|
2653
|
-
}
|
|
2654
|
-
handler(params);
|
|
2655
|
-
}
|
|
2656
|
-
_onresponse(response) {
|
|
2657
|
-
const messageId = Number(response.id);
|
|
2658
|
-
const handler = this._responseHandlers.get(messageId);
|
|
2659
|
-
if (handler === void 0) {
|
|
2660
|
-
this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
|
|
2661
|
-
return;
|
|
2662
|
-
}
|
|
2663
|
-
this._responseHandlers.delete(messageId);
|
|
2664
|
-
this._cleanupTimeout(messageId);
|
|
2665
|
-
this._progressHandlers.delete(messageId);
|
|
2666
|
-
if (isJSONRPCResultResponse(response)) handler(response);
|
|
2667
|
-
else handler(ProtocolError.fromError(response.error.code, response.error.message, response.error.data));
|
|
2668
|
-
}
|
|
2669
|
-
get transport() {
|
|
2670
|
-
return this._transport;
|
|
2671
|
-
}
|
|
2672
|
-
/**
|
|
2673
|
-
* Closes the connection.
|
|
2674
|
-
*/
|
|
2675
|
-
async close() {
|
|
2676
|
-
await this._transport?.close();
|
|
2677
|
-
}
|
|
2678
|
-
request(request, schemaOrOptions, maybeOptions) {
|
|
2679
|
-
if (isStandardSchema(schemaOrOptions)) return this._requestWithSchema(request, schemaOrOptions, maybeOptions);
|
|
2680
|
-
const resultSchema = getResultSchema(request.method);
|
|
2681
|
-
if (!resultSchema) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);
|
|
2682
|
-
return this._requestWithSchema(request, resultSchema, schemaOrOptions);
|
|
2683
|
-
}
|
|
2684
|
-
/**
|
|
2685
|
-
* Sends a request and waits for a response, using the provided schema for validation.
|
|
2686
|
-
*
|
|
2687
|
-
* This is the internal implementation used by SDK methods that need to specify
|
|
2688
|
-
* a particular result schema (e.g., for compatibility schemas).
|
|
2689
|
-
*/
|
|
2690
|
-
_requestWithSchema(request, resultSchema, options) {
|
|
2691
|
-
const { relatedRequestId, resumptionToken, onresumptiontoken } = options ?? {};
|
|
2692
|
-
let onAbort;
|
|
2693
|
-
let cleanupMessageId;
|
|
2694
|
-
return new Promise((resolve, reject) => {
|
|
2695
|
-
const earlyReject = (error) => {
|
|
2696
|
-
reject(error);
|
|
2697
|
-
};
|
|
2698
|
-
if (!this._transport) {
|
|
2699
|
-
earlyReject(/* @__PURE__ */ new Error("Not connected"));
|
|
2700
|
-
return;
|
|
2701
|
-
}
|
|
2702
|
-
if (this._options?.enforceStrictCapabilities === true) try {
|
|
2703
|
-
this.assertCapabilityForMethod(request.method);
|
|
2704
|
-
} catch (error) {
|
|
2705
|
-
earlyReject(error);
|
|
2706
|
-
return;
|
|
2707
|
-
}
|
|
2708
|
-
options?.signal?.throwIfAborted();
|
|
2709
|
-
const messageId = this._requestMessageId++;
|
|
2710
|
-
cleanupMessageId = messageId;
|
|
2711
|
-
const jsonrpcRequest = {
|
|
2712
|
-
...request,
|
|
2713
|
-
jsonrpc: "2.0",
|
|
2714
|
-
id: messageId
|
|
2715
|
-
};
|
|
2716
|
-
if (options?.onprogress) {
|
|
2717
|
-
this._progressHandlers.set(messageId, options.onprogress);
|
|
2718
|
-
jsonrpcRequest.params = {
|
|
2719
|
-
...request.params,
|
|
2720
|
-
_meta: {
|
|
2721
|
-
...request.params?._meta,
|
|
2722
|
-
progressToken: messageId
|
|
2723
|
-
}
|
|
2724
|
-
};
|
|
2725
|
-
}
|
|
2726
|
-
let responseReceived = false;
|
|
2727
|
-
const cancel = (reason) => {
|
|
2728
|
-
if (responseReceived) return;
|
|
2729
|
-
this._progressHandlers.delete(messageId);
|
|
2730
|
-
this._transport?.send({
|
|
2731
|
-
jsonrpc: "2.0",
|
|
2732
|
-
method: "notifications/cancelled",
|
|
2733
|
-
params: {
|
|
2734
|
-
requestId: messageId,
|
|
2735
|
-
reason: String(reason)
|
|
2736
|
-
}
|
|
2737
|
-
}, {
|
|
2738
|
-
relatedRequestId,
|
|
2739
|
-
resumptionToken,
|
|
2740
|
-
onresumptiontoken
|
|
2741
|
-
}).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`)));
|
|
2742
|
-
reject(reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)));
|
|
2743
|
-
};
|
|
2744
|
-
this._responseHandlers.set(messageId, (response) => {
|
|
2745
|
-
if (options?.signal?.aborted) return;
|
|
2746
|
-
responseReceived = true;
|
|
2747
|
-
if (response instanceof Error) return reject(response);
|
|
2748
|
-
validateStandardSchema(resultSchema, response.result).then((parseResult) => {
|
|
2749
|
-
if (parseResult.success) resolve(parseResult.data);
|
|
2750
|
-
else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
|
|
2751
|
-
}, reject);
|
|
2752
|
-
});
|
|
2753
|
-
onAbort = () => cancel(options?.signal?.reason);
|
|
2754
|
-
options?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2755
|
-
const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
|
|
2756
|
-
const timeoutHandler = () => cancel(new SdkError(SdkErrorCode.RequestTimeout, "Request timed out", { timeout }));
|
|
2757
|
-
this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
|
|
2758
|
-
this._transport.send(jsonrpcRequest, {
|
|
2759
|
-
relatedRequestId,
|
|
2760
|
-
resumptionToken,
|
|
2761
|
-
onresumptiontoken
|
|
2762
|
-
}).catch((error) => {
|
|
2763
|
-
this._progressHandlers.delete(messageId);
|
|
2764
|
-
reject(error);
|
|
2765
|
-
});
|
|
2766
|
-
}).finally(() => {
|
|
2767
|
-
if (onAbort) options?.signal?.removeEventListener("abort", onAbort);
|
|
2768
|
-
if (cleanupMessageId !== void 0) {
|
|
2769
|
-
this._responseHandlers.delete(cleanupMessageId);
|
|
2770
|
-
this._cleanupTimeout(cleanupMessageId);
|
|
2771
|
-
}
|
|
2772
|
-
});
|
|
2773
|
-
}
|
|
2774
|
-
/**
|
|
2775
|
-
* Emits a notification, which is a one-way message that does not expect a response.
|
|
2776
|
-
*/
|
|
2777
|
-
async notification(notification, options) {
|
|
2778
|
-
if (!this._transport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected");
|
|
2779
|
-
this.assertNotificationCapability(notification.method);
|
|
2780
|
-
const jsonrpcNotification = {
|
|
2781
|
-
jsonrpc: "2.0",
|
|
2782
|
-
...notification
|
|
2783
|
-
};
|
|
2784
|
-
if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) {
|
|
2785
|
-
if (this._pendingDebouncedNotifications.has(notification.method)) return;
|
|
2786
|
-
this._pendingDebouncedNotifications.add(notification.method);
|
|
2787
|
-
Promise.resolve().then(() => {
|
|
2788
|
-
this._pendingDebouncedNotifications.delete(notification.method);
|
|
2789
|
-
if (!this._transport) return;
|
|
2790
|
-
this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error));
|
|
2791
|
-
});
|
|
2792
|
-
return;
|
|
2793
|
-
}
|
|
2794
|
-
await this._transport.send(jsonrpcNotification, options);
|
|
2795
|
-
}
|
|
2796
|
-
setRequestHandler(method, schemasOrHandler, maybeHandler) {
|
|
2797
|
-
this.assertRequestHandlerCapability(method);
|
|
2798
|
-
let stored;
|
|
2799
|
-
if (typeof schemasOrHandler === "function") {
|
|
2800
|
-
const schema = getRequestSchema(method);
|
|
2801
|
-
if (!schema) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);
|
|
2802
|
-
stored = (request, ctx) => Promise.resolve(schemasOrHandler(schema.parse(request), ctx));
|
|
2803
|
-
} else if (maybeHandler) stored = async (request, ctx) => {
|
|
2804
|
-
const userParams = { ...request.params };
|
|
2805
|
-
delete userParams._meta;
|
|
2806
|
-
const parsed = await validateStandardSchema(schemasOrHandler.params, userParams);
|
|
2807
|
-
if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`);
|
|
2808
|
-
return maybeHandler(parsed.data, ctx);
|
|
2809
|
-
};
|
|
2810
|
-
else throw new TypeError("setRequestHandler: handler is required");
|
|
2811
|
-
this._requestHandlers.set(method, this._wrapHandler(method, stored));
|
|
2812
|
-
}
|
|
2813
|
-
/**
|
|
2814
|
-
* Hook for subclasses to wrap a registered request handler with role-specific
|
|
2815
|
-
* validation or behavior (e.g. `Server` validates `tools/call` results, `Client`
|
|
2816
|
-
* validates `elicitation/create` mode and result). Runs for both the 2-arg and
|
|
2817
|
-
* 3-arg registration paths. The default implementation is identity.
|
|
2818
|
-
*
|
|
2819
|
-
* Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set.
|
|
2820
|
-
*/
|
|
2821
|
-
_wrapHandler(_method, handler) {
|
|
2822
|
-
return handler;
|
|
2823
|
-
}
|
|
2824
|
-
/**
|
|
2825
|
-
* Removes the request handler for the given method.
|
|
2826
|
-
*/
|
|
2827
|
-
removeRequestHandler(method) {
|
|
2828
|
-
this._requestHandlers.delete(method);
|
|
2829
|
-
}
|
|
2830
|
-
/**
|
|
2831
|
-
* Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
|
|
2832
|
-
*/
|
|
2833
|
-
assertCanSetRequestHandler(method) {
|
|
2834
|
-
if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`);
|
|
2835
|
-
}
|
|
2836
|
-
setNotificationHandler(method, schemasOrHandler, maybeHandler) {
|
|
2837
|
-
if (typeof schemasOrHandler === "function") {
|
|
2838
|
-
const schema = getNotificationSchema(method);
|
|
2839
|
-
if (!schema) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);
|
|
2840
|
-
this._notificationHandlers.set(method, (notification) => Promise.resolve(schemasOrHandler(schema.parse(notification))));
|
|
2841
|
-
return;
|
|
2842
|
-
}
|
|
2843
|
-
if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required");
|
|
2844
|
-
this._notificationHandlers.set(method, async (notification) => {
|
|
2845
|
-
const userParams = { ...notification.params };
|
|
2846
|
-
delete userParams._meta;
|
|
2847
|
-
const parsed = await validateStandardSchema(schemasOrHandler.params, userParams);
|
|
2848
|
-
if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`);
|
|
2849
|
-
await maybeHandler(parsed.data, notification);
|
|
2850
|
-
});
|
|
2851
|
-
}
|
|
2852
|
-
/**
|
|
2853
|
-
* Removes the notification handler for the given method.
|
|
2854
|
-
*/
|
|
2855
|
-
removeNotificationHandler(method) {
|
|
2856
|
-
this._notificationHandlers.delete(method);
|
|
2857
|
-
}
|
|
2858
|
-
};
|
|
2859
|
-
function isPlainObject(value) {
|
|
2860
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2861
|
-
}
|
|
2862
|
-
function mergeCapabilities(base, additional) {
|
|
2863
|
-
const result = { ...base };
|
|
2864
|
-
for (const key in additional) {
|
|
2865
|
-
const k = key;
|
|
2866
|
-
const addValue = additional[k];
|
|
2867
|
-
if (addValue === void 0) continue;
|
|
2868
|
-
const baseValue = result[k];
|
|
2869
|
-
result[k] = isPlainObject(baseValue) && isPlainObject(addValue) ? {
|
|
2870
|
-
...baseValue,
|
|
2871
|
-
...addValue
|
|
2872
|
-
} : addValue;
|
|
2873
|
-
}
|
|
2874
|
-
return result;
|
|
2875
|
-
}
|
|
2876
|
-
|
|
2877
|
-
//#endregion
|
|
2878
|
-
//#region ../core-internal/src/shared/stdio.ts
|
|
2879
|
-
const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
2880
|
-
/**
|
|
2881
|
-
* Buffers a continuous stdio stream into discrete JSON-RPC messages.
|
|
2882
|
-
*/
|
|
2883
|
-
var ReadBuffer = class {
|
|
2884
|
-
_buffer;
|
|
2885
|
-
_maxBufferSize;
|
|
2886
|
-
constructor(options) {
|
|
2887
|
-
this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
|
|
2888
|
-
}
|
|
2889
|
-
append(chunk) {
|
|
2890
|
-
if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) {
|
|
2891
|
-
this.clear();
|
|
2892
|
-
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
2893
|
-
}
|
|
2894
|
-
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
2895
|
-
}
|
|
2896
|
-
readMessage() {
|
|
2897
|
-
while (this._buffer) {
|
|
2898
|
-
const index = this._buffer.indexOf("\n");
|
|
2899
|
-
if (index === -1) return null;
|
|
2900
|
-
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
|
|
2901
|
-
this._buffer = this._buffer.subarray(index + 1);
|
|
2902
|
-
try {
|
|
2903
|
-
return deserializeMessage(line);
|
|
2904
|
-
} catch (error) {
|
|
2905
|
-
if (error instanceof SyntaxError) continue;
|
|
2906
|
-
throw error;
|
|
2907
|
-
}
|
|
2908
|
-
}
|
|
2909
|
-
return null;
|
|
2910
|
-
}
|
|
2911
|
-
clear() {
|
|
2912
|
-
this._buffer = void 0;
|
|
2913
|
-
}
|
|
2914
|
-
};
|
|
2915
|
-
function deserializeMessage(line) {
|
|
2916
|
-
return JSONRPCMessageSchema.parse(JSON.parse(line));
|
|
2917
|
-
}
|
|
2918
|
-
function serializeMessage(message) {
|
|
2919
|
-
return JSON.stringify(message) + "\n";
|
|
2920
|
-
}
|
|
2921
|
-
|
|
2922
|
-
//#endregion
|
|
2923
|
-
//#region ../core-internal/src/shared/toolNameValidation.ts
|
|
2924
|
-
/**
|
|
2925
|
-
* Tool name validation utilities according to SEP: Specify Format for Tool Names
|
|
2926
|
-
*
|
|
2927
|
-
* Tool names SHOULD be between 1 and 128 characters in length (inclusive).
|
|
2928
|
-
* Tool names are case-sensitive.
|
|
2929
|
-
* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits
|
|
2930
|
-
* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`).
|
|
2931
|
-
* Tool names SHOULD NOT contain spaces, commas, or other special characters.
|
|
2932
|
-
*
|
|
2933
|
-
* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names}
|
|
2934
|
-
*/
|
|
2935
|
-
/**
|
|
2936
|
-
* Regular expression for valid tool names according to SEP-986 specification
|
|
2937
|
-
*/
|
|
2938
|
-
const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
|
|
2939
|
-
/**
|
|
2940
|
-
* Validates a tool name according to the SEP specification
|
|
2941
|
-
* @param name - The tool name to validate
|
|
2942
|
-
* @returns An object containing validation result and any warnings
|
|
2943
|
-
*/
|
|
2944
|
-
function validateToolName(name) {
|
|
2945
|
-
const warnings = [];
|
|
2946
|
-
if (name.length === 0) return {
|
|
2947
|
-
isValid: false,
|
|
2948
|
-
warnings: ["Tool name cannot be empty"]
|
|
2949
|
-
};
|
|
2950
|
-
if (name.length > 128) return {
|
|
2951
|
-
isValid: false,
|
|
2952
|
-
warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
|
|
2953
|
-
};
|
|
2954
|
-
if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues");
|
|
2955
|
-
if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues");
|
|
2956
|
-
if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
|
|
2957
|
-
if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
|
|
2958
|
-
if (!TOOL_NAME_REGEX.test(name)) {
|
|
2959
|
-
const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
|
|
2960
|
-
warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");
|
|
2961
|
-
return {
|
|
2962
|
-
isValid: false,
|
|
2963
|
-
warnings
|
|
2964
|
-
};
|
|
2965
|
-
}
|
|
2966
|
-
return {
|
|
2967
|
-
isValid: true,
|
|
2968
|
-
warnings
|
|
2969
|
-
};
|
|
2970
|
-
}
|
|
2971
|
-
/**
|
|
2972
|
-
* Issues warnings for non-conforming tool names
|
|
2973
|
-
* @param name - The tool name that triggered the warnings
|
|
2974
|
-
* @param warnings - Array of warning messages
|
|
2975
|
-
*/
|
|
2976
|
-
function issueToolNameWarning(name, warnings) {
|
|
2977
|
-
if (warnings.length > 0) {
|
|
2978
|
-
console.warn(`Tool name validation warning for "${name}":`);
|
|
2979
|
-
for (const warning of warnings) console.warn(` - ${warning}`);
|
|
2980
|
-
console.warn("Tool registration will proceed, but this may cause compatibility issues.");
|
|
2981
|
-
console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
|
|
2982
|
-
console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
|
|
2983
|
-
}
|
|
2984
|
-
}
|
|
2985
|
-
/**
|
|
2986
|
-
* Validates a tool name and issues warnings for non-conforming names
|
|
2987
|
-
* @param name - The tool name to validate
|
|
2988
|
-
* @returns `true` if the name is valid, `false` otherwise
|
|
2989
|
-
*/
|
|
2990
|
-
function validateAndWarnToolName(name) {
|
|
2991
|
-
const result = validateToolName(name);
|
|
2992
|
-
issueToolNameWarning(name, result.warnings);
|
|
2993
|
-
return result.isValid;
|
|
2994
|
-
}
|
|
2995
|
-
|
|
2996
|
-
//#endregion
|
|
2997
|
-
//#region ../core-internal/src/shared/transport.ts
|
|
2998
|
-
/**
|
|
2999
|
-
* Normalizes `HeadersInit` to a plain `Record<string, string>` for manipulation.
|
|
3000
|
-
* Handles `Headers` objects, arrays of tuples, and plain objects.
|
|
3001
|
-
*/
|
|
3002
|
-
function normalizeHeaders(headers) {
|
|
3003
|
-
if (!headers) return {};
|
|
3004
|
-
if (headers instanceof Headers) return Object.fromEntries(headers.entries());
|
|
3005
|
-
if (Array.isArray(headers)) return Object.fromEntries(headers);
|
|
3006
|
-
return { ...headers };
|
|
3007
|
-
}
|
|
3008
|
-
/**
|
|
3009
|
-
* Creates a fetch function that includes base `RequestInit` options.
|
|
3010
|
-
* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.
|
|
3011
|
-
*
|
|
3012
|
-
* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`)
|
|
3013
|
-
* @param baseInit - The base `RequestInit` to merge with each request
|
|
3014
|
-
* @returns A wrapped fetch function that merges base options with call-specific options
|
|
3015
|
-
*/
|
|
3016
|
-
function createFetchWithInit(baseFetch = fetch, baseInit) {
|
|
3017
|
-
if (!baseInit) return baseFetch;
|
|
3018
|
-
return async (url, init) => {
|
|
3019
|
-
return baseFetch(url, {
|
|
3020
|
-
...baseInit,
|
|
3021
|
-
...init,
|
|
3022
|
-
headers: init?.headers ? {
|
|
3023
|
-
...normalizeHeaders(baseInit.headers),
|
|
3024
|
-
...normalizeHeaders(init.headers)
|
|
3025
|
-
} : baseInit.headers
|
|
3026
|
-
});
|
|
3027
|
-
};
|
|
3028
|
-
}
|
|
3029
|
-
|
|
3030
|
-
//#endregion
|
|
3031
|
-
//#region ../core-internal/src/shared/uriTemplate.ts
|
|
3032
|
-
const MAX_TEMPLATE_LENGTH = 1e6;
|
|
3033
|
-
const MAX_VARIABLE_LENGTH = 1e6;
|
|
3034
|
-
const MAX_TEMPLATE_EXPRESSIONS = 1e4;
|
|
3035
|
-
const MAX_REGEX_LENGTH = 1e6;
|
|
3036
|
-
var UriTemplate = class UriTemplate {
|
|
3037
|
-
/**
|
|
3038
|
-
* Returns true if the given string contains any URI template expressions.
|
|
3039
|
-
* A template expression is a sequence of characters enclosed in curly braces,
|
|
3040
|
-
* like `{foo}` or `{?bar}`.
|
|
3041
|
-
*/
|
|
3042
|
-
static isTemplate(str) {
|
|
3043
|
-
return /\{[^}\s]+\}/.test(str);
|
|
3044
|
-
}
|
|
3045
|
-
static validateLength(str, max, context) {
|
|
3046
|
-
if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);
|
|
3047
|
-
}
|
|
3048
|
-
template;
|
|
3049
|
-
parts;
|
|
3050
|
-
get variableNames() {
|
|
3051
|
-
return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names);
|
|
3052
|
-
}
|
|
3053
|
-
constructor(template) {
|
|
3054
|
-
UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template");
|
|
3055
|
-
this.template = template;
|
|
3056
|
-
this.parts = this.parse(template);
|
|
3057
|
-
}
|
|
3058
|
-
toString() {
|
|
3059
|
-
return this.template;
|
|
3060
|
-
}
|
|
3061
|
-
parse(template) {
|
|
3062
|
-
const parts = [];
|
|
3063
|
-
let currentText = "";
|
|
3064
|
-
let i = 0;
|
|
3065
|
-
let expressionCount = 0;
|
|
3066
|
-
while (i < template.length) if (template[i] === "{") {
|
|
3067
|
-
if (currentText) {
|
|
3068
|
-
parts.push(currentText);
|
|
3069
|
-
currentText = "";
|
|
3070
|
-
}
|
|
3071
|
-
const end = template.indexOf("}", i);
|
|
3072
|
-
if (end === -1) throw new Error("Unclosed template expression");
|
|
3073
|
-
expressionCount++;
|
|
3074
|
-
if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);
|
|
3075
|
-
const expr = template.slice(i + 1, end);
|
|
3076
|
-
const operator = this.getOperator(expr);
|
|
3077
|
-
const exploded = expr.includes("*");
|
|
3078
|
-
const names = this.getNames(expr);
|
|
3079
|
-
const name = names[0];
|
|
3080
|
-
for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name");
|
|
3081
|
-
parts.push({
|
|
3082
|
-
name,
|
|
3083
|
-
operator,
|
|
3084
|
-
names,
|
|
3085
|
-
exploded
|
|
3086
|
-
});
|
|
3087
|
-
i = end + 1;
|
|
3088
|
-
} else {
|
|
3089
|
-
currentText += template[i];
|
|
3090
|
-
i++;
|
|
3091
|
-
}
|
|
3092
|
-
if (currentText) parts.push(currentText);
|
|
3093
|
-
return parts;
|
|
3094
|
-
}
|
|
3095
|
-
getOperator(expr) {
|
|
3096
|
-
return [
|
|
3097
|
-
"+",
|
|
3098
|
-
"#",
|
|
3099
|
-
".",
|
|
3100
|
-
"/",
|
|
3101
|
-
"?",
|
|
3102
|
-
"&"
|
|
3103
|
-
].find((op) => expr.startsWith(op)) || "";
|
|
3104
|
-
}
|
|
3105
|
-
getNames(expr) {
|
|
3106
|
-
const operator = this.getOperator(expr);
|
|
3107
|
-
return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0);
|
|
3108
|
-
}
|
|
3109
|
-
encodeValue(value, operator) {
|
|
3110
|
-
UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value");
|
|
3111
|
-
if (operator === "+" || operator === "#") return encodeURI(value);
|
|
3112
|
-
return encodeURIComponent(value);
|
|
3113
|
-
}
|
|
3114
|
-
expandPart(part, variables) {
|
|
3115
|
-
if (part.operator === "?" || part.operator === "&") {
|
|
3116
|
-
const pairs = part.names.map((name) => {
|
|
3117
|
-
const value$1 = variables[name];
|
|
3118
|
-
if (value$1 === void 0) return "";
|
|
3119
|
-
return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`;
|
|
3120
|
-
}).filter((pair) => pair.length > 0);
|
|
3121
|
-
if (pairs.length === 0) return "";
|
|
3122
|
-
return (part.operator === "?" ? "?" : "&") + pairs.join("&");
|
|
3123
|
-
}
|
|
3124
|
-
if (part.names.length > 1) {
|
|
3125
|
-
const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0);
|
|
3126
|
-
if (values.length === 0) return "";
|
|
3127
|
-
return values.map((v) => Array.isArray(v) ? v[0] : v).join(",");
|
|
3128
|
-
}
|
|
3129
|
-
const value = variables[part.name];
|
|
3130
|
-
if (value === void 0) return "";
|
|
3131
|
-
const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator));
|
|
3132
|
-
switch (part.operator) {
|
|
3133
|
-
case "": return encoded.join(",");
|
|
3134
|
-
case "+": return encoded.join(",");
|
|
3135
|
-
case "#": return "#" + encoded.join(",");
|
|
3136
|
-
case ".": return "." + encoded.join(".");
|
|
3137
|
-
case "/": return "/" + encoded.join("/");
|
|
3138
|
-
default: return encoded.join(",");
|
|
3139
|
-
}
|
|
3140
|
-
}
|
|
3141
|
-
expand(variables) {
|
|
3142
|
-
let result = "";
|
|
3143
|
-
let hasQueryParam = false;
|
|
3144
|
-
for (const part of this.parts) {
|
|
3145
|
-
if (typeof part === "string") {
|
|
3146
|
-
result += part;
|
|
3147
|
-
continue;
|
|
3148
|
-
}
|
|
3149
|
-
const expanded = this.expandPart(part, variables);
|
|
3150
|
-
if (!expanded) continue;
|
|
3151
|
-
result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded;
|
|
3152
|
-
if (part.operator === "?" || part.operator === "&") hasQueryParam = true;
|
|
3153
|
-
}
|
|
3154
|
-
return result;
|
|
3155
|
-
}
|
|
3156
|
-
escapeRegExp(str) {
|
|
3157
|
-
return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
|
|
3158
|
-
}
|
|
3159
|
-
partToRegExp(part) {
|
|
3160
|
-
const patterns = [];
|
|
3161
|
-
for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name");
|
|
3162
|
-
if (part.operator === "?" || part.operator === "&") {
|
|
3163
|
-
for (let i = 0; i < part.names.length; i++) {
|
|
3164
|
-
const name$1 = part.names[i];
|
|
3165
|
-
const prefix = i === 0 ? "\\" + part.operator : "&";
|
|
3166
|
-
patterns.push({
|
|
3167
|
-
pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)",
|
|
3168
|
-
name: name$1
|
|
3169
|
-
});
|
|
3170
|
-
}
|
|
3171
|
-
return patterns;
|
|
3172
|
-
}
|
|
3173
|
-
let pattern;
|
|
3174
|
-
const name = part.name;
|
|
3175
|
-
switch (part.operator) {
|
|
3176
|
-
case "":
|
|
3177
|
-
pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)";
|
|
3178
|
-
break;
|
|
3179
|
-
case "+":
|
|
3180
|
-
case "#":
|
|
3181
|
-
pattern = "(.+)";
|
|
3182
|
-
break;
|
|
3183
|
-
case ".":
|
|
3184
|
-
pattern = String.raw`\.([^/,]+)`;
|
|
3185
|
-
break;
|
|
3186
|
-
case "/":
|
|
3187
|
-
pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)");
|
|
3188
|
-
break;
|
|
3189
|
-
default: pattern = "([^/]+)";
|
|
3190
|
-
}
|
|
3191
|
-
patterns.push({
|
|
3192
|
-
pattern,
|
|
3193
|
-
name
|
|
3194
|
-
});
|
|
3195
|
-
return patterns;
|
|
3196
|
-
}
|
|
3197
|
-
match(uri) {
|
|
3198
|
-
UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI");
|
|
3199
|
-
let pattern = "^";
|
|
3200
|
-
const names = [];
|
|
3201
|
-
for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part);
|
|
3202
|
-
else {
|
|
3203
|
-
const patterns = this.partToRegExp(part);
|
|
3204
|
-
for (const { pattern: partPattern, name } of patterns) {
|
|
3205
|
-
pattern += partPattern;
|
|
3206
|
-
names.push({
|
|
3207
|
-
name,
|
|
3208
|
-
exploded: part.exploded
|
|
3209
|
-
});
|
|
3210
|
-
}
|
|
3211
|
-
}
|
|
3212
|
-
pattern += "$";
|
|
3213
|
-
UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern");
|
|
3214
|
-
const regex = new RegExp(pattern);
|
|
3215
|
-
const match = uri.match(regex);
|
|
3216
|
-
if (!match) return null;
|
|
3217
|
-
const result = {};
|
|
3218
|
-
for (const [i, name_] of names.entries()) {
|
|
3219
|
-
const { name, exploded } = name_;
|
|
3220
|
-
const value = match[i + 1];
|
|
3221
|
-
const cleanName = name.replace("*", "");
|
|
3222
|
-
result[cleanName] = exploded && value.includes(",") ? value.split(",") : value;
|
|
3223
|
-
}
|
|
3224
|
-
return result;
|
|
3225
|
-
}
|
|
3226
|
-
};
|
|
3227
|
-
|
|
3228
|
-
//#endregion
|
|
3229
|
-
//#region ../core-internal/src/util/inMemory.ts
|
|
3230
|
-
/**
|
|
3231
|
-
* In-memory transport for creating clients and servers that talk to each other within the same process.
|
|
3232
|
-
*
|
|
3233
|
-
* Intended for testing and development. For production in-process connections, use
|
|
3234
|
-
* `StreamableHTTPClientTransport` against a local server URL.
|
|
3235
|
-
*/
|
|
3236
|
-
var InMemoryTransport = class InMemoryTransport {
|
|
3237
|
-
_otherTransport;
|
|
3238
|
-
_messageQueue = [];
|
|
3239
|
-
_closed = false;
|
|
3240
|
-
onclose;
|
|
3241
|
-
onerror;
|
|
3242
|
-
onmessage;
|
|
3243
|
-
sessionId;
|
|
3244
|
-
/**
|
|
3245
|
-
* Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}.
|
|
3246
|
-
*/
|
|
3247
|
-
static createLinkedPair() {
|
|
3248
|
-
const clientTransport = new InMemoryTransport();
|
|
3249
|
-
const serverTransport = new InMemoryTransport();
|
|
3250
|
-
clientTransport._otherTransport = serverTransport;
|
|
3251
|
-
serverTransport._otherTransport = clientTransport;
|
|
3252
|
-
return [clientTransport, serverTransport];
|
|
3253
|
-
}
|
|
3254
|
-
async start() {
|
|
3255
|
-
while (this._messageQueue.length > 0) {
|
|
3256
|
-
const queuedMessage = this._messageQueue.shift();
|
|
3257
|
-
this.onmessage?.(queuedMessage.message, queuedMessage.extra);
|
|
3258
|
-
}
|
|
3259
|
-
}
|
|
3260
|
-
async close() {
|
|
3261
|
-
if (this._closed) return;
|
|
3262
|
-
this._closed = true;
|
|
3263
|
-
const other = this._otherTransport;
|
|
3264
|
-
this._otherTransport = void 0;
|
|
3265
|
-
try {
|
|
3266
|
-
await other?.close();
|
|
3267
|
-
} finally {
|
|
3268
|
-
this.onclose?.();
|
|
3269
|
-
}
|
|
3270
|
-
}
|
|
3271
|
-
/**
|
|
3272
|
-
* Sends a message with optional auth info.
|
|
3273
|
-
* This is useful for testing authentication scenarios.
|
|
3274
|
-
*/
|
|
3275
|
-
async send(message, options) {
|
|
3276
|
-
if (!this._otherTransport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected");
|
|
3277
|
-
if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo });
|
|
3278
|
-
else this._otherTransport._messageQueue.push({
|
|
3279
|
-
message,
|
|
3280
|
-
extra: { authInfo: options?.authInfo }
|
|
3281
|
-
});
|
|
3282
|
-
}
|
|
3283
|
-
};
|
|
3284
|
-
|
|
3285
|
-
//#endregion
|
|
3286
|
-
//#region ../core-internal/src/util/schema.ts
|
|
3287
|
-
/**
|
|
3288
|
-
* Internal Zod schema utilities for protocol handling.
|
|
3289
|
-
* These are used internally by the SDK for protocol message validation.
|
|
3290
|
-
*/
|
|
3291
|
-
/**
|
|
3292
|
-
* Parses data against a Zod schema (synchronous).
|
|
3293
|
-
* Returns a discriminated union with success/error.
|
|
3294
|
-
*/
|
|
3295
|
-
function parseSchema(schema, data) {
|
|
3296
|
-
return z.safeParse(schema, data);
|
|
3297
|
-
}
|
|
3298
|
-
|
|
3299
|
-
//#endregion
|
|
3300
|
-
//#region ../core-internal/src/util/zodCompat.ts
|
|
3301
|
-
/**
|
|
3302
|
-
* Zod-specific helpers for the v1-compat raw-shape shorthand on
|
|
3303
|
-
* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so
|
|
3304
|
-
* that file stays library-agnostic per the Standard Schema spec.
|
|
3305
|
-
*/
|
|
3306
|
-
function isZodV4Schema(v) {
|
|
3307
|
-
return typeof v === "object" && v !== null && "_zod" in v;
|
|
3308
|
-
}
|
|
3309
|
-
function looksLikeZodV3(v) {
|
|
3310
|
-
return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string";
|
|
3311
|
-
}
|
|
3312
|
-
/**
|
|
3313
|
-
* Detects a "raw shape" — a plain object whose values are Zod field schemas,
|
|
3314
|
-
* e.g. `{ name: z.string() }`. Powers the auto-wrap in
|
|
3315
|
-
* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only
|
|
3316
|
-
* Zod values are supported.
|
|
3317
|
-
*
|
|
3318
|
-
* @internal
|
|
3319
|
-
*/
|
|
3320
|
-
function isZodRawShape(obj) {
|
|
3321
|
-
if (typeof obj !== "object" || obj === null) return false;
|
|
3322
|
-
if (isStandardSchema(obj)) return false;
|
|
3323
|
-
const proto = Object.getPrototypeOf(obj);
|
|
3324
|
-
if (proto !== Object.prototype && proto !== null) return false;
|
|
3325
|
-
return Object.values(obj).every((v) => isZodV4Schema(v));
|
|
3326
|
-
}
|
|
3327
|
-
/**
|
|
3328
|
-
* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape
|
|
3329
|
-
* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}.
|
|
3330
|
-
* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a
|
|
3331
|
-
* uniform schema type; already-wrapped schemas pass through unchanged.
|
|
3332
|
-
*
|
|
3333
|
-
* @internal
|
|
3334
|
-
*/
|
|
3335
|
-
function normalizeRawShapeSchema(schema) {
|
|
3336
|
-
if (schema === void 0) return void 0;
|
|
3337
|
-
if (isZodRawShape(schema)) return z.object(schema);
|
|
3338
|
-
if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");
|
|
3339
|
-
if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");
|
|
3340
|
-
return schema;
|
|
3341
|
-
}
|
|
3342
|
-
|
|
3343
|
-
//#endregion
|
|
3344
|
-
//#region ../core-internal/src/validators/fromJsonSchema.ts
|
|
3345
|
-
/**
|
|
3346
|
-
* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be
|
|
3347
|
-
* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON
|
|
3348
|
-
* Schema (e.g. from TypeBox, or hand-written) and want to register it without going
|
|
3349
|
-
* through a Standard Schema library.
|
|
3350
|
-
*
|
|
3351
|
-
* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript
|
|
3352
|
-
* types attached). Cast at the call site, or use the generic `fromJsonSchema<MyType>(...)`.
|
|
3353
|
-
*
|
|
3354
|
-
* @param schema - A JSON Schema object describing the expected shape
|
|
3355
|
-
* @param validator - A validator provider. When importing `fromJsonSchema` from
|
|
3356
|
-
* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate
|
|
3357
|
-
* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes).
|
|
3358
|
-
*
|
|
3359
|
-
* @example
|
|
3360
|
-
* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage"
|
|
3361
|
-
* const inputSchema = fromJsonSchema<{ name: string }>(
|
|
3362
|
-
* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
|
|
3363
|
-
* validator
|
|
3364
|
-
* );
|
|
3365
|
-
* // Use with server.registerTool('greet', { inputSchema }, handler)
|
|
3366
|
-
* ```
|
|
3367
|
-
*/
|
|
3368
|
-
function fromJsonSchema(schema, validator) {
|
|
3369
|
-
const check = validator.getValidator(schema);
|
|
3370
|
-
return { "~standard": {
|
|
3371
|
-
version: 1,
|
|
3372
|
-
vendor: "mcp",
|
|
3373
|
-
jsonSchema: {
|
|
3374
|
-
input: () => schema,
|
|
3375
|
-
output: () => schema
|
|
3376
|
-
},
|
|
3377
|
-
validate: (data) => {
|
|
3378
|
-
const result = check(data);
|
|
3379
|
-
return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] };
|
|
3380
|
-
}
|
|
3381
|
-
} };
|
|
3382
|
-
}
|
|
3383
|
-
|
|
3384
|
-
//#endregion
|
|
3385
|
-
export { LATEST_PROTOCOL_VERSION as $, isTaskAugmentedRequestParams as A, LoggingLevelSchema as B, isInitializeRequest as C, isJSONRPCRequest as D, isJSONRPCNotification as E, CreateMessageResultWithToolsSchema as F, BAGGAGE_META_KEY as G, UnsupportedProtocolVersionError as H, ElicitResultSchema as I, DEFAULT_NEGOTIATED_PROTOCOL_VERSION as J, CLIENT_CAPABILITIES_META_KEY as K, EmptyResultSchema as L, CallToolRequestSchema as M, CallToolResultSchema as N, isJSONRPCResponse as O, CreateMessageResultSchema as P, JSONRPC_VERSION as Q, JSONRPCMessageSchema as R, isCallToolResult as S, isJSONRPCErrorResponse as T, UrlElicitationRequiredError as U, ProtocolError as V, ProtocolErrorCode as W, INVALID_PARAMS as X, INTERNAL_ERROR as Y, INVALID_REQUEST as Z, validateStandardSchema as _, UriTemplate as a, SUPPORTED_PROTOCOL_VERSIONS as at, assertCompleteRequestPrompt as b, ReadBuffer as c, getDisplayName as ct, serializeMessage as d, SdkError as dt, LOG_LEVEL_META_KEY as et, DEFAULT_REQUEST_TIMEOUT_MSEC as f, SdkErrorCode as ft, standardSchemaToJsonSchema as g, promptArgumentsFromStandardSchema as h, OAuthErrorCode as ht, InMemoryTransport as i, RELATED_TASK_META_KEY as it, parseJSONRPCMessage as j, isJSONRPCResultResponse as k, STDIO_DEFAULT_MAX_BUFFER_SIZE as l, checkResourceAllowed as lt, mergeCapabilities as m, OAuthError as mt, normalizeRawShapeSchema as n, PARSE_ERROR as nt, createFetchWithInit as o, TRACEPARENT_META_KEY as ot, Protocol as p, SdkHttpError as pt, CLIENT_INFO_META_KEY as q, parseSchema as r, PROTOCOL_VERSION_META_KEY as rt, validateAndWarnToolName as s, TRACESTATE_META_KEY as st, fromJsonSchema as t, METHOD_NOT_FOUND as tt, deserializeMessage as u, resourceUrlFromServerUrl as ut, isSpecType as v, isInitializedNotification as w, assertCompleteRequestResourceTemplate as x, specTypeSchemas as y, ListRootsResultSchema as z };
|
|
3386
|
-
//# sourceMappingURL=src-Pa1iAvsj.mjs.map
|