@c9up/polaris 0.0.0-stage → 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 (253) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1146 -2
  3. package/dist/Polaris.d.ts +80 -0
  4. package/dist/Polaris.d.ts.map +1 -0
  5. package/dist/Polaris.js +208 -0
  6. package/dist/Polaris.js.map +1 -0
  7. package/dist/PolarisClient.d.ts +184 -0
  8. package/dist/PolarisClient.d.ts.map +1 -0
  9. package/dist/PolarisClient.js +576 -0
  10. package/dist/PolarisClient.js.map +1 -0
  11. package/dist/PolarisProvider.d.ts +40 -0
  12. package/dist/PolarisProvider.d.ts.map +1 -0
  13. package/dist/PolarisProvider.js +79 -0
  14. package/dist/PolarisProvider.js.map +1 -0
  15. package/dist/augmentations.d.ts +18 -0
  16. package/dist/augmentations.d.ts.map +1 -0
  17. package/dist/augmentations.js +9 -0
  18. package/dist/augmentations.js.map +1 -0
  19. package/dist/budget.d.ts +77 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +134 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/catalog/catalog.d.ts +37 -0
  24. package/dist/catalog/catalog.d.ts.map +1 -0
  25. package/dist/catalog/catalog.js +145 -0
  26. package/dist/catalog/catalog.js.map +1 -0
  27. package/dist/catalog/discover.d.ts +64 -0
  28. package/dist/catalog/discover.d.ts.map +1 -0
  29. package/dist/catalog/discover.js +148 -0
  30. package/dist/catalog/discover.js.map +1 -0
  31. package/dist/catalog/index.d.ts +8 -0
  32. package/dist/catalog/index.d.ts.map +1 -0
  33. package/dist/catalog/index.js +8 -0
  34. package/dist/catalog/index.js.map +1 -0
  35. package/dist/commands/index.d.ts +82 -0
  36. package/dist/commands/index.d.ts.map +1 -0
  37. package/dist/commands/index.js +278 -0
  38. package/dist/commands/index.js.map +1 -0
  39. package/dist/cost.d.ts +50 -0
  40. package/dist/cost.d.ts.map +1 -0
  41. package/dist/cost.js +131 -0
  42. package/dist/cost.js.map +1 -0
  43. package/dist/drivers/anthropic.d.ts +44 -0
  44. package/dist/drivers/anthropic.d.ts.map +1 -0
  45. package/dist/drivers/anthropic.js +539 -0
  46. package/dist/drivers/anthropic.js.map +1 -0
  47. package/dist/drivers/openai-compatible.d.ts +54 -0
  48. package/dist/drivers/openai-compatible.d.ts.map +1 -0
  49. package/dist/drivers/openai-compatible.js +699 -0
  50. package/dist/drivers/openai-compatible.js.map +1 -0
  51. package/dist/drivers/status.d.ts +8 -0
  52. package/dist/drivers/status.d.ts.map +1 -0
  53. package/dist/drivers/status.js +21 -0
  54. package/dist/drivers/status.js.map +1 -0
  55. package/dist/errors.d.ts +79 -0
  56. package/dist/errors.d.ts.map +1 -0
  57. package/dist/errors.js +86 -0
  58. package/dist/errors.js.map +1 -0
  59. package/dist/extract.d.ts +38 -0
  60. package/dist/extract.d.ts.map +1 -0
  61. package/dist/extract.js +144 -0
  62. package/dist/extract.js.map +1 -0
  63. package/dist/index.d.ts +21 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +15 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/json-schema.d.ts +33 -0
  68. package/dist/json-schema.d.ts.map +1 -0
  69. package/dist/json-schema.js +508 -0
  70. package/dist/json-schema.js.map +1 -0
  71. package/dist/log.d.ts +47 -0
  72. package/dist/log.d.ts.map +1 -0
  73. package/dist/log.js +35 -0
  74. package/dist/log.js.map +1 -0
  75. package/dist/mcp/client.d.ts +81 -0
  76. package/dist/mcp/client.d.ts.map +1 -0
  77. package/dist/mcp/client.js +401 -0
  78. package/dist/mcp/client.js.map +1 -0
  79. package/dist/mcp/endpoint.d.ts +54 -0
  80. package/dist/mcp/endpoint.d.ts.map +1 -0
  81. package/dist/mcp/endpoint.js +158 -0
  82. package/dist/mcp/endpoint.js.map +1 -0
  83. package/dist/mcp/host.d.ts +42 -0
  84. package/dist/mcp/host.d.ts.map +1 -0
  85. package/dist/mcp/host.js +111 -0
  86. package/dist/mcp/host.js.map +1 -0
  87. package/dist/mcp/http.d.ts +32 -0
  88. package/dist/mcp/http.d.ts.map +1 -0
  89. package/dist/mcp/http.js +190 -0
  90. package/dist/mcp/http.js.map +1 -0
  91. package/dist/mcp/index.d.ts +23 -0
  92. package/dist/mcp/index.d.ts.map +1 -0
  93. package/dist/mcp/index.js +21 -0
  94. package/dist/mcp/index.js.map +1 -0
  95. package/dist/mcp/manifest.d.ts +36 -0
  96. package/dist/mcp/manifest.d.ts.map +1 -0
  97. package/dist/mcp/manifest.js +40 -0
  98. package/dist/mcp/manifest.js.map +1 -0
  99. package/dist/mcp/rpc.d.ts +39 -0
  100. package/dist/mcp/rpc.d.ts.map +1 -0
  101. package/dist/mcp/rpc.js +149 -0
  102. package/dist/mcp/rpc.js.map +1 -0
  103. package/dist/mcp/stdio.d.ts +24 -0
  104. package/dist/mcp/stdio.d.ts.map +1 -0
  105. package/dist/mcp/stdio.js +157 -0
  106. package/dist/mcp/stdio.js.map +1 -0
  107. package/dist/mcp/worker-main.d.ts +6 -0
  108. package/dist/mcp/worker-main.d.ts.map +1 -0
  109. package/dist/mcp/worker-main.js +17 -0
  110. package/dist/mcp/worker-main.js.map +1 -0
  111. package/dist/mcp/worker.d.ts +54 -0
  112. package/dist/mcp/worker.d.ts.map +1 -0
  113. package/dist/mcp/worker.js +166 -0
  114. package/dist/mcp/worker.js.map +1 -0
  115. package/dist/meter.d.ts +63 -0
  116. package/dist/meter.d.ts.map +1 -0
  117. package/dist/meter.js +94 -0
  118. package/dist/meter.js.map +1 -0
  119. package/dist/providers.d.ts +23 -0
  120. package/dist/providers.d.ts.map +1 -0
  121. package/dist/providers.js +21 -0
  122. package/dist/providers.js.map +1 -0
  123. package/dist/redact.d.ts +12 -0
  124. package/dist/redact.d.ts.map +1 -0
  125. package/dist/redact.js +77 -0
  126. package/dist/redact.js.map +1 -0
  127. package/dist/redis-budget.d.ts +45 -0
  128. package/dist/redis-budget.d.ts.map +1 -0
  129. package/dist/redis-budget.js +56 -0
  130. package/dist/redis-budget.js.map +1 -0
  131. package/dist/response.d.ts +39 -0
  132. package/dist/response.d.ts.map +1 -0
  133. package/dist/response.js +109 -0
  134. package/dist/response.js.map +1 -0
  135. package/dist/schema.d.ts +45 -0
  136. package/dist/schema.d.ts.map +1 -0
  137. package/dist/schema.js +43 -0
  138. package/dist/schema.js.map +1 -0
  139. package/dist/server-sent.d.ts +9 -0
  140. package/dist/server-sent.d.ts.map +1 -0
  141. package/dist/server-sent.js +74 -0
  142. package/dist/server-sent.js.map +1 -0
  143. package/dist/server-tools.d.ts +12 -0
  144. package/dist/server-tools.d.ts.map +1 -0
  145. package/dist/server-tools.js +71 -0
  146. package/dist/server-tools.js.map +1 -0
  147. package/dist/services/catalog.d.ts +19 -0
  148. package/dist/services/catalog.d.ts.map +1 -0
  149. package/dist/services/catalog.js +37 -0
  150. package/dist/services/catalog.js.map +1 -0
  151. package/dist/services/main.d.ts +23 -0
  152. package/dist/services/main.d.ts.map +1 -0
  153. package/dist/services/main.js +43 -0
  154. package/dist/services/main.js.map +1 -0
  155. package/dist/skills/folder.d.ts +32 -0
  156. package/dist/skills/folder.d.ts.map +1 -0
  157. package/dist/skills/folder.js +170 -0
  158. package/dist/skills/folder.js.map +1 -0
  159. package/dist/skills/frontmatter.d.ts +15 -0
  160. package/dist/skills/frontmatter.d.ts.map +1 -0
  161. package/dist/skills/frontmatter.js +92 -0
  162. package/dist/skills/frontmatter.js.map +1 -0
  163. package/dist/skills/index.d.ts +18 -0
  164. package/dist/skills/index.d.ts.map +1 -0
  165. package/dist/skills/index.js +18 -0
  166. package/dist/skills/index.js.map +1 -0
  167. package/dist/skills/kit.d.ts +39 -0
  168. package/dist/skills/kit.d.ts.map +1 -0
  169. package/dist/skills/kit.js +124 -0
  170. package/dist/skills/kit.js.map +1 -0
  171. package/dist/skills/skill.d.ts +67 -0
  172. package/dist/skills/skill.d.ts.map +1 -0
  173. package/dist/skills/skill.js +114 -0
  174. package/dist/skills/skill.js.map +1 -0
  175. package/dist/sse.d.ts +95 -0
  176. package/dist/sse.d.ts.map +1 -0
  177. package/dist/sse.js +117 -0
  178. package/dist/sse.js.map +1 -0
  179. package/dist/testing/FakeProvider.d.ts +85 -0
  180. package/dist/testing/FakeProvider.d.ts.map +1 -0
  181. package/dist/testing/FakeProvider.js +214 -0
  182. package/dist/testing/FakeProvider.js.map +1 -0
  183. package/dist/testing/index.d.ts +7 -0
  184. package/dist/testing/index.d.ts.map +1 -0
  185. package/dist/testing/index.js +7 -0
  186. package/dist/testing/index.js.map +1 -0
  187. package/dist/tool-modules.d.ts +17 -0
  188. package/dist/tool-modules.d.ts.map +1 -0
  189. package/dist/tool-modules.js +43 -0
  190. package/dist/tool-modules.js.map +1 -0
  191. package/dist/tools.d.ts +132 -0
  192. package/dist/tools.d.ts.map +1 -0
  193. package/dist/tools.js +250 -0
  194. package/dist/tools.js.map +1 -0
  195. package/dist/transport.d.ts +23 -0
  196. package/dist/transport.d.ts.map +1 -0
  197. package/dist/transport.js +83 -0
  198. package/dist/transport.js.map +1 -0
  199. package/dist/types.d.ts +397 -0
  200. package/dist/types.d.ts.map +1 -0
  201. package/dist/types.js +12 -0
  202. package/dist/types.js.map +1 -0
  203. package/package.json +97 -3
  204. package/src/Polaris.ts +304 -0
  205. package/src/PolarisClient.ts +828 -0
  206. package/src/PolarisProvider.ts +111 -0
  207. package/src/augmentations.ts +20 -0
  208. package/src/budget.ts +201 -0
  209. package/src/catalog/catalog.ts +180 -0
  210. package/src/catalog/discover.ts +234 -0
  211. package/src/catalog/index.ts +19 -0
  212. package/src/commands/index.ts +412 -0
  213. package/src/cost.ts +176 -0
  214. package/src/drivers/anthropic.ts +703 -0
  215. package/src/drivers/openai-compatible.ts +907 -0
  216. package/src/drivers/status.ts +30 -0
  217. package/src/errors.ts +202 -0
  218. package/src/extract.ts +214 -0
  219. package/src/index.ts +85 -0
  220. package/src/json-schema.ts +597 -0
  221. package/src/log.ts +86 -0
  222. package/src/mcp/client.ts +532 -0
  223. package/src/mcp/endpoint.ts +229 -0
  224. package/src/mcp/host.ts +140 -0
  225. package/src/mcp/http.ts +276 -0
  226. package/src/mcp/index.ts +51 -0
  227. package/src/mcp/manifest.ts +73 -0
  228. package/src/mcp/rpc.ts +197 -0
  229. package/src/mcp/stdio.ts +190 -0
  230. package/src/mcp/worker-main.ts +18 -0
  231. package/src/mcp/worker.ts +212 -0
  232. package/src/meter.ts +199 -0
  233. package/src/providers.ts +25 -0
  234. package/src/redact.ts +81 -0
  235. package/src/redis-budget.ts +85 -0
  236. package/src/response.ts +143 -0
  237. package/src/schema.ts +88 -0
  238. package/src/server-sent.ts +70 -0
  239. package/src/server-tools.ts +77 -0
  240. package/src/services/catalog.ts +43 -0
  241. package/src/services/main.ts +49 -0
  242. package/src/skills/folder.ts +231 -0
  243. package/src/skills/frontmatter.ts +92 -0
  244. package/src/skills/index.ts +38 -0
  245. package/src/skills/kit.ts +163 -0
  246. package/src/skills/skill.ts +171 -0
  247. package/src/sse.ts +194 -0
  248. package/src/testing/FakeProvider.ts +322 -0
  249. package/src/testing/index.ts +12 -0
  250. package/src/tool-modules.ts +49 -0
  251. package/src/tools.ts +399 -0
  252. package/src/transport.ts +107 -0
  253. package/src/types.ts +434 -0
