@lushly-dev/afd-server 2.4.0 → 2.5.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.
Files changed (206) hide show
  1. package/README.md +178 -48
  2. package/dist/app-call-registry.d.ts +31 -0
  3. package/dist/app-call-registry.d.ts.map +1 -0
  4. package/dist/app-call-registry.js +56 -0
  5. package/dist/app-call-registry.js.map +1 -0
  6. package/dist/approval-admission.d.ts +93 -0
  7. package/dist/approval-admission.d.ts.map +1 -0
  8. package/dist/approval-admission.js +165 -0
  9. package/dist/approval-admission.js.map +1 -0
  10. package/dist/approval-crypto.d.ts +22 -16
  11. package/dist/approval-crypto.d.ts.map +1 -1
  12. package/dist/approval-crypto.js +41 -66
  13. package/dist/approval-crypto.js.map +1 -1
  14. package/dist/approval-process-state.d.ts +20 -0
  15. package/dist/approval-process-state.d.ts.map +1 -0
  16. package/dist/approval-process-state.js +28 -0
  17. package/dist/approval-process-state.js.map +1 -0
  18. package/dist/approval-relay.d.ts +171 -8
  19. package/dist/approval-relay.d.ts.map +1 -1
  20. package/dist/approval-relay.js +42 -3
  21. package/dist/approval-relay.js.map +1 -1
  22. package/dist/approval-up-front.d.ts +40 -0
  23. package/dist/approval-up-front.d.ts.map +1 -0
  24. package/dist/approval-up-front.js +365 -0
  25. package/dist/approval-up-front.js.map +1 -0
  26. package/dist/approval.d.ts +17 -12
  27. package/dist/approval.d.ts.map +1 -1
  28. package/dist/approval.js +178 -41
  29. package/dist/approval.js.map +1 -1
  30. package/dist/approver.d.ts +84 -0
  31. package/dist/approver.d.ts.map +1 -0
  32. package/dist/approver.js +107 -0
  33. package/dist/approver.js.map +1 -0
  34. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  35. package/dist/bootstrap/afd-docs.js +4 -0
  36. package/dist/bootstrap/afd-docs.js.map +1 -1
  37. package/dist/bootstrap/afd-help.d.ts +2 -1
  38. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  39. package/dist/bootstrap/afd-help.js +17 -4
  40. package/dist/bootstrap/afd-help.js.map +1 -1
  41. package/dist/bootstrap/described-command.d.ts +2 -1
  42. package/dist/bootstrap/described-command.d.ts.map +1 -1
  43. package/dist/bootstrap/described-command.js.map +1 -1
  44. package/dist/command-timeout.d.ts +17 -0
  45. package/dist/command-timeout.d.ts.map +1 -0
  46. package/dist/command-timeout.js +92 -0
  47. package/dist/command-timeout.js.map +1 -0
  48. package/dist/context-fields.d.ts.map +1 -1
  49. package/dist/context-fields.js +9 -9
  50. package/dist/context-fields.js.map +1 -1
  51. package/dist/define-core.d.ts +27 -1
  52. package/dist/define-core.d.ts.map +1 -1
  53. package/dist/define-core.js +8 -1
  54. package/dist/define-core.js.map +1 -1
  55. package/dist/define.d.ts +3 -2
  56. package/dist/define.d.ts.map +1 -1
  57. package/dist/define.js +1 -1
  58. package/dist/define.js.map +1 -1
  59. package/dist/direct-registry.d.ts +27 -3
  60. package/dist/direct-registry.d.ts.map +1 -1
  61. package/dist/direct-registry.js +41 -6
  62. package/dist/direct-registry.js.map +1 -1
  63. package/dist/direct-tool-surface.d.ts +1 -1
  64. package/dist/direct-tool-surface.d.ts.map +1 -1
  65. package/dist/direct-tool-surface.js +14 -4
  66. package/dist/direct-tool-surface.js.map +1 -1
  67. package/dist/direct.d.ts +3 -1
  68. package/dist/direct.d.ts.map +1 -1
  69. package/dist/direct.js +2 -1
  70. package/dist/direct.js.map +1 -1
  71. package/dist/elicitation-state.d.ts +5 -1
  72. package/dist/elicitation-state.d.ts.map +1 -1
  73. package/dist/elicitation-state.js +4 -1
  74. package/dist/elicitation-state.js.map +1 -1
  75. package/dist/execution.d.ts +17 -0
  76. package/dist/execution.d.ts.map +1 -1
  77. package/dist/execution.js +78 -7
  78. package/dist/execution.js.map +1 -1
  79. package/dist/http-handler.d.ts +20 -2
  80. package/dist/http-handler.d.ts.map +1 -1
  81. package/dist/http-handler.js +139 -16
  82. package/dist/http-handler.js.map +1 -1
  83. package/dist/http-security.d.ts +14 -1
  84. package/dist/http-security.d.ts.map +1 -1
  85. package/dist/http-security.js +79 -17
  86. package/dist/http-security.js.map +1 -1
  87. package/dist/http-sessions.d.ts +35 -5
  88. package/dist/http-sessions.d.ts.map +1 -1
  89. package/dist/http-sessions.js +42 -10
  90. package/dist/http-sessions.js.map +1 -1
  91. package/dist/index.d.ts +13 -6
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +11 -4
  94. package/dist/index.js.map +1 -1
  95. package/dist/instance-state.d.ts +46 -0
  96. package/dist/instance-state.d.ts.map +1 -0
  97. package/dist/instance-state.js +91 -0
  98. package/dist/instance-state.js.map +1 -0
  99. package/dist/journal-replay.d.ts.map +1 -1
  100. package/dist/journal-replay.js +41 -3
  101. package/dist/journal-replay.js.map +1 -1
  102. package/dist/journal.d.ts +10 -1
  103. package/dist/journal.d.ts.map +1 -1
  104. package/dist/journal.js +95 -10
  105. package/dist/journal.js.map +1 -1
  106. package/dist/json-rpc.d.ts +3 -2
  107. package/dist/json-rpc.d.ts.map +1 -1
  108. package/dist/json-rpc.js +5 -3
  109. package/dist/json-rpc.js.map +1 -1
  110. package/dist/lazy-tools.d.ts +16 -1
  111. package/dist/lazy-tools.d.ts.map +1 -1
  112. package/dist/lazy-tools.js +13 -2
  113. package/dist/lazy-tools.js.map +1 -1
  114. package/dist/mcp-auth-bearer.d.ts +2 -0
  115. package/dist/mcp-auth-bearer.d.ts.map +1 -1
  116. package/dist/mcp-auth-bearer.js +1 -1
  117. package/dist/mcp-auth-bearer.js.map +1 -1
  118. package/dist/mcp-auth-dispatch.d.ts +38 -0
  119. package/dist/mcp-auth-dispatch.d.ts.map +1 -0
  120. package/dist/mcp-auth-dispatch.js +113 -0
  121. package/dist/mcp-auth-dispatch.js.map +1 -0
  122. package/dist/mcp-auth-jwt.d.ts +3 -2
  123. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  124. package/dist/mcp-auth-jwt.js.map +1 -1
  125. package/dist/mcp-auth-resource.d.ts +6 -2
  126. package/dist/mcp-auth-resource.d.ts.map +1 -1
  127. package/dist/mcp-auth-resource.js +6 -5
  128. package/dist/mcp-auth-resource.js.map +1 -1
  129. package/dist/mcp-auth-scopes.d.ts +84 -0
  130. package/dist/mcp-auth-scopes.d.ts.map +1 -0
  131. package/dist/mcp-auth-scopes.js +125 -0
  132. package/dist/mcp-auth-scopes.js.map +1 -0
  133. package/dist/mcp-auth-view.d.ts +50 -0
  134. package/dist/mcp-auth-view.d.ts.map +1 -0
  135. package/dist/mcp-auth-view.js +166 -0
  136. package/dist/mcp-auth-view.js.map +1 -0
  137. package/dist/mcp-auth.d.ts +79 -3
  138. package/dist/mcp-auth.d.ts.map +1 -1
  139. package/dist/mcp-auth.js +206 -20
  140. package/dist/mcp-auth.js.map +1 -1
  141. package/dist/mcp-modern.d.ts +12 -1
  142. package/dist/mcp-modern.d.ts.map +1 -1
  143. package/dist/mcp-modern.js +210 -29
  144. package/dist/mcp-modern.js.map +1 -1
  145. package/dist/meta-argument.d.ts +8 -8
  146. package/dist/meta-argument.d.ts.map +1 -1
  147. package/dist/meta-argument.js +17 -10
  148. package/dist/meta-argument.js.map +1 -1
  149. package/dist/meta-tools.js +1 -1
  150. package/dist/meta-tools.js.map +1 -1
  151. package/dist/middleware.d.ts.map +1 -1
  152. package/dist/middleware.js +16 -6
  153. package/dist/middleware.js.map +1 -1
  154. package/dist/output-budget.d.ts +77 -0
  155. package/dist/output-budget.d.ts.map +1 -0
  156. package/dist/output-budget.js +200 -0
  157. package/dist/output-budget.js.map +1 -0
  158. package/dist/resources.d.ts +35 -10
  159. package/dist/resources.d.ts.map +1 -1
  160. package/dist/resources.js +59 -18
  161. package/dist/resources.js.map +1 -1
  162. package/dist/scope-view.d.ts +59 -0
  163. package/dist/scope-view.d.ts.map +1 -0
  164. package/dist/scope-view.js +44 -0
  165. package/dist/scope-view.js.map +1 -0
  166. package/dist/server-types.d.ts +157 -25
  167. package/dist/server-types.d.ts.map +1 -1
  168. package/dist/server-types.js.map +1 -1
  169. package/dist/server.d.ts.map +1 -1
  170. package/dist/server.js +162 -20
  171. package/dist/server.js.map +1 -1
  172. package/dist/skills.d.ts.map +1 -1
  173. package/dist/skills.js +99 -3
  174. package/dist/skills.js.map +1 -1
  175. package/dist/task-dispatch.d.ts +34 -0
  176. package/dist/task-dispatch.d.ts.map +1 -0
  177. package/dist/task-dispatch.js +26 -0
  178. package/dist/task-dispatch.js.map +1 -0
  179. package/dist/tasks-runtime.d.ts +113 -0
  180. package/dist/tasks-runtime.d.ts.map +1 -0
  181. package/dist/tasks-runtime.js +687 -0
  182. package/dist/tasks-runtime.js.map +1 -0
  183. package/dist/tasks.d.ts +210 -0
  184. package/dist/tasks.d.ts.map +1 -0
  185. package/dist/tasks.js +289 -0
  186. package/dist/tasks.js.map +1 -0
  187. package/dist/tool-router.d.ts +4 -0
  188. package/dist/tool-router.d.ts.map +1 -1
  189. package/dist/tool-router.js +103 -26
  190. package/dist/tool-router.js.map +1 -1
  191. package/dist/tools.d.ts.map +1 -1
  192. package/dist/tools.js +11 -18
  193. package/dist/tools.js.map +1 -1
  194. package/dist/up-front-steps.d.ts +27 -0
  195. package/dist/up-front-steps.d.ts.map +1 -0
  196. package/dist/up-front-steps.js +110 -0
  197. package/dist/up-front-steps.js.map +1 -0
  198. package/dist/validation.d.ts +24 -3
  199. package/dist/validation.d.ts.map +1 -1
  200. package/dist/validation.js +56 -6
  201. package/dist/validation.js.map +1 -1
  202. package/dist/verified-credentials.d.ts +13 -5
  203. package/dist/verified-credentials.d.ts.map +1 -1
  204. package/dist/verified-credentials.js +43 -10
  205. package/dist/verified-credentials.js.map +1 -1
  206. package/package.json +7 -7
