@dev-crowagent/pigeon-mcp 0.0.0-stage → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +143 -0
  2. package/README.md +256 -2
  3. package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
  4. package/dist/auth-provider.d.ts +19 -0
  5. package/dist/auth-provider.d.ts.map +1 -0
  6. package/dist/auth-provider.js +2 -0
  7. package/dist/auth-provider.js.map +1 -0
  8. package/dist/client.d.ts +193 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +747 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/config-schema.d.ts +105 -0
  13. package/dist/config-schema.d.ts.map +1 -0
  14. package/dist/config-schema.js +101 -0
  15. package/dist/config-schema.js.map +1 -0
  16. package/dist/config.d.ts +57 -0
  17. package/dist/config.d.ts.map +1 -0
  18. package/dist/config.js +160 -0
  19. package/dist/config.js.map +1 -0
  20. package/dist/index.d.ts +16 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +14 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/input-schema.d.ts +7 -0
  25. package/dist/input-schema.d.ts.map +1 -0
  26. package/dist/input-schema.js +13 -0
  27. package/dist/input-schema.js.map +1 -0
  28. package/dist/model-content.d.ts +19 -0
  29. package/dist/model-content.d.ts.map +1 -0
  30. package/dist/model-content.js +67 -0
  31. package/dist/model-content.js.map +1 -0
  32. package/dist/naming.d.ts +23 -0
  33. package/dist/naming.d.ts.map +1 -0
  34. package/dist/naming.js +37 -0
  35. package/dist/naming.js.map +1 -0
  36. package/dist/oauth/auth-provider.d.ts +52 -0
  37. package/dist/oauth/auth-provider.d.ts.map +1 -0
  38. package/dist/oauth/auth-provider.js +97 -0
  39. package/dist/oauth/auth-provider.js.map +1 -0
  40. package/dist/oauth/callback.d.ts +48 -0
  41. package/dist/oauth/callback.d.ts.map +1 -0
  42. package/dist/oauth/callback.js +121 -0
  43. package/dist/oauth/callback.js.map +1 -0
  44. package/dist/oauth/client-settings.d.ts +107 -0
  45. package/dist/oauth/client-settings.d.ts.map +1 -0
  46. package/dist/oauth/client-settings.js +114 -0
  47. package/dist/oauth/client-settings.js.map +1 -0
  48. package/dist/oauth/discovery.d.ts +30 -0
  49. package/dist/oauth/discovery.d.ts.map +1 -0
  50. package/dist/oauth/discovery.js +156 -0
  51. package/dist/oauth/discovery.js.map +1 -0
  52. package/dist/oauth/errors.d.ts +32 -0
  53. package/dist/oauth/errors.d.ts.map +1 -0
  54. package/dist/oauth/errors.js +58 -0
  55. package/dist/oauth/errors.js.map +1 -0
  56. package/dist/oauth/flow.d.ts +112 -0
  57. package/dist/oauth/flow.d.ts.map +1 -0
  58. package/dist/oauth/flow.js +360 -0
  59. package/dist/oauth/flow.js.map +1 -0
  60. package/dist/oauth/index.d.ts +11 -0
  61. package/dist/oauth/index.d.ts.map +1 -0
  62. package/dist/oauth/index.js +9 -0
  63. package/dist/oauth/index.js.map +1 -0
  64. package/dist/oauth/loopback.d.ts +51 -0
  65. package/dist/oauth/loopback.d.ts.map +1 -0
  66. package/dist/oauth/loopback.js +98 -0
  67. package/dist/oauth/loopback.js.map +1 -0
  68. package/dist/oauth/provider.d.ts +62 -0
  69. package/dist/oauth/provider.d.ts.map +1 -0
  70. package/dist/oauth/provider.js +118 -0
  71. package/dist/oauth/provider.js.map +1 -0
  72. package/dist/oauth/sign-in.d.ts +73 -0
  73. package/dist/oauth/sign-in.d.ts.map +1 -0
  74. package/dist/oauth/sign-in.js +182 -0
  75. package/dist/oauth/sign-in.js.map +1 -0
  76. package/dist/oauth/types.d.ts +83 -0
  77. package/dist/oauth/types.d.ts.map +1 -0
  78. package/dist/oauth/types.js +113 -0
  79. package/dist/oauth/types.js.map +1 -0
  80. package/dist/output-limit.d.ts +24 -0
  81. package/dist/output-limit.d.ts.map +1 -0
  82. package/dist/output-limit.js +58 -0
  83. package/dist/output-limit.js.map +1 -0
  84. package/dist/protocol/content.d.ts +83 -0
  85. package/dist/protocol/content.d.ts.map +1 -0
  86. package/dist/protocol/content.js +41 -0
  87. package/dist/protocol/content.js.map +1 -0
  88. package/dist/protocol/http-headers.d.ts +31 -0
  89. package/dist/protocol/http-headers.d.ts.map +1 -0
  90. package/dist/protocol/http-headers.js +129 -0
  91. package/dist/protocol/http-headers.js.map +1 -0
  92. package/dist/protocol/jsonrpc.d.ts +64 -0
  93. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  94. package/dist/protocol/jsonrpc.js +74 -0
  95. package/dist/protocol/jsonrpc.js.map +1 -0
  96. package/dist/protocol/stateless.d.ts +47 -0
  97. package/dist/protocol/stateless.d.ts.map +1 -0
  98. package/dist/protocol/stateless.js +102 -0
  99. package/dist/protocol/stateless.js.map +1 -0
  100. package/dist/protocol/types.d.ts +156 -0
  101. package/dist/protocol/types.d.ts.map +1 -0
  102. package/dist/protocol/types.js +12 -0
  103. package/dist/protocol/types.js.map +1 -0
  104. package/dist/result-schema.d.ts +10 -0
  105. package/dist/result-schema.d.ts.map +1 -0
  106. package/dist/result-schema.js +78 -0
  107. package/dist/result-schema.js.map +1 -0
  108. package/dist/testing/index.d.ts +2 -0
  109. package/dist/testing/index.d.ts.map +1 -0
  110. package/dist/testing/index.js +2 -0
  111. package/dist/testing/index.js.map +1 -0
  112. package/dist/transports/in-memory.d.ts +19 -0
  113. package/dist/transports/in-memory.d.ts.map +1 -0
  114. package/dist/transports/in-memory.js +50 -0
  115. package/dist/transports/in-memory.js.map +1 -0
  116. package/dist/transports/lines.d.ts +34 -0
  117. package/dist/transports/lines.d.ts.map +1 -0
  118. package/dist/transports/lines.js +85 -0
  119. package/dist/transports/lines.js.map +1 -0
  120. package/dist/transports/pipe.d.ts +49 -0
  121. package/dist/transports/pipe.d.ts.map +1 -0
  122. package/dist/transports/pipe.js +96 -0
  123. package/dist/transports/pipe.js.map +1 -0
  124. package/dist/transports/stdio.d.ts +29 -0
  125. package/dist/transports/stdio.d.ts.map +1 -0
  126. package/dist/transports/stdio.js +170 -0
  127. package/dist/transports/stdio.js.map +1 -0
  128. package/dist/transports/streamable-http.d.ts +113 -0
  129. package/dist/transports/streamable-http.d.ts.map +1 -0
  130. package/dist/transports/streamable-http.js +586 -0
  131. package/dist/transports/streamable-http.js.map +1 -0
  132. package/dist/transports/transport.d.ts +48 -0
  133. package/dist/transports/transport.d.ts.map +1 -0
  134. package/dist/transports/transport.js +38 -0
  135. package/dist/transports/transport.js.map +1 -0
  136. package/package.json +65 -5
