mcp-server.test.ts•2.76 kB
import { describe, it, expect } from "bun:test";
import os from "node:os";
import path from "node:path";
import { mkdir, mkdtemp, writeFile, chmod } from "node:fs/promises";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
function startClient(env?: Record<string, string>) {
const transport = new StdioClientTransport({
command: "bun",
args: ["src/server.ts"],
env,
stderr: "pipe",
});
const client = new Client({ name: "test-client", version: "0.0.0" });
// Surface server stderr in test output for debugging
transport.stderr?.on("data", (chunk) => {
console.error(String(chunk));
});
const connected = client.connect(transport, { timeout: 15000 });
// @ts-ignore attach for cleanup
(client as any)._connected = connected;
return client;
}
async function stopClient(client: Client) {
// @ts-ignore grab underlying transport
const transport = client.transport;
await transport?.close?.();
}
describe("swift-test-mcp-server", () => {
it("returns an error when Package.swift is missing", async () => {
const client = startClient();
try {
const tmp = await mkdtemp(path.join(os.tmpdir(), "swift-mcp-no-manifest-"));
const result = await client.callTool({
name: "swift-test",
arguments: { packagePath: tmp },
});
expect(result.isError).toBe(true);
const text = result.content?.[0]?.type === "text" ? result.content?.[0]?.text : "";
expect(text).toContain("No Package.swift");
} finally {
await stopClient(client);
}
});
it("executes with a shimmed swift and succeeds", async () => {
const pkgRoot = await mkdtemp(path.join(os.tmpdir(), "swift-mcp-pkg-"));
await writeFile(path.join(pkgRoot, "Package.swift"), "// fake manifest for tests\n", "utf8");
const binDir = path.join(pkgRoot, "bin");
await mkdir(binDir, { recursive: true });
const swiftShim = path.join(binDir, "swift");
const shimContent = `#!/usr/bin/env bash\n\n# ignore args; emulate swift test\necho \"FAKE SWIFT: $*\"\nexit 0\n`;
await writeFile(swiftShim, shimContent, { encoding: "utf8" });
await chmod(swiftShim, 0o755);
const client = startClient({ PATH: `${binDir}:${process.env.PATH ?? ""}` });
try {
const result = await client.callTool({
name: "swift-test",
arguments: { packagePath: pkgRoot },
});
const text = result.content?.[0]?.type === "text" ? result.content?.[0]?.text : "";
expect(text).toContain("FAKE SWIFT:");
expect(text).toContain("exitCode: 0");
expect(result.isError).toBe(false);
} finally {
await stopClient(client);
}
});
});