stitchkit 0.132.2 → 0.133.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 (341) hide show
  1. package/CHANGELOG.md +181 -1
  2. package/dist/agent-executor/acp/v1-connect.d.ts +12 -1
  3. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  4. package/dist/agent-executor/acp/v1-driver.d.ts +3 -1
  5. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
  6. package/dist/agent-executor/acp/v1-handlers.d.ts +9 -1
  7. package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -1
  8. package/dist/agent-executor/acp/v1-permission.d.ts +3 -2
  9. package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -1
  10. package/dist/agent-executor/acp/v1-probe.d.ts +10 -1
  11. package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -1
  12. package/dist/agent-executor/acp/v1-session.d.ts +11 -2
  13. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  14. package/dist/agent-executor/acp/v1-turn.d.ts +13 -10
  15. package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
  16. package/dist/agent-executor/claude/cli-driver.d.ts +6 -0
  17. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
  18. package/dist/agent-executor/claude/record-router.d.ts +44 -0
  19. package/dist/agent-executor/claude/record-router.d.ts.map +1 -0
  20. package/dist/agent-executor/claude/session.d.ts +2 -0
  21. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  22. package/dist/agent-executor/claude-sdk/controls.d.ts +1 -0
  23. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
  24. package/dist/agent-executor/claude-sdk/driver.d.ts +20 -2
  25. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  26. package/dist/agent-executor/claude-sdk/engine-spawn.d.ts +18 -0
  27. package/dist/agent-executor/claude-sdk/engine-spawn.d.ts.map +1 -0
  28. package/dist/agent-executor/claude-sdk/query-loop.d.ts +9 -7
  29. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  30. package/dist/agent-executor/claude-sdk/query-manager.d.ts +42 -0
  31. package/dist/agent-executor/claude-sdk/query-manager.d.ts.map +1 -0
  32. package/dist/agent-executor/claude-sdk/query-options.d.ts +4 -1
  33. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
  34. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  35. package/dist/agent-executor/codex/capabilities.d.ts +8 -0
  36. package/dist/agent-executor/codex/capabilities.d.ts.map +1 -0
  37. package/dist/agent-executor/codex/connect.d.ts +6 -1
  38. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  39. package/dist/agent-executor/codex/driver.d.ts +10 -0
  40. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  41. package/dist/agent-executor/codex/event-routing.d.ts +23 -1
  42. package/dist/agent-executor/codex/event-routing.d.ts.map +1 -1
  43. package/dist/agent-executor/codex/handlers.d.ts +24 -4
  44. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  45. package/dist/agent-executor/codex/limits.d.ts +17 -0
  46. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  47. package/dist/agent-executor/codex/request-answers.d.ts +23 -3
  48. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
  49. package/dist/agent-executor/codex/session-bind.d.ts +6 -1
  50. package/dist/agent-executor/codex/session-bind.d.ts.map +1 -1
  51. package/dist/agent-executor/codex/session-types.d.ts +5 -1
  52. package/dist/agent-executor/codex/session-types.d.ts.map +1 -1
  53. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  54. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  55. package/dist/agent-executor/codex/shared-thread.d.ts +7 -7
  56. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  57. package/dist/agent-executor/codex/thread-open.d.ts +12 -3
  58. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  59. package/dist/agent-executor/engine-requests.d.ts +42 -0
  60. package/dist/agent-executor/engine-requests.d.ts.map +1 -1
  61. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -1
  62. package/dist/agent-executor/handoff.d.ts.map +1 -1
  63. package/dist/agent-executor/image-input.d.ts +6 -5
  64. package/dist/agent-executor/image-input.d.ts.map +1 -1
  65. package/dist/agent-executor/profile.d.ts +3 -5
  66. package/dist/agent-executor/profile.d.ts.map +1 -1
  67. package/dist/agent-executor/session-primitives.d.ts +64 -3
  68. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  69. package/dist/agent-executor/testing/claude-sdk-stubs.d.ts +5 -0
  70. package/dist/agent-executor/testing/claude-sdk-stubs.d.ts.map +1 -0
  71. package/dist/agent-executor/testing/conformance-lifecycle.d.ts +11 -0
  72. package/dist/agent-executor/testing/conformance-lifecycle.d.ts.map +1 -0
  73. package/dist/agent-executor/testing/conformance-support.d.ts +23 -0
  74. package/dist/agent-executor/testing/conformance-support.d.ts.map +1 -0
  75. package/dist/agent-executor/testing/conformance.d.ts +7 -2
  76. package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
  77. package/dist/agent-executor/testing/consumer-stubs.d.ts +5 -3
  78. package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -1
  79. package/dist/agent-executor/testing/fake-codex-app-server.d.ts +5 -1
  80. package/dist/agent-executor/testing/fake-codex-app-server.d.ts.map +1 -1
  81. package/dist/agent-executor/testing/replay-driver.d.ts +6 -0
  82. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -1
  83. package/dist/agent-executor/testing/replay-gate.d.ts +4 -1
  84. package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -1
  85. package/dist/agent-runtime/deferred-tool-types.d.ts +2 -0
  86. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  87. package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
  88. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  89. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  90. package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
  91. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  92. package/dist/browser/client.d.ts.map +1 -1
  93. package/dist/browser/operation-refusal.d.ts +10 -0
  94. package/dist/browser/operation-refusal.d.ts.map +1 -0
  95. package/dist/contract/client-types.d.ts +13 -4
  96. package/dist/contract/client-types.d.ts.map +1 -1
  97. package/dist/contract/define-validation.d.ts +6 -0
  98. package/dist/contract/define-validation.d.ts.map +1 -1
  99. package/dist/contract/define.d.ts +3 -0
  100. package/dist/contract/define.d.ts.map +1 -1
  101. package/dist/contract/errors-factory.d.ts +8 -2
  102. package/dist/contract/errors-factory.d.ts.map +1 -1
  103. package/dist/contract/errors.d.ts +9 -0
  104. package/dist/contract/errors.d.ts.map +1 -1
  105. package/dist/contract/fingerprint.d.ts +4 -1
  106. package/dist/contract/fingerprint.d.ts.map +1 -1
  107. package/dist/contract/operation-refusals.d.ts +51 -0
  108. package/dist/contract/operation-refusals.d.ts.map +1 -0
  109. package/dist/contract/tool-options.d.ts +4 -0
  110. package/dist/contract/tool-options.d.ts.map +1 -1
  111. package/dist/entrypoints/agent-executor/acp.js +254 -196
  112. package/dist/entrypoints/agent-executor/claude-sdk.js +467 -294
  113. package/dist/entrypoints/agent-executor/claude.js +130 -99
  114. package/dist/entrypoints/agent-executor/codex.js +441 -314
  115. package/dist/entrypoints/agent-executor/testing/claude-sdk.d.ts +3 -0
  116. package/dist/entrypoints/agent-executor/testing/claude-sdk.d.ts.map +1 -0
  117. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +329 -0
  118. package/dist/entrypoints/agent-executor/testing.d.ts +1 -2
  119. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  120. package/dist/entrypoints/agent-executor/testing.js +413 -667
  121. package/dist/entrypoints/agent-executor.d.ts +1 -1
  122. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  123. package/dist/entrypoints/agent-executor.js +12 -12
  124. package/dist/entrypoints/agent-runtime/browser.js +2 -2
  125. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  126. package/dist/entrypoints/agent-runtime/harness.js +8 -8
  127. package/dist/entrypoints/agent-runtime/postgres.js +5 -5
  128. package/dist/entrypoints/agent-runtime/realtime.js +2 -2
  129. package/dist/entrypoints/agent-runtime/sandbox.js +3 -3
  130. package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
  131. package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
  132. package/dist/entrypoints/agent-runtime/testing.js +5 -5
  133. package/dist/entrypoints/agent-runtime.js +26 -18
  134. package/dist/entrypoints/application/grammy.js +1 -1
  135. package/dist/entrypoints/application.js +2 -2
  136. package/dist/entrypoints/cli.js +8 -8
  137. package/dist/entrypoints/contract.d.ts +3 -2
  138. package/dist/entrypoints/contract.d.ts.map +1 -1
  139. package/dist/entrypoints/contract.js +6 -4
  140. package/dist/entrypoints/files/packaging.d.ts +4 -1
  141. package/dist/entrypoints/files/packaging.d.ts.map +1 -1
  142. package/dist/entrypoints/files/packaging.js +868 -167
  143. package/dist/entrypoints/files.js +1 -1
  144. package/dist/entrypoints/handler.js +7 -7
  145. package/dist/entrypoints/http.js +2 -2
  146. package/dist/entrypoints/index.js +10 -8
  147. package/dist/entrypoints/node.js +11 -11
  148. package/dist/entrypoints/observability.js +1 -1
  149. package/dist/entrypoints/process/bootstrap.d.ts +3 -0
  150. package/dist/entrypoints/process/bootstrap.d.ts.map +1 -0
  151. package/dist/entrypoints/process/bootstrap.js +16 -0
  152. package/dist/entrypoints/process.js +7 -7
  153. package/dist/entrypoints/realtime.js +3 -3
  154. package/dist/entrypoints/remote.js +8 -7
  155. package/dist/entrypoints/server.js +30 -14
  156. package/dist/entrypoints/service-host/macos.js +72 -206
  157. package/dist/entrypoints/service-host/work.d.ts +15 -0
  158. package/dist/entrypoints/service-host/work.d.ts.map +1 -0
  159. package/dist/entrypoints/service-host/work.js +676 -0
  160. package/dist/entrypoints/service-host.js +146 -536
  161. package/dist/entrypoints/telegram/screens.js +4 -4
  162. package/dist/entrypoints/telegram.js +4 -4
  163. package/dist/entrypoints/testing.d.ts +2 -1
  164. package/dist/entrypoints/testing.d.ts.map +1 -1
  165. package/dist/entrypoints/testing.js +27 -8
  166. package/dist/entrypoints/tools/agent.js +6 -6
  167. package/dist/entrypoints/tools/connections.js +2 -2
  168. package/dist/entrypoints/tools/invoker.js +5 -5
  169. package/dist/entrypoints/tools/mcp.js +8 -6
  170. package/dist/entrypoints/tools/toolkit.js +11 -9
  171. package/dist/entrypoints/tools.js +19 -17
  172. package/dist/entrypoints/tracking/contract.js +1 -1
  173. package/dist/entrypoints/tracking/performance.js +3 -3
  174. package/dist/files/client-artifact.d.ts +14 -42
  175. package/dist/files/client-artifact.d.ts.map +1 -1
  176. package/dist/files/client-build.d.ts +57 -0
  177. package/dist/files/client-build.d.ts.map +1 -0
  178. package/dist/files/client-declarations.d.ts +35 -0
  179. package/dist/files/client-declarations.d.ts.map +1 -0
  180. package/dist/files/client-package-contract.d.ts +162 -0
  181. package/dist/files/client-package-contract.d.ts.map +1 -0
  182. package/dist/files/client-package-proof.d.ts +38 -0
  183. package/dist/files/client-package-proof.d.ts.map +1 -0
  184. package/dist/files/client-package.d.ts +17 -0
  185. package/dist/files/client-package.d.ts.map +1 -0
  186. package/dist/files/declaration-specifiers.d.ts +30 -0
  187. package/dist/files/declaration-specifiers.d.ts.map +1 -0
  188. package/dist/{index-v759mzed.js → index-02r5sq9p.js} +36 -23
  189. package/dist/{index-0r15pkjq.js → index-0k1ba0ss.js} +1 -1
  190. package/dist/{index-znd1b57f.js → index-1dn2wjq6.js} +5 -4
  191. package/dist/{index-p06z7g7w.js → index-1p8q0yrt.js} +6 -5
  192. package/dist/{index-wa6h4tz6.js → index-1qwd54n3.js} +6 -5
  193. package/dist/index-2dzc7mv9.js +174 -0
  194. package/dist/index-2mz8hj58.js +155 -0
  195. package/dist/{index-17qgm6xe.js → index-34k82crg.js} +2 -2
  196. package/dist/index-3mcbr8sx.js +349 -0
  197. package/dist/{index-ybdq8kk2.js → index-3y2tzhr8.js} +3 -3
  198. package/dist/{index-fgahdc7s.js → index-5n3a8hd8.js} +5 -3
  199. package/dist/{index-jb4m241t.js → index-6918kxbf.js} +45 -1
  200. package/dist/{index-n3bm7zqq.js → index-6kmjcm81.js} +4 -4
  201. package/dist/{index-akf0xkrm.js → index-78da4g74.js} +1 -1
  202. package/dist/{index-9pv126eh.js → index-7fjbdga8.js} +7 -1
  203. package/dist/{index-zhshhxew.js → index-8jf4bt7v.js} +1 -1
  204. package/dist/{index-p16q492v.js → index-8t9dr41h.js} +18 -5
  205. package/dist/{index-xq4s9mka.js → index-8yt3rwe7.js} +1 -1
  206. package/dist/{index-39c2hj6h.js → index-9c76vfxf.js} +7 -3
  207. package/dist/index-9ft4n9j1.js +432 -0
  208. package/dist/{index-sd4e5x5j.js → index-9wdrwx3b.js} +8 -7
  209. package/dist/{index-z114ax5e.js → index-an7vcmwf.js} +49 -2
  210. package/dist/{index-pzhqydxb.js → index-d04w81fz.js} +1 -1
  211. package/dist/index-d2drhb9c.js +219 -0
  212. package/dist/{index-8gmmdz7k.js → index-dacxr7nf.js} +1 -1
  213. package/dist/{index-dnzxxf8a.js → index-dm6nxkn1.js} +1 -1
  214. package/dist/index-dxft2mnm.js +42 -0
  215. package/dist/{index-rxh3qy4x.js → index-fzd477xk.js} +1 -1
  216. package/dist/{index-xgae0bn7.js → index-g4gstmp1.js} +2 -2
  217. package/dist/{index-athc412x.js → index-g5fgeb6v.js} +1 -1
  218. package/dist/{index-z9d74jmb.js → index-gbhj370g.js} +3 -3
  219. package/dist/{index-3fym4j8n.js → index-gtaaxe9d.js} +1 -1
  220. package/dist/{index-v59pxmf1.js → index-jpecjm30.js} +2 -2
  221. package/dist/index-k9g061ma.js +164 -0
  222. package/dist/{index-669374qc.js → index-ma26mfnt.js} +84 -315
  223. package/dist/{index-ryxb427v.js → index-msxf2r8x.js} +16 -3
  224. package/dist/{index-rbd2rq3z.js → index-nr4fhfn4.js} +1 -1
  225. package/dist/{index-qa2jjb65.js → index-pbekeqzm.js} +1 -1
  226. package/dist/{index-mkfhpk11.js → index-pq6g1k9t.js} +2 -2
  227. package/dist/{index-gya4hwh3.js → index-pws5c3x6.js} +21 -1
  228. package/dist/{index-x2fb37t0.js → index-q427q23r.js} +3 -2
  229. package/dist/{index-jcrj0b8z.js → index-qggqqja2.js} +39 -2
  230. package/dist/{index-jxtg307y.js → index-rkjfzs0a.js} +1 -1
  231. package/dist/{index-5tdc0q43.js → index-rw8ze745.js} +5 -3
  232. package/dist/index-s43tr4my.js +129 -0
  233. package/dist/{index-f9p62ean.js → index-stpy56r3.js} +175 -249
  234. package/dist/index-t5g5rm9n.js +213 -0
  235. package/dist/{index-z20pdxeb.js → index-tmv3ez1h.js} +3 -3
  236. package/dist/{index-dcsxj68j.js → index-tqjamnax.js} +1 -1
  237. package/dist/{index-j15dhkda.js → index-wddcfbng.js} +1 -325
  238. package/dist/{index-9sfhje6y.js → index-wh70tmpd.js} +24 -234
  239. package/dist/index-wxjv4sqx.js +82 -0
  240. package/dist/{index-qhjmmsm2.js → index-x46y9z26.js} +2 -2
  241. package/dist/{index-nk0cy9g1.js → index-y53cqwke.js} +1 -1
  242. package/dist/{index-sv5svtq7.js → index-y68gavb5.js} +1 -1
  243. package/dist/{index-5y7j383h.js → index-yrhw10ef.js} +1 -1
  244. package/dist/process/bootstrap.d.ts +12 -0
  245. package/dist/process/bootstrap.d.ts.map +1 -0
  246. package/dist/process/owner-loss-guard.d.ts +2 -9
  247. package/dist/process/owner-loss-guard.d.ts.map +1 -1
  248. package/dist/process/work-root.d.ts +20 -0
  249. package/dist/process/work-root.d.ts.map +1 -0
  250. package/dist/server/contract-identity.d.ts.map +1 -1
  251. package/dist/server/contract-method.d.ts +12 -0
  252. package/dist/server/contract-method.d.ts.map +1 -1
  253. package/dist/server/implement.d.ts.map +1 -1
  254. package/dist/server/openapi.d.ts.map +1 -1
  255. package/dist/server/types.d.ts +10 -9
  256. package/dist/server/types.d.ts.map +1 -1
  257. package/dist/service-host/host-adapter.d.ts +2 -0
  258. package/dist/service-host/host-adapter.d.ts.map +1 -1
  259. package/dist/service-host/work/command.d.ts +72 -0
  260. package/dist/service-host/work/command.d.ts.map +1 -0
  261. package/dist/service-host/work/errors.d.ts +29 -0
  262. package/dist/service-host/work/errors.d.ts.map +1 -0
  263. package/dist/service-host/work/host.d.ts +38 -0
  264. package/dist/service-host/work/host.d.ts.map +1 -0
  265. package/dist/service-host/work/launch.d.ts +51 -0
  266. package/dist/service-host/work/launch.d.ts.map +1 -0
  267. package/dist/service-host/work/membership.d.ts +51 -0
  268. package/dist/service-host/work/membership.d.ts.map +1 -0
  269. package/dist/service-host/work/origin.d.ts +79 -0
  270. package/dist/service-host/work/origin.d.ts.map +1 -0
  271. package/dist/service-host/work/owner.d.ts +45 -0
  272. package/dist/service-host/work/owner.d.ts.map +1 -0
  273. package/dist/service-host/work/placement.d.ts +55 -0
  274. package/dist/service-host/work/placement.d.ts.map +1 -0
  275. package/dist/service-host/work/probe.d.ts +24 -0
  276. package/dist/service-host/work/probe.d.ts.map +1 -0
  277. package/dist/service-host/work/scope-command.d.ts +68 -0
  278. package/dist/service-host/work/scope-command.d.ts.map +1 -0
  279. package/dist/sync/session.d.ts +4 -1
  280. package/dist/sync/session.d.ts.map +1 -1
  281. package/dist/testing/surface-manifest-digest.d.ts +2 -0
  282. package/dist/testing/surface-manifest-digest.d.ts.map +1 -1
  283. package/dist/testing/surface-manifest.d.ts +32 -3
  284. package/dist/testing/surface-manifest.d.ts.map +1 -1
  285. package/dist/tools/agent.d.ts +2 -0
  286. package/dist/tools/agent.d.ts.map +1 -1
  287. package/dist/tools/cli/stream-surface.d.ts.map +1 -1
  288. package/dist/tools/internal/mcp-projection.d.ts +58 -0
  289. package/dist/tools/internal/mcp-projection.d.ts.map +1 -0
  290. package/dist/tools/internal/surface-projector.d.ts +3 -47
  291. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  292. package/dist/tools/invoker.d.ts +2 -0
  293. package/dist/tools/invoker.d.ts.map +1 -1
  294. package/dist/tools/manifest.d.ts +2 -0
  295. package/dist/tools/manifest.d.ts.map +1 -1
  296. package/dist/tools/mcp/handler.d.ts.map +1 -1
  297. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -1
  298. package/dist/tools/mcp/mount.d.ts +4 -0
  299. package/dist/tools/mcp/mount.d.ts.map +1 -1
  300. package/dist/tools/mcp/prepare.d.ts +5 -2
  301. package/dist/tools/mcp/prepare.d.ts.map +1 -1
  302. package/dist/tools/mount.d.ts +2 -0
  303. package/dist/tools/mount.d.ts.map +1 -1
  304. package/dist/tools/remote.d.ts.map +1 -1
  305. package/dist/tools/schema/nesting-limit.d.ts +8 -0
  306. package/dist/tools/schema/nesting-limit.d.ts.map +1 -0
  307. package/dist/tools/schema/presentation.d.ts +7 -0
  308. package/dist/tools/schema/presentation.d.ts.map +1 -1
  309. package/dist/tools/surface.d.ts.map +1 -1
  310. package/llms/agent-executor-acp.txt +3 -3
  311. package/llms/agent-executor-claude-sdk.txt +1 -1
  312. package/llms/agent-executor-claude.txt +1 -1
  313. package/llms/agent-executor-codex.txt +1 -1
  314. package/llms/agent-executor-testing-claude-sdk.txt +28 -0
  315. package/llms/agent-executor-testing.txt +7 -8
  316. package/llms/agent-executor.txt +27 -4
  317. package/llms/agent-runtime.txt +1 -1
  318. package/llms/contract.txt +8 -2
  319. package/llms/files-packaging.txt +11 -6
  320. package/llms/process-bootstrap.txt +18 -0
  321. package/llms/process.2.txt +215 -18
  322. package/llms/process.txt +130 -92
  323. package/llms/server.4.txt +49 -1
  324. package/llms/service-host-work.txt +34 -0
  325. package/llms/stitchkit.2.txt +31 -0
  326. package/llms/stitchkit.txt +78 -75
  327. package/llms/sync.txt +5 -2
  328. package/llms/testing.txt +1 -0
  329. package/llms/tools.2.txt +747 -775
  330. package/llms/tools.3.txt +846 -210
  331. package/llms/tools.4.txt +226 -0
  332. package/llms/tools.txt +3 -790
  333. package/llms/{upgrading-0.128.0-0.132.0.txt → upgrading-0.128.0-0.133.0.txt} +194 -6
  334. package/llms/upgrading.txt +1 -1
  335. package/llms-full.txt +746 -135
  336. package/llms.txt +18 -16
  337. package/package.json +12 -4
  338. package/dist/entrypoints/process/owner-loss.d.ts +0 -3
  339. package/dist/entrypoints/process/owner-loss.d.ts.map +0 -1
  340. package/dist/entrypoints/process/owner-loss.js +0 -7
  341. package/llms/process-owner-loss.txt +0 -18
