@hyperwindmill/caretaker-cli 0.11.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 (275) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +25 -0
  3. package/dist/agents/dispatch.d.ts +35 -0
  4. package/dist/agents/dispatch.d.ts.map +1 -0
  5. package/dist/agents/dispatch.js +108 -0
  6. package/dist/agents/sync.d.ts +10 -0
  7. package/dist/agents/sync.d.ts.map +1 -0
  8. package/dist/agents/sync.js +95 -0
  9. package/dist/cli/index.d.ts +2 -0
  10. package/dist/cli/index.d.ts.map +1 -0
  11. package/dist/cli/index.js +50 -0
  12. package/dist/cli/run.d.ts +11 -0
  13. package/dist/cli/run.d.ts.map +1 -0
  14. package/dist/cli/run.js +89 -0
  15. package/dist/cli/web/fs.d.ts +3 -0
  16. package/dist/cli/web/fs.d.ts.map +1 -0
  17. package/dist/cli/web/fs.js +35 -0
  18. package/dist/cli/web/mcp_bridge.d.ts +7 -0
  19. package/dist/cli/web/mcp_bridge.d.ts.map +1 -0
  20. package/dist/cli/web/mcp_bridge.js +86 -0
  21. package/dist/cli/web/scheduler/heartbeat.d.ts +16 -0
  22. package/dist/cli/web/scheduler/heartbeat.d.ts.map +1 -0
  23. package/dist/cli/web/scheduler/heartbeat.js +181 -0
  24. package/dist/cli/web/scheduler/locks.d.ts +8 -0
  25. package/dist/cli/web/scheduler/locks.d.ts.map +1 -0
  26. package/dist/cli/web/scheduler/locks.js +7 -0
  27. package/dist/cli/web/scheduler/logs.d.ts +21 -0
  28. package/dist/cli/web/scheduler/logs.d.ts.map +1 -0
  29. package/dist/cli/web/scheduler/logs.js +62 -0
  30. package/dist/cli/web/scheduler/strategy.d.ts +6 -0
  31. package/dist/cli/web/scheduler/strategy.d.ts.map +1 -0
  32. package/dist/cli/web/scheduler/strategy.js +1 -0
  33. package/dist/cli/web/scheduler/task_review.d.ts +18 -0
  34. package/dist/cli/web/scheduler/task_review.d.ts.map +1 -0
  35. package/dist/cli/web/scheduler/task_review.js +77 -0
  36. package/dist/cli/web/scheduler/task_roles.d.ts +22 -0
  37. package/dist/cli/web/scheduler/task_roles.d.ts.map +1 -0
  38. package/dist/cli/web/scheduler/task_roles.js +70 -0
  39. package/dist/cli/web/scheduler/task_strategy.d.ts +2 -0
  40. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -0
  41. package/dist/cli/web/scheduler/task_strategy.js +437 -0
  42. package/dist/cli/web/scheduler/telegram.d.ts +7 -0
  43. package/dist/cli/web/scheduler/telegram.d.ts.map +1 -0
  44. package/dist/cli/web/scheduler/telegram.js +393 -0
  45. package/dist/cli/web/scheduler.d.ts +15 -0
  46. package/dist/cli/web/scheduler.d.ts.map +1 -0
  47. package/dist/cli/web/scheduler.js +60 -0
  48. package/dist/cli/web/server.d.ts +38 -0
  49. package/dist/cli/web/server.d.ts.map +1 -0
  50. package/dist/cli/web/server.js +970 -0
  51. package/dist/commands/loader.d.ts +37 -0
  52. package/dist/commands/loader.d.ts.map +1 -0
  53. package/dist/commands/loader.js +110 -0
  54. package/dist/harness/claude_code_runner.d.ts +47 -0
  55. package/dist/harness/claude_code_runner.d.ts.map +1 -0
  56. package/dist/harness/claude_code_runner.js +325 -0
  57. package/dist/harness/claude_code_stream.d.ts +32 -0
  58. package/dist/harness/claude_code_stream.d.ts.map +1 -0
  59. package/dist/harness/claude_code_stream.js +121 -0
  60. package/dist/harness/context_files.d.ts +23 -0
  61. package/dist/harness/context_files.d.ts.map +1 -0
  62. package/dist/harness/context_files.js +126 -0
  63. package/dist/harness/history.d.ts +4 -0
  64. package/dist/harness/history.d.ts.map +1 -0
  65. package/dist/harness/history.js +120 -0
  66. package/dist/harness/index.d.ts +8 -0
  67. package/dist/harness/index.d.ts.map +1 -0
  68. package/dist/harness/index.js +8 -0
  69. package/dist/harness/loop.d.ts +73 -0
  70. package/dist/harness/loop.d.ts.map +1 -0
  71. package/dist/harness/loop.js +373 -0
  72. package/dist/harness/model_limits.d.ts +25 -0
  73. package/dist/harness/model_limits.d.ts.map +1 -0
  74. package/dist/harness/model_limits.js +67 -0
  75. package/dist/harness/models.d.ts +9 -0
  76. package/dist/harness/models.d.ts.map +1 -0
  77. package/dist/harness/models.js +38 -0
  78. package/dist/harness/prelude.d.ts +21 -0
  79. package/dist/harness/prelude.d.ts.map +1 -0
  80. package/dist/harness/prelude.js +41 -0
  81. package/dist/harness/provider.d.ts +87 -0
  82. package/dist/harness/provider.d.ts.map +1 -0
  83. package/dist/harness/provider.js +140 -0
  84. package/dist/harness/runtime_info.d.ts +7 -0
  85. package/dist/harness/runtime_info.d.ts.map +1 -0
  86. package/dist/harness/runtime_info.js +15 -0
  87. package/dist/harness/think_tag_splitter.d.ts +33 -0
  88. package/dist/harness/think_tag_splitter.d.ts.map +1 -0
  89. package/dist/harness/think_tag_splitter.js +70 -0
  90. package/dist/harness/title.d.ts +17 -0
  91. package/dist/harness/title.d.ts.map +1 -0
  92. package/dist/harness/title.js +75 -0
  93. package/dist/harness/tools/builtin/bash.d.ts +3 -0
  94. package/dist/harness/tools/builtin/bash.d.ts.map +1 -0
  95. package/dist/harness/tools/builtin/bash.js +137 -0
  96. package/dist/harness/tools/builtin/edit.d.ts +6 -0
  97. package/dist/harness/tools/builtin/edit.d.ts.map +1 -0
  98. package/dist/harness/tools/builtin/edit.js +85 -0
  99. package/dist/harness/tools/builtin/fetch.d.ts +3 -0
  100. package/dist/harness/tools/builtin/fetch.d.ts.map +1 -0
  101. package/dist/harness/tools/builtin/fetch.js +75 -0
  102. package/dist/harness/tools/builtin/get_agent_context.d.ts +3 -0
  103. package/dist/harness/tools/builtin/get_agent_context.d.ts.map +1 -0
  104. package/dist/harness/tools/builtin/get_agent_context.js +76 -0
  105. package/dist/harness/tools/builtin/glob.d.ts +3 -0
  106. package/dist/harness/tools/builtin/glob.d.ts.map +1 -0
  107. package/dist/harness/tools/builtin/glob.js +52 -0
  108. package/dist/harness/tools/builtin/grep.d.ts +3 -0
  109. package/dist/harness/tools/builtin/grep.d.ts.map +1 -0
  110. package/dist/harness/tools/builtin/grep.js +126 -0
  111. package/dist/harness/tools/builtin/index.d.ts +23 -0
  112. package/dist/harness/tools/builtin/index.d.ts.map +1 -0
  113. package/dist/harness/tools/builtin/index.js +74 -0
  114. package/dist/harness/tools/builtin/invoke_agent.d.ts +3 -0
  115. package/dist/harness/tools/builtin/invoke_agent.d.ts.map +1 -0
  116. package/dist/harness/tools/builtin/invoke_agent.js +106 -0
  117. package/dist/harness/tools/builtin/invoke_command.d.ts +3 -0
  118. package/dist/harness/tools/builtin/invoke_command.d.ts.map +1 -0
  119. package/dist/harness/tools/builtin/invoke_command.js +42 -0
  120. package/dist/harness/tools/builtin/list_agents.d.ts +3 -0
  121. package/dist/harness/tools/builtin/list_agents.d.ts.map +1 -0
  122. package/dist/harness/tools/builtin/list_agents.js +32 -0
  123. package/dist/harness/tools/builtin/list_commands.d.ts +3 -0
  124. package/dist/harness/tools/builtin/list_commands.d.ts.map +1 -0
  125. package/dist/harness/tools/builtin/list_commands.js +27 -0
  126. package/dist/harness/tools/builtin/list_skills.d.ts +3 -0
  127. package/dist/harness/tools/builtin/list_skills.d.ts.map +1 -0
  128. package/dist/harness/tools/builtin/list_skills.js +24 -0
  129. package/dist/harness/tools/builtin/multiedit.d.ts +3 -0
  130. package/dist/harness/tools/builtin/multiedit.d.ts.map +1 -0
  131. package/dist/harness/tools/builtin/multiedit.js +88 -0
  132. package/dist/harness/tools/builtin/read_attachment.d.ts +3 -0
  133. package/dist/harness/tools/builtin/read_attachment.d.ts.map +1 -0
  134. package/dist/harness/tools/builtin/read_attachment.js +128 -0
  135. package/dist/harness/tools/builtin/read_document.d.ts +37 -0
  136. package/dist/harness/tools/builtin/read_document.d.ts.map +1 -0
  137. package/dist/harness/tools/builtin/read_document.js +238 -0
  138. package/dist/harness/tools/builtin/read_file.d.ts +3 -0
  139. package/dist/harness/tools/builtin/read_file.d.ts.map +1 -0
  140. package/dist/harness/tools/builtin/read_file.js +141 -0
  141. package/dist/harness/tools/builtin/read_image.d.ts +3 -0
  142. package/dist/harness/tools/builtin/read_image.d.ts.map +1 -0
  143. package/dist/harness/tools/builtin/read_image.js +80 -0
  144. package/dist/harness/tools/builtin/read_skill.d.ts +3 -0
  145. package/dist/harness/tools/builtin/read_skill.d.ts.map +1 -0
  146. package/dist/harness/tools/builtin/read_skill.js +30 -0
  147. package/dist/harness/tools/builtin/shell-env.d.ts +55 -0
  148. package/dist/harness/tools/builtin/shell-env.d.ts.map +1 -0
  149. package/dist/harness/tools/builtin/shell-env.js +181 -0
  150. package/dist/harness/tools/builtin/task_tools.d.ts +21 -0
  151. package/dist/harness/tools/builtin/task_tools.d.ts.map +1 -0
  152. package/dist/harness/tools/builtin/task_tools.js +708 -0
  153. package/dist/harness/tools/builtin/write.d.ts +3 -0
  154. package/dist/harness/tools/builtin/write.d.ts.map +1 -0
  155. package/dist/harness/tools/builtin/write.js +56 -0
  156. package/dist/harness/tools/index.d.ts +6 -0
  157. package/dist/harness/tools/index.d.ts.map +1 -0
  158. package/dist/harness/tools/index.js +7 -0
  159. package/dist/harness/tools/instance.d.ts +3 -0
  160. package/dist/harness/tools/instance.d.ts.map +1 -0
  161. package/dist/harness/tools/instance.js +19 -0
  162. package/dist/harness/tools/registry.d.ts +21 -0
  163. package/dist/harness/tools/registry.d.ts.map +1 -0
  164. package/dist/harness/tools/registry.js +33 -0
  165. package/dist/harness/tools/resolve.d.ts +5 -0
  166. package/dist/harness/tools/resolve.d.ts.map +1 -0
  167. package/dist/harness/tools/resolve.js +60 -0
  168. package/dist/harness/tools/sandbox.d.ts +6 -0
  169. package/dist/harness/tools/sandbox.d.ts.map +1 -0
  170. package/dist/harness/tools/sandbox.js +23 -0
  171. package/dist/harness/tools/types.d.ts +80 -0
  172. package/dist/harness/tools/types.d.ts.map +1 -0
  173. package/dist/harness/tools/types.js +16 -0
  174. package/dist/index.d.ts +3 -0
  175. package/dist/index.d.ts.map +1 -0
  176. package/dist/index.js +46 -0
  177. package/dist/lib/encryption.d.ts +24 -0
  178. package/dist/lib/encryption.d.ts.map +1 -0
  179. package/dist/lib/encryption.js +163 -0
  180. package/dist/lib/open_url.d.ts +9 -0
  181. package/dist/lib/open_url.d.ts.map +1 -0
  182. package/dist/lib/open_url.js +23 -0
  183. package/dist/lib/task_git.d.ts +11 -0
  184. package/dist/lib/task_git.d.ts.map +1 -0
  185. package/dist/lib/task_git.js +100 -0
  186. package/dist/mcp/adapter.d.ts +9 -0
  187. package/dist/mcp/adapter.d.ts.map +1 -0
  188. package/dist/mcp/adapter.js +74 -0
  189. package/dist/mcp/client.d.ts +50 -0
  190. package/dist/mcp/client.d.ts.map +1 -0
  191. package/dist/mcp/client.js +243 -0
  192. package/dist/mcp/oauth.d.ts +30 -0
  193. package/dist/mcp/oauth.d.ts.map +1 -0
  194. package/dist/mcp/oauth.js +171 -0
  195. package/dist/mcp/oauth_callback.d.ts +9 -0
  196. package/dist/mcp/oauth_callback.d.ts.map +1 -0
  197. package/dist/mcp/oauth_callback.js +51 -0
  198. package/dist/mcp/oauth_store.d.ts +22 -0
  199. package/dist/mcp/oauth_store.d.ts.map +1 -0
  200. package/dist/mcp/oauth_store.js +40 -0
  201. package/dist/mcp/server_manager.d.ts +49 -0
  202. package/dist/mcp/server_manager.d.ts.map +1 -0
  203. package/dist/mcp/server_manager.js +271 -0
  204. package/dist/plugins/fetchers/git.d.ts +67 -0
  205. package/dist/plugins/fetchers/git.d.ts.map +1 -0
  206. package/dist/plugins/fetchers/git.js +130 -0
  207. package/dist/plugins/fetchers/path.d.ts +4 -0
  208. package/dist/plugins/fetchers/path.d.ts.map +1 -0
  209. package/dist/plugins/fetchers/path.js +22 -0
  210. package/dist/plugins/loader.d.ts +31 -0
  211. package/dist/plugins/loader.d.ts.map +1 -0
  212. package/dist/plugins/loader.js +146 -0
  213. package/dist/plugins/manifest.d.ts +56 -0
  214. package/dist/plugins/manifest.d.ts.map +1 -0
  215. package/dist/plugins/manifest.js +389 -0
  216. package/dist/plugins/refresh_on_start.d.ts +7 -0
  217. package/dist/plugins/refresh_on_start.d.ts.map +1 -0
  218. package/dist/plugins/refresh_on_start.js +35 -0
  219. package/dist/plugins/source_manager.d.ts +27 -0
  220. package/dist/plugins/source_manager.d.ts.map +1 -0
  221. package/dist/plugins/source_manager.js +211 -0
  222. package/dist/plugins/types.d.ts +41 -0
  223. package/dist/plugins/types.d.ts.map +1 -0
  224. package/dist/plugins/types.js +11 -0
  225. package/dist/session/context_usage.d.ts +13 -0
  226. package/dist/session/context_usage.d.ts.map +1 -0
  227. package/dist/session/context_usage.js +25 -0
  228. package/dist/session/index.d.ts +7 -0
  229. package/dist/session/index.d.ts.map +1 -0
  230. package/dist/session/index.js +5 -0
  231. package/dist/session/store.d.ts +68 -0
  232. package/dist/session/store.d.ts.map +1 -0
  233. package/dist/session/store.js +268 -0
  234. package/dist/session/types.d.ts +60 -0
  235. package/dist/session/types.d.ts.map +1 -0
  236. package/dist/session/types.js +11 -0
  237. package/dist/store/db.d.ts +64 -0
  238. package/dist/store/db.d.ts.map +1 -0
  239. package/dist/store/db.js +91 -0
  240. package/dist/store/json.d.ts +21 -0
  241. package/dist/store/json.d.ts.map +1 -0
  242. package/dist/store/json.js +135 -0
  243. package/dist/tui/agents.d.ts +4 -0
  244. package/dist/tui/agents.d.ts.map +1 -0
  245. package/dist/tui/agents.js +616 -0
  246. package/dist/tui/app.d.ts +2 -0
  247. package/dist/tui/app.d.ts.map +1 -0
  248. package/dist/tui/app.js +32 -0
  249. package/dist/tui/chat.d.ts +10 -0
  250. package/dist/tui/chat.d.ts.map +1 -0
  251. package/dist/tui/chat.js +258 -0
  252. package/dist/tui/logo.d.ts +2 -0
  253. package/dist/tui/logo.d.ts.map +1 -0
  254. package/dist/tui/logo.js +10 -0
  255. package/dist/tui/mcp_servers.d.ts +4 -0
  256. package/dist/tui/mcp_servers.d.ts.map +1 -0
  257. package/dist/tui/mcp_servers.js +287 -0
  258. package/dist/tui/plugins.d.ts +4 -0
  259. package/dist/tui/plugins.d.ts.map +1 -0
  260. package/dist/tui/plugins.js +234 -0
  261. package/dist/tui/providers.d.ts +4 -0
  262. package/dist/tui/providers.d.ts.map +1 -0
  263. package/dist/tui/providers.js +178 -0
  264. package/dist/tui/tool_picker_state.d.ts +9 -0
  265. package/dist/tui/tool_picker_state.d.ts.map +1 -0
  266. package/dist/tui/tool_picker_state.js +37 -0
  267. package/dist/types.d.ts +2 -0
  268. package/dist/types.d.ts.map +1 -0
  269. package/dist/types.js +1 -0
  270. package/dist/webview/index.html +22 -0
  271. package/dist/webview/standalone.css +2732 -0
  272. package/dist/webview/standalone.css.map +7 -0
  273. package/dist/webview/standalone.js +20641 -0
  274. package/dist/webview/standalone.js.map +7 -0
  275. package/package.json +120 -0
