@minhluudev/ai-tools 1.0.21 → 1.0.25

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.
@@ -1,665 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { copyFile, readFile } from "node:fs/promises";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
- const GITLAB_REMOTE_URL = "https://gitlab.com/api/v4/mcp";
6
- const GITHUB_REMOTE_URL = "https://api.githubcopilot.com/mcp/";
7
- const FIGMA_REMOTE_URL = "https://mcp.figma.com/mcp";
8
- const MCP_SOURCES = {
9
- antd: {
10
- server: "antd",
11
- label: "Ant Design MCP Server",
12
- url: "https://ant.design/docs/react/mcp/"
13
- },
14
- gitlab: {
15
- server: "gitlab",
16
- label: "GitLab MCP server",
17
- url: "https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_server/"
18
- },
19
- github: {
20
- server: "github",
21
- label: "GitHub MCP server",
22
- url: "https://github.com/github/github-mcp-server/blob/main/docs/installation-guides/install-codex.md"
23
- },
24
- figma: {
25
- server: "figma",
26
- label: "Figma MCP server",
27
- url: "https://developers.figma.com/docs/figma-mcp-server/remote-server-installation/"
28
- },
29
- shadcn: {
30
- server: "shadcn",
31
- label: "Shadcn MCP Server",
32
- url: "https://ui.shadcn.com/docs/mcp"
33
- }
34
- };
35
- function uniq(items) {
36
- return [...new Set(items)];
37
- }
38
- function escapeRegExp(value) {
39
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
40
- }
41
- function buildAntdSteps(agent, mode) {
42
- if (mode === "uninstall") {
43
- return [{
44
- id: `antd-${agent}-remove`,
45
- server: "antd",
46
- agent,
47
- phase: "uninstall",
48
- title: "Remove Ant Design MCP config",
49
- description: `Remove the Ant Design MCP entry from ${agent}.`,
50
- command: agent === "codex" ? "codex mcp remove antd" : "claude mcp remove --scope local antd"
51
- }];
52
- }
53
- return [
54
- {
55
- id: "antd-cli-install",
56
- server: "antd",
57
- agent,
58
- phase: "install",
59
- title: "Install @ant-design/cli",
60
- description: "Install the official Ant Design CLI that exposes the `antd mcp` server.",
61
- command: "npm install -g @ant-design/cli"
62
- },
63
- {
64
- id: `antd-${agent}-add`,
65
- server: "antd",
66
- agent,
67
- phase: "configure",
68
- title: `Register Ant Design MCP in ${agent}`,
69
- description: "Configure the MCP client to launch `antd mcp` over stdio.",
70
- command: agent === "codex"
71
- ? "codex mcp add antd -- antd mcp"
72
- : "claude mcp add antd -- antd mcp"
73
- }
74
- ];
75
- }
76
- function buildGitLabSteps(agent, mode) {
77
- if (mode === "uninstall") {
78
- return agent === "codex"
79
- ? [{
80
- id: "gitlab-codex-remove",
81
- server: "gitlab",
82
- agent,
83
- phase: "uninstall",
84
- title: "Remove GitLab MCP config",
85
- description: "Delete the GitLab MCP entry from Codex.",
86
- command: "codex mcp remove gitlab"
87
- }]
88
- : [{
89
- id: "gitlab-claude-remove",
90
- server: "gitlab",
91
- agent,
92
- phase: "uninstall",
93
- title: "Remove GitLab MCP config",
94
- description: "Delete the GitLab MCP entry from Claude Code.",
95
- command: "claude mcp remove --scope local gitlab"
96
- }];
97
- }
98
- return agent === "codex"
99
- ? [
100
- {
101
- id: "gitlab-codex-add",
102
- server: "gitlab",
103
- agent,
104
- phase: "configure",
105
- title: "Register GitLab MCP in Codex",
106
- description: "Add the GitLab.com MCP endpoint to Codex using streamable HTTP.",
107
- command: `codex mcp add gitlab --url ${GITLAB_REMOTE_URL}`
108
- },
109
- {
110
- id: "gitlab-codex-login",
111
- server: "gitlab",
112
- agent,
113
- phase: "authenticate",
114
- title: "Authenticate GitLab MCP in Codex",
115
- description: "Start the GitLab OAuth flow after the server entry is added.",
116
- command: "codex mcp login gitlab"
117
- }
118
- ]
119
- : [{
120
- id: "gitlab-claude-add",
121
- server: "gitlab",
122
- agent,
123
- phase: "configure",
124
- title: "Register GitLab MCP in Claude Code",
125
- description: "Add the GitLab.com MCP endpoint to Claude Code over HTTP transport.",
126
- command: `claude mcp add --transport http gitlab ${GITLAB_REMOTE_URL}`
127
- }];
128
- }
129
- function buildGitHubSteps(agent, mode) {
130
- if (mode === "uninstall") {
131
- return [{
132
- id: `github-${agent}-remove`,
133
- server: "github",
134
- agent,
135
- phase: "uninstall",
136
- title: "Remove GitHub MCP config",
137
- description: `Delete the GitHub MCP entry from ${agent}.`,
138
- command: agent === "codex" ? "codex mcp remove github" : "claude mcp remove --scope local github"
139
- }];
140
- }
141
- return agent === "codex"
142
- ? [{
143
- id: "github-codex-add",
144
- server: "github",
145
- agent,
146
- phase: "configure",
147
- title: "Register GitHub MCP in Codex",
148
- description: "Add the hosted GitHub MCP server and reference `GITHUB_PAT_TOKEN` for PAT auth.",
149
- command: `codex mcp add github --url ${GITHUB_REMOTE_URL} --bearer-token-env-var GITHUB_PAT_TOKEN`
150
- }]
151
- : [{
152
- id: "github-claude-add",
153
- server: "github",
154
- agent,
155
- phase: "configure",
156
- title: "Register GitHub MCP in Claude Code",
157
- description: "Add the hosted GitHub MCP server and inject the PAT from `GITHUB_PAT_TOKEN`.",
158
- command: `claude mcp add --transport http github ${GITHUB_REMOTE_URL} --header "Authorization: Bearer \${GITHUB_PAT_TOKEN:?Set GITHUB_PAT_TOKEN first}"`
159
- }];
160
- }
161
- function buildFigmaSteps(agent, mode) {
162
- if (mode === "uninstall") {
163
- return agent === "codex"
164
- ? [{
165
- id: "figma-codex-remove",
166
- server: "figma",
167
- agent,
168
- phase: "uninstall",
169
- title: "Remove Figma MCP config",
170
- description: "Delete the Figma MCP entry from Codex.",
171
- command: "codex mcp remove figma"
172
- }]
173
- : [{
174
- id: "figma-claude-remove",
175
- server: "figma",
176
- agent,
177
- phase: "uninstall",
178
- title: "Remove Figma MCP config",
179
- description: "Delete the Figma MCP entry from Claude Code.",
180
- command: "claude mcp remove --scope local figma"
181
- }];
182
- }
183
- return agent === "codex"
184
- ? [{
185
- id: "figma-codex-add",
186
- server: "figma",
187
- agent,
188
- phase: "configure",
189
- title: "Register Figma MCP in Codex",
190
- description: "Add the remote Figma MCP endpoint. Codex will prompt for authentication.",
191
- command: `codex mcp add figma --url ${FIGMA_REMOTE_URL}`
192
- }]
193
- : [{
194
- id: "figma-claude-add",
195
- server: "figma",
196
- agent,
197
- phase: "configure",
198
- title: "Register Figma MCP in Claude Code",
199
- description: "Add the remote Figma MCP endpoint over HTTP transport.",
200
- command: `claude mcp add --transport http figma ${FIGMA_REMOTE_URL}`
201
- }];
202
- }
203
- function buildShadcnSteps(agent, mode) {
204
- if (mode === "uninstall") {
205
- return [{
206
- id: `shadcn-${agent}-remove`,
207
- server: "shadcn",
208
- agent,
209
- phase: "uninstall",
210
- title: "Remove Shadcn MCP config",
211
- description: `Delete the Shadcn MCP entry from ${agent}.`,
212
- command: agent === "codex" ? "codex mcp remove shadcn" : "claude mcp remove --scope local shadcn"
213
- }];
214
- }
215
- return [{
216
- id: `shadcn-${agent}-add`,
217
- server: "shadcn",
218
- agent,
219
- phase: "configure",
220
- title: `Register Shadcn MCP in ${agent}`,
221
- description: "Configure the MCP client to launch `shadcn@latest mcp` over stdio.",
222
- command: agent === "codex"
223
- ? "codex mcp add shadcn -- npx shadcn@latest mcp"
224
- : "claude mcp add shadcn -- npx shadcn@latest mcp"
225
- }];
226
- }
227
- function buildStepsForServer(server, agent, mode) {
228
- if (server === "antd") {
229
- return buildAntdSteps(agent, mode);
230
- }
231
- if (server === "gitlab") {
232
- return buildGitLabSteps(agent, mode);
233
- }
234
- if (server === "github") {
235
- return buildGitHubSteps(agent, mode);
236
- }
237
- if (server === "figma") {
238
- return buildFigmaSteps(agent, mode);
239
- }
240
- return buildShadcnSteps(agent, mode);
241
- }
242
- function buildNotes(input) {
243
- const notes = [];
244
- if (input.servers.includes("antd")) {
245
- notes.push("Ant Design uses the official `antd mcp` stdio server from `@ant-design/cli` v6.3.5+.");
246
- if (input.mode === "uninstall") {
247
- notes.push("Removing Ant Design from the MCP client does not uninstall the global `@ant-design/cli` package.");
248
- }
249
- }
250
- if (input.servers.includes("gitlab")) {
251
- notes.push("GitLab defaults to the GitLab.com MCP endpoint. Self-managed GitLab instances still require a manual URL change.");
252
- if (input.agents.includes("claude") && input.mode === "install") {
253
- notes.push("After adding GitLab to Claude Code, open Claude and use `/mcp` to complete OAuth authorization.");
254
- }
255
- if (input.mode === "uninstall" && input.agents.includes("codex")) {
256
- notes.push("GitLab + Codex uninstall removes the MCP config only. It intentionally does not run `codex mcp logout gitlab`, so shared OAuth credentials are left untouched.");
257
- }
258
- }
259
- if (input.servers.includes("github")) {
260
- notes.push("GitHub remote MCP access requires a GitHub PAT. Use least-privilege scopes and keep the token out of source control.");
261
- if (input.agents.includes("codex")) {
262
- notes.push("Codex stores only the bearer-token environment variable name. Add `export GITHUB_PAT_TOKEN=<your-token>` to `~/.zshrc` or `~/.bashrc` and restart your terminal before launching Codex.");
263
- }
264
- if (input.agents.includes("claude")) {
265
- notes.push("Claude Code will store the expanded GitHub PAT in its MCP config when this install command runs. Remove the server or rotate the PAT if needed.");
266
- }
267
- }
268
- if (input.servers.includes("figma")) {
269
- notes.push("Figma recommends the remote MCP server and completes authentication with OAuth.");
270
- if (input.agents.includes("claude") && input.mode === "install") {
271
- notes.push("After adding Figma to Claude Code, open Claude and use `/mcp` to connect the server.");
272
- }
273
- if (input.mode === "uninstall" && input.agents.includes("codex")) {
274
- notes.push("Figma + Codex uninstall removes the MCP config only. It intentionally does not run `codex mcp logout figma`, so shared OAuth credentials are left untouched.");
275
- }
276
- }
277
- if (input.servers.includes("shadcn")) {
278
- notes.push("Shadcn runs as a stdio MCP server via `npx shadcn@latest mcp`.");
279
- notes.push("Shadcn expects a project-level `components.json`. The standard shadcn registry works without extra registry configuration.");
280
- if (input.agents.includes("codex")) {
281
- notes.push("Shadcn's official docs say the shadcn CLI cannot automatically update `~/.codex/config.toml`; this workflow uses Codex's own `codex mcp add` command to register the same stdio server.");
282
- }
283
- }
284
- return uniq(notes);
285
- }
286
- function buildPostInstallConfig(input) {
287
- if (input.mode === "uninstall") {
288
- return [];
289
- }
290
- const items = [];
291
- if (input.servers.includes("antd")) {
292
- items.push("Ant Design: no extra required configuration after registration. Optional: pin a specific docs version by changing the server args to `antd mcp --version <antd-version>`.");
293
- }
294
- if (input.servers.includes("gitlab")) {
295
- if (input.agents.includes("codex")) {
296
- items.push("GitLab + Codex: if the OAuth session is not already active, run `codex mcp login gitlab`. For self-managed GitLab, replace the default GitLab.com URL with your own instance URL.");
297
- }
298
- if (input.agents.includes("claude")) {
299
- items.push("GitLab + Claude: open Claude Code, run `/mcp`, select `gitlab`, then approve the OAuth request in your browser. Run `/mcp` again to verify the server shows as connected.");
300
- }
301
- }
302
- if (input.servers.includes("github")) {
303
- if (input.agents.includes("codex")) {
304
- items.push("GitHub + Codex: add `export GITHUB_PAT_TOKEN=<your-token>` to your shell profile (`~/.zshrc` or `~/.bashrc`), then restart your terminal before launching Codex. Ensure the PAT has the scopes you actually need (e.g. `repo`, `read:org`).");
305
- }
306
- if (input.agents.includes("claude")) {
307
- items.push("GitHub + Claude: no extra runtime configuration is needed if install succeeded, but the PAT used during install must have the required scopes. Rotate the PAT and reinstall the MCP entry if that token changes.");
308
- }
309
- }
310
- if (input.servers.includes("figma")) {
311
- if (input.agents.includes("codex")) {
312
- items.push("Figma + Codex: complete Figma OAuth when Codex prompts for it. If needed, run `codex mcp login figma` to re-trigger authentication.");
313
- }
314
- if (input.agents.includes("claude")) {
315
- items.push("Figma + Claude: open Claude Code, run `/mcp`, select `figma`, choose `Authenticate`, and approve `Allow Access` in the browser.");
316
- }
317
- items.push("Figma: for better output, keep working files open in Figma and consider adding Figma-specific rules/instructions for your agent.");
318
- }
319
- if (input.servers.includes("shadcn")) {
320
- items.push("Shadcn: ensure the project has a valid `components.json`. The default shadcn/ui registry works without extra registry configuration.");
321
- items.push("Shadcn: if you use private or third-party registries, add them under `registries` in `components.json` and provide any required secrets such as `REGISTRY_TOKEN` in `.env.local`.");
322
- }
323
- return uniq(items);
324
- }
325
- function hasCodexServerEntry(content, server) {
326
- const escaped = escapeRegExp(server);
327
- return new RegExp(`^\\s*\\[mcp_servers\\.${escaped}\\]\\s*$`, "m").test(content);
328
- }
329
- function getCodexServerSection(content, server) {
330
- if (!content) {
331
- return null;
332
- }
333
- const lines = content.split("\n");
334
- const escaped = escapeRegExp(server);
335
- const headerPattern = new RegExp(`^\\s*\\[mcp_servers\\.${escaped}\\]\\s*$`);
336
- const nextSectionPattern = /^\s*\[\[?.+\]?\]\s*$/;
337
- const startIndex = lines.findIndex((line) => headerPattern.test(line));
338
- if (startIndex === -1) {
339
- return null;
340
- }
341
- const sectionLines = [lines[startIndex]];
342
- for (let index = startIndex + 1; index < lines.length; index += 1) {
343
- const line = lines[index];
344
- if (nextSectionPattern.test(line)) {
345
- break;
346
- }
347
- sectionLines.push(line);
348
- }
349
- return sectionLines.join("\n");
350
- }
351
- async function readFileIfExists(targetPath) {
352
- try {
353
- return await readFile(targetPath, "utf8");
354
- }
355
- catch {
356
- return null;
357
- }
358
- }
359
- function getClaudeProjectLocalServer(content, cwd, server) {
360
- if (!content) {
361
- return false;
362
- }
363
- try {
364
- const parsed = JSON.parse(content);
365
- return Boolean(parsed.projects?.[cwd]?.mcpServers?.[server]);
366
- }
367
- catch {
368
- return false;
369
- }
370
- }
371
- function getClaudeUserServer(content, server) {
372
- if (!content) {
373
- return false;
374
- }
375
- try {
376
- const parsed = JSON.parse(content);
377
- return Boolean(parsed.mcpServers?.[server]);
378
- }
379
- catch {
380
- return false;
381
- }
382
- }
383
- function getClaudeProjectScopeServer(content, server) {
384
- if (!content) {
385
- return false;
386
- }
387
- try {
388
- const parsed = JSON.parse(content);
389
- return Boolean(parsed.mcpServers?.[server]);
390
- }
391
- catch {
392
- return false;
393
- }
394
- }
395
- function describeAgent(agent) {
396
- return agent === "codex" ? "Codex" : "Claude";
397
- }
398
- function getStepAgent(step) {
399
- return step.agent;
400
- }
401
- function codexIdentityMatches(server, section) {
402
- if (!section) {
403
- return false;
404
- }
405
- if (server === "antd") {
406
- return /command\s*=\s*"antd"/.test(section) && /args\s*=\s*\[[^\]]*"mcp"[^\]]*\]/.test(section);
407
- }
408
- if (server === "shadcn") {
409
- return /command\s*=\s*"npx"/.test(section)
410
- && /args\s*=\s*\[[^\]]*"shadcn@latest"[^\]]*"mcp"[^\]]*\]/.test(section);
411
- }
412
- if (server === "gitlab") {
413
- return new RegExp(`url\\s*=\\s*"${escapeRegExp(GITLAB_REMOTE_URL)}"`).test(section);
414
- }
415
- if (server === "github") {
416
- return new RegExp(`url\\s*=\\s*"${escapeRegExp(GITHUB_REMOTE_URL)}"`).test(section)
417
- && /bearer_token_env_var\s*=\s*"GITHUB_PAT_TOKEN"/.test(section);
418
- }
419
- return new RegExp(`url\\s*=\\s*"${escapeRegExp(FIGMA_REMOTE_URL)}"`).test(section);
420
- }
421
- function isRecord(value) {
422
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
423
- }
424
- function arrayIncludesStrings(value, expected) {
425
- if (!Array.isArray(value) || value.length !== expected.length) {
426
- return false;
427
- }
428
- return expected.every((item, index) => value[index] === item);
429
- }
430
- function claudeIdentityMatches(server, entry) {
431
- if (!isRecord(entry)) {
432
- return false;
433
- }
434
- if (server === "antd") {
435
- return entry.command === "antd" && arrayIncludesStrings(entry.args, ["mcp"]);
436
- }
437
- if (server === "shadcn") {
438
- return entry.command === "npx" && arrayIncludesStrings(entry.args, ["shadcn@latest", "mcp"]);
439
- }
440
- if (server === "gitlab") {
441
- return entry.type === "http" && entry.url === GITLAB_REMOTE_URL;
442
- }
443
- if (server === "github") {
444
- return entry.type === "http" && entry.url === GITHUB_REMOTE_URL;
445
- }
446
- return entry.type === "http" && entry.url === FIGMA_REMOTE_URL;
447
- }
448
- async function createBackupIfExists(targetPath) {
449
- const content = await readFileIfExists(targetPath);
450
- if (content === null) {
451
- return null;
452
- }
453
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
454
- const backupPath = `${targetPath}.ai-tools-backup-${timestamp}`;
455
- await copyFile(targetPath, backupPath);
456
- return backupPath;
457
- }
458
- export async function createMcpUninstallBackups(input) {
459
- const targets = new Set();
460
- const homeDir = os.homedir();
461
- for (const step of input.steps) {
462
- const agent = getStepAgent(step);
463
- if (agent === "codex") {
464
- targets.add(path.join(homeDir, ".codex", "config.toml"));
465
- }
466
- else {
467
- targets.add(path.join(homeDir, ".claude.json"));
468
- }
469
- }
470
- const backups = await Promise.all([...targets].map((target) => createBackupIfExists(target)));
471
- return backups.filter((item) => Boolean(item));
472
- }
473
- export async function inspectMcpUninstallSafety(input) {
474
- if (input.plan.mode !== "uninstall") {
475
- return {
476
- effectiveSteps: input.plan.steps,
477
- safeNotes: [],
478
- skippedSteps: [],
479
- backupTargets: []
480
- };
481
- }
482
- const homeDir = os.homedir();
483
- const codexUserConfigPath = path.join(homeDir, ".codex", "config.toml");
484
- const codexProjectConfigPath = path.join(input.cwd, ".codex", "config.toml");
485
- const claudeHomeConfigPath = path.join(homeDir, ".claude.json");
486
- const claudeProjectConfigPath = path.join(input.cwd, ".mcp.json");
487
- const [codexUserConfig, codexProjectConfig, claudeHomeConfig, claudeProjectConfig] = await Promise.all([
488
- readFileIfExists(codexUserConfigPath),
489
- readFileIfExists(codexProjectConfigPath),
490
- readFileIfExists(claudeHomeConfigPath),
491
- readFileIfExists(claudeProjectConfigPath)
492
- ]);
493
- const effectiveSteps = [];
494
- const safeNotes = [];
495
- const skippedSteps = [];
496
- for (const step of input.plan.steps) {
497
- const agent = getStepAgent(step);
498
- const label = `${describeAgent(agent)} ${step.server}`;
499
- if (agent === "codex") {
500
- const existsInUser = codexUserConfig ? hasCodexServerEntry(codexUserConfig, step.server) : false;
501
- const existsInProject = codexProjectConfig ? hasCodexServerEntry(codexProjectConfig, step.server) : false;
502
- const userSection = getCodexServerSection(codexUserConfig, step.server);
503
- const userIdentityMatches = codexIdentityMatches(step.server, userSection);
504
- if (!existsInUser) {
505
- skippedSteps.push({
506
- step,
507
- reason: `${label}: no matching user-scoped entry was found in ${codexUserConfigPath}, so this remove step will be skipped.`
508
- });
509
- }
510
- else if (!userIdentityMatches) {
511
- skippedSteps.push({
512
- step,
513
- reason: `${label}: a user-scoped entry named "${step.server}" exists in ${codexUserConfigPath}, but it does not match the MCP identity this installer manages, so uninstall will skip it for safety.`
514
- });
515
- }
516
- else {
517
- effectiveSteps.push(step);
518
- safeNotes.push(`${label}: uninstall will remove only the entry in ${codexUserConfigPath}.`);
519
- }
520
- if (existsInProject) {
521
- safeNotes.push(`${label}: a project-scoped entry also exists in ${codexProjectConfigPath}; Codex will still see that entry after uninstall because ` + "`codex mcp remove`" + ` does not edit project config files.`);
522
- }
523
- continue;
524
- }
525
- const existsInLocal = getClaudeProjectLocalServer(claudeHomeConfig, input.cwd, step.server);
526
- const existsInUser = getClaudeUserServer(claudeHomeConfig, step.server);
527
- const existsInProject = getClaudeProjectScopeServer(claudeProjectConfig, step.server);
528
- let localEntry = null;
529
- if (claudeHomeConfig) {
530
- try {
531
- const parsed = JSON.parse(claudeHomeConfig);
532
- localEntry = parsed.projects?.[input.cwd]?.mcpServers?.[step.server] ?? null;
533
- }
534
- catch {
535
- localEntry = null;
536
- }
537
- }
538
- if (!existsInLocal) {
539
- skippedSteps.push({
540
- step,
541
- reason: `${label}: no matching local-scope entry was found for this project in ${claudeHomeConfigPath}, so this remove step will be skipped.`
542
- });
543
- }
544
- else if (!claudeIdentityMatches(step.server, localEntry)) {
545
- skippedSteps.push({
546
- step,
547
- reason: `${label}: a local-scope entry named "${step.server}" exists for this project in ${claudeHomeConfigPath}, but it does not match the MCP identity this installer manages, so uninstall will skip it for safety.`
548
- });
549
- }
550
- else {
551
- effectiveSteps.push(step);
552
- safeNotes.push(`${label}: uninstall targets only the local-scope entry for ${input.cwd} stored in ${claudeHomeConfigPath}.`);
553
- }
554
- if (existsInProject) {
555
- safeNotes.push(`${label}: a project-scoped entry also exists in ${claudeProjectConfigPath}; it will not be removed because this workflow uses ` + "`claude mcp remove --scope local`" + ` for safety.`);
556
- }
557
- if (existsInUser) {
558
- safeNotes.push(`${label}: a user-scoped entry also exists in ${claudeHomeConfigPath}; it will not be removed because this workflow uses ` + "`claude mcp remove --scope local`" + ` for safety.`);
559
- }
560
- }
561
- return {
562
- effectiveSteps,
563
- safeNotes: uniq(safeNotes),
564
- skippedSteps,
565
- backupTargets: uniq([
566
- ...effectiveSteps.filter((step) => getStepAgent(step) === "codex").map(() => codexUserConfigPath),
567
- ...effectiveSteps.filter((step) => getStepAgent(step) === "claude").map(() => claudeHomeConfigPath)
568
- ])
569
- };
570
- }
571
- function formatMcpSteps(steps) {
572
- if (steps.length === 0) {
573
- return "(none)";
574
- }
575
- return steps.map((step) => `${step.id} -> ${step.command}`).join("; ");
576
- }
577
- function isSameMcpStep(left, right) {
578
- return left.id === right.id
579
- && left.server === right.server
580
- && left.phase === right.phase
581
- && left.command === right.command;
582
- }
583
- export async function verifyMcpUninstallExecutionSafety(input) {
584
- if (input.originalPlan.mode !== "uninstall") {
585
- return {
586
- effectiveSteps: input.expectedSteps,
587
- safeNotes: [],
588
- skippedSteps: [],
589
- backupTargets: []
590
- };
591
- }
592
- const refreshedReport = await inspectMcpUninstallSafety({
593
- cwd: input.cwd,
594
- plan: input.originalPlan
595
- });
596
- const originalStepsById = new Map(input.originalPlan.steps.map((step) => [step.id, step]));
597
- const everyExpectedStepIsCanonical = input.expectedSteps.every((step) => {
598
- const canonicalStep = originalStepsById.get(step.id);
599
- return canonicalStep ? isSameMcpStep(step, canonicalStep) : false;
600
- });
601
- if (!everyExpectedStepIsCanonical) {
602
- throw new Error("MCP uninstall safety verification failed because one or more removal commands no longer match the canonical uninstall plan.");
603
- }
604
- const stepsStillMatch = refreshedReport.effectiveSteps.length === input.expectedSteps.length
605
- && refreshedReport.effectiveSteps.every((step, index) => isSameMcpStep(step, input.expectedSteps[index]));
606
- if (!stepsStillMatch) {
607
- throw new Error(`MCP uninstall safety verification failed because the allowed uninstall steps changed after preflight. `
608
- + `Expected ${formatMcpSteps(input.expectedSteps)}. `
609
- + `Current ${formatMcpSteps(refreshedReport.effectiveSteps)}. `
610
- + "Re-run the uninstall flow and review the current MCP config before removing anything.");
611
- }
612
- return refreshedReport;
613
- }
614
- export function buildMcpInstallPlan(input) {
615
- const agents = uniq(input.agents);
616
- const servers = uniq(input.servers);
617
- const allSteps = agents.flatMap((agent) => servers.flatMap((server) => buildStepsForServer(server, agent, input.mode)));
618
- const seen = new Set();
619
- const steps = allSteps.filter((step) => {
620
- if (seen.has(step.id))
621
- return false;
622
- seen.add(step.id);
623
- return true;
624
- });
625
- return {
626
- mode: input.mode,
627
- agents,
628
- servers,
629
- os: input.os,
630
- steps,
631
- notes: buildNotes({
632
- agents,
633
- mode: input.mode,
634
- servers
635
- }),
636
- postInstallConfig: buildPostInstallConfig({
637
- agents,
638
- mode: input.mode,
639
- servers
640
- }),
641
- sources: servers.map((server) => MCP_SOURCES[server])
642
- };
643
- }
644
- export async function executeMcpInstallPlan(input) {
645
- for (const step of input.plan.steps) {
646
- input.onProgress?.(step);
647
- await runShellCommand(step.command, input.cwd);
648
- }
649
- }
650
- function runShellCommand(command, cwd) {
651
- return new Promise((resolve, reject) => {
652
- const child = spawn("/bin/sh", ["-lc", command], {
653
- cwd,
654
- stdio: "inherit"
655
- });
656
- child.on("error", reject);
657
- child.on("close", (code) => {
658
- if (code === 0) {
659
- resolve();
660
- return;
661
- }
662
- reject(new Error(`Command failed with exit code ${code}: ${command}`));
663
- });
664
- });
665
- }