diff --git a/src/mcp/server.ts b/src/mcp/server.ts index ef26427aaf..51e22a87e1 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -40,6 +40,98 @@ 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 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 ` + + `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" && utf8Bytes(body.error) > max) { + return { + ...res, + body: { ...body, error: sliceToUtf8Bytes(body.error, 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 - utf8Bytes(notice)); + + 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 = budget - used; + if (room <= 0) { + truncated = true; + return { ...c, text: "" }; + } + const size = utf8Bytes(c.text); + if (size <= room) { + used += size; + return part; + } + truncated = true; + used = budget; + return { ...c, text: sliceToUtf8Bytes(c.text, room) }; + }); + if (!truncated) return res; + next.push({ type: "text", text: notice }); + return { ...res, body: { ...body, content: next } }; +} + export function registerMcpEndpoints( sdk: ISdk, kv: StateKV, @@ -84,7 +176,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 +227,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 +252,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 +343,75 @@ 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. + 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); + 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 +438,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 +464,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 +487,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 +508,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 +520,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 +546,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 +567,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 +593,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 +604,31 @@ 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. + 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({ function_id: "mem::graph-query", payload, @@ -462,7 +637,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 +665,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 +703,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 +731,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 +760,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 +795,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 +819,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 +867,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 +890,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 +906,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 +921,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 +968,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 +990,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 +1017,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 +1040,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 +1091,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 +1106,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 +1138,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 +1161,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 +1182,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 +1197,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 +1210,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 +1218,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 +1229,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 +1239,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 +1260,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 +1268,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 +1286,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 +1299,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 +1309,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 +1317,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 +1326,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 +1337,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 +1354,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 +1373,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 +1384,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 +1396,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 +1406,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 +1417,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 +1427,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,16 +1443,20 @@ 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 }) }] }, }; } default: return { status_code: 400, - body: { error: `Unknown tool: ${name}` }, + body: { error: `Unknown tool: ${String(name).slice(0, 100)}` }, }; } + }; + + try { + return capMcpResponse(await dispatch(), name); } catch (err) { return { status_code: 500, @@ -1645,9 +1824,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; @@ -1703,7 +1885,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 +1914,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 +1943,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)}`, }, }, ], @@ -1772,9 +1954,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/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.", + }, }, }, }, diff --git a/test/mcp-response-bounds.test.ts b/test/mcp-response-bounds.test.ts new file mode 100644 index 0000000000..e88232a6ed --- /dev/null +++ b/test/mcp-response-bounds.test.ts @@ -0,0 +1,171 @@ +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, 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 () => { + 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) => Buffer.byteLength(c.text, "utf8")) + .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"); + }); + + // 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); + expect((res.body.error as string).length).toBeLessThan(200); + }); +});