@c9up/polaris 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +614 -10
- package/dist/Polaris.d.ts +6 -2
- package/dist/Polaris.d.ts.map +1 -1
- package/dist/Polaris.js +14 -0
- package/dist/Polaris.js.map +1 -1
- package/dist/PolarisClient.d.ts +51 -3
- package/dist/PolarisClient.d.ts.map +1 -1
- package/dist/PolarisClient.js +213 -45
- package/dist/PolarisClient.js.map +1 -1
- package/dist/PolarisProvider.d.ts +7 -2
- package/dist/PolarisProvider.d.ts.map +1 -1
- package/dist/PolarisProvider.js +34 -2
- package/dist/PolarisProvider.js.map +1 -1
- package/dist/augmentations.d.ts +4 -1
- package/dist/augmentations.d.ts.map +1 -1
- package/dist/augmentations.js +1 -1
- package/dist/budget.d.ts +39 -6
- package/dist/budget.d.ts.map +1 -1
- package/dist/budget.js +79 -12
- package/dist/budget.js.map +1 -1
- package/dist/catalog/catalog.d.ts +37 -0
- package/dist/catalog/catalog.d.ts.map +1 -0
- package/dist/catalog/catalog.js +145 -0
- package/dist/catalog/catalog.js.map +1 -0
- package/dist/catalog/discover.d.ts +64 -0
- package/dist/catalog/discover.d.ts.map +1 -0
- package/dist/catalog/discover.js +148 -0
- package/dist/catalog/discover.js.map +1 -0
- package/dist/catalog/index.d.ts +8 -0
- package/dist/catalog/index.d.ts.map +1 -0
- package/dist/catalog/index.js +8 -0
- package/dist/catalog/index.js.map +1 -0
- package/dist/commands/index.d.ts +82 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +278 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/cost.d.ts +3 -1
- package/dist/cost.d.ts.map +1 -1
- package/dist/cost.js +8 -3
- package/dist/cost.js.map +1 -1
- package/dist/drivers/anthropic.d.ts +6 -1
- package/dist/drivers/anthropic.d.ts.map +1 -1
- package/dist/drivers/anthropic.js +166 -21
- package/dist/drivers/anthropic.js.map +1 -1
- package/dist/drivers/openai-compatible.d.ts +1 -1
- package/dist/drivers/openai-compatible.d.ts.map +1 -1
- package/dist/drivers/openai-compatible.js +106 -70
- package/dist/drivers/openai-compatible.js.map +1 -1
- package/dist/errors.d.ts +24 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/json-schema.d.ts +33 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +508 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +3 -1
- package/dist/log.js.map +1 -1
- package/dist/mcp/client.d.ts +81 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +401 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/endpoint.d.ts +54 -0
- package/dist/mcp/endpoint.d.ts.map +1 -0
- package/dist/mcp/endpoint.js +158 -0
- package/dist/mcp/endpoint.js.map +1 -0
- package/dist/mcp/host.d.ts +42 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +111 -0
- package/dist/mcp/host.js.map +1 -0
- package/dist/mcp/http.d.ts +32 -0
- package/dist/mcp/http.d.ts.map +1 -0
- package/dist/mcp/http.js +190 -0
- package/dist/mcp/http.js.map +1 -0
- package/dist/mcp/index.d.ts +23 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +21 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manifest.d.ts +36 -0
- package/dist/mcp/manifest.d.ts.map +1 -0
- package/dist/mcp/manifest.js +40 -0
- package/dist/mcp/manifest.js.map +1 -0
- package/dist/mcp/rpc.d.ts +39 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +149 -0
- package/dist/mcp/rpc.js.map +1 -0
- package/dist/mcp/stdio.d.ts +24 -0
- package/dist/mcp/stdio.d.ts.map +1 -0
- package/dist/mcp/stdio.js +157 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/worker-main.d.ts +6 -0
- package/dist/mcp/worker-main.d.ts.map +1 -0
- package/dist/mcp/worker-main.js +17 -0
- package/dist/mcp/worker-main.js.map +1 -0
- package/dist/mcp/worker.d.ts +54 -0
- package/dist/mcp/worker.d.ts.map +1 -0
- package/dist/mcp/worker.js +166 -0
- package/dist/mcp/worker.js.map +1 -0
- package/dist/meter.d.ts +6 -0
- package/dist/meter.d.ts.map +1 -1
- package/dist/meter.js +6 -3
- package/dist/meter.js.map +1 -1
- package/dist/redact.d.ts +4 -3
- package/dist/redact.d.ts.map +1 -1
- package/dist/redact.js +5 -4
- package/dist/redact.js.map +1 -1
- package/dist/redis-budget.d.ts +45 -0
- package/dist/redis-budget.d.ts.map +1 -0
- package/dist/redis-budget.js +56 -0
- package/dist/redis-budget.js.map +1 -0
- package/dist/response.d.ts +21 -3
- package/dist/response.d.ts.map +1 -1
- package/dist/response.js +71 -7
- package/dist/response.js.map +1 -1
- package/dist/server-sent.d.ts +9 -0
- package/dist/server-sent.d.ts.map +1 -0
- package/dist/server-sent.js +74 -0
- package/dist/server-sent.js.map +1 -0
- package/dist/server-tools.d.ts +12 -0
- package/dist/server-tools.d.ts.map +1 -0
- package/dist/server-tools.js +71 -0
- package/dist/server-tools.js.map +1 -0
- package/dist/services/catalog.d.ts +19 -0
- package/dist/services/catalog.d.ts.map +1 -0
- package/dist/services/catalog.js +37 -0
- package/dist/services/catalog.js.map +1 -0
- package/dist/skills/folder.d.ts +32 -0
- package/dist/skills/folder.d.ts.map +1 -0
- package/dist/skills/folder.js +170 -0
- package/dist/skills/folder.js.map +1 -0
- package/dist/skills/frontmatter.d.ts +15 -0
- package/dist/skills/frontmatter.d.ts.map +1 -0
- package/dist/skills/frontmatter.js +92 -0
- package/dist/skills/frontmatter.js.map +1 -0
- package/dist/skills/index.d.ts +18 -0
- package/dist/skills/index.d.ts.map +1 -0
- package/dist/skills/index.js +18 -0
- package/dist/skills/index.js.map +1 -0
- package/dist/skills/kit.d.ts +39 -0
- package/dist/skills/kit.d.ts.map +1 -0
- package/dist/skills/kit.js +124 -0
- package/dist/skills/kit.js.map +1 -0
- package/dist/skills/skill.d.ts +67 -0
- package/dist/skills/skill.d.ts.map +1 -0
- package/dist/skills/skill.js +114 -0
- package/dist/skills/skill.js.map +1 -0
- package/dist/sse.d.ts +43 -6
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +44 -18
- package/dist/sse.js.map +1 -1
- package/dist/testing/FakeProvider.d.ts.map +1 -1
- package/dist/testing/FakeProvider.js +1 -0
- package/dist/testing/FakeProvider.js.map +1 -1
- package/dist/tool-modules.d.ts +17 -0
- package/dist/tool-modules.d.ts.map +1 -0
- package/dist/tool-modules.js +43 -0
- package/dist/tool-modules.js.map +1 -0
- package/dist/tools.d.ts +69 -5
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +174 -31
- package/dist/tools.js.map +1 -1
- package/dist/transport.d.ts +8 -3
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +19 -4
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +106 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +22 -1
- package/src/Polaris.ts +25 -1
- package/src/PolarisClient.ts +288 -51
- package/src/PolarisProvider.ts +40 -2
- package/src/augmentations.ts +4 -1
- package/src/budget.ts +115 -15
- package/src/catalog/catalog.ts +180 -0
- package/src/catalog/discover.ts +234 -0
- package/src/catalog/index.ts +19 -0
- package/src/commands/index.ts +412 -0
- package/src/cost.ts +9 -3
- package/src/drivers/anthropic.ts +203 -20
- package/src/drivers/openai-compatible.ts +143 -76
- package/src/errors.ts +41 -0
- package/src/index.ts +16 -0
- package/src/json-schema.ts +597 -0
- package/src/log.ts +3 -1
- package/src/mcp/client.ts +532 -0
- package/src/mcp/endpoint.ts +229 -0
- package/src/mcp/host.ts +140 -0
- package/src/mcp/http.ts +276 -0
- package/src/mcp/index.ts +51 -0
- package/src/mcp/manifest.ts +73 -0
- package/src/mcp/rpc.ts +197 -0
- package/src/mcp/stdio.ts +190 -0
- package/src/mcp/worker-main.ts +18 -0
- package/src/mcp/worker.ts +212 -0
- package/src/meter.ts +13 -2
- package/src/redact.ts +6 -3
- package/src/redis-budget.ts +85 -0
- package/src/response.ts +86 -8
- package/src/server-sent.ts +70 -0
- package/src/server-tools.ts +77 -0
- package/src/services/catalog.ts +43 -0
- package/src/skills/folder.ts +231 -0
- package/src/skills/frontmatter.ts +92 -0
- package/src/skills/index.ts +38 -0
- package/src/skills/kit.ts +163 -0
- package/src/skills/skill.ts +171 -0
- package/src/sse.ts +88 -22
- package/src/testing/FakeProvider.ts +1 -0
- package/src/tool-modules.ts +49 -0
- package/src/tools.ts +260 -27
- package/src/transport.ts +25 -3
- package/src/types.ts +108 -2
package/README.md
CHANGED
|
@@ -187,6 +187,472 @@ Schema v1, as rune's schemas do. polaris itself depends on no validation
|
|
|
187
187
|
library. A returned string goes to the model as it is; anything else is sent as
|
|
188
188
|
JSON.
|
|
189
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
|
+
|
|
190
656
|
## Structured output
|
|
191
657
|
|
|
192
658
|
`extract()` asks for one JSON value that matches a schema, and returns it typed
|
|
@@ -237,6 +703,7 @@ pnpm add @anthropic-ai/sdk
|
|
|
237
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. |
|
|
238
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. |
|
|
239
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). |
|
|
240
707
|
|
|
241
708
|
Fields polaris does not model go through `providerOptions.anthropic`, as they
|
|
242
709
|
are written in the API:
|
|
@@ -259,6 +726,83 @@ reaches Claude exactly as Claude wrote it: Claude rejects a history whose
|
|
|
259
726
|
reasoning was altered. Blocks with no neutral equivalent, such as the result
|
|
260
727
|
of a server-side tool, come back as `provider` parts for the same reason.
|
|
261
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
|
+
|
|
262
806
|
## OpenAI-compatible services
|
|
263
807
|
|
|
264
808
|
`providers.openaiCompatible()` talks to a service that speaks OpenAI's chat
|
|
@@ -305,7 +849,7 @@ providers: {
|
|
|
305
849
|
| `name` | The provider's name in responses and in `providerOptions`. Default `openai-compatible`. |
|
|
306
850
|
| `embeddingModel` | The embedding model. Without it, the provider does not embed. |
|
|
307
851
|
| `embeddingBatchSize` | Inputs per embedding request; a longer list is sent in batches, in order. Default 128. |
|
|
308
|
-
| `features` | What the model supports: `{ tools, structuredOutput, images }`. Default: tools and structured output on, images off. |
|
|
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. |
|
|
309
853
|
| `maxTokens` | The output limit when a request sets none. Default 16 000. |
|
|
310
854
|
| `maxTokensField` | `max_tokens` (default: Ollama, Workers AI) or `max_completion_tokens` (Infomaniak). |
|
|
311
855
|
| `streamUsage` | Ask a stream for its token usage. Default true; turn it off for a service that rejects the field. |
|
|
@@ -330,6 +874,11 @@ Notes on the services, from their documentation:
|
|
|
330
874
|
only sends `json_schema`).
|
|
331
875
|
- **Workers AI** documents structured output for a few models only, and none
|
|
332
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.
|
|
333
882
|
|
|
334
883
|
## Cost, budgets and the exchange log
|
|
335
884
|
|
|
@@ -353,19 +902,52 @@ reply.usage // { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }
|
|
|
353
902
|
|
|
354
903
|
The three input counts never overlap: `inputTokens` are the tokens billed at
|
|
355
904
|
the full input price, neither read from nor written to a cache. Cache prices
|
|
356
|
-
default to the input price. `run()` and `extract()` add up the
|
|
357
|
-
requests.
|
|
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.
|
|
358
935
|
|
|
359
936
|
### Budgets
|
|
360
937
|
|
|
361
|
-
A budget limits what a scope (a user, a tenant) may spend
|
|
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:
|
|
362
940
|
|
|
363
941
|
```ts
|
|
942
|
+
import { redisBudgetStore } from '@c9up/polaris'
|
|
943
|
+
import redis from '@c9up/quasar/services/main'
|
|
944
|
+
|
|
364
945
|
defineConfig({
|
|
365
946
|
// ...
|
|
366
947
|
budget: {
|
|
367
948
|
limit: (scope) => (scope.startsWith('user:') ? '5' : undefined),
|
|
368
|
-
|
|
949
|
+
period: 'month',
|
|
950
|
+
store: redisBudgetStore(() => redis.connection()),
|
|
369
951
|
},
|
|
370
952
|
})
|
|
371
953
|
|
|
@@ -383,8 +965,25 @@ the spend is what keeps requests sent at the same moment from passing the
|
|
|
383
965
|
limit together. A failed request gives its reservation back; a stream the
|
|
384
966
|
client left after it started keeps it, as the provider may bill it.
|
|
385
967
|
|
|
386
|
-
|
|
387
|
-
|
|
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
|
|
388
987
|
asked for, or the request is refused with `E_POLARIS_UNKNOWN_PRICE`: a budget
|
|
389
988
|
cannot be kept for a model whose cost is unknown.
|
|
390
989
|
|
|
@@ -508,7 +1107,9 @@ export function myDriver(options: { apiKey: string }): PolarisDriver {
|
|
|
508
1107
|
```
|
|
509
1108
|
|
|
510
1109
|
Send every HTTP request through `call.fetch` with `call.signal`: that is how
|
|
511
|
-
the deadline, the size limit and cancellation reach the network.
|
|
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.
|
|
512
1113
|
|
|
513
1114
|
## Errors
|
|
514
1115
|
|
|
@@ -526,7 +1127,7 @@ the deadline, the size limit and cancellation reach the network.
|
|
|
526
1127
|
| `E_POLARIS_BUDGET_EXCEEDED` | A request would pass its `maxCost` or its scope's budget. Nothing was sent. HTTP status 429. |
|
|
527
1128
|
| `E_POLARIS_UNKNOWN_PRICE` | A budget applies, but `pricing` has no price for the model. Nothing was sent. |
|
|
528
1129
|
| `E_POLARIS_INVALID_OUTPUT` | `extract()` got no answer matching the schema, after its retries; or the answer was refused or cut. |
|
|
529
|
-
| `E_POLARIS_TOO_MANY_STEPS` | `run()` reached `maxSteps` with the model still calling tools. |
|
|
1130
|
+
| `E_POLARIS_TOO_MANY_STEPS` | `run()` or `streamRun()` reached `maxSteps` with the model still calling tools. |
|
|
530
1131
|
| `E_POLARIS_INVALID_RESPONSE` | A driver broke the contract (wrong number of vectors…). |
|
|
531
1132
|
| `E_POLARIS_AUTHENTICATION` | The provider refused the key (401, 403). HTTP status 502. |
|
|
532
1133
|
| `E_POLARIS_RATE_LIMITED` | The provider is rate limiting, after the retries. HTTP status 503. |
|
|
@@ -534,9 +1135,12 @@ the deadline, the size limit and cancellation reach the network.
|
|
|
534
1135
|
| `E_POLARIS_PROVIDER_REJECTED` | The provider rejected the request itself (400, 404…). HTTP status 502. |
|
|
535
1136
|
| `E_POLARIS_PROVIDER_UNREACHABLE` | The provider could not be reached. HTTP status 502. |
|
|
536
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. |
|
|
537
1141
|
| `E_POLARIS_FAKE_NO_REPLY` | The test fake was asked for a reply it was not given. |
|
|
538
1142
|
| `E_POLARIS_ASSERTION_FAILED` | An assertion of the test fake does not hold. |
|
|
539
|
-
| `E_POLARIS_NOT_BOOTED` | `services/main` was used before the provider booted. |
|
|
1143
|
+
| `E_POLARIS_NOT_BOOTED` | `services/main` or `services/catalog` was used before the provider booted. |
|
|
540
1144
|
|
|
541
1145
|
## License
|
|
542
1146
|
|