@lushly-dev/afd-server 2.1.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +233 -8
- package/dist/approval-crypto.d.ts +33 -0
- package/dist/approval-crypto.d.ts.map +1 -0
- package/dist/approval-crypto.js +121 -0
- package/dist/approval-crypto.js.map +1 -0
- package/dist/approval-relay.d.ts +85 -0
- package/dist/approval-relay.d.ts.map +1 -0
- package/dist/approval-relay.js +62 -0
- package/dist/approval-relay.js.map +1 -0
- package/dist/approval.d.ts +156 -0
- package/dist/approval.d.ts.map +1 -0
- package/dist/approval.js +299 -0
- package/dist/approval.js.map +1 -0
- package/dist/bootstrap/afd-context.d.ts +13 -0
- package/dist/bootstrap/afd-context.d.ts.map +1 -1
- package/dist/bootstrap/afd-context.js +12 -1
- package/dist/bootstrap/afd-context.js.map +1 -1
- package/dist/bootstrap/afd-docs.d.ts.map +1 -1
- package/dist/bootstrap/afd-docs.js +6 -1
- package/dist/bootstrap/afd-docs.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +2 -1
- package/dist/bootstrap/described-command.d.ts.map +1 -1
- package/dist/bootstrap/described-command.js.map +1 -1
- package/dist/confirmations.d.ts +115 -0
- package/dist/confirmations.d.ts.map +1 -0
- package/dist/confirmations.js +186 -0
- package/dist/confirmations.js.map +1 -0
- package/dist/define.d.ts +1 -1
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js.map +1 -1
- package/dist/direct-registry.d.ts +10 -1
- package/dist/direct-registry.d.ts.map +1 -1
- package/dist/direct-registry.js +15 -5
- package/dist/direct-registry.js.map +1 -1
- package/dist/elicitation-state.d.ts +30 -0
- package/dist/elicitation-state.d.ts.map +1 -0
- package/dist/elicitation-state.js +25 -0
- package/dist/elicitation-state.js.map +1 -0
- package/dist/execution.d.ts +4 -2
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +9 -4
- package/dist/execution.js.map +1 -1
- package/dist/http-handler.d.ts +6 -0
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +34 -14
- package/dist/http-handler.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/journal-replay.d.ts +97 -0
- package/dist/journal-replay.d.ts.map +1 -0
- package/dist/journal-replay.js +250 -0
- package/dist/journal-replay.js.map +1 -0
- package/dist/journal.d.ts +90 -0
- package/dist/journal.d.ts.map +1 -0
- package/dist/journal.js +175 -0
- package/dist/journal.js.map +1 -0
- package/dist/lazy-tools.d.ts +1 -0
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +2 -1
- package/dist/lazy-tools.js.map +1 -1
- package/dist/mcp-modern.d.ts +76 -0
- package/dist/mcp-modern.d.ts.map +1 -0
- package/dist/mcp-modern.js +329 -0
- package/dist/mcp-modern.js.map +1 -0
- package/dist/meta-tools.d.ts +8 -1
- package/dist/meta-tools.d.ts.map +1 -1
- package/dist/meta-tools.js +12 -0
- package/dist/meta-tools.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +8 -5
- package/dist/middleware.js.map +1 -1
- package/dist/request-context.d.ts +15 -0
- package/dist/request-context.d.ts.map +1 -0
- package/dist/request-context.js +21 -0
- package/dist/request-context.js.map +1 -0
- package/dist/schema.d.ts +9 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -0
- package/dist/schema.js.map +1 -1
- package/dist/server-types.d.ts +60 -1
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +37 -21
- package/dist/server.js.map +1 -1
- package/dist/tool-router.d.ts +5 -0
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +82 -6
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts +5 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +35 -5
- package/dist/tools.js.map +1 -1
- package/package.json +7 -5
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
/** Longest input shown in an approval elicitation, in characters. */
|
|
56
|
+
const MAX_SHOWN_INPUT = 1000;
|
|
57
|
+
/** The question of a relayed approval: the summary, then what exactly would run. */
|
|
58
|
+
export function relayMessage(summary, command, input, note) {
|
|
59
|
+
const shown = input.length > MAX_SHOWN_INPUT ? `${input.slice(0, MAX_SHOWN_INPUT)}…` : input;
|
|
60
|
+
return [...(note ? [note] : []), summary, '', `Command: ${command}`, `Input: ${shown}`].join('\n');
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=approval-relay.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approval-relay.js","sourceRoot":"","sources":["../src/approval-relay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,2DAA2D;AAC3D,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAE7C,2DAA2D;AAC3D,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACX,OAAO,EAAE;YACR,IAAI,EAAE,SAAS;YACf,KAAK,EAAE,SAAS;YAChB,WAAW,EAAE,0BAA0B;SACvC;KACD;IACD,QAAQ,EAAE,CAAC,SAAS,CAAC;CACZ,CAAC;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,EAAE,UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,CAC3F,IAAI,CACJ,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Pre-execution approval gate (#272).
|
|
3
|
+
*
|
|
4
|
+
* `createApprovalMiddleware` holds a call whose command's `approval` policy requires a human's
|
|
5
|
+
* sign-off and returns `APPROVAL_REQUIRED` before the handler runs. The result carries an
|
|
6
|
+
* approval token; once a human approves, the surface retries the same call with that token in
|
|
7
|
+
* `context.approval`.
|
|
8
|
+
*
|
|
9
|
+
* Token format: `afdap1.<payload>.<mac>`, both parts base64url. The payload is JSON:
|
|
10
|
+
*
|
|
11
|
+
* - `c`: the command name;
|
|
12
|
+
* - `i`: HMAC-SHA256 of the canonical JSON of the validated input;
|
|
13
|
+
* - `a`: HMAC-SHA256 of the canonical JSON of the actor's `kind`, `id` and `onBehalfOf`
|
|
14
|
+
* (`null` when the call has no actor);
|
|
15
|
+
* - `iat`, `exp`: issue and expiry times in epoch milliseconds;
|
|
16
|
+
* - `n`: a 128-bit random nonce.
|
|
17
|
+
*
|
|
18
|
+
* The MAC is HMAC-SHA256 over `afdap1.<payload>` with the application's secret. The input and
|
|
19
|
+
* actor are keyed digests rather than plain hashes, so a token reveals neither a low-entropy
|
|
20
|
+
* input (such as a record ID) nor the actor ID. Every comparison is constant-time.
|
|
21
|
+
*
|
|
22
|
+
* With `relay: 'mcp-elicitation'` (#418), an MCP call that can carry a form elicitation is not
|
|
23
|
+
* answered with a token at all: the MCP lane asks the human behind the client, and the retry runs
|
|
24
|
+
* once the signed `requestState` and the human's answer check out (see `approval-relay.ts`).
|
|
25
|
+
*/
|
|
26
|
+
import type { Actor, ApprovalPolicy, Clock, CommandContext, CommandMiddleware } from '@lushly-dev/afd-core';
|
|
27
|
+
import { type ApprovalSecret, canonicalJson } from './approval-crypto.js';
|
|
28
|
+
export { type ApprovalSecret, canonicalJson };
|
|
29
|
+
/** What the middleware reads from a command: its name, approval policy and confirmation prompt. */
|
|
30
|
+
export interface ApprovalCommand {
|
|
31
|
+
name: string;
|
|
32
|
+
approval?: ApprovalPolicy<never>;
|
|
33
|
+
confirmPrompt?: string;
|
|
34
|
+
}
|
|
35
|
+
/** Why a supplied approval token was not accepted. */
|
|
36
|
+
export type ApprovalRejection = 'malformed' | 'invalid-signature' | 'expired' | 'command-mismatch' | 'input-mismatch' | 'actor-mismatch' | 'already-used';
|
|
37
|
+
/**
|
|
38
|
+
* Records which single-use tokens have been spent. The default keeps them in memory, which
|
|
39
|
+
* holds only within one process: give servers that run several instances a shared store.
|
|
40
|
+
*/
|
|
41
|
+
export interface ApprovalNonceStore {
|
|
42
|
+
/**
|
|
43
|
+
* Mark `nonce` as used until `expiresAt` (epoch milliseconds; it can be forgotten after).
|
|
44
|
+
* Return `false` when it was already used. Must be atomic: of two concurrent calls with the
|
|
45
|
+
* same nonce, exactly one returns `true`.
|
|
46
|
+
*/
|
|
47
|
+
consume(nonce: string, expiresAt: number): boolean | Promise<boolean>;
|
|
48
|
+
}
|
|
49
|
+
/** A call held for approval, as passed to `onApprovalRequired`. */
|
|
50
|
+
export interface ApprovalRequest {
|
|
51
|
+
command: string;
|
|
52
|
+
/** The validated input the token is bound to. */
|
|
53
|
+
input: unknown;
|
|
54
|
+
actor?: Actor;
|
|
55
|
+
approvalToken: string;
|
|
56
|
+
/** ISO 8601 expiry of `approvalToken`. */
|
|
57
|
+
expiresAt: string;
|
|
58
|
+
summary: string;
|
|
59
|
+
/** Set when the call carried a token that was rejected. */
|
|
60
|
+
rejected?: ApprovalRejection;
|
|
61
|
+
}
|
|
62
|
+
/** Options for {@link createApprovalMiddleware}. */
|
|
63
|
+
export interface ApprovalMiddlewareOptions {
|
|
64
|
+
/**
|
|
65
|
+
* The HMAC key, or several during a key rotation: the first signs, any of them verifies.
|
|
66
|
+
* Required, with no default; each key must be at least 32 bytes. Keep it out of source.
|
|
67
|
+
*/
|
|
68
|
+
secret: ApprovalSecret | readonly ApprovalSecret[];
|
|
69
|
+
/**
|
|
70
|
+
* The commands to gate: pass the same list given to `createMcpServer` or
|
|
71
|
+
* `createDirectRegistry`. A command that is not in this list is never held, whatever its
|
|
72
|
+
* `approval` policy says.
|
|
73
|
+
*/
|
|
74
|
+
commands: Iterable<ApprovalCommand>;
|
|
75
|
+
/** How long a token stays valid, in milliseconds. Default: 300000 (5 minutes); at most 24 hours. */
|
|
76
|
+
ttlMs?: number;
|
|
77
|
+
/**
|
|
78
|
+
* `'single-use'` (default): a token runs the command once; a second call with it is held
|
|
79
|
+
* again with `rejected: 'already-used'`. `'within-ttl'`: a token runs the same command, input
|
|
80
|
+
* and actor as often as it is presented until it expires, so one approval also covers
|
|
81
|
+
* repeats (for example duplicate batch items), not only retries after a transient failure.
|
|
82
|
+
*/
|
|
83
|
+
replay?: 'single-use' | 'within-ttl';
|
|
84
|
+
/**
|
|
85
|
+
* Where single-use nonces are recorded. Default: in memory, for this middleware instance
|
|
86
|
+
* only. Share one store between every instance that uses the same secret (several
|
|
87
|
+
* processes, or both a server and a `createDirectRegistry`), or a token works once on each.
|
|
88
|
+
*/
|
|
89
|
+
nonceStore?: ApprovalNonceStore;
|
|
90
|
+
/**
|
|
91
|
+
* The text shown to the human who approves, from the call. Default (also for an empty
|
|
92
|
+
* string): the command's `confirmPrompt`, else `Run <command>`.
|
|
93
|
+
*/
|
|
94
|
+
summarize?: (command: string, input: unknown, context: CommandContext) => string | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* Whether the `APPROVAL_REQUIRED` result carries `details.approvalToken`. Default: `false`
|
|
97
|
+
* when `context.interface` is `'mcp'` (every MCP lane, and the HTTP routes of
|
|
98
|
+
* `createMcpHandler`), whose caller is the agent, and `true` elsewhere. Without the token in the result, deliver it to the approving human through
|
|
99
|
+
* `onApprovalRequired`. `true` is safe only while the gated caller cannot set
|
|
100
|
+
* `context.approval` itself. DirectClient, createDirectRegistry and the in-process CLI
|
|
101
|
+
* use a private exchange instead: evidence is omitted regardless of this option.
|
|
102
|
+
*/
|
|
103
|
+
includeToken?: boolean;
|
|
104
|
+
/**
|
|
105
|
+
* How an MCP call asks the human. `'none'` (default): it fails with `APPROVAL_REQUIRED`, and
|
|
106
|
+
* the application obtains the approval out of band. `'mcp-elicitation'`: a call to a single
|
|
107
|
+
* command from an MCP client that declares form elicitation is answered with a form
|
|
108
|
+
* elicitation showing the summary, and runs once the human accepts. No token is issued on that
|
|
109
|
+
* path. Calls that cannot elicit (no capability, a 2025-era HTTP request, an `afd-batch` or
|
|
110
|
+
* `afd-pipe` step) still fail with `APPROVAL_REQUIRED`.
|
|
111
|
+
*
|
|
112
|
+
* This trusts the MCP client application to show the question to a human: the server cannot
|
|
113
|
+
* tell a person's answer from client code that accepts on its own. Leave it off when the
|
|
114
|
+
* agent's own code is the MCP client. Servers with several instances must share
|
|
115
|
+
* `confirmationKey` (it signs the elicitation state) and `nonceStore`.
|
|
116
|
+
*/
|
|
117
|
+
relay?: 'none' | 'mcp-elicitation';
|
|
118
|
+
/**
|
|
119
|
+
* Called for every call held with a token, before the result is returned, for example to notify
|
|
120
|
+
* a human. Not called for a call whose approval is asked over MCP (`relay`): no token exists.
|
|
121
|
+
*/
|
|
122
|
+
onApprovalRequired?: (request: ApprovalRequest) => void | Promise<void>;
|
|
123
|
+
/**
|
|
124
|
+
* Source of time for issuing and expiring tokens and for forgetting spent nonces. Default:
|
|
125
|
+
* the system clock. `context.clock` is never used: a caller can set it, and this is
|
|
126
|
+
* security time.
|
|
127
|
+
*/
|
|
128
|
+
clock?: Clock;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Create a middleware that runs a command whose `approval` policy requires approval only when
|
|
132
|
+
* `context.approval` holds a valid token for this command, input and actor. Otherwise it
|
|
133
|
+
* returns `APPROVAL_REQUIRED` with a fresh token, and the handler does not run.
|
|
134
|
+
*
|
|
135
|
+
* Install it after any middleware that sets or refines `context.actor` (such as auth), since
|
|
136
|
+
* tokens are bound to the actor. `context.approval` must only ever be set by trusted surface
|
|
137
|
+
* code once a human approved, never from tool arguments: whoever holds a token can use it.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* const commands = [todoDelete, todoList];
|
|
142
|
+
* const server = createMcpServer({
|
|
143
|
+
* name: 'todo',
|
|
144
|
+
* version: '1.0.0',
|
|
145
|
+
* commands,
|
|
146
|
+
* middleware: [
|
|
147
|
+
* createApprovalMiddleware({ secret: process.env.AFD_APPROVAL_SECRET!, commands }),
|
|
148
|
+
* ],
|
|
149
|
+
* });
|
|
150
|
+
* ```
|
|
151
|
+
*
|
|
152
|
+
* @throws TypeError when no secret is given, a secret is shorter than 32 bytes, `ttlMs` is not
|
|
153
|
+
* a positive number, or a command declares an approval policy that is not valid
|
|
154
|
+
*/
|
|
155
|
+
export declare function createApprovalMiddleware(options: ApprovalMiddlewareOptions): CommandMiddleware;
|
|
156
|
+
//# sourceMappingURL=approval.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approval.d.ts","sourceRoot":"","sources":["../src/approval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,KAAK,EACX,KAAK,EAEL,cAAc,EACd,KAAK,EACL,cAAc,EACd,iBAAiB,EACjB,MAAM,sBAAsB,CAAC;AAO9B,OAAO,EACN,KAAK,cAAc,EAEnB,aAAa,EAMb,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,KAAK,cAAc,EAAE,aAAa,EAAE,CAAC;AAQ9C,mGAAmG;AACnG,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC;IACjC,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,sDAAsD;AACtD,MAAM,MAAM,iBAAiB,GAC1B,WAAW,GACX,mBAAmB,GACnB,SAAS,GACT,kBAAkB,G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CAAC,IAAI,CAAC,CAAC;IAExE;;;;OAIG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC;CACd;AAeD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,iBAAiB,CAsQ9F"}
|
package/dist/approval.js
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Pre-execution approval gate (#272).
|
|
3
|
+
*
|
|
4
|
+
* `createApprovalMiddleware` holds a call whose command's `approval` policy requires a human's
|
|
5
|
+
* sign-off and returns `APPROVAL_REQUIRED` before the handler runs. The result carries an
|
|
6
|
+
* approval token; once a human approves, the surface retries the same call with that token in
|
|
7
|
+
* `context.approval`.
|
|
8
|
+
*
|
|
9
|
+
* Token format: `afdap1.<payload>.<mac>`, both parts base64url. The payload is JSON:
|
|
10
|
+
*
|
|
11
|
+
* - `c`: the command name;
|
|
12
|
+
* - `i`: HMAC-SHA256 of the canonical JSON of the validated input;
|
|
13
|
+
* - `a`: HMAC-SHA256 of the canonical JSON of the actor's `kind`, `id` and `onBehalfOf`
|
|
14
|
+
* (`null` when the call has no actor);
|
|
15
|
+
* - `iat`, `exp`: issue and expiry times in epoch milliseconds;
|
|
16
|
+
* - `n`: a 128-bit random nonce.
|
|
17
|
+
*
|
|
18
|
+
* The MAC is HMAC-SHA256 over `afdap1.<payload>` with the application's secret. The input and
|
|
19
|
+
* actor are keyed digests rather than plain hashes, so a token reveals neither a low-entropy
|
|
20
|
+
* input (such as a record ID) nor the actor ID. Every comparison is constant-time.
|
|
21
|
+
*
|
|
22
|
+
* With `relay: 'mcp-elicitation'` (#418), an MCP call that can carry a form elicitation is not
|
|
23
|
+
* answered with a token at all: the MCP lane asks the human behind the client, and the retry runs
|
|
24
|
+
* once the signed `requestState` and the human's answer check out (see `approval-relay.ts`).
|
|
25
|
+
*/
|
|
26
|
+
import { randomBytes } from 'node:crypto';
|
|
27
|
+
import { ErrorCodes, failure, systemClock } from '@lushly-dev/afd-core';
|
|
28
|
+
import { directApprovalExchange, holdDirectApproval, takeDirectApproval, } from '@lushly-dev/afd-core/internal/direct-approval';
|
|
29
|
+
import { actorJson, canonicalJson, createMemoryNonceStore, digest, hmac, safeEqual, toKeys, } from './approval-crypto.js';
|
|
30
|
+
import { approvalRelay, relayMessage } from './approval-relay.js';
|
|
31
|
+
export { canonicalJson };
|
|
32
|
+
const TOKEN_PREFIX = 'afdap1';
|
|
33
|
+
const DEFAULT_TTL_MS = 5 * 60_000;
|
|
34
|
+
const MAX_TTL_MS = 24 * 60 * 60_000;
|
|
35
|
+
/** Longer evidence is rejected unread, so a caller cannot make the server hash megabytes. */
|
|
36
|
+
const MAX_TOKEN_LENGTH = 1024;
|
|
37
|
+
/**
|
|
38
|
+
* Create a middleware that runs a command whose `approval` policy requires approval only when
|
|
39
|
+
* `context.approval` holds a valid token for this command, input and actor. Otherwise it
|
|
40
|
+
* returns `APPROVAL_REQUIRED` with a fresh token, and the handler does not run.
|
|
41
|
+
*
|
|
42
|
+
* Install it after any middleware that sets or refines `context.actor` (such as auth), since
|
|
43
|
+
* tokens are bound to the actor. `context.approval` must only ever be set by trusted surface
|
|
44
|
+
* code once a human approved, never from tool arguments: whoever holds a token can use it.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```typescript
|
|
48
|
+
* const commands = [todoDelete, todoList];
|
|
49
|
+
* const server = createMcpServer({
|
|
50
|
+
* name: 'todo',
|
|
51
|
+
* version: '1.0.0',
|
|
52
|
+
* commands,
|
|
53
|
+
* middleware: [
|
|
54
|
+
* createApprovalMiddleware({ secret: process.env.AFD_APPROVAL_SECRET!, commands }),
|
|
55
|
+
* ],
|
|
56
|
+
* });
|
|
57
|
+
* ```
|
|
58
|
+
*
|
|
59
|
+
* @throws TypeError when no secret is given, a secret is shorter than 32 bytes, `ttlMs` is not
|
|
60
|
+
* a positive number, or a command declares an approval policy that is not valid
|
|
61
|
+
*/
|
|
62
|
+
export function createApprovalMiddleware(options) {
|
|
63
|
+
const keys = toKeys(options.secret);
|
|
64
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
65
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0 || ttlMs > MAX_TTL_MS) {
|
|
66
|
+
throw new TypeError('Approval ttlMs must be a positive number of milliseconds, at most 24 hours');
|
|
67
|
+
}
|
|
68
|
+
const clock = options.clock ?? systemClock;
|
|
69
|
+
const singleUse = (options.replay ?? 'single-use') === 'single-use';
|
|
70
|
+
const memoryStore = options.nonceStore ? undefined : createMemoryNonceStore();
|
|
71
|
+
const relayMode = options.relay ?? 'none';
|
|
72
|
+
if (relayMode !== 'none' && relayMode !== 'mcp-elicitation') {
|
|
73
|
+
throw new TypeError("Approval relay must be 'none' or 'mcp-elicitation'");
|
|
74
|
+
}
|
|
75
|
+
const commands = new Map();
|
|
76
|
+
for (const command of options.commands) {
|
|
77
|
+
const { approval } = command;
|
|
78
|
+
if (approval !== undefined &&
|
|
79
|
+
approval !== 'required' &&
|
|
80
|
+
approval !== 'not-required' &&
|
|
81
|
+
typeof approval !== 'function') {
|
|
82
|
+
throw new TypeError(`Command '${command.name}' has an invalid approval policy: use 'required', 'not-required' or a function`);
|
|
83
|
+
}
|
|
84
|
+
commands.set(command.name, command);
|
|
85
|
+
}
|
|
86
|
+
async function requiresApproval(command, input, context) {
|
|
87
|
+
const policy = command?.approval;
|
|
88
|
+
if (policy === undefined || policy === 'not-required')
|
|
89
|
+
return false;
|
|
90
|
+
if (policy === 'required')
|
|
91
|
+
return true;
|
|
92
|
+
const decide = policy;
|
|
93
|
+
// Fail closed: anything but an explicit 'not-required' holds the call.
|
|
94
|
+
return (await decide(input, context)) !== 'not-required';
|
|
95
|
+
}
|
|
96
|
+
function verify(evidence, commandName, input, actor, now) {
|
|
97
|
+
if (typeof evidence !== 'string' || evidence.length > MAX_TOKEN_LENGTH) {
|
|
98
|
+
return { ok: false, reason: 'malformed' };
|
|
99
|
+
}
|
|
100
|
+
const parts = evidence.split('.');
|
|
101
|
+
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX)
|
|
102
|
+
return { ok: false, reason: 'malformed' };
|
|
103
|
+
const [, encodedPayload = '', encodedMac = ''] = parts;
|
|
104
|
+
const signingInput = `${TOKEN_PREFIX}.${encodedPayload}`;
|
|
105
|
+
// Compare the encoded MACs, so that a token has exactly one valid spelling (base64url
|
|
106
|
+
// decoding ignores padding bits and stray characters). The key that signed the token
|
|
107
|
+
// also keyed its digests.
|
|
108
|
+
const mac = Buffer.from(encodedMac);
|
|
109
|
+
const key = keys.find((candidate) => safeEqual(mac, Buffer.from(hmac(candidate, signingInput).toString('base64url'))));
|
|
110
|
+
if (!key)
|
|
111
|
+
return { ok: false, reason: 'invalid-signature' };
|
|
112
|
+
const payload = parsePayload(encodedPayload);
|
|
113
|
+
if (!payload)
|
|
114
|
+
return { ok: false, reason: 'malformed' };
|
|
115
|
+
if (now >= payload.exp)
|
|
116
|
+
return { ok: false, reason: 'expired' };
|
|
117
|
+
if (!safeEqual(Buffer.from(payload.c), Buffer.from(commandName))) {
|
|
118
|
+
return { ok: false, reason: 'command-mismatch' };
|
|
119
|
+
}
|
|
120
|
+
if (!safeEqual(Buffer.from(payload.i, 'base64url'), digest(key, 'input', input))) {
|
|
121
|
+
return { ok: false, reason: 'input-mismatch' };
|
|
122
|
+
}
|
|
123
|
+
if (!safeEqual(Buffer.from(payload.a, 'base64url'), digest(key, 'actor', actor))) {
|
|
124
|
+
return { ok: false, reason: 'actor-mismatch' };
|
|
125
|
+
}
|
|
126
|
+
return { ok: true, nonce: payload.n, expiresAt: payload.exp };
|
|
127
|
+
}
|
|
128
|
+
function issue(commandName, input, actor, now) {
|
|
129
|
+
const key = keys[0];
|
|
130
|
+
return {
|
|
131
|
+
c: commandName,
|
|
132
|
+
i: digest(key, 'input', input).toString('base64url'),
|
|
133
|
+
a: digest(key, 'actor', actor).toString('base64url'),
|
|
134
|
+
iat: now,
|
|
135
|
+
exp: now + ttlMs,
|
|
136
|
+
n: randomBytes(16).toString('base64url'),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** The binding of a relayed approval, one per key: a keyed digest of the command, input and actor. */
|
|
140
|
+
function relayBindings(commandName, input, actor) {
|
|
141
|
+
return keys.map((key) => hmac(key, `relay\0${canonicalJson([commandName, input, actor])}`).toString('base64url'));
|
|
142
|
+
}
|
|
143
|
+
/** The MAC of a relayed approval's nonce and expiry, so the elicitation state cannot set them. */
|
|
144
|
+
function holdMac(key, binding, nonce, expiresAt) {
|
|
145
|
+
return hmac(key, `relay-hold\0${canonicalJson([binding, nonce, expiresAt])}`).toString('base64url');
|
|
146
|
+
}
|
|
147
|
+
/** Whether an accepted relayed approval is genuine, unexpired and (single-use) unspent. */
|
|
148
|
+
async function relayedApprovalHolds(answer, bindings, now) {
|
|
149
|
+
const key = keys[bindings.indexOf(answer.binding)];
|
|
150
|
+
if (!key)
|
|
151
|
+
return false;
|
|
152
|
+
const expected = Buffer.from(holdMac(key, answer.binding, answer.nonce, answer.expiresAt));
|
|
153
|
+
if (!safeEqual(Buffer.from(answer.mac), expected))
|
|
154
|
+
return false;
|
|
155
|
+
if (now >= answer.expiresAt || answer.expiresAt > now + ttlMs)
|
|
156
|
+
return false;
|
|
157
|
+
return spend(answer.nonce, answer.expiresAt, now);
|
|
158
|
+
}
|
|
159
|
+
/** Spend a single-use nonce; `true` when it was fresh (or reuse is allowed). */
|
|
160
|
+
async function spend(nonce, expiresAt, now) {
|
|
161
|
+
if (!singleUse)
|
|
162
|
+
return true;
|
|
163
|
+
// Only an explicit `true` from the store counts as fresh.
|
|
164
|
+
return memoryStore
|
|
165
|
+
? memoryStore.consume(nonce, expiresAt, now)
|
|
166
|
+
: (await options.nonceStore?.consume(nonce, expiresAt)) === true;
|
|
167
|
+
}
|
|
168
|
+
function sign(payload) {
|
|
169
|
+
const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
|
170
|
+
const signingInput = `${TOKEN_PREFIX}.${encodedPayload}`;
|
|
171
|
+
return `${signingInput}.${hmac(keys[0], signingInput).toString('base64url')}`;
|
|
172
|
+
}
|
|
173
|
+
return async (commandName, input, context, next) => {
|
|
174
|
+
// Claimed only by the command the tool call routes to, once, gated or not, so a command
|
|
175
|
+
// that runs inside another (or after it) cannot turn the tool call into an elicitation.
|
|
176
|
+
const bound = relayMode === 'mcp-elicitation' ? approvalRelay(context) : undefined;
|
|
177
|
+
const relay = bound?.claim(commandName) ? bound : undefined;
|
|
178
|
+
const command = commands.get(commandName);
|
|
179
|
+
if (!(await requiresApproval(command, input, context)))
|
|
180
|
+
return next();
|
|
181
|
+
const now = clock.now();
|
|
182
|
+
const inputBinding = canonicalJson(input);
|
|
183
|
+
const actorBinding = actorJson(context.actor);
|
|
184
|
+
let rejected;
|
|
185
|
+
const directExchange = directApprovalExchange(context);
|
|
186
|
+
const evidence = directExchange ? takeDirectApproval(context) : context.approval;
|
|
187
|
+
if (evidence !== undefined) {
|
|
188
|
+
const verdict = verify(evidence, commandName, inputBinding, actorBinding, now);
|
|
189
|
+
if (verdict.ok) {
|
|
190
|
+
if (await spend(verdict.nonce, verdict.expiresAt, now))
|
|
191
|
+
return next();
|
|
192
|
+
rejected = 'already-used';
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
rejected = verdict.reason;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const summary = options.summarize?.(commandName, input, context) ||
|
|
199
|
+
command?.confirmPrompt ||
|
|
200
|
+
`Run ${commandName}`;
|
|
201
|
+
if (relay) {
|
|
202
|
+
const bindings = relayBindings(commandName, inputBinding, actorBinding);
|
|
203
|
+
const answer = await relay.answer(bindings);
|
|
204
|
+
if (answer.kind === 'decline') {
|
|
205
|
+
return failure({
|
|
206
|
+
code: ErrorCodes.APPROVAL_REQUIRED,
|
|
207
|
+
message: `The user did not approve ${commandName}`,
|
|
208
|
+
suggestion: 'Do not run this again without asking the user first; the user chose not to approve it.',
|
|
209
|
+
retryable: false,
|
|
210
|
+
details: { summary, reason: 'declined' },
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
if (answer.kind === 'accept' && (await relayedApprovalHolds(answer, bindings, now))) {
|
|
214
|
+
return next();
|
|
215
|
+
}
|
|
216
|
+
// An expired, spent or invalid approval is asked again, saying why.
|
|
217
|
+
const binding = bindings[0];
|
|
218
|
+
const nonce = randomBytes(16).toString('base64url');
|
|
219
|
+
const expiresAt = now + ttlMs;
|
|
220
|
+
relay.hold({
|
|
221
|
+
binding,
|
|
222
|
+
bindings,
|
|
223
|
+
nonce,
|
|
224
|
+
expiresAt,
|
|
225
|
+
mac: holdMac(keys[0], binding, nonce, expiresAt),
|
|
226
|
+
message: relayMessage(summary, commandName, inputBinding, answer.kind === 'accept'
|
|
227
|
+
? 'The earlier approval expired or was already used; approve again to run it.'
|
|
228
|
+
: undefined),
|
|
229
|
+
});
|
|
230
|
+
// The lane answers with the elicitation instead; this result is never sent.
|
|
231
|
+
return failure({
|
|
232
|
+
code: ErrorCodes.APPROVAL_REQUIRED,
|
|
233
|
+
message: `${commandName} needs approval before it runs`,
|
|
234
|
+
suggestion: `Wait for the user to approve "${summary}" in the client.`,
|
|
235
|
+
retryable: false,
|
|
236
|
+
details: { expiresAt: new Date(expiresAt).toISOString(), summary },
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
const payload = issue(commandName, inputBinding, actorBinding, now);
|
|
240
|
+
const approvalToken = sign(payload);
|
|
241
|
+
const expiresAt = new Date(payload.exp).toISOString();
|
|
242
|
+
const includeToken = !directExchange && (options.includeToken ?? context.interface !== 'mcp');
|
|
243
|
+
if (directExchange) {
|
|
244
|
+
holdDirectApproval(context, {
|
|
245
|
+
approvalToken,
|
|
246
|
+
expiresAt,
|
|
247
|
+
summary,
|
|
248
|
+
...(rejected && { reason: rejected }),
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
await options.onApprovalRequired?.({
|
|
252
|
+
command: commandName,
|
|
253
|
+
input,
|
|
254
|
+
...(context.actor && { actor: { ...context.actor } }),
|
|
255
|
+
approvalToken,
|
|
256
|
+
expiresAt,
|
|
257
|
+
summary,
|
|
258
|
+
...(rejected && { rejected }),
|
|
259
|
+
});
|
|
260
|
+
const why = rejected ? `The approval token was not accepted (${rejected}). ` : '';
|
|
261
|
+
// Addressed to whoever relays the decision: the token is the approval, so the gated
|
|
262
|
+
// caller must not resubmit it on its own, and tool arguments cannot carry it.
|
|
263
|
+
const retry = includeToken
|
|
264
|
+
? `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). The token expires at ${expiresAt}${singleUse ? ' and works once' : ''}.`
|
|
265
|
+
: bound
|
|
266
|
+
? `the client could not be asked from inside afd-batch, afd-pipe or another command. Call ${commandName} on its own so the client can ask the user.`
|
|
267
|
+
: relayMode === 'mcp-elicitation' && context.interface === 'mcp'
|
|
268
|
+
? `the client could not be asked here. Call ${commandName} from an MCP client that supports form elicitation, or the application records the approval and retries.`
|
|
269
|
+
: 'the application retries the same call once it has recorded the approval.';
|
|
270
|
+
return failure({
|
|
271
|
+
code: ErrorCodes.APPROVAL_REQUIRED,
|
|
272
|
+
message: `${commandName} needs approval before it runs`,
|
|
273
|
+
suggestion: `${why}Ask the user to approve "${summary}"; ${retry}`,
|
|
274
|
+
retryable: false,
|
|
275
|
+
details: {
|
|
276
|
+
...(includeToken && { approvalToken }),
|
|
277
|
+
expiresAt,
|
|
278
|
+
summary,
|
|
279
|
+
...(rejected && { reason: rejected }),
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function parsePayload(encoded) {
|
|
285
|
+
let value;
|
|
286
|
+
try {
|
|
287
|
+
value = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
return undefined;
|
|
291
|
+
}
|
|
292
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
293
|
+
return undefined;
|
|
294
|
+
const payload = value;
|
|
295
|
+
const strings = ['c', 'i', 'a', 'n'].every((field) => typeof payload[field] === 'string');
|
|
296
|
+
const times = ['iat', 'exp'].every((field) => Number.isFinite(payload[field]));
|
|
297
|
+
return strings && times ? payload : undefined;
|
|
298
|
+
}
|
|
299
|
+
//# sourceMappingURL=approval.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approval.js","sourceRoot":"","sources":["../src/approval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAS1C,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EACN,sBAAsB,EACtB,kBAAkB,EAClB,kBAAkB,GAClB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAEN,SAAS,EACT,aAAa,EACb,sBAAsB,EACtB,MAAM,EACN,IAAI,EACJ,SAAS,EACT,MAAM,GACN,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAuB,aAAa,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEvF,OAAO,EAAuB,aAAa,EAAE,CAAC;AAE9C,MAAM,YAAY,GAAG,QAAQ,CAAC;AAC9B,MAAM,cAAc,GAAG,CAAC,GAAG,MAAM,CAAC;AAClC,MAAM,UAAU,GAAG,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC;AACpC,6FAA6F;AAC7F,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAyI9B;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,wBAAwB,CAAC,OAAkC;IAC1E,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,cAAc,CAAC;IAC9C,IAAI,CAA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AAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAClF,MAAM,OAAO,GAAG,KAAgC,CAAC;IACjD,MAAM,OAAO,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,OAAO,CAAC,KAAK,CAAC,KAAK,QAAQ,CAAC,CAAC;IAC1F,MAAM,KAAK,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC/E,OAAO,OAAO,IAAI,KAAK,CAAC,CAAC,CAAE,OAAmC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC5E,CAAC"}
|
|
@@ -13,6 +13,12 @@ export interface ContextState {
|
|
|
13
13
|
stack: string[];
|
|
14
14
|
/** Maximum stack depth (default: 16). `afd-context-enter` fails once it is reached. */
|
|
15
15
|
maxDepth?: number;
|
|
16
|
+
/**
|
|
17
|
+
* `false` for the per-request state of a stateless MCP 2026-07-28 request: the active
|
|
18
|
+
* context comes from the request's `_meta["dev.afd/context"]`, and `afd-context-enter` and
|
|
19
|
+
* `afd-context-exit` validate but never change it. Omitted (persistent) otherwise.
|
|
20
|
+
*/
|
|
21
|
+
persistent?: boolean;
|
|
16
22
|
getActive(): string | null;
|
|
17
23
|
enter(name: string): void;
|
|
18
24
|
exit(): string | null;
|
|
@@ -25,7 +31,10 @@ export interface ContextState {
|
|
|
25
31
|
*/
|
|
26
32
|
export declare function createContextState(options?: {
|
|
27
33
|
maxDepth?: number;
|
|
34
|
+
persistent?: boolean;
|
|
28
35
|
}): ContextState;
|
|
36
|
+
/** `_meta` key that selects the active context of one MCP 2026-07-28 request. */
|
|
37
|
+
export declare const AFD_CONTEXT_META_KEY = "dev.afd/context";
|
|
29
38
|
declare const listInputSchema: z.ZodObject<{}, z.core.$strip>;
|
|
30
39
|
interface ContextInfo {
|
|
31
40
|
name: string;
|
|
@@ -47,6 +56,8 @@ declare const enterInputSchema: z.ZodObject<{
|
|
|
47
56
|
interface ContextEnterOutput {
|
|
48
57
|
entered: string;
|
|
49
58
|
previous: string | null;
|
|
59
|
+
/** `false` on a stateless request: nothing was stored, see the reasoning. */
|
|
60
|
+
persisted?: false;
|
|
50
61
|
}
|
|
51
62
|
/**
|
|
52
63
|
* Create the afd-context-enter bootstrap command.
|
|
@@ -56,6 +67,8 @@ declare const exitInputSchema: z.ZodObject<{}, z.core.$strip>;
|
|
|
56
67
|
interface ContextExitOutput {
|
|
57
68
|
exited: string | null;
|
|
58
69
|
current: string | null;
|
|
70
|
+
/** `false` on a stateless request: nothing was changed, see the reasoning. */
|
|
71
|
+
persisted?: false;
|
|
59
72
|
}
|
|
60
73
|
/**
|
|
61
74
|
* Create the afd-context-exit bootstrap command.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"afd-context.d.ts","sourceRoot":"","sources":["../../src/bootstrap/afd-context.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAiB,MAAM,sBAAsB,CAAC;AAE7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAMxD,gDAAgD;AAChD,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C,MAAM,WAAW,YAAY;IAC5B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,uFAAuF;IACvF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,IAAI,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,IAAI,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xB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CAC1C,WAAW,EAAE,MAAM,aAAa,EAAE,EAClC,YAAY,EAAE,YAAY,GACxB,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,EAAE,iBAAiB,CAAC,CAkCvE;AAMD,QAAA,MAAM,gBAAgB;;iBAEpB,CAAC;AAEH,UAAU,kBAAkB;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,6EAA6E;IAC7E,SAAS,CAAC,EAAE,KAAK,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,4BAA4B,CAC3C,WAAW,EAAE,MAAM,aAAa,EAAE,EAClC,YAAY,EAAE,YAAY,GACxB,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,EAAE,kBAAkB,CAAC,CA4DzE;AAMD,QAAA,MAAM,eAAe,gCAAe,CAAC;AAErC,UAAU,iBAAiB;IAC1B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,8EAA8E;IAC9E,SAAS,CAAC,EAAE,KAAK,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CAC1C,YAAY,EAAE,YAAY,GACxB,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,EAAE,iBAAiB,CAAC,CAkCvE"}
|
|
@@ -27,6 +27,7 @@ export function createContextState(options = {}) {
|
|
|
27
27
|
return {
|
|
28
28
|
stack,
|
|
29
29
|
maxDepth,
|
|
30
|
+
...(options.persistent === false && { persistent: false }),
|
|
30
31
|
getActive() {
|
|
31
32
|
return stack.length > 0 ? (stack[stack.length - 1] ?? null) : null;
|
|
32
33
|
},
|
|
@@ -48,9 +49,12 @@ function sessionRequired() {
|
|
|
48
49
|
return failure({
|
|
49
50
|
code: 'SESSION_REQUIRED',
|
|
50
51
|
message: 'Entering or exiting a context needs an MCP session, and this request has none',
|
|
51
|
-
suggestion: 'Send an MCP initialize request to /message and repeat its Mcp-Session-Id response header on later requests',
|
|
52
|
+
suggestion: 'Send an MCP initialize request to /message and repeat its Mcp-Session-Id response header on later requests, or use the stateless /mcp endpoint and send _meta["dev.afd/context"] on each request',
|
|
52
53
|
});
|
|
53
54
|
}
|
|
55
|
+
/** `_meta` key that selects the active context of one MCP 2026-07-28 request. */
|
|
56
|
+
export const AFD_CONTEXT_META_KEY = 'dev.afd/context';
|
|
57
|
+
const STATELESS_CONTEXT_HINT = `Context changes do not persist between stateless MCP requests. Send _meta["${AFD_CONTEXT_META_KEY}"] with the context name on each tools/list and tools/call request instead.`;
|
|
54
58
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
55
59
|
// afd-context-list
|
|
56
60
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -124,6 +128,9 @@ export function createAfdContextEnterCommand(getContexts, contextState) {
|
|
|
124
128
|
});
|
|
125
129
|
}
|
|
126
130
|
const previous = state.getActive();
|
|
131
|
+
if (state.persistent === false) {
|
|
132
|
+
return success({ entered: contextName, previous, persisted: false }, { reasoning: STATELESS_CONTEXT_HINT, confidence: 1.0 });
|
|
133
|
+
}
|
|
127
134
|
if (previous === contextName) {
|
|
128
135
|
return success({ entered: contextName, previous }, { reasoning: `Already in context '${contextName}'; nothing changed`, confidence: 1.0 });
|
|
129
136
|
}
|
|
@@ -163,6 +170,10 @@ export function createAfdContextExitCommand(contextState) {
|
|
|
163
170
|
const state = resolveContextState(context, contextState);
|
|
164
171
|
if (!state)
|
|
165
172
|
return sessionRequired();
|
|
173
|
+
if (state.persistent === false) {
|
|
174
|
+
const current = state.getActive();
|
|
175
|
+
return success({ exited: null, current, persisted: false }, { reasoning: STATELESS_CONTEXT_HINT, confidence: 1.0 });
|
|
176
|
+
}
|
|
166
177
|
const exited = state.exit();
|
|
167
178
|
const current = state.getActive();
|
|
168
179
|
return success({ exited, current }, {
|