package/llms/tools.txt CHANGED
@@ -1,4 +1,4 @@
1
- # stitchkit/tools — stitchkit docs slice, part 1 of 3
1
+ # stitchkit/tools — stitchkit docs slice, part 1 of 4
2
2
 
3
3
  > Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
4
4
  > `llms.txt` in this package.
@@ -7,7 +7,8 @@
7
7
  Parts of this slice:
8
8
  - `llms/tools.txt`: Guide: MCP & agents (docs/guide/mcp-and-agents.md)
9
9
  - `llms/tools.2.txt`: Guide: MCP & agents (docs/guide/mcp-and-agents.md)
10
- - `llms/tools.3.txt`: API reference: `stitchkit/tools` (docs/api/reference.md)
10
+ - `llms/tools.3.txt`: Guide: MCP & agents (docs/guide/mcp-and-agents.md)
11
+ - `llms/tools.4.txt`: API reference: `stitchkit/tools` (docs/api/reference.md)
11
12
 
12
13
  ==============================================================================
13
14
  # Guide: MCP & agents (docs/guide/mcp-and-agents.md)
@@ -145,791 +146,3 @@ The invoker's caller is code, so it gets an endpoint's full answer even where a
145
146
  invoker backs a transport a model reads, pass `toolSurface: true`: calls then
