@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
package/README.md CHANGED
@@ -1,3 +1,1147 @@
1
- # Temporary Holding Version
1
+ # @c9up/polaris
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One API for language models, whatever the provider. Your application sends a
4
+ request and reads a reply the same way, whether it talks to Claude, to an
5
+ OpenAI-compatible endpoint or to a model running on your own server.
6
+ Switching provider is a config change.
7
+
8
+ It ships two providers: Claude, and every service that speaks OpenAI's chat
9
+ completions API (Groq, Cloudflare Workers AI, Infomaniak, a local Ollama
10
+ server, OpenAI itself).
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @c9up/polaris
16
+ ```
17
+
18
+ Register the provider in `reamrc.ts`:
19
+
20
+ ```ts
21
+ providers: [() => import('@c9up/polaris/provider')]
22
+ ```
23
+
24
+ ## Configure
25
+
26
+ `config/polaris.ts` declares the providers by name and picks a default:
27
+
28
+ ```ts
29
+ import { defineConfig, type InferProviders, providers } from '@c9up/polaris'
30
+
31
+ const polarisConfig = defineConfig({
32
+ default: 'claude',
33
+ providers: {
34
+ claude: providers.anthropic({
35
+ model: 'claude-opus-5-5',
36
+ apiKey: env.get('ANTHROPIC_API_KEY'),
37
+ }),
38
+ },
39
+ // Optional bounds, applied to every call:
40
+ timeout: 600_000, // ms, per call, streams included
41
+ maxResponseBytes: 32 * 1024 * 1024,
42
+ })
43
+
44
+ export default polarisConfig
45
+
46
+ declare module '@c9up/polaris/types' {
47
+ interface ProvidersList extends InferProviders<typeof polarisConfig> {}
48
+ }
49
+ ```
50
+
51
+ The `declare module` block makes `polaris.use('claude')` type-checked: a name
52
+ that is not in `providers` does not compile.
53
+
54
+ ## Send a request
55
+
56
+ ```ts
57
+ import polaris from '@c9up/polaris/services/main'
58
+
59
+ const reply = await polaris.use('claude').chat({
60
+ system: 'Answer in one sentence.',
61
+ messages: [{ role: 'user', content: 'What is a cross-border commuter?' }],
62
+ })
63
+
64
+ reply.text // the reply's text
65
+ reply.toolCalls // the tools the model asks to run
66
+ reply.stopReason // 'end', 'max_tokens', 'tool_use', 'refusal'…
67
+ reply.usage // input, output and cache tokens
68
+ ```
69
+
70
+ `polaris.chat()` without `use()` goes to the default provider.
71
+
72
+ ### Stream a reply
73
+
74
+ ```ts
75
+ for await (const event of polaris.stream({ messages })) {
76
+ if (event.type === 'text') process.stdout.write(event.text)
77
+ if (event.type === 'done') console.log(event.response.usage)
78
+ }
79
+ ```
80
+
81
+ The stream ends with one `done` event holding the whole response. Leaving the
82
+ loop early cancels the request to the provider.
83
+
84
+ ### Stream a reply to the browser
85
+
86
+ In a ream route, answer with an SSE stream and hand it to `streamTo()`:
87
+
88
+ ```ts
89
+ router.post('/chat', async ({ auth, request, response }) => {
90
+ // The question comes from the browser; the history comes from your
91
+ // database. Never take assistant turns or tool results from the client.
92
+ const { question } = await request.validateUsing(chatValidator)
93
+ const messages = [...(await conversations.history(auth.user)), { role: 'user', content: question }]
94
+
95
+ const sse = await response.sse()
96
+ void polaris.use('claude').streamTo(sse, { messages }).then((outcome) => {
97
+ if (outcome.status === 'failed') logger.error(outcome.error)
98
+ })
99
+ })
100
+ ```
101
+
102
+ Do not `await` it: ream starts sending the response once the handler has
103
+ returned, so an awaited stream would reach the browser all at once, at the end.
104
+ `streamTo()` never rejects; how it ended is in its result (`done`,
105
+ `client_left` or `failed`).
106
+
107
+ The browser receives named events: `text` and `reasoning` (`{ text }`),
108
+ `tool_call` (`{ id, name, input }`), then `done` (`{ id, provider, model, text,
109
+ stopReason, usage }`), after which the stream ends. `{ prefix: 'polaris.' }`
110
+ names them `polaris.text` and so on. When the browser leaves, the request to
111
+ the provider is cancelled, and you stop paying for a reply nobody reads. A
112
+ failure sends `error` with the polaris code only (`{ code: 'E_POLARIS_RATE_LIMITED' }`,
113
+ or `null` for another error): a message can carry details the page must not see.
114
+
115
+ The stream of the request is what carries the reply, rather than a relay
116
+ channel: it belongs to the one client waiting, and its close tells for sure
117
+ that the client left, even with several instances. To show the same reply to
118
+ other people as well (a consultant following the conversation), broadcast the
119
+ events on a relay channel next to it.
120
+
121
+ ### Embeddings
122
+
123
+ ```ts
124
+ const { vectors, model, dimensions } = await polaris.use('local').embed({ inputs: passages })
125
+ ```
126
+
127
+ One `Float32Array` per input, in input order, every one of `dimensions`
128
+ numbers. `model` is the model that answered: keep it with the vectors, so an
129
+ index can refuse vectors from another model, which would not compare.
130
+
131
+ A long list is split into batches of `embeddingBatchSize` inputs (128 by
132
+ default), sent one after the other, their order kept; polaris checks that
133
+ every batch answered with vectors of one size. `dimensions` in the request
134
+ asks a model that can shorten its vectors for that length.
135
+
136
+ Claude has no embedding model: `polaris.use('claude').features.embeddings` is
137
+ `false`, and `embed()` raises `E_POLARIS_UNSUPPORTED`.
138
+ Use an OpenAI-compatible provider with an `embeddingModel`, such as a local
139
+ Ollama (`bge-m3`, `nomic-embed-text`: the texts never leave the server),
140
+ Infomaniak in Switzerland (`bge_multilingual_gemma2`), Cloudflare Workers AI
141
+ (`@cf/baai/bge-m3`) or OpenAI (`text-embedding-3-small`).
142
+
143
+ ## Tools
144
+
145
+ A tool is a function the model may ask your application to run. Declare it
146
+ with a schema for its input, and let `run()` handle the back and forth:
147
+
148
+ ```ts
149
+ import rune from '@c9up/rune'
150
+ import { defineTool, ToolError } from '@c9up/polaris'
151
+
152
+ const cantonRule = defineTool({
153
+ name: 'canton_rule',
154
+ description: 'Look up a tax rule for a Swiss canton',
155
+ schema: rune.create({ canton: rune.string().minLength(2) }),
156
+ async run({ canton }) {
157
+ const rule = await rules.find(canton)
158
+ if (!rule) throw new ToolError(`No canton named '${canton}'.`)
159
+ return rule
160
+ },
161
+ })
162
+
163
+ const { response, messages, steps, usage } = await polaris.run(
164
+ { messages: [{ role: 'user', content: 'How is a cross-border commuter taxed in Geneva?' }], tools: [cantonRule] },
165
+ { maxSteps: 5, onToolError: (error, call) => logger.warn({ error, tool: call.name }) },
166
+ )
167
+ ```
168
+
169
+ `run()` sends the request, runs the tools the model calls, sends their results
170
+ back, and goes on until the model answers without calling a tool:
171
+
172
+ - The handler's input is typed from the schema, and checked by it first. Input
173
+ that fails the schema goes back to the model as an error it can correct; the
174
+ handler does not run.
175
+ - The calls of one turn run at the same time, and their results go back in one
176
+ message.
177
+ - A `ToolError`'s message is shown to the model. Any other error reaches it as
178
+ "The tool failed.": its message and stack stay on your server.
179
+ `onToolError` receives the real error.
180
+ - After `maxSteps` requests (8 by default) with the model still calling tools,
181
+ `run()` raises `E_POLARIS_TOO_MANY_STEPS`.
182
+ - A reply cut at the output limit, or refused, is returned without running its
183
+ tool calls, which may be incomplete.
184
+
185
+ The schema is any object that implements Standard Schema v1 and Standard JSON
186
+ Schema v1, as rune's schemas do. polaris itself depends on no validation
187
+ library. A returned string goes to the model as it is; anything else is sent as
188
+ JSON.
189
+
190
+ ### A tool with a plain JSON Schema
191
+
192
+ A tool whose input is already described by JSON Schema (one from an MCP server,
193
+ from a skill, or written by hand) takes `inputSchema` in place of `schema`:
194
+
195
+ ```ts
196
+ const weather = defineTool<{ city: string }>({
197
+ name: 'weather',
198
+ description: 'The weather in a city',
199
+ inputSchema: {
200
+ type: 'object',
201
+ properties: { city: { type: 'string', minLength: 2 } },
202
+ required: ['city'],
203
+ },
204
+ run: ({ city }) => forecasts.today(city),
205
+ })
206
+ ```
207
+
208
+ - The schema goes to the provider as it was given, without its `$schema` key.
209
+ - polaris checks the model's input against it before `run`, as it does with
210
+ rune. The type parameter only types the handler's input: nothing checks it
211
+ against the schema.
212
+ - The schema itself is checked when the tool is defined. Each keyword must be
213
+ one polaris checks, or an annotation (`description`, `default`, `format`...);
214
+ any other keyword (`if`, `nullable`, a remote `$ref`) is refused with
215
+ `E_POLARIS_INVALID_REQUEST`, so a schema is never half-checked.
216
+ `JSON_SCHEMA_KEYWORDS` lists them. `format` is sent but not checked, as JSON
217
+ Schema has it by default.
218
+ - A schema must describe an object, be at most 256 KiB as JSON and 32 levels
219
+ deep; `$ref` points inside the schema (`#/$defs/...`, `#/definitions/...`).
220
+ - Defaults are not filled in: the handler gets the input as the model wrote it.
221
+
222
+ `jsonSchema(schema)` wraps a JSON Schema as a Standard Schema, for anywhere
223
+ else polaris takes one.
224
+
225
+ ### Tools added during a run
226
+
227
+ A tool can add tools to its run, so loading a skill or a server's tools does
228
+ not mean declaring every tool upfront. The handler calls `context.addTools()`;
229
+ the model can call the new tools from the run's next request:
230
+
231
+ ```ts
232
+ const rate = defineTool({ name: 'canton_rate', /* ... */ })
233
+
234
+ const loadTaxTools = defineTool({
235
+ name: 'load_tax_tools',
236
+ description: 'Make the tax tools available',
237
+ inputSchema: { type: 'object', properties: {} },
238
+ run: (_input, { addTools }) => {
239
+ addTools([rate])
240
+ return 'The tax tools are loaded.'
241
+ },
242
+ })
243
+
244
+ // Tools added when loaded: the request after the load sends `canton_rate`.
245
+ await polaris.run({ messages, tools: [loadTaxTools] })
246
+
247
+ // Declared upfront: `canton_rate` is sent from the first request, and callable once loaded.
248
+ await polaris.run({ messages, tools: [loadTaxTools], inactiveTools: [rate], cache: true })
249
+ ```
250
+
251
+ - The tools of one turn are added once the turn is answered: the other calls of
252
+ that turn do not see them.
253
+ - Adding a tool already in the run does nothing, so loading twice is harmless.
254
+ Another tool under a name the run has is refused with a `ToolError`, which the
255
+ model reads, and nothing of that batch is added. A run holds at most
256
+ `MAX_RUN_TOOLS` (128) tools, active and inactive.
257
+ - `maxSteps`, `maxToolCalls` and budgets count added tools as the others.
258
+
259
+ Which mode pays off depends on the prompt cache: the tools sent are the start
260
+ of the cached prefix, so adding one makes the next request write the prefix
261
+ again, once per load. That is fine for a run that loads rarely, or a few times
262
+ over many steps. With `inactiveTools`, the tools sent never change and the
263
+ prefix stays cached through the whole run; a call to an inactive tool is
264
+ answered with an error the model can read, until a tool adds it. It pays off
265
+ for long runs over a known set of tools, at the price of sending them all from
266
+ the first request.
267
+
268
+ ### Stream a tool run
269
+
270
+ `streamRun()` is `run()` read as it is written: the events of each step as
271
+ `stream()` gives them, a `tool_result` for each call as soon as its tool is
272
+ done, then one `done` holding what `run()` returns.
273
+
274
+ ```ts
275
+ for await (const event of polaris.streamRun({ messages, tools: [cantonRule] })) {
276
+ if (event.type === 'text') write(event.text)
277
+ if (event.type === 'tool_call') showLookup(event.call.name)
278
+ if (event.type === 'tool_result') hideLookup(event.call.id, event.result.isError)
279
+ if (event.type === 'done') save(event.result.messages, event.result.cost)
280
+ }
281
+ ```
282
+
283
+ Every rule of `run()` holds, and each step is a request of its own for the
284
+ budget and the exchange log; the run's cost is their sum. Leaving the loop
285
+ cancels the provider request in flight and aborts the signal handed to the
286
+ tools still running; so does the call's `signal`, and the run then stops
287
+ waiting for a tool that ignores it.
288
+
289
+ `streamRunTo()` sends it to the browser as `streamTo()` does for one reply.
290
+ `tool_result` carries `{ id, name, isError }`: the result itself is your
291
+ application's data, read by the model, and stays on the server. `done` adds
292
+ the run's `steps`, and its `usage` counts every step. When the browser leaves,
293
+ the run stops, tools included.
294
+
295
+ ```ts
296
+ router.post('/chat', async ({ response }) => {
297
+ const sse = await response.sse()
298
+ void polaris.use('claude').streamRunTo(sse, { messages, tools: [cantonRule] }).then((outcome) => {
299
+ if (outcome.status === 'done') return conversations.save(outcome.result.messages)
300
+ if (outcome.status === 'failed') logger.error(outcome.error)
301
+ })
302
+ })
303
+ ```
304
+
305
+ ## MCP servers
306
+
307
+ `@c9up/polaris/mcp` connects to a [Model Context Protocol](https://modelcontextprotocol.io)
308
+ server and turns its tools into polaris tools. polaris speaks the protocol
309
+ itself: there is no SDK to install.
310
+
311
+ ```ts
312
+ import { connectMcp } from '@c9up/polaris/mcp'
313
+
314
+ const github = await connectMcp({
315
+ name: 'github',
316
+ server: {
317
+ type: 'http',
318
+ url: 'https://mcp.example.com/mcp',
319
+ token: () => oauth.accessToken('github'),
320
+ },
321
+ allow: ['search_issues', 'get_issue'],
322
+ prefix: 'github_',
323
+ })
324
+
325
+ const files = await connectMcp({
326
+ name: 'files',
327
+ server: { type: 'stdio', command: 'node', args: ['./mcp/files.js'] },
328
+ allow: 'all',
329
+ })
330
+
331
+ try {
332
+ await polaris.run({ messages, tools: [...github.tools, ...files.tools] })
333
+ } finally {
334
+ await Promise.all([github.close(), files.close()])
335
+ }
336
+ ```
337
+
338
+ - `allow` is required. It lists the tools the model may see, by the server's
339
+ names, or is `'all'`. `client.skipped` lists the allowed tools the model
340
+ does not see, with the reason: a name the server does not offer, a name
341
+ outside `[a-zA-Z0-9_-]`, a schema keyword polaris does not check, or no
342
+ input schema.
343
+ - `prefix` keeps the tool names of two servers apart. The server is still
344
+ called with its own name. polaris checks the input against the tool's
345
+ schema before calling the server, as for [`jsonSchema`](#a-tool-with-a-plain-json-schema).
346
+ - Everything the server writes is untrusted, like any text that reaches the
347
+ model: tool descriptions, schemas, results and `client.server.instructions`.
348
+ A result can try to steer the model. Connect to servers you trust, and allow
349
+ only the tools you need.
350
+ - What the model reads: text as it is, and an embedded resource as its text.
351
+ An image or audio clip becomes a mention (`[image: image/png, about 2048 bytes, not shown]`),
352
+ and a linked resource its URI. `structuredContent` is sent as JSON when the
353
+ result has no other content. A result the server flags `isError` is a tool
354
+ error, which the model reads.
355
+ - Limits:
356
+ - `timeout` applies to each request, connecting included (default 60 s).
357
+ A call that times out, or whose run is cancelled, is cancelled at the
358
+ server too.
359
+ - A result larger than `maxResultBytes` (256 KiB) becomes a tool error.
360
+ - A message larger than `maxMessageBytes` (4 MiB) ends the connection.
361
+ - When the server says its tool list changed, polaris reads the list again and
362
+ `client.tools` changes. A run that calls one of the server's tools gets the
363
+ new ones from its next request (see [Tools added during a run](#tools-added-during-a-run)).
364
+ A tool the server dropped answers with an error. If reading the list fails in
365
+ the background, the error goes to `onError`.
366
+ - A stdio server inherits only `PATH`, `HOME`, `USER`, `SHELL`, `TERM` and
367
+ `LOGNAME` (their Windows counterparts on Windows), plus its own `env`: the
368
+ application's secrets are not passed on. Its stderr goes to the
369
+ application's, unless `stderr: 'ignore'`. On `close()`, polaris ends its
370
+ stdin, then sends `SIGTERM`, then `SIGKILL`, allowing 2 s at each step.
371
+ - An HTTP server is spoken to over Streamable HTTP: one POST per message, and
372
+ the session id the server gives with every request. Redirects are refused.
373
+ Credentials go in `headers`, or in `token`, which polaris sends as a bearer
374
+ token. polaris asks `token` once, and again when the server answers 401.
375
+ Getting the token (the OAuth flow, its refresh) is up to the application.
376
+ - Header values, tokens, `env` values and the URL's password are taken out of
377
+ error messages.
378
+ - polaris speaks the protocol versions from 2024-11-05 to 2025-11-25
379
+ (`MCP_PROTOCOL_VERSIONS`), and uses only the server's tools: not its
380
+ resources, prompts or sampling.
381
+
382
+ ## Offer your tools over MCP
383
+
384
+ The same module serves the application's tools to outside agents (Claude
385
+ Code, an IDE, another service), in two ways: a route of the application, over
386
+ Streamable HTTP, and a stdio server, through a manifest and a worker.
387
+
388
+ Put the tools you offer in one module. Export them as `default` or `tools`:
389
+ a list, or a function (sync or async) that returns one. A function is where
390
+ the application boots what its tools need (a database pool, a container),
391
+ once.
392
+
393
+ ```ts
394
+ // app/mcp/tools.ts
395
+ import { app } from '#start/app'
396
+
397
+ export default async function tools() {
398
+ await app.boot()
399
+ const cantons = await app.container.make(CantonService)
400
+ return [cantonRate(cantons), cantonHolidays(cantons)]
401
+ }
402
+ ```
403
+
404
+ Offer only the tools an agent should have: the module is the list. A tool
405
+ that only reads is a safer first offer than one that writes.
406
+
407
+ ### A route of the application
408
+
409
+ `mcpEndpoint` answers one request at a time, with no session: each POST
410
+ carries one JSON-RPC message (`initialize`, `ping`, `tools/list`,
411
+ `tools/call`) and gets JSON back.
412
+
413
+ ```ts
414
+ import { mcpEndpoint } from '@c9up/polaris/mcp'
415
+ import tools from '#app/mcp/tools'
416
+
417
+ const mcp = mcpEndpoint({ tools: await tools(), name: 'cantons', version: '1.0.0' })
418
+
419
+ router.post('/mcp', async ({ request, response }) => {
420
+ const answer = await mcp.handle({
421
+ method: request.method(),
422
+ header: (name) => request.header(name),
423
+ body: request.rawBuffer(),
424
+ })
425
+ response.status(answer.status)
426
+ for (const [name, value] of Object.entries(answer.headers)) response.header(name, value)
427
+ response.send(answer.body)
428
+ }).use(middleware.auth())
429
+ ```
430
+
431
+ `mcp.fetch(request)` does the same for a framework that hands over a Fetch
432
+ API `Request` and expects a `Response`.
433
+
434
+ - **Authentication is the application's.** The endpoint checks no identity:
435
+ mount it behind the middleware that checks the bearer token or the session.
436
+ Every caller that reaches it can list and call every tool of the list.
437
+ - A request from a browser carries an `Origin`: it is refused with 403 unless
438
+ `allowedOrigins` lists it, so a page cannot drive the tools with a logged-in
439
+ user's cookies. Agents send none.
440
+ - A body over `maxBodyBytes` (1 MiB) is refused with 413; `fetch` stops
441
+ reading it there. Set the framework's own body limit too. A body that is not JSON, a batch, a method other than POST or an
442
+ unsupported `MCP-Protocol-Version` are refused too (415, 400, 405, 400).
443
+ - polaris checks the input against the tool's schema before running it.
444
+ - A tool that fails answers the agent `The tool failed.` (or the message of a
445
+ `ToolError`): no stack trace, no error message that might hold a secret.
446
+ `onToolError` receives the real error, to log it.
447
+ - A tool gets `timeout` (60 s) to finish. Past it, or when the client leaves
448
+ (`signal`), its run is cancelled and the agent told so.
449
+ - The endpoint sends no server-sent stream and no notification: an agent
450
+ reads the tool list when it connects.
451
+
452
+ ### A stdio server: the manifest and the worker
453
+
454
+ An agent that starts its MCP servers itself (Claude Code, an IDE) talks over
455
+ stdio. The application then writes a manifest, `tools.json`, at build time:
456
+
457
+ ```ts
458
+ import { writeToolsManifest } from '@c9up/polaris/mcp'
459
+
460
+ await writeToolsManifest({ module: 'build/app/mcp/tools.js', output: 'build/tools.json' })
461
+ ```
462
+
463
+ It holds the tools' definitions, the path to the module and the path to the
464
+ polaris worker, both relative to the manifest. The server that reads it, such
465
+ as `ream mcp:serve`, answers `initialize` and `tools/list` from the manifest,
466
+ without starting Node, and starts the worker for the first call:
467
+ `node <worker> <tools.json>`. The worker imports the module once and runs the
468
+ calls until its stdin ends.
469
+
470
+ The worker speaks one JSON object per line, both ways (protocol 1,
471
+ `WORKER_PROTOCOL`):
472
+
473
+ | From | Line | Meaning |
474
+ |---|---|---|
475
+ | worker | `{"type":"ready","protocol":1}` | The tools are loaded. Always the first line. |
476
+ | worker | `{"type":"failed","message":"..."}` | The module could not be loaded. The worker exits with code 1. |
477
+ | parent | `{"type":"call","id":1,"name":"canton_rate","input":{...}}` | Run a tool. `id` is a string or a number. |
478
+ | parent | `{"type":"cancel","id":1}` | Cancel a running call. |
479
+ | worker | `{"type":"result","id":1,"ok":true,"content":"..."}` | The call's answer. `ok: false` is a failure meant for the agent. |
480
+ | worker | `{"type":"error","id":null,"message":"..."}` | A line the worker could not read, or a call it refused. |
481
+
482
+ - Calls run side by side. Each call is answered once, even when it is
483
+ cancelled.
484
+ - An unknown tool, an input the schema refuses or a failing tool is a result
485
+ with `ok: false`, never a crash. A line over 4 MiB is answered with an
486
+ `error` and skipped.
487
+ - stdout carries only the protocol. What the application writes there
488
+ (`console.log`) goes to stderr, with the tools' errors and their stacks.
489
+ - A manifest that asks for another protocol is refused with `failed`: write
490
+ it again with the polaris that runs it.
491
+
492
+ ## Skills
493
+
494
+ A skill is a set of instructions the model loads when a task calls for it,
495
+ with the files those instructions refer to and, if it needs them, its own
496
+ tools. Only each skill's name and description sit in the system prompt; the
497
+ rest costs tokens once the model asks for it.
498
+
499
+ A skill is a folder whose `SKILL.md` starts with a frontmatter:
500
+
501
+ ```
502
+ resources/skills/payroll/
503
+ SKILL.md name, description, then the instructions
504
+ reference/avs.md a file the model may read
505
+ scripts/compute.sh text the model may read: never run
506
+ tools/rates.ts a tool module: exports tools
507
+ ```
508
+
509
+ ```md
510
+ ---
511
+ name: payroll
512
+ description: Compute a Swiss payslip. Use it for any salary question.
513
+ ---
514
+ # Payroll
515
+
516
+ 1. Ask for the canton.
517
+ 2. Read reference/avs.md, then call social_rate.
518
+ ```
519
+
520
+ ```ts
521
+ import { readSkill, readSkills, useSkills } from '@c9up/polaris/skills'
522
+
523
+ const skills = useSkills(await readSkills('resources/skills'))
524
+
525
+ await polaris.run({
526
+ system: `${prompt}\n\n${skills.system}`,
527
+ messages,
528
+ tools: [...tools, ...skills.tools],
529
+ inactiveTools: skills.inactiveTools,
530
+ })
531
+ ```
532
+
533
+ `useSkills()` gives the run two tools. `load_skill` returns a skill's
534
+ instructions and the list of its files, and lets its tools in from the next
535
+ request. `read_skill_file` returns one of its files. A skill's tool called
536
+ before the skill is loaded is answered with an error the model reads.
537
+
538
+ What runs, and what does not:
539
+
540
+ - The modules of `tools/` (`.js`, `.mjs`, `.ts`, `.mts`) are imported in the
541
+ application's process and run like its own code. Each exports a tool, a
542
+ list, or a function (sync or async) that returns one, as `default` or
543
+ `tools`. A file whose name starts with `_` or `.`, a `.d.ts` and a test are
544
+ not tool modules: put shared code in `tools/_shared.ts`.
545
+ `readSkill(dir, { importTools: false })` imports none of them, for a skill
546
+ you did not write.
547
+ - Nothing else in the folder runs. A script is text the model can read, and
548
+ `allowed-tools` in the frontmatter is ignored.
549
+ - An MCP server is attached by the application, never by a `SKILL.md`:
550
+ `readSkill(dir, { tools: github.tools })`.
551
+ - `read_skill_file` reads within the skill's folder only: no `..`, no
552
+ absolute path, no symbolic link leading out. It reads UTF-8 text up to
553
+ 256 KiB, and lists at most 500 files, 8 folders deep, without hidden files
554
+ and `node_modules`.
555
+
556
+ A skill can be declared in code as well, with its files as strings:
557
+
558
+ ```ts
559
+ import { defineSkill } from '@c9up/polaris/skills'
560
+
561
+ const vat = defineSkill({
562
+ name: 'vat',
563
+ description: 'Swiss VAT rates: compute a price with VAT.',
564
+ instructions: 'The standard rate is 8.1%. Read rates.md for the others.',
565
+ files: { 'rates.md': '...' },
566
+ tools: [vatRate],
567
+ })
568
+ ```
569
+
570
+ - A name is 1 to 64 lower-case letters, digits and single hyphens; a
571
+ description at most 1024 characters; instructions at most 256 KiB. A
572
+ `SKILL.md` that breaks a rule raises `E_POLARIS_INVALID_SKILL`, which names
573
+ the folder; `defineSkill()` raises `E_POLARIS_INVALID_REQUEST`.
574
+ - `readSkills(dir)` reads each sub-folder that holds a `SKILL.md`, and refuses
575
+ two skills under one name.
576
+ - `useSkills()` takes 1 to 64 skills, and refuses one tool name in two skills,
577
+ or a skill tool named `load_skill` or `read_skill_file`.
578
+ - `useSkills(skills, { sendTools: 'from-start' })` sends the skills' tools from
579
+ the first request, callable once their skill is loaded: the tools sent never
580
+ change, so the cached prompt prefix holds (see
581
+ [Tools added during a run](#tools-added-during-a-run)).
582
+
583
+ ## Tools and skills in folders
584
+
585
+ An application's tools and skills live in folders polaris finds by itself:
586
+ `app/tools/` and `resources/skills/` by default, or wherever `config/polaris.ts`
587
+ says, a module's own folders included:
588
+
589
+ ```ts
590
+ const polarisConfig = defineConfig({
591
+ providers: { /* ... */ },
592
+ catalog: {
593
+ tools: ['app/tools', 'app/modules/*/tools', 'app/modules/*/http/*_tool.ts'],
594
+ skills: ['app/modules/*/skills'],
595
+ manifest: 'polaris.json', // the default
596
+ },
597
+ })
598
+ ```
599
+
600
+ Each entry is a glob pattern, relative to the application's root: no absolute
601
+ path, no `..`. A folder it matches gives its tool modules (the rules of a
602
+ skill's `tools/` apply: `_shared.ts`, a `.d.ts` and a test are not tool
603
+ modules); a file it matches is one. A folder that holds other code as well,
604
+ such as a module's `infrastructure/`, is named by its tool files:
605
+ `app/modules/*/infrastructure/*_tool.ts`. For skills, a folder that holds a
606
+ `SKILL.md` is a skill, and so is each sub-folder of a matched folder that
607
+ holds one. Two tools, or two skills, under one name are refused, and the error
608
+ names both files.
609
+
610
+ `ream polaris:index` imports each module once and lists every tool and skill,
611
+ name and description, in `polaris.json`. Run it after adding or renaming one,
612
+ and in the build; list the manifest in `metaFiles` of `reamrc.ts` so the build
613
+ copies it. At boot, `PolarisProvider` reads it (an absent manifest is an empty
614
+ catalog), binds it as `polaris.catalog` and publishes it:
615
+
616
+ ```ts
617
+ import catalog from '@c9up/polaris/services/catalog'
618
+
619
+ await polaris.run({
620
+ messages,
621
+ tools: await catalog.tools(['canton_rate', 'open_checklist']),
622
+ })
623
+
624
+ const skills = useSkills(await catalog.skills(['payroll']))
625
+ ```
626
+
627
+ `catalog.tools(names)` imports only the modules that export those tools, once;
628
+ without names, all of them. `catalog.skills(names, options)` reads those skill
629
+ folders, which must ship with the application. `catalog.toolList` and
630
+ `catalog.skillList` give what the manifest lists, without importing anything.
631
+ A name the manifest does not list, or a module that no longer exports its
632
+ tool, raises `E_POLARIS_INVALID_CATALOG`, which says to run
633
+ `ream polaris:index`. In a built application, a module listed as `.ts` is
634
+ imported from its `.js`. `catalog: false` reads no manifest.
635
+
636
+ The commands come with the package, registered once in `reamrc.ts`:
637
+
638
+ ```ts
639
+ commands: [() => import('@c9up/polaris/commands')]
640
+ ```
641
+
642
+ ```sh
643
+ ream polaris:index
644
+ ream make:tool canton_rate # app/tools/canton_rate.ts
645
+ ream make:tool open_checklist --module checklists
646
+ # app/modules/checklists/tools/open_checklist.ts
647
+ ream make:skill payroll --module hr # app/modules/hr/skills/payroll/SKILL.md
648
+ ```
649
+
650
+ `make:tool` and `make:skill` write in the first pattern that fits: with
651
+ `--module`, the first whose folder has a `*`, which the module replaces;
652
+ without, the first with none. A file pattern like `http/*_tool.ts` names the
653
+ file. `--dry-run` shows the path and the content and writes nothing;
654
+ `--force` overwrites a file that exists, which is otherwise left alone.
655
+
656
+ ## Structured output
657
+
658
+ `extract()` asks for one JSON value that matches a schema, and returns it typed
659
+ and validated:
660
+
661
+ ```ts
662
+ const profile = rune.create({
663
+ canton: rune.string().minLength(2),
664
+ borderCommuter: rune.boolean(),
665
+ })
666
+
667
+ const { value, attempts, usage } = await polaris.extract({
668
+ messages: conversation,
669
+ schema: profile,
670
+ name: 'profile',
671
+ description: "The person's situation, as far as the conversation tells",
672
+ })
673
+
674
+ value.canton // string, checked by the schema
675
+ ```
676
+
677
+ - The provider's own structured-output mode is used when it has one. Without
678
+ it, polaris gives the model a tool to call with the answer.
679
+ - The answer is always checked against the schema itself, constraints the
680
+ provider does not enforce included (`minLength`, `minimum`…).
681
+ - An answer that fails the schema, or is not JSON, goes back to the model with
682
+ the schema's issues, once by default (`{ retries: 2 }` to allow more). After
683
+ that, `extract()` raises `E_POLARIS_INVALID_OUTPUT`; its `cause.issues` lists
684
+ what was wrong.
685
+ - A refused answer, or one cut at the output limit, raises at once: asking
686
+ again the same way would not help.
687
+
688
+ ## Claude
689
+
690
+ `providers.anthropic()` talks to Claude through the official SDK. Install it
691
+ next to polaris; it is loaded the first time the provider is used:
692
+
693
+ ```sh
694
+ pnpm add @anthropic-ai/sdk
695
+ ```
696
+
697
+ | Option | What it does |
698
+ |---|---|
699
+ | `model` | The model every request uses, unless the request names another. Required. |
700
+ | `apiKey` | The API key. Without it, the SDK reads `ANTHROPIC_API_KEY`. |
701
+ | `baseURL` | Another endpoint that speaks the Anthropic API. |
702
+ | `maxTokens` | The output limit when a request sets none. Default 16 000, or 64 000 for a stream. |
703
+ | `maxRetries` | How many times a rate-limited, overloaded or failed request is retried, following the API's `retry-after`. Default 2. All retries stay within the call's deadline. |
704
+ | `fallbacks` | When the model declines a request, run it again on a fallback model: `'default'` lets the API choose, or name the models. Recommended on the current Opus, Sonnet and Fable models. |
705
+ | `betas` | Extra `anthropic-beta` flags sent with every request. |
706
+ | `server` | Server-side tools every request gets: see [Server-side tools](#server-side-tools-code-execution-skills-mcp-servers). |
707
+
708
+ Fields polaris does not model go through `providerOptions.anthropic`, as they
709
+ are written in the API:
710
+
711
+ ```ts
712
+ await polaris.chat({
713
+ messages,
714
+ providerOptions: { anthropic: { thinking: { type: 'adaptive', display: 'summarized' } } },
715
+ })
716
+ ```
717
+
718
+ A structured output's schema is rewritten into what Claude accepts (every
719
+ object closed with `additionalProperties: false`, unsupported constraints moved
720
+ into the description), with the SDK's own rewrite; polaris then checks the
721
+ answer against your full schema.
722
+
723
+ Claude's reasoning comes back as `reasoning` parts. Every part of a reply keeps
724
+ the block Claude sent (`origin`), so a reply passed back in the next request
725
+ reaches Claude exactly as Claude wrote it: Claude rejects a history whose
726
+ reasoning was altered. Blocks with no neutral equivalent, such as the result
727
+ of a server-side tool, come back as `provider` parts for the same reason.
728
+
729
+ ### Server-side tools: code execution, skills, MCP servers
730
+
731
+ Claude can run some tools on Anthropic's side: code in a sandboxed container,
732
+ the skills loaded into it, and MCP servers it connects to over the internet.
733
+ Ask for them with the request's `server`, or with the provider's `server`
734
+ option for every request:
735
+
736
+ ```ts
737
+ const result = await polaris.run({
738
+ messages: [{ role: 'user', content: "Put last month's invoices in a spreadsheet." }],
739
+ tools: [listInvoices],
740
+ server: {
741
+ skills: [{ source: 'anthropic', id: 'xlsx' }],
742
+ mcpServers: [
743
+ { name: 'crm', url: 'https://mcp.example.com/sse', authorizationToken: env.get('CRM_TOKEN'), tools: ['find_client'] },
744
+ ],
745
+ },
746
+ })
747
+ ```
748
+
749
+ | `server` | What it does |
750
+ |---|---|
751
+ | `codeExecution` | Let Claude run code in a container. Implied by `skills`. |
752
+ | `skills` | `{ source: 'anthropic' \| 'custom'; id: string; version?: string }[]`, at most 20: Anthropic's skills (`xlsx`, `pptx`, `docx`, `pdf`) or one uploaded to your account (`skill_…`). Default version `latest`. They are loaded into the container and bring the code execution tool. |
753
+ | `mcpServers` | `{ name: string; url: string; authorizationToken?: string; tools?: string[] }[]`: `https://` servers speaking Streamable HTTP or SSE, each name unique. `tools` keeps only those; default all. Turns on the `mcp-client-2025-11-20` beta. |
754
+ | `container` | The id of a container to work in again (`response.container.id`), so its files are still there. |
755
+
756
+ A key the request's `server` sets replaces the same key of the provider's;
757
+ `container` is per request only. polaris runs none of these calls: they come
758
+ back as `provider` parts with their results, `toolCalls` holds only your own
759
+ tools' calls, and `run()` sends the server's blocks back to Claude unchanged.
760
+ A long turn the API pauses (`stopReason: 'pause'`) resumes by itself in
761
+ `run()`, in the same container: `run()` carries `response.container.id` from
762
+ one step to the next. Files the code writes are Files API ids inside the
763
+ result blocks; download them with the SDK's Files API.
764
+
765
+ Tokens the skills and the MCP results read and write are in `usage`, priced as
766
+ usual. The server's tool calls are counted in `usage.serverToolUse`
767
+ (`{ codeExecutionRequests: 2 }`), as the API counts them, and added up over a
768
+ run. The container's time is not: Anthropic bills code execution per container
769
+ hour (1,550 free hours a month per organization, then $0.05 an hour, 5 minutes
770
+ at least; free alongside the current web search and web fetch tools), and the
771
+ response does not report it, so `cost` and budgets leave it out. The Console's
772
+ usage page shows it.
773
+
774
+ The MCP token goes to Anthropic, which calls the server with it; polaris keeps
775
+ it out of errors and of the exchange log (`[redacted]`). Only Claude takes
776
+ `server`: another provider refuses the request with `E_POLARIS_UNSUPPORTED`
777
+ before sending it.
778
+
779
+ #### Server-side or client-side
780
+
781
+ polaris runs skills and MCP servers itself too ([Skills](#skills),
782
+ [MCP servers](#mcp-servers)). The server-side form is the better one when:
783
+
784
+ - the skill has to run code and you have no sandbox to give it: building a
785
+ spreadsheet, a deck or a PDF, analysing a file in Python. Anthropic's
786
+ document skills come ready-made;
787
+ - the MCP server is public over HTTPS and you only need its tools: Claude
788
+ calls it within its turn, with no step and no history sent again per call,
789
+ and your process holds no connection.
790
+
791
+ The client-side form is the better one when:
792
+
793
+ - the tools touch your application: its database, its services, the user's
794
+ session, anything behind your network;
795
+ - the MCP server runs over stdio or on a private network, or you need its
796
+ resources and prompts;
797
+ - your code has to check, approve, log or limit each call (`onToolError`,
798
+ `maxToolCalls`, budgets per scope);
799
+ - the data or the token must not leave your infrastructure;
800
+ - the same code has to work with another provider;
801
+ - you need what each call costs: a client tool costs its tokens only, a server
802
+ container costs time polaris cannot see.
803
+
804
+ The two mix: your tools and the server's go in the same request.
805
+
806
+ ## OpenAI-compatible services
807
+
808
+ `providers.openaiCompatible()` talks to a service that speaks OpenAI's chat
809
+ completions API. It needs no SDK.
810
+
811
+ ```ts
812
+ providers: {
813
+ // A local Ollama server: no key, data never leaves the machine.
814
+ local: providers.openaiCompatible({
815
+ name: 'ollama',
816
+ baseURL: 'http://localhost:11434/v1',
817
+ model: 'qwen3',
818
+ embeddingModel: 'bge-m3',
819
+ }),
820
+ groq: providers.openaiCompatible({
821
+ name: 'groq',
822
+ baseURL: 'https://api.groq.com/openai/v1',
823
+ apiKey: env.get('GROQ_API_KEY'),
824
+ model: 'openai/gpt-oss-20b',
825
+ }),
826
+ workers: providers.openaiCompatible({
827
+ name: 'workers-ai',
828
+ baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.get('CF_ACCOUNT_ID')}/ai/v1`,
829
+ apiKey: env.get('CF_API_TOKEN'),
830
+ model: '@cf/qwen/qwen3-30b-a3b-fp8',
831
+ }),
832
+ // Hosted in Switzerland: "data centers in Switzerland", requests neither
833
+ // stored nor used for training (infomaniak.com/en/hosting/llm-api).
834
+ swiss: providers.openaiCompatible({
835
+ name: 'infomaniak',
836
+ baseURL: `https://api.infomaniak.com/2/ai/${env.get('INFOMANIAK_PRODUCT_ID')}/openai/v1`,
837
+ apiKey: env.get('INFOMANIAK_TOKEN'),
838
+ model: 'Qwen/Qwen3-VL-235B-A22B-Instruct',
839
+ maxTokensField: 'max_completion_tokens',
840
+ }),
841
+ }
842
+ ```
843
+
844
+ | Option | What it does |
845
+ |---|---|
846
+ | `baseURL` | The API's base URL, up to and including `/v1`. Required. |
847
+ | `model` | The chat model every request uses, unless the request names another. Required. |
848
+ | `apiKey` | Sent as a bearer token. Leave it out for a server that needs none. |
849
+ | `name` | The provider's name in responses and in `providerOptions`. Default `openai-compatible`. |
850
+ | `embeddingModel` | The embedding model. Without it, the provider does not embed. |
851
+ | `embeddingBatchSize` | Inputs per embedding request; a longer list is sent in batches, in order. Default 128. |
852
+ | `features` | What the model supports: `{ tools, structuredOutput, images }`. Default: tools and structured output on, images off. `serverTools` stays off: the API has no server-side tools to send. |
853
+ | `maxTokens` | The output limit when a request sets none. Default 16 000. |
854
+ | `maxTokensField` | `max_tokens` (default: Ollama, Workers AI) or `max_completion_tokens` (Infomaniak). |
855
+ | `streamUsage` | Ask a stream for its token usage. Default true; turn it off for a service that rejects the field. |
856
+ | `maxRetries` | How many times a rate-limited, overloaded or failed request is retried, following `retry-after`. Default 2. |
857
+ | `headers` | Further headers sent with every request. |
858
+
859
+ What a model can do depends on the model, not on the API: declare it in
860
+ `features`, and polaris refuses a request asking for more before sending it.
861
+ Reasoning comes back as `reasoning` parts, wherever the service puts it
862
+ (`reasoning` for Groq and Ollama, `reasoning_content` for Workers AI). A tool
863
+ call whose arguments are not valid JSON keeps the string the model wrote, so
864
+ your validation refuses it.
865
+
866
+ Notes on the services, from their documentation:
867
+
868
+ - **Ollama** ignores `toolChoice`, and reports an error met mid-stream inside
869
+ the stream; polaris raises it as `E_POLARIS_PROVIDER_UNAVAILABLE`.
870
+ - **Groq** offers strict structured output on a few models only, and none while
871
+ streaming or with tools.
872
+ - **Infomaniak** streams unless told not to (polaris always says), reads only
873
+ `max_completion_tokens`, and rejects the older `json_object` format (polaris
874
+ only sends `json_schema`).
875
+ - **Workers AI** documents structured output for a few models only, and none
876
+ while streaming.
877
+ - **Gemini** (`https://generativelanguage.googleapis.com/v1beta/openai`) signs
878
+ each tool call (`extra_content.google.thought_signature`) and rejects a
879
+ history without the signature. A tool call keeps the fields polaris does not
880
+ model in its `origin`, and they go back with it to the provider that wrote
881
+ them, so `run()` works there as elsewhere.
882
+
883
+ ## Cost, budgets and the exchange log
884
+
885
+ Declare your prices, and every response carries its cost, computed exactly
886
+ with `@c9up/atom` (decimal strings, never floating point):
887
+
888
+ ```ts
889
+ defineConfig({
890
+ providers: { claude: providers.anthropic({ model: 'claude-opus-5-5' }) },
891
+ pricing: {
892
+ currency: 'USD',
893
+ // Per million tokens, by the model id the provider answers with.
894
+ models: { 'claude-opus-5-5': { input: '4', output: '20', cacheRead: '0.2' } },
895
+ },
896
+ })
897
+
898
+ const reply = await polaris.chat(request)
899
+ reply.cost // for example { amount: '0.0114', currency: 'USD' }
900
+ reply.usage // { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }
901
+ ```
902
+
903
+ The three input counts never overlap: `inputTokens` are the tokens billed at
904
+ the full input price, neither read from nor written to a cache. Cache prices
905
+ default to the input price. `run()`, `streamRun()` and `extract()` add up the
906
+ cost of their requests.
907
+
908
+ ### Prompt caching
909
+
910
+ A request that starts the same way as the previous one (the same tools, the
911
+ same system prompt, the same first messages) can have that prefix read from
912
+ the provider's cache, at a fraction of the input price. Ask for it with
913
+ `cache: true`:
914
+
915
+ ```ts
916
+ await polaris.chat({ system: longInstructions, messages, cache: true })
917
+ ```
918
+
919
+ Claude caches only when asked: writing the prefix costs more than plain input
920
+ (1.25 times the input price), and every read within the next 5 minutes costs a
921
+ tenth of it. It pays off when the same long prefix comes back within minutes:
922
+ a long system prompt or document, a conversation, each step of a tool run. A
923
+ prefix shorter than the model's minimum (from 512 to 4 096 tokens, by model)
924
+ is not cached, and a change anywhere in it, even a date in the system prompt,
925
+ makes the next request write it again. For a 1-hour cache, add
926
+ `providerOptions: { anthropic: { cache_control: { type: 'ephemeral', ttl: '1h' } } }`
927
+ and declare its write price (twice the input price) as `cacheWrite`.
928
+
929
+ The OpenAI-compatible services cache on their own, or not at all, and ignore
930
+ the option. Either way, `usage.cacheReadTokens` says how much was read from the
931
+ cache and `usage.cacheWriteTokens` how much was written: if reads stay at 0
932
+ over repeated requests, the prefix is changing. Declare `cacheRead` and
933
+ `cacheWrite` in the price table, and the cost and the budget estimate (which
934
+ counts the input of a cached request at the write price) follow.
935
+
936
+ ### Budgets
937
+
938
+ A budget limits what a scope (a user, a tenant) may spend, here 5 CHF a month
939
+ per user, counted across every instance of the application:
940
+
941
+ ```ts
942
+ import { redisBudgetStore } from '@c9up/polaris'
943
+ import redis from '@c9up/quasar/services/main'
944
+
945
+ defineConfig({
946
+ // ...
947
+ budget: {
948
+ limit: (scope) => (scope.startsWith('user:') ? '5' : undefined),
949
+ period: 'month',
950
+ store: redisBudgetStore(() => redis.connection()),
951
+ },
952
+ })
953
+
954
+ await polaris.chat(request, { scope: `user:${user.id}` })
955
+ await polaris.chat(request, { maxCost: '0.50' }) // a ceiling for this one request
956
+ ```
957
+
958
+ Before a request is sent, its most expensive outcome is estimated: its input
959
+ from its length (erring high) and its output at the full `maxTokens`. That
960
+ estimate is reserved on the scope; if the total would pass the limit, the
961
+ reservation is taken back and the request refused with
962
+ `E_POLARIS_BUDGET_EXCEEDED`, before anything is sent. Once the reply is in,
963
+ the reservation is replaced by the real cost. Reserving rather than reading
964
+ the spend is what keeps requests sent at the same moment from passing the
965
+ limit together. A failed request gives its reservation back; a stream the
966
+ client left after it started keeps it, as the provider may bill it.
967
+
968
+ `period` is `'day'` or `'month'`, in UTC: spend counts from the start of the
969
+ current period and starts again at zero on the next. Without it, spend counts
970
+ for as long as the store keeps it. A reservation stays on the period it was
971
+ made in, so a request sent just before midnight settles into the day it
972
+ reserved on, and the reservation of a process that died before settling goes
973
+ with its period instead of holding the scope's spend for ever.
974
+
975
+ The default store is in memory: one process, lost on restart.
976
+ `redisBudgetStore(client, { prefix })` keeps spend in Redis, shared by every
977
+ instance that talks to the same server; it takes a `@c9up/quasar` connection
978
+ or an ioredis client as they are, or a function that answers one on each
979
+ addition, so that a config read before the connections are booted can name it. It adds with `INCRBY`, exactly, in
980
+ billionths of the currency, and expires a past period's key a day after the
981
+ period ends, in the same transaction. Keys start with `polaris:budget:`
982
+ unless `prefix` says otherwise. Another store implements
983
+ `add(key, amount, expiresAt?)`: an atomic addition (an SQL
984
+ `UPDATE … SET spent = spent + ?` does it), and, with a period, the time in
985
+ epoch milliseconds after which the key may be dropped. A scope with no limit
986
+ is neither refused nor counted. A budget needs a price for the model
987
+ asked for, or the request is refused with `E_POLARIS_UNKNOWN_PRICE`: a budget
988
+ cannot be kept for a model whose cost is unknown.
989
+
990
+ ### Exchange log
991
+
992
+ ```ts
993
+ defineConfig({
994
+ // ...
995
+ log: { handler: (entry) => logger.info(entry, 'llm exchange') },
996
+ })
997
+ ```
998
+
999
+ Every exchange reaches `handler`: provider, model, operation, status (`ok`,
1000
+ `error`, `cancelled`), the polaris error code, stop reason, usage, cost,
1001
+ duration and scope. It holds no message content: conversations carry personal
1002
+ data. `content: true` adds the request and the response; `redact(entry)` runs
1003
+ before every entry is handed over, to take out what must not be kept. A
1004
+ per-call key never appears in an entry, and a handler that throws does not
1005
+ fail the call.
1006
+
1007
+ ## A key per call
1008
+
1009
+ When each account brings its own provider key, pass it with the call:
1010
+
1011
+ ```ts
1012
+ await polaris.use('claude').chat(request, { apiKey: account.llmKey })
1013
+ ```
1014
+
1015
+ It replaces the configured key for that call only. If the provider's error
1016
+ mentions the key, polaris replaces the error with `E_POLARIS_PROVIDER_FAILED`,
1017
+ whose message has the key taken out and which keeps no reference to the
1018
+ original error.
1019
+
1020
+ ## Limits and cancellation
1021
+
1022
+ Every call runs under a deadline (`timeout`, overridable per call) and reads at
1023
+ most `maxResponseBytes` from the provider. Pass `signal` to cancel a call:
1024
+
1025
+ ```ts
1026
+ await polaris.chat(request, { signal: AbortSignal.timeout(5_000) })
1027
+ ```
1028
+
1029
+ A call that runs out of time raises `E_POLARIS_TIMEOUT`. A call cancelled by
1030
+ your signal rejects with your signal's reason.
1031
+
1032
+ ## Checked before sending
1033
+
1034
+ polaris checks a request against what the provider supports before anything
1035
+ leaves the server. Asking a provider for something it cannot do raises
1036
+ `E_POLARIS_UNSUPPORTED` the same way on every provider: tools, structured
1037
+ output, images, streaming or embeddings.
1038
+
1039
+ ## Testing
1040
+
1041
+ `polaris.fake()` makes every provider answer from a script until `restore()`:
1042
+ no network, no key.
1043
+
1044
+ ```ts
1045
+ const fake = polaris.fake()
1046
+ fake
1047
+ .reply('Bonjour') // a text reply
1048
+ .callTool('canton_rule', { canton: 'GE' }) // a turn that calls a tool
1049
+ .replyJson({ canton: 'VD', borderCommuter: true }) // a structured answer
1050
+ .reply({ text: 'Hello', chunks: ['Hel', 'lo'], usage: { inputTokens: 900, outputTokens: 40 } })
1051
+ .fail(new errors.E_POLARIS_RATE_LIMITED(['fake', 'slow down']))
1052
+
1053
+ await assistant.answer(question)
1054
+
1055
+ fake.assertSent((request) => request.system?.includes('newcomer'))
1056
+ fake.assertSentCount(2)
1057
+ fake.calls // every call: operation, provider, request, per-call key
1058
+ polaris.restore()
1059
+ ```
1060
+
1061
+ Each request takes the next scripted reply, in order; a request the script
1062
+ did not plan for raises `E_POLARIS_FAKE_NO_REPLY`. `replyJson()` answers as
1063
+ structured output, or through the answer's tool when the fake is told it has
1064
+ no structured output (`polaris.fake({ features: { structuredOutput: false } })`).
1065
+ Streams send the reply's chunks, then `done`. Embeddings return the same
1066
+ vector for the same text (`fake.embedWith(fn)` to choose them).
1067
+
1068
+ The fake reports usage (10 input and 10 output tokens unless the reply says
1069
+ otherwise), so prices, budgets and the exchange log run as they would against
1070
+ a provider. It answers with the model `fake-model` unless the request names
1071
+ one: give it a price to test cost code.
1072
+
1073
+ `FakeProvider` is also exported from `@c9up/polaris/testing`, to declare it as
1074
+ a provider of its own: `providers: { main: () => fake.driver('main') }`.
1075
+
1076
+ ## Write a driver
1077
+
1078
+ A driver is an object with a provider name, the features it supports and a
1079
+ `chat()` method. `stream()` and `embed()` are optional.
1080
+
1081
+ ```ts
1082
+ import { createResponse, type PolarisDriver } from '@c9up/polaris'
1083
+
1084
+ export function myDriver(options: { apiKey: string }): PolarisDriver {
1085
+ return {
1086
+ provider: 'my-provider',
1087
+ features: { tools: false, structuredOutput: false, images: false },
1088
+ async chat(request, call) {
1089
+ const response = await call.fetch('https://llm.example/v1/chat', {
1090
+ method: 'POST',
1091
+ signal: call.signal,
1092
+ headers: { authorization: `Bearer ${call.apiKey ?? options.apiKey}` },
1093
+ body: JSON.stringify({ messages: request.messages }),
1094
+ })
1095
+ const body = await response.json()
1096
+ return createResponse({
1097
+ id: body.id,
1098
+ provider: 'my-provider',
1099
+ model: body.model,
1100
+ content: [{ type: 'text', text: body.text }],
1101
+ stopReason: 'end',
1102
+ usage: { inputTokens: body.input_tokens, outputTokens: body.output_tokens },
1103
+ })
1104
+ },
1105
+ }
1106
+ }
1107
+ ```
1108
+
1109
+ Send every HTTP request through `call.fetch` with `call.signal`: that is how
1110
+ the deadline, the size limit and cancellation reach the network. A driver that
1111
+ can send a request's `server` tools declares `serverTools: true` in its
1112
+ features; without it, polaris refuses such a request.
1113
+
1114
+ ## Errors
1115
+
1116
+ | Code | When |
1117
+ |---|---|
1118
+ | `E_POLARIS_MISSING_CONFIG` | The application has no `polaris` config. |
1119
+ | `E_POLARIS_INVALID_CONFIG` | A config value or a call option is out of range. |
1120
+ | `E_POLARIS_NO_DEFAULT_PROVIDER` | `use()` without a name, and no `default`. |
1121
+ | `E_POLARIS_UNKNOWN_PROVIDER` | `use(name)` names an undeclared provider. |
1122
+ | `E_POLARIS_INVALID_REQUEST` | No messages, a bad token limit, two tools with one name… |
1123
+ | `E_POLARIS_UNSUPPORTED` | The provider cannot serve what the request asks for. |
1124
+ | `E_POLARIS_TIMEOUT` | The call ran past its deadline. |
1125
+ | `E_POLARIS_RESPONSE_TOO_LARGE` | The provider sent more than `maxResponseBytes`. |
1126
+ | `E_POLARIS_STREAM_INCOMPLETE` | A stream ended without its final response. |
1127
+ | `E_POLARIS_BUDGET_EXCEEDED` | A request would pass its `maxCost` or its scope's budget. Nothing was sent. HTTP status 429. |
1128
+ | `E_POLARIS_UNKNOWN_PRICE` | A budget applies, but `pricing` has no price for the model. Nothing was sent. |
1129
+ | `E_POLARIS_INVALID_OUTPUT` | `extract()` got no answer matching the schema, after its retries; or the answer was refused or cut. |
1130
+ | `E_POLARIS_TOO_MANY_STEPS` | `run()` or `streamRun()` reached `maxSteps` with the model still calling tools. |
1131
+ | `E_POLARIS_INVALID_RESPONSE` | A driver broke the contract (wrong number of vectors…). |
1132
+ | `E_POLARIS_AUTHENTICATION` | The provider refused the key (401, 403). HTTP status 502. |
1133
+ | `E_POLARIS_RATE_LIMITED` | The provider is rate limiting, after the retries. HTTP status 503. |
1134
+ | `E_POLARIS_PROVIDER_UNAVAILABLE` | The provider is overloaded or failing, after the retries. HTTP status 503. |
1135
+ | `E_POLARIS_PROVIDER_REJECTED` | The provider rejected the request itself (400, 404…). HTTP status 502. |
1136
+ | `E_POLARIS_PROVIDER_UNREACHABLE` | The provider could not be reached. HTTP status 502. |
1137
+ | `E_POLARIS_PROVIDER_FAILED` | A provider error mentioned the call's key; the key is removed. |
1138
+ | `E_POLARIS_INVALID_SKILL` | A skill folder has no `SKILL.md`, a frontmatter without `name` or `description`, a value out of bounds, or a tool module that exports no tools. |
1139
+ | `E_POLARIS_INVALID_CATALOG` | A catalog pattern leaves the application, two tools or skills share a name, a module exports no tool, `polaris.json` is not a manifest, or a run asks for a name it does not list. |
1140
+ | `E_POLARIS_MCP` | An MCP server could not be started or reached, refused a request, broke the protocol or ran past `timeout`. HTTP status 502. |
1141
+ | `E_POLARIS_FAKE_NO_REPLY` | The test fake was asked for a reply it was not given. |
1142
+ | `E_POLARIS_ASSERTION_FAILED` | An assertion of the test fake does not hold. |
1143
+ | `E_POLARIS_NOT_BOOTED` | `services/main` or `services/catalog` was used before the provider booted. |
1144
+
1145
+ ## License
1146
+
1147
+ MIT