@lushly-dev/afd-server 2.4.0 → 3.0.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 (279) hide show
  1. package/README.md +239 -56
  2. package/dist/admission.d.ts +137 -0
  3. package/dist/admission.d.ts.map +1 -0
  4. package/dist/admission.js +144 -0
  5. package/dist/admission.js.map +1 -0
  6. package/dist/app-call-registry.d.ts +31 -0
  7. package/dist/app-call-registry.d.ts.map +1 -0
  8. package/dist/app-call-registry.js +64 -0
  9. package/dist/app-call-registry.js.map +1 -0
  10. package/dist/approval-admission.d.ts +139 -0
  11. package/dist/approval-admission.d.ts.map +1 -0
  12. package/dist/approval-admission.js +252 -0
  13. package/dist/approval-admission.js.map +1 -0
  14. package/dist/approval-crypto.d.ts +37 -17
  15. package/dist/approval-crypto.d.ts.map +1 -1
  16. package/dist/approval-crypto.js +84 -75
  17. package/dist/approval-crypto.js.map +1 -1
  18. package/dist/approval-process-state.d.ts +21 -0
  19. package/dist/approval-process-state.d.ts.map +1 -0
  20. package/dist/approval-process-state.js +29 -0
  21. package/dist/approval-process-state.js.map +1 -0
  22. package/dist/approval-relay.d.ts +192 -9
  23. package/dist/approval-relay.d.ts.map +1 -1
  24. package/dist/approval-relay.js +45 -9
  25. package/dist/approval-relay.js.map +1 -1
  26. package/dist/approval-up-front.d.ts +40 -0
  27. package/dist/approval-up-front.d.ts.map +1 -0
  28. package/dist/approval-up-front.js +409 -0
  29. package/dist/approval-up-front.js.map +1 -0
  30. package/dist/approval.d.ts +65 -12
  31. package/dist/approval.d.ts.map +1 -1
  32. package/dist/approval.js +311 -47
  33. package/dist/approval.js.map +1 -1
  34. package/dist/approver.d.ts +84 -0
  35. package/dist/approver.d.ts.map +1 -0
  36. package/dist/approver.js +107 -0
  37. package/dist/approver.js.map +1 -0
  38. package/dist/auth-middleware-check.d.ts +23 -0
  39. package/dist/auth-middleware-check.d.ts.map +1 -0
  40. package/dist/auth-middleware-check.js +48 -0
  41. package/dist/auth-middleware-check.js.map +1 -0
  42. package/dist/bootstrap/afd-context.d.ts.map +1 -1
  43. package/dist/bootstrap/afd-context.js +27 -3
  44. package/dist/bootstrap/afd-context.js.map +1 -1
  45. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  46. package/dist/bootstrap/afd-docs.js +4 -0
  47. package/dist/bootstrap/afd-docs.js.map +1 -1
  48. package/dist/bootstrap/afd-help.d.ts +4 -1
  49. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  50. package/dist/bootstrap/afd-help.js +19 -4
  51. package/dist/bootstrap/afd-help.js.map +1 -1
  52. package/dist/bootstrap/described-command.d.ts +3 -1
  53. package/dist/bootstrap/described-command.d.ts.map +1 -1
  54. package/dist/bootstrap/described-command.js.map +1 -1
  55. package/dist/command-allow.d.ts +4 -4
  56. package/dist/command-allow.d.ts.map +1 -1
  57. package/dist/command-allow.js +10 -15
  58. package/dist/command-allow.js.map +1 -1
  59. package/dist/command-routing.d.ts +56 -8
  60. package/dist/command-routing.d.ts.map +1 -1
  61. package/dist/command-routing.js +82 -16
  62. package/dist/command-routing.js.map +1 -1
  63. package/dist/command-timeout.d.ts +17 -0
  64. package/dist/command-timeout.d.ts.map +1 -0
  65. package/dist/command-timeout.js +99 -0
  66. package/dist/command-timeout.js.map +1 -0
  67. package/dist/confirmation-gate.d.ts +7 -7
  68. package/dist/confirmation-gate.d.ts.map +1 -1
  69. package/dist/confirmation-gate.js +26 -12
  70. package/dist/confirmation-gate.js.map +1 -1
  71. package/dist/confirmations.d.ts +28 -3
  72. package/dist/confirmations.d.ts.map +1 -1
  73. package/dist/confirmations.js +6 -7
  74. package/dist/confirmations.js.map +1 -1
  75. package/dist/context-fields.d.ts +16 -1
  76. package/dist/context-fields.d.ts.map +1 -1
  77. package/dist/context-fields.js +30 -13
  78. package/dist/context-fields.js.map +1 -1
  79. package/dist/context-scope.d.ts +3 -3
  80. package/dist/context-scope.d.ts.map +1 -1
  81. package/dist/context-scope.js +7 -8
  82. package/dist/context-scope.js.map +1 -1
  83. package/dist/define-core.d.ts +63 -1
  84. package/dist/define-core.d.ts.map +1 -1
  85. package/dist/define-core.js +27 -4
  86. package/dist/define-core.js.map +1 -1
  87. package/dist/define.d.ts +4 -3
  88. package/dist/define.d.ts.map +1 -1
  89. package/dist/define.js +1 -1
  90. package/dist/define.js.map +1 -1
  91. package/dist/direct-registry.d.ts +54 -8
  92. package/dist/direct-registry.d.ts.map +1 -1
  93. package/dist/direct-registry.js +64 -8
  94. package/dist/direct-registry.js.map +1 -1
  95. package/dist/direct-tool-surface.d.ts +1 -1
  96. package/dist/direct-tool-surface.d.ts.map +1 -1
  97. package/dist/direct-tool-surface.js +28 -6
  98. package/dist/direct-tool-surface.js.map +1 -1
  99. package/dist/direct.d.ts +6 -2
  100. package/dist/direct.d.ts.map +1 -1
  101. package/dist/direct.js +4 -1
  102. package/dist/direct.js.map +1 -1
  103. package/dist/elicitation-state.d.ts +5 -1
  104. package/dist/elicitation-state.d.ts.map +1 -1
  105. package/dist/elicitation-state.js +4 -1
  106. package/dist/elicitation-state.js.map +1 -1
  107. package/dist/execution.d.ts +52 -6
  108. package/dist/execution.d.ts.map +1 -1
  109. package/dist/execution.js +183 -19
  110. package/dist/execution.js.map +1 -1
  111. package/dist/host-state.d.ts +81 -0
  112. package/dist/host-state.d.ts.map +1 -0
  113. package/dist/host-state.js +62 -0
  114. package/dist/host-state.js.map +1 -0
  115. package/dist/http-handler.d.ts +48 -11
  116. package/dist/http-handler.d.ts.map +1 -1
  117. package/dist/http-handler.js +207 -58
  118. package/dist/http-handler.js.map +1 -1
  119. package/dist/http-security.d.ts +14 -1
  120. package/dist/http-security.d.ts.map +1 -1
  121. package/dist/http-security.js +79 -17
  122. package/dist/http-security.js.map +1 -1
  123. package/dist/http-sessions.d.ts +45 -5
  124. package/dist/http-sessions.d.ts.map +1 -1
  125. package/dist/http-sessions.js +52 -10
  126. package/dist/http-sessions.js.map +1 -1
  127. package/dist/http-sse.d.ts +9 -0
  128. package/dist/http-sse.d.ts.map +1 -1
  129. package/dist/http-sse.js +12 -3
  130. package/dist/http-sse.js.map +1 -1
  131. package/dist/human-relay.d.ts +195 -0
  132. package/dist/human-relay.d.ts.map +1 -0
  133. package/dist/human-relay.js +670 -0
  134. package/dist/human-relay.js.map +1 -0
  135. package/dist/idempotency-step.d.ts +231 -0
  136. package/dist/idempotency-step.d.ts.map +1 -0
  137. package/dist/idempotency-step.js +389 -0
  138. package/dist/idempotency-step.js.map +1 -0
  139. package/dist/idempotency-store.d.ts +107 -0
  140. package/dist/idempotency-store.d.ts.map +1 -0
  141. package/dist/idempotency-store.js +100 -0
  142. package/dist/idempotency-store.js.map +1 -0
  143. package/dist/index.d.ts +18 -8
  144. package/dist/index.d.ts.map +1 -1
  145. package/dist/index.js +15 -4
  146. package/dist/index.js.map +1 -1
  147. package/dist/instance-state.d.ts +53 -0
  148. package/dist/instance-state.d.ts.map +1 -0
  149. package/dist/instance-state.js +94 -0
  150. package/dist/instance-state.js.map +1 -0
  151. package/dist/journal-off-tape.d.ts +52 -0
  152. package/dist/journal-off-tape.d.ts.map +1 -0
  153. package/dist/journal-off-tape.js +150 -0
  154. package/dist/journal-off-tape.js.map +1 -0
  155. package/dist/journal-replay.d.ts.map +1 -1
  156. package/dist/journal-replay.js +48 -3
  157. package/dist/journal-replay.js.map +1 -1
  158. package/dist/journal-view.d.ts +50 -0
  159. package/dist/journal-view.d.ts.map +1 -0
  160. package/dist/journal-view.js +214 -0
  161. package/dist/journal-view.js.map +1 -0
  162. package/dist/journal.d.ts +34 -6
  163. package/dist/journal.d.ts.map +1 -1
  164. package/dist/journal.js +183 -47
  165. package/dist/journal.js.map +1 -1
  166. package/dist/json-rpc.d.ts +3 -2
  167. package/dist/json-rpc.d.ts.map +1 -1
  168. package/dist/json-rpc.js +5 -3
  169. package/dist/json-rpc.js.map +1 -1
  170. package/dist/lazy-tools.d.ts +27 -2
  171. package/dist/lazy-tools.d.ts.map +1 -1
  172. package/dist/lazy-tools.js +22 -4
  173. package/dist/lazy-tools.js.map +1 -1
  174. package/dist/mcp-auth-bearer.d.ts +2 -0
  175. package/dist/mcp-auth-bearer.d.ts.map +1 -1
  176. package/dist/mcp-auth-bearer.js +1 -1
  177. package/dist/mcp-auth-bearer.js.map +1 -1
  178. package/dist/mcp-auth-dispatch.d.ts +38 -0
  179. package/dist/mcp-auth-dispatch.d.ts.map +1 -0
  180. package/dist/mcp-auth-dispatch.js +113 -0
  181. package/dist/mcp-auth-dispatch.js.map +1 -0
  182. package/dist/mcp-auth-jwt.d.ts +3 -2
  183. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  184. package/dist/mcp-auth-jwt.js.map +1 -1
  185. package/dist/mcp-auth-resource.d.ts +6 -2
  186. package/dist/mcp-auth-resource.d.ts.map +1 -1
  187. package/dist/mcp-auth-resource.js +6 -5
  188. package/dist/mcp-auth-resource.js.map +1 -1
  189. package/dist/mcp-auth-scopes.d.ts +84 -0
  190. package/dist/mcp-auth-scopes.d.ts.map +1 -0
  191. package/dist/mcp-auth-scopes.js +125 -0
  192. package/dist/mcp-auth-scopes.js.map +1 -0
  193. package/dist/mcp-auth-view.d.ts +50 -0
  194. package/dist/mcp-auth-view.d.ts.map +1 -0
  195. package/dist/mcp-auth-view.js +179 -0
  196. package/dist/mcp-auth-view.js.map +1 -0
  197. package/dist/mcp-auth.d.ts +94 -3
  198. package/dist/mcp-auth.d.ts.map +1 -1
  199. package/dist/mcp-auth.js +241 -23
  200. package/dist/mcp-auth.js.map +1 -1
  201. package/dist/mcp-modern.d.ts +80 -6
  202. package/dist/mcp-modern.d.ts.map +1 -1
  203. package/dist/mcp-modern.js +378 -91
  204. package/dist/mcp-modern.js.map +1 -1
  205. package/dist/meta-argument.d.ts +9 -8
  206. package/dist/meta-argument.d.ts.map +1 -1
  207. package/dist/meta-argument.js +28 -10
  208. package/dist/meta-argument.js.map +1 -1
  209. package/dist/meta-tools.js +2 -2
  210. package/dist/meta-tools.js.map +1 -1
  211. package/dist/middleware.d.ts +16 -1
  212. package/dist/middleware.d.ts.map +1 -1
  213. package/dist/middleware.js +57 -10
  214. package/dist/middleware.js.map +1 -1
  215. package/dist/output-budget.d.ts +77 -0
  216. package/dist/output-budget.d.ts.map +1 -0
  217. package/dist/output-budget.js +202 -0
  218. package/dist/output-budget.js.map +1 -0
  219. package/dist/principal-binding.js +1 -1
  220. package/dist/principal-binding.js.map +1 -1
  221. package/dist/relay-evidence.d.ts +74 -0
  222. package/dist/relay-evidence.d.ts.map +1 -0
  223. package/dist/relay-evidence.js +143 -0
  224. package/dist/relay-evidence.js.map +1 -0
  225. package/dist/resources.d.ts +35 -10
  226. package/dist/resources.d.ts.map +1 -1
  227. package/dist/resources.js +59 -18
  228. package/dist/resources.js.map +1 -1
  229. package/dist/schema.d.ts +4 -3
  230. package/dist/schema.d.ts.map +1 -1
  231. package/dist/schema.js +3 -3
  232. package/dist/schema.js.map +1 -1
  233. package/dist/scope-view.d.ts +65 -0
  234. package/dist/scope-view.d.ts.map +1 -0
  235. package/dist/scope-view.js +45 -0
  236. package/dist/scope-view.js.map +1 -0
  237. package/dist/server-types.d.ts +182 -27
  238. package/dist/server-types.d.ts.map +1 -1
  239. package/dist/server-types.js.map +1 -1
  240. package/dist/server.d.ts +26 -0
  241. package/dist/server.d.ts.map +1 -1
  242. package/dist/server.js +403 -61
  243. package/dist/server.js.map +1 -1
  244. package/dist/skills.d.ts.map +1 -1
  245. package/dist/skills.js +99 -3
  246. package/dist/skills.js.map +1 -1
  247. package/dist/task-dispatch.d.ts +35 -0
  248. package/dist/task-dispatch.d.ts.map +1 -0
  249. package/dist/task-dispatch.js +25 -0
  250. package/dist/task-dispatch.js.map +1 -0
  251. package/dist/tasks-runtime.d.ts +115 -0
  252. package/dist/tasks-runtime.d.ts.map +1 -0
  253. package/dist/tasks-runtime.js +760 -0
  254. package/dist/tasks-runtime.js.map +1 -0
  255. package/dist/tasks.d.ts +237 -0
  256. package/dist/tasks.d.ts.map +1 -0
  257. package/dist/tasks.js +321 -0
  258. package/dist/tasks.js.map +1 -0
  259. package/dist/tool-router.d.ts +68 -3
  260. package/dist/tool-router.d.ts.map +1 -1
  261. package/dist/tool-router.js +293 -70
  262. package/dist/tool-router.js.map +1 -1
  263. package/dist/tools.d.ts +32 -0
  264. package/dist/tools.d.ts.map +1 -1
  265. package/dist/tools.js +162 -55
  266. package/dist/tools.js.map +1 -1
  267. package/dist/up-front-steps.d.ts +35 -0
  268. package/dist/up-front-steps.d.ts.map +1 -0
  269. package/dist/up-front-steps.js +159 -0
  270. package/dist/up-front-steps.js.map +1 -0
  271. package/dist/validation.d.ts +38 -3
  272. package/dist/validation.d.ts.map +1 -1
  273. package/dist/validation.js +118 -23
  274. package/dist/validation.js.map +1 -1
  275. package/dist/verified-credentials.d.ts +13 -5
  276. package/dist/verified-credentials.d.ts.map +1 -1
  277. package/dist/verified-credentials.js +43 -10
  278. package/dist/verified-credentials.js.map +1 -1
  279. package/package.json +15 -11
