When testing thedotmack/claude-mem next to an existing Claude Code pipeline, the integration claim is plain. Capture the session, compress it, and inject a relevant slice on the next session. The project also targets other harnesses we already run, including Codex, Copilot, and OpenCode. The production question is narrower: where does that slice enter the context window, and what does the MCP process do when the slice is not small?
We did not replace our tool server with claude-mem. Capture and compression stay there. A separate TypeScript process, session-memory-gate, is the only component allowed to return recalled text to the model. Tool results and memory results fail differently. Putting both on one stdout makes the failure mode ambiguous, and ambiguous stdio failures are expensive to diagnose under a desktop host.
JSON-RPC over stdio has a single legal channel for frames, and that channel is stdout. In our first rollout a handler threw after a partial log line hit stdout. The client could not parse the frame. Claude Desktop did not surface a structured RPC error. The child exited, the host restarted it, and the session looked idle. Cursor behaved the same way. From the operator side this is a silent crash: an unhandled stdio parse error, not a defect inside claude-mem's compressor.
Stdout stays protocol-only. Diagnostics go to stderr. An error on stdin exits non-zero. We do not attempt to resynchronize a half-read frame; once the byte stream is torn, the next read is not a new message, it is leftover payload. Boot failures write one stderr line so the host log contains a cause instead of an empty restart loop.
The second outage was the context window. A session that had written a large generated file was stored almost raw after compression timed out. The following turn started with that payload already resident, and tool results appended more JSON. The agent stopped calling tools and started paraphrasing its own prompt. Persistent memory that fails open is a replay buffer pointed at the window.
claude-mem only pays for itself when compression actually shrinks history. We do not assume that on the request path. recall_session slices to MAX_INJECT_CHARS, default 4000, and rejects payloads over 24 KB. A missing artifact returns an empty string. Empty means a degraded session. A raw transcript means an outage. Relevance filtering remains in claude-mem. The byte budget remains in our process, where a thrown error is visible on stderr.
Compression is its own dependency on the session edge. Timeout and oversize both become an empty inject. A short summary passes through the cap unchanged. We do not retry inside the MCP handler. A retry holds the stdio response open, and the desktop host treats the server as hung. If the summary dropped a diff, the agent can call recall_session again with a tighter query. It cannot recover a window that is already full.
The compressor client is OpenAI-compatible. In this topology that client sets baseURL to https://b-lost.com/v1, so provider fallback stays on one relay while we vary only the inject cap and check that the next tool call still fits. The thing under measurement was truncation and residual window, not model brand.
The process below will not open a raw session log. It only reads an already compressed artifact from MEMORY_ROOT.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
const MAX_CHARS = Number(process.env.MAX_INJECT_CHARS ?? 4000);
const MAX_BYTES = 24_000;
const server = new Server(
{ name: "session-memory-gate", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: "recall_session",
description: "Return a size-capped slice of compressed session memory",
inputSchema: {
type: "object",
properties: { query: { type: "string", maxLength: 200 } },
required: ["query"],
},
},
],
}));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
if (req.params.name !== "recall_session") {
throw new Error(`unknown tool: ${req.params.name}`);
}
const query = String(req.params.arguments?.query ?? "");
const text = (await readCompressed(query)).slice(0, MAX_CHARS);
if (Buffer.byteLength(text, "utf8") > MAX_BYTES) {
throw new Error("inject exceeds stdio budget");
}
return { content: [{ type: "text", text }] };
});
async function readCompressed(query: string): Promise<string> {
const root = process.env.MEMORY_ROOT;
if (!root) throw new Error("MEMORY_ROOT is required");
const safe = query.replace(/[^a-zA-Z0-9._-]/g, "").slice(0, 64);
if (!safe) return "";
try {
return await readFile(join(root, `${safe}.md`), "utf8");
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") return "";
throw err;
}
}
async function main() {
process.stdin.on("error", (err) => {
process.stderr.write(`stdio read failed: ${err.message}\n`);
process.exit(1);
});
await server.connect(new StdioServerTransport());
}
main().catch((err) => {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`mcp boot failed: ${msg}\n`);
process.exit(1);
});
Claude Desktop (claude_desktop_config.json) and Cursor's MCP settings use the same entry. Do not wrap the command in a shell that prints a banner. Any bytes on stdout that are not a JSON-RPC frame desynchronize the client.
{
"mcpServers": {
"session-memory-gate": {
"command": "node",
"args": ["/opt/agents/session-memory-gate/dist/index.js"],
"env": {
"MEMORY_ROOT": "/var/lib/agent-memory",
"MAX_INJECT_CHARS": "4000"
}
}
}
}
claude-mem still owns capture and compression for the harness. This server only answers recall_session, and only from artifacts that already survived compression.
The cap keeps the window alive and also drops detail the next session may need, especially diffs the compressor ranked as low relevance and the byte budget then cut again. Fail closed and the agent repeats work. Fail open and it loses the ability to call tools. I still do not have a stable rule for which sessions may exceed the cap, and I do not want that rule living in a prompt where one oversized observation can vote itself back into context.