package/README.md CHANGED
@@ -260,7 +260,7 @@ imports from `/direct`. It exports everything `/define` does, plus:
260
260
  - `createDirectToolSurface`, the MCP tool surface for that registry (see
261
261
  below);
262
262
  - `createApprovalMiddleware`, on WebCrypto (see [Approvals](#approvals));
263
- - `createJournalMiddleware`, `replayJournal` and `MemoryJournalSink`;
263
+ - `createJournalMiddleware`, `JOURNAL_RESULT_UNSERIALIZABLE`, `replayJournal` and `MemoryJournalSink`;
264
264
  - the middleware with no Node.js builtin in its module graph:
265
265
  `composeMiddleware`, `defaultMiddleware`, `createLoggingMiddleware`,
266
266
  `createTimingMiddleware`, `createRetryMiddleware`, `createTracingMiddleware`,
@@ -408,11 +408,13 @@ permitted action is `COMMAND_NOT_ALLOWED`.
408
408
 
409
409
  `isVerifiedCredentials(value)` answers whether `value` is the `credentials`
410
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
411
+ a private `WeakMap` holding each object's admitted expiry deadline, so a copy,
412
+ an object built with the same fields, the `credentials` a direct-registry
413
+ caller passes, and those a host's `createContext` sets are never recognised.
414
+ Branded credentials are frozen, and stop being recognised once their admitted
415
+ deadline (`expiresAt` plus any admission clock skew, checked against `now` in
416
+ `isVerifiedCredentials(value, now?)`, defaulting to `Date.now()`) has passed or
417
+ their request has ended. No entry exports
416
418
  the functions that brand and unbrand: only the [`auth` option](#mcp-authorization)
417
419
  brands, the credentials of a request it verified. A nested call keeps the brand
418
420
  only if it is given the same object.
@@ -434,7 +436,7 @@ The entry loads nothing else of the server and is held browser-safe by
434
436
 
435
437
  With `auth`, `createMcpHandler` (and `createMcpServer` over HTTP) is an OAuth 2.1
436
438
  protected resource, as [`spec/authorization.md`](../../spec/authorization.md) M1
437
- to M5 and M7 specify:
439
+ to M7 specify:
438
440
 
439
441
  ```typescript
440
442
  import { createMcpHandler, JwtVerifier, jwksKeySource } from '@lushly-dev/afd-server';
@@ -491,21 +493,22 @@ const handler = createMcpHandler({
491
493
  an issuer `authorizationServers` does not name. `jwksKeySource` keeps the last
492
494
  good keys while loads fail, for at most `maxStaleMs` (default one hour), then
493
495
  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.
496
+ - **Whatever the verifier, the layer checks** `rules.clockSkewS` (when present,
497
+ a whole number from 0 to 300 seconds, or construction throws), the
498
+ credentials' shape, their certificate binding against this request's TLS
499
+ client certificate, the binding requirement, and `expiresAt` (within the
500
+ verifier's skew), refusing with M5's 401.
498
501
  - **HTTP sessions belong to their caller.** With `contexts`, a session that
499
502
  `initialize` creates on `/message` is bound to the credentials' issuer,
500
503
  subject and client; another caller presenting its `Mcp-Session-Id` is
501
- answered as for an unknown session.
504
+ answered as for an unknown session, and another caller's `initialize` never
505
+ evicts it (see [Sessions](#sessions-mcp-session-id)).
502
506
  - **Commands see `context.credentials`** (`issuer`, `subject`, `clientId`,
503
507
  `scopes`, `resource`, `expiresAt`, `issuedAt`, and `authTime`, `acr` and `cnf`
504
508
  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
+ request ends or its admitted expiry (`expiresAt` plus admission clock skew)
510
+ passes. Once that deadline passes, afd-auth's middleware fails closed with
511
+ `TOKEN_EXPIRED` without reading the session. Never the token: the layer removes the `Authorization` header
509
512
  before `createContext` runs, and the journal never records credentials.
510
513
  Without an `actor` from `createContext`, the actor is
511
514
  `{ kind: 'agent', id: <clientId>, onBehalfOf: <subject> }`.
@@ -513,8 +516,73 @@ const handler = createMcpHandler({
513
516
  `auth.onRefusal`, by default a `console.warn` line, with the issuer's alias;
514
517
  never the token or a claim. A host verifier may wrap `JwtVerifier` to refuse
515
518
  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.
519
+ - **Scopes (M6).** A command declares the scopes a caller's token needs with
520
+ `defineCommand({ scopes: ['todo:write'] })`, and `auth.requiredScopes` names
521
+ those every request needs; a call needs both, compared exactly. A missing
522
+ scope is one 403 before dispatch, with M5's challenge
523
+ (`Bearer error="insufficient_scope", scope="<missing>", resource_metadata=...`)
524
+ and body, naming every missing scope of every step once, in step order: for
525
+ a command's own tool, a grouped action, `afd-call`, each step of `afd-batch`
526
+ and `afd-pipe`, `/rpc`, `/batch` and `/stream`. A JSON-RPC batch is refused
527
+ with 400 first. A call decided after routing (`GET /stream`, say) fails with
528
+ `INSUFFICIENT_SCOPE` (`details.scopes`, not retryable) before any
529
+ confirmation, a batch or pipeline as a whole.
530
+ - **A resolver** (`auth.resolver`) decides every call instead of the static
531
+ rule: `resolve(command, input, credentials)` answers `'allowed'`,
532
+ `{ missing: [...] }` or `'defer'` (the registry answers), first on the
533
+ arguments as sent, then again at execution on the validated input, so a rule
534
+ keyed on an argument holds when a default or a pipeline step supplies it.
535
+ `visible` and, optionally, `known` decide the listings; both must be pure.
536
+ - **Listing** (`auth.filterToolsByScope: true`): `tools/list` (then
537
+ `cacheScope: "private"`), `afd-discover`, `afd-detail`, `afd-help` and
538
+ grouped actions show only what the caller may use, and no suggestion names
539
+ another command. With a resolver, a command its `known` rejects does not
540
+ exist for that caller at all: every route answers it exactly as a name that
541
+ does not exist, before validation, middleware or a confirmation.
542
+
543
+ #### A host's own layer
544
+
545
+ A gateway that authenticates its callers itself, instead of a bearer token,
546
+ vouches for each one with `handler.admit(req, credentials)`. **This is the host
547
+ vouching for a caller:** only a gateway that has itself authenticated the
548
+ caller may call it, never with anything the caller sent. The credentials are
549
+ checked as a verifier's are (shape, a numeric `expiresAt` not yet passed, the
550
+ certificate binding where required), frozen and branded while the handler
551
+ serves `req`; `admit` refuses a request that carries a bearer token, or was
552
+ admitted before. It exists only on the handler object, which the host holds.
553
+ The host then runs the bearer layer's own decision before dispatch, and passes
554
+ the body it read on to the handler:
555
+
556
+ ```typescript
557
+ const check = handler.preDispatchCheck({
558
+ challenge: new ScopeChallenge('Gateway', { realm: 'todo' }),
559
+ scopeSource: 'a new assertion from the gateway',
560
+ });
561
+
562
+ async function serve(req, res) {
563
+ const body = await readBody(req, check.maxBodyBytes + 1);
564
+ try {
565
+ handler.admit(req, await gatewayCredentials(req));
566
+ } catch {
567
+ // A bearer token beside the gateway's credentials, or credentials that fail the checks.
568
+ res.writeHead(400, { 'Content-Type': 'text/plain' });
569
+ res.end('One request has one source of credentials');
570
+ return;
571
+ }
572
+ const decided = check.decide(req, body);
573
+ if (!decided.proceed) {
574
+ res.writeHead(decided.status, decided.headers);
575
+ res.end(decided.body);
576
+ return;
577
+ }
578
+ await handler(req, res, body);
579
+ }
580
+ ```
581
+
582
+ `decide` answers exactly what the bearer layer would after admitting the same
583
+ credentials (a 403, a 400 for a JSON-RPC batch, a 413 over the cap), but for a
584
+ 403's challenge in the host's scheme and its suggestion. A request with
585
+ neither admitted credentials nor a valid bearer token still gets M5's 401.
518
586
 
519
587
  A server that also runs afd-auth's middleware passes `isVerifiedCredentials` to
520
588
  `createAuthMiddleware`, as [above](#verified-credentials-lushly-devafd-servercredentials).
@@ -664,8 +732,11 @@ createMcpServer({ name: 'todo', version: '1.0.0', commands: [clearTodos], confir
664
732
  `confirm: true` (on `afd-batch` and `afd-pipe`, `confirm: ['todo-clear']`; on the HTTP
665
733
  routes, the `Afd-Confirm: todo-clear` header). That acknowledgement comes from the agent, not
666
734
  the user. `confirmations: 'require-human'` refuses it and accepts only an elicitation.
667
- - **Several instances** behind one URL need the same `confirmationKey` (32 bytes or more), which
668
- signs the confirmation's `requestState`.
735
+ - **The `requestState` key is per process by default.** Without `confirmationKey` (a string or
736
+ bytes, 32 bytes or more, checked when the server is created), each process signs the
737
+ confirmation's `requestState` with its own random key, so the answer must reach the process
738
+ that asked. Several instances behind one URL need the same `confirmationKey`; see
739
+ [Several instances](#several-instances).
669
740
 
670
741
  `server.execute()` and DirectClient calls are never gated.
671
742
 
@@ -683,7 +754,7 @@ const server = createMcpServer({
683
754
  port: 3100, // Default: 3100
684
755
  host: 'localhost', // Default: localhost
685
756
  transport: 'http', // Default: 'auto' (see the pitfall above)
686
- cors: true, // Send CORS headers (default: follows devMode)
757
+ cors: true, // Send CORS headers for accepted origins (default: false)
687
758
  toolStrategy: 'grouped', // Default: 'grouped' (see "Tool Strategies")
688
759
  bootstrap: true, // Add afd-help, afd-docs, afd-schema (default: false)
689
760
  resources: provider, // MCP resources (see "Resources, Skills and Tool _meta")
@@ -695,6 +766,10 @@ const server = createMcpServer({
695
766
  // Middleware — zero-config observability
696
767
  middleware: defaultMiddleware(),
697
768
 
769
+ // Several processes behind one URL (see "Several instances")
770
+ instances: 'multiple',
771
+ confirmationKey: process.env.AFD_CONFIRMATION_KEY!, // shared by every instance
772
+
698
773
  // Callbacks
699
774
  onCommand(command, input, result) {
700
775
  console.log(`Executed ${command}:`, result.success);
@@ -705,6 +780,25 @@ const server = createMcpServer({
705
780
  });
706
781
  ```
707
782
 
783
+ ### Several instances
784
+
785
+ Two things are kept per process unless you share them:
786
+
787
+ | What | Default | Used when | Share it with |
788
+ |------|---------|-----------|---------------|
789
+ | The key that signs elicitation `requestState` | A random key per server or handler, so even two handlers in one process do not share it | `confirmations` is not `'off'`, or an approval middleware has `relay: 'mcp-elicitation'` | `confirmationKey` on every instance (32 bytes or more) |
790
+ | Spent single-use approval tokens | In memory, per `createApprovalMiddleware` | An approval middleware with the default `replay: 'single-use'` | `nonceStore` on every instance's approval middleware |
791
+
792
+ Behind one process the defaults are enough. Behind several (a load balancer, or several engines answering the same callers), a `requestState` signed by one process is unanswered on another, so the person is asked again, and a single-use token works once on each process. Say which you run with `instances`:
793
+
794
+ - **`instances: 'multiple'`**: creating the server throws unless each default in use is supplied, naming what is missing.
795
+ - **`instances: 'single'`**: one process serves every request; nothing is required or logged. A supplied `confirmationKey` is still checked (32 bytes or more).
796
+ - **Left out**: as `'single'`, but a server served over HTTP (`start()` on the HTTP transport, or `createMcpHandler`) logs one warning to stderr when it relies on either default, once per process however many servers and handlers it creates. stdio logs nothing.
797
+
798
+ The check sees approval middleware passed in `middleware` directly or inside `composeMiddleware`, made by any installed copy of this package from this version on (older copies do not mark theirs), but not one wrapped inside another middleware. A `taskStore` is shared separately.
799
+
800
+ The `instances` check is TypeScript only for now. The Python server (`create_server(confirmation_key=...)`, else a random key per server, and the approval middleware's `nonce_store`, else memory) and the Rust server (`McpServer::with_confirmations_key`, else a random key, and `ApprovalMiddlewareOptions::with_nonce_store`, else memory) have the same defaults: share them yourself behind several processes.
801
+
708
802
  ## Middleware
709
803
 
710
804
  ### Default Middleware (Recommended)
@@ -836,15 +930,13 @@ const todoDelete = defineCommand({
836
930
  },
837
931
  });
838
932
 
839
- const commands = [todoDelete];
840
933
  const server = createMcpServer({
841
934
  name: 'todo',
842
935
  version: '1.0.0',
843
- commands,
936
+ commands: [todoDelete],
844
937
  middleware: [
845
938
  createApprovalMiddleware({
846
939
  secret: process.env.AFD_APPROVAL_SECRET!, // required, at least 32 bytes, no default
847
- commands,
848
940
  summarize: (command, input) => `Delete todo ${(input as { id: string }).id} (permanent)`,
849
941
  }),
850
942
  ],
@@ -871,15 +963,17 @@ To resume, retry the same command with the same input and `context.approval` set
871
963
  - **The token is the approval.** It is an HMAC-SHA256 over the command name, a keyed digest of the validated input (canonical JSON: sorted keys, so key order and defaults do not matter), a keyed digest of the actor's `kind`, `id` and `onBehalfOf`, an expiry and a random nonce. Tampered, expired, other-command, other-input and other-actor tokens are rejected, using constant-time comparisons; the new result's `details.reason` says why (which also tells a token's holder that its signature is valid).
872
964
  - **Only trusted code sets `context.approval`**, after a human approved: a surface such as `createContext(req)` or the application, never tool arguments. Whoever holds a token can use it, and the `APPROVAL_REQUIRED` result goes to the caller. So `includeToken` defaults to `false` when `context.interface` is `'mcp'` (every MCP lane, and the HTTP routes of `createMcpHandler`), whose caller is the agent: deliver the token to the human through `onApprovalRequired`. Elsewhere it defaults to `true`; set it explicitly to override either default. A DirectClient/DirectRegistry or in-process CLI exchange always suppresses the token regardless of this option.
873
965
  - **Plain JSON input only.** A validated input holding a `Map`, `Set`, `RegExp`, typed array, class instance, `bigint` or non-finite number cannot be bound without ambiguity, so such a call fails before the handler instead of being held.
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`.
966
+ - **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, so by default a token works once per process: 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`. A server with `instances: 'multiple'` refuses single-use approval middleware without one ([Several instances](#several-instances)).
875
967
  - **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.
876
968
  - **Key rotation:** pass `secret: [newKey, oldKey]`; the first signs, any verifies.
877
969
  - **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
970
  - **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.
879
971
  - **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'`).
880
- - **Gates only the listed commands.** Pass the same `commands` as the server or registry: a command missing from the list is never held.
972
+ - **A declared policy always holds.** The middleware decides from the policy and `confirmPrompt` of the command each call runs, and from the policy its `commands` option lists for that command: a call is held when either holds it. Without an approval middleware, `createMcpServer` and `createDirectRegistry` refuse a command whose policy is not `'not-required'` with `APPROVAL_UNAVAILABLE` before its handler runs (a policy function is not evaluated: declaring one needs the middleware). Each batch item, pipeline step and command run from another command's handler is checked on its own. The `commands` option is optional; outside those two, where no engine names the command, only it decides, and a command missing from it is not held.
973
+ - **One approval runs one handler, on the approved input.** The middleware admits the command and the canonical input it decided on (the input it verified the token against, computed before any await), and the engine takes that admission as it dispatches: a second dispatch on the same context, another command or an input changed after the approval answers `APPROVAL_UNAVAILABLE`. This holds whether the gating policy is the command's own or given only in the `commands` option. A call that needs approval on a validated input with no canonical form (a `bigint`, a `Set`, a class instance from a transform) gets `APPROVAL_UNAVAILABLE` with `details.reason: 'input-not-canonical'` from the middleware, without asking anyone; one its policy lets through runs, compared by identity at dispatch (a change inside the same object is not seen). An input that changes while the middleware decides (in a policy function) is refused the same way, and nobody is asked. Install one approval middleware per engine: a second one that does not gate a command leaves the first one's admission to decide, and a retry between two that both admit a call is refused, since each must admit it again; but two that both gate a command's own policy each ask. So put `createRetryMiddleware` before (outside) the approval middleware, where each attempt is decided again, never after it, where a retry is refused; and never change `input` in middleware after the approval.
974
+ - **Admission is not a boundary against code in the same process or page.** The records live on `globalThis`, shared by installed copies of this package, and any code running beside it could reach them; the gate stops the model, as the secret does in a page.
881
975
  - **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`.
882
- - **Batches and pipelines** pass one `context.approval` to every step. Retrying a pipeline reruns its ungated steps, and a gated step whose input comes from an earlier step may never match its token, so approve such steps as separate calls.
976
+ - **Batches and pipelines** pass one `context.approval` to every step. Retrying a pipeline reruns its ungated steps, and a gated step whose input comes from an earlier step may never match its token, so approve such steps as separate calls. Over MCP with `relay: 'mcp-elicitation'`, a batch or pipeline is approved up front instead (below).
883
977
  - `afd validate` warns (`MISSING_APPROVAL_POLICY`) about `mutation` or `destructive` commands that declare no policy. Declare `approval: 'not-required'` to say a command was considered and needs none.
884
978
 
885
979
  #### Asking the human over MCP
@@ -887,7 +981,7 @@ To resume, retry the same command with the same input and `context.approval` set
887
981
  Over MCP the caller is the agent, so the human has to be reached some other way. With `relay: 'mcp-elicitation'`, the middleware asks the human behind the MCP client, through a form elicitation, instead of returning a token:
888
982
 
889
983
  ```typescript
890
- createApprovalMiddleware({ secret, commands, relay: 'mcp-elicitation' });
984
+ createApprovalMiddleware({ secret, relay: 'mcp-elicitation' });
891
985
  ```
892
986
 
893
987
  A call to one gated command (its own tool, `afd-call` or a grouped tool) from a client that declares form elicitation gets an `input_required` result on `/mcp` (MCP 2026-07-28), or a server-sent `elicitation/create` on a 2025-era stdio connection. The form shows the approval summary, the command name and its validated input, and one required `approve` checkbox. The client asks its user and retries, and the command runs once:
@@ -903,12 +997,34 @@ No approval token is issued on this path, so the model never sees one. A stale,
903
997
  Calls that cannot elicit fail with `APPROVAL_REQUIRED` and no token, as without the relay:
904
998
 
905
999
  - the client declares no form elicitation;
906
- - a 2025-era HTTP request, or the legacy `/message` lane, which have no back channel;
907
- - an `afd-batch` or `afd-pipe` step. Asking mid-run would rerun the earlier steps on the retry, so call the gated command on its own.
1000
+ - a 2025-era HTTP request, or the legacy `/message` lane, which have no back channel.
1001
+
1002
+ An `afd-batch` or `afd-pipe` from a client that can elicit is approved up front, as a whole, before any step runs (#459): asking mid-run would rerun the earlier steps on the retry. One form lists every gated step's summary, command and validated input (a pipeline's `$input` references resolved), at most 20 of them, and on acceptance each gated step runs once on its own approval, bound to the whole request as sent and to its command, input and actor: an approval covers that exact batch or pipeline, never another call. Every nonce is spent before the first step runs, so a replayed retry runs nothing. A step whose command has an approval policy runs on the input validated up front, and the retry reads each gated step's approved input back from the `requestState`, so a schema whose default is random or reads the clock (`.default(() => randomUUID())`) runs the input the human was shown (#1414). The step is still validated as sent when it runs, so a schema that checks state an earlier step changed fails it with `VALIDATION_ERROR`. The `requestState` is signed, not encrypted: the client can read the kept input, schema defaults and transforms included, so a gated command's schema must not compute a secret. A decline runs nothing (`reason: 'declined'`). A pipeline whose gated step takes its input from an earlier step (`$prev`, `$first`, `$steps`) cannot be shown to the human first, so it runs nothing and fails with `APPROVAL_REQUIRED`, `details.reason: 'input-not-known'` and the step's index and command: split it there and call that command on its own.
908
1003
 
909
1004
  Only the command the tool call routes to can use the relay, once: a command that a handler runs cannot elicit. An accepted approval that has expired or was already used is asked again, and the question says so. `onApprovalRequired` is not called on the relay path, since no token exists.
910
1005
 
911
- The relay trusts the MCP client application to put the question to a person. The server cannot tell a human's click from client code that accepts on its own, so the relay is off by default. Leave it off where the agent's own code is the MCP client, for example an `McpClient` whose `onElicitation` answers automatically. Servers with several instances must share `confirmationKey` and `nonceStore`.
1006
+ #### An approver client
1007
+
1008
+ A trusted MCP client that shows a person the held action itself, such as an application shell that mounts this server, can carry the person's decision back (`spec/command-metadata.md`, "Approval evidence from an approver client"). Name it with `approver`, a predicate over the call's context after `createContext`:
1009
+
1010
+ ```typescript
1011
+ createMcpServer({
1012
+ name: 'mail',
1013
+ version: '1.0.0',
1014
+ commands,
1015
+ createContext: (_req, { credentials }) => ({ credentials }),
1016
+ approver: (context) => context.credentials?.clientId === 'loam-shell',
1017
+ middleware: [createApprovalMiddleware({ secret })],
1018
+ });
1019
+ ```
1020
+
1021
+ - **An approver gets the token:** its `APPROVAL_REQUIRED` results carry `details.approvalToken` whatever `includeToken` says, and the relay never answers it with a form.
1022
+ - **It retries one command on MCP 2026-07-28** with the token in `_meta["dev.afd/approval"]` (`AFD_APPROVAL_META_KEY`) and the same input. On `afd-batch`, `afd-pipe` or a 2025-era request the key fails the call with `APPROVAL_REQUIRED` before anything runs.
1023
+ - **Its tokens bind its principal binding** (the actor and the credentials' issuer, subject and client), so another client, even of the same person, gets `credentials-mismatch`.
1024
+ - **Anyone else's key is ignored,** and the key in tool arguments (or the HTTP routes' input) is refused with `VALIDATION_ERROR`, from every caller.
1025
+ - **The approver promises** never to give the token to an agent or a model, and to present it only on a retry a person approved after seeing the action, shown by `approvalDisplay` from `@lushly-dev/afd-core`, which refuses input too large, too deep or hiding characters.
1026
+
1027
+ The relay trusts the MCP client application to put the question to a person. The server cannot tell a human's click from client code that accepts on its own, so the relay is off by default. Leave it off where the agent's own code is the MCP client, for example an `McpClient` whose `onElicitation` answers automatically. The relay's `requestState` is signed with the server's `confirmationKey`, a random key per process when it is not set, and its nonces are spent in the middleware's `nonceStore`, in memory per process by default: servers with several instances must share both and set `instances: 'multiple'` ([Several instances](#several-instances)).
912
1028
 
913
1029
  `spec/command-metadata.md` ("Approvals") is the cross-language contract.
914
1030
 
@@ -940,9 +1056,9 @@ await server.execute('project-summary', {}, { scope: { project: 'p-1' } });
940
1056
 
941
1057
  ### Command Journal and Replay
942
1058
 
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.
1059
+ `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`. When a result cannot be copied as JSON (a throwing getter, circular reference or `bigint`), the error goes to `onError`, the live return value is unchanged, and the entry records a `JOURNAL_RESULT_UNSERIALIZABLE` failure instead of dropping the call. 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.
944
1060
 
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).
1061
+ `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`. For an entry recorded with `JOURNAL_RESULT_UNSERIALIZABLE`, replay still runs the command and adds a note that the original result was not captured: an unserializable replayed result reports `error`, a serializable one reports `different`, and a recorded-answer target returning the entry verbatim reports `same` with the note. 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. A journal entry does not show that a call was approved: with `recordFailures: true` the journal also keeps calls that never ran, such as an `APPROVAL_REQUIRED` hold, and `replayJournal` executes every entry it is given before comparing, failed ones included. So replay gated commands against a target with the approval middleware, which holds them again, or pass only the entries whose recorded result succeeded (`entries.filter((entry) => entry.result.success)`) to a target that serves those commands with `approval: 'not-required'`. A target without either refuses them with `APPROVAL_UNAVAILABLE`. The format is specified in [`spec/journal.md`](../../spec/journal.md).
946
1062
 
947
1063
  ```typescript
948
1064
  import { readFileSync } from 'node:fs';
@@ -1075,7 +1191,7 @@ Create a command definition with Zod schema.
1075
1191
  | `errors` | string[] | No | Possible error codes |
1076
1192
  | `expose` | ExposeOptions | No | Surfaces the command is exposed to; `{ mcp: true }` is required for MCP tools |
1077
1193
  | `examples` | `{ title, input }[]` | No | Example inputs, validated against `input` at define time |
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) |
1194
+ | `approval` | `'required'` \| `'not-required'` \| `(input, context) => …` | No | Whether a call needs human approval before the handler runs (default `'not-required'`); enforced by [`createApprovalMiddleware`](#approvals), and refused with `APPROVAL_UNAVAILABLE` when no approval middleware admits the call |
1079
1195
  | `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
1196
  | `advertisedInputSchema` | JSON Schema object | No | The input schema shown on every surface in place of the one generated from `input`, which still validates |
1081
1197
 
@@ -1096,15 +1212,16 @@ Create an MCP server from commands.
1096
1212
  | `groupByFn` | `(command) => string \| undefined` | No | Group name for the grouped strategy (default: `category`, else the first name segment) |
1097
1213
  | `contexts` | `{ name, description }[]` | No | Context scopes for dynamic tool filtering |
1098
1214
  | `bootstrap` | boolean | No | Register the `afd-help`, `afd-docs` and `afd-schema` MCP tools (default: `false`) |
1099
- | `devMode` | boolean | No | Enable development mode (default: false) |
1100
- | `cors` | boolean | No | Enable CORS for HTTP transport (default: follows devMode) |
1101
- | `allowedOrigins` | string[] | No | Additional exact browser origins |
1215
+ | `devMode` | boolean | No | Exception details in error responses; changes no Origin or CORS check (default: false) |
1216
+ | `cors` | boolean | No | Send CORS headers for accepted origins (default: false) |
1217
+ | `allowedOrigins` | string[] | No | Additional exact browser origins, such as `http://localhost:5173` (refused otherwise, in `devMode` too) |
1102
1218
  | `allowedHosts` | string[] | No | Accepted HTTP hostnames, without ports |
1103
1219
  | `maxBodyBytes` | number | No | Maximum JSON body bytes (default: 1048576) |
1104
1220
  | `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 |
1221
+ | `auth` | `McpAuthOptions` | No | [MCP authorization](#mcp-authorization): every HTTP route needs a verified bearer token, and `scopes`, `requiredScopes`, a `resolver` and `filterToolsByScope` decide each call |
1106
1222
  | `maxSseConnections` | number | No | Concurrent `/sse` connections before HTTP 503 (default: 100) |
1107
- | `maxSessions` | number | No | Live HTTP sessions when `contexts` are set; the least recently used is evicted (default: 1000) |
1223
+ | `maxSessions` | number | No | Live HTTP sessions when `contexts` are set; at the cap the owner's own least recently used session is evicted, or `initialize` gets 503 (default: 1000) |
1224
+ | `maxSessionsPerOwner` | number | No | With `auth`, live HTTP sessions one issuer and subject may hold across its clients; at it, its own least recently used session is evicted (default: 100, never above `maxSessions`; checked but without effect when there are no `contexts`; throws without `auth`) |
1108
1225
  | `sessionIdleTimeoutMs` | number | No | Idle time before an HTTP session expires (default: 1800000, 30 minutes) |
1109
1226
  | `clock` | `Clock` | No | `context.clock` for every command, and the clock for HTTP session expiry (default: `systemClock`) |
1110
1227
  | `random` | `RandomSource` | No | `context.random` for every command (default: `systemRandom`) |
@@ -1113,6 +1230,9 @@ Create an MCP server from commands.
1113
1230
  | `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
1231
  | `resources` | `ResourceProvider \| ResourceEntry[]` | No | MCP resources served on `/mcp` and stdio; declares the `resources` capability |
1115
1232
  | `skills` | `SkillCatalog` | No | Agent Skills served through `skills/list`, `skills/get` and as `skill://` resources; declares `io.modelcontextprotocol/skills` |
1233
+ | `confirmations` | `'off' \| 'enforce' \| 'require-human'` | No | Enforce `confirmPrompt` on the MCP and HTTP surfaces (default: `'off'`) |
1234
+ | `confirmationKey` | `string \| Uint8Array` | No | Key (32 bytes or more) that signs elicitation `requestState` (default: a random key per process) |
1235
+ | `instances` | `'single' \| 'multiple'` | No | `'multiple'` refuses per-process defaults in use; left out, HTTP logs one warning when it relies on one ([Several instances](#several-instances)) |
1116
1236
  | `middleware` | array | No | Middleware functions |
1117
1237
  | `onCommand` | function | No | Command execution callback |
1118
1238
  | `onError` | function | No | Error callback |
@@ -1179,6 +1299,7 @@ The `/sse` and `/message` routes below are the deprecated 2024-11-05 transport.
1179
1299
  | `-32603` | Internal error (for example a throwing `createContext`); details only in `devMode` | 200 |
1180
1300
  | `-32000` | Transport rejection: Host, Origin, Content-Type or body size | 400, 403, 413 or 415 |
1181
1301
  | `-32001` | Unknown or expired `Mcp-Session-Id` | 404 |
1302
+ | `-32000` with `data.code: "SESSION_LIMIT_REACHED"` | `initialize` refused: the session store is full and the caller holds no session; retry after `Retry-After` (also `data.retryAfter`, in seconds) | 503 |
1182
1303
 
1183
1304
  Command failures are not protocol errors: they stay AFD `CommandResult` failures inside `result`. `/batch` and `/stream` are not JSON-RPC and answer errors with `{ success: false, error: { code, message, suggestion } }`.
1184
1305
 
@@ -1192,6 +1313,13 @@ Batch (`/batch`, `afd-batch`) and stream execution use the core `executeBatch()`
1192
1313
 
1193
1314
  Sessions exist only on the deprecated `/message` lane; `/mcp` never issues one. When `contexts` are configured, `initialize` on `/message` returns an `Mcp-Session-Id` response header. Repeat it on later `/message`, `/rpc`, `/batch` and `/stream` requests to use that session's context stack. Requests without the header are stateless. An unknown or expired session ID is answered with HTTP 404; start a new session with `initialize`. `@lushly-dev/afd-client` does this automatically. Without `contexts`, no session is issued and the header is ignored.
1194
1315
 
1316
+ A session belongs to the owner that created it. Only that owner can use it, and only its subject can displace it:
1317
+
1318
+ - **Owner.** With `auth`, the owner is the verified credentials' issuer, subject and client. Another principal presenting the session's ID is answered as for an unknown session. Without `auth` the transport carries no identity, so every caller is one owner and the unguessable session ID (a random UUID) is the only binding: anyone holding it can use the session.
1319
+ - **Ending a session.** There is no explicit close (`DELETE` is not served). A session ends when it is idle for `sessionIdleTimeoutMs`, when an `initialize` of the same subject (issuer and subject, any client) displaces it at the quota or the cap, or when the server stops.
1320
+ - **The quota.** With `auth`, one issuer and subject holds at most `maxSessionsPerOwner` live sessions (default 100, never more than `maxSessions`), counted across all its client IDs. At the quota, its `initialize` evicts its own least recently used session, so one subject cannot fill the store. Up to `maxSessions / maxSessionsPerOwner` distinct subjects (10 with the defaults) can still fill it between them; a new subject is then refused until sessions expire, so size the two for the subjects you expect. Without `contexts` no session is issued and the quota has no effect.
1321
+ - **The cap.** At `maxSessions` live sessions, `initialize` evicts the least recently used session of the same subject. Only when the store is full and the subject holds no session is it refused: HTTP 503 with a `Retry-After` header, and a JSON-RPC error `-32000` carrying the request's `id` and `data: { code: "SESSION_LIMIT_REACHED", suggestion, retryAfter }`, whose suggestion is to retry after that delay or reuse a session. (`-32002` is not used: MCP reserves it as the deprecated `SERVER_NOT_INITIALIZED`.) `@lushly-dev/afd-client`'s `connect()` and calls report it as the retryable `SESSION_LIMIT_REACHED`. Another subject's session is never evicted. Without `auth`, every caller is one owner whose quota is `maxSessions`, so the least recently used session overall is evicted, as before.
1322
+
1195
1323
  ### SSE Connections
1196
1324
 
1197
1325
  `/sse` accepts at most `maxSseConnections` concurrent connections (default: 100); more receive HTTP 503 with `Retry-After`. Open connections get a `: ping` comment every 25 seconds so proxies keep them open and dead peers are detected. Closed connections are removed immediately, and `dispose()`/`stop()` closes the rest.
@@ -1238,7 +1366,7 @@ console.log(result.data.greeting); // "Hello, World!"
1238
1366
 
1239
1367
  ### CORS Configuration
1240
1368
 
1241
- HTTP requests validate Host and browser Origin before dispatch. The default Host allowlist contains the configured host and loopback names. Requests without an Origin (such as CLI clients) and same-origin browser requests are accepted. Cross-site browser requests are rejected unless their exact Origin is listed in `allowedOrigins`. `cors: true` adds response headers for accepted origins; it does not disable request validation. `devMode: true` intentionally permits any browser origin, while Host checks remain enabled.
1369
+ HTTP requests validate Host and browser Origin before dispatch. The default Host allowlist contains the configured host and loopback names. Same-origin browser requests are accepted, and so are requests without an Origin (such as CLI clients) unless their Fetch Metadata says otherwise: one without an Origin whose `Sec-Fetch-Site` is `cross-site` or `same-site` gets 403. Cross-site browser requests are rejected unless their exact Origin is listed in `allowedOrigins`. Each `allowedOrigins` entry must be a serialized http(s) origin, `scheme://host[:port]` with no path or trailing slash; `*`, `null` or anything else throws when the server is built. `cors: true` (off by default) adds response headers for accepted origins, echoing the request's origin and never `*`; it does not disable request validation. `devMode` changes neither: it only adds exception details to errors, so a page a developer visits cannot reach a dev server. To call a local server from a browser app on another port, list that origin, for example `allowedOrigins: ['http://localhost:5173']`, with `cors: true`.
1242
1370
 
1243
1371
  All POST endpoints require `Content-Type: application/json`. Request bodies, and the `input` query parameter of `GET /stream`, are limited to 1 MiB (UTF-8 bytes) by default; set `maxBodyBytes` to change the limit. Larger input is refused with HTTP 413 whatever header size limit the host sets. Configure `allowedHosts` and `allowedOrigins` explicitly when embedding behind a proxy. Forwarded headers are not trusted automatically.
1244
1372
 
@@ -1262,14 +1390,14 @@ const server = createMcpServer({
1262
1390
 
1263
1391
  ## Tool Strategies
1264
1392
 
1265
- `toolStrategy` controls how MCP-exposed commands appear in `tools/list`. `afd-call`, `afd-batch` and `afd-pipe` are listed in every strategy.
1393
+ `toolStrategy` controls how MCP-exposed commands appear in `tools/list`. Every strategy lists the five meta-tools first, in this order: `afd-discover`, `afd-detail`, `afd-call`, `afd-batch`, `afd-pipe` ([`spec/tool-strategies.md`](../../spec/tool-strategies.md#tool-lists), #533). Then:
1266
1394
 
1267
- | Strategy | Tools listed |
1395
+ | Strategy | Tools listed after the meta-tools |
1268
1396
  |----------|--------------|
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)` |
1397
+ | `grouped` (default) | One tool per group. A group is the command's `category`, else the first name segment (`todo-create` → `todo`), or `groupByFn(command)` |
1270
1398
  | `individual` | One tool per command, with its full input schema and `_meta` |
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) |
1399
+ | `lazy` | The context tools when `contexts` are set, and nothing else |
1400
+ | `hybrid` | The context tools when `contexts` are set, then the commands in `firstClassTools` (at most 8) as individual tools. See [Hybrid Strategy](#hybrid-strategy) |
1273
1401
 
1274
1402
  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`:
1275
1403
 
@@ -1305,7 +1433,7 @@ When a group's per-action schemas are small (at most 8,192 characters of JSON, a
1305
1433
 
1306
1434
  ## Lazy Strategy
1307
1435
 
1308
- For servers with many commands, the `lazy` strategy exposes 5 meta-tools instead of listing all commands:
1436
+ For servers with many commands, the `lazy` strategy lists the 5 meta-tools (and the context tools) instead of the commands:
1309
1437
 
1310
1438
  ```typescript
1311
1439
  const server = createMcpServer({
@@ -1381,12 +1509,12 @@ const server = createMcpServer({
1381
1509
  });
1382
1510
  ```
1383
1511
 
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`.
1512
+ `resources` takes a provider (`list(caller?)`, optional `read(uri, caller?)`) 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
1513
 
1386
1514
  - **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
1515
  - **`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
1516
  - **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"`.
1517
+ - **Per-caller filtering and caching.** No cursor (a `cursor` is `-32602`), and lists never vary by connection, session or context. Under MCP authorization (`auth`), `list(caller)` and `read(uri, caller)` receive a frozen `ResourceCaller` carrying verified `credentials` (on HTTP; `undefined` on unauthenticated servers and over stdio) so a provider may filter listings and return `undefined` for unreadable URIs (answering `-32602`, identical to an absent URI). A modern-era result carries `ttlMs` (the `toolsListTtlMs` option, 300,000 by default, not lowered by `contexts`) and `cacheScope: "private"` on `resources/list` and provider-backed `resources/read` whenever a `ResourceProvider` is attached on an authorized server or a request carries verified credentials; static `SkillCatalog` reads, `resources/templates/list`, `skills/*`, and unauthenticated or skills-only servers carry `cacheScope: "public"`.
1390
1518
  - **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
1519
 
1392
1520
  ### Skills
@@ -1513,6 +1641,8 @@ const server = createMcpServer({
1513
1641
 
1514
1642
  - The server sets `traceId`, `signal` and `interface` (`'mcp'`) itself; `createContext` cannot override them.
1515
1643
  - `context.signal` aborts when the client disconnects before the response is finished, on every route, not only streams. Long-running handlers should honor it.
1644
+ - A positive finite `context.timeout` (milliseconds, for example from `createContext`) bounds each command's middleware and handler execution. The deadline aborts its signal and returns `TIMEOUT` with a recovery suggestion, even if the handler ignores cancellation. Each batch item and pipeline step gets its own deadline; batch/pipeline options still bound the whole operation. Nonpositive or nonfinite values disable this command deadline. A timed-out mutation may still complete if it already started: check its effect before retrying. Work waiting in middleware cannot start its handler after cancellation or timeout.
1645
+ - This deadline boundary belongs to `createMcpServer` and `createMcpHandler`, including `server.execute()`. In-process hosts using `createDirectRegistry` get per-call deadlines through DirectClient; `/direct` alone includes no server deadline machinery.
1516
1646
  - A throw from `createContext` is reported to `onError` and answered as an internal error (`-32603` on JSON-RPC routes, HTTP 500 elsewhere).
1517
1647
  - Pipeline `$input` does not expose these values, so a pipeline cannot copy them into step inputs.
1518
1648
  - stdio has no HTTP request, so `createContext` is not called there.
@@ -0,0 +1,31 @@
1
+ import { type CallGrant } from '@lushly-dev/afd-core/internal/app-calls';
2
+ import { type DirectCommandRegistry, type DirectRegistryOptions } from './direct-registry.js';
3
+ import type { ZodCommandDefinition } from './schema.js';
4
+ /** Options for {@link createAppCallRegistry}: `createDirectRegistry`'s, less `interface` and `tools`. */
5
+ export interface AppCallRegistryOptions extends Omit<DirectRegistryOptions, 'interface' | 'tools'> {
6
+ /**
7
+ * The host's grant check: whether the caller in `context` holds a grant naming `command`. AFD
8
+ * does not define a grant or who the caller is; read the host's own declared context field, such
9
+ * as Loam's `caller`. It runs before the context fields are validated, so check the type of what
10
+ * it reads. Only an explicit `true` grants; anything else, or a throw, refuses.
11
+ */
12
+ callGrant: CallGrant;
13
+ }
14
+ /**
15
+ * Create the registry a host runs an app's calls through, with the `apps` interface.
16
+ *
17
+ * A call runs only when the command sets `expose.apps` and `callGrant` returns `true`; it then runs
18
+ * as in `createDirectRegistry`, with `apps` as its interface, so middleware and the journal see it.
19
+ * Anything else (a missing command, one not exposed to apps, one the caller is not granted, any of
20
+ * them with invalid input) returns one fixed `CALL_NOT_GRANTED` before lookup, the `allow` option,
21
+ * the active context, validation and middleware, so an app learns nothing about commands it may not
22
+ * call. It serves no tool surface (an app calls commands one by one), and `hasCommand` answers
23
+ * `true` for every name, since `execute` answers every name. `DirectClient` and `DirectTransport`
24
+ * refuse to wrap it: their `allow`, middleware and tool listing would answer before the check. Its
25
+ * listings hold the commands exposed to apps, whatever any caller is granted: build what an app
26
+ * may see from your grants, never from them.
27
+ *
28
+ * @throws TypeError without `callGrant`; otherwise as `createDirectRegistry`
29
+ */
30
+ export declare function createAppCallRegistry(commands: ZodCommandDefinition[], options: AppCallRegistryOptions): DirectCommandRegistry;
31
+ //# sourceMappingURL=app-call-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app-call-registry.d.ts","sourceRoot":"","sources":["../src/app-call-registry.ts"],"names":[],"mappings":"AAOA,OAAO,EAEN,KAAK,SAAS,EAEd,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAExD,yGAAyG;AACzG,MAAM,WAAW,sBAAuB,SAAQ,IAAI,CAAC,qBAAqB,EAAE,WAAW,GAAG,OAAO,CAAC;IACjG;;;;;OAKG;IACH,SAAS,EAAE,SAAS,CAAC;CACrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,oBAAoB,EAAE,EAChC,OAAO,EAAE,sBAAsB,GAC7B,qBAAqB,CA+BvB"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The in-process registry for app-to-app calls (`spec/command-metadata.md`, "App-to-app calls").
3
+ *
4
+ * Its own module, so a host that never serves app calls bundles none of it: `createDirectRegistry`
5
+ * only refuses the `apps` interface.
6
+ */
7
+ import { failure } from '@lushly-dev/afd-core';
8
+ import { appCallGranted, callNotGranted, } from '@lushly-dev/afd-core/internal/app-calls';
9
+ import { APP_CALLS, createDirectRegistry, } from './direct-registry.js';
10
+ /**
11
+ * Create the registry a host runs an app's calls through, with the `apps` interface.
12
+ *
13
+ * A call runs only when the command sets `expose.apps` and `callGrant` returns `true`; it then runs
14
+ * as in `createDirectRegistry`, with `apps` as its interface, so middleware and the journal see it.
15
+ * Anything else (a missing command, one not exposed to apps, one the caller is not granted, any of
16
+ * them with invalid input) returns one fixed `CALL_NOT_GRANTED` before lookup, the `allow` option,
17
+ * the active context, validation and middleware, so an app learns nothing about commands it may not
18
+ * call. It serves no tool surface (an app calls commands one by one), and `hasCommand` answers
19
+ * `true` for every name, since `execute` answers every name. `DirectClient` and `DirectTransport`
20
+ * refuse to wrap it: their `allow`, middleware and tool listing would answer before the check. Its
21
+ * listings hold the commands exposed to apps, whatever any caller is granted: build what an app
22
+ * may see from your grants, never from them.
23
+ *
24
+ * @throws TypeError without `callGrant`; otherwise as `createDirectRegistry`
25
+ */
26
+ export function createAppCallRegistry(commands, options) {
27
+ const { callGrant, ...rest } = options;
28
+ if (typeof callGrant !== 'function') {
29
+ throw new TypeError("createAppCallRegistry needs callGrant, the host's check of the caller's grants");
30
+ }
31
+ // Neither `interface` nor `tools` reaches it, even from a caller outside the type checker.
32
+ const { interface: _interface, tools: _tools, ...direct } = rest;
33
+ const registry = createDirectRegistry(commands, {
34
+ ...direct,
35
+ interface: 'apps',
36
+ [APP_CALLS]: true,
37
+ });
38
+ const byName = new Map(commands.map((command) => [command.name, command]));
39
+ return {
40
+ interface: registry.interface,
41
+ contextFields: registry.contextFields,
42
+ async execute(name, input, context = {}, callOptions) {
43
+ // The grant check sees the interface the call runs with, as in the core registry.
44
+ const appContext = { ...context, interface: 'apps' };
45
+ if (!appCallGranted(byName.get(name), name, appContext, callGrant)) {
46
+ return failure(callNotGranted());
47
+ }
48
+ return registry.execute(name, input, appContext, callOptions);
49
+ },
50
+ listTools: registry.listTools,
51
+ listCommandNames: registry.listCommandNames,
52
+ listCommands: registry.listCommands,
53
+ hasCommand: () => true,
54
+ };
55
+ }
56
+ //# sourceMappingURL=app-call-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app-call-registry.js","sourceRoot":"","sources":["../src/app-call-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAuB,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACN,cAAc,EAEd,cAAc,GACd,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACN,SAAS,EACT,oBAAoB,GAGpB,MAAM,sBAAsB,CAAC;AAc9B;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,qBAAqB,CACpC,QAAgC,EAChC,OAA+B;IAE/B,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IACvC,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;QACrC,MAAM,IAAI,SAAS,CAClB,gFAAgF,CAChF,CAAC;IACH,CAAC;IACD,2FAA2F;IAC3F,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,IAA6B,CAAC;IAC1F,MAAM,QAAQ,GAAG,oBAAoB,CAAC,QAAQ,EAAE;QAC/C,GAAG,MAAM;QACT,SAAS,EAAE,MAAiB;QAC5B,CAAC,SAAS,CAAC,EAAE,IAAI;KACQ,CAAC,CAAC;IAC5B,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAC3E,OAAO;QACN,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,aAAa,EAAE,QAAQ,CAAC,aAAa;QACrC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,GAAmB,EAAE,EAAE,WAAW;YACnE,kFAAkF;YAClF,MAAM,UAAU,GAAmB,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC;YACrE,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,CAAC,EAAE,CAAC;gBACpE,OAAO,OAAO,CAAC,cAAc,EAAE,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;QAC/D,CAAC;QACD,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI;KACtB,CAAC;AACH,CAAC"}