@@ -0,0 +1,171 @@
1
+ // OAuthClientProvider backed by an mcp.json row's encrypted `oauthState`.
2
+ // The interactive authenticateMcpServer flow lives in the same module.
3
+ // Client-info + tokens persist; the PKCE verifier is in-memory only.
4
+ import { openUrl } from '../lib/open_url.js';
5
+ import { loadMcpServers, saveMcpServers, withMcpServersLock } from '../store/json.js';
6
+ import { readOAuthBlob, writeOAuthBlob, staleRegistrationReset } from './oauth_store.js';
7
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
9
+ import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
10
+ import { startCallbackListener } from './oauth_callback.js';
11
+ import { closeClient } from './client.js';
12
+ export class StoredOAuthProvider {
13
+ serverId;
14
+ _redirectUrl;
15
+ interactive;
16
+ verifier;
17
+ constructor(serverId, _redirectUrl, interactive = false) {
18
+ this.serverId = serverId;
19
+ this._redirectUrl = _redirectUrl;
20
+ this.interactive = interactive;
21
+ }
22
+ get redirectUrl() {
23
+ return this._redirectUrl;
24
+ }
25
+ get clientMetadata() {
26
+ return {
27
+ client_name: 'caretaker-cli',
28
+ redirect_uris: [this._redirectUrl],
29
+ grant_types: ['authorization_code', 'refresh_token'],
30
+ response_types: ['code'],
31
+ token_endpoint_auth_method: 'none',
32
+ };
33
+ }
34
+ async readBlob() {
35
+ const file = await loadMcpServers();
36
+ const row = file.servers.find((s) => s.id === this.serverId);
37
+ return row ? readOAuthBlob(row) : {};
38
+ }
39
+ // Merge one field into the row's blob and persist atomically.
40
+ // Uses withMcpServersLock to prevent race conditions during RMW.
41
+ async mergeBlob(patch) {
42
+ await withMcpServersLock(async () => {
43
+ try {
44
+ const file = await loadMcpServers();
45
+ const row = file.servers.find((s) => s.id === this.serverId);
46
+ if (!row)
47
+ return;
48
+ row.oauthState = writeOAuthBlob({ ...readOAuthBlob(row), ...patch });
49
+ await saveMcpServers(file);
50
+ }
51
+ catch (err) {
52
+ console.error(`[mcp oauth] failed to persist state for ${this.serverId}:`, err);
53
+ }
54
+ });
55
+ }
56
+ async clientInformation() {
57
+ try {
58
+ return (await this.readBlob()).clientInformation;
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ }
64
+ async saveClientInformation(info) {
65
+ await this.mergeBlob({ clientInformation: info });
66
+ }
67
+ async tokens() {
68
+ try {
69
+ return (await this.readBlob()).tokens;
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ async saveTokens(tokens) {
76
+ await this.mergeBlob({ tokens });
77
+ }
78
+ saveCodeVerifier(codeVerifier) {
79
+ this.verifier = codeVerifier;
80
+ }
81
+ codeVerifier() {
82
+ if (!this.verifier)
83
+ throw new Error('no PKCE code verifier in memory');
84
+ return this.verifier;
85
+ }
86
+ redirectToAuthorization(authorizationUrl) {
87
+ if (!this.interactive) {
88
+ throw new Error("Interactive OAuth authentication is not allowed on passive connections");
89
+ }
90
+ openUrl(authorizationUrl.toString());
91
+ }
92
+ }
93
+ export function buildAuthProvider(server) {
94
+ // Passive/pool path never redirects; a placeholder redirectUrl satisfies the SDK interface.
95
+ // Passing interactive = false will prevent DCR/Browser spawn and raise UnauthorizedError.
96
+ return new StoredOAuthProvider(server.id, 'http://127.0.0.1/callback', false);
97
+ }
98
+ /** Interactive OAuth: open the browser, capture the code on a loopback
99
+ * listener, exchange it, and persist tokens. Explicit user action only —
100
+ * never called from the passive pool. */
101
+ export async function authenticateMcpServer(id) {
102
+ const file = await loadMcpServers();
103
+ const server = file.servers.find((s) => s.id === id);
104
+ if (!server)
105
+ throw new Error(`MCP server ${id} not found`);
106
+ if (server.transport !== 'http' || !server.url) {
107
+ throw new Error(`MCP server "${server.name}" is not an http server`);
108
+ }
109
+ const listener = await startCallbackListener();
110
+ // M1 fix: If clientInformation redirect_uris do not contain the current port,
111
+ // clear clientInformation to force a DCR fresh registration.
112
+ await withMcpServersLock(async () => {
113
+ const freshFile = await loadMcpServers();
114
+ const freshServer = freshFile.servers.find((s) => s.id === id);
115
+ if (freshServer) {
116
+ try {
117
+ // R1: when the ephemeral redirect port no longer matches the stored
118
+ // DCR registration, clear BOTH clientInformation and tokens — the
119
+ // tokens are bound to the old client_id and, if kept, would send the
120
+ // next connect down a refresh-with-wrong-client path (invalid_grant)
121
+ // instead of opening the browser.
122
+ const reset = staleRegistrationReset(readOAuthBlob(freshServer), listener.redirectUrl);
123
+ if (reset) {
124
+ freshServer.oauthState = writeOAuthBlob(reset);
125
+ await saveMcpServers(freshFile);
126
+ }
127
+ }
128
+ catch {
129
+ // If decryption fails, clear all oauthState to heal
130
+ delete freshServer.oauthState;
131
+ await saveMcpServers(freshFile);
132
+ }
133
+ }
134
+ });
135
+ const provider = new StoredOAuthProvider(id, listener.redirectUrl, true);
136
+ const client = new Client({ name: 'caretaker-cli', version: '1.0.0' }, { capabilities: {} });
137
+ const transport = new StreamableHTTPClientTransport(new URL(server.url), {
138
+ authProvider: provider,
139
+ });
140
+ try {
141
+ try {
142
+ await client.connect(transport);
143
+ return; // already authorized (saved tokens still valid)
144
+ }
145
+ catch (err) {
146
+ if (!(err instanceof UnauthorizedError))
147
+ throw err;
148
+ // redirectToAuthorization already opened the browser via the provider.
149
+ }
150
+ const code = await listener.waitForCode();
151
+ await transport.finishAuth(code);
152
+ // Drop any stale pooled connection so the next getClient picks up tokens.
153
+ await closeClient(id);
154
+ }
155
+ finally {
156
+ listener.close();
157
+ await client.close().catch(() => { });
158
+ }
159
+ }
160
+ /** Clear stored OAuth state (logout) and drop any pooled connection. */
161
+ export async function revokeMcpAuth(id) {
162
+ await closeClient(id);
163
+ await withMcpServersLock(async () => {
164
+ const file = await loadMcpServers();
165
+ const server = file.servers.find((s) => s.id === id);
166
+ if (!server || !server.oauthState)
167
+ return;
168
+ delete server.oauthState;
169
+ await saveMcpServers(file);
170
+ });
171
+ }
@@ -0,0 +1,9 @@
1
+ export interface CallbackListener {
2
+ redirectUrl: string;
3
+ waitForCode(): Promise<string>;
4
+ close(): void;
5
+ }
6
+ export declare function startCallbackListener(opts?: {
7
+ timeoutMs?: number;
8
+ }): Promise<CallbackListener>;
9
+ //# sourceMappingURL=oauth_callback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth_callback.d.ts","sourceRoot":"","sources":["../../src/mcp/oauth_callback.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/B,KAAK,IAAI,IAAI,CAAC;CACf;AAED,wBAAsB,qBAAqB,CACzC,IAAI,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA+C3B"}
@@ -0,0 +1,51 @@
1
+ // Ephemeral loopback listener that captures the OAuth authorization-code
2
+ // redirect. Binds 127.0.0.1 on an OS-assigned free port; the caller uses
3
+ // `redirectUrl` as the OAuth redirect_uri and awaits `waitForCode()`.
4
+ import { createServer } from 'node:http';
5
+ export async function startCallbackListener(opts) {
6
+ const timeoutMs = opts?.timeoutMs ?? 300_000;
7
+ let resolveCode;
8
+ let rejectCode;
9
+ const codePromise = new Promise((res, rej) => {
10
+ resolveCode = res;
11
+ rejectCode = rej;
12
+ });
13
+ const server = createServer((req, res) => {
14
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
15
+ if (url.pathname !== '/callback') {
16
+ res.writeHead(404).end();
17
+ return;
18
+ }
19
+ const error = url.searchParams.get('error');
20
+ const code = url.searchParams.get('code');
21
+ res.writeHead(200, { 'content-type': 'text/html' });
22
+ if (error) {
23
+ res.end('<html><body>Authorization failed. You can close this tab.</body></html>');
24
+ rejectCode(new Error(`OAuth authorization failed: ${error}`));
25
+ }
26
+ else if (code) {
27
+ res.end('<html><body>Authorization complete. You can close this tab.</body></html>');
28
+ resolveCode(code);
29
+ }
30
+ else {
31
+ res.end('<html><body>Missing code. You can close this tab.</body></html>');
32
+ rejectCode(new Error('OAuth callback missing "code"'));
33
+ }
34
+ });
35
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
36
+ const addr = server.address();
37
+ if (!addr || typeof addr === 'string')
38
+ throw new Error('failed to bind loopback listener');
39
+ const redirectUrl = `http://127.0.0.1:${addr.port}/callback`;
40
+ let timer;
41
+ const waitForCode = () => {
42
+ timer = setTimeout(() => rejectCode(new Error('OAuth flow timed out')), timeoutMs);
43
+ return codePromise.finally(() => timer && clearTimeout(timer));
44
+ };
45
+ const close = () => {
46
+ if (timer)
47
+ clearTimeout(timer);
48
+ server.close();
49
+ };
50
+ return { redirectUrl, waitForCode, close };
51
+ }
@@ -0,0 +1,22 @@
1
+ import type { OAuthClientInformationFull, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
2
+ import type { McpServerConfig } from '../types.js';
3
+ export type OAuthBlob = {
4
+ clientInformation?: OAuthClientInformationFull;
5
+ tokens?: OAuthTokens;
6
+ };
7
+ export declare function readOAuthBlob(server: McpServerConfig): OAuthBlob;
8
+ export declare function readOAuthBlobSafe(server: McpServerConfig): OAuthBlob;
9
+ export declare function writeOAuthBlob(blob: OAuthBlob): string;
10
+ /**
11
+ * Decide whether a stored DCR registration is stale for the current loopback
12
+ * redirect. The ephemeral callback port changes on every interactive attempt
13
+ * (`listen(0)`), so once the registered `redirect_uris` no longer include the
14
+ * current redirect, the client registration is unusable — and so are the
15
+ * tokens, which are bound to that same `client_id`. Returns the cleared blob
16
+ * to persist, or `null` when nothing is stale (no registration, or the current
17
+ * redirect still matches). Clearing tokens alongside clientInformation is what
18
+ * lets the next interactive connect reach the browser flow instead of failing
19
+ * a refresh against a freshly re-registered client_id.
20
+ */
21
+ export declare function staleRegistrationReset(blob: OAuthBlob, currentRedirectUrl: string): OAuthBlob | null;
22
+ //# sourceMappingURL=oauth_store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth_store.d.ts","sourceRoot":"","sources":["../../src/mcp/oauth_store.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,0BAA0B,EAAE,WAAW,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,MAAM,SAAS,GAAG;IACtB,iBAAiB,CAAC,EAAE,0BAA0B,CAAC;IAC/C,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,CAKhE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,CAMpE;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAEtD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAIpG"}
@@ -0,0 +1,40 @@
1
+ // Codec for the per-server OAuth blob persisted in McpServerConfig.oauthState.
2
+ // The blob holds the DCR client registration and the OAuth tokens; it is a
3
+ // single AES-256-GCM encrypted JSON string so the client_secret and
4
+ // refresh_token never touch disk in cleartext.
5
+ import { decrypt, encrypt, isEncrypted } from '../lib/encryption.js';
6
+ export function readOAuthBlob(server) {
7
+ const raw = server.oauthState;
8
+ if (!raw)
9
+ return {};
10
+ const json = isEncrypted(raw) ? decrypt(raw) : raw;
11
+ return JSON.parse(json);
12
+ }
13
+ export function readOAuthBlobSafe(server) {
14
+ try {
15
+ return readOAuthBlob(server);
16
+ }
17
+ catch {
18
+ return {};
19
+ }
20
+ }
21
+ export function writeOAuthBlob(blob) {
22
+ return encrypt(JSON.stringify(blob));
23
+ }
24
+ /**
25
+ * Decide whether a stored DCR registration is stale for the current loopback
26
+ * redirect. The ephemeral callback port changes on every interactive attempt
27
+ * (`listen(0)`), so once the registered `redirect_uris` no longer include the
28
+ * current redirect, the client registration is unusable — and so are the
29
+ * tokens, which are bound to that same `client_id`. Returns the cleared blob
30
+ * to persist, or `null` when nothing is stale (no registration, or the current
31
+ * redirect still matches). Clearing tokens alongside clientInformation is what
32
+ * lets the next interactive connect reach the browser flow instead of failing
33
+ * a refresh against a freshly re-registered client_id.
34
+ */
35
+ export function staleRegistrationReset(blob, currentRedirectUrl) {
36
+ const uris = blob.clientInformation?.redirect_uris;
37
+ if (!uris || uris.includes(currentRedirectUrl))
38
+ return null;
39
+ return { ...blob, clientInformation: undefined, tokens: undefined };
40
+ }
@@ -0,0 +1,49 @@
1
+ import type { McpServerConfig, McpTransport } from '../types.js';
2
+ /**
3
+ * Prune the given MCP server ids from every agent's `mcpServers` array.
4
+ * Returns the number of agents that were actually modified. Idempotent —
5
+ * calling with ids that aren't referenced anywhere is a cheap no-op load
6
+ * (no save). Used both by single-server delete and by cascade-delete on
7
+ * plugin source removal, so agents never carry dangling MCP references.
8
+ */
9
+ export declare function pruneAgentMcpRefs(removedIds: readonly string[]): Promise<number>;
10
+ export interface CreateMcpServerInput {
11
+ name: string;
12
+ transport: McpTransport;
13
+ enabled?: boolean;
14
+ command?: string;
15
+ args?: string[];
16
+ env?: Record<string, string>;
17
+ url?: string;
18
+ headers?: Record<string, string>;
19
+ }
20
+ export interface PatchMcpServerInput {
21
+ name?: string;
22
+ enabled?: boolean;
23
+ command?: string;
24
+ args?: string[];
25
+ env?: Record<string, string>;
26
+ url?: string;
27
+ /** Pass the full headers map; values not yet encrypted will be encrypted
28
+ * on save. Pass `null` to clear all headers. */
29
+ headers?: Record<string, string> | null;
30
+ }
31
+ export declare function createMcpServer(input: CreateMcpServerInput): Promise<McpServerConfig>;
32
+ export declare function deleteMcpServer(id: string): Promise<boolean>;
33
+ export declare function listMcpServers(): Promise<McpServerConfig[]>;
34
+ export declare function getMcpServer(id: string): Promise<McpServerConfig | null>;
35
+ export declare function patchMcpServer(id: string, input: PatchMcpServerInput): Promise<McpServerConfig | null>;
36
+ /**
37
+ * Reconcile mcp.json with plugins.json. For every plugin with an
38
+ * `mcpServers` manifest entry, ensure a corresponding managed row exists in
39
+ * mcp.json (created if missing, refreshed in place if present). Managed rows
40
+ * whose source plugin or manifest entry has disappeared are removed and
41
+ * their pooled connection (if any) is closed.
42
+ *
43
+ * User-authored rows (no `pluginId`) are never touched. Idempotent: calling
44
+ * twice with no plugin changes leaves the file in the same shape.
45
+ */
46
+ export declare function syncManagedMcpServers(): Promise<void>;
47
+ export { authenticateMcpServer, revokeMcpAuth } from './oauth.js';
48
+ export { readOAuthBlob, readOAuthBlobSafe } from './oauth_store.js';
49
+ //# sourceMappingURL=server_manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server_manager.d.ts","sourceRoot":"","sources":["../../src/mcp/server_manager.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,eAAe,EAAiB,YAAY,EAAgB,MAAM,aAAa,CAAC;AAU9F;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBtF;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,YAAY,CAAC;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;qDACiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;CACzC;AAgCD,wBAAsB,eAAe,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,eAAe,CAAC,CA6B3F;AAED,wBAAsB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAgBlE;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC,CAGjE;AAED,wBAAsB,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAI9E;AAED,wBAAsB,cAAc,CAClC,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,mBAAmB,GACzB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAqCjC;AAkED;;;;;;;;;GASG;AACH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAsD3D;AAED,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,271 @@
1
+ // CRUD for mcp.json. Mirrors src/plugins/source_manager.ts in shape so the
2
+ // TUI patterns map 1:1. Header values that look like plaintext are encrypted
3
+ // at create/patch time (encrypted blobs are passed through unchanged), so a
4
+ // hand-edited mcp.json with a raw token gets cleaned up on the next save.
5
+ import { randomUUID } from 'node:crypto';
6
+ import { encrypt, isEncrypted } from '../lib/encryption.js';
7
+ import { loadAgents, loadMcpServers, loadPlugins, saveAgents, saveMcpServers, withMcpServersLock, } from '../store/json.js';
8
+ import { closeClient } from './client.js';
9
+ import { readOAuthBlobSafe } from './oauth_store.js';
10
+ function enrichServerConfig(server) {
11
+ const hasMcpTokens = readOAuthBlobSafe(server).tokens != null;
12
+ return {
13
+ ...server,
14
+ hasMcpTokens,
15
+ };
16
+ }
17
+ /**
18
+ * Prune the given MCP server ids from every agent's `mcpServers` array.
19
+ * Returns the number of agents that were actually modified. Idempotent —
20
+ * calling with ids that aren't referenced anywhere is a cheap no-op load
21
+ * (no save). Used both by single-server delete and by cascade-delete on
22
+ * plugin source removal, so agents never carry dangling MCP references.
23
+ */
24
+ export async function pruneAgentMcpRefs(removedIds) {
25
+ if (removedIds.length === 0)
26
+ return 0;
27
+ const removed = new Set(removedIds);
28
+ const agents = await loadAgents();
29
+ let touched = 0;
30
+ for (const agent of agents) {
31
+ const refs = agent.mcpServers;
32
+ if (!refs || refs.length === 0)
33
+ continue;
34
+ const next = refs.filter((id) => !removed.has(id));
35
+ if (next.length !== refs.length) {
36
+ agent.mcpServers = next;
37
+ touched++;
38
+ }
39
+ }
40
+ if (touched > 0)
41
+ await saveAgents(agents);
42
+ return touched;
43
+ }
44
+ function encryptHeaderValues(headers) {
45
+ if (!headers)
46
+ return undefined;
47
+ const out = {};
48
+ for (const [k, v] of Object.entries(headers)) {
49
+ out[k] = isEncrypted(v) ? v : encrypt(v);
50
+ }
51
+ return out;
52
+ }
53
+ function validateInput(input) {
54
+ if (input.transport === 'stdio') {
55
+ if ('command' in input && input.command !== undefined && input.command.trim() === '') {
56
+ throw new Error('stdio MCP server requires a non-empty command');
57
+ }
58
+ }
59
+ if (input.transport === 'http') {
60
+ if ('url' in input && input.url !== undefined && input.url.trim() !== '') {
61
+ try {
62
+ new URL(input.url);
63
+ }
64
+ catch {
65
+ throw new Error(`http MCP server requires a valid URL (got "${input.url}")`);
66
+ }
67
+ }
68
+ }
69
+ }
70
+ export async function createMcpServer(input) {
71
+ validateInput(input);
72
+ if (input.transport === 'stdio' && !input.command?.trim()) {
73
+ throw new Error('stdio MCP server requires a command');
74
+ }
75
+ if (input.transport === 'http' && !input.url?.trim()) {
76
+ throw new Error('http MCP server requires a url');
77
+ }
78
+ const server = {
79
+ id: randomUUID(),
80
+ name: input.name.trim(),
81
+ transport: input.transport,
82
+ enabled: input.enabled ?? true,
83
+ command: input.transport === 'stdio' ? input.command : undefined,
84
+ args: input.transport === 'stdio' ? (input.args ?? []) : undefined,
85
+ env: input.transport === 'stdio' ? input.env : undefined,
86
+ url: input.transport === 'http' ? input.url : undefined,
87
+ headers: input.transport === 'http' ? encryptHeaderValues(input.headers) : undefined,
88
+ lastConnectedAt: null,
89
+ lastConnectError: null,
90
+ };
91
+ return withMcpServersLock(async () => {
92
+ const file = await loadMcpServers();
93
+ file.servers.push(server);
94
+ await saveMcpServers(file);
95
+ return enrichServerConfig(server);
96
+ });
97
+ }
98
+ export async function deleteMcpServer(id) {
99
+ // closeClient first before write lock to prevent race conditions (M3)
100
+ await closeClient(id);
101
+ const deleted = await withMcpServersLock(async () => {
102
+ const file = await loadMcpServers();
103
+ const idx = file.servers.findIndex((s) => s.id === id);
104
+ if (idx === -1)
105
+ return false;
106
+ file.servers.splice(idx, 1);
107
+ await saveMcpServers(file);
108
+ return true;
109
+ });
110
+ if (deleted) {
111
+ await pruneAgentMcpRefs([id]);
112
+ }
113
+ return deleted;
114
+ }
115
+ export async function listMcpServers() {
116
+ const file = await loadMcpServers();
117
+ return file.servers.map(enrichServerConfig);
118
+ }
119
+ export async function getMcpServer(id) {
120
+ const file = await loadMcpServers();
121
+ const found = file.servers.find((s) => s.id === id) ?? null;
122
+ return found ? enrichServerConfig(found) : null;
123
+ }
124
+ export async function patchMcpServer(id, input) {
125
+ return withMcpServersLock(async () => {
126
+ const file = await loadMcpServers();
127
+ const srv = file.servers.find((s) => s.id === id);
128
+ if (!srv)
129
+ return null;
130
+ validateInput({ ...input, transport: srv.transport });
131
+ // Plugin-managed rows: only `enabled` is mutable. Everything else is the
132
+ // plugin manifest's responsibility and would be overwritten on next sync.
133
+ if (srv.pluginId) {
134
+ if (input.enabled !== undefined) {
135
+ srv.enabled = input.enabled;
136
+ await closeClient(id);
137
+ await saveMcpServers(file);
138
+ }
139
+ return enrichServerConfig(srv);
140
+ }
141
+ if (input.name !== undefined)
142
+ srv.name = input.name.trim();
143
+ if (input.enabled !== undefined)
144
+ srv.enabled = input.enabled;
145
+ if (srv.transport === 'stdio') {
146
+ if (input.command !== undefined)
147
+ srv.command = input.command;
148
+ if (input.args !== undefined)
149
+ srv.args = input.args;
150
+ if (input.env !== undefined)
151
+ srv.env = input.env;
152
+ }
153
+ else {
154
+ if (input.url !== undefined)
155
+ srv.url = input.url;
156
+ if (input.headers !== undefined) {
157
+ srv.headers = input.headers === null ? undefined : encryptHeaderValues(input.headers);
158
+ }
159
+ }
160
+ await closeClient(id);
161
+ await saveMcpServers(file);
162
+ return enrichServerConfig(srv);
163
+ });
164
+ }
165
+ // ─── Plugin-managed sync ─────────────────────────────────────────────────
166
+ function specTransport(spec) {
167
+ return 'command' in spec ? 'stdio' : 'http';
168
+ }
169
+ function managedRowKey(pluginId, scopedName) {
170
+ return `${pluginId}::${scopedName}`;
171
+ }
172
+ function buildManagedRow(plugin, scopedName, spec) {
173
+ const transport = specTransport(spec);
174
+ return {
175
+ id: randomUUID(),
176
+ name: `${plugin.name}/${scopedName}`,
177
+ transport,
178
+ enabled: true,
179
+ pluginId: plugin.id,
180
+ pluginScopedName: scopedName,
181
+ lastConnectedAt: null,
182
+ lastConnectError: null,
183
+ ...(transport === 'stdio'
184
+ ? {
185
+ command: spec.command,
186
+ args: spec.args ?? [],
187
+ env: spec.env,
188
+ }
189
+ : {
190
+ url: spec.url,
191
+ headers: encryptHeaderValues(spec.headers),
192
+ }),
193
+ };
194
+ }
195
+ function applySpecToManagedRow(existing, plugin, scopedName, spec) {
196
+ // Preserve user-controllable bits (`enabled`, `lastConnectedAt`,
197
+ // `lastConnectError`); refresh everything else from the manifest.
198
+ const transport = specTransport(spec);
199
+ return {
200
+ ...existing,
201
+ name: `${plugin.name}/${scopedName}`,
202
+ transport,
203
+ pluginId: plugin.id,
204
+ pluginScopedName: scopedName,
205
+ command: transport === 'stdio' ? spec.command : undefined,
206
+ args: transport === 'stdio' ? (spec.args ?? []) : undefined,
207
+ env: transport === 'stdio' ? spec.env : undefined,
208
+ url: transport === 'http' ? spec.url : undefined,
209
+ headers: transport === 'http'
210
+ ? encryptHeaderValues(spec.headers)
211
+ : undefined,
212
+ };
213
+ }
214
+ /**
215
+ * Reconcile mcp.json with plugins.json. For every plugin with an
216
+ * `mcpServers` manifest entry, ensure a corresponding managed row exists in
217
+ * mcp.json (created if missing, refreshed in place if present). Managed rows
218
+ * whose source plugin or manifest entry has disappeared are removed and
219
+ * their pooled connection (if any) is closed.
220
+ *
221
+ * User-authored rows (no `pluginId`) are never touched. Idempotent: calling
222
+ * twice with no plugin changes leaves the file in the same shape.
223
+ */
224
+ export async function syncManagedMcpServers() {
225
+ const pluginsFile = await loadPlugins();
226
+ const droppedIds = await withMcpServersLock(async () => {
227
+ const mcpFile = await loadMcpServers();
228
+ // Build the set of expected (pluginId, scopedName) → (plugin, spec).
229
+ const expected = new Map();
230
+ for (const plugin of pluginsFile.plugins) {
231
+ if (!plugin.mcpServers)
232
+ continue;
233
+ for (const [scopedName, spec] of Object.entries(plugin.mcpServers)) {
234
+ expected.set(managedRowKey(plugin.id, scopedName), { plugin, scopedName, spec });
235
+ }
236
+ }
237
+ const out = [];
238
+ const seenKeys = new Set();
239
+ const droppedIds = [];
240
+ for (const srv of mcpFile.servers) {
241
+ if (!srv.pluginId) {
242
+ out.push(srv); // user-authored, leave alone
243
+ continue;
244
+ }
245
+ const key = managedRowKey(srv.pluginId, srv.pluginScopedName ?? '');
246
+ const exp = expected.get(key);
247
+ if (!exp) {
248
+ droppedIds.push(srv.id);
249
+ continue;
250
+ }
251
+ seenKeys.add(key);
252
+ out.push(applySpecToManagedRow(srv, exp.plugin, exp.scopedName, exp.spec));
253
+ }
254
+ for (const [key, exp] of expected) {
255
+ if (seenKeys.has(key))
256
+ continue;
257
+ out.push(buildManagedRow(exp.plugin, exp.scopedName, exp.spec));
258
+ }
259
+ await saveMcpServers({ servers: out });
260
+ // Drop pooled connections for removed rows so the runtime stops talking
261
+ // to a config that no longer exists.
262
+ for (const id of droppedIds) {
263
+ await closeClient(id);
264
+ }
265
+ return droppedIds;
266
+ });
267
+ // Same agent-ref cleanup as a direct deleteMcpServer call.
268
+ await pruneAgentMcpRefs(droppedIds);
269
+ }
270
+ export { authenticateMcpServer, revokeMcpAuth } from './oauth.js';
271
+ export { readOAuthBlob, readOAuthBlobSafe } from './oauth_store.js';