@@ -18,22 +18,30 @@
18
18
  */
19
19
  import { AsyncLocalStorage } from 'node:async_hooks';
20
20
  import { randomBytes } from 'node:crypto';
21
- import { failure } from '@lushly-dev/afd-core';
21
+ import { AFD_CONTRACT_META_KEY, buildServerContract, failure, TS_SUPPORTED_PROFILES, } from '@lushly-dev/afd-core';
22
22
  import { toNodeHandler } from '@modelcontextprotocol/node';
23
23
  import { CLIENT_CAPABILITIES_META_KEY, createMcpHandler, createRequestStateCodec, inputRequired, inputResponse, ProtocolError, ProtocolErrorCode, Server, } from '@modelcontextprotocol/server';
24
24
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
25
+ import { createAdmission } from './admission.js';
25
26
  import { APPROVAL_INPUT_KEY, APPROVAL_REQUESTED_SCHEMA, bindApprovalRelay, } from './approval-relay.js';
27
+ import { createUpFrontApproval } from './approval-up-front.js';
28
+ import { approvalKeyInInput } from './approver.js';
26
29
  import { AFD_CONTEXT_META_KEY, createContextState, } from './bootstrap/afd-context.js';
27
30
  import { AFD_CONFIRM_META_KEY, bindConfirmationChannel, CONFIRM_INPUT_KEY, CONFIRM_REQUESTED_SCHEMA, InputRequiredSignal, } from './confirmations.js';
