Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(mcp): never respond to JSON-RPC notifications (#129)

Rohit Ghumare745ad8709546
diff --git a/src/mcp/transport.ts b/src/mcp/transport.ts
index 4dac9d73..98856175 100644
--- a/src/mcp/transport.ts
+++ b/src/mcp/transport.ts
@@ -2,14 +2,14 @@ import { createInterface } from "node:readline";
export interface JsonRpcRequest {
jsonrpc: "2.0";
- id: string | number;
+ id?: string | number;
method: string;
params?: Record<string, unknown>;
}
export interface JsonRpcResponse {
jsonrpc: "2.0";
- id: string | number;
+ id: string | number | null;
result?: unknown;
error?: { code: number; message: string; data?: unknown };
}
@@ -19,65 +19,96 @@ export type RequestHandler = (
params: Record<string, unknown>,
) => Promise<unknown>;
-export function createStdioTransport(handler: RequestHandler): {
- start: () => void;
- stop: () => void;
-} {
- let rl: ReturnType<typeof createInterface> | null = null;
+// JSON-RPC 2.0 notifications are messages without an `id` field. The spec
+// (and the MCP transport contract) requires the server to NOT send a
+// response for notifications. Some clients tolerate spurious responses;
+// stricter clients (e.g. Codex CLI) treat them as protocol violations and
+// close the transport. See agentmemory#129.
+function isNotification(req: JsonRpcRequest): boolean {
+ return req.id === undefined || req.id === null;
+}
- const onLine = async (line: string) => {
- const trimmed = line.trim();
- if (!trimmed) return;
+// Exported for unit tests so the line-handling logic is exercised
+// independently of process.stdin / process.stdout.
+export async function processLine(
+ line: string,
+ handler: RequestHandler,
+ writeOut: (response: JsonRpcResponse) => void,
+ writeErr: (msg: string) => void = (msg) => process.stderr.write(msg),
+): Promise<void> {
+ const trimmed = line.trim();
+ if (!trimmed) return;
- let parsed: unknown;
- try {
- parsed = JSON.parse(trimmed);
- } catch {
- const error: JsonRpcResponse = {
- jsonrpc: "2.0",
- id: null as unknown as number,
- error: { code: -32700, message: "Parse error" },
- };
- process.stdout.write(JSON.stringify(error) + "\n");
- return;
- }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ writeOut({
+ jsonrpc: "2.0",
+ id: null,
+ error: { code: -32700, message: "Parse error" },
+ });
+ return;
+ }
- const request = parsed as JsonRpcRequest;
- if (
- !request ||
- request.jsonrpc !== "2.0" ||
- typeof request.method !== "string"
- ) {
- const error: JsonRpcResponse = {
+ const request = parsed as JsonRpcRequest;
+ if (
+ !request ||
+ request.jsonrpc !== "2.0" ||
+ typeof request.method !== "string"
+ ) {
+ if (request && (request as { id?: unknown }).id != null) {
+ writeOut({
jsonrpc: "2.0",
- id: request?.id ?? (null as unknown as number),
+ id: (request as JsonRpcRequest).id as string | number,
error: { code: -32600, message: "Invalid Request" },
- };
- process.stdout.write(JSON.stringify(error) + "\n");
- return;
+ });
}
+ return;
+ }
- try {
- const result = await handler(request.method, request.params || {});
- const response: JsonRpcResponse = {
- jsonrpc: "2.0",
- id: request.id,
- result,
- };
- process.stdout.write(JSON.stringify(response) + "\n");
- } catch (err) {
- const response: JsonRpcResponse = {
- jsonrpc: "2.0",
- id: request.id,
- error: {
- code: -32603,
- message: err instanceof Error ? err.message : String(err),
- },
- };
- process.stdout.write(JSON.stringify(response) + "\n");
+ const notification = isNotification(request);
+
+ try {
+ const result = await handler(request.method, request.params || {});
+ if (notification) return;
+ writeOut({
+ jsonrpc: "2.0",
+ id: request.id as string | number,
+ result,
+ });
+ } catch (err) {
+ if (notification) {
+ writeErr(
+ `[mcp-transport] notification handler error for ${request.method}: ${
+ err instanceof Error ? err.message : String(err)
+ }\n`,
+ );
+ return;
}
+ writeOut({
+ jsonrpc: "2.0",
+ id: request.id as string | number,
+ error: {
+ code: -32603,
+ message: err instanceof Error ? err.message : String(err),
+ },
+ });
+ }
+}
+
+export function createStdioTransport(handler: RequestHandler): {
+ start: () => void;
+ stop: () => void;
+} {
+ let rl: ReturnType<typeof createInterface> | null = null;
+
+ const writeResponse = (response: JsonRpcResponse) => {
+ process.stdout.write(JSON.stringify(response) + "\n");
};
+ const onLine = (line: string) => processLine(line, handler, writeResponse);
+
return {
start() {
rl = createInterface({ input: process.stdin });
diff --git a/test/mcp-transport.test.ts b/test/mcp-transport.test.ts
new file mode 100644
index 00000000..681d9c6b
--- /dev/null
+++ b/test/mcp-transport.test.ts
@@ -0,0 +1,152 @@
+import { describe, it, expect, vi } from "vitest";
+import {
+ processLine,
+ type JsonRpcResponse,
+ type RequestHandler,
+} from "../src/mcp/transport.js";
+
+function collector() {
+ const out: JsonRpcResponse[] = [];
+ const err: string[] = [];
+ return {
+ out,
+ err,
+ writeOut: (r: JsonRpcResponse) => out.push(r),
+ writeErr: (m: string) => err.push(m),
+ };
+}
+
+const okHandler: RequestHandler = async (method) => ({ method });
+
+describe("processLine — request path", () => {
+ it("emits a response for a request with id", async () => {
+ const c = collector();
+ await processLine(
+ JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" }),
+ okHandler,
+ c.writeOut,
+ c.writeErr,
+ );
+ expect(c.out).toHaveLength(1);
+ expect(c.out[0]).toEqual({
+ jsonrpc: "2.0",
+ id: 1,
+ result: { method: "initialize" },
+ });
+ });
+
+ it("emits an error response when the handler throws on a request", async () => {
+ const c = collector();
+ const throwingHandler: RequestHandler = async () => {
+ throw new Error("boom");
+ };
+ await processLine(
+ JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/list" }),
+ throwingHandler,
+ c.writeOut,
+ c.writeErr,
+ );
+ expect(c.out).toHaveLength(1);
+ expect(c.out[0].id).toBe(7);
+ expect(c.out[0].error?.code).toBe(-32603);
+ expect(c.out[0].error?.message).toBe("boom");
+ });
+});
+
+describe("processLine — notification path (#129)", () => {
+ it("does NOT emit a response for a notification (no id field)", async () => {
+ const c = collector();
+ const handlerCalled = vi.fn(async () => ({ shouldNotEscape: true }));
+ await processLine(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ method: "notifications/initialized",
+ }),
+ handlerCalled,
+ c.writeOut,
+ c.writeErr,
+ );
+ expect(handlerCalled).toHaveBeenCalledOnce();
+ expect(c.out).toHaveLength(0);
+ expect(c.err).toHaveLength(0);
+ });
+
+ it("does NOT emit a response for a notification with id: null", async () => {
+ const c = collector();
+ await processLine(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ id: null,
+ method: "notifications/cancelled",
+ }),
+ okHandler,
+ c.writeOut,
+ c.writeErr,
+ );
+ expect(c.out).toHaveLength(0);
+ });
+
+ it("logs to stderr but does NOT emit a response when a notification handler throws", async () => {
+ const c = collector();
+ const throwingHandler: RequestHandler = async () => {
+ throw new Error("notification crash");
+ };
+ await processLine(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ method: "notifications/initialized",
+ }),
+ throwingHandler,
+ c.writeOut,
+ c.writeErr,
+ );
+ expect(c.out).toHaveLength(0);
+ expect(c.err).toHaveLength(1);
+ expect(c.err[0]).toContain("notification handler error");
+ expect(c.err[0]).toContain("notification crash");
+ });
+});
+
+describe("processLine — malformed input", () => {
+ it("emits a parse error with id: null for invalid JSON", async () => {
+ const c = collector();
+ await processLine("not-json", okHandler, c.writeOut, c.writeErr);
+ expect(c.out).toHaveLength(1);
+ expect(c.out[0].id).toBeNull();
+ expect(c.out[0].error?.code).toBe(-32700);
+ expect(c.out[0].error?.message).toBe("Parse error");
+ });
+
+ it("ignores empty / whitespace-only lines", async () => {
+ const c = collector();
+ await processLine("", okHandler, c.writeOut, c.writeErr);
+ await processLine(" \t ", okHandler, c.writeOut, c.writeErr);
+ expect(c.out).toHaveLength(0);
+ expect(c.err).toHaveLength(0);
+ });
+
+ it("emits an Invalid Request error when a request has an id but no jsonrpc", async () => {
+ const c = collector();
+ await processLine(
+ JSON.stringify({ id: 1, method: "tools/list" }),
+ okHandler,
+ c.writeOut,
+ c.writeErr,
+ );
+ expect(c.out).toHaveLength(1);
+ expect(c.out[0].id).toBe(1);
+ expect(c.out[0].error?.code).toBe(-32600);
+ });
+
+ it("silently drops a malformed message that has no id (treated as notification)", async () => {
+ const c = collector();
+ await processLine(
+ JSON.stringify({ method: "broken" }),
+ okHandler,
+ c.writeOut,
+ c.writeErr,
+ );
+ // No jsonrpc field, no id — drop without responding.
+ expect(c.out).toHaveLength(0);
+ });
+});