Skip to content

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

fix(mcp): proxy standalone tools to running server when reachable (#159)

Rohit Ghumare7ef615580612
diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts
new file mode 100644
index 00000000..9f9ed785
--- /dev/null
+++ b/src/mcp/rest-proxy.ts
@@ -0,0 +1,88 @@
+const DEFAULT_URL = "http://localhost:3111";
+const HEALTH_PROBE_TIMEOUT_MS = 500;
+const CALL_TIMEOUT_MS = 15_000;
+
+export interface ProxyHandle {
+ mode: "proxy";
+ baseUrl: string;
+ call: (path: string, init?: RequestInit) => Promise<unknown>;
+}
+
+export interface LocalHandle {
+ mode: "local";
+}
+
+export type Handle = ProxyHandle | LocalHandle;
+
+let cached: Handle | null = null;
+let probeInFlight: Promise<Handle> | null = null;
+
+function baseUrl(): string {
+ return (process.env["AGENTMEMORY_URL"] || DEFAULT_URL).replace(/\/+$/, "");
+}
+
+function authHeader(): Record<string, string> {
+ const secret = process.env["AGENTMEMORY_SECRET"];
+ return secret ? { authorization: `Bearer ${secret}` } : {};
+}
+
+async function probe(url: string): Promise<boolean> {
+ try {
+ const res = await fetch(`${url}/agentmemory/livez`, {
+ method: "GET",
+ headers: authHeader(),
+ signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS),
+ });
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
+export async function resolveHandle(): Promise<Handle> {
+ if (cached) return cached;
+ if (probeInFlight) return probeInFlight;
+ const url = baseUrl();
+ probeInFlight = (async () => {
+ const up = await probe(url);
+ if (up) {
+ const handle: ProxyHandle = {
+ mode: "proxy",
+ baseUrl: url,
+ call: async (path, init) => {
+ const res = await fetch(`${url}${path}`, {
+ ...init,
+ headers: {
+ "content-type": "application/json",
+ ...authHeader(),
+ ...(init?.headers as Record<string, string> | undefined),
+ },
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
+ });
+ if (!res.ok) {
+ throw new Error(
+ `${init?.method || "GET"} ${path} -> ${res.status} ${res.statusText}`,
+ );
+ }
+ const text = await res.text();
+ return text ? JSON.parse(text) : null;
+ },
+ };
+ cached = handle;
+ return handle;
+ }
+ const local: LocalHandle = { mode: "local" };
+ cached = local;
+ return local;
+ })();
+ try {
+ return await probeInFlight;
+ } finally {
+ probeInFlight = null;
+ }
+}
+
+export function resetHandleForTests(): void {
+ cached = null;
+ probeInFlight = null;
+}
diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts
index e623669c..ad4c15d4 100644
--- a/src/mcp/standalone.ts
+++ b/src/mcp/standalone.ts
@@ -6,6 +6,7 @@ import { getVisibleTools } from "./tools-registry.js";
import { getStandalonePersistPath } from "../config.js";
import { VERSION } from "../version.js";
import { generateId } from "../state/schema.js";
+import { resolveHandle, type Handle, type ProxyHandle } from "./rest-proxy.js";
const IMPLEMENTED_TOOLS = new Set([
"memory_save",
@@ -24,10 +25,22 @@ const SERVER_INFO = {
};
const kv = new InMemoryKV(getStandalonePersistPath());
+let modeAnnounced = false;
+
+function announceMode(handle: Handle): void {
+ if (modeAnnounced) return;
+ modeAnnounced = true;
+ if (handle.mode === "proxy") {
+ process.stderr.write(
+ `[@agentmemory/mcp] proxying to agentmemory server at ${handle.baseUrl}\n`,
+ );
+ } else {
+ process.stderr.write(
+ `[@agentmemory/mcp] no server reachable at ${process.env["AGENTMEMORY_URL"] || "http://localhost:3111"}; falling back to local InMemoryKV\n`,
+ );
+ }
+}
-// Accept arrays, comma-separated strings, or a single string and always
-// return a trimmed, non-empty string array. Plugin skills (#139) tell
-// Claude to pass arrays; older clients may still pass CSV strings.
function normalizeList(value: unknown): string[] {
if (!value) return [];
if (Array.isArray(value)) {
@@ -44,29 +57,112 @@ function normalizeList(value: unknown): string[] {
return [];
}
-// Parse a user-supplied limit argument, clamping to a sane range so an
-// adversarial or buggy caller can't request a million memories or pass
-// a negative / NaN / Infinity value that breaks .slice().
const DEFAULT_LIMIT = 10;
const MAX_LIMIT = 100;
function parseLimit(raw: unknown, fallback = DEFAULT_LIMIT): number {
- // Only accept explicit numbers or numeric strings. Reject booleans,
- // objects, arrays, null, undefined — they shouldn't silently coerce
- // (e.g. `Number(true) === 1` would sneak a limit of 1 through).
if (typeof raw !== "number" && typeof raw !== "string") return fallback;
const n = Number(raw);
if (!Number.isFinite(n) || n <= 0) return fallback;
return Math.min(Math.floor(n), MAX_LIMIT);
}
-export async function handleToolCall(
+function textResponse(payload: unknown, pretty = false): {
+ content: Array<{ type: string; text: string }>;
+} {
+ return {
+ content: [
+ { type: "text", text: JSON.stringify(payload, null, pretty ? 2 : 0) },
+ ],
+ };
+}
+
+async function handleProxy(
toolName: string,
args: Record<string, unknown>,
- kvInstance: InMemoryKV = kv,
+ handle: ProxyHandle,
+): Promise<{ content: Array<{ type: string; text: string }> }> {
+ switch (toolName) {
+ case "memory_save": {
+ const content = args["content"];
+ if (typeof content !== "string" || !content.trim()) {
+ throw new Error("content is required");
+ }
+ const payload = {
+ content,
+ type: (args["type"] as string) || "fact",
+ concepts: normalizeList(args["concepts"]),
+ files: normalizeList(args["files"]),
+ };
+ const result = await handle.call("/agentmemory/remember", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ return textResponse(result);
+ }
+
+ case "memory_recall":
+ case "memory_smart_search": {
+ const query = args["query"];
+ if (typeof query !== "string" || !query.trim()) {
+ throw new Error("query is required");
+ }
+ const limit = parseLimit(args["limit"]);
+ const result = await handle.call("/agentmemory/smart-search", {
+ method: "POST",
+ body: JSON.stringify({ query: query.trim(), limit }),
+ });
+ return textResponse(result, true);
+ }
+
+ case "memory_sessions": {
+ const limit = parseLimit(args["limit"], 20);
+ const result = await handle.call(
+ `/agentmemory/sessions?limit=${limit}`,
+ { method: "GET" },
+ );
+ return textResponse(result, true);
+ }
+
+ case "memory_governance_delete": {
+ const ids = normalizeList(args["memoryIds"]);
+ if (ids.length === 0) throw new Error("memoryIds is required");
+ const result = await handle.call("/agentmemory/governance/memories", {
+ method: "POST",
+ body: JSON.stringify({
+ memoryIds: ids,
+ reason: (args["reason"] as string) || "plugin skill request",
+ }),
+ });
+ return textResponse(result);
+ }
+
+ case "memory_export": {
+ const result = await handle.call("/agentmemory/export", { method: "GET" });
+ return textResponse(result, true);
+ }
+
+ case "memory_audit": {
+ const limit = parseLimit(args["limit"], 50);
+ const result = await handle.call(
+ `/agentmemory/audit?limit=${limit}`,
+ { method: "GET" },
+ );
+ return textResponse(result, true);
+ }
+
+ default:
+ throw new Error(`Unknown tool: ${toolName}`);
+ }
+}
+
+async function handleLocal(
+ toolName: string,
+ args: Record<string, unknown>,
+ kvInstance: InMemoryKV,
): Promise<{ content: Array<{ type: string; text: string }> }> {
switch (toolName) {
case "memory_save": {
- const rawContent = args.content;
+ const rawContent = args["content"];
if (typeof rawContent !== "string" || !rawContent.trim()) {
throw new Error("content is required");
}
@@ -75,11 +171,11 @@ export async function handleToolCall(
const isoNow = new Date().toISOString();
await kvInstance.set("mem:memories", id, {
id,
- type: (args.type as string) || "fact",
+ type: (args["type"] as string) || "fact",
title: content.slice(0, 80),
content,
- concepts: normalizeList(args.concepts),
- files: normalizeList(args.files),
+ concepts: normalizeList(args["concepts"]),
+ files: normalizeList(args["files"]),
createdAt: isoNow,
updatedAt: isoNow,
strength: 7,
@@ -88,36 +184,21 @@ export async function handleToolCall(
sessionIds: [],
});
kvInstance.persist();
- return {
- content: [{ type: "text", text: JSON.stringify({ saved: id }) }],
- };
+ return textResponse({ saved: id });
}
case "memory_recall":
case "memory_smart_search": {
- // memory_smart_search would normally run hybrid BM25+vector+graph
- // in the engine-backed path, but the standalone shim (#139) only
- // has the in-memory KV store, so we fall back to a substring
- // filter. The tool name is kept so plugin skills that say "use
- // memory_smart_search" still work.
- //
- // Empty/missing query is rejected — the forget skill uses this
- // as its confirmation step before a destructive delete, and an
- // empty query would match every memory in the store, surfacing
- // unrelated IDs for deletion.
- const rawQuery = args.query;
+ const rawQuery = args["query"];
if (typeof rawQuery !== "string" || !rawQuery.trim()) {
throw new Error("query is required");
}
const query = rawQuery.trim().toLowerCase();
- const limit = parseLimit(args.limit);
+ const limit = parseLimit(args["limit"]);
const all =
await kvInstance.list<Record<string, unknown>>("mem:memories");
const results = all
.filter((m) => {
- // Search title/content AND files/concepts/sessionIds so the
- // forget skill can find memories by file path or session
- // ID, not just by narrative text.
const text = [
typeof m["title"] === "string" ? m["title"] : "",
typeof m["content"] === "string" ? m["content"] : "",
@@ -131,39 +212,19 @@ export async function handleToolCall(
return query.split(/\s+/).every((word) => text.includes(word));
})
.slice(0, limit);
- return {
- content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
- };
+ return textResponse(results, true);
}
case "memory_sessions": {
const sessions =
await kvInstance.list<Record<string, unknown>>("mem:sessions");
- const limit = parseLimit(args.limit, 20);
- return {
- content: [
- {
- type: "text",
- text: JSON.stringify(
- { sessions: sessions.slice(0, limit) },
- null,
- 2,
- ),
- },
- ],
- };
+ const limit = parseLimit(args["limit"], 20);
+ return textResponse({ sessions: sessions.slice(0, limit) }, true);
}
case "memory_governance_delete": {
- // Deletes memories by id. Accepts either a memoryIds array or a
- // comma-separated memoryIds string (same normalization pattern as
- // concepts/files) so plugin skills and legacy clients both work.
- // Unknown ids are silently skipped — the response reports how many
- // were actually removed so the caller can tell the user.
- const ids = normalizeList(args.memoryIds);
- if (ids.length === 0) {
- throw new Error("memoryIds is required");
- }
+ const ids = normalizeList(args["memoryIds"]);
+ if (ids.length === 0) throw new Error("memoryIds is required");
let deleted = 0;
for (const id of ids) {
const existing = await kvInstance.get("mem:memories", id);
@@ -173,52 +234,26 @@ export async function handleToolCall(
}
}
kvInstance.persist();
- return {
- content: [
- {
- type: "text",
- text: JSON.stringify({
- deleted,
- requested: ids.length,
- reason: (args.reason as string) || "plugin skill request",
- }),
- },
- ],
- };
+ return textResponse({
+ deleted,
+ requested: ids.length,
+ reason: (args["reason"] as string) || "plugin skill request",
+ });
}
case "memory_export": {
const memories = await kvInstance.list("mem:memories");
const sessions = await kvInstance.list("mem:sessions");
- return {
- content: [
- {
- type: "text",
- text: JSON.stringify(
- { version: VERSION, memories, sessions },
- null,
- 2,
- ),
- },
- ],
- };
+ return textResponse({ version: VERSION, memories, sessions }, true);
}
case "memory_audit": {
const entries = await kvInstance.list("mem:audit");
- const limit = parseLimit(args.limit, 50);
- return {
- content: [
- {
- type: "text",
- text: JSON.stringify(
- (entries as Array<Record<string, unknown>>).slice(0, limit),
- null,
- 2,
- ),
- },
- ],
- };
+ const limit = parseLimit(args["limit"], 50);
+ return textResponse(
+ (entries as Array<Record<string, unknown>>).slice(0, limit),
+ true,
+ );
}
default:
@@ -226,14 +261,31 @@ export async function handleToolCall(
}
}
+export async function handleToolCall(
+ toolName: string,
+ args: Record<string, unknown>,
+ kvInstance: InMemoryKV = kv,
+): Promise<{ content: Array<{ type: string; text: string }> }> {
+ const handle = await resolveHandle();
+ announceMode(handle);
+ if (handle.mode === "proxy") {
+ try {
+ return await handleProxy(toolName, args, handle);
+ } catch (err) {
+ process.stderr.write(
+ `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}; falling back to local KV for this request\n`,
+ );
+ }
+ }
+ return handleLocal(toolName, args, kvInstance);
+}
+
const transport = createStdioTransport(async (method, params) => {
switch (method) {
case "initialize":
return {
protocolVersion: SERVER_INFO.protocolVersion,
- capabilities: {
- tools: { listChanged: false },
- },
+ capabilities: { tools: { listChanged: false } },
serverInfo: {
name: SERVER_INFO.name,
version: SERVER_INFO.version,
diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts
new file mode 100644
index 00000000..43462cb0
--- /dev/null
+++ b/test/mcp-standalone-proxy.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it, beforeEach, afterEach, vi } from "vitest";
+import { handleToolCall } from "../src/mcp/standalone.js";
+import { resetHandleForTests } from "../src/mcp/rest-proxy.js";
+import { InMemoryKV } from "../src/mcp/in-memory-kv.js";
+
+type FetchMock = ReturnType<typeof vi.fn>;
+
+function installFetch(handler: (url: string, init?: RequestInit) => Response): FetchMock {
+ const fn = vi.fn(async (url: string | URL, init?: RequestInit) =>
+ handler(url.toString(), init),
+ );
+ (globalThis as { fetch: typeof fetch }).fetch = fn as unknown as typeof fetch;
+ return fn;
+}
+
+const BASE = "http://localhost:3111";
+
+describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ resetHandleForTests();
+ process.env["AGENTMEMORY_URL"] = BASE;
+ delete process.env["AGENTMEMORY_SECRET"];
+ });
+
+ afterEach(() => {
+ resetHandleForTests();
+ globalThis.fetch = originalFetch;
+ delete process.env["AGENTMEMORY_URL"];
+ });
+
+ it("proxies memory_sessions to GET /agentmemory/sessions when server is up", async () => {
+ const calls: Array<{ url: string; method: string }> = [];
+ installFetch((url, init) => {
+ calls.push({ url, method: init?.method || "GET" });
+ if (url.endsWith("/agentmemory/livez")) {
+ return new Response("ok", { status: 200 });
+ }
+ if (url.includes("/agentmemory/sessions")) {
+ return new Response(
+ JSON.stringify({ sessions: [{ id: "sess-1", observations: 69 }] }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ );
+ }
+ return new Response("not found", { status: 404 });
+ });
+
+ const res = await handleToolCall("memory_sessions", { limit: 5 });
+ const body = JSON.parse(res.content[0].text);
+ expect(body.sessions).toHaveLength(1);
+ expect(body.sessions[0].id).toBe("sess-1");
+ expect(calls.find((c) => c.url.includes("/sessions"))).toBeDefined();
+ });
+
+ it("proxies memory_smart_search to POST /agentmemory/smart-search", async () => {
+ installFetch((url, init) => {
+ if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });
+ if (url.endsWith("/agentmemory/smart-search")) {
+ const body = JSON.parse((init?.body as string) || "{}");
+ return new Response(
+ JSON.stringify({ query: body.query, hits: [{ id: "m1", score: 0.9 }] }),
+ { status: 200 },
+ );
+ }
+ return new Response("", { status: 404 });
+ });
+ const res = await handleToolCall("memory_smart_search", { query: "auth bug", limit: 5 });
+ const body = JSON.parse(res.content[0].text);
+ expect(body.query).toBe("auth bug");
+ expect(body.hits[0].id).toBe("m1");
+ });
+
+ it("attaches Bearer token when AGENTMEMORY_SECRET is set", async () => {
+ process.env["AGENTMEMORY_SECRET"] = "s3cret";
+ const seen: string[] = [];
+ installFetch((url, init) => {
+ const auth = (init?.headers as Record<string, string> | undefined)?.["authorization"];
+ if (auth) seen.push(`${url}|${auth}`);
+ if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });
+ return new Response(JSON.stringify({ sessions: [] }), { status: 200 });
+ });
+ await handleToolCall("memory_sessions", {});
+ expect(seen.every((s) => s.endsWith("|Bearer s3cret"))).toBe(true);
+ expect(seen.some((s) => s.includes("/agentmemory/livez"))).toBe(true);
+ });
+
+ it("falls back to local InMemoryKV when server is unreachable", async () => {
+ installFetch(() => {
+ throw new Error("ECONNREFUSED");
+ });
+ const localKv = new InMemoryKV(undefined);
+ await handleToolCall("memory_save", { content: "local only" }, localKv);
+ const recall = await handleToolCall("memory_recall", { query: "local" }, localKv);
+ const out = JSON.parse(recall.content[0].text);
+ expect(Array.isArray(out)).toBe(true);
+ expect(out).toHaveLength(1);
+ expect(out[0].content).toBe("local only");
+ });
+
+ it("falls back to local KV for a single request if proxy call throws after probe succeeded", async () => {
+ let callCount = 0;
+ installFetch((url) => {
+ callCount++;
+ if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });
+ return new Response("boom", { status: 500, statusText: "Internal Server Error" });
+ });
+ const localKv = new InMemoryKV(undefined);
+ await handleToolCall("memory_save", { content: "fallback entry" }, localKv);
+ const recall = await handleToolCall("memory_recall", { query: "fallback" }, localKv);
+ const out = JSON.parse(recall.content[0].text);
+ expect(out[0].content).toBe("fallback entry");
+ expect(callCount).toBeGreaterThan(1);
+ });
+});