146
147
  get the view's defaults and projected answer, which is what `collectTools` and
147
148
  `buildToolManifest` advertise.
148
-
149
- ## MCP — `createMcpHandler`
150
-
151
- An MCP-only server imports `stitchkit/tools/mcp` and installs
152
- `stitchkit`, `zod` and `@modelcontextprotocol/server`. The leaf's runtime and strict
153
- NodeNext declarations require no `ai`. It exports the existing HTTP/stdio server,
154
- schema policy, catalog and resource helpers, and it is the only entrypoint that does:
155
- `stitchkit/tools` loads no optional peer. AI SDK tools come from `stitchkit/tools/agent`.
156
-
157
- `createMcpHandler` builds a complete stateless Streamable-HTTP MCP endpoint on
158
- the official TypeScript SDK v2 server package. It owns server creation,
159
- protocol-era negotiation and shutdown; application code does not import the SDK
160
- to mount a normal endpoint.
161
-
162
- ```ts
163
- import { createMcpHandler, createMcpHttpRoute } from 'stitchkit/tools/mcp'
164
- import { createServer } from 'stitchkit/server'
165
-
166
- const mcp = createMcpHandler({
167
- serverInfo: { name: 'my-app', version: '1.0.0' },
168
- auth: (req) => resolveApiKey(req), // → an identity, or null for 401
169
- services: [usersService, catalogService],
170
- access: { gate: { beforeHandle: authHook } },
171
- })
172
-
173
- createServer({
174
- services,
175
- rawRoutes: [createMcpHttpRoute({ path: '/mcp', handler: mcp })],
176
- })
177
-
178
- // During graceful shutdown:
179
- await mcp.close()
180
- ```
181
-
182
- ### `McpHandlerConfig`
183
-
184
- | Field | Purpose |
185
- |-------|---------|
186
- | `serverInfo` | MCP server identity — `{ name, version }` |
187
- | `auth` | `(req) => identity \| null` — `null` rejects with 401 |
188
- | `services` | the services to expose — an array, or `(auth) => ServiceDef[]` |
189
- | `runtimeTools` | managed pathless operations — an array, or `(auth) => RuntimeToolDefinition[]` |
190
- | `surfaces` | finite `{ key: { services, runtimeTools } }` registry prepared eagerly |
191
- | `selectSurface` | `(auth) => declaredKey` — required with `surfaces` |
192
- | `context` | `(auth) => {…}` — values merged into every tool handler's `ctx` |
193
- | `access` | **required** — `{ gate: { beforeHandle, afterHandle? } }` or `{ open: 'public' \| 'local-operator' \| 'remote', afterHandle? }` (see below) |
194
- | `multiRound` | Typed MRTR state policy for guarded multi-round tool calls |
195
- | `hooks` | tool-call observability hooks — `afterToolCall` fires on every result |
196
- | `extend` | extra advertised arguments resolved into handler context |
197
- | `schemaValidation` | compatibility policy, typed-property guard and portable-format guard |
198
- | `logger` | a `StitchLogger` for the `'warn'` policy |
199
- | `rawTools` | `(server, auth) => …` — explicit SDK registration without framework guarantees |
200
- | `resources` | MCP Apps `ui://` resources mounted on every server |
201
- | `instructions` | a short host-facing usage hint, surfaced to MCP tool-search |
202
- | `coerceJsonArgs` | coerce JSON-stringified object/array arguments (default `true`) |
203
- | `flattenUnionInput` | advertise discriminated unions as one object (default `false`) |
204
- | `inputRecursionDepth` | advertise inputs with no `$ref`, recursion unrolled this many levels (default: references stay) |
205
- | `errorHint` | add a project-owned hint to failed tool results |
206
- | `onOutputStrip` | observe output keys removed by contract validation |
207
- | `protectedResource` | RFC 9728 metadata used by HTTP `401` responses |
208
- | `legacy` | `'serve'` (default) or `'reject'` for pre-2026 clients |
209
- | `security` | optional Host/Origin allowlists at the Fetch boundary |
210
- | `onTransportRejected` | observe HTTP/protocol rejections without entering lifecycle or tool hooks |
211
- | `cache` | explicit operation cache hints; omitted means zero/private |
212
-
213
- Direct `services` / `runtimeTools` factories, `context`, `selectSurface` and
214
- `rawTools` receive the resolved identity, so a tenant can be shown only its own
215
- tools and every handler can read `ctx.tenantId`.
216
-
217
- Use direct factories only when the definitions are genuinely arbitrary per
218
- identity. For a bounded role/plan set, declare a finite registry instead:
219
-
220
- ```ts
221
- const handleMcp = createMcpHandler({
222
- serverInfo,
223
- auth,
224
- surfaces: {
225
- admin: { services: allServices, runtimeTools: [renderPreview] },
226
- member: { services: memberServices, runtimeTools: [renderPreview] },
227
- },
228
- selectSurface: (identity) => identity.isAdmin ? 'admin' : 'member',
229
- context: (identity) => ({ identity }),
230
- access: { gate: { beforeHandle: authHook } },
231
- })
232
- ```
233
-
234
- Every declared entry is schema-validated and prepared once when the handler is
235
- constructed. The selected immutable descriptors are shared; the SDK server,
236
- transport, auth-derived context, lifecycle runner and tool-call context are
237
- fresh for every request. Unknown keys
238
- fail before the server connects. The registry never retains auth values.
239
-
240
- ### Stateless transport and protocol eras
241
-
242
- Every request gets a fresh SDK server, resolved auth/context and tool-call
243
- runner. Static direct and finite registry schemas are still prepared once when
244
- the handler is constructed. There is no session map, event store,
245
- `Mcp-Session-Id` or resumable cross-request SSE state. Process replacement and
246
- load balancing therefore cannot strand a client on an in-memory session.
247
-
248
- The default `legacy: 'serve'` lets the official SDK negotiate either modern
249
- `2026-07-28` or the supported legacy stateless opening on this same endpoint.
250
- Set `legacy: 'reject'` when every host is modern. Legacy support is protocol
251
- translation inside the SDK, not a second Stitchkit transport or compatibility
252
- API. Stateful MCP and subscriptions are intentionally outside this layer.
253
-
254
- `createMcpHttpRoute` is the framework-owned raw-route adapter. It registers
255
- `ALL` because Streamable HTTP uses multiple HTTP methods, delegates only to
256
- `handler.fetch`, and leaves lifecycle ownership with the returned handler.
257
-
258
- By default, a present `Host` header must match the request URL and a present
259
- browser `Origin` must be same-origin. Non-browser hosts may omit `Origin`. Behind
260
- a trusted reverse proxy, reconstruct the public request URL before calling the
261
- handler or configure exact `security.allowedHosts` / `allowedOrigins`; never
262
- copy arbitrary forwarded headers into the trusted URL. If a browser calls MCP
263
- cross-origin, its HTTP server or gateway must also answer CORS preflight and
264
- expose the protocol headers. `onTransportRejected` is the audit boundary for
265
- HTTP/security rejections; it is deliberately separate from tool lifecycle and
266
- must not be used as authorization input.
267
-
268
- ### Modern discovery, routing and cache hints
269
-
270
- Stitchkit forwards the negotiated protocol era and validated MCP request data
271
- to both `RequestEvent.mcp` and the current managed call's typed `context.mcp`;
272
- untrusted routing headers never become application identity. The SDK validates
273
- `MCP-Protocol-Version`, JSON-RPC shape and routing
274
- metadata before lifecycle or tool handlers run. Framework-owned tool and
275
- resource registration preserves declaration order across HTTP and stdio. Tool
276
- manifests preserve mount order; `listToolNames` is a sorted diagnostics view.
277
- Consumer-owned raw SDK registrations are outside this guarantee.
278
-
279
- Caching is opt-in. `cache.operations` maps directly to SDK v2 operation cache
280
- hints, while each `McpResourceDef` may declare its own `cacheHint`. Omission
281
- means zero/private: neither a prepared surface nor a deterministic response is
282
- silently treated as public. Unbounded auth-selected surface factories are
283
- always forced to zero/private even when an operation policy is present; use a
284
- finite `surfaces` registry when identities share a provably immutable surface.
285
- Stitchkit never advertises list-change or subscription capabilities
286
- without an implementation.
287
-
288
- ### Knowing your catalog is stale — the catalog stamp
289
-
290
- A client lists the tools once and keeps that list. If the server's contract
291
- moves afterwards, the client's copy is wrong and *nothing tells it so*: calls
292
- are refused, and from inside the client a refusal looks like a broken server.
293
- This is the most expensive shape a contract disagreement takes, because the
294
- party able to fix it is the one with no evidence.
295
-
296
- Every advertised tool and every tool result therefore carries the fingerprint of
297
- the catalog it came from:
298
-
299
- ```ts
300
- import { readMcpCatalogStamp } from 'stitchkit/tools/mcp';
301
-
302
- const listed = await client.listTools();
303
- let known = readMcpCatalogStamp(listed.tools[0]?._meta); // { digest, tools }
304
-
305
- const result = await client.callTool({ name: 'record_journal', arguments });
306
- const live = readMcpCatalogStamp(result._meta);
307
- if (live && known && live.digest !== known.digest) {
308
- // The catalog moved under us. Re-list before blaming the result.
309
- known = readMcpCatalogStamp((await client.listTools()).tools[0]?._meta);
310
- }
311
- ```
312
-
313
- The comparison costs nothing and runs on a response you were already receiving —
314
- including a refusal, which is exactly when a stale catalog is the likeliest
315
- explanation. `notifications/tools/list_changed` is the push-shaped answer to the
316
- same problem and `createMcpHandler` cannot send it: it is stateless by
317
- construction, so there is no retained session to push down.
318
-
319
- The digest covers each advertised tool's name, description, input schema, output
320
- schema, annotations and MCP Apps `ui` resource, and nothing else — it moves when the
321
- contract moves and not when a handler does. Raw SDK registrations stay consumer-owned
322
- and are outside it, so a handler with `rawTools` sends no stamp header.
323
-
324
- `createMcpHandler` also sends the stamp of the surface each request was served from as
325
- the `stitchkit-catalog` response header (the same `{ digest, tools }` JSON), on the
326
- `initialize` answer included — the SDK assembles that result itself and leaves no
327
- `_meta` to fill. A client can therefore tell whether its stored catalog is current
328
- before it asks for `tools/list`; `defineMcpClientConnection({ catalog })` does exactly
329
- that ([CLI → commands discovered from a running server](./cli.md#commands-discovered-from-a-running-server)).
330
-
331
- ### Saying which tools only read — `readOnlyHint`
332
-
333
- A host reads a tool's `annotations` to group tools and to choose permission
334
- defaults, and a CLI mounted over this surface reads them to decide what a
335
- refused view may withhold ([CLI → views](./cli.md#aggregate-views)). The server publishes the
336
- annotations the tool declared, and states `readOnlyHint: true` for a read that
337
- declared none:
338
-
339
- | The tool | Published `readOnlyHint` |
340
- |---|---|
341
- | declares `readOnlyHint`, either way | as declared |
342
- | `effect: 'write'` with no `readOnlyHint` (even on `GET`) | none |
343
- | `effect: 'read'` with no `readOnlyHint` and `destructiveHint !== true` (even on non-`GET`) | `true` |
344
- | `GET` with no `readOnlyHint`, no `effect: 'write'`, and `destructiveHint !== true` | `true` |
345
- | any other method, or `destructiveHint: true` with no `readOnlyHint` | none |
346
-
347
- A runtime tool follows the same rule by its `identity.effect` and `identity.method`. A raw SDK
348
- registration (`mountWait`, `mountViewFile` and the like) publishes only what it
349
- passes. The catalog digest hashes the published annotations, so it moves once
350
- when a server starts publishing the derived hint.
351
-
352
- > **A `GET` with a write effect must say so.** Hosts may run a tool that publishes
353
- > `readOnlyHint: true` without asking. An endpoint that changes something on
354
- > `GET` — marks as seen, rotates a token — declares `effect: 'write'` or
355
- > `tool: { annotations: { readOnlyHint: false } }`.
356
-
357
- A client connection (`defineMcpClientConnection`) carries the hints a server
358
- published onto the tools it mounts, field by field: a hint of the wrong type is
359
- dropped and the tool stays. The mounted tool is as read-only as its server says
360
- it is, and a surface that re-publishes mounted tools passes those hints on.
361
-
362
- ### Shaping arguments before validation — `beforeToolCall`
363
-
364
- `beforeToolCall` sees the arguments as they arrived and may **replace** them:
365
-
366
- ```ts
367
- hooks: {
368
- beforeToolCall: async ({ args }) =>
369
- typeof args.id === 'string' && args.id.startsWith('@')
370
- ? { ...args, id: await resolveReference(args.id) }
371
- : undefined, // undefined / null / nothing → unchanged
372
- }
373
- ```
374
-
375
- The replacement is validated by the contract schema like any other input, so this
376
- shapes a call and never bypasses the schema — a hook returning something the
377
- contract refuses produces an ordinary `VALIDATION_ERROR`. It runs before the
378
- params/input split, before argument coercion and before both schemas, which is
379
- why a field declared `z.string()` can receive a reference and still be a string by
380
- the time it is checked. `access.gate.beforeHandle` is too late for this: the schemas
381
- have already answered.
382
-
383
- The audit trail is unaffected. `afterToolCall` reports what the caller sent as
384
- `args` and the replacement separately as `effectiveArgs`, so a rewrite is visible
385
- as a rewrite rather than by overwriting the evidence.
386
-
387
- ### Knowing the outcome of a call — `afterToolCall` and `toolCallId`
388
-
389
- `afterToolCall` receives the whole `ToolResult` — `{ok: true, data}` or
390
- `{ok: false, code, …}` — on every exit, including a validation failure that never
391
- reached the handler, and on all three transports. It is the answer to "did this
392
- call fail"; deriving that from the serialized error text instead is the mistake
393
- this section exists to prevent, and it is a mistake that does not announce itself:
394
- one consumer had five places asking the question and getting five answers.
395
-
396
- To correlate an outcome with the call the model made, read `context.toolCallId`:
397
-
398
- ```ts
399
- hooks: {
400
- afterToolCall: ({ context, result }) => {
401
- loop.record(context.toolCallId, result.ok ? 'ok' : result.code);
402
- },
403
- }
404
- ```
405
-
406
- Two exits are deliberately **not** reported: a runtime tool presenter that throws
407
- on the agent surface (the AI SDK calls it after `execute` has already returned)
408
- and `ToolExecutionControlError`, which is a run being stopped rather than a tool
409
- failing — check it with `isToolExecutionControlError`.
410
-
411
- ### Restartable tool bodies — `durability`
412
-
413
- A tool that starts slow work and must report exactly once, including after a host
414
- restart, can keep that bookkeeping **inside** the tool:
415
-
416
- ```ts
417
- mountAgent(services, {
418
- access: { gate: { beforeHandle: authHook } },
419
- durability: (toolCallId, signal) => myLedgerFor(toolCallId, signal),
420
- });
421
-
422
- // in the handler
423
- const asset = await ctx.step('render', () => renderAsset(ctx.input));
424
- await ctx.waitFor({ event: 'render-done', id: assetId });
425
- ```
426
-
427
- `ToolDurability` is the port a tool body sees — `step`, `sleep`, `waitFor`. You
428
- do not have to implement it: the engine ships from `stitchkit/tools`, and it needs
429
- a ledger of two methods over storage you already have:
430
-
431
- ```ts
432
- import { createLocalStepDurability, type StepDurabilityLedger } from 'stitchkit/tools';
433
-
434
- const ledger: StepDurabilityLedger = {
435
- appendEvent: (event) => db.durabilityEvents.insert(event), // returns the row with `seq`
436
- readEvents: ({ conversationId, fromSeq, toSeq }) => db.durabilityEvents.page(…),
437
- };
438
-
439
- mountAgent(services, {
440
- access: { gate: { beforeHandle: authHook } },
441
- durability: (toolCallId, signal) =>
442
- createLocalStepDurability({ store: ledger, conversationId, runId: toolCallId, signal }),
443
- });
444
- ```
445
-
446
- That gives replay, absolute deadlines and decode refusal without writing them.
447
- The port is there for an application that already has its own ledger engine.
448
-
449
- One thing the port deliberately leaves out: **delivery**. `waitFor` parks until
450
- `{ event, id }` arrives, and a tool body has no business delivering to itself —
451
- so `deliver` lives on the engine object you constructed, not in the handler
452
- context. Whatever produces the event (a webhook, a queue consumer, a cron) calls
453
- `engine.deliver({ event, id, payload })` against the same ledger; the parked
454
- `waitFor` resolves, and a `waitFor` that starts after the delivery returns at
455
- once. Taking `agent-runtime` is not required and nothing of the runtime proper
456
- enters the `stitchkit/tools` graph. An application that *does* run on
457
- `agent-runtime` gets durability through the run context and needs no option;
458
- where both exist the runtime's wins, because the run is recorded in its ledger.
459
-
460
- #### An effect in another system — `effect`, at most once
461
-
462
- Standalone callers must hold an application-owned exclusive execution lease for the conversation/run
463
- through the whole effect call. Sharing a ledger or separate ledger adapters is not an atomic claim;
464
- the runtime supplies its run lease. Process-local coalescing only covers the same ledger object.
465
-
466
- `step` records its result **after** the body, so a body cut short by a crash
467
- runs again. For sending a message or starting a turn at a provider, a repeat is
468
- worse than a loss. The engine's `effect` records the intent **before** it runs:
469
-
470
- ```ts
471
- const sent = await engine.effect('reply', {
472
- run: () => chat.send({ clientId, text }), // → { messageId }
473
- reconcile: (signal) => chat.findByClientId(clientId, { signal }), // → { messageId } | null
474
- })
475
- if (sent.outcome === 'uncertain') reportPossiblyLost(clientId)
476
- ```
477
-
478
- A later call — the same process or a restarted one — that finds the intent with
479
- no outcome calls `reconcile`, never `run`. Found is `accepted` with the proof;
480
- not found is `uncertain`. Both are recorded and final: `run` is never called for
481
- that name again, and `uncertain` is not asked again — it is the honest third
482
- answer, and retrying it is the caller's decision under a new name. A `run` that
483
- throws, or a `reconcile` that throws or overruns `reconcileTimeoutMs` (default
484
- 30 s), rejects with `EffectUnresolvedError` and leaves the intent for the next
485
- call. The proof is JSON of at most 64 KiB — the identity the recipient assigned,
486
- not a payload. → [ADR 0200](../decisions/0200-an-effect-is-recorded-before-it-runs.md)
487
-
488
- Caller abort during reconcile releases the wait with `StepAbortedError`, leaves the intent and ignores
489
- a late result. A coalesced caller can cancel its own await without cancelling the shared owner;
490
- the first caller owns reconciliation handlers/deadline. `reconcileTimeoutMs` cannot exceed the native
491
- timer range (2147483647 ms). It does not turn cancellation into proof of absence. Neither `null` nor an absence digest
492
- proves that an earlier recipient request cannot complete later. Safe retries require recipient-side
493
- idempotency or a verified fence. See [ADR 0224](../decisions/0224-native-primitives-have-one-owner.md).
494
-
495
- Ledger reads are paged at 10 000 and incremental in one engine; a fresh engine replays the conversation
496
- and retains its durable keys. This is not a bounded outstanding index/direct terminal receipt store.
497
- For application delivery, `defineDomainEventDelivery` in `stitchkit/primitives` composes a caller-owned
498
- atomic outbox claim with delivered/retryable/terminal/unknown states, bounded dispatch count (default
499
- 100). Storage retention, per-key lookup, recipient proof and transactions remain in that adapter;
500
- it is not an automatic cutover for a different reconciliation protocol.
501
-
502
- ### Typed MCP call metadata
503
-
504
- Contract handlers, runtime-tool handlers/factories, lifecycle and tool hooks all
505
- see the same optional `McpCallContext` for the current invocation:
506
-
507
- ```ts
508
- const sourceLabel = context.mcp?.clientInfo?.name ?? context.source
509
-
510
- context.mcp?.era // 'modern' | 'legacy'
511
- context.mcp?.method // validated MCP method
512
- context.mcp?.toolName // resolved framework tool name
513
- context.mcp?.protocolVersion // when supplied by a modern host
514
- context.mcp?.clientInfo // { name, version } when validated
515
- context.mcp?.outcome // multi-round attempt outcome
516
- context.mcp?.round // multi-round attempt number
517
- ```
518
-
519
- The field is absent on HTTP, Agent, CLI and bring-your-own transports. A legacy
520
- MCP call exposes `era: 'legacy'` but does not invent modern client information.
521
- `clientInfo` is the host's self-description: use it for labels or analytics,
522
- never for authentication, RBAC, tenant selection or rate limiting. Verified
523
- identity still comes from `auth`; the `context(auth)` callback remains the
524
- application-context factory and receives no protocol metadata.
525
-
526
- ### Telling the host what a long call is doing — `ctx.reportProgress`
527
-
528
- A tool that takes ten minutes tells a text host nothing: the call is made, and
529
- the next thing the host shows is the answer. The protocol has a channel for
530
- this — the host sends a `progressToken` with the call, the server relates
531
- progress notifications to it — and a handler reaches it through
532
- `ctx.reportProgress`:
533
-
534
- ```ts
535
- render: async (ctx) => {
536
- await ctx.reportProgress?.({ message: 'queued' })
537
- const job = await jobs.start(ctx.input)
538
- await ctx.reportProgress?.({ message: 'rendering', progress: 1, total: 3 })
539
- return await jobs.finish(job)
540
- }
541
- ```
542
-
543
- `reportProgress` is present on every **tool** call — MCP, agent and CLI — so a
544
- handler never branches on transport, and it does nothing wherever nobody is
545
- listening. Under the agent runtime somebody is: each report becomes a transient
546
- `tool-progress` event of the run, so the person watching the agent sees the
547
- stage while the model still reads only the tool's result (see
548
- [Agent runtime → events](./agent-runtime.md)). It is absent on the HTTP transport, which has no channel for it, so a
549
- handler that also serves HTTP writes `ctx.reportProgress?.(…)`. It never throws and never
550
- rejects: a message about work must not be able to kill the work it describes, so
551
- a refused notification leaves the host exactly where a host that never asked for
552
- progress already is.
553
-
554
- `progress` is a number the protocol requires and a handler often does not have —
555
- there is a stage to name and no scale to name it on. Omit it and the ordinal of
556
- the update is sent, with no `total`, so the host shows a counter rather than a
557
- bar stuck at 3%. That is a fact about what happened; a synthesised percentage
558
- would be a claim nobody measured.
559
-
560
- The framework sends nothing on its own. Progress is meaningful only where an
561
- operation has observable stages, and manufacturing one per call would be
562
- inventing a second transport beside the one the protocol already provides. The
563
- one exception is the managed wait tool (`mountWait`), which already polls and
564
- therefore already knows: when the host asked for progress it reports each poll
565
- and the phase it last saw, which is the tool whose silence raised the question
566
- in the first place.
567
-
568
- The token itself is on `ctx.mcp.progressToken` when a caller wants to know
569
- whether anyone is listening.
570
-
571
- ### Multi-round tool input (`input_required`)
572
-
573
- An MCP-only operation can require typed user input before its final side effect:
574
-
575
- ```ts
576
- const DeleteConfirmationSchema = z.object({ confirmed: z.boolean() })
577
-
578
- deleteProject: {
579
- method: 'DELETE',
580
- path: '/projects/:id',
581
- expose: ['MCP'],
582
- input: DeleteProjectSchema,
583
- output: DeleteProjectResultSchema,
584
- tool: {
585
- mcp: {
586
- inputRequired: [
587
- {
588
- key: 'confirmation',
589
- schema: DeleteConfirmationSchema,
590
- message: 'Confirm permanent deletion',
591
- },
592
- {
593
- key: 'reason',
594
- schema: z.object({ value: z.string().min(3) }),
595
- message: 'Record the reason',
596
- },
597
- ],
598
- },
599
- },
600
- }
601
- ```
602
-
603
- Each continuation accepts exactly the currently requested item. Only after the
604
- ordered sequence completes does the handler receive the exact aggregate as
605
- `ctx.mcpInput.confirmation` and `ctx.mcpInput.reason`; before then the framework
606
- returns `input_required` without calling it. Set
607
- `multiRound.serving.maxRounds` to the maximum declaration size you accept
608
- (default `10`); empty sequences, duplicate keys and overflow fail first. State
609
- is bound to principal, full operation identity, current round, accepted
610
- aggregate and canonical original-argument digest and is
611
- expiry-checked. Tampered, expired, cross-user or cross-tool state fails before
612
- the side effect. Output validation applies only to the final result.
613
-
614
- Every attempt re-runs auth/lifecycle and emits its own tool hooks; audit metadata
615
- contains the attempt's `mcp.outcome` and `mcp.round`. Stitchkit does not merge
616
- separate HTTP attempts into one logical trace. Parallel
617
- rounds have isolated context. HTTP/stdio modern hosts and the supported legacy
618
- stdio bridge may use this declaration; Agent, CLI and ordinary HTTP invocation
619
- remain single-round and unchanged. Hosts without the capability receive an
620
- ordinary unsupported result rather than a falsely advertised round. Signed
621
- state is tamper-resistant, not an exactly-once replay store; destructive
622
- handlers must still be idempotent where retries matter.
623
-
624
- #### Questions chosen from the arguments
625
-
626
- The list above is fixed when the contract is written, which is right when the
627
- questions belong to the operation. It is not enough when they belong to the
628
- **arguments** — one model takes `aspect_ratio`, another `duration`, a third an
629
- input image — and there a declared list can only be empty. `inputRequired` also
630
- accepts a function of the parsed call:
631
-
632
- ```ts
633
- tool: {
634
- mcp: {
635
- inputRequired: async ({ input }) => {
636
- const model = await catalog.get(input.model)
637
- return model.needsRatio
638
- ? [{ key: 'ratio', schema: RatioSchema, message: 'Which aspect ratio?' }]
639
- : []
640
- },
641
- },
642
- }
643
- ```
644
-
645
- It receives the same `params` / `input` the handler receives — parsed, so
646
- defaults and coercions are already applied. Returning an empty array means this
647
- call needs nothing and runs straight through. Everything else is unchanged: the
648
- state is still signed and bound to principal, operation and argument digest, the
649
- rounds are still counted against `maxRounds`, and a resolved list with duplicate
650
- keys or more rounds than allowed is refused.
651
-
652
- **The plan is fingerprinted, and that matters more than it looks.** Between two
653
- rounds there is a full round trip to the host, and a resolver that reads
654
- anything outside its arguments — a model catalog, a feature flag — can answer
655
- differently the second time. Every other check would still pass: same principal,
656
- same operation, same arguments, round still in range. Round 2's question would
657
- be asked under round 1's key, and if the schemas happened to be compatible the
658
- user's answer would be accepted for a question nobody asked. So the resolved
659
- list is fingerprinted into the signed state and re-checked every round; a plan
660
- that moved is refused, not asked. A resolver that reads only its arguments never
661
- sees this.
662
-
663
- **What a dynamic declaration costs.** One extra pass through the contract
664
- pipeline per round — `access.gate.beforeHandle` runs once more and one more
665
- `toolPhase: 'input-round'` audit row is written. That is the price of ordering:
666
- the resolver is your code and may reach a network, so it runs **after**
667
- authorisation, never before, and the only thing that can authorise is a pipeline
668
- pass. Resolving itself is free — the arguments are parsed by the same pure
669
- function the call parses with, not by a second run of anything. A fixed list
670
- pays none of this; its call sequence is unchanged.
671
-
672
- One thing does change for a fixed list: the signed round state now carries a
673
- fingerprint of the question plan, and it is checked on every round. A
674
- conversation already in flight when you deploy this has no fingerprint in its
675
- state and is refused once with `INVALID_REQUEST_STATE`; the host re-asks and the
676
- retry succeeds.
677
-
678
- ### Guarding tools — `access`
679
-
680
- A tool call runs the same handler an HTTP request would. Every tool mount
681
- (`createMcpHandler`, `createStdioMcpServer`, `buildMcpServer`, `mountMcp`,
682
- `mountAgent`, `createToolInvoker`, managed `createCli` / `createCliInvoker`, and
683
- `createDeferredAgentToolSurface().mount`) requires an explicit `access` policy
684
- at compile time and at runtime before the first call (→ [ADR 0311](../decisions/0311-planned-breaking-release-access-expose-and-clean-boundaries.md)):
685
-
686
- - **`{ gate: { beforeHandle, afterHandle? } }`** — enforces a mandatory
687
- `beforeHandle` gate (pass the **same**
688
- [`createAuthHook`](./auth-and-errors.md#createauthhook) result used as the
689
- HTTP server's `authorize` hook, or compose multiple lifecycles with
690
- `composeToolLifecycle(authGate, ...)`).
691
- - **`{ open: 'public' | 'local-operator' | 'remote', afterHandle? }`** —
692
- explicitly declares why no `beforeHandle` gate runs on this surface.
693
-
694
- ```ts
695
- createMcpHandler({ serverInfo, auth, services, access: { gate: { beforeHandle: authHook } } })
696
- ```
697
-
698
- Omitting `access`, passing `{}` / `{ gate: {} }`, or passing the removed
699
- `lifecycle` key throws a `TypeError` naming the mount entrypoint at startup.
700
-
701
- The observability `hooks` are symmetric with the HTTP side too: `beforeToolCall`
702
- and `afterToolCall` receive the resolved **`MethodDef`** as `endpoint` —
703
- the tool-side twin of `afterHandle(ctx, result, endpoint)`. Read
704
- `endpoint.serviceName` / `.key` / `.meta` directly for an audit row; you do not
705
- need to rebuild a `toolName → identity` map:
706
-
707
- ```ts
708
- hooks: {
709
- afterToolCall: ({ result, durationMs, endpoint }) => {
710
- audit({
711
- service: endpoint.serviceName,
712
- action: endpoint.key,
713
- ok: result.ok,
714
- ms: durationMs,
715
- })
716
- },
717
- }
718
- ```
719
-
720
- > **Tool-path identity.** A tool call has no `req`, so `createAuthHook` resolves
721
- > identity through `resolveFromContext`, not `resolve`. Set it (read the
722
- > identity your `auth` / `context` injected) — without it a scoped tool call
723
- > has no identity and **fails closed**. See
724
- > [Auth on the tool surface](./auth-and-errors.md#auth-on-the-tool-surface--resolvefromcontext).
725
-
726
- ### Lazy tool discovery — `discovery`
727
-
728
- Large stateful MCP surfaces (for example stdio servers or stateful `McpServer` mounts with dozens of tools) can opt into lazy discovery so clients start with a compact initial tool list and reveal additional tools on demand:
729
-
730
- ```ts
731
- createStdioMcpServer({
732
- serverInfo: { name: 'my-mcp', version: '1.0.0' },
733
- auth: { userId: 'local-operator' },
734
- services,
735
- access: { gate: { beforeHandle: authHook } },
736
- discovery: {
737
- mode: 'lazy',
738
- initialTools: ['get_status'],
739
- searchToolName: 'tool_search', // default
740
- maxResults: 10, // default 10, range 1..50
741
- },
742
- })
743
- ```
744
-
745
- - **Opt-in only.** Omitting `discovery` keeps the default full `tools/list` surface untouched. In `'lazy'` mode `initialTools` is required (pass `[]` to hide every contract tool initially).
746
- - **Session-isolated reveal.** Every contract tool outside `initialTools` starts disabled on that `McpServer` instance. Calling `tool_search` ranks hidden tools by name and description (exact/phrase matches first, then deduplicated word matches), enables up to `maxResults` matches on that session's `McpServer`, and emits a single `notifications/tools/list_changed` when at least one new tool is revealed. Enabling tools in one session never mutates another session or the shared prepared surface.
747
- - **Identical access & catalog stamp.** `tool_search` and every revealed tool enforce the exact same `access` policy (`gate` / `inspect` / `open`), hooks, and `stitchkit/catalog` `_meta` stamp (which fingerprints the full underlying contract and runtime tool catalog, excluding synthetic `tool_search`). Unknown names in `initialTools`, `searchToolName` collisions with real tools, and out-of-range `maxResults` throw synchronously at mount time.
748
- - **Stateful mounts only.** `createMcpHandler` creates a fresh stateless `McpServer` per HTTP request and therefore refuses `discovery` synchronously with `TypeError`; use `discovery` on stateful mounts (`createStdioMcpServer`, `buildMcpServer`, `mountMcp`).
749
-
750
- ### MCP schema validation profile
751
-
752
- A contract schema that JSON Schema cannot represent (a `z.date()`, a `z.map()`)
753
- cannot become a tool. `schemaValidation.policy` decides what happens:
754
-
755
- - `'throw'` (default) — fail the build, listing every offending tool. A static
756
- `services` array is checked when `createMcpHandler` is constructed, so a bad
757
- schema fails the deploy, not the first request. Better than a tool that
758
- silently vanishes from the surface.
759
- - `'warn'` — log through `logger` and drop the tool.
760
- - `'skip'` — drop the tool silently.
761
-
762
- `validateMcpSchemas({ services })` runs the same check on its own — useful in a
763
- startup assertion or a test.
764
-
765
- For a static `services` array, collection, schema conversion and every enabled
766
- validation guard run once when the handler is created. Each HTTP request still
767
- receives a fresh `McpServer`, runner, context and native registration over that
768
- immutable prepared surface. A `services(auth)` factory
769
- is deliberately prepared after resolving each identity because its tool set may
770
- change by tenant.
771
-
772
- #### Is every property actually usable by a model?
773
-
774
- A tool schema is the only instruction a model gets about the shape of its
775
- arguments. A property that carries a `description` and no `type` / `enum` /
776
- `anyOf` / `$ref` tells it nothing — and nothing fails: the schema converts, the
777
- mount succeeds, the tool is advertised, and the model then guesses, retrying the
778
- same wrong guess because the error does not say what the right one would be.
779
-
780
- ```ts
781
- validateMcpSchemas({
782
- services,
783
- policy: 'throw',
784
- logger,
785
- extend,
786
- flattenUnionInput: true,
787
- requireTypedProperties: true,
788
- requirePortableFormats: true,
789
- allowFormats: [],
790
- })
791
- ```
792
-
793
- For an arbitrary **JSON value**, declare `z.json()`: its recursive JSON Schema
794
- describes strings, numbers, booleans, null, arrays and objects, so strict schema
795
- validation needs no exception. The schema refers to itself, so where a model
796
- provider refuses recursive schemas set `inputRecursionDepth` as well (below). `z.unknown()` means an unknown runtime value —
797
- including values JSON cannot represent — and therefore gives a model no usable
798
- shape. The guard is off by default for existing contracts. `allowUntyped` takes
799
- dotted `tool.property` paths and is reserved for a presentation value that is
800
- genuinely impossible to represent as JSON Schema. On `createMcpHandler`, put the policy under
801
- `schemaValidation`; the handler supplies its real `extend` and
802
- `flattenUnionInput`, so the check cannot vet a different document from the one
803
- advertised.
804
-
805
- `requirePortableFormats` rejects custom `format` values common MCP/AJV clients
806
- do not know, such as the `cuid2` emitted by `z.cuid2()`. Use a portable
807
- schema/pattern, or list it in `allowFormats` only when every client supports it.
808
- stitchkit never removes or rewrites the keyword.
809
-
810
- `findUntypedProperties(jsonSchema)` is the same walk, exported on its own if you
811
- want to assert on a schema you built elsewhere.
812
-
813
- ### Discriminated unions for weaker models — `flattenUnionInput`
814
-
815
- A discriminated union in a tool's input becomes a JSON Schema `oneOf` / `anyOf`.
816
- Capable models (Claude, Gemini, GPT) handle that; weaker / cheaper ones can drop
817
- the field or mangle its strings. Set `flattenUnionInput: true` (on
818
- `createMcpHandler` / `mountMcp` / `mountAgent`) to advertise each discriminated
819
- union as a **single flat object** instead — the discriminator becomes an enum and
820
- each field required by every variant stays required. Other fields become optional
821
- with `Available if <disc> = …` and, where applicable, `Required if <disc> = …` hints.
822
-
823
- **Branch explanations keep their meaning.** A shared description appears once;
824
- different descriptions are grouped by text and qualified with `When <disc> = …:`.
825
- A branch without a description does not inherit another branch's explanation.
826
- For example, an optional object `value` in `single` and a required array `value`
827
- in `group` advertise:
828
-
829
- ```text
830
- When kind = single: One reference.
831
- When kind = group: Two to ten references.
832
- Available if kind = single | group. Required if kind = group
833
- ```
834
-
835
- A third branch without `value` is absent from those labels. The object and array
836
- retain their separate shapes; the array's minimum length does not apply to the object.
837
- Discriminator values, branch explanation labels, enum values and joined
838
- properties keep the order of their first appearance across the variants, so the
839
- order you declare is the order the model reads. Alternatives of different kinds
840
- keep one canonical order, so one declaration always yields one document. → ADR [0221](../decisions/0221-flat-field-explanations-retain-branch-meaning.md).
841
-
842
- **A field several variants declare keeps its type.** Flattening puts every
843
- variant's fields side by side, so a key two variants share has to be advertised
844
- as one thing. Where they agree, that is what you get; where they disagree — a
845
- `.refine()` only one of them carries, two different bounds on the same number, an
846
- enum against a free string — the *constraint* is dropped and the **type** is not.
847
- A field that is a number in every variant is advertised as a number, not as a
848
- bare description. Scalar collisions keep every provable kind in a deterministic
849
- JSON Schema type array. If any alternative is an object or array, the property
850
- retains distinct structural alternatives in `anyOf`: object properties, typed
851
- array items, bounds and nullable values remain available to the model. Each
852
- alternative is described by the discriminator values that select it
853
- (`When type = image.`, or `When type = photo | video.` for a shape two values share),
854
- so the model can pair a shape with its value; the order of the alternatives is
855
- canonical, not the order of the variants. The
856
- containing discriminated union still becomes one object; flat mode does not
857
- promise to remove every nested union keyword. Only a branch whose kind is
858
- actually unknowable, such as a free-form schema or unresolved reference, leaves
859
- the collision unconstrained. → ADRs [0044](../decisions/0044-a-collided-field-keeps-its-type.md),
860
- [0205](../decisions/0205-flat-tool-collisions-retain-structural-alternatives.md)
861
- and [0267](../decisions/0267-a-flat-alternative-names-the-values-that-select-it.md).
862
-
863
- It is **deep** because the projection walks the generated JSON Schema document,
864
- including objects, arrays, tuples and schema-definition nodes. Structurally
865
- identifiable discriminated object unions are flattened wherever they occur.
866
- Plain unions and unions hidden behind unresolved external references remain
867
- unions because Stitchkit cannot soundly invent a discriminator.
868
-
869
- Use the default `flattenUnionInput: false` when the model must see the exact
870
- relationship between a discriminator and each branch. Joined property schemas
871
- describe allowed values without reconstructing those correlations.
872
-
873
- The flattened form is **lossy but never executable**. Per-variant refinements
874
- and incompatible constraints are widened in the presentation document; the
875
- original Zod contract enforces them exactly once inside `executeToolMethod`.
876
- MCP and AI adapters forward the raw argument object unchanged, so defaults,
877
- coercions and transforms cannot run before Stitchkit. Strict violations return
878
- the normal `VALIDATION_ERROR` tool envelope and fire `beforeToolCall` /
879
- `afterToolCall`. → [ADR 0050](../decisions/0050-presentation-schema-is-not-a-parser.md).
880
-
881
- ### Recursive inputs without references — `inputRecursionDepth`
882
-
883
- A recursive input (`z.lazy`, `z.json()`) is advertised as a definition that
884
- refers to itself. Some model providers refuse the whole request when one tool
885
- carries such a cycle; others accept it and never read a definition reached
886
- through `allOf: [{ $ref }]`. `inputRecursionDepth` advertises every input with
887
- no `$ref`, `definitions` or `$defs`:
888
-
889
- ```ts
890
- const projection = { flattenUnionInput: true, inputRecursionDepth: 1 } as const
891
-
892
- mountAgent(services, { access, runtimeTools, ...projection })
893
- createMcpHandler({ access, services, runtimeTools, ...projection, /* … */ })
894
- buildToolManifest({ services, runtimeTools, transport: 'AGENT', ...projection })
895
-
896
- // a tool whose model needs to see deeper nesting says so beside its name
897
- formula: { method: 'POST', path: '/formula', input, tool: { name: 'formula_create', inputRecursionDepth: 3 } }
898
- ```
899
-
900
- - Every reference is written out in place; the `allOf` wrapper beside a
901
- described reference merges into one node.
902
- - Each **recursive** definition is written out at most `N` times along any path;
903
- a reference without a cycle is always written out. Depth 1 shows one level of a
904
- formula, depth 3 a formula of three nested calls.
905
- - The reference past the last level becomes an **open node** typed by every JSON
906
- type the definition can take (`{ type: 'object' }`, `{ type: 'array', items: {} }`,
907
- or an `anyOf` of them). It accepts every value the definition accepts, so a
908
- deeper argument is never refused by the document — the handler still parses the
909
- contract's own recursive schema.
910
- - `tool.inputRecursionDepth` wins over the surface's value and projects that tool
911
- even where the surface sets none. Runtime tools, including tools discovered from
912
- a server, take the surface's `inputRecursionDepth` and `flattenUnionInput`.
913
- - Without the option the document is unchanged. With it, an `allowUntyped` path
914
- for a property inside a definition is reported from its full path.
915
-
916
- The depth is a number, not a size: a provider may limit nesting from above, and a
917
- model forced to call the tool may need more levels from below. Measure the cost
918
- with `describeToolCatalog({ …, maxSchemaBytes })`. → [ADR 0319](../decisions/0319-a-tool-input-can-be-advertised-without-references.md).
919
-
920
- ## `mountMcp`
921
-
922
- If you already run an `McpServer` from the SDK, `mountMcp` adds contract tools
923
- to it instead of owning the lifecycle:
924
-
925
- ```ts
926
- import { mountMcp } from 'stitchkit/tools/mcp'
927
-
928
- mountMcp(mcpServer, [usersService], {
929
- context: { source: 'mcp' },
930
- access: { gate: { beforeHandle: authHook } },
931
- })
932
- ```
933
-
934
- `createMcpHandler` is the batteries-included path; `mountMcp` is the building
935
- block under it.