28
- import { AFD_CONTEXT_FIELDS_META_KEY, contextFieldValues, } from './context-fields.js';
31
+ import { AFD_CONTEXT_FIELDS_META_KEY } from './context-fields.js';
29
32
  import { describeContextFields } from './context-fields-describe.js';
30
33
  import { bindContextState } from './context-scope.js';
31
34
  import { ANSWER_TTL_SECONDS, isRoundState, } from './elicitation-state.js';
32
- import { liftMetaArgument, metaArgumentKeys } from './meta-argument.js';
35
+ import { prereadBody } from './http-security.js';
36
+ import { bindHumanRelayChannel, RELAY_INPUT_KEY } from './human-relay.js';
33
37
  import { principalBinding } from './principal-binding.js';
34
38
  import { requestContextValues } from './request-context.js';
35
39
  import { resourceCacheHints } from './resources.js';
36
- import { resultContent } from './tool-router.js';
40
+ import { bindScopeView } from './scope-view.js';
41
+ import { bindTaskDispatch } from './task-dispatch.js';
42
+ import { TASKS_EXTENSION_ID } from './tasks.js';
43
+ import { CreateTaskSignal, patchToolsCallForTasks } from './tasks-runtime.js';
44
+ import { asToolRouter, resultContent, toolResultOf, } from './tool-router.js';
37
45
  /** The MCP protocol revision this lane serves statelessly. */
