From 5984b2508235117ef639f35ade5a264bbacaefe9 Mon Sep 17 00:00:00 2001 From: reddeye1337 Date: Mon, 7 Sep 2026 21:47:20 +0300 Subject: [PATCH 1/3] fix(mcp): bound tool responses so one call cannot exhaust an agent context Two tools returned their whole backing collection, which for an MCP consumer means the response does not merely arrive slowly, it consumes the one budget the caller cannot expand. memory_sessions was kv.list(KV.sessions) verbatim: every session row, pretty-printed. On a 3,646-session store that is 7.7 MB, and the tool declared no arguments at all despite promising recent sessions, so a caller had no way to ask for less. The summary field alone was 76 percent of those bytes. It now accepts limit, project and status and returns a projected summary row, newest first, with total and truncated alongside. memory_graph_query inherited the REST default of 500 nodes, which suits the viewer and is far too large for an agent. It defaults to 25 and leaves provenance projected out unless includeSources is passed. Adds one response ceiling applied to every tool on the way out, so a tool added later cannot reintroduce the same failure, and drops pretty-printing from 57 responses where it was roughly 13 percent pure whitespace. Measured through the MCP shim on that install: memory_sessions 8,062,197 to 5,715 characters, memory_graph_query 14,792,717 to 30,872. Deliberately excludes two adjacent fixes already open as PRs: the /sessions REST limit param is #1034, and the slot-tool guard is #894 and #1149. This is only the MCP payload shaping, so it should not conflict with either. Signed-off-by: reddeye1337 --- src/mcp/server.ts | 214 +++++++++++++++++++++++++++----------- src/mcp/tools-registry.ts | 26 ++++- 2 files changed, 180 insertions(+), 60 deletions(-) diff --git a/src/mcp/server.ts b/src/mcp/server.ts index ef26427aaf..605bc4ae30 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -40,6 +40,56 @@ function parseCsvList(value: unknown): string[] { return []; } +// Last-resort ceiling on any tool response. Individual tools bound +// their own output, but a single unbounded one costs the caller its +// entire context window: memory_sessions returned 7.7 MB (all 3,646 +// rows, pretty-printed) and memory_graph_query 14.8 MB before this. +// One guard here covers every tool, including ones added later. +const MCP_MAX_RESPONSE_BYTES_DEFAULT = 262_144; + +function mcpMaxResponseBytes(): number { + const raw = process.env["AGENTMEMORY_MCP_MAX_RESPONSE_BYTES"]; + const parsed = raw ? parseInt(raw, 10) : NaN; + return Number.isFinite(parsed) && parsed > 0 + ? parsed + : MCP_MAX_RESPONSE_BYTES_DEFAULT; +} + +function capMcpResponse(res: McpResponse, toolName: string): McpResponse { + const content = (res?.body as { content?: unknown })?.content; + if (!Array.isArray(content)) return res; + const max = mcpMaxResponseBytes(); + let used = 0; + let truncated = false; + const next = content.map((part) => { + const c = part as { type?: string; text?: string }; + if (c?.type !== "text" || typeof c.text !== "string") return part; + const room = max - used; + if (room <= 0) { + truncated = true; + return { ...c, text: "" }; + } + if (c.text.length <= room) { + used += c.text.length; + return part; + } + truncated = true; + used = max; + return { ...c, text: c.text.slice(0, room) }; + }); + if (!truncated) return res; + next.push({ + type: "text", + text: + `\n\n[agentmemory] ${toolName} produced more than ${max} bytes and was ` + + `truncated, so the payload above is cut mid-value and will not parse ` + + `as JSON. Re-run with a narrower request (lower limit, add a filter, ` + + `or ask for fewer fields), or raise ` + + `AGENTMEMORY_MCP_MAX_RESPONSE_BYTES.`, + }); + return { ...res, body: { ...(res.body as object), content: next } }; +} + export function registerMcpEndpoints( sdk: ISdk, kv: StateKV, @@ -84,7 +134,7 @@ export function registerMcpEndpoints( const { name, arguments: args = {} } = req.body; - try { + const dispatch = async (): Promise => { switch (name) { case "memory_recall": { if (typeof args.query !== "string" || !args.query.trim()) { @@ -135,7 +185,7 @@ export function registerMcpEndpoints( "text" in (result as Record) && typeof (result as { text?: unknown }).text === "string" ? (result as { text: string }).text - : JSON.stringify(result, null, 2); + : JSON.stringify(result); return { status_code: 200, body: { @@ -160,7 +210,7 @@ export function registerMcpEndpoints( return { status_code: 200, body: { - content: [{ type: "text", text: JSON.stringify(result, null, 2) }], + content: [{ type: "text", text: JSON.stringify(result) }], }, }; } @@ -251,19 +301,56 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; } case "memory_sessions": { - const sessions = await kv.list(KV.sessions); + // Was `kv.list(KV.sessions)` verbatim: all 3,646 rows, + // pretty-printed, 7.7 MB, and the tool declared no arguments + // at all despite promising "recent" sessions. `summary` alone + // was 76% of those bytes. Return a bounded, projected list; + // the full row is one memory_recall away. + const limit = Math.max(1, Math.min(200, asNumber(args.limit, 20) ?? 20)); + const project = asNonEmptyString(args.project); + const status = asNonEmptyString(args.status); + const all = (await kv.list(KV.sessions)) as Array>; + const rows = all + .filter((s) => !project || s["project"] === project) + .filter((s) => !status || s["status"] === status) + .sort((a, b) => + String(b["startedAt"] ?? "").localeCompare(String(a["startedAt"] ?? "")), + ); + const page = rows.slice(0, limit).map((s) => { + const summary = s["summary"]; + return { + id: s["id"], + project: s["project"], + status: s["status"], + startedAt: s["startedAt"], + endedAt: s["endedAt"], + observationCount: s["observationCount"], + title: + summary && typeof summary === "object" + ? (summary as { title?: string }).title + : undefined, + }; + }); return { status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify({ sessions }, null, 2) }, + { + type: "text", + text: JSON.stringify({ + sessions: page, + total: rows.length, + returned: page.length, + truncated: rows.length > page.length, + }), + }, ], }, }; @@ -290,7 +377,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -316,7 +403,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -339,7 +426,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -360,7 +447,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -372,7 +459,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -398,7 +485,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -419,7 +506,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -445,6 +532,8 @@ export function registerMcpEndpoints( nodeType?: string; maxDepth?: number; query?: string; + limit?: number; + includeSources?: boolean; } = {}; const startNodeId = asNonEmptyString(args.startNodeId); const nodeType = asNonEmptyString(args.nodeType); @@ -454,6 +543,11 @@ export function registerMcpEndpoints( if (nodeType) payload.nodeType = nodeType; if (query) payload.query = query; if (maxDepth !== undefined) payload.maxDepth = Math.max(1, Math.min(8, maxDepth)); + // The REST default of 500 nodes is fine for the viewer and + // far too large for an agent; 25 is a readable page. The + // provenance array stays projected out unless asked for. + payload.limit = Math.max(1, Math.min(200, asNumber(args.limit, 25) ?? 25)); + payload.includeSources = args.includeSources === true; const result = await sdk.trigger({ function_id: "mem::graph-query", payload, @@ -462,7 +556,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -490,7 +584,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -528,7 +622,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -556,7 +650,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -585,7 +679,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -620,7 +714,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -644,7 +738,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, + { type: "text", text: JSON.stringify(result) }, ], }, }; @@ -692,7 +786,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(actionResult, null, 2) }, + { type: "text", text: JSON.stringify(actionResult) }, ], }, }; @@ -715,7 +809,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(updateResult, null, 2) }, + { type: "text", text: JSON.stringify(updateResult) }, ], }, }; @@ -731,7 +825,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(frontierResult, null, 2) }, + { type: "text", text: JSON.stringify(frontierResult) }, ], }, }; @@ -746,7 +840,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(nextResult, null, 2) }, + { type: "text", text: JSON.stringify(nextResult) }, ], }, }; @@ -793,7 +887,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(leaseResult, null, 2) }, + { type: "text", text: JSON.stringify(leaseResult) }, ], }, }; @@ -815,7 +909,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(runResult, null, 2) }, + { type: "text", text: JSON.stringify(runResult) }, ], }, }; @@ -842,7 +936,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(sigResult, null, 2) }, + { type: "text", text: JSON.stringify(sigResult) }, ], }, }; @@ -865,7 +959,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(readResult, null, 2) }, + { type: "text", text: JSON.stringify(readResult) }, ], }, }; @@ -916,7 +1010,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(cpResult, null, 2) }, + { type: "text", text: JSON.stringify(cpResult) }, ], }, }; @@ -931,7 +1025,7 @@ export function registerMcpEndpoints( status_code: 200, body: { content: [ - { type: "text", text: JSON.stringify(meshResult, null, 2) }, + { type: "text", text: JSON.stringify(meshResult) }, ], }, }; @@ -963,7 +1057,7 @@ export function registerMcpEndpoints( function_id: "mem::sentinel-create", payload, }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlResult) }] } }; } case "memory_sentinel_trigger": { @@ -986,7 +1080,7 @@ export function registerMcpEndpoints( sentinelId, result: snlTrigPayload, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlTrigResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlTrigResult) }] } }; } case "memory_sketch_create": { @@ -1007,7 +1101,7 @@ export function registerMcpEndpoints( function_id: "mem::sketch-create", payload: sketchPayload, }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skResult) }] } }; } case "memory_sketch_promote": { @@ -1022,7 +1116,7 @@ export function registerMcpEndpoints( sketchId, project: args.project, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skpResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skpResult) }] } }; } case "memory_crystallize": { @@ -1035,7 +1129,7 @@ export function registerMcpEndpoints( project: args.project, sessionId: args.sessionId, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(crysResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(crysResult) }] } }; } case "memory_diagnose": { @@ -1043,7 +1137,7 @@ export function registerMcpEndpoints( ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean) : undefined; const diagResult = await sdk.trigger({ function_id: "mem::diagnose", payload: { categories: diagCats } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(diagResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(diagResult) }] } }; } case "memory_heal": { @@ -1054,7 +1148,7 @@ export function registerMcpEndpoints( categories: healCats, dryRun: args.dryRun === true || args.dryRun === "true", } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(healResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(healResult) }] } }; } case "memory_facet_tag": { @@ -1064,7 +1158,7 @@ export function registerMcpEndpoints( dimension: args.dimension, value: args.value, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fctResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fctResult) }] } }; } case "memory_facet_query": { @@ -1085,7 +1179,7 @@ export function registerMcpEndpoints( matchAny: fqAny, targetType: args.targetType, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fqResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fqResult) }] } }; } case "memory_verify": { @@ -1093,7 +1187,7 @@ export function registerMcpEndpoints( return { status_code: 400, body: { error: "id is required" } }; } const verifyResult = await sdk.trigger({ function_id: "mem::verify", payload: { id: args.id } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(verifyResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(verifyResult) }] } }; } case "memory_lesson_save": { @@ -1111,7 +1205,7 @@ export function registerMcpEndpoints( tags: lessonTags, source: "manual", } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonSaveResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonSaveResult) }] } }; } case "memory_lesson_recall": { @@ -1124,7 +1218,7 @@ export function registerMcpEndpoints( minConfidence: args.minConfidence, limit: args.limit, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult) }] } }; } case "memory_lesson_delete": { @@ -1134,7 +1228,7 @@ export function registerMcpEndpoints( const lessonDeleteResult = await sdk.trigger({ function_id: "mem::lesson-delete", payload: { lessonId: args.lessonId.trim(), } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonDeleteResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonDeleteResult) }] } }; } case "memory_reflect": { @@ -1142,7 +1236,7 @@ export function registerMcpEndpoints( project: args.project, maxClusters: args.maxClusters, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(reflectResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(reflectResult) }] } }; } case "memory_insight_list": { @@ -1151,7 +1245,7 @@ export function registerMcpEndpoints( minConfidence: args.minConfidence, limit: args.limit, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(insightListResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(insightListResult) }] } }; } case "memory_obsidian_export": { @@ -1162,14 +1256,14 @@ export function registerMcpEndpoints( vaultDir: args.vaultDir, types: exportTypes, } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(obsidianResult, null, 2) }] } }; + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(obsidianResult) }] } }; } case "memory_slot_list": { const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify(result) }] }, }; } @@ -1179,7 +1273,7 @@ export function registerMcpEndpoints( const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify(result) }] }, }; } @@ -1198,7 +1292,7 @@ export function registerMcpEndpoints( const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify(result) }] }, }; } @@ -1209,7 +1303,7 @@ export function registerMcpEndpoints( const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify(result) }] }, }; } @@ -1221,7 +1315,7 @@ export function registerMcpEndpoints( const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content: args.content } }); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify(result) }] }, }; } @@ -1231,7 +1325,7 @@ export function registerMcpEndpoints( const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify(result) }] }, }; } @@ -1242,7 +1336,7 @@ export function registerMcpEndpoints( if (!link) { return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify({ commit: null, sessions: [] }, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify({ commit: null, sessions: [] }) }] }, }; } const linkRecord = link as { sessionIds?: string[] }; @@ -1252,7 +1346,7 @@ export function registerMcpEndpoints( const sessions = fetched.filter((s) => s !== null); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify({ commit: link, sessions }, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify({ commit: link, sessions }) }] }, }; } @@ -1268,7 +1362,7 @@ export function registerMcpEndpoints( .slice(0, limit); return { status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify({ commits: filtered }, null, 2) }] }, + body: { content: [{ type: "text", text: JSON.stringify({ commits: filtered }) }] }, }; } @@ -1278,6 +1372,10 @@ export function registerMcpEndpoints( body: { error: `Unknown tool: ${name}` }, }; } + }; + + try { + return capMcpResponse(await dispatch(), name); } catch (err) { return { status_code: 500, @@ -1703,7 +1801,7 @@ export function registerMcpEndpoints( role: "user", content: { type: "text", - text: `Here is relevant context from past sessions for the task: "${taskDesc}"\n\n## Past Observations\n${JSON.stringify(searchResult, null, 2)}\n\n## Relevant Memories\n${JSON.stringify(relevant, null, 2)}`, + text: `Here is relevant context from past sessions for the task: "${taskDesc}"\n\n## Past Observations\n${JSON.stringify(searchResult)}\n\n## Relevant Memories\n${JSON.stringify(relevant)}`, }, }, ], @@ -1732,7 +1830,7 @@ export function registerMcpEndpoints( role: "user", content: { type: "text", - text: `## Session Handoff\n\n### Session\n${JSON.stringify(session, null, 2)}\n\n### Summary\n${JSON.stringify(summary || "No summary available", null, 2)}`, + text: `## Session Handoff\n\n### Session\n${JSON.stringify(session)}\n\n### Summary\n${JSON.stringify(summary || "No summary available")}`, }, }, ], @@ -1761,7 +1859,7 @@ export function registerMcpEndpoints( role: "user", content: { type: "text", - text: `## Pattern Analysis\n\n${JSON.stringify(result, null, 2)}`, + text: `## Pattern Analysis\n\n${JSON.stringify(result)}`, }, }, ], diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts index 1225b4ce7d..efb577b35f 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -121,8 +121,19 @@ export const CORE_TOOLS: McpToolDef[] = [ { name: "memory_sessions", description: - "List recent sessions with their status and observation counts.", - inputSchema: { type: "object", properties: {} }, + "List recent sessions with their status and observation counts. " + + "Returns the newest sessions first, projected to a summary row.", + inputSchema: { + type: "object", + properties: { + limit: { + type: "number", + description: "Max sessions to return (default 20, max 200)", + }, + project: { type: "string", description: "Filter by project" }, + status: { type: "string", description: "Filter by status" }, + }, + }, }, { name: "memory_smart_search", @@ -280,6 +291,17 @@ export const V040_TOOLS: McpToolDef[] = [ description: "Max BFS depth (default 3, max 5)", }, query: { type: "string", description: "Search nodes by name" }, + limit: { + type: "number", + description: "Max nodes to return (default 25, max 200)", + }, + includeSources: { + type: "boolean", + description: + "Return the full sourceObservationIds array per node/edge. " + + "Off by default: it is ~99% of the payload. A count is always " + + "returned as sourceObservationCount.", + }, }, }, }, From 00c50808fd6b07399aa3e1c527606cf8e9757994 Mon Sep 17 00:00:00 2001 From: reddeye1337 Date: Mon, 7 Sep 2026 22:07:01 +0300 Subject: [PATCH 2/3] fix(mcp): cap every response body and validate tool arguments Four issues from review on this PR. capMcpResponse only touched content arrays, so an error body passed through uncapped - including the default branch, which echoed a caller-supplied tool name. Error bodies are now capped and the reflected name is bounded at the source. The truncation notice was appended after the budget was already spent, so a response one character over the limit came back larger than the ceiling it advertises. The notice is reserved up front. memory_sessions and memory_graph_query coerced malformed arguments instead of rejecting them: a non-string project or status silently dropped the filter and widened the query to everything. Both now return 400, per the input-validation guideline for MCP handlers. mcp::prompts::get bypassed the ceiling entirely and can echo a caller-supplied task_description. Its dispatch now routes through the same cap. Adds test/mcp-response-bounds.test.ts covering projection, filtering, argument rejection, the ceiling holding on a truncated response, and the bounded unknown-tool error. Signed-off-by: reddeye1337 --- src/mcp/server.ts | 101 +++++++++++++++++---- test/mcp-response-bounds.test.ts | 145 +++++++++++++++++++++++++++++++ 2 files changed, 228 insertions(+), 18 deletions(-) create mode 100644 test/mcp-response-bounds.test.ts diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 605bc4ae30..cafd26403d 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -55,16 +55,43 @@ function mcpMaxResponseBytes(): number { : MCP_MAX_RESPONSE_BYTES_DEFAULT; } -function capMcpResponse(res: McpResponse, toolName: string): McpResponse { - const content = (res?.body as { content?: unknown })?.content; - if (!Array.isArray(content)) return res; +function truncationNotice(label: string, max: number): string { + return ( + `\n\n[agentmemory] ${label} produced more than ${max} bytes and was ` + + `truncated, so the payload above is cut mid-value and will not parse ` + + `as JSON. Re-run with a narrower request (lower limit, add a filter, ` + + `or ask for fewer fields), or raise ` + + `AGENTMEMORY_MCP_MAX_RESPONSE_BYTES.` + ); +} + +function capMcpResponse(res: McpResponse, label: string): McpResponse { + const body = res?.body as + | { content?: unknown; messages?: unknown; error?: unknown } + | undefined; + if (!body) return res; const max = mcpMaxResponseBytes(); + + // Error bodies are not content arrays, and some of them echo a + // caller-supplied name, so they need the ceiling too. + if (typeof body.error === "string" && body.error.length > max) { + return { ...res, body: { ...body, error: body.error.slice(0, max) } }; + } + + const content = body.content; + if (!Array.isArray(content)) return res; + + // Reserve the notice up front, so a response that overshoots by one + // character does not come back larger than the advertised ceiling. + const notice = truncationNotice(label, max); + const budget = Math.max(0, max - notice.length); + let used = 0; let truncated = false; const next = content.map((part) => { const c = part as { type?: string; text?: string }; if (c?.type !== "text" || typeof c.text !== "string") return part; - const room = max - used; + const room = budget - used; if (room <= 0) { truncated = true; return { ...c, text: "" }; @@ -74,20 +101,12 @@ function capMcpResponse(res: McpResponse, toolName: string): McpResponse { return part; } truncated = true; - used = max; + used = budget; return { ...c, text: c.text.slice(0, room) }; }); if (!truncated) return res; - next.push({ - type: "text", - text: - `\n\n[agentmemory] ${toolName} produced more than ${max} bytes and was ` + - `truncated, so the payload above is cut mid-value and will not parse ` + - `as JSON. Re-run with a narrower request (lower limit, add a filter, ` + - `or ask for fewer fields), or raise ` + - `AGENTMEMORY_MCP_MAX_RESPONSE_BYTES.`, - }); - return { ...res, body: { ...(res.body as object), content: next } }; + next.push({ type: "text", text: notice }); + return { ...res, body: { ...body, content: next } }; } export function registerMcpEndpoints( @@ -313,6 +332,25 @@ export function registerMcpEndpoints( // at all despite promising "recent" sessions. `summary` alone // was 76% of those bytes. Return a bounded, projected list; // the full row is one memory_recall away. + if ( + args.limit !== undefined && + (typeof args.limit !== "number" || + !Number.isInteger(args.limit) || + args.limit < 1) + ) { + return { + status_code: 400, + body: { error: "limit must be a positive integer" }, + }; + } + for (const key of ["project", "status"] as const) { + if (args[key] !== undefined && !asNonEmptyString(args[key])) { + return { + status_code: 400, + body: { error: `${key} must be a non-empty string` }, + }; + } + } const limit = Math.max(1, Math.min(200, asNumber(args.limit, 20) ?? 20)); const project = asNonEmptyString(args.project); const status = asNonEmptyString(args.status); @@ -546,6 +584,26 @@ export function registerMcpEndpoints( // The REST default of 500 nodes is fine for the viewer and // far too large for an agent; 25 is a readable page. The // provenance array stays projected out unless asked for. + if ( + args.limit !== undefined && + (typeof args.limit !== "number" || + !Number.isInteger(args.limit) || + args.limit < 1) + ) { + return { + status_code: 400, + body: { error: "limit must be a positive integer" }, + }; + } + if ( + args.includeSources !== undefined && + typeof args.includeSources !== "boolean" + ) { + return { + status_code: 400, + body: { error: "includeSources must be a boolean" }, + }; + } payload.limit = Math.max(1, Math.min(200, asNumber(args.limit, 25) ?? 25)); payload.includeSources = args.includeSources === true; const result = await sdk.trigger({ @@ -1369,7 +1427,7 @@ export function registerMcpEndpoints( default: return { status_code: 400, - body: { error: `Unknown tool: ${name}` }, + body: { error: `Unknown tool: ${String(name).slice(0, 100)}` }, }; } }; @@ -1743,9 +1801,12 @@ export function registerMcpEndpoints( return { status_code: 400, body: { error: "name is required" } }; } + const capped = (res: McpResponse): McpResponse => + capMcpResponse(res, `prompt ${promptName.slice(0, 100)}`); + const promptArgs = req.body?.arguments || {}; - try { + const build = async (): Promise => { switch (promptName) { case "recall_context": { const taskDesc = promptArgs.task_description; @@ -1870,9 +1931,13 @@ export function registerMcpEndpoints( default: return { status_code: 400, - body: { error: `Unknown prompt: ${promptName}` }, + body: { error: `Unknown prompt: ${promptName.slice(0, 100)}` }, }; } + }; + + try { + return capped(await build()); } catch { return { status_code: 500, body: { error: "Internal error" } }; } diff --git a/test/mcp-response-bounds.test.ts b/test/mcp-response-bounds.test.ts new file mode 100644 index 0000000000..fc50ca7e69 --- /dev/null +++ b/test/mcp-response-bounds.test.ts @@ -0,0 +1,145 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +import { registerMcpEndpoints } from "../src/mcp/server.js"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function mockSdk() { + const functions = new Map(); + const overrides = new Map(); + return { + overrides, + registerFunction: (id: string, handler: Function) => functions.set(id, handler), + registerTrigger: () => {}, + trigger: async (input: { function_id: string; payload: unknown }) => { + if (overrides.has(input.function_id)) { + return overrides.get(input.function_id)!(input.payload); + } + const fn = functions.get(input.function_id); + if (!fn) throw new Error(`No function: ${input.function_id}`); + return fn(input.payload); + }, + call: async (id: string, body: unknown) => { + const fn = functions.get(id); + if (!fn) throw new Error(`No function: ${id}`); + return fn({ body, headers: {}, query_params: {} }); + }, + }; +} + +type Res = { status_code: number; body: Record }; + +describe("MCP response bounds", () => { + let sdk: ReturnType; + let kv: ReturnType; + const ORIG_MAX = process.env["AGENTMEMORY_MCP_MAX_RESPONSE_BYTES"]; + + const call = (name: string, args: Record) => + sdk.call("mcp::tools::call", { name, arguments: args }) as Promise; + + beforeEach(async () => { + sdk = mockSdk(); + kv = mockKV(); + registerMcpEndpoints(sdk as never, kv as never, undefined); + for (let i = 0; i < 40; i++) { + await kv.set("mem:sessions", `s${i}`, { + id: `s${i}`, + project: i % 2 === 0 ? "alpha" : "beta", + status: "completed", + startedAt: `2026-02-${String((i % 27) + 1).padStart(2, "0")}T10:00:00Z`, + observationCount: i, + }); + } + }); + + afterEach(() => { + if (ORIG_MAX === undefined) delete process.env["AGENTMEMORY_MCP_MAX_RESPONSE_BYTES"]; + else process.env["AGENTMEMORY_MCP_MAX_RESPONSE_BYTES"] = ORIG_MAX; + }); + + it("memory_sessions bounds and projects its rows", async () => { + const res = await call("memory_sessions", { limit: 5 }); + expect(res.status_code).toBe(200); + const text = (res.body.content as Array<{ text: string }>)[0].text; + const parsed = JSON.parse(text) as { + sessions: Array>; + total: number; + truncated: boolean; + }; + expect(parsed.sessions.length).toBe(5); + expect(parsed.total).toBe(40); + expect(parsed.truncated).toBe(true); + // newest first + expect(parsed.sessions[0].startedAt as string).toBeDefined(); + }); + + it("memory_sessions filters by project", async () => { + const res = await call("memory_sessions", { project: "alpha", limit: 100 }); + const parsed = JSON.parse( + (res.body.content as Array<{ text: string }>)[0].text, + ) as { sessions: Array<{ project: string }> }; + expect(parsed.sessions.length).toBe(20); + expect(parsed.sessions.every((s) => s.project === "alpha")).toBe(true); + }); + + // A malformed filter used to be dropped, silently widening the query to + // every project instead of failing. + it("rejects malformed arguments instead of dropping the filter", async () => { + expect((await call("memory_sessions", { project: 42 })).status_code).toBe(400); + expect((await call("memory_sessions", { status: "" })).status_code).toBe(400); + expect((await call("memory_sessions", { limit: 0 })).status_code).toBe(400); + expect((await call("memory_sessions", { limit: 2.5 })).status_code).toBe(400); + expect( + (await call("memory_graph_query", { includeSources: "yes" })).status_code, + ).toBe(400); + }); + + it("keeps a truncated response inside the advertised ceiling", async () => { + process.env["AGENTMEMORY_MCP_MAX_RESPONSE_BYTES"] = "2000"; + sdk.overrides.set("mem::search", async () => ({ + format: "full", + results: Array.from({ length: 200 }, (_, i) => ({ + observation: { id: `obs_${i}`, narrative: "x".repeat(500) }, + })), + })); + + const res = await call("memory_recall", { query: "anything" }); + const total = (res.body.content as Array<{ text: string }>) + .map((c) => c.text.length) + .reduce((a, b) => a + b, 0); + + expect(total).toBeLessThanOrEqual(2000); + const joined = (res.body.content as Array<{ text: string }>) + .map((c) => c.text) + .join(""); + expect(joined).toContain("truncated"); + }); + + it("bounds an unknown tool name echoed back in the error", async () => { + const res = await call("z".repeat(100_000), {}); + expect(res.status_code).toBe(400); + expect((res.body.error as string).length).toBeLessThan(200); + }); +}); From a491e7e7ff01f8a141159d80d6b58de0ccdb3b28 Mon Sep 17 00:00:00 2001 From: reddeye1337 Date: Mon, 7 Sep 2026 22:36:44 +0300 Subject: [PATCH 3/3] fix(mcp): measure the response ceiling in UTF-8 bytes AGENTMEMORY_MCP_MAX_RESPONSE_BYTES is named in bytes but the cap counted String.length, which is UTF-16 code units. CJK or emoji content passed the check at roughly three times the advertised limit, and slicing on the same metric could cut a multibyte sequence in half. Measures with Buffer.byteLength and cuts on a code-point boundary, dropping a trailing partial sequence rather than emitting a replacement character the caller never sent. Applies to content parts, the reserved notice and error bodies. Test now measures bytes rather than characters, adds a multibyte fixture that fails on the previous metric, and asserts newest-first ordering as an ordering rather than mere presence. From the second review round on this PR. Signed-off-by: reddeye1337 --- src/mcp/server.ts | 35 ++++++++++++++++++++++++++------ test/mcp-response-bounds.test.ts | 32 ++++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/src/mcp/server.ts b/src/mcp/server.ts index cafd26403d..51e22a87e1 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -55,6 +55,25 @@ function mcpMaxResponseBytes(): number { : MCP_MAX_RESPONSE_BYTES_DEFAULT; } +function utf8Bytes(text: string): number { + return Buffer.byteLength(text, "utf8"); +} + +/** + * Cut a string to a UTF-8 byte budget without splitting a code point. + * String.slice counts UTF-16 units, so it neither measures the budget the + * env var names nor guarantees a valid tail. + */ +function sliceToUtf8Bytes(text: string, maxBytes: number): string { + if (maxBytes <= 0) return ""; + if (utf8Bytes(text) <= maxBytes) return text; + const cut = Buffer.from(text, "utf8").subarray(0, maxBytes); + const decoded = new TextDecoder("utf-8", { fatal: false }).decode(cut); + // A trailing partial sequence decodes to U+FFFD; drop it rather than + // emit a character the caller never sent. + return decoded.endsWith("\uFFFD") ? decoded.slice(0, -1) : decoded; +} + function truncationNotice(label: string, max: number): string { return ( `\n\n[agentmemory] ${label} produced more than ${max} bytes and was ` + @@ -74,8 +93,11 @@ function capMcpResponse(res: McpResponse, label: string): McpResponse { // Error bodies are not content arrays, and some of them echo a // caller-supplied name, so they need the ceiling too. - if (typeof body.error === "string" && body.error.length > max) { - return { ...res, body: { ...body, error: body.error.slice(0, max) } }; + if (typeof body.error === "string" && utf8Bytes(body.error) > max) { + return { + ...res, + body: { ...body, error: sliceToUtf8Bytes(body.error, max) }, + }; } const content = body.content; @@ -84,7 +106,7 @@ function capMcpResponse(res: McpResponse, label: string): McpResponse { // Reserve the notice up front, so a response that overshoots by one // character does not come back larger than the advertised ceiling. const notice = truncationNotice(label, max); - const budget = Math.max(0, max - notice.length); + const budget = Math.max(0, max - utf8Bytes(notice)); let used = 0; let truncated = false; @@ -96,13 +118,14 @@ function capMcpResponse(res: McpResponse, label: string): McpResponse { truncated = true; return { ...c, text: "" }; } - if (c.text.length <= room) { - used += c.text.length; + const size = utf8Bytes(c.text); + if (size <= room) { + used += size; return part; } truncated = true; used = budget; - return { ...c, text: c.text.slice(0, room) }; + return { ...c, text: sliceToUtf8Bytes(c.text, room) }; }); if (!truncated) return res; next.push({ type: "text", text: notice }); diff --git a/test/mcp-response-bounds.test.ts b/test/mcp-response-bounds.test.ts index fc50ca7e69..e88232a6ed 100644 --- a/test/mcp-response-bounds.test.ts +++ b/test/mcp-response-bounds.test.ts @@ -91,8 +91,11 @@ describe("MCP response bounds", () => { expect(parsed.sessions.length).toBe(5); expect(parsed.total).toBe(40); expect(parsed.truncated).toBe(true); - // newest first - expect(parsed.sessions[0].startedAt as string).toBeDefined(); + // Newest first, asserted as an ordering rather than mere presence: + // insertion order would otherwise pass. + const dates = parsed.sessions.map((s) => s.startedAt as string); + expect(dates).toEqual([...dates].sort().reverse()); + expect(dates[0]).toBe("2026-02-27T10:00:00Z"); }); it("memory_sessions filters by project", async () => { @@ -127,7 +130,7 @@ describe("MCP response bounds", () => { const res = await call("memory_recall", { query: "anything" }); const total = (res.body.content as Array<{ text: string }>) - .map((c) => c.text.length) + .map((c) => Buffer.byteLength(c.text, "utf8")) .reduce((a, b) => a + b, 0); expect(total).toBeLessThanOrEqual(2000); @@ -137,6 +140,29 @@ describe("MCP response bounds", () => { expect(joined).toContain("truncated"); }); + // The ceiling is named in bytes. Measuring String.length instead would + // let multibyte content through at roughly three times the limit. + it("counts multibyte text in bytes, not UTF-16 units", async () => { + process.env["AGENTMEMORY_MCP_MAX_RESPONSE_BYTES"] = "2000"; + sdk.overrides.set("mem::search", async () => ({ + format: "full", + results: Array.from({ length: 200 }, (_, i) => ({ + // 3 bytes per character in UTF-8. + observation: { id: `obs_${i}`, narrative: "\u4e2d".repeat(500) }, + })), + })); + + const res = await call("memory_recall", { query: "anything" }); + const parts = res.body.content as Array<{ text: string }>; + const bytes = parts + .map((c) => Buffer.byteLength(c.text, "utf8")) + .reduce((a, b) => a + b, 0); + + expect(bytes).toBeLessThanOrEqual(2000); + // And the cut must not leave a broken code point behind. + expect(parts.map((c) => c.text).join("")).not.toContain("\uFFFD"); + }); + it("bounds an unknown tool name echoed back in the error", async () => { const res = await call("z".repeat(100_000), {}); expect(res.status_code).toBe(400);