@lushly-dev/afd-server 2.0.0 → 2.2.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 (103) hide show
  1. package/README.md +233 -8
  2. package/dist/approval-crypto.d.ts +33 -0
  3. package/dist/approval-crypto.d.ts.map +1 -0
  4. package/dist/approval-crypto.js +121 -0
  5. package/dist/approval-crypto.js.map +1 -0
  6. package/dist/approval-relay.d.ts +83 -0
  7. package/dist/approval-relay.d.ts.map +1 -0
  8. package/dist/approval-relay.js +55 -0
  9. package/dist/approval-relay.js.map +1 -0
  10. package/dist/approval.d.ts +155 -0
  11. package/dist/approval.d.ts.map +1 -0
  12. package/dist/approval.js +295 -0
  13. package/dist/approval.js.map +1 -0
  14. package/dist/bootstrap/afd-context.d.ts +13 -0
  15. package/dist/bootstrap/afd-context.d.ts.map +1 -1
  16. package/dist/bootstrap/afd-context.js +12 -1
  17. package/dist/bootstrap/afd-context.js.map +1 -1
  18. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  19. package/dist/bootstrap/afd-docs.js +19 -1
  20. package/dist/bootstrap/afd-docs.js.map +1 -1
  21. package/dist/bootstrap/afd-help.d.ts +5 -0
  22. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  23. package/dist/bootstrap/afd-help.js +5 -1
  24. package/dist/bootstrap/afd-help.js.map +1 -1
  25. package/dist/bootstrap/described-command.d.ts +5 -1
  26. package/dist/bootstrap/described-command.d.ts.map +1 -1
  27. package/dist/bootstrap/described-command.js.map +1 -1
  28. package/dist/bootstrap/registry.d.ts.map +1 -1
  29. package/dist/bootstrap/registry.js +3 -6
  30. package/dist/bootstrap/registry.js.map +1 -1
  31. package/dist/confirmations.d.ts +115 -0
  32. package/dist/confirmations.d.ts.map +1 -0
  33. package/dist/confirmations.js +186 -0
  34. package/dist/confirmations.js.map +1 -0
  35. package/dist/define.d.ts +1 -1
  36. package/dist/define.d.ts.map +1 -1
  37. package/dist/define.js.map +1 -1
  38. package/dist/direct-registry.d.ts +11 -1
  39. package/dist/direct-registry.d.ts.map +1 -1
  40. package/dist/direct-registry.js +2 -0
  41. package/dist/direct-registry.js.map +1 -1
  42. package/dist/elicitation-state.d.ts +30 -0
  43. package/dist/elicitation-state.d.ts.map +1 -0
  44. package/dist/elicitation-state.js +25 -0
  45. package/dist/elicitation-state.js.map +1 -0
  46. package/dist/execution.d.ts +4 -2
  47. package/dist/execution.d.ts.map +1 -1
  48. package/dist/execution.js +9 -4
  49. package/dist/execution.js.map +1 -1
  50. package/dist/http-handler.d.ts +6 -0
  51. package/dist/http-handler.d.ts.map +1 -1
  52. package/dist/http-handler.js +38 -16
  53. package/dist/http-handler.js.map +1 -1
  54. package/dist/index.d.ts +4 -1
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +5 -0
  57. package/dist/index.js.map +1 -1
  58. package/dist/journal-replay.d.ts +97 -0
  59. package/dist/journal-replay.d.ts.map +1 -0
  60. package/dist/journal-replay.js +250 -0
  61. package/dist/journal-replay.js.map +1 -0
  62. package/dist/journal.d.ts +90 -0
  63. package/dist/journal.d.ts.map +1 -0
  64. package/dist/journal.js +175 -0
  65. package/dist/journal.js.map +1 -0
  66. package/dist/lazy-tools.d.ts +2 -0
  67. package/dist/lazy-tools.d.ts.map +1 -1
  68. package/dist/lazy-tools.js +3 -1
  69. package/dist/lazy-tools.js.map +1 -1
  70. package/dist/mcp-modern.d.ts +76 -0
  71. package/dist/mcp-modern.d.ts.map +1 -0
  72. package/dist/mcp-modern.js +329 -0
  73. package/dist/mcp-modern.js.map +1 -0
  74. package/dist/meta-tools.d.ts +14 -13
  75. package/dist/meta-tools.d.ts.map +1 -1
  76. package/dist/meta-tools.js +19 -9
  77. package/dist/meta-tools.js.map +1 -1
  78. package/dist/middleware.d.ts.map +1 -1
  79. package/dist/middleware.js +8 -5
  80. package/dist/middleware.js.map +1 -1
  81. package/dist/request-context.d.ts +15 -0
  82. package/dist/request-context.d.ts.map +1 -0
  83. package/dist/request-context.js +21 -0
  84. package/dist/request-context.js.map +1 -0
  85. package/dist/schema.d.ts +16 -1
  86. package/dist/schema.d.ts.map +1 -1
  87. package/dist/schema.js +7 -1
  88. package/dist/schema.js.map +1 -1
  89. package/dist/server-types.d.ts +60 -1
  90. package/dist/server-types.d.ts.map +1 -1
  91. package/dist/server-types.js.map +1 -1
  92. package/dist/server.d.ts.map +1 -1
  93. package/dist/server.js +37 -21
  94. package/dist/server.js.map +1 -1
  95. package/dist/tool-router.d.ts +5 -0
  96. package/dist/tool-router.d.ts.map +1 -1
  97. package/dist/tool-router.js +86 -28
  98. package/dist/tool-router.js.map +1 -1
  99. package/dist/tools.d.ts +5 -1
  100. package/dist/tools.d.ts.map +1 -1
  101. package/dist/tools.js +37 -24
  102. package/dist/tools.js.map +1 -1
  103. package/package.json +7 -5