@@ -0,0 +1,229 @@
1
+ /**
2
+ * The application's tools as an MCP server over Streamable HTTP, in a route
3
+ * of the application, behind the application's own authentication.
4
+ *
5
+ * Stateless: each POST carries one JSON-RPC message and is answered with
6
+ * JSON. No session, no server-sent stream, no notification of a changed
7
+ * tool list: an agent reads the list when it connects.
8
+ */
9
+
10
+ import type { PolarisTool } from "../tools.js";
11
+ import { type OnHostedToolError, ToolHost } from "./host.js";
12
+ import { isObject, type JsonObject } from "./rpc.js";
13
+
14
+ /** The protocol revisions the endpoint answers, newest first. */
15
+ const VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
16
+
17
+ const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
18
+ const DEFAULT_TIMEOUT_MS = 60_000;
19
+
20
+ export interface McpEndpointOptions {
21
+ /** The tools agents may list and call. */
22
+ readonly tools: readonly PolarisTool[];
23
+ /** What the server calls itself in `initialize`. Default `polaris`. */
24
+ readonly name?: string;
25
+ readonly version?: string;
26
+ /** Told to the agent at `initialize`: how to use the tools. */
27
+ readonly instructions?: string;
28
+ /** Bytes of a request body. A larger one is answered 413. Default 1 MiB. */
29
+ readonly maxBodyBytes?: number;
30
+ /** Milliseconds a tool may take. Default 60 000. */
31
+ readonly timeout?: number;
32
+ /**
33
+ * The `Origin` values a request may carry. A request from a browser
34
+ * carries one: unless it is listed, it is answered 403, so a page cannot
35
+ * drive the tools with the user's cookies. Agents send none.
36
+ */
37
+ readonly allowedOrigins?: readonly string[];
38
+ /** Told of every failed call, with the error the agent does not see. */
39
+ readonly onToolError?: OnHostedToolError;
40
+ }
41
+
42
+ /** A request, whichever framework received it. */
43
+ export interface EndpointRequest {
44
+ readonly method: string;
45
+ /** A header's value, by its lower-case name. */
46
+ header(name: string): string | null | undefined;
47
+ readonly body: string | Uint8Array;
48
+ /** Aborted when the client leaves: the running tool is cancelled. */
49
+ readonly signal?: AbortSignal;
50
+ }
51
+
52
+ export interface EndpointResponse {
53
+ readonly status: number;
54
+ readonly headers: Readonly<Record<string, string>>;
55
+ /** Empty when there is nothing to send. */
56
+ readonly body: string;
57
+ }
58
+
59
+ export interface McpEndpoint {
60
+ /** Answer one request. Never rejects. */
61
+ handle(request: EndpointRequest): Promise<EndpointResponse>;
62
+ /** The same, for a Fetch API `Request`. */
63
+ fetch(request: Request): Promise<Response>;
64
+ }
65
+
66
+ type Id = string | number | null;
67
+
68
+ const json = (status: number, message: unknown): EndpointResponse => ({
69
+ status,
70
+ headers: { "content-type": "application/json" },
71
+ body: JSON.stringify(message),
72
+ });
73
+
74
+ const failure = (
75
+ status: number,
76
+ id: Id,
77
+ code: number,
78
+ message: string,
79
+ ): EndpointResponse =>
80
+ json(status, { jsonrpc: "2.0", id, error: { code, message } });
81
+
82
+ export function mcpEndpoint(options: McpEndpointOptions): McpEndpoint {
83
+ const host = new ToolHost(options.tools, options.onToolError);
84
+ const names = new Set(host.definitions.map((tool) => tool.name));
85
+ const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
86
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
87
+ const origins = new Set(options.allowedOrigins ?? []);
88
+ const decoder = new TextDecoder("utf-8", { fatal: true });
89
+
90
+ const answer = async (
91
+ id: string | number,
92
+ method: string,
93
+ params: JsonObject,
94
+ signal: AbortSignal | undefined,
95
+ ): Promise<EndpointResponse> => {
96
+ const result = (value: unknown) =>
97
+ json(200, { jsonrpc: "2.0", id, result: value });
98
+ switch (method) {
99
+ case "initialize": {
100
+ const asked = params.protocolVersion;
101
+ return result({
102
+ protocolVersion:
103
+ typeof asked === "string" && VERSIONS.includes(asked)
104
+ ? asked
105
+ : VERSIONS[0],
106
+ capabilities: { tools: { listChanged: false } },
107
+ serverInfo: {
108
+ name: options.name ?? "polaris",
109
+ version: options.version ?? "0.0.0",
110
+ },
111
+ ...(options.instructions !== undefined
112
+ ? { instructions: options.instructions }
113
+ : {}),
114
+ });
115
+ }
116
+ case "ping":
117
+ return result({});
118
+ case "tools/list":
119
+ return result({ tools: host.definitions });
120
+ case "tools/call": {
121
+ const { name } = params;
122
+ if (typeof name !== "string") {
123
+ return failure(200, id, -32602, "`name` is missing.");
124
+ }
125
+ if (!names.has(name)) {
126
+ return failure(200, id, -32602, `Unknown tool: ${name.slice(0, 64)}`);
127
+ }
128
+ const called = await host.call(name, params.arguments ?? {}, {
129
+ signal,
130
+ timeout,
131
+ });
132
+ return result({
133
+ content: [{ type: "text", text: called.content }],
134
+ isError: !called.ok,
135
+ });
136
+ }
137
+ default:
138
+ return failure(200, id, -32601, "Method not found");
139
+ }
140
+ };
141
+
142
+ const handle = async (
143
+ request: EndpointRequest,
144
+ ): Promise<EndpointResponse> => {
145
+ if (request.method.toUpperCase() !== "POST") {
146
+ return { status: 405, headers: { allow: "POST" }, body: "" };
147
+ }
148
+ const origin = request.header("origin");
149
+ if (origin && !origins.has(origin)) {
150
+ return failure(403, null, -32600, "This origin is not allowed.");
151
+ }
152
+ const version = request.header("mcp-protocol-version");
153
+ if (version && !VERSIONS.includes(version)) {
154
+ return failure(400, null, -32600, "Unsupported protocol version.");
155
+ }
156
+ const type = request.header("content-type") ?? "";
157
+ if (!type.toLowerCase().startsWith("application/json")) {
158
+ return failure(415, null, -32600, "The body must be JSON.");
159
+ }
160
+ const bytes =
161
+ typeof request.body === "string"
162
+ ? Buffer.byteLength(request.body, "utf8")
163
+ : request.body.byteLength;
164
+ if (bytes > maxBodyBytes) {
165
+ return failure(413, null, -32600, "The body is too large.");
166
+ }
167
+ let message: unknown;
168
+ try {
169
+ const text =
170
+ typeof request.body === "string"
171
+ ? request.body
172
+ : decoder.decode(request.body);
173
+ message = JSON.parse(text);
174
+ } catch {
175
+ return failure(400, null, -32700, "Parse error");
176
+ }
177
+ if (!isObject(message) || message.jsonrpc !== "2.0") {
178
+ return failure(400, null, -32600, "Invalid Request");
179
+ }
180
+ const { id, method } = message;
181
+ // A notification, or a response to a request the endpoint never sends.
182
+ if (id === undefined || typeof method !== "string") {
183
+ return { status: 202, headers: {}, body: "" };
184
+ }
185
+ if (typeof id !== "string" && typeof id !== "number") {
186
+ return failure(400, null, -32600, "Invalid Request");
187
+ }
188
+ const params = message.params ?? {};
189
+ if (!isObject(params)) {
190
+ return failure(200, id, -32602, "`params` must be an object.");
191
+ }
192
+ return answer(id, method, params, request.signal);
193
+ };
194
+
195
+ return {
196
+ handle,
197
+ async fetch(request: Request): Promise<Response> {
198
+ const answered = await handle({
199
+ method: request.method,
200
+ header: (name) => request.headers.get(name),
201
+ body: await readBody(request, maxBodyBytes),
202
+ signal: request.signal,
203
+ });
204
+ return new Response(answered.body === "" ? null : answered.body, {
205
+ status: answered.status,
206
+ headers: answered.headers,
207
+ });
208
+ },
209
+ };
210
+ }
211
+
212
+ /** The body, read up to one byte past `max`, so a larger one is refused unread. */
213
+ async function readBody(request: Request, max: number): Promise<Uint8Array> {
214
+ if (request.body === null) return new Uint8Array();
215
+ const reader = request.body.getReader();
216
+ const chunks: Uint8Array[] = [];
217
+ let seen = 0;
218
+ try {
219
+ while (seen <= max) {
220
+ const { value, done } = await reader.read();
221
+ if (done) break;
222
+ chunks.push(value);
223
+ seen += value.byteLength;
224
+ }
225
+ } finally {
226
+ await reader.cancel().catch(() => undefined);
227
+ }
228
+ return Buffer.concat(chunks);
229
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * The application's tools as an outside agent calls them: by name, with an
3
+ * input to check, a deadline, and an answer that carries no stack trace.
4
+ * Shared by the worker (`ream mcp:serve`) and the HTTP endpoint.
5
+ */
6
+
7
+ import { pathToFileURL } from "node:url";
8
+ import { E_POLARIS_INVALID_REQUEST } from "../errors.js";
9
+ import { isTool, type PolarisTool } from "../tools.js";
10
+ import type { ToolDefinition } from "../types.js";
11
+ import { isObject } from "./rpc.js";
12
+
13
+ /** What an agent is answered for one call. */
14
+ export interface HostedResult {
15
+ readonly ok: boolean;
16
+ readonly content: string;
17
+ }
18
+
19
+ /** Told of every failed call, with the error the agent does not see. */
20
+ export type OnHostedToolError = (
21
+ error: unknown,
22
+ call: { readonly name: string; readonly input: unknown },
23
+ ) => void;
24
+
25
+ export interface CallOptions {
26
+ readonly signal?: AbortSignal | undefined;
27
+ /** Milliseconds the tool may take. */
28
+ readonly timeout?: number | undefined;
29
+ }
30
+
31
+ export class ToolHost {
32
+ readonly #tools: Map<string, PolarisTool>;
33
+ readonly #onToolError: OnHostedToolError | undefined;
34
+
35
+ constructor(tools: readonly unknown[], onToolError?: OnHostedToolError) {
36
+ this.#tools = toolMap(tools);
37
+ this.#onToolError = onToolError;
38
+ }
39
+
40
+ get definitions(): ToolDefinition[] {
41
+ return [...this.#tools.values()].map((tool) => tool.definition);
42
+ }
43
+
44
+ /**
45
+ * Run a tool. An unknown name, an input the schema refuses, a tool that
46
+ * throws, runs past `timeout` or is cancelled: each is answered with
47
+ * `ok: false` and a message meant for the agent. Never rejects.
48
+ */
49
+ async call(
50
+ name: string,
51
+ input: unknown,
52
+ options: CallOptions = {},
53
+ ): Promise<HostedResult> {
54
+ const tool = this.#tools.get(name);
55
+ if (tool === undefined) {
56
+ return { ok: false, content: `Unknown tool '${name.slice(0, 64)}'.` };
57
+ }
58
+ const stop = new AbortController();
59
+ const outer = options.signal;
60
+ const signal = outer ? AbortSignal.any([stop.signal, outer]) : stop.signal;
61
+ let timer: NodeJS.Timeout | undefined;
62
+ let onAbort: (() => void) | undefined;
63
+ const late = new Promise<HostedResult>((resolve) => {
64
+ const giveUp = (content: string): void => {
65
+ stop.abort();
66
+ resolve({ ok: false, content });
67
+ };
68
+ if (options.timeout !== undefined) {
69
+ timer = setTimeout(
70
+ () => giveUp("The tool did not finish in time."),
71
+ options.timeout,
72
+ );
73
+ }
74
+ onAbort = () => giveUp("The call was cancelled.");
75
+ if (outer?.aborted) onAbort();
76
+ else outer?.addEventListener("abort", onAbort, { once: true });
77
+ });
78
+ const id = `mcp_${name}`;
79
+ const run = tool
80
+ .execute(
81
+ { type: "tool_call", id, name, input },
82
+ { toolCallId: id, signal },
83
+ )
84
+ .then((outcome): HostedResult => {
85
+ if (!outcome.ok) this.#onToolError?.(outcome.error, { name, input });
86
+ return { ok: outcome.ok, content: outcome.content };
87
+ });
88
+ try {
89
+ return await Promise.race([run, late]);
90
+ } finally {
91
+ clearTimeout(timer);
92
+ if (onAbort) outer?.removeEventListener("abort", onAbort);
93
+ }
94
+ }
95
+ }
96
+
97
+ /** The tools by name, refusing what is not a tool and a name used twice. */
98
+ function toolMap(tools: readonly unknown[]): Map<string, PolarisTool> {
99
+ const map = new Map<string, PolarisTool>();
100
+ for (const tool of tools) {
101
+ if (!isTool(tool)) {
102
+ throw new E_POLARIS_INVALID_REQUEST([
103
+ "the tools to expose must be built by defineTool()",
104
+ ]);
105
+ }
106
+ if (map.has(tool.name)) {
107
+ throw new E_POLARIS_INVALID_REQUEST([
108
+ `two tools to expose are named '${tool.name}'`,
109
+ ]);
110
+ }
111
+ map.set(tool.name, tool);
112
+ }
113
+ return map;
114
+ }
115
+
116
+ /** A module path, `file:` URL string or URL, as a URL. */
117
+ export function moduleUrl(module: string | URL): URL {
118
+ if (module instanceof URL) return module;
119
+ return module.startsWith("file:") ? new URL(module) : pathToFileURL(module);
120
+ }
121
+
122
+ /**
123
+ * The tools a module exports: as its default export or as `tools`, a list or
124
+ * a function (sync or async) that returns one. A function is where the
125
+ * application boots what its tools need.
126
+ */
127
+ export async function loadTools(module: string | URL): Promise<PolarisTool[]> {
128
+ const url = moduleUrl(module);
129
+ const imported: unknown = await import(url.href);
130
+ let exported: unknown = isObject(imported)
131
+ ? (imported.default ?? imported.tools)
132
+ : undefined;
133
+ if (typeof exported === "function") exported = await exported();
134
+ if (!Array.isArray(exported)) {
135
+ throw new E_POLARIS_INVALID_REQUEST([
136
+ `'${url.pathname}' must export its tools: a list, or a function returning one, as \`default\` or \`tools\``,
137
+ ]);
138
+ }
139
+ return [...toolMap(exported).values()];
140
+ }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * An MCP server over Streamable HTTP: each message is POSTed; the server
3
+ * answers with JSON, with a server-sent event stream carrying the response
4
+ * (and whatever it sends before it), or with 202 for a notification. A
5
+ * session id the server gives at `initialize` goes with every later request.
6
+ */
7
+
8
+ import { E_POLARIS_MCP } from "../errors.js";
9
+ import { serverSentData } from "../server-sent.js";
10
+ import type { Transport } from "../types.js";
11
+ import {
12
+ type Channel,
13
+ type ChannelEvents,
14
+ isObject,
15
+ type JsonObject,
16
+ } from "./rpc.js";
17
+
18
+ export interface HttpServer {
19
+ readonly type: "http";
20
+ /** The server's MCP endpoint. Put no secret in it: use `headers` or `token`. */
21
+ readonly url: string | URL;
22
+ /** Sent with every request (`x-api-key`...). The values are kept out of errors. */
23
+ readonly headers?: Readonly<Record<string, string>>;
24
+ /**
25
+ * An OAuth access token, sent as `Authorization: Bearer`. Asked once, and
26
+ * again when the server answers 401. Getting the token (the authorization
27
+ * flow, its refresh) is the application's: polaris only sends it. The
28
+ * values are kept out of errors.
29
+ */
30
+ readonly token?: () => string | Promise<string>;
31
+ /** The `fetch` to use. Default the global one. */
32
+ readonly fetch?: Transport;
33
+ }
34
+
35
+ export interface HttpChannel extends Channel {
36
+ /** The protocol version agreed on at `initialize`, sent with every later request. */
37
+ negotiated(version: string): void;
38
+ /** Listen for what the server sends on its own (a tool list that changed). */
39
+ listen(onError: (error: unknown) => void): void;
40
+ }
41
+
42
+ /** How long `close()` waits for the server to end the session. */
43
+ const CLOSE_TIMEOUT_MS = 5_000;
44
+
45
+ export function openHttp(
46
+ name: string,
47
+ server: HttpServer,
48
+ maxMessageBytes: number,
49
+ secrets: Set<string>,
50
+ events: ChannelEvents,
51
+ ): HttpChannel {
52
+ const url = new URL(server.url);
53
+ const base: Transport = server.fetch ?? globalThis.fetch;
54
+ const stop = new AbortController();
55
+ let session: string | undefined;
56
+ let version: string | undefined;
57
+ let token: string | undefined;
58
+
59
+ const fail = (problem: string): Error => new E_POLARIS_MCP([name, problem]);
60
+
61
+ const bearer = async (fresh: boolean): Promise<string | undefined> => {
62
+ if (server.token === undefined) return undefined;
63
+ if (token === undefined || fresh) {
64
+ const value = await server.token();
65
+ if (typeof value !== "string" || value === "") {
66
+ throw fail("`token` did not give a token");
67
+ }
68
+ secrets.add(value);
69
+ token = value;
70
+ }
71
+ return token;
72
+ };
73
+
74
+ const headers = async (
75
+ accept: string,
76
+ fresh = false,
77
+ ): Promise<Record<string, string>> => {
78
+ const auth = await bearer(fresh);
79
+ return {
80
+ ...server.headers,
81
+ accept,
82
+ ...(auth !== undefined ? { authorization: `Bearer ${auth}` } : {}),
83
+ ...(session !== undefined ? { "mcp-session-id": session } : {}),
84
+ ...(version !== undefined ? { "mcp-protocol-version": version } : {}),
85
+ };
86
+ };
87
+
88
+ const fetchOnce = async (
89
+ method: string,
90
+ accept: string,
91
+ body: string | undefined,
92
+ signal: AbortSignal,
93
+ fresh: boolean,
94
+ ): Promise<Response> => {
95
+ let response: Response;
96
+ try {
97
+ response = await base(url, {
98
+ method,
99
+ headers: {
100
+ ...(await headers(accept, fresh)),
101
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
102
+ },
103
+ ...(body !== undefined ? { body } : {}),
104
+ redirect: "manual",
105
+ signal,
106
+ });
107
+ } catch (error) {
108
+ if (signal.aborted) throw signal.reason;
109
+ const detail = error instanceof Error ? error.message : String(error);
110
+ throw fail(`it could not be reached: ${detail}`);
111
+ }
112
+ if (
113
+ response.type === "opaqueredirect" ||
114
+ (response.status >= 300 && response.status < 400)
115
+ ) {
116
+ await response.body?.cancel().catch(() => undefined);
117
+ throw fail(
118
+ `it answered with a redirect (HTTP ${response.status}), which polaris does not follow`,
119
+ );
120
+ }
121
+ return response;
122
+ };
123
+
124
+ /** A request, sent again once with a fresh token when the server answers 401. */
125
+ const call = async (
126
+ method: string,
127
+ accept: string,
128
+ body: string | undefined,
129
+ signal: AbortSignal,
130
+ ): Promise<Response> => {
131
+ const response = await fetchOnce(method, accept, body, signal, false);
132
+ if (response.status !== 401 || server.token === undefined) return response;
133
+ await response.body?.cancel().catch(() => undefined);
134
+ return fetchOnce(method, accept, body, signal, true);
135
+ };
136
+
137
+ /** Hand the messages in `text` on; what was parsed, or `undefined` when it is not JSON. */
138
+ const deliver = (text: string): unknown => {
139
+ let message: unknown;
140
+ try {
141
+ message = JSON.parse(text);
142
+ } catch {
143
+ return undefined;
144
+ }
145
+ const all = Array.isArray(message) ? message : [message];
146
+ for (const one of all) events.receive(one);
147
+ return message;
148
+ };
149
+
150
+ const tooLong = (): Error =>
151
+ fail(`it sent a message longer than ${maxMessageBytes} bytes`);
152
+
153
+ return {
154
+ async send(message: JsonObject, signal?: AbortSignal): Promise<void> {
155
+ const own = signal ? AbortSignal.any([signal, stop.signal]) : stop.signal;
156
+ const response = await call(
157
+ "POST",
158
+ "application/json, text/event-stream",
159
+ JSON.stringify(message),
160
+ own,
161
+ );
162
+ if (response.status === 202 || response.status === 204) {
163
+ await response.body?.cancel().catch(() => undefined);
164
+ return;
165
+ }
166
+ if (!response.ok) {
167
+ await response.body?.cancel().catch(() => undefined);
168
+ if (response.status === 404 && session !== undefined) {
169
+ throw fail("its session has ended (HTTP 404)");
170
+ }
171
+ if (response.status === 401 || response.status === 403) {
172
+ throw fail(`it refused the credentials (HTTP ${response.status})`);
173
+ }
174
+ throw fail(`it answered HTTP ${response.status}`);
175
+ }
176
+ if (message.method === "initialize") {
177
+ session = response.headers.get("mcp-session-id") ?? undefined;
178
+ }
179
+
180
+ const type = response.headers.get("content-type") ?? "";
181
+ if (type.includes("text/event-stream") && response.body !== null) {
182
+ // The stream ends with the response to this message: stop there.
183
+ for await (const data of serverSentData(
184
+ response.body,
185
+ maxMessageBytes,
186
+ tooLong,
187
+ )) {
188
+ const parsed = deliver(data);
189
+ if (
190
+ isObject(parsed) &&
191
+ parsed.id === message.id &&
192
+ !("method" in parsed)
193
+ ) {
194
+ return;
195
+ }
196
+ }
197
+ return;
198
+ }
199
+ if (type.includes("application/json")) {
200
+ const text = await readText(response, maxMessageBytes, tooLong);
201
+ if (deliver(text) === undefined) {
202
+ throw fail("it answered with something not JSON");
203
+ }
204
+ return;
205
+ }
206
+ await response.body?.cancel().catch(() => undefined);
207
+ throw fail(`it answered with an unexpected content type '${type}'`);
208
+ },
209
+
210
+ negotiated(agreed: string): void {
211
+ version = agreed;
212
+ },
213
+
214
+ listen(onError: (error: unknown) => void): void {
215
+ void (async () => {
216
+ const response = await call(
217
+ "GET",
218
+ "text/event-stream",
219
+ undefined,
220
+ stop.signal,
221
+ );
222
+ // 405: the server offers no stream of its own.
223
+ if (!response.ok || response.body === null) {
224
+ await response.body?.cancel().catch(() => undefined);
225
+ return;
226
+ }
227
+ for await (const data of serverSentData(
228
+ response.body,
229
+ maxMessageBytes,
230
+ tooLong,
231
+ )) {
232
+ deliver(data);
233
+ }
234
+ })().catch((error: unknown) => {
235
+ if (!stop.signal.aborted) onError(error);
236
+ });
237
+ },
238
+
239
+ async close(): Promise<void> {
240
+ if (stop.signal.aborted) return;
241
+ stop.abort();
242
+ if (session === undefined) return;
243
+ const ending = await call(
244
+ "DELETE",
245
+ "application/json",
246
+ undefined,
247
+ AbortSignal.timeout(CLOSE_TIMEOUT_MS),
248
+ ).catch(() => undefined);
249
+ await ending?.body?.cancel().catch(() => undefined);
250
+ },
251
+ };
252
+ }
253
+
254
+ /** The body as text, refused past `maxBytes`. */
255
+ async function readText(
256
+ response: Response,
257
+ maxBytes: number,
258
+ tooLong: () => Error,
259
+ ): Promise<string> {
260
+ if (response.body === null) return "";
261
+ const reader = response.body.getReader();
262
+ const chunks: Uint8Array[] = [];
263
+ let seen = 0;
264
+ try {
265
+ while (true) {
266
+ const { value, done } = await reader.read();
267
+ if (done) break;
268
+ seen += value.byteLength;
269
+ if (seen > maxBytes) throw tooLong();
270
+ chunks.push(value);
271
+ }
272
+ } finally {
273
+ await reader.cancel().catch(() => undefined);
274
+ }
275
+ return Buffer.concat(chunks).toString("utf8");
276
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `@c9up/polaris/mcp`: the tools of an MCP server, as polaris tools; and the
3
+ * application's tools, offered to outside agents (`mcpEndpoint`, the
4
+ * `tools.json` manifest and the worker of `ream mcp:serve`). Not loaded by
5
+ * the rest of polaris.
6
+ *
7
+ * const github = await connectMcp({
8
+ * name: 'github',
9
+ * server: { type: 'http', url: 'https://mcp.example.com/mcp', token: () => tokens.github() },
10
+ * allow: ['search_issues', 'get_issue'],
11
+ * prefix: 'github_',
12
+ * })
13
+ * const result = await polaris.run({ messages, tools: github.tools })
14
+ * await github.close()
15
+ */
16
+
17
+ export {
18
+ connectMcp,
19
+ MCP_PROTOCOL_VERSIONS,
20
+ McpClient,
21
+ type McpOptions,
22
+ type McpServerInfo,
23
+ type SkippedTool,
24
+ } from "./client.js";
25
+ export {
26
+ type EndpointRequest,
27
+ type EndpointResponse,
28
+ type McpEndpoint,
29
+ type McpEndpointOptions,
30
+ mcpEndpoint,
31
+ } from "./endpoint.js";
32
+ export {
33
+ type HostedResult,
34
+ loadTools,
35
+ type OnHostedToolError,
36
+ } from "./host.js";
37
+ export type { HttpServer } from "./http.js";
38
+ export {
39
+ type ToolsManifest,
40
+ type ToolsManifestOptions,
41
+ writeToolsManifest,
42
+ } from "./manifest.js";
43
+ export type { StdioServer } from "./stdio.js";
44
+ export {
45
+ MAX_WORKER_LINE,
46
+ runWorker,
47
+ startWorker,
48
+ WORKER_PROTOCOL,
49
+ type WorkerOptions,
50
+ type WorkerProcess,
51
+ } from "./worker.js";