@bloxystudios/bloxycode 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 (344) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +256 -0
  3. package/bin/bloxycode +84 -0
  4. package/package.json +133 -0
  5. package/src/acp/README.md +164 -0
  6. package/src/acp/agent.ts +1437 -0
  7. package/src/acp/session.ts +105 -0
  8. package/src/acp/types.ts +22 -0
  9. package/src/agent/agent.ts +356 -0
  10. package/src/agent/generate.txt +75 -0
  11. package/src/agent/prompt/bloxy.txt +46 -0
  12. package/src/agent/prompt/compaction.txt +12 -0
  13. package/src/agent/prompt/explore.txt +18 -0
  14. package/src/agent/prompt/summary.txt +11 -0
  15. package/src/agent/prompt/title.txt +44 -0
  16. package/src/auth/index.ts +73 -0
  17. package/src/bloxy/event.ts +41 -0
  18. package/src/bloxy/index.ts +5 -0
  19. package/src/bloxy/parser.ts +263 -0
  20. package/src/bloxy/prompt.ts +121 -0
  21. package/src/bloxy/runner.ts +193 -0
  22. package/src/bloxy/state.ts +246 -0
  23. package/src/bun/index.ts +134 -0
  24. package/src/bus/bus-event.ts +43 -0
  25. package/src/bus/global.ts +10 -0
  26. package/src/bus/index.ts +105 -0
  27. package/src/cli/bootstrap.ts +17 -0
  28. package/src/cli/cmd/acp.ts +69 -0
  29. package/src/cli/cmd/agent.ts +257 -0
  30. package/src/cli/cmd/auth.ts +400 -0
  31. package/src/cli/cmd/cmd.ts +7 -0
  32. package/src/cli/cmd/debug/agent.ts +167 -0
  33. package/src/cli/cmd/debug/config.ts +16 -0
  34. package/src/cli/cmd/debug/file.ts +97 -0
  35. package/src/cli/cmd/debug/index.ts +48 -0
  36. package/src/cli/cmd/debug/lsp.ts +52 -0
  37. package/src/cli/cmd/debug/ripgrep.ts +87 -0
  38. package/src/cli/cmd/debug/scrap.ts +16 -0
  39. package/src/cli/cmd/debug/skill.ts +16 -0
  40. package/src/cli/cmd/debug/snapshot.ts +52 -0
  41. package/src/cli/cmd/export.ts +88 -0
  42. package/src/cli/cmd/generate.ts +38 -0
  43. package/src/cli/cmd/github.ts +1548 -0
  44. package/src/cli/cmd/import.ts +98 -0
  45. package/src/cli/cmd/mcp.ts +755 -0
  46. package/src/cli/cmd/models.ts +77 -0
  47. package/src/cli/cmd/pr.ts +112 -0
  48. package/src/cli/cmd/run.ts +395 -0
  49. package/src/cli/cmd/serve.ts +20 -0
  50. package/src/cli/cmd/session.ts +135 -0
  51. package/src/cli/cmd/stats.ts +402 -0
  52. package/src/cli/cmd/tui/app.tsx +771 -0
  53. package/src/cli/cmd/tui/attach.ts +39 -0
  54. package/src/cli/cmd/tui/component/border.tsx +21 -0
  55. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  56. package/src/cli/cmd/tui/component/dialog-command.tsx +148 -0
  57. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  58. package/src/cli/cmd/tui/component/dialog-model.tsx +234 -0
  59. package/src/cli/cmd/tui/component/dialog-provider.tsx +256 -0
  60. package/src/cli/cmd/tui/component/dialog-session-list.tsx +114 -0
  61. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  62. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  63. package/src/cli/cmd/tui/component/dialog-status.tsx +164 -0
  64. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  65. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  66. package/src/cli/cmd/tui/component/logo.tsx +102 -0
  67. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +653 -0
  68. package/src/cli/cmd/tui/component/prompt/frecency.tsx +89 -0
  69. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  70. package/src/cli/cmd/tui/component/prompt/index.tsx +1138 -0
  71. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  72. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  73. package/src/cli/cmd/tui/component/tips.tsx +153 -0
  74. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  75. package/src/cli/cmd/tui/context/args.tsx +14 -0
  76. package/src/cli/cmd/tui/context/directory.ts +13 -0
  77. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  78. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  79. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  80. package/src/cli/cmd/tui/context/kv.tsx +52 -0
  81. package/src/cli/cmd/tui/context/local.tsx +402 -0
  82. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  83. package/src/cli/cmd/tui/context/route.tsx +46 -0
  84. package/src/cli/cmd/tui/context/sdk.tsx +94 -0
  85. package/src/cli/cmd/tui/context/sync.tsx +470 -0
  86. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  87. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  88. package/src/cli/cmd/tui/context/theme/bloxycode.json +245 -0
  89. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  90. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  91. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  92. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  93. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  94. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  95. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  96. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  97. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  98. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  99. package/src/cli/cmd/tui/context/theme/gruvbox.json +242 -0
  100. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  101. package/src/cli/cmd/tui/context/theme/lucent-orng.json +237 -0
  102. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  103. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  104. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  105. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  106. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  107. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  108. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  109. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  110. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  111. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  112. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  113. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  114. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  115. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  116. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  117. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  118. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  119. package/src/cli/cmd/tui/context/theme.tsx +1152 -0
  120. package/src/cli/cmd/tui/event.ts +48 -0
  121. package/src/cli/cmd/tui/routes/home.tsx +140 -0
  122. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  123. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  124. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  125. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  126. package/src/cli/cmd/tui/routes/session/footer.tsx +91 -0
  127. package/src/cli/cmd/tui/routes/session/header.tsx +142 -0
  128. package/src/cli/cmd/tui/routes/session/index.tsx +2048 -0
  129. package/src/cli/cmd/tui/routes/session/permission.tsx +508 -0
  130. package/src/cli/cmd/tui/routes/session/question.tsx +453 -0
  131. package/src/cli/cmd/tui/routes/session/sidebar.tsx +313 -0
  132. package/src/cli/cmd/tui/thread.ts +165 -0
  133. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  134. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  135. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +204 -0
  136. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  137. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  138. package/src/cli/cmd/tui/ui/dialog-select.tsx +385 -0
  139. package/src/cli/cmd/tui/ui/dialog.tsx +167 -0
  140. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  141. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  142. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  143. package/src/cli/cmd/tui/util/clipboard.ts +160 -0
  144. package/src/cli/cmd/tui/util/editor.ts +32 -0
  145. package/src/cli/cmd/tui/util/signal.ts +7 -0
  146. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  147. package/src/cli/cmd/tui/util/transcript.ts +98 -0
  148. package/src/cli/cmd/tui/worker.ts +152 -0
  149. package/src/cli/cmd/uninstall.ts +357 -0
  150. package/src/cli/cmd/upgrade.ts +73 -0
  151. package/src/cli/cmd/web.ts +81 -0
  152. package/src/cli/error.ts +57 -0
  153. package/src/cli/network.ts +53 -0
  154. package/src/cli/ui.ts +86 -0
  155. package/src/cli/upgrade.ts +25 -0
  156. package/src/command/index.ts +173 -0
  157. package/src/command/template/bloxy-resume.txt +15 -0
  158. package/src/command/template/bloxy-status.txt +25 -0
  159. package/src/command/template/bloxy-validate.txt +22 -0
  160. package/src/command/template/bloxy.txt +14 -0
  161. package/src/command/template/initialize.txt +10 -0
  162. package/src/command/template/review.txt +99 -0
  163. package/src/config/config.ts +1367 -0
  164. package/src/config/markdown.ts +93 -0
  165. package/src/env/index.ts +26 -0
  166. package/src/file/ignore.ts +83 -0
  167. package/src/file/index.ts +415 -0
  168. package/src/file/ripgrep.ts +407 -0
  169. package/src/file/time.ts +69 -0
  170. package/src/file/watcher.ts +127 -0
  171. package/src/flag/flag.ts +79 -0
  172. package/src/format/formatter.ts +357 -0
  173. package/src/format/index.ts +137 -0
  174. package/src/global/index.ts +55 -0
  175. package/src/id/id.ts +83 -0
  176. package/src/ide/index.ts +76 -0
  177. package/src/index.ts +159 -0
  178. package/src/installation/index.ts +246 -0
  179. package/src/lsp/client.ts +252 -0
  180. package/src/lsp/index.ts +485 -0
  181. package/src/lsp/language.ts +119 -0
  182. package/src/lsp/server.ts +2046 -0
  183. package/src/mcp/auth.ts +135 -0
  184. package/src/mcp/index.ts +934 -0
  185. package/src/mcp/oauth-callback.ts +200 -0
  186. package/src/mcp/oauth-provider.ts +154 -0
  187. package/src/patch/index.ts +680 -0
  188. package/src/permission/arity.ts +163 -0
  189. package/src/permission/index.ts +210 -0
  190. package/src/permission/next.ts +280 -0
  191. package/src/plugin/antigravity.ts +378 -0
  192. package/src/plugin/codex.ts +506 -0
  193. package/src/plugin/copilot.ts +298 -0
  194. package/src/plugin/index.ts +136 -0
  195. package/src/project/bootstrap.ts +35 -0
  196. package/src/project/instance.ts +91 -0
  197. package/src/project/project.ts +371 -0
  198. package/src/project/state.ts +66 -0
  199. package/src/project/vcs.ts +76 -0
  200. package/src/provider/auth.ts +147 -0
  201. package/src/provider/models-snapshot.ts +2 -0
  202. package/src/provider/models.ts +133 -0
  203. package/src/provider/provider.ts +1241 -0
  204. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  205. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  206. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
  207. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  208. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  209. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  210. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  211. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  212. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1732 -0
  213. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  214. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  215. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  216. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  217. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  218. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  219. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  220. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  221. package/src/provider/transform.ts +741 -0
  222. package/src/pty/index.ts +241 -0
  223. package/src/question/index.ts +171 -0
  224. package/src/scheduler/index.ts +61 -0
  225. package/src/server/error.ts +36 -0
  226. package/src/server/event.ts +7 -0
  227. package/src/server/mdns.ts +59 -0
  228. package/src/server/routes/config.ts +92 -0
  229. package/src/server/routes/experimental.ts +208 -0
  230. package/src/server/routes/file.ts +197 -0
  231. package/src/server/routes/global.ts +135 -0
  232. package/src/server/routes/mcp.ts +225 -0
  233. package/src/server/routes/permission.ts +68 -0
  234. package/src/server/routes/project.ts +82 -0
  235. package/src/server/routes/provider.ts +165 -0
  236. package/src/server/routes/pty.ts +169 -0
  237. package/src/server/routes/question.ts +98 -0
  238. package/src/server/routes/session.ts +939 -0
  239. package/src/server/routes/tui.ts +379 -0
  240. package/src/server/server.ts +604 -0
  241. package/src/session/compaction.ts +225 -0
  242. package/src/session/fallback.ts +246 -0
  243. package/src/session/index.ts +498 -0
  244. package/src/session/instruction.ts +164 -0
  245. package/src/session/llm.ts +298 -0
  246. package/src/session/message-v2.ts +747 -0
  247. package/src/session/message.ts +189 -0
  248. package/src/session/processor.ts +450 -0
  249. package/src/session/prompt/anthropic-20250930.txt +166 -0
  250. package/src/session/prompt/anthropic.txt +105 -0
  251. package/src/session/prompt/beast.txt +147 -0
  252. package/src/session/prompt/build-switch.txt +5 -0
  253. package/src/session/prompt/codex_header.txt +79 -0
  254. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  255. package/src/session/prompt/gemini.txt +155 -0
  256. package/src/session/prompt/max-steps.txt +16 -0
  257. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  258. package/src/session/prompt/plan.txt +26 -0
  259. package/src/session/prompt/qwen.txt +109 -0
  260. package/src/session/prompt.ts +1822 -0
  261. package/src/session/retry.ts +99 -0
  262. package/src/session/revert.ts +121 -0
  263. package/src/session/status.ts +100 -0
  264. package/src/session/summary.ts +217 -0
  265. package/src/session/system.ts +52 -0
  266. package/src/session/todo.ts +37 -0
  267. package/src/share/share-next.ts +200 -0
  268. package/src/share/share.ts +92 -0
  269. package/src/shell/shell.ts +67 -0
  270. package/src/skill/index.ts +1 -0
  271. package/src/skill/skill.ts +135 -0
  272. package/src/snapshot/index.ts +236 -0
  273. package/src/storage/storage.ts +227 -0
  274. package/src/tool/apply_patch.ts +281 -0
  275. package/src/tool/apply_patch.txt +33 -0
  276. package/src/tool/bash.ts +258 -0
  277. package/src/tool/bash.txt +115 -0
  278. package/src/tool/batch.ts +175 -0
  279. package/src/tool/batch.txt +24 -0
  280. package/src/tool/bloxy-control.ts +123 -0
  281. package/src/tool/bloxy-control.txt +13 -0
  282. package/src/tool/codesearch.ts +132 -0
  283. package/src/tool/codesearch.txt +12 -0
  284. package/src/tool/edit.ts +655 -0
  285. package/src/tool/edit.txt +10 -0
  286. package/src/tool/external-directory.ts +32 -0
  287. package/src/tool/glob.ts +77 -0
  288. package/src/tool/glob.txt +6 -0
  289. package/src/tool/grep.ts +154 -0
  290. package/src/tool/grep.txt +8 -0
  291. package/src/tool/invalid.ts +17 -0
  292. package/src/tool/ls.ts +121 -0
  293. package/src/tool/ls.txt +1 -0
  294. package/src/tool/lsp.ts +96 -0
  295. package/src/tool/lsp.txt +19 -0
  296. package/src/tool/multiedit.ts +46 -0
  297. package/src/tool/multiedit.txt +41 -0
  298. package/src/tool/plan-enter.txt +14 -0
  299. package/src/tool/plan-exit.txt +13 -0
  300. package/src/tool/plan.ts +130 -0
  301. package/src/tool/question.ts +33 -0
  302. package/src/tool/question.txt +10 -0
  303. package/src/tool/read.ts +211 -0
  304. package/src/tool/read.txt +12 -0
  305. package/src/tool/registry.ts +161 -0
  306. package/src/tool/skill.ts +82 -0
  307. package/src/tool/task.ts +191 -0
  308. package/src/tool/task.txt +60 -0
  309. package/src/tool/todo.ts +53 -0
  310. package/src/tool/todoread.txt +14 -0
  311. package/src/tool/todowrite.txt +167 -0
  312. package/src/tool/tool.ts +89 -0
  313. package/src/tool/truncation.ts +106 -0
  314. package/src/tool/webfetch.ts +188 -0
  315. package/src/tool/webfetch.txt +13 -0
  316. package/src/tool/websearch.ts +150 -0
  317. package/src/tool/websearch.txt +14 -0
  318. package/src/tool/write.ts +85 -0
  319. package/src/tool/write.txt +8 -0
  320. package/src/util/archive.ts +16 -0
  321. package/src/util/binary.ts +41 -0
  322. package/src/util/color.ts +19 -0
  323. package/src/util/context.ts +25 -0
  324. package/src/util/defer.ts +12 -0
  325. package/src/util/error.ts +54 -0
  326. package/src/util/eventloop.ts +20 -0
  327. package/src/util/filesystem.ts +93 -0
  328. package/src/util/fn.ts +11 -0
  329. package/src/util/format.ts +20 -0
  330. package/src/util/iife.ts +3 -0
  331. package/src/util/keybind.ts +103 -0
  332. package/src/util/lazy.ts +23 -0
  333. package/src/util/locale.ts +81 -0
  334. package/src/util/lock.ts +98 -0
  335. package/src/util/log.ts +180 -0
  336. package/src/util/queue.ts +32 -0
  337. package/src/util/rpc.ts +66 -0
  338. package/src/util/scrap.ts +10 -0
  339. package/src/util/signal.ts +12 -0
  340. package/src/util/slug.ts +74 -0
  341. package/src/util/timeout.ts +14 -0
  342. package/src/util/token.ts +7 -0
  343. package/src/util/wildcard.ts +56 -0
  344. package/src/worktree/index.ts +549 -0
@@ -0,0 +1,934 @@
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 "@/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 { McpOAuthProvider } from "./oauth-provider"
20
+ import { McpOAuthCallback } from "./oauth-callback"
21
+ import { McpAuth } from "./auth"
22
+ import { BusEvent } from "../bus/bus-event"
23
+ import { Bus } from "@/bus"
24
+ import { TuiEvent } from "@/cli/cmd/tui/event"
25
+ import open from "open"
26
+
27
+ export namespace MCP {
28
+ const log = Log.create({ service: "mcp" })
29
+ const DEFAULT_TIMEOUT = 30_000
30
+
31
+ export const Resource = z
32
+ .object({
33
+ name: z.string(),
34
+ uri: z.string(),
35
+ description: z.string().optional(),
36
+ mimeType: z.string().optional(),
37
+ client: z.string(),
38
+ })
39
+ .meta({ ref: "McpResource" })
40
+ export type Resource = z.infer<typeof Resource>
41
+
42
+ export const ToolsChanged = BusEvent.define(
43
+ "mcp.tools.changed",
44
+ z.object({
45
+ server: z.string(),
46
+ }),
47
+ )
48
+
49
+ export const BrowserOpenFailed = BusEvent.define(
50
+ "mcp.browser.open.failed",
51
+ z.object({
52
+ mcpName: z.string(),
53
+ url: z.string(),
54
+ }),
55
+ )
56
+
57
+ export const Failed = NamedError.create(
58
+ "MCPFailed",
59
+ z.object({
60
+ name: z.string(),
61
+ }),
62
+ )
63
+
64
+ type MCPClient = Client
65
+
66
+ export const Status = z
67
+ .discriminatedUnion("status", [
68
+ z
69
+ .object({
70
+ status: z.literal("connected"),
71
+ })
72
+ .meta({
73
+ ref: "MCPStatusConnected",
74
+ }),
75
+ z
76
+ .object({
77
+ status: z.literal("disabled"),
78
+ })
79
+ .meta({
80
+ ref: "MCPStatusDisabled",
81
+ }),
82
+ z
83
+ .object({
84
+ status: z.literal("failed"),
85
+ error: z.string(),
86
+ })
87
+ .meta({
88
+ ref: "MCPStatusFailed",
89
+ }),
90
+ z
91
+ .object({
92
+ status: z.literal("needs_auth"),
93
+ })
94
+ .meta({
95
+ ref: "MCPStatusNeedsAuth",
96
+ }),
97
+ z
98
+ .object({
99
+ status: z.literal("needs_client_registration"),
100
+ error: z.string(),
101
+ })
102
+ .meta({
103
+ ref: "MCPStatusNeedsClientRegistration",
104
+ }),
105
+ ])
106
+ .meta({
107
+ ref: "MCPStatus",
108
+ })
109
+ export type Status = z.infer<typeof Status>
110
+
111
+ // Register notification handlers for MCP client
112
+ function registerNotificationHandlers(client: MCPClient, serverName: string) {
113
+ client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
114
+ log.info("tools list changed notification received", { server: serverName })
115
+ Bus.publish(ToolsChanged, { server: serverName })
116
+ })
117
+ }
118
+
119
+ // Convert MCP tool definition to AI SDK Tool type
120
+ async function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Promise<Tool> {
121
+ const inputSchema = mcpTool.inputSchema
122
+
123
+ // Spread first, then override type to ensure it's always "object"
124
+ const schema: JSONSchema7 = {
125
+ ...(inputSchema as JSONSchema7),
126
+ type: "object",
127
+ properties: (inputSchema.properties ?? {}) as JSONSchema7["properties"],
128
+ additionalProperties: false,
129
+ }
130
+
131
+ return dynamicTool({
132
+ description: mcpTool.description ?? "",
133
+ inputSchema: jsonSchema(schema),
134
+ execute: async (args: unknown) => {
135
+ return client.callTool(
136
+ {
137
+ name: mcpTool.name,
138
+ arguments: args as Record<string, unknown>,
139
+ },
140
+ CallToolResultSchema,
141
+ {
142
+ resetTimeoutOnProgress: true,
143
+ timeout,
144
+ },
145
+ )
146
+ },
147
+ })
148
+ }
149
+
150
+ // Store transports for OAuth servers to allow finishing auth
151
+ type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
152
+ const pendingOAuthTransports = new Map<string, TransportWithAuth>()
153
+
154
+ // Prompt cache types
155
+ type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
156
+
157
+ type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
158
+ type McpEntry = NonNullable<Config.Info["mcp"]>[string]
159
+ function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
160
+ return typeof entry === "object" && entry !== null && "type" in entry
161
+ }
162
+
163
+ const state = Instance.state(
164
+ async () => {
165
+ const cfg = await Config.get()
166
+ const config = cfg.mcp ?? {}
167
+ const clients: Record<string, MCPClient> = {}
168
+ const status: Record<string, Status> = {}
169
+
170
+ await Promise.all(
171
+ Object.entries(config).map(async ([key, mcp]) => {
172
+ if (!isMcpConfigured(mcp)) {
173
+ log.error("Ignoring MCP config entry without type", { key })
174
+ return
175
+ }
176
+
177
+ // If disabled by config, mark as disabled without trying to connect
178
+ if (mcp.enabled === false) {
179
+ status[key] = { status: "disabled" }
180
+ return
181
+ }
182
+
183
+ const result = await create(key, mcp).catch(() => undefined)
184
+ if (!result) return
185
+
186
+ status[key] = result.status
187
+
188
+ if (result.mcpClient) {
189
+ clients[key] = result.mcpClient
190
+ }
191
+ }),
192
+ )
193
+ return {
194
+ status,
195
+ clients,
196
+ }
197
+ },
198
+ async (state) => {
199
+ await Promise.all(
200
+ Object.values(state.clients).map((client) =>
201
+ client.close().catch((error) => {
202
+ log.error("Failed to close MCP client", {
203
+ error,
204
+ })
205
+ }),
206
+ ),
207
+ )
208
+ pendingOAuthTransports.clear()
209
+ },
210
+ )
211
+
212
+ // Helper function to fetch prompts for a specific client
213
+ async function fetchPromptsForClient(clientName: string, client: Client) {
214
+ const prompts = await client.listPrompts().catch((e) => {
215
+ log.error("failed to get prompts", { clientName, error: e.message })
216
+ return undefined
217
+ })
218
+
219
+ if (!prompts) {
220
+ return
221
+ }
222
+
223
+ const commands: Record<string, PromptInfo & { client: string }> = {}
224
+
225
+ for (const prompt of prompts.prompts) {
226
+ const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
227
+ const sanitizedPromptName = prompt.name.replace(/[^a-zA-Z0-9_-]/g, "_")
228
+ const key = sanitizedClientName + ":" + sanitizedPromptName
229
+
230
+ commands[key] = { ...prompt, client: clientName }
231
+ }
232
+ return commands
233
+ }
234
+
235
+ async function fetchResourcesForClient(clientName: string, client: Client) {
236
+ const resources = await client.listResources().catch((e) => {
237
+ log.error("failed to get prompts", { clientName, error: e.message })
238
+ return undefined
239
+ })
240
+
241
+ if (!resources) {
242
+ return
243
+ }
244
+
245
+ const commands: Record<string, ResourceInfo & { client: string }> = {}
246
+
247
+ for (const resource of resources.resources) {
248
+ const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
249
+ const sanitizedResourceName = resource.name.replace(/[^a-zA-Z0-9_-]/g, "_")
250
+ const key = sanitizedClientName + ":" + sanitizedResourceName
251
+
252
+ commands[key] = { ...resource, client: clientName }
253
+ }
254
+ return commands
255
+ }
256
+
257
+ export async function add(name: string, mcp: Config.Mcp) {
258
+ const s = await state()
259
+ const result = await create(name, mcp)
260
+ if (!result) {
261
+ const status = {
262
+ status: "failed" as const,
263
+ error: "unknown error",
264
+ }
265
+ s.status[name] = status
266
+ return {
267
+ status,
268
+ }
269
+ }
270
+ if (!result.mcpClient) {
271
+ s.status[name] = result.status
272
+ return {
273
+ status: s.status,
274
+ }
275
+ }
276
+ // Close existing client if present to prevent memory leaks
277
+ const existingClient = s.clients[name]
278
+ if (existingClient) {
279
+ await existingClient.close().catch((error) => {
280
+ log.error("Failed to close existing MCP client", { name, error })
281
+ })
282
+ }
283
+ s.clients[name] = result.mcpClient
284
+ s.status[name] = result.status
285
+
286
+ return {
287
+ status: s.status,
288
+ }
289
+ }
290
+
291
+ async function create(key: string, mcp: Config.Mcp) {
292
+ if (mcp.enabled === false) {
293
+ log.info("mcp server disabled", { key })
294
+ return {
295
+ mcpClient: undefined,
296
+ status: { status: "disabled" as const },
297
+ }
298
+ }
299
+
300
+ log.info("found", { key, type: mcp.type })
301
+ let mcpClient: MCPClient | undefined
302
+ let status: Status | undefined = undefined
303
+
304
+ if (mcp.type === "remote") {
305
+ // OAuth is enabled by default for remote servers unless explicitly disabled with oauth: false
306
+ const oauthDisabled = mcp.oauth === false
307
+ const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
308
+ let authProvider: McpOAuthProvider | undefined
309
+
310
+ if (!oauthDisabled) {
311
+ authProvider = new McpOAuthProvider(
312
+ key,
313
+ mcp.url,
314
+ {
315
+ clientId: oauthConfig?.clientId,
316
+ clientSecret: oauthConfig?.clientSecret,
317
+ scope: oauthConfig?.scope,
318
+ },
319
+ {
320
+ onRedirect: async (url) => {
321
+ log.info("oauth redirect requested", { key, url: url.toString() })
322
+ // Store the URL - actual browser opening is handled by startAuth
323
+ },
324
+ },
325
+ )
326
+ }
327
+
328
+ const transports: Array<{ name: string; transport: TransportWithAuth }> = [
329
+ {
330
+ name: "StreamableHTTP",
331
+ transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
332
+ authProvider,
333
+ requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
334
+ }),
335
+ },
336
+ {
337
+ name: "SSE",
338
+ transport: new SSEClientTransport(new URL(mcp.url), {
339
+ authProvider,
340
+ requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
341
+ }),
342
+ },
343
+ ]
344
+
345
+ let lastError: Error | undefined
346
+ const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
347
+ for (const { name, transport } of transports) {
348
+ try {
349
+ const client = new Client({
350
+ name: "opencode",
351
+ version: Installation.VERSION,
352
+ })
353
+ await withTimeout(client.connect(transport), connectTimeout)
354
+ registerNotificationHandlers(client, key)
355
+ mcpClient = client
356
+ log.info("connected", { key, transport: name })
357
+ status = { status: "connected" }
358
+ break
359
+ } catch (error) {
360
+ lastError = error instanceof Error ? error : new Error(String(error))
361
+
362
+ // Handle OAuth-specific errors
363
+ if (error instanceof UnauthorizedError) {
364
+ log.info("mcp server requires authentication", { key, transport: name })
365
+
366
+ // Check if this is a "needs registration" error
367
+ if (lastError.message.includes("registration") || lastError.message.includes("client_id")) {
368
+ status = {
369
+ status: "needs_client_registration" as const,
370
+ error: "Server does not support dynamic client registration. Please provide clientId in config.",
371
+ }
372
+ // Show toast for needs_client_registration
373
+ Bus.publish(TuiEvent.ToastShow, {
374
+ title: "MCP Authentication Required",
375
+ message: `Server "${key}" requires a pre-registered client ID. Add clientId to your config.`,
376
+ variant: "warning",
377
+ duration: 8000,
378
+ }).catch((e) => log.debug("failed to show toast", { error: e }))
379
+ } else {
380
+ // Store transport for later finishAuth call
381
+ pendingOAuthTransports.set(key, transport)
382
+ status = { status: "needs_auth" as const }
383
+ // Show toast for needs_auth
384
+ Bus.publish(TuiEvent.ToastShow, {
385
+ title: "MCP Authentication Required",
386
+ message: `Server "${key}" requires authentication. Run: bloxycode mcp auth ${key}`,
387
+ variant: "warning",
388
+ duration: 8000,
389
+ }).catch((e) => log.debug("failed to show toast", { error: e }))
390
+ }
391
+ break
392
+ }
393
+
394
+ log.debug("transport connection failed", {
395
+ key,
396
+ transport: name,
397
+ url: mcp.url,
398
+ error: lastError.message,
399
+ })
400
+ status = {
401
+ status: "failed" as const,
402
+ error: lastError.message,
403
+ }
404
+ }
405
+ }
406
+ }
407
+
408
+ if (mcp.type === "local") {
409
+ const [cmd, ...args] = mcp.command
410
+ const cwd = Instance.directory
411
+ const transport = new StdioClientTransport({
412
+ stderr: "pipe",
413
+ command: cmd,
414
+ args,
415
+ cwd,
416
+ env: {
417
+ ...process.env,
418
+ ...(cmd === "opencode" ? { BUN_BE_BUN: "1" } : {}),
419
+ ...mcp.environment,
420
+ },
421
+ })
422
+ transport.stderr?.on("data", (chunk: Buffer) => {
423
+ log.info(`mcp stderr: ${chunk.toString()}`, { key })
424
+ })
425
+
426
+ const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
427
+ try {
428
+ const client = new Client({
429
+ name: "opencode",
430
+ version: Installation.VERSION,
431
+ })
432
+ await withTimeout(client.connect(transport), connectTimeout)
433
+ registerNotificationHandlers(client, key)
434
+ mcpClient = client
435
+ status = {
436
+ status: "connected",
437
+ }
438
+ } catch (error) {
439
+ log.error("local mcp startup failed", {
440
+ key,
441
+ command: mcp.command,
442
+ cwd,
443
+ error: error instanceof Error ? error.message : String(error),
444
+ })
445
+ status = {
446
+ status: "failed" as const,
447
+ error: error instanceof Error ? error.message : String(error),
448
+ }
449
+ }
450
+ }
451
+
452
+ if (!status) {
453
+ status = {
454
+ status: "failed" as const,
455
+ error: "Unknown error",
456
+ }
457
+ }
458
+
459
+ if (!mcpClient) {
460
+ return {
461
+ mcpClient: undefined,
462
+ status,
463
+ }
464
+ }
465
+
466
+ const result = await withTimeout(mcpClient.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
467
+ log.error("failed to get tools from client", { key, error: err })
468
+ return undefined
469
+ })
470
+ if (!result) {
471
+ await mcpClient.close().catch((error) => {
472
+ log.error("Failed to close MCP client", {
473
+ error,
474
+ })
475
+ })
476
+ status = {
477
+ status: "failed",
478
+ error: "Failed to get tools",
479
+ }
480
+ return {
481
+ mcpClient: undefined,
482
+ status: {
483
+ status: "failed" as const,
484
+ error: "Failed to get tools",
485
+ },
486
+ }
487
+ }
488
+
489
+ log.info("create() successfully created client", { key, toolCount: result.tools.length })
490
+ return {
491
+ mcpClient,
492
+ status,
493
+ }
494
+ }
495
+
496
+ export async function status() {
497
+ const s = await state()
498
+ const cfg = await Config.get()
499
+ const config = cfg.mcp ?? {}
500
+ const result: Record<string, Status> = {}
501
+
502
+ // Include all configured MCPs from config, not just connected ones
503
+ for (const [key, mcp] of Object.entries(config)) {
504
+ if (!isMcpConfigured(mcp)) continue
505
+ result[key] = s.status[key] ?? { status: "disabled" }
506
+ }
507
+
508
+ return result
509
+ }
510
+
511
+ export async function clients() {
512
+ return state().then((state) => state.clients)
513
+ }
514
+
515
+ export async function connect(name: string) {
516
+ const cfg = await Config.get()
517
+ const config = cfg.mcp ?? {}
518
+ const mcp = config[name]
519
+ if (!mcp) {
520
+ log.error("MCP config not found", { name })
521
+ return
522
+ }
523
+
524
+ if (!isMcpConfigured(mcp)) {
525
+ log.error("Ignoring MCP connect request for config without type", { name })
526
+ return
527
+ }
528
+
529
+ const result = await create(name, { ...mcp, enabled: true })
530
+
531
+ if (!result) {
532
+ const s = await state()
533
+ s.status[name] = {
534
+ status: "failed",
535
+ error: "Unknown error during connection",
536
+ }
537
+ return
538
+ }
539
+
540
+ const s = await state()
541
+ s.status[name] = result.status
542
+ if (result.mcpClient) {
543
+ // Close existing client if present to prevent memory leaks
544
+ const existingClient = s.clients[name]
545
+ if (existingClient) {
546
+ await existingClient.close().catch((error) => {
547
+ log.error("Failed to close existing MCP client", { name, error })
548
+ })
549
+ }
550
+ s.clients[name] = result.mcpClient
551
+ }
552
+ }
553
+
554
+ export async function disconnect(name: string) {
555
+ const s = await state()
556
+ const client = s.clients[name]
557
+ if (client) {
558
+ await client.close().catch((error) => {
559
+ log.error("Failed to close MCP client", { name, error })
560
+ })
561
+ delete s.clients[name]
562
+ }
563
+ s.status[name] = { status: "disabled" }
564
+ }
565
+
566
+ export async function tools() {
567
+ const result: Record<string, Tool> = {}
568
+ const s = await state()
569
+ const cfg = await Config.get()
570
+ const config = cfg.mcp ?? {}
571
+ const clientsSnapshot = await clients()
572
+ const defaultTimeout = cfg.experimental?.mcp_timeout
573
+
574
+ for (const [clientName, client] of Object.entries(clientsSnapshot)) {
575
+ // Only include tools from connected MCPs (skip disabled ones)
576
+ if (s.status[clientName]?.status !== "connected") {
577
+ continue
578
+ }
579
+
580
+ const toolsResult = await client.listTools().catch((e) => {
581
+ log.error("failed to get tools", { clientName, error: e.message })
582
+ const failedStatus = {
583
+ status: "failed" as const,
584
+ error: e instanceof Error ? e.message : String(e),
585
+ }
586
+ s.status[clientName] = failedStatus
587
+ delete s.clients[clientName]
588
+ return undefined
589
+ })
590
+ if (!toolsResult) {
591
+ continue
592
+ }
593
+ const mcpConfig = config[clientName]
594
+ const entry = isMcpConfigured(mcpConfig) ? mcpConfig : undefined
595
+ const timeout = entry?.timeout ?? defaultTimeout
596
+ for (const mcpTool of toolsResult.tools) {
597
+ const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
598
+ const sanitizedToolName = mcpTool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
599
+ result[sanitizedClientName + "_" + sanitizedToolName] = await convertMcpTool(mcpTool, client, timeout)
600
+ }
601
+ }
602
+ return result
603
+ }
604
+
605
+ export async function prompts() {
606
+ const s = await state()
607
+ const clientsSnapshot = await clients()
608
+
609
+ const prompts = Object.fromEntries<PromptInfo & { client: string }>(
610
+ (
611
+ await Promise.all(
612
+ Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
613
+ if (s.status[clientName]?.status !== "connected") {
614
+ return []
615
+ }
616
+
617
+ return Object.entries((await fetchPromptsForClient(clientName, client)) ?? {})
618
+ }),
619
+ )
620
+ ).flat(),
621
+ )
622
+
623
+ return prompts
624
+ }
625
+
626
+ export async function resources() {
627
+ const s = await state()
628
+ const clientsSnapshot = await clients()
629
+
630
+ const result = Object.fromEntries<ResourceInfo & { client: string }>(
631
+ (
632
+ await Promise.all(
633
+ Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
634
+ if (s.status[clientName]?.status !== "connected") {
635
+ return []
636
+ }
637
+
638
+ return Object.entries((await fetchResourcesForClient(clientName, client)) ?? {})
639
+ }),
640
+ )
641
+ ).flat(),
642
+ )
643
+
644
+ return result
645
+ }
646
+
647
+ export async function getPrompt(clientName: string, name: string, args?: Record<string, string>) {
648
+ const clientsSnapshot = await clients()
649
+ const client = clientsSnapshot[clientName]
650
+
651
+ if (!client) {
652
+ log.warn("client not found for prompt", {
653
+ clientName,
654
+ })
655
+ return undefined
656
+ }
657
+
658
+ const result = await client
659
+ .getPrompt({
660
+ name: name,
661
+ arguments: args,
662
+ })
663
+ .catch((e) => {
664
+ log.error("failed to get prompt from MCP server", {
665
+ clientName,
666
+ promptName: name,
667
+ error: e.message,
668
+ })
669
+ return undefined
670
+ })
671
+
672
+ return result
673
+ }
674
+
675
+ export async function readResource(clientName: string, resourceUri: string) {
676
+ const clientsSnapshot = await clients()
677
+ const client = clientsSnapshot[clientName]
678
+
679
+ if (!client) {
680
+ log.warn("client not found for prompt", {
681
+ clientName: clientName,
682
+ })
683
+ return undefined
684
+ }
685
+
686
+ const result = await client
687
+ .readResource({
688
+ uri: resourceUri,
689
+ })
690
+ .catch((e) => {
691
+ log.error("failed to get prompt from MCP server", {
692
+ clientName: clientName,
693
+ resourceUri: resourceUri,
694
+ error: e.message,
695
+ })
696
+ return undefined
697
+ })
698
+
699
+ return result
700
+ }
701
+
702
+ /**
703
+ * Start OAuth authentication flow for an MCP server.
704
+ * Returns the authorization URL that should be opened in a browser.
705
+ */
706
+ export async function startAuth(mcpName: string): Promise<{ authorizationUrl: string }> {
707
+ const cfg = await Config.get()
708
+ const mcpConfig = cfg.mcp?.[mcpName]
709
+
710
+ if (!mcpConfig) {
711
+ throw new Error(`MCP server not found: ${mcpName}`)
712
+ }
713
+
714
+ if (!isMcpConfigured(mcpConfig)) {
715
+ throw new Error(`MCP server ${mcpName} is disabled or missing configuration`)
716
+ }
717
+
718
+ if (mcpConfig.type !== "remote") {
719
+ throw new Error(`MCP server ${mcpName} is not a remote server`)
720
+ }
721
+
722
+ if (mcpConfig.oauth === false) {
723
+ throw new Error(`MCP server ${mcpName} has OAuth explicitly disabled`)
724
+ }
725
+
726
+ // Start the callback server
727
+ await McpOAuthCallback.ensureRunning()
728
+
729
+ // Generate and store a cryptographically secure state parameter BEFORE creating the provider
730
+ // The SDK will call provider.state() to read this value
731
+ const oauthState = Array.from(crypto.getRandomValues(new Uint8Array(32)))
732
+ .map((b) => b.toString(16).padStart(2, "0"))
733
+ .join("")
734
+ await McpAuth.updateOAuthState(mcpName, oauthState)
735
+
736
+ // Create a new auth provider for this flow
737
+ // OAuth config is optional - if not provided, we'll use auto-discovery
738
+ const oauthConfig = typeof mcpConfig.oauth === "object" ? mcpConfig.oauth : undefined
739
+ let capturedUrl: URL | undefined
740
+ const authProvider = new McpOAuthProvider(
741
+ mcpName,
742
+ mcpConfig.url,
743
+ {
744
+ clientId: oauthConfig?.clientId,
745
+ clientSecret: oauthConfig?.clientSecret,
746
+ scope: oauthConfig?.scope,
747
+ },
748
+ {
749
+ onRedirect: async (url) => {
750
+ capturedUrl = url
751
+ },
752
+ },
753
+ )
754
+
755
+ // Create transport with auth provider
756
+ const transport = new StreamableHTTPClientTransport(new URL(mcpConfig.url), {
757
+ authProvider,
758
+ })
759
+
760
+ // Try to connect - this will trigger the OAuth flow
761
+ try {
762
+ const client = new Client({
763
+ name: "opencode",
764
+ version: Installation.VERSION,
765
+ })
766
+ await client.connect(transport)
767
+ // If we get here, we're already authenticated
768
+ return { authorizationUrl: "" }
769
+ } catch (error) {
770
+ if (error instanceof UnauthorizedError && capturedUrl) {
771
+ // Store transport for finishAuth
772
+ pendingOAuthTransports.set(mcpName, transport)
773
+ return { authorizationUrl: capturedUrl.toString() }
774
+ }
775
+ throw error
776
+ }
777
+ }
778
+
779
+ /**
780
+ * Complete OAuth authentication after user authorizes in browser.
781
+ * Opens the browser and waits for callback.
782
+ */
783
+ export async function authenticate(mcpName: string): Promise<Status> {
784
+ const { authorizationUrl } = await startAuth(mcpName)
785
+
786
+ if (!authorizationUrl) {
787
+ // Already authenticated
788
+ const s = await state()
789
+ return s.status[mcpName] ?? { status: "connected" }
790
+ }
791
+
792
+ // Get the state that was already generated and stored in startAuth()
793
+ const oauthState = await McpAuth.getOAuthState(mcpName)
794
+ if (!oauthState) {
795
+ throw new Error("OAuth state not found - this should not happen")
796
+ }
797
+
798
+ // The SDK has already added the state parameter to the authorization URL
799
+ // We just need to open the browser
800
+ log.info("opening browser for oauth", { mcpName, url: authorizationUrl, state: oauthState })
801
+
802
+ // Register the callback BEFORE opening the browser to avoid race condition
803
+ // when the IdP has an active SSO session and redirects immediately
804
+ const callbackPromise = McpOAuthCallback.waitForCallback(oauthState)
805
+
806
+ try {
807
+ const subprocess = await open(authorizationUrl)
808
+ // The open package spawns a detached process and returns immediately.
809
+ // We need to listen for errors which fire asynchronously:
810
+ // - "error" event: command not found (ENOENT)
811
+ // - "exit" with non-zero code: command exists but failed (e.g., no display)
812
+ await new Promise<void>((resolve, reject) => {
813
+ // Give the process a moment to fail if it's going to
814
+ const timeout = setTimeout(() => resolve(), 500)
815
+ subprocess.on("error", (error) => {
816
+ clearTimeout(timeout)
817
+ reject(error)
818
+ })
819
+ subprocess.on("exit", (code) => {
820
+ if (code !== null && code !== 0) {
821
+ clearTimeout(timeout)
822
+ reject(new Error(`Browser open failed with exit code ${code}`))
823
+ }
824
+ })
825
+ })
826
+ } catch (error) {
827
+ // Browser opening failed (e.g., in remote/headless sessions like SSH, devcontainers)
828
+ // Emit event so CLI can display the URL for manual opening
829
+ log.warn("failed to open browser, user must open URL manually", { mcpName, error })
830
+ Bus.publish(BrowserOpenFailed, { mcpName, url: authorizationUrl })
831
+ }
832
+
833
+ // Wait for callback using the already-registered promise
834
+ const code = await callbackPromise
835
+
836
+ // Validate and clear the state
837
+ const storedState = await McpAuth.getOAuthState(mcpName)
838
+ if (storedState !== oauthState) {
839
+ await McpAuth.clearOAuthState(mcpName)
840
+ throw new Error("OAuth state mismatch - potential CSRF attack")
841
+ }
842
+
843
+ await McpAuth.clearOAuthState(mcpName)
844
+
845
+ // Finish auth
846
+ return finishAuth(mcpName, code)
847
+ }
848
+
849
+ /**
850
+ * Complete OAuth authentication with the authorization code.
851
+ */
852
+ export async function finishAuth(mcpName: string, authorizationCode: string): Promise<Status> {
853
+ const transport = pendingOAuthTransports.get(mcpName)
854
+
855
+ if (!transport) {
856
+ throw new Error(`No pending OAuth flow for MCP server: ${mcpName}`)
857
+ }
858
+
859
+ try {
860
+ // Call finishAuth on the transport
861
+ await transport.finishAuth(authorizationCode)
862
+
863
+ // Clear the code verifier after successful auth
864
+ await McpAuth.clearCodeVerifier(mcpName)
865
+
866
+ // Now try to reconnect
867
+ const cfg = await Config.get()
868
+ const mcpConfig = cfg.mcp?.[mcpName]
869
+
870
+ if (!mcpConfig) {
871
+ throw new Error(`MCP server not found: ${mcpName}`)
872
+ }
873
+
874
+ if (!isMcpConfigured(mcpConfig)) {
875
+ throw new Error(`MCP server ${mcpName} is disabled or missing configuration`)
876
+ }
877
+
878
+ // Re-add the MCP server to establish connection
879
+ pendingOAuthTransports.delete(mcpName)
880
+ const result = await add(mcpName, mcpConfig)
881
+
882
+ const statusRecord = result.status as Record<string, Status>
883
+ return statusRecord[mcpName] ?? { status: "failed", error: "Unknown error after auth" }
884
+ } catch (error) {
885
+ log.error("failed to finish oauth", { mcpName, error })
886
+ return {
887
+ status: "failed",
888
+ error: error instanceof Error ? error.message : String(error),
889
+ }
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Remove OAuth credentials for an MCP server.
895
+ */
896
+ export async function removeAuth(mcpName: string): Promise<void> {
897
+ await McpAuth.remove(mcpName)
898
+ McpOAuthCallback.cancelPending(mcpName)
899
+ pendingOAuthTransports.delete(mcpName)
900
+ await McpAuth.clearOAuthState(mcpName)
901
+ log.info("removed oauth credentials", { mcpName })
902
+ }
903
+
904
+ /**
905
+ * Check if an MCP server supports OAuth (remote servers support OAuth by default unless explicitly disabled).
906
+ */
907
+ export async function supportsOAuth(mcpName: string): Promise<boolean> {
908
+ const cfg = await Config.get()
909
+ const mcpConfig = cfg.mcp?.[mcpName]
910
+ if (!mcpConfig) return false
911
+ if (!isMcpConfigured(mcpConfig)) return false
912
+ return mcpConfig.type === "remote" && mcpConfig.oauth !== false
913
+ }
914
+
915
+ /**
916
+ * Check if an MCP server has stored OAuth tokens.
917
+ */
918
+ export async function hasStoredTokens(mcpName: string): Promise<boolean> {
919
+ const entry = await McpAuth.get(mcpName)
920
+ return !!entry?.tokens
921
+ }
922
+
923
+ export type AuthStatus = "authenticated" | "expired" | "not_authenticated"
924
+
925
+ /**
926
+ * Get the authentication status for an MCP server.
927
+ */
928
+ export async function getAuthStatus(mcpName: string): Promise<AuthStatus> {
929
+ const hasTokens = await hasStoredTokens(mcpName)
930
+ if (!hasTokens) return "not_authenticated"
931
+ const expired = await McpAuth.isTokenExpired(mcpName)
932
+ return expired ? "expired" : "authenticated"
933
+ }
934
+ }