stitchkit 0.132.3 → 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 (335) hide show
  1. package/CHANGELOG.md +172 -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/driver.d.ts +20 -2
  23. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  24. package/dist/agent-executor/claude-sdk/engine-spawn.d.ts +18 -0
  25. package/dist/agent-executor/claude-sdk/engine-spawn.d.ts.map +1 -0
  26. package/dist/agent-executor/claude-sdk/query-loop.d.ts +8 -11
  27. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  28. package/dist/agent-executor/claude-sdk/query-manager.d.ts +4 -2
  29. package/dist/agent-executor/claude-sdk/query-manager.d.ts.map +1 -1
  30. package/dist/agent-executor/claude-sdk/query-options.d.ts +1 -0
  31. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
  32. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  33. package/dist/agent-executor/codex/capabilities.d.ts +8 -0
  34. package/dist/agent-executor/codex/capabilities.d.ts.map +1 -0
  35. package/dist/agent-executor/codex/connect.d.ts +6 -1
  36. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  37. package/dist/agent-executor/codex/driver.d.ts +10 -0
  38. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  39. package/dist/agent-executor/codex/event-routing.d.ts +23 -1
  40. package/dist/agent-executor/codex/event-routing.d.ts.map +1 -1
  41. package/dist/agent-executor/codex/handlers.d.ts +23 -3
  42. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  43. package/dist/agent-executor/codex/limits.d.ts +17 -0
  44. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  45. package/dist/agent-executor/codex/request-answers.d.ts +23 -3
  46. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
  47. package/dist/agent-executor/codex/session-bind.d.ts +6 -1
  48. package/dist/agent-executor/codex/session-bind.d.ts.map +1 -1
  49. package/dist/agent-executor/codex/session-types.d.ts +5 -1
  50. package/dist/agent-executor/codex/session-types.d.ts.map +1 -1
  51. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  52. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  53. package/dist/agent-executor/codex/shared-thread.d.ts +6 -8
  54. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  55. package/dist/agent-executor/codex/thread-open.d.ts +12 -3
  56. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  57. package/dist/agent-executor/engine-requests.d.ts +42 -0
  58. package/dist/agent-executor/engine-requests.d.ts.map +1 -1
  59. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -1
  60. package/dist/agent-executor/handoff.d.ts.map +1 -1
  61. package/dist/agent-executor/image-input.d.ts +6 -5
  62. package/dist/agent-executor/image-input.d.ts.map +1 -1
  63. package/dist/agent-executor/profile.d.ts +3 -5
  64. package/dist/agent-executor/profile.d.ts.map +1 -1
  65. package/dist/agent-executor/session-primitives.d.ts +64 -3
  66. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  67. package/dist/agent-executor/testing/claude-sdk-stubs.d.ts +5 -0
  68. package/dist/agent-executor/testing/claude-sdk-stubs.d.ts.map +1 -0
  69. package/dist/agent-executor/testing/conformance-lifecycle.d.ts +11 -0
  70. package/dist/agent-executor/testing/conformance-lifecycle.d.ts.map +1 -0
  71. package/dist/agent-executor/testing/conformance-support.d.ts +23 -0
  72. package/dist/agent-executor/testing/conformance-support.d.ts.map +1 -0
  73. package/dist/agent-executor/testing/conformance.d.ts +7 -2
  74. package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
  75. package/dist/agent-executor/testing/consumer-stubs.d.ts +5 -3
  76. package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -1
  77. package/dist/agent-executor/testing/fake-codex-app-server.d.ts +5 -1
  78. package/dist/agent-executor/testing/fake-codex-app-server.d.ts.map +1 -1
  79. package/dist/agent-executor/testing/replay-driver.d.ts +6 -0
  80. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -1
  81. package/dist/agent-executor/testing/replay-gate.d.ts +4 -1
  82. package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -1
  83. package/dist/agent-runtime/deferred-tool-types.d.ts +2 -0
  84. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  85. package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
  86. package/dist/browser/client.d.ts.map +1 -1
  87. package/dist/browser/operation-refusal.d.ts +10 -0
  88. package/dist/browser/operation-refusal.d.ts.map +1 -0
  89. package/dist/contract/client-types.d.ts +13 -4
  90. package/dist/contract/client-types.d.ts.map +1 -1
  91. package/dist/contract/define-validation.d.ts +6 -0
  92. package/dist/contract/define-validation.d.ts.map +1 -1
  93. package/dist/contract/define.d.ts +3 -0
  94. package/dist/contract/define.d.ts.map +1 -1
  95. package/dist/contract/errors-factory.d.ts +8 -2
  96. package/dist/contract/errors-factory.d.ts.map +1 -1
  97. package/dist/contract/errors.d.ts +9 -0
  98. package/dist/contract/errors.d.ts.map +1 -1
  99. package/dist/contract/fingerprint.d.ts +4 -1
  100. package/dist/contract/fingerprint.d.ts.map +1 -1
  101. package/dist/contract/operation-refusals.d.ts +51 -0
  102. package/dist/contract/operation-refusals.d.ts.map +1 -0
  103. package/dist/contract/tool-options.d.ts +4 -0
  104. package/dist/contract/tool-options.d.ts.map +1 -1
  105. package/dist/entrypoints/agent-executor/acp.js +253 -210
  106. package/dist/entrypoints/agent-executor/claude-sdk.js +248 -173
  107. package/dist/entrypoints/agent-executor/claude.js +57 -109
  108. package/dist/entrypoints/agent-executor/codex.js +412 -335
  109. package/dist/entrypoints/agent-executor/testing/claude-sdk.d.ts +3 -0
  110. package/dist/entrypoints/agent-executor/testing/claude-sdk.d.ts.map +1 -0
  111. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +329 -0
  112. package/dist/entrypoints/agent-executor/testing.d.ts +1 -2
  113. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  114. package/dist/entrypoints/agent-executor/testing.js +413 -667
  115. package/dist/entrypoints/agent-executor.d.ts +1 -1
  116. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  117. package/dist/entrypoints/agent-executor.js +12 -12
  118. package/dist/entrypoints/agent-runtime/browser.js +2 -2
  119. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  120. package/dist/entrypoints/agent-runtime/harness.js +8 -8
  121. package/dist/entrypoints/agent-runtime/postgres.js +5 -5
  122. package/dist/entrypoints/agent-runtime/realtime.js +2 -2
  123. package/dist/entrypoints/agent-runtime/sandbox.js +3 -3
  124. package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
  125. package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
  126. package/dist/entrypoints/agent-runtime/testing.js +5 -5
  127. package/dist/entrypoints/agent-runtime.js +26 -18
  128. package/dist/entrypoints/application/grammy.js +1 -1
  129. package/dist/entrypoints/application.js +2 -2
  130. package/dist/entrypoints/cli.js +8 -8
  131. package/dist/entrypoints/contract.d.ts +3 -2
  132. package/dist/entrypoints/contract.d.ts.map +1 -1
  133. package/dist/entrypoints/contract.js +6 -4
  134. package/dist/entrypoints/files/packaging.d.ts +4 -1
  135. package/dist/entrypoints/files/packaging.d.ts.map +1 -1
  136. package/dist/entrypoints/files/packaging.js +868 -167
  137. package/dist/entrypoints/files.js +1 -1
  138. package/dist/entrypoints/handler.js +7 -7
  139. package/dist/entrypoints/http.js +2 -2
  140. package/dist/entrypoints/index.js +10 -8
  141. package/dist/entrypoints/node.js +11 -11
  142. package/dist/entrypoints/observability.js +1 -1
  143. package/dist/entrypoints/process/bootstrap.d.ts +3 -0
  144. package/dist/entrypoints/process/bootstrap.d.ts.map +1 -0
  145. package/dist/entrypoints/process/bootstrap.js +16 -0
  146. package/dist/entrypoints/process.js +7 -7
  147. package/dist/entrypoints/realtime.js +3 -3
  148. package/dist/entrypoints/remote.js +8 -7
  149. package/dist/entrypoints/server.js +30 -14
  150. package/dist/entrypoints/service-host/macos.js +72 -206
  151. package/dist/entrypoints/service-host/work.d.ts +15 -0
  152. package/dist/entrypoints/service-host/work.d.ts.map +1 -0
  153. package/dist/entrypoints/service-host/work.js +676 -0
  154. package/dist/entrypoints/service-host.js +146 -536
  155. package/dist/entrypoints/telegram/screens.js +4 -4
  156. package/dist/entrypoints/telegram.js +4 -4
  157. package/dist/entrypoints/testing.d.ts +2 -1
  158. package/dist/entrypoints/testing.d.ts.map +1 -1
  159. package/dist/entrypoints/testing.js +27 -8
  160. package/dist/entrypoints/tools/agent.js +6 -6
  161. package/dist/entrypoints/tools/connections.js +2 -2
  162. package/dist/entrypoints/tools/invoker.js +5 -5
  163. package/dist/entrypoints/tools/mcp.js +8 -6
  164. package/dist/entrypoints/tools/toolkit.js +11 -9
  165. package/dist/entrypoints/tools.js +19 -17
  166. package/dist/entrypoints/tracking/contract.js +1 -1
  167. package/dist/entrypoints/tracking/performance.js +3 -3
  168. package/dist/files/client-artifact.d.ts +14 -42
  169. package/dist/files/client-artifact.d.ts.map +1 -1
  170. package/dist/files/client-build.d.ts +57 -0
  171. package/dist/files/client-build.d.ts.map +1 -0
  172. package/dist/files/client-declarations.d.ts +35 -0
  173. package/dist/files/client-declarations.d.ts.map +1 -0
  174. package/dist/files/client-package-contract.d.ts +162 -0
  175. package/dist/files/client-package-contract.d.ts.map +1 -0
  176. package/dist/files/client-package-proof.d.ts +38 -0
  177. package/dist/files/client-package-proof.d.ts.map +1 -0
  178. package/dist/files/client-package.d.ts +17 -0
  179. package/dist/files/client-package.d.ts.map +1 -0
  180. package/dist/files/declaration-specifiers.d.ts +30 -0
  181. package/dist/files/declaration-specifiers.d.ts.map +1 -0
  182. package/dist/{index-v759mzed.js → index-02r5sq9p.js} +36 -23
  183. package/dist/{index-0r15pkjq.js → index-0k1ba0ss.js} +1 -1
  184. package/dist/{index-znd1b57f.js → index-1dn2wjq6.js} +5 -4
  185. package/dist/{index-p06z7g7w.js → index-1p8q0yrt.js} +6 -5
  186. package/dist/{index-wa6h4tz6.js → index-1qwd54n3.js} +6 -5
  187. package/dist/index-2dzc7mv9.js +174 -0
  188. package/dist/index-2mz8hj58.js +155 -0
  189. package/dist/{index-17qgm6xe.js → index-34k82crg.js} +2 -2
  190. package/dist/index-3mcbr8sx.js +349 -0
  191. package/dist/{index-ybdq8kk2.js → index-3y2tzhr8.js} +3 -3
  192. package/dist/{index-fgahdc7s.js → index-5n3a8hd8.js} +5 -3
  193. package/dist/{index-jb4m241t.js → index-6918kxbf.js} +45 -1
  194. package/dist/{index-n3bm7zqq.js → index-6kmjcm81.js} +4 -4
  195. package/dist/{index-akf0xkrm.js → index-78da4g74.js} +1 -1
  196. package/dist/{index-9pv126eh.js → index-7fjbdga8.js} +7 -1
  197. package/dist/{index-zhshhxew.js → index-8jf4bt7v.js} +1 -1
  198. package/dist/{index-p16q492v.js → index-8t9dr41h.js} +18 -5
  199. package/dist/{index-xq4s9mka.js → index-8yt3rwe7.js} +1 -1
  200. package/dist/{index-39c2hj6h.js → index-9c76vfxf.js} +7 -3
  201. package/dist/index-9ft4n9j1.js +432 -0
  202. package/dist/{index-sd4e5x5j.js → index-9wdrwx3b.js} +8 -7
  203. package/dist/{index-z114ax5e.js → index-an7vcmwf.js} +49 -2
  204. package/dist/{index-pzhqydxb.js → index-d04w81fz.js} +1 -1
  205. package/dist/index-d2drhb9c.js +219 -0
  206. package/dist/{index-8gmmdz7k.js → index-dacxr7nf.js} +1 -1
  207. package/dist/{index-dnzxxf8a.js → index-dm6nxkn1.js} +1 -1
  208. package/dist/index-dxft2mnm.js +42 -0
  209. package/dist/{index-rxh3qy4x.js → index-fzd477xk.js} +1 -1
  210. package/dist/{index-xgae0bn7.js → index-g4gstmp1.js} +2 -2
  211. package/dist/{index-athc412x.js → index-g5fgeb6v.js} +1 -1
  212. package/dist/{index-z9d74jmb.js → index-gbhj370g.js} +3 -3
  213. package/dist/{index-3fym4j8n.js → index-gtaaxe9d.js} +1 -1
  214. package/dist/{index-v59pxmf1.js → index-jpecjm30.js} +2 -2
  215. package/dist/index-k9g061ma.js +164 -0
  216. package/dist/{index-669374qc.js → index-ma26mfnt.js} +84 -315
  217. package/dist/{index-ryxb427v.js → index-msxf2r8x.js} +16 -3
  218. package/dist/{index-rbd2rq3z.js → index-nr4fhfn4.js} +1 -1
  219. package/dist/{index-qa2jjb65.js → index-pbekeqzm.js} +1 -1
  220. package/dist/{index-mkfhpk11.js → index-pq6g1k9t.js} +2 -2
  221. package/dist/{index-gya4hwh3.js → index-pws5c3x6.js} +21 -1
  222. package/dist/{index-x2fb37t0.js → index-q427q23r.js} +3 -2
  223. package/dist/{index-jcrj0b8z.js → index-qggqqja2.js} +39 -2
  224. package/dist/{index-jxtg307y.js → index-rkjfzs0a.js} +1 -1
  225. package/dist/{index-5tdc0q43.js → index-rw8ze745.js} +5 -3
  226. package/dist/index-s43tr4my.js +129 -0
  227. package/dist/{index-f9p62ean.js → index-stpy56r3.js} +175 -249
  228. package/dist/index-t5g5rm9n.js +213 -0
  229. package/dist/{index-z20pdxeb.js → index-tmv3ez1h.js} +3 -3
  230. package/dist/{index-dcsxj68j.js → index-tqjamnax.js} +1 -1
  231. package/dist/{index-j15dhkda.js → index-wddcfbng.js} +1 -325
  232. package/dist/{index-9sfhje6y.js → index-wh70tmpd.js} +24 -234
  233. package/dist/index-wxjv4sqx.js +82 -0
  234. package/dist/{index-qhjmmsm2.js → index-x46y9z26.js} +2 -2
  235. package/dist/{index-nk0cy9g1.js → index-y53cqwke.js} +1 -1
  236. package/dist/{index-sv5svtq7.js → index-y68gavb5.js} +1 -1
  237. package/dist/{index-5y7j383h.js → index-yrhw10ef.js} +1 -1
  238. package/dist/process/bootstrap.d.ts +12 -0
  239. package/dist/process/bootstrap.d.ts.map +1 -0
  240. package/dist/process/owner-loss-guard.d.ts +2 -9
  241. package/dist/process/owner-loss-guard.d.ts.map +1 -1
  242. package/dist/process/work-root.d.ts +20 -0
  243. package/dist/process/work-root.d.ts.map +1 -0
  244. package/dist/server/contract-identity.d.ts.map +1 -1
  245. package/dist/server/contract-method.d.ts +12 -0
  246. package/dist/server/contract-method.d.ts.map +1 -1
  247. package/dist/server/implement.d.ts.map +1 -1
  248. package/dist/server/openapi.d.ts.map +1 -1
  249. package/dist/server/types.d.ts +10 -9
  250. package/dist/server/types.d.ts.map +1 -1
  251. package/dist/service-host/host-adapter.d.ts +2 -0
  252. package/dist/service-host/host-adapter.d.ts.map +1 -1
  253. package/dist/service-host/work/command.d.ts +72 -0
  254. package/dist/service-host/work/command.d.ts.map +1 -0
  255. package/dist/service-host/work/errors.d.ts +29 -0
  256. package/dist/service-host/work/errors.d.ts.map +1 -0
  257. package/dist/service-host/work/host.d.ts +38 -0
  258. package/dist/service-host/work/host.d.ts.map +1 -0
  259. package/dist/service-host/work/launch.d.ts +51 -0
  260. package/dist/service-host/work/launch.d.ts.map +1 -0
  261. package/dist/service-host/work/membership.d.ts +51 -0
  262. package/dist/service-host/work/membership.d.ts.map +1 -0
  263. package/dist/service-host/work/origin.d.ts +79 -0
  264. package/dist/service-host/work/origin.d.ts.map +1 -0
  265. package/dist/service-host/work/owner.d.ts +45 -0
  266. package/dist/service-host/work/owner.d.ts.map +1 -0
  267. package/dist/service-host/work/placement.d.ts +55 -0
  268. package/dist/service-host/work/placement.d.ts.map +1 -0
  269. package/dist/service-host/work/probe.d.ts +24 -0
  270. package/dist/service-host/work/probe.d.ts.map +1 -0
  271. package/dist/service-host/work/scope-command.d.ts +68 -0
  272. package/dist/service-host/work/scope-command.d.ts.map +1 -0
  273. package/dist/sync/session.d.ts +4 -1
  274. package/dist/sync/session.d.ts.map +1 -1
  275. package/dist/testing/surface-manifest-digest.d.ts +2 -0
  276. package/dist/testing/surface-manifest-digest.d.ts.map +1 -1
  277. package/dist/testing/surface-manifest.d.ts +32 -3
  278. package/dist/testing/surface-manifest.d.ts.map +1 -1
  279. package/dist/tools/agent.d.ts +2 -0
  280. package/dist/tools/agent.d.ts.map +1 -1
  281. package/dist/tools/cli/stream-surface.d.ts.map +1 -1
  282. package/dist/tools/internal/mcp-projection.d.ts +58 -0
  283. package/dist/tools/internal/mcp-projection.d.ts.map +1 -0
  284. package/dist/tools/internal/surface-projector.d.ts +3 -47
  285. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  286. package/dist/tools/invoker.d.ts +2 -0
  287. package/dist/tools/invoker.d.ts.map +1 -1
  288. package/dist/tools/manifest.d.ts +2 -0
  289. package/dist/tools/manifest.d.ts.map +1 -1
  290. package/dist/tools/mcp/handler.d.ts.map +1 -1
  291. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -1
  292. package/dist/tools/mcp/mount.d.ts +4 -0
  293. package/dist/tools/mcp/mount.d.ts.map +1 -1
  294. package/dist/tools/mcp/prepare.d.ts +5 -2
  295. package/dist/tools/mcp/prepare.d.ts.map +1 -1
  296. package/dist/tools/mount.d.ts +2 -0
  297. package/dist/tools/mount.d.ts.map +1 -1
  298. package/dist/tools/remote.d.ts.map +1 -1
  299. package/dist/tools/schema/nesting-limit.d.ts +8 -0
  300. package/dist/tools/schema/nesting-limit.d.ts.map +1 -0
  301. package/dist/tools/schema/presentation.d.ts +7 -0
  302. package/dist/tools/schema/presentation.d.ts.map +1 -1
  303. package/dist/tools/surface.d.ts.map +1 -1
  304. package/llms/agent-executor-acp.txt +3 -3
  305. package/llms/agent-executor-claude-sdk.txt +1 -1
  306. package/llms/agent-executor-claude.txt +1 -1
  307. package/llms/agent-executor-codex.txt +1 -1
  308. package/llms/agent-executor-testing-claude-sdk.txt +28 -0
  309. package/llms/agent-executor-testing.txt +7 -8
  310. package/llms/agent-executor.txt +27 -4
  311. package/llms/agent-runtime.txt +1 -1
  312. package/llms/contract.txt +8 -2
  313. package/llms/files-packaging.txt +11 -6
  314. package/llms/process-bootstrap.txt +18 -0
  315. package/llms/process.2.txt +215 -18
  316. package/llms/process.txt +130 -92
  317. package/llms/server.4.txt +49 -1
  318. package/llms/service-host-work.txt +34 -0
  319. package/llms/stitchkit.2.txt +31 -0
  320. package/llms/stitchkit.txt +78 -75
  321. package/llms/sync.txt +5 -2
  322. package/llms/testing.txt +1 -0
  323. package/llms/tools.2.txt +747 -775
  324. package/llms/tools.3.txt +846 -210
  325. package/llms/tools.4.txt +226 -0
  326. package/llms/tools.txt +3 -790
  327. package/llms/{upgrading-0.128.0-0.132.0.txt → upgrading-0.128.0-0.133.0.txt} +194 -6
  328. package/llms/upgrading.txt +1 -1
  329. package/llms-full.txt +746 -135
  330. package/llms.txt +18 -16
  331. package/package.json +12 -4
  332. package/dist/entrypoints/process/owner-loss.d.ts +0 -3
  333. package/dist/entrypoints/process/owner-loss.d.ts.map +0 -1
  334. package/dist/entrypoints/process/owner-loss.js +0 -7
  335. package/llms/process-owner-loss.txt +0 -18
