-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.ts
More file actions
1704 lines (1557 loc) · 59.9 KB
/
Copy pathindex.ts
File metadata and controls
1704 lines (1557 loc) · 59.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawnSync } from "node:child_process";
import {
chmodSync,
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
renameSync,
rmSync,
statSync,
writeFileSync
} from "node:fs";
import { homedir } from "node:os";
import { dirname, join, sep } from "node:path";
import {
IDE_METADATA,
MCP_TRANSPORT_DEFAULT,
PERPLEXITY_MCP_SERVER_KEY,
PERPLEXITY_RULES_SECTION_START,
PERPLEXITY_RULES_SECTION_END,
type IdeMeta,
type IdeStatus,
type IdeTarget,
type McpTransportId,
type RulesStatus
} from "@perplexity-user-mcp/shared";
import { checkLauncherHealth } from "../launcher/write-launcher.js";
import { validateCommand } from "../launcher/validate-command.js";
import {
getTransportBuilder,
StabilityGateError,
type McpServerEntry,
} from "./transports/index.js";
interface McpConfigFile {
mcpServers?: Record<string, unknown>;
servers?: Record<string, unknown>;
context_servers?: Record<string, unknown>;
mcp?: Record<string, unknown>;
[key: string]: unknown;
}
type JsonConfigRootKey = NonNullable<IdeMeta["jsonConfigRootKey"]>;
export interface IdeConfigOptions {
target: IdeTarget;
serverPath: string;
chromePath?: string;
configPath?: string;
nodePath?: string;
serverName?: string;
// Phase 8.6.4: transport picker. `undefined` defaults to the workspace-wide
// MCP_TRANSPORT_DEFAULT so callers pre-dating the picker keep working.
transportId?: McpTransportId;
}
/**
* Phase 8.6.4 dispatch dependencies. All fields optional — omitted defaults
* are safe-for-tests (no real VS Code, no real git spawn, no prompts) so any
* call site that passes `undefined` won't accidentally reach out to the host.
*/
export interface ApplyIdeConfigDeps {
confirmTransport?: (args: {
ideTag: IdeTarget;
transportId: McpTransportId;
configPath: string;
}) => Promise<boolean>;
warnSyncFolder?: (args: {
configPath: string;
matchedPattern: string;
}) => Promise<"override" | "cancel">;
nudgePortPin?: (args: { ideTag: IdeTarget }) => void;
auditGenerated?: (entry: {
ideTag: IdeTarget;
transportId: McpTransportId;
configPath: string;
bearerKind: "none" | "local" | "static";
resultCode:
| "ok"
| "rejected-unsupported"
| "rejected-sync"
| "rejected-tunnel-unstable"
| "rejected-cancelled"
| "rejected-port-unavailable"
| "error";
ts: string;
}) => void;
issueLocalToken?: (input: { ideTag: string; label: string }) => {
token: string;
metadata: { id: string };
};
/** Reads the daemon's static bearer token. Loopback-only use — tunnel paths never embed this. Default: throws "not provided". */
getDaemonBearer?: () => Promise<string | null>;
getDaemonPort?: () => number | null;
getActiveTunnel?: () => {
providerId: "cf-quick" | "ngrok" | "cf-named";
url: string;
reservedDomain: boolean;
} | null;
syncFolderPatterns?: readonly string[];
homeDir?: () => string;
isGitTracked?: (dir: string) => boolean;
}
export type ApplyIdeConfigResult =
| {
ok: true;
path: string;
bearerKind: "none" | "local" | "static";
transportId: McpTransportId;
warnings: string[];
}
| {
ok: false;
reason:
| "unsupported"
| "cancelled"
| "sync-folder"
| "tunnel-unstable"
| "port-unavailable"
| "error";
message: string;
transportId: McpTransportId;
};
export function getIdeConfigPath(
target: IdeTarget,
options?: { homeDir?: string; platform?: NodeJS.Platform; workspaceRoot?: string }
): string {
const home = options?.homeDir ?? homedir();
const platform = options?.platform ?? process.platform;
const appData = process.env.APPDATA ?? join(home, "AppData", "Roaming");
const workspaceRoot = options?.workspaceRoot;
switch (target) {
case "cursor":
return join(home, ".cursor", "mcp.json");
case "windsurf":
return join(home, ".codeium", "windsurf", "mcp_config.json");
case "windsurfNext":
return join(home, ".codeium", "windsurf-next", "mcp_config.json");
case "claudeDesktop":
if (platform === "win32") return join(appData, "Claude", "claude_desktop_config.json");
if (platform === "darwin") return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
return join(home, ".config", "Claude", "claude_desktop_config.json");
case "claudeCode":
return join(home, ".claude.json");
case "cline":
return join(home, ".cline", "data", "settings", "cline_mcp_settings.json");
case "amp":
if (platform === "win32") return join(appData, "amp", "settings.json");
return join(home, ".config", "amp", "settings.json");
case "rooCode":
return join(home, ".roo", "mcp.json");
case "codexCli":
return join(home, ".codex", "config.toml");
case "continueDev":
return join(home, ".continue", "config.yaml");
case "copilot":
return join(home, ".github", "copilot-instructions.md");
case "vscode":
return workspaceRoot ? join(workspaceRoot, ".vscode", "mcp.json") : join(home, ".vscode", "mcp.json");
case "zed":
if (platform === "darwin") return join(home, "Library", "Application Support", "Zed", "settings.json");
return join(home, ".local", "share", "zed", "settings.json");
case "geminiCli":
return join(home, ".gemini", "settings.json");
case "antigravity":
return join(home, ".gemini", "antigravity", "mcp_config.json");
case "kiro":
return join(home, ".kiro", "settings", "mcp.json");
case "firebaseStudio":
return workspaceRoot ? join(workspaceRoot, ".idx", "mcp.json") : join(home, ".idx", "mcp.json");
case "amazonQ":
return join(home, ".aws", "amazonq", "default.json");
case "goose":
if (platform === "win32") return join(appData, "Block", "goose", "config", "config.yaml");
return join(home, ".config", "goose", "config.yaml");
case "trae":
return workspaceRoot ? join(workspaceRoot, ".trae", "mcp.json") : join(home, ".trae", "mcp.json");
case "warp":
// Warp's MCP is GUI-only; this path is a detection sentinel, not a write
// target. `~/.warp/` is created by Warp on first launch (mac/linux), so
// checking dirname-existence answers "is Warp installed for this user".
return join(home, ".warp", "mcp.json");
case "aider":
return join(home, ".aider.conf.yml");
case "augment":
return join(home, ".augment", "rules");
case "vs2022":
// Per Microsoft docs, VS 2022 reads `<sln>/.mcp.json` first (source-controlled
// option). User-global fallback is `%USERPROFILE%\.mcp.json` (dot-prefixed).
return workspaceRoot ? join(workspaceRoot, ".mcp.json") : join(home, ".mcp.json");
case "copilotCli":
return join(home, ".copilot", "mcp-config.json");
case "openCode":
// User-scoped path; Vite-style $HOME/.config tree on all platforms per docs.
return join(home, ".config", "opencode", "opencode.json");
case "factoryDroid":
return join(home, ".factory", "mcp.json");
case "qwenCode":
return join(home, ".qwen", "settings.json");
case "kiloCode":
// Detection sentinel; kilo.jsonc not auto-written (needs JSONC writer).
return join(home, ".config", "kilo", "kilo.jsonc");
case "lmStudio":
// ui-only; detection sentinel pointing at LM Studio's app data dir.
if (platform === "win32") return join(appData, "LM Studio", "mcp.json");
if (platform === "darwin") return join(home, ".cache", "lm-studio", "mcp.json");
return join(home, ".cache", "lm-studio", "mcp.json");
}
}
/**
* Resolve a working Node.js executable path.
* In VSCode/Windsurf extension host, `process.execPath` returns the IDE binary
* (e.g. "Windsurf - Next.exe"), NOT node. We need to find actual node.
*
* Exported so the staleness auto-regen path in `regenerateStaleIdes` can reuse
* the same resolution rules without duplicating the candidate ladder.
*/
export function resolveNodePath(): string {
const log = (msg: string) => { try { console.error(`[resolveNodePath] ${msg}`); } catch {} };
log(`process.execPath = ${process.execPath}`);
log(`process.platform = ${process.platform}`);
log(`PROGRAMFILES = ${process.env.PROGRAMFILES}`);
// 1. Explicit override
if (process.env.PERPLEXITY_NODE_PATH && existsSync(process.env.PERPLEXITY_NODE_PATH)) {
log(`Using PERPLEXITY_NODE_PATH: ${process.env.PERPLEXITY_NODE_PATH}`);
return process.env.PERPLEXITY_NODE_PATH;
}
// 2. Check if process.execPath is actually node (standalone MCP usage)
const execName = process.execPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? "";
log(`execName = ${execName}`);
if (execName.startsWith("node")) {
log(`process.execPath is node: ${process.execPath}`);
return process.execPath;
}
// 3. Well-known node locations
const candidates: string[] = [];
if (process.platform === "win32") {
const pf = process.env.PROGRAMFILES ?? "C:\\Program Files";
candidates.push(
join(pf, "nodejs", "node.exe"),
join(process.env.LOCALAPPDATA ?? "", "Programs", "nodejs", "node.exe"),
join(process.env.APPDATA ?? "", "nvm", "current", "node.exe"),
);
} else {
candidates.push(
"/usr/local/bin/node",
"/usr/bin/node",
join(homedir(), ".nvm", "current", "bin", "node"),
);
}
for (const p of candidates) {
const found = existsSync(p);
log(`Checking ${p} → ${found}`);
if (p && found) return p;
}
// 4. Fallback — just "node" and hope it's on PATH
log("Falling back to bare 'node'");
return "node";
}
export function buildServerConfig(serverPath: string, options?: { nodePath?: string; chromePath?: string }): Record<string, unknown> {
const env: Record<string, string> = {
PERPLEXITY_HEADLESS_ONLY: "1"
};
if (options?.chromePath) {
env.PERPLEXITY_CHROME_PATH = options.chromePath;
}
return {
command: options?.nodePath ?? resolveNodePath(),
args: [serverPath],
env
};
}
function getJsonConfigRootKey(meta: IdeMeta | undefined): JsonConfigRootKey {
return meta?.jsonConfigRootKey ?? "mcpServers";
}
function normalizeJsonServerConfig(meta: IdeMeta, serverConfig: McpServerEntry): Record<string, unknown> {
if (meta.jsonServerEntryFormat === "opencode") {
return normalizeOpenCodeServerConfig(serverConfig);
}
const normalized: Record<string, unknown> = { ...serverConfig };
if (meta.jsonServerTypeField && !("type" in normalized)) {
normalized.type = "command" in serverConfig ? "stdio" : "http";
}
return normalized;
}
function normalizeOpenCodeServerConfig(serverConfig: McpServerEntry): Record<string, unknown> {
if ("url" in serverConfig) {
return {
type: "remote",
url: serverConfig.url,
enabled: true,
...(serverConfig.headers ? { headers: serverConfig.headers } : {}),
};
}
return {
type: "local",
command: [serverConfig.command, ...serverConfig.args],
enabled: true,
...(serverConfig.env ? { environment: serverConfig.env } : {}),
};
}
export function mergeMcpConfig(
existingConfig: unknown,
serverName: string,
serverConfig: Record<string, unknown>,
rootKey: JsonConfigRootKey = "mcpServers"
): McpConfigFile {
const safeExisting =
existingConfig && typeof existingConfig === "object" && !Array.isArray(existingConfig)
? (existingConfig as McpConfigFile)
: {};
const existingServers =
safeExisting[rootKey] && typeof safeExisting[rootKey] === "object" && !Array.isArray(safeExisting[rootKey])
? (safeExisting[rootKey] as Record<string, unknown>)
: {};
return {
...safeExisting,
[rootKey]: {
...existingServers,
[serverName]: serverConfig
}
};
}
export function removeMcpEntry(
existingConfig: unknown,
serverName: string,
rootKey: JsonConfigRootKey = "mcpServers"
): McpConfigFile {
const safeExisting =
existingConfig && typeof existingConfig === "object" && !Array.isArray(existingConfig)
? (existingConfig as McpConfigFile)
: {};
const existingServers =
safeExisting[rootKey] && typeof safeExisting[rootKey] === "object" && !Array.isArray(safeExisting[rootKey])
? { ...(safeExisting[rootKey] as Record<string, unknown>) }
: {};
delete existingServers[serverName];
return {
...safeExisting,
[rootKey]: existingServers
};
}
function readExistingConfig(configPath: string): McpConfigFile {
if (!existsSync(configPath)) {
return {};
}
try {
return JSON.parse(readFileSync(configPath, "utf8")) as McpConfigFile;
} catch (error) {
throw new Error(`Invalid JSON in ${configPath}: ${(error as Error).message}`);
}
}
/* ─── Minimal TOML helpers for Codex CLI config ─── */
function readTomlFile(configPath: string): string {
if (!existsSync(configPath)) return "";
return readFileSync(configPath, "utf8");
}
function tomlHasMcpServer(toml: string, serverName: string): boolean {
return extractTomlMcpServerBlock(toml, serverName) !== null;
}
function extractTomlMcpServerBlock(toml: string, serverName: string): string | null {
const sectionHeader = `[mcp_servers.${serverName}]`;
const startIdx = toml.indexOf(sectionHeader);
if (startIdx === -1) return null;
const afterHeader = startIdx + sectionHeader.length;
const remaining = toml.slice(afterHeader);
const lines = remaining.split("\n");
let endOffset = remaining.length;
let offset = 0;
for (const line of lines) {
const trimmed = line.trim();
if (
trimmed.startsWith("[") &&
trimmed.endsWith("]") &&
!trimmed.startsWith(`[mcp_servers.${serverName}.`)
) {
endOffset = offset;
break;
}
offset += line.length + 1;
}
return remaining.slice(0, endOffset);
}
function buildTomlMcpBlock(serverName: string, serverConfig: Record<string, unknown>): string {
const lines: string[] = [];
lines.push(`[mcp_servers.${serverName}]`);
if (typeof serverConfig.url === "string") {
lines.push(`url = ${JSON.stringify(serverConfig.url)}`);
const bearer = extractBearerToken(serverConfig.headers);
const envVarName = `${serverName.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_MCP_BEARER`;
if (bearer) {
lines.push(`bearer_token_env_var = ${JSON.stringify(envVarName)}`);
}
lines.push(`enabled = true`);
if (bearer) {
lines.push("");
lines.push(`[mcp_servers.${serverName}.env_http_headers]`);
lines.push(`${envVarName} = ${JSON.stringify(bearer)}`);
}
return lines.join("\n");
}
lines.push(`command = ${JSON.stringify(serverConfig.command)}`);
const args = serverConfig.args as string[] | undefined;
if (args?.length) {
lines.push(`args = [${args.map(a => JSON.stringify(a)).join(", ")}]`);
}
lines.push(`enabled = true`);
const env = serverConfig.env as Record<string, string> | undefined;
if (env && Object.keys(env).length > 0) {
lines.push("");
lines.push(`[mcp_servers.${serverName}.env]`);
for (const [k, v] of Object.entries(env)) {
lines.push(`${k} = ${JSON.stringify(v)}`);
}
}
return lines.join("\n");
}
function extractBearerToken(headers: unknown): string | null {
if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
return null;
}
const authorization = (headers as Record<string, unknown>).Authorization;
if (typeof authorization !== "string") {
return null;
}
const match = authorization.match(/^Bearer\s+(.+)$/i);
return match?.[1] ?? null;
}
function mergeTomlMcpServer(
toml: string,
serverName: string,
serverConfig: Record<string, unknown>,
): string {
const block = buildTomlMcpBlock(serverName, serverConfig);
if (tomlHasMcpServer(toml, serverName)) {
// Replace existing block: find [mcp_servers.<name>] and replace up to next [section] or EOF
const sectionHeader = `[mcp_servers.${serverName}]`;
const envHeader = `[mcp_servers.${serverName}.env]`;
const startIdx = toml.indexOf(sectionHeader);
if (startIdx === -1) return toml + "\n\n" + block + "\n";
// Find the end: next top-level section that isn't our .env sub-section
let endIdx = toml.length;
const searchFrom = startIdx + sectionHeader.length;
const nextSectionRegex = /^\[(?!mcp_servers\.\S+\.env\b)/m;
// Find all [...] headers after our section
const remaining = toml.slice(searchFrom);
const lines = remaining.split("\n");
let offset = searchFrom;
let passedEnv = false;
for (const line of lines) {
const trimmed = line.trimStart();
if (trimmed === envHeader) {
passedEnv = true;
offset += line.length + 1;
continue;
}
if (trimmed.startsWith("[") && !trimmed.startsWith(`[mcp_servers.${serverName}`)) {
endIdx = offset;
break;
}
offset += line.length + 1;
}
const before = toml.slice(0, startIdx).trimEnd();
const after = toml.slice(endIdx).trimStart();
return (before ? before + "\n\n" : "") + block + "\n" + (after ? "\n" + after : "");
}
// Append new block
const trimmed = toml.trimEnd();
return (trimmed ? trimmed + "\n\n" : "") + block + "\n";
}
function removeTomlMcpServer(toml: string, serverName: string): string {
if (!tomlHasMcpServer(toml, serverName)) return toml;
const sectionHeader = `[mcp_servers.${serverName}]`;
const startIdx = toml.indexOf(sectionHeader);
if (startIdx === -1) return toml;
// Find end of this server's block
const searchFrom = startIdx + sectionHeader.length;
const remaining = toml.slice(searchFrom);
const lines = remaining.split("\n");
let offset = searchFrom;
let endIdx = toml.length;
for (const line of lines) {
const trimmed = line.trimStart();
if (trimmed.startsWith("[") && !trimmed.startsWith(`[mcp_servers.${serverName}`)) {
endIdx = offset;
break;
}
offset += line.length + 1;
}
const before = toml.slice(0, startIdx).trimEnd();
const after = toml.slice(endIdx).trimStart();
return (before ? before + "\n" : "") + (after ? "\n" + after : "");
}
function writeJsonAtomic(configPath: string, data: McpConfigFile): void {
mkdirSync(dirname(configPath), { recursive: true });
const tempPath = `${configPath}.tmp`;
// H3 invariant: the tempfile may transiently contain a bearer token during
// http-loopback bearer-kind writes. `writeFileSync`'s default mode is 0o666
// minus umask (typically 0o644, world-readable) — unacceptable for secrets.
// Match `writeTextAtomic` and the `.bak` hygiene: open at 0o600 on POSIX,
// then run `applyPrivatePermissions` (chmod/icacls) BEFORE the rename so the
// target inherits the hardened ACL.
writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
applyPrivatePermissions(tempPath);
renameSync(tempPath, configPath);
}
/**
* Phase 8.6.4 dispatch pipeline. The pre-phase applyIdeConfig synchronously
* merged a fixed stdio server entry; this version routes through the transport
* registry with H3–H8 security prechecks (capability gate, sync-folder detection,
* confirmation modal, port-pin nudge, sanitized .bak, audit sink). Callers that
* used the v1 sync signature must migrate to `await`; tests silently accept
* via the injectable `deps` defaults.
*/
export async function applyIdeConfig(
options: IdeConfigOptions,
deps: ApplyIdeConfigDeps = {}
): Promise<ApplyIdeConfigResult> {
const target = options.target;
const transportId: McpTransportId = options.transportId ?? MCP_TRANSPORT_DEFAULT;
const meta = IDE_METADATA[target];
const configPath = options.configPath ?? getIdeConfigPath(target);
const serverName = options.serverName ?? PERPLEXITY_MCP_SERVER_KEY;
const homeDir = deps.homeDir ?? (() => homedir());
const auditSink = deps.auditGenerated ?? (() => {});
const confirm = deps.confirmTransport ?? (async () => true);
const warnSync = deps.warnSyncFolder ?? (async () => "cancel" as const);
const nudgePort = deps.nudgePortPin ?? (() => {});
const getDaemonPort = deps.getDaemonPort ?? (() => null);
const getActiveTunnel = deps.getActiveTunnel ?? (() => null);
const syncFolderPatterns = deps.syncFolderPatterns ?? [];
const isGitTracked = deps.isGitTracked ?? defaultIsGitTracked;
const issueLocalToken = deps.issueLocalToken ?? defaultIssueLocalToken;
const audit = (
resultCode: Parameters<NonNullable<ApplyIdeConfigDeps["auditGenerated"]>>[0]["resultCode"],
bearerKind: "none" | "local" | "static"
): void => {
auditSink({
ideTag: target,
transportId,
configPath: redactHome(configPath, homeDir()),
bearerKind,
resultCode,
ts: new Date().toISOString(),
});
};
if (!meta) {
const message = `Unknown IDE target "${target}".`;
audit("rejected-unsupported", "none");
return { ok: false, reason: "unsupported", message, transportId };
}
// H3 guard — legacy callers relied on `autoConfigurable` as a whole-IDE gate.
// Keep respecting it: if the IDE isn't auto-configurable at all, refuse.
if (!meta.autoConfigurable) {
const message = `${meta.displayName} does not support automatic MCP configuration.`;
audit("rejected-unsupported", "none");
return { ok: false, reason: "unsupported", message, transportId };
}
// H3 — capability gate. Each transport maps to one or more capability flags.
// No flag is ever flipped `true` without smoke evidence (see shared/constants.ts).
const caps = meta.capabilities;
const capabilityOk =
transportId === "stdio-in-process" || transportId === "stdio-daemon-proxy"
? caps.stdio
: transportId === "http-loopback"
? caps.httpOAuthLoopback || caps.httpBearerLoopback
: transportId === "http-tunnel"
? caps.httpOAuthTunnel
: false;
if (!capabilityOk) {
const message =
`${meta.displayName} does not support transport ${transportId}. ` +
`Enable the capability in constants.ts (requires smoke evidence).`;
audit("rejected-unsupported", "none");
return { ok: false, reason: "unsupported", message, transportId };
}
// Format gate. Builders declare which native config formats they can emit;
// http-loopback supports JSON clients and Codex's streamable-HTTP TOML shape.
const builder = getTransportBuilder(transportId);
const configFormat = meta.configFormat;
if (configFormat !== "json" && configFormat !== "toml") {
// Non-JSON/TOML formats (yaml, ui-only) are outside 8.6.4 scope.
const message = `${meta.displayName} config format "${configFormat}" is not supported by transport ${transportId}.`;
audit("rejected-unsupported", "none");
return { ok: false, reason: "unsupported", message, transportId };
}
if (!builder.supportedFormats.includes(configFormat)) {
const message = `Transport ${transportId} cannot emit ${configFormat} (supported: ${builder.supportedFormats.join(", ")}).`;
audit("rejected-unsupported", "none");
return { ok: false, reason: "unsupported", message, transportId };
}
// Decide bearer fate BEFORE any prompt so the sync-folder warning below
// can accurately skip for the no-secret-written paths.
//
// Priority order for http-loopback:
// 1. httpOAuthLoopback → "none" (OAuth variant; no IDE has this flag yet,
// but the branch stays so a future evidence-gated flip lights up cleanly).
// 2. httpBearerLoopback → "static" (v0.8.4 pragmatic default — embeds the
// daemon's shared static bearer; accepted on loopback by the daemon).
// 3. fallback → "local" (per-IDE scoped; primitives stay for future flip).
const bearerKind: "none" | "local" | "static" =
transportId === "http-loopback"
? caps.httpOAuthLoopback
? "none"
: caps.httpBearerLoopback
? "static"
: "local"
: "none";
// H4 — sync-folder detection. Only http-loopback with a secret-bearing bearer
// kind actually writes a secret to disk; stdio stores no secret at all, and
// http-tunnel intentionally refuses to bake a bearer into a public-URL config.
const syncFolderApplies =
transportId === "http-loopback" &&
(bearerKind === "local" || bearerKind === "static");
if (syncFolderApplies) {
const match = detectSyncFolder(
configPath,
syncFolderPatterns,
isGitTracked
);
if (match) {
const decision = await warnSync({
configPath,
matchedPattern: match,
});
if (decision === "cancel") {
audit("rejected-sync", bearerKind);
return {
ok: false,
reason: "sync-folder",
message: `Config path is inside a sync folder (${match}). Writing a bearer here would propagate the secret. Cancelled.`,
transportId,
};
}
}
}
// H5 — first-time confirmation modal. Default accepts in tests; caller in
// extension.ts wires the real VS Code prompt and remembers per-pair acceptance.
const accepted = await confirm({
ideTag: target,
transportId,
configPath,
});
if (!accepted) {
audit("rejected-cancelled", bearerKind);
return {
ok: false,
reason: "cancelled",
message: "User cancelled the transport confirmation.",
transportId,
};
}
// H6 — port-pin nudge. The caller uses workspace state to only call this
// once per session; here we only fire when the builder is actually going to
// bake the port into a config and the port is ephemeral (0 ⇒ OS-assigned).
if (transportId === "http-loopback" && getDaemonPort() === 0) {
try {
nudgePort({ ideTag: target });
} catch {
// Non-blocking by contract. Ignore handler failures.
}
}
// Issue the local token AFTER confirmation (don't mint a secret we may throw
// away) and BEFORE the builder runs (builder needs the token in its input).
let localToken: string | undefined;
let staticBearer: string | undefined;
if (bearerKind === "local") {
try {
const result = issueLocalToken({
ideTag: target,
label: meta.displayName,
});
localToken = result.token;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
audit("error", bearerKind);
return {
ok: false,
reason: "error",
message,
transportId,
};
}
}
if (bearerKind === "static") {
try {
const bearer = await (deps.getDaemonBearer?.() ?? Promise.reject(new Error("getDaemonBearer not provided")));
if (!bearer) {
audit("error", bearerKind);
return {
ok: false,
reason: "error",
message: "Daemon bearer unavailable — start the daemon first.",
transportId,
};
}
staticBearer = bearer;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
audit("error", bearerKind);
return {
ok: false,
reason: "error",
message,
transportId,
};
}
}
const activeTunnel = getActiveTunnel();
let entry: McpServerEntry;
try {
entry = builder.build({
launcherPath: options.serverPath,
daemonPort: getDaemonPort() ?? null,
tunnelUrl: activeTunnel?.url ?? null,
tunnelProviderId: activeTunnel?.providerId ?? null,
tunnelReservedDomain: activeTunnel?.reservedDomain ?? false,
bearerKind,
...(localToken !== undefined ? { localToken } : {}),
...(staticBearer !== undefined ? { staticBearer } : {}),
...(options.chromePath !== undefined ? { chromePath: options.chromePath } : {}),
...(options.nodePath !== undefined ? { nodePath: options.nodePath } : {}),
});
} catch (err) {
if (err instanceof StabilityGateError) {
audit("rejected-tunnel-unstable", bearerKind);
return {
ok: false,
reason: "tunnel-unstable",
message: err.reason,
transportId,
};
}
const message = err instanceof Error ? err.message : String(err);
audit("error", bearerKind);
return { ok: false, reason: "error", message, transportId };
}
// H3 — sanitized .bak + atomic write.
const hadExisting = existsSync(configPath);
let bakPath: string | null = null;
if (hadExisting) {
bakPath = `${configPath}.bak`;
try {
const raw = readFileSync(configPath, "utf8");
const sanitized = sanitizeConfigForBackup(raw, configFormat);
writeFileSync(bakPath, sanitized, { encoding: "utf8", mode: 0o600 });
applyPrivatePermissions(bakPath);
} catch (err) {
// If we can't even read the existing file, surface a structured error
// rather than silently clobbering it.
const message = err instanceof Error ? err.message : String(err);
audit("error", bearerKind);
return { ok: false, reason: "error", message, transportId };
}
}
try {
if (configFormat === "toml") {
const existing = readTomlFile(configPath);
const merged = mergeTomlMcpServer(
existing,
serverName,
entry as Record<string, unknown>
);
writeTextAtomic(configPath, merged);
} else {
const existingConfig = readExistingConfig(configPath);
const rootKey = getJsonConfigRootKey(meta);
const jsonEntry = normalizeJsonServerConfig(meta, entry);
const mergedConfig = mergeMcpConfig(
existingConfig,
serverName,
jsonEntry,
rootKey
);
writeJsonAtomic(configPath, mergedConfig);
}
} catch (err) {
// H3 rollback — restore the sanitized .bak over target then remove it.
if (bakPath && existsSync(bakPath)) {
try {
copyFileSync(bakPath, configPath);
rmSync(bakPath, { force: true });
} catch {
// Best-effort rollback; surface the original error.
}
}
const message = err instanceof Error ? err.message : String(err);
audit("error", bearerKind);
return { ok: false, reason: "error", message, transportId };
}
// Success — clean up .bak. A stale .bak on disk is a weaker redaction target
// than a freshly-written one; deleting keeps the blast radius minimal.
if (bakPath && existsSync(bakPath)) {
try {
rmSync(bakPath, { force: true });
} catch {
// Best-effort cleanup only.
}
}
audit("ok", bearerKind);
return {
ok: true,
path: configPath,
bearerKind,
transportId,
warnings: [],
};
}
function redactHome(p: string, home: string): string {
if (!home) return p;
// Case-sensitive normalize on POSIX; case-insensitive on Windows where
// file paths are not case-sensitive in practice.
const norm = (s: string) => (process.platform === "win32" ? s.toLowerCase() : s);
const normP = norm(p);
const normHome = norm(home);
if (normP === normHome) return "~";
if (normP.startsWith(normHome + "/") || normP.startsWith(normHome + "\\")) {
return "~" + p.slice(home.length);
}
return p;
}
const SYNC_FOLDER_BUILTIN = /^(icloud|onedrive|dropbox|google\s*drive|syncthing|pcloud)/i;
function detectSyncFolder(
configPath: string,
userPatterns: readonly string[],
isGitTracked: (dir: string) => boolean
): string | null {
// Walk ancestor directory names for the built-in sync-folder name list.
const parts = configPath.split(/[\\/]/).filter((s) => s.length > 0);
for (const part of parts) {
if (SYNC_FOLDER_BUILTIN.test(part)) {
const m = part.match(SYNC_FOLDER_BUILTIN);
return m ? normalizeMatch(m[0]) : part;
}
}
// Git-tracked check — only the containing directory, not the whole tree.
try {
const parent = dirname(configPath);
if (isGitTracked(parent)) {
return "git-tracked";
}
} catch {
// Never let git detection failures leak through as a false positive.
}
// User-supplied regex patterns. Invalid regexes are ignored silently — the
// settings UI may predate validation, and a broken pattern shouldn't DOS the
// entire config-generate flow.
for (const raw of userPatterns) {
if (typeof raw !== "string" || raw.length === 0) continue;
let re: RegExp;
try {
re = new RegExp(raw, "i");
} catch {
continue;
}
if (re.test(configPath)) {
return raw;
}
}
return null;
}
function normalizeMatch(raw: string): string {
const t = raw.trim().toLowerCase();
if (t.startsWith("icloud")) return "iCloud";
if (t.startsWith("onedrive")) return "OneDrive";
if (t.startsWith("dropbox")) return "Dropbox";
if (t.startsWith("google")) return "Google Drive";
if (t.startsWith("syncthing")) return "Syncthing";
if (t.startsWith("pcloud")) return "pCloud";
return raw;
}
// Keys redacted case-insensitively anywhere in the tree. "Authorization" is
// separate from "bearerToken"/"token" because some clients write it nested
// under `headers`; the scanner visits both shapes.
const REDACT_KEYS = new Set(["bearertoken", "token", "secret", "authorization"]);
const LOCAL_TOKEN_RE = /^pplx_(local|at|rt|ac)_/;
function sanitizeConfigForBackup(raw: string, format: "json" | "toml"): string {
if (format === "json") {
try {
const parsed = JSON.parse(raw);
return JSON.stringify(redactTree(parsed), null, 2) + "\n";
} catch {
// If existing file was non-JSON garbage, write a regex-scrubbed copy so
// we never persist a plaintext bearer in the .bak even on malformed input.
return scrubTextBearer(raw);
}
}
// TOML — regex-scrub. We don't round-trip-parse TOML here.
return scrubTextBearer(raw);
}
function scrubTextBearer(raw: string): string {
return raw
.replace(/Bearer\s+[A-Za-z0-9._\-+/=]+/g, "Bearer <redacted>")
.replace(/pplx_(local|at|rt|ac)_[A-Za-z0-9_\-]+/g, "<redacted>");
}
function redactTree(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(redactTree);
}
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (REDACT_KEYS.has(k.toLowerCase())) {
out[k] = "<redacted>";
continue;
}
out[k] = redactTree(v);
}
return out;
}
if (typeof value === "string") {
if (LOCAL_TOKEN_RE.test(value) || /\bBearer\s+/i.test(value)) {
return "<redacted>";
}
}
return value;
}
function writeTextAtomic(configPath: string, data: string): void {
mkdirSync(dirname(configPath), { recursive: true });
const tempPath = `${configPath}.tmp`;