-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathup.test.ts
More file actions
588 lines (518 loc) · 19.4 KB
/
Copy pathup.test.ts
File metadata and controls
588 lines (518 loc) · 19.4 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
import { describe, it, expect, vi, beforeEach } from "vitest";
import { handleUp } from "../../commands/up.js";
import type { UpDeps, UpOptions } from "../../commands/up.js";
import type { ClientId } from "../../config/paths.js";
import type { ServerEntry } from "../../registry/types.js";
import type { TrustScore } from "../../scanner/trust-score.js";
import type { McpServerEntry } from "../../config/adapters/index.js";
import { writeFile, mkdtemp } from "fs/promises";
import path from "path";
import os from "os";
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
function makeServerEntry(name: string, version: string): ServerEntry {
return {
server: {
name,
version,
packages: [
{
registryType: "npm",
identifier: `@test/${name.split("/").pop()}`,
environmentVariables: [],
},
],
},
};
}
const goodTrust: TrustScore = {
score: 75,
maxPossible: 80,
level: "safe",
breakdown: { healthCheck: 15, staticScan: 40, externalScan: 0, registryMeta: 10 },
};
const lowTrust: TrustScore = {
score: 30,
maxPossible: 80,
level: "risky",
breakdown: { healthCheck: 0, staticScan: 20, externalScan: 0, registryMeta: 10 },
};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeAdapter(servers: Record<string, McpServerEntry> = {}) {
return {
clientId: "claude-desktop" as ClientId,
read: vi.fn().mockResolvedValue({ ...servers }),
addServer: vi.fn().mockResolvedValue(undefined),
removeServer: vi.fn().mockResolvedValue(undefined),
setServerDisabled: vi.fn().mockResolvedValue(undefined),
};
}
function makeDeps(overrides: Partial<UpDeps> = {}): UpDeps {
const adapter = makeAdapter();
return {
detectClients: vi.fn<() => Promise<ClientId[]>>().mockResolvedValue(["claude-desktop"]),
getAdapter: vi.fn().mockReturnValue(adapter),
getPath: vi.fn().mockReturnValue("/mock/config.json"),
getServer: vi.fn().mockImplementation((name: string, version?: string) =>
Promise.resolve(makeServerEntry(name, version ?? "1.0.0"))
),
scanTier1: vi.fn().mockReturnValue([]),
checkScannerAvailable: vi.fn().mockResolvedValue(false),
scanTier2: vi.fn().mockResolvedValue([]),
computeTrustScore: vi.fn().mockReturnValue(goodTrust),
runLock: vi.fn().mockResolvedValue(undefined),
confirm: vi.fn().mockResolvedValue(true),
promptEnvVar: vi.fn().mockResolvedValue("prompted_value"),
output: vi.fn(),
...overrides,
};
}
async function writeStackAndLock(
stackYaml: string,
lockYaml: string
): Promise<string> {
const dir = await mkdtemp(path.join(os.tmpdir(), "mcpm-up-test-"));
await writeFile(path.join(dir, "mcpm.yaml"), stackYaml, "utf-8");
await writeFile(path.join(dir, "mcpm-lock.yaml"), lockYaml, "utf-8");
return path.join(dir, "mcpm.yaml");
}
const basicStack = `
version: "1"
servers:
io.github.test/server-a:
version: "^1.0.0"
`;
const basicLock = `
lockfileVersion: 1
lockedAt: "2026-04-05T10:00:00Z"
servers:
io.github.test/server-a:
version: "1.2.0"
registryType: npm
identifier: "@test/server-a"
trust:
score: 75
maxPossible: 80
level: safe
assessedAt: "2026-04-05T10:00:00Z"
`;
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("handleUp", () => {
it("installs all servers from yaml + lock", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const deps = makeDeps();
await handleUp({ stackFile: stackPath }, deps);
const adapter = (deps.getAdapter as ReturnType<typeof vi.fn>).mock.results[0].value;
expect(adapter.addServer).toHaveBeenCalledTimes(1);
expect(adapter.addServer).toHaveBeenCalledWith(
"/mock/config.json",
"io.github.test/server-a",
expect.objectContaining({ command: "npx" }),
{ force: true }
);
});
it("auto-runs lock when no lock file exists", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "mcpm-up-nolock-"));
const stackPath = path.join(dir, "mcpm.yaml");
await writeFile(stackPath, basicStack, "utf-8");
// runLock creates the lock file
const deps = makeDeps({
runLock: vi.fn().mockImplementation(async () => {
await writeFile(
path.join(dir, "mcpm-lock.yaml"),
basicLock,
"utf-8"
);
}),
});
await handleUp({ stackFile: stackPath }, deps);
expect(deps.runLock).toHaveBeenCalledWith(stackPath);
});
it("blocks server when trust score is below policy minTrustScore", async () => {
const stackWithPolicy = `
version: "1"
policy:
minTrustScore: 60
servers:
io.github.test/server-a:
version: "^1.0.0"
`;
const stackPath = await writeStackAndLock(stackWithPolicy, basicLock);
const deps = makeDeps({
computeTrustScore: vi.fn().mockReturnValue(lowTrust),
});
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow(
"could not be installed"
);
const outputCalls = (deps.output as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
expect(outputCalls).toContain("below the minimum");
});
it("blocks server when trust score dropped with blockOnScoreDrop", async () => {
const stackWithDrop = `
version: "1"
policy:
blockOnScoreDrop: true
servers:
io.github.test/server-a:
version: "^1.0.0"
`;
// Lock has 75/80 = 94%. Current is 30/80 = 38%. Drop detected.
const stackPath = await writeStackAndLock(stackWithDrop, basicLock);
const deps = makeDeps({
computeTrustScore: vi.fn().mockReturnValue(lowTrust),
});
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow(
"could not be installed"
);
});
it("prints plan without writing in --dry-run mode", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter();
const deps = makeDeps({
getAdapter: vi.fn().mockReturnValue(adapter),
});
await handleUp({ stackFile: stackPath, dryRun: true }, deps);
expect(adapter.addServer).not.toHaveBeenCalled();
const outputCalls = (deps.output as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
expect(outputCalls).toContain("Dry run");
expect(outputCalls).toContain("would install");
});
it("errors in --ci mode when required env var is missing", async () => {
const stackWithEnv = `
version: "1"
servers:
io.github.test/server-a:
version: "^1.0.0"
env:
API_TOKEN:
required: true
secret: true
`;
const stackPath = await writeStackAndLock(stackWithEnv, basicLock);
const deps = makeDeps();
await expect(
handleUp({ stackFile: stackPath, ci: true }, deps)
).rejects.toThrow("could not be installed");
const outputCalls = (deps.output as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
expect(outputCalls).toContain("API_TOKEN");
});
it("filters servers by --profile", async () => {
const multiProfile = `
version: "1"
servers:
io.github.test/dev-only:
version: "^1.0.0"
profiles: [dev]
io.github.test/prod-only:
version: "^1.0.0"
profiles: [prod]
`;
const multiLock = `
lockfileVersion: 1
lockedAt: "2026-04-05T10:00:00Z"
servers:
io.github.test/dev-only:
version: "1.0.0"
registryType: npm
identifier: "@test/dev-only"
trust:
score: 75
maxPossible: 80
level: safe
assessedAt: "2026-04-05T10:00:00Z"
io.github.test/prod-only:
version: "1.0.0"
registryType: npm
identifier: "@test/prod-only"
trust:
score: 75
maxPossible: 80
level: safe
assessedAt: "2026-04-05T10:00:00Z"
`;
const stackPath = await writeStackAndLock(multiProfile, multiLock);
const deps = makeDeps();
await handleUp({ stackFile: stackPath, profile: "dev" }, deps);
const adapter = (deps.getAdapter as ReturnType<typeof vi.fn>).mock.results[0].value;
expect(adapter.addServer).toHaveBeenCalledTimes(1);
expect(adapter.addServer).toHaveBeenCalledWith(
expect.anything(),
"io.github.test/dev-only",
expect.anything(),
expect.anything()
);
});
it("errors with --strict --ci without --yes", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter({ "extra-server": { command: "npx", args: ["-y", "extra"] } });
const deps = makeDeps({
getAdapter: vi.fn().mockReturnValue(adapter),
});
await expect(
handleUp({ stackFile: stackPath, strict: true, ci: true }, deps)
).rejects.toThrow("--strict --ci requires --yes");
});
it("removes extra servers with --strict --yes", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter({ "extra-server": { command: "npx", args: ["-y", "extra"] } });
const deps = makeDeps({
getAdapter: vi.fn().mockReturnValue(adapter),
});
await handleUp({ stackFile: stackPath, strict: true, yes: true }, deps);
expect(adapter.removeServer).toHaveBeenCalledWith(
"/mock/config.json",
"extra-server"
);
});
// Issue #22: the MCP mcpm_up surface wires `confirm: async () => false` so it
// never auto-confirms destructive actions on the no-human-in-loop path. This
// proves that a refusing confirm callback declines strict-mode removals.
it("does NOT remove extra servers when confirm refuses (non-CI strict)", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter({ "extra-server": { command: "npx", args: ["-y", "extra"] } });
const deps = makeDeps({
getAdapter: vi.fn().mockReturnValue(adapter),
confirm: vi.fn().mockResolvedValue(false),
});
await handleUp({ stackFile: stackPath, strict: true }, deps);
expect(adapter.removeServer).not.toHaveBeenCalled();
});
it("continues when one server fails and reports all errors", async () => {
const twoServers = `
version: "1"
servers:
io.github.test/good:
version: "^1.0.0"
io.github.test/bad:
version: "^1.0.0"
`;
const twoLock = `
lockfileVersion: 1
lockedAt: "2026-04-05T10:00:00Z"
servers:
io.github.test/good:
version: "1.0.0"
registryType: npm
identifier: "@test/good"
trust:
score: 75
maxPossible: 80
level: safe
assessedAt: "2026-04-05T10:00:00Z"
io.github.test/bad:
version: "1.0.0"
registryType: npm
identifier: "@test/bad"
trust:
score: 75
maxPossible: 80
level: safe
assessedAt: "2026-04-05T10:00:00Z"
`;
const stackPath = await writeStackAndLock(twoServers, twoLock);
const deps = makeDeps({
getServer: vi.fn().mockImplementation((name: string) => {
if (name === "io.github.test/bad") {
return Promise.reject(new Error("Registry error"));
}
return Promise.resolve(makeServerEntry(name, "1.0.0"));
}),
});
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow(
"could not be installed"
);
// Good server should still have been installed
const adapter = (deps.getAdapter as ReturnType<typeof vi.fn>).mock.results[0].value;
expect(adapter.addServer).toHaveBeenCalledWith(
expect.anything(),
"io.github.test/good",
expect.anything(),
expect.anything()
);
});
it("resolves env vars from process.env and .env file", async () => {
const stackWithEnv = `
version: "1"
servers:
io.github.test/server-a:
version: "^1.0.0"
env:
FROM_PROCESS:
required: true
FROM_DEFAULT:
required: true
default: "default_val"
`;
const stackPath = await writeStackAndLock(stackWithEnv, basicLock);
// Set a process.env var for the test
const originalEnv = process.env.FROM_PROCESS;
process.env.FROM_PROCESS = "process_val";
try {
const deps = makeDeps();
await handleUp({ stackFile: stackPath }, deps);
const adapter = (deps.getAdapter as ReturnType<typeof vi.fn>).mock.results[0].value;
const addCall = adapter.addServer.mock.calls[0];
const entry = addCall[2] as McpServerEntry;
expect(entry.env?.FROM_PROCESS).toBe("process_val");
expect(entry.env?.FROM_DEFAULT).toBe("default_val");
} finally {
if (originalEnv === undefined) {
delete process.env.FROM_PROCESS;
} else {
process.env.FROM_PROCESS = originalEnv;
}
}
});
it("exits nonzero when any server fails", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const deps = makeDeps({
getServer: vi.fn().mockRejectedValue(new Error("Network error")),
});
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow();
});
// Fix #1: when every client write fails (e.g. all configs read-only), the
// server must be reported as failed — not silently "installed".
it("reports failure (not installed) when all client writes throw", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter();
adapter.addServer = vi.fn().mockRejectedValue(new Error("EACCES: read-only config"));
const deps = makeDeps({ getAdapter: vi.fn().mockReturnValue(adapter) });
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow(
"could not be installed"
);
const outputCalls = (deps.output as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
expect(outputCalls).toContain("could not write to any client");
expect(outputCalls).toContain("EACCES");
// Summary must not claim an install happened.
expect(outputCalls).toMatch(/0 installed/);
});
// Fix #1: partial failure (one of two clients fails) still installs but
// surfaces a warning rather than swallowing the error.
it("installs with a warning when some clients fail", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const okAdapter = makeAdapter();
const badAdapter = makeAdapter();
badAdapter.addServer = vi.fn().mockRejectedValue(new Error("EROFS"));
const deps = makeDeps({
detectClients: vi.fn<() => Promise<ClientId[]>>().mockResolvedValue([
"claude-desktop",
"cursor",
]),
getAdapter: vi.fn().mockImplementation((id: ClientId) =>
id === "cursor" ? badAdapter : okAdapter
),
});
await handleUp({ stackFile: stackPath }, deps);
expect(okAdapter.addServer).toHaveBeenCalledTimes(1);
const outputCalls = (deps.output as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
expect(outputCalls).toContain("warning: failed on");
expect(outputCalls).toContain("cursor");
expect(outputCalls).toMatch(/1 installed/);
});
// Fix #2: removed servers must be counted as "removed", not inflate the
// "N installed" summary.
it("counts strict-removed servers as removed, not installed", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter({
"io.github.test/server-a": { command: "npx", args: ["-y", "server-a"] },
"extra-server": { command: "npx", args: ["-y", "extra"] },
});
const deps = makeDeps({ getAdapter: vi.fn().mockReturnValue(adapter) });
await handleUp({ stackFile: stackPath, strict: true, yes: true }, deps);
expect(adapter.removeServer).toHaveBeenCalledWith("/mock/config.json", "extra-server");
const outputCalls = (deps.output as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
// server-a installs (1), extra-server is removed (1) — not 2 installed.
expect(outputCalls).toMatch(/1 installed/);
expect(outputCalls).toContain("1 removed");
});
// Fix #3: --strict --yes in interactive (non-CI) mode must honor --yes and
// NOT prompt via confirm.
it("does not prompt for strict removal when --yes is passed (non-CI)", async () => {
const stackPath = await writeStackAndLock(basicStack, basicLock);
const adapter = makeAdapter({ "extra-server": { command: "npx", args: ["-y", "extra"] } });
const confirm = vi.fn().mockResolvedValue(true);
const deps = makeDeps({
getAdapter: vi.fn().mockReturnValue(adapter),
confirm,
});
await handleUp({ stackFile: stackPath, strict: true, yes: true }, deps);
expect(confirm).not.toHaveBeenCalled();
expect(adapter.removeServer).toHaveBeenCalledWith("/mock/config.json", "extra-server");
});
// M4a (PR #66): the up path now validates stack-file `url:` servers before writing.
// These exercise processUrlServer end-to-end (previously untested at this level).
const urlStack = (url: string) => `
version: "1"
servers:
io.github.test/remote:
url: "${url}"
`;
it("installs a valid https url: server to Cursor", async () => {
const stackPath = await writeStackAndLock(urlStack("https://api.example.com/mcp"), basicLock);
const adapter = makeAdapter();
const deps = makeDeps({
detectClients: vi.fn<() => Promise<ClientId[]>>().mockResolvedValue(["cursor"]),
getAdapter: vi.fn().mockReturnValue(adapter),
});
await handleUp({ stackFile: stackPath }, deps);
expect(adapter.addServer).toHaveBeenCalledWith(
"/mock/config.json",
"io.github.test/remote",
{ url: "https://api.example.com/mcp" },
{ force: true }
);
});
it("blocks a url: server with a non-loopback plaintext-http URL (M4a)", async () => {
const stackPath = await writeStackAndLock(urlStack("http://10.0.0.5/mcp"), basicLock);
const adapter = makeAdapter();
const deps = makeDeps({
detectClients: vi.fn<() => Promise<ClientId[]>>().mockResolvedValue(["cursor"]),
getAdapter: vi.fn().mockReturnValue(adapter),
});
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow(/could not be installed/);
expect(adapter.addServer).not.toHaveBeenCalled();
});
it("blocks a url: server with a non-http(s) scheme", async () => {
const stackPath = await writeStackAndLock(urlStack("file:///etc/passwd"), basicLock);
const adapter = makeAdapter();
const deps = makeDeps({
detectClients: vi.fn<() => Promise<ClientId[]>>().mockResolvedValue(["cursor"]),
getAdapter: vi.fn().mockReturnValue(adapter),
});
await expect(handleUp({ stackFile: stackPath }, deps)).rejects.toThrow(/could not be installed/);
expect(adapter.addServer).not.toHaveBeenCalled();
});
// Regression: --dry-run is read-only — an invalid URL must NOT throw or exit
// non-zero; it is previewed as "would reject".
it("dry-run does not fail on an invalid url: server (regression)", async () => {
const stackPath = await writeStackAndLock(urlStack("http://10.0.0.5/mcp"), basicLock);
const adapter = makeAdapter();
const deps = makeDeps({
detectClients: vi.fn<() => Promise<ClientId[]>>().mockResolvedValue(["cursor"]),
getAdapter: vi.fn().mockReturnValue(adapter),
});
await expect(
handleUp({ stackFile: stackPath, dryRun: true }, deps)
).resolves.toBeUndefined();
expect(adapter.addServer).not.toHaveBeenCalled();
const out = (deps.output as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0]).join("\n");
expect(out).toMatch(/would reject URL/);
});
});