package/llms/tools.2.txt CHANGED
@@ -1,4 +1,4 @@
1
- # stitchkit/tools — stitchkit docs slice, part 2 of 3
1
+ # stitchkit/tools — stitchkit docs slice, part 2 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,905 +7,877 @@
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) (continued)
14
15
  ==============================================================================
15
16
 
16
- ## MCP over stdio — `createStdioMcpServer`
17
+ ## MCP — `createMcpHandler`
17
18
 
18
- `createMcpHandler` serves MCP over HTTP. `createStdioMcpServer` serves the same
19
- contract tools over **stdio** — the server runs as a subprocess of the MCP
20
- client (Claude Desktop, Claude Code, Cursor, Codex), on the user's machine, so
21
- it can reach the local filesystem.
19
+ An MCP-only server imports `stitchkit/tools/mcp` and installs
20
+ `stitchkit`, `zod` and `@modelcontextprotocol/server`. The leaf's runtime and strict
21
+ NodeNext declarations require no `ai`. It exports the existing HTTP/stdio server,
22
+ schema policy, catalog and resource helpers, and it is the only entrypoint that does:
23
+ `stitchkit/tools` loads no optional peer. AI SDK tools come from `stitchkit/tools/agent`.
24
+
25
+ `createMcpHandler` builds a complete stateless Streamable-HTTP MCP endpoint on
26
+ the official TypeScript SDK v2 server package. It owns server creation,
27
+ protocol-era negotiation and shutdown; application code does not import the SDK
28
+ to mount a normal endpoint.
22
29
 
23
30
  ```ts
24
- import { bindStdioProcessSignals, createStdioMcpServer } from 'stitchkit/tools/mcp'
31
+ import { createMcpHandler, createMcpHttpRoute } from 'stitchkit/tools/mcp'
32
+ import { createServer } from 'stitchkit/server'
25
33
 
26
- const stdio = await createStdioMcpServer({
34
+ const mcp = createMcpHandler({
27
35
  serverInfo: { name: 'my-app', version: '1.0.0' },
28
- auth: resolveIdentity(), // resolved once at startup, not per request
29
- services: [usersService],
36
+ auth: (req) => resolveApiKey(req), // → an identity, or null for 401
37
+ services: [usersService, catalogService],
30
38
  access: { gate: { beforeHandle: authHook } },
31
39
  })
32
40
 
33
- const signals = bindStdioProcessSignals(stdio, {
34
- onClose: () => stopWorkers(),
35
- onComplete: () => { process.exitCode = 0 },
36
- onError: (_phase, error) => {
37
- console.error(error) // stderr only — stdout is JSON-RPC
38
- process.exitCode = 1
39
- },
41
+ createServer({
42
+ services,
43
+ rawRoutes: [createMcpHttpRoute({ path: '/mcp', handler: mcp })],
40
44
  })
41
45
 
42
- await signals.promise
46
+ // During graceful shutdown:
47
+ await mcp.close()
43
48
  ```
44
49
 
45
- A stdio server is a single process serving one client, so `auth` is a value (or
46
- a promise of one) resolved once at startup — typically from an env var — rather
47
- than a per-request `(req) => …`. Keep all logging on **stderr**: stdout is the
48
- JSON-RPC channel.
50
+ ### `McpHandlerConfig`
49
51
 
50
- The default `legacy: 'serve'` negotiates the modern or supported legacy opening
51
- through the official stdio adapter. Use `legacy: 'reject'` for a modern-only
52
- binary. Each invocation builds a fresh server; the returned handle owns
53
- transport shutdown.
52
+ | Field | Purpose |
53
+ |-------|---------|
54
+ | `serverInfo` | MCP server identity — `{ name, version }` |
55
+ | `auth` | `(req) => identity \| null` — `null` rejects with 401 |
56
+ | `services` | the services to expose — an array, or `(auth) => ServiceDef[]` |
57
+ | `runtimeTools` | managed pathless operations — an array, or `(auth) => RuntimeToolDefinition[]` |
58
+ | `surfaces` | finite `{ key: { services, runtimeTools } }` registry prepared eagerly |
59
+ | `selectSurface` | `(auth) => declaredKey` — required with `surfaces` |
60
+ | `context` | `(auth) => {…}` — values merged into every tool handler's `ctx` |
61
+ | `access` | **required** — `{ gate: { beforeHandle, afterHandle? } }` or `{ open: 'public' \| 'local-operator' \| 'remote', afterHandle? }` (see below) |
62
+ | `multiRound` | Typed MRTR state policy for guarded multi-round tool calls |
63
+ | `hooks` | tool-call observability hooks — `afterToolCall` fires on every result |
64
+ | `extend` | extra advertised arguments resolved into handler context |
65
+ | `schemaValidation` | compatibility policy, typed-property guard and portable-format guard |
66
+ | `logger` | a `StitchLogger` for the `'warn'` policy |
67
+ | `rawTools` | `(server, auth) => …` — explicit SDK registration without framework guarantees |
68
+ | `resources` | MCP Apps `ui://` resources mounted on every server |
69
+ | `instructions` | a short host-facing usage hint, surfaced to MCP tool-search |
70
+ | `coerceJsonArgs` | coerce JSON-stringified object/array arguments (default `true`) |
71
+ | `flattenUnionInput` | advertise discriminated unions as one object (default `false`) |
72
+ | `inputRecursionDepth` | advertise inputs with no `$ref`, recursion unrolled this many levels (default: references stay) |
73
+ | `inputNestingDepth` | keep every advertised input within this many nesting levels, as a provider counts them (default: no limit) |
74
+ | `errorHint` | add a project-owned hint to failed tool results |
75
+ | `onOutputStrip` | observe output keys removed by contract validation |
76
+ | `protectedResource` | RFC 9728 metadata used by HTTP `401` responses |
77
+ | `legacy` | `'serve'` (default) or `'reject'` for pre-2026 clients |
78
+ | `security` | optional Host/Origin allowlists at the Fetch boundary |
79
+ | `onTransportRejected` | observe HTTP/protocol rejections without entering lifecycle or tool hooks |
80
+ | `cache` | explicit operation cache hints; omitted means zero/private |
81
+
82
+ Direct `services` / `runtimeTools` factories, `context`, `selectSurface` and
83
+ `rawTools` receive the resolved identity, so a tenant can be shown only its own
84
+ tools and every handler can read `ctx.tenantId`.
85
+
86
+ Use direct factories only when the definitions are genuinely arbitrary per
87
+ identity. For a bounded role/plan set, declare a finite registry instead:
54
88
 