package/dist/client.js ADDED
@@ -0,0 +1,747 @@
1
+ import { toolHeaderBindings, toolParamHeaders } from "./protocol/http-headers.js";
2
+ import { isJsonRpcId, isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isObject, JSON_RPC_ERROR_CODES, McpAbortError, McpConnectionClosedError, McpError, McpTimeoutError, normalizeOwnRequestId, toError, } from "./protocol/jsonrpc.js";
3
+ import { HEADER_MISMATCH_ERROR_CODE, readStatelessResult, readSubscriptionFilter, STATELESS_ERROR_CODES, subscriptionIdOf, validateDiscoverResult, withStatelessMeta, } from "./protocol/stateless.js";
4
+ import { LATEST_PROTOCOL_VERSION, STATELESS_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "./protocol/types.js";
5
+ import { jsonRpcErrorIn, McpHttpError } from "./transports/streamable-http.js";
6
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
7
+ const MAX_LIST_PAGES = 1_000;
8
+ /**
9
+ * Bounds `server/discover` after a rejected `initialize`. The server already answered once, so a
10
+ * stateless server answers quickly; a legacy server that ignores the request must not hold up the error.
11
+ */
12
+ const DISCOVER_AFTER_INITIALIZE_TIMEOUT_MS = 10_000;
13
+ /**
14
+ * Rounds of input a server may ask for before one request completes. Servers may ask again until they
15
+ * have what they need; this bounds a server that never does.
16
+ */
17
+ const MAX_INPUT_ROUNDS = 16;
18
+ /** Methods whose results may ask for input in MCP 2026-07-28 (multi round-trip requests). */
19
+ const INPUT_METHODS = new Set(["tools/call", "resources/read", "prompts/get"]);
20
+ /**
21
+ * `connect()` failed after the server rejected `initialize`: `server/discover` on the same connection
22
+ * failed too. Some stdio servers that only speak the stateless revision exit after rejecting
23
+ * `initialize`, or refuse it on a process that saw `initialize`; a new process connected with
24
+ * `protocol: "2026-07-28"` may still work.
25
+ */
26
+ export class McpInitializeRejectedError extends Error {
27
+ /** The server's answer to `initialize`. */
28
+ rejection;
29
+ /** Why `server/discover` failed. */
30
+ discoverError;
31
+ constructor(message, rejection, discoverError) {
32
+ super(message);
33
+ this.name = "McpInitializeRejectedError";
34
+ this.rejection = rejection;
35
+ this.discoverError = discoverError;
36
+ }
37
+ }
38
+ function validateInitializeResult(value) {
39
+ if (!isObject(value) ||
40
+ typeof value.protocolVersion !== "string" ||
41
+ !isObject(value.capabilities) ||
42
+ !isObject(value.serverInfo) ||
43
+ typeof value.serverInfo.name !== "string" ||
44
+ typeof value.serverInfo.version !== "string" ||
45
+ (value.instructions !== undefined && typeof value.instructions !== "string")) {
46
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP initialize result");
47
+ }
48
+ return value;
49
+ }
50
+ function invalid(message) {
51
+ return new McpError(JSON_RPC_ERROR_CODES.invalidRequest, message);
52
+ }
53
+ /** One page of a paginated list: the items under `key`, each checked by `isItem`. */
54
+ function validateListPage(method, key, value, isItem) {
55
+ const items = isObject(value) ? value[key] : undefined;
56
+ if (!isObject(value) || !Array.isArray(items))
57
+ throw invalid(`Invalid MCP ${method} result`);
58
+ for (const item of items) {
59
+ if (!isObject(item) || !isItem(item))
60
+ throw invalid(`Invalid entry in MCP ${method} result`);
61
+ }
62
+ // Some servers end pagination with `null` or `""` instead of omitting the cursor.
63
+ const nextCursor = value.nextCursor === null || value.nextCursor === "" ? undefined : value.nextCursor;
64
+ if (nextCursor !== undefined && typeof nextCursor !== "string")
65
+ throw invalid(`Invalid MCP ${method} cursor`);
66
+ return { items, ...(nextCursor === undefined ? {} : { nextCursor }) };
67
+ }
68
+ const isTool = (tool) => typeof tool.name === "string" && isObject(tool.inputSchema);
69
+ // `name` is required by the spec, but some servers omit it; the URI stands in.
70
+ const isResource = (resource) => typeof resource.uri === "string" && (resource.name === undefined || typeof resource.name === "string");
71
+ const isResourceTemplate = (template) => typeof template.uriTemplate === "string" && (template.name === undefined || typeof template.name === "string");
72
+ function toResource(item) {
73
+ return { ...item, name: item.name ?? item.uri };
74
+ }
75
+ function toResourceTemplate(item) {
76
+ return { ...item, name: item.name ?? item.uriTemplate };
77
+ }
78
+ function pageCursor(page) {
79
+ return page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor };
80
+ }
81
+ function validateReadResourceResult(value) {
82
+ if (!isObject(value) || !Array.isArray(value.contents))
83
+ throw invalid("Invalid MCP resources/read result");
84
+ for (const contents of value.contents) {
85
+ if (!isObject(contents) ||
86
+ typeof contents.uri !== "string" ||
87
+ (typeof contents.text !== "string" && typeof contents.blob !== "string")) {
88
+ throw invalid("Invalid contents in MCP resources/read result");
89
+ }
90
+ }
91
+ return value;
92
+ }
93
+ /**
94
+ * `content` is required by the spec, but servers that only return `structuredContent` omit it (the SDK defaults it too).
95
+ * `structuredContent` may be any JSON value, as MCP 2026-07-28 allows.
96
+ */
97
+ function validateCallToolResult(value) {
98
+ if (!isObject(value) || (value.content !== undefined && !Array.isArray(value.content))) {
99
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP tools/call result");
100
+ }
101
+ return (value.content === undefined ? { ...value, content: [] } : value);
102
+ }
103
+ /**
104
+ * What a failed `initialize` tells about the server. Servers that only speak the stateless revision
105
+ * reject it with a JSON-RPC error, over HTTP with a 400: `stateless` when the error has a code only that
106
+ * revision uses, `unknown` for other such rejections, and undefined for failures that are no answer
107
+ * (timeouts, closed connections, authorization).
108
+ */
109
+ function initializeRejection(error) {
110
+ const code = error instanceof McpError
111
+ ? error.code
112
+ : error instanceof McpHttpError && error.status === 400
113
+ ? jsonRpcErrorIn(error.body)?.code
114
+ : null;
115
+ if (code === null)
116
+ return undefined;
117
+ return code !== undefined && STATELESS_ERROR_CODES.includes(code) ? "stateless" : "unknown";
118
+ }
119
+ /** The connection closed under a request: the transport closed, or the stdio server was gone when written to. */
120
+ function isConnectionLost(error) {
121
+ // Node's write errors are the trust boundary here: `code` is all they carry.
122
+ return (error instanceof McpConnectionClosedError || (error instanceof Error && "code" in error && error.code === "EPIPE"));
123
+ }
124
+ /** Thrown for an `initialize` answered with the stateless revision, which has no handshake. */
125
+ class StatelessInitializeError extends Error {
126
+ }
127
+ export class McpClient {
128
+ options;
129
+ state = "idle";
130
+ transport;
131
+ nextRequestId = 1;
132
+ serverInfoValue;
133
+ serverCapabilitiesValue;
134
+ instructionsValue;
135
+ protocolVersionValue;
136
+ /** Whether the connection speaks the stateless revision: every request carries {@link meta}. */
137
+ stateless = false;
138
+ meta;
139
+ /** `Mcp-Param-*` bindings of the tools last listed, for servers on the stateless revision. */
140
+ toolHeaders = new Map();
141
+ /** Open `subscriptions/listen` requests by id. */
142
+ subscriptions = new Map();
143
+ pending = new Map();
144
+ progressRequests = new Map();
145
+ incoming = new Map();
146
+ requestHandlers = new Map();
147
+ notificationListeners = new Map();
148
+ errorListeners = new Set();
149
+ closeListeners = new Set();
150
+ disposers = [];
151
+ constructor(options) {
152
+ this.options = Object.freeze({ ...options });
153
+ const capabilities = { ...options.capabilities };
154
+ if (options.roots && capabilities.roots === undefined)
155
+ capabilities.roots = {};
156
+ this.meta = {
157
+ protocolVersion: STATELESS_PROTOCOL_VERSION,
158
+ clientInfo: {
159
+ name: options.name,
160
+ version: options.version,
161
+ ...(options.title === undefined ? {} : { title: options.title }),
162
+ },
163
+ clientCapabilities: capabilities,
164
+ logLevel: options.logLevel,
165
+ };
166
+ this.requestHandlers.set("ping", () => ({}));
167
+ const roots = options.roots;
168
+ if (roots) {
169
+ this.requestHandlers.set("roots/list", async () => ({
170
+ roots: [...(typeof roots === "function" ? await roots() : roots)],
171
+ }));
172
+ }
173
+ }
174
+ get connectionState() {
175
+ return this.state;
176
+ }
177
+ get serverInfo() {
178
+ return this.serverInfoValue;
179
+ }
180
+ get serverCapabilities() {
181
+ return this.serverCapabilitiesValue;
182
+ }
183
+ get instructions() {
184
+ return this.instructionsValue;
185
+ }
186
+ get protocolVersion() {
187
+ return this.protocolVersionValue;
188
+ }
189
+ /**
190
+ * Connect over `transport`. Resolves to what the server reported about itself; for servers on the
191
+ * stateless revision, a result in the shape of `initialize` built from `server/discover`.
192
+ */
193
+ async connect(transport) {
194
+ if (this.state !== "idle")
195
+ throw new Error(`Cannot connect MCP client in ${this.state} state`);
196
+ this.state = "connecting";
197
+ this.transport = transport;
198
+ this.disposers = [
199
+ transport.onMessage((message) => this.handleMessage(message)),
200
+ // Transport errors are reported only. Pending requests fail when the transport closes.
201
+ transport.onError((error) => this.emitError(error)),
202
+ transport.onClose(() => this.handleTransportClose()),
203
+ ];
204
+ try {
205
+ await transport.start();
206
+ const result = this.options.protocol === STATELESS_PROTOCOL_VERSION
207
+ ? await this.discover(transport, this.connectTimeoutMs())
208
+ : await this.initializeOrDiscover(transport);
209
+ this.state = "connected";
210
+ return result;
211
+ }
212
+ catch (error) {
213
+ await this.close().catch(() => { });
214
+ throw error;
215
+ }
216
+ }
217
+ /**
218
+ * `initialize` first, so servers of every earlier revision see what they always saw. Only a server
219
+ * that rejects it is asked with `server/discover`. When that fails too, the error is an
220
+ * {@link McpInitializeRejectedError} with the rejection's message, or with the message of
221
+ * `server/discover` when the rejection proved a stateless server that is still there. Such a server
222
+ * failing `server/discover` without answering it (sign-in required, say) fails with that error.
223
+ */
224
+ async initializeOrDiscover(transport) {
225
+ try {
226
+ return await this.initialize(transport);
227
+ }
228
+ catch (error) {
229
+ const rejection = error instanceof StatelessInitializeError ? "stateless" : initializeRejection(error);
230
+ if (rejection === undefined)
231
+ throw error;
232
+ const timeoutMs = rejection === "stateless"
233
+ ? this.connectTimeoutMs()
234
+ : Math.min(this.connectTimeoutMs(), DISCOVER_AFTER_INITIALIZE_TIMEOUT_MS);
235
+ try {
236
+ return await this.discover(transport, timeoutMs);
237
+ }
238
+ catch (discoverError) {
239
+ const answered = discoverError instanceof McpError;
240
+ if (rejection === "stateless" && !answered && !isConnectionLost(discoverError))
241
+ throw discoverError;
242
+ const message = rejection === "stateless" && answered ? discoverError.message : toError(error).message;
243
+ throw new McpInitializeRejectedError(message, error, discoverError);
244
+ }
245
+ }
246
+ }
247
+ async initialize(transport) {
248
+ const result = validateInitializeResult(await this.requestInternal("initialize", {
249
+ protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
250
+ capabilities: this.meta.clientCapabilities,
251
+ clientInfo: this.meta.clientInfo,
252
+ }, { timeoutMs: this.connectTimeoutMs() }, true));
253
+ if (result.protocolVersion === STATELESS_PROTOCOL_VERSION) {
254
+ throw new StatelessInitializeError("MCP server answered initialize with the stateless protocol revision");
255
+ }
256
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
257
+ throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
258
+ }
259
+ this.protocolVersionValue = result.protocolVersion;
260
+ this.serverInfoValue = result.serverInfo;
261
+ this.serverCapabilitiesValue = result.capabilities;
262
+ this.instructionsValue = result.instructions;
263
+ transport.setProtocolVersion?.(result.protocolVersion);
264
+ await this.notifyInternal("notifications/initialized", undefined, true);
265
+ return result;
266
+ }
267
+ /** Speak the stateless revision: no handshake, `server/discover` tells what the server offers. */
268
+ async discover(transport, timeoutMs) {
269
+ this.stateless = true;
270
+ transport.setProtocolVersion?.(STATELESS_PROTOCOL_VERSION);
271
+ const { result, serverInfo } = validateDiscoverResult(await this.requestInternal("server/discover", undefined, { timeoutMs }, true));
272
+ if (!result.supportedVersions.includes(STATELESS_PROTOCOL_VERSION)) {
273
+ throw new Error(`MCP server supports none of this client's protocol versions: ${result.supportedVersions}`);
274
+ }
275
+ this.protocolVersionValue = STATELESS_PROTOCOL_VERSION;
276
+ this.serverInfoValue = serverInfo;
277
+ this.serverCapabilitiesValue = result.capabilities;
278
+ this.instructionsValue = result.instructions;
279
+ return {
280
+ protocolVersion: STATELESS_PROTOCOL_VERSION,
281
+ capabilities: result.capabilities,
282
+ serverInfo: serverInfo ?? { name: "", version: "" },
283
+ ...(result.instructions === undefined ? {} : { instructions: result.instructions }),
284
+ };
285
+ }
286
+ request(method, params, options = {}) {
287
+ return this.requestConnected(method, params, options);
288
+ }
289
+ notify(method, params) {
290
+ return this.notifyInternal(method, params, false);
291
+ }
292
+ /**
293
+ * Answer requests of `method` from the server: requests a legacy server sends, and the input requests
294
+ * of the same method that results of the stateless revision ask for (`roots/list`, say).
295
+ */
296
+ setRequestHandler(method, handler) {
297
+ this.requestHandlers.set(method, handler);
298
+ return () => {
299
+ if (this.requestHandlers.get(method) === handler)
300
+ this.requestHandlers.delete(method);
301
+ };
302
+ }
303
+ onNotification(method, listener) {
304
+ const listeners = this.notificationListeners.get(method) ?? new Set();
305
+ this.notificationListeners.set(method, listeners);
306
+ listeners.add(listener);
307
+ return () => {
308
+ listeners.delete(listener);
309
+ if (listeners.size === 0)
310
+ this.notificationListeners.delete(method);
311
+ };
312
+ }
313
+ onError(listener) {
314
+ this.errorListeners.add(listener);
315
+ return () => this.errorListeners.delete(listener);
316
+ }
317
+ /** Called once when the connection closes, whether the transport dropped or `close()` was called. */
318
+ onClose(listener) {
319
+ this.closeListeners.add(listener);
320
+ return () => this.closeListeners.delete(listener);
321
+ }
322
+ /** Check that the server answers: `ping`, or `server/discover` on the stateless revision, which has no `ping`. */
323
+ async ping(options = {}) {
324
+ await this.request(this.stateless ? "server/discover" : "ping", undefined, options);
325
+ }
326
+ /**
327
+ * Every tool, following `nextCursor` through all pages. On the stateless revision over HTTP, tools
328
+ * whose `x-mcp-header` annotations are invalid are left out and reported through `onError`.
329
+ */
330
+ async listTools(options = {}) {
331
+ const tools = (await this.listAll("tools/list", "tools", isTool, options));
332
+ if (!this.stateless || !this.transport?.sendsHeaders)
333
+ return tools;
334
+ const kept = [];
335
+ const headers = new Map();
336
+ for (const tool of tools) {
337
+ const bindings = toolHeaderBindings(tool.inputSchema);
338
+ if (bindings.kind === "invalid") {
339
+ this.emitError(new Error(`Excluded MCP tool "${tool.name}": ${bindings.reason}`));
340
+ continue;
341
+ }
342
+ if (bindings.bindings.length > 0)
343
+ headers.set(tool.name, bindings.bindings);
344
+ kept.push(tool);
345
+ }
346
+ this.toolHeaders = headers;
347
+ return kept;
348
+ }
349
+ /** Every resource, following `nextCursor` through all pages. */
350
+ async listResources(options = {}) {
351
+ return (await this.listAll("resources/list", "resources", isResource, options)).map(toResource);
352
+ }
353
+ /** One page of resources, starting at `cursor`. */
354
+ async listResourcesPage(cursor, options = {}) {
355
+ const page = await this.listPage("resources/list", "resources", isResource, cursor, options);
356
+ return { resources: page.items.map(toResource), ...pageCursor(page) };
357
+ }
358
+ /** Every resource template, following `nextCursor` through all pages. */
359
+ async listResourceTemplates(options = {}) {
360
+ const templates = await this.listAll("resources/templates/list", "resourceTemplates", isResourceTemplate, options);
361
+ return templates.map(toResourceTemplate);
362
+ }
363
+ /** One page of resource templates, starting at `cursor`. */
364
+ async listResourceTemplatesPage(cursor, options = {}) {
365
+ const page = await this.listPage("resources/templates/list", "resourceTemplates", isResourceTemplate, cursor, options);
366
+ return { resourceTemplates: page.items.map(toResourceTemplate), ...pageCursor(page) };
367
+ }
368
+ async readResource(uri, options = {}) {
369
+ return validateReadResourceResult(await this.request("resources/read", { uri }, options));
370
+ }
371
+ async listPage(method, key, isItem, cursor, options) {
372
+ return validateListPage(method, key, await this.request(method, cursor === undefined ? undefined : { cursor }, options), isItem);
373
+ }
374
+ /** Every item of a paginated list method. */
375
+ async listAll(method, key, isItem, options) {
376
+ const items = [];
377
+ const cursors = new Set();
378
+ let cursor;
379
+ for (let pageNumber = 0; pageNumber < MAX_LIST_PAGES; pageNumber++) {
380
+ const page = await this.listPage(method, key, isItem, cursor, options);
381
+ items.push(...page.items);
382
+ if (page.nextCursor === undefined)
383
+ return items;
384
+ if (cursors.has(page.nextCursor))
385
+ throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);
386
+ cursors.add(page.nextCursor);
387
+ cursor = page.nextCursor;
388
+ }
389
+ throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);
390
+ }
391
+ /**
392
+ * Call a tool. On the stateless revision, arguments the tool marks with `x-mcp-header` go into
393
+ * `Mcp-Param-*` headers too; when the server reports that they do not match, the tools are listed
394
+ * again for their current annotations and the call is sent once more.
395
+ */
396
+ async callTool(name, args, options = {}) {
397
+ const params = { name, ...(args === undefined ? {} : { arguments: args }) };
398
+ const call = async () => {
399
+ const bindings = this.toolHeaders.get(name);
400
+ const headers = bindings ? toolParamHeaders(bindings, args) : undefined;
401
+ return validateCallToolResult(await this.requestConnected("tools/call", params, options, headers));
402
+ };
403
+ try {
404
+ return await call();
405
+ }
406
+ catch (error) {
407
+ if (!(this.stateless && error instanceof McpError && error.code === HEADER_MISMATCH_ERROR_CODE))
408
+ throw error;
409
+ await this.listTools(options.signal ? { signal: options.signal } : {});
410
+ return await call();
411
+ }
412
+ }
413
+ /**
414
+ * Open a `subscriptions/listen` stream of a server on the stateless revision, which delivers the
415
+ * notifications `filter` names to `onNotification` listeners. Resolves once the server acknowledged
416
+ * it; servers of earlier revisions send their notifications without one.
417
+ */
418
+ async listen(filter, options = {}) {
419
+ if (!this.stateless)
420
+ throw new Error("subscriptions/listen needs a server on the stateless revision");
421
+ const controller = new AbortController();
422
+ const close = () => controller.abort();
423
+ options.signal?.addEventListener("abort", close, { once: true });
424
+ let id;
425
+ let endedByServer = false;
426
+ let acknowledge = (_notifications) => { };
427
+ const acknowledged = new Promise((resolve) => {
428
+ acknowledge = resolve;
429
+ });
430
+ const request = this.requestInternal("subscriptions/listen", { notifications: filter }, { signal: controller.signal, timeoutMs: Number.POSITIVE_INFINITY }, false, {
431
+ onId: (requestId) => {
432
+ id = requestId;
433
+ const end = () => {
434
+ endedByServer = true;
435
+ this.cancelPending(requestId, new McpConnectionClosedError("MCP subscription ended"), false);
436
+ };
437
+ this.subscriptions.set(requestId, { acknowledge, end });
438
+ },
439
+ });
440
+ // The server ends a subscription with a result or `notifications/cancelled`; the client by aborting it.
441
+ const closed = request
442
+ .then(() => undefined, (error) => {
443
+ if (!endedByServer && !controller.signal.aborted)
444
+ throw error;
445
+ })
446
+ .finally(() => {
447
+ if (id !== undefined)
448
+ this.subscriptions.delete(id);
449
+ options.signal?.removeEventListener("abort", close);
450
+ });
451
+ const endedEarly = closed.then(() => {
452
+ throw new Error("MCP subscription ended before the server acknowledged it");
453
+ });
454
+ // Only the race waits for it; once acknowledged, the caller waits for `closed`.
455
+ endedEarly.catch(() => { });
456
+ return { notifications: await Promise.race([acknowledged, endedEarly]), closed, close };
457
+ }
458
+ async close() {
459
+ const transport = this.transport;
460
+ this.transport = undefined;
461
+ this.disposeTransportListeners();
462
+ this.markClosed(new McpConnectionClosedError());
463
+ await transport?.close();
464
+ }
465
+ /**
466
+ * A request on the connection. On the stateless revision, a result that asks for input is answered
467
+ * with the handlers of the input requests' methods, and one of an extension result type with
468
+ * `onExtensionResult`; the request is sent again with the answers until it completes. Every attempt
469
+ * is a new JSON-RPC request.
470
+ */
471
+ async requestConnected(method, params, options, headers) {
472
+ if (!this.stateless)
473
+ return this.requestInternal(method, params, options, false, { headers });
474
+ let input = {};
475
+ for (let round = 0;; round++) {
476
+ const result = readStatelessResult(method, await this.requestInternal(method, { ...params, ...input }, options, false, { headers }));
477
+ if (result.kind === "complete")
478
+ return result.result;
479
+ if (round + 1 >= MAX_INPUT_ROUNDS) {
480
+ throw new Error(`MCP ${method} still asks for input after ${MAX_INPUT_ROUNDS} rounds`);
481
+ }
482
+ input = await this.answerResult(method, result, options);
483
+ }
484
+ }
485
+ /** The params that answer a result asking for more, which the request is sent again with. */
486
+ async answerResult(method, result, options) {
487
+ const signal = options.signal ?? new AbortController().signal;
488
+ if (result.kind === "extension") {
489
+ if (!options.onExtensionResult)
490
+ throw invalid(`Unsupported MCP ${method} result type: ${result.resultType}`);
491
+ const { requestState } = await options.onExtensionResult(result.result, { signal });
492
+ return { requestState };
493
+ }
494
+ if (!INPUT_METHODS.has(method))
495
+ throw new Error(`MCP ${method} result asks for input, which it may not`);
496
+ return {
497
+ inputResponses: await this.answerInputRequests(result.inputRequests, signal),
498
+ ...(result.requestState === undefined ? {} : { requestState: result.requestState }),
499
+ };
500
+ }
501
+ async answerInputRequests(requests, signal) {
502
+ const responses = {};
503
+ for (const [key, request] of Object.entries(requests)) {
504
+ const handler = this.requestHandlers.get(request.method);
505
+ if (!handler)
506
+ throw new Error(`MCP server asked for input this client does not provide: ${request.method}`);
507
+ responses[key] = (await handler(request.params, { signal })) ?? {};
508
+ }
509
+ return responses;
510
+ }
511
+ requestTimeoutMs() {
512
+ return this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
513
+ }
514
+ connectTimeoutMs() {
515
+ return this.options.connectTimeoutMs ?? this.requestTimeoutMs();
516
+ }
517
+ async requestInternal(method, params, options, allowConnecting, send = {}) {
518
+ const transport = this.requireTransport(allowConnecting);
519
+ if (options.signal?.aborted)
520
+ throw new McpAbortError();
521
+ const id = this.nextRequestId++;
522
+ send.onId?.(id);
523
+ const { headers } = send;
524
+ const progressToken = options.onProgress ? id : undefined;
525
+ const metaParams = this.stateless ? withStatelessMeta(params, this.meta) : params;
526
+ const requestParams = progressToken === undefined
527
+ ? metaParams
528
+ : { ...metaParams, _meta: { ...(isObject(metaParams?._meta) ? metaParams._meta : {}), progressToken } };
529
+ const message = {
530
+ jsonrpc: "2.0",
531
+ id,
532
+ method,
533
+ ...(requestParams === undefined ? {} : { params: requestParams }),
534
+ };
535
+ return new Promise((resolve, reject) => {
536
+ const entry = {
537
+ resolve,
538
+ reject,
539
+ timeoutMs: options.timeoutMs ?? this.requestTimeoutMs(),
540
+ timer: undefined,
541
+ signal: options.signal,
542
+ // The spec forbids cancelling `initialize`.
543
+ onAbort: () => this.cancelPending(id, new McpAbortError(), method !== "initialize", String(options.signal?.reason ?? "Aborted")),
544
+ sendController: new AbortController(),
545
+ cancellable: method !== "initialize",
546
+ onProgress: options.onProgress,
547
+ progressToken,
548
+ };
549
+ this.pending.set(id, entry);
550
+ if (progressToken !== undefined)
551
+ this.progressRequests.set(progressToken, id);
552
+ options.signal?.addEventListener("abort", entry.onAbort, { once: true });
553
+ this.armTimeout(id, entry);
554
+ transport
555
+ .send(message, { signal: entry.sendController.signal, ...(headers === undefined ? {} : { headers }) })
556
+ .catch((error) => this.cancelPending(id, error, false));
557
+ });
558
+ }
559
+ async notifyInternal(method, params, allowConnecting) {
560
+ await this.requireTransport(allowConnecting).send({
561
+ jsonrpc: "2.0",
562
+ method,
563
+ ...(params === undefined ? {} : { params }),
564
+ });
565
+ }
566
+ requireTransport(allowConnecting) {
567
+ if (this.transport && (this.state === "connected" || (allowConnecting && this.state === "connecting"))) {
568
+ return this.transport;
569
+ }
570
+ throw new McpConnectionClosedError(`MCP client is ${this.state}`);
571
+ }
572
+ handleMessage(message) {
573
+ if (isJsonRpcResponse(message)) {
574
+ this.handleResponse(message);
575
+ return;
576
+ }
577
+ if (isJsonRpcRequest(message)) {
578
+ void this.handleRequest(message);
579
+ return;
580
+ }
581
+ if (isJsonRpcNotification(message)) {
582
+ this.handleNotification(message.method, message.params);
583
+ return;
584
+ }
585
+ this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Received invalid JSON-RPC message"));
586
+ }
587
+ handleResponse(message) {
588
+ const id = normalizeOwnRequestId(message.id);
589
+ const entry = this.pending.get(id);
590
+ if (!entry) {
591
+ this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));
592
+ return;
593
+ }
594
+ this.removePending(id, entry);
595
+ if ("error" in message)
596
+ entry.reject(new McpError(message.error.code, message.error.message, message.error.data));
597
+ else
598
+ entry.resolve(message.result);
599
+ }
600
+ async handleRequest(message) {
601
+ const transport = this.transport;
602
+ if (!transport)
603
+ return;
604
+ const handler = this.requestHandlers.get(message.method);
605
+ if (!handler) {
606
+ await transport
607
+ .send({
608
+ jsonrpc: "2.0",
609
+ id: message.id,
610
+ error: { code: JSON_RPC_ERROR_CODES.methodNotFound, message: `Method not found: ${message.method}` },
611
+ })
612
+ .catch((error) => this.emitError(error));
613
+ return;
614
+ }
615
+ const controller = new AbortController();
616
+ this.incoming.set(message.id, controller);
617
+ try {
618
+ const result = await handler(message.params, { signal: controller.signal });
619
+ await transport.send({ jsonrpc: "2.0", id: message.id, result: result ?? {} });
620
+ }
621
+ catch (error) {
622
+ const responseError = error instanceof McpError
623
+ ? { code: error.code, message: error.message, data: error.data }
624
+ : { code: JSON_RPC_ERROR_CODES.internalError, message: toError(error).message };
625
+ await transport
626
+ .send({ jsonrpc: "2.0", id: message.id, error: responseError })
627
+ .catch((sendError) => this.emitError(sendError));
628
+ }
629
+ finally {
630
+ this.incoming.delete(message.id);
631
+ }
632
+ }
633
+ handleNotification(method, params) {
634
+ if (method === "notifications/progress")
635
+ this.handleProgress(params);
636
+ else if (method === "notifications/cancelled")
637
+ this.handleCancelled(params);
638
+ else if (method === "notifications/subscriptions/acknowledged")
639
+ this.subscriptionOf(params)?.acknowledge(readSubscriptionFilter(params));
640
+ for (const listener of this.notificationListeners.get(method) ?? []) {
641
+ try {
642
+ listener(params);
643
+ }
644
+ catch (error) {
645
+ this.emitError(error);
646
+ }
647
+ }
648
+ }
649
+ handleProgress(params) {
650
+ if (!isObject(params) || !isJsonRpcId(params.progressToken) || typeof params.progress !== "number")
651
+ return;
652
+ const requestId = this.progressRequests.get(normalizeOwnRequestId(params.progressToken));
653
+ const entry = requestId === undefined ? undefined : this.pending.get(requestId);
654
+ if (requestId === undefined || !entry)
655
+ return;
656
+ this.armTimeout(requestId, entry);
657
+ try {
658
+ entry.onProgress?.(params);
659
+ }
660
+ catch (error) {
661
+ this.emitError(error);
662
+ }
663
+ }
664
+ /** Servers cancel requests they sent, and on the stateless revision end subscriptions this way. */
665
+ handleCancelled(params) {
666
+ if (!isObject(params) || !isJsonRpcId(params.requestId))
667
+ return;
668
+ this.incoming.get(params.requestId)?.abort(params.reason);
669
+ this.subscriptions.get(normalizeOwnRequestId(params.requestId))?.end();
670
+ }
671
+ subscriptionOf(params) {
672
+ const id = subscriptionIdOf(params);
673
+ return isJsonRpcId(id) ? this.subscriptions.get(normalizeOwnRequestId(id)) : undefined;
674
+ }
675
+ armTimeout(id, entry) {
676
+ if (entry.timer)
677
+ clearTimeout(entry.timer);
678
+ if (!Number.isFinite(entry.timeoutMs) || entry.timeoutMs <= 0)
679
+ return;
680
+ entry.timer = setTimeout(() => {
681
+ this.cancelPending(id, new McpTimeoutError(entry.timeoutMs), entry.cancellable, "Request timed out");
682
+ }, entry.timeoutMs);
683
+ }
684
+ cancelPending(id, error, notifyServer, reason) {
685
+ const entry = this.pending.get(id);
686
+ if (!entry)
687
+ return;
688
+ this.removePending(id, entry);
689
+ entry.reject(error);
690
+ if (notifyServer && this.transport) {
691
+ void this.transport
692
+ .send({
693
+ jsonrpc: "2.0",
694
+ method: "notifications/cancelled",
695
+ params: { requestId: id, ...(reason ? { reason } : {}) },
696
+ })
697
+ .catch((sendError) => this.emitError(sendError));
698
+ }
699
+ }
700
+ removePending(id, entry) {
701
+ this.pending.delete(id);
702
+ if (entry.timer)
703
+ clearTimeout(entry.timer);
704
+ if (entry.progressToken !== undefined)
705
+ this.progressRequests.delete(entry.progressToken);
706
+ entry.signal?.removeEventListener("abort", entry.onAbort);
707
+ entry.sendController.abort();
708
+ }
709
+ rejectPending(error) {
710
+ for (const [id, entry] of this.pending) {
711
+ this.removePending(id, entry);
712
+ entry.reject(error);
713
+ }
714
+ }
715
+ handleTransportClose() {
716
+ this.markClosed(new McpConnectionClosedError());
717
+ }
718
+ /** Idempotent: rejects in-flight requests, aborts server requests we are serving, and flips the state. */
719
+ markClosed(error) {
720
+ const wasClosed = this.state === "closed";
721
+ this.state = "closed";
722
+ this.rejectPending(error);
723
+ for (const controller of this.incoming.values())
724
+ controller.abort(error);
725
+ this.incoming.clear();
726
+ if (wasClosed)
727
+ return;
728
+ for (const listener of [...this.closeListeners]) {
729
+ try {
730
+ listener();
731
+ }
732
+ catch (listenerError) {
733
+ this.emitError(listenerError);
734
+ }
735
+ }
736
+ }
737
+ emitError(error) {
738
+ const normalized = toError(error);
739
+ for (const listener of this.errorListeners)
740
+ listener(normalized);
741
+ }
742
+ disposeTransportListeners() {
743
+ for (const dispose of this.disposers.splice(0))
744
+ dispose();
745
+ }
746
+ }
747
+ //# sourceMappingURL=client.js.map