{"slug": "adopting-claude-mem-behind-a-bounded-mcp-stdio-gate", "title": "Adopting claude-mem Behind a Bounded MCP Stdio Gate", "summary": "A developer built session-memory-gate, a separate TypeScript MCP process that acts as the sole gate for injecting recalled session memory from thedotmack/claude-mem into Claude Code and other harnesses. The gate keeps stdout protocol-only with diagnostics on stderr, caps injected memory at 4,000 characters by default and rejects payloads over 24 KB, after earlier rollouts produced silent stdio crashes and a context window flooded by an uncompressed transcript. The developer reports that compression timeouts and oversize payloads now degrade to an empty inject rather than failing open.", "body_md": "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?\n\nWe 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.\n\nJSON-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.\n\nStdout 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.\n\nThe 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.\n\nclaude-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.\n\nCompression 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.\n\nThe 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.\n\nThe process below will not open a raw session log. It only reads an already compressed artifact from `MEMORY_ROOT`.\n\n``` js\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n  CallToolRequestSchema,\n  ListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\nconst MAX_CHARS = Number(process.env.MAX_INJECT_CHARS ?? 4000);\nconst MAX_BYTES = 24_000;\n\nconst server = new Server(\n  { name: \"session-memory-gate\", version: \"1.0.0\" },\n  { capabilities: { tools: {} } }\n);\n\nserver.setRequestHandler(ListToolsRequestSchema, async () => ({\n  tools: [\n    {\n      name: \"recall_session\",\n      description: \"Return a size-capped slice of compressed session memory\",\n      inputSchema: {\n        type: \"object\",\n        properties: { query: { type: \"string\", maxLength: 200 } },\n        required: [\"query\"],\n      },\n    },\n  ],\n}));\n\nserver.setRequestHandler(CallToolRequestSchema, async (req) => {\n  if (req.params.name !== \"recall_session\") {\n    throw new Error(`unknown tool: ${req.params.name}`);\n  }\n  const query = String(req.params.arguments?.query ?? \"\");\n  const text = (await readCompressed(query)).slice(0, MAX_CHARS);\n  if (Buffer.byteLength(text, \"utf8\") > MAX_BYTES) {\n    throw new Error(\"inject exceeds stdio budget\");\n  }\n  return { content: [{ type: \"text\", text }] };\n});\n\nasync function readCompressed(query: string): Promise<string> {\n  const root = process.env.MEMORY_ROOT;\n  if (!root) throw new Error(\"MEMORY_ROOT is required\");\n  const safe = query.replace(/[^a-zA-Z0-9._-]/g, \"\").slice(0, 64);\n  if (!safe) return \"\";\n  try {\n    return await readFile(join(root, `${safe}.md`), \"utf8\");\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return \"\";\n    throw err;\n  }\n}\n\nasync function main() {\n  process.stdin.on(\"error\", (err) => {\n    process.stderr.write(`stdio read failed: ${err.message}\\n`);\n    process.exit(1);\n  });\n  await server.connect(new StdioServerTransport());\n}\n\nmain().catch((err) => {\n  const msg = err instanceof Error ? err.message : String(err);\n  process.stderr.write(`mcp boot failed: ${msg}\\n`);\n  process.exit(1);\n});\n```\n\nClaude 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.\n\n```\n{\n  \"mcpServers\": {\n    \"session-memory-gate\": {\n      \"command\": \"node\",\n      \"args\": [\"/opt/agents/session-memory-gate/dist/index.js\"],\n      \"env\": {\n        \"MEMORY_ROOT\": \"/var/lib/agent-memory\",\n        \"MAX_INJECT_CHARS\": \"4000\"\n      }\n    }\n  }\n}\n```\n\nclaude-mem still owns capture and compression for the harness. This server only answers `recall_session`, and only from artifacts that already survived compression.\n\nThe 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.", "url": "https://wpnews.pro/news/adopting-claude-mem-behind-a-bounded-mcp-stdio-gate", "canonical_source": "https://dev.to/lucas_vance/adopting-claude-mem-behind-a-bounded-mcp-stdio-gate-4442", "published_at": "2026-11-23 20:40:58+00:00", "updated_at": "2026-11-23 20:42:34.094704+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "ai-tools", "large-language-models", "developer-tools"], "entities": ["claude-mem", "Claude Code", "Claude Desktop", "Cursor", "Codex", "Copilot", "OpenCode", "Model Context Protocol"], "also_reported_by": [], "takeaway": "Keeping MCP stdout protocol-only and capping injected memory at 4,000 characters (rejecting payloads over 24 KB) prevents a failed compression from flooding the context window and silently crashing the host.", "recommendation": {"advice": "Route recalled memory through a dedicated MCP gate that writes diagnostics only to stderr and degrades to an empty inject on compression timeout or oversize payloads.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/adopting-claude-mem-behind-a-bounded-mcp-stdio-gate", "markdown": "https://wpnews.pro/news/adopting-claude-mem-behind-a-bounded-mcp-stdio-gate.md", "text": "https://wpnews.pro/news/adopting-claude-mem-behind-a-bounded-mcp-stdio-gate.txt", "jsonld": "https://wpnews.pro/news/adopting-claude-mem-behind-a-bounded-mcp-stdio-gate.jsonld"}}