Skip to content

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

fix(mcp): address CodeRabbit review on standalone proxy

Rohit Ghumare8f2e14ce9cff
diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts
index 9f9ed785..8a188fbf 100644
--- a/src/mcp/rest-proxy.ts
+++ b/src/mcp/rest-proxy.ts
@@ -1,6 +1,7 @@
const DEFAULT_URL = "http://localhost:3111";
const HEALTH_PROBE_TIMEOUT_MS = 500;
const CALL_TIMEOUT_MS = 15_000;
+const LOCAL_MODE_TTL_MS = 30_000;
export interface ProxyHandle {
mode: "proxy";
@@ -15,6 +16,7 @@ export interface LocalHandle {
export type Handle = ProxyHandle | LocalHandle;
let cached: Handle | null = null;
+let cachedAt = 0;
let probeInFlight: Promise<Handle> | null = null;
function baseUrl(): string {
@@ -39,8 +41,21 @@ async function probe(url: string): Promise<boolean> {
}
}
+export function invalidateHandle(): void {
+ cached = null;
+ cachedAt = 0;
+}
+
export async function resolveHandle(): Promise<Handle> {
- if (cached) return cached;
+ const now = Date.now();
+ if (cached) {
+ if (cached.mode === "local" && now - cachedAt >= LOCAL_MODE_TTL_MS) {
+ cached = null;
+ cachedAt = 0;
+ } else {
+ return cached;
+ }
+ }
if (probeInFlight) return probeInFlight;
const url = baseUrl();
probeInFlight = (async () => {
@@ -69,10 +84,12 @@ export async function resolveHandle(): Promise<Handle> {
},
};
cached = handle;
+ cachedAt = Date.now();
return handle;
}
const local: LocalHandle = { mode: "local" };
cached = local;
+ cachedAt = Date.now();
return local;
})();
try {
@@ -84,5 +101,6 @@ export async function resolveHandle(): Promise<Handle> {
export function resetHandleForTests(): void {
cached = null;
+ cachedAt = 0;
probeInFlight = null;
}
diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts
index ad4c15d4..812a8356 100644
--- a/src/mcp/standalone.ts
+++ b/src/mcp/standalone.ts
@@ -6,7 +6,12 @@ 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";
+import {
+ resolveHandle,
+ invalidateHandle,
+ type Handle,
+ type ProxyHandle,
+} from "./rest-proxy.js";
const IMPLEMENTED_TOOLS = new Set([
"memory_save",
@@ -76,106 +81,137 @@ function textResponse(payload: unknown, pretty = false): {
};
}
-async function handleProxy(
- toolName: string,
- args: Record<string, unknown>,
- handle: ProxyHandle,
-): Promise<{ content: Array<{ type: string; text: string }> }> {
+interface Validated {
+ tool: string;
+ content?: string;
+ type?: string;
+ concepts?: string[];
+ files?: string[];
+ query?: string;
+ limit?: number;
+ memoryIds?: string[];
+ reason?: string;
+}
+
+function validate(toolName: string, args: Record<string, unknown>): Validated {
+ if (!IMPLEMENTED_TOOLS.has(toolName)) {
+ throw new Error(`Unknown tool: ${toolName}`);
+ }
+ const v: Validated = { tool: toolName };
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);
+ v.content = content;
+ v.type = (args["type"] as string) || "fact";
+ v.concepts = normalizeList(args["concepts"]);
+ v.files = normalizeList(args["files"]);
+ return v;
}
-
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"]);
+ v.query = query.trim();
+ v.limit = parseLimit(args["limit"]);
+ return v;
+ }
+ case "memory_sessions": {
+ v.limit = parseLimit(args["limit"], 20);
+ return v;
+ }
+ case "memory_governance_delete": {
+ const ids = normalizeList(args["memoryIds"]);
+ if (ids.length === 0) throw new Error("memoryIds is required");
+ v.memoryIds = ids;
+ v.reason = (args["reason"] as string) || "plugin skill request";
+ return v;
+ }
+ case "memory_export":
+ return v;
+ case "memory_audit": {
+ v.limit = parseLimit(args["limit"], 50);
+ return v;
+ }
+ default:
+ throw new Error(`Unknown tool: ${toolName}`);
+ }
+}
+
+async function handleProxy(
+ v: Validated,
+ handle: ProxyHandle,
+): Promise<{ content: Array<{ type: string; text: string }> }> {
+ switch (v.tool) {
+ case "memory_save": {
+ const result = await handle.call("/agentmemory/remember", {
+ method: "POST",
+ body: JSON.stringify({
+ content: v.content,
+ type: v.type,
+ concepts: v.concepts,
+ files: v.files,
+ }),
+ });
+ return textResponse(result);
+ }
+ case "memory_recall":
+ case "memory_smart_search": {
const result = await handle.call("/agentmemory/smart-search", {
method: "POST",
- body: JSON.stringify({ query: query.trim(), limit }),
+ body: JSON.stringify({ query: v.query, limit: v.limit }),
});
return textResponse(result, true);
}
-
case "memory_sessions": {
- const limit = parseLimit(args["limit"], 20);
const result = await handle.call(
- `/agentmemory/sessions?limit=${limit}`,
+ `/agentmemory/sessions?limit=${v.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",
- }),
+ body: JSON.stringify({ memoryIds: v.memoryIds, reason: v.reason }),
});
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}`,
+ `/agentmemory/audit?limit=${v.limit}`,
{ method: "GET" },
);
return textResponse(result, true);
}
-
default:
- throw new Error(`Unknown tool: ${toolName}`);
+ throw new Error(`Unknown tool: ${v.tool}`);
}
}
async function handleLocal(
- toolName: string,
- args: Record<string, unknown>,
+ v: Validated,
kvInstance: InMemoryKV,
): Promise<{ content: Array<{ type: string; text: string }> }> {
- switch (toolName) {
+ switch (v.tool) {
case "memory_save": {
- const rawContent = args["content"];
- if (typeof rawContent !== "string" || !rawContent.trim()) {
- throw new Error("content is required");
- }
- const content = rawContent;
const id = generateId("mem");
const isoNow = new Date().toISOString();
await kvInstance.set("mem:memories", id, {
id,
- type: (args["type"] as string) || "fact",
- title: content.slice(0, 80),
- content,
- concepts: normalizeList(args["concepts"]),
- files: normalizeList(args["files"]),
+ type: v.type,
+ title: (v.content || "").slice(0, 80),
+ content: v.content,
+ concepts: v.concepts,
+ files: v.files,
createdAt: isoNow,
updatedAt: isoNow,
strength: 7,
@@ -189,12 +225,8 @@ async function handleLocal(
case "memory_recall":
case "memory_smart_search": {
- 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 query = (v.query || "").toLowerCase();
+ const limit = v.limit ?? DEFAULT_LIMIT;
const all =
await kvInstance.list<Record<string, unknown>>("mem:memories");
const results = all
@@ -212,21 +244,19 @@ async function handleLocal(
return query.split(/\s+/).every((word) => text.includes(word));
})
.slice(0, limit);
- return textResponse(results, true);
+ return textResponse({ mode: "compact", results }, true);
}
case "memory_sessions": {
const sessions =
await kvInstance.list<Record<string, unknown>>("mem:sessions");
- const limit = parseLimit(args["limit"], 20);
+ const limit = v.limit ?? 20;
return textResponse({ sessions: sessions.slice(0, limit) }, true);
}
case "memory_governance_delete": {
- const ids = normalizeList(args["memoryIds"]);
- if (ids.length === 0) throw new Error("memoryIds is required");
let deleted = 0;
- for (const id of ids) {
+ for (const id of v.memoryIds || []) {
const existing = await kvInstance.get("mem:memories", id);
if (existing) {
await kvInstance.delete("mem:memories", id);
@@ -236,8 +266,8 @@ async function handleLocal(
kvInstance.persist();
return textResponse({
deleted,
- requested: ids.length,
- reason: (args["reason"] as string) || "plugin skill request",
+ requested: (v.memoryIds || []).length,
+ reason: v.reason,
});
}
@@ -249,15 +279,17 @@ async function handleLocal(
case "memory_audit": {
const entries = await kvInstance.list("mem:audit");
- const limit = parseLimit(args["limit"], 50);
+ const limit = v.limit ?? 50;
return textResponse(
- (entries as Array<Record<string, unknown>>).slice(0, limit),
+ {
+ entries: (entries as Array<Record<string, unknown>>).slice(0, limit),
+ },
true,
);
}
default:
- throw new Error(`Unknown tool: ${toolName}`);
+ throw new Error(`Unknown tool: ${v.tool}`);
}
}
@@ -266,18 +298,20 @@ export async function handleToolCall(
args: Record<string, unknown>,
kvInstance: InMemoryKV = kv,
): Promise<{ content: Array<{ type: string; text: string }> }> {
+ const validated = validate(toolName, args);
const handle = await resolveHandle();
announceMode(handle);
if (handle.mode === "proxy") {
try {
- return await handleProxy(toolName, args, handle);
+ return await handleProxy(validated, 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`,
+ `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}; invalidating handle and falling back to local KV\n`,
);
+ invalidateHandle();
}
}
- return handleLocal(toolName, args, kvInstance);
+ return handleLocal(validated, kvInstance);
}
const transport = createStdioTransport(async (method, params) => {
diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts
index 43462cb0..81037652 100644
--- a/test/mcp-standalone-proxy.test.ts
+++ b/test/mcp-standalone-proxy.test.ts
@@ -59,7 +59,11 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {
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 }] }),
+ JSON.stringify({
+ mode: "compact",
+ query: body.query,
+ results: [{ id: "m1", score: 0.9 }],
+ }),
{ status: 200 },
);
}
@@ -68,21 +72,37 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {
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");
+ expect(body.results[0].id).toBe("m1");
});
- it("attaches Bearer token when AGENTMEMORY_SECRET is set", async () => {
+ it("local fallback returns the same shape as proxy for memory_smart_search", async () => {
+ installFetch(() => {
+ throw new Error("ECONNREFUSED");
+ });
+ const localKv = new InMemoryKV(undefined);
+ await handleToolCall("memory_save", { content: "shape-check entry" }, localKv);
+ const res = await handleToolCall("memory_smart_search", { query: "shape" }, localKv);
+ const body = JSON.parse(res.content[0].text);
+ expect(body).toHaveProperty("mode", "compact");
+ expect(Array.isArray(body.results)).toBe(true);
+ expect(body.results[0].content).toBe("shape-check entry");
+ });
+
+ it("attaches Bearer token on the proxied tool request, not just the probe", async () => {
process.env["AGENTMEMORY_SECRET"] = "s3cret";
- const seen: string[] = [];
+ const authByPath = new Map<string, string | undefined>();
installFetch((url, init) => {
- const auth = (init?.headers as Record<string, string> | undefined)?.["authorization"];
- if (auth) seen.push(`${url}|${auth}`);
+ const auth = (init?.headers as Record<string, string> | undefined)?.[
+ "authorization"
+ ];
+ const u = new URL(url);
+ authByPath.set(u.pathname, 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);
+ expect(authByPath.get("/agentmemory/livez")).toBe("Bearer s3cret");
+ expect(authByPath.get("/agentmemory/sessions")).toBe("Bearer s3cret");
});
it("falls back to local InMemoryKV when server is unreachable", async () => {
@@ -93,23 +113,41 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {
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");
+ expect(out.mode).toBe("compact");
+ expect(out.results).toHaveLength(1);
+ expect(out.results[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;
+ it("invalidates the handle on proxy failure, so the next call re-probes", async () => {
+ let probeCount = 0;
+ let serverUp = true;
installFetch((url) => {
- callCount++;
- if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });
+ if (url.endsWith("/agentmemory/livez")) {
+ probeCount++;
+ return serverUp ? new Response("ok", { status: 200 }) : new Response("", { status: 500 });
+ }
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);
+ await handleToolCall("memory_save", { content: "first fallback" }, localKv);
+ expect(probeCount).toBe(1);
+ serverUp = false;
+ await handleToolCall("memory_save", { content: "second fallback" }, localKv);
+ expect(probeCount).toBe(2);
+ });
+
+ it("does not retry local after a validation error", async () => {
+ const fetchFn = installFetch((url) => {
+ if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });
+ return new Response("{}", { status: 200 });
+ });
+ const localKv = new InMemoryKV(undefined);
+ await expect(
+ handleToolCall("memory_save", { content: "" }, localKv),
+ ).rejects.toThrow("content is required");
+ const remembersCalled = fetchFn.mock.calls.some(([url]) =>
+ String(url).endsWith("/agentmemory/remember"),
+ );
+ expect(remembersCalled).toBe(false);
});
});
diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts
index d099431d..def82928 100644
--- a/test/mcp-standalone.test.ts
+++ b/test/mcp-standalone.test.ts
@@ -172,9 +172,9 @@ describe("handleToolCall", () => {
{ query: "typescript" },
kv,
);
- const memories = JSON.parse(result.content[0].text);
- expect(memories).toHaveLength(1);
- expect(memories[0].content).toBe("TypeScript is great");
+ const parsed = JSON.parse(result.content[0].text);
+ expect(parsed.results).toHaveLength(1);
+ expect(parsed.results[0].content).toBe("TypeScript is great");
});
it("memory_save accepts concepts/files as arrays (plugin skill format, #139)", async () => {
@@ -234,9 +234,9 @@ describe("handleToolCall", () => {
{ query: "bcrypt", limit: 5 },
kv,
);
- const memories = JSON.parse(result.content[0].text);
- expect(memories).toHaveLength(1);
- expect(memories[0].content).toBe("Use bcrypt for password hashing");
+ const parsed = JSON.parse(result.content[0].text);
+ expect(parsed.results).toHaveLength(1);
+ expect(parsed.results[0].content).toBe("Use bcrypt for password hashing");
});
it("memory_smart_search rejects empty query to prevent match-all in forget flow (#139)", async () => {
@@ -276,8 +276,8 @@ describe("handleToolCall", () => {
)
).content[0].text,
);
- expect(byFile).toHaveLength(1);
- expect(byFile[0].files).toContain("src/auth/refresh.ts");
+ expect(byFile.results).toHaveLength(1);
+ expect(byFile.results[0].files).toContain("src/auth/refresh.ts");
// Find by concept
const byConcept = JSON.parse(
@@ -289,7 +289,7 @@ describe("handleToolCall", () => {
)
).content[0].text,
);
- expect(byConcept).toHaveLength(1);
+ expect(byConcept.results).toHaveLength(1);
});
it("memory_sessions honours the limit arg (#139)", async () => {
@@ -323,7 +323,7 @@ describe("handleToolCall", () => {
{ query: "mem", limit: bogus },
kv,
);
- expect(JSON.parse(r.content[0].text)).toHaveLength(10);
+ expect(JSON.parse(r.content[0].text).results).toHaveLength(10);
}
// An absurdly large limit gets clamped to MAX_LIMIT (100).
@@ -332,7 +332,7 @@ describe("handleToolCall", () => {
{ query: "mem", limit: 99999 },
kv,
);
- expect(JSON.parse(huge.content[0].text)).toHaveLength(100);
+ expect(JSON.parse(huge.content[0].text).results).toHaveLength(100);
});
it("memory_governance_delete removes memories by id array (#139)", async () => {