summaryrefslogtreecommitdiffhomepage
path: root/packages/mcp/src/transport.test.ts
blob: b369e74e9c0d8a6039a371cbb27024e8cfac9857 (plain)
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
import { describe, expect, it } from "vitest";
import { encode } from "./framing.js";
import type { SpawnedProcess, SpawnProcess } from "./transport.js";
import { createStdioTransport } from "./transport.js";

/**
 * In-memory pipe pair: simulates a child process. `emitStdout` pushes framed
 * bytes the server "wrote" to stdout (which we read); `writtenToStdin` captures
 * what we wrote to the child's stdin (our outgoing framed messages).
 */
function makePipe(): {
	process: SpawnedProcess;
	emitStdout: (data: Uint8Array) => void;
	emitEnd: () => void;
	writtenToStdin: () => Uint8Array[];
	killed: () => boolean;
} {
	const dataListeners: Array<(data: Uint8Array) => void> = [];
	const endListeners: Array<() => void> = [];
	const stdinWrites: Uint8Array[] = [];
	let killed = false;

	const process: SpawnedProcess = {
		stdin: {
			write: (bytes: Uint8Array) => {
				stdinWrites.push(bytes);
			},
		},
		stdout: {
			on: (event: string, cb: (data: Uint8Array) => void) => {
				if (event === "data") dataListeners.push(cb);
				else if (event === "end") endListeners.push(cb as unknown as () => void);
			},
		},
		pid: 12345,
		kill: () => {
			killed = true;
		},
	};

	return {
		process,
		emitStdout: (data: Uint8Array) => {
			for (const cb of dataListeners) cb(data);
		},
		emitEnd: () => {
			for (const cb of endListeners) cb();
		},
		writtenToStdin: () => stdinWrites,
		killed: () => killed,
	};
}

describe("createStdioTransport", () => {
	it("creates connection with correct pid", () => {
		const pair = makePipe();
		const spawn: SpawnProcess = () => pair.process;

		const { connection } = createStdioTransport({ spawn, command: ["test-server"] }, "/tmp");

		expect(connection.pid).toBe(12345);
		connection.close();
	});

	it("connection sends framed messages via stdin", () => {
		const pair = makePipe();
		const spawn: SpawnProcess = () => pair.process;

		const { connection } = createStdioTransport({ spawn, command: ["test"] }, "/tmp");

		connection.notify("test/method", { key: "value" });

		const writes = pair.writtenToStdin();
		expect(writes.length).toBe(1);
		const text = new TextDecoder().decode(writes[0]);
		expect(text).toContain("Content-Length:");
		expect(text).toContain('"method":"test/method"');
		connection.close();
	});

	it("close kills the child process", () => {
		const pair = makePipe();
		const spawn: SpawnProcess = () => pair.process;

		const { connection } = createStdioTransport({ spawn, command: ["test"] }, "/tmp");

		connection.close();
		expect(pair.killed()).toBe(true);
	});

	it("pipes stdout through framing: a notification triggers onNotification", async () => {
		const pair = makePipe();
		const spawn: SpawnProcess = () => pair.process;

		const { connection } = createStdioTransport({ spawn, command: ["test"] }, "/tmp");

		let received: unknown = null;
		connection.onNotification("notifications/tools/list_changed", (params) => {
			received = params;
		});

		// Simulate the server writing a framed notification to stdout.
		const notification = JSON.stringify({
			jsonrpc: "2.0",
			method: "notifications/tools/list_changed",
			params: { reason: "tools added" },
		});
		pair.emitStdout(encode(notification));

		// onNotification is invoked synchronously inside the data handler.
		expect(received).toEqual({ reason: "tools added" });
		connection.close();
	});

	it("pipes stdout through framing: a response resolves a request", async () => {
		const pair = makePipe();
		const spawn: SpawnProcess = () => pair.process;

		const { connection } = createStdioTransport({ spawn, command: ["test"] }, "/tmp");

		const resultPromise = connection.send("tools/list");

		// The request was framed and written to stdin; respond via stdout.
		const response = JSON.stringify({
			jsonrpc: "2.0",
			id: 1,
			result: { tools: [{ name: "t", description: "d", inputSchema: { type: "object" } }] },
		});
		pair.emitStdout(encode(response));

		const result = await resultPromise;
		expect(result).toEqual({
			tools: [{ name: "t", description: "d", inputSchema: { type: "object" } }],
		});
		connection.close();
	});

	it("handles a frame split across two stdout chunks", async () => {
		const pair = makePipe();
		const spawn: SpawnProcess = () => pair.process;

		const { connection } = createStdioTransport({ spawn, command: ["test"] }, "/tmp");

		const resultPromise = connection.send("ping");

		const response = encode(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { ok: true } }));
		const mid = Math.floor(response.length / 2);
		pair.emitStdout(response.slice(0, mid));
		pair.emitStdout(response.slice(mid));

		await expect(resultPromise).resolves.toEqual({ ok: true });
		connection.close();
	});
});