55
- Signal binding is explicit: `createStdioMcpServer` installs no global process
56
- listeners by itself. The first `SIGINT`/`SIGTERM` starts exactly one official
57
- `close()` chain. Stdio has no force primitive, so a later signal restores the
58
- OS default disposition instead of reporting a fictional forced result.
59
- `signals.close()` removes an idle binding; the framework never calls
60
- `process.exit()` or chooses the exit code. See
61
- [deployment lifecycle](./testing-and-deployment.md#stdio-process-signals).
89
+ ```ts
90
+ const handleMcp = createMcpHandler({
91
+ serverInfo,
92
+ auth,
93
+ surfaces: {
94
+ admin: { services: allServices, runtimeTools: [renderPreview] },
95
+ member: { services: memberServices, runtimeTools: [renderPreview] },
96
+ },
97
+ selectSurface: (identity) => identity.isAdmin ? 'admin' : 'member',
98
+ context: (identity) => ({ identity }),
99
+ access: { gate: { beforeHandle: authHook } },
100
+ })
101
+ ```
62
102
 
63
- Both transports build the server through the shared `buildMcpServer` — same
64
- contract/runtime pipeline, same surface selection, context, hooks, raw escape
65
- hatch and instructions.
103
+ Every declared entry is schema-validated and prepared once when the handler is
104
+ constructed. The selected immutable descriptors are shared; the SDK server,
105
+ transport, auth-derived context, lifecycle runner and tool-call context are
106
+ fresh for every request. Unknown keys
107
+ fail before the server connects. The registry never retains auth values.
108
+
109
+ ### Stateless transport and protocol eras
110
+
111
+ Every request gets a fresh SDK server, resolved auth/context and tool-call
112
+ runner. Static direct and finite registry schemas are still prepared once when
113
+ the handler is constructed. There is no session map, event store,
114
+ `Mcp-Session-Id` or resumable cross-request SSE state. Process replacement and
115
+ load balancing therefore cannot strand a client on an in-memory session.
116
+
117
+ The default `legacy: 'serve'` lets the official SDK negotiate either modern
118
+ `2026-07-28` or the supported legacy stateless opening on this same endpoint.
119
+ Set `legacy: 'reject'` when every host is modern. Legacy support is protocol
120
+ translation inside the SDK, not a second Stitchkit transport or compatibility
121
+ API. Stateful MCP and subscriptions are intentionally outside this layer.
122
+
123
+ `createMcpHttpRoute` is the framework-owned raw-route adapter. It registers
124
+ `ALL` because Streamable HTTP uses multiple HTTP methods, delegates only to
125
+ `handler.fetch`, and leaves lifecycle ownership with the returned handler.
126
+
127
+ By default, a present `Host` header must match the request URL and a present
128
+ browser `Origin` must be same-origin. Non-browser hosts may omit `Origin`. Behind
129
+ a trusted reverse proxy, reconstruct the public request URL before calling the
130
+ handler or configure exact `security.allowedHosts` / `allowedOrigins`; never
131
+ copy arbitrary forwarded headers into the trusted URL. If a browser calls MCP
132
+ cross-origin, its HTTP server or gateway must also answer CORS preflight and
133
+ expose the protocol headers. `onTransportRejected` is the audit boundary for
134
+ HTTP/security rejections; it is deliberately separate from tool lifecycle and
135
+ must not be used as authorization input.
136
+
137
+ ### Modern discovery, routing and cache hints
138
+
139
+ Stitchkit forwards the negotiated protocol era and validated MCP request data
140
+ to both `RequestEvent.mcp` and the current managed call's typed `context.mcp`;
141
+ untrusted routing headers never become application identity. The SDK validates
142
+ `MCP-Protocol-Version`, JSON-RPC shape and routing
143
+ metadata before lifecycle or tool handlers run. Framework-owned tool and
144
+ resource registration preserves declaration order across HTTP and stdio. Tool
145
+ manifests preserve mount order; `listToolNames` is a sorted diagnostics view.
146
+ Consumer-owned raw SDK registrations are outside this guarantee.
147
+
148
+ Caching is opt-in. `cache.operations` maps directly to SDK v2 operation cache
149
+ hints, while each `McpResourceDef` may declare its own `cacheHint`. Omission
150
+ means zero/private: neither a prepared surface nor a deterministic response is
151
+ silently treated as public. Unbounded auth-selected surface factories are
152
+ always forced to zero/private even when an operation policy is present; use a
153
+ finite `surfaces` registry when identities share a provably immutable surface.
154
+ Stitchkit never advertises list-change or subscription capabilities
155
+ without an implementation.
156
+
157
+ ### Knowing your catalog is stale — the catalog stamp
158
+
159
+ A client lists the tools once and keeps that list. If the server's contract
160
+ moves afterwards, the client's copy is wrong and *nothing tells it so*: calls
161
+ are refused, and from inside the client a refusal looks like a broken server.
162
+ This is the most expensive shape a contract disagreement takes, because the
163
+ party able to fix it is the one with no evidence.
164
+
165
+ Every advertised tool and every tool result therefore carries the fingerprint of
166
+ the catalog it came from:
66
167
 
67
- ## OAuth 2.1 — a native remote connector
168
+ ```ts
169
+ import { readMcpCatalogStamp } from 'stitchkit/tools/mcp';
170
+
171
+ const listed = await client.listTools();
172
+ let known = readMcpCatalogStamp(listed.tools[0]?._meta); // { digest, tools }
68
173
 
69
- A remote MCP server is connectable from Claude (Desktop / web "custom
70
- connector") only through the MCP authorization spec: OAuth 2.1 with PKCE, plus
71
- the discovery documents (RFC 9728 / 8414), Client ID Metadata Documents (CIMD)
72
- and resource indicators (RFC 8707). A Bearer-only server returns a
73
- bare `401` and the connector never establishes.
174
+ const result = await client.callTool({ name: 'record_journal', arguments });
175
+ const live = readMcpCatalogStamp(result._meta);
176
+ if (live && known && live.digest !== known.digest) {
177
+ // The catalog moved under us. Re-list before blaming the result.
178
+ known = readMcpCatalogStamp((await client.listTools()).tools[0]?._meta);
179
+ }
180
+ ```
74
181
 
75
- stitchkit ships the OAuth **protocol mechanics**; the app supplies only
76
- **identity and storage**. Three pieces wire it together:
182
+ The comparison costs nothing and runs on a response you were already receiving —
183
+ including a refusal, which is exactly when a stale catalog is the likeliest
184
+ explanation. `notifications/tools/list_changed` is the push-shaped answer to the
185
+ same problem and `createMcpHandler` cannot send it: it is stateless by
186
+ construction, so there is no retained session to push down.
187
+
188
+ The digest covers each advertised tool's name, description, input schema, output
189
+ schema, annotations and MCP Apps `ui` resource, and nothing else — it moves when the
190
+ contract moves and not when a handler does. Raw SDK registrations stay consumer-owned
191
+ and are outside it, so a handler with `rawTools` sends no stamp header.
192
+
193
+ `createMcpHandler` also sends the stamp of the surface each request was served from as
194
+ the `stitchkit-catalog` response header (the same `{ digest, tools }` JSON), on the
195
+ `initialize` answer included — the SDK assembles that result itself and leaves no
196
+ `_meta` to fill. A client can therefore tell whether its stored catalog is current
197
+ before it asks for `tools/list`; `defineMcpClientConnection({ catalog })` does exactly
198
+ that ([CLI → commands discovered from a running server](./cli.md#commands-discovered-from-a-running-server)).
199
+
200
+ ### Saying which tools only read — `readOnlyHint`
201
+
202
+ A host reads a tool's `annotations` to group tools and to choose permission
203
+ defaults, and a CLI mounted over this surface reads them to decide what a
204
+ refused view may withhold ([CLI → views](./cli.md#aggregate-views)). The server publishes the
205
+ annotations the tool declared, and states `readOnlyHint: true` for a read that
206
+ declared none:
207
+
208
+ | The tool | Published `readOnlyHint` |
209
+ |---|---|
210
+ | declares `readOnlyHint`, either way | as declared |
211
+ | `effect: 'write'` with no `readOnlyHint` (even on `GET`) | none |
212
+ | `effect: 'read'` with no `readOnlyHint` and `destructiveHint !== true` (even on non-`GET`) | `true` |
213
+ | `GET` with no `readOnlyHint`, no `effect: 'write'`, and `destructiveHint !== true` | `true` |
214
+ | any other method, or `destructiveHint: true` with no `readOnlyHint` | none |
215
+
216
+ A runtime tool follows the same rule by its `identity.effect` and `identity.method`. A raw SDK
217
+ registration (`mountWait`, `mountViewFile` and the like) publishes only what it
218
+ passes. The catalog digest hashes the published annotations, so it moves once
219
+ when a server starts publishing the derived hint.
220
+
221
+ > **A `GET` with a write effect must say so.** Hosts may run a tool that publishes
222
+ > `readOnlyHint: true` without asking. An endpoint that changes something on
223
+ > `GET` — marks as seen, rotates a token — declares `effect: 'write'` or
224
+ > `tool: { annotations: { readOnlyHint: false } }`.
225
+
226
+ A client connection (`defineMcpClientConnection`) carries the hints a server
227
+ published onto the tools it mounts, field by field: a hint of the wrong type is
228
+ dropped and the tool stays. The mounted tool is as read-only as its server says
229
+ it is, and a surface that re-publishes mounted tools passes those hints on.
230
+
231
+ ### Shaping arguments before validation — `beforeToolCall`
232
+
233
+ `beforeToolCall` sees the arguments as they arrived and may **replace** them:
77
234
 
78
235
  ```ts
79
- import { mountOAuthProvider, oauthProtectedResourceRoute } from 'stitchkit/tools'
80
- import { createMcpHandler, createMcpHttpRoute } from 'stitchkit/tools/mcp'
81
- import { createServer } from 'stitchkit/server'
236
+ hooks: {
237
+ beforeToolCall: async ({ args }) =>
238
+ typeof args.id === 'string' && args.id.startsWith('@')
239
+ ? { ...args, id: await resolveReference(args.id) }
240
+ : undefined, // undefined / null / nothing → unchanged
241
+ }
242
+ ```
82
243
 
83
- const resource = 'https://api.example.com/mcp'
84
- const issuer = 'https://api.example.com'
244
+ The replacement is validated by the contract schema like any other input, so this
245
+ shapes a call and never bypasses the schema — a hook returning something the
246
+ contract refuses produces an ordinary `VALIDATION_ERROR`. It runs before the
247
+ params/input split, before argument coercion and before both schemas, which is
248
+ why a field declared `z.string()` can receive a reference and still be a string by
249
+ the time it is checked. `access.gate.beforeHandle` is too late for this: the schemas
250
+ have already answered.
85
251
 
86
- // 1. Resource server — the 401 now points at the metadata.
87
- const mcp = createMcpHandler({
88
- serverInfo: { name: 'my-app', version: '1.0.0' },
89
- auth: resolveOAuthToken, // validate the Bearer JWT (verifyJwt + audience)
90
- services,
91
- access: { gate: { beforeHandle: authHook } },
92
- protectedResource: { resource, authorizationServers: [issuer] },
93
- })
252
+ The audit trail is unaffected. `afterToolCall` reports what the caller sent as
253
+ `args` and the replacement separately as `effectiveArgs`, so a rewrite is visible
254
+ as a rewrite rather than by overwriting the evidence.
94
255
 
95
- // 2. Authorization server — CIMD, /authorize (PKCE), /token.
96
- const oauthRoutes = mountOAuthProvider({
97
- issuer,
98
- resource,
99
- signingSecret: env.OAUTH_SECRET,
100
- clientRegistration: {
101
- preRegistered: { get: getFirstPartyClient },
102
- // CIMD is enabled with secure defaults; DCR remains disabled.
103
- },
104
- codes, refreshTokens, // your stores (DB or in-memory)
105
- authorizeUser, // → { userId, approvedScopes } | Response
106
- })
256
+ ### Knowing the outcome of a call — `afterToolCall` and `toolCallId`
107
257
 
108
- createServer({
109
- services,
110
- rawRoutes: [
111
- createMcpHttpRoute({ path: '/mcp', handler: mcp }),
112
- oauthProtectedResourceRoute({ resource, authorizationServers: [issuer] }),
113
- ...oauthRoutes,
114
- ],
115
- })
116
- ```
258
+ `afterToolCall` receives the whole `ToolResult` — `{ok: true, data}` or
259
+ `{ok: false, code, …}` — on every exit, including a validation failure that never
260
+ reached the handler, and on all three transports. It is the answer to "did this
261
+ call fail"; deriving that from the serialized error text instead is the mistake
262
+ this section exists to prevent, and it is a mistake that does not announce itself:
263
+ one consumer had five places asking the question and getting five answers.
117
264
 
118
- Access tokens are signed HS256 JWTs (`signJwt`) whose `aud` is the resource and
119
- whose `iss` is the issuer — validate both in `auth` with
120
- `verifyJwt(token, secret, { audience: resource, issuer })`. `authorizeUser` is
121
- where the app authenticates the user (reuse an existing session) and records
122
- consent; return `{ userId, approvedScopes }`, where approved scopes are a subset
123
- of the requested/supported values, or a `Response` to redirect the browser to a
124
- login page first. The AS and resource server can co-locate or live
125
- on separate origins. See
126
- [ADR 0015](../decisions/0015-oauth-resource-server.md).
127
-
128
- Client resolution is deterministic: exact pre-registered client, then an HTTPS
129
- URL client id resolved as CIMD, then explicitly enabled DCR. CIMD is on by
130
- default; DCR is off unless `clientRegistration.dcr` supplies both `register` and
131
- `get`. A CIMD-only deployment therefore exposes neither `/register` nor a
132
- `registration_endpoint`. The metadata document must declare a `client_id` that
133
- exactly equals its URL, explicit redirect URIs and
134
- `token_endpoint_auth_method: 'none'`.
135
-
136
- The token endpoint and `/register` read at most 64 KiB of a request body, or
137
- `maxRequestBodyBytes` when you set it; a larger one is answered `413` with
138
- `invalid_request` and the rest is not read.
139
-
140
- The production fetcher rejects credentials, fragments, non-HTTPS URLs and
141
- private/reserved targets. Every redirect is DNS-resolved and IP-pinned again;
142
- timeouts, redirect count and body size are bounded. Its bounded cache respects
143
- `Cache-Control` (including `no-store`/`no-cache`), `Age`, `Expires`, `ETag` and
144
- `Last-Modified`, coalesces concurrent misses and reports sanitized cache events;
145
- invalid or unavailable identity receives only a short fail-closed cache entry.
146
-
147
- Resolution itself is rate-limited on two levels (`CimdCachePolicy`):
148
- `maxResolutionsPerClient` (default 10) bounds ONE `client_id` per
149
- `resolutionWindowMs` window (default 60 s) — a client whose document disables
150
- caching burns its own budget, not the server's — while `maxResolutions`
151
- (default 120) caps the server-wide outbound rate as the flood backstop.
152
- Positive and negative cache entries keep separate pools of `maxEntries` each,
153
- so a flood of unresolvable ids cannot evict warmed clients and a burst of
154
- successes cannot reset a failing client's backoff.
155
-
156
- ### Authorization hardening (MCP 2026-07-28)
157
-
158
- - **`iss` on every authorization response (RFC 9207, SEP-2468).** Success *and*
159
- error redirects carry `iss`, and the AS metadata advertises
160
- `authorization_response_iss_parameter_supported: true`. A client that talks to
161
- several authorization servers validates `iss` before redeeming the code, which
162
- closes the **mix-up attack** — an attacker's server cannot pass its response
163
- off as this issuer's. Additive on the wire: a client that ignores `iss` is
164
- unaffected.
165
- - **`application_type` on registration (SEP-837).** A client may declare
166
- `"native"` (desktop / CLI) or `"web"` in its DCR body. A **native** client may
167
- register an `http` loopback redirect (`http://127.0.0.1:…`, RFC 8252 §7.3); a
168
- **web** client is held to `https` only — that mismatch is the usual cause of
169
- the `redirect_uri` rejection CLI clients hit. Omit the field and registration
170
- behaves exactly as before (loopback allowed); an unknown value is rejected
171
- rather than silently defaulted.
172
-
173
- > Dynamic Client Registration is an explicit interoperability mode, not the
174
- > default. Enabling it changes public discovery and adds `/register`; keep it off
175
- > unless a client that cannot publish CIMD requires it.
176
-
177
- ## Proxying a remote API — `implementRemote`
178
-
179
- `implement` binds a contract to local handlers. `implementRemote` binds it to a
180
- remote HTTP API instead — every handler forwards the call to a deployed server
181
- through the contract's typed client:
265
+ To correlate an outcome with the call the model made, read `context.toolCallId`:
182
266
 
183
267
  ```ts
184
- import { createHttpClient } from 'stitchkit'
185
- import { implementRemote } from 'stitchkit/remote'
186
- import { createStdioMcpServer } from 'stitchkit/tools/mcp'
268
+ hooks: {
269
+ afterToolCall: ({ context, result }) => {
270
+ loop.record(context.toolCallId, result.ok ? 'ok' : result.code);
271
+ },
272
+ }
273
+ ```
187
274
 
188
- const http = createHttpClient({
189
- baseUrl: 'https://api.example.com',
190
- headers: () => ({ Authorization: `Bearer ${apiKey}` }),
191
- })
275
+ Two exits are deliberately **not** reported: a runtime tool presenter that throws
276
+ on the agent surface (the AI SDK calls it after `execute` has already returned)
277
+ and `ToolExecutionControlError`, which is a run being stopped rather than a tool
278
+ failing — check it with `isToolExecutionControlError`.
192
279
 
193
- const stdio = await createStdioMcpServer({
194
- serverInfo: { name: 'my-app', version: '1.0.0' },
195
- auth: null,
196
- services: contracts.map((c) => implementRemote(c, http)),
197
- access: { open: 'remote' },
198
- })
280
+ ### Restartable tool bodies — `durability`
199
281
 
200
- // During graceful shutdown:
201
- await stdio.close()
202
- ```
203
-
204
- This is how you ship a thin **local** MCP server for an API that already runs in
205
- the cloud: the local process owns only the transport and any filesystem-facing
206
- native tools, while every contract tool proxies to the remote API. One contract,
207
- no duplicated business logic.
208
-
209
- `implementRemote(contract, http, { transformArgs })` takes an optional
210
- `transformArgs` hook that rewrites a call's arguments before they are forwarded
211
- — e.g. to upload a local file referenced in the args and swap in its URL.
212
-
213
- The call's signal reaches the existing typed HTTP client's request options, for endpoints
214
- with or without arguments. An already cancelled call, including cancellation while an async
215
- argument transform runs, dispatches no request. Bind your process signal to `createCli` or
216
- `createCliInvoker`; `REQUEST_ABORTED` is a safe nonretryable failure with CLI exit `130`.
217
- Cooperative origins observe `ctx.signal` and release resources when their work ends. An
218
- origin or provider ignoring cancellation may continue after the local wait stops.
219
-
220
- An explicit `AppError.retryable` boolean also survives this remote hop. `false` on `502` and
221
- `true` on `409` remain the application's recommendation through HTTP, CLI, MCP and AI tools.
222
- Absent metadata keeps the previous defaults and does not alter HTTP transport retries.
223
-
224
- A remote failure that carries no stitchkit error envelope — an HTML `503` from a proxy
225
- during a deploy, a `429` from a rate limiter, a `404` page, a refused connection — keeps
226
- what the caller can act on and drops what it must not see. A response with a status
227
- becomes `HTTP_ERROR` with that status and a fixed message; a failure with no response
228
- becomes `CONNECTION_REQUEST_FAILED` (`502`). Neither carries `details`: the upstream
229
- body, URL and credentials stay in the raw cause that `onToolError` and `AgentToolError.cause`
230
- expose in-process. One rule decides `retryable` for every origin: the declared value wins,
231
- otherwise the status decides (`408`, `429`, `502`, `503`, `504` are retryable, as for any
232
- local tool). A call the caller cancelled (`REQUEST_ABORTED`) declares `retryable: false`;
233
- a deadline the remote client hit (`REQUEST_TIMEOUT`, `408`) follows the status like a
234
- `408` from a local handler.
235
-
236
- ## Structured output
237
-
238
- When a contract endpoint or runtime tool declares `output`, its MCP tool
239
- registers that exact schema as `outputSchema` and returns the validated value as
240
- `structuredContent` alongside a JSON text block. Every JSON root type is kept
241
- unchanged: object, array, string, number, boolean and `null`. Stitchkit does not
242
- wrap non-object values in `{ result }`; protocol-era adaptation belongs to the
243
- official SDK.
244
-
245
- A tool without an output contract advertises no `outputSchema` and returns no
246
- invented structured value. Its successful MCP result has an empty `content`
247
- list.
248
-
249
- ## A different answer for tools — `withToolView`
250
-
251
- An admin page wants the full record; a model wants a card. Every byte of a
252
- tool result enters the model's context and stays in its history, and personal
253
- fields a task does not need are better never shown to it. Two endpoints on one
254
- path (one `expose: ['HTTP']`, one for the tools) duplicate the description, the
255
- schemas and the handler; branching on `ctx.source` teaches every handler about
256
- transports and still advertises the full output schema.
257
-
258
- A **tool view** declares the difference on the endpoint instead. Most often the
259
- difference is only the call — a model needs a lighter one, and the answer keeps
260
- its one shape:
282
+ A tool that starts slow work and must report exactly once, including after a host
283
+ restart, can keep that bookkeeping **inside** the tool:
261
284
 
262
285
  ```ts
263
- import { defineContract, withToolView } from 'stitchkit';
264
-
265
- export const items = defineContract({ prefix: 'items' }, {
266
- list: withToolView(
267
- {
268
- method: 'GET', path: '/:slug/items', desc: 'List items', tool: { name: 'db_items' },
269
- input: ItemsQuery, // include: z.array(...).default(['relations'])
270
- output: ItemsResponse, // one answer on HTTP and on the tools
271
- },
272
- { defaults: { include: [] } }, // what a tool call gets when it passes nothing
273
- ),
286
+ mountAgent(services, {
287
+ access: { gate: { beforeHandle: authHook } },
288
+ durability: (toolCallId, signal) => myLedgerFor(toolCallId, signal),
274
289
  });
290
+
291
+ // in the handler
292
+ const asset = await ctx.step('render', () => renderAsset(ctx.input));
293
+ await ctx.waitFor({ event: 'render-done', id: assetId });
275
294
  ```
276
295
 
277
- When the answer itself differs, the view carries its own schema too:
296
+ `ToolDurability` is the port a tool body sees — `step`, `sleep`, `waitFor`. You
297
+ do not have to implement it: the engine ships from `stitchkit/tools`, and it needs
298
+ a ledger of two methods over storage you already have:
278
299
 
279
300
  ```ts
280
- import { defineContract, withToolView } from 'stitchkit';
281
-
282
- export const users = defineContract({ prefix: 'users' }, {
283
- list: withToolView(
284
- {
285
- method: 'GET', path: '/', desc: 'List users', tool: { name: 'user_list' },
286
- input: UserListQuery, // include: z.array(...).default(['profile', 'stats'])
287
- output: UserListResponse, // HTTP, OpenAPI and the typed client — unchanged
288
- },
289
- {
290
- defaults: { include: [] }, // what a tool call gets when it passes nothing
291
- output: UserCardList, // the tool answer and its schema
292
- project: (full, { input }) => ({ items: full.items.map(toCard) }), // optional: without it, `output` slices
293
- },
294
- ),
301
+ import { createLocalStepDurability, type StepDurabilityLedger } from 'stitchkit/tools';
302
+
303
+ const ledger: StepDurabilityLedger = {
304
+ appendEvent: (event) => db.durabilityEvents.insert(event), // returns the row with `seq`
305
+ readEvents: ({ conversationId, fromSeq, toSeq }) => db.durabilityEvents.page(…),
306
+ };
307
+
308
+ mountAgent(services, {
309
+ access: { gate: { beforeHandle: authHook } },
310
+ durability: (toolCallId, signal) =>
311
+ createLocalStepDurability({ store: ledger, conversationId, runId: toolCallId, signal }),
295
312
  });
296
313
  ```
297
314
 
298
- - **One handler, one parser.** `defaults` joins the tool call's arguments
299
- *before* the endpoint's own `input` parses them, so the handler receives an
300
- ordinary `input` — `include: []` from a tool, the HTTP default from HTTP — and
301
- loads only what was asked for. An explicit argument wins over the default.
302
- - **The answer is derived, then checked.** The handler's result is validated
303
- against the full `output` first, as always; then `project` (a pure,
304
- synchronous function of the full result and the parsed input) or a slice by
305
- the view's `output`, then validation against the view's schema. A projection
306
- that throws, returns a Promise or breaks its schema is `INTERNAL_SERVER_ERROR`
307
- — a server fault, like any output mismatch.
308
- - **Where it applies.** The MCP, agent and CLI mounts answer with the view;
309
- `outputSchema`, `structuredContent`, the advertised input `default`, the
310
- catalog stamp and the surface snapshot follow it. HTTP, OpenAPI, the typed
311
- client and the in-process [`createToolInvoker`](#in-process-calls--createtoolinvoker)
312
- keep the full answer — code, not a model, is calling there.
313
- - **Four forms, one helper.** With `defaults` alone the call changes and the
314
- answer is the full `output`, validated by it and advertised as it. With
315
- `output` and `project` the answer has its own schema. With `project` alone it
316
- reshapes values inside the full schema. With `output` alone it is a slice, and
317
- the full result must fit that schema — `withToolView` refuses the endpoint at
318
- compile time when it does not.
319
- - **Exposure.** A view needs a tool transport. With `createContractFactory<Scope>().configure({
320
- toolExposure: { default: ['HTTP'] } })` an endpoint without `expose` is HTTP-only, so an
321
- endpoint with a view names its tool transports in `expose`.
322
- - **What it refuses.** `defineContract` rejects a view on an endpoint with no
323
- tool transport or no full `output`, on a raw, `rawBody`, multipart,
324
- `responseMeta` or streaming endpoint, a view that declares no `defaults`,
325
- `output` or `project` — it would change nothing — and a default for a key the input does not have, for a path
326
- param, or with a value the input would reject.
327
-
328
- A projection adds nothing the full result does not carry: a field the tool
329
- answer needs belongs in the full answer, loaded by the handler. Keys a
330
- projection returns beyond its schema are reported by `onOutputStrip`; a slice
331
- removes keys on purpose and is not reported. → [ADR 0196](../decisions/0196-a-tool-answer-is-a-declared-view.md)
332
-
333
- ## AI agents — `mountAgent`
334
-
335
- `mountAgent` remains the low-level path when the application owns its own model
336
- loop and conversation state. For the optional Stitchkit-owned run/history loop,
337
- see [Agent application runtime](./agent-runtime.md).
338
-
339
- `mountAgent` turns a service into a Vercel AI SDK `ToolSet`, ready for
340
- `generateText` / `streamText`:
315
+ That gives replay, absolute deadlines and decode refusal without writing them.
316
+ The port is there for an application that already has its own ledger engine.
341
317
 
342
- ```ts
343
- import { mountAgent } from 'stitchkit/tools/agent'
344
- import { generateText } from 'ai'
318
+ One thing the port deliberately leaves out: **delivery**. `waitFor` parks until
319
+ `{ event, id }` arrives, and a tool body has no business delivering to itself —
320
+ so `deliver` lives on the engine object you constructed, not in the handler
321
+ context. Whatever produces the event (a webhook, a queue consumer, a cron) calls
322
+ `engine.deliver({ event, id, payload })` against the same ledger; the parked
323
+ `waitFor` resolves, and a `waitFor` that starts after the delivery returns at
324
+ once. Taking `agent-runtime` is not required and nothing of the runtime proper
325
+ enters the `stitchkit/tools` graph. An application that *does* run on
326
+ `agent-runtime` gets durability through the run context and needs no option;
327
+ where both exist the runtime's wins, because the run is recorded in its ledger.
345
328
 
346
- const tools = mountAgent(usersService, {
347
- context: { userId: 'agent-1' },
348
- access: { gate: { beforeHandle: authHook } },
349
- })
329
+ #### An effect in another system — `effect`, at most once
330
+
331
+ Standalone callers must hold an application-owned exclusive execution lease for the conversation/run
332
+ through the whole effect call. Sharing a ledger or separate ledger adapters is not an atomic claim;
333
+ the runtime supplies its run lease. Process-local coalescing only covers the same ledger object.
334
+
335
+ `step` records its result **after** the body, so a body cut short by a crash
336
+ runs again. For sending a message or starting a turn at a provider, a repeat is
337
+ worse than a loss. The engine's `effect` records the intent **before** it runs:
350
338
 
351
- const result = await generateText({
352
- model,
353
- tools,
354
- prompt: 'Create a user named Max',
339
+ ```ts
340
+ const sent = await engine.effect('reply', {
341
+ run: () => chat.send({ clientId, text }), // → { messageId }
342
+ reconcile: (signal) => chat.findByClientId(clientId, { signal }), // → { messageId } | null
355
343
  })
344
+ if (sent.outcome === 'uncertain') reportPossiblyLost(clientId)
356
345
  ```
357
346
 
358
- Each contract endpoint exposed on `AGENT` becomes a tool whose input schema is
359
- the merged `params` + `input`. `context` is merged into every tool handler's
360
- `ctx`, alongside `source: 'agent'`.
361
-
362
- ### `AgentMountConfig`
347
+ A later call — the same process or a restarted one — that finds the intent with
348
+ no outcome calls `reconcile`, never `run`. Found is `accepted` with the proof;
349
+ not found is `uncertain`. Both are recorded and final: `run` is never called for
350
+ that name again, and `uncertain` is not asked again — it is the honest third
351
+ answer, and retrying it is the caller's decision under a new name. A `run` that
352
+ throws, or a `reconcile` that throws or overruns `reconcileTimeoutMs` (default
353
+ 30 s), rejects with `EffectUnresolvedError` and leaves the intent for the next
354
+ call. The proof is JSON of at most 64 KiB — the identity the recipient assigned,
355
+ not a payload. → [ADR 0200](../decisions/0200-an-effect-is-recorded-before-it-runs.md)
356
+
357
+ Caller abort during reconcile releases the wait with `StepAbortedError`, leaves the intent and ignores
358
+ a late result. A coalesced caller can cancel its own await without cancelling the shared owner;
359
+ the first caller owns reconciliation handlers/deadline. `reconcileTimeoutMs` cannot exceed the native
360
+ timer range (2147483647 ms). It does not turn cancellation into proof of absence. Neither `null` nor an absence digest
361
+ proves that an earlier recipient request cannot complete later. Safe retries require recipient-side
362
+ idempotency or a verified fence. See [ADR 0224](../decisions/0224-native-primitives-have-one-owner.md).
363
+
364
+ Ledger reads are paged at 10 000 and incremental in one engine; a fresh engine replays the conversation
365
+ and retains its durable keys. This is not a bounded outstanding index/direct terminal receipt store.
366
+ For application delivery, `defineDomainEventDelivery` in `stitchkit/primitives` composes a caller-owned
367
+ atomic outbox claim with delivered/retryable/terminal/unknown states, bounded dispatch count (default
368
+ 100). Storage retention, per-key lookup, recipient proof and transactions remain in that adapter;
369
+ it is not an automatic cutover for a different reconciliation protocol.
370
+
371
+ ### Typed MCP call metadata
372
+
373
+ Contract handlers, runtime-tool handlers/factories, lifecycle and tool hooks all
374
+ see the same optional `McpCallContext` for the current invocation:
363
375
 
364
- | Field | Purpose |
365
- |-------|---------|
366
- | `context` | values merged into every tool handler's `ctx` |
367
- | `access` | **required** — `{ gate: { beforeHandle, afterHandle? } }` or `{ open, afterHandle? }` (see [Guarding tools](#guarding-tools--access)) |
368
- | `hooks` | tool-call observability hooks — `afterToolCall` fires on every result |
369
- | `extend` | add extra args resolved before the handler runs (see below) |
370
- | `runtimeTools` | framework-managed pathless operations from `defineRuntimeTool` |
376
+ ```ts
377
+ const sourceLabel = context.mcp?.clientInfo?.name ?? context.source
378
+
379
+ context.mcp?.era // 'modern' | 'legacy'
380
+ context.mcp?.method // validated MCP method
381
+ context.mcp?.toolName // resolved framework tool name
382
+ context.mcp?.protocolVersion // when supplied by a modern host
383
+ context.mcp?.clientInfo // { name, version } when validated
384
+ context.mcp?.outcome // multi-round attempt outcome
385
+ context.mcp?.round // multi-round attempt number
386
+ ```
371
387
 
372
- `access` works the same as on the MCP server — pass `{ gate: { beforeHandle: authHook } }`
373
- (or an explicit `{ open }` reason when unguarded).
388
+ The field is absent on HTTP, Agent, CLI and bring-your-own transports. A legacy
389
+ MCP call exposes `era: 'legacy'` but does not invent modern client information.
390
+ `clientInfo` is the host's self-description: use it for labels or analytics,
391
+ never for authentication, RBAC, tenant selection or rate limiting. Verified
392
+ identity still comes from `auth`; the `context(auth)` callback remains the
393
+ application-context factory and receives no protocol metadata.
374
394
 
375
- ### Adding tool-only args — `extend`
395
+ ### Telling the host what a long call is doing — `ctx.reportProgress`
376
396
 
377
- `extend` adds **tool-only** arguments — fields the model fills that are resolved
378
- into context, then stripped before the contract handler sees them. Use it when a
379
- tool needs an argument the HTTP endpoint does not — the classic case being a
380
- **multi-tenant** server reached by one API key, where the model passes `tenantId`
381
- on every call. It is the same `ToolExtend` shape on `mountMcp`, `createMcpHandler`
382
- and `mountAgent`:
397
+ A tool that takes ten minutes tells a text host nothing: the call is made, and
398
+ the next thing the host shows is the answer. The protocol has a channel for
399
+ this — the host sends a `progressToken` with the call, the server relates
400
+ progress notifications to it — and a handler reaches it through
401
+ `ctx.reportProgress`:
383
402
 
384
403
  ```ts
385
- interface ToolExtend {
386
- /** Extra Zod fields added to every matching tool's input schema. */
387
- schema: Record<string, z.ZodType>
388
- /** Turn the extra args into context merged into the handler's ctx. */
389
- resolve: (args: Record<string, unknown>) => Partial<Ctx> | Promise<Partial<Ctx>>
390
- /** Limit the extension to specific methods — default: every method. */
391
- filter?: (service: ServiceDef, method: MethodDef) => boolean
404
+ render: async (ctx) => {
405
+ await ctx.reportProgress?.({ message: 'queued' })
406
+ const job = await jobs.start(ctx.input)
407
+ await ctx.reportProgress?.({ message: 'rendering', progress: 1, total: 3 })
408
+ return await jobs.finish(job)
392
409
  }
393
410
  ```
394
411
 
395
- On the MCP server — add `tenantId` to each tool, validate access in `resolve`,
396
- inject the resolved tenant into `ctx`, and `filter` to the tenant-scoped tools:
412
+ `reportProgress` is present on every **tool** call — MCP, agent and CLI — so a
413
+ handler never branches on transport, and it does nothing wherever nobody is
414
+ listening. Under the agent runtime somebody is: each report becomes a transient
415
+ `tool-progress` event of the run, so the person watching the agent sees the
416
+ stage while the model still reads only the tool's result (see
417
+ [Agent runtime → events](./agent-runtime.md)). It is absent on the HTTP transport, which has no channel for it, so a
418
+ handler that also serves HTTP writes `ctx.reportProgress?.(…)`. It never throws and never
419
+ rejects: a message about work must not be able to kill the work it describes, so
420
+ a refused notification leaves the host exactly where a host that never asked for
421
+ progress already is.
422
+
423
+ `progress` is a number the protocol requires and a handler often does not have —
424
+ there is a stage to name and no scale to name it on. Omit it and the ordinal of
425
+ the update is sent, with no `total`, so the host shows a counter rather than a
426
+ bar stuck at 3%. That is a fact about what happened; a synthesised percentage
427
+ would be a claim nobody measured.
428
+
429
+ The framework sends nothing on its own. Progress is meaningful only where an
430
+ operation has observable stages, and manufacturing one per call would be
431
+ inventing a second transport beside the one the protocol already provides. The
432
+ one exception is the managed wait tool (`mountWait`), which already polls and
433
+ therefore already knows: when the host asked for progress it reports each poll
434
+ and the phase it last saw, which is the tool whose silence raised the question
435
+ in the first place.
436
+
437
+ The token itself is on `ctx.mcp.progressToken` when a caller wants to know
438
+ whether anyone is listening.
439
+
440
+ ### Multi-round tool input (`input_required`)
441
+
442
+ An MCP-only operation can require typed user input before its final side effect:
397
443
 
398
444
  ```ts
399
- createMcpHandler({
400
- serverInfo, auth,
401
- services: [widgetsService],
402
- access: { gate: { beforeHandle: authHook } },
403
- extend: {
404
- schema: { tenantId: z.string().describe('Tenant to act on') },
405
- resolve: async ({ tenantId }) => {
406
- const id = String(tenantId)
407
- if (!(await tenantExists(id))) throw new Error(`unknown tenant ${id}`)
408
- return { tenantId: id } // merged into ctx → ctx.tenantId
445
+ const DeleteConfirmationSchema = z.object({ confirmed: z.boolean() })
446
+
447
+ deleteProject: {
448
+ method: 'DELETE',
449
+ path: '/projects/:id',
450
+ expose: ['MCP'],
451
+ input: DeleteProjectSchema,
452
+ output: DeleteProjectResultSchema,
453
+ tool: {
454
+ mcp: {
455
+ inputRequired: [
456
+ {
457
+ key: 'confirmation',
458
+ schema: DeleteConfirmationSchema,
459
+ message: 'Confirm permanent deletion',
460
+ },
461
+ {
462
+ key: 'reason',
463
+ schema: z.object({ value: z.string().min(3) }),
464
+ message: 'Record the reason',
465
+ },
466
+ ],
409
467
  },
410
- filter: (_service, method) => method.scope === 'tenant',
411
468
  },
412
- })
469
+ }
413
470
  ```
414
471
 
415
- The model calls `widgets_list({ tenantId: 't_123' })`; `resolve` checks access and
416
- puts `tenantId` on `ctx`; the contract handler reads `ctx.tenantId` (same place
417
- as the HTTP prefix param — see
418
- [Route groups → param prefixes](./server.md#param-prefixes-resource-scoped-paths)),
419
- so one handler serves both surfaces. Pair `extend` with `access: { gate: { beforeHandle: authHook } }`
420
- so the tool call is still scope-gated.
421
-
422
- ## Pathless runtime tools and multimodal results
423
-
424
- Use `defineRuntimeTool` for an operation that has no HTTP path but still needs
425
- the same validation, isolated per-call context, lifecycle/RBAC and hooks as a
426
- contract tool. The handler returns one transport-neutral, schema-validated
427
- result. Optional presentation callbacks map that result to MCP content and AI
428
- SDK model output without coupling the handler to either SDK:
472
+ Each continuation accepts exactly the currently requested item. Only after the
473
+ ordered sequence completes does the handler receive the exact aggregate as
474
+ `ctx.mcpInput.confirmation` and `ctx.mcpInput.reason`; before then the framework
475
+ returns `input_required` without calling it. Set
476
+ `multiRound.serving.maxRounds` to the maximum declaration size you accept
477
+ (default `10`); empty sequences, duplicate keys and overflow fail first. State
478
+ is bound to principal, full operation identity, current round, accepted
479
+ aggregate and canonical original-argument digest and is
480
+ expiry-checked. Tampered, expired, cross-user or cross-tool state fails before
481
+ the side effect. Output validation applies only to the final result.
482
+
483
+ Every attempt re-runs auth/lifecycle and emits its own tool hooks; audit metadata
484
+ contains the attempt's `mcp.outcome` and `mcp.round`. Stitchkit does not merge
485
+ separate HTTP attempts into one logical trace. Parallel
486
+ rounds have isolated context. HTTP/stdio modern hosts and the supported legacy
487
+ stdio bridge may use this declaration; Agent, CLI and ordinary HTTP invocation
488
+ remain single-round and unchanged. Hosts without the capability receive an
489
+ ordinary unsupported result rather than a falsely advertised round. Signed
490
+ state is tamper-resistant, not an exactly-once replay store; destructive
491
+ handlers must still be idempotent where retries matter.
492
+
493
+ #### Questions chosen from the arguments
494
+
495
+ The list above is fixed when the contract is written, which is right when the
496
+ questions belong to the operation. It is not enough when they belong to the
497
+ **arguments** — one model takes `aspect_ratio`, another `duration`, a third an
498
+ input image — and there a declared list can only be empty. `inputRequired` also
499
+ accepts a function of the parsed call:
429
500
 
430
501
  ```ts
431
- import { defineRuntimeTool } from 'stitchkit/tools'
432
- import { createMcpHandler } from 'stitchkit/tools/mcp'
433
- import { mountAgent } from 'stitchkit/tools/agent'
434
- import { z } from 'zod'
435
-
436
- const renderPreview = defineRuntimeTool({
437
- name: 'render_preview',
438
- description: 'Render and inspect a preview',
439
- identity: {
440
- serviceName: 'mediaTools',
441
- action: 'renderPreview',
442
- scope: 'admin',
443
- method: 'POST',
444
- },
445
- input: z.object({ prompt: z.string() }),
446
- output: z.object({ assetId: z.string(), imageBase64: z.string() }),
447
- handler: async ({ input }) => renderAndSave(input.prompt),
448
- present: {
449
- mcp: (output) => ({
450
- content: [
451
- { type: 'image', data: output.imageBase64, mimeType: 'image/png' },
452
- { type: 'text', text: output.assetId },
453
- ],
454
- }),
455
- agent: (output) => ({
456
- type: 'content',
457
- value: [{
458
- type: 'file',
459
- data: { type: 'data', data: output.imageBase64 },
460
- mediaType: 'image/png',
461
- filename: `${output.assetId}.png`,
462
- }],
463
- }),
502
+ tool: {
503
+ mcp: {
504
+ inputRequired: async ({ input }) => {
505
+ const model = await catalog.get(input.model)
506
+ return model.needsRatio
507
+ ? [{ key: 'ratio', schema: RatioSchema, message: 'Which aspect ratio?' }]
508
+ : []
509
+ },
464
510
  },
465
- })
466
-
467
- const handleMcp = createMcpHandler({
468
- serverInfo: { name: 'my-app', version: '1.0.0' },
469
- auth,
470
- services: [service],
471
- runtimeTools: [renderPreview],
472
- access: { gate: { beforeHandle: authHook } },
473
- hooks: audit.toolCall,
474
- })
475
-
476
- const agentTools = mountAgent([service], {
477
- runtimeTools: [renderPreview],
478
- access: { gate: { beforeHandle: authHook } },
479
- hooks: audit.toolCall,
480
- })
511
+ }
481
512
  ```
482
513
 
483
- When several runtime tools share application context and identity, bind both
484
- once with `createRuntimeToolFactory`. Its Zod context schema is parsed once per
485
- call inside the same runner; the authored handler receives validated context and
486
- parsed `input`, while lifecycle, hooks, output validation and presenters remain
487
- unchanged:
514
+ It receives the same `params` / `input` the handler receives — parsed, so
515
+ defaults and coercions are already applied. Returning an empty array means this
516
+ call needs nothing and runs straight through. Everything else is unchanged: the
517
+ state is still signed and bound to principal, operation and argument digest, the
518
+ rounds are still counted against `maxRounds`, and a resolved list with duplicate
519
+ keys or more rounds than allowed is refused.
520
+
521
+ **The plan is fingerprinted, and that matters more than it looks.** Between two
522
+ rounds there is a full round trip to the host, and a resolver that reads
523
+ anything outside its arguments — a model catalog, a feature flag — can answer
524
+ differently the second time. Every other check would still pass: same principal,
525
+ same operation, same arguments, round still in range. Round 2's question would
526
+ be asked under round 1's key, and if the schemas happened to be compatible the
527
+ user's answer would be accepted for a question nobody asked. So the resolved
528
+ list is fingerprinted into the signed state and re-checked every round; a plan
529
+ that moved is refused, not asked. A resolver that reads only its arguments never
530
+ sees this.
531
+
532
+ **What a dynamic declaration costs.** One extra pass through the contract
533
+ pipeline per round — `access.gate.beforeHandle` runs once more and one more
534
+ `toolPhase: 'input-round'` audit row is written. That is the price of ordering:
535
+ the resolver is your code and may reach a network, so it runs **after**
536
+ authorisation, never before, and the only thing that can authorise is a pipeline
537
+ pass. Resolving itself is free — the arguments are parsed by the same pure
538
+ function the call parses with, not by a second run of anything. A fixed list
539
+ pays none of this; its call sequence is unchanged.
540
+
541
+ One thing does change for a fixed list: the signed round state now carries a
542
+ fingerprint of the question plan, and it is checked on every round. A
543
+ conversation already in flight when you deploy this has no fingerprint in its
544
+ state and is refused once with `INVALID_REQUEST_STATE`; the host re-asks and the
545
+ retry succeeds.
546
+
547
+ ### Guarding tools — `access`
548
+
549
+ A tool call runs the same handler an HTTP request would. Every tool mount
550
+ (`createMcpHandler`, `createStdioMcpServer`, `buildMcpServer`, `mountMcp`,
551
+ `mountAgent`, `createToolInvoker`, managed `createCli` / `createCliInvoker`, and
552
+ `createDeferredAgentToolSurface().mount`) requires an explicit `access` policy
553
+ at compile time and at runtime before the first call (→ [ADR 0311](../decisions/0311-planned-breaking-release-access-expose-and-clean-boundaries.md)):
554
+
555
+ - **`{ gate: { beforeHandle, afterHandle? } }`** — enforces a mandatory
556
+ `beforeHandle` gate (pass the **same**
557
+ [`createAuthHook`](./auth-and-errors.md#createauthhook) result used as the
558
+ HTTP server's `authorize` hook, or compose multiple lifecycles with
559
+ `composeToolLifecycle(authGate, ...)`).
560
+ - **`{ open: 'public' | 'local-operator' | 'remote', afterHandle? }`** —
561
+ explicitly declares why no `beforeHandle` gate runs on this surface.
488
562
 
489
563
  ```ts
490
- const knowledgeTools = createRuntimeToolFactory({
491
- serviceName: 'agentKnowledge',
492
- scope: 'user',
493
- context: z.object({ userId: z.string(), tz: z.string() }),
494
- })
495
-
496
- const countRecords = knowledgeTools.define({
497
- name: 'count_records',
498
- action: 'countRecords',
499
- method: 'GET',
500
- description: 'Count records',
501
- input: z.object({ kind: z.string() }),
502
- output: z.object({ count: z.number() }),
503
- handler: async ({ userId, tz, input }) => countFor(userId, tz, input.kind),
504
- })
564
+ createMcpHandler({ serverInfo, auth, services, access: { gate: { beforeHandle: authHook } } })
505
565
  ```
506
566
 
507
- `serviceName` and `scope` cannot be overridden by one definition. Use standalone
508
- `defineRuntimeTool` when tools do not share a context schema or identity.
567
+ Omitting `access`, passing `{}` / `{ gate: {} }`, or passing the removed
568
+ `lifecycle` key throws a `TypeError` naming the mount entrypoint at startup.
509
569
 
510
- `expose` defaults to `['MCP', 'AGENT']`; set an explicit subset when an
511
- operation belongs on only one surface. Include `'CLI'` explicitly to reuse the
512
- definition through `createCli({ runtimeTools, access })`; adding CLI support never
513
- widens existing definitions silently. The configured identity becomes the
514
- hook/lifecycle `OperationIdentity` and the tool `RequestEvent`
515
- (`serviceName`, `action`, `httpMethod`). A runtime operation has no HTTP route,
516
- so no fake `path` is added.
570
+ The observability `hooks` are symmetric with the HTTP side too: `beforeToolCall`
571
+ and `afterToolCall` receive the resolved **`MethodDef`** as `endpoint` —
572
+ the tool-side twin of `afterHandle(ctx, result, endpoint)`. Read
573
+ `endpoint.serviceName` / `.key` / `.meta` directly for an audit row; you do not
574
+ need to rebuild a `toolName → identity` map:
517
575
 
518
- When `output` is declared, Stitchkit validates the neutral handler result after
519
- `afterHandle`. MCP owns `structuredContent` and `isError`: a presenter supplies
520
- only rich `content`/metadata, while the framework inserts the validated
521
- structured result and normalises failures. The Agent adapter uses the AI SDK's
522
- official `toModelOutput` callback, so `execute` and application UI keep the
523
- neutral output while the model receives text/file content. Presentation
524
- callbacks require an output schema.
576
+ ```ts
577
+ hooks: {
578
+ afterToolCall: ({ result, durationMs, endpoint }) => {
579
+ audit({
580
+ service: endpoint.serviceName,
581
+ action: endpoint.key,
582
+ ok: result.ok,
583
+ ms: durationMs,
584
+ })
585
+ },
586
+ }
587
+ ```
525
588
 
526
- The MCP registration uses an identity carrier: the SDK advertises the compiled
527
- JSON Schema but forwards the raw object into Stitchkit. Input failures therefore
528
- use the same validation, lifecycle and hook path as contract tools.
589
+ > **Tool-path identity.** A tool call has no `req`, so `createAuthHook` resolves
590
+ > identity through `resolveFromContext`, not `resolve`. Set it (read the
591
+ > identity your `auth` / `context` injected) — without it a scoped tool call
592
+ > has no identity and **fails closed**. See
593
+ > [Auth on the tool surface](./auth-and-errors.md#auth-on-the-tool-surface--resolvefromcontext).
529
594
 
530
- ### Managed wait, download, upload and view-file
595
+ ### Lazy tool discovery — `discovery`
531
596
 
532
- The common imperative shapes have typed definition factories. They produce
533
- ordinary runtime-tool definitions, so one value can enter `runtimeTools` on MCP
534
- and Agent and receives the same lifecycle, hooks, context, cancellation,
535
- collision checks and introspection as any `defineRuntimeTool` operation:
597
+ 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:
536
598
 
537
599
  ```ts
538
- import {
539
- defineDownloadTool,
540
- defineUploadTool,
541
- defineViewFileTool,
542
- defineWaitTool,
543
- } from 'stitchkit/tools'
544
- import { createManagedFileBoundary } from 'stitchkit/files'
545
- import { z } from 'zod'
546
-
547
- const files = await createManagedFileBoundary({
548
- root: '/srv/job-media',
549
- createRoot: true, // creates only this final directory; /srv must already be trusted
550
- inspectionTimeoutMs: 15_000,
551
- inspect: ({ prefix, name, declaredMediaType, signal }) =>
552
- inspectFile(prefix, { name, declaredMediaType, signal }),
600
+ createStdioMcpServer({
601
+ serverInfo: { name: 'my-mcp', version: '1.0.0' },
602
+ auth: { userId: 'local-operator' },
603
+ services,
604
+ access: { gate: { beforeHandle: authHook } },
605
+ discovery: {
606
+ mode: 'lazy',
607
+ initialTools: ['get_status'],
608
+ searchToolName: 'tool_search', // default
609
+ maxResults: 10, // default 10, range 1..50
610
+ },
553
611
  })
612
+ ```
554
613
 
555
- const waitForJob = defineWaitTool({
556
- name: 'wait_for_job',
557
- description: 'Wait for a job to finish',
558
- identity: { serviceName: 'jobs', action: 'waitForJob', scope: 'user' },
559
- input: z.object({ id: z.string() }),
560
- state: z.object({ id: z.string(), status: z.enum(['RUNNING', 'DONE']) }),
561
- poll: ({ id }, context) => getJob(id, context.signal),
562
- done: (state) => state.status === 'DONE',
563
- backoff: [2, 3, 5],
564
- defaultTimeout: 120,
565
- })
614
+ - **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).
615
+ - **Session-isolated reveal.** Every contract tool outside `initialTools` starts disabled on that `McpServer` instance. Calling `tool_search` ranks the still-hidden tools by name and description (exact/phrase matches first, then deduplicated word matches), enables up to `maxResults` of them on that session's `McpServer` — tools already enabled never take a slot, so repeating a search reaches the matches past the first `maxResults`; they are listed after the new ones with `newlyEnabled: false` — 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.
616
+ - **Identical access, no catalog stamp.** `tool_search` and every revealed tool enforce the exact same `access` policy (`gate` / `inspect` / `open`) and hooks. A surface with discovery sends no `stitchkit/catalog` stamp: each session lists its own subset, which no digest of the whole surface describes, so a connection's catalog store lists afresh instead of keeping one session's view. Unknown names in `initialTools`, `searchToolName` collisions with real tools, and out-of-range `maxResults` throw synchronously at mount time.
617
+ - **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`).
566
618
 
567
- const downloadResult = defineDownloadTool({
568
- name: 'download_result',
569
- description: 'Download a completed result',
570
- identity: { serviceName: 'jobs', action: 'downloadResult', scope: 'user' },
571
- input: z.object({ id: z.string() }),
572
- resolveUrl: ({ id }) => resolveResultUrl(id),
573
- files,
574
- pathFromInput: ({ id }) => `results/${id}.bin`,
575
- })
619
+ ### MCP schema validation profile
576
620
 
577
- const uploadInput = defineUploadTool({
578
- name: 'upload_input',
579
- description: 'Upload a local input file',
580
- identity: { serviceName: 'jobs', action: 'uploadInput', scope: 'user' },
581
- output: z.object({ url: z.url() }),
582
- files,
583
- upload: (source, context) => uploadBytes(source.bytes, context.signal),
584
- })
621
+ A contract schema that JSON Schema cannot represent (a `z.date()`, a `z.map()`)
622
+ cannot become a tool. `schemaValidation.policy` decides what happens:
585
623
 
586
- const viewResult = defineViewFileTool({
587
- name: 'view_result',
588
- description: 'Inspect generated media',
589
- identity: { serviceName: 'jobs', action: 'viewResult', scope: 'user' },
590
- // Local files are disabled when files is omitted. URL fetches retain SSRF
591
- // protection; use allowPrivateHosts only for an explicitly trusted network.
592
- files,
593
- })
624
+ - `'throw'` (default) — fail the build, listing every offending tool. A static
625
+ `services` array is checked when `createMcpHandler` is constructed, so a bad
626
+ schema fails the deploy, not the first request. Better than a tool that
627
+ silently vanishes from the surface.
628
+ - `'warn'` — log through `logger` and drop the tool.
629
+ - `'skip'` — drop the tool silently.
594
630
 
595
- const runtimeTools = [waitForJob, downloadResult, uploadInput, viewResult]
596
- ```
631
+ `validateMcpSchemas({ services })` runs the same check on its own — useful in a
632
+ startup assertion or a test.
597
633
 
598
- Managed factories return neutral validated data. Expected failures go through
599
- the standard failed `ToolResult` path rather than masquerading as a successful
600
- payload with `isError`. Wait sleep is abort-aware, guarded downloads receive the
601
- active signal, and upload implementations receive it on their typed context.
602
- Managed view-file accepts one or several paths/URLs, retains successful
603
- multimodal content beside structured per-item `errors`, and charges every item
604
- to one total 20 MB batch budget. Its MCP and Agent presenters are built in;
605
- remote fetch cancellation follows the active call signal.
606
-
607
- `paths` is one path/URL string or an actual array of strings (at most 20).
608
- Pass `{ paths: ['image.png'] }`, not `{ paths: '["image.png"]' }`: a JSON
609
- array written as text fails input validation before any file or network access,
610
- with the hint `paths is a list written as text — pass an array of paths or one
611
- path`. The same rule applies to array items and the raw `mountViewFile` input.
612
- Ordinary file names containing brackets, such as `[preview].png`, remain valid.
613
- A local file with an unsupported extension is refused before reading; its
614
- per-item error identifies the caller's path and the extension it saw.
615
-
616
- Each inline `image` and `audio` block carries the file name of its source in
617
- `_meta['stitchkit/fileName']` (`MCP_FILE_NAME_META_KEY`): a managed file keeps
618
- its own name, a URL takes its download name — the path's base name with the
619
- body's extension. MCP declares no file name on `ImageContent` or `AudioContent`,
620
- and the MCP server SDK drops an undeclared field from `content`, so the name is
621
- in `_meta`, the protocol's place for what a block carries beyond it. The block
622
- is therefore the same in the handler's output, an Agent's result,
623
- `structuredContent` and MCP `content`, and a host reads the name from the block
624
- it renders. A CLI saves the block under that name with
625
- [`--output-dir`](cli.md#saving-result-media).
626
-
627
- The older `mountWait`, `mountDownload`, `mountUpload` and `mountViewFile`
628
- functions remain
629
- intentional raw MCP adapters with their text-envelope behavior. Use them under
630
- `rawTools` only when opting out of managed policy is deliberate; they share the
631
- same neutral mechanics but do not gain lifecycle or hooks. The raw view-file
632
- adapter preserves its content-only MCP envelope while using the same bounded
633
- batch operation.
634
-
635
- ### Async-operation protocol
636
-
637
- For a complete long-running operation, define the linked runtime-only surface
638
- once. Stitchkit owns transport names, validation and wait mechanics; the
639
- application still owns storage, execution, retries and domain states:
634
+ For a static `services` array, collection, schema conversion and every enabled
635
+ validation guard run once when the handler is created. Each HTTP request still
636
+ receives a fresh `McpServer`, runner, context and native registration over that
637
+ immutable prepared surface. A `services(auth)` factory
638
+ is deliberately prepared after resolving each identity because its tool set may
639
+ change by tenant.
640
640
 
641
- ```ts
642
- import {
643
- createAsyncOperationSnapshotSchema,
644
- defineAsyncOperation,
645
- } from 'stitchkit/tools'
646
-
647
- const id = z.object({ id: z.string() })
648
- const state = z.object({
649
- phase: z.enum(['pending', 'running', 'succeeded']),
650
- value: z.string().optional(),
651
- })
652
- const snapshot = createAsyncOperationSnapshotSchema({
653
- failure: z.object({ code: z.string() }),
654
- progress: z.object({ current: z.number(), total: z.number() }),
655
- })
641
+ #### Is every property actually usable by a model?
656
642
 
657
- const exportOperation = defineAsyncOperation({
658
- mode: 'runtime-only',
659
- name: 'export',
660
- description: 'Export project data',
661
- identity: { serviceName: 'exports', action: 'export', scope: 'user' },
662
- startInput: z.object({ projectId: z.string() }),
663
- id,
664
- state,
665
- snapshot,
666
- start: ({ projectId }) => enqueueExport(projectId),
667
- authorize: ({ id }, capability, ctx) => authorizeExport(id, capability, ctx),
668
- inspect: ({ id }, ctx) => readExport(id, ctx.signal),
669
- classify: (job) => ({ phase: job.phase }),
670
- result: {
671
- output: z.object({ value: z.string() }),
672
- handler: (job) => ({ value: job.value ?? '' }),
673
- },
643
+ A tool schema is the only instruction a model gets about the shape of its
644
+ arguments. A property that carries a `description` and no `type` / `enum` /
645
+ `anyOf` / `$ref` tells it nothing — and nothing fails: the schema converts, the
646
+ mount succeeds, the tool is advertised, and the model then guesses, retrying the
647
+ same wrong guess because the error does not say what the right one would be.
648
+
649
+ ```ts
650
+ validateMcpSchemas({
651
+ services,
652
+ policy: 'throw',
653
+ logger,
654
+ extend,
655
+ flattenUnionInput: true,
656
+ requireTypedProperties: true,
657
+ requirePortableFormats: true,
658
+ allowFormats: [],
674
659
  })
660
+ ```
675
661
 
676
- const runtimeTools = exportOperation.runtimeTools
662
+ For an arbitrary **JSON value**, declare `z.json()`: its recursive JSON Schema
663
+ describes strings, numbers, booleans, null, arrays and objects, so strict schema
664
+ validation needs no exception. The schema refers to itself, so where a model
665
+ provider refuses recursive schemas set `inputRecursionDepth` as well (below). `z.unknown()` means an unknown runtime value —
666
+ including values JSON cannot represent — and therefore gives a model no usable
667
+ shape. The guard is off by default for existing contracts. `allowUntyped` takes
668
+ dotted `tool.property` paths and is reserved for a presentation value that is
669
+ genuinely impossible to represent as JSON Schema. On `createMcpHandler`, put the policy under
670
+ `schemaValidation`; the handler supplies its real `extend` and
671
+ `flattenUnionInput`, so the check cannot vet a different document from the one
672
+ advertised.
673
+
674
+ `requirePortableFormats` rejects custom `format` values common MCP/AJV clients
675
+ do not know, such as the `cuid2` emitted by `z.cuid2()`. Use a portable
676
+ schema/pattern, or list it in `allowFormats` only when every client supports it.
677
+ stitchkit never removes or rewrites the keyword.
678
+
679
+ `findUntypedProperties(jsonSchema)` is the same walk, exported on its own if you
680
+ want to assert on a schema you built elsewhere.
681
+
682
+ ### Discriminated unions for weaker models — `flattenUnionInput`
683
+
684
+ A discriminated union in a tool's input becomes a JSON Schema `oneOf` / `anyOf`.
685
+ Capable models (Claude, Gemini, GPT) handle that; weaker / cheaper ones can drop
686
+ the field or mangle its strings. Set `flattenUnionInput: true` (on
687
+ `createMcpHandler` / `mountMcp` / `mountAgent`) to advertise each discriminated
688
+ union as a **single flat object** instead — the discriminator becomes an enum and
689
+ each field required by every variant stays required. Other fields become optional
690
+ with `Available if <disc> = …` and, where applicable, `Required if <disc> = …` hints.
691
+
692
+ **Branch explanations keep their meaning.** A shared description appears once;
693
+ different descriptions are grouped by text and qualified with `When <disc> = …:`.
694
+ A branch without a description does not inherit another branch's explanation.
695
+ For example, an optional object `value` in `single` and a required array `value`
696
+ in `group` advertise:
697
+
698
+ ```text
699
+ When kind = single: One reference.
700
+ When kind = group: Two to ten references.
701
+ Available if kind = single | group. Required if kind = group
677
702
  ```
678
703
 
679
- #### Durable application-owned execution
680
-
681
- The executable reference
682
- [`durable-async-operation-harness.ts`](../../packages/core/examples/tools/durable-async-operation-harness.ts)
683
- shows the complete boundary behind that surface. It composes
684
- `defineAsyncOperationContract`, `defineAsyncOperation`, `createApplication`,
685
- `createBoundedAdmission`, managed shutdown and `createAgentToolFenceLifecycle`
686
- around an injected store and provider.
687
-
688
- The store transactionally owns the idempotency key **and normalized request
689
- hash**. Reusing both returns the existing operation; reusing the key with a
690
- different hash conflicts. Every mutation is an expected-revision CAS. Before an
691
- external call, the application persists a unique attempt/effect key and marks
692
- the dispatch `possibly-dispatched`; a lost response is therefore reconciled by
693
- that key after restart and is never treated as permission to submit the effect
694
- again. Provider acknowledgement, progress, cancellation intent, result and
695
- artifact references remain durable application state.
696
-
697
- Agent tool fencing and operation idempotency are separate guarantees. The fence
698
- prevents a stale run owner from crossing an effect boundary; the transactional
699
- idempotency record makes a repeated current call converge on one operation.
700
- Neither replaces the other.
701
-
702
- Stitchkit deliberately does **not** own the durable queue, operation database,
703
- lease renewal, provider retry/reconciliation protocol, asset catalog or domain
704
- states. The process-local application resource stops admission and drains
705
- accepted work; unresolved durable records survive shutdown for the next
706
- recovery pass. The packed consumer lane executes this composition from the
707
- published package on Bun and Node.
708
-
709
- Every follow-up repeats `authorize`; an opaque id is never authority. Aborting
710
- `wait` only stops waiting and never calls optional domain `cancel`.
711
-
712
- For a new HTTP surface, derive the canonical capability contract once. The
713
- factory defines schemas and routes only; the application still supplies normal
714
- handlers to `implement` and owns the job:
704
+ A third branch without `value` is absent from those labels. The object and array
705
+ retain their separate shapes; the array's minimum length does not apply to the object.
706
+ Discriminator values, branch explanation labels, enum values and joined
707
+ properties keep the order of their first appearance across the variants, so the
708
+ order you declare is the order the model reads. Alternatives of different kinds
709
+ keep one canonical order, so one declaration always yields one document. → ADR [0221](../decisions/0221-flat-field-explanations-retain-branch-meaning.md).
710
+
711
+ **A field several variants declare keeps its type.** Flattening puts every
712
+ variant's fields side by side, so a key two variants share has to be advertised
713
+ as one thing. Where they agree, that is what you get; where they disagree — a
714
+ `.refine()` only one of them carries, two different bounds on the same number, an
715
+ enum against a free string — the *constraint* is dropped and the **type** is not.
716
+ A field that is a number in every variant is advertised as a number, not as a
717
+ bare description. Scalar collisions keep every provable kind in a deterministic
718
+ JSON Schema type array. If any alternative is an object or array, the property
719
+ retains distinct structural alternatives in `anyOf`: object properties, typed
720
+ array items, bounds and nullable values remain available to the model. Each
721
+ alternative is described by the discriminator values that select it
722
+ (`When type = image.`, or `When type = photo | video.` for a shape two values share),
723
+ so the model can pair a shape with its value; the order of the alternatives is
724
+ canonical, not the order of the variants. The
725
+ containing discriminated union still becomes one object; flat mode does not
726
+ promise to remove every nested union keyword. Only a branch whose kind is
727
+ actually unknowable, such as a free-form schema or unresolved reference, leaves
728
+ the collision unconstrained. → ADRs [0044](../decisions/0044-a-collided-field-keeps-its-type.md),
729
+ [0205](../decisions/0205-flat-tool-collisions-retain-structural-alternatives.md)
730
+ and [0267](../decisions/0267-a-flat-alternative-names-the-values-that-select-it.md).
731
+
732
+ It is **deep** because the projection walks the generated JSON Schema document,
733
+ including objects, arrays, tuples and schema-definition nodes. Structurally
734
+ identifiable discriminated object unions are flattened wherever they occur.
735
+ Plain unions and unions hidden behind unresolved external references remain
736
+ unions because Stitchkit cannot soundly invent a discriminator.
737
+
738
+ Use the default `flattenUnionInput: false` when the model must see the exact
739
+ relationship between a discriminator and each branch. Joined property schemas
740
+ describe allowed values without reconstructing those correlations.
741
+
742
+ The flattened form is **lossy but never executable**. Per-variant refinements
743
+ and incompatible constraints are widened in the presentation document; the
744
+ original Zod contract enforces them exactly once inside `executeToolMethod`.
745
+ MCP and AI adapters forward the raw argument object unchanged, so defaults,
746
+ coercions and transforms cannot run before Stitchkit. Strict violations return
747
+ the normal `VALIDATION_ERROR` tool envelope and fire `beforeToolCall` /
748
+ `afterToolCall`. → [ADR 0050](../decisions/0050-presentation-schema-is-not-a-parser.md).
749
+
750
+ ### Recursive inputs without references — `inputRecursionDepth`
751
+
752
+ A recursive input (`z.lazy`, `z.json()`) is advertised as a definition that
753
+ refers to itself. Some model providers refuse the whole request when one tool
754
+ carries such a cycle; others accept it and never read a definition reached
755
+ through `allOf: [{ $ref }]`. `inputRecursionDepth` advertises every input with
756
+ no `$ref`, `definitions` or `$defs`:
715
757
 
716
758
  ```ts
717
- import { defineAsyncOperationContract } from 'stitchkit/tools'
718
- import { z } from 'zod'
759
+ const projection = { flattenUnionInput: true, inputRecursionDepth: 1 } as const
719
760
 
720
- const operationId = z.object({ id: z.string() })
721
- const operationSnapshot = z.object({
722
- phase: z.enum(['pending', 'running', 'succeeded', 'failed', 'cancelled']),
723
- })
724
-
725
- const operations = defineAsyncOperationContract({
726
- prefix: 'exports',
727
- scope: 'user',
728
- description: 'Export project data',
729
- startInput: z.object({ projectId: z.string() }),
730
- id: operationId,
731
- snapshot: operationSnapshot,
732
- cancel: true,
733
- result: z.object({ downloadUrl: z.url() }),
734
- })
761
+ mountAgent(services, { access, runtimeTools, ...projection })
762
+ createMcpHandler({ access, services, runtimeTools, ...projection, /* … */ })
763
+ buildToolManifest({ services, runtimeTools, transport: 'AGENT', ...projection })
735
764
 
736
- // Pass operations.contract and ordinary handlers to implement(...).
737
- // operations.capabilities/schemas/adapters are the canonical protocol metadata.
765
+ // a tool whose model needs to see deeper nesting says so beside its name
766
+ formula: { method: 'POST', path: '/formula', input, tool: { name: 'formula_create', inputRecursionDepth: 3 } }
738
767
  ```
739
768
 
740
- If an existing dedicated contract has a different wire shape — for example
741
- `start` returns a snapshot while follow-ups accept separate envelopes — bind it
742
- without casts or duplicate endpoints. Inline callbacks are contextually typed;
743
- every returned id/input is parsed by the destination schema:
769
+ - Every reference is written out in place; the `allOf` wrapper beside a
770
+ described reference merges into one node.
771
+ - Each **recursive** definition is written out at most `N` times along any path;
772
+ a reference without a cycle is always written out. Depth 1 shows one level of a
773
+ formula, depth 3 a formula of three nested calls.
774
+ - The reference past the last level becomes an **open node** typed by every JSON
775
+ type the definition can take (`{ type: 'object' }`, `{ type: 'array', items: {} }`,
776
+ or an `anyOf` of them). It accepts every value the definition accepts, so a
777
+ deeper argument is never refused by the document — the handler still parses the
778
+ contract's own recursive schema.
779
+ - `tool.inputRecursionDepth` wins over the surface's value and projects that tool
780
+ even where the surface sets none. Runtime tools, including tools discovered from
781
+ a server, take the surface's `inputRecursionDepth` and `flattenUnionInput`.
782
+ - Without the option the document is unchanged. With it, an `allowUntyped` path
783
+ for a property inside a definition is reported from its full path.
784
+
785
+ The depth is a number, not a size: a provider may limit nesting from above, and a
786
+ model forced to call the tool may need more levels from below. Measure the cost
787
+ with `describeToolCatalog({ …, maxSchemaBytes })`. → [ADR 0319](../decisions/0319-a-tool-input-can-be-advertised-without-references.md).
788
+
789
+ ### A provider's nesting limit — `inputNestingDepth`
790
+
791
+ Some providers refuse the whole tool set when one input document is nested deeper than a fixed
792
+ number of levels. `inputNestingDepth` keeps every advertised input within such a limit, counting
793
+ as such a provider counts: a level per step `properties → property` or `items`; `anyOf`, `oneOf`,
794
+ `allOf` and `additionalProperties` cost nothing; a property named `items` or `properties` costs two.
744
795
 
745
796
  ```ts
746
- import { defineContract } from 'stitchkit/contract'
747
- import { bindContractAsyncOperation } from 'stitchkit/tools'
748
-
749
- const startOutput = z.object({ operation: operationId, acceptedAt: z.string() })
750
- const statusInput = z.object({ operationId: z.string() })
751
- const waitInput = z.object({ lookup: operationId })
752
-
753
- const existing = defineContract({ prefix: 'exports' }, {
754
- start: {
755
- method: 'POST', path: '/', desc: 'Start export',
756
- input: z.object({ projectId: z.string() }), output: startOutput,
757
- },
758
- status: {
759
- method: 'POST', path: '/status', desc: 'Read export status',
760
- input: statusInput, output: operationSnapshot,
761
- },
762
- wait: {
763
- method: 'POST', path: '/wait', desc: 'Wait for export',
764
- input: waitInput, output: operationSnapshot,
765
- },
766
- })
797
+ const projection = { flattenUnionInput: true, inputRecursionDepth: 1, inputNestingDepth: 10 } as const
798
+ mountAgent(services, { access, runtimeTools, ...projection })
767
799
 
768
- const operationHandlers = {
769
- start: () => ({ operation: { id: 'example' }, acceptedAt: new Date().toISOString() }),
770
- status: (): z.output<typeof operationSnapshot> => ({ phase: 'pending' }),
771
- wait: (): z.output<typeof operationSnapshot> => ({ phase: 'succeeded' }),
772
- }
773
-
774
- const bound = bindContractAsyncOperation({
775
- mode: 'contract-backed',
776
- binding: 'adapted',
777
- contract: existing,
778
- id: operationId,
779
- capabilities: { start: 'start', status: 'status', wait: 'wait' },
780
- adapters: {
781
- idFromStart: (output) => output.operation,
782
- inputFor: {
783
- status: (id) => ({ operationId: id.id }),
784
- wait: (id) => ({ lookup: id }),
785
- },
786
- },
787
- handlers: operationHandlers,
788
- })
800
+ // one tool may say its own, as with inputRecursionDepth
801
+ put: { method: 'POST', path: '/put', input, tool: { name: 'lesson_put', inputNestingDepth: 10 } }
789
802
  ```
790
803
 
791
- Direct binding remains the short form when start already returns the id and
792
- every follow-up reuses that exact schema instance. Its ID schema must be
793
- wire-stable: input and output types match and parsing has no transform,
794
- coercion, default or overwrite. This also excludes same-type transforms because
795
- the direct adapters would parse an already parsed ID again. Use adapted binding
796
- and explicitly project the parsed ID back into each follow-up input. In both
797
- modes the binder creates no router;
798
- it returns the existing contract, handlers and protocol metadata for
799
- application composition.
804
+ - A document at or under the limit is unchanged. Deeper, the node whose next step would cross the
805
+ limit becomes an open node `{}` (its `description` kept), as deep as the limit allows: the rest
806
+ of the structure stays visible to the model.
807
+ - The open node accepts every value — the document widens, it never narrows — and the handler still
808
+ parses the contract's own schema. An array whose `items` would cross the limit is opened itself,
809
+ so no array is left without `items`.
810
+ - The limit applies last, to the document as it is advertised: after `inputRecursionDepth` writes
811
+ references out (so it also bounds the unrolled recursion), `flattenUnionInput` and tool defaults.
812
+ With references kept, a `$ref` counts as a leaf.
813
+ - `schemaValidation.requireTypedProperties` accepts the open nodes: the limit declared them.
814
+ - `tool.inputNestingDepth` wins over the surface's value, as `tool.inputRecursionDepth` does; runtime
815
+ tools and the deferred tool surface take the surface's value.
800
816
 
801
- ### Explicit raw SDK registration
817
+ ## `mountMcp`
802
818
 
803
- `rawTools` is deliberately named as an escape hatch. A tool registered there
804
- does **not** receive stitchkit schema policy, lifecycle, per-call context or
805
- hooks. The built-in `mountViewFile`, `mountWait`, `mountDownload` and
806
- `mountUpload` helpers remain raw for callers that choose that boundary; the
807
- media helper fetches with SSRF and path-traversal defenses:
819
+ If you already run an `McpServer` from the SDK, `mountMcp` adds contract tools
820
+ to it instead of owning the lifecycle:
808
821
 
809
822
  ```ts
810
- import { mountViewFile } from 'stitchkit/tools'
811
- import { createMcpHandler } from 'stitchkit/tools/mcp'
823
+ import { mountMcp } from 'stitchkit/tools/mcp'
812
824
 
813
- const handleMcp = createMcpHandler({
814
- serverInfo: { name: 'my-app', version: '1.0.0' },
815
- auth,
816
- services: [service],
825
+ mountMcp(mcpServer, [usersService], {
826
+ context: { source: 'mcp' },
817
827
  access: { gate: { beforeHandle: authHook } },
818
- rawTools: (server) => mountViewFile(server, { files }),
819
828
  })
820
829
  ```
821
830
 
822
- Use raw registration only when opting out is intentional. For a protected
823
- `view_file`, use `defineViewFileTool` in `runtimeTools`; it supplies the
824
- canonical schemas, shared batch budget, structured partial failures and both
825
- multimodal presenters. `resolveMedia` remains the single-item core for custom
826
- operations whose contract intentionally differs.
831
+ `createMcpHandler` is the batteries-included path; `mountMcp` is the building
832
+ block under it.
827
833
 
828
- ## Introspecting the complete tool surface
834
+ ## MCP over stdio — `createStdioMcpServer`
829
835
 
830
- Deferred tool search, name snapshots and boot diagnostics accept the same
831
- object-shaped surface as the mounts. Contract operations are followed by
832
- runtime definitions, matching mount order; exposure filters and collisions are
833
- resolved by Stitchkit rather than by consumer code:
836
+ `createMcpHandler` serves MCP over HTTP. `createStdioMcpServer` serves the same
837
+ contract tools over **stdio** — the server runs as a subprocess of the MCP
838
+ client (Claude Desktop, Claude Code, Cursor, Codex), on the user's machine, so
839
+ it can reach the local filesystem.
834
840
 
835
841
  ```ts
836
- import {
837
- buildToolManifest,
838
- listToolNames,
839
- summarizeTransports,
840
- } from 'stitchkit/tools'
842
+ import { bindStdioProcessSignals, createStdioMcpServer } from 'stitchkit/tools/mcp'
841
843
 
842
- const surface = { services, runtimeTools: [renderPreview] }
844
+ const stdio = await createStdioMcpServer({
845
+ serverInfo: { name: 'my-app', version: '1.0.0' },
846
+ auth: resolveIdentity(), // resolved once at startup, not per request
847
+ services: [usersService],
848
+ access: { gate: { beforeHandle: authHook } },
849
+ })
843
850
 
844
- const manifest = buildToolManifest({
845
- ...surface,
846
- transport: 'AGENT',
847
- flattenUnionInput: true,
851
+ const signals = bindStdioProcessSignals(stdio, {
852
+ onClose: () => stopWorkers(),
853
+ onComplete: () => { process.exitCode = 0 },
854
+ onError: (_phase, error) => {
855
+ console.error(error) // stderr only — stdout is JSON-RPC
856
+ process.exitCode = 1
857
+ },
848
858
  })
849
859
 
850
- const names = listToolNames(surface)
851
- const summary = summarizeTransports(surface)
860
+ await signals.promise
852
861
  ```
853
862
 
854
- `buildToolManifest` returns the exact immutable presentation schema shown to
855
- the selected MCP or Agent transport. It does not execute validation effects and
856
- fails first on duplicate contract/runtime names. There is no runtime-only
857
- manifest helper or public mount adapter: the framework owns merging and schema
858
- projection.
859
-
860
- Applications using Stitchkit's durable runtime can compose this manifest with
861
- bounded per-run activation through `createDeferredAgentToolSurface` from
862
- `stitchkit/agent-runtime`. It keeps selected calls as direct `mountAgent` tools
863
- rather than routing them through a generic executor. Search receipts live in
864
- ordinary durable tool-result history, so recovery restores activation and a
865
- queued successor cannot inherit it. See
866
- [Bounded deferred tool catalogs](./agent-runtime.md#bounded-deferred-tool-catalogs)
867
- and ADR 0129. Raw `mountAgent`, `mountMcp` and `buildToolManifest` behavior is
868
- unchanged.
869
-
870
- `listToolNames` remains diagnostic and reports `kind: 'contract' | 'runtime'`
871
- for every identity (with `expose` listing its resolved transports). `summarizeTransports` returns `contractServices`,
872
- `runtimeTools`, aggregate `totals`, and a `sources` breakdown. Runtime tools
873
- contribute only to MCP/Agent/CLI according to their `expose`; they never inflate
874
- HTTP counts.
875
-
876
- ## Logging tool calls — `createToolLogger`
877
-
878
- Every tool mount fires an `afterToolCall` hook. `createToolLogger` is a ready
879
- preset for it — one line logs each call (ok / failed, duration, which endpoint,
880
- keyed by the endpoint's stable `serviceName` / `key` identity):
863
+ A stdio server is a single process serving one client, so `auth` is a value (or
864
+ a promise of one) resolved once at startup — typically from an env var — rather
865
+ than a per-request `(req) => …`. Keep all logging on **stderr**: stdout is the
866
+ JSON-RPC channel.
881
867
 
882
- ```ts
883
- import { createToolLogger } from 'stitchkit/tools'
868
+ The default `legacy: 'serve'` negotiates the modern or supported legacy opening
869
+ through the official stdio adapter. Use `legacy: 'reject'` for a modern-only
870
+ binary. Each invocation builds a fresh server; the returned handle owns
871
+ transport shutdown.
884
872
 
885
- mountMcp(server, services, {
886
- access: { gate: { beforeHandle: authHook } },
887
- hooks: createToolLogger(),
888
- })
889
- // [tool] ok list_widgets (widgets.list) 12ms
890
- // [tool] warn get_widget (widgets.get) NOT_FOUND 4ms
891
- ```
873
+ Signal binding is explicit: `createStdioMcpServer` installs no global process
874
+ listeners by itself. The first `SIGINT`/`SIGTERM` starts exactly one official
875
+ `close()` chain. Stdio has no force primitive, so a later signal restores the
876
+ OS default disposition instead of reporting a fictional forced result.
877
+ `signals.close()` removes an idle binding; the framework never calls
878
+ `process.exit()` or chooses the exit code. See
879
+ [deployment lifecycle](./testing-and-deployment.md#stdio-process-signals).
892
880
 
893
- By default the line goes to `console.error` — **stderr, never stdout**. That is
894
- deliberate: in a stdio-MCP server stdout is the JSON-RPC protocol channel, and a
895
- log line written there corrupts the stream. If you pass your own `log`, keep it
896
- off stdout for any stdio deployment.
897
-
898
- Pass `log` to redirect the line, or `onRecord` to feed a metrics sink the
899
- structured `ToolCallRecord`. That record carries `traceId` whenever an
900
- observability context is active, so a tool call made inside an HTTP request
901
- joins that request's log line on one key — see
902
- [Observability](./observability.md). For a boot-time picture of what is exposed
903
- where, `summarizeTransports({ services, runtimeTools })` returns the mixed
904
- per-transport counts for you to log.
905
-
906
- ## One handler, three callers
907
-
908
- A contract handler runs the same for an HTTP request, an MCP tool call and an
909
- agent tool call. `ctx.source` (`'http'` · `'mcp'` · `'agent'`) tells it which —
910
- the rest of the context (`params`, `input`, anything `context` injects) is
911
- identical. Write the handler once; it serves every surface.
881
+ Both transports build the server through the shared `buildMcpServer` — same
882
+ contract/runtime pipeline, same surface selection, context, hooks, raw escape
883
+ hatch and instructions.