package/README.md CHANGED
@@ -14,10 +14,11 @@ pnpm add @lushly-dev/afd-server
14
14
 
15
15
  - **Zod-based Command Definition** - Define commands with Zod schemas for type-safe validation
16
16
  - **Auto JSON Schema Generation** - Automatic conversion to JSON Schema for MCP tool definitions
17
- - **Multiple Transport Support** - stdio for IDE/agent integration, HTTP/SSE for browser clients
17
+ - **Multiple Transport Support** - stdio and Streamable HTTP (`/mcp`), each serving MCP 2026-07-28 and 2025 clients
18
18
  - **Auto Transport Detection** - Automatically selects the right transport based on environment
19
19
  - **Built-in Validation** - Automatic input validation before handler execution
20
- - **Middleware System** - Logging, tracing, rate limiting, and custom middleware
20
+ - **Middleware System** - Logging, tracing, rate limiting, approvals, and custom middleware
21
+ - **Pre-execution Approvals** - Hold commands for human sign-off with signed, short-lived approval tokens
21
22
  - **Command Prerequisites** - Declare `requires` dependencies so agents can plan execution order
22
23
  - **Agent Discovery** - Grouped, individual or lazy tool strategies, `afd-detail`, and optional `afd-help`/`afd-docs`/`afd-schema` bootstrap tools
23
24
  - **Full TypeScript Support** - Complete type inference from Zod schemas
@@ -133,6 +134,8 @@ await server.start();
133
134
  // Server reads JSON-RPC from stdin, writes to stdout
134
135
  ```
135
136
 
137
+ stdio serves both MCP protocol eras on one connection: a client that opens with `server/discover` and per-request `_meta` gets MCP 2026-07-28, and a client that opens with `initialize` gets the 2025 protocol for the rest of the connection.
138
+
136
139
  In your IDE's MCP configuration (adjust the path to match your project):
137
140
  ```json