38
46
  export const MODERN_PROTOCOL_VERSION = '2026-07-28';
39
47
  /**
@@ -57,10 +65,6 @@ function reporter(onError) {
57
65
  function isRecord(value) {
58
66
  return !!value && typeof value === 'object' && !Array.isArray(value);
59
67
  }
60
- /** A shallow copy of a plain object; anything else as it is. */
61
- function shallowCopy(value) {
62
- return isRecord(value) ? { ...value } : value;
63
- }
64
68
  /**
65
69
  * Whether declared client capabilities allow a form elicitation: `elicitation: {}` means form
66
70
  * only; otherwise `form` must be listed.
@@ -76,7 +80,7 @@ function allowsFormElicitation(capabilities) {
76
80
  */
77
81
  export function defaultInstructions(options) {
78
82
  const lines = [
79
- `${options.name} is an AFD server. Every tool returns a CommandResult as JSON text: { success, data, error: { code, message, suggestion } }; follow error.suggestion to recover.`,
83
+ `${options.name} is an AFD server. Every tool returns a CommandResult as JSON text: { success, data, error: { code, message, suggestion, recovery } }; follow error.suggestion to recover. When error.recovery is present, it is the same step in a form a program can follow.`,
80
84
  ];
81
85
  if (options.toolStrategy === 'lazy') {
82
86
  lines.push('Call afd-discover to find commands, afd-detail for a command schema, and afd-call to run one.');
@@ -99,20 +103,168 @@ export function defaultInstructions(options) {
99
103
  return lines.join(' ');
100
104
  }
101
105
  /**
102
- * Create the server factory both entries share. It runs once per HTTP request, and once per
103
- * stdio connection (plus a discarded `server/discover` probe instance).
106
+ * Refuse a `tools/call` whose arguments hold `dev.afd/approval` as the transport delivers it,
107
+ * before the SDK validates the request ("Approval evidence from an approver client", rule 5).
108
+ * The SDK's validation rebuilds `arguments` and drops a member named `__proto__`, so a key
109
+ * beneath one would never reach the router's own check: it would vanish instead of being refused.
104
110
  */
105
- function createServerFactory(deps, options) {
106
- const report = reporter(deps.onError);
107
- const contextNames = new Set((deps.contexts ?? []).map((context) => context.name));
111
+ export function refuseApprovalKeyBeforeParsing(server, modern, report) {
112
+ if (typeof server.connect !== 'function') {
113
+ throw new Error('@modelcontextprotocol/server Server.connect is missing; refuseApprovalKeyBeforeParsing requires it (#1744)');
114
+ }
115
+ const connect = server.connect.bind(server);
116
+ server.connect = async (transport) => {
117
+ await connect(transport);
118
+ const deliver = transport.onmessage;
119
+ if (typeof deliver !== 'function') {
120
+ throw new Error('@modelcontextprotocol/server Server.connect did not install transport.onmessage; refuseApprovalKeyBeforeParsing cannot intercept pre-parse arguments (#1744)');
121
+ }
122
+ transport.onmessage = (message, extra) => {
123
+ const request = message;
124
+ const refusal = request.method === 'tools/call' && request.id !== undefined
125
+ ? approvalKeyInInput(request.params?.arguments)
126
+ : undefined;
127
+ if (!refusal)
128
+ return deliver(message, extra);
129
+ transport
130
+ .send({
131
+ jsonrpc: '2.0',
132
+ id: request.id,
133
+ result: {
134
+ ...resultContent(failure(refusal), true),
135
+ ...(modern && { resultType: 'complete' }),
136
+ },
137
+ })
138
+ .catch(report);
139
+ };
140
+ };
141
+ }
142
+ /**
143
+ * Compute the `_meta["dev.afd/contract"]` advertisement for a server lane
144
+ * (`spec/tool-strategies.md#contract-advertisement`, #1927).
145
+ */
146
+ export function serverContractFor(deps, isHttp, authActive = false) {
147
+ const active = {};
148
+ const add = (id) => {
149
+ const ver = TS_SUPPORTED_PROFILES[id];
150
+ if (ver)
151
+ active[id] = ver;
152
+ };
153
+ // Always-on profiles supported in full by TypeScript.
154
+ add('app-calls');
155
+ add('output-budgets');
156
+ add('streaming');
157
+ // Opt-in profiles active on this server instance.
158
+ if (deps.hasApprovals)
159
+ add('approvals');
160
+ if (isHttp && (deps.authConfigured || authActive))
161
+ add('authorization');
162
+ if (deps.hasConfirmations)
163
+ add('confirmations');
164
+ if (deps.contexts?.length)
165
+ add('contexts');
166
+ if (isHttp)
167
+ add('http');
168
+ if (deps.hasIdempotency)
169
+ add('idempotency');
170
+ if (deps.hasJournal)
171
+ add('journal');
172
+ if (deps.resources)
173
+ add('resources-and-skills');
174
+ if (deps.tasks?.declaresTasksTo(isHttp) === true)
175
+ add('tasks');
176
+ return buildServerContract(active);
177
+ }
178
+ /**
179
+ * Wrap the SDK's private `server._ondiscover()` and `server._oninitialize()` so both
180
+ * `server/discover` (2026-07-28) and `InitializeResult` (2025) carry
181
+ * `_meta["dev.afd/contract"]` (`spec/tool-strategies.md#contract-advertisement`, #1927).
182
+ */
183
+ export function wrapServerContract(server, contract) {
184
+ const sdk = server;
185
+ if (typeof sdk._ondiscover !== 'function') {
186
+ throw new Error('@modelcontextprotocol/server Server._ondiscover is missing; contract advertisement requires it (#1927)');
187
+ }
188
+ if (typeof sdk._oninitialize !== 'function') {
189
+ throw new Error('@modelcontextprotocol/server Server._oninitialize is missing; contract advertisement requires it (#1927)');
190
+ }
191
+ const discover = sdk._ondiscover.bind(server);
192
+ sdk._ondiscover = () => {
193
+ const result = discover();
194
+ const meta = result._meta && typeof result._meta === 'object' ? result._meta : {};
195
+ return { ...result, _meta: { ...meta, [AFD_CONTRACT_META_KEY]: contract } };
196
+ };
197
+ const initialize = sdk._oninitialize.bind(server);
198
+ sdk._oninitialize = async (request) => {
199
+ const result = await initialize(request);
200
+ const meta = result._meta && typeof result._meta === 'object' ? result._meta : {};
201
+ return { ...result, _meta: { ...meta, [AFD_CONTRACT_META_KEY]: contract } };
202
+ };
203
+ }
204
+ /**
205
+ * Wrap the SDK's private `server._ondiscover()` so `server/discover` advertises AFD's declared
206
+ * context fields in `_meta["dev.afd/contextFields"]`.
207
+ */
208
+ export function wrapServerDiscover(server, fields) {
209
+ // The SDK's serving layer installs its own `server/discover` handler, which calls
210
+ // `_ondiscover()` per request; wrapping it adds the declared fields to that answer.
211
+ // `mcp-sdk-guards.test.ts` and `context-fields-mcp.test.ts` fail if an SDK upgrade changes this.
212
+ const sdk = server;
213
+ if (typeof sdk._ondiscover !== 'function') {
214
+ throw new Error('@modelcontextprotocol/server Server._ondiscover is missing; contextFields discovery requires it (#1744)');
215
+ }
216
+ const discover = sdk._ondiscover.bind(server);
217
+ sdk._ondiscover = () => {
218
+ const result = discover();
219
+ const meta = result._meta && typeof result._meta === 'object' ? result._meta : {};
220
+ return { ...result, _meta: { ...meta, [AFD_CONTEXT_FIELDS_META_KEY]: fields } };
221
+ };
222
+ }
223
+ /**
224
+ * The freshness hint of `tools/list` and `server/discover`, defaults applied.
225
+ *
226
+ * @throws Error when `toolsListTtlMs` is not a non-negative integer
227
+ */
228
+ export function resolveToolsListTtlMs(deps) {
108
229
  // With contexts, tools/list varies by `_meta["dev.afd/context"]`, which SDK clients leave
109
- // out of their cache key, so the default is "always stale" there. The hybrid list does not
110
- // vary by context (spec/tool-strategies.md, H6).
111
- const listVariesByContext = Boolean(deps.contexts?.length) && deps.toolStrategy !== 'hybrid';
230
+ // out of their cache key, so the default is "always stale" there. The hybrid and lazy lists
231
+ // do not vary by context (spec/tool-strategies.md, H6 and "lazy").
232
+ const listVariesByContext = Boolean(deps.contexts?.length) &&
233
+ deps.toolStrategy !== 'hybrid' &&
234
+ deps.toolStrategy !== 'lazy';
112
235
  const ttlMs = deps.toolsListTtlMs ?? (listVariesByContext ? 0 : DEFAULT_TOOLS_LIST_TTL_MS);
113
236
  if (!Number.isSafeInteger(ttlMs) || ttlMs < 0) {
114
237
  throw new Error('toolsListTtlMs must be a non-negative integer');
115
238
  }
239
+ return ttlMs;
240
+ }
241
+ /**
242
+ * The SDK's own check of the `/mcp` body limit (`createMcpHandler`'s `maxRequestBodySize`, the
243
+ * first the lane's options meet), made without building the lane, so stdio refuses what HTTP
244
+ * would with the same error. `stdio-runtime.test.ts` calls the SDK's check beside it and fails if
245
+ * an SDK upgrade changes it.
246
+ *
247
+ * @throws RangeError when `maxBodyBytes` is not a positive number
248
+ */
249
+ export function checkModernBodyLimit(maxBodyBytes) {
250
+ if (typeof maxBodyBytes !== 'number' || !Number.isFinite(maxBodyBytes) || maxBodyBytes <= 0) {
251
+ throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(maxBodyBytes)}`);
252
+ }
253
+ }
254
+ /**
255
+ * Create the server factory both entries share. It runs once per HTTP request, and once per
256
+ * stdio connection (plus a discarded `server/discover` probe instance).
257
+ *
258
+ * The SDK needs a new `Server` for each exchange: `createMcpHandler` refuses an instance still
259
+ * serving another request, and binds the request's era, protocol revision and client identity
260
+ * to the instance. So the factory builds one per call, and everything that does not depend on
261
+ * the request is built once per server (#1746): capabilities and cache hints for each era here,
262
+ * and the described context fields at the first call that needs them.
263
+ */
264
+ function createServerFactory(deps, options) {
265
+ const report = reporter(deps.onError);
266
+ const contextNames = new Set((deps.contexts ?? []).map((context) => context.name));
267
+ const ttlMs = resolveToolsListTtlMs(deps);
116
268
  /**
117
269
  * The context state of one request: `undefined` without contexts; the connection's stack
118
270
  * on legacy stdio; `null` on legacy HTTP (no session); otherwise a per-request state with
@@ -133,7 +285,18 @@ function createServerFactory(deps, options) {
133
285
  state.enter(requested);
134
286
  return state;
135
287
  }
136
- const metaKeys = metaArgumentKeys(deps.contextFields);
288
+ const admission = createAdmission({
289
+ router: asToolRouter(deps.routeToolCall),
290
+ contextFields: deps.contextFields,
291
+ approver: deps.approver,
292
+ actor: deps.actor,
293
+ identifiesHttpCaller: deps.identifiesHttpCaller,
294
+ });
295
+ /**
296
+ * How this lane tells callers apart (`spec/idempotency.md`, S3): over HTTP, by what the server
297
+ * knows of each request; over stdio, by this connection, which each factory serves alone.
298
+ */
299
+ const transport = (options.requestValues !== undefined ? { kind: 'http' } : { kind: 'connection', connection: {} });
137
300
  function scoped(context, state) {
138
301
  return state === undefined ? context : bindContextState(context, state);
139
302
  }
@@ -203,20 +366,25 @@ function createServerFactory(deps, options) {
203
366
  })();
204
367
  return answers;
205
368
  };
206
- const ask = async (question, message, requestedSchema, replaces = [question.b]) => {
369
+ /**
370
+ * Ask `questions` with one form elicitation under their shared input key: one answer
371
+ * covers them all. Earlier answers to the same questions (`replaces`, their bindings under
372
+ * every key: an expired or spent approval) are dropped, so the new answer is the only one.
373
+ */
374
+ const askAll = async (questions, message, requestedSchema, replaces) => {
207
375
  const { accepted } = await read();
208
- // Earlier answers to the same question (an expired or spent approval, under any key)
209
- // are dropped, so the new answer is the only one.
210
- const kept = accepted.filter((item) => item.k !== question.k || !replaces.includes(item.b));
211
- const asked = { ...question, t: Date.now() + ANSWER_TTL_SECONDS * 1000 };
376
+ const key = questions[0].k;
377
+ const kept = accepted.filter((item) => item.k !== key || !replaces.includes(item.b));
378
+ const t = Date.now() + ANSWER_TTL_SECONDS * 1000;
212
379
  return inputRequired({
213
380
  inputRequests: {
214
- [asked.k]: inputRequired.elicit({ message, requestedSchema: requestedSchema }),
381
+ [key]: inputRequired.elicit({ message, requestedSchema: requestedSchema }),
215
382
  },
216
- requestState: await stateCodec.mint({ p: [asked], a: kept }, ctx),
383
+ requestState: await stateCodec.mint({ p: questions.map((question) => ({ ...question, t })), a: kept }, ctx),
217
384
  });
218
385
  };
219
- return { read, ask };
386
+ const ask = (question, message, requestedSchema, replaces = [question.b]) => askAll([question], message, requestedSchema, replaces);
387
+ return { read, ask, askAll };
220
388
  }
221
389
  /**
222
390
  * Whether one `tools/call` can carry a form elicitation. A modern request can when it declares
@@ -244,7 +412,10 @@ function createServerFactory(deps, options) {
244
412
  request: (message, binding) => round.ask({ k: CONFIRM_INPUT_KEY, b: binding }, message, CONFIRM_REQUESTED_SCHEMA),
245
413
  };
246
414
  }
247
- /** The approval relay of one `tools/call` that can elicit, and the hold recorded on it. */
415
+ /**
416
+ * The approval relay of one `tools/call` that can elicit, and the hold recorded on it: one
417
+ * command's, or every gated step's of an `afd-batch` or `afd-pipe` asked up front.
418
+ */
248
419
  function approvalRelayFor(round) {
249
420
  let routed;
250
421
  let claimed = false;
@@ -270,9 +441,36 @@ function createServerFactory(deps, options) {
270
441
  ? { kind: 'accept', binding: match.b, nonce: match.n, expiresAt: match.x, mac: match.m }
271
442
  : { kind: 'missing' };
272
443
  },
273
- hold(hold) {
274
- held ??= hold;
444
+ hold({ message, ...question }) {
445
+ held ??= { questions: [question], message };
275
446
  },
447
+ async answers() {
448
+ const { accepted, declined } = await round.read();
449
+ const approval = (item) => item.k === APPROVAL_INPUT_KEY;
450
+ return {
451
+ accepted: accepted.filter(approval).flatMap((item) => item.n !== undefined && item.x !== undefined && item.m !== undefined
452
+ ? [
453
+ {
454
+ binding: item.b,
455
+ nonce: item.n,
456
+ expiresAt: item.x,
457
+ mac: item.m,
458
+ ...(item.s !== undefined &&
459
+ item.i !== undefined &&
460
+ item.c !== undefined && {
461
+ step: { index: item.s, input: item.i, call: item.c },
462
+ }),
463
+ },
464
+ ]
465
+ : []),
466
+ declined: declined.filter(approval).map((item) => item.b),
467
+ };
468
+ },
469
+ holdSteps(hold) {
470
+ if (hold.questions.length > 0)
471
+ held ??= hold;
472
+ },
473
+ upFront: (tool, request, commands) => createUpFrontApproval(relay, tool, request, commands),
276
474
  };
277
475
  return { relay, held: () => held };
278
476
  }
@@ -280,95 +478,178 @@ function createServerFactory(deps, options) {
280
478
  report(error);
281
479
  return new ProtocolError(ProtocolErrorCode.InternalError, deps.devMode && error instanceof Error ? error.message : 'Internal error');
282
480
  }
481
+ const isHttp = options.requestValues !== undefined;
482
+ const authConfigured = deps.authConfigured === true || options.requireView === true;
483
+ const resourceCaps = deps.resources?.capabilities;
484
+ /** The capabilities of an exchange in `era`: only a modern one may declare MCP Tasks. */
485
+ const capabilitiesFor = (era) => {
486
+ const declaresTasks = era === 'modern' && deps.tasks?.declaresTasksTo(isHttp) === true;
487
+ const extensions = {
488
+ ...(resourceCaps?.extensions ?? {}),
489
+ ...(declaresTasks ? { [TASKS_EXTENSION_ID]: {} } : {}),
490
+ };
491
+ return {
492
+ tools: { listChanged: false },
493
+ ...resourceCaps,
494
+ ...(Object.keys(extensions).length > 0 && { extensions }),
495
+ };
496
+ };
497
+ // The SDK copies these before changing them, so every instance can be given the same objects.
498
+ const capabilities = {
499
+ modern: capabilitiesFor('modern'),
500
+ legacy: capabilitiesFor('legacy'),
501
+ };
502
+ const cacheHints = {
503
+ // A list filtered by authorization varies by caller (M6, "Listing").
504
+ 'tools/list': { ttlMs, cacheScope: options.privateToolsList ? 'private' : 'public' },
505
+ 'server/discover': { ttlMs, cacheScope: 'public' },
506
+ ...(deps.resources &&
507
+ resourceCacheHints(deps.resourcesTtlMs ?? ttlMs, Boolean(authConfigured && deps.resources.hasProvider))),
508
+ };
509
+ /**
510
+ * The declared context fields as `server/discover` lists them. Described at the first exchange,
511
+ * where they always were: a field JSON Schema cannot represent (`z.coerce.date()`) fails each
512
+ * `/mcp` exchange and stdio connection, as before, not the server's construction.
513
+ */
514
+ let described;
283
515
  return ({ era }) => {
284
516
  const server = new Server({ name: deps.name, version: deps.version }, {
285
- capabilities: { tools: { listChanged: false }, ...deps.resources?.capabilities },
517
+ capabilities: capabilities[era],
286
518
  instructions: deps.instructions,
287
- cacheHints: {
288
- 'tools/list': { ttlMs, cacheScope: 'public' },
289
- 'server/discover': { ttlMs, cacheScope: 'public' },
290
- ...(deps.resources && resourceCacheHints(deps.resourcesTtlMs ?? ttlMs)),
291
- },
519
+ cacheHints: cacheHints,
520
+ });
521
+ deps.resources?.install(server, {
522
+ modern: era === 'modern',
523
+ internalError,
524
+ requestView: options.requestView,
525
+ authConfigured,
526
+ requireView: options.requireView,
527
+ });
528
+ if (deps.tasks?.servesTasks) {
529
+ patchToolsCallForTasks(server);
530
+ }
531
+ deps.tasks?.installHandlers(server, {
532
+ era,
533
+ isHttp,
534
+ requestValues: options.requestValues,
535
+ requestView: options.requestView,
536
+ internalError,
292
537
  });
293
- deps.resources?.install(server, { modern: era === 'modern', internalError });
538
+ refuseApprovalKeyBeforeParsing(server, era === 'modern', report);
539
+ wrapServerContract(server, serverContractFor(deps, isHttp, authConfigured));
294
540
  if (deps.contextFields?.length) {
295
- // The SDK's serving layer installs its own `server/discover` handler, which calls
296
- // `_ondiscover()` per request; wrapping it adds the declared fields to that answer.
297
- // `context-fields-mcp.test.ts` fails if an SDK upgrade changes this.
298
- const described = describeContextFields(deps.contextFields);
299
- const sdk = server;
300
- const discover = sdk._ondiscover.bind(server);
301
- sdk._ondiscover = () => {
302
- const result = discover();
303
- const meta = result._meta && typeof result._meta === 'object' ? result._meta : {};
304
- return { ...result, _meta: { ...meta, [AFD_CONTEXT_FIELDS_META_KEY]: described } };
305
- };
541
+ described ??= describeContextFields(deps.contextFields);
542
+ wrapServerDiscover(server, described);
306
543
  }
307
544
  // The SDK lifts `_meta` (minus the reserved envelope keys) into `ctx.mcpReq._meta`.
308
545
  server.setRequestHandler('tools/list', async (_request, ctx) => {
309
546
  const state = contextStateFor(era, ctx.mcpReq._meta);
310
- return { tools: deps.getToolsList(scoped({}, state)) };
547
+ const view = options.requestView?.();
548
+ // M6, "Other methods": a listing needs the required scopes.
549
+ const decision = view?.decideRequest();
550
+ if (view && decision && decision !== 'proceed') {
551
+ const error = view.insufficientScope(decision.forbidden);
552
+ throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
553
+ code: error.code,
554
+ suggestion: error.suggestion,
555
+ scopes: decision.forbidden,
556
+ });
557
+ }
558
+ return { tools: deps.getToolsList(bindScopeView(scoped({}, state), view)) };
311
559
  });
312
560
  server.setRequestHandler('tools/call', async (request, ctx) => {
313
- const { name } = request.params;
314
- // A meta-tool's `meta` argument counts as `_meta` from here on.
315
- const lifted = liftMetaArgument(name, request.params.arguments, ctx.mcpReq._meta, metaKeys);
316
- if (!lifted.ok)
317
- return resultContent(failure(lifted.error), true);
318
- const { args, meta } = lifted;
319
- const state = contextStateFor(era, meta);
320
- let values;
321
- try {
322
- values = options.requestValues ? await options.requestValues() : {};
323
- }
324
- catch (error) {
325
- throw internalError(error);
326
- }
561
+ // Decode the call; admission (`admission.ts`) and the router decide it.
327
562
  const canElicit = canElicitFor(era, server, ctx);
328
- // Declared fields from `_meta` first, so a value `createContext` sets wins. Neither
329
- // `actor` nor `credentials` can be a declared field: only `createContext` sets them.
330
- const declared = contextFieldValues(deps.contextFields, meta);
331
- const callValues = { ...declared, ...values };
332
- // Who is calling, as the call starts: the actor the commands run with (`createContext`'s,
333
- // or the server's default) and `createContext`'s credentials, copied so that code
334
- // changing them in place later cannot change what the state binds. They are checked
335
- // and bound only when a state is read or minted, so other calls are unaffected.
336
- const actorAtStart = shallowCopy(callValues.actor ?? deps.actor);
337
- const credentialsAtStart = shallowCopy(callValues.credentials);
338
- let principal;
339
- const round = elicitationRound(ctx, () => {
340
- principal ??= principalBinding(actorAtStart, credentialsAtStart);
341
- return principal;
342
- });
343
- const relay = canElicit ? approvalRelayFor(round) : undefined;
344
- let context = bindConfirmationChannel(scoped({ ...callValues, signal: ctx.mcpReq.signal, interface: 'mcp' }, state), confirmationChannelFor(canElicit, round, ctx));
345
- if (relay)
346
- context = bindApprovalRelay(context, relay.relay);
563
+ const rawCaps = ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY];
564
+ const relayView = inputResponse(ctx.mcpReq.inputResponses, RELAY_INPUT_KEY);
565
+ const rawState = ctx.mcpReq.requestState();
566
+ const view = options.requestView?.();
567
+ let relay;
568
+ let round;
347
569
  try {
348
- const result = await deps.routeToolCall(name, (args ?? {}), context);
570
+ const outcome = await admission.run({
571
+ lane: era === 'modern' ? 'mcp' : 'mcp-legacy',
572
+ tool: request.params.name,
573
+ args: request.params.arguments,
574
+ meta: ctx.mcpReq._meta,
575
+ state: (meta) => contextStateFor(era, meta),
576
+ values: options.requestValues ?? (() => ({})),
577
+ view,
578
+ signal: ctx.mcpReq.signal,
579
+ transport,
580
+ channels(context, principal) {
581
+ // The principal binding of the elicitations' `requestState`: who is calling, as
582
+ // the call starts. It is checked and bound only when a state is read or minted,
583
+ // so other calls are unaffected.
584
+ let binding;
585
+ const callRound = elicitationRound(ctx, () => {
586
+ binding ??= principalBinding(principal.actor, principal.credentials);
587
+ return binding;
588
+ });
589
+ round = callRound;
590
+ // An approver's call carries its token in `_meta`, and is never asked with a form.
591
+ relay = canElicit && !principal.approver ? approvalRelayFor(callRound) : undefined;
592
+ let bound = bindHumanRelayChannel(bindConfirmationChannel(context, confirmationChannelFor(canElicit, callRound, ctx)), {
593
+ modern: era === 'modern',
594
+ ...(isRecord(rawCaps) && { clientCapabilities: rawCaps }),
595
+ ...(typeof rawState === 'string' && { requestState: rawState }),
596
+ ...(relayView.kind === 'elicit' && { relayAction: relayView.action }),
597
+ });
598
+ if (relay)
599
+ bound = bindApprovalRelay(bound, relay.relay);
600
+ if (deps.tasks) {
601
+ bound = bindTaskDispatch(bound, deps.tasks.dispatchFor(era, isHttp, ctx, view?.credentials));
602
+ }
603
+ return bound;
604
+ },
605
+ });
349
606
  // The approval middleware held the call for the human: ask, instead of returning
350
607
  // the held result.
351
608
  const held = relay?.held();
352
- if (held) {
353
- return (await round.ask({
609
+ if (held && round) {
610
+ return (await round.askAll(held.questions.map((question) => ({
354
611
  k: APPROVAL_INPUT_KEY,
355
- b: held.binding,
356
- n: held.nonce,
357
- x: held.expiresAt,
358
- m: held.mac,
359
- }, held.message, APPROVAL_REQUESTED_SCHEMA, held.bindings));
612
+ b: question.binding,
613
+ n: question.nonce,
614
+ x: question.expiresAt,
615
+ m: question.mac,
616
+ ...(question.step && {
617
+ s: question.step.index,
618
+ i: question.step.input,
619
+ c: question.step.call,
620
+ }),
621
+ })), held.message, APPROVAL_REQUESTED_SCHEMA, held.questions.flatMap((question) => question.bindings)));
360
622
  }
361
- return { ...result };
623
+ return { ...toolResultOf(outcome) };
362
624
  }
363
625
  catch (error) {
364
626
  if (error instanceof InputRequiredSignal)
365
627
  return error.result;
628
+ if (error instanceof CreateTaskSignal || error instanceof ProtocolError)
629
+ throw error;
366
630
  throw internalError(error);
367
631
  }
368
632
  });
369
633
  return server;
370
634
  };
371
635
  }
636
+ /**
637
+ * `req`, or, when its body was read before routing (the authorization layer's decision before
638
+ * dispatch, M6), a request that yields those same bytes, so the SDK reads exactly what was sent.
639
+ */
640
+ export function replayed(req) {
641
+ const body = prereadBody(req);
642
+ if (!body)
643
+ return req;
644
+ return {
645
+ method: req.method,
646
+ url: req.url,
647
+ headers: req.headers,
648
+ async *[Symbol.asyncIterator]() {
649
+ yield body;
650
+ },
651
+ };
652
+ }
372
653
  /** Create the `/mcp` endpoint handler. */
373
654
  export function createModernHttpLane(deps) {
374
655
  const currentRequest = new AsyncLocalStorage();
@@ -383,6 +664,12 @@ export function createModernHttpLane(deps) {
383
664
  }
384
665
  return requestContextValues(deps.createContext, req, deps.auth?.credentialsFor(req));
385
666
  },
667
+ requestView: () => {
668
+ const req = currentRequest.getStore();
669
+ return req ? deps.auth?.viewFor(req) : undefined;
670
+ },
671
+ requireView: Boolean(deps.auth),
672
+ privateToolsList: deps.auth?.filterToolsByScope === true,
386
673
  });
387
674
  // The SDK reports rejected requests (bad headers, unsupported versions) through `onerror`;
388
675
  // those are client mistakes answered on the wire, so they are not forwarded to `onError`.
@@ -392,7 +679,7 @@ export function createModernHttpLane(deps) {
392
679
  onerror: reporter(deps.onError),
393
680
  });
394
681
  return {
395
- handle: (req, res) => currentRequest.run(req, () => node(req, res)),
682
+ handle: (req, res) => currentRequest.run(req, () => node(replayed(req), res)),
396
683
  close: () => handler.close(),
397
684
  };
398
685
  }