@draht/mcp 2026.10.4-2

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 (74) hide show
  1. package/LICENSES/modelcontextprotocol-typescript-sdk.txt +21 -0
  2. package/dist/auth-provider.d.ts +15 -0
  3. package/dist/auth-provider.d.ts.map +1 -0
  4. package/dist/auth-provider.js +2 -0
  5. package/dist/auth-provider.js.map +1 -0
  6. package/dist/client.d.ts +89 -0
  7. package/dist/client.d.ts.map +1 -0
  8. package/dist/client.js +456 -0
  9. package/dist/client.js.map +1 -0
  10. package/dist/index.d.ts +9 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +7 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/oauth/callback.d.ts +42 -0
  15. package/dist/oauth/callback.d.ts.map +1 -0
  16. package/dist/oauth/callback.js +106 -0
  17. package/dist/oauth/callback.js.map +1 -0
  18. package/dist/oauth/discovery.d.ts +25 -0
  19. package/dist/oauth/discovery.d.ts.map +1 -0
  20. package/dist/oauth/discovery.js +142 -0
  21. package/dist/oauth/discovery.js.map +1 -0
  22. package/dist/oauth/errors.d.ts +23 -0
  23. package/dist/oauth/errors.d.ts.map +1 -0
  24. package/dist/oauth/errors.js +45 -0
  25. package/dist/oauth/errors.js.map +1 -0
  26. package/dist/oauth/flow.d.ts +75 -0
  27. package/dist/oauth/flow.d.ts.map +1 -0
  28. package/dist/oauth/flow.js +276 -0
  29. package/dist/oauth/flow.js.map +1 -0
  30. package/dist/oauth/index.d.ts +7 -0
  31. package/dist/oauth/index.d.ts.map +1 -0
  32. package/dist/oauth/index.js +6 -0
  33. package/dist/oauth/index.js.map +1 -0
  34. package/dist/oauth/provider.d.ts +59 -0
  35. package/dist/oauth/provider.d.ts.map +1 -0
  36. package/dist/oauth/provider.js +116 -0
  37. package/dist/oauth/provider.js.map +1 -0
  38. package/dist/oauth/types.d.ts +75 -0
  39. package/dist/oauth/types.d.ts.map +1 -0
  40. package/dist/oauth/types.js +98 -0
  41. package/dist/oauth/types.js.map +1 -0
  42. package/dist/protocol/content.d.ts +82 -0
  43. package/dist/protocol/content.d.ts.map +1 -0
  44. package/dist/protocol/content.js +41 -0
  45. package/dist/protocol/content.js.map +1 -0
  46. package/dist/protocol/jsonrpc.d.ts +59 -0
  47. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  48. package/dist/protocol/jsonrpc.js +67 -0
  49. package/dist/protocol/jsonrpc.js.map +1 -0
  50. package/dist/protocol/types.d.ts +123 -0
  51. package/dist/protocol/types.d.ts.map +1 -0
  52. package/dist/protocol/types.js +7 -0
  53. package/dist/protocol/types.js.map +1 -0
  54. package/dist/testing/index.d.ts +2 -0
  55. package/dist/testing/index.d.ts.map +1 -0
  56. package/dist/testing/index.js +2 -0
  57. package/dist/testing/index.js.map +1 -0
  58. package/dist/transports/in-memory.d.ts +19 -0
  59. package/dist/transports/in-memory.d.ts.map +1 -0
  60. package/dist/transports/in-memory.js +50 -0
  61. package/dist/transports/in-memory.js.map +1 -0
  62. package/dist/transports/stdio.d.ts +32 -0
  63. package/dist/transports/stdio.d.ts.map +1 -0
  64. package/dist/transports/stdio.js +201 -0
  65. package/dist/transports/stdio.js.map +1 -0
  66. package/dist/transports/streamable-http.d.ts +96 -0
  67. package/dist/transports/streamable-http.d.ts.map +1 -0
  68. package/dist/transports/streamable-http.js +456 -0
  69. package/dist/transports/streamable-http.js.map +1 -0
  70. package/dist/transports/transport.d.ts +28 -0
  71. package/dist/transports/transport.d.ts.map +1 -0
  72. package/dist/transports/transport.js +38 -0
  73. package/dist/transports/transport.js.map +1 -0
  74. package/package.json +61 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Anthropic, PBC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ export type McpFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
