-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathtrpc-mcp-config.test.ts
More file actions
359 lines (322 loc) · 13.4 KB
/
Copy pathtrpc-mcp-config.test.ts
File metadata and controls
359 lines (322 loc) · 13.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
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { appRouter } from "../src/trpc/router.js";
import { createCallerFactory } from "../src/trpc/index.js";
import type { Context } from "../src/trpc/context.js";
// Mock filesystem + os helpers so we don't touch real user config dirs.
vi.mock("node:fs", async (orig) => {
const actual = await orig<typeof import("node:fs")>();
return {
...actual,
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn()
};
});
vi.mock("node:os", async (orig) => {
const actual = await orig<typeof import("node:os")>();
return {
...actual,
homedir: vi.fn(() => "/home/user")
};
});
import {
existsSync,
readFileSync,
writeFileSync,
mkdirSync
} from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
// The router builds config paths with path.join, which uses backslashes on
// Windows. Build the expected paths the same way (content keys inside the
// JSON fixtures stay POSIX — they come from the mocked homedir()).
const HOME = "/home/user";
const CLAUDE_JSON = join(HOME, ".claude.json");
const CODEX_DIR = join(HOME, ".codex");
const CODEX_TOML = join(CODEX_DIR, "config.toml");
const OPENCODE_DIR = join(HOME, ".config", "opencode");
const OPENCODE_JSON = join(OPENCODE_DIR, "opencode.json");
const createCaller = createCallerFactory(appRouter);
function makeCtx(overrides: Partial<Context> = {}): Context {
return {
userId: "user-1",
registry: {} as never,
apiOptions: { metadataRoots: [], registry: {} as never } as never,
pythonBridge: {} as never,
getPythonBridgeReady: () => false,
...overrides
};
}
describe("mcpConfig router", () => {
beforeEach(() => {
// resetAllMocks also clears `mockImplementation` from previous tests —
// necessary because some tests install throwing implementations on
// writeFileSync that would leak into later tests otherwise.
vi.resetAllMocks();
// Re-install defaults that the whole suite relies on.
(homedir as ReturnType<typeof vi.fn>).mockReturnValue("/home/user");
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
delete process.env.NODETOOL_ENV;
delete process.env.PORT;
delete process.env.TLS_CERT;
delete process.env.TLS_KEY;
});
afterEach(() => {
vi.restoreAllMocks();
});
// ── production gate ─────────────────────────────────────────────
describe("production mode", () => {
it("status throws SERVICE_UNAVAILABLE in production", async () => {
process.env.NODETOOL_ENV = "production";
const caller = createCaller(makeCtx());
await expect(caller.mcpConfig.status()).rejects.toMatchObject({
code: "INTERNAL_SERVER_ERROR" // tRPC maps SERVICE_UNAVAILABLE → INTERNAL_SERVER_ERROR
});
});
it("install throws SERVICE_UNAVAILABLE in production", async () => {
process.env.NODETOOL_ENV = "production";
const caller = createCaller(makeCtx());
await expect(
caller.mcpConfig.install({ targets: ["claude"] })
).rejects.toMatchObject({ code: "INTERNAL_SERVER_ERROR" });
});
it("uninstall throws SERVICE_UNAVAILABLE in production", async () => {
process.env.NODETOOL_ENV = "production";
const caller = createCaller(makeCtx());
await expect(
caller.mcpConfig.uninstall({ targets: ["claude"] })
).rejects.toMatchObject({ code: "INTERNAL_SERVER_ERROR" });
});
});
// ── status ──────────────────────────────────────────────────────
describe("status", () => {
it("returns all targets as not-installed when no config files exist", async () => {
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
expect(result.targets).toHaveLength(3);
for (const t of result.targets) {
expect(t.installed).toBe(false);
expect(t.url).toBeNull();
}
expect(result.defaultUrl).toMatch(/^https?:\/\//);
});
it("defaultUrl uses PORT env var", async () => {
process.env.PORT = "9999";
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
expect(result.defaultUrl).toBe("http://127.0.0.1:9999/mcp");
});
it("defaultUrl switches to https when TLS_CERT and TLS_KEY are set", async () => {
process.env.TLS_CERT = "/etc/cert.pem";
process.env.TLS_KEY = "/etc/key.pem";
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
expect(result.defaultUrl).toMatch(/^https:\/\//);
});
it("reads claude installation when .claude.json has nodetool MCP server", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockImplementation(
(p: string) => p === CLAUDE_JSON
);
(readFileSync as ReturnType<typeof vi.fn>).mockReturnValue(
JSON.stringify({
projects: {
"/home/user": {
mcpServers: {
nodetool: { type: "http", url: "http://127.0.0.1:7777/mcp" }
}
}
}
})
);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
const claude = result.targets.find((t) => t.target === "claude");
expect(claude?.installed).toBe(true);
expect(claude?.url).toBe("http://127.0.0.1:7777/mcp");
expect(claude?.configPath).toBe(CLAUDE_JSON);
});
it("reads codex installation by regex from config.toml", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockImplementation(
(p: string) => p === CODEX_TOML
);
(readFileSync as ReturnType<typeof vi.fn>).mockReturnValue(
`# BEGIN NODETOOL MCP
[mcp_servers.nodetool]
url = "http://127.0.0.1:7777/mcp"
# END NODETOOL MCP
`
);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
const codex = result.targets.find((t) => t.target === "codex");
expect(codex?.installed).toBe(true);
expect(codex?.url).toBe("http://127.0.0.1:7777/mcp");
});
it("reads opencode installation from opencode.json", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockImplementation(
(p: string) => p === OPENCODE_JSON
);
(readFileSync as ReturnType<typeof vi.fn>).mockReturnValue(
JSON.stringify({
mcp: {
nodetool: { type: "remote", url: "http://127.0.0.1:7777/mcp" }
}
})
);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
const opencode = result.targets.find((t) => t.target === "opencode");
expect(opencode?.installed).toBe(true);
expect(opencode?.url).toBe("http://127.0.0.1:7777/mcp");
});
it("tolerates corrupt JSON config files gracefully", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(true);
(readFileSync as ReturnType<typeof vi.fn>).mockReturnValue("{garbage");
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.status();
for (const t of result.targets) {
expect(t.installed).toBe(false);
}
});
it("rejects unauthenticated callers", async () => {
const caller = createCaller(makeCtx({ userId: null }));
await expect(caller.mcpConfig.status()).rejects.toMatchObject({
code: "UNAUTHORIZED"
});
});
});
// ── install ─────────────────────────────────────────────────────
describe("install", () => {
it("installs all targets when no targets specified", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.install({});
expect(result.results).toHaveLength(3);
expect(writeFileSync).toHaveBeenCalledTimes(3);
expect(result.url).toMatch(/^http/);
});
it("installs only requested targets", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.install({ targets: ["claude"] });
expect(result.results).toHaveLength(1);
expect(result.results[0]?.target).toBe("claude");
expect(result.results[0]?.success).toBe(true);
expect(result.results[0]?.configPath).toBe(CLAUDE_JSON);
});
it("uses provided url when specified", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.install({
targets: ["claude"],
url: "http://example.com:9000/mcp"
});
expect(result.url).toBe("http://example.com:9000/mcp");
});
it("creates parent directories for codex/opencode", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
const caller = createCaller(makeCtx());
await caller.mcpConfig.install({ targets: ["codex", "opencode"] });
expect(mkdirSync).toHaveBeenCalledWith(CODEX_DIR, {
recursive: true
});
expect(mkdirSync).toHaveBeenCalledWith(
OPENCODE_DIR,
{ recursive: true }
);
});
it("captures per-target error without failing the whole request", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
(writeFileSync as ReturnType<typeof vi.fn>).mockImplementation(
(p: string) => {
if (p === CLAUDE_JSON) throw new Error("disk full");
}
);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.install({
targets: ["claude", "codex"]
});
expect(result.results).toHaveLength(2);
const claude = result.results.find((r) => r.target === "claude");
expect(claude?.success).toBe(false);
expect(claude?.error).toContain("disk full");
const codex = result.results.find((r) => r.target === "codex");
expect(codex?.success).toBe(true);
});
it("rejects unauthenticated callers", async () => {
const caller = createCaller(makeCtx({ userId: null }));
await expect(
caller.mcpConfig.install({ targets: ["claude"] })
).rejects.toMatchObject({ code: "UNAUTHORIZED" });
});
});
// ── uninstall ───────────────────────────────────────────────────
describe("uninstall", () => {
it("returns removed=false for targets with no config files", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.uninstall({ targets: ["claude"] });
expect(result.results[0]?.removed).toBe(false);
});
it("removes nodetool entry from .claude.json when present", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockImplementation(
(p: string) => p === CLAUDE_JSON
);
(readFileSync as ReturnType<typeof vi.fn>).mockReturnValue(
JSON.stringify({
projects: {
"/home/user": {
mcpServers: {
nodetool: { url: "x" },
other: { url: "y" }
}
}
}
})
);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.uninstall({ targets: ["claude"] });
expect(result.results[0]?.removed).toBe(true);
// Verify writeFileSync was called with the modified config.
const writeCalls = (writeFileSync as ReturnType<typeof vi.fn>).mock.calls;
expect(writeCalls).toHaveLength(1);
const writtenContent = writeCalls[0]?.[1] as string;
const parsed = JSON.parse(writtenContent);
expect(parsed.projects["/home/user"].mcpServers.nodetool).toBeUndefined();
expect(parsed.projects["/home/user"].mcpServers.other).toBeDefined();
});
it("removes block from codex config.toml", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockImplementation(
(p: string) => p === CODEX_TOML
);
(readFileSync as ReturnType<typeof vi.fn>).mockReturnValue(
`[something_else]
foo = "bar"
# BEGIN NODETOOL MCP
url = "x"
# END NODETOOL MCP
`
);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.uninstall({ targets: ["codex"] });
expect(result.results[0]?.removed).toBe(true);
const writtenContent = (writeFileSync as ReturnType<typeof vi.fn>).mock
.calls[0]?.[1] as string;
expect(writtenContent).not.toContain("BEGIN NODETOOL MCP");
expect(writtenContent).toContain("something_else");
});
it("uninstalls all targets when none specified", async () => {
(existsSync as ReturnType<typeof vi.fn>).mockReturnValue(false);
const caller = createCaller(makeCtx());
const result = await caller.mcpConfig.uninstall({});
expect(result.results).toHaveLength(3);
});
it("rejects unauthenticated callers", async () => {
const caller = createCaller(makeCtx({ userId: null }));
await expect(
caller.mcpConfig.uninstall({ targets: ["claude"] })
).rejects.toMatchObject({ code: "UNAUTHORIZED" });
});
});
});