138
141
  {
@@ -160,9 +163,11 @@ const server = createMcpServer({
160
163
 
161
164
  await server.start();
162
165
  console.error(`Server running at ${server.getUrl()}`);
163
- // Exposes /sse, /message, /health endpoints
166
+ // MCP clients connect to http://localhost:3100/mcp
164
167
  ```
165
168
 
169
+ Point MCP clients at `/mcp`, for example `claude mcp add --transport http my-server http://localhost:3100/mcp`. See [MCP endpoint](#mcp-endpoint-mcp).
170
+
166
171
  ## Defining Commands
167
172
 
168
173
  ### Browser-safe entry point: `@lushly-dev/afd-server/define`
@@ -309,6 +314,37 @@ const formatDoc = defineCommand({
309
314
 
310
315
  Commands without `contexts` are universal (always visible). See "Context Management" below for server-level context configuration.
311
316
 
317
+ ### Command that asks for confirmation
318
+
319
+ A command with `confirmPrompt` can be gated on the server's MCP and HTTP surfaces with the
320
+ `confirmations` option ([`spec/command-metadata.md`](../../spec/command-metadata.md#confirmations)):
321
+
322
+ ```typescript
323
+ const clearTodos = defineCommand({
324
+ name: 'todo-clear',
325
+ description: 'Delete every todo',
326
+ mutation: true,
327
+ destructive: true,
328
+ confirmPrompt: 'Delete every todo? This cannot be undone.',
329
+ input: z.object({}),
330
+ async handler() { ... },
331
+ });
332
+
333
+ createMcpServer({ name: 'todo', version: '1.0.0', commands: [clearTodos], confirmations: 'enforce' });
334
+ ```
335
+
336
+ - **An MCP client that supports elicitation** is asked `confirmPrompt` through an
337
+ `input_required` result, and the command runs only if the user accepts. A decline gives
338
+ `CONFIRMATION_DECLINED`.
339
+ - **Any other caller** gets `CONFIRMATION_REQUIRED` until it repeats the call with
340
+ `confirm: true` (on `afd-batch` and `afd-pipe`, `confirm: ['todo-clear']`; on the HTTP
341
+ routes, the `Afd-Confirm: todo-clear` header). That acknowledgement comes from the agent, not
342
+ the user. `confirmations: 'require-human'` refuses it and accepts only an elicitation.
343
+ - **Several instances** behind one URL need the same `confirmationKey` (32 bytes or more), which
344
+ signs the confirmation's `requestState`.
345
+
346
+ `server.execute()` and DirectClient calls are never gated.
347
+
312
348
 
313
349
  ## Server Configuration
314
350
 
@@ -454,6 +490,128 @@ const retry = createRetryMiddleware({
454
490
  });
455
491
  ```
456
492
 
493
+ ### Approvals
494
+
495
+ `destructive` and `confirmPrompt` describe a command; `approval` holds it. A command whose `approval` policy requires it does not run until a human has approved that exact call. `createApprovalMiddleware` returns `APPROVAL_REQUIRED` before the handler runs, with a token the surface passes back once the human said yes:
496
+
497
+ ```typescript
498
+ import { createApprovalMiddleware, createMcpServer, defineCommand, success } from '@lushly-dev/afd-server';
499
+
500
+ const todoDelete = defineCommand({
501
+ name: 'todo-delete',
502
+ description: 'Delete a todo permanently',
503
+ mutation: true,
504
+ destructive: true,
505
+ // Or a function: (input, context) => context.actor?.kind === 'human' ? 'not-required' : 'required'
506
+ approval: 'required',
507
+ input: z.object({ id: z.string() }),
508
+ async handler(input) {
509
+ return success({ deleted: input.id });
510
+ },
511
+ });
512
+
513
+ const commands = [todoDelete];
514
+ const server = createMcpServer({
515
+ name: 'todo',
516
+ version: '1.0.0',
517
+ commands,
518
+ middleware: [
519
+ createApprovalMiddleware({
520
+ secret: process.env.AFD_APPROVAL_SECRET!, // required, at least 32 bytes, no default
521
+ commands,
522
+ summarize: (command, input) => `Delete todo ${(input as { id: string }).id} (permanent)`,
523
+ }),
524
+ ],
525
+ });
526
+ ```
527
+
528
+ A held call returns:
529
+
530
+ ```json
531
+ {
532
+ "success": false,
533
+ "error": {
534
+ "code": "APPROVAL_REQUIRED",
535
+ "message": "todo-delete needs approval before it runs",
536
+ "suggestion": "Ask the user to approve \"Delete todo 42 (permanent)\"; once they approve, the application retries the same call with the same input and details.approvalToken as its approval evidence (tool arguments cannot carry it). …",
537
+ "retryable": false,
538
+ "details": { "approvalToken": "afdap1.…", "expiresAt": "2026-10-26T12:05:00.000Z", "summary": "Delete todo 42 (permanent)" }
539
+ }
540
+ }
541
+ ```
542
+
543
+ To resume, retry the same command with the same input and `context.approval` set to the token, for example `registry.execute('todo-delete', { id: '42' }, { approval: token })`.
544
+
545
+ - **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).
546
+ - **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.
547
+ - **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.
548
+ - **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
+ - **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
+ - **Key rotation:** pass `secret: [newKey, oldKey]`; the first signs, any verifies.
551
+ - **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
+ - **Gates only the listed commands.** Pass the same `commands` as the server or registry: a command missing from the list is never held.
553
+ - **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`.
554
+ - **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.
555
+ - `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.
556
+
557
+ #### Asking the human over MCP
558
+
559
+ 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:
560
+
561
+ ```typescript
562
+ createApprovalMiddleware({ secret, commands, relay: 'mcp-elicitation' });
563
+ ```
564
+
565
+ 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:
566
+
567
+ - the `requestState` verifies (HMAC-signed with `confirmationKey`, bound to the method and the OAuth client id when there is one; an answer counts for 10 minutes from when it was asked);
568
+ - it names this command, validated input and actor (a digest keyed with the approval secret), and its nonce and expiry carry a MAC under the approval secret, so `confirmationKey` alone cannot mint an approval;
569
+ - the approval has not expired (`ttlMs`, on the middleware's clock);
570
+ - the answer is `accept` with `approve: true`;
571
+ - its nonce is unspent (single-use by default; `replay: 'within-ttl'` allows reuse).
572
+
573
+ No approval token is issued on this path, so the model never sees one. A stale, altered or mismatched state counts as unanswered and the human is asked again. A declined or cancelled form fails the call with `APPROVAL_REQUIRED`, `details.reason: 'declined'` and `retryable: false`. A call that needs both a confirmation and an approval asks for each in turn.
574
+
575
+ Calls that cannot elicit fail with `APPROVAL_REQUIRED` and no token, as without the relay:
576
+
577
+ - the client declares no form elicitation;
578
+ - a 2025-era HTTP request, or the legacy `/message` lane, which have no back channel;
579
+ - 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.
580
+
581
+ 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.
582
+
583
+ 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`.
584
+
585
+ `spec/command-metadata.md` ("Approvals") is the cross-language contract.
586
+
587
+ ### Command Journal and Replay
588
+
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.
590
+
591
+ `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
+
593
+ ```typescript
594
+ import { readFileSync } from 'node:fs';
595
+ import { parseJournal } from '@lushly-dev/afd-core';
596
+ import { FileJournalSink } from '@lushly-dev/afd-core/journal-file';
597
+ import { createJournalMiddleware, createMcpServer, replayJournal } from '@lushly-dev/afd-server';
598
+
599
+ // Record
600
+ const server = createMcpServer({
601
+ name: 'todo',
602
+ version: '1.0.0',
603
+ commands,
604
+ middleware: [createJournalMiddleware(new FileJournalSink('./session.jsonl'))],
605
+ });
606
+
607
+ // Later: replay against a fresh build
608
+ const entries = parseJournal(readFileSync('./session.jsonl', 'utf8'));
609
+ const report = await replayJournal(createMcpServer({ name: 'todo', version: '2.0.0', commands }), entries);
610
+ for (const entry of report.entries.filter((e) => e.status !== 'same')) {
611
+ console.log(entry.seq, entry.command, entry.status, entry.differences ?? entry.error);
612
+ }
613
+ ```
614
+
457
615
  ### Custom Middleware
458
616
 
459
617
  ```typescript
@@ -561,6 +719,7 @@ Create a command definition with Zod schema.
561
719
  | `errors` | string[] | No | Possible error codes |
562
720
  | `expose` | ExposeOptions | No | Surfaces the command is exposed to; `{ mcp: true }` is required for MCP tools |
563
721
  | `examples` | `{ title, input }[]` | No | Example inputs, validated against `input` at define time |
722
+ | `approval` | `'required'` \| `'not-required'` \| `(input, context) => …` | No | Whether a call needs human approval before the handler runs (default `'not-required'`); enforced by [`createApprovalMiddleware`](#approvals) |
564
723
 
565
724
  ### createMcpServer(options)
566
725
 
@@ -587,6 +746,11 @@ Create an MCP server from commands.
587
746
  | `maxSseConnections` | number | No | Concurrent `/sse` connections before HTTP 503 (default: 100) |
588
747
  | `maxSessions` | number | No | Live HTTP sessions when `contexts` are set; the least recently used is evicted (default: 1000) |
589
748
  | `sessionIdleTimeoutMs` | number | No | Idle time before an HTTP session expires (default: 1800000, 30 minutes) |
749
+ | `clock` | `Clock` | No | `context.clock` for every command, and the clock for HTTP session expiry (default: `systemClock`) |
750
+ | `random` | `RandomSource` | No | `context.random` for every command (default: `systemRandom`) |
751
+ | `actor` | `Actor` | No | `context.actor` for commands called over MCP when the context has none (default: `{ kind: 'agent' }`) |
752
+ | `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) |
590
754
  | `middleware` | array | No | Middleware functions |
591
755
  | `onCommand` | function | No | Command execution callback |
592
756
  | `onError` | function | No | Error callback |
@@ -618,14 +782,27 @@ The server exposes these endpoints:
618
782
 
619
783
  | Endpoint | Method | Description |
620
784
  |----------|--------|-------------|
621
- | `/sse` | GET | SSE connection for MCP clients |
622
- | `/message` | POST | JSON-RPC message endpoint |
785
+ | `/mcp` | POST | MCP Streamable HTTP endpoint: MCP 2026-07-28 statelessly, and 2025 clients that send `initialize` |
786
+ | `/sse` | GET | Deprecated: the 2024-11-05 HTTP+SSE transport, for `@lushly-dev/afd-client` 2.x |
787
+ | `/message` | POST | Deprecated: JSON-RPC message endpoint of the `/sse` transport |
623
788
  | `/rpc` | POST | Simple JSON-RPC for browser clients |
624
789
  | `/health` | GET | Health check |
625
790
  | `/batch` | POST | Batch command execution |
626
791
  | `/stream/:name` | POST | SSE chunks with command input in the JSON body |
627
792
  | `/stream/:name?input=...` | GET | Legacy streaming with JSON input in the query; refused (HTTP 405) for `mutation: true` commands; input over `maxBodyBytes` is refused (HTTP 413) |
628
793
 
794
+ ### MCP endpoint (`/mcp`)
795
+
796
+ `/mcp` is the MCP endpoint for MCP clients and agents. It is served by the official MCP TypeScript SDK (`@modelcontextprotocol/server`), behind the same Host, Origin, CORS and `maxBodyBytes` checks as every other route.
797
+
798
+ - **MCP 2026-07-28 requests** carry their protocol version and client capabilities in `_meta` and the `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers. Each request is served on its own, with no session: any instance behind a load balancer can answer it. `server/discover` returns the supported versions, capabilities, `instructions` and server identity. `tools/list` and `server/discover` results carry `ttlMs` (see `toolsListTtlMs`) and `cacheScope: "public"`.
799
+ - **2025 clients** that open with `initialize` are served on the same path, statelessly: no `Mcp-Session-Id` is issued, and `GET` and `DELETE` answer 405.
800
+ - **Protocol errors** follow the specification: header/body mismatch or a missing header is 400 with `-32020`, an unsupported protocol version is 400 with `-32022` and the supported list, a request missing required `_meta` is 400 with `-32602`, and an unknown method is 404 with `-32601`. These are answered on the wire and not reported to `onError`.
801
+ - **Tool results** are unchanged: the `CommandResult` JSON in `content[0].text`, with `isError` set on failure. Unknown and private commands are `COMMAND_NOT_FOUND` tool results.
802
+ - `createContext(req)` runs for every `tools/call`, and a handler error is reported to `onError` and answered as a redacted JSON-RPC internal error (details only in `devMode`).
803
+
804
+ The `/sse` and `/message` routes below are the deprecated 2024-11-05 transport. They stay unchanged for `@lushly-dev/afd-client` 2.x and are removed in 3.0.
805
+
629
806
  ### JSON-RPC Behavior (`/message` and `/rpc`)
630
807
 
631
808
  - A message with `"jsonrpc": "2.0"` and no `id` is a notification. It is answered with HTTP 202 and an empty body. On `/message` it is not executed (MCP notifications need no work here, and a request method sent without an `id` could not return its result). On `/rpc` the command runs, but its result is not sent. The simple `/rpc` format without a `jsonrpc` member is always answered, with `id: null` if omitted.
@@ -651,7 +828,7 @@ Batch (`/batch`, `afd-batch`) and stream execution use the core `executeBatch()`
651
828
 
652
829
  ### Sessions (`Mcp-Session-Id`)
653
830
 
654
- 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.
831
+ 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.
655
832
 
656
833
  ### SSE Connections
657
834
 
@@ -845,8 +1022,10 @@ Commands without `contexts` are always visible. Context commands themselves are
845
1022
 
846
1023
  Context state is per client:
847
1024
 
848
- - **stdio** serves one client, so it keeps one stack.
849
- - **HTTP** 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.
1025
+ - **stdio** opened with `initialize` serves one client, so it keeps one stack.
1026
+ - **MCP 2026-07-28** (`/mcp`, and stdio connections opened with `server/discover`) is stateless: the active context is request input. Send `_meta["dev.afd/context"]` with a context name on `tools/list` and `tools/call` to work in that context; an unknown name is a `-32602` error. `afd-context-enter` and `afd-context-exit` validate the name but store nothing, and return `persisted: false` with a reasoning that says to use `_meta`. Because MCP clients cache `tools/list` without its `_meta`, `toolsListTtlMs` defaults to 0 when contexts are configured. Contexts are not a security boundary: use `createContext` and middleware to restrict commands by caller.
1027
+ - **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
+ - **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.
850
1029
  - A stack holds at most 16 contexts (`CONTEXT_DEPTH_EXCEEDED` beyond that), and re-entering the active context is a no-op.
851
1030
  - In-process `server.execute()` ignores contexts.
852
1031
 
@@ -876,6 +1055,52 @@ const server = createMcpServer({
876
1055
  - Pipeline `$input` does not expose these values, so a pipeline cannot copy them into step inputs.
877
1056
  - stdio has no HTTP request, so `createContext` is not called there.
878
1057
 
1058
+ ## Actor, Clock and Random
1059
+
1060
+ Every command context carries three standard values. Read them instead of ambient globals, so that tests and replays can control them and middleware can tell callers apart:
1061
+
1062
+ | Field | What it is | Filled in by |
1063
+ |-------|------------|--------------|
1064
+ | `context.actor` | Who is calling: `{ kind, id?, label?, onBehalfOf? }`, `kind` one of `human`, `agent`, `service`, `script`, `test` | MCP calls (stdio and HTTP): the `actor` option, default `{ kind: 'agent' }`; `createContext` can set one per request; `createAuthMiddleware` adds the session user. `server.execute()` sets none. |
1065
+ | `context.clock` | `{ now(): number }`, milliseconds since the epoch | The `clock` option, default `systemClock` (`Date.now()`) |
1066
+ | `context.random` | `{ next(): number; seed? }`, a number in [0, 1) | The `random` option, default `systemRandom` (`Math.random()`) |
1067
+
1068
+ A value the caller puts on the context always wins over the server default.
1069
+
1070
+ ```typescript
1071
+ import { fixedClock, seededRandom, systemClock, systemRandom } from '@lushly-dev/afd-core';
1072
+
1073
+ const createTodo = defineCommand({
1074
+ name: 'todo-create',
1075
+ description: 'Create a todo',
1076
+ input: z.object({ title: z.string() }),
1077
+ async handler(input, context) {
1078
+ // The fields are optional in the type (a handler can be called directly);
1079
+ // every AFD surface sets them.
1080
+ const clock = context.clock ?? systemClock;
1081
+ const random = context.random ?? systemRandom;
1082
+ const createdAt = new Date(clock.now()).toISOString();
1083
+ const id = `todo-${Math.floor(random.next() * 1e9)}`;
1084
+ return success({ id, title: input.title, createdAt });
1085
+ },
1086
+ });
1087
+
1088
+ // Deterministic in tests: the same ids and timestamps on every run.
1089
+ const server = createMcpServer({
1090
+ name: 'todo',
1091
+ version: '1.0.0',
1092
+ commands: [createTodo],
1093
+ clock: fixedClock('2026-01-01T00:00:00Z'),
1094
+ random: seededRandom('test-seed'),
1095
+ });
1096
+ ```
1097
+
1098
+ - The execution engine stamps `metadata.actorKind` on every result whose context has an actor, and the telemetry middleware records it as `actorKind`. Only the kind is reported, never the actor's `id` or `label`.
1099
+ - Middleware can read and refine `context.actor` before calling `next()`; `actorKind` reflects the actor after the middleware ran.
1100
+ - The context's clock also times `metadata.executionTimeMs` and the telemetry middleware's timestamps, so a fixed clock gives deterministic durations.
1101
+ - `seededRandom()` is reproducible, not cryptographic. Use `crypto.getRandomValues()` for tokens and keys.
1102
+ - Using the actor to decide what data a handler returns is application logic: handlers read `context.actor` and filter their own data.
1103
+
879
1104
  ## Related
880
1105
 
881
1106
  - [@lushly-dev/afd-core](../core) - Core types and helpers
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @fileoverview The keyed digests, canonical JSON and nonce bookkeeping behind approval tokens and
3
+ * relayed approvals (`approval.ts`).
4
+ */
5
+ import type { Actor } from '@lushly-dev/afd-core';
6
+ /** An HMAC key: a string (UTF-8) or raw bytes, at least 32 bytes long. */
7
+ export type ApprovalSecret = string | Uint8Array;
8
+ /**
9
+ * Stable JSON for binding a token to an input: object keys sorted at every depth, otherwise the
10
+ * `JSON.stringify` rules (`toJSON` is honoured, so a `Date` is its ISO string; `undefined`
11
+ * members are dropped, and `undefined` in an array is `null`).
12
+ *
13
+ * It fails closed rather than collide: only plain objects, arrays, strings, finite numbers,
14
+ * booleans, `null` and values with `toJSON` are accepted. A `bigint`, a non-finite number, a
15
+ * cycle, or an object of any other kind (`Map`, `Set`, `RegExp`, typed arrays, class
16
+ * instances) throws, so a call whose validated input holds one cannot be approved.
17
+ *
18
+ * @throws TypeError for a value it cannot encode without ambiguity
19
+ */
20
+ export declare function canonicalJson(value: unknown): string;
21
+ /** The actor fields a token is bound to. `label` is display text, so it is left out. */
22
+ export declare function actorJson(actor: Actor | undefined): string;
23
+ export declare function toKeys(secret: ApprovalSecret | readonly ApprovalSecret[] | undefined): Buffer[];
24
+ export declare function hmac(key: Buffer, data: string): Buffer;
25
+ /** A keyed digest; `purpose` keeps an input digest from ever matching an actor digest. */
26
+ export declare function digest(key: Buffer, purpose: 'input' | 'actor', value: string): Buffer;
27
+ /** Constant-time equality. Lengths are not secret (every digest here is 32 bytes). */
28
+ export declare function safeEqual(a: Buffer, b: Buffer): boolean;
29
+ /** In-memory single-use nonces, forgotten once their token has expired. */
30
+ export declare function createMemoryNonceStore(): {
31
+ consume(nonce: string, expiresAt: number, now: number): boolean;
32
+ };
33
+ //# sourceMappingURL=approval-crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-crypto.d.ts","sourceRoot":"","sources":["../src/approval-crypto.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAIlD,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,wBAAgB,MAAM,CAAC,MAAM,EAAE,cAAc,GAAG,SAAS,cAAc,EAAE,GAAG,SAAS,GAAG,MAAM,EAAE,CAa/F;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,0FAA0F;AAC1F,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAErF;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAEvD;AAED,2EAA2E;AAC3E,wBAAgB,sBAAsB;mBAGrB,MAAM,aAAa,MAAM,OAAO,MAAM,GAAG,OAAO;EAShE"}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @fileoverview The keyed digests, canonical JSON and nonce bookkeeping behind approval tokens and
3
+ * relayed approvals (`approval.ts`).
4
+ */
5
+ import { createHmac, timingSafeEqual } from 'node:crypto';
6
+ const MIN_SECRET_BYTES = 32;
7
+ /**
8
+ * Stable JSON for binding a token to an input: object keys sorted at every depth, otherwise the
9
+ * `JSON.stringify` rules (`toJSON` is honoured, so a `Date` is its ISO string; `undefined`
10
+ * members are dropped, and `undefined` in an array is `null`).
11
+ *
12
+ * It fails closed rather than collide: only plain objects, arrays, strings, finite numbers,
13
+ * booleans, `null` and values with `toJSON` are accepted. A `bigint`, a non-finite number, a
14
+ * cycle, or an object of any other kind (`Map`, `Set`, `RegExp`, typed arrays, class
15
+ * instances) throws, so a call whose validated input holds one cannot be approved.
16
+ *
17
+ * @throws TypeError for a value it cannot encode without ambiguity
18
+ */
19
+ export function canonicalJson(value) {
20
+ const ancestors = new Set();
21
+ function encode(raw) {
22
+ let value = raw;
23
+ if (value !== null && typeof value === 'object' && 'toJSON' in value) {
24
+ const toJSON = value.toJSON;
25
+ if (typeof toJSON === 'function')
26
+ value = toJSON.call(value);
27
+ }
28
+ switch (typeof value) {
29
+ case 'string':
30
+ case 'boolean':
31
+ return JSON.stringify(value);
32
+ case 'number':
33
+ if (!Number.isFinite(value)) {
34
+ throw new TypeError('Cannot bind an approval to a non-finite number');
35
+ }
36
+ return JSON.stringify(value);
37
+ case 'bigint':
38
+ throw new TypeError('Cannot bind an approval to a bigint');
39
+ case 'undefined':
40
+ case 'function':
41
+ case 'symbol':
42
+ return undefined;
43
+ }
44
+ if (value === null)
45
+ return 'null';
46
+ const object = value;
47
+ if (ancestors.has(object))
48
+ throw new TypeError('Cannot bind an approval to a cyclic input');
49
+ ancestors.add(object);
50
+ try {
51
+ if (Array.isArray(object)) {
52
+ return `[${object.map((item) => encode(item) ?? 'null').join(',')}]`;
53
+ }
54
+ const prototype = Object.getPrototypeOf(object);
55
+ if (prototype !== Object.prototype && prototype !== null) {
56
+ const kind = object.constructor?.name ?? 'object';
57
+ throw new TypeError(`Cannot bind an approval to a ${kind}: use plain JSON input`);
58
+ }
59
+ const members = [];
60
+ for (const key of Object.keys(object).sort()) {
61
+ const member = encode(object[key]);
62
+ if (member !== undefined)
63
+ members.push(`${JSON.stringify(key)}:${member}`);
64
+ }
65
+ return `{${members.join(',')}}`;
66
+ }
67
+ finally {
68
+ ancestors.delete(object);
69
+ }
70
+ }
71
+ return encode(value) ?? 'null';
72
+ }
73
+ /** The actor fields a token is bound to. `label` is display text, so it is left out. */
74
+ export function actorJson(actor) {
75
+ if (!actor)
76
+ return 'null';
77
+ return canonicalJson({ kind: actor.kind, id: actor.id, onBehalfOf: actor.onBehalfOf });
78
+ }
79
+ export function toKeys(secret) {
80
+ const secrets = Array.isArray(secret) ? secret : [secret];
81
+ if (secrets.length === 0)
82
+ throw new TypeError('Approval secret is required');
83
+ return secrets.map((candidate) => {
84
+ if (typeof candidate !== 'string' && !(candidate instanceof Uint8Array)) {
85
+ throw new TypeError('Approval secret is required: pass a string or Uint8Array');
86
+ }
87
+ const key = Buffer.from(candidate);
88
+ if (key.length < MIN_SECRET_BYTES) {
89
+ throw new TypeError(`Approval secret must be at least ${MIN_SECRET_BYTES} bytes`);
90
+ }
91
+ return key;
92
+ });
93
+ }
94
+ export function hmac(key, data) {
95
+ return createHmac('sha256', key).update(data).digest();
96
+ }
97
+ /** A keyed digest; `purpose` keeps an input digest from ever matching an actor digest. */
98
+ export function digest(key, purpose, value) {
99
+ return hmac(key, `${purpose}\0${value}`);
100
+ }
101
+ /** Constant-time equality. Lengths are not secret (every digest here is 32 bytes). */
102
+ export function safeEqual(a, b) {
103
+ return a.length === b.length && timingSafeEqual(a, b);
104
+ }
105
+ /** In-memory single-use nonces, forgotten once their token has expired. */
106
+ export function createMemoryNonceStore() {
107
+ const used = new Map();
108
+ return {
109
+ consume(nonce, expiresAt, now) {
110
+ for (const [spent, until] of used) {
111
+ if (until <= now)
112
+ used.delete(spent);
113
+ }
114
+ if (used.has(nonce))
115
+ return false;
116
+ used.set(nonce, expiresAt);
117
+ return true;
118
+ },
119
+ };
120
+ }
121
+ //# sourceMappingURL=approval-crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-crypto.js","sourceRoot":"","sources":["../src/approval-crypto.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG1D,MAAM,gBAAgB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AU,SAAS,CAAC,CAAS,EAAE,CAAS;IAC7C,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACvD,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,sBAAsB;IACrC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,OAAO;QACN,OAAO,CAAC,KAAa,EAAE,SAAiB,EAAE,GAAW;YACpD,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC;gBACnC,IAAI,KAAK,IAAI,GAAG;oBAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACtC,CAAC;YACD,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;gBAAE,OAAO,KAAK,CAAC;YAClC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YAC3B,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @fileoverview The MCP approval relay (#418): how the approval middleware asks the human behind
3
+ * an MCP client, through a form elicitation, instead of returning a token to the agent.
4
+ *
5
+ * The MCP lane binds an {@link ApprovalRelay} to the context of each `tools/call` that can carry a
6
+ * form elicitation, under a private symbol (as the confirmation channel is), so neither
7
+ * `createContext` nor tool arguments can forge one. The tool router names the one command the
8
+ * call routes to; with `relay: 'mcp-elicitation'`, the approval middleware of that command reads
9
+ * the human's answer from the relay or records a hold on it, and the lane then answers the call
10
+ * with `input_required` instead of the held result.
11
+ *
12
+ * `afd-batch` and `afd-pipe` replace the relay with one that never asks, because asking mid-run
13
+ * would run the earlier steps again on the retry.
14
+ */
15
+ import type { CommandContext } from '@lushly-dev/afd-core';
16
+ /** The `inputRequests` key of the approval elicitation. */
17
+ export declare const APPROVAL_INPUT_KEY = "approval";
18
+ /** The approval elicitation form: one required boolean. */
19
+ export declare const APPROVAL_REQUESTED_SCHEMA: {
20
+ readonly type: "object";
21
+ readonly properties: {
22
+ readonly approve: {
23
+ readonly type: "boolean";
24
+ readonly title: "Approve";
25
+ readonly description: "Allow this action to run";
26
+ };
27
+ };
28
+ readonly required: readonly ["approve"];
29
+ };
30
+ /** A call held for the human's approval, as recorded by the middleware. */
31
+ export interface ApprovalHold {
32
+ /** Keyed digest of the command, its validated input and the actor, under the signing key. */
33
+ binding: string;
34
+ /** The same digest under every verification key: earlier answers to any of them are dropped. */
35
+ bindings: readonly string[];
36
+ /** Random nonce, spent when the approved call runs. */
37
+ nonce: string;
38
+ /** Expiry of the approval, epoch milliseconds on the middleware's clock. */
39
+ expiresAt: number;
40
+ /** MAC of the binding, nonce and expiry under the approval secret. */
41
+ mac: string;
42
+ /** The question shown to the human. */
43
+ message: string;
44
+ }
45
+ /** The human's answer to an earlier approval elicitation for one binding. */
46
+ export type ApprovalAnswer = {
47
+ kind: 'accept';
48
+ binding: string;
49
+ nonce: string;
50
+ expiresAt: number;
51
+ mac: string;
52
+ } | {
53
+ kind: 'decline';
54
+ } | {
55
+ kind: 'missing';
56
+ };
57
+ /** What one MCP `tools/call` offers the approval middleware. */
58
+ export interface ApprovalRelay {
59
+ /** Name the command this tool call routes to; only that command can claim the relay. */
60
+ route(command: string): void;
61
+ /**
62
+ * Take the relay for `command`. Only the routed command, and only once, so a command run by
63
+ * another command's handler (or a later step) cannot turn the tool call into an elicitation.
64
+ */
65
+ claim(command: string): boolean;
66
+ /**
67
+ * The answer this request carries for any of `bindings` (one per verification key): `missing`
68
+ * unless its `requestState` verifies and names that binding. The latest answer wins.
69
+ */
70
+ answer(bindings: readonly string[]): Promise<ApprovalAnswer>;
71
+ /** Record that the call needs the human's approval; the lane asks once the call returns. */
72
+ hold(hold: ApprovalHold): void;
73
+ }
74
+ /** Return a copy of `context` bound to `relay`. */
75
+ export declare function bindApprovalRelay(context: CommandContext, relay: ApprovalRelay): CommandContext;
76
+ /**
77
+ * Return a copy of `context` whose relay never asks (for `afd-batch` and `afd-pipe` steps), so the
78
+ * middleware can still tell the agent to run the command on its own.
79
+ */
80
+ export declare function withoutApprovalRelay(context: CommandContext): CommandContext;
81
+ /** The relay bound to `context`, if any. */
82
+ export declare function approvalRelay(context: CommandContext | undefined): ApprovalRelay | undefined;
83
+ //# sourceMappingURL=approval-relay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-relay.d.ts","sourceRoot":"","sources":["../src/approval-relay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,2DAA2D;AAC3D,eAAO,MAAM,kBAAkB,aAAa,CAAC;AAE7C,2DAA2D;AAC3D,eAAO,MAAM,yBAAyB;;;;;;;;;;CAU5B,CAAC;AAEX,2EAA2E;AAC3E,MAAM,WAAW,YAAY;IAC5B,6FAA6F;IAC7F,OAAO,EAAE,MAAM,CAAC;IAChB,gGAAgG;IAChG,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,4EAA4E;IAC5E,SAAS,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,EAAE,MAAM,CAAC;IACZ,uCAAuC;IACvC,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,6EAA6E;AAC7E,MAAM,MAAM,cAAc,GACvB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAClF;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAEvB,gEAAgE;AAChE,MAAM,WAAW,aAAa;IAC7B,wFAAwF;IACxF,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;OAGG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IAChC;;;OAGG;IACH,MAAM,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IAC7D,4FAA4F;IAC5F,IAAI,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;CAC/B;AAcD,mDAAmD;AACnD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,GAAG,cAAc,CAG/F;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,cAAc,GAAG,cAAc,CAG5E;AAED,4CAA4C;AAC5C,wBAAgB,aAAa,CAAC,OAAO,EAAE,cAAc,GAAG,SAAS,GAAG,aAAa,GAAG,SAAS,CAE5F"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @fileoverview The MCP approval relay (#418): how the approval middleware asks the human behind
3
+ * an MCP client, through a form elicitation, instead of returning a token to the agent.
4
+ *
5
+ * The MCP lane binds an {@link ApprovalRelay} to the context of each `tools/call` that can carry a
6
+ * form elicitation, under a private symbol (as the confirmation channel is), so neither
7
+ * `createContext` nor tool arguments can forge one. The tool router names the one command the
8
+ * call routes to; with `relay: 'mcp-elicitation'`, the approval middleware of that command reads
9
+ * the human's answer from the relay or records a hold on it, and the lane then answers the call
10
+ * with `input_required` instead of the held result.
11
+ *
12
+ * `afd-batch` and `afd-pipe` replace the relay with one that never asks, because asking mid-run
13
+ * would run the earlier steps again on the retry.
14
+ */
15
+ /** The `inputRequests` key of the approval elicitation. */
16
+ export const APPROVAL_INPUT_KEY = 'approval';
17
+ /** The approval elicitation form: one required boolean. */
18
+ export const APPROVAL_REQUESTED_SCHEMA = {
19
+ type: 'object',
20
+ properties: {
21
+ approve: {
22
+ type: 'boolean',
23
+ title: 'Approve',
24
+ description: 'Allow this action to run',
25
+ },
26
+ },
27
+ required: ['approve'],
28
+ };
29
+ const RELAY = Symbol('afd.approvalRelay');
30
+ /** A relay that never asks: the steps of `afd-batch` and `afd-pipe` get it. */
31
+ const NEVER_ASKS = {
32
+ route() { },
33
+ claim: () => false,
34
+ answer: async () => ({ kind: 'missing' }),
35
+ hold() { },
36
+ };
37
+ /** Return a copy of `context` bound to `relay`. */
38
+ export function bindApprovalRelay(context, relay) {
39
+ const bound = { ...context, [RELAY]: relay };
40
+ return bound;
41
+ }
42
+ /**
43
+ * Return a copy of `context` whose relay never asks (for `afd-batch` and `afd-pipe` steps), so the
44
+ * middleware can still tell the agent to run the command on its own.
45
+ */
46
+ export function withoutApprovalRelay(context) {
47
+ if (!context[RELAY])
48
+ return context;
49
+ return bindApprovalRelay(context, NEVER_ASKS);
50
+ }
51
+ /** The relay bound to `context`, if any. */
52
+ export function approvalRelay(context) {
53
+ return context?.[RELAY];
54
+ }
55
+ //# sourceMappingURL=approval-relay.js.map