Repository navigation
Expand file tree
/
Copy pathdisabled_mcp_servers.e2e.test.ts
More file actions
485 lines (450 loc) · 17.6 KB
/
Copy pathdisabled_mcp_servers.e2e.test.ts
File metadata and controls
485 lines (450 loc) · 17.6 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
approveAll,
CopilotRequestHandler,
RuntimeConnection,
type CopilotSession,
} from "../../src/index.js";
import { createSdkTestContext, isInProcessTransport } from "./harness/sdkTestContext.js";
import { waitForCondition } from "./harness/sdkTestHelper.js";
const __dirname = resolve(fileURLToPath(new URL(".", import.meta.url)));
const TEST_MCP_SERVER = resolve(__dirname, "../../../test/harness/test-mcp-server.mjs");
const SYNTHETIC_RESPONSE = "PERSISTED_SESSION_READY";
const MCP_TRIGGER_PROMPT = "Reply with the configured MCP test completion marker.";
class PersistingRequestHandler extends CopilotRequestHandler {
protected override async sendRequest(request: Request): Promise<Response> {
const body = request.body ? await request.text() : "";
const wantsStream = /"stream"\s*:\s*true/.test(body);
const url = request.url.toLowerCase();
if (url.endsWith("/models")) {
return new Response(MODEL_CATALOG_JSON, {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (url.includes("/responses")) {
return new Response(wantsStream ? RESPONSE_STREAM : RESPONSE_JSON, {
status: 200,
headers: {
"content-type": wantsStream ? "text/event-stream" : "application/json",
},
});
}
if (url.includes("/chat/completions")) {
return new Response(
wantsStream ? CHAT_COMPLETION_STREAM : CHAT_COMPLETION_RESPONSE_JSON,
{
status: 200,
headers: {
"content-type": wantsStream ? "text/event-stream" : "application/json",
},
}
);
}
return new Response("{}", {
status: 200,
headers: { "content-type": "application/json" },
});
}
}
const RESPONSE_STREAM = [
{
event: "response.created",
data: {
type: "response.created",
response: {
id: "persisted-session",
object: "response",
status: "in_progress",
output: [],
},
},
},
{
event: "response.output_item.added",
data: {
type: "response.output_item.added",
output_index: 0,
item: { id: "message-1", type: "message", role: "assistant", content: [] },
},
},
{
event: "response.content_part.added",
data: {
type: "response.content_part.added",
output_index: 0,
content_index: 0,
part: { type: "output_text", text: "" },
},
},
{
event: "response.output_text.delta",
data: {
type: "response.output_text.delta",
output_index: 0,
content_index: 0,
delta: SYNTHETIC_RESPONSE,
},
},
{
event: "response.output_text.done",
data: {
type: "response.output_text.done",
output_index: 0,
content_index: 0,
text: SYNTHETIC_RESPONSE,
},
},
{
event: "response.completed",
data: {
type: "response.completed",
response: {
id: "persisted-session",
object: "response",
status: "completed",
output: [
{
id: "message-1",
type: "message",
role: "assistant",
content: [{ type: "output_text", text: SYNTHETIC_RESPONSE }],
},
],
usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
},
},
},
]
.map(({ event, data }) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
.join("");
const RESPONSE_JSON = JSON.stringify({
id: "persisted-session",
object: "response",
status: "completed",
output: [
{
id: "message-1",
type: "message",
role: "assistant",
content: [{ type: "output_text", text: SYNTHETIC_RESPONSE }],
},
],
usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
});
const CHAT_COMPLETION_STREAM = [
{
id: "persisted-session",
object: "chat.completion.chunk",
created: 1,
model: "claude-sonnet-5",
choices: [
{
index: 0,
delta: { role: "assistant", content: SYNTHETIC_RESPONSE },
finish_reason: null,
},
],
},
{
id: "persisted-session",
object: "chat.completion.chunk",
created: 1,
model: "claude-sonnet-5",
choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
},
]
.map((data) => `data: ${JSON.stringify(data)}\n\n`)
.concat("data: [DONE]\n\n")
.join("");
const CHAT_COMPLETION_RESPONSE_JSON = JSON.stringify({
id: "persisted-session",
object: "chat.completion",
created: 1,
model: "claude-sonnet-5",
choices: [
{
index: 0,
message: { role: "assistant", content: SYNTHETIC_RESPONSE },
finish_reason: "stop",
},
],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
});
const MODEL_CATALOG_JSON = JSON.stringify({
data: [
{
id: "claude-sonnet-5",
name: "Claude Sonnet 5",
object: "model",
vendor: "Anthropic",
version: "1",
preview: false,
model_picker_enabled: true,
capabilities: {
type: "chat",
family: "claude-sonnet-5",
tokenizer: "o200k_base",
limits: { max_context_window_tokens: 200000, max_output_tokens: 8192 },
supports: { streaming: true, tool_calls: true, parallel_tool_calls: true },
},
},
],
});
describe("disabled MCP servers", async () => {
const {
copilotClient: client,
createClient,
openAiEndpoint,
workDir,
} = await createSdkTestContext({
copilotClientOptions: {
requestHandler: new PersistingRequestHandler(),
},
});
function createPluginDirectory(prefix: string): {
pluginDirectory: string;
controlMarker: string;
disabledMarker: string;
} {
const pluginDirectory = join(workDir, `${prefix}-${randomUUID()}`);
mkdirSync(pluginDirectory, { recursive: true });
const controlMarker = join(pluginDirectory, "control-started.log");
const disabledMarker = join(pluginDirectory, "disabled-started.log");
writeFileSync(
join(pluginDirectory, "plugin.json"),
JSON.stringify({
name: `${prefix}-${randomUUID()}`,
version: "1.0.0",
})
);
writeFileSync(
join(pluginDirectory, ".mcp.json"),
JSON.stringify({
mcpServers: {
control: {
type: "stdio",
command: process.execPath,
args: [
TEST_MCP_SERVER,
"--startup-marker",
controlMarker,
"--server-name",
"control",
],
},
disabled: {
type: "stdio",
command: process.execPath,
args: [
TEST_MCP_SERVER,
"--startup-marker",
disabledMarker,
"--server-name",
"disabled",
],
},
},
})
);
return { pluginDirectory, controlMarker, disabledMarker };
}
function markerCount(markerPath: string): number {
if (!existsSync(markerPath)) {
return 0;
}
return readFileSync(markerPath, "utf8").trim().split("\n").filter(Boolean).length;
}
async function waitForMarkerCount(markerPath: string, expectedCount: number): Promise<void> {
await waitForCondition(() => markerCount(markerPath) >= expectedCount, {
timeoutMs: 60_000,
intervalMs: 100,
timeoutMessage: `Timed out waiting for ${markerPath} to be written ${expectedCount} time(s).`,
});
}
async function waitForMcpStatus(
session: CopilotSession,
serverName: string,
expectedStatus: string
): Promise<void> {
let lastStatus = "<not listed>";
await waitForCondition(
async () => {
const result = await session.rpc.mcp.list();
const server = result.servers.find((candidate) => candidate.name === serverName);
lastStatus = server?.status ?? "<not listed>";
return lastStatus === expectedStatus;
},
{
timeoutMs: 60_000,
intervalMs: 100,
timeoutMessage: `${serverName} did not reach ${expectedStatus}; last status was ${lastStatus}.`,
}
);
}
function expectSyntheticResponse(response: Awaited<ReturnType<CopilotSession["sendAndWait"]>>) {
expect(response?.data.content).toBe(SYNTHETIC_RESPONSE);
}
async function drainPostCreateRpc(session: CopilotSession): Promise<void> {
// Drain a non-MCP post-create RPC so session initialization settles before assertions.
await session.rpc.metadata.snapshot();
}
async function mcpRequestCount(): Promise<number> {
const requests = await openAiEndpoint.getRequests();
return requests.filter((request) => request.method === "POST" && request.url === "/mcp")
.length;
}
async function waitForMcpRequestCount(expectedCount: number): Promise<void> {
let lastCount = 0;
await waitForCondition(
async () => {
lastCount = await mcpRequestCount();
return lastCount >= expectedCount;
},
{
timeoutMs: 60_000,
intervalMs: 100,
timeoutMessage: `Timed out waiting for ${expectedCount} /mcp request(s); saw ${lastCount}.`,
}
);
}
it(
"keeps disabled plugin MCP servers per-session on create",
{ timeout: 120_000 },
async () => {
const {
pluginDirectory: disabledPluginDirectory,
controlMarker: disabledControlMarker,
disabledMarker,
} = createPluginDirectory("disabled-mcp-create");
await using disabledSession = await client.createSession({
onPermissionRequest: approveAll,
pluginDirectories: [disabledPluginDirectory],
disabledMcpServers: ["disabled"],
});
await drainPostCreateRpc(disabledSession);
expect(existsSync(disabledControlMarker)).toBe(false);
expect(existsSync(disabledMarker)).toBe(false);
expectSyntheticResponse(
await disabledSession.sendAndWait({ prompt: MCP_TRIGGER_PROMPT })
);
await waitForMarkerCount(disabledControlMarker, 1);
expect(existsSync(disabledMarker)).toBe(false);
await waitForMcpStatus(disabledSession, "control", "connected");
await waitForMcpStatus(disabledSession, "disabled", "disabled");
const {
pluginDirectory: enabledPluginDirectory,
controlMarker: enabledControlMarker,
disabledMarker: enabledDisabledMarker,
} = createPluginDirectory("enabled-mcp-create");
await using enabledSession = await client.createSession({
onPermissionRequest: approveAll,
pluginDirectories: [enabledPluginDirectory],
});
await drainPostCreateRpc(enabledSession);
expect(existsSync(enabledControlMarker)).toBe(false);
expect(existsSync(enabledDisabledMarker)).toBe(false);
expectSyntheticResponse(
await enabledSession.sendAndWait({ prompt: MCP_TRIGGER_PROMPT })
);
await waitForMarkerCount(enabledControlMarker, 1);
await waitForMarkerCount(enabledDisabledMarker, 1);
await waitForMcpStatus(enabledSession, "control", "connected");
await waitForMcpStatus(enabledSession, "disabled", "connected");
}
);
it(
"keeps the built-in GitHub MCP server disabled on the first message",
{ timeout: 120_000 },
async () => {
const disabledSession = await client.createSession({
onPermissionRequest: approveAll,
enableConfigDiscovery: true,
enableMcpApps: true,
githubMcpToolConfig: { enableAllTools: true },
disabledMcpServers: ["github-mcp-server"],
});
let disabledRequestsBeforeFirstMessage: number;
try {
await drainPostCreateRpc(disabledSession);
disabledRequestsBeforeFirstMessage = await mcpRequestCount();
expect(disabledRequestsBeforeFirstMessage).toBe(0);
expectSyntheticResponse(
await disabledSession.sendAndWait({ prompt: MCP_TRIGGER_PROMPT })
);
expect(await mcpRequestCount()).toBe(disabledRequestsBeforeFirstMessage);
await waitForMcpStatus(disabledSession, "github-mcp-server", "disabled");
expect(await mcpRequestCount()).toBe(disabledRequestsBeforeFirstMessage);
} finally {
await disabledSession.disconnect();
}
expect(await mcpRequestCount()).toBe(disabledRequestsBeforeFirstMessage);
await using enabledSession = await client.createSession({
onPermissionRequest: approveAll,
enableConfigDiscovery: true,
enableMcpApps: true,
githubMcpToolConfig: { enableAllTools: true },
});
await drainPostCreateRpc(enabledSession);
await waitForMcpStatus(enabledSession, "github-mcp-server", "connected");
const requestsBeforeFirstMessage = await mcpRequestCount();
expect(requestsBeforeFirstMessage).toBeGreaterThan(0);
expectSyntheticResponse(
await enabledSession.sendAndWait({ prompt: MCP_TRIGGER_PROMPT })
);
await waitForMcpRequestCount(requestsBeforeFirstMessage + 1);
}
);
it.skipIf(isInProcessTransport)(
"applies disabled plugin MCP servers on cold stdio resume",
async () => {
const { pluginDirectory, controlMarker, disabledMarker } =
createPluginDirectory("disabled-mcp-resume");
const initialClient = createClient({
connection: RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }),
requestHandler: new PersistingRequestHandler(),
});
const resumeClient = createClient({
connection: RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }),
});
try {
const originalSession = await initialClient.createSession({
onPermissionRequest: approveAll,
enableSessionStore: true,
});
const sessionId = originalSession.sessionId;
// A session.log entry alone does not materialize a session that a
// restarted runtime can resume. This self-contained model turn
// persists it without initializing MCP because no plugin directory
// is supplied until the resume request below.
const response = await originalSession.sendAndWait({
prompt: "Return the configured persistence marker.",
});
expectSyntheticResponse(response);
expect(existsSync(controlMarker)).toBe(false);
expect(existsSync(disabledMarker)).toBe(false);
await initialClient.stop();
await using resumedSession = await resumeClient.resumeSession(sessionId, {
onPermissionRequest: approveAll,
enableSessionStore: true,
pluginDirectories: [pluginDirectory],
disabledMcpServers: ["disabled"],
});
await waitForMcpStatus(resumedSession, "control", "connected");
await waitForMcpStatus(resumedSession, "disabled", "disabled");
await waitForMarkerCount(controlMarker, 1);
expect(existsSync(disabledMarker)).toBe(false);
} finally {
await initialClient.stop().catch(() => {});
await resumeClient.stop().catch(() => {});
}
}
);
});