@draht/coding-agent 2026.10.31-1 → 2026.11.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (492) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/bundle/chunks/anthropic-messages-UJZ4SGHU.js +6 -0
  3. package/dist/bundle/chunks/azure-openai-responses-NCMJPZVJ.js +2 -0
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +8 -5
  5. package/dist/bundle/chunks/{chunk-IGO52ZOY.js → chunk-3BJ462DN.js} +2 -2
  6. package/dist/bundle/chunks/chunk-5OXIAQP5.js +2 -0
  7. package/dist/bundle/chunks/chunk-6M3D4XVD.js +2 -0
  8. package/dist/bundle/chunks/chunk-AOCWORXE.js +2 -0
  9. package/dist/bundle/chunks/chunk-BK5LXGIH.js +2 -0
  10. package/dist/bundle/chunks/chunk-CA23BDNK.js +2 -0
  11. package/dist/bundle/chunks/chunk-DWOGGNWY.js +18 -0
  12. package/dist/bundle/chunks/{chunk-7ATV4EYW.js → chunk-EOXOMUKR.js} +1 -1
  13. package/dist/bundle/chunks/chunk-F5TDVH26.js +159 -0
  14. package/dist/bundle/chunks/chunk-HJ3PS7QP.js +4 -0
  15. package/dist/bundle/chunks/chunk-ITKDPD4D.js +12 -0
  16. package/dist/bundle/chunks/chunk-KFREX3FS.js +10 -0
  17. package/dist/bundle/chunks/{chunk-E4VZJRJ2.js → chunk-P7O36UDU.js} +2 -2
  18. package/dist/bundle/chunks/chunk-PMINB7UH.js +1401 -0
  19. package/dist/bundle/chunks/chunk-PZKD35UB.js +2 -0
  20. package/dist/bundle/chunks/{chunk-CPFKZX4B.js → chunk-Q2QKCYPU.js} +1 -1
  21. package/dist/bundle/chunks/chunk-QBUTRTYN.js +2 -0
  22. package/dist/bundle/chunks/chunk-SUVMF4W5.js +2 -0
  23. package/dist/bundle/chunks/chunk-UFACUBF2.js +16 -0
  24. package/dist/bundle/chunks/chunk-VXO6B72D.js +9 -0
  25. package/dist/bundle/chunks/{chunk-PMDUR6B5.js → chunk-WXASQQBZ.js} +2 -2
  26. package/dist/bundle/chunks/chunk-Y3NLUJYO.js +2 -0
  27. package/dist/bundle/chunks/chunk-Y7QE2R34.js +2 -0
  28. package/dist/bundle/chunks/chunk-YD5VPPI4.js +30 -0
  29. package/dist/bundle/chunks/chunk-YWRWN7ZB.js +82 -0
  30. package/dist/bundle/chunks/{cli-HTUB6WOG.js → cli-4SUT6MJ6.js} +10 -10
  31. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-BJVMNETD.js +2 -0
  32. package/dist/bundle/chunks/{execute-UUPNZJJG.js → execute-ZI7T2SUH.js} +1 -1
  33. package/dist/bundle/chunks/github-copilot.js +1 -1
  34. package/dist/bundle/chunks/{google-generative-ai-A2277FHU.js → google-generative-ai-N5IPPKQY.js} +1 -1
  35. package/dist/bundle/chunks/{google-vertex-2KSVQZQN.js → google-vertex-A4BKUE4H.js} +1 -1
  36. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  37. package/dist/bundle/chunks/kimi-coding.js +1 -1
  38. package/dist/bundle/chunks/{llama-cpp-classify-Y3DUSEM2.js → llama-cpp-classify-L4URPZ4F.js} +1 -1
  39. package/dist/bundle/chunks/meta.js +1 -1
  40. package/dist/bundle/chunks/mistral-conversations-CK2BS74V.js +5 -0
  41. package/dist/bundle/chunks/openai-codex-responses-XGVNKP4D.js +10 -0
  42. package/dist/bundle/chunks/openai-completions-72XZO4Q3.js +7 -0
  43. package/dist/bundle/chunks/{openai-decisions-JRN6M2KB.js → openai-decisions-P5OCXLLD.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-RGLZ4E3Q.js +4 -0
  45. package/dist/bundle/chunks/{openrouter-images-2XTVCXIC.js → openrouter-images-LSBWMZDK.js} +1 -1
  46. package/dist/bundle/chunks/pi-messages-CL4MEVNS.js +8 -0
  47. package/dist/bundle/chunks/radius.js +1 -1
  48. package/dist/bundle/chunks/{runtime-IB3XQ7E3.js → runtime-F4362CZF.js} +1 -1
  49. package/dist/bundle/chunks/{runtime-LB35PK4J.js → runtime-FJYRBK3O.js} +1 -1
  50. package/dist/bundle/chunks/settings-manager-T6G6KKY3.js +2 -0
  51. package/dist/bundle/chunks/typesafe-system-one-BFYS6AEA.js +2 -0
  52. package/dist/bundle/chunks/virtual-modules-BPZIVXNK.js +2 -0
  53. package/dist/bundle/cli-runtime.js +1 -1
  54. package/dist/bundle/index.js +1 -1
  55. package/dist/bundle/rpc-entry.js +1 -1
  56. package/dist/cli/args.d.ts.map +1 -1
  57. package/dist/cli/args.js +8 -7
  58. package/dist/cli/args.js.map +1 -1
  59. package/dist/cli/config-selector.d.ts.map +1 -1
  60. package/dist/cli/config-selector.js +3 -1
  61. package/dist/cli/config-selector.js.map +1 -1
  62. package/dist/config.d.ts +10 -0
  63. package/dist/config.d.ts.map +1 -1
  64. package/dist/config.js +24 -5
  65. package/dist/config.js.map +1 -1
  66. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  67. package/dist/core/agent-session-runtime.js +4 -3
  68. package/dist/core/agent-session-runtime.js.map +1 -1
  69. package/dist/core/agent-session.d.ts +16 -1
  70. package/dist/core/agent-session.d.ts.map +1 -1
  71. package/dist/core/agent-session.js +104 -30
  72. package/dist/core/agent-session.js.map +1 -1
  73. package/dist/core/ai-schemas.d.ts +166 -0
  74. package/dist/core/ai-schemas.d.ts.map +1 -0
  75. package/dist/core/ai-schemas.js +21 -0
  76. package/dist/core/ai-schemas.js.map +1 -0
  77. package/dist/core/auth-storage.d.ts.map +1 -1
  78. package/dist/core/auth-storage.js +3 -2
  79. package/dist/core/auth-storage.js.map +1 -1
  80. package/dist/core/bash-executor.d.ts.map +1 -1
  81. package/dist/core/bash-executor.js +3 -1
  82. package/dist/core/bash-executor.js.map +1 -1
  83. package/dist/core/bug-report.d.ts +4 -4
  84. package/dist/core/cache-warmer.d.ts.map +1 -1
  85. package/dist/core/cache-warmer.js +2 -0
  86. package/dist/core/cache-warmer.js.map +1 -1
  87. package/dist/core/compaction/branch-summarization.d.ts +4 -2
  88. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  89. package/dist/core/compaction/branch-summarization.js +16 -4
  90. package/dist/core/compaction/branch-summarization.js.map +1 -1
  91. package/dist/core/exec.d.ts +9 -1
  92. package/dist/core/exec.d.ts.map +1 -1
  93. package/dist/core/exec.js +104 -60
  94. package/dist/core/exec.js.map +1 -1
  95. package/dist/core/export-html/template.css +9 -0
  96. package/dist/core/export-html/template.js +165 -45
  97. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  98. package/dist/core/export-html/tool-renderer.js +3 -0
  99. package/dist/core/export-html/tool-renderer.js.map +1 -1
  100. package/dist/core/extensions/ai-extension-view.d.ts +19 -0
  101. package/dist/core/extensions/ai-extension-view.d.ts.map +1 -0
  102. package/dist/core/extensions/ai-extension-view.js +22 -0
  103. package/dist/core/extensions/ai-extension-view.js.map +1 -0
  104. package/dist/core/extensions/index.d.ts +1 -1
  105. package/dist/core/extensions/index.d.ts.map +1 -1
  106. package/dist/core/extensions/index.js.map +1 -1
  107. package/dist/core/extensions/loader.d.ts.map +1 -1
  108. package/dist/core/extensions/loader.js +15 -9
  109. package/dist/core/extensions/loader.js.map +1 -1
  110. package/dist/core/extensions/runner.d.ts +1 -0
  111. package/dist/core/extensions/runner.d.ts.map +1 -1
  112. package/dist/core/extensions/runner.js +9 -1
  113. package/dist/core/extensions/runner.js.map +1 -1
  114. package/dist/core/extensions/types.d.ts +55 -11
  115. package/dist/core/extensions/types.d.ts.map +1 -1
  116. package/dist/core/extensions/types.js.map +1 -1
  117. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  118. package/dist/core/extensions/virtual-modules.js +6 -5
  119. package/dist/core/extensions/virtual-modules.js.map +1 -1
  120. package/dist/core/keybindings.d.ts +2 -2
  121. package/dist/core/keybindings.js +1 -1
  122. package/dist/core/keybindings.js.map +1 -1
  123. package/dist/core/mcp-servers.d.ts +21 -38
  124. package/dist/core/mcp-servers.d.ts.map +1 -1
  125. package/dist/core/mcp-servers.js +58 -134
  126. package/dist/core/mcp-servers.js.map +1 -1
  127. package/dist/core/model-config.d.ts +1717 -1990
  128. package/dist/core/model-config.d.ts.map +1 -1
  129. package/dist/core/model-config.js +2 -3
  130. package/dist/core/model-config.js.map +1 -1
  131. package/dist/core/model-resolver.d.ts.map +1 -1
  132. package/dist/core/model-resolver.js +16 -9
  133. package/dist/core/model-resolver.js.map +1 -1
  134. package/dist/core/model-runtime.d.ts.map +1 -1
  135. package/dist/core/model-runtime.js +4 -4
  136. package/dist/core/model-runtime.js.map +1 -1
  137. package/dist/core/package-manager.d.ts +24 -1
  138. package/dist/core/package-manager.d.ts.map +1 -1
  139. package/dist/core/package-manager.js +215 -52
  140. package/dist/core/package-manager.js.map +1 -1
  141. package/dist/core/pi-manifest.d.ts +1 -0
  142. package/dist/core/pi-manifest.d.ts.map +1 -1
  143. package/dist/core/pi-manifest.js +3 -0
  144. package/dist/core/pi-manifest.js.map +1 -1
  145. package/dist/core/project-trust.js +1 -1
  146. package/dist/core/project-trust.js.map +1 -1
  147. package/dist/core/provider-composer.d.ts +2 -1
  148. package/dist/core/provider-composer.d.ts.map +1 -1
  149. package/dist/core/provider-composer.js +8 -4
  150. package/dist/core/provider-composer.js.map +1 -1
  151. package/dist/core/resource-loader.d.ts +4 -1
  152. package/dist/core/resource-loader.d.ts.map +1 -1
  153. package/dist/core/resource-loader.js +38 -23
  154. package/dist/core/resource-loader.js.map +1 -1
  155. package/dist/core/sdk.d.ts.map +1 -1
  156. package/dist/core/sdk.js +3 -1
  157. package/dist/core/sdk.js.map +1 -1
  158. package/dist/core/session-manager.d.ts +7 -0
  159. package/dist/core/session-manager.d.ts.map +1 -1
  160. package/dist/core/session-manager.js +32 -13
  161. package/dist/core/session-manager.js.map +1 -1
  162. package/dist/core/settings-manager.d.ts +2 -0
  163. package/dist/core/settings-manager.d.ts.map +1 -1
  164. package/dist/core/settings-manager.js +11 -0
  165. package/dist/core/settings-manager.js.map +1 -1
  166. package/dist/core/settings-schema.d.ts +4 -2
  167. package/dist/core/settings-schema.d.ts.map +1 -1
  168. package/dist/core/settings-schema.js +8 -1
  169. package/dist/core/settings-schema.js.map +1 -1
  170. package/dist/core/skills.d.ts.map +1 -1
  171. package/dist/core/skills.js +6 -15
  172. package/dist/core/skills.js.map +1 -1
  173. package/dist/core/slash-commands.js +2 -2
  174. package/dist/core/slash-commands.js.map +1 -1
  175. package/dist/core/source-info.d.ts +9 -0
  176. package/dist/core/source-info.d.ts.map +1 -1
  177. package/dist/core/source-info.js +14 -0
  178. package/dist/core/source-info.js.map +1 -1
  179. package/dist/core/system-prompt.d.ts.map +1 -1
  180. package/dist/core/system-prompt.js +5 -6
  181. package/dist/core/system-prompt.js.map +1 -1
  182. package/dist/core/tools/bash.d.ts +2 -2
  183. package/dist/core/tools/bash.d.ts.map +1 -1
  184. package/dist/core/tools/bash.js.map +1 -1
  185. package/dist/core/tools/edit.d.ts +3 -3
  186. package/dist/core/tools/edit.d.ts.map +1 -1
  187. package/dist/core/tools/edit.js +2 -4
  188. package/dist/core/tools/edit.js.map +1 -1
  189. package/dist/core/tools/find.d.ts +2 -2
  190. package/dist/core/tools/find.d.ts.map +1 -1
  191. package/dist/core/tools/find.js +41 -25
  192. package/dist/core/tools/find.js.map +1 -1
  193. package/dist/core/tools/grep.d.ts +4 -5
  194. package/dist/core/tools/grep.d.ts.map +1 -1
  195. package/dist/core/tools/grep.js +73 -70
  196. package/dist/core/tools/grep.js.map +1 -1
  197. package/dist/core/tools/ls.d.ts +2 -2
  198. package/dist/core/tools/ls.d.ts.map +1 -1
  199. package/dist/core/tools/ls.js +2 -1
  200. package/dist/core/tools/ls.js.map +1 -1
  201. package/dist/core/tools/read.d.ts +2 -2
  202. package/dist/core/tools/read.d.ts.map +1 -1
  203. package/dist/core/tools/read.js.map +1 -1
  204. package/dist/core/tools/render-utils.d.ts.map +1 -1
  205. package/dist/core/tools/render-utils.js +2 -7
  206. package/dist/core/tools/render-utils.js.map +1 -1
  207. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  208. package/dist/core/tools/renderers/write.js +19 -19
  209. package/dist/core/tools/renderers/write.js.map +1 -1
  210. package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
  211. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  212. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  213. package/dist/core/tools/truncate.d.ts +0 -14
  214. package/dist/core/tools/truncate.d.ts.map +1 -1
  215. package/dist/core/tools/truncate.js +0 -29
  216. package/dist/core/tools/truncate.js.map +1 -1
  217. package/dist/core/tools/write.d.ts +2 -2
  218. package/dist/core/tools/write.d.ts.map +1 -1
  219. package/dist/core/tools/write.js.map +1 -1
  220. package/dist/core/trust-manager.d.ts.map +1 -1
  221. package/dist/core/trust-manager.js +15 -8
  222. package/dist/core/trust-manager.js.map +1 -1
  223. package/dist/core/usage-totals.d.ts.map +1 -1
  224. package/dist/core/usage-totals.js +2 -0
  225. package/dist/core/usage-totals.js.map +1 -1
  226. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  227. package/dist/extensions/codemode/renderer.js +6 -2
  228. package/dist/extensions/codemode/renderer.js.map +1 -1
  229. package/dist/extensions/codemode/tool.d.ts +2 -1
  230. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  231. package/dist/extensions/codemode/tool.js +33 -8
  232. package/dist/extensions/codemode/tool.js.map +1 -1
  233. package/dist/extensions/llama/client.d.ts +2 -0
  234. package/dist/extensions/llama/client.d.ts.map +1 -1
  235. package/dist/extensions/llama/client.js +23 -2
  236. package/dist/extensions/llama/client.js.map +1 -1
  237. package/dist/extensions/llama/ui.d.ts.map +1 -1
  238. package/dist/extensions/llama/ui.js +16 -4
  239. package/dist/extensions/llama/ui.js.map +1 -1
  240. package/dist/extensions/mcp/cli.d.ts +2 -0
  241. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  242. package/dist/extensions/mcp/cli.js +72 -15
  243. package/dist/extensions/mcp/cli.js.map +1 -1
  244. package/dist/extensions/mcp/config.d.ts.map +1 -1
  245. package/dist/extensions/mcp/config.js +4 -7
  246. package/dist/extensions/mcp/config.js.map +1 -1
  247. package/dist/extensions/mcp/index.d.ts.map +1 -1
  248. package/dist/extensions/mcp/index.js +2 -2
  249. package/dist/extensions/mcp/index.js.map +1 -1
  250. package/dist/extensions/mcp/oauth.d.ts +13 -50
  251. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  252. package/dist/extensions/mcp/oauth.js +53 -319
  253. package/dist/extensions/mcp/oauth.js.map +1 -1
  254. package/dist/extensions/mcp/resources.d.ts +1 -1
  255. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  256. package/dist/extensions/mcp/resources.js +4 -3
  257. package/dist/extensions/mcp/resources.js.map +1 -1
  258. package/dist/extensions/mcp/runtime.d.ts +4 -3
  259. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  260. package/dist/extensions/mcp/runtime.js +4 -3
  261. package/dist/extensions/mcp/runtime.js.map +1 -1
  262. package/dist/extensions/mcp/tools.d.ts +2 -23
  263. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  264. package/dist/extensions/mcp/tools.js +6 -58
  265. package/dist/extensions/mcp/tools.js.map +1 -1
  266. package/dist/extensions/mcp/ui.d.ts +1 -0
  267. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  268. package/dist/extensions/mcp/ui.js +33 -24
  269. package/dist/extensions/mcp/ui.js.map +1 -1
  270. package/dist/extensions/tool-search/tool.d.ts +21 -6
  271. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  272. package/dist/extensions/tool-search/tool.js +104 -36
  273. package/dist/extensions/tool-search/tool.js.map +1 -1
  274. package/dist/index.d.ts +2 -2
  275. package/dist/index.d.ts.map +1 -1
  276. package/dist/index.js.map +1 -1
  277. package/dist/main.d.ts.map +1 -1
  278. package/dist/main.js +16 -8
  279. package/dist/main.js.map +1 -1
  280. package/dist/modes/interactive/components/assistant-message.d.ts +4 -1
  281. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  282. package/dist/modes/interactive/components/assistant-message.js +44 -20
  283. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  284. package/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
  285. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  286. package/dist/modes/interactive/components/branch-summary-message.js +12 -4
  287. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  288. package/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
  289. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  290. package/dist/modes/interactive/components/compaction-summary-message.js +12 -4
  291. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  292. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/config-selector.js +4 -18
  294. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  295. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  296. package/dist/modes/interactive/components/custom-editor.js +7 -0
  297. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  298. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  299. package/dist/modes/interactive/components/custom-entry.js +2 -1
  300. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  301. package/dist/modes/interactive/components/custom-message.d.ts +5 -2
  302. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  303. package/dist/modes/interactive/components/custom-message.js +12 -4
  304. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  305. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  306. package/dist/modes/interactive/components/diff.js +11 -5
  307. package/dist/modes/interactive/components/diff.js.map +1 -1
  308. package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
  309. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  310. package/dist/modes/interactive/components/extension-editor.js +4 -0
  311. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  312. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  313. package/dist/modes/interactive/components/extension-selector.js +9 -1
  314. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  315. package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
  316. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  317. package/dist/modes/interactive/components/login-dialog.js +104 -10
  318. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  319. package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
  320. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
  321. package/dist/modes/interactive/components/markdown-transform.js +3 -2
  322. package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
  323. package/dist/modes/interactive/components/mermaid.d.ts +2 -1
  324. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  325. package/dist/modes/interactive/components/mermaid.js +25 -20
  326. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  327. package/dist/modes/interactive/components/model-selector.d.ts +1 -0
  328. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  329. package/dist/modes/interactive/components/model-selector.js +17 -6
  330. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  331. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
  332. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  333. package/dist/modes/interactive/components/oauth-selector.js +13 -4
  334. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  335. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
  336. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  337. package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
  338. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  339. package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
  340. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  341. package/dist/modes/interactive/components/session-selector-search.js +86 -22
  342. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  343. package/dist/modes/interactive/components/session-selector.d.ts +2 -1
  344. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  345. package/dist/modes/interactive/components/session-selector.js +20 -27
  346. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  347. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  348. package/dist/modes/interactive/components/settings-submenu.js +2 -0
  349. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  350. package/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
  351. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  352. package/dist/modes/interactive/components/skill-invocation-message.js +12 -4
  353. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  354. package/dist/modes/interactive/components/tool-execution.d.ts +6 -0
  355. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  356. package/dist/modes/interactive/components/tool-execution.js +14 -2
  357. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  358. package/dist/modes/interactive/components/tree-selector.d.ts +2 -0
  359. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  360. package/dist/modes/interactive/components/tree-selector.js +24 -16
  361. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  362. package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
  363. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  364. package/dist/modes/interactive/components/user-message-selector.js +9 -1
  365. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  366. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  367. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  368. package/dist/modes/interactive/components/user-message.js +6 -2
  369. package/dist/modes/interactive/components/user-message.js.map +1 -1
  370. package/dist/modes/interactive/external-editor.d.ts +1 -0
  371. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  372. package/dist/modes/interactive/external-editor.js +16 -4
  373. package/dist/modes/interactive/external-editor.js.map +1 -1
  374. package/dist/modes/interactive/interactive-mode.d.ts +7 -0
  375. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  376. package/dist/modes/interactive/interactive-mode.js +179 -53
  377. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  378. package/dist/modes/interactive/model-search.d.ts +10 -0
  379. package/dist/modes/interactive/model-search.d.ts.map +1 -1
  380. package/dist/modes/interactive/model-search.js +21 -0
  381. package/dist/modes/interactive/model-search.js.map +1 -1
  382. package/dist/modes/interactive/theme/theme.d.ts +10 -0
  383. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  384. package/dist/modes/interactive/theme/theme.js +35 -23
  385. package/dist/modes/interactive/theme/theme.js.map +1 -1
  386. package/dist/modes/print-mode.d.ts.map +1 -1
  387. package/dist/modes/print-mode.js +19 -10
  388. package/dist/modes/print-mode.js.map +1 -1
  389. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  390. package/dist/modes/rpc/rpc-mode.js +53 -23
  391. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  392. package/dist/package-manager-cli.d.ts.map +1 -1
  393. package/dist/package-manager-cli.js +78 -9
  394. package/dist/package-manager-cli.js.map +1 -1
  395. package/dist/utils/ansi.d.ts.map +1 -1
  396. package/dist/utils/ansi.js +5 -2
  397. package/dist/utils/ansi.js.map +1 -1
  398. package/dist/utils/changelog.d.ts +2 -2
  399. package/dist/utils/changelog.d.ts.map +1 -1
  400. package/dist/utils/changelog.js +15 -2
  401. package/dist/utils/changelog.js.map +1 -1
  402. package/dist/utils/clipboard-command.d.ts.map +1 -1
  403. package/dist/utils/clipboard-command.js +4 -0
  404. package/dist/utils/clipboard-command.js.map +1 -1
  405. package/dist/utils/git.d.ts +1 -1
  406. package/dist/utils/git.d.ts.map +1 -1
  407. package/dist/utils/git.js.map +1 -1
  408. package/dist/utils/image-resize-core.d.ts.map +1 -1
  409. package/dist/utils/image-resize-core.js +5 -3
  410. package/dist/utils/image-resize-core.js.map +1 -1
  411. package/dist/utils/open-browser.d.ts.map +1 -1
  412. package/dist/utils/open-browser.js +4 -1
  413. package/dist/utils/open-browser.js.map +1 -1
  414. package/dist/utils/paths.d.ts +17 -0
  415. package/dist/utils/paths.d.ts.map +1 -1
  416. package/dist/utils/paths.js +42 -1
  417. package/dist/utils/paths.js.map +1 -1
  418. package/dist/utils/shell.d.ts.map +1 -1
  419. package/dist/utils/shell.js +14 -0
  420. package/dist/utils/shell.js.map +1 -1
  421. package/dist/utils/syntax-highlight.d.ts +5 -0
  422. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  423. package/dist/utils/syntax-highlight.js +7 -0
  424. package/dist/utils/syntax-highlight.js.map +1 -1
  425. package/dist/utils/tools-manager.d.ts.map +1 -1
  426. package/dist/utils/tools-manager.js +30 -35
  427. package/dist/utils/tools-manager.js.map +1 -1
  428. package/docs/cli.md +22 -10
  429. package/docs/custom-provider.md +2 -0
  430. package/docs/environment-variables.md +2 -0
  431. package/docs/extensions.md +3201 -233
  432. package/docs/keybindings.md +2 -2
  433. package/docs/llama-cpp.md +23 -15
  434. package/docs/message-types.md +1 -1
  435. package/docs/models-configuration.md +17 -4
  436. package/docs/models.md +9 -4
  437. package/docs/packages.md +24 -0
  438. package/docs/providers.md +1 -1
  439. package/docs/rpc.md +3 -1
  440. package/docs/sessions.md +11 -3
  441. package/docs/settings.md +5 -4
  442. package/docs/slash-commands.md +3 -2
  443. package/docs/terminal-setup.md +3 -1
  444. package/docs/tmux.md +6 -0
  445. package/docs/tui.md +2 -0
  446. package/docs/windows.md +27 -0
  447. package/eval/drahtbank/isolated-tools.ts +0 -1
  448. package/examples/extensions/antigravity-image-gen.ts +1 -1
  449. package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  450. package/examples/extensions/debug-provider.ts +2 -2
  451. package/examples/extensions/gondolin/package.json +1 -1
  452. package/examples/extensions/plan-mode/index.ts +23 -13
  453. package/examples/extensions/plan-mode/utils.ts +42 -16
  454. package/examples/extensions/preset.ts +2 -0
  455. package/examples/extensions/reload-runtime.ts +17 -5
  456. package/examples/extensions/sandbox/package-lock.json +15 -41
  457. package/examples/extensions/sandbox/package.json +1 -1
  458. package/examples/extensions/subagent/index.ts +388 -171
  459. package/examples/extensions/todo.ts +7 -0
  460. package/examples/extensions/tools.ts +2 -0
  461. package/examples/tsconfig.json +188 -0
  462. package/package.json +15 -16
  463. package/schemas/models.schema.json +85 -39
  464. package/schemas/settings.schema.json +17 -0
  465. package/dist/bundle/chunks/anthropic-messages-CZYDBUW7.js +0 -6
  466. package/dist/bundle/chunks/azure-openai-responses-UKM4K3L6.js +0 -2
  467. package/dist/bundle/chunks/chunk-2TZWVGCR.js +0 -2
  468. package/dist/bundle/chunks/chunk-76YNMQ57.js +0 -2
  469. package/dist/bundle/chunks/chunk-AS6DCLAM.js +0 -1428
  470. package/dist/bundle/chunks/chunk-BL72B6LV.js +0 -82
  471. package/dist/bundle/chunks/chunk-C2XCXA6V.js +0 -2
  472. package/dist/bundle/chunks/chunk-CLKG6K6Z.js +0 -7
  473. package/dist/bundle/chunks/chunk-FOYIPAAD.js +0 -6
  474. package/dist/bundle/chunks/chunk-FXCTQRNN.js +0 -2
  475. package/dist/bundle/chunks/chunk-H5BLLINF.js +0 -11
  476. package/dist/bundle/chunks/chunk-IT4RIOZD.js +0 -2
  477. package/dist/bundle/chunks/chunk-N3FZGIII.js +0 -16
  478. package/dist/bundle/chunks/chunk-OCUU7HYF.js +0 -2
  479. package/dist/bundle/chunks/chunk-QMN7OD6G.js +0 -2
  480. package/dist/bundle/chunks/chunk-UCJ7FLSO.js +0 -166
  481. package/dist/bundle/chunks/chunk-WFHH5SX6.js +0 -4
  482. package/dist/bundle/chunks/chunk-WYWBXNDO.js +0 -6
  483. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +0 -2
  484. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-V37VPUK4.js +0 -2
  485. package/dist/bundle/chunks/mistral-conversations-R2NJADHS.js +0 -5
  486. package/dist/bundle/chunks/openai-codex-responses-KJZDJELP.js +0 -10
  487. package/dist/bundle/chunks/openai-completions-RTWADJBP.js +0 -7
  488. package/dist/bundle/chunks/openai-responses-B7ASLN2Z.js +0 -4
  489. package/dist/bundle/chunks/pi-messages-7TX4RC24.js +0 -8
  490. package/dist/bundle/chunks/settings-manager-YNY5F4RU.js +0 -2
  491. package/dist/bundle/chunks/typesafe-system-one-7BNMQFXE.js +0 -2
  492. package/dist/bundle/chunks/virtual-modules-OFCQ5AEG.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../../src/extensions/mcp/oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9E,OAAO,EAEN,YAAY,EACZ,kCAAkC,EAClC,gBAAgB,EAKhB,mBAAmB,EAInB,oBAAoB,EACpB,WAAW,GACX,MAAM,kBAAkB,CAAC;AAC1B,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAA2B,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC7F,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAEzD,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,2FAA2F;AAC3F,MAAM,qBAAqB,GAAG,UAAU,aAAa,GAAG,aAAa,EAAE,CAAC;AACxE,6EAA6E;AAC7E,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B;;;GAGG;AACH,MAAM,wBAAwB,GAAG,MAAM,CAAC;AACxC,yGAAyG;AACzG,MAAM,qBAAqB,GAAG,MAAM,CAAC;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EAAE,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAChG;SACD,CAAC;QACF,sFAAsF;QACtF,MAAM,WAAW,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM,YAAY,CAAC,QAAQ,EAAE,EAAE,GAAG,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC,KAAK,YAAY;YAAE,OAAO;QACtF,IAAI,CAAC,gBAAgB;YAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;QAE1F,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;QACrC,4EAA4E;QAC5E,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,YAAY,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,WAAW,CAAC,CAAC;QAC3G,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC,gBAAgB,CAAC,CAAC;QACtD,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,MAAM,4BAA4B,CACvD,QAAQ,EACR,KAAK,EACL,wBAAwB,EACxB,OAAO,CAAC,MAAM,EACd,MAAM,CACN,CAAC;QACF,MAAM,YAAY,CAAC,QAAQ,EAAE,EAAE,GAAG,IAAI,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC;IACzE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,4FAA4F;QAC5F,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,uBAAuB,EAAE,CAAC;QACzD,MAAM,KAAK,CAAC;IACb,CAAC;YAAS,CAAC;QACV,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;IACxB,CAAC;AACF,CAAC","sourcesContent":["/**\n * OAuth sign-in for remote MCP servers.\n *\n * Connections never start a browser flow on their own. They send the stored access token and, after\n * a 401, try the stored refresh token. When that is not possible they fail with\n * `McpOAuthAuthorizationRequiredError`, and the user signs in through `/mcp`, which runs\n * the authorization code flow (PKCE, a Client ID Metadata Document or dynamic client registration)\n * against a loopback callback.\n *\n * Credentials live in `<agent-dir>/mcp-auth.json`, keyed by server name and URL.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"@draht/ai/utils/oauth-page\";\nimport type { AuthProvider, McpFetch } from \"@draht/mcp\";\nimport {\n\ttype AuthorizationServerMetadata,\n\tauthorizeMcp,\n\tMcpOAuthAuthorizationRequiredError,\n\tMcpOAuthProvider,\n\ttype McpOAuthState,\n\ttype McpOAuthStateStore,\n\ttype OAuthCallback,\n\ttype OAuthCallbackPage,\n\tOAuthCallbackServer,\n\ttype OAuthChallenge,\n\ttype OAuthClientInformationMixed,\n\ttype OAuthClientMetadataDocument,\n\tparseWwwAuthenticate,\n\tstepUpScope,\n} from \"@draht/mcp/oauth\";\nimport lockfile from \"proper-lockfile\";\nimport { APP_NAME, getAgentDir } from \"../../config.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"../../core/auth-storage.ts\";\nimport { mcpNamespace } from \"../../core/mcp-servers.ts\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PATH = \"/callback\";\n/** Redirect URI for refreshes when none is stored. Refreshing never redirects the user. */\nconst FALLBACK_REDIRECT_URL = `http://${CALLBACK_HOST}${CALLBACK_PATH}`;\n/** Access tokens this close to expiry are refreshed before they are sent. */\nconst REFRESH_SKEW_MS = 30_000;\n/**\n * Bounds each request to the authorization server, so an unresponsive one cannot hold the refresh lock,\n * delay shutdown, or keep a sign-in waiting for long.\n */\nconst OAUTH_REQUEST_TIMEOUT_MS = 15_000;\n/** A refresh lock that its holder stopped renewing (the process was killed) is taken over after this. */\nconst REFRESH_LOCK_STALE_MS = 20_000;\n/** How long to wait for another process's refresh: longer than a stale lock lives. */\nconst REFRESH_LOCK_WAIT_MS = 25_000;\nconst REFRESH_LOCK_RETRY_MS = 100;\n\nexport interface McpOAuthSettings {\n\tclientId?: string;\n\t/** Already resolved. */\n\tclientSecret?: string;\n\tcallbackPort?: number;\n\t/** Loopback redirect URI; see `McpOAuthConfig.callbackUrl`. */\n\tcallbackUrl?: string;\n\t/** Scopes to request, separated by spaces. */\n\tscope?: string;\n\t/** `client_name` for dynamic client registration. Default: `APP_NAME`. */\n\tclientName?: string;\n\t/** See `McpOAuthConfig.clientRegistration`. */\n\tclientRegistration?: \"dcr\" | \"cimd\";\n\t/** Validated by the config boundary, with a trailing slash. Required for `cimd`. */\n\tclientMetadataBaseUrl?: string;\n\t/** See `McpOAuthConfig.authServerMetadataUrl`. */\n\tauthServerMetadataUrl?: URL;\n}\n\n/** Where the loopback callback server listens and the redirect URI it serves. */\ninterface CallbackSettings {\n\t/** Address to listen on. */\n\thost: string;\n\t/** Host name in the redirect URI. */\n\tredirectHost: string;\n\tport: number | undefined;\n\tpath: string;\n\t/** The exact redirect URI, when the port is fixed. */\n\tfixedRedirectUrl: string | undefined;\n}\n\nfunction callbackSettings(settings: McpOAuthSettings): CallbackSettings {\n\tconst url = new URL(settings.callbackUrl ?? `http://${CALLBACK_HOST}${CALLBACK_PATH}`);\n\tconst address = url.hostname.replace(/^\\[|\\]$/g, \"\");\n\tconst port = url.port ? Number(url.port) : settings.callbackPort;\n\tlet fixedRedirectUrl: string | undefined;\n\t// A configured URI with a port is sent exactly as written, since servers compare it as a string.\n\tif (url.port) fixedRedirectUrl = settings.callbackUrl;\n\telse if (port !== undefined) {\n\t\turl.port = String(port);\n\t\tfixedRedirectUrl = url.href;\n\t}\n\treturn {\n\t\t// `localhost` is served on 127.0.0.1; browsers fall back to it when ::1 refuses.\n\t\thost: address === \"localhost\" ? CALLBACK_HOST : address,\n\t\tredirectHost: address,\n\t\tport,\n\t\tpath: url.pathname,\n\t\tfixedRedirectUrl,\n\t};\n}\n\n/** Scopes of both lists, each once. */\nfunction mergeScopes(...scopes: (string | undefined)[]): string | undefined {\n\tconst merged = [...new Set(scopes.flatMap((scope) => scope?.split(/\\s+/).filter(Boolean) ?? []))];\n\treturn merged.length > 0 ? merged.join(\" \") : undefined;\n}\n\ntype StoredStates = Record<string, McpOAuthState>;\n\nfunction parseStates(content: string | undefined): StoredStates {\n\tif (!content?.trim()) return {};\n\tconst parsed: unknown = JSON.parse(content);\n\treturn typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as StoredStates) : {};\n}\n\nfunction serializeStates(states: StoredStates): string {\n\treturn `${JSON.stringify(states, null, 2)}\\n`;\n}\n\n/**\n * Keys of a server's state: by name and URL, so servers sharing a URL keep separate accounts, and the\n * legacy key by URL alone, written by older versions.\n */\nfunction storeKeys(name: string, serverUrl: string): { key: string; legacyKey: string } {\n\tconst legacyKey = String(new URL(serverUrl));\n\treturn { key: `${mcpNamespace(name)}|${legacyKey}`, legacyKey };\n}\n\nexport interface McpOAuthServerStore extends McpOAuthStateStore {\n\t/** Run `fn` while no other process refreshes the server's tokens. */\n\twithRefreshLock<T>(fn: () => Promise<T>): Promise<T>;\n}\n\n/** Per-server OAuth state (client registration, tokens, pending PKCE verifier) in `mcp-auth.json`. */\nexport class McpOAuthCredentialStore {\n\tprivate readonly backend: AuthStorageBackend;\n\t/** Directory for the refresh lock files. Without one, refreshes are only serialized in this process. */\n\tprivate readonly lockDir: string | undefined;\n\n\tconstructor(backend?: AuthStorageBackend, lockDir?: string) {\n\t\tthis.backend = backend ?? new FileAuthStorageBackend(join(getAgentDir(), \"mcp-auth.json\"));\n\t\tthis.lockDir = backend ? lockDir : getAgentDir();\n\t}\n\n\tforServer(name: string, serverUrl: string): McpOAuthServerStore {\n\t\tconst { key, legacyKey } = storeKeys(name, serverUrl);\n\t\treturn {\n\t\t\t// The first server to load legacy state takes it over; others with the same URL sign in again.\n\t\t\tload: () =>\n\t\t\t\tthis.backend.withLock((current) => {\n\t\t\t\t\tconst states = parseStates(current);\n\t\t\t\t\tif (states[key] || !states[legacyKey]) return { result: states[key] };\n\t\t\t\t\tstates[key] = states[legacyKey];\n\t\t\t\t\tdelete states[legacyKey];\n\t\t\t\t\treturn { result: states[key], next: serializeStates(states) };\n\t\t\t\t}),\n\t\t\tsave: (state) =>\n\t\t\t\tthis.write((states) => {\n\t\t\t\t\tstates[key] = state;\n\t\t\t\t}),\n\t\t\twithRefreshLock: (fn) => this.withRefreshLock(key, fn),\n\t\t};\n\t}\n\n\t/**\n\t * A lock file per server. When the process exits, proper-lockfile removes the locks it holds; when\n\t * it is killed, the lock goes stale because it is no longer renewed, and the next process takes it over.\n\t */\n\tprivate async withRefreshLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n\t\tif (!this.lockDir) return fn();\n\t\tmkdirSync(this.lockDir, { recursive: true, mode: 0o700 });\n\t\tconst hash = createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 16);\n\t\tconst release = await lockfile.lock(join(this.lockDir, `mcp-auth-refresh-${hash}`), {\n\t\t\trealpath: false,\n\t\t\tstale: REFRESH_LOCK_STALE_MS,\n\t\t\tretries: {\n\t\t\t\tretries: REFRESH_LOCK_WAIT_MS / REFRESH_LOCK_RETRY_MS,\n\t\t\t\tfactor: 1,\n\t\t\t\tminTimeout: REFRESH_LOCK_RETRY_MS,\n\t\t\t\tmaxTimeout: REFRESH_LOCK_RETRY_MS,\n\t\t\t},\n\t\t\t// The default throws from a timer. A lost lock at worst lets two refreshes overlap.\n\t\t\tonCompromised: () => {},\n\t\t});\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tawait release().catch(() => undefined);\n\t\t}\n\t}\n\n\t/** The stored tokens of a server, for noticing sign-ins done by another process. Does not take over legacy state. */\n\ttokens(name: string, serverUrl: string): McpOAuthState[\"tokens\"] {\n\t\tconst { key, legacyKey } = storeKeys(name, serverUrl);\n\t\tconst states = this.backend.withLock((current) => ({ result: parseStates(current) }));\n\t\treturn (states[key] ?? states[legacyKey])?.tokens;\n\t}\n\n\t/** Returns whether credentials were stored for the server. Removes legacy state the server would take over. */\n\tremove(name: string, serverUrl: string): boolean {\n\t\tconst { key, legacyKey } = storeKeys(name, serverUrl);\n\t\treturn this.backend.withLock((current) => {\n\t\t\tconst states = parseStates(current);\n\t\t\tconst stored = key in states ? key : legacyKey in states ? legacyKey : undefined;\n\t\t\tif (!stored) return { result: false };\n\t\t\tdelete states[stored];\n\t\t\treturn { result: true, next: serializeStates(states) };\n\t\t});\n\t}\n\n\tprivate write(update: (states: StoredStates) => void): void {\n\t\tthis.backend.withLock((current) => {\n\t\t\tconst states = parseStates(current);\n\t\t\tupdate(states);\n\t\t\treturn { result: undefined, next: serializeStates(states) };\n\t\t});\n\t}\n}\n\n/** `fetch` with `OAUTH_REQUEST_TIMEOUT_MS` per request, on top of the request's own signal. */\nfunction timedFetch(fetch: McpFetch = globalThis.fetch): McpFetch {\n\treturn (input, init) => {\n\t\tconst timeout = AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);\n\t\treturn fetch(input, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout });\n\t};\n}\n\nfunction registeredRedirectUrls(client: OAuthClientInformationMixed | undefined): string[] {\n\treturn client && \"redirect_uris\" in client ? client.redirect_uris : [];\n}\n\n/** 12 characters identifying an MCP server URL in callback paths, computed like Codex does. */\nfunction callbackId(serverUrl: string): string {\n\tconst url = new URL(serverUrl);\n\turl.hash = \"\";\n\treturn createHash(\"sha256\").update(url.href).digest().subarray(0, 9).toString(\"base64url\");\n}\n\n/**\n * An operator-hosted Client ID Metadata Document, for `clientRegistration: \"cimd\"`.\n * The configuration ensures the default callback path. Without the `iss` parameter in authorization\n * responses (RFC 9207), the redirect URI and the document are specific to the MCP server, so a response\n * cannot be mixed up with one from another authorization server (RFC 9700 section 4.4.2.2).\n */\nfunction clientMetadataDocument(\n\tbaseUrl: string,\n\tserverUrl: string,\n\tredirectUrl: string,\n\tmetadata: AuthorizationServerMetadata | undefined,\n): OAuthClientMetadataDocument {\n\tif (\n\t\t!metadata?.client_id_metadata_document_supported ||\n\t\t!metadata.token_endpoint_auth_methods_supported?.includes(\"none\")\n\t) {\n\t\tthrow new Error(\n\t\t\t'The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration \"cimd\"',\n\t\t);\n\t}\n\tif (metadata.authorization_response_iss_parameter_supported) {\n\t\treturn { url: new URL(\"client.json\", baseUrl).href, redirectUrl };\n\t}\n\tconst id = callbackId(serverUrl);\n\tconst redirect = new URL(redirectUrl);\n\tredirect.pathname = `${CALLBACK_PATH}/${id}`;\n\treturn { url: new URL(`${id}/client.json`, baseUrl).href, redirectUrl: redirect.href };\n}\n\nfunction metadataBaseUrl(settings: McpOAuthSettings): string | undefined {\n\tif (settings.clientRegistration !== \"cimd\") return undefined;\n\tif (!settings.clientMetadataBaseUrl) throw new Error('oauth.clientMetadataBaseUrl is required for \"cimd\"');\n\treturn settings.clientMetadataBaseUrl;\n}\n\n/** A cached token belongs to this registration mode and metadata base, or it needs a new sign-in. */\nfunction matchesClient(state: McpOAuthState | undefined, serverUrl: string, baseUrl: string | undefined): boolean {\n\tif (!state || state.serverUrl !== new URL(serverUrl).href) return false;\n\tif (!baseUrl) return state.clientMetadataUrl === undefined;\n\treturn (\n\t\tstate.clientMetadataUrl === new URL(\"client.json\", baseUrl).href ||\n\t\tstate.clientMetadataUrl === new URL(`${callbackId(serverUrl)}/client.json`, baseUrl).href\n\t);\n}\n\nfunction createProvider(\n\tserverUrl: string,\n\tstore: McpOAuthStateStore,\n\tsettings: McpOAuthSettings,\n\tredirectUrl: string,\n\tonRedirect: (url: URL) => void,\n): McpOAuthProvider {\n\tconst baseUrl = metadataBaseUrl(settings);\n\treturn new McpOAuthProvider({\n\t\tserverUrl,\n\t\tredirectUrl,\n\t\tclientMetadata: { client_name: settings.clientName ?? APP_NAME },\n\t\tclientMetadataDocument: baseUrl\n\t\t\t? (metadata) => clientMetadataDocument(baseUrl, serverUrl, redirectUrl, metadata)\n\t\t\t: undefined,\n\t\tclientId: settings.clientId,\n\t\tclientSecret: settings.clientSecret,\n\t\tstore,\n\t\tonRedirect,\n\t});\n}\n\nexport interface McpAuthProvider extends AuthProvider {\n\t/** Resolves when no refresh is running, so shutdown does not drop rotated tokens before they are saved. */\n\tsettled(): Promise<void>;\n}\n\n/**\n * Auth provider for MCP connections: sends the stored access token and refreshes it when it is about\n * to expire or after a 401. Throws `McpOAuthAuthorizationRequiredError` when the user has to sign in,\n * including when the server asks for more scope (`insufficient_scope`). `onChallenge` receives the\n * server's `WWW-Authenticate` challenge so sign-in can use its resource metadata URL and scope.\n * `settings` is only called when a refresh is needed, so a secret that fails to resolve fails the\n * refresh instead of the whole connection setup.\n *\n * Many servers rotate refresh tokens, so two refreshes with the same refresh token lose the grant.\n * Requests in this process share one refresh, and other processes are kept out by the store's\n * refresh lock, held from reading the tokens to saving new ones. Tokens that changed meanwhile\n * (another process refreshed them, or the user signed in) are used without refreshing.\n */\nexport function createMcpAuthProvider(options: {\n\tserverUrl: string;\n\tstore: McpOAuthServerStore;\n\t/** Validated CIMD base, or undefined for DCR. Separate from settings so token reads do not resolve secrets. */\n\tclientMetadataBaseUrl: string | undefined;\n\tsettings: () => McpOAuthSettings;\n\tonChallenge: (challenge: OAuthChallenge) => void;\n}): McpAuthProvider {\n\tconst { serverUrl, store } = options;\n\tlet refreshing: Promise<void> | undefined;\n\n\t/** Replace `staleToken`, the access token that expired or was rejected. */\n\tconst refresh = (staleToken: string | undefined, fetch: McpFetch = globalThis.fetch, challenge?: OAuthChallenge) => {\n\t\trefreshing ??= store\n\t\t\t.withRefreshLock(async () => {\n\t\t\t\tconst state = await store.load();\n\t\t\t\tif (!matchesClient(state, serverUrl, options.clientMetadataBaseUrl)) {\n\t\t\t\t\tthrow new McpOAuthAuthorizationRequiredError();\n\t\t\t\t}\n\t\t\t\tif (state?.tokens?.access_token !== staleToken) return;\n\t\t\t\tif (!state?.tokens?.refresh_token) throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\tconst settings = options.settings();\n\t\t\t\tconst redirectUrl =\n\t\t\t\t\tcallbackSettings(settings).fixedRedirectUrl ??\n\t\t\t\t\tregisteredRedirectUrls(state.clientInformation)[0] ??\n\t\t\t\t\tFALLBACK_REDIRECT_URL;\n\t\t\t\tconst provider = createProvider(serverUrl, store, settings, redirectUrl, () => {});\n\t\t\t\t// Refreshes the tokens, or reports that a new sign-in is needed. Not cancellable: a refresh the\n\t\t\t\t// server answered may have rotated the refresh token, so its answer must be saved.\n\t\t\t\tconst result = await authorizeMcp(provider, {\n\t\t\t\t\tserverUrl,\n\t\t\t\t\tresourceMetadataUrl: challenge?.resourceMetadataUrl,\n\t\t\t\t\tauthorizationServerMetadataUrl: settings.authServerMetadataUrl,\n\t\t\t\t\tscope: challenge?.scope,\n\t\t\t\t\tfetch: timedFetch(fetch),\n\t\t\t\t});\n\t\t\t\tif (result === \"REDIRECT\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\trefreshing = undefined;\n\t\t\t});\n\t\treturn refreshing;\n\t};\n\n\treturn {\n\t\ttoken: async () => {\n\t\t\tawait refreshing?.catch(() => undefined);\n\t\t\tconst state = await store.load();\n\t\t\tif (!matchesClient(state, serverUrl, options.clientMetadataBaseUrl)) return undefined;\n\t\t\tconst token = state?.tokens?.access_token;\n\t\t\tconst expired = state?.tokensExpireAt !== undefined && state.tokensExpireAt - REFRESH_SKEW_MS <= Date.now();\n\t\t\tif (!expired || !state?.tokens?.refresh_token) return token;\n\t\t\t// Failures fall through: the request goes out with the old token and a 401 decides what happens.\n\t\t\tawait refresh(token).catch(() => undefined);\n\t\t\tconst refreshed = await store.load();\n\t\t\treturn matchesClient(refreshed, serverUrl, options.clientMetadataBaseUrl)\n\t\t\t\t? refreshed?.tokens?.access_token\n\t\t\t\t: undefined;\n\t\t},\n\t\tonUnauthorized: async (context) => {\n\t\t\tconst challenge = parseWwwAuthenticate(context.response.headers.get(\"www-authenticate\"));\n\t\t\toptions.onChallenge(challenge);\n\t\t\t// A refresh keeps the granted scope, so more scope needs a new sign-in.\n\t\t\tif (challenge.error === \"insufficient_scope\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\tawait refresh(context.token, context.fetch, challenge);\n\t\t},\n\t\tsettled: async () => {\n\t\t\tawait refreshing?.catch(() => undefined);\n\t\t},\n\t};\n}\n\nexport interface McpSignInPrompt {\n\t/** Show the authorization URL to the user and open it in a browser. */\n\tshowAuthorizationUrl(url: URL): void;\n\t/**\n\t * Ask for the redirect URL from the browser address bar, for when the browser cannot reach the\n\t * loopback callback (for example over SSH). Aborted once the callback arrives or the sign-in is\n\t * cancelled. Resolves to `undefined` or an empty string when the user cancels.\n\t */\n\tpromptForRedirectUrl(signal: AbortSignal): Promise<string | undefined>;\n}\n\nexport class McpSignInCancelledError extends Error {\n\tconstructor() {\n\t\tsuper(\"Sign-in cancelled\");\n\t\tthis.name = \"McpSignInCancelledError\";\n\t}\n}\n\ntype AuthorizationResponse = Pick<OAuthCallback, \"code\" | \"iss\">;\n\nfunction responseFromRedirectUrl(input: string, state: string, redirectUrl: URL): AuthorizationResponse {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Expected the full redirect URL from the browser address bar\");\n\t}\n\t// A server-specific redirect URI tells authorization servers apart, so it must match exactly.\n\tif (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {\n\t\tthrow new Error(\"The redirect URL does not match this sign-in's redirect URI\");\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(url.searchParams.get(\"error_description\") ?? error);\n\tif (url.searchParams.get(\"state\") !== state) throw new Error(\"The redirect URL belongs to a different sign-in\");\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"The redirect URL does not contain an authorization code\");\n\treturn { code, iss: url.searchParams.get(\"iss\") ?? undefined };\n}\n\n/**\n * Wait for the browser callback or a pasted redirect URL, whichever comes first. Aborting `signal`\n * aborts the prompt, which then cancels the sign-in.\n */\nasync function waitForAuthorizationResponse(\n\tcallback: OAuthCallbackServer,\n\tstate: string,\n\tredirectUrl: URL,\n\tprompt: McpSignInPrompt,\n\tsignal: AbortSignal | undefined,\n): Promise<AuthorizationResponse> {\n\tconst controller = new AbortController();\n\tconst promptSignal = signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;\n\tconst fromBrowser = callback.waitForCallback(state, redirectUrl.pathname);\n\tconst fromUser = prompt.promptForRedirectUrl(promptSignal).then((input) => {\n\t\tif (!input?.trim()) throw new McpSignInCancelledError();\n\t\treturn responseFromRedirectUrl(input, state, redirectUrl);\n\t});\n\ttry {\n\t\treturn await Promise.race([fromBrowser, fromUser]);\n\t} finally {\n\t\t// The losing side rejects once the prompt is aborted or the callback server closes.\n\t\tcontroller.abort();\n\t\tfromBrowser.catch(() => undefined);\n\t\tfromUser.catch(() => undefined);\n\t}\n}\n\n/** Listen on `port`, or on a free port when it is taken and not `required`. */\nasync function listenForCallback(\n\tsettings: CallbackSettings,\n\textraPaths: string[],\n\tport: number | undefined,\n\trequired: boolean,\n): Promise<OAuthCallbackServer> {\n\tconst options = {\n\t\thost: settings.host,\n\t\tredirectHost: settings.redirectHost,\n\t\tpath: settings.path,\n\t\textraPaths,\n\t\trenderPage: (page: OAuthCallbackPage) =>\n\t\t\tpage.ok\n\t\t\t\t? oauthSuccessHtml(\"Signed in to the MCP server. You may now close this page.\")\n\t\t\t\t: oauthErrorHtml(page.message, page.details),\n\t};\n\ttry {\n\t\treturn await OAuthCallbackServer.listen({ ...options, port: port ?? 0 });\n\t} catch (error) {\n\t\tif (required || port === undefined) throw error;\n\t\treturn OAuthCallbackServer.listen(options);\n\t}\n}\n\n/**\n * Sign in to an MCP server. Uses the stored refresh token when possible; otherwise runs the browser\n * authorization code flow. Tokens are saved to `store`. Aborting `signal` stops the sign-in at any\n * step with `McpSignInCancelledError`; requests to the authorization server are also time-limited.\n */\nexport async function signInMcpServer(options: {\n\tserverUrl: string;\n\tstore: McpOAuthStateStore;\n\tsettings: McpOAuthSettings;\n\tchallenge?: OAuthChallenge;\n\tprompt: McpSignInPrompt;\n\tsignal?: AbortSignal;\n}): Promise<void> {\n\tconst { serverUrl, store, settings, signal } = options;\n\tif (signal?.aborted) throw new McpSignInCancelledError();\n\tconst baseUrl = metadataBaseUrl(settings);\n\tconst previous = await store.load();\n\tconst stored = matchesClient(previous, serverUrl, baseUrl) ? previous : undefined;\n\tif (previous && !stored) await store.save({ serverUrl });\n\tconst stepUp = options.challenge?.error === \"insufficient_scope\";\n\tconst callbackOptions = callbackSettings(settings);\n\t// Reuse the port of the registered redirect URI so the registered client stays valid.\n\tconst registered = registeredRedirectUrls(stored?.clientInformation)[0];\n\tconst preferredPort =\n\t\tcallbackOptions.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);\n\tconst cimd = settings.clientRegistration === \"cimd\";\n\tconst callback = await listenForCallback(\n\t\tcallbackOptions,\n\t\t// The redirect URI of a server-specific Client ID Metadata Document.\n\t\tcimd ? [`${CALLBACK_PATH}/${callbackId(serverUrl)}`] : [],\n\t\tpreferredPort,\n\t\tcallbackOptions.port !== undefined,\n\t);\n\tconst redirectUrl = callbackOptions.fixedRedirectUrl ?? callback.redirectUrl;\n\ttry {\n\t\tif (stored) {\n\t\t\tconst next: McpOAuthState = { ...stored };\n\t\t\t// Every sign-in gets a fresh `state` parameter.\n\t\t\tdelete next.oauthState;\n\t\t\t// A registered client cannot use another redirect URI. CIMD tokens were checked against the base above.\n\t\t\tconst keepClient =\n\t\t\t\tsettings.clientId ||\n\t\t\t\t(cimd ? !stored.clientInformation : registeredRedirectUrls(stored.clientInformation).includes(redirectUrl));\n\t\t\tif (!keepClient) {\n\t\t\t\tdelete next.clientInformation;\n\t\t\t\tdelete next.tokens;\n\t\t\t\tdelete next.tokensExpireAt;\n\t\t\t}\n\t\t\tawait store.save(next);\n\t\t}\n\n\t\tlet authorizationUrl: URL | undefined;\n\t\tconst provider = createProvider(serverUrl, store, settings, redirectUrl, (url) => {\n\t\t\tauthorizationUrl = url;\n\t\t});\n\t\tconst flow = {\n\t\t\tserverUrl,\n\t\t\tfetch: timedFetch(),\n\t\t\tsignal,\n\t\t\tresourceMetadataUrl: options.challenge?.resourceMetadataUrl,\n\t\t\tauthorizationServerMetadataUrl: settings.authServerMetadataUrl,\n\t\t\t// A server asking for more scope gets it on top of the configured scope and, since the challenge\n\t\t\t// may list only the missing scopes, on top of the scope granted so far.\n\t\t\tscope: mergeScopes(\n\t\t\t\tsettings.scope,\n\t\t\t\tstepUp ? stepUpScope(stored?.tokens?.scope, options.challenge?.scope) : options.challenge?.scope,\n\t\t\t),\n\t\t};\n\t\t// A refresh keeps the granted scope; a server asking for more needs the browser flow.\n\t\tconst skipRefresh = stepUp;\n\t\tif ((await authorizeMcp(provider, { ...flow, skipRefresh })) === \"AUTHORIZED\") return;\n\t\tif (!authorizationUrl) throw new Error(\"OAuth flow did not produce an authorization URL\");\n\n\t\tconst state = await provider.state();\n\t\t// The flow picks the redirect URI, which may be specific to the MCP server.\n\t\tconst authorizationRedirectUrl = new URL(authorizationUrl.searchParams.get(\"redirect_uri\") ?? redirectUrl);\n\t\toptions.prompt.showAuthorizationUrl(authorizationUrl);\n\t\tconst { code, iss } = await waitForAuthorizationResponse(\n\t\t\tcallback,\n\t\t\tstate,\n\t\t\tauthorizationRedirectUrl,\n\t\t\toptions.prompt,\n\t\t\tsignal,\n\t\t);\n\t\tawait authorizeMcp(provider, { ...flow, authorizationCode: code, iss });\n\t} catch (error) {\n\t\t// Aborted requests fail with the signal's reason; report them as the cancellation they are.\n\t\tif (signal?.aborted) throw new McpSignInCancelledError();\n\t\tthrow error;\n\t} finally {\n\t\tawait callback.close();\n\t}\n}\n"]}
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../../src/extensions/mcp/oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,C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QACL,QAAQ;QACR,UAAU,EAAE,kBAAkB;KAC9B,CAAC,CAAC;IACH,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,YAAY,EAAE,CAAC;QAC/F,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,MAAM,CAAC,CAAC;QACnD,IAAI,aAAa,CAAC,IAAI,KAAK,YAAY;YAAE,OAAO;QAChD,MAAM,CAAC,oBAAoB,CAAC,IAAI,GAAG,CAAC,aAAa,CAAC,gBAAgB,CAAC,CAAC,CAAC;QACrE,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC;YAC5C,QAAQ;YACR,aAAa;YACb,oBAAoB,EAAE,CAAC,YAAY,EAAE,EAAE,CAAC,MAAM,CAAC,oBAAoB,CAAC,YAAY,CAAC;YACjF,MAAM;SACN,CAAC,CAAC;QACH,MAAM,iBAAiB,CAAC,EAAE,GAAG,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,CAAC;IACjE,CAAC;YAAS,CAAC;QACV,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;IACxB,CAAC;AACF,CAAC","sourcesContent":["/**\n * OAuth sign-in for remote MCP servers: draht's credential store and its side of the sign-in.\n *\n * Connections never start a browser flow on their own. They send the stored access token and, after\n * a 401, try the stored refresh token. When that is not possible they fail with\n * `McpOAuthAuthorizationRequiredError`, and the user signs in through `/mcp` or `draht mcp login`, which\n * run @draht/mcp's sign-in (PKCE, the operator's Client ID Metadata Document or dynamic client\n * registration) against a loopback callback or a pasted redirect URL.\n *\n * Credentials live in `<agent-dir>/mcp-auth.json`, keyed by server name and URL.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"@draht/ai/utils/oauth-page\";\nimport { mcpNamespace } from \"@draht/mcp\";\nimport {\n\tcompleteMcpSignIn,\n\tcreateMcpAuthProvider as createAuthProvider,\n\tlistenForLoopbackSignIn,\n\ttype McpAuthProvider,\n\ttype McpClientMetadataDocuments,\n\ttype McpOAuthServerStore,\n\ttype McpOAuthSettings,\n\ttype McpOAuthState,\n\tMcpRefreshLockBusyError,\n\ttype OAuthCallbackPage,\n\ttype OAuthChallenge,\n\tstartMcpSignIn,\n\twaitForLoopbackSignIn,\n} from \"@draht/mcp/oauth\";\nimport lockfile from \"proper-lockfile\";\nimport { APP_NAME, getAgentDir } from \"../../config.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"../../core/auth-storage.ts\";\nimport { isClientMetadataDocumentCallback } from \"../../core/mcp-servers.ts\";\n\n/** A refresh lock that its holder stopped renewing (the process was killed) is taken over after this. */\nconst REFRESH_LOCK_STALE_MS = 20_000;\n/** How long to wait for another process's refresh: longer than a stale lock lives. */\nconst REFRESH_LOCK_WAIT_MS = 25_000;\nconst REFRESH_LOCK_RETRY_MS = 100;\n\ntype StoredStates = Record<string, McpOAuthState>;\n\nfunction parseStates(content: string | undefined): StoredStates {\n\tif (!content?.trim()) return {};\n\tconst parsed: unknown = JSON.parse(content);\n\treturn typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as StoredStates) : {};\n}\n\nfunction serializeStates(states: StoredStates): string {\n\treturn `${JSON.stringify(states, null, 2)}\\n`;\n}\n\n/**\n * Keys of a server's state: by name and URL, so servers sharing a URL keep separate accounts, and the\n * legacy key by URL alone, written by older versions.\n */\nfunction storeKeys(name: string, serverUrl: string): { key: string; legacyKey: string } {\n\tconst legacyKey = String(new URL(serverUrl));\n\treturn { key: `${mcpNamespace(name)}|${legacyKey}`, legacyKey };\n}\n\n/** Per-server OAuth state (client registration, tokens, pending PKCE verifier) in `mcp-auth.json`. */\nexport class McpOAuthCredentialStore {\n\tprivate readonly backend: AuthStorageBackend;\n\t/** Directory for the refresh lock files. Without one, refreshes are only serialized in this process. */\n\tprivate readonly lockDir: string | undefined;\n\n\tconstructor(backend?: AuthStorageBackend, lockDir?: string) {\n\t\tthis.backend = backend ?? new FileAuthStorageBackend(join(getAgentDir(), \"mcp-auth.json\"));\n\t\tthis.lockDir = backend ? lockDir : getAgentDir();\n\t}\n\n\tforServer(name: string, serverUrl: string): McpOAuthServerStore {\n\t\tconst { key, legacyKey } = storeKeys(name, serverUrl);\n\t\treturn {\n\t\t\t// The first server to load legacy state takes it over; others with the same URL sign in again.\n\t\t\tload: () =>\n\t\t\t\tthis.backend.withLock((current) => {\n\t\t\t\t\tconst states = parseStates(current);\n\t\t\t\t\tif (states[key] || !states[legacyKey]) return { result: states[key] };\n\t\t\t\t\tstates[key] = states[legacyKey];\n\t\t\t\t\tdelete states[legacyKey];\n\t\t\t\t\treturn { result: states[key], next: serializeStates(states) };\n\t\t\t\t}),\n\t\t\tsave: (state) =>\n\t\t\t\tthis.write((states) => {\n\t\t\t\t\tstates[key] = state;\n\t\t\t\t}),\n\t\t\twithRefreshLock: (fn) => this.withRefreshLock(key, fn),\n\t\t};\n\t}\n\n\t/**\n\t * A lock file per server. When the process exits, proper-lockfile removes the locks it holds; when\n\t * it is killed, the lock goes stale because it is no longer renewed, and the next process takes it over.\n\t * Throws `McpRefreshLockBusyError` when another process holds the lock for the whole wait.\n\t */\n\tprivate async withRefreshLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n\t\tif (!this.lockDir) return fn();\n\t\tmkdirSync(this.lockDir, { recursive: true, mode: 0o700 });\n\t\tconst hash = createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 16);\n\t\tconst release = await lockfile\n\t\t\t.lock(join(this.lockDir, `mcp-auth-refresh-${hash}`), {\n\t\t\t\trealpath: false,\n\t\t\t\tstale: REFRESH_LOCK_STALE_MS,\n\t\t\t\tretries: {\n\t\t\t\t\tretries: REFRESH_LOCK_WAIT_MS / REFRESH_LOCK_RETRY_MS,\n\t\t\t\t\tfactor: 1,\n\t\t\t\t\tminTimeout: REFRESH_LOCK_RETRY_MS,\n\t\t\t\t\tmaxTimeout: REFRESH_LOCK_RETRY_MS,\n\t\t\t\t},\n\t\t\t\t// The default throws from a timer. A lost lock at worst lets two refreshes overlap.\n\t\t\t\tonCompromised: () => {},\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\t// proper-lockfile reports a lock held by another process as `ELOCKED`.\n\t\t\t\tif (error instanceof Error && \"code\" in error && error.code === \"ELOCKED\")\n\t\t\t\t\tthrow new McpRefreshLockBusyError();\n\t\t\t\tthrow error;\n\t\t\t});\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tawait release().catch(() => undefined);\n\t\t}\n\t}\n\n\t/** The stored tokens of a server, for noticing sign-ins done by another process. Does not take over legacy state. */\n\ttokens(name: string, serverUrl: string): McpOAuthState[\"tokens\"] {\n\t\tconst { key, legacyKey } = storeKeys(name, serverUrl);\n\t\tconst states = this.backend.withLock((current) => ({ result: parseStates(current) }));\n\t\treturn (states[key] ?? states[legacyKey])?.tokens;\n\t}\n\n\t/** Returns whether credentials were stored for the server. Removes legacy state the server would take over. */\n\tremove(name: string, serverUrl: string): boolean {\n\t\tconst { key, legacyKey } = storeKeys(name, serverUrl);\n\t\treturn this.backend.withLock((current) => {\n\t\t\tconst states = parseStates(current);\n\t\t\tconst stored = key in states ? key : legacyKey in states ? legacyKey : undefined;\n\t\t\tif (!stored) return { result: false };\n\t\t\tdelete states[stored];\n\t\t\treturn { result: true, next: serializeStates(states) };\n\t\t});\n\t}\n\n\tprivate write(update: (states: StoredStates) => void): void {\n\t\tthis.backend.withLock((current) => {\n\t\t\tconst states = parseStates(current);\n\t\t\tupdate(states);\n\t\t\treturn { result: undefined, next: serializeStates(states) };\n\t\t});\n\t}\n}\n\n/**\n * The redirect URIs the operator's Client ID Metadata Documents list (docs/mcp.md): `/callback` on\n * localhost and 127.0.0.1. draht names no document host: with `cimd`, @draht/mcp takes the documents'\n * base from the validated `oauth.clientMetadataBaseUrl` only, and without `cimd` it registers a client.\n */\nconst CLIENT_METADATA_DOCUMENTS: McpClientMetadataDocuments = {\n\tlistsRedirectUrl: isClientMetadataDocumentCallback,\n};\n\n/** draht's client identity for sign-in and refresh. */\nconst DRAHT_CLIENT = { clientName: APP_NAME, clientMetadataDocuments: CLIENT_METADATA_DOCUMENTS };\n\n/**\n * @draht/mcp's `createMcpAuthProvider` with draht's client identity. `clientMetadataBaseUrl` is the\n * validated base from the configuration (or undefined without `cimd`), apart from `settings` so that\n * reading a cached token never resolves `oauth.clientSecret`.\n */\nexport function createMcpAuthProvider(options: {\n\tserverUrl: string;\n\tstore: McpOAuthServerStore;\n\tclientMetadataBaseUrl: string | undefined;\n\tsettings: () => McpOAuthSettings;\n\tonChallenge: (challenge: OAuthChallenge) => void;\n}): McpAuthProvider {\n\treturn createAuthProvider({ ...options, ...DRAHT_CLIENT });\n}\n\nexport interface McpSignInPrompt {\n\t/** Show the authorization URL to the user and open it in a browser. */\n\tshowAuthorizationUrl(url: URL): void;\n\t/**\n\t * Ask for the redirect URL from the browser address bar, for when the browser cannot reach the\n\t * loopback callback (for example over SSH). Aborted once the callback arrives or the sign-in is\n\t * cancelled. Resolves to `undefined` or an empty string when the user cancels.\n\t */\n\tpromptForRedirectUrl(signal: AbortSignal): Promise<string | undefined>;\n}\n\nfunction renderCallbackPage(page: OAuthCallbackPage): string {\n\treturn page.ok\n\t\t? oauthSuccessHtml(\"Signed in to the MCP server. You may now close this page.\")\n\t\t: oauthErrorHtml(page.message, page.details);\n}\n\n/**\n * Sign in to an MCP server. Uses the stored refresh token when possible; otherwise runs the browser\n * authorization code flow against a loopback callback or a pasted redirect URL. Tokens are saved to\n * `store`. Aborting `signal` stops the sign-in at any step with `McpSignInCancelledError`; requests to\n * the authorization server are also time-limited.\n */\nexport async function signInMcpServer(options: {\n\tserverUrl: string;\n\tstore: McpOAuthServerStore;\n\tsettings: McpOAuthSettings;\n\tchallenge?: OAuthChallenge;\n\tprompt: McpSignInPrompt;\n\tsignal?: AbortSignal;\n}): Promise<void> {\n\tconst { serverUrl, store, settings, challenge, prompt, signal } = options;\n\tconst { callback, redirectUrl } = await listenForLoopbackSignIn({\n\t\tserverUrl,\n\t\tstore,\n\t\tsettings,\n\t\trenderPage: renderCallbackPage,\n\t});\n\ttry {\n\t\tconst signIn = { serverUrl, store, settings, redirectUrl, challenge, signal, ...DRAHT_CLIENT };\n\t\tconst authorization = await startMcpSignIn(signIn);\n\t\tif (authorization.kind === \"authorized\") return;\n\t\tprompt.showAuthorizationUrl(new URL(authorization.authorizationUrl));\n\t\tconst response = await waitForLoopbackSignIn({\n\t\t\tcallback,\n\t\t\tauthorization,\n\t\t\tpromptForRedirectUrl: (promptSignal) => prompt.promptForRedirectUrl(promptSignal),\n\t\t\tsignal,\n\t\t});\n\t\tawait completeMcpSignIn({ ...signIn, authorization, response });\n\t} finally {\n\t\tawait callback.close();\n\t}\n}\n"]}
@@ -9,7 +9,7 @@
9
9
  * interfaces for hosts that render them, and so are icons. Read resources become text and images for
10
10
  * the model; binary resources are saved to temp files. Scripts get the JSON payloads.
11
11
  */
12
- import type { ListResourcesResult, ListResourceTemplatesResult, McpRequestOptions, ReadResourceResult, Resource, ResourceTemplate } from "@draht/mcp";
12
+ import { type ListResourcesResult, type ListResourceTemplatesResult, type McpRequestOptions, type ReadResourceResult, type Resource, type ResourceTemplate } from "@draht/mcp";
13
13
  import type { TSchema } from "typebox";
14
14
  import type { ToolDefinition } from "../../core/extensions/types.ts";
15
15
  import { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAEX,mBAAmB,EACnB,2BAA2B,EAC3B,iBAAiB,EACjB,kBAAkB,EAClB,QAAQ,E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AEG;AACH,wBAAgB,gCAAgC,CAAC,OAAO,EAAE;IACzD,QAAQ,EAAE,WAAW,CAAC;IACtB,OAAO,EAAE,MAAM,SAAS,iBAAiB,EAAE,CAAC;CAC5C,GAAG,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,CA+I5C"}
@@ -9,8 +9,9 @@
9
9
  * interfaces for hosts that render them, and so are icons. Read resources become text and images for
10
10
  * the model; binary resources are saved to temp files. Scripts get the JSON payloads.
11
11
  */
12
+ import { limitMcpContent, } from "@draht/mcp";
12
13
  import { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL, } from "../../core/mcp-servers.js";
13
- import { limitMcpContent, toModelContent, toToolExposure } from "./tools.js";
14
+ import { saveToTempFile, toModelContent, toToolExposure } from "./tools.js";
14
15
  export { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };
15
16
  /** MCP App user interfaces, which only hosts that render them can use. */
16
17
  function isMcpAppResource(item) {
@@ -139,7 +140,7 @@ function errorMessage(error) {
139
140
  return error instanceof Error ? error.message : String(error);
140
141
  }
141
142
  async function jsonResult(tool, server, payload) {
142
- const { content, fullOutputPath } = await limitMcpContent([{ type: "text", text: JSON.stringify(payload) }]);
143
+ const { content, fullOutputPath } = await limitMcpContent([{ type: "text", text: JSON.stringify(payload) }], saveToTempFile);
143
144
  return {
144
145
  content,
145
146
  details: { server: server ?? "", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },
@@ -243,7 +244,7 @@ export function createMcpResourceToolDefinitions(options) {
243
244
  { type: "resource", resource: contents },
244
245
  ]);
245
246
  const converted = await toModelContent(server.name, blocks);
246
- const { content, fullOutputPath } = await limitMcpContent(converted.length > 0 ? converted : [{ type: "text", text: `Resource ${uri} is empty.` }]);
247
+ const { content, fullOutputPath } = await limitMcpContent(converted.length > 0 ? converted : [{ type: "text", text: `Resource ${uri} is empty.` }], saveToTempFile);
247
248
  const contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);
248
249
  return {
249
250
  content,
@@ -1 +1 @@
1
- {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAcH,OAAO,EACN,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,eAAe,EAAuB,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAElG,OAAO,EAAE,gCAAgC,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,CAAC;AAa7F,0EAA0E;AAC1E,SAAS,gBAAgB,CAAC,IAA+D;IACxF,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;IAC/C,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,gCAAgC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,uFAAuF;AACvF,SAAS,MAAM,CAAgC,MAAc,EAAE,IAAO;IACrE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAA+B,CAAC;IAC1E,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC;AAC5B,CAAC;AAED,MAAM,cAAc,GAAG,CAAC,WAAmB,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAClF,MAAM,aAAa,GAAG,cAAc,CAAC,4DAA4D,CAAC,CAAC;AACnG,MAAM,MAAM,GAAG,cAAc,CAAC,mFAAmF,CAAC,CAAC;AACnH,MAAM,eAAe,GAAG;IACvB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,EAAE,MAAM,EAAE,aAAa,E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xF,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;YAC7E,OAAO;gBACN,OAAO;gBACP,OAAO,EAAE;oBACR,MAAM,EAAE,MAAM,CAAC,IAAI;oBACnB,IAAI,EAAE,sBAAsB;oBAC5B,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7C;gBACD,iBAAiB,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,QAAQ,EAA0B;aACjF,CAAC;QACH,CAAC;KACD,CAAC;IAEF,OAAO,CAAC,aAAa,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * MCP resources, through the tools Codex and opencode use: `list_mcp_resources`,\n * `list_mcp_resource_templates`, and `read_mcp_resource`. They take a `server` argument and cover\n * every connected server with resources, so models trained on those tools use them unchanged.\n *\n * Listings are JSON, as in Codex: `{ server?, resources: [{ server, ...resource }], nextCursor? }`.\n * With a `server`, one page is listed and `cursor` continues it; without, every page of every server.\n * MCP App resources (`ui://` URIs and `profile=mcp-app` HTML) are left out, since they are user\n * interfaces for hosts that render them, and so are icons. Read resources become text and images for\n * the model; binary resources are saved to temp files. Scripts get the JSON payloads.\n */\n\nimport type { ImageContent, JsonValue, TextContent } from \"@draht/ai\";\nimport type {\n\tContentBlock,\n\tListResourcesResult,\n\tListResourceTemplatesResult,\n\tMcpRequestOptions,\n\tReadResourceResult,\n\tResource,\n\tResourceTemplate,\n} from \"@draht/mcp\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolAnnotations, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport {\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tLIST_MCP_RESOURCES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n} from \"../../core/mcp-servers.ts\";\nimport type { McpExposure } from \"./config.ts\";\nimport { limitMcpContent, type McpToolDetails, toModelContent, toToolExposure } from \"./tools.ts\";\n\nexport { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };\n\n/** A connected server that offers resources. */\nexport interface McpResourceServer {\n\tname: string;\n\ttimeoutMs: number;\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult>;\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult>;\n\tallResources(options: McpRequestOptions): Promise<Resource[]>;\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;\n}\n\n/** MCP App user interfaces, which only hosts that render them can use. */\nfunction isMcpAppResource(item: { uri?: string; uriTemplate?: string; mimeType?: string }): boolean {\n\tconst uri = item.uri ?? item.uriTemplate ?? \"\";\n\treturn uri.startsWith(\"ui://\") || /;\\s*profile\\s*=\\s*\"?mcp-app\"?/i.test(item.mimeType ?? \"\");\n}\n\n/** A listed resource or template without `_meta` and icons, tagged with its server. */\nfunction listed<T extends { _meta?: unknown }>(server: string, item: T): Record<string, unknown> {\n\tconst { _meta, icons: _icons, ...rest } = item as T & { icons?: unknown };\n\treturn { server, ...rest };\n}\n\nconst stringProperty = (description: string) => ({ type: \"string\", description });\nconst SERVER_FILTER = stringProperty(\"MCP server name. Omit to list every server with resources.\");\nconst CURSOR = stringProperty(\"Opaque cursor from a previous call with the same server; omit for the first page.\");\nconst LIST_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: { server: SERVER_FILTER, cursor: CURSOR },\n\tadditionalProperties: false,\n};\nconst READ_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: stringProperty(\n\t\t\t\"MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources.\",\n\t\t),\n\t\turi: stringProperty(\"Resource URI to read. Must be one of the URIs returned by list_mcp_resources.\"),\n\t},\n\trequired: [\"server\", \"uri\"],\n\tadditionalProperties: false,\n};\n\nconst optionalString = { type: \"string\" };\nconst LISTING_ERRORS = {\n\ttype: \"array\",\n\tdescription: \"Servers that could not be listed\",\n\titems: {\n\t\ttype: \"object\",\n\t\tproperties: { server: { type: \"string\" }, error: { type: \"string\" } },\n\t\trequired: [\"server\", \"error\"],\n\t},\n};\nconst LIST_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresources: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\tsize: { type: \"number\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uri\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resources\"],\n};\nconst LIST_TEMPLATES_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresourceTemplates: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turiTemplate: { type: \"string\", description: \"RFC 6570 URI template\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uriTemplate\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resourceTemplates\"],\n};\nconst READ_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: { type: \"string\" },\n\t\turi: { type: \"string\" },\n\t\tcontents: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\tanyOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { uri: { type: \"string\" }, mimeType: optionalString, text: { type: \"string\" } },\n\t\t\t\t\t\trequired: [\"uri\", \"text\"],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\t\t\tblob: { type: \"string\", description: \"base64\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"uri\", \"blob\"],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t},\n\t},\n\trequired: [\"server\", \"uri\", \"contents\"],\n};\n\nfunction stringArgument(params: unknown, key: string): string | undefined {\n\tconst value = (params as Record<string, unknown> | undefined)?.[key];\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be a string`);\n\treturn value.trim() || undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nasync function jsonResult(\n\ttool: string,\n\tserver: string | undefined,\n\tpayload: Record<string, unknown>,\n): Promise<{ content: (TextContent | ImageContent)[]; details: McpToolDetails; structuredContent: JsonValue }> {\n\tconst { content, fullOutputPath } = await limitMcpContent([{ type: \"text\", text: JSON.stringify(payload) }]);\n\treturn {\n\t\tcontent,\n\t\tdetails: { server: server ?? \"\", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: payload as unknown as JsonValue,\n\t};\n}\n\n/**\n * The three resource tools. `servers` returns the servers whose resources they reach, at call time.\n */\nexport function createMcpResourceToolDefinitions(options: {\n\texposure: McpExposure;\n\tservers: () => readonly McpResourceServer[];\n}): ToolDefinition<TSchema, McpToolDetails>[] {\n\tconst readOnly: ToolAnnotations = { readOnlyHint: true };\n\n\tconst findServer = (name: string): McpResourceServer => {\n\t\tconst servers = options.servers();\n\t\tconst server = servers.find((candidate) => candidate.name === name);\n\t\tif (server) return server;\n\t\tconst available = servers.map((candidate) => candidate.name).join(\", \");\n\t\tthrow new Error(\n\t\t\t`MCP server \"${name}\" has no resources${available ? `. Servers with resources: ${available}` : \"\"}`,\n\t\t);\n\t};\n\n\t/** One page of one server, or every page of every server. */\n\tconst list = async <T extends { _meta?: unknown }>(\n\t\tparams: unknown,\n\t\tsignal: AbortSignal | undefined,\n\t\tkey: \"resources\" | \"resourceTemplates\",\n\t\tpage: (\n\t\t\tserver: McpResourceServer,\n\t\t\tcursor: string | undefined,\n\t\t\toptions: McpRequestOptions,\n\t\t) => Promise<{\n\t\t\titems: T[];\n\t\t\tnextCursor?: string;\n\t\t}>,\n\t\tall: (server: McpResourceServer, options: McpRequestOptions) => Promise<T[]>,\n\t): Promise<Record<string, unknown>> => {\n\t\tconst serverName = stringArgument(params, \"server\");\n\t\tconst cursor = stringArgument(params, \"cursor\");\n\t\tconst visible = (item: T) => !isMcpAppResource(item as { uri?: string; uriTemplate?: string; mimeType?: string });\n\t\tif (serverName) {\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await page(server, cursor, { signal, timeoutMs: server.timeoutMs });\n\t\t\treturn {\n\t\t\t\tserver: server.name,\n\t\t\t\t[key]: result.items.filter(visible).map((item) => listed(server.name, item)),\n\t\t\t\t...(result.nextCursor === undefined ? {} : { nextCursor: result.nextCursor }),\n\t\t\t};\n\t\t}\n\t\tif (cursor) throw new Error(\"cursor can only be used when a server is specified\");\n\t\tconst servers = [...options.servers()].sort((a, b) => a.name.localeCompare(b.name));\n\t\tconst results = await Promise.allSettled(\n\t\t\tservers.map((server) => all(server, { signal, timeoutMs: server.timeoutMs })),\n\t\t);\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tconst errors: { server: string; error: string }[] = [];\n\t\tresults.forEach((result, index) => {\n\t\t\tconst server = servers[index].name;\n\t\t\tif (result.status === \"fulfilled\")\n\t\t\t\titems.push(...result.value.filter(visible).map((item) => listed(server, item)));\n\t\t\telse errors.push({ server, error: errorMessage(result.reason) });\n\t\t});\n\t\treturn { [key]: items, ...(errors.length > 0 ? { errors } : {}) };\n\t};\n\n\tconst listResources: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resources\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourcesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resources, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResources(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst listTemplates: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_TEMPLATES_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resourceTemplates\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourceTemplatesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resourceTemplates, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResourceTemplates(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst readResource: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: READ_MCP_RESOURCE_TOOL,\n\t\tlabel: READ_MCP_RESOURCE_TOOL,\n\t\tdescription: \"Read a specific resource from an MCP server given the server name and resource URI.\",\n\t\tparameters: READ_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: READ_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst serverName = stringArgument(params, \"server\");\n\t\t\tconst uri = stringArgument(params, \"uri\");\n\t\t\tif (!serverName) throw new Error(\"server must be provided\");\n\t\t\tif (!uri) throw new Error(\"uri must be provided\");\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await server.readResource(uri, { signal, timeoutMs: server.timeoutMs });\n\t\t\t// Several contents (for example a directory) are labeled with their URIs.\n\t\t\tconst blocks: ContentBlock[] = result.contents.flatMap((contents) => [\n\t\t\t\t...(result.contents.length > 1 ? [{ type: \"text\" as const, text: `${contents.uri}:` }] : []),\n\t\t\t\t{ type: \"resource\" as const, resource: contents },\n\t\t\t]);\n\t\t\tconst converted = await toModelContent(server.name, blocks);\n\t\t\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t\t\tconverted.length > 0 ? converted : [{ type: \"text\", text: `Resource ${uri} is empty.` }],\n\t\t\t);\n\t\t\tconst contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);\n\t\t\treturn {\n\t\t\t\tcontent,\n\t\t\t\tdetails: {\n\t\t\t\t\tserver: server.name,\n\t\t\t\t\ttool: READ_MCP_RESOURCE_TOOL,\n\t\t\t\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t\t\t\t},\n\t\t\t\tstructuredContent: { server: server.name, uri, contents } as unknown as JsonValue,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn [listResources, listTemplates, readResource];\n}\n"]}
1
+ {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/extensions/mcp/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAIN,eAAe,GAKf,MAAM,YAAY,CAAC;AAGpB,OAAO,EACN,gCAAgC,EAChC,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAuB,cAAc,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjG,OAAO,EAAE,gCAAgC,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,CAAC;AAa7F,0EAA0E;AAC1E,SAAS,gBAAgB,CAAC,IAA+D;IACxF,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;IAC/C,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,gCAAgC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,uFAAuF;AACvF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CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC5F,EAAE,IAAI,EAAE,UAAmB,EAAE,QAAQ,EAAE,QAAQ,EAAE;aACjD,CAAC,CAAC;YACH,MAAM,SAAS,GAAG,MAAM,cAAc,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YAC5D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,eAAe,CACxD,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,YAAY,EAAE,CAAC,EACxF,cAAc,CACd,CAAC;YACF,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;YAC7E,OAAO;gBACN,OAAO;gBACP,OAAO,EAAE;oBACR,MAAM,EAAE,MAAM,CAAC,IAAI;oBACnB,IAAI,EAAE,sBAAsB;oBAC5B,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7C;gBACD,iBAAiB,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,QAAQ,EAA0B;aACjF,CAAC;QACH,CAAC;KACD,CAAC;IAEF,OAAO,CAAC,aAAa,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * MCP resources, through the tools Codex and opencode use: `list_mcp_resources`,\n * `list_mcp_resource_templates`, and `read_mcp_resource`. They take a `server` argument and cover\n * every connected server with resources, so models trained on those tools use them unchanged.\n *\n * Listings are JSON, as in Codex: `{ server?, resources: [{ server, ...resource }], nextCursor? }`.\n * With a `server`, one page is listed and `cursor` continues it; without, every page of every server.\n * MCP App resources (`ui://` URIs and `profile=mcp-app` HTML) are left out, since they are user\n * interfaces for hosts that render them, and so are icons. Read resources become text and images for\n * the model; binary resources are saved to temp files. Scripts get the JSON payloads.\n */\n\nimport type { ImageContent, JsonValue, TextContent } from \"@draht/ai\";\nimport {\n\ttype ContentBlock,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tlimitMcpContent,\n\ttype McpRequestOptions,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n} from \"@draht/mcp\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolAnnotations, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport {\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tLIST_MCP_RESOURCES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n} from \"../../core/mcp-servers.ts\";\nimport type { McpExposure } from \"./config.ts\";\nimport { type McpToolDetails, saveToTempFile, toModelContent, toToolExposure } from \"./tools.ts\";\n\nexport { LIST_MCP_RESOURCE_TEMPLATES_TOOL, LIST_MCP_RESOURCES_TOOL, READ_MCP_RESOURCE_TOOL };\n\n/** A connected server that offers resources. */\nexport interface McpResourceServer {\n\tname: string;\n\ttimeoutMs: number;\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult>;\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult>;\n\tallResources(options: McpRequestOptions): Promise<Resource[]>;\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]>;\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult>;\n}\n\n/** MCP App user interfaces, which only hosts that render them can use. */\nfunction isMcpAppResource(item: { uri?: string; uriTemplate?: string; mimeType?: string }): boolean {\n\tconst uri = item.uri ?? item.uriTemplate ?? \"\";\n\treturn uri.startsWith(\"ui://\") || /;\\s*profile\\s*=\\s*\"?mcp-app\"?/i.test(item.mimeType ?? \"\");\n}\n\n/** A listed resource or template without `_meta` and icons, tagged with its server. */\nfunction listed<T extends { _meta?: unknown }>(server: string, item: T): Record<string, unknown> {\n\tconst { _meta, icons: _icons, ...rest } = item as T & { icons?: unknown };\n\treturn { server, ...rest };\n}\n\nconst stringProperty = (description: string) => ({ type: \"string\", description });\nconst SERVER_FILTER = stringProperty(\"MCP server name. Omit to list every server with resources.\");\nconst CURSOR = stringProperty(\"Opaque cursor from a previous call with the same server; omit for the first page.\");\nconst LIST_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: { server: SERVER_FILTER, cursor: CURSOR },\n\tadditionalProperties: false,\n};\nconst READ_PARAMETERS = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: stringProperty(\n\t\t\t\"MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources.\",\n\t\t),\n\t\turi: stringProperty(\"Resource URI to read. Must be one of the URIs returned by list_mcp_resources.\"),\n\t},\n\trequired: [\"server\", \"uri\"],\n\tadditionalProperties: false,\n};\n\nconst optionalString = { type: \"string\" };\nconst LISTING_ERRORS = {\n\ttype: \"array\",\n\tdescription: \"Servers that could not be listed\",\n\titems: {\n\t\ttype: \"object\",\n\t\tproperties: { server: { type: \"string\" }, error: { type: \"string\" } },\n\t\trequired: [\"server\", \"error\"],\n\t},\n};\nconst LIST_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresources: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\tsize: { type: \"number\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uri\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resources\"],\n};\nconst LIST_TEMPLATES_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: optionalString,\n\t\tresourceTemplates: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tserver: { type: \"string\" },\n\t\t\t\t\turiTemplate: { type: \"string\", description: \"RFC 6570 URI template\" },\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: optionalString,\n\t\t\t\t\tdescription: optionalString,\n\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t},\n\t\t\t\trequired: [\"server\", \"uriTemplate\", \"name\"],\n\t\t\t},\n\t\t},\n\t\tnextCursor: optionalString,\n\t\terrors: LISTING_ERRORS,\n\t},\n\trequired: [\"resourceTemplates\"],\n};\nconst READ_OUTPUT_SCHEMA = {\n\ttype: \"object\",\n\tproperties: {\n\t\tserver: { type: \"string\" },\n\t\turi: { type: \"string\" },\n\t\tcontents: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\tanyOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: { uri: { type: \"string\" }, mimeType: optionalString, text: { type: \"string\" } },\n\t\t\t\t\t\trequired: [\"uri\", \"text\"],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\turi: { type: \"string\" },\n\t\t\t\t\t\t\tmimeType: optionalString,\n\t\t\t\t\t\t\tblob: { type: \"string\", description: \"base64\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"uri\", \"blob\"],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t},\n\t},\n\trequired: [\"server\", \"uri\", \"contents\"],\n};\n\nfunction stringArgument(params: unknown, key: string): string | undefined {\n\tconst value = (params as Record<string, unknown> | undefined)?.[key];\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be a string`);\n\treturn value.trim() || undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nasync function jsonResult(\n\ttool: string,\n\tserver: string | undefined,\n\tpayload: Record<string, unknown>,\n): Promise<{ content: (TextContent | ImageContent)[]; details: McpToolDetails; structuredContent: JsonValue }> {\n\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t[{ type: \"text\", text: JSON.stringify(payload) }],\n\t\tsaveToTempFile,\n\t);\n\treturn {\n\t\tcontent,\n\t\tdetails: { server: server ?? \"\", tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: payload as unknown as JsonValue,\n\t};\n}\n\n/**\n * The three resource tools. `servers` returns the servers whose resources they reach, at call time.\n */\nexport function createMcpResourceToolDefinitions(options: {\n\texposure: McpExposure;\n\tservers: () => readonly McpResourceServer[];\n}): ToolDefinition<TSchema, McpToolDetails>[] {\n\tconst readOnly: ToolAnnotations = { readOnlyHint: true };\n\n\tconst findServer = (name: string): McpResourceServer => {\n\t\tconst servers = options.servers();\n\t\tconst server = servers.find((candidate) => candidate.name === name);\n\t\tif (server) return server;\n\t\tconst available = servers.map((candidate) => candidate.name).join(\", \");\n\t\tthrow new Error(\n\t\t\t`MCP server \"${name}\" has no resources${available ? `. Servers with resources: ${available}` : \"\"}`,\n\t\t);\n\t};\n\n\t/** One page of one server, or every page of every server. */\n\tconst list = async <T extends { _meta?: unknown }>(\n\t\tparams: unknown,\n\t\tsignal: AbortSignal | undefined,\n\t\tkey: \"resources\" | \"resourceTemplates\",\n\t\tpage: (\n\t\t\tserver: McpResourceServer,\n\t\t\tcursor: string | undefined,\n\t\t\toptions: McpRequestOptions,\n\t\t) => Promise<{\n\t\t\titems: T[];\n\t\t\tnextCursor?: string;\n\t\t}>,\n\t\tall: (server: McpResourceServer, options: McpRequestOptions) => Promise<T[]>,\n\t): Promise<Record<string, unknown>> => {\n\t\tconst serverName = stringArgument(params, \"server\");\n\t\tconst cursor = stringArgument(params, \"cursor\");\n\t\tconst visible = (item: T) => !isMcpAppResource(item as { uri?: string; uriTemplate?: string; mimeType?: string });\n\t\tif (serverName) {\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await page(server, cursor, { signal, timeoutMs: server.timeoutMs });\n\t\t\treturn {\n\t\t\t\tserver: server.name,\n\t\t\t\t[key]: result.items.filter(visible).map((item) => listed(server.name, item)),\n\t\t\t\t...(result.nextCursor === undefined ? {} : { nextCursor: result.nextCursor }),\n\t\t\t};\n\t\t}\n\t\tif (cursor) throw new Error(\"cursor can only be used when a server is specified\");\n\t\tconst servers = [...options.servers()].sort((a, b) => a.name.localeCompare(b.name));\n\t\tconst results = await Promise.allSettled(\n\t\t\tservers.map((server) => all(server, { signal, timeoutMs: server.timeoutMs })),\n\t\t);\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tconst errors: { server: string; error: string }[] = [];\n\t\tresults.forEach((result, index) => {\n\t\t\tconst server = servers[index].name;\n\t\t\tif (result.status === \"fulfilled\")\n\t\t\t\titems.push(...result.value.filter(visible).map((item) => listed(server, item)));\n\t\t\telse errors.push({ server, error: errorMessage(result.reason) });\n\t\t});\n\t\treturn { [key]: items, ...(errors.length > 0 ? { errors } : {}) };\n\t};\n\n\tconst listResources: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resources\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourcesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resources, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResources(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst listTemplates: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tlabel: LIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\t\tdescription:\n\t\t\t\"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.\",\n\t\tparameters: LIST_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: LIST_TEMPLATES_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst payload = await list(\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\t\"resourceTemplates\",\n\t\t\t\tasync (server, cursor, requestOptions) => {\n\t\t\t\t\tconst result = await server.resourceTemplatesPage(cursor, requestOptions);\n\t\t\t\t\treturn { items: result.resourceTemplates, nextCursor: result.nextCursor };\n\t\t\t\t},\n\t\t\t\t(server, requestOptions) => server.allResourceTemplates(requestOptions),\n\t\t\t);\n\t\t\treturn jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL, stringArgument(params, \"server\"), payload);\n\t\t},\n\t};\n\n\tconst readResource: ToolDefinition<TSchema, McpToolDetails> = {\n\t\tname: READ_MCP_RESOURCE_TOOL,\n\t\tlabel: READ_MCP_RESOURCE_TOOL,\n\t\tdescription: \"Read a specific resource from an MCP server given the server name and resource URI.\",\n\t\tparameters: READ_PARAMETERS as unknown as TSchema,\n\t\toutputSchema: READ_OUTPUT_SCHEMA as unknown as TSchema,\n\t\texposure: toToolExposure(options.exposure),\n\t\tannotations: readOnly,\n\t\tasync execute(_toolCallId, params, signal) {\n\t\t\tconst serverName = stringArgument(params, \"server\");\n\t\t\tconst uri = stringArgument(params, \"uri\");\n\t\t\tif (!serverName) throw new Error(\"server must be provided\");\n\t\t\tif (!uri) throw new Error(\"uri must be provided\");\n\t\t\tconst server = findServer(serverName);\n\t\t\tconst result = await server.readResource(uri, { signal, timeoutMs: server.timeoutMs });\n\t\t\t// Several contents (for example a directory) are labeled with their URIs.\n\t\t\tconst blocks: ContentBlock[] = result.contents.flatMap((contents) => [\n\t\t\t\t...(result.contents.length > 1 ? [{ type: \"text\" as const, text: `${contents.uri}:` }] : []),\n\t\t\t\t{ type: \"resource\" as const, resource: contents },\n\t\t\t]);\n\t\t\tconst converted = await toModelContent(server.name, blocks);\n\t\t\tconst { content, fullOutputPath } = await limitMcpContent(\n\t\t\t\tconverted.length > 0 ? converted : [{ type: \"text\", text: `Resource ${uri} is empty.` }],\n\t\t\t\tsaveToTempFile,\n\t\t\t);\n\t\t\tconst contents = result.contents.map(({ _meta: _ignored, ...rest }) => rest);\n\t\t\treturn {\n\t\t\t\tcontent,\n\t\t\t\tdetails: {\n\t\t\t\t\tserver: server.name,\n\t\t\t\t\ttool: READ_MCP_RESOURCE_TOOL,\n\t\t\t\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t\t\t\t},\n\t\t\t\tstructuredContent: { server: server.name, uri, contents } as unknown as JsonValue,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn [listResources, listTemplates, readResource];\n}\n"]}
@@ -4,14 +4,15 @@
4
4
  * server is configured.
5
5
  */
6
6
  import { type AuthProvider, type CallToolResult, type ListResourcesResult, type ListResourceTemplatesResult, McpClient, type McpRequestOptions, type Tool as McpTool, type McpTransport, type ReadResourceResult, type Resource, type ResourceTemplate } from "@draht/mcp";
7
- import { type OAuthChallenge } from "@draht/mcp/oauth";
7
+ import { type McpOAuthSettings, type OAuthChallenge } from "@draht/mcp/oauth";
8
8
  import type { McpServerEntry } from "./config.ts";
9
9
  import type { McpServerLog } from "./log.ts";
10
- import { type McpOAuthCredentialStore, type McpOAuthSettings } from "./oauth.ts";
10
+ import { type McpOAuthCredentialStore } from "./oauth.ts";
11
11
  import type { McpResourceServer } from "./resources.ts";
12
12
  import type { McpToolCaller } from "./tools.ts";
13
+ export { McpSignInCancelledError } from "@draht/mcp/oauth";
13
14
  export { McpServerLog } from "./log.ts";
14
- export { McpOAuthCredentialStore, McpSignInCancelledError, signInMcpServer } from "./oauth.ts";
15
+ export { McpOAuthCredentialStore, signInMcpServer } from "./oauth.ts";
15
16
  /**
16
17
  * `disconnected`: the connection dropped (for example the stdio server exited); the next call
17
18
  * reconnects.
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAMH,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,cAAc,EAEnB,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAEhC,SAAS,EAGT,KAAK,iBAAiB,EAEtB,KAAK,IAAI,IAAI,OAAO,EACpB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,KAAK,gBAAgB,EAGrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAsC,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAG3F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAGN,KA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,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CAEzG;IAED,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAEjF;IAED,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAElG;IAED,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAMlH;IAED,YAAY,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAE5D;IAED,oBAAoB,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAE5E;IAED;;;OAGG;YACW,UAAU;IAyBxB,0EAA0E;IACpE,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAI/B;IAED,4DAA4D;IACtD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAI7B;IAED,kGAAkG;IAClG,OAAO,CAAC,WAAW;IAOnB,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,OAAO;YAID,UAAU;YAKV,IAAI;YAmBJ,WAAW;IAkDzB,OAAO,CAAC,aAAa;IAWrB,wFAAwF;IACxF,OAAO,CAAC,iBAAiB;YASX,YAAY;IAY1B,kGAAkG;IAC5F,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAU3B;CACD"}
@@ -8,12 +8,13 @@ import { basename, join, resolve } from "node:path";
8
8
  import { setTimeout as sleep } from "node:timers/promises";
9
9
  import { pathToFileURL } from "node:url";
10
10
  import { JSON_RPC_ERROR_CODES, McpAuthRequiredError, McpClient, McpError, McpHttpError, McpSessionExpiredError, StdioTransport, StreamableHttpTransport, } from "@draht/mcp";
11
- import { McpOAuthAuthorizationRequiredError } from "@draht/mcp/oauth";
11
+ import { McpOAuthAuthorizationRequiredError, } from "@draht/mcp/oauth";
12
12
  import { APP_NAME, VERSION } from "../../config.js";
13
13
  import { resolveConfigValueOrThrow, resolveHeadersOrThrow } from "../../core/resolve-config-value.js";
14
- import { createMcpAuthProvider, } from "./oauth.js";
14
+ import { createMcpAuthProvider } from "./oauth.js";
15
+ export { McpSignInCancelledError } from "@draht/mcp/oauth";
15
16
  export { McpServerLog } from "./log.js";
16
- export { McpOAuthCredentialStore, McpSignInCancelledError, signInMcpServer } from "./oauth.js";
17
+ export { McpOAuthCredentialStore, signInMcpServer } from "./oauth.js";
17
18
  const DEFAULT_TIMEOUT_SECONDS = 60;
18
19
  const STDERR_TAIL_CHARS = 2_000;
19
20
  /** Delays between attempts to connect to an HTTP server that failed with a transient error. */
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/extensions/mcp/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAGN,oBAAoB,EAGpB,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,YAAY,EAEZ,sBAAsB,EAMtB,cAAc,EACd,uBAAuB,GACvB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kCAAkC,EAAuB,MAAM,kBAAkB,CAAC;AAC3F,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAGtG,OAAO,EACN,qBAAqB,GAIrB,MAAM,YAAY,CAAC;AAIpB,OAAO,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AAS,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAClG,+FAA+F;QAC/F,6CAA6C;QAC7C,MAAM,IAAI,CAAC,YAAY,EAAE,OAAO,EAAE,CAAC;IACpC,CAAC;CACD","sourcesContent":["/**\n * The part of the MCP integration that talks to servers: connections, transports, and OAuth\n * sign-in. It pulls in the MCP client, so index.ts loads it through runtime.lazy.ts only when a\n * server is configured.\n */\n\nimport { homedir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n\ttype AuthProvider,\n\ttype CallToolResult,\n\tJSON_RPC_ERROR_CODES,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tMcpAuthRequiredError,\n\tMcpClient,\n\tMcpError,\n\tMcpHttpError,\n\ttype McpRequestOptions,\n\tMcpSessionExpiredError,\n\ttype Tool as McpTool,\n\ttype McpTransport,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n\tStdioTransport,\n\tStreamableHttpTransport,\n} from \"@draht/mcp\";\nimport { McpOAuthAuthorizationRequiredError, type OAuthChallenge } from \"@draht/mcp/oauth\";\nimport { APP_NAME, VERSION } from \"../../config.ts\";\nimport { resolveConfigValueOrThrow, resolveHeadersOrThrow } from \"../../core/resolve-config-value.ts\";\nimport type { McpServerEntry } from \"./config.ts\";\nimport type { McpServerLog } from \"./log.ts\";\nimport {\n\tcreateMcpAuthProvider,\n\ttype McpAuthProvider,\n\ttype McpOAuthCredentialStore,\n\ttype McpOAuthSettings,\n} from \"./oauth.ts\";\nimport type { McpResourceServer } from \"./resources.ts\";\nimport type { McpToolCaller } from \"./tools.ts\";\n\nexport { McpServerLog } from \"./log.ts\";\nexport { McpOAuthCredentialStore, McpSignInCancelledError, signInMcpServer } from \"./oauth.ts\";\n\nconst DEFAULT_TIMEOUT_SECONDS = 60;\nconst STDERR_TAIL_CHARS = 2_000;\n/** Delays between attempts to connect to an HTTP server that failed with a transient error. */\nconst CONNECT_RETRY_DELAYS_MS = [250, 1_000];\n\n/**\n * `disconnected`: the connection dropped (for example the stdio server exited); the next call\n * reconnects.\n */\ntype ServerState = \"connecting\" | \"connected\" | \"disconnected\" | \"needs-auth\" | \"failed\" | \"closed\";\n\nexport type McpTransportFactory = (\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n) => McpTransport;\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Network failures and overloaded or restarting servers, which are worth another attempt. */\nfunction isTransientError(error: unknown): boolean {\n\tif (error instanceof McpHttpError) {\n\t\treturn error.status === 408 || error.status === 429 || (error.status >= 500 && error.status !== 501);\n\t}\n\treturn error instanceof TypeError;\n}\n\nfunction signInRequiredMessage(entry: McpServerEntry): string {\n\tconst provider = \"url\" in entry.config ? entry.config.auth?.provider : undefined;\n\treturn `MCP server \"${entry.name}\" requires sign-in. Run ${provider ? `/login ${provider}` : \"/mcp\"} to sign in.`;\n}\n\n/** HTTP servers authenticate with OAuth unless the config supplies an `Authorization` header or `auth`. */\nfunction usesOAuth(entry: McpServerEntry): boolean {\n\tconst { config } = entry;\n\tif (!(\"url\" in config) || config.auth) return false;\n\treturn !Object.keys(config.headers ?? {}).some((header) => header.toLowerCase() === \"authorization\");\n}\n\n/** `~` and `~/…` (also `~\\…` on Windows) name the home directory, like in a shell. */\nfunction expandHome(value: string): string {\n\tif (value === \"~\") return homedir();\n\tif (value.startsWith(\"~/\") || (process.platform === \"win32\" && value.startsWith(\"~\\\\\"))) {\n\t\treturn join(homedir(), value.slice(2));\n\t}\n\treturn value;\n}\n\nexport function createDefaultTransport(\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n): McpTransport {\n\tconst { config, name } = entry;\n\tif (\"url\" in config) {\n\t\treturn new StreamableHttpTransport({\n\t\t\turl: config.url,\n\t\t\theaders: resolveHeadersOrThrow(config.headers, `MCP server \"${name}\"`),\n\t\t\tauthProvider,\n\t\t});\n\t}\n\tconst env: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(config.env ?? {})) {\n\t\tenv[key] = resolveConfigValueOrThrow(value, `MCP server \"${name}\" env \"${key}\"`);\n\t}\n\treturn new StdioTransport({\n\t\tcommand: expandHome(config.command),\n\t\targs: config.args?.map(expandHome),\n\t\tcwd: resolve(cwd, expandHome(config.cwd ?? \".\")),\n\t\tenv,\n\t\tstderr: \"pipe\",\n\t});\n}\n\n/** Servers that do not implement `resources/templates/list` have no templates. */\nasync function withoutTemplates<T>(list: () => Promise<T>, empty: T): Promise<T> {\n\ttry {\n\t\treturn await list();\n\t} catch (error) {\n\t\tif (error instanceof McpError && error.code === JSON_RPC_ERROR_CODES.methodNotFound) return empty;\n\t\tthrow error;\n\t}\n}\n\nfunction listTemplates(client: McpClient, options: McpRequestOptions = {}): Promise<ResourceTemplate[]> {\n\treturn withoutTemplates(() => client.listResourceTemplates(options), []);\n}\n\n/** One configured server. Reconnects lazily when a call finds the connection gone. */\nexport class McpServerConnection implements McpToolCaller, McpResourceServer {\n\treadonly entry: McpServerEntry;\n\tstate: ServerState = \"connecting\";\n\terror: string | undefined;\n\ttools: McpTool[] = [];\n\t/**\n\t * Whether the server offers resources, which the resource tools list and read on demand. They are\n\t * not listed at connect: listing every resource can take long (a large drive, say).\n\t */\n\thasResources = false;\n\t/** Server instructions from `initialize`, describing its tools as a group. */\n\tinstructions: string | undefined;\n\t/** Last OAuth challenge from the server; sign-in uses its resource metadata URL and scope. */\n\tchallenge: OAuthChallenge | undefined;\n\tprivate client: McpClient | undefined;\n\tprivate opening: Promise<McpClient> | undefined;\n\t/** Aborted by `close()`; cancels a connect in progress, including the wait between retries. */\n\tprivate readonly shutdown = new AbortController();\n\t/** Stderr of the last stdio server that failed to connect. */\n\tprivate stderrTail: string | undefined;\n\tprivate readonly cwd: string;\n\tprivate readonly createTransport: McpTransportFactory;\n\tprivate readonly authProvider: McpAuthProvider | undefined;\n\tprivate readonly onTools: (connection: McpServerConnection) => void;\n\tprivate readonly onChange: ((connection: McpServerConnection) => void) | undefined;\n\tprivate readonly log: McpServerLog | undefined;\n\n\tconstructor(options: {\n\t\tentry: McpServerEntry;\n\t\tcwd: string;\n\t\tcreateTransport: McpTransportFactory;\n\t\tcredentials: McpOAuthCredentialStore;\n\t\t/** The current token of a pi provider, for servers with `auth.provider`. */\n\t\tproviderToken?: (provider: string) => Promise<string | undefined>;\n\t\tonTools: (connection: McpServerConnection) => void;\n\t\t/** Called when `state`, `error`, or `tools` change. */\n\t\tonChange?: (connection: McpServerConnection) => void;\n\t\t/** Receives the server's log messages (`notifications/message`). */\n\t\tlog?: McpServerLog;\n\t}) {\n\t\tthis.entry = options.entry;\n\t\tthis.cwd = options.cwd;\n\t\tthis.createTransport = options.createTransport;\n\t\tthis.onTools = options.onTools;\n\t\tthis.onChange = options.onChange;\n\t\tthis.log = options.log;\n\t\tconst url = this.oauthUrl;\n\t\tconst provider = \"url\" in this.entry.config ? this.entry.config.auth?.provider : undefined;\n\t\tthis.authProvider = url\n\t\t\t? createMcpAuthProvider({\n\t\t\t\t\tserverUrl: url,\n\t\t\t\t\tstore: options.credentials.forServer(this.entry.name, url),\n\t\t\t\t\tclientMetadataBaseUrl:\n\t\t\t\t\t\t\"url\" in this.entry.config ? this.entry.config.oauth?.clientMetadataBaseUrl : undefined,\n\t\t\t\t\tsettings: () => this.oauthSettings(),\n\t\t\t\t\tonChallenge: (challenge) => {\n\t\t\t\t\t\tthis.challenge = challenge;\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t: provider\n\t\t\t\t? // Read on every request, so the provider's refreshes apply; MCP stores no copy.\n\t\t\t\t\t{ token: async () => options.providerToken?.(provider), settled: async () => {} }\n\t\t\t\t: undefined;\n\t}\n\n\tget name(): string {\n\t\treturn this.entry.name;\n\t}\n\n\tprivate get closed(): boolean {\n\t\treturn this.shutdown.signal.aborted;\n\t}\n\n\tget timeoutMs(): number {\n\t\treturn (this.entry.config.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n\t}\n\n\t/** Server URL when the server authenticates with OAuth. */\n\tget oauthUrl(): string | undefined {\n\t\treturn usesOAuth(this.entry) && \"url\" in this.entry.config ? this.entry.config.url : undefined;\n\t}\n\n\toauthSettings(): McpOAuthSettings {\n\t\tconst oauth = \"url\" in this.entry.config ? this.entry.config.oauth : undefined;\n\t\tif (!oauth) return {};\n\t\treturn {\n\t\t\tclientId: oauth.clientId,\n\t\t\tclientSecret:\n\t\t\t\toauth.clientSecret === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: resolveConfigValueOrThrow(oauth.clientSecret, `MCP server \"${this.entry.name}\" oauth.clientSecret`),\n\t\t\tcallbackPort: oauth.callbackPort,\n\t\t\tcallbackUrl: oauth.callbackUrl,\n\t\t\tscope: oauth.scope,\n\t\t\tclientName: oauth.clientName,\n\t\t\tclientRegistration: oauth.clientRegistration,\n\t\t\tclientMetadataBaseUrl: oauth.clientMetadataBaseUrl,\n\t\t\tauthServerMetadataUrl: oauth.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : undefined,\n\t\t};\n\t}\n\n\tgetClient(): Promise<McpClient> {\n\t\tif (this.closed) return Promise.reject(new Error(`MCP server \"${this.entry.name}\" is shut down`));\n\t\tif (this.client?.connectionState === \"connected\") return Promise.resolve(this.client);\n\t\tthis.opening ??= this.open().finally(() => {\n\t\t\tthis.opening = undefined;\n\t\t});\n\t\treturn this.opening;\n\t}\n\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult> {\n\t\treturn this.withClient((client) => client.callTool(name, args, options));\n\t}\n\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult> {\n\t\treturn this.withClient((client) => client.readResource(uri, options), true);\n\t}\n\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult> {\n\t\treturn this.withClient((client) => client.listResourcesPage(cursor, options), true);\n\t}\n\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult> {\n\t\treturn this.withClient(\n\t\t\t(client) =>\n\t\t\t\twithoutTemplates(() => client.listResourceTemplatesPage(cursor, options), { resourceTemplates: [] }),\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tallResources(options: McpRequestOptions): Promise<Resource[]> {\n\t\treturn this.withClient((client) => client.listResources(options), true);\n\t}\n\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]> {\n\t\treturn this.withClient((client) => listTemplates(client, options), true);\n\t}\n\n\t/**\n\t * Run a request, reconnecting when needed. `readOnly` requests are retried once after a transient\n\t * HTTP error; tool calls are not, since they may have run.\n\t */\n\tprivate async withClient<T>(run: (client: McpClient) => Promise<T>, readOnly = false): Promise<T> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst client = await this.getClient();\n\t\t\ttry {\n\t\t\t\treturn await run(client);\n\t\t\t} catch (error) {\n\t\t\t\tif (readOnly && attempt === 1 && error instanceof McpHttpError && isTransientError(error)) {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_DELAYS_MS[0]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (error instanceof McpSessionExpiredError && attempt === 1) {\n\t\t\t\t\t// The server no longer knows the session (restart, deploy), so it did not run the request.\n\t\t\t\t\t// Retry once on a new session. The old client is detached but not closed: closing would\n\t\t\t\t\t// fail its other in-flight calls, which instead get the same 404 and retry the same way.\n\t\t\t\t\tif (this.client === client) this.client = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!this.needsSignIn(error)) throw error;\n\t\t\t\tawait this.dropClient(client);\n\t\t\t\tthis.markNeedsAuth();\n\t\t\t\tthrow new Error(signInRequiredMessage(this.entry));\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Connect again with fresh credentials, for example after signing in. */\n\tasync reconnect(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tawait this.getClient();\n\t}\n\n\t/** Disconnect after the stored credentials were removed. */\n\tasync signOut(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tif (!this.closed) this.markNeedsAuth();\n\t}\n\n\t/** OAuth servers that still reject the request after a refresh need the user to sign in again. */\n\tprivate needsSignIn(error: unknown): boolean {\n\t\treturn (\n\t\t\terror instanceof McpOAuthAuthorizationRequiredError ||\n\t\t\t(this.authProvider !== undefined && error instanceof McpAuthRequiredError)\n\t\t);\n\t}\n\n\tprivate markNeedsAuth(): void {\n\t\tthis.state = \"needs-auth\";\n\t\tthis.error = undefined;\n\t\tthis.changed();\n\t}\n\n\tprivate changed(): void {\n\t\tthis.onChange?.(this);\n\t}\n\n\tprivate async dropClient(client: McpClient): Promise<void> {\n\t\tif (this.client === client) this.client = undefined;\n\t\tawait client.close().catch(() => undefined);\n\t}\n\n\tprivate async open(): Promise<McpClient> {\n\t\tthis.state = \"connecting\";\n\t\tthis.changed();\n\t\tconst retries = \"url\" in this.entry.config ? CONNECT_RETRY_DELAYS_MS : [];\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tthis.stderrTail = undefined;\n\t\t\ttry {\n\t\t\t\treturn await this.connectOnce();\n\t\t\t} catch (error) {\n\t\t\t\tconst delay = retries[attempt];\n\t\t\t\tif (this.closed || delay === undefined || !isTransientError(error)) {\n\t\t\t\t\tthrow this.connectFailed(error);\n\t\t\t\t}\n\t\t\t\tawait sleep(delay, undefined, { signal: this.shutdown.signal }).catch(() => undefined);\n\t\t\t\tif (this.closed) throw this.connectFailed(error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async connectOnce(): Promise<McpClient> {\n\t\tconst client = new McpClient({\n\t\t\tname: APP_NAME,\n\t\t\tversion: VERSION,\n\t\t\trequestTimeoutMs: this.timeoutMs,\n\t\t\troots: [{ uri: pathToFileURL(this.cwd).href, name: basename(this.cwd) }],\n\t\t});\n\t\tconst log = this.log;\n\t\tif (log) client.onNotification(\"notifications/message\", (params) => log.write(this.entry.name, params));\n\t\t// Closing the client fails its pending initialize or discovery requests and closes the transport.\n\t\t// Memoized: a second `client.close()` returns before the first finished closing the transport.\n\t\tlet closing: Promise<void> | undefined;\n\t\tconst closeClient = () => {\n\t\t\tclosing ??= client.close().catch(() => undefined);\n\t\t\treturn closing;\n\t\t};\n\t\tthis.shutdown.signal.addEventListener(\"abort\", closeClient, { once: true });\n\t\tlet transport: McpTransport | undefined;\n\t\ttry {\n\t\t\ttransport = this.createTransport(this.entry, this.cwd, this.authProvider);\n\t\t\tawait client.connect(transport);\n\t\t\tclient.onNotification(\"notifications/tools/list_changed\", () => {\n\t\t\t\tvoid this.refreshTools(client);\n\t\t\t});\n\t\t\tconst stdio = transport instanceof StdioTransport ? transport : undefined;\n\t\t\tclient.onClose(() => this.handleClientClose(client, stdio));\n\t\t\t// Servers without the tools capability (prompts or resources only) do not answer tools/list.\n\t\t\tconst tools = client.serverCapabilities?.tools ? await client.listTools() : [];\n\t\t\tif (this.closed) throw new Error(\"shut down while connecting\");\n\t\t\tif (client.connectionState !== \"connected\") throw new Error(\"connection closed during setup\");\n\t\t\tthis.client = client;\n\t\t\tthis.tools = tools;\n\t\t\tthis.hasResources = client.serverCapabilities?.resources !== undefined;\n\t\t\tthis.instructions = client.instructions?.trim() || undefined;\n\t\t\tthis.state = \"connected\";\n\t\t\tthis.error = undefined;\n\t\t\tthis.onTools(this);\n\t\t\tthis.changed();\n\t\t\treturn client;\n\t\t} catch (error) {\n\t\t\tawait closeClient();\n\t\t\tif (transport instanceof StdioTransport) {\n\t\t\t\tthis.stderrTail = transport.stderr.trim().slice(-STDERR_TAIL_CHARS) || undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.shutdown.signal.removeEventListener(\"abort\", closeClient);\n\t\t}\n\t}\n\n\tprivate connectFailed(error: unknown): Error {\n\t\tif (this.needsSignIn(error) && !this.closed) {\n\t\t\tthis.markNeedsAuth();\n\t\t\treturn new Error(signInRequiredMessage(this.entry));\n\t\t}\n\t\tthis.state = this.closed ? \"closed\" : \"failed\";\n\t\tthis.error = this.stderrTail ? `${errorMessage(error)}\\n${this.stderrTail}` : errorMessage(error);\n\t\tthis.changed();\n\t\treturn new Error(`MCP server \"${this.entry.name}\" failed to connect: ${this.error}`);\n\t}\n\n\t/** The transport dropped. The next call reconnects; until then the status shows why. */\n\tprivate handleClientClose(client: McpClient, stdio: StdioTransport | undefined): void {\n\t\tif (this.client !== client || this.closed) return;\n\t\tthis.client = undefined;\n\t\tthis.state = \"disconnected\";\n\t\tconst stderr = stdio?.stderr.trim().slice(-STDERR_TAIL_CHARS);\n\t\tthis.error = stderr ? `Connection closed\\n${stderr}` : \"Connection closed\";\n\t\tthis.changed();\n\t}\n\n\tprivate async refreshTools(client: McpClient): Promise<void> {\n\t\ttry {\n\t\t\tconst tools = await client.listTools();\n\t\t\tif (this.client !== client || this.closed) return;\n\t\t\tthis.tools = tools;\n\t\t\tthis.onTools(this);\n\t\t} catch (error) {\n\t\t\tthis.error = `Failed to refresh tools: ${errorMessage(error)}`;\n\t\t}\n\t\tthis.changed();\n\t}\n\n\t/** Resolves once no transport of this server is open, including one that was still connecting. */\n\tasync close(): Promise<void> {\n\t\tthis.shutdown.abort();\n\t\tthis.state = \"closed\";\n\t\tthis.changed();\n\t\tconst client = this.client;\n\t\tthis.client = undefined;\n\t\tawait Promise.all([client?.close().catch(() => undefined), this.opening?.catch(() => undefined)]);\n\t\t// A refresh the server already answered may have rotated the refresh token; exiting before the\n\t\t// new tokens are saved would lose the grant.\n\t\tawait this.authProvider?.settled();\n\t}\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/extensions/mcp/runtime.ts"],"names":[],"mappings":"AAAA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MAAM,KAAK,MAAM,IAAI,IAAI,CAAC,MAAM;gBAAE,OAAO;YAClD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;YACnB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,CAAC,KAAK,GAAG,4BAA4B,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;QAChE,CAAC;QACD,IAAI,CAAC,OAAO,EAAE,CAAC;IAChB,CAAC;IAED,kGAAkG;IAClG,KAAK,CAAC,KAAK;QACV,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC;QACtB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAClG,+FAA+F;QAC/F,6CAA6C;QAC7C,MAAM,IAAI,CAAC,YAAY,EAAE,OAAO,EAAE,CAAC;IACpC,CAAC;CACD","sourcesContent":["/**\n * The part of the MCP integration that talks to servers: connections, transports, and OAuth\n * sign-in. It pulls in the MCP client, so index.ts loads it through runtime.lazy.ts only when a\n * server is configured.\n */\n\nimport { homedir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n\ttype AuthProvider,\n\ttype CallToolResult,\n\tJSON_RPC_ERROR_CODES,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tMcpAuthRequiredError,\n\tMcpClient,\n\tMcpError,\n\tMcpHttpError,\n\ttype McpRequestOptions,\n\tMcpSessionExpiredError,\n\ttype Tool as McpTool,\n\ttype McpTransport,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n\tStdioTransport,\n\tStreamableHttpTransport,\n} from \"@draht/mcp\";\nimport {\n\ttype McpAuthProvider,\n\tMcpOAuthAuthorizationRequiredError,\n\ttype McpOAuthSettings,\n\ttype OAuthChallenge,\n} from \"@draht/mcp/oauth\";\nimport { APP_NAME, VERSION } from \"../../config.ts\";\nimport { resolveConfigValueOrThrow, resolveHeadersOrThrow } from \"../../core/resolve-config-value.ts\";\nimport type { McpServerEntry } from \"./config.ts\";\nimport type { McpServerLog } from \"./log.ts\";\nimport { createMcpAuthProvider, type McpOAuthCredentialStore } from \"./oauth.ts\";\nimport type { McpResourceServer } from \"./resources.ts\";\nimport type { McpToolCaller } from \"./tools.ts\";\n\nexport { McpSignInCancelledError } from \"@draht/mcp/oauth\";\nexport { McpServerLog } from \"./log.ts\";\nexport { McpOAuthCredentialStore, signInMcpServer } from \"./oauth.ts\";\n\nconst DEFAULT_TIMEOUT_SECONDS = 60;\nconst STDERR_TAIL_CHARS = 2_000;\n/** Delays between attempts to connect to an HTTP server that failed with a transient error. */\nconst CONNECT_RETRY_DELAYS_MS = [250, 1_000];\n\n/**\n * `disconnected`: the connection dropped (for example the stdio server exited); the next call\n * reconnects.\n */\ntype ServerState = \"connecting\" | \"connected\" | \"disconnected\" | \"needs-auth\" | \"failed\" | \"closed\";\n\nexport type McpTransportFactory = (\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n) => McpTransport;\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Network failures and overloaded or restarting servers, which are worth another attempt. */\nfunction isTransientError(error: unknown): boolean {\n\tif (error instanceof McpHttpError) {\n\t\treturn error.status === 408 || error.status === 429 || (error.status >= 500 && error.status !== 501);\n\t}\n\treturn error instanceof TypeError;\n}\n\nfunction signInRequiredMessage(entry: McpServerEntry): string {\n\tconst provider = \"url\" in entry.config ? entry.config.auth?.provider : undefined;\n\treturn `MCP server \"${entry.name}\" requires sign-in. Run ${provider ? `/login ${provider}` : \"/mcp\"} to sign in.`;\n}\n\n/** HTTP servers authenticate with OAuth unless the config supplies an `Authorization` header or `auth`. */\nfunction usesOAuth(entry: McpServerEntry): boolean {\n\tconst { config } = entry;\n\tif (!(\"url\" in config) || config.auth) return false;\n\treturn !Object.keys(config.headers ?? {}).some((header) => header.toLowerCase() === \"authorization\");\n}\n\n/** `~` and `~/…` (also `~\\…` on Windows) name the home directory, like in a shell. */\nfunction expandHome(value: string): string {\n\tif (value === \"~\") return homedir();\n\tif (value.startsWith(\"~/\") || (process.platform === \"win32\" && value.startsWith(\"~\\\\\"))) {\n\t\treturn join(homedir(), value.slice(2));\n\t}\n\treturn value;\n}\n\nexport function createDefaultTransport(\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n): McpTransport {\n\tconst { config, name } = entry;\n\tif (\"url\" in config) {\n\t\treturn new StreamableHttpTransport({\n\t\t\turl: config.url,\n\t\t\theaders: resolveHeadersOrThrow(config.headers, `MCP server \"${name}\"`),\n\t\t\tauthProvider,\n\t\t});\n\t}\n\tconst env: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(config.env ?? {})) {\n\t\tenv[key] = resolveConfigValueOrThrow(value, `MCP server \"${name}\" env \"${key}\"`);\n\t}\n\treturn new StdioTransport({\n\t\tcommand: expandHome(config.command),\n\t\targs: config.args?.map(expandHome),\n\t\tcwd: resolve(cwd, expandHome(config.cwd ?? \".\")),\n\t\tenv,\n\t\tstderr: \"pipe\",\n\t});\n}\n\n/** Servers that do not implement `resources/templates/list` have no templates. */\nasync function withoutTemplates<T>(list: () => Promise<T>, empty: T): Promise<T> {\n\ttry {\n\t\treturn await list();\n\t} catch (error) {\n\t\tif (error instanceof McpError && error.code === JSON_RPC_ERROR_CODES.methodNotFound) return empty;\n\t\tthrow error;\n\t}\n}\n\nfunction listTemplates(client: McpClient, options: McpRequestOptions = {}): Promise<ResourceTemplate[]> {\n\treturn withoutTemplates(() => client.listResourceTemplates(options), []);\n}\n\n/** One configured server. Reconnects lazily when a call finds the connection gone. */\nexport class McpServerConnection implements McpToolCaller, McpResourceServer {\n\treadonly entry: McpServerEntry;\n\tstate: ServerState = \"connecting\";\n\terror: string | undefined;\n\ttools: McpTool[] = [];\n\t/**\n\t * Whether the server offers resources, which the resource tools list and read on demand. They are\n\t * not listed at connect: listing every resource can take long (a large drive, say).\n\t */\n\thasResources = false;\n\t/** Server instructions from `initialize`, describing its tools as a group. */\n\tinstructions: string | undefined;\n\t/** Last OAuth challenge from the server; sign-in uses its resource metadata URL and scope. */\n\tchallenge: OAuthChallenge | undefined;\n\tprivate client: McpClient | undefined;\n\tprivate opening: Promise<McpClient> | undefined;\n\t/** Aborted by `close()`; cancels a connect in progress, including the wait between retries. */\n\tprivate readonly shutdown = new AbortController();\n\t/** Stderr of the last stdio server that failed to connect. */\n\tprivate stderrTail: string | undefined;\n\tprivate readonly cwd: string;\n\tprivate readonly createTransport: McpTransportFactory;\n\tprivate readonly authProvider: McpAuthProvider | undefined;\n\tprivate readonly onTools: (connection: McpServerConnection) => void;\n\tprivate readonly onChange: ((connection: McpServerConnection) => void) | undefined;\n\tprivate readonly log: McpServerLog | undefined;\n\n\tconstructor(options: {\n\t\tentry: McpServerEntry;\n\t\tcwd: string;\n\t\tcreateTransport: McpTransportFactory;\n\t\tcredentials: McpOAuthCredentialStore;\n\t\t/** The current token of a pi provider, for servers with `auth.provider`. */\n\t\tproviderToken?: (provider: string) => Promise<string | undefined>;\n\t\tonTools: (connection: McpServerConnection) => void;\n\t\t/** Called when `state`, `error`, or `tools` change. */\n\t\tonChange?: (connection: McpServerConnection) => void;\n\t\t/** Receives the server's log messages (`notifications/message`). */\n\t\tlog?: McpServerLog;\n\t}) {\n\t\tthis.entry = options.entry;\n\t\tthis.cwd = options.cwd;\n\t\tthis.createTransport = options.createTransport;\n\t\tthis.onTools = options.onTools;\n\t\tthis.onChange = options.onChange;\n\t\tthis.log = options.log;\n\t\tconst url = this.oauthUrl;\n\t\tconst provider = \"url\" in this.entry.config ? this.entry.config.auth?.provider : undefined;\n\t\tthis.authProvider = url\n\t\t\t? createMcpAuthProvider({\n\t\t\t\t\tserverUrl: url,\n\t\t\t\t\tstore: options.credentials.forServer(this.entry.name, url),\n\t\t\t\t\tclientMetadataBaseUrl:\n\t\t\t\t\t\t\"url\" in this.entry.config ? this.entry.config.oauth?.clientMetadataBaseUrl : undefined,\n\t\t\t\t\tsettings: () => this.oauthSettings(),\n\t\t\t\t\tonChallenge: (challenge) => {\n\t\t\t\t\t\tthis.challenge = challenge;\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t: provider\n\t\t\t\t? // Read on every request, so the provider's refreshes apply; MCP stores no copy.\n\t\t\t\t\t{ token: async () => options.providerToken?.(provider), settled: async () => {} }\n\t\t\t\t: undefined;\n\t}\n\n\tget name(): string {\n\t\treturn this.entry.name;\n\t}\n\n\tprivate get closed(): boolean {\n\t\treturn this.shutdown.signal.aborted;\n\t}\n\n\tget timeoutMs(): number {\n\t\treturn (this.entry.config.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n\t}\n\n\t/** Server URL when the server authenticates with OAuth. */\n\tget oauthUrl(): string | undefined {\n\t\treturn usesOAuth(this.entry) && \"url\" in this.entry.config ? this.entry.config.url : undefined;\n\t}\n\n\toauthSettings(): McpOAuthSettings {\n\t\tconst oauth = \"url\" in this.entry.config ? this.entry.config.oauth : undefined;\n\t\tif (!oauth) return {};\n\t\treturn {\n\t\t\tclientId: oauth.clientId,\n\t\t\tclientSecret:\n\t\t\t\toauth.clientSecret === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: resolveConfigValueOrThrow(oauth.clientSecret, `MCP server \"${this.entry.name}\" oauth.clientSecret`),\n\t\t\tcallbackPort: oauth.callbackPort,\n\t\t\tcallbackUrl: oauth.callbackUrl,\n\t\t\tscope: oauth.scope,\n\t\t\tclientName: oauth.clientName,\n\t\t\tclientRegistration: oauth.clientRegistration,\n\t\t\tclientMetadataBaseUrl: oauth.clientMetadataBaseUrl,\n\t\t\tauthServerMetadataUrl: oauth.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : undefined,\n\t\t};\n\t}\n\n\tgetClient(): Promise<McpClient> {\n\t\tif (this.closed) return Promise.reject(new Error(`MCP server \"${this.entry.name}\" is shut down`));\n\t\tif (this.client?.connectionState === \"connected\") return Promise.resolve(this.client);\n\t\tthis.opening ??= this.open().finally(() => {\n\t\t\tthis.opening = undefined;\n\t\t});\n\t\treturn this.opening;\n\t}\n\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult> {\n\t\treturn this.withClient((client) => client.callTool(name, args, options));\n\t}\n\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult> {\n\t\treturn this.withClient((client) => client.readResource(uri, options), true);\n\t}\n\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult> {\n\t\treturn this.withClient((client) => client.listResourcesPage(cursor, options), true);\n\t}\n\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult> {\n\t\treturn this.withClient(\n\t\t\t(client) =>\n\t\t\t\twithoutTemplates(() => client.listResourceTemplatesPage(cursor, options), { resourceTemplates: [] }),\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tallResources(options: McpRequestOptions): Promise<Resource[]> {\n\t\treturn this.withClient((client) => client.listResources(options), true);\n\t}\n\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]> {\n\t\treturn this.withClient((client) => listTemplates(client, options), true);\n\t}\n\n\t/**\n\t * Run a request, reconnecting when needed. `readOnly` requests are retried once after a transient\n\t * HTTP error; tool calls are not, since they may have run.\n\t */\n\tprivate async withClient<T>(run: (client: McpClient) => Promise<T>, readOnly = false): Promise<T> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst client = await this.getClient();\n\t\t\ttry {\n\t\t\t\treturn await run(client);\n\t\t\t} catch (error) {\n\t\t\t\tif (readOnly && attempt === 1 && error instanceof McpHttpError && isTransientError(error)) {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_DELAYS_MS[0]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (error instanceof McpSessionExpiredError && attempt === 1) {\n\t\t\t\t\t// The server no longer knows the session (restart, deploy), so it did not run the request.\n\t\t\t\t\t// Retry once on a new session. The old client is detached but not closed: closing would\n\t\t\t\t\t// fail its other in-flight calls, which instead get the same 404 and retry the same way.\n\t\t\t\t\tif (this.client === client) this.client = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!this.needsSignIn(error)) throw error;\n\t\t\t\tawait this.dropClient(client);\n\t\t\t\tthis.markNeedsAuth();\n\t\t\t\tthrow new Error(signInRequiredMessage(this.entry));\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Connect again with fresh credentials, for example after signing in. */\n\tasync reconnect(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tawait this.getClient();\n\t}\n\n\t/** Disconnect after the stored credentials were removed. */\n\tasync signOut(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tif (!this.closed) this.markNeedsAuth();\n\t}\n\n\t/** OAuth servers that still reject the request after a refresh need the user to sign in again. */\n\tprivate needsSignIn(error: unknown): boolean {\n\t\treturn (\n\t\t\terror instanceof McpOAuthAuthorizationRequiredError ||\n\t\t\t(this.authProvider !== undefined && error instanceof McpAuthRequiredError)\n\t\t);\n\t}\n\n\tprivate markNeedsAuth(): void {\n\t\tthis.state = \"needs-auth\";\n\t\tthis.error = undefined;\n\t\tthis.changed();\n\t}\n\n\tprivate changed(): void {\n\t\tthis.onChange?.(this);\n\t}\n\n\tprivate async dropClient(client: McpClient): Promise<void> {\n\t\tif (this.client === client) this.client = undefined;\n\t\tawait client.close().catch(() => undefined);\n\t}\n\n\tprivate async open(): Promise<McpClient> {\n\t\tthis.state = \"connecting\";\n\t\tthis.changed();\n\t\tconst retries = \"url\" in this.entry.config ? CONNECT_RETRY_DELAYS_MS : [];\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tthis.stderrTail = undefined;\n\t\t\ttry {\n\t\t\t\treturn await this.connectOnce();\n\t\t\t} catch (error) {\n\t\t\t\tconst delay = retries[attempt];\n\t\t\t\tif (this.closed || delay === undefined || !isTransientError(error)) {\n\t\t\t\t\tthrow this.connectFailed(error);\n\t\t\t\t}\n\t\t\t\tawait sleep(delay, undefined, { signal: this.shutdown.signal }).catch(() => undefined);\n\t\t\t\tif (this.closed) throw this.connectFailed(error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async connectOnce(): Promise<McpClient> {\n\t\tconst client = new McpClient({\n\t\t\tname: APP_NAME,\n\t\t\tversion: VERSION,\n\t\t\trequestTimeoutMs: this.timeoutMs,\n\t\t\troots: [{ uri: pathToFileURL(this.cwd).href, name: basename(this.cwd) }],\n\t\t});\n\t\tconst log = this.log;\n\t\tif (log) client.onNotification(\"notifications/message\", (params) => log.write(this.entry.name, params));\n\t\t// Closing the client fails its pending initialize or discovery requests and closes the transport.\n\t\t// Memoized: a second `client.close()` returns before the first finished closing the transport.\n\t\tlet closing: Promise<void> | undefined;\n\t\tconst closeClient = () => {\n\t\t\tclosing ??= client.close().catch(() => undefined);\n\t\t\treturn closing;\n\t\t};\n\t\tthis.shutdown.signal.addEventListener(\"abort\", closeClient, { once: true });\n\t\tlet transport: McpTransport | undefined;\n\t\ttry {\n\t\t\ttransport = this.createTransport(this.entry, this.cwd, this.authProvider);\n\t\t\tawait client.connect(transport);\n\t\t\tclient.onNotification(\"notifications/tools/list_changed\", () => {\n\t\t\t\tvoid this.refreshTools(client);\n\t\t\t});\n\t\t\tconst stdio = transport instanceof StdioTransport ? transport : undefined;\n\t\t\tclient.onClose(() => this.handleClientClose(client, stdio));\n\t\t\t// Servers without the tools capability (prompts or resources only) do not answer tools/list.\n\t\t\tconst tools = client.serverCapabilities?.tools ? await client.listTools() : [];\n\t\t\tif (this.closed) throw new Error(\"shut down while connecting\");\n\t\t\tif (client.connectionState !== \"connected\") throw new Error(\"connection closed during setup\");\n\t\t\tthis.client = client;\n\t\t\tthis.tools = tools;\n\t\t\tthis.hasResources = client.serverCapabilities?.resources !== undefined;\n\t\t\tthis.instructions = client.instructions?.trim() || undefined;\n\t\t\tthis.state = \"connected\";\n\t\t\tthis.error = undefined;\n\t\t\tthis.onTools(this);\n\t\t\tthis.changed();\n\t\t\treturn client;\n\t\t} catch (error) {\n\t\t\tawait closeClient();\n\t\t\tif (transport instanceof StdioTransport) {\n\t\t\t\tthis.stderrTail = transport.stderr.trim().slice(-STDERR_TAIL_CHARS) || undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.shutdown.signal.removeEventListener(\"abort\", closeClient);\n\t\t}\n\t}\n\n\tprivate connectFailed(error: unknown): Error {\n\t\tif (this.needsSignIn(error) && !this.closed) {\n\t\t\tthis.markNeedsAuth();\n\t\t\treturn new Error(signInRequiredMessage(this.entry));\n\t\t}\n\t\tthis.state = this.closed ? \"closed\" : \"failed\";\n\t\tthis.error = this.stderrTail ? `${errorMessage(error)}\\n${this.stderrTail}` : errorMessage(error);\n\t\tthis.changed();\n\t\treturn new Error(`MCP server \"${this.entry.name}\" failed to connect: ${this.error}`);\n\t}\n\n\t/** The transport dropped. The next call reconnects; until then the status shows why. */\n\tprivate handleClientClose(client: McpClient, stdio: StdioTransport | undefined): void {\n\t\tif (this.client !== client || this.closed) return;\n\t\tthis.client = undefined;\n\t\tthis.state = \"disconnected\";\n\t\tconst stderr = stdio?.stderr.trim().slice(-STDERR_TAIL_CHARS);\n\t\tthis.error = stderr ? `Connection closed\\n${stderr}` : \"Connection closed\";\n\t\tthis.changed();\n\t}\n\n\tprivate async refreshTools(client: McpClient): Promise<void> {\n\t\ttry {\n\t\t\tconst tools = await client.listTools();\n\t\t\tif (this.client !== client || this.closed) return;\n\t\t\tthis.tools = tools;\n\t\t\tthis.onTools(this);\n\t\t} catch (error) {\n\t\t\tthis.error = `Failed to refresh tools: ${errorMessage(error)}`;\n\t\t}\n\t\tthis.changed();\n\t}\n\n\t/** Resolves once no transport of this server is open, including one that was still connecting. */\n\tasync close(): Promise<void> {\n\t\tthis.shutdown.abort();\n\t\tthis.state = \"closed\";\n\t\tthis.changed();\n\t\tconst client = this.client;\n\t\tthis.client = undefined;\n\t\tawait Promise.all([client?.close().catch(() => undefined), this.opening?.catch(() => undefined)]);\n\t\t// A refresh the server already answered may have rotated the refresh token; exiting before the\n\t\t// new tokens are saved would lose the grant.\n\t\tawait this.authProvider?.settled();\n\t}\n}\n"]}
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import type { AgentToolResult } from "@draht/agent-core";
13
13
  import type { ImageContent, TextContent } from "@draht/ai";
14
- import { type CallToolResult, type ContentBlock, type McpRequestOptions, type Tool as McpTool } from "@draht/mcp";
14
+ import { type CallToolResult, type ContentBlock, type McpOutputSaver, type McpRequestOptions, type Tool as McpTool } from "@draht/mcp";
15
15
  import type { TSchema } from "typebox";
16
16
  import type { ToolDefinition, ToolExposure, ToolNamespace, ToolRenderers } from "../../core/extensions/types.ts";
17
17
  import { READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.ts";
@@ -22,8 +22,6 @@ import type { McpExposure } from "./config.ts";
22
22
  * description; they differ only in which tool the MCP extension activates to reach them.
23
23
  */
24
24
  export declare function toToolExposure(exposure: McpExposure): ToolExposure;
25
- /** Model-facing text of an MCP result beyond this is cut in the middle. */
26
- export declare const MCP_OUTPUT_MAX_BYTES: number;
27
25
  /** Tool that reads the resources named by resource links. */
28
26
  export { READ_MCP_RESOURCE_TOOL };
29
27
  export interface McpToolDetails {
@@ -32,35 +30,16 @@ export interface McpToolDetails {
32
30
  /** Temp file with the full text output, when the model-facing text was truncated. */
33
31
  fullOutputPath?: string;
34
32
  }
35
- /**
36
- * Saves the full text of a truncated result, or a binary resource, and returns the file path.
37
- * `extension` includes the dot, for example `.txt`.
38
- */
39
- export type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;
33
+ /** Saves the full text of a truncated result, or a binary resource, to a temp file and returns its path. */
40
34
  export declare function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string>;
41
35
  export interface McpToolCaller {
42
36
  callTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;
43
37
  }
44
- /**
45
- * `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex,
46
- * everything but `[A-Za-z0-9_]` becomes `_`, so the name is also the identifier codemode scripts
47
- * call it by. `isTaken` reports names used by a different MCP tool: sanitizing can map two tools to
48
- * one name (`a-b` and `a_b`), which then get the hash suffix.
49
- */
50
- export declare function createMcpToolName(server: string, tool: string, isTaken?: (name: string) => boolean): string;
51
38
  /**
52
39
  * Output schema of every MCP tool: the `CallToolResult` scripts receive (without `_meta`, which
53
40
  * {@link convertMcpResult} drops), with the tool's own output schema as `structuredContent`.
54
41
  */
55
42
  export declare function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema;
56
- /**
57
- * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in
58
- * Codex's truncation format, followed by the path of the file with the full text; images follow it.
59
- */
60
- export declare function limitMcpContent(content: (TextContent | ImageContent)[], saveOutput?: McpOutputSaver): Promise<{
61
- content: (TextContent | ImageContent)[];
62
- fullOutputPath?: string;
63
- }>;
64
43
  export interface ConvertMcpResultOptions {
65
44
  /** Saves truncated text and binary resources. Default: a temp file. */
66
45
  saveOutput?: McpOutputSaver;