2
+ export interface UnauthorizedContext {
3
+ /** The 401 response, or a 403 response whose challenge reports `insufficient_scope`. */
4
+ response: Response;
5
+ serverUrl: URL;
6
+ fetch: McpFetch;
7
+ /** Access token the rejected request carried, if any. A different current token means another request already refreshed it. */
8
+ token?: string;
9
+ }
10
+ /** Supplies bearer tokens to an MCP HTTP transport and may refresh them after a 401 response. */
11
+ export interface AuthProvider {
12
+ token(): Promise<string | undefined>;
13
+ onUnauthorized?(context: UnauthorizedContext): Promise<void>;
14
+ }
15
+ //# sourceMappingURL=auth-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-provider.d.ts","sourceRoot":"","sources":["../src/auth-provider.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,QAAQ,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEtF,MAAM,WAAW,mBAAmB;IACnC,wFAAwF;IACxF,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,EAAE,GAAG,CAAC;IACf,KAAK,EAAE,QAAQ,CAAC;IAChB,+HAA+H;IAC/H,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,iGAAiG;AACjG,MAAM,WAAW,YAAY;IAC5B,KAAK,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACrC,cAAc,CAAC,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7D"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=auth-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-provider.js","sourceRoot":"","sources":["../src/auth-provider.ts"],"names":[],"mappings":"","sourcesContent":["export type McpFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface UnauthorizedContext {\n\t/** The 401 response, or a 403 response whose challenge reports `insufficient_scope`. */\n\tresponse: Response;\n\tserverUrl: URL;\n\tfetch: McpFetch;\n\t/** Access token the rejected request carried, if any. A different current token means another request already refreshed it. */\n\ttoken?: string;\n}\n\n/** Supplies bearer tokens to an MCP HTTP transport and may refresh them after a 401 response. */\nexport interface AuthProvider {\n\ttoken(): Promise<string | undefined>;\n\tonUnauthorized?(context: UnauthorizedContext): Promise<void>;\n}\n"]}
@@ -0,0 +1,89 @@
1
+ import type { CallToolResult } from "./protocol/content.ts";
2
+ import { type ClientCapabilities, type Implementation, type InitializeResult, type ListResourcesResult, type ListResourceTemplatesResult, type ProgressNotification, type ReadResourceResult, type Resource, type ResourceTemplate, type Root, type ServerCapabilities, type SupportedProtocolVersion, type Tool } from "./protocol/types.ts";
3
+ import type { McpTransport } from "./transports/transport.ts";
4
+ type ClientState = "idle" | "connecting" | "connected" | "closed";
5
+ type NotificationListener = (params: unknown) => void;
6
+ type ErrorListener = (error: Error) => void;
7
+ type CloseListener = () => void;
8
+ type RequestHandler = (params: unknown, context: {
9
+ signal: AbortSignal;
10
+ }) => unknown | Promise<unknown>;
11
+ export interface McpClientOptions extends Implementation {
12
+ capabilities?: ClientCapabilities;
13
+ protocolVersion?: SupportedProtocolVersion;
14
+ requestTimeoutMs?: number;
15
+ roots?: readonly Root[] | (() => readonly Root[] | Promise<readonly Root[]>);
16
+ }
17
+ export interface McpRequestOptions {
18
+ signal?: AbortSignal;
19
+ timeoutMs?: number;
20
+ onProgress?: (progress: ProgressNotification) => void;
21
+ }
22
+ export declare class McpClient {
23
+ readonly options: Readonly<McpClientOptions>;
24
+ private state;
25
+ private transport;
26
+ private nextRequestId;
27
+ private serverInfoValue;
28
+ private serverCapabilitiesValue;
29
+ private instructionsValue;
30
+ private protocolVersionValue;
31
+ private pending;
32
+ private progressRequests;
33
+ private incoming;
34
+ private requestHandlers;
35
+ private notificationListeners;
36
+ private errorListeners;
37
+ private closeListeners;
38
+ private disposers;
39
+ constructor(options: McpClientOptions);
40
+ get connectionState(): ClientState;
41
+ get serverInfo(): Implementation | undefined;
42
+ get serverCapabilities(): ServerCapabilities | undefined;
43
+ get instructions(): string | undefined;
44
+ get protocolVersion(): string | undefined;
45
+ connect(transport: McpTransport): Promise<InitializeResult>;
46
+ request<Result = unknown>(method: string, params?: Record<string, unknown>, options?: McpRequestOptions): Promise<Result>;
47
+ notify(method: string, params?: Record<string, unknown>): Promise<void>;
48
+ setRequestHandler(method: string, handler: RequestHandler): () => void;
49
+ onNotification(method: string, listener: NotificationListener): () => void;
50
+ onError(listener: ErrorListener): () => void;
51
+ /** Called once when the connection closes, whether the transport dropped or `close()` was called. */
52
+ onClose(listener: CloseListener): () => void;
53
+ ping(options?: McpRequestOptions): Promise<void>;
54
+ listTools(options?: McpRequestOptions): Promise<Tool[]>;
55
+ /** Every resource, following `nextCursor` through all pages. */
56
+ listResources(options?: McpRequestOptions): Promise<Resource[]>;
57
+ /** One page of resources, starting at `cursor`. */
58
+ listResourcesPage(cursor?: string, options?: McpRequestOptions): Promise<ListResourcesResult>;
59
+ /** Every resource template, following `nextCursor` through all pages. */
60
+ listResourceTemplates(options?: McpRequestOptions): Promise<ResourceTemplate[]>;
61
+ /** One page of resource templates, starting at `cursor`. */
62
+ listResourceTemplatesPage(cursor?: string, options?: McpRequestOptions): Promise<ListResourceTemplatesResult>;
63
+ readResource(uri: string, options?: McpRequestOptions): Promise<ReadResourceResult>;
64
+ private listPage;
65
+ /** Every item of a paginated list method. */
66
+ private listAll;
67
+ callTool(name: string, args?: Record<string, unknown>, options?: McpRequestOptions): Promise<CallToolResult>;
68
+ close(): Promise<void>;
69
+ private requestInternal;
70
+ private notifyInternal;
71
+ private requireTransport;
72
+ private handleMessage;
73
+ private handleResponse;
74
+ private handleRequest;
75
+ private handleNotification;
76
+ private handleProgress;
77
+ private handleCancelled;
78
+ private armTimeout;
79
+ private cancelPending;
80
+ private removePending;
81
+ private rejectPending;
82
+ private handleTransportClose;
83
+ /** Idempotent: rejects in-flight requests, aborts server requests we are serving, and flips the state. */
84
+ private markClosed;
85
+ private emitError;
86
+ private disposeTransportListeners;
87
+ }
88
+ export {};
89
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAkB5D,OAAO,EACN,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EAErB,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,kBAAkB,EAEvB,KAAK,wBAAwB,EAC7B,KAAK,IAAI,EACT,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAK9D,KAAK,WAAW,GAAG,MAAM,GAAG,YAAY,GAAG,WAAW,GAAG,QAAQ,CAAC;A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AS;IAKjB,OAAO,CAAC,yBAAyB;CAGjC"}
package/dist/client.js ADDED
@@ -0,0 +1,456 @@
1
+ import { isJsonRpcId, isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isObject, JSON_RPC_ERROR_CODES, McpAbortError, McpConnectionClosedError, McpError, McpTimeoutError, toError, } from "./protocol/jsonrpc.js";
2
+ import { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "./protocol/types.js";
3
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
4
+ const MAX_LIST_PAGES = 1_000;
5
+ function validateInitializeResult(value) {
6
+ if (!isObject(value) ||
7
+ typeof value.protocolVersion !== "string" ||
8
+ !isObject(value.capabilities) ||
9
+ !isObject(value.serverInfo) ||
10
+ typeof value.serverInfo.name !== "string" ||
11
+ typeof value.serverInfo.version !== "string" ||
12
+ (value.instructions !== undefined && typeof value.instructions !== "string")) {
13
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP initialize result");
14
+ }
15
+ return value;
16
+ }
17
+ function invalid(message) {
18
+ return new McpError(JSON_RPC_ERROR_CODES.invalidRequest, message);
19
+ }
20
+ /** One page of a paginated list: the items under `key`, each checked by `isItem`. */
21
+ function validateListPage(method, key, value, isItem) {
22
+ const items = isObject(value) ? value[key] : undefined;
23
+ if (!isObject(value) || !Array.isArray(items))
24
+ throw invalid(`Invalid MCP ${method} result`);
25
+ for (const item of items) {
26
+ if (!isObject(item) || !isItem(item))
27
+ throw invalid(`Invalid entry in MCP ${method} result`);
28
+ }
29
+ if (value.nextCursor !== undefined && typeof value.nextCursor !== "string") {
30
+ throw invalid(`Invalid MCP ${method} cursor`);
31
+ }
32
+ return { items, ...(value.nextCursor === undefined ? {} : { nextCursor: value.nextCursor }) };
33
+ }
34
+ const isTool = (tool) => typeof tool.name === "string" && isObject(tool.inputSchema);
35
+ // `name` is required by the spec, but some servers omit it; the URI stands in.
36
+ const isResource = (resource) => typeof resource.uri === "string" && (resource.name === undefined || typeof resource.name === "string");
37
+ const isResourceTemplate = (template) => typeof template.uriTemplate === "string" && (template.name === undefined || typeof template.name === "string");
38
+ function toResource(item) {
39
+ return { ...item, name: item.name ?? item.uri };
40
+ }
41
+ function toResourceTemplate(item) {
42
+ return { ...item, name: item.name ?? item.uriTemplate };
43
+ }
44
+ function pageCursor(page) {
45
+ return page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor };
46
+ }
47
+ function validateReadResourceResult(value) {
48
+ if (!isObject(value) || !Array.isArray(value.contents))
49
+ throw invalid("Invalid MCP resources/read result");
50
+ for (const contents of value.contents) {
51
+ if (!isObject(contents) ||
52
+ typeof contents.uri !== "string" ||
53
+ (typeof contents.text !== "string" && typeof contents.blob !== "string")) {
54
+ throw invalid("Invalid contents in MCP resources/read result");
55
+ }
56
+ }
57
+ return value;
58
+ }
59
+ /** `content` is required by the spec, but servers that only return `structuredContent` omit it (the SDK defaults it too). */
60
+ function validateCallToolResult(value) {
61
+ if (!isObject(value) || (value.content !== undefined && !Array.isArray(value.content))) {
62
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP tools/call result");
63
+ }
64
+ if (value.structuredContent !== undefined && !isObject(value.structuredContent)) {
65
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP tools/call structured content");
66
+ }
67
+ return (value.content === undefined ? { ...value, content: [] } : value);
68
+ }
69
+ export class McpClient {
70
+ options;
71
+ state = "idle";
72
+ transport;
73
+ nextRequestId = 1;
74
+ serverInfoValue;
75
+ serverCapabilitiesValue;
76
+ instructionsValue;
77
+ protocolVersionValue;
78
+ pending = new Map();
79
+ progressRequests = new Map();
80
+ incoming = new Map();
81
+ requestHandlers = new Map();
82
+ notificationListeners = new Map();
83
+ errorListeners = new Set();
84
+ closeListeners = new Set();
85
+ disposers = [];
86
+ constructor(options) {
87
+ this.options = Object.freeze({ ...options });
88
+ this.requestHandlers.set("ping", () => ({}));
89
+ const roots = options.roots;
90
+ if (roots) {
91
+ this.requestHandlers.set("roots/list", async () => ({
92
+ roots: [...(typeof roots === "function" ? await roots() : roots)],
93
+ }));
94
+ }
95
+ }
96
+ get connectionState() {
97
+ return this.state;
98
+ }
99
+ get serverInfo() {
100
+ return this.serverInfoValue;
101
+ }
102
+ get serverCapabilities() {
103
+ return this.serverCapabilitiesValue;
104
+ }
105
+ get instructions() {
106
+ return this.instructionsValue;
107
+ }
108
+ get protocolVersion() {
109
+ return this.protocolVersionValue;
110
+ }
111
+ async connect(transport) {
112
+ if (this.state !== "idle")
113
+ throw new Error(`Cannot connect MCP client in ${this.state} state`);
114
+ this.state = "connecting";
115
+ this.transport = transport;
116
+ this.disposers = [
117
+ transport.onMessage((message) => this.handleMessage(message)),
118
+ // Transport errors are reported only. Pending requests fail when the transport closes.
119
+ transport.onError((error) => this.emitError(error)),
120
+ transport.onClose(() => this.handleTransportClose()),
121
+ ];
122
+ try {
123
+ await transport.start();
124
+ const capabilities = { ...this.options.capabilities };
125
+ if (this.options.roots && capabilities.roots === undefined)
126
+ capabilities.roots = {};
127
+ const result = validateInitializeResult(await this.requestInternal("initialize", {
128
+ protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
129
+ capabilities,
130
+ clientInfo: {
131
+ name: this.options.name,
132
+ version: this.options.version,
133
+ ...(this.options.title === undefined ? {} : { title: this.options.title }),
134
+ },
135
+ }, {}, true));
136
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
137
+ throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
138
+ }
139
+ this.protocolVersionValue = result.protocolVersion;
140
+ this.serverInfoValue = result.serverInfo;
141
+ this.serverCapabilitiesValue = result.capabilities;
142
+ this.instructionsValue = result.instructions;
143
+ transport.setProtocolVersion?.(result.protocolVersion);
144
+ await this.notifyInternal("notifications/initialized", undefined, true);
145
+ this.state = "connected";
146
+ return result;
147
+ }
148
+ catch (error) {
149
+ await this.close().catch(() => { });
150
+ throw error;
151
+ }
152
+ }
153
+ request(method, params, options = {}) {
154
+ return this.requestInternal(method, params, options, false);
155
+ }
156
+ notify(method, params) {
157
+ return this.notifyInternal(method, params, false);
158
+ }
159
+ setRequestHandler(method, handler) {
160
+ this.requestHandlers.set(method, handler);
161
+ return () => {
162
+ if (this.requestHandlers.get(method) === handler)
163
+ this.requestHandlers.delete(method);
164
+ };
165
+ }
166
+ onNotification(method, listener) {
167
+ const listeners = this.notificationListeners.get(method) ?? new Set();
168
+ this.notificationListeners.set(method, listeners);
169
+ listeners.add(listener);
170
+ return () => {
171
+ listeners.delete(listener);
172
+ if (listeners.size === 0)
173
+ this.notificationListeners.delete(method);
174
+ };
175
+ }
176
+ onError(listener) {
177
+ this.errorListeners.add(listener);
178
+ return () => this.errorListeners.delete(listener);
179
+ }
180
+ /** Called once when the connection closes, whether the transport dropped or `close()` was called. */
181
+ onClose(listener) {
182
+ this.closeListeners.add(listener);
183
+ return () => this.closeListeners.delete(listener);
184
+ }
185
+ async ping(options = {}) {
186
+ await this.request("ping", undefined, options);
187
+ }
188
+ async listTools(options = {}) {
189
+ return (await this.listAll("tools/list", "tools", isTool, options));
190
+ }
191
+ /** Every resource, following `nextCursor` through all pages. */
192
+ async listResources(options = {}) {
193
+ return (await this.listAll("resources/list", "resources", isResource, options)).map(toResource);
194
+ }
195
+ /** One page of resources, starting at `cursor`. */
196
+ async listResourcesPage(cursor, options = {}) {
197
+ const page = await this.listPage("resources/list", "resources", isResource, cursor, options);
198
+ return { resources: page.items.map(toResource), ...pageCursor(page) };
199
+ }
200
+ /** Every resource template, following `nextCursor` through all pages. */
201
+ async listResourceTemplates(options = {}) {
202
+ const templates = await this.listAll("resources/templates/list", "resourceTemplates", isResourceTemplate, options);
203
+ return templates.map(toResourceTemplate);
204
+ }
205
+ /** One page of resource templates, starting at `cursor`. */
206
+ async listResourceTemplatesPage(cursor, options = {}) {
207
+ const page = await this.listPage("resources/templates/list", "resourceTemplates", isResourceTemplate, cursor, options);
208
+ return { resourceTemplates: page.items.map(toResourceTemplate), ...pageCursor(page) };
209
+ }
210
+ async readResource(uri, options = {}) {
211
+ return validateReadResourceResult(await this.request("resources/read", { uri }, options));
212
+ }
213
+ async listPage(method, key, isItem, cursor, options) {
214
+ return validateListPage(method, key, await this.request(method, cursor === undefined ? undefined : { cursor }, options), isItem);
215
+ }
216
+ /** Every item of a paginated list method. */
217
+ async listAll(method, key, isItem, options) {
218
+ const items = [];
219
+ const cursors = new Set();
220
+ let cursor;
221
+ for (let pageNumber = 0; pageNumber < MAX_LIST_PAGES; pageNumber++) {
222
+ const page = await this.listPage(method, key, isItem, cursor, options);
223
+ items.push(...page.items);
224
+ if (page.nextCursor === undefined)
225
+ return items;
226
+ if (cursors.has(page.nextCursor))
227
+ throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);
228
+ cursors.add(page.nextCursor);
229
+ cursor = page.nextCursor;
230
+ }
231
+ throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);
232
+ }
233
+ async callTool(name, args, options = {}) {
234
+ return validateCallToolResult(await this.request("tools/call", { name, ...(args === undefined ? {} : { arguments: args }) }, options));
235
+ }
236
+ async close() {
237
+ const transport = this.transport;
238
+ this.transport = undefined;
239
+ this.disposeTransportListeners();
240
+ this.markClosed(new McpConnectionClosedError());
241
+ await transport?.close();
242
+ }
243
+ async requestInternal(method, params, options, allowConnecting) {
244
+ const transport = this.requireTransport(allowConnecting);
245
+ if (options.signal?.aborted)
246
+ throw new McpAbortError();
247
+ const id = this.nextRequestId++;
248
+ const progressToken = options.onProgress ? id : undefined;
249
+ const requestParams = progressToken === undefined
250
+ ? params
251
+ : { ...params, _meta: { ...(isObject(params?._meta) ? params._meta : {}), progressToken } };
252
+ const message = {
253
+ jsonrpc: "2.0",
254
+ id,
255
+ method,
256
+ ...(requestParams === undefined ? {} : { params: requestParams }),
257
+ };
258
+ return new Promise((resolve, reject) => {
259
+ const entry = {
260
+ resolve,
261
+ reject,
262
+ timeoutMs: options.timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
263
+ timer: undefined,
264
+ signal: options.signal,
265
+ // The spec forbids cancelling `initialize`.
266
+ onAbort: () => this.cancelPending(id, new McpAbortError(), method !== "initialize", String(options.signal?.reason ?? "Aborted")),
267
+ cancellable: method !== "initialize",
268
+ onProgress: options.onProgress,
269
+ progressToken,
270
+ };
271
+ this.pending.set(id, entry);
272
+ if (progressToken !== undefined)
273
+ this.progressRequests.set(progressToken, id);
274
+ options.signal?.addEventListener("abort", entry.onAbort, { once: true });
275
+ this.armTimeout(id, entry);
276
+ transport.send(message).catch((error) => this.cancelPending(id, error, false));
277
+ });
278
+ }
279
+ async notifyInternal(method, params, allowConnecting) {
280
+ await this.requireTransport(allowConnecting).send({
281
+ jsonrpc: "2.0",
282
+ method,
283
+ ...(params === undefined ? {} : { params }),
284
+ });
285
+ }
286
+ requireTransport(allowConnecting) {
287
+ if (this.transport && (this.state === "connected" || (allowConnecting && this.state === "connecting"))) {
288
+ return this.transport;
289
+ }
290
+ throw new McpConnectionClosedError(`MCP client is ${this.state}`);
291
+ }
292
+ handleMessage(message) {
293
+ if (isJsonRpcResponse(message)) {
294
+ this.handleResponse(message);
295
+ return;
296
+ }
297
+ if (isJsonRpcRequest(message)) {
298
+ void this.handleRequest(message);
299
+ return;
300
+ }
301
+ if (isJsonRpcNotification(message)) {
302
+ this.handleNotification(message.method, message.params);
303
+ return;
304
+ }
305
+ this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Received invalid JSON-RPC message"));
306
+ }
307
+ handleResponse(message) {
308
+ const entry = this.pending.get(message.id);
309
+ if (!entry) {
310
+ this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));
311
+ return;
312
+ }
313
+ this.removePending(message.id, entry);
314
+ if ("error" in message)
315
+ entry.reject(new McpError(message.error.code, message.error.message, message.error.data));
316
+ else
317
+ entry.resolve(message.result);
318
+ }
319
+ async handleRequest(message) {
320
+ const transport = this.transport;
321
+ if (!transport)
322
+ return;
323
+ const handler = this.requestHandlers.get(message.method);
324
+ if (!handler) {
325
+ await transport
326
+ .send({
327
+ jsonrpc: "2.0",
328
+ id: message.id,
329
+ error: { code: JSON_RPC_ERROR_CODES.methodNotFound, message: `Method not found: ${message.method}` },
330
+ })
331
+ .catch((error) => this.emitError(error));
332
+ return;
333
+ }
334
+ const controller = new AbortController();
335
+ this.incoming.set(message.id, controller);
336
+ try {
337
+ const result = await handler(message.params, { signal: controller.signal });
338
+ await transport.send({ jsonrpc: "2.0", id: message.id, result: result ?? {} });
339
+ }
340
+ catch (error) {
341
+ const responseError = error instanceof McpError
342
+ ? { code: error.code, message: error.message, data: error.data }
343
+ : { code: JSON_RPC_ERROR_CODES.internalError, message: toError(error).message };
344
+ await transport
345
+ .send({ jsonrpc: "2.0", id: message.id, error: responseError })
346
+ .catch((sendError) => this.emitError(sendError));
347
+ }
348
+ finally {
349
+ this.incoming.delete(message.id);
350
+ }
351
+ }
352
+ handleNotification(method, params) {
353
+ if (method === "notifications/progress")
354
+ this.handleProgress(params);
355
+ else if (method === "notifications/cancelled")
356
+ this.handleCancelled(params);
357
+ for (const listener of this.notificationListeners.get(method) ?? []) {
358
+ try {
359
+ listener(params);
360
+ }
361
+ catch (error) {
362
+ this.emitError(error);
363
+ }
364
+ }
365
+ }
366
+ handleProgress(params) {
367
+ if (!isObject(params) || !isJsonRpcId(params.progressToken) || typeof params.progress !== "number")
368
+ return;
369
+ const requestId = this.progressRequests.get(params.progressToken);
370
+ const entry = requestId === undefined ? undefined : this.pending.get(requestId);
371
+ if (requestId === undefined || !entry)
372
+ return;
373
+ this.armTimeout(requestId, entry);
374
+ try {
375
+ entry.onProgress?.(params);
376
+ }
377
+ catch (error) {
378
+ this.emitError(error);
379
+ }
380
+ }
381
+ handleCancelled(params) {
382
+ if (isObject(params) && isJsonRpcId(params.requestId))
383
+ this.incoming.get(params.requestId)?.abort(params.reason);
384
+ }
385
+ armTimeout(id, entry) {
386
+ if (entry.timer)
387
+ clearTimeout(entry.timer);
388
+ if (!Number.isFinite(entry.timeoutMs) || entry.timeoutMs <= 0)
389
+ return;
390
+ entry.timer = setTimeout(() => {
391
+ this.cancelPending(id, new McpTimeoutError(entry.timeoutMs), entry.cancellable, "Request timed out");
392
+ }, entry.timeoutMs);
393
+ }
394
+ cancelPending(id, error, notifyServer, reason) {
395
+ const entry = this.pending.get(id);
396
+ if (!entry)
397
+ return;
398
+ this.removePending(id, entry);
399
+ entry.reject(error);
400
+ if (notifyServer && this.transport) {
401
+ void this.transport
402
+ .send({
403
+ jsonrpc: "2.0",
404
+ method: "notifications/cancelled",
405
+ params: { requestId: id, ...(reason ? { reason } : {}) },
406
+ })
407
+ .catch((sendError) => this.emitError(sendError));
408
+ }
409
+ }
410
+ removePending(id, entry) {
411
+ this.pending.delete(id);
412
+ if (entry.timer)
413
+ clearTimeout(entry.timer);
414
+ if (entry.progressToken !== undefined)
415
+ this.progressRequests.delete(entry.progressToken);
416
+ entry.signal?.removeEventListener("abort", entry.onAbort);
417
+ }
418
+ rejectPending(error) {
419
+ for (const [id, entry] of this.pending) {
420
+ this.removePending(id, entry);
421
+ entry.reject(error);
422
+ }
423
+ }
424
+ handleTransportClose() {
425
+ this.markClosed(new McpConnectionClosedError());
426
+ }
427
+ /** Idempotent: rejects in-flight requests, aborts server requests we are serving, and flips the state. */
428
+ markClosed(error) {
429
+ const wasClosed = this.state === "closed";
430
+ this.state = "closed";
431
+ this.rejectPending(error);
432
+ for (const controller of this.incoming.values())
433
+ controller.abort(error);
434
+ this.incoming.clear();
435
+ if (wasClosed)
436
+ return;
437
+ for (const listener of [...this.closeListeners]) {
438
+ try {
439
+ listener();
440
+ }
441
+ catch (listenerError) {
442
+ this.emitError(listenerError);
443
+ }
444
+ }
445
+ }
446
+ emitError(error) {
447
+ const normalized = toError(error);
448
+ for (const listener of this.errorListeners)
449
+ listener(normalized);
450
+ }
451
+ disposeTransportListeners() {
452
+ for (const dispose of this.disposers.splice(0))
453
+ dispose();
454
+ }
455
+ }
456
+ //# sourceMappingURL=client.js.map