chad-code 1.3.1

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