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.3.txt CHANGED
@@ -1,225 +1,861 @@
1
- # stitchkit/tools — stitchkit docs slice, part 3 of 3
1
+ # stitchkit/tools — stitchkit docs slice, part 3 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.
5
+ > Continues in `llms/tools.4.txt`.
5
6
 
6
7
  Parts of this slice:
7
8
  - `llms/tools.txt`: Guide: MCP & agents (docs/guide/mcp-and-agents.md)
8
9
  - `llms/tools.2.txt`: Guide: MCP & agents (docs/guide/mcp-and-agents.md)
9
- - `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)
10
12
 
11
13
  ==============================================================================
12
- # API reference: `stitchkit/tools` (docs/api/reference.md)
14
+ # Guide: MCP & agents (docs/guide/mcp-and-agents.md) (continued)
13
15
  ==============================================================================
14
16
 
15
- ## `stitchkit/tools`
16
-
17
- Server-only, and imported without any optional peer: the transport-neutral tool layer —
18
- the registry, tool names and manifest, runtime tools, native tools, the invoker, the OAuth
19
- provider and the durability engine. An application that serves its operations over HTTP and
20
- CLI lists its tool names here with neither MCP nor the AI SDK installed. The adapters that
21
- need a peer have their own subpaths: [`stitchkit/tools/mcp`](#stitchkittoolsmcp) (the MCP
22
- server SDK), [`stitchkit/tools/agent`](#stitchkittoolsagent) (the `ai` peer) and
23
- [`stitchkit/tools/toolkit`](#stitchkittoolstoolkit) (both). → ADR 0284.
24
-
25
- | Export | Kind | Summary |
26
- |--------|------|---------|
27
- | `defineRuntimeTool` | function | define one validated pathless operation for explicit MCP, Agent and/or CLI surfaces — [guide](../guide/mcp-and-agents.md#pathless-runtime-tools-and-multimodal-results) |
28
- | `createRuntimeToolFactory` | function | bind shared identity and Zod-validated per-call context for runtime tools — [guide](../guide/mcp-and-agents.md#pathless-runtime-tools-and-multimodal-results) |
29
- | `createToolInvoker` | function | compile an exposure-aware in-process dispatcher over the canonical tool runner; use `stitchkit/tools/invoker` or `stitchkit/tools`, both peer-free — [guide](../guide/mcp-and-agents.md#in-process-calls--createtoolinvoker) |
30
- | `mountViewFile` | function | a native multimodal "view file" MCP tool |
31
- | `resolveMedia` | function | resolve a media reference for a tool result |
32
- | `listToolNames` | function | every contract/runtime tool name with origin, identity and transports — for stable snapshots — [guide](../guide/mcp-and-agents.md#pinning-tool-names--listtoolnames) |
33
- | `listContractToolNames` | function | the same listing straight from contracts — no handlers or stub services needed |
34
- | `describeToolCatalog` | function | inspect the exact model-facing names, source identities, schema byte sizes and deferred state; an explicit total byte budget fails closed |
35
- | `ToolCatalogConfig` / `ToolCatalogEntry` | _type_ | catalog source, transport, optional explicit schema budget and one inspectable result row |
36
- | `RuntimeToolDefinition` | _type_ | heterogeneous registration of pathless operations in `runtimeTools: [...]`; an inline handler is contextually typed by the parsed object, a definition constructed with its own schema registers unchanged, and the runner validates input before the handler |
37
- | `RuntimeToolDefinitionBase` | _type_ | common name, identity, input, exposure and MCP metadata fields |
38
- | `RuntimeToolDefinitionWithOutput` | _type_ | the one neutral construction: identity, schemas and a handler typed from them; the fourth type argument names the adapter's `present` extension (`RuntimeToolPresenters<…>` here, `RuntimeMcpToolPresenters<…>` on `stitchkit/tools/mcp`, none by default) |
39
- | `RuntimeToolDefinitionWithoutOutput` | _type_ | the same construction with a void handler and no presentation callbacks |
40
- | `RuntimeToolFactory` | _type_ | identity/context-bound runtime-tool definition factory |
41
- | `RuntimeToolFactoryConfig` | _type_ | factory service identity and context schema |
42
- | `RuntimeToolFactoryDefinitionWithOutput` | _type_ | factory-authored runtime tool with a validated output schema |
43
- | `RuntimeToolFactoryDefinitionWithoutOutput` | _type_ | factory-authored void runtime tool without presenters |
44
- | `RuntimeToolFactoryHandlerContext` | _type_ | parsed factory context plus parsed tool input |
45
- | `RuntimeToolFactoryIdentityFields` | _type_ | per-tool action, semantic method, optional `effect?` and optional identity metadata |
46
- | `RuntimeToolIdentity` | _type_ | `{ serviceName, action, scope?, method, effect?, meta? }` for runtime lifecycle/audit and repeatable-read derivation (`readOnlyHint` → `effect: 'write'` → `effect: 'read'` → `GET`, guarded by `destructiveHint !== true`) |
47
- | `RuntimeToolHandlerContext` | _type_ | runtime context with the definition's parsed input |
48
- | `RuntimeToolOutput` | _type_ | output inferred from a runtime tool's optional Zod schema |
49
- | `RuntimeToolPresenters` | _type_ | optional MCP and AI SDK `toModelOutput` presentation callbacks |
50
- | `RuntimeMcpPresentation` | _type_ | MCP content/metadata result without framework-owned `structuredContent` or `isError` |
51
- | `RuntimeMcpInput` | _type_ | typed accepted multi-round input for an opted-in runtime tool |
52
- | `OAuthClientRegistrationConfig` | _type_ | deterministic pre-registered → CIMD → explicit-DCR client resolution |
53
- | `CimdClientMetadata` | _type_ | validated Client ID Metadata Document |
54
- | `CimdClientMetadataFetcher` | _type_ | injectable secure network boundary for metadata loading |
55
- | `CimdFetchResponse` | _type_ | bounded metadata fetch result passed across the injectable network boundary |
56
- | `CimdFetchPolicy` | _type_ | CIMD timeout, redirect and size limits |
57
- | `CimdCachePolicy` | _type_ | bounded HTTP-aware cache policy: separate positive/negative pools (`maxEntries`), per-client and server-wide resolution rate limits (`maxResolutionsPerClient` / `maxResolutions` per `resolutionWindowMs`) |
58
- | `CimdCacheEvent` | _type_ | observable CIMD cache hit, miss, revalidation and eviction event |
59
- | `createSecureClientMetadataFetcher` | function | production HTTPS, DNS/IP-pinned CIMD fetcher |
60
- | `RuntimeAgentModelOutput` | _type_ | AI SDK model-facing text/JSON/content output returned by `present.agent` |
61
- | `AgentToolRegistry` / `AgentToolRegistryBuilder` / `AgentToolRegistryInput` | _type_ | the composed runtime surface and its builder: declared defaults, `replace`/`disable` by name, and the exact `{ tools, names }` a mount receives |
62
- | `defineToolRegistry` | function | compose runtime tools over one declared default set; an unknown `replace`/`disable` name is refused instead of silently leaving the default in place |
63
- | `ToolExtend` | _type_ | extra-args extension for `mountMcp` / `mountAgent` |
64
- | `ToolAccess` / `ToolGate` / `ToolOpenReason` | _types_ | mandatory mount-time access policy: `{ gate: ToolGate }` (with required `beforeHandle`), explicit `{ open: 'public' \| 'local-operator' \| 'remote', afterHandle? }`, or `{ inspect: true }` (read-only surface inspection: mounts schemas/catalog/help while refusing every tool invocation fail-closed with `FORBIDDEN` before extensions, hooks, durability, auth or multi-round handlers) |
65
- | `ToolLifecycle` | _type_ | `beforeHandle` / `afterHandle` hooks composed into a `ToolGate` via `composeToolLifecycle` |
66
- | `ToolExecutionControlReason` | _type_ | internal managed-execution stop reason: stale run or requested interruption |
67
- | `ToolExecutionControlError` | class | control-flow error used to unwind a superseded managed tool call without presenting it as a model-facing tool failure |
68
- | `isToolExecutionControlError` | function | narrow an unknown thrown value to the managed execution control error |
69
- | `ToolOperation` | _type_ | executable path-free operation shape shared by contract and framework-native runners |
70
- | `ToolCallHooks` | _type_ | object-shaped `beforeToolCall` / `afterToolCall` / `onToolError` observability hooks; the raw thrown value reaches the last two as `error` ([guide](../guide/observability.md#the-cause-behind-a-failed-tool-call)) |
71
- | `BeforeToolCallOptions` | _type_ | `{ toolName, args, context, endpoint }` passed before execution |
72
- | `AfterToolCallOptions` | _type_ | completed call options plus `{ result, durationMs, error? }` |
73
- | `ToolErrorOptions` | _type_ | `{ toolName, error, context, endpoint }` for a thrown handler-path value |
74
- | `ErrorHintFn` | _type_ | `(toolName, errorCode) => string \| null` — a per-tool recovery hint, shared by every mount |
75
- | `ToolResult` | _type_ | the result of one tool call |
76
- | `ToolInvoker` | _type_ | immutable compiled dispatcher (`names`, envelope `invoke`, throwing `invokeOrThrow`) |
77
- | `ToolInvokerConfig` | _type_ | compile-time `access`, exposure, extension and presentation options |
78
- | `ToolInvocationOptions` | _type_ | per-call source, context, hooks and output-strip reporter |
79
- | `ToolCallContext` | _type_ | the context every tool hook receives — `{ source, mcp? }` plus whatever the mount's `context` added |
80
- | `ViewFileOptions` | _type_ | shared URL/managed-file-boundary policy for `defineViewFileTool`, `mountViewFile` and `resolveMedia` |
81
- | `ViewFileOutput` | _type_ | neutral managed batch result with multimodal `content` and per-item `errors` |
82
- | `ViewFileInputSchema` | constant | one media path/URL or an array of at most 20; rejects a JSON array written as text, including in array items, before IO |
83
- | `ViewFileOutputSchema` | constant | Zod schema for the neutral managed view-file batch result |
84
- | `ViewFileErrorSchema` | constant | Zod schema for one structured per-item view failure |
85
- | `McpAnnotations` | _type_ | MCP annotations on a media result |
86
- | `McpAnnotationsSchema` | constant | Zod schema for MCP media annotations |
87
- | `McpMediaContentSchema` | constant | Zod schema for text/image/audio media content — the blocks MCP declares, field for field |
88
- | `MCP_FILE_NAME_META_KEY` | constant | the namespaced `_meta` key (`stitchkit/fileName`) under which an `image` or `audio` block carries the file name of its source |
89
- | `CollectToolsConfig` | _type_ | options for `collectTools` |
90
- | `findUntypedProperties` | function | every property in a JSON Schema with no `type`/`enum`/`$ref` — what a model is shown and cannot obey ([guide](../guide/mcp-and-agents.md)) |
91
- | `UntypedProperty` | _type_ | one such property — `{ path, description? }` |
92
- | `findNonPortableFormats` | function | deep finder for formats outside the portable MCP/AJV baseline |
93
- | `NonPortableFormat` | _type_ | one `{ path, format }` portability finding |
94
- | `PORTABLE_JSON_SCHEMA_FORMATS` | constant | portable-format baseline used by MCP validation |
95
- | `ToolNameEntry` | _type_ | one `listToolNames` row — `{ kind, name, service, method, expose }` |
96
- | `McpMediaContent` | _type_ | a multimodal MCP content item |
97
-
98
- ### Native tools
99
-
100
- Generic host-supplied operations — managed definitions for the canonical
101
- runtime-tool runner, plus deliberate raw MCP adapters over the same mechanics.
102
-
103
- | Export | Kind | Summary |
104
- |--------|------|---------|
105
- | `defineDownloadTool` | function | define a guarded, size-capped managed download for MCP/Agent `runtimeTools` |
106
- | `defineUploadTool` | function | define a typed managed local-file upload for MCP/Agent `runtimeTools` |
107
- | `defineWaitTool` | function | define a typed, cancellable managed polling operation for MCP/Agent `runtimeTools` |
108
- | `defineViewFileTool` | function | define a guarded, batch-capped managed multimodal operation for MCP/Agent `runtimeTools` |
109
- | `DefineDownloadToolConfig` | _type_ | Zod input, stable identity, URL resolver, storage policy and presenters for `defineDownloadTool` |
110
- | `DefineUploadToolConfig` | _type_ | stable identity, typed output, upload callback and presenters for `defineUploadTool` |
111
- | `DefineWaitToolConfig` | _type_ | Zod input/state, identity, poll/done/timeout policy and presenters for `defineWaitTool` |
112
- | `DefineViewFileToolConfig` | _type_ | identity, media security policy and optional presenters for `defineViewFileTool` |
113
- | `ManagedNativeToolConfig` | _type_ | shared name, description, identity, exposure and annotations for managed native factories |
114
- | `NativeToolIdentity` | _type_ | pathless service/action/scope/meta identity; semantic method is factory-owned |
115
- | `ManagedWaitRender` | _type_ | optional managed wait terminal text and failure classification |
116
- | `UploadToolInputSchema` | constant | fixed `{ path: string }` input schema for `defineUploadTool` |
117
- | `defineAsyncOperation` | function | runtime-only start/status/wait plus configured cancel/result/artifacts definitions; see the [durable application-owned recipe](../guide/mcp-and-agents.md#durable-application-owned-execution) |
118
- | `defineAsyncOperationContract` | function | define one canonical Zod-first HTTP contract for start/status/wait plus optional capabilities; execution and recovery remain application-owned |
119
- | `bindContractAsyncOperation` | function | bind literal methods from an existing contract without creating another HTTP surface |
120
- | `createAsyncOperationSnapshotSchema` | function | canonical pending/running/succeeded/failed/cancelled Zod snapshot |
121
- | `AsyncOperationSnapshotSchema` | _type_ | the snapshot union `createAsyncOperationSnapshotSchema` returns when no `progress` schema is configured |
122
- | `AsyncOperationSnapshotSchemaWithProgress` | _type_ | the same union with the configured `progress` schema optional on every phase |
123
- | `AsyncOperationCancelResultSchema` | constant | validated accepted/already_terminal/rejected cancellation result |
124
- | `AsyncOperationCancelResult` | _type_ | validated cancel capability result |
125
- | `AsyncOperationCancelCapability` | _type_ | optional typed domain cancellation callback |
126
- | `AsyncOperationCapability` | _type_ | generated capability-name union |
127
- | `AsyncOperationStartDefinition` / `AsyncOperationFollowDefinition` | _type_ | generated runtime definition types |
128
- | `AsyncOperationIdentity` | _type_ | shared service/action/scope/meta identity for an operation |
129
- | `AsyncOperationOutputCapability` | _type_ | optional result/artifact schema plus handler |
130
- | `RuntimeAsyncOperationConfig` | _type_ | runtime-only descriptor configuration |
131
- | `RuntimeAsyncOperation` | _type_ | inferred generated definitions and schemas |
132
- | `AsyncOperationContractConfig` | _type_ | canonical contract config where start returns the operation id; optional `expose` names the transports per capability, because this contract is built inside the framework and never passes through a consumer's configured factory |
133
- | `AsyncOperationContractWithStartOutputConfig` | _type_ | canonical contract config with an application start envelope and typed id extractor |
134
- | `DefinedAsyncOperationContract` | _type_ | generated contract, capability keys, schemas and parsed adapters |
135
- | `ContractAsyncOperationConfig` | _type_ | literal contract method binding and handlers |
136
- | `AdaptedContractAsyncOperationConfig` | _type_ | existing-contract binding with explicit id and per-capability input adapters |
137
- | `BoundAdaptedContractAsyncOperation` | _type_ | inferred adapted binding with parsed id/input projectors |
138
- | `AdaptedContractAsyncOperationStartKey` | _type_ | existing-contract keys with a declared start output |
139
- | `AdaptedContractAsyncOperationFollowKey` | _type_ | existing-contract keys with both input and output schemas |
140
- | `AdaptedContractAsyncOperationWaitKey` | _type_ | adapted follow-up keys whose output matches the selected status snapshot |
141
- | `ContractAsyncOperationInputAdapters` | _type_ | guaranteed direct-binding status/wait input adapters plus configured optional capabilities |
142
- | `ContractAsyncOperationKeys` | _type_ | literal method-key union of a bound contract |
143
- | `ContractAsyncOperationStartKey` | _type_ | direct-binding start keys whose declared ID schema has stable input/output |
144
- | `ContractAsyncOperationFollowKey` | _type_ | contract keys whose input schema type matches the selected start output |
145
- | `ContractAsyncOperationWaitKey` | _type_ | follow-up keys whose output schema type also matches the selected status output |
146
- | `composeToolLifecycle` | function | ordered composition of tool before/after phases |
147
- | `mountDownload` | function | raw MCP "download a URL to disk" adapter (SSRF-guarded, size-capped) |
148
- | `mountUpload` | function | raw MCP "upload a local file" adapter |
149
- | `mountWait` | function | raw MCP generic `--wait`-style polling adapter |
150
- | `DownloadToolConfig` | _type_ | config for `mountDownload` |
151
- | `UploadToolConfig` | _type_ | config for `mountUpload` |
152
- | `WaitToolConfig` | _type_ | config for `mountWait` |
153
-
154
- ### OAuth 2.1 provider
155
-
156
- A native remote-connector auth surface for MCP — [guide](../guide/mcp-and-agents.md#oauth-21--a-native-remote-connector).
157
-
158
- | Export | Kind | Summary |
159
- |--------|------|---------|
160
- | `mountOAuthProvider` | function | the OAuth 2.1 provider routes (DCR, PKCE, token) |
161
- | `oauthProtectedResourceRoute` | function | the RFC 9728 protected-resource-metadata route |
162
- | `protectedResourceMetadataUrl` | function | build the metadata URL for a resource |
163
- | `wwwAuthenticateHeader` | function | build the `WWW-Authenticate` challenge header |
164
- | `PROTECTED_RESOURCE_PATH` | const | the well-known metadata path |
165
- | `OAuthProviderConfig` | _type_ | config for `mountOAuthProvider`; `maxRequestBodyBytes` bounds the `/token` and `/register` bodies (64 KiB by default) |
166
- | `ProtectedResourceConfig` | _type_ | config for `oauthProtectedResourceRoute` |
167
- | `ApplicationType` | _type_ | DCR `application_type` — `'native'` (loopback allowed) \| `'web'` (https only) |
168
- | `AuthCodeData` | _type_ | a stored authorization-code record |
169
- | `AuthRequest` | _type_ | a parsed authorization request |
170
- | `ClientMetadata` | _type_ | dynamic-client-registration metadata |
171
- | `RefreshData` | _type_ | a stored refresh-token record |
172
- | `RegisteredClient` | _type_ | a registered OAuth client |
173
-
174
- ### Durable tool bodies
175
-
176
- A mounted tool body can be made restartable without adopting `agent-runtime`: declare a
177
- factory and `step` / `sleep` / `waitFor` appear in the handler context, backed by whatever
178
- ledger the application already has.
179
-
180
- ```ts
181
- mountAgent(services, {
17
+ ## OAuth 2.1 — a native remote connector
18
+
19
+ A remote MCP server is connectable from Claude (Desktop / web "custom
20
+ connector") only through the MCP authorization spec: OAuth 2.1 with PKCE, plus
21
+ the discovery documents (RFC 9728 / 8414), Client ID Metadata Documents (CIMD)
22
+ and resource indicators (RFC 8707). A Bearer-only server returns a
23
+ bare `401` and the connector never establishes.
24
+
25
+ stitchkit ships the OAuth **protocol mechanics**; the app supplies only
26
+ **identity and storage**. Three pieces wire it together:
27
+
28
+ ```ts
29
+ import { mountOAuthProvider, oauthProtectedResourceRoute } from 'stitchkit/tools'
30
+ import { createMcpHandler, createMcpHttpRoute } from 'stitchkit/tools/mcp'
31
+ import { createServer } from 'stitchkit/server'
32
+
33
+ const resource = 'https://api.example.com/mcp'
34
+ const issuer = 'https://api.example.com'
35
+
36
+ // 1. Resource server — the 401 now points at the metadata.
37
+ const mcp = createMcpHandler({
38
+ serverInfo: { name: 'my-app', version: '1.0.0' },
39
+ auth: resolveOAuthToken, // validate the Bearer JWT (verifyJwt + audience)
40
+ services,
182
41
  access: { gate: { beforeHandle: authHook } },
183
- durability: (toolCallId) => myLedgerFor(toolCallId),
42
+ protectedResource: { resource, authorizationServers: [issuer] },
43
+ })
44
+
45
+ // 2. Authorization server — CIMD, /authorize (PKCE), /token.
46
+ const oauthRoutes = mountOAuthProvider({
47
+ issuer,
48
+ resource,
49
+ signingSecret: env.OAUTH_SECRET,
50
+ clientRegistration: {
51
+ preRegistered: { get: getFirstPartyClient },
52
+ // CIMD is enabled with secure defaults; DCR remains disabled.
53
+ },
54
+ codes, refreshTokens, // your stores (DB or in-memory)
55
+ authorizeUser, // → { userId, approvedScopes } | Response
56
+ })
57
+
58
+ createServer({
59
+ services,
60
+ rawRoutes: [
61
+ createMcpHttpRoute({ path: '/mcp', handler: mcp }),
62
+ oauthProtectedResourceRoute({ resource, authorizationServers: [issuer] }),
63
+ ...oauthRoutes,
64
+ ],
65
+ })
66
+ ```
67
+
68
+ Access tokens are signed HS256 JWTs (`signJwt`) whose `aud` is the resource and
69
+ whose `iss` is the issuer — validate both in `auth` with
70
+ `verifyJwt(token, secret, { audience: resource, issuer })`. `authorizeUser` is
71
+ where the app authenticates the user (reuse an existing session) and records
72
+ consent; return `{ userId, approvedScopes }`, where approved scopes are a subset
73
+ of the requested/supported values, or a `Response` to redirect the browser to a
74
+ login page first. The AS and resource server can co-locate or live
75
+ on separate origins. See
76
+ [ADR 0015](../decisions/0015-oauth-resource-server.md).
77
+
78
+ Client resolution is deterministic: exact pre-registered client, then an HTTPS
79
+ URL client id resolved as CIMD, then explicitly enabled DCR. CIMD is on by
80
+ default; DCR is off unless `clientRegistration.dcr` supplies both `register` and
81
+ `get`. A CIMD-only deployment therefore exposes neither `/register` nor a
82
+ `registration_endpoint`. The metadata document must declare a `client_id` that
83
+ exactly equals its URL, explicit redirect URIs and
84
+ `token_endpoint_auth_method: 'none'`.
85
+
86
+ The token endpoint and `/register` read at most 64 KiB of a request body, or
87
+ `maxRequestBodyBytes` when you set it; a larger one is answered `413` with
88
+ `invalid_request` and the rest is not read.
89
+
90
+ The production fetcher rejects credentials, fragments, non-HTTPS URLs and
91
+ private/reserved targets. Every redirect is DNS-resolved and IP-pinned again;
92
+ timeouts, redirect count and body size are bounded. Its bounded cache respects
93
+ `Cache-Control` (including `no-store`/`no-cache`), `Age`, `Expires`, `ETag` and
94
+ `Last-Modified`, coalesces concurrent misses and reports sanitized cache events;
95
+ invalid or unavailable identity receives only a short fail-closed cache entry.
96
+
97
+ Resolution itself is rate-limited on two levels (`CimdCachePolicy`):
98
+ `maxResolutionsPerClient` (default 10) bounds ONE `client_id` per
99
+ `resolutionWindowMs` window (default 60 s) — a client whose document disables
100
+ caching burns its own budget, not the server's — while `maxResolutions`
101
+ (default 120) caps the server-wide outbound rate as the flood backstop.
102
+ Positive and negative cache entries keep separate pools of `maxEntries` each,
103
+ so a flood of unresolvable ids cannot evict warmed clients and a burst of
104
+ successes cannot reset a failing client's backoff.
105
+
106
+ ### Authorization hardening (MCP 2026-07-28)
107
+
108
+ - **`iss` on every authorization response (RFC 9207, SEP-2468).** Success *and*
109
+ error redirects carry `iss`, and the AS metadata advertises
110
+ `authorization_response_iss_parameter_supported: true`. A client that talks to
111
+ several authorization servers validates `iss` before redeeming the code, which
112
+ closes the **mix-up attack** — an attacker's server cannot pass its response
113
+ off as this issuer's. Additive on the wire: a client that ignores `iss` is
114
+ unaffected.
115
+ - **`application_type` on registration (SEP-837).** A client may declare
116
+ `"native"` (desktop / CLI) or `"web"` in its DCR body. A **native** client may
117
+ register an `http` loopback redirect (`http://127.0.0.1:…`, RFC 8252 §7.3); a
118
+ **web** client is held to `https` only — that mismatch is the usual cause of
119
+ the `redirect_uri` rejection CLI clients hit. Omit the field and registration
120
+ behaves exactly as before (loopback allowed); an unknown value is rejected
121
+ rather than silently defaulted.
122
+
123
+ > Dynamic Client Registration is an explicit interoperability mode, not the
124
+ > default. Enabling it changes public discovery and adds `/register`; keep it off
125
+ > unless a client that cannot publish CIMD requires it.
126
+
127
+ ## Proxying a remote API — `implementRemote`
128
+
129
+ `implement` binds a contract to local handlers. `implementRemote` binds it to a
130
+ remote HTTP API instead — every handler forwards the call to a deployed server
131
+ through the contract's typed client:
132
+
133
+ ```ts
134
+ import { createHttpClient } from 'stitchkit'
135
+ import { implementRemote } from 'stitchkit/remote'
136
+ import { createStdioMcpServer } from 'stitchkit/tools/mcp'
137
+
138
+ const http = createHttpClient({
139
+ baseUrl: 'https://api.example.com',
140
+ headers: () => ({ Authorization: `Bearer ${apiKey}` }),
141
+ })
142
+
143
+ const stdio = await createStdioMcpServer({
144
+ serverInfo: { name: 'my-app', version: '1.0.0' },
145
+ auth: null,
146
+ services: contracts.map((c) => implementRemote(c, http)),
147
+ access: { open: 'remote' },
148
+ })
149
+
150
+ // During graceful shutdown:
151
+ await stdio.close()
152
+ ```
153
+
154
+ This is how you ship a thin **local** MCP server for an API that already runs in
155
+ the cloud: the local process owns only the transport and any filesystem-facing
156
+ native tools, while every contract tool proxies to the remote API. One contract,
157
+ no duplicated business logic.
158
+
159
+ `implementRemote(contract, http, { transformArgs })` takes an optional
160
+ `transformArgs` hook that rewrites a call's arguments before they are forwarded
161
+ — e.g. to upload a local file referenced in the args and swap in its URL.
162
+
163
+ The call's signal reaches the existing typed HTTP client's request options, for endpoints
164
+ with or without arguments. An already cancelled call, including cancellation while an async
165
+ argument transform runs, dispatches no request. Bind your process signal to `createCli` or
166
+ `createCliInvoker`; `REQUEST_ABORTED` is a safe nonretryable failure with CLI exit `130`.
167
+ Cooperative origins observe `ctx.signal` and release resources when their work ends. An
168
+ origin or provider ignoring cancellation may continue after the local wait stops.
169
+
170
+ An explicit `AppError.retryable` boolean also survives this remote hop. `false` on `502` and
171
+ `true` on `409` remain the application's recommendation through HTTP, CLI, MCP and AI tools.
172
+ Absent metadata keeps the previous defaults and does not alter HTTP transport retries.
173
+
174
+ A remote failure that carries no stitchkit error envelope — an HTML `503` from a proxy
175
+ during a deploy, a `429` from a rate limiter, a `404` page, a refused connection — keeps
176
+ what the caller can act on and drops what it must not see. A response with a status
177
+ becomes `HTTP_ERROR` with that status and a fixed message; a failure with no response
178
+ becomes `CONNECTION_REQUEST_FAILED` (`502`). Neither carries `details`: the upstream
179
+ body, URL and credentials stay in the raw cause that `onToolError` and `AgentToolError.cause`
180
+ expose in-process. One rule decides `retryable` for every origin: the declared value wins,
181
+ otherwise the status decides (`408`, `429`, `502`, `503`, `504` are retryable, as for any
182
+ local tool). A call the caller cancelled (`REQUEST_ABORTED`) declares `retryable: false`;
183
+ a deadline the remote client hit (`REQUEST_TIMEOUT`, `408`) follows the status like a
184
+ `408` from a local handler.
185
+
186
+ ## Structured output
187
+
188
+ When a contract endpoint or runtime tool declares `output`, its MCP tool
189
+ registers that exact schema as `outputSchema` and returns the validated value as
190
+ `structuredContent` alongside a JSON text block. Every JSON root type is kept
191
+ unchanged: object, array, string, number, boolean and `null`. Stitchkit does not
192
+ wrap non-object values in `{ result }`; protocol-era adaptation belongs to the
193
+ official SDK.
194
+
195
+ A tool without an output contract advertises no `outputSchema` and returns no
196
+ invented structured value. Its successful MCP result has an empty `content`
197
+ list.
198
+
199
+ ## A different answer for tools — `withToolView`
200
+
201
+ An admin page wants the full record; a model wants a card. Every byte of a
202
+ tool result enters the model's context and stays in its history, and personal
203
+ fields a task does not need are better never shown to it. Two endpoints on one
204
+ path (one `expose: ['HTTP']`, one for the tools) duplicate the description, the
205
+ schemas and the handler; branching on `ctx.source` teaches every handler about
206
+ transports and still advertises the full output schema.
207
+
208
+ A **tool view** declares the difference on the endpoint instead. Most often the
209
+ difference is only the call — a model needs a lighter one, and the answer keeps
210
+ its one shape:
211
+
212
+ ```ts
213
+ import { defineContract, withToolView } from 'stitchkit';
214
+
215
+ export const items = defineContract({ prefix: 'items' }, {
216
+ list: withToolView(
217
+ {
218
+ method: 'GET', path: '/:slug/items', desc: 'List items', tool: { name: 'db_items' },
219
+ input: ItemsQuery, // include: z.array(...).default(['relations'])
220
+ output: ItemsResponse, // one answer on HTTP and on the tools
221
+ },
222
+ { defaults: { include: [] } }, // what a tool call gets when it passes nothing
223
+ ),
224
+ });
225
+ ```
226
+
227
+ When the answer itself differs, the view carries its own schema too:
228
+
229
+ ```ts
230
+ import { defineContract, withToolView } from 'stitchkit';
231
+
232
+ export const users = defineContract({ prefix: 'users' }, {
233
+ list: withToolView(
234
+ {
235
+ method: 'GET', path: '/', desc: 'List users', tool: { name: 'user_list' },
236
+ input: UserListQuery, // include: z.array(...).default(['profile', 'stats'])
237
+ output: UserListResponse, // HTTP, OpenAPI and the typed client — unchanged
238
+ },
239
+ {
240
+ defaults: { include: [] }, // what a tool call gets when it passes nothing
241
+ output: UserCardList, // the tool answer and its schema
242
+ project: (full, { input }) => ({ items: full.items.map(toCard) }), // optional: without it, `output` slices
243
+ },
244
+ ),
184
245
  });
185
246
  ```
186
247
 
187
- | Export | Kind | Summary |
188
- |--------|------|---------|
189
- | `ToolDurability` | _type_ | the port a tool body needs: `step`, `sleep`, `waitFor` |
190
- | `ToolDurabilityFactory` | _type_ | `(toolCallId, signal) => ToolDurability`, called once per call |
191
- | `DurableJsonValue` | _type_ | what a durable step result may hold — a record is read back in another process, so it must be JSON |
192
- | `createLocalStepDurability` | function | the durability engine — replay, absolute deadlines, park/deliver — over a two-method ledger the application owns |
193
- | `StepDurabilityLedger` | _type_ | the two methods an engine needs: `appendEvent`, `readEvents` |
194
- | `LocalStepDurability` | _type_ | what the engine returns; satisfies `ToolDurability` and adds `deliver`, `effect` and record introspection for the ledger's owner |
195
- | `EffectHandlers` / `EffectOutcome` / `EffectRunOptions` | _type_ | `effect(name, { run, reconcile }, { signal, reconcileTimeoutMs })`: the intent is recorded before `run`, an intent without an outcome is settled by `reconcile` and never run again; `accepted` with the proof or a recorded, final `uncertain` → ADR 0200 |
196
- | `EffectUnresolvedError` | class | an effect whose outcome this call could not settle — `run` or `reconcile` threw, `reconcile` overran, the proof was not recordable; the intent stands and the next call reconciles |
197
- | `LocalStepDurabilityOptions` | _type_ | `{ store, conversationId, runId, signal?, subscribe?, clock? }` |
198
- | `AppendAgentStoreEvent` / `ReadAgentStoreEvents` / `AgentStoreEventEnvelope` / `AgentStoreEventPage` | _type_ | the ledger's row shapes, re-exported so a ledger is typed from the entrypoint that consumes it |
199
- | `AgentToolError` | class | the model-safe envelope a failed agent tool throws |
200
- | `isAgentToolError` | function | brand check for it — a consumer running its own loop no longer parses the message |
201
-
202
- ### Introspection & internals
203
-
204
- Advanced building blocks — the shared machinery the mounts are built on.
205
-
206
- | Export | Kind | Summary |
207
- |--------|------|---------|
208
- | `collectTools` | function | resolve a service's methods to mountable tools (the shared resolver) |
209
- | `createToolLogger` | function | a ready `afterToolCall` that logs every tool call — [guide](../guide/mcp-and-agents.md#logging-tool-calls--createtoollogger) |
210
- | `summarizeTransports` | function | mixed contract/runtime operation counts and per-source breakdown for a boot-time summary |
211
- | `buildToolManifest` | function | transport-aware searchable `{ name, description, inputSchema }` rows from a mixed surface |
212
- | `ToolLoggerConfig` | _type_ | config for `createToolLogger` |
213
- | `ToolCallRecord` | _type_ | the structured record `createToolLogger` passes to `onRecord` |
214
- | `TransportSummary` | _type_ | `{ contractServices, runtimeTools, totals, sources }` from `summarizeTransports` |
215
- | `TransportCounts` | _type_ | per-transport counts (`{ HTTP, MCP, AGENT, CLI }`) |
216
- | `ToolSurfaceProjection` | _type_ | the one readonly `{ services?, runtimeTools? }` container shared by full, MCP-only and introspection surfaces (`buildToolManifest`, `listToolNames` and `describeToolCatalog` accept `ToolSurfaceProjection<SurfaceRuntimeToolDefinition>`) |
217
- | `SurfaceRuntimeToolDefinition` | _type_ | peer-free non-executable runtime-tool descriptor accepted by `listToolNames`, `buildToolManifest` and `describeToolCatalog` (including static `AGENT_*_TOOL_DESCRIPTORS`) |
218
- | `ToolManifestConfig` | _type_ | mixed surface plus required model-facing `transport` and presentation options (`flattenUnionInput`, `inputRecursionDepth`) |
219
- | `coerceJsonArgs` | function | coerce JSON-stringified array/object tool arguments, including object guards restored from JSON Schema; arbitrary transform pipes stay untouched; throws a `ZodError` naming the field when a union that keeps a string member receives a string that parses to an array its array member accepts |
220
- | `flattenToolJsonSchema` | function | project structurally identifiable discriminated unions into conservative object joins; scalar collisions retain provable types, object/array collisions retain structural alternatives, and field descriptions retain discriminator labels plus availability/requiredness hints; the projection never executes validation |
221
- | `ToolPresentationSchema` | _type_ | immutable model-facing JSON Schema document shared by tool transports |
222
- | `MountableTool` | _type_ | one operation with separate executable CLI argument schema and model-facing presentation schema |
223
- | `ToolManifestEntry` | _type_ | one `buildToolManifest` row |
224
-
225
- ---
248
+ - **One handler, one parser.** `defaults` joins the tool call's arguments
249
+ *before* the endpoint's own `input` parses them, so the handler receives an
250
+ ordinary `input` — `include: []` from a tool, the HTTP default from HTTP — and
251
+ loads only what was asked for. An explicit argument wins over the default.
252
+ - **The answer is derived, then checked.** The handler's result is validated
253
+ against the full `output` first, as always; then `project` (a pure,
254
+ synchronous function of the full result and the parsed input) or a slice by
255
+ the view's `output`, then validation against the view's schema. A projection
256
+ that throws, returns a Promise or breaks its schema is `INTERNAL_SERVER_ERROR`
257
+ — a server fault, like any output mismatch.
258
+ - **Where it applies.** The MCP, agent and CLI mounts answer with the view;
259
+ `outputSchema`, `structuredContent`, the advertised input `default`, the
260
+ catalog stamp and the surface snapshot follow it. HTTP, OpenAPI, the typed
261
+ client and the in-process [`createToolInvoker`](#in-process-calls--createtoolinvoker)
262
+ keep the full answer — code, not a model, is calling there.
263
+ - **Four forms, one helper.** With `defaults` alone the call changes and the
264
+ answer is the full `output`, validated by it and advertised as it. With
265
+ `output` and `project` the answer has its own schema. With `project` alone it
266
+ reshapes values inside the full schema. With `output` alone it is a slice, and
267
+ the full result must fit that schema — `withToolView` refuses the endpoint at
268
+ compile time when it does not.
269
+ - **Exposure.** A view needs a tool transport. With `createContractFactory<Scope>().configure({
270
+ toolExposure: { default: ['HTTP'] } })` an endpoint without `expose` is HTTP-only, so an
271
+ endpoint with a view names its tool transports in `expose`.
272
+ - **What it refuses.** `defineContract` rejects a view on an endpoint with no
273
+ tool transport or no full `output`, on a raw, `rawBody`, multipart,
274
+ `responseMeta` or streaming endpoint, a view that declares no `defaults`,
275
+ `output` or `project` — it would change nothing — and a default for a key the input does not have, for a path
276
+ param, or with a value the input would reject.
277
+
278
+ A projection adds nothing the full result does not carry: a field the tool
279
+ answer needs belongs in the full answer, loaded by the handler. Keys a
280
+ projection returns beyond its schema are reported by `onOutputStrip`; a slice
281
+ removes keys on purpose and is not reported. → [ADR 0196](../decisions/0196-a-tool-answer-is-a-declared-view.md)
282
+
283
+ ## AI agents — `mountAgent`
284
+
285
+ `mountAgent` remains the low-level path when the application owns its own model
286
+ loop and conversation state. For the optional Stitchkit-owned run/history loop,
287
+ see [Agent application runtime](./agent-runtime.md).
288
+
289
+ `mountAgent` turns a service into a Vercel AI SDK `ToolSet`, ready for
290
+ `generateText` / `streamText`:
291
+
292
+ ```ts
293
+ import { mountAgent } from 'stitchkit/tools/agent'
294
+ import { generateText } from 'ai'
295
+
296
+ const tools = mountAgent(usersService, {
297
+ context: { userId: 'agent-1' },
298
+ access: { gate: { beforeHandle: authHook } },
299
+ })
300
+
301
+ const result = await generateText({
302
+ model,
303
+ tools,
304
+ prompt: 'Create a user named Max',
305
+ })
306
+ ```
307
+
308
+ Each contract endpoint exposed on `AGENT` becomes a tool whose input schema is
309
+ the merged `params` + `input`. `context` is merged into every tool handler's
310
+ `ctx`, alongside `source: 'agent'`.
311
+
312
+ ### `AgentMountConfig`
313
+
314
+ | Field | Purpose |
315
+ |-------|---------|
316
+ | `context` | values merged into every tool handler's `ctx` |
317
+ | `access` | **required** — `{ gate: { beforeHandle, afterHandle? } }` or `{ open, afterHandle? }` (see [Guarding tools](#guarding-tools--access)) |
318
+ | `hooks` | tool-call observability hooks — `afterToolCall` fires on every result |
319
+ | `extend` | add extra args resolved before the handler runs (see below) |
320
+ | `runtimeTools` | framework-managed pathless operations from `defineRuntimeTool` |
321
+
322
+ `access` works the same as on the MCP server — pass `{ gate: { beforeHandle: authHook } }`
323
+ (or an explicit `{ open }` reason when unguarded).
324
+
325
+ ### Adding tool-only args — `extend`
326
+
327
+ `extend` adds **tool-only** arguments — fields the model fills that are resolved
328
+ into context, then stripped before the contract handler sees them. Use it when a
329
+ tool needs an argument the HTTP endpoint does not — the classic case being a
330
+ **multi-tenant** server reached by one API key, where the model passes `tenantId`
331
+ on every call. It is the same `ToolExtend` shape on `mountMcp`, `createMcpHandler`
332
+ and `mountAgent`:
333
+
334
+ ```ts
335
+ interface ToolExtend {
336
+ /** Extra Zod fields added to every matching tool's input schema. */
337
+ schema: Record<string, z.ZodType>
338
+ /** Turn the extra args into context merged into the handler's ctx. */
339
+ resolve: (args: Record<string, unknown>) => Partial<Ctx> | Promise<Partial<Ctx>>
340
+ /** Limit the extension to specific methods — default: every method. */
341
+ filter?: (service: ServiceDef, method: MethodDef) => boolean
342
+ }
343
+ ```
344
+
345
+ On the MCP server — add `tenantId` to each tool, validate access in `resolve`,
346
+ inject the resolved tenant into `ctx`, and `filter` to the tenant-scoped tools:
347
+
348
+ ```ts
349
+ createMcpHandler({
350
+ serverInfo, auth,
351
+ services: [widgetsService],
352
+ access: { gate: { beforeHandle: authHook } },
353
+ extend: {
354
+ schema: { tenantId: z.string().describe('Tenant to act on') },
355
+ resolve: async ({ tenantId }) => {
356
+ const id = String(tenantId)
357
+ if (!(await tenantExists(id))) throw new Error(`unknown tenant ${id}`)
358
+ return { tenantId: id } // merged into ctx → ctx.tenantId
359
+ },
360
+ filter: (_service, method) => method.scope === 'tenant',
361
+ },
362
+ })
363
+ ```
364
+
365
+ The model calls `widgets_list({ tenantId: 't_123' })`; `resolve` checks access and
366
+ puts `tenantId` on `ctx`; the contract handler reads `ctx.tenantId` (same place
367
+ as the HTTP prefix param — see
368
+ [Route groups → param prefixes](./server.md#param-prefixes-resource-scoped-paths)),
369
+ so one handler serves both surfaces. Pair `extend` with `access: { gate: { beforeHandle: authHook } }`
370
+ so the tool call is still scope-gated.
371
+
372
+ ## Pathless runtime tools and multimodal results
373
+
374
+ Use `defineRuntimeTool` for an operation that has no HTTP path but still needs
375
+ the same validation, isolated per-call context, lifecycle/RBAC and hooks as a
376
+ contract tool. The handler returns one transport-neutral, schema-validated
377
+ result. Optional presentation callbacks map that result to MCP content and AI
378
+ SDK model output without coupling the handler to either SDK:
379
+
380
+ ```ts
381
+ import { defineRuntimeTool } from 'stitchkit/tools'
382
+ import { createMcpHandler } from 'stitchkit/tools/mcp'
383
+ import { mountAgent } from 'stitchkit/tools/agent'
384
+ import { z } from 'zod'
385
+
386
+ const renderPreview = defineRuntimeTool({
387
+ name: 'render_preview',
388
+ description: 'Render and inspect a preview',
389
+ identity: {
390
+ serviceName: 'mediaTools',
391
+ action: 'renderPreview',
392
+ scope: 'admin',
393
+ method: 'POST',
394
+ },
395
+ input: z.object({ prompt: z.string() }),
396
+ output: z.object({ assetId: z.string(), imageBase64: z.string() }),
397
+ handler: async ({ input }) => renderAndSave(input.prompt),
398
+ present: {
399
+ mcp: (output) => ({
400
+ content: [
401
+ { type: 'image', data: output.imageBase64, mimeType: 'image/png' },
402
+ { type: 'text', text: output.assetId },
403
+ ],
404
+ }),
405
+ agent: (output) => ({
406
+ type: 'content',
407
+ value: [{
408
+ type: 'file',
409
+ data: { type: 'data', data: output.imageBase64 },
410
+ mediaType: 'image/png',
411
+ filename: `${output.assetId}.png`,
412
+ }],
413
+ }),
414
+ },
415
+ })
416
+
417
+ const handleMcp = createMcpHandler({
418
+ serverInfo: { name: 'my-app', version: '1.0.0' },
419
+ auth,
420
+ services: [service],
421
+ runtimeTools: [renderPreview],
422
+ access: { gate: { beforeHandle: authHook } },
423
+ hooks: audit.toolCall,
424
+ })
425
+
426
+ const agentTools = mountAgent([service], {
427
+ runtimeTools: [renderPreview],
428
+ access: { gate: { beforeHandle: authHook } },
429
+ hooks: audit.toolCall,
430
+ })
431
+ ```
432
+
433
+ When several runtime tools share application context and identity, bind both
434
+ once with `createRuntimeToolFactory`. Its Zod context schema is parsed once per
435
+ call inside the same runner; the authored handler receives validated context and
436
+ parsed `input`, while lifecycle, hooks, output validation and presenters remain
437
+ unchanged:
438
+
439
+ ```ts
440
+ const knowledgeTools = createRuntimeToolFactory({
441
+ serviceName: 'agentKnowledge',
442
+ scope: 'user',
443
+ context: z.object({ userId: z.string(), tz: z.string() }),
444
+ })
445
+
446
+ const countRecords = knowledgeTools.define({
447
+ name: 'count_records',
448
+ action: 'countRecords',
449
+ method: 'GET',
450
+ description: 'Count records',
451
+ input: z.object({ kind: z.string() }),
452
+ output: z.object({ count: z.number() }),
453
+ handler: async ({ userId, tz, input }) => countFor(userId, tz, input.kind),
454
+ })
455
+ ```
456
+
457
+ `serviceName` and `scope` cannot be overridden by one definition. Use standalone
458
+ `defineRuntimeTool` when tools do not share a context schema or identity.
459
+
460
+ `expose` defaults to `['MCP', 'AGENT']`; set an explicit subset when an
461
+ operation belongs on only one surface. Include `'CLI'` explicitly to reuse the
462
+ definition through `createCli({ runtimeTools, access })`; adding CLI support never
463
+ widens existing definitions silently. The configured identity becomes the
464
+ hook/lifecycle `OperationIdentity` and the tool `RequestEvent`
465
+ (`serviceName`, `action`, `httpMethod`). A runtime operation has no HTTP route,
466
+ so no fake `path` is added.
467
+
468
+ When `output` is declared, Stitchkit validates the neutral handler result after
469
+ `afterHandle`. MCP owns `structuredContent` and `isError`: a presenter supplies
470
+ only rich `content`/metadata, while the framework inserts the validated
471
+ structured result and normalises failures. The Agent adapter uses the AI SDK's
472
+ official `toModelOutput` callback, so `execute` and application UI keep the
473
+ neutral output while the model receives text/file content. Presentation
474
+ callbacks require an output schema.
475
+
476
+ The MCP registration uses an identity carrier: the SDK advertises the compiled
477
+ JSON Schema but forwards the raw object into Stitchkit. Input failures therefore
478
+ use the same validation, lifecycle and hook path as contract tools.
479
+
480
+ ### Managed wait, download, upload and view-file
481
+
482
+ The common imperative shapes have typed definition factories. They produce
483
+ ordinary runtime-tool definitions, so one value can enter `runtimeTools` on MCP
484
+ and Agent and receives the same lifecycle, hooks, context, cancellation,
485
+ collision checks and introspection as any `defineRuntimeTool` operation:
486
+
487
+ ```ts
488
+ import {
489
+ defineDownloadTool,
490
+ defineUploadTool,
491
+ defineViewFileTool,
492
+ defineWaitTool,
493
+ } from 'stitchkit/tools'
494
+ import { createManagedFileBoundary } from 'stitchkit/files'
495
+ import { z } from 'zod'
496
+
497
+ const files = await createManagedFileBoundary({
498
+ root: '/srv/job-media',
499
+ createRoot: true, // creates only this final directory; /srv must already be trusted
500
+ inspectionTimeoutMs: 15_000,
501
+ inspect: ({ prefix, name, declaredMediaType, signal }) =>
502
+ inspectFile(prefix, { name, declaredMediaType, signal }),
503
+ })
504
+
505
+ const waitForJob = defineWaitTool({
506
+ name: 'wait_for_job',
507
+ description: 'Wait for a job to finish',
508
+ identity: { serviceName: 'jobs', action: 'waitForJob', scope: 'user' },
509
+ input: z.object({ id: z.string() }),
510
+ state: z.object({ id: z.string(), status: z.enum(['RUNNING', 'DONE']) }),
511
+ poll: ({ id }, context) => getJob(id, context.signal),
512
+ done: (state) => state.status === 'DONE',
513
+ backoff: [2, 3, 5],
514
+ defaultTimeout: 120,
515
+ })
516
+
517
+ const downloadResult = defineDownloadTool({
518
+ name: 'download_result',
519
+ description: 'Download a completed result',
520
+ identity: { serviceName: 'jobs', action: 'downloadResult', scope: 'user' },
521
+ input: z.object({ id: z.string() }),
522
+ resolveUrl: ({ id }) => resolveResultUrl(id),
523
+ files,
524
+ pathFromInput: ({ id }) => `results/${id}.bin`,
525
+ })
526
+
527
+ const uploadInput = defineUploadTool({
528
+ name: 'upload_input',
529
+ description: 'Upload a local input file',
530
+ identity: { serviceName: 'jobs', action: 'uploadInput', scope: 'user' },
531
+ output: z.object({ url: z.url() }),
532
+ files,
533
+ upload: (source, context) => uploadBytes(source.bytes, context.signal),
534
+ })
535
+
536
+ const viewResult = defineViewFileTool({
537
+ name: 'view_result',
538
+ description: 'Inspect generated media',
539
+ identity: { serviceName: 'jobs', action: 'viewResult', scope: 'user' },
540
+ // Local files are disabled when files is omitted. URL fetches retain SSRF
541
+ // protection; use allowPrivateHosts only for an explicitly trusted network.
542
+ files,
543
+ })
544
+
545
+ const runtimeTools = [waitForJob, downloadResult, uploadInput, viewResult]
546
+ ```
547
+
548
+ Managed factories return neutral validated data. Expected failures go through
549
+ the standard failed `ToolResult` path rather than masquerading as a successful
550
+ payload with `isError`. Wait sleep is abort-aware, guarded downloads receive the
551
+ active signal, and upload implementations receive it on their typed context.
552
+ Managed view-file accepts one or several paths/URLs, retains successful
553
+ multimodal content beside structured per-item `errors`, and charges every item
554
+ to one total 20 MB batch budget. Its MCP and Agent presenters are built in;
555
+ remote fetch cancellation follows the active call signal.
556
+
557
+ `paths` is one path/URL string or an actual array of strings (at most 20).
558
+ Pass `{ paths: ['image.png'] }`, not `{ paths: '["image.png"]' }`: a JSON
559
+ array written as text fails input validation before any file or network access,
560
+ with the hint `paths is a list written as text — pass an array of paths or one
561
+ path`. The same rule applies to array items and the raw `mountViewFile` input.
562
+ Ordinary file names containing brackets, such as `[preview].png`, remain valid.
563
+ A local file with an unsupported extension is refused before reading; its
564
+ per-item error identifies the caller's path and the extension it saw.
565
+
566
+ Each inline `image` and `audio` block carries the file name of its source in
567
+ `_meta['stitchkit/fileName']` (`MCP_FILE_NAME_META_KEY`): a managed file keeps
568
+ its own name, a URL takes its download name — the path's base name with the
569
+ body's extension. MCP declares no file name on `ImageContent` or `AudioContent`,
570
+ and the MCP server SDK drops an undeclared field from `content`, so the name is
571
+ in `_meta`, the protocol's place for what a block carries beyond it. The block
572
+ is therefore the same in the handler's output, an Agent's result,
573
+ `structuredContent` and MCP `content`, and a host reads the name from the block
574
+ it renders. A CLI saves the block under that name with
575
+ [`--output-dir`](cli.md#saving-result-media).
576
+
577
+ The older `mountWait`, `mountDownload`, `mountUpload` and `mountViewFile`
578
+ functions remain
579
+ intentional raw MCP adapters with their text-envelope behavior. Use them under
580
+ `rawTools` only when opting out of managed policy is deliberate; they share the
581
+ same neutral mechanics but do not gain lifecycle or hooks. The raw view-file
582
+ adapter preserves its content-only MCP envelope while using the same bounded
583
+ batch operation.
584
+
585
+ ### Async-operation protocol
586
+
587
+ For a complete long-running operation, define the linked runtime-only surface
588
+ once. Stitchkit owns transport names, validation and wait mechanics; the
589
+ application still owns storage, execution, retries and domain states:
590
+
591
+ ```ts
592
+ import {
593
+ createAsyncOperationSnapshotSchema,
594
+ defineAsyncOperation,
595
+ } from 'stitchkit/tools'
596
+
597
+ const id = z.object({ id: z.string() })
598
+ const state = z.object({
599
+ phase: z.enum(['pending', 'running', 'succeeded']),
600
+ value: z.string().optional(),
601
+ })
602
+ const snapshot = createAsyncOperationSnapshotSchema({
603
+ failure: z.object({ code: z.string() }),
604
+ progress: z.object({ current: z.number(), total: z.number() }),
605
+ })
606
+
607
+ const exportOperation = defineAsyncOperation({
608
+ mode: 'runtime-only',
609
+ name: 'export',
610
+ description: 'Export project data',
611
+ identity: { serviceName: 'exports', action: 'export', scope: 'user' },
612
+ startInput: z.object({ projectId: z.string() }),
613
+ id,
614
+ state,
615
+ snapshot,
616
+ start: ({ projectId }) => enqueueExport(projectId),
617
+ authorize: ({ id }, capability, ctx) => authorizeExport(id, capability, ctx),
618
+ inspect: ({ id }, ctx) => readExport(id, ctx.signal),
619
+ classify: (job) => ({ phase: job.phase }),
620
+ result: {
621
+ output: z.object({ value: z.string() }),
622
+ handler: (job) => ({ value: job.value ?? '' }),
623
+ },
624
+ })
625
+
626
+ const runtimeTools = exportOperation.runtimeTools
627
+ ```
628
+
629
+ #### Durable application-owned execution
630
+
631
+ The executable reference
632
+ [`durable-async-operation-harness.ts`](../../packages/core/examples/tools/durable-async-operation-harness.ts)
633
+ shows the complete boundary behind that surface. It composes
634
+ `defineAsyncOperationContract`, `defineAsyncOperation`, `createApplication`,
635
+ `createBoundedAdmission`, managed shutdown and `createAgentToolFenceLifecycle`
636
+ around an injected store and provider.
637
+
638
+ The store transactionally owns the idempotency key **and normalized request
639
+ hash**. Reusing both returns the existing operation; reusing the key with a
640
+ different hash conflicts. Every mutation is an expected-revision CAS. Before an
641
+ external call, the application persists a unique attempt/effect key and marks
642
+ the dispatch `possibly-dispatched`; a lost response is therefore reconciled by
643
+ that key after restart and is never treated as permission to submit the effect
644
+ again. Provider acknowledgement, progress, cancellation intent, result and
645
+ artifact references remain durable application state.
646
+
647
+ Agent tool fencing and operation idempotency are separate guarantees. The fence
648
+ prevents a stale run owner from crossing an effect boundary; the transactional
649
+ idempotency record makes a repeated current call converge on one operation.
650
+ Neither replaces the other.
651
+
652
+ Stitchkit deliberately does **not** own the durable queue, operation database,
653
+ lease renewal, provider retry/reconciliation protocol, asset catalog or domain
654
+ states. The process-local application resource stops admission and drains
655
+ accepted work; unresolved durable records survive shutdown for the next
656
+ recovery pass. The packed consumer lane executes this composition from the
657
+ published package on Bun and Node.
658
+
659
+ Every follow-up repeats `authorize`; an opaque id is never authority. Aborting
660
+ `wait` only stops waiting and never calls optional domain `cancel`.
661
+
662
+ For a new HTTP surface, derive the canonical capability contract once. The
663
+ factory defines schemas and routes only; the application still supplies normal
664
+ handlers to `implement` and owns the job:
665
+
666
+ ```ts
667
+ import { defineAsyncOperationContract } from 'stitchkit/tools'
668
+ import { z } from 'zod'
669
+
670
+ const operationId = z.object({ id: z.string() })
671
+ const operationSnapshot = z.object({
672
+ phase: z.enum(['pending', 'running', 'succeeded', 'failed', 'cancelled']),
673
+ })
674
+
675
+ const operations = defineAsyncOperationContract({
676
+ prefix: 'exports',
677
+ scope: 'user',
678
+ description: 'Export project data',
679
+ startInput: z.object({ projectId: z.string() }),
680
+ id: operationId,
681
+ snapshot: operationSnapshot,
682
+ cancel: true,
683
+ result: z.object({ downloadUrl: z.url() }),
684
+ })
685
+
686
+ // Pass operations.contract and ordinary handlers to implement(...).
687
+ // operations.capabilities/schemas/adapters are the canonical protocol metadata.
688
+ ```
689
+
690
+ If an existing dedicated contract has a different wire shape — for example
691
+ `start` returns a snapshot while follow-ups accept separate envelopes — bind it
692
+ without casts or duplicate endpoints. Inline callbacks are contextually typed;
693
+ every returned id/input is parsed by the destination schema:
694
+
695
+ ```ts
696
+ import { defineContract } from 'stitchkit/contract'
697
+ import { bindContractAsyncOperation } from 'stitchkit/tools'
698
+
699
+ const startOutput = z.object({ operation: operationId, acceptedAt: z.string() })
700
+ const statusInput = z.object({ operationId: z.string() })
701
+ const waitInput = z.object({ lookup: operationId })
702
+
703
+ const existing = defineContract({ prefix: 'exports' }, {
704
+ start: {
705
+ method: 'POST', path: '/', desc: 'Start export',
706
+ input: z.object({ projectId: z.string() }), output: startOutput,
707
+ },
708
+ status: {
709
+ method: 'POST', path: '/status', desc: 'Read export status',
710
+ input: statusInput, output: operationSnapshot,
711
+ },
712
+ wait: {
713
+ method: 'POST', path: '/wait', desc: 'Wait for export',
714
+ input: waitInput, output: operationSnapshot,
715
+ },
716
+ })
717
+
718
+ const operationHandlers = {
719
+ start: () => ({ operation: { id: 'example' }, acceptedAt: new Date().toISOString() }),
720
+ status: (): z.output<typeof operationSnapshot> => ({ phase: 'pending' }),
721
+ wait: (): z.output<typeof operationSnapshot> => ({ phase: 'succeeded' }),
722
+ }
723
+
724
+ const bound = bindContractAsyncOperation({
725
+ mode: 'contract-backed',
726
+ binding: 'adapted',
727
+ contract: existing,
728
+ id: operationId,
729
+ capabilities: { start: 'start', status: 'status', wait: 'wait' },
730
+ adapters: {
731
+ idFromStart: (output) => output.operation,
732
+ inputFor: {
733
+ status: (id) => ({ operationId: id.id }),
734
+ wait: (id) => ({ lookup: id }),
735
+ },
736
+ },
737
+ handlers: operationHandlers,
738
+ })
739
+ ```
740
+
741
+ Direct binding remains the short form when start already returns the id and
742
+ every follow-up reuses that exact schema instance. Its ID schema must be
743
+ wire-stable: input and output types match and parsing has no transform,
744
+ coercion, default or overwrite. This also excludes same-type transforms because
745
+ the direct adapters would parse an already parsed ID again. Use adapted binding
746
+ and explicitly project the parsed ID back into each follow-up input. In both
747
+ modes the binder creates no router;
748
+ it returns the existing contract, handlers and protocol metadata for
749
+ application composition.
750
+
751
+ ### Explicit raw SDK registration
752
+
753
+ `rawTools` is deliberately named as an escape hatch. A tool registered there
754
+ does **not** receive stitchkit schema policy, lifecycle, per-call context or
755
+ hooks. The built-in `mountViewFile`, `mountWait`, `mountDownload` and
756
+ `mountUpload` helpers remain raw for callers that choose that boundary; the
757
+ media helper fetches with SSRF and path-traversal defenses:
758
+
759
+ ```ts
760
+ import { mountViewFile } from 'stitchkit/tools'
761
+ import { createMcpHandler } from 'stitchkit/tools/mcp'
762
+
763
+ const handleMcp = createMcpHandler({
764
+ serverInfo: { name: 'my-app', version: '1.0.0' },
765
+ auth,
766
+ services: [service],
767
+ access: { gate: { beforeHandle: authHook } },
768
+ rawTools: (server) => mountViewFile(server, { files }),
769
+ })
770
+ ```
771
+
772
+ Use raw registration only when opting out is intentional. For a protected
773
+ `view_file`, use `defineViewFileTool` in `runtimeTools`; it supplies the
774
+ canonical schemas, shared batch budget, structured partial failures and both
775
+ multimodal presenters. `resolveMedia` remains the single-item core for custom
776
+ operations whose contract intentionally differs.
777
+
778
+ ## Introspecting the complete tool surface
779
+
780
+ Deferred tool search, name snapshots and boot diagnostics accept the same
781
+ object-shaped surface as the mounts. Contract operations are followed by
782
+ runtime definitions, matching mount order; exposure filters and collisions are
783
+ resolved by Stitchkit rather than by consumer code:
784
+
785
+ ```ts
786
+ import {
787
+ buildToolManifest,
788
+ listToolNames,
789
+ summarizeTransports,
790
+ } from 'stitchkit/tools'
791
+
792
+ const surface = { services, runtimeTools: [renderPreview] }
793
+
794
+ const manifest = buildToolManifest({
795
+ ...surface,
796
+ transport: 'AGENT',
797
+ flattenUnionInput: true,
798
+ })
799
+
800
+ const names = listToolNames(surface)
801
+ const summary = summarizeTransports(surface)
802
+ ```
803
+
804
+ `buildToolManifest` returns the exact immutable presentation schema shown to
805
+ the selected MCP or Agent transport. It does not execute validation effects and
806
+ fails first on duplicate contract/runtime names. There is no runtime-only
807
+ manifest helper or public mount adapter: the framework owns merging and schema
808
+ projection.
809
+
810
+ Applications using Stitchkit's durable runtime can compose this manifest with
811
+ bounded per-run activation through `createDeferredAgentToolSurface` from
812
+ `stitchkit/agent-runtime`. It keeps selected calls as direct `mountAgent` tools
813
+ rather than routing them through a generic executor. Search receipts live in
814
+ ordinary durable tool-result history, so recovery restores activation and a
815
+ queued successor cannot inherit it. See
816
+ [Bounded deferred tool catalogs](./agent-runtime.md#bounded-deferred-tool-catalogs)
817
+ and ADR 0129. Raw `mountAgent`, `mountMcp` and `buildToolManifest` behavior is
818
+ unchanged.
819
+
820
+ `listToolNames` remains diagnostic and reports `kind: 'contract' | 'runtime'`
821
+ for every identity (with `expose` listing its resolved transports). `summarizeTransports` returns `contractServices`,
822
+ `runtimeTools`, aggregate `totals`, and a `sources` breakdown. Runtime tools
823
+ contribute only to MCP/Agent/CLI according to their `expose`; they never inflate
824
+ HTTP counts.
825
+
826
+ ## Logging tool calls — `createToolLogger`
827
+
828
+ Every tool mount fires an `afterToolCall` hook. `createToolLogger` is a ready
829
+ preset for it — one line logs each call (ok / failed, duration, which endpoint,
830
+ keyed by the endpoint's stable `serviceName` / `key` identity):
831
+
832
+ ```ts
833
+ import { createToolLogger } from 'stitchkit/tools'
834
+
835
+ mountMcp(server, services, {
836
+ access: { gate: { beforeHandle: authHook } },
837
+ hooks: createToolLogger(),
838
+ })
839
+ // [tool] ok list_widgets (widgets.list) 12ms
840
+ // [tool] warn get_widget (widgets.get) NOT_FOUND 4ms
841
+ ```
842
+
843
+ By default the line goes to `console.error` — **stderr, never stdout**. That is
844
+ deliberate: in a stdio-MCP server stdout is the JSON-RPC protocol channel, and a
845
+ log line written there corrupts the stream. If you pass your own `log`, keep it
846
+ off stdout for any stdio deployment.
847
+
848
+ Pass `log` to redirect the line, or `onRecord` to feed a metrics sink the
849
+ structured `ToolCallRecord`. That record carries `traceId` whenever an
850
+ observability context is active, so a tool call made inside an HTTP request
851
+ joins that request's log line on one key — see
852
+ [Observability](./observability.md). For a boot-time picture of what is exposed
853
+ where, `summarizeTransports({ services, runtimeTools })` returns the mixed
854
+ per-transport counts for you to log.
855
+
856
+ ## One handler, three callers
857
+
858
+ A contract handler runs the same for an HTTP request, an MCP tool call and an
859
+ agent tool call. `ctx.source` (`'http'` · `'mcp'` · `'agent'`) tells it which —
860
+ the rest of the context (`params`, `input`, anything `context` injects) is
861
+ identical. Write the handler once; it serves every surface.