Skip to content

Commit b2610cb

Browse files
cliffhallclaude
andcommitted
test(memory): protocol-level characterization suite and per-file 90% coverage gate
Drive the memory server through an SDK Client over an in-memory transport and pin its current behavior on SDK 1.x: the advertised tool list, all nine tool handlers, the knowledge-graph resource and its subscriptions (including notifyGraphUpdated), persistence and loadGraph's skip paths. Characterize, without fixing, #4887, #4885, #4827 and #4797. Add a thin stdio smoke test of dist/index.js, also run through a symlink as npm's bin. To make the server buildable in-process, index.ts now exports a createServer(memoryFilePath) factory and starts stdio from main() only when isMainModule() says the file is the process entry point. version.ts takes an optional start URL so its fallback and error paths are testable. Enforce perFile 90/90/90/90 in vitest.config.ts. Remove the mocked-server resource tests, delete-reporting.test.ts and search-nodes-schema.test.ts, which the protocol suite now covers. Part of #4854 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent deb9b00 commit b2610cb

14 files changed

Lines changed: 2185 additions & 591 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-memory": patch
3+
---
4+
5+
Build the server with an exported `createServer()` factory and start stdio only when the package is run as a program, so importing the module no longer starts a server. Behavior over stdio is unchanged.

‎src/memory/__tests__/delete-reporting.test.ts‎

Lines changed: 0 additions & 105 deletions
This file was deleted.
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Tests for the memory server's startup path (#4854): main() run in-process
2+
// over an in-memory transport, so its MEMORY_FILE_PATH handling is covered,
3+
// and isMainModule(), the guard that keeps importing index.ts from starting a
4+
// stdio server. The bin itself is exercised over real stdio by
5+
// stdio-smoke.test.ts.
6+
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
7+
import { promises as fs } from "fs";
8+
import path from "path";
9+
import { pathToFileURL } from "url";
10+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
12+
import { isMainModule, main } from "../index.js";
13+
import { call, makeTempGraph, readFileText } from "./helpers.js";
14+
15+
describe("main", () => {
16+
let originalEnv: string | undefined;
17+
let dir: string;
18+
let cleanup: () => Promise<void>;
19+
20+
beforeEach(async () => {
21+
originalEnv = process.env.MEMORY_FILE_PATH;
22+
({ dir, cleanup } = await makeTempGraph());
23+
});
24+
25+
afterEach(async () => {
26+
if (originalEnv === undefined) {
27+
delete process.env.MEMORY_FILE_PATH;
28+
} else {
29+
process.env.MEMORY_FILE_PATH = originalEnv;
30+
}
31+
vi.restoreAllMocks();
32+
await cleanup();
33+
});
34+
35+
it("serves the graph file MEMORY_FILE_PATH names and logs a banner", async () => {
36+
const graphPath = path.join(dir, "custom-graph.jsonl");
37+
process.env.MEMORY_FILE_PATH = graphPath;
38+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
39+
const [clientTransport, serverTransport] =
40+
InMemoryTransport.createLinkedPair();
41+
const client = new Client({ name: "memory-test-client", version: "0.0.0" });
42+
43+
const server = await main(serverTransport);
44+
await client.connect(clientTransport);
45+
try {
46+
expect(client.getServerVersion()?.name).toBe("memory-server");
47+
await call(client, "create_entities", {
48+
entities: [{ name: "Alice", entityType: "person", observations: [] }],
49+
});
50+
expect(await readFileText(graphPath)).toBe(
51+
'{"type":"entity","name":"Alice","entityType":"person","observations":[]}\n',
52+
);
53+
expect(errorSpy).toHaveBeenCalledWith(
54+
"Knowledge Graph MCP Server running on stdio",
55+
);
56+
} finally {
57+
await client.close();
58+
await server.close();
59+
}
60+
});
61+
});
62+
63+
describe("isMainModule", () => {
64+
let dir: string;
65+
let cleanup: () => Promise<void>;
66+
let modulePath: string;
67+
68+
beforeEach(async () => {
69+
({ dir, cleanup } = await makeTempGraph());
70+
modulePath = path.join(dir, "index.js");
71+
await fs.writeFile(modulePath, "");
72+
});
73+
74+
afterEach(async () => {
75+
await cleanup();
76+
});
77+
78+
it("is false when imported by the test runner", () => {
79+
expect(isMainModule()).toBe(false);
80+
});
81+
82+
it("is true when the entry path is the module itself", () => {
83+
expect(isMainModule(modulePath, pathToFileURL(modulePath).href)).toBe(true);
84+
});
85+
86+
it("is true when the entry path is a symlink to the module, as npm's bin is", async () => {
87+
const link = path.join(dir, "mcp-server-memory");
88+
await fs.symlink(modulePath, link);
89+
expect(isMainModule(link, pathToFileURL(modulePath).href)).toBe(true);
90+
});
91+
92+
it("is false for another file", async () => {
93+
const other = path.join(dir, "other.js");
94+
await fs.writeFile(other, "");
95+
expect(isMainModule(other, pathToFileURL(modulePath).href)).toBe(false);
96+
});
97+
98+
it("is false when the entry path does not exist", () => {
99+
expect(
100+
isMainModule(
101+
path.join(dir, "missing.js"),
102+
pathToFileURL(modulePath).href,
103+
),
104+
).toBe(false);
105+
});
106+
107+
it("is false when there is no entry path, as in a REPL", () => {
108+
// An explicit undefined would select the default (the runner's argv[1]),
109+
// so pass the other falsy string a missing entry can arrive as.
110+
expect(isMainModule("", pathToFileURL(modulePath).href)).toBe(false);
111+
});
112+
});

‎src/memory/__tests__/file-path.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
// handling, the memory.json -> memory.jsonl migration, and "~" expansion.
33
//
44
// Every test runs ensureMemoryFilePath against its own temporary directory.
5-
// Importing ../index.js starts the server's main(), which runs the same
6-
// migration on the package directory, and Vitest runs test files in parallel:
7-
// files written beside the source are shared with every other test file, and
8-
// were migrated away mid-test (#4922).
5+
// Vitest runs test files in parallel, so files written beside the source are
6+
// shared with every other test file; when importing ../index.js still started
7+
// main(), its migration of the package directory moved them away mid-test
8+
// (#4922).
99
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
1010
import { promises as fs } from "fs";
1111
import path from "path";

‎src/memory/__tests__/helpers.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// Shared harness for the memory server's protocol-level tests: builds a server
2+
// with createServer(), links an SDK Client to it over an in-memory transport,
3+
// and gives each test its own temporary graph file. Tests assert on what the
4+
// client receives, so they hold across an SDK upgrade that keeps the wire
5+
// format; nothing here reaches into SDK internals.
6+
import { promises as fs } from "fs";
7+
import os from "os";
8+
import path from "path";
9+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
10+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
11+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
13+
import { createServer } from "../index.js";
14+
15+
export interface Connection {
16+
client: Client;
17+
server: McpServer;
18+
serverTransport: InMemoryTransport;
19+
close: () => Promise<void>;
20+
}
21+
22+
// Connect a fresh client to a fresh server over the graph file at filePath.
23+
export async function connect(filePath: string): Promise<Connection> {
24+
const server = createServer(filePath);
25+
const [clientTransport, serverTransport] =
26+
InMemoryTransport.createLinkedPair();
27+
const client = new Client({ name: "memory-test-client", version: "0.0.0" });
28+
await Promise.all([
29+
server.connect(serverTransport),
30+
client.connect(clientTransport),
31+
]);
32+
return {
33+
client,
34+
server,
35+
serverTransport,
36+
close: async () => {
37+
await client.close();
38+
await server.close();
39+
},
40+
};
41+
}
42+
43+
// A temporary directory holding the graph file, removed by cleanup().
44+
export async function makeTempGraph(): Promise<{
45+
dir: string;
46+
filePath: string;
47+
cleanup: () => Promise<void>;
48+
}> {
49+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mcp-memory-test-"));
50+
return {
51+
dir,
52+
filePath: path.join(dir, "memory.jsonl"),
53+
cleanup: () => fs.rm(dir, { recursive: true, force: true }),
54+
};
55+
}
56+
57+
// Call a tool and return its result typed as a CallToolResult. callTool's
58+
// declared return type also admits the legacy toolResult shape, which this
59+
// server never sends.
60+
export async function call(
61+
client: Client,
62+
name: string,
63+
args: Record<string, unknown> = {},
64+
): Promise<CallToolResult> {
65+
return (await client.callTool({
66+
name,
67+
arguments: args,
68+
})) as CallToolResult;
69+
}
70+
71+
// The text of a result's single text content block.
72+
export function textOf(result: CallToolResult): string {
73+
const [block] = result.content;
74+
if (result.content.length !== 1 || block.type !== "text") {
75+
throw new Error(
76+
`expected one text block, got ${JSON.stringify(result.content)}`,
77+
);
78+
}
79+
return block.text;
80+
}
81+
82+
// The graph file's raw contents.
83+
export function readFileText(filePath: string): Promise<string> {
84+
return fs.readFile(filePath, "utf-8");
85+
}

0 commit comments

Comments
 (0)