Skip to content

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

fix(api): return 413 instead of 200 when export refuses an oversized payload (#1422)

Rohit Ghumare00411d63f5d9
diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts
index 1adbb46e..05fa4956 100644
--- a/src/mcp/rest-proxy.ts
+++ b/src/mcp/rest-proxy.ts
@@ -21,6 +21,18 @@ export interface ProxyHandle {
call: (path: string, init?: RequestInit) => Promise<unknown>;
}
+export class ProxyCallError extends Error {
+ status: number;
+ body: unknown;
+
+ constructor(message: string, status: number, body: unknown) {
+ super(message);
+ this.name = "ProxyCallError";
+ this.status = status;
+ this.body = body;
+ }
+}
+
export interface LocalHandle {
mode: "local";
}
@@ -147,8 +159,19 @@ export async function resolveHandle(): Promise<Handle> {
signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
});
if (!res.ok) {
- throw new Error(
+ const errText = await res.text().catch(() => "");
+ let errBody: unknown = undefined;
+ if (errText) {
+ try {
+ errBody = JSON.parse(errText);
+ } catch {
+ errBody = undefined;
+ }
+ }
+ throw new ProxyCallError(
`${init?.method || "GET"} ${path} -> ${res.status} ${res.statusText}`,
+ res.status,
+ errBody,
);
}
const text = await res.text();
diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts
index f425b159..5a4a891b 100644
--- a/src/mcp/standalone.ts
+++ b/src/mcp/standalone.ts
@@ -9,6 +9,7 @@ import { generateId } from "../state/schema.js";
import {
resolveHandle,
invalidateHandle,
+ ProxyCallError,
type Handle,
type ProxyHandle,
} from "./rest-proxy.js";
@@ -241,8 +242,20 @@ async function handleProxy(
return textResponse(result);
}
case "memory_export": {
- const result = await handle.call("/agentmemory/export", { method: "GET" });
- return textResponse(result, true);
+ try {
+ const result = await handle.call("/agentmemory/export", { method: "GET" });
+ return textResponse(result, true);
+ } catch (err) {
+ if (
+ err instanceof ProxyCallError &&
+ err.body != null &&
+ typeof err.body === "object" &&
+ (err.body as { oversized?: boolean }).oversized === true
+ ) {
+ return textResponse(err.body, true);
+ }
+ throw err;
+ }
}
case "memory_audit": {
const result = await handle.call(
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 337e34b5..4a1d3519 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1441,6 +1441,10 @@ export function registerApiTriggers(
function_id: "mem::export",
payload,
});
+ const resp = result as { success?: boolean; oversized?: boolean };
+ if (resp?.success === false && resp?.oversized === true) {
+ return { status_code: 413, body: result };
+ }
return { status_code: 200, body: result };
},
);
diff --git a/test/export-refusal-status.test.ts b/test/export-refusal-status.test.ts
new file mode 100644
index 00000000..f1b65d11
--- /dev/null
+++ b/test/export-refusal-status.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect, vi } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import { registerApiTriggers } from "../src/triggers/api.js";
+import { registerExportImportFunction } from "../src/functions/export-import.js";
+import { KV } from "../src/state/schema.js";
+import { SAFE_PAYLOAD_BYTES } from "../src/state/frame-guard.js";
+import type { Memory } from "../src/types.js";
+
+const SECRET = "export-test-secret";
+
+function mockKV(store = new Map<string, Map<string, unknown>>()) {
+ return {
+ get: async <T>(scope: string, key: string): Promise<T | null> =>
+ (store.get(scope)?.get(key) as T) ?? null,
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ delete: async (scope: string, key: string): Promise<void> => {
+ store.get(scope)?.delete(key);
+ },
+ update: async () => {},
+ list: async <T>(scope: string): Promise<T[]> =>
+ Array.from(store.get(scope)?.values() ?? []) as T[],
+ _store: store,
+ };
+}
+
+function mockSdk() {
+ const fns = new Map<string, Function>();
+ return {
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ fns.set(id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (input: { function_id: string; payload?: unknown }) =>
+ fns.get(input.function_id)?.(input.payload),
+ _fns: fns,
+ };
+}
+
+function hugeMemory(): Memory {
+ return {
+ id: "m-huge",
+ type: "pattern",
+ title: "big",
+ content: "z".repeat(SAFE_PAYLOAD_BYTES + 4096),
+ createdAt: "2026-08-01T00:00:00Z",
+ updatedAt: "2026-08-01T00:00:00Z",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ };
+}
+
+async function apiExport(
+ sdk: ReturnType<typeof mockSdk>,
+): Promise<{ status_code: number; body: Record<string, unknown> }> {
+ const handler = sdk._fns.get("api::export")!;
+ return handler({
+ headers: { authorization: `Bearer ${SECRET}` },
+ query_params: {},
+ });
+}
+
+describe("api::export refusal status", () => {
+ it("returns 200 with the export payload for a normal-sized export", async () => {
+ const kv = mockKV();
+ const sdk = mockSdk();
+ registerExportImportFunction(sdk as never, kv as never);
+ registerApiTriggers(sdk as never, kv as never, SECRET);
+
+ const res = await apiExport(sdk);
+
+ expect(res.status_code).toBe(200);
+ expect(res.body.version).toBeDefined();
+ expect(res.body.oversized).toBeUndefined();
+ });
+
+ it("returns 413 with the refusal body instead of 200 when mem::export refuses an oversized export", async () => {
+ const kv = mockKV();
+ await kv.set(KV.memories, "m-huge", hugeMemory());
+ const sdk = mockSdk();
+ registerExportImportFunction(sdk as never, kv as never);
+ registerApiTriggers(sdk as never, kv as never, SECRET);
+
+ const res = await apiExport(sdk);
+
+ expect(res.status_code).toBe(413);
+ expect(res.body.oversized).toBe(true);
+ expect(res.body.success).toBe(false);
+ expect(res.body.version).toBeUndefined();
+ });
+});
diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts
index dc08a024..8b0aee6c 100644
--- a/test/mcp-standalone-proxy.test.ts
+++ b/test/mcp-standalone-proxy.test.ts
@@ -228,6 +228,47 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {
expect(probeCount).toBe(2);
});
+ it("surfaces the export refusal body on a 413 instead of falling back to local KV", async () => {
+ let probeCount = 0;
+ const refusal = {
+ success: false,
+ error: "Response is 20.0 MiB, over the ~15 MiB engine transport frame limit; narrow the range",
+ oversized: true,
+ bytes: 20 * 1024 * 1024,
+ limitBytes: 15 * 1024 * 1024,
+ };
+ installFetch((url) => {
+ if (url.endsWith("/agentmemory/livez")) {
+ probeCount++;
+ return new Response("ok", { status: 200 });
+ }
+ if (url.endsWith("/agentmemory/export")) {
+ return new Response(JSON.stringify(refusal), {
+ status: 413,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ if (url.includes("/agentmemory/sessions")) {
+ return new Response(JSON.stringify({ sessions: [] }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ return new Response("not found", { status: 404 });
+ });
+
+ const res = await handleToolCall("memory_export", {});
+ const body = JSON.parse(res.content[0].text);
+ expect(body.oversized).toBe(true);
+ expect(body.success).toBe(false);
+ expect(body.bytes).toBe(refusal.bytes);
+
+ expect(probeCount).toBe(1);
+ const sessionsRes = await handleToolCall("memory_sessions", { limit: 5 });
+ expect(JSON.parse(sessionsRes.content[0].text).sessions).toEqual([]);
+ expect(probeCount).toBe(1);
+ });
+
it("forwards non-essential tools to /agentmemory/mcp/call (#234)", async () => {
const calls: Array<{ url: string; body?: unknown }> = [];
installFetch((url, init) => {