@c9up/polaris 0.1.0 → 0.1.1

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 (217) hide show
  1. package/README.md +614 -10
  2. package/dist/Polaris.d.ts +6 -2
  3. package/dist/Polaris.d.ts.map +1 -1
  4. package/dist/Polaris.js +14 -0
  5. package/dist/Polaris.js.map +1 -1
  6. package/dist/PolarisClient.d.ts +51 -3
  7. package/dist/PolarisClient.d.ts.map +1 -1
  8. package/dist/PolarisClient.js +213 -45
  9. package/dist/PolarisClient.js.map +1 -1
  10. package/dist/PolarisProvider.d.ts +7 -2
  11. package/dist/PolarisProvider.d.ts.map +1 -1
  12. package/dist/PolarisProvider.js +34 -2
  13. package/dist/PolarisProvider.js.map +1 -1
  14. package/dist/augmentations.d.ts +4 -1
  15. package/dist/augmentations.d.ts.map +1 -1
  16. package/dist/augmentations.js +1 -1
  17. package/dist/budget.d.ts +39 -6
  18. package/dist/budget.d.ts.map +1 -1
  19. package/dist/budget.js +79 -12
  20. package/dist/budget.js.map +1 -1
  21. package/dist/catalog/catalog.d.ts +37 -0
  22. package/dist/catalog/catalog.d.ts.map +1 -0
  23. package/dist/catalog/catalog.js +145 -0
  24. package/dist/catalog/catalog.js.map +1 -0
  25. package/dist/catalog/discover.d.ts +64 -0
  26. package/dist/catalog/discover.d.ts.map +1 -0
  27. package/dist/catalog/discover.js +148 -0
  28. package/dist/catalog/discover.js.map +1 -0
  29. package/dist/catalog/index.d.ts +8 -0
  30. package/dist/catalog/index.d.ts.map +1 -0
  31. package/dist/catalog/index.js +8 -0
  32. package/dist/catalog/index.js.map +1 -0
  33. package/dist/commands/index.d.ts +82 -0
  34. package/dist/commands/index.d.ts.map +1 -0
  35. package/dist/commands/index.js +278 -0
  36. package/dist/commands/index.js.map +1 -0
  37. package/dist/cost.d.ts +3 -1
  38. package/dist/cost.d.ts.map +1 -1
  39. package/dist/cost.js +8 -3
  40. package/dist/cost.js.map +1 -1
  41. package/dist/drivers/anthropic.d.ts +6 -1
  42. package/dist/drivers/anthropic.d.ts.map +1 -1
  43. package/dist/drivers/anthropic.js +166 -21
  44. package/dist/drivers/anthropic.js.map +1 -1
  45. package/dist/drivers/openai-compatible.d.ts +1 -1
  46. package/dist/drivers/openai-compatible.d.ts.map +1 -1
  47. package/dist/drivers/openai-compatible.js +106 -70
  48. package/dist/drivers/openai-compatible.js.map +1 -1
  49. package/dist/errors.d.ts +24 -0
  50. package/dist/errors.d.ts.map +1 -1
  51. package/dist/errors.js +24 -0
  52. package/dist/errors.js.map +1 -1
  53. package/dist/index.d.ts +6 -4
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +3 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/json-schema.d.ts +33 -0
  58. package/dist/json-schema.d.ts.map +1 -0
  59. package/dist/json-schema.js +508 -0
  60. package/dist/json-schema.js.map +1 -0
  61. package/dist/log.d.ts.map +1 -1
  62. package/dist/log.js +3 -1
  63. package/dist/log.js.map +1 -1
  64. package/dist/mcp/client.d.ts +81 -0
  65. package/dist/mcp/client.d.ts.map +1 -0
  66. package/dist/mcp/client.js +401 -0
  67. package/dist/mcp/client.js.map +1 -0
  68. package/dist/mcp/endpoint.d.ts +54 -0
  69. package/dist/mcp/endpoint.d.ts.map +1 -0
  70. package/dist/mcp/endpoint.js +158 -0
  71. package/dist/mcp/endpoint.js.map +1 -0
  72. package/dist/mcp/host.d.ts +42 -0
  73. package/dist/mcp/host.d.ts.map +1 -0
  74. package/dist/mcp/host.js +111 -0
  75. package/dist/mcp/host.js.map +1 -0
  76. package/dist/mcp/http.d.ts +32 -0
  77. package/dist/mcp/http.d.ts.map +1 -0
  78. package/dist/mcp/http.js +190 -0
  79. package/dist/mcp/http.js.map +1 -0
  80. package/dist/mcp/index.d.ts +23 -0
  81. package/dist/mcp/index.d.ts.map +1 -0
  82. package/dist/mcp/index.js +21 -0
  83. package/dist/mcp/index.js.map +1 -0
  84. package/dist/mcp/manifest.d.ts +36 -0
  85. package/dist/mcp/manifest.d.ts.map +1 -0
  86. package/dist/mcp/manifest.js +40 -0
  87. package/dist/mcp/manifest.js.map +1 -0
  88. package/dist/mcp/rpc.d.ts +39 -0
  89. package/dist/mcp/rpc.d.ts.map +1 -0
  90. package/dist/mcp/rpc.js +149 -0
  91. package/dist/mcp/rpc.js.map +1 -0
  92. package/dist/mcp/stdio.d.ts +24 -0
  93. package/dist/mcp/stdio.d.ts.map +1 -0
  94. package/dist/mcp/stdio.js +157 -0
  95. package/dist/mcp/stdio.js.map +1 -0
  96. package/dist/mcp/worker-main.d.ts +6 -0
  97. package/dist/mcp/worker-main.d.ts.map +1 -0
  98. package/dist/mcp/worker-main.js +17 -0
  99. package/dist/mcp/worker-main.js.map +1 -0
  100. package/dist/mcp/worker.d.ts +54 -0
  101. package/dist/mcp/worker.d.ts.map +1 -0
  102. package/dist/mcp/worker.js +166 -0
  103. package/dist/mcp/worker.js.map +1 -0
  104. package/dist/meter.d.ts +6 -0
  105. package/dist/meter.d.ts.map +1 -1
  106. package/dist/meter.js +6 -3
  107. package/dist/meter.js.map +1 -1
  108. package/dist/redact.d.ts +4 -3
  109. package/dist/redact.d.ts.map +1 -1
  110. package/dist/redact.js +5 -4
  111. package/dist/redact.js.map +1 -1
  112. package/dist/redis-budget.d.ts +45 -0
  113. package/dist/redis-budget.d.ts.map +1 -0
  114. package/dist/redis-budget.js +56 -0
  115. package/dist/redis-budget.js.map +1 -0
  116. package/dist/response.d.ts +21 -3
  117. package/dist/response.d.ts.map +1 -1
  118. package/dist/response.js +71 -7
  119. package/dist/response.js.map +1 -1
  120. package/dist/server-sent.d.ts +9 -0
  121. package/dist/server-sent.d.ts.map +1 -0
  122. package/dist/server-sent.js +74 -0
  123. package/dist/server-sent.js.map +1 -0
  124. package/dist/server-tools.d.ts +12 -0
  125. package/dist/server-tools.d.ts.map +1 -0
  126. package/dist/server-tools.js +71 -0
  127. package/dist/server-tools.js.map +1 -0
  128. package/dist/services/catalog.d.ts +19 -0
  129. package/dist/services/catalog.d.ts.map +1 -0
  130. package/dist/services/catalog.js +37 -0
  131. package/dist/services/catalog.js.map +1 -0
  132. package/dist/skills/folder.d.ts +32 -0
  133. package/dist/skills/folder.d.ts.map +1 -0
  134. package/dist/skills/folder.js +170 -0
  135. package/dist/skills/folder.js.map +1 -0
  136. package/dist/skills/frontmatter.d.ts +15 -0
  137. package/dist/skills/frontmatter.d.ts.map +1 -0
  138. package/dist/skills/frontmatter.js +92 -0
  139. package/dist/skills/frontmatter.js.map +1 -0
  140. package/dist/skills/index.d.ts +18 -0
  141. package/dist/skills/index.d.ts.map +1 -0
  142. package/dist/skills/index.js +18 -0
  143. package/dist/skills/index.js.map +1 -0
  144. package/dist/skills/kit.d.ts +39 -0
  145. package/dist/skills/kit.d.ts.map +1 -0
  146. package/dist/skills/kit.js +124 -0
  147. package/dist/skills/kit.js.map +1 -0
  148. package/dist/skills/skill.d.ts +67 -0
  149. package/dist/skills/skill.d.ts.map +1 -0
  150. package/dist/skills/skill.js +114 -0
  151. package/dist/skills/skill.js.map +1 -0
  152. package/dist/sse.d.ts +43 -6
  153. package/dist/sse.d.ts.map +1 -1
  154. package/dist/sse.js +44 -18
  155. package/dist/sse.js.map +1 -1
  156. package/dist/testing/FakeProvider.d.ts.map +1 -1
  157. package/dist/testing/FakeProvider.js +1 -0
  158. package/dist/testing/FakeProvider.js.map +1 -1
  159. package/dist/tool-modules.d.ts +17 -0
  160. package/dist/tool-modules.d.ts.map +1 -0
  161. package/dist/tool-modules.js +43 -0
  162. package/dist/tool-modules.js.map +1 -0
  163. package/dist/tools.d.ts +69 -5
  164. package/dist/tools.d.ts.map +1 -1
  165. package/dist/tools.js +174 -31
  166. package/dist/tools.js.map +1 -1
  167. package/dist/transport.d.ts +8 -3
  168. package/dist/transport.d.ts.map +1 -1
  169. package/dist/transport.js +19 -4
  170. package/dist/transport.js.map +1 -1
  171. package/dist/types.d.ts +106 -2
  172. package/dist/types.d.ts.map +1 -1
  173. package/package.json +22 -1
  174. package/src/Polaris.ts +25 -1
  175. package/src/PolarisClient.ts +288 -51
  176. package/src/PolarisProvider.ts +40 -2
  177. package/src/augmentations.ts +4 -1
  178. package/src/budget.ts +115 -15
  179. package/src/catalog/catalog.ts +180 -0
  180. package/src/catalog/discover.ts +234 -0
  181. package/src/catalog/index.ts +19 -0
  182. package/src/commands/index.ts +412 -0
  183. package/src/cost.ts +9 -3
  184. package/src/drivers/anthropic.ts +203 -20
  185. package/src/drivers/openai-compatible.ts +143 -76
  186. package/src/errors.ts +41 -0
  187. package/src/index.ts +16 -0
  188. package/src/json-schema.ts +597 -0
  189. package/src/log.ts +3 -1
  190. package/src/mcp/client.ts +532 -0
  191. package/src/mcp/endpoint.ts +229 -0
  192. package/src/mcp/host.ts +140 -0
  193. package/src/mcp/http.ts +276 -0
  194. package/src/mcp/index.ts +51 -0
  195. package/src/mcp/manifest.ts +73 -0
  196. package/src/mcp/rpc.ts +197 -0
  197. package/src/mcp/stdio.ts +190 -0
  198. package/src/mcp/worker-main.ts +18 -0
  199. package/src/mcp/worker.ts +212 -0
  200. package/src/meter.ts +13 -2
  201. package/src/redact.ts +6 -3
  202. package/src/redis-budget.ts +85 -0
  203. package/src/response.ts +86 -8
  204. package/src/server-sent.ts +70 -0
  205. package/src/server-tools.ts +77 -0
  206. package/src/services/catalog.ts +43 -0
  207. package/src/skills/folder.ts +231 -0
  208. package/src/skills/frontmatter.ts +92 -0
  209. package/src/skills/index.ts +38 -0
  210. package/src/skills/kit.ts +163 -0
  211. package/src/skills/skill.ts +171 -0
  212. package/src/sse.ts +88 -22
  213. package/src/testing/FakeProvider.ts +1 -0
  214. package/src/tool-modules.ts +49 -0
  215. package/src/tools.ts +260 -27
  216. package/src/transport.ts +25 -3
  217. package/src/types.ts +108 -2
@@ -0,0 +1,532 @@
1
+ /**
2
+ * A connection to one MCP server, whose tools become polaris tools.
3
+ */
4
+
5
+ import { E_POLARIS_INVALID_REQUEST, E_POLARIS_MCP } from "../errors.js";
6
+ import { scrub } from "../redact.js";
7
+ import {
8
+ defineTool,
9
+ type PolarisTool,
10
+ type ToolContext,
11
+ ToolError,
12
+ } from "../tools.js";
13
+ import type { JsonSchema } from "../types.js";
14
+ import { type HttpChannel, type HttpServer, openHttp } from "./http.js";
15
+ import { isObject, type JsonObject, Session } from "./rpc.js";
16
+ import { openStdio, type StdioServer } from "./stdio.js";
17
+
18
+ /** The protocol revisions polaris speaks, newest first. */
19
+ export const MCP_PROTOCOL_VERSIONS = [
20
+ "2025-11-25",
21
+ "2025-06-18",
22
+ "2025-03-26",
23
+ "2024-11-05",
24
+ ] as const;
25
+
26
+ const DEFAULT_TIMEOUT_MS = 60_000;
27
+ const DEFAULT_MAX_RESULT_BYTES = 256 * 1024;
28
+ const DEFAULT_MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
29
+ /** Pages of `tools/list` read at most, and tools kept at most. */
30
+ const MAX_PAGES = 50;
31
+ const MAX_TOOLS = 1_000;
32
+ const PREFIX = /^[a-zA-Z0-9_-]*$/;
33
+
34
+ export interface McpOptions {
35
+ /** What the server is called in errors: `github`, `files`. */
36
+ readonly name: string;
37
+ readonly server: StdioServer | HttpServer;
38
+ /**
39
+ * The tools the model may see, by the server's names, or `all`. A name the
40
+ * server does not offer is listed in `skipped`.
41
+ */
42
+ readonly allow: readonly string[] | "all";
43
+ /** Put before every tool's name (`github_`), to keep the names of two servers apart. */
44
+ readonly prefix?: string;
45
+ /** Milliseconds one request may take, connecting included. Default 60 000. */
46
+ readonly timeout?: number;
47
+ /**
48
+ * Bytes of a tool's result, as the model would read it. A larger one is
49
+ * answered with a tool error. Default 256 KiB.
50
+ */
51
+ readonly maxResultBytes?: number;
52
+ /** Bytes of one message from the server. Default 4 MiB. */
53
+ readonly maxMessageBytes?: number;
54
+ /** Cancels connecting. */
55
+ readonly signal?: AbortSignal;
56
+ /**
57
+ * Told of what fails in the background: reading a tool list that changed,
58
+ * the stream an HTTP server sends notifications on.
59
+ */
60
+ readonly onError?: (error: unknown) => void;
61
+ }
62
+
63
+ /** A tool of the server the model does not see, and why. */
64
+ export interface SkippedTool {
65
+ readonly name: string;
66
+ readonly reason: string;
67
+ }
68
+
69
+ /** What the server says of itself. Written by the server: untrusted. */
70
+ export interface McpServerInfo {
71
+ readonly name?: string;
72
+ readonly version?: string;
73
+ readonly instructions?: string;
74
+ readonly protocolVersion: string;
75
+ }
76
+
77
+ interface Listed {
78
+ readonly name: string;
79
+ readonly description: string;
80
+ /** Absent when the server gave none: the tool is skipped. */
81
+ readonly inputSchema: JsonSchema | undefined;
82
+ }
83
+
84
+ /** Connect to an MCP server and read its tools. */
85
+ export async function connectMcp(options: McpOptions): Promise<McpClient> {
86
+ const settings = check(options);
87
+ const secrets = new Set<string>();
88
+ const server = options.server;
89
+ let http: HttpChannel | undefined;
90
+ let client: McpClient | undefined;
91
+ const pendingNotifications: string[] = [];
92
+
93
+ const session = new Session(
94
+ options.name,
95
+ (events) => {
96
+ if (server.type === "stdio") {
97
+ for (const value of Object.values(server.env ?? {})) secrets.add(value);
98
+ return openStdio(
99
+ options.name,
100
+ server,
101
+ settings.maxMessageBytes,
102
+ events,
103
+ );
104
+ }
105
+ for (const value of Object.values(server.headers ?? {}))
106
+ secrets.add(value);
107
+ const password = new URL(server.url).password;
108
+ if (password !== "") secrets.add(decodeURIComponent(password));
109
+ http = openHttp(
110
+ options.name,
111
+ server,
112
+ settings.maxMessageBytes,
113
+ secrets,
114
+ events,
115
+ );
116
+ return http;
117
+ },
118
+ (method) => {
119
+ if (client) client.notified(method);
120
+ else pendingNotifications.push(method);
121
+ },
122
+ );
123
+ const clean = (error: unknown): unknown =>
124
+ scrub(error, options.name, [...secrets], (name, message) => {
125
+ const prefix = `[polaris] the MCP server '${name}' failed: `;
126
+ return new E_POLARIS_MCP([
127
+ name,
128
+ message.startsWith(prefix) ? message.slice(prefix.length) : message,
129
+ ]);
130
+ });
131
+
132
+ try {
133
+ const init = await session.request(
134
+ "initialize",
135
+ {
136
+ protocolVersion: MCP_PROTOCOL_VERSIONS[0],
137
+ capabilities: {},
138
+ clientInfo: { name: "polaris", version: "0.1" },
139
+ },
140
+ {
141
+ timeout: settings.timeout,
142
+ signal: options.signal,
143
+ cancellable: false,
144
+ },
145
+ );
146
+ if (!isObject(init) || typeof init.protocolVersion !== "string") {
147
+ throw new E_POLARIS_MCP([
148
+ options.name,
149
+ "its `initialize` result is not valid",
150
+ ]);
151
+ }
152
+ const version = init.protocolVersion;
153
+ if (!(MCP_PROTOCOL_VERSIONS as readonly string[]).includes(version)) {
154
+ throw new E_POLARIS_MCP([
155
+ options.name,
156
+ `it speaks protocol version '${version.slice(0, 40)}', which polaris does not`,
157
+ ]);
158
+ }
159
+ http?.negotiated(version);
160
+ session.notify("notifications/initialized");
161
+
162
+ const serverInfo = isObject(init.serverInfo) ? init.serverInfo : {};
163
+ const capabilities = isObject(init.capabilities) ? init.capabilities : {};
164
+ const info: McpServerInfo = {
165
+ protocolVersion: version,
166
+ ...(typeof serverInfo.name === "string" ? { name: serverInfo.name } : {}),
167
+ ...(typeof serverInfo.version === "string"
168
+ ? { version: serverInfo.version }
169
+ : {}),
170
+ ...(typeof init.instructions === "string"
171
+ ? { instructions: init.instructions }
172
+ : {}),
173
+ };
174
+ client = new McpClient(session, options, settings, info, clean, () =>
175
+ isObject(capabilities.tools),
176
+ );
177
+ await client.refresh(options.signal);
178
+ for (const method of pendingNotifications) client.notified(method);
179
+ const tools = capabilities.tools;
180
+ if (isObject(tools) && tools.listChanged === true) {
181
+ http?.listen((error) => options.onError?.(clean(error)));
182
+ }
183
+ return client;
184
+ } catch (error) {
185
+ await session.close();
186
+ throw clean(error);
187
+ }
188
+ }
189
+
190
+ interface Settings {
191
+ readonly prefix: string;
192
+ readonly timeout: number;
193
+ readonly maxResultBytes: number;
194
+ readonly maxMessageBytes: number;
195
+ }
196
+
197
+ function check(options: McpOptions): Settings {
198
+ const refuse = (problem: string): never => {
199
+ throw new E_POLARIS_INVALID_REQUEST([problem]);
200
+ };
201
+ if (typeof options.name !== "string" || options.name === "") {
202
+ refuse("an MCP server needs a `name`");
203
+ }
204
+ const server = options.server;
205
+ if (
206
+ !isObject(server) ||
207
+ (server.type !== "stdio" && server.type !== "http")
208
+ ) {
209
+ refuse("`server.type` is `stdio` or `http`");
210
+ }
211
+ if (
212
+ server.type === "stdio" &&
213
+ (typeof server.command !== "string" || server.command === "")
214
+ ) {
215
+ refuse("a stdio server needs a `command`");
216
+ }
217
+ if (server.type === "http") {
218
+ try {
219
+ const url = new URL(server.url);
220
+ if (url.protocol !== "https:" && url.protocol !== "http:")
221
+ throw new Error();
222
+ } catch {
223
+ refuse("an HTTP server needs an http(s) `url`");
224
+ }
225
+ }
226
+ const allow = options.allow;
227
+ if (
228
+ allow !== "all" &&
229
+ !(Array.isArray(allow) && allow.every((name) => typeof name === "string"))
230
+ ) {
231
+ refuse("`allow` is a list of tool names, or `all`");
232
+ }
233
+ const prefix = options.prefix ?? "";
234
+ if (typeof prefix !== "string" || !PREFIX.test(prefix)) {
235
+ refuse("`prefix` holds only letters, digits, `_` and `-`");
236
+ }
237
+ const count = (
238
+ key: string,
239
+ value: number | undefined,
240
+ fallback: number,
241
+ ): number => {
242
+ const chosen = value ?? fallback;
243
+ if (!(Number.isSafeInteger(chosen) && chosen > 0)) {
244
+ refuse(`\`${key}\` must be a positive integer`);
245
+ }
246
+ return chosen;
247
+ };
248
+ return {
249
+ prefix,
250
+ timeout: count("timeout", options.timeout, DEFAULT_TIMEOUT_MS),
251
+ maxResultBytes: count(
252
+ "maxResultBytes",
253
+ options.maxResultBytes,
254
+ DEFAULT_MAX_RESULT_BYTES,
255
+ ),
256
+ maxMessageBytes: count(
257
+ "maxMessageBytes",
258
+ options.maxMessageBytes,
259
+ DEFAULT_MAX_MESSAGE_BYTES,
260
+ ),
261
+ };
262
+ }
263
+
264
+ /**
265
+ * One MCP server's tools, as polaris tools. `tools` is what to give a run;
266
+ * a run that calls one of them is given the server's new tools when its list
267
+ * changes.
268
+ */
269
+ export class McpClient {
270
+ readonly #session: Session;
271
+ readonly #options: McpOptions;
272
+ readonly #settings: Settings;
273
+ readonly #clean: (error: unknown) => unknown;
274
+ readonly #hasTools: () => boolean;
275
+ /** Every tool built so far, by the server's name: kept, so a run sees one object per name. */
276
+ readonly #built = new Map<string, PolarisTool>();
277
+ /** The server's names offered by its last list. */
278
+ #offered = new Set<string>();
279
+ #tools: readonly PolarisTool[] = [];
280
+ #skipped: readonly SkippedTool[] = [];
281
+ #refreshing: Promise<void> | undefined;
282
+ #stale = false;
283
+ #closed = false;
284
+
285
+ /** What the server said of itself when connecting. */
286
+ readonly server: McpServerInfo;
287
+
288
+ /** @internal Use {@link connectMcp}. */
289
+ constructor(
290
+ session: Session,
291
+ options: McpOptions,
292
+ settings: Settings,
293
+ server: McpServerInfo,
294
+ clean: (error: unknown) => unknown,
295
+ hasTools: () => boolean,
296
+ ) {
297
+ this.#session = session;
298
+ this.#options = options;
299
+ this.#settings = settings;
300
+ this.server = server;
301
+ this.#clean = clean;
302
+ this.#hasTools = hasTools;
303
+ }
304
+
305
+ /** The server's tools the model may call: allowed, and usable by polaris. */
306
+ get tools(): readonly PolarisTool[] {
307
+ return this.#tools;
308
+ }
309
+
310
+ /** Allowed tools the model does not see, and why. */
311
+ get skipped(): readonly SkippedTool[] {
312
+ return this.#skipped;
313
+ }
314
+
315
+ /** End the session, and the server's process for a stdio server. */
316
+ async close(): Promise<void> {
317
+ if (this.#closed) return;
318
+ this.#closed = true;
319
+ await this.#session.close();
320
+ }
321
+
322
+ /** @internal A notification from the server. */
323
+ notified(method: string): void {
324
+ if (method !== "notifications/tools/list_changed" || this.#closed) return;
325
+ if (this.#refreshing !== undefined) {
326
+ this.#stale = true;
327
+ return;
328
+ }
329
+ this.#refreshing = (async () => {
330
+ do {
331
+ this.#stale = false;
332
+ await this.refresh();
333
+ } while (this.#stale && !this.#closed);
334
+ })()
335
+ .catch((error: unknown) => {
336
+ if (!this.#closed) this.#options.onError?.(this.#clean(error));
337
+ })
338
+ .finally(() => {
339
+ this.#refreshing = undefined;
340
+ });
341
+ }
342
+
343
+ /** @internal Read the server's tool list again. */
344
+ async refresh(signal?: AbortSignal): Promise<void> {
345
+ const listed = this.#hasTools() ? await this.#list(signal) : [];
346
+ const allow = this.#options.allow;
347
+ const allowed = (name: string): boolean =>
348
+ allow === "all" || allow.includes(name);
349
+ const skipped: SkippedTool[] = [];
350
+ const offered = new Set<string>();
351
+ const tools: PolarisTool[] = [];
352
+
353
+ for (const entry of listed) {
354
+ if (!allowed(entry.name)) continue;
355
+ offered.add(entry.name);
356
+ let tool = this.#built.get(entry.name);
357
+ if (tool === undefined) {
358
+ try {
359
+ tool = this.#build(entry);
360
+ } catch (error) {
361
+ skipped.push({
362
+ name: entry.name,
363
+ reason: error instanceof Error ? error.message : String(error),
364
+ });
365
+ continue;
366
+ }
367
+ this.#built.set(entry.name, tool);
368
+ }
369
+ tools.push(tool);
370
+ }
371
+ if (allow !== "all") {
372
+ const names = new Set(listed.map((entry) => entry.name));
373
+ for (const name of allow) {
374
+ if (!names.has(name)) {
375
+ skipped.push({ name, reason: "the server does not offer it" });
376
+ }
377
+ }
378
+ }
379
+ this.#offered = offered;
380
+ this.#tools = tools;
381
+ this.#skipped = skipped;
382
+ }
383
+
384
+ async #list(signal: AbortSignal | undefined): Promise<Listed[]> {
385
+ const listed: Listed[] = [];
386
+ let cursor: string | undefined;
387
+ for (let page = 0; page < MAX_PAGES; page++) {
388
+ const result = await this.#session.request(
389
+ "tools/list",
390
+ cursor !== undefined ? { cursor } : undefined,
391
+ { timeout: this.#settings.timeout, signal },
392
+ );
393
+ if (!isObject(result) || !Array.isArray(result.tools)) {
394
+ throw new E_POLARIS_MCP([
395
+ this.#options.name,
396
+ "its tool list is not valid",
397
+ ]);
398
+ }
399
+ for (const entry of result.tools) {
400
+ if (!isObject(entry) || typeof entry.name !== "string") continue;
401
+ listed.push({
402
+ name: entry.name,
403
+ description:
404
+ typeof entry.description === "string"
405
+ ? entry.description
406
+ : typeof entry.title === "string"
407
+ ? entry.title
408
+ : "",
409
+ inputSchema: isObject(entry.inputSchema)
410
+ ? (entry.inputSchema as JsonSchema)
411
+ : undefined,
412
+ });
413
+ }
414
+ if (listed.length > MAX_TOOLS) {
415
+ throw new E_POLARIS_MCP([
416
+ this.#options.name,
417
+ `it offers more than ${MAX_TOOLS} tools`,
418
+ ]);
419
+ }
420
+ if (typeof result.nextCursor !== "string") return listed;
421
+ cursor = result.nextCursor;
422
+ }
423
+ throw new E_POLARIS_MCP([
424
+ this.#options.name,
425
+ `its tool list runs over more than ${MAX_PAGES} pages`,
426
+ ]);
427
+ }
428
+
429
+ #build(entry: Listed): PolarisTool {
430
+ if (entry.inputSchema === undefined) {
431
+ throw new Error("it has no input schema");
432
+ }
433
+ const name = `${this.#settings.prefix}${entry.name}`;
434
+ return defineTool<JsonObject>({
435
+ name,
436
+ description: entry.description,
437
+ inputSchema: entry.inputSchema,
438
+ run: (input, context) => this.#call(entry.name, input, context),
439
+ });
440
+ }
441
+
442
+ async #call(
443
+ name: string,
444
+ input: JsonObject,
445
+ context: ToolContext,
446
+ ): Promise<string> {
447
+ if (!this.#offered.has(name)) {
448
+ throw new ToolError(`The server no longer offers the tool '${name}'.`);
449
+ }
450
+ let result: unknown;
451
+ try {
452
+ result = await this.#session.request(
453
+ "tools/call",
454
+ { name, arguments: input },
455
+ { timeout: this.#settings.timeout, signal: context.signal },
456
+ );
457
+ } catch (error) {
458
+ throw this.#clean(error);
459
+ }
460
+ const text = resultText(this.#options.name, result);
461
+ // A server tells of a changed list before it answers: let the list be
462
+ // read again, so the run gets the new tools from the next request.
463
+ if (this.#refreshing !== undefined) await this.#refreshing;
464
+ this.#grow(context);
465
+ if (Buffer.byteLength(text, "utf8") > this.#settings.maxResultBytes) {
466
+ throw new ToolError(
467
+ `The result is larger than ${this.#settings.maxResultBytes} bytes, and was dropped. Ask for less.`,
468
+ );
469
+ }
470
+ if (isObject(result) && result.isError === true) {
471
+ throw new ToolError(text === "" ? "The tool failed." : text);
472
+ }
473
+ return text;
474
+ }
475
+
476
+ /** Give the run the server's current tools: the new ones join it. */
477
+ #grow(context: ToolContext): void {
478
+ try {
479
+ context.addTools(this.#tools);
480
+ } catch (error) {
481
+ // Outside a run, past the run's limit, or a name the run already has.
482
+ if (!(error instanceof ToolError)) throw error;
483
+ }
484
+ }
485
+ }
486
+
487
+ /** What the model reads of a `tools/call` result. */
488
+ function resultText(server: string, result: unknown): string {
489
+ if (!isObject(result)) {
490
+ throw new E_POLARIS_MCP([server, "a tool result is not valid"]);
491
+ }
492
+ const content = result.content ?? [];
493
+ if (!Array.isArray(content)) {
494
+ throw new E_POLARIS_MCP([server, "a tool result is not valid"]);
495
+ }
496
+ const parts = content.map(partText);
497
+ if (parts.length === 0 && result.structuredContent !== undefined) {
498
+ return JSON.stringify(result.structuredContent);
499
+ }
500
+ return parts.join("\n\n");
501
+ }
502
+
503
+ function partText(part: unknown): string {
504
+ if (!isObject(part)) return "[content not shown]";
505
+ const mime =
506
+ typeof part.mimeType === "string" ? part.mimeType : "unknown type";
507
+ const size = (data: unknown): string =>
508
+ typeof data === "string"
509
+ ? `, about ${Math.floor((data.length * 3) / 4)} bytes`
510
+ : "";
511
+ switch (part.type) {
512
+ case "text":
513
+ return typeof part.text === "string" ? part.text : "";
514
+ case "image":
515
+ return `[image: ${mime}${size(part.data)}, not shown]`;
516
+ case "audio":
517
+ return `[audio: ${mime}${size(part.data)}, not shown]`;
518
+ case "resource_link":
519
+ return `[resource: ${String(part.uri)}]`;
520
+ case "resource": {
521
+ const resource = isObject(part.resource) ? part.resource : {};
522
+ if (typeof resource.text === "string") return resource.text;
523
+ const type =
524
+ typeof resource.mimeType === "string"
525
+ ? resource.mimeType
526
+ : "unknown type";
527
+ return `[resource: ${String(resource.uri)}, ${type}${size(resource.blob)}, not shown]`;
528
+ }
529
+ default:
530
+ return `[${typeof part.type === "string" ? part.type.slice(0, 40) : "unknown"} content, not shown]`;
531
+ }
532
+ }