@lushly-dev/afd-server 2.2.1 → 2.4.0
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 +468 -6
- package/dist/approval-crypto.d.ts +26 -4
- package/dist/approval-crypto.d.ts.map +1 -1
- package/dist/approval-crypto.js +90 -7
- package/dist/approval-crypto.js.map +1 -1
- package/dist/approval-relay.d.ts +5 -5
- package/dist/approval-relay.d.ts.map +1 -1
- package/dist/approval.d.ts +6 -1
- package/dist/approval.d.ts.map +1 -1
- package/dist/approval.js +43 -32
- package/dist/approval.js.map +1 -1
- package/dist/bootstrap/afd-context.d.ts +2 -27
- package/dist/bootstrap/afd-context.d.ts.map +1 -1
- package/dist/bootstrap/afd-context.js +6 -36
- package/dist/bootstrap/afd-context.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +24 -2
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +17 -2
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +1 -0
- package/dist/bootstrap/described-command.d.ts.map +1 -1
- package/dist/bootstrap/described-command.js.map +1 -1
- package/dist/bootstrap/registry.d.ts +13 -0
- package/dist/bootstrap/registry.d.ts.map +1 -1
- package/dist/bootstrap/registry.js +30 -1
- package/dist/bootstrap/registry.js.map +1 -1
- package/dist/command-allow.d.ts +31 -0
- package/dist/command-allow.d.ts.map +1 -0
- package/dist/command-allow.js +55 -0
- package/dist/command-allow.js.map +1 -0
- package/dist/command-names.d.ts +17 -0
- package/dist/command-names.d.ts.map +1 -1
- package/dist/command-names.js +55 -0
- package/dist/command-names.js.map +1 -1
- package/dist/command-routing.d.ts +10 -3
- package/dist/command-routing.d.ts.map +1 -1
- package/dist/command-routing.js +18 -7
- package/dist/command-routing.js.map +1 -1
- package/dist/confirmation-gate.d.ts +32 -0
- package/dist/confirmation-gate.d.ts.map +1 -0
- package/dist/confirmation-gate.js +140 -0
- package/dist/confirmation-gate.js.map +1 -0
- package/dist/confirmations.d.ts +15 -23
- package/dist/confirmations.d.ts.map +1 -1
- package/dist/confirmations.js +8 -127
- package/dist/confirmations.js.map +1 -1
- package/dist/context-fields-describe.d.ts +18 -0
- package/dist/context-fields-describe.d.ts.map +1 -0
- package/dist/context-fields-describe.js +17 -0
- package/dist/context-fields-describe.js.map +1 -0
- package/dist/context-fields.d.ts +50 -0
- package/dist/context-fields.d.ts.map +1 -0
- package/dist/context-fields.js +146 -0
- package/dist/context-fields.js.map +1 -0
- package/dist/context-scope.d.ts +29 -2
- package/dist/context-scope.d.ts.map +1 -1
- package/dist/context-scope.js +37 -1
- package/dist/context-scope.js.map +1 -1
- package/dist/credentials.d.ts +17 -0
- package/dist/credentials.d.ts.map +1 -0
- package/dist/credentials.js +16 -0
- package/dist/credentials.js.map +1 -0
- package/dist/define-core.d.ts +213 -0
- package/dist/define-core.d.ts.map +1 -0
- package/dist/define-core.js +161 -0
- package/dist/define-core.js.map +1 -0
- package/dist/define.d.ts +13 -8
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js +13 -8
- package/dist/define.js.map +1 -1
- package/dist/direct-registry.d.ts +154 -7
- package/dist/direct-registry.d.ts.map +1 -1
- package/dist/direct-registry.js +111 -13
- package/dist/direct-registry.js.map +1 -1
- package/dist/direct-tool-surface.d.ts +66 -0
- package/dist/direct-tool-surface.d.ts.map +1 -0
- package/dist/direct-tool-surface.js +162 -0
- package/dist/direct-tool-surface.js.map +1 -0
- package/dist/direct.d.ts +68 -0
- package/dist/direct.d.ts.map +1 -0
- package/dist/direct.js +66 -0
- package/dist/direct.js.map +1 -0
- package/dist/execution.d.ts +11 -1
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +18 -4
- package/dist/execution.js.map +1 -1
- package/dist/frontmatter.d.ts +16 -0
- package/dist/frontmatter.d.ts.map +1 -0
- package/dist/frontmatter.js +111 -0
- package/dist/frontmatter.js.map +1 -0
- package/dist/http-handler.d.ts +11 -2
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +46 -15
- package/dist/http-handler.js.map +1 -1
- package/dist/http-security.d.ts.map +1 -1
- package/dist/http-security.js.map +1 -1
- package/dist/http-sessions.d.ts +12 -4
- package/dist/http-sessions.d.ts.map +1 -1
- package/dist/http-sessions.js +4 -4
- package/dist/http-sessions.js.map +1 -1
- package/dist/http-sse.js.map +1 -1
- package/dist/index.d.ts +16 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/issue-message.d.ts +20 -0
- package/dist/issue-message.d.ts.map +1 -0
- package/dist/issue-message.js +55 -0
- package/dist/issue-message.js.map +1 -0
- package/dist/journal-replay.d.ts +7 -0
- package/dist/journal-replay.d.ts.map +1 -1
- package/dist/journal-replay.js +18 -1
- package/dist/journal-replay.js.map +1 -1
- package/dist/journal.d.ts +9 -1
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +44 -1
- package/dist/journal.js.map +1 -1
- package/dist/json-rpc.d.ts +2 -2
- package/dist/json-rpc.d.ts.map +1 -1
- package/dist/json-rpc.js.map +1 -1
- package/dist/json-schema.d.ts +30 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +25 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/lazy-tools.d.ts +3 -0
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +2 -0
- package/dist/lazy-tools.js.map +1 -1
- package/dist/mcp-auth-bearer.d.ts +23 -0
- package/dist/mcp-auth-bearer.d.ts.map +1 -0
- package/dist/mcp-auth-bearer.js +50 -0
- package/dist/mcp-auth-bearer.js.map +1 -0
- package/dist/mcp-auth-jwt.d.ts +178 -0
- package/dist/mcp-auth-jwt.d.ts.map +1 -0
- package/dist/mcp-auth-jwt.js +365 -0
- package/dist/mcp-auth-jwt.js.map +1 -0
- package/dist/mcp-auth-resource.d.ts +74 -0
- package/dist/mcp-auth-resource.d.ts.map +1 -0
- package/dist/mcp-auth-resource.js +196 -0
- package/dist/mcp-auth-resource.js.map +1 -0
- package/dist/mcp-auth-rules.d.ts +135 -0
- package/dist/mcp-auth-rules.d.ts.map +1 -0
- package/dist/mcp-auth-rules.js +306 -0
- package/dist/mcp-auth-rules.js.map +1 -0
- package/dist/mcp-auth.d.ts +81 -0
- package/dist/mcp-auth.d.ts.map +1 -0
- package/dist/mcp-auth.js +256 -0
- package/dist/mcp-auth.js.map +1 -0
- package/dist/mcp-modern.d.ts +29 -5
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +99 -19
- package/dist/mcp-modern.js.map +1 -1
- package/dist/meta-argument.d.ts +42 -0
- package/dist/meta-argument.d.ts.map +1 -0
- package/dist/meta-argument.js +102 -0
- package/dist/meta-argument.js.map +1 -0
- package/dist/meta-keys.d.ts +29 -0
- package/dist/meta-keys.d.ts.map +1 -0
- package/dist/meta-keys.js +90 -0
- package/dist/meta-keys.js.map +1 -0
- package/dist/meta-tools.d.ts +8 -1
- package/dist/meta-tools.d.ts.map +1 -1
- package/dist/meta-tools.js +17 -7
- package/dist/meta-tools.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +0 -1
- package/dist/middleware.js.map +1 -1
- package/dist/patterns.d.ts +46 -0
- package/dist/patterns.d.ts.map +1 -0
- package/dist/patterns.js +38 -0
- package/dist/patterns.js.map +1 -0
- package/dist/principal-binding.d.ts +42 -0
- package/dist/principal-binding.d.ts.map +1 -0
- package/dist/principal-binding.js +70 -0
- package/dist/principal-binding.js.map +1 -0
- package/dist/request-context.d.ts +7 -1
- package/dist/request-context.d.ts.map +1 -1
- package/dist/request-context.js +14 -3
- package/dist/request-context.js.map +1 -1
- package/dist/resources.d.ts +122 -0
- package/dist/resources.d.ts.map +1 -0
- package/dist/resources.js +256 -0
- package/dist/resources.js.map +1 -0
- package/dist/schema.d.ts +7 -171
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +10 -135
- package/dist/schema.js.map +1 -1
- package/dist/server-types.d.ts +94 -7
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js +2 -0
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +45 -31
- package/dist/server.js.map +1 -1
- package/dist/skills.d.ts +95 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +340 -0
- package/dist/skills.js.map +1 -0
- package/dist/strict-json.d.ts +17 -0
- package/dist/strict-json.d.ts.map +1 -0
- package/dist/strict-json.js +93 -0
- package/dist/strict-json.js.map +1 -0
- package/dist/tool-router.d.ts +13 -1
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +44 -10
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts +10 -5
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +48 -22
- package/dist/tools.js.map +1 -1
- package/dist/validation.d.ts +6 -45
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +25 -58
- package/dist/validation.js.map +1 -1
- package/dist/verified-credentials.d.ts +34 -0
- package/dist/verified-credentials.d.ts.map +1 -0
- package/dist/verified-credentials.js +51 -0
- package/dist/verified-credentials.js.map +1 -0
- package/package.json +18 -6
package/README.md
CHANGED
|
@@ -175,7 +175,8 @@ Point MCP clients at `/mcp`, for example `claude mcp add --transport http my-ser
|
|
|
175
175
|
The root entry loads the MCP SDK, `node:http` and `node:tls`, so it cannot be
|
|
176
176
|
bundled for the browser. Code that only defines commands (shared command
|
|
177
177
|
modules, UI state packages, in-app agents) can import from the `/define`
|
|
178
|
-
subpath instead. It exports `defineCommand`,
|
|
178
|
+
subpath instead. It exports `defineCommand`, `defineCommandWithSchema` (see
|
|
179
|
+
[below](#the-lean-path-definecommandwithschema)), the schema helpers
|
|
179
180
|
(`zodToJsonSchema`, `getRequiredFields`, `isObjectSchema`), the result helpers
|
|
180
181
|
(`success`, `failure`, `error`, `isSuccess`, `isFailure`), `defaultExpose` and
|
|
181
182
|
the matching types, with no MCP SDK or Node.js builtin in its module graph:
|
|
@@ -196,6 +197,328 @@ export const panelOpen = defineCommand({
|
|
|
196
197
|
|
|
197
198
|
The same functions are still exported from `@lushly-dev/afd-server`.
|
|
198
199
|
|
|
200
|
+
### The lean path: `defineCommandWithSchema`
|
|
201
|
+
|
|
202
|
+
`defineCommand` computes each command's JSON Schema with `toJSONSchema` as it
|
|
203
|
+
loads, and takes classic Zod. A browser bundle pays for both. When you already
|
|
204
|
+
have the JSON Schema, `defineCommandWithSchema` takes it as written, with a
|
|
205
|
+
classic or a [Zod Mini](https://zod.dev/packages/mini) schema to validate. A host
|
|
206
|
+
that defines every command this way and imports only `createDirectRegistry`,
|
|
207
|
+
`createJournalMiddleware` and the middleware bundles `zod/v4/core` and neither
|
|
208
|
+
classic Zod nor `toJSONSchema`. A test holds that, with esbuild. Import Zod Mini as
|
|
209
|
+
`import * as z from 'zod/mini'`: esbuild cannot tree-shake `import { z }`, and keeps
|
|
210
|
+
all of it, locales and `toJSONSchema` included. Vite 8 handles either form.
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
import * as z from 'zod/mini';
|
|
214
|
+
import { defineCommandWithSchema, success } from '@lushly-dev/afd-server/define';
|
|
215
|
+
|
|
216
|
+
export const panelOpen = defineCommandWithSchema({
|
|
217
|
+
name: 'panel-open',
|
|
218
|
+
description: 'Open a panel',
|
|
219
|
+
input: z.object({ id: z.string() }),
|
|
220
|
+
jsonSchema: {
|
|
221
|
+
type: 'object',
|
|
222
|
+
properties: { id: { type: 'string' } },
|
|
223
|
+
required: ['id'],
|
|
224
|
+
},
|
|
225
|
+
async handler(input) {
|
|
226
|
+
return success({ id: input.id, open: true });
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
- **Nothing compares the two.** `input` validates every call and `jsonSchema` is
|
|
232
|
+
what every surface shows, so hold them equal in a test, against
|
|
233
|
+
`zodToJsonSchema(schema)`. `advertisedInputSchema` still replaces it.
|
|
234
|
+
- **Output is not converted either.** Pass `outputJsonSchema` beside `output` to
|
|
235
|
+
advertise it. With `output` alone, no surface shows an output schema.
|
|
236
|
+
- **`createDirectToolSurface` and the MCP servers still load both**, since their
|
|
237
|
+
own tools are defined on classic Zod.
|
|
238
|
+
- **Messages.** Zod Mini loads no locale, so with no classic schema built on the
|
|
239
|
+
page an issue says only `Invalid input`. `VALIDATION_ERROR` then builds its text
|
|
240
|
+
from the issue, as Zod's English does for a wrong type, a value, a size other than a
|
|
241
|
+
file's, an unknown key, a regex or a discriminator. A format keeps its own name (`Invalid
|
|
242
|
+
email` for `Invalid email address`), and a rarer code, such as `multipleOf`, says
|
|
243
|
+
`Invalid input`, with the field's path. With a locale loaded, or a message of the
|
|
244
|
+
schema's own, nothing is rebuilt.
|
|
245
|
+
|
|
246
|
+
Types: `ZodCommandDefinition` with no type argument still reads as classic, so
|
|
247
|
+
`command.inputSchema.safeParse(input)` works as before. A Mini command is cast to
|
|
248
|
+
it for `createDirectRegistry`, as a typed classic command is, with
|
|
249
|
+
`as unknown as ZodCommandDefinition`.
|
|
250
|
+
|
|
251
|
+
### In-process entry point: `@lushly-dev/afd-server/direct`
|
|
252
|
+
|
|
253
|
+
A host that runs commands in its own process (a browser app, a web worker, a
|
|
254
|
+
Tauri or Electron webview, or a Node.js host that does not want the MCP SDK)
|
|
255
|
+
imports from `/direct`. It exports everything `/define` does, plus:
|
|
256
|
+
|
|
257
|
+
- `createDirectRegistry`, with validation, middleware, exposure checks and
|
|
258
|
+
error sanitization, as `createMcpServer` runs them, and AFD contexts scoped
|
|
259
|
+
per call;
|
|
260
|
+
- `createDirectToolSurface`, the MCP tool surface for that registry (see
|
|
261
|
+
below);
|
|
262
|
+
- `createApprovalMiddleware`, on WebCrypto (see [Approvals](#approvals));
|
|
263
|
+
- `createJournalMiddleware`, `replayJournal` and `MemoryJournalSink`;
|
|
264
|
+
- the middleware with no Node.js builtin in its module graph:
|
|
265
|
+
`composeMiddleware`, `defaultMiddleware`, `createLoggingMiddleware`,
|
|
266
|
+
`createTimingMiddleware`, `createRetryMiddleware`, `createTracingMiddleware`,
|
|
267
|
+
`createAutoTraceIdMiddleware`, `createRateLimitMiddleware`,
|
|
268
|
+
`createTelemetryMiddleware` and `ConsoleTelemetrySink`.
|
|
269
|
+
|
|
270
|
+
```typescript
|
|
271
|
+
import {
|
|
272
|
+
createDirectRegistry,
|
|
273
|
+
createJournalMiddleware,
|
|
274
|
+
MemoryJournalSink,
|
|
275
|
+
} from '@lushly-dev/afd-server/direct';
|
|
276
|
+
import { panelOpen } from './commands.js';
|
|
277
|
+
|
|
278
|
+
const journal = new MemoryJournalSink();
|
|
279
|
+
const registry = createDirectRegistry([panelOpen], {
|
|
280
|
+
middleware: [createJournalMiddleware(journal)],
|
|
281
|
+
});
|
|
282
|
+
await registry.execute('panel-open', { id: 'settings' });
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
A test bundles `/direct` for the browser, failing on any MCP SDK or Node.js
|
|
286
|
+
builtin, and holds AFD's own code (minified, Zod excluded) to 39 KB for a host
|
|
287
|
+
that imports the registry, the journal and `defineCommand`, 52 KB with the
|
|
288
|
+
approval middleware as well, 74 KB for a host that also imports
|
|
289
|
+
`createDirectToolSurface`, and 113 KB for every export. A host that does
|
|
290
|
+
not import the tool surface does not bundle the tool router. A Chromium test
|
|
291
|
+
runs a command through the registry with the journal and approval middleware,
|
|
292
|
+
approves it through `DirectClient`, and replays the journal.
|
|
293
|
+
|
|
294
|
+
#### Contexts and `activeContext`
|
|
295
|
+
|
|
296
|
+
`createDirectRegistry(commands, { contexts })` takes the same context
|
|
297
|
+
definitions as `createMcpServer`. The active context is per-call input, as
|
|
298
|
+
`_meta["dev.afd/context"]` is on MCP 2026-07-28, never registry state: a call
|
|
299
|
+
names it in the `activeContext` option, passed beside the command context so a
|
|
300
|
+
handler cannot read or set it.
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
const registry = createDirectRegistry(commands, {
|
|
304
|
+
contexts: [{ name: 'billing' }, { name: 'writing' }],
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
await registry.execute('invoice-pay', { id: 'in-1' }, {}, { activeContext: 'billing' });
|
|
308
|
+
await registry.execute('note-create', { title: 'x' }, {}, { activeContext: 'billing' });
|
|
309
|
+
// → COMMAND_NOT_IN_CONTEXT: note-create declares contexts: ['writing']
|
|
310
|
+
await registry.execute('note-create', { title: 'x' }, {}, { activeContext: 'nope' });
|
|
311
|
+
// → CONTEXT_NOT_FOUND, before anything runs
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Without `activeContext` every command is available, as on MCP with no context
|
|
315
|
+
selected. The option covers the commands a call runs through `afd-call`,
|
|
316
|
+
`afd-batch` and `afd-pipe` too. Naming a context on a registry that configures
|
|
317
|
+
none fails with `CONTEXT_NOT_FOUND`. `DirectClient` takes the same option on
|
|
318
|
+
`call()` and `pipe()` (see `@lushly-dev/afd-client`). Contexts scope what an
|
|
319
|
+
agent sees; they are not a security boundary.
|
|
320
|
+
|
|
321
|
+
#### The tool surface: `createDirectToolSurface`
|
|
322
|
+
|
|
323
|
+
An in-page agent that should see what an MCP agent sees gets the MCP tool
|
|
324
|
+
surface from the code the MCP server runs: its tool list for every strategy, its
|
|
325
|
+
tool router, the meta-tools (`afd-discover`, `afd-detail`, `afd-call`,
|
|
326
|
+
`afd-batch`, `afd-pipe`), the context tools when `contexts` is set, and, with
|
|
327
|
+
`bootstrap: true`, `afd-help`, `afd-docs` and `afd-schema`.
|
|
328
|
+
|
|
329
|
+
```typescript
|
|
330
|
+
import { createDirectRegistry, createDirectToolSurface } from '@lushly-dev/afd-server/direct';
|
|
331
|
+
|
|
332
|
+
const registry = createDirectRegistry(commands, {
|
|
333
|
+
contexts,
|
|
334
|
+
tools: createDirectToolSurface({ strategy: 'lazy' }),
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
registry.listTools(); // what an MCP server with these commands lists
|
|
338
|
+
registry.listTools({ strategy: 'grouped', activeContext: 'billing' });
|
|
339
|
+
await registry.execute('afd-discover', {}, {}, { activeContext: 'billing' });
|
|
340
|
+
await registry.execute('afd-call', { command: 'invoice-pay', input: { id: 'in-1' } });
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
| `createDirectToolSurface` option | Default | Description |
|
|
344
|
+
|--------|---------|-------------|
|
|
345
|
+
| `strategy` | `'individual'` | `'individual'`, `'grouped'`, `'lazy'` or `'hybrid'`: the default for `listTools`, and the strategy grouped tool calls route by |
|
|
346
|
+
| `firstClassTools` | — | The hybrid strategy's first-class commands, checked as `createMcpServer` checks them |
|
|
347
|
+
| `bootstrap` | `false` | Register `afd-help`, `afd-docs` and `afd-schema` |
|
|
348
|
+
|
|
349
|
+
- `registry.listTools({ strategy?, activeContext?, allow? })` returns exactly
|
|
350
|
+
what an MCP server with the same commands, contexts and strategy lists, by
|
|
351
|
+
calling the server's own tool list, with the server's defaults for
|
|
352
|
+
`groupByFn`, `advertiseOutputSchema` and `confirmations` (in-process calls are
|
|
353
|
+
never confirmation-gated). With `allow`, it leaves out the commands and tool
|
|
354
|
+
names the predicate rejects (see below). It throws a `TypeError` on a
|
|
355
|
+
registry built without `tools`, and a `RangeError` for an unknown context.
|
|
356
|
+
- `registry.execute` sends meta-tool names, and grouped tool names under the
|
|
357
|
+
grouped strategy, through the server's tool router, and returns the JSON an
|
|
358
|
+
MCP client reads (`afd-batch` a `BatchResult`, `afd-pipe` a
|
|
359
|
+
`PipelineResult`). Command names, the context tools and the bootstrap tools
|
|
360
|
+
run as commands. `hasCommand` answers `true` for the routed tool names.
|
|
361
|
+
- `afd-context-enter` and `afd-context-exit` behave as on the stateless MCP
|
|
362
|
+
2026-07-28 lane: they validate the name, change nothing, and return
|
|
363
|
+
`persisted: false` with the hint to send the context on each call. A host
|
|
364
|
+
that wants a context stack keeps it and passes its top as `activeContext`.
|
|
365
|
+
- Exposure: where the MCP server lists and routes its MCP-exposed commands, the
|
|
366
|
+
surface uses the commands exposed to the registry's `interface` (`'agent'`
|
|
367
|
+
by default), and exposes its own tools to that interface. A registry built
|
|
368
|
+
with `interface: 'mcp'` sees exactly the MCP server's commands.
|
|
369
|
+
- With the surface, a command named like a meta-tool always throws, and like a
|
|
370
|
+
context or bootstrap tool when those are registered, as on `createMcpServer`.
|
|
371
|
+
Refusals point to `afd-discover` and the context tools only when the surface
|
|
372
|
+
serves them; without it, `COMMAND_NOT_FOUND` ends "Check the command name
|
|
373
|
+
against the available commands." and `COMMAND_NOT_IN_CONTEXT` names the
|
|
374
|
+
command's contexts.
|
|
375
|
+
|
|
376
|
+
#### The `allow` call option
|
|
377
|
+
|
|
378
|
+
`allow` is a trusted, in-process predicate over names, passed beside
|
|
379
|
+
`activeContext`. It covers the name a call names and every command that call
|
|
380
|
+
runs: the `afd-call` target, each `afd-batch` item, each `afd-pipe` step, a
|
|
381
|
+
grouped tool's action, and a command a handler runs by passing its own context
|
|
382
|
+
to `execute`. A name it rejects, or a predicate that throws, fails with
|
|
383
|
+
`COMMAND_NOT_ALLOWED` (the failure `DirectClient` gives) before anything runs.
|
|
384
|
+
`afd-discover`, `afd-detail` and the bootstrap tools leave refused commands
|
|
385
|
+
out, and so does `listTools({ allow })`.
|
|
386
|
+
|
|
387
|
+
```typescript
|
|
388
|
+
const allowed = new Set(['afd-call', 'afd-batch', 'note-list']);
|
|
389
|
+
const allow = (name: string) => allowed.has(name);
|
|
390
|
+
|
|
391
|
+
await registry.execute('afd-call', { command: 'note-list', input: {} }, {}, { allow }); // runs
|
|
392
|
+
await registry.execute('afd-call', { command: 'note-delete', input: { id: 'n1' } }, {}, { allow });
|
|
393
|
+
// → COMMAND_NOT_ALLOWED; so is note-delete as an afd-batch item or an afd-pipe step
|
|
394
|
+
registry.listTools({ allow }); // afd-batch, afd-call, note-list
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
`DirectClient` passes its own `allow` this way on every call, `pipe()` step and
|
|
398
|
+
approval retry, so allowing a meta-tool or a grouped tool no longer reaches
|
|
399
|
+
commands `allow` refuses. The registry binds the predicate to the call's context
|
|
400
|
+
as an opaque token, so handlers cannot read or replace it, and tool arguments
|
|
401
|
+
cannot carry one. Without `allow`, nothing changes. A grouped tool's own name
|
|
402
|
+
is checked too: allow the group (`note`) to call its permitted actions. The
|
|
403
|
+
action resolves among the permitted commands only, so a refused action is
|
|
404
|
+
`COMMAND_NOT_FOUND` and cannot make another ambiguous, and a group with no
|
|
405
|
+
permitted action is `COMMAND_NOT_ALLOWED`.
|
|
406
|
+
|
|
407
|
+
### Verified credentials: `@lushly-dev/afd-server/credentials`
|
|
408
|
+
|
|
409
|
+
`isVerifiedCredentials(value)` answers whether `value` is the `credentials`
|
|
410
|
+
object afd-server put on a call after verifying the call's token. The brand is
|
|
411
|
+
a private `WeakSet`, so a copy, an object built with the same fields, the
|
|
412
|
+
`credentials` a direct-registry caller passes, and those a host's
|
|
413
|
+
`createContext` sets are never recognised. Branded credentials are frozen, and
|
|
414
|
+
stop being recognised once their `expiresAt` has passed (`isVerifiedCredentials(value, now?)`,
|
|
415
|
+
`now` defaulting to `Date.now()`) or their request has ended. No entry exports
|
|
416
|
+
the functions that brand and unbrand: only the [`auth` option](#mcp-authorization)
|
|
417
|
+
brands, the credentials of a request it verified. A nested call keeps the brand
|
|
418
|
+
only if it is given the same object.
|
|
419
|
+
|
|
420
|
+
A host that serves MCP with token authorization through afd-auth's middleware
|
|
421
|
+
passes it there, so a token's call keeps its actor rather than the session's:
|
|
422
|
+
|
|
423
|
+
```typescript
|
|
424
|
+
import { createAuthMiddleware } from '@lushly-dev/afd-auth';
|
|
425
|
+
import { isVerifiedCredentials } from '@lushly-dev/afd-server/credentials';
|
|
426
|
+
|
|
427
|
+
const auth = createAuthMiddleware(adapter, { isVerifiedCredentials });
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
The entry loads nothing else of the server and is held browser-safe by
|
|
431
|
+
`entry-points.test.ts`. The root entry exports the same function.
|
|
432
|
+
|
|
433
|
+
### MCP authorization
|
|
434
|
+
|
|
435
|
+
With `auth`, `createMcpHandler` (and `createMcpServer` over HTTP) is an OAuth 2.1
|
|
436
|
+
protected resource, as [`spec/authorization.md`](../../spec/authorization.md) M1
|
|
437
|
+
to M5 and M7 specify:
|
|
438
|
+
|
|
439
|
+
```typescript
|
|
440
|
+
import { createMcpHandler, JwtVerifier, jwksKeySource } from '@lushly-dev/afd-server';
|
|
441
|
+
|
|
442
|
+
const resource = 'https://todo.example.com/mcp';
|
|
443
|
+
const handler = createMcpHandler({
|
|
444
|
+
name: 'todo',
|
|
445
|
+
version: '1.0.0',
|
|
446
|
+
commands,
|
|
447
|
+
allowedHosts: ['todo.example.com'],
|
|
448
|
+
auth: {
|
|
449
|
+
resource,
|
|
450
|
+
authorizationServers: ['https://auth.example.com'],
|
|
451
|
+
scopesSupported: ['todo:read'],
|
|
452
|
+
verifier: new JwtVerifier({
|
|
453
|
+
rules: { resource },
|
|
454
|
+
issuers: [
|
|
455
|
+
{
|
|
456
|
+
issuer: 'https://auth.example.com',
|
|
457
|
+
algorithms: ['RS256', 'ES256', 'EdDSA'],
|
|
458
|
+
// The host fetches; AFD opens no socket.
|
|
459
|
+
keys: jwksKeySource(() => fetch('https://auth.example.com/jwks').then((r) => r.json())),
|
|
460
|
+
},
|
|
461
|
+
],
|
|
462
|
+
}),
|
|
463
|
+
},
|
|
464
|
+
// Map the verified credentials to an actor (optional).
|
|
465
|
+
createContext: (_req, { credentials }) => ({
|
|
466
|
+
actor: { kind: 'agent', id: credentials?.clientId, onBehalfOf: credentials?.subject },
|
|
467
|
+
}),
|
|
468
|
+
});
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
- **Every HTTP route needs exactly one bearer token** in the `Authorization`
|
|
472
|
+
header (`/mcp`, `/sse`, `/message`, `/rpc`, `/batch`, `/stream`, `/health`
|
|
473
|
+
and any other path). A missing, malformed or refused one, a token in the query
|
|
474
|
+
or a form body, or a second header is a 401 with M5's exact
|
|
475
|
+
`WWW-Authenticate` challenge and JSON body. Only the RFC 9728 metadata,
|
|
476
|
+
served by `GET` at `/.well-known/oauth-protected-resource<path>` and
|
|
477
|
+
`/.well-known/oauth-protected-resource`, and CORS preflights are public.
|
|
478
|
+
`/health` needs a token too, so it fails closed: a host that needs a public
|
|
479
|
+
health check serves its own route before handing the request to the handler.
|
|
480
|
+
stdio, `server.execute()` and in-process registries are unaffected.
|
|
481
|
+
- **`JwtVerifier`** applies every M3 rule itself, in order; `jose` checks the
|
|
482
|
+
signature only, through WebCrypto (RS256 to RS512, PS256 to PS512, ES256,
|
|
483
|
+
ES384 and EdDSA on Ed25519). The audience check is not optional: `aud` must be
|
|
484
|
+
the `resource`, alone. `none` and `HS*` are always refused, the clock skew is
|
|
485
|
+
at most 300 seconds (default 60) and the lifetime at most 3600 seconds by
|
|
486
|
+
default. An opaque token goes to `createIntrospectionVerifier({ issuer, rules,
|
|
487
|
+
introspect })`, given as `introspection`, whose `introspect(token)` is the
|
|
488
|
+
host's RFC 7662 call; its rules must name the same resource and binding
|
|
489
|
+
requirement. Give each issuer a key source of its own (a `kid` names a key
|
|
490
|
+
only within one issuer's set): two issuers sharing one are refused, and so is
|
|
491
|
+
an issuer `authorizationServers` does not name. `jwksKeySource` keeps the last
|
|
492
|
+
good keys while loads fail, for at most `maxStaleMs` (default one hour), then
|
|
493
|
+
answers `unavailable`.
|
|
494
|
+
- **Whatever the verifier, the layer checks** the credentials' shape, their
|
|
495
|
+
certificate binding against this request's TLS client certificate, the
|
|
496
|
+
binding requirement, and `expiresAt` (within the verifier's skew), refusing
|
|
497
|
+
with M5's 401.
|
|
498
|
+
- **HTTP sessions belong to their caller.** With `contexts`, a session that
|
|
499
|
+
`initialize` creates on `/message` is bound to the credentials' issuer,
|
|
500
|
+
subject and client; another caller presenting its `Mcp-Session-Id` is
|
|
501
|
+
answered as for an unknown session.
|
|
502
|
+
- **Commands see `context.credentials`** (`issuer`, `subject`, `clientId`,
|
|
503
|
+
`scopes`, `resource`, `expiresAt`, `issuedAt`, and `authTime`, `acr` and `cnf`
|
|
504
|
+
when present), frozen and recognised by `isVerifiedCredentials` until the
|
|
505
|
+
request ends. A token accepted inside the clock skew after its `exp` has
|
|
506
|
+
credentials `isVerifiedCredentials` no longer recognises, so afd-auth's
|
|
507
|
+
middleware gates that call on its session, and a server with no session
|
|
508
|
+
answers it `UNAUTHORIZED`: the safe side. Never the token: the layer removes the `Authorization` header
|
|
509
|
+
before `createContext` runs, and the journal never records credentials.
|
|
510
|
+
Without an `actor` from `createContext`, the actor is
|
|
511
|
+
`{ kind: 'agent', id: <clientId>, onBehalfOf: <subject> }`.
|
|
512
|
+
- **A refused token's rule code** (`audience`, `expired`, ...) goes to
|
|
513
|
+
`auth.onRefusal`, by default a `console.warn` line, with the issuer's alias;
|
|
514
|
+
never the token or a claim. A host verifier may wrap `JwtVerifier` to refuse
|
|
515
|
+
more with a code of its own, which is answered the same way.
|
|
516
|
+
- **Scopes (M6) are not enforced yet.** `requiredScopes`, `resolver` and
|
|
517
|
+
`filterToolsByScope` throw rather than be ignored.
|
|
518
|
+
|
|
519
|
+
A server that also runs afd-auth's middleware passes `isVerifiedCredentials` to
|
|
520
|
+
`createAuthMiddleware`, as [above](#verified-credentials-lushly-devafd-servercredentials).
|
|
521
|
+
|
|
199
522
|
### Basic Command
|
|
200
523
|
|
|
201
524
|
```typescript
|
|
@@ -204,6 +527,7 @@ import { defineCommand, success, failure } from '@lushly-dev/afd-server';
|
|
|
204
527
|
|
|
205
528
|
const createUser = defineCommand({
|
|
206
529
|
name: 'user-create',
|
|
530
|
+
title: 'Create user', // optional display label: the MCP tool title
|
|
207
531
|
description: 'Create a new user',
|
|
208
532
|
category: 'users',
|
|
209
533
|
mutation: true,
|
|
@@ -362,6 +686,8 @@ const server = createMcpServer({
|
|
|
362
686
|
cors: true, // Send CORS headers (default: follows devMode)
|
|
363
687
|
toolStrategy: 'grouped', // Default: 'grouped' (see "Tool Strategies")
|
|
364
688
|
bootstrap: true, // Add afd-help, afd-docs, afd-schema (default: false)
|
|
689
|
+
resources: provider, // MCP resources (see "Resources, Skills and Tool _meta")
|
|
690
|
+
skills: catalog, // Agent Skills over MCP (a SkillCatalog)
|
|
365
691
|
|
|
366
692
|
// Per-request context for HTTP calls (see "Request Context")
|
|
367
693
|
createContext: (req) => ({ clientIp: req.socket.remoteAddress ?? 'unknown' }),
|
|
@@ -548,6 +874,8 @@ To resume, retry the same command with the same input and `context.approval` set
|
|
|
548
874
|
- **Single-use by default.** A token runs the command once (`reason: 'already-used'` after). `replay: 'within-ttl'` lets it run the same call as often as it is presented until it expires, so one approval also covers repeats such as duplicate batch items. Spent tokens are remembered in memory by this middleware instance: share one `nonceStore` (`consume(nonce, expiresAt)` returning `true` only for an unused nonce, atomically) between every instance that uses the secret, across processes or between a server and a `createDirectRegistry`.
|
|
549
875
|
- **Short-lived.** `ttlMs` defaults to 5 minutes, at most 24 hours. Time comes from the `clock` option, else the system clock; never from `context.clock`, which a caller can set.
|
|
550
876
|
- **Key rotation:** pass `secret: [newKey, oldKey]`; the first signs, any verifies.
|
|
877
|
+
- **WebCrypto.** The middleware uses `globalThis.crypto` (Node.js 22 and every current browser on a secure origin), so it also runs in a browser or webview through `@lushly-dev/afd-server/direct`. Tokens are byte for byte the same in TypeScript, Python, Rust and C++ (`spec/vectors/approval-tokens.json`).
|
|
878
|
+
- **In a page, the secret is not a boundary.** A signing secret held in a page is visible to every script on that page. The gate still stops a model from approving its own call through tool input, and DirectClient's private exchange never puts the secret or a token in a result the model reads, but it does not protect against code running in the page. When you need that, keep approvals on a server.
|
|
551
879
|
- **Fails closed.** A policy function that returns anything but `'not-required'` holds the call; one that throws fails it before the handler. Write policies so that a missing actor is held (`kind === 'human' ? 'not-required' : 'required'`).
|
|
552
880
|
- **Gates only the listed commands.** Pass the same `commands` as the server or registry: a command missing from the list is never held.
|
|
553
881
|
- **Actor binding is as strong as the actor.** The MCP default actor is `{ kind: 'agent' }` with no `id`, so tokens are bound to a specific agent or user only when `createContext` or auth middleware sets one. Install the middleware after any middleware that sets or refines `context.actor`.
|
|
@@ -584,9 +912,35 @@ The relay trusts the MCP client application to put the question to a person. The
|
|
|
584
912
|
|
|
585
913
|
`spec/command-metadata.md` ("Approvals") is the cross-language contract.
|
|
586
914
|
|
|
915
|
+
### Declared Context Fields
|
|
916
|
+
|
|
917
|
+
Some values belong to a request rather than to one command's input: the project a shell is scoped to, the space a query targets, the calling app, a locale. Declare each one on the server or registry with `contextFields`, and a call carries it on its context under the field's name:
|
|
918
|
+
|
|
919
|
+
```typescript
|
|
920
|
+
const server = createMcpServer({
|
|
921
|
+
name: 'shell',
|
|
922
|
+
version: '1.0.0',
|
|
923
|
+
commands,
|
|
924
|
+
contextFields: [
|
|
925
|
+
{ name: 'scope', meta: 'dev.example/scope', schema: z.object({ project: z.string() }), journal: true },
|
|
926
|
+
{ name: 'locale', meta: 'dev.example/locale', schema: z.string().max(35) },
|
|
927
|
+
],
|
|
928
|
+
});
|
|
929
|
+
await server.execute('project-summary', {}, { scope: { project: 'p-1' } });
|
|
930
|
+
// The handler reads context.scope, validated by its schema.
|
|
931
|
+
```
|
|
932
|
+
|
|
933
|
+
- The value is validated before middleware runs. An invalid value, or a missing `required: true` one, fails the call with `VALIDATION_ERROR`, whose `details` name the `field` and its `meta` key. `null` is no value. AFD's own `afd-*` commands do not enforce `required`, so a client can discover the fields first.
|
|
934
|
+
- Names AFD already uses (`actor`, `approval`, `auth`, `clock`, `credentials`, `interface`, `random`, `session`, `signal`, `source`, `timeout`, `traceId`) are refused, as is a `meta` key without a reverse-DNS prefix or with `dev.afd/` or an MCP-reserved prefix.
|
|
935
|
+
- A field is a claim made by the caller: use it to narrow what a handler does (pick a project), never to grant access. Check the caller's access to the claimed scope.
|
|
936
|
+
- `journal: true` keeps the value in the journal (below). Only declare it for a field that never holds a secret.
|
|
937
|
+
- Over MCP the value comes from `tools/call`'s `params._meta[meta]`, on both eras and over stdio and HTTP; undeclared `_meta` keys are dropped, and a value `createContext` sets for the same name wins. On AFD's HTTP lanes, `/message` reads `params._meta`, `/rpc` reads `params._meta` and `/stream` the `_meta` member of its input (both leave it out of the command input), and `/batch` reads the body's `_meta`.
|
|
938
|
+
- A client that cannot set `_meta` can send the same values in the meta-tools' `meta` argument: `afd-call`, `afd-batch`, `afd-pipe`, `afd-discover` and `afd-detail` take `meta: { "dev.afd/context": "billing", "dev.loam/scope": { ... } }`, applied as if sent in `_meta`. Other keys are dropped, and a key sent both ways must agree, or the call fails with `VALIDATION_ERROR`.
|
|
939
|
+
- `server/discover` lists the fields under `_meta["dev.afd/context-fields"]` and `afd-help` returns them as `contextFields`, each with its JSON Schema. `tools/list` never varies by a field. `spec/context-fields.md` is the cross-language contract.
|
|
940
|
+
|
|
587
941
|
### Command Journal and Replay
|
|
588
942
|
|
|
589
|
-
`createJournalMiddleware(sink)` records each accepted call (validation and lookup rejections never reach middleware) as a `JournalEntry`: command, validated input, actor, trace ID, a context digest, the result and the duration. Context values outside the allowlist (actor, interface, trace ID) are never stored, so auth sessions and tokens stay out of the journal. Each entry also holds a tape of the values the handler read from `context.clock` and `context.random`. Failures are recorded only with `recordFailures: true`. Commands named `auth-*` are skipped by default; `filter` and `redact` keep other secret inputs or results out (drop `tape` as well when a secret comes from `context.random`). Put it last in the middleware list.
|
|
943
|
+
`createJournalMiddleware(sink)` records each accepted call (validation and lookup rejections never reach middleware) as a `JournalEntry`: command, validated input, actor, trace ID, a context digest, the result and the duration. Context values outside the allowlist (actor, interface, trace ID) are never stored, so auth sessions and tokens stay out of the journal. Each entry also holds a tape of the values the handler read from `context.clock` and `context.random`. Failures are recorded only with `recordFailures: true`. A [declared context field](#declared-context-fields) marked `journal: true` is kept in the entry's `context`, or named in `contextOmitted` when its canonical JSON exceeds 4096 bytes, and replay restores it. Commands named `auth-*` are skipped by default; `filter` and `redact` keep other secret inputs or results out (drop `tape` as well when a secret comes from `context.random`). Put it last in the middleware list.
|
|
590
944
|
|
|
591
945
|
`replayJournal(registry, entries)` re-runs the entries in order against a fresh server or registry, feeds each call its recorded clock and random values, and reports every entry as `same`, `different` (with a structural diff) or `error`. Replay against a server with the same middleware: the journal middleware in it lines the tape up with the handler and records nothing during replay. It reports divergence; it does not make other nondeterminism go away. The format is specified in [`spec/journal.md`](../../spec/journal.md).
|
|
592
946
|
|
|
@@ -654,6 +1008,8 @@ await client.call('todo-create', { title: { nested: true } });
|
|
|
654
1008
|
| `middleware` | `[]` | Middleware, as for `createMcpServer` |
|
|
655
1009
|
| `devMode` | `false` | Include exception messages and stacks in failures |
|
|
656
1010
|
| `onCommand`, `onError` | — | Hooks, as for `createMcpServer` |
|
|
1011
|
+
| `contexts` | — | Contexts, as for `createMcpServer`; a call names its own in the `activeContext` option |
|
|
1012
|
+
| `tools` | — | `createDirectToolSurface()`: `listTools`, the meta-tools, the context tools and, optionally, the bootstrap tools |
|
|
657
1013
|
|
|
658
1014
|
A command is exposed to the interface when its `expose` flag for it is `true`.
|
|
659
1015
|
Flags a command leaves out fall back to `defaultExpose` (`palette` and `agent`
|
|
@@ -720,6 +1076,8 @@ Create a command definition with Zod schema.
|
|
|
720
1076
|
| `expose` | ExposeOptions | No | Surfaces the command is exposed to; `{ mcp: true }` is required for MCP tools |
|
|
721
1077
|
| `examples` | `{ title, input }[]` | No | Example inputs, validated against `input` at define time |
|
|
722
1078
|
| `approval` | `'required'` \| `'not-required'` \| `(input, context) => …` | No | Whether a call needs human approval before the handler runs (default `'not-required'`); enforced by [`createApprovalMiddleware`](#approvals) |
|
|
1079
|
+
| `toolMeta` | `Record<string, unknown>` | No | Extra `_meta` entries on the command's tool, grouped action entry and `afd-detail`: prefixed keys with two or more labels, or `ui`; the server refuses others (see [Resources, Skills and Tool `_meta`](#resources-skills-and-tool-_meta)) |
|
|
1080
|
+
| `advertisedInputSchema` | JSON Schema object | No | The input schema shown on every surface in place of the one generated from `input`, which still validates |
|
|
723
1081
|
|
|
724
1082
|
### createMcpServer(options)
|
|
725
1083
|
|
|
@@ -733,7 +1091,8 @@ Create an MCP server from commands.
|
|
|
733
1091
|
| `transport` | `'stdio' \| 'http' \| 'auto'` | No | Transport protocol (default: `'auto'`, which picks stdio whenever stdin is not a TTY) |
|
|
734
1092
|
| `port` | number | No | Port for HTTP transport (default: 3100) |
|
|
735
1093
|
| `host` | string | No | Host for HTTP transport (default: localhost) |
|
|
736
|
-
| `toolStrategy` | `'individual' \| 'grouped' \| 'lazy'` | No | How commands appear as MCP tools (default: `'grouped'`) |
|
|
1094
|
+
| `toolStrategy` | `'individual' \| 'grouped' \| 'lazy' \| 'hybrid'` | No | How commands appear as MCP tools (default: `'grouped'`) |
|
|
1095
|
+
| `firstClassTools` | `string[]` | With `'hybrid'` | The commands a hybrid server lists as their own tools, in list order (1 to 8; refused with any other strategy) |
|
|
737
1096
|
| `groupByFn` | `(command) => string \| undefined` | No | Group name for the grouped strategy (default: `category`, else the first name segment) |
|
|
738
1097
|
| `contexts` | `{ name, description }[]` | No | Context scopes for dynamic tool filtering |
|
|
739
1098
|
| `bootstrap` | boolean | No | Register the `afd-help`, `afd-docs` and `afd-schema` MCP tools (default: `false`) |
|
|
@@ -742,7 +1101,8 @@ Create an MCP server from commands.
|
|
|
742
1101
|
| `allowedOrigins` | string[] | No | Additional exact browser origins |
|
|
743
1102
|
| `allowedHosts` | string[] | No | Accepted HTTP hostnames, without ports |
|
|
744
1103
|
| `maxBodyBytes` | number | No | Maximum JSON body bytes (default: 1048576) |
|
|
745
|
-
| `createContext` | `(req) => object \| Promise<object>` | No | Per-request values merged into the `CommandContext` of every remotely executed HTTP command |
|
|
1104
|
+
| `createContext` | `(req, { credentials? }) => object \| Promise<object>` | No | Per-request values merged into the `CommandContext` of every remotely executed HTTP command; with `auth`, it is given the verified credentials |
|
|
1105
|
+
| `auth` | `McpAuthOptions` | No | [MCP authorization](#mcp-authorization): every HTTP route needs a verified bearer token |
|
|
746
1106
|
| `maxSseConnections` | number | No | Concurrent `/sse` connections before HTTP 503 (default: 100) |
|
|
747
1107
|
| `maxSessions` | number | No | Live HTTP sessions when `contexts` are set; the least recently used is evicted (default: 1000) |
|
|
748
1108
|
| `sessionIdleTimeoutMs` | number | No | Idle time before an HTTP session expires (default: 1800000, 30 minutes) |
|
|
@@ -750,7 +1110,9 @@ Create an MCP server from commands.
|
|
|
750
1110
|
| `random` | `RandomSource` | No | `context.random` for every command (default: `systemRandom`) |
|
|
751
1111
|
| `actor` | `Actor` | No | `context.actor` for commands called over MCP when the context has none (default: `{ kind: 'agent' }`) |
|
|
752
1112
|
| `instructions` | string | No | Agent guidance returned by MCP `server/discover` (default: a description of the tool strategy, meta-tools and contexts) |
|
|
753
|
-
| `toolsListTtlMs` | number | No | `ttlMs` freshness hint on MCP 2026-07-28 `tools/list` and `server/discover` results (default: 300000, or 0 when `contexts` are set) |
|
|
1113
|
+
| `toolsListTtlMs` | number | No | `ttlMs` freshness hint on MCP 2026-07-28 `tools/list` and `server/discover` results (default: 300000, or 0 when `contexts` are set); also the `ttlMs` of resource and skill results, which `contexts` never lower |
|
|
1114
|
+
| `resources` | `ResourceProvider \| ResourceEntry[]` | No | MCP resources served on `/mcp` and stdio; declares the `resources` capability |
|
|
1115
|
+
| `skills` | `SkillCatalog` | No | Agent Skills served through `skills/list`, `skills/get` and as `skill://` resources; declares `io.modelcontextprotocol/skills` |
|
|
754
1116
|
| `middleware` | array | No | Middleware functions |
|
|
755
1117
|
| `onCommand` | function | No | Command execution callback |
|
|
756
1118
|
| `onError` | function | No | Error callback |
|
|
@@ -907,6 +1269,7 @@ const server = createMcpServer({
|
|
|
907
1269
|
| `grouped` (default) | One tool per group plus `afd-detail`. A group is the command's `category`, else the first name segment (`todo-create` → `todo`), or `groupByFn(command)` |
|
|
908
1270
|
| `individual` | One tool per command, with its full input schema and `_meta` |
|
|
909
1271
|
| `lazy` | `afd-discover` and `afd-detail` only |
|
|
1272
|
+
| `hybrid` | The five meta-tools, the context tools when `contexts` are set, then the commands in `firstClassTools` (at most 8) as individual tools. See [Hybrid Strategy](#hybrid-strategy) |
|
|
910
1273
|
|
|
911
1274
|
A grouped tool takes `{ action, params }`, where `action` is the command name without its group segment (`todo-create-batch` → `create-batch`). So that agents need not guess `params`, each grouped tool carries every action's schema and metadata in `_meta.actions`:
|
|
912
1275
|
|
|
@@ -971,6 +1334,105 @@ Output is kept small so lazy discovery stays cheap:
|
|
|
971
1334
|
- An unknown command name, whether called directly, through `afd-call`, `/rpc`, a batch entry or a pipeline step, returns `COMMAND_NOT_FOUND`. Its suggestion names at most three close matches callable in the active context and points to `afd-discover`, for example `Did you mean 'todo-create'? Other close matches: 'todo-update'. Use afd-discover to list all commands.` It never lists every command.
|
|
972
1335
|
- `afd-detail` entries for unknown names echo the requested name cut to 128 characters plus `…`. Found commands keep their exact name.
|
|
973
1336
|
|
|
1337
|
+
## Hybrid Strategy (Hot Path Plus Discovery)
|
|
1338
|
+
|
|
1339
|
+
The `hybrid` strategy lists a few commands as their own tools beside the lazy meta-tools. The list stays fixed as the command set grows, commands outside the set change without the client reloading tools, and `afd-call`, `afd-batch` and `afd-pipe` still reach every command ([`spec/tool-strategies.md`](../../spec/tool-strategies.md#hybrid)).
|
|
1340
|
+
|
|
1341
|
+
```typescript
|
|
1342
|
+
const server = createMcpServer({
|
|
1343
|
+
name: 'my-server',
|
|
1344
|
+
version: '1.0.0',
|
|
1345
|
+
commands: allCommands,
|
|
1346
|
+
toolStrategy: 'hybrid',
|
|
1347
|
+
firstClassTools: ['knowledge-search', 'knowledge-open', 'memory-remember'], // at most 8, in list order
|
|
1348
|
+
});
|
|
1349
|
+
```
|
|
1350
|
+
|
|
1351
|
+
`tools/list` is `afd-discover`, `afd-detail`, `afd-call`, `afd-batch`, `afd-pipe`; then `afd-context-list`, `afd-context-enter` and `afd-context-exit` when `contexts` are configured; then the first-class tools in the order given. Each first-class tool is the tool the `individual` strategy would list for that command (`inputSchema` with `confirm`, `annotations`, `outputSchema`, `_meta`).
|
|
1352
|
+
|
|
1353
|
+
- **Construction checks.** `createMcpServer` and `createMcpHandler` throw, naming the entry, when an entry is not a registered command, is not `expose.mcp`, is a meta-tool or context tool name, repeats, or is beyond the cap of 8; and when `firstClassTools` is given with another strategy, or `hybrid` has none or an empty list. A bootstrap tool (`afd-help`) may be first-class with `bootstrap: true`.
|
|
1354
|
+
- **Contexts.** The list never varies by the active context, so `toolsListTtlMs` keeps its 300,000 default even with `contexts`. A first-class command outside its `contexts` stays listed and answers `COMMAND_NOT_IN_CONTEXT`; `afd validate --surface` warns about it.
|
|
1355
|
+
- **Calls.** A first-class tool behaves as under `individual` (confirmations, approvals, errors); an exposed command that is not first-class runs by name or through the meta-tools.
|
|
1356
|
+
- **Fixed while running.** `tools/list` never changes and `listChanged` is `false`; changing the set is a restart.
|
|
1357
|
+
- **Reporting.** `afd-help` reports `toolStrategy` on every strategy and, on a hybrid server, `firstClassTools` and `firstClass: true` on those commands.
|
|
1358
|
+
|
|
1359
|
+
## Resources, Skills and Tool `_meta`
|
|
1360
|
+
|
|
1361
|
+
A server can serve more than tools: MCP **resources**, **Agent Skills** over the Skills extension (SEP-2640), extra `_meta` on a command's tool, and a command's input schema shown apart from the one that validates. Everything is opt-in; a server that uses none of it is unchanged. The rules are in [`spec/mcp-resources.md`](../../spec/mcp-resources.md). It is served on `/mcp` and on stdio, in both MCP eras, not on the deprecated `/sse` and `/message` lane.
|
|
1362
|
+
|
|
1363
|
+
### Resources
|
|
1364
|
+
|
|
1365
|
+
```typescript
|
|
1366
|
+
import { createMcpServer, MCP_APP_MIME_TYPE } from '@lushly-dev/afd-server';
|
|
1367
|
+
|
|
1368
|
+
const server = createMcpServer({
|
|
1369
|
+
name: 'notes',
|
|
1370
|
+
version: '1.0.0',
|
|
1371
|
+
commands,
|
|
1372
|
+
resources: {
|
|
1373
|
+
// Called on every list, so entries may change while the server runs.
|
|
1374
|
+
list: () => [
|
|
1375
|
+
{ uri: 'ui://notes/list.html', name: 'Notes view', mimeType: MCP_APP_MIME_TYPE, content: viewHtml },
|
|
1376
|
+
{ uri: 'file:///notes/readme.txt', name: 'Readme', mimeType: 'text/plain' },
|
|
1377
|
+
],
|
|
1378
|
+
// Reads every entry that has no `content`; return `undefined` for an unknown URI.
|
|
1379
|
+
read: (uri) => (uri === 'file:///notes/readme.txt' ? { content: 'Hello\n' } : undefined),
|
|
1380
|
+
},
|
|
1381
|
+
});
|
|
1382
|
+
```
|
|
1383
|
+
|
|
1384
|
+
`resources` takes a provider (`list()`, optional `read(uri)`) or an array of static entries. The server then declares the `resources` capability (never `subscribe` or `listChanged`) and answers `resources/list`, `resources/read` and an empty `resources/templates/list`.
|
|
1385
|
+
|
|
1386
|
+
- **Entries** need a `uri` (absolute, unique, no whitespace, not `skill://`) and a non-empty `name`; a `ui://` entry needs `MCP_APP_MIME_TYPE`. `_meta` follows the key rule below, without `ui`. A bad entry throws when the server is built, naming it; a provider that breaks a rule later is answered `-32603`.
|
|
1387
|
+
- **`content`** (a string or `Uint8Array`) is served by the server, which fills `size` and sets `_meta["dev.afd/digest"]` (`sha256:<hex>`). Bytes that are valid UTF-8 are sent as `text`, others as `blob`.
|
|
1388
|
+
- **An MCP Apps view** reads back with its own `_meta.ui` (`csp`, `permissions`, `domain`, `prefersBorder`): return `{ content, mimeType, _meta: { ui: { prefersBorder: true } } }` from `read`.
|
|
1389
|
+
- **Lists are fixed.** No cursor (a `cursor` is `-32602`), the same list for every connection, session and context. A modern-era result carries `ttlMs` (the `toolsListTtlMs` option, 300,000 by default, not lowered by `contexts`) and `cacheScope: "public"`.
|
|
1390
|
+
- **An unknown URI** is `-32602`, `Resource not found`, with `data: { uri }`, on both eras. A read runs no command, middleware, confirmation or journal entry, and `createContext` does not run for it.
|
|
1391
|
+
|
|
1392
|
+
### Skills
|
|
1393
|
+
|
|
1394
|
+
```typescript
|
|
1395
|
+
import { createMcpServer, SkillCatalog, skillFromDirectory } from '@lushly-dev/afd-server';
|
|
1396
|
+
|
|
1397
|
+
const skills = new SkillCatalog(
|
|
1398
|
+
[
|
|
1399
|
+
await skillFromDirectory('acme/lint-rules', './skills/lint-rules'),
|
|
1400
|
+
{ path: 'hello-greeting', files: { 'SKILL.md': skillMarkdown, 'references/STYLE.md': '# Style\n' } },
|
|
1401
|
+
],
|
|
1402
|
+
{ directoryRead: false }
|
|
1403
|
+
);
|
|
1404
|
+
createMcpServer({ name: 'notes', version: '1.0.0', commands, skills });
|
|
1405
|
+
```
|
|
1406
|
+
|
|
1407
|
+
A `SkillCatalog` is fixed when it is built: it reads each skill's bytes once, checks them and computes the digests. The constructor throws, naming the skill and the rule, when:
|
|
1408
|
+
|
|
1409
|
+
- a skill has no `SKILL.md`, or its frontmatter is not one YAML mapping (read with the YAML 1.2 core schema, so `2026-11-01` stays a string; no tags, anchors, aliases, repeated keys or more than 64 levels);
|
|
1410
|
+
- `name` is not 1 to 64 characters of `a-z`, `0-9` and `-` (no leading, trailing or doubled `-`), does not equal the path's last segment, or is used by another skill; `description` is empty or over 1,024 characters;
|
|
1411
|
+
- a file path is not relative and `/`-separated, or a skill has more than 512 files or 16 MiB.
|
|
1412
|
+
|
|
1413
|
+
The server declares the `io.modelcontextprotocol/skills` extension (and `resources`), answers `skills/list` and `skills/get`, and serves every skill file as a `skill://<path>/<file>` resource after the provider's entries, each with `size`, a MIME type by suffix and its `dev.afd/digest`. `directoryRead: true` also serves `resources/directory/read` for every skill directory and declares `directoryRead`. `skillFromDirectory` refuses a symbolic link that leaves the directory. Skills are untrusted content: the server serves bytes and never acts on them.
|
|
1414
|
+
|
|
1415
|
+
### Tool `_meta`
|
|
1416
|
+
|
|
1417
|
+
```typescript
|
|
1418
|
+
const notesList = defineCommand({
|
|
1419
|
+
name: 'notes-list',
|
|
1420
|
+
description: 'List notes',
|
|
1421
|
+
input: z.object({}),
|
|
1422
|
+
toolMeta: {
|
|
1423
|
+
ui: { resourceUri: 'ui://notes/list.html' }, // MCP Apps: the view of this tool
|
|
1424
|
+
'dev.umbel/origin': { plugin: 'notes' },
|
|
1425
|
+
},
|
|
1426
|
+
handler: async () => success({ notes: [] }),
|
|
1427
|
+
});
|
|
1428
|
+
```
|
|
1429
|
+
|
|
1430
|
+
`toolMeta` entries are emitted in the tool's `_meta` (individual strategy and hybrid first-class tools), in the command's entry of a grouped tool's `_meta.actions`, and by `afd-detail` as `toolMeta`; never on meta-tools. A key is allowed when it is a reverse-DNS prefixed key with two or more labels outside `dev.afd/` and the prefixes MCP reserves (`dev.umbel/origin`), or exactly `ui` (an object; a `resourceUri` must begin `ui://`). The server refuses any other key when it registers the command (`createMcpServer`, `createMcpHandler`), naming the command and the key, so an entry never replaces one the server sets. `defineCommand` and the in-process registry do not check, to keep `/direct` small.
|
|
1431
|
+
|
|
1432
|
+
### Advertised schema
|
|
1433
|
+
|
|
1434
|
+
`advertisedInputSchema` is the input schema every surface shows (tool `inputSchema`, grouped entries, `afd-detail`, `afd-schema`, `afd-docs`); `input` still validates every call. It must be a JSON object whose `type` is `"object"`, and nothing else in it is checked. Use it to re-serve a wrapped tool whose schema uses keywords the generated one cannot express. Keeping `input` no wider than the advertised schema is your job.
|
|
1435
|
+
|
|
974
1436
|
## Bootstrap Tools
|
|
975
1437
|
|
|
976
1438
|
Set `bootstrap: true` to register three onboarding tools, exposed over MCP like any other command:
|
|
@@ -1027,7 +1489,7 @@ Context state is per client:
|
|
|
1027
1489
|
- **2025 clients on `/mcp`** have no session, so they see no active context and `afd-context-enter` returns `SESSION_REQUIRED`, as on `/message` without a session.
|
|
1028
1490
|
- **HTTP `/message`** keeps one stack per session. `initialize` returns an `Mcp-Session-Id` header, and requests that repeat it share that session's stack; one client entering a context never changes another client's `tools/list` or execution. Requests without the header see no active context, and `afd-context-enter`/`afd-context-exit` return `SESSION_REQUIRED` for them. Sessions expire after `sessionIdleTimeoutMs` of inactivity, and at most `maxSessions` are kept.
|
|
1029
1491
|
- A stack holds at most 16 contexts (`CONTEXT_DEPTH_EXCEEDED` beyond that), and re-entering the active context is a no-op.
|
|
1030
|
-
- In-process `server.execute()` ignores contexts.
|
|
1492
|
+
- In-process `server.execute()` ignores contexts. `createDirectRegistry({ contexts })` scopes each call to its `activeContext` option instead (see the `/direct` entry above).
|
|
1031
1493
|
|
|
1032
1494
|
## Request Context
|
|
1033
1495
|
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @fileoverview The keyed digests, canonical JSON and nonce bookkeeping behind approval tokens and
|
|
3
3
|
* relayed approvals (`approval.ts`).
|
|
4
|
+
*
|
|
5
|
+
* Runs on WebCrypto (`globalThis.crypto`), which Node.js 22 and every current browser provide, so
|
|
6
|
+
* the approval middleware loads no Node.js built-in. Tokens are byte for byte what the
|
|
7
|
+
* `node:crypto` implementation issued: `spec/vectors/approval-tokens.json` checks it.
|
|
4
8
|
*/
|
|
5
9
|
import type { Actor } from '@lushly-dev/afd-core';
|
|
6
10
|
/** An HMAC key: a string (UTF-8) or raw bytes, at least 32 bytes long. */
|
|
@@ -20,12 +24,30 @@ export type ApprovalSecret = string | Uint8Array;
|
|
|
20
24
|
export declare function canonicalJson(value: unknown): string;
|
|
21
25
|
/** The actor fields a token is bound to. `label` is display text, so it is left out. */
|
|
22
26
|
export declare function actorJson(actor: Actor | undefined): string;
|
|
23
|
-
|
|
24
|
-
export
|
|
27
|
+
/** An HMAC-SHA256 key, imported once and reused for every token it signs or checks. */
|
|
28
|
+
export interface ApprovalKey {
|
|
29
|
+
readonly key: Promise<CryptoKey>;
|
|
30
|
+
}
|
|
31
|
+
export declare function toKeys(secret: ApprovalSecret | readonly ApprovalSecret[] | undefined): ApprovalKey[];
|
|
32
|
+
/** HMAC-SHA256 of the UTF-8 bytes of `data`. */
|
|
33
|
+
export declare function hmac(key: ApprovalKey, data: string): Promise<Uint8Array>;
|
|
25
34
|
/** A keyed digest; `purpose` keeps an input digest from ever matching an actor digest. */
|
|
26
|
-
export declare function digest(key:
|
|
35
|
+
export declare function digest(key: ApprovalKey, purpose: 'input' | 'actor', value: string): Promise<Uint8Array>;
|
|
27
36
|
/** Constant-time equality. Lengths are not secret (every digest here is 32 bytes). */
|
|
28
|
-
export declare function safeEqual(a:
|
|
37
|
+
export declare function safeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
38
|
+
/** Constant-time equality of two strings' UTF-8 bytes. */
|
|
39
|
+
export declare function safeEqualText(a: string, b: string): boolean;
|
|
40
|
+
/** `count` random bytes from the platform's cryptographic source. */
|
|
41
|
+
export declare function randomBytes(count: number): Uint8Array;
|
|
42
|
+
/** Unpadded base64url, as Node.js `Buffer.toString('base64url')` writes it. */
|
|
43
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
44
|
+
/** Unpadded base64url of a string's UTF-8 bytes. */
|
|
45
|
+
export declare function base64urlText(text: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Decode unpadded base64url to UTF-8 text, or `undefined` when it is not base64url. Invalid UTF-8
|
|
48
|
+
* becomes U+FFFD, as `Buffer.toString('utf8')` does.
|
|
49
|
+
*/
|
|
50
|
+
export declare function decodeBase64urlText(text: string): string | undefined;
|
|
29
51
|
/** In-memory single-use nonces, forgotten once their token has expired. */
|
|
30
52
|
export declare function createMemoryNonceStore(): {
|
|
31
53
|
consume(nonce: string, expiresAt: number, now: number): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approval-crypto.d.ts","sourceRoot":"","sources":["../src/approval-crypto.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"approval-crypto.d.ts","sourceRoot":"","sources":["../src/approval-crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAMlD,0EAA0E;AAC1E,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,CAAC;AAEjD;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAmDpD;AAED,wFAAwF;AACxF,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,SAAS,GAAG,MAAM,CAG1D;AAED,uFAAuF;AACvF,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;CACjC;AAED,wBAAgB,MAAM,CACrB,MAAM,EAAE,cAAc,GAAG,SAAS,cAAc,EAAE,GAAG,SAAS,GAC5D,WAAW,EAAE,CAuBf;AAED,gDAAgD;AAChD,wBAAsB,IAAI,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAG9E;AAED,0FAA0F;AAC1F,wBAAgB,MAAM,CACrB,GAAG,EAAE,WAAW,EAChB,OAAO,EAAE,OAAO,GAAG,OAAO,EAC1B,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,UAAU,CAAC,CAErB;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,OAAO,CAO/D;AAED,0DAA0D;AAC1D,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED,qEAAqE;AACrE,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAErD;AAKD,+EAA+E;AAC/E,wBAAgB,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAmBnD;AAED,oDAAoD;AACpD,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAiBpE;AAED,2EAA2E;AAC3E,wBAAgB,sBAAsB;IAGpC,OAAO,QAAQ,MAAM,aAAa,MAAM,OAAO,MAAM,GAAG,OAAO;EAShE"}
|