alchemylab-opencode 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/LICENSE +21 -0
  2. package/NODE_COMPAT.md +184 -0
  3. package/package.json +112 -0
  4. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/migration.sql +90 -0
  5. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/snapshot.json +796 -0
  6. package/packages/opencode/migration/20260211171708_add_project_commands/migration.sql +1 -0
  7. package/packages/opencode/migration/20260211171708_add_project_commands/snapshot.json +806 -0
  8. package/packages/opencode/migration/20260213144116_wakeful_the_professor/migration.sql +11 -0
  9. package/packages/opencode/migration/20260213144116_wakeful_the_professor/snapshot.json +897 -0
  10. package/packages/opencode/migration/20260225215848_workspace/migration.sql +7 -0
  11. package/packages/opencode/migration/20260225215848_workspace/snapshot.json +959 -0
  12. package/packages/opencode/migration/20260227213759_add_session_workspace_id/migration.sql +2 -0
  13. package/packages/opencode/migration/20260227213759_add_session_workspace_id/snapshot.json +983 -0
  14. package/packages/opencode/migration/20260228203230_blue_harpoon/migration.sql +17 -0
  15. package/packages/opencode/migration/20260228203230_blue_harpoon/snapshot.json +1102 -0
  16. package/packages/opencode/migration/20260303231226_add_workspace_fields/migration.sql +5 -0
  17. package/packages/opencode/migration/20260303231226_add_workspace_fields/snapshot.json +1013 -0
  18. package/packages/opencode/migration/20260309230000_move_org_to_state/migration.sql +3 -0
  19. package/packages/opencode/migration/20260309230000_move_org_to_state/snapshot.json +1156 -0
  20. package/packages/opencode/migration/20260312043431_session_message_cursor/migration.sql +4 -0
  21. package/packages/opencode/migration/20260312043431_session_message_cursor/snapshot.json +1168 -0
  22. package/packages/opencode/migration/20260323234822_events/migration.sql +13 -0
  23. package/packages/opencode/migration/20260323234822_events/snapshot.json +1271 -0
  24. package/packages/opencode/package.json +140 -0
  25. package/packages/opencode/src/account/account.sql.ts +39 -0
  26. package/packages/opencode/src/account/index.ts +463 -0
  27. package/packages/opencode/src/account/repo.ts +163 -0
  28. package/packages/opencode/src/account/schema.ts +91 -0
  29. package/packages/opencode/src/acp/README.md +174 -0
  30. package/packages/opencode/src/acp/agent.ts +1847 -0
  31. package/packages/opencode/src/acp/session.ts +116 -0
  32. package/packages/opencode/src/acp/types.ts +24 -0
  33. package/packages/opencode/src/agent/agent.ts +420 -0
  34. package/packages/opencode/src/agent/generate.txt +75 -0
  35. package/packages/opencode/src/agent/prompt/compaction.txt +15 -0
  36. package/packages/opencode/src/agent/prompt/explore.txt +18 -0
  37. package/packages/opencode/src/agent/prompt/summary.txt +11 -0
  38. package/packages/opencode/src/agent/prompt/title.txt +44 -0
  39. package/packages/opencode/src/auth/index.ts +110 -0
  40. package/packages/opencode/src/bus/bus-event.ts +40 -0
  41. package/packages/opencode/src/bus/global.ts +10 -0
  42. package/packages/opencode/src/bus/index.ts +185 -0
  43. package/packages/opencode/src/cli/bootstrap.ts +17 -0
  44. package/packages/opencode/src/cli/cmd/cmd.ts +7 -0
  45. package/packages/opencode/src/cli/cmd/run.ts +689 -0
  46. package/packages/opencode/src/cli/cmd/serve.ts +24 -0
  47. package/packages/opencode/src/cli/cmd/tui/event.ts +49 -0
  48. package/packages/opencode/src/cli/effect/prompt.ts +25 -0
  49. package/packages/opencode/src/cli/error.ts +46 -0
  50. package/packages/opencode/src/cli/heap.ts +59 -0
  51. package/packages/opencode/src/cli/logo.ts +6 -0
  52. package/packages/opencode/src/cli/network.ts +60 -0
  53. package/packages/opencode/src/cli/ui.ts +133 -0
  54. package/packages/opencode/src/cli/upgrade.ts +31 -0
  55. package/packages/opencode/src/command/index.ts +195 -0
  56. package/packages/opencode/src/command/template/initialize.txt +66 -0
  57. package/packages/opencode/src/command/template/review.txt +101 -0
  58. package/packages/opencode/src/config/config.ts +1599 -0
  59. package/packages/opencode/src/config/console-state.ts +15 -0
  60. package/packages/opencode/src/config/markdown.ts +99 -0
  61. package/packages/opencode/src/config/paths.ts +167 -0
  62. package/packages/opencode/src/config/tui-migrate.ts +155 -0
  63. package/packages/opencode/src/config/tui-schema.ts +37 -0
  64. package/packages/opencode/src/config/tui.ts +179 -0
  65. package/packages/opencode/src/control-plane/adaptors/index.ts +20 -0
  66. package/packages/opencode/src/control-plane/adaptors/worktree.ts +42 -0
  67. package/packages/opencode/src/control-plane/schema.ts +17 -0
  68. package/packages/opencode/src/control-plane/sse.ts +66 -0
  69. package/packages/opencode/src/control-plane/types.ts +32 -0
  70. package/packages/opencode/src/control-plane/workspace.sql.ts +17 -0
  71. package/packages/opencode/src/control-plane/workspace.ts +168 -0
  72. package/packages/opencode/src/effect/cross-spawn-spawner.ts +502 -0
  73. package/packages/opencode/src/effect/instance-ref.ts +6 -0
  74. package/packages/opencode/src/effect/instance-registry.ts +12 -0
  75. package/packages/opencode/src/effect/instance-state.ts +82 -0
  76. package/packages/opencode/src/effect/run-service.ts +33 -0
  77. package/packages/opencode/src/effect/runner.ts +216 -0
  78. package/packages/opencode/src/env/index.ts +28 -0
  79. package/packages/opencode/src/file/ignore.ts +82 -0
  80. package/packages/opencode/src/file/index.ts +686 -0
  81. package/packages/opencode/src/file/protected.ts +59 -0
  82. package/packages/opencode/src/file/ripgrep.ts +376 -0
  83. package/packages/opencode/src/file/time.ts +133 -0
  84. package/packages/opencode/src/file/watcher.ts +173 -0
  85. package/packages/opencode/src/filesystem/index.ts +236 -0
  86. package/packages/opencode/src/flag/flag.ts +156 -0
  87. package/packages/opencode/src/format/formatter.ts +413 -0
  88. package/packages/opencode/src/format/index.ts +203 -0
  89. package/packages/opencode/src/git/index.ts +303 -0
  90. package/packages/opencode/src/global/index.ts +56 -0
  91. package/packages/opencode/src/id/id.ts +85 -0
  92. package/packages/opencode/src/ide/index.ts +74 -0
  93. package/packages/opencode/src/installation/index.ts +355 -0
  94. package/packages/opencode/src/installation/meta.ts +7 -0
  95. package/packages/opencode/src/lsp/client.ts +252 -0
  96. package/packages/opencode/src/lsp/index.ts +558 -0
  97. package/packages/opencode/src/lsp/language.ts +120 -0
  98. package/packages/opencode/src/lsp/launch.ts +21 -0
  99. package/packages/opencode/src/lsp/server.ts +1968 -0
  100. package/packages/opencode/src/mcp/auth.ts +173 -0
  101. package/packages/opencode/src/mcp/index.ts +931 -0
  102. package/packages/opencode/src/mcp/oauth-callback.ts +216 -0
  103. package/packages/opencode/src/mcp/oauth-provider.ts +185 -0
  104. package/packages/opencode/src/node-loader.mjs +104 -0
  105. package/packages/opencode/src/node-preload.mjs +39 -0
  106. package/packages/opencode/src/node.ts +1 -0
  107. package/packages/opencode/src/npm/index.ts +188 -0
  108. package/packages/opencode/src/patch/index.ts +680 -0
  109. package/packages/opencode/src/permission/arity.ts +163 -0
  110. package/packages/opencode/src/permission/evaluate.ts +15 -0
  111. package/packages/opencode/src/permission/index.ts +325 -0
  112. package/packages/opencode/src/permission/schema.ts +17 -0
  113. package/packages/opencode/src/plugin/cloudflare.ts +67 -0
  114. package/packages/opencode/src/plugin/codex.ts +608 -0
  115. package/packages/opencode/src/plugin/github-copilot/copilot.ts +361 -0
  116. package/packages/opencode/src/plugin/github-copilot/models.ts +144 -0
  117. package/packages/opencode/src/plugin/index.ts +299 -0
  118. package/packages/opencode/src/plugin/install.ts +439 -0
  119. package/packages/opencode/src/plugin/loader.ts +174 -0
  120. package/packages/opencode/src/plugin/meta.ts +188 -0
  121. package/packages/opencode/src/plugin/shared.ts +323 -0
  122. package/packages/opencode/src/project/bootstrap.ts +31 -0
  123. package/packages/opencode/src/project/instance.ts +175 -0
  124. package/packages/opencode/src/project/project.sql.ts +16 -0
  125. package/packages/opencode/src/project/project.ts +519 -0
  126. package/packages/opencode/src/project/schema.ts +16 -0
  127. package/packages/opencode/src/project/state.ts +70 -0
  128. package/packages/opencode/src/project/vcs.ts +240 -0
  129. package/packages/opencode/src/provider/auth.ts +253 -0
  130. package/packages/opencode/src/provider/error.ts +197 -0
  131. package/packages/opencode/src/provider/models.ts +162 -0
  132. package/packages/opencode/src/provider/provider.ts +1709 -0
  133. package/packages/opencode/src/provider/schema.ts +38 -0
  134. package/packages/opencode/src/provider/sdk/copilot/README.md +5 -0
  135. package/packages/opencode/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  136. package/packages/opencode/src/provider/sdk/copilot/chat/get-response-metadata.ts +15 -0
  137. package/packages/opencode/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  138. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +64 -0
  139. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  140. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +28 -0
  141. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  142. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  143. package/packages/opencode/src/provider/sdk/copilot/copilot-provider.ts +100 -0
  144. package/packages/opencode/src/provider/sdk/copilot/index.ts +2 -0
  145. package/packages/opencode/src/provider/sdk/copilot/openai-compatible-error.ts +27 -0
  146. package/packages/opencode/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  147. package/packages/opencode/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  148. package/packages/opencode/src/provider/sdk/copilot/responses/openai-config.ts +18 -0
  149. package/packages/opencode/src/provider/sdk/copilot/responses/openai-error.ts +22 -0
  150. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  151. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +1769 -0
  152. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  153. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  154. package/packages/opencode/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  155. package/packages/opencode/src/provider/sdk/copilot/responses/tool/file-search.ts +127 -0
  156. package/packages/opencode/src/provider/sdk/copilot/responses/tool/image-generation.ts +114 -0
  157. package/packages/opencode/src/provider/sdk/copilot/responses/tool/local-shell.ts +64 -0
  158. package/packages/opencode/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  159. package/packages/opencode/src/provider/sdk/copilot/responses/tool/web-search.ts +102 -0
  160. package/packages/opencode/src/provider/transform.ts +1050 -0
  161. package/packages/opencode/src/pty/index.ts +397 -0
  162. package/packages/opencode/src/pty/pty.node.ts +27 -0
  163. package/packages/opencode/src/pty/pty.ts +25 -0
  164. package/packages/opencode/src/pty/schema.ts +17 -0
  165. package/packages/opencode/src/question/index.ts +224 -0
  166. package/packages/opencode/src/question/schema.ts +17 -0
  167. package/packages/opencode/src/run.ts +28 -0
  168. package/packages/opencode/src/serve.ts +45 -0
  169. package/packages/opencode/src/server/error.ts +36 -0
  170. package/packages/opencode/src/server/event.ts +7 -0
  171. package/packages/opencode/src/server/instance.ts +324 -0
  172. package/packages/opencode/src/server/mdns.ts +60 -0
  173. package/packages/opencode/src/server/middleware.ts +33 -0
  174. package/packages/opencode/src/server/projectors.ts +28 -0
  175. package/packages/opencode/src/server/proxy.ts +131 -0
  176. package/packages/opencode/src/server/router.ts +105 -0
  177. package/packages/opencode/src/server/routes/config.ts +92 -0
  178. package/packages/opencode/src/server/routes/event.ts +83 -0
  179. package/packages/opencode/src/server/routes/experimental.ts +374 -0
  180. package/packages/opencode/src/server/routes/file.ts +197 -0
  181. package/packages/opencode/src/server/routes/global.ts +312 -0
  182. package/packages/opencode/src/server/routes/mcp.ts +225 -0
  183. package/packages/opencode/src/server/routes/permission.ts +69 -0
  184. package/packages/opencode/src/server/routes/project.ts +118 -0
  185. package/packages/opencode/src/server/routes/provider.ts +171 -0
  186. package/packages/opencode/src/server/routes/pty.ts +210 -0
  187. package/packages/opencode/src/server/routes/question.ts +99 -0
  188. package/packages/opencode/src/server/routes/session.ts +1030 -0
  189. package/packages/opencode/src/server/routes/tui.ts +379 -0
  190. package/packages/opencode/src/server/routes/workspace.ts +94 -0
  191. package/packages/opencode/src/server/server.ts +353 -0
  192. package/packages/opencode/src/session/compaction.ts +428 -0
  193. package/packages/opencode/src/session/index.ts +887 -0
  194. package/packages/opencode/src/session/instruction.ts +258 -0
  195. package/packages/opencode/src/session/llm.ts +354 -0
  196. package/packages/opencode/src/session/message-v2.ts +1031 -0
  197. package/packages/opencode/src/session/message.ts +191 -0
  198. package/packages/opencode/src/session/overflow.ts +22 -0
  199. package/packages/opencode/src/session/processor.ts +523 -0
  200. package/packages/opencode/src/session/projectors.ts +135 -0
  201. package/packages/opencode/src/session/prompt/anthropic.txt +105 -0
  202. package/packages/opencode/src/session/prompt/beast.txt +147 -0
  203. package/packages/opencode/src/session/prompt/build-switch.txt +5 -0
  204. package/packages/opencode/src/session/prompt/codex.txt +79 -0
  205. package/packages/opencode/src/session/prompt/copilot-gpt-5.txt +143 -0
  206. package/packages/opencode/src/session/prompt/default.txt +105 -0
  207. package/packages/opencode/src/session/prompt/gemini.txt +155 -0
  208. package/packages/opencode/src/session/prompt/gpt.txt +107 -0
  209. package/packages/opencode/src/session/prompt/kimi.txt +95 -0
  210. package/packages/opencode/src/session/prompt/max-steps.txt +16 -0
  211. package/packages/opencode/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  212. package/packages/opencode/src/session/prompt/plan.txt +26 -0
  213. package/packages/opencode/src/session/prompt/trinity.txt +97 -0
  214. package/packages/opencode/src/session/prompt.ts +1911 -0
  215. package/packages/opencode/src/session/retry.ts +106 -0
  216. package/packages/opencode/src/session/revert.ts +176 -0
  217. package/packages/opencode/src/session/schema.ts +38 -0
  218. package/packages/opencode/src/session/session.sql.ts +103 -0
  219. package/packages/opencode/src/session/status.ts +102 -0
  220. package/packages/opencode/src/session/summary.ts +177 -0
  221. package/packages/opencode/src/session/system.ts +76 -0
  222. package/packages/opencode/src/session/todo.ts +95 -0
  223. package/packages/opencode/src/share/share-next.ts +369 -0
  224. package/packages/opencode/src/share/share.sql.ts +13 -0
  225. package/packages/opencode/src/shell/shell.ts +110 -0
  226. package/packages/opencode/src/skill/discovery.ts +116 -0
  227. package/packages/opencode/src/skill/index.ts +277 -0
  228. package/packages/opencode/src/snapshot/index.ts +726 -0
  229. package/packages/opencode/src/sql.d.ts +4 -0
  230. package/packages/opencode/src/storage/db.node.ts +8 -0
  231. package/packages/opencode/src/storage/db.ts +177 -0
  232. package/packages/opencode/src/storage/json-migration.ts +425 -0
  233. package/packages/opencode/src/storage/schema.sql.ts +10 -0
  234. package/packages/opencode/src/storage/schema.ts +5 -0
  235. package/packages/opencode/src/storage/storage.ts +353 -0
  236. package/packages/opencode/src/sync/README.md +179 -0
  237. package/packages/opencode/src/sync/event.sql.ts +16 -0
  238. package/packages/opencode/src/sync/index.ts +263 -0
  239. package/packages/opencode/src/sync/schema.ts +14 -0
  240. package/packages/opencode/src/tool/apply_patch.ts +281 -0
  241. package/packages/opencode/src/tool/apply_patch.txt +33 -0
  242. package/packages/opencode/src/tool/bash.ts +496 -0
  243. package/packages/opencode/src/tool/bash.txt +117 -0
  244. package/packages/opencode/src/tool/batch.ts +183 -0
  245. package/packages/opencode/src/tool/batch.txt +24 -0
  246. package/packages/opencode/src/tool/codesearch.ts +132 -0
  247. package/packages/opencode/src/tool/codesearch.txt +12 -0
  248. package/packages/opencode/src/tool/edit.ts +667 -0
  249. package/packages/opencode/src/tool/edit.txt +10 -0
  250. package/packages/opencode/src/tool/external-directory.ts +46 -0
  251. package/packages/opencode/src/tool/glob.ts +78 -0
  252. package/packages/opencode/src/tool/glob.txt +6 -0
  253. package/packages/opencode/src/tool/grep.ts +156 -0
  254. package/packages/opencode/src/tool/grep.txt +8 -0
  255. package/packages/opencode/src/tool/invalid.ts +17 -0
  256. package/packages/opencode/src/tool/ls.ts +121 -0
  257. package/packages/opencode/src/tool/ls.txt +1 -0
  258. package/packages/opencode/src/tool/lsp.ts +97 -0
  259. package/packages/opencode/src/tool/lsp.txt +19 -0
  260. package/packages/opencode/src/tool/multiedit.ts +46 -0
  261. package/packages/opencode/src/tool/multiedit.txt +41 -0
  262. package/packages/opencode/src/tool/plan-enter.txt +14 -0
  263. package/packages/opencode/src/tool/plan-exit.txt +13 -0
  264. package/packages/opencode/src/tool/plan.ts +131 -0
  265. package/packages/opencode/src/tool/question.ts +46 -0
  266. package/packages/opencode/src/tool/question.txt +10 -0
  267. package/packages/opencode/src/tool/read.ts +332 -0
  268. package/packages/opencode/src/tool/read.txt +14 -0
  269. package/packages/opencode/src/tool/registry.ts +265 -0
  270. package/packages/opencode/src/tool/schema.ts +17 -0
  271. package/packages/opencode/src/tool/skill.ts +105 -0
  272. package/packages/opencode/src/tool/task.ts +166 -0
  273. package/packages/opencode/src/tool/task.txt +60 -0
  274. package/packages/opencode/src/tool/todo.ts +48 -0
  275. package/packages/opencode/src/tool/todowrite.txt +167 -0
  276. package/packages/opencode/src/tool/tool.ts +112 -0
  277. package/packages/opencode/src/tool/truncate.ts +144 -0
  278. package/packages/opencode/src/tool/truncation-dir.ts +4 -0
  279. package/packages/opencode/src/tool/webfetch.ts +206 -0
  280. package/packages/opencode/src/tool/webfetch.txt +13 -0
  281. package/packages/opencode/src/tool/websearch.ts +150 -0
  282. package/packages/opencode/src/tool/websearch.txt +14 -0
  283. package/packages/opencode/src/tool/write.ts +84 -0
  284. package/packages/opencode/src/tool/write.txt +8 -0
  285. package/packages/opencode/src/util/abort.ts +35 -0
  286. package/packages/opencode/src/util/archive.ts +17 -0
  287. package/packages/opencode/src/util/color.ts +19 -0
  288. package/packages/opencode/src/util/context.ts +25 -0
  289. package/packages/opencode/src/util/data-url.ts +9 -0
  290. package/packages/opencode/src/util/defer.ts +12 -0
  291. package/packages/opencode/src/util/effect-http-client.ts +11 -0
  292. package/packages/opencode/src/util/effect-zod.ts +98 -0
  293. package/packages/opencode/src/util/error.ts +77 -0
  294. package/packages/opencode/src/util/filesystem.ts +245 -0
  295. package/packages/opencode/src/util/flock.ts +333 -0
  296. package/packages/opencode/src/util/fn.ts +21 -0
  297. package/packages/opencode/src/util/format.ts +20 -0
  298. package/packages/opencode/src/util/glob.ts +34 -0
  299. package/packages/opencode/src/util/hash.ts +7 -0
  300. package/packages/opencode/src/util/iife.ts +3 -0
  301. package/packages/opencode/src/util/keybind.ts +103 -0
  302. package/packages/opencode/src/util/lazy.ts +23 -0
  303. package/packages/opencode/src/util/locale.ts +81 -0
  304. package/packages/opencode/src/util/lock.ts +98 -0
  305. package/packages/opencode/src/util/log.ts +182 -0
  306. package/packages/opencode/src/util/network.ts +9 -0
  307. package/packages/opencode/src/util/process.ts +176 -0
  308. package/packages/opencode/src/util/queue.ts +32 -0
  309. package/packages/opencode/src/util/record.ts +3 -0
  310. package/packages/opencode/src/util/rpc.ts +66 -0
  311. package/packages/opencode/src/util/schema.ts +53 -0
  312. package/packages/opencode/src/util/scrap.ts +10 -0
  313. package/packages/opencode/src/util/signal.ts +12 -0
  314. package/packages/opencode/src/util/timeout.ts +14 -0
  315. package/packages/opencode/src/util/token.ts +7 -0
  316. package/packages/opencode/src/util/update-schema.ts +13 -0
  317. package/packages/opencode/src/util/which.ts +14 -0
  318. package/packages/opencode/src/util/wildcard.ts +59 -0
  319. package/packages/opencode/src/worktree/index.ts +612 -0
  320. package/packages/plugin/package.json +38 -0
  321. package/packages/plugin/src/example.ts +18 -0
  322. package/packages/plugin/src/index.ts +282 -0
  323. package/packages/plugin/src/shell.ts +136 -0
  324. package/packages/plugin/src/tool.ts +38 -0
  325. package/packages/plugin/src/tui.ts +508 -0
  326. package/packages/script/package.json +16 -0
  327. package/packages/script/src/index.ts +77 -0
  328. package/packages/sdk/package.json +33 -0
  329. package/packages/sdk/src/client.ts +55 -0
  330. package/packages/sdk/src/gen/client/client.gen.ts +212 -0
  331. package/packages/sdk/src/gen/client/index.ts +25 -0
  332. package/packages/sdk/src/gen/client/types.gen.ts +222 -0
  333. package/packages/sdk/src/gen/client/utils.gen.ts +287 -0
  334. package/packages/sdk/src/gen/client.gen.ts +22 -0
  335. package/packages/sdk/src/gen/core/auth.gen.ts +41 -0
  336. package/packages/sdk/src/gen/core/bodySerializer.gen.ts +74 -0
  337. package/packages/sdk/src/gen/core/params.gen.ts +144 -0
  338. package/packages/sdk/src/gen/core/pathSerializer.gen.ts +167 -0
  339. package/packages/sdk/src/gen/core/queryKeySerializer.gen.ts +111 -0
  340. package/packages/sdk/src/gen/core/serverSentEvents.gen.ts +210 -0
  341. package/packages/sdk/src/gen/core/types.gen.ts +91 -0
  342. package/packages/sdk/src/gen/core/utils.gen.ts +109 -0
  343. package/packages/sdk/src/gen/sdk.gen.ts +1197 -0
  344. package/packages/sdk/src/gen/types.gen.ts +3904 -0
  345. package/packages/sdk/src/index.ts +21 -0
  346. package/packages/sdk/src/process.ts +31 -0
  347. package/packages/sdk/src/server.ts +134 -0
  348. package/packages/sdk/src/v2/client.ts +81 -0
  349. package/packages/sdk/src/v2/gen/client/client.gen.ts +285 -0
  350. package/packages/sdk/src/v2/gen/client/index.ts +25 -0
  351. package/packages/sdk/src/v2/gen/client/types.gen.ts +202 -0
  352. package/packages/sdk/src/v2/gen/client/utils.gen.ts +289 -0
  353. package/packages/sdk/src/v2/gen/client.gen.ts +18 -0
  354. package/packages/sdk/src/v2/gen/core/auth.gen.ts +41 -0
  355. package/packages/sdk/src/v2/gen/core/bodySerializer.gen.ts +82 -0
  356. package/packages/sdk/src/v2/gen/core/params.gen.ts +169 -0
  357. package/packages/sdk/src/v2/gen/core/pathSerializer.gen.ts +167 -0
  358. package/packages/sdk/src/v2/gen/core/queryKeySerializer.gen.ts +111 -0
  359. package/packages/sdk/src/v2/gen/core/serverSentEvents.gen.ts +239 -0
  360. package/packages/sdk/src/v2/gen/core/types.gen.ts +86 -0
  361. package/packages/sdk/src/v2/gen/core/utils.gen.ts +137 -0
  362. package/packages/sdk/src/v2/gen/sdk.gen.ts +4223 -0
  363. package/packages/sdk/src/v2/gen/types.gen.ts +5265 -0
  364. package/packages/sdk/src/v2/index.ts +21 -0
  365. package/packages/sdk/src/v2/server.ts +134 -0
  366. package/packages/util/package.json +20 -0
  367. package/packages/util/src/array.ts +10 -0
  368. package/packages/util/src/binary.ts +41 -0
  369. package/packages/util/src/encode.ts +51 -0
  370. package/packages/util/src/error.ts +54 -0
  371. package/packages/util/src/fn.ts +11 -0
  372. package/packages/util/src/identifier.ts +48 -0
  373. package/packages/util/src/iife.ts +3 -0
  374. package/packages/util/src/lazy.ts +11 -0
  375. package/packages/util/src/module.ts +10 -0
  376. package/packages/util/src/path.ts +37 -0
  377. package/packages/util/src/retry.ts +41 -0
  378. package/packages/util/src/slug.ts +74 -0
  379. package/postinstall.cjs +55 -0
@@ -0,0 +1,931 @@
1
+ import { dynamicTool, type Tool, jsonSchema, type JSONSchema7 } from "ai"
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js"
3
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
4
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
5
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
6
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
7
+ import {
8
+ CallToolResultSchema,
9
+ type Tool as MCPToolDef,
10
+ ToolListChangedNotificationSchema,
11
+ } from "@modelcontextprotocol/sdk/types.js"
12
+ import { Config } from "../config/config"
13
+ import { Log } from "../util/log"
14
+ import { NamedError } from "@opencode-ai/util/error"
15
+ import z from "zod/v4"
16
+ import { Instance } from "../project/instance"
17
+ import { Installation } from "../installation"
18
+ import { withTimeout } from "@/util/timeout"
19
+ import { AppFileSystem } from "@/filesystem"
20
+ import { McpOAuthProvider } from "./oauth-provider"
21
+ import { McpOAuthCallback } from "./oauth-callback"
22
+ import { McpAuth } from "./auth"
23
+ import { BusEvent } from "../bus/bus-event"
24
+ import { Bus } from "@/bus"
25
+ import { TuiEvent } from "@/cli/cmd/tui/event"
26
+ import open from "open"
27
+ import { Effect, Exit, Layer, Option, ServiceMap, Stream } from "effect"
28
+ import { InstanceState } from "@/effect/instance-state"
29
+ import { makeRuntime } from "@/effect/run-service"
30
+ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
31
+ import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
32
+
33
+ export namespace MCP {
34
+ const log = Log.create({ service: "mcp" })
35
+ const DEFAULT_TIMEOUT = 30_000
36
+
37
+ export const Resource = z
38
+ .object({
39
+ name: z.string(),
40
+ uri: z.string(),
41
+ description: z.string().optional(),
42
+ mimeType: z.string().optional(),
43
+ client: z.string(),
44
+ })
45
+ .meta({ ref: "McpResource" })
46
+ export type Resource = z.infer<typeof Resource>
47
+
48
+ export const ToolsChanged = BusEvent.define(
49
+ "mcp.tools.changed",
50
+ z.object({
51
+ server: z.string(),
52
+ }),
53
+ )
54
+
55
+ export const BrowserOpenFailed = BusEvent.define(
56
+ "mcp.browser.open.failed",
57
+ z.object({
58
+ mcpName: z.string(),
59
+ url: z.string(),
60
+ }),
61
+ )
62
+
63
+ export const Failed = NamedError.create(
64
+ "MCPFailed",
65
+ z.object({
66
+ name: z.string(),
67
+ }),
68
+ )
69
+
70
+ type MCPClient = Client
71
+
72
+ export const Status = z
73
+ .discriminatedUnion("status", [
74
+ z
75
+ .object({
76
+ status: z.literal("connected"),
77
+ })
78
+ .meta({
79
+ ref: "MCPStatusConnected",
80
+ }),
81
+ z
82
+ .object({
83
+ status: z.literal("disabled"),
84
+ })
85
+ .meta({
86
+ ref: "MCPStatusDisabled",
87
+ }),
88
+ z
89
+ .object({
90
+ status: z.literal("failed"),
91
+ error: z.string(),
92
+ })
93
+ .meta({
94
+ ref: "MCPStatusFailed",
95
+ }),
96
+ z
97
+ .object({
98
+ status: z.literal("needs_auth"),
99
+ })
100
+ .meta({
101
+ ref: "MCPStatusNeedsAuth",
102
+ }),
103
+ z
104
+ .object({
105
+ status: z.literal("needs_client_registration"),
106
+ error: z.string(),
107
+ })
108
+ .meta({
109
+ ref: "MCPStatusNeedsClientRegistration",
110
+ }),
111
+ ])
112
+ .meta({
113
+ ref: "MCPStatus",
114
+ })
115
+ export type Status = z.infer<typeof Status>
116
+
117
+ // Store transports for OAuth servers to allow finishing auth
118
+ type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
119
+ const pendingOAuthTransports = new Map<string, TransportWithAuth>()
120
+
121
+ // Prompt cache types
122
+ type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
123
+ type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
124
+ type McpEntry = NonNullable<Config.Info["mcp"]>[string]
125
+
126
+ function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
127
+ return typeof entry === "object" && entry !== null && "type" in entry
128
+ }
129
+
130
+ const sanitize = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, "_")
131
+
132
+ // Thread-local context for passing session identity to MCP tool calls.
133
+ // Set by prompt.ts before each tool execution, read by callTool below.
134
+ export let currentToolContext: { sessionId?: string; messageId?: string } = {}
135
+
136
+ // Convert MCP tool definition to AI SDK Tool type
137
+ function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Tool {
138
+ const inputSchema = mcpTool.inputSchema
139
+
140
+ // Spread first, then override type to ensure it's always "object"
141
+ const schema: JSONSchema7 = {
142
+ ...(inputSchema as JSONSchema7),
143
+ type: "object",
144
+ properties: (inputSchema.properties ?? {}) as JSONSchema7["properties"],
145
+ additionalProperties: false,
146
+ }
147
+
148
+ return dynamicTool({
149
+ description: mcpTool.description ?? "",
150
+ inputSchema: jsonSchema(schema),
151
+ execute: async (args: unknown) => {
152
+ // Include session identity in _meta so the MCP server knows which session
153
+ // this tool call belongs to (avoids races when MCP processes are shared)
154
+ const _meta: Record<string, unknown> = {}
155
+ if (currentToolContext.sessionId) _meta.sessionId = currentToolContext.sessionId
156
+ if (currentToolContext.messageId) _meta.messageId = currentToolContext.messageId
157
+ return client.callTool(
158
+ {
159
+ name: mcpTool.name,
160
+ arguments: (args || {}) as Record<string, unknown>,
161
+ _meta: Object.keys(_meta).length > 0 ? _meta : undefined,
162
+ },
163
+ CallToolResultSchema,
164
+ {
165
+ resetTimeoutOnProgress: true,
166
+ timeout,
167
+ },
168
+ )
169
+ },
170
+ })
171
+ }
172
+
173
+ function defs(key: string, client: MCPClient, timeout?: number) {
174
+ return Effect.tryPromise({
175
+ try: () => withTimeout(client.listTools(), timeout ?? DEFAULT_TIMEOUT),
176
+ catch: (err) => (err instanceof Error ? err : new Error(String(err))),
177
+ }).pipe(
178
+ Effect.map((result) => result.tools),
179
+ Effect.catch((err) => {
180
+ log.error("failed to get tools from client", { key, error: err })
181
+ return Effect.succeed(undefined)
182
+ }),
183
+ )
184
+ }
185
+
186
+ function fetchFromClient<T extends { name: string }>(
187
+ clientName: string,
188
+ client: Client,
189
+ listFn: (c: Client) => Promise<T[]>,
190
+ label: string,
191
+ ) {
192
+ return Effect.tryPromise({
193
+ try: () => listFn(client),
194
+ catch: (e: any) => {
195
+ log.error(`failed to get ${label}`, { clientName, error: e.message })
196
+ return e
197
+ },
198
+ }).pipe(
199
+ Effect.map((items) => {
200
+ const out: Record<string, T & { client: string }> = {}
201
+ const sanitizedClient = sanitize(clientName)
202
+ for (const item of items) {
203
+ out[sanitizedClient + ":" + sanitize(item.name)] = { ...item, client: clientName }
204
+ }
205
+ return out
206
+ }),
207
+ Effect.orElseSucceed(() => undefined),
208
+ )
209
+ }
210
+
211
+ interface CreateResult {
212
+ mcpClient?: MCPClient
213
+ status: Status
214
+ defs?: MCPToolDef[]
215
+ }
216
+
217
+ // --- Effect Service ---
218
+
219
+ interface State {
220
+ status: Record<string, Status>
221
+ clients: Record<string, MCPClient>
222
+ defs: Record<string, MCPToolDef[]>
223
+ }
224
+
225
+ export interface Interface {
226
+ readonly status: () => Effect.Effect<Record<string, Status>>
227
+ readonly clients: () => Effect.Effect<Record<string, MCPClient>>
228
+ readonly tools: () => Effect.Effect<Record<string, Tool>>
229
+ readonly prompts: () => Effect.Effect<Record<string, PromptInfo & { client: string }>>
230
+ readonly resources: () => Effect.Effect<Record<string, ResourceInfo & { client: string }>>
231
+ readonly add: (name: string, mcp: Config.Mcp) => Effect.Effect<{ status: Record<string, Status> | Status }>
232
+ readonly connect: (name: string) => Effect.Effect<void>
233
+ readonly disconnect: (name: string) => Effect.Effect<void>
234
+ readonly getPrompt: (
235
+ clientName: string,
236
+ name: string,
237
+ args?: Record<string, string>,
238
+ ) => Effect.Effect<Awaited<ReturnType<MCPClient["getPrompt"]>> | undefined>
239
+ readonly readResource: (
240
+ clientName: string,
241
+ resourceUri: string,
242
+ ) => Effect.Effect<Awaited<ReturnType<MCPClient["readResource"]>> | undefined>
243
+ readonly startAuth: (mcpName: string) => Effect.Effect<{ authorizationUrl: string; oauthState: string }>
244
+ readonly authenticate: (mcpName: string) => Effect.Effect<Status>
245
+ readonly finishAuth: (mcpName: string, authorizationCode: string) => Effect.Effect<Status>
246
+ readonly removeAuth: (mcpName: string) => Effect.Effect<void>
247
+ readonly supportsOAuth: (mcpName: string) => Effect.Effect<boolean>
248
+ readonly hasStoredTokens: (mcpName: string) => Effect.Effect<boolean>
249
+ readonly getAuthStatus: (mcpName: string) => Effect.Effect<AuthStatus>
250
+ }
251
+
252
+ export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/MCP") {}
253
+
254
+ export const layer = Layer.effect(
255
+ Service,
256
+ Effect.gen(function* () {
257
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
258
+ const auth = yield* McpAuth.Service
259
+ const bus = yield* Bus.Service
260
+
261
+ type Transport = StdioClientTransport | StreamableHTTPClientTransport | SSEClientTransport
262
+
263
+ /**
264
+ * Connect a client via the given transport with resource safety:
265
+ * on failure the transport is closed; on success the caller owns it.
266
+ */
267
+ const connectTransport = (transport: Transport, timeout: number) =>
268
+ Effect.acquireUseRelease(
269
+ Effect.succeed(transport),
270
+ (t) =>
271
+ Effect.tryPromise({
272
+ try: () => {
273
+ const client = new Client({ name: "opencode", version: Installation.VERSION })
274
+ return withTimeout(client.connect(t), timeout).then(() => client)
275
+ },
276
+ catch: (e) => (e instanceof Error ? e : new Error(String(e))),
277
+ }),
278
+ (t, exit) => (Exit.isFailure(exit) ? Effect.tryPromise(() => t.close()).pipe(Effect.ignore) : Effect.void),
279
+ )
280
+
281
+ const DISABLED_RESULT: CreateResult = { status: { status: "disabled" } }
282
+
283
+ const connectRemote = Effect.fn("MCP.connectRemote")(function* (
284
+ key: string,
285
+ mcp: Config.Mcp & { type: "remote" },
286
+ ) {
287
+ const oauthDisabled = mcp.oauth === false
288
+ const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
289
+ let authProvider: McpOAuthProvider | undefined
290
+
291
+ if (!oauthDisabled) {
292
+ authProvider = new McpOAuthProvider(
293
+ key,
294
+ mcp.url,
295
+ {
296
+ clientId: oauthConfig?.clientId,
297
+ clientSecret: oauthConfig?.clientSecret,
298
+ scope: oauthConfig?.scope,
299
+ },
300
+ {
301
+ onRedirect: async (url) => {
302
+ log.info("oauth redirect requested", { key, url: url.toString() })
303
+ },
304
+ },
305
+ )
306
+ }
307
+
308
+ const transports: Array<{ name: string; transport: TransportWithAuth }> = [
309
+ {
310
+ name: "StreamableHTTP",
311
+ transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
312
+ authProvider,
313
+ requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
314
+ }),
315
+ },
316
+ {
317
+ name: "SSE",
318
+ transport: new SSEClientTransport(new URL(mcp.url), {
319
+ authProvider,
320
+ requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
321
+ }),
322
+ },
323
+ ]
324
+
325
+ const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
326
+ let lastStatus: Status | undefined
327
+
328
+ for (const { name, transport } of transports) {
329
+ const result = yield* connectTransport(transport, connectTimeout).pipe(
330
+ Effect.map((client) => ({ client, transportName: name })),
331
+ Effect.catch((error) => {
332
+ const lastError = error instanceof Error ? error : new Error(String(error))
333
+ const isAuthError =
334
+ error instanceof UnauthorizedError || (authProvider && lastError.message.includes("OAuth"))
335
+
336
+ if (isAuthError) {
337
+ log.info("mcp server requires authentication", { key, transport: name })
338
+
339
+ if (lastError.message.includes("registration") || lastError.message.includes("client_id")) {
340
+ lastStatus = {
341
+ status: "needs_client_registration" as const,
342
+ error: "Server does not support dynamic client registration. Please provide clientId in config.",
343
+ }
344
+ return bus
345
+ .publish(TuiEvent.ToastShow, {
346
+ title: "MCP Authentication Required",
347
+ message: `Server "${key}" requires a pre-registered client ID. Add clientId to your config.`,
348
+ variant: "warning",
349
+ duration: 8000,
350
+ })
351
+ .pipe(Effect.ignore, Effect.as(undefined))
352
+ } else {
353
+ pendingOAuthTransports.set(key, transport)
354
+ lastStatus = { status: "needs_auth" as const }
355
+ return bus
356
+ .publish(TuiEvent.ToastShow, {
357
+ title: "MCP Authentication Required",
358
+ message: `Server "${key}" requires authentication. Run: opencode mcp auth ${key}`,
359
+ variant: "warning",
360
+ duration: 8000,
361
+ })
362
+ .pipe(Effect.ignore, Effect.as(undefined))
363
+ }
364
+ }
365
+
366
+ log.debug("transport connection failed", {
367
+ key,
368
+ transport: name,
369
+ url: mcp.url,
370
+ error: lastError.message,
371
+ })
372
+ lastStatus = { status: "failed" as const, error: lastError.message }
373
+ return Effect.succeed(undefined)
374
+ }),
375
+ )
376
+ if (result) {
377
+ log.info("connected", { key, transport: result.transportName })
378
+ return { client: result.client as MCPClient | undefined, status: { status: "connected" } as Status }
379
+ }
380
+ // If this was an auth error, stop trying other transports
381
+ if (lastStatus?.status === "needs_auth" || lastStatus?.status === "needs_client_registration") break
382
+ }
383
+
384
+ return {
385
+ client: undefined as MCPClient | undefined,
386
+ status: (lastStatus ?? { status: "failed", error: "Unknown error" }) as Status,
387
+ }
388
+ })
389
+
390
+ const connectLocal = Effect.fn("MCP.connectLocal")(function* (key: string, mcp: Config.Mcp & { type: "local" }) {
391
+ const [cmd, ...args] = mcp.command
392
+ const cwd = Instance.directory
393
+ const transport = new StdioClientTransport({
394
+ stderr: "pipe",
395
+ command: cmd,
396
+ args,
397
+ cwd,
398
+ env: {
399
+ ...process.env,
400
+ ...(cmd === "opencode" ? { BUN_BE_BUN: "1" } : {}),
401
+ ...mcp.environment,
402
+ },
403
+ })
404
+ transport.stderr?.on("data", (chunk: Buffer) => {
405
+ log.info(`mcp stderr: ${chunk.toString()}`, { key })
406
+ })
407
+
408
+ const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
409
+ return yield* connectTransport(transport, connectTimeout).pipe(
410
+ Effect.map((client): { client: MCPClient | undefined; status: Status } => ({
411
+ client,
412
+ status: { status: "connected" },
413
+ })),
414
+ Effect.catch((error): Effect.Effect<{ client: MCPClient | undefined; status: Status }> => {
415
+ const msg = error instanceof Error ? error.message : String(error)
416
+ log.error("local mcp startup failed", { key, command: mcp.command, cwd, error: msg })
417
+ return Effect.succeed({ client: undefined, status: { status: "failed", error: msg } })
418
+ }),
419
+ )
420
+ })
421
+
422
+ const create = Effect.fn("MCP.create")(function* (key: string, mcp: Config.Mcp) {
423
+ if (mcp.enabled === false) {
424
+ log.info("mcp server disabled", { key })
425
+ return DISABLED_RESULT
426
+ }
427
+
428
+ log.info("found", { key, type: mcp.type })
429
+
430
+ const { client: mcpClient, status } =
431
+ mcp.type === "remote"
432
+ ? yield* connectRemote(key, mcp as Config.Mcp & { type: "remote" })
433
+ : yield* connectLocal(key, mcp as Config.Mcp & { type: "local" })
434
+
435
+ if (!mcpClient) {
436
+ return { status } satisfies CreateResult
437
+ }
438
+
439
+ const listed = yield* defs(key, mcpClient, mcp.timeout)
440
+ if (!listed) {
441
+ yield* Effect.tryPromise(() => mcpClient.close()).pipe(Effect.ignore)
442
+ return { status: { status: "failed", error: "Failed to get tools" } } satisfies CreateResult
443
+ }
444
+
445
+ log.info("create() successfully created client", { key, toolCount: listed.length })
446
+ return { mcpClient, status, defs: listed } satisfies CreateResult
447
+ })
448
+ const cfgSvc = yield* Config.Service
449
+
450
+ const descendants = Effect.fnUntraced(
451
+ function* (pid: number) {
452
+ if (process.platform === "win32") return [] as number[]
453
+ const pids: number[] = []
454
+ const queue = [pid]
455
+ while (queue.length > 0) {
456
+ const current = queue.shift()!
457
+ const handle = yield* spawner.spawn(
458
+ ChildProcess.make("pgrep", ["-P", String(current)], { stdin: "ignore" }),
459
+ )
460
+ const text = yield* Stream.mkString(Stream.decodeText(handle.stdout))
461
+ yield* handle.exitCode
462
+ for (const tok of text.split("\n")) {
463
+ const cpid = parseInt(tok, 10)
464
+ if (!isNaN(cpid) && !pids.includes(cpid)) {
465
+ pids.push(cpid)
466
+ queue.push(cpid)
467
+ }
468
+ }
469
+ }
470
+ return pids
471
+ },
472
+ Effect.scoped,
473
+ Effect.catch(() => Effect.succeed([] as number[])),
474
+ )
475
+
476
+ function watch(s: State, name: string, client: MCPClient, timeout?: number) {
477
+ client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
478
+ log.info("tools list changed notification received", { server: name })
479
+ if (s.clients[name] !== client || s.status[name]?.status !== "connected") return
480
+
481
+ const listed = await Effect.runPromise(defs(name, client, timeout))
482
+ if (!listed) return
483
+ if (s.clients[name] !== client || s.status[name]?.status !== "connected") return
484
+
485
+ s.defs[name] = listed
486
+ await Effect.runPromise(bus.publish(ToolsChanged, { server: name }).pipe(Effect.ignore))
487
+ })
488
+ }
489
+
490
+ const state = yield* InstanceState.make<State>(
491
+ Effect.fn("MCP.state")(function* () {
492
+ const cfg = yield* cfgSvc.get()
493
+ const config = cfg.mcp ?? {}
494
+ const s: State = {
495
+ status: {},
496
+ clients: {},
497
+ defs: {},
498
+ }
499
+
500
+ yield* Effect.forEach(
501
+ Object.entries(config),
502
+ ([key, mcp]) =>
503
+ Effect.gen(function* () {
504
+ if (!isMcpConfigured(mcp)) {
505
+ log.error("Ignoring MCP config entry without type", { key })
506
+ return
507
+ }
508
+
509
+ if (mcp.enabled === false) {
510
+ s.status[key] = { status: "disabled" }
511
+ return
512
+ }
513
+
514
+ const result = yield* create(key, mcp).pipe(Effect.catch(() => Effect.succeed(undefined)))
515
+ if (!result) return
516
+
517
+ s.status[key] = result.status
518
+ if (result.mcpClient) {
519
+ s.clients[key] = result.mcpClient
520
+ s.defs[key] = result.defs!
521
+ watch(s, key, result.mcpClient, mcp.timeout)
522
+ }
523
+ }),
524
+ { concurrency: "unbounded" },
525
+ )
526
+
527
+ yield* Effect.addFinalizer(() =>
528
+ Effect.gen(function* () {
529
+ yield* Effect.forEach(
530
+ Object.values(s.clients),
531
+ (client) =>
532
+ Effect.gen(function* () {
533
+ const pid = (client.transport as any)?.pid
534
+ if (typeof pid === "number") {
535
+ const pids = yield* descendants(pid)
536
+ for (const dpid of pids) {
537
+ try {
538
+ process.kill(dpid, "SIGTERM")
539
+ } catch {}
540
+ }
541
+ }
542
+ yield* Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
543
+ }),
544
+ { concurrency: "unbounded" },
545
+ )
546
+ pendingOAuthTransports.clear()
547
+ }),
548
+ )
549
+
550
+ return s
551
+ }),
552
+ )
553
+
554
+ function closeClient(s: State, name: string) {
555
+ const client = s.clients[name]
556
+ delete s.defs[name]
557
+ if (!client) return Effect.void
558
+ return Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
559
+ }
560
+
561
+ const status = Effect.fn("MCP.status")(function* () {
562
+ const s = yield* InstanceState.get(state)
563
+
564
+ const cfg = yield* cfgSvc.get()
565
+ const config = cfg.mcp ?? {}
566
+ const result: Record<string, Status> = {}
567
+
568
+ for (const [key, mcp] of Object.entries(config)) {
569
+ if (!isMcpConfigured(mcp)) continue
570
+ result[key] = s.status[key] ?? { status: "disabled" }
571
+ }
572
+
573
+ return result
574
+ })
575
+
576
+ const clients = Effect.fn("MCP.clients")(function* () {
577
+ const s = yield* InstanceState.get(state)
578
+ return s.clients
579
+ })
580
+
581
+ const createAndStore = Effect.fn("MCP.createAndStore")(function* (name: string, mcp: Config.Mcp) {
582
+ const s = yield* InstanceState.get(state)
583
+ const result = yield* create(name, mcp)
584
+
585
+ s.status[name] = result.status
586
+ if (!result.mcpClient) {
587
+ yield* closeClient(s, name)
588
+ delete s.clients[name]
589
+ return result.status
590
+ }
591
+
592
+ yield* closeClient(s, name)
593
+ s.clients[name] = result.mcpClient
594
+ s.defs[name] = result.defs!
595
+ watch(s, name, result.mcpClient, mcp.timeout)
596
+ return result.status
597
+ })
598
+
599
+ const add = Effect.fn("MCP.add")(function* (name: string, mcp: Config.Mcp) {
600
+ yield* createAndStore(name, mcp)
601
+ const s = yield* InstanceState.get(state)
602
+ return { status: s.status }
603
+ })
604
+
605
+ const connect = Effect.fn("MCP.connect")(function* (name: string) {
606
+ const mcp = yield* getMcpConfig(name)
607
+ if (!mcp) {
608
+ log.error("MCP config not found or invalid", { name })
609
+ return
610
+ }
611
+ yield* createAndStore(name, { ...mcp, enabled: true })
612
+ })
613
+
614
+ const disconnect = Effect.fn("MCP.disconnect")(function* (name: string) {
615
+ const s = yield* InstanceState.get(state)
616
+ yield* closeClient(s, name)
617
+ delete s.clients[name]
618
+ s.status[name] = { status: "disabled" }
619
+ })
620
+
621
+ const tools = Effect.fn("MCP.tools")(function* () {
622
+ const result: Record<string, Tool> = {}
623
+ const s = yield* InstanceState.get(state)
624
+
625
+ const cfg = yield* cfgSvc.get()
626
+ const config = cfg.mcp ?? {}
627
+ const defaultTimeout = cfg.experimental?.mcp_timeout
628
+
629
+ const connectedClients = Object.entries(s.clients).filter(
630
+ ([clientName]) => s.status[clientName]?.status === "connected",
631
+ )
632
+
633
+ yield* Effect.forEach(
634
+ connectedClients,
635
+ ([clientName, client]) =>
636
+ Effect.gen(function* () {
637
+ const mcpConfig = config[clientName]
638
+ const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : undefined
639
+
640
+ const listed = s.defs[clientName]
641
+ if (!listed) {
642
+ log.warn("missing cached tools for connected server", { clientName })
643
+ return
644
+ }
645
+
646
+ const timeout = entry?.timeout ?? defaultTimeout
647
+ for (const mcpTool of listed) {
648
+ result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = convertMcpTool(mcpTool, client, timeout)
649
+ }
650
+ }),
651
+ { concurrency: "unbounded" },
652
+ )
653
+ return result
654
+ })
655
+
656
+ function collectFromConnected<T extends { name: string }>(
657
+ s: State,
658
+ listFn: (c: Client) => Promise<T[]>,
659
+ label: string,
660
+ ) {
661
+ return Effect.forEach(
662
+ Object.entries(s.clients).filter(([name]) => s.status[name]?.status === "connected"),
663
+ ([clientName, client]) =>
664
+ fetchFromClient(clientName, client, listFn, label).pipe(Effect.map((items) => Object.entries(items ?? {}))),
665
+ { concurrency: "unbounded" },
666
+ ).pipe(Effect.map((results) => Object.fromEntries<T & { client: string }>(results.flat())))
667
+ }
668
+
669
+ const prompts = Effect.fn("MCP.prompts")(function* () {
670
+ const s = yield* InstanceState.get(state)
671
+ return yield* collectFromConnected(s, (c) => c.listPrompts().then((r) => r.prompts), "prompts")
672
+ })
673
+
674
+ const resources = Effect.fn("MCP.resources")(function* () {
675
+ const s = yield* InstanceState.get(state)
676
+ return yield* collectFromConnected(s, (c) => c.listResources().then((r) => r.resources), "resources")
677
+ })
678
+
679
+ const withClient = Effect.fnUntraced(function* <A>(
680
+ clientName: string,
681
+ fn: (client: MCPClient) => Promise<A>,
682
+ label: string,
683
+ meta?: Record<string, unknown>,
684
+ ) {
685
+ const s = yield* InstanceState.get(state)
686
+ const client = s.clients[clientName]
687
+ if (!client) {
688
+ log.warn(`client not found for ${label}`, { clientName })
689
+ return undefined
690
+ }
691
+ return yield* Effect.tryPromise({
692
+ try: () => fn(client),
693
+ catch: (e: any) => {
694
+ log.error(`failed to ${label}`, { clientName, ...meta, error: e?.message })
695
+ return e
696
+ },
697
+ }).pipe(Effect.orElseSucceed(() => undefined))
698
+ })
699
+
700
+ const getPrompt = Effect.fn("MCP.getPrompt")(function* (
701
+ clientName: string,
702
+ name: string,
703
+ args?: Record<string, string>,
704
+ ) {
705
+ return yield* withClient(clientName, (client) => client.getPrompt({ name, arguments: args }), "getPrompt", {
706
+ promptName: name,
707
+ })
708
+ })
709
+
710
+ const readResource = Effect.fn("MCP.readResource")(function* (clientName: string, resourceUri: string) {
711
+ return yield* withClient(clientName, (client) => client.readResource({ uri: resourceUri }), "readResource", {
712
+ resourceUri,
713
+ })
714
+ })
715
+
716
+ const getMcpConfig = Effect.fnUntraced(function* (mcpName: string) {
717
+ const cfg = yield* cfgSvc.get()
718
+ const mcpConfig = cfg.mcp?.[mcpName]
719
+ if (!mcpConfig || !isMcpConfigured(mcpConfig)) return undefined
720
+ return mcpConfig
721
+ })
722
+
723
+ const startAuth = Effect.fn("MCP.startAuth")(function* (mcpName: string) {
724
+ const mcpConfig = yield* getMcpConfig(mcpName)
725
+ if (!mcpConfig) throw new Error(`MCP server ${mcpName} not found or disabled`)
726
+ if (mcpConfig.type !== "remote") throw new Error(`MCP server ${mcpName} is not a remote server`)
727
+ if (mcpConfig.oauth === false) throw new Error(`MCP server ${mcpName} has OAuth explicitly disabled`)
728
+
729
+ yield* Effect.promise(() => McpOAuthCallback.ensureRunning())
730
+
731
+ const oauthState = Array.from(crypto.getRandomValues(new Uint8Array(32)))
732
+ .map((b) => b.toString(16).padStart(2, "0"))
733
+ .join("")
734
+ yield* auth.updateOAuthState(mcpName, oauthState)
735
+ const oauthConfig = typeof mcpConfig.oauth === "object" ? mcpConfig.oauth : undefined
736
+ let capturedUrl: URL | undefined
737
+ const authProvider = new McpOAuthProvider(
738
+ mcpName,
739
+ mcpConfig.url,
740
+ {
741
+ clientId: oauthConfig?.clientId,
742
+ clientSecret: oauthConfig?.clientSecret,
743
+ scope: oauthConfig?.scope,
744
+ },
745
+ {
746
+ onRedirect: async (url) => {
747
+ capturedUrl = url
748
+ },
749
+ },
750
+ )
751
+
752
+ const transport = new StreamableHTTPClientTransport(new URL(mcpConfig.url), { authProvider })
753
+
754
+ return yield* Effect.tryPromise({
755
+ try: () => {
756
+ const client = new Client({ name: "opencode", version: Installation.VERSION })
757
+ return client.connect(transport).then(() => ({ authorizationUrl: "", oauthState }))
758
+ },
759
+ catch: (error) => error,
760
+ }).pipe(
761
+ Effect.catch((error) => {
762
+ if (error instanceof UnauthorizedError && capturedUrl) {
763
+ pendingOAuthTransports.set(mcpName, transport)
764
+ return Effect.succeed({ authorizationUrl: capturedUrl.toString(), oauthState })
765
+ }
766
+ return Effect.die(error)
767
+ }),
768
+ )
769
+ })
770
+
771
+ const authenticate = Effect.fn("MCP.authenticate")(function* (mcpName: string) {
772
+ const { authorizationUrl, oauthState } = yield* startAuth(mcpName)
773
+ if (!authorizationUrl) return { status: "connected" } as Status
774
+
775
+ log.info("opening browser for oauth", { mcpName, url: authorizationUrl, state: oauthState })
776
+
777
+ const callbackPromise = McpOAuthCallback.waitForCallback(oauthState, mcpName)
778
+
779
+ yield* Effect.tryPromise(() => open(authorizationUrl)).pipe(
780
+ Effect.flatMap((subprocess) =>
781
+ Effect.callback<void, Error>((resume) => {
782
+ const timer = setTimeout(() => resume(Effect.void), 500)
783
+ subprocess.on("error", (err) => {
784
+ clearTimeout(timer)
785
+ resume(Effect.fail(err))
786
+ })
787
+ subprocess.on("exit", (code) => {
788
+ if (code !== null && code !== 0) {
789
+ clearTimeout(timer)
790
+ resume(Effect.fail(new Error(`Browser open failed with exit code ${code}`)))
791
+ }
792
+ })
793
+ }),
794
+ ),
795
+ Effect.catch(() => {
796
+ log.warn("failed to open browser, user must open URL manually", { mcpName })
797
+ return bus.publish(BrowserOpenFailed, { mcpName, url: authorizationUrl }).pipe(Effect.ignore)
798
+ }),
799
+ )
800
+
801
+ const code = yield* Effect.promise(() => callbackPromise)
802
+
803
+ const storedState = yield* auth.getOAuthState(mcpName)
804
+ if (storedState !== oauthState) {
805
+ yield* auth.clearOAuthState(mcpName)
806
+ throw new Error("OAuth state mismatch - potential CSRF attack")
807
+ }
808
+ yield* auth.clearOAuthState(mcpName)
809
+ return yield* finishAuth(mcpName, code)
810
+ })
811
+
812
+ const finishAuth = Effect.fn("MCP.finishAuth")(function* (mcpName: string, authorizationCode: string) {
813
+ const transport = pendingOAuthTransports.get(mcpName)
814
+ if (!transport) throw new Error(`No pending OAuth flow for MCP server: ${mcpName}`)
815
+
816
+ const result = yield* Effect.tryPromise({
817
+ try: () => transport.finishAuth(authorizationCode).then(() => true as const),
818
+ catch: (error) => {
819
+ log.error("failed to finish oauth", { mcpName, error })
820
+ return error
821
+ },
822
+ }).pipe(Effect.option)
823
+
824
+ if (Option.isNone(result)) {
825
+ return { status: "failed", error: "OAuth completion failed" } as Status
826
+ }
827
+
828
+ yield* auth.clearCodeVerifier(mcpName)
829
+ pendingOAuthTransports.delete(mcpName)
830
+
831
+ const mcpConfig = yield* getMcpConfig(mcpName)
832
+ if (!mcpConfig) return { status: "failed", error: "MCP config not found after auth" } as Status
833
+
834
+ return yield* createAndStore(mcpName, mcpConfig)
835
+ })
836
+
837
+ const removeAuth = Effect.fn("MCP.removeAuth")(function* (mcpName: string) {
838
+ yield* auth.remove(mcpName)
839
+ McpOAuthCallback.cancelPending(mcpName)
840
+ pendingOAuthTransports.delete(mcpName)
841
+ log.info("removed oauth credentials", { mcpName })
842
+ })
843
+
844
+ const supportsOAuth = Effect.fn("MCP.supportsOAuth")(function* (mcpName: string) {
845
+ const mcpConfig = yield* getMcpConfig(mcpName)
846
+ if (!mcpConfig) return false
847
+ return mcpConfig.type === "remote" && mcpConfig.oauth !== false
848
+ })
849
+
850
+ const hasStoredTokens = Effect.fn("MCP.hasStoredTokens")(function* (mcpName: string) {
851
+ const entry = yield* auth.get(mcpName)
852
+ return !!entry?.tokens
853
+ })
854
+
855
+ const getAuthStatus = Effect.fn("MCP.getAuthStatus")(function* (mcpName: string) {
856
+ const entry = yield* auth.get(mcpName)
857
+ if (!entry?.tokens) return "not_authenticated" as AuthStatus
858
+ const expired = yield* auth.isTokenExpired(mcpName)
859
+ return (expired ? "expired" : "authenticated") as AuthStatus
860
+ })
861
+
862
+ return Service.of({
863
+ status,
864
+ clients,
865
+ tools,
866
+ prompts,
867
+ resources,
868
+ add,
869
+ connect,
870
+ disconnect,
871
+ getPrompt,
872
+ readResource,
873
+ startAuth,
874
+ authenticate,
875
+ finishAuth,
876
+ removeAuth,
877
+ supportsOAuth,
878
+ hasStoredTokens,
879
+ getAuthStatus,
880
+ })
881
+ }),
882
+ )
883
+
884
+ export type AuthStatus = "authenticated" | "expired" | "not_authenticated"
885
+
886
+ // --- Per-service runtime ---
887
+
888
+ export const defaultLayer = layer.pipe(
889
+ Layer.provide(McpAuth.layer),
890
+ Layer.provide(Bus.layer),
891
+ Layer.provide(Config.defaultLayer),
892
+ Layer.provide(CrossSpawnSpawner.defaultLayer),
893
+ Layer.provide(AppFileSystem.defaultLayer),
894
+ )
895
+
896
+ const { runPromise } = makeRuntime(Service, defaultLayer)
897
+
898
+ // --- Async facade functions ---
899
+
900
+ export const status = async () => runPromise((svc) => svc.status())
901
+
902
+ export const tools = async () => runPromise((svc) => svc.tools())
903
+
904
+ export const prompts = async () => runPromise((svc) => svc.prompts())
905
+
906
+ export const resources = async () => runPromise((svc) => svc.resources())
907
+
908
+ export const add = async (name: string, mcp: Config.Mcp) => runPromise((svc) => svc.add(name, mcp))
909
+
910
+ export const connect = async (name: string) => runPromise((svc) => svc.connect(name))
911
+
912
+ export const disconnect = async (name: string) => runPromise((svc) => svc.disconnect(name))
913
+
914
+ export const getPrompt = async (clientName: string, name: string, args?: Record<string, string>) =>
915
+ runPromise((svc) => svc.getPrompt(clientName, name, args))
916
+
917
+ export const startAuth = async (mcpName: string) => runPromise((svc) => svc.startAuth(mcpName))
918
+
919
+ export const authenticate = async (mcpName: string) => runPromise((svc) => svc.authenticate(mcpName))
920
+
921
+ export const finishAuth = async (mcpName: string, authorizationCode: string) =>
922
+ runPromise((svc) => svc.finishAuth(mcpName, authorizationCode))
923
+
924
+ export const removeAuth = async (mcpName: string) => runPromise((svc) => svc.removeAuth(mcpName))
925
+
926
+ export const supportsOAuth = async (mcpName: string) => runPromise((svc) => svc.supportsOAuth(mcpName))
927
+
928
+ export const hasStoredTokens = async (mcpName: string) => runPromise((svc) => svc.hasStoredTokens(mcpName))
929
+
930
+ export const getAuthStatus = async (mcpName: string) => runPromise((svc) => svc.getAuthStatus(mcpName))
931
+ }