diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md index b2a78fe5f6..360cbaa901 100644 --- a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md +++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md @@ -43,7 +43,7 @@ agentmemory exposes 54 MCP tools. 8 are in the lean core set (`--tools core` or | `memory_save` | yes | `content`*: string, `type`: string, `concepts`: string, `files`: string, `project`: string, `agentId`: string | Explicitly save an important insight, decision, or pattern to long-term memory. | | `memory_sentinel_create` | | `name`*: string, `type`*: string, `config`: string, `linkedActionIds`: string, `expiresInMs`: number | Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered. | | `memory_sentinel_trigger` | | `sentinelId`*: string, `result`: string | Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions. | -| `memory_sessions` | yes | none | List recent sessions with their status and observation counts. | +| `memory_sessions` | yes | `limit`: number | List recent sessions with their status and observation counts. | | `memory_signal_read` | | `agentId`*: string, `unreadOnly`: string, `threadId`: string, `limit`: number | Read messages for an agent. Marks delivered messages as read. | | `memory_signal_send` | | `from`*: string, `to`: string, `content`*: string, `type`: string, `replyTo`: string | Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration. | | `memory_sketch_create` | | `title`*: string, `description`: string, `expiresInMs`: number, `project`: string | Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded. | diff --git a/src/mcp/server.ts b/src/mcp/server.ts index ef26427aaf..b938df0e52 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -8,7 +8,8 @@ import type { GraphNode, GraphEdge, } from "../types.js"; -import { getVisibleTools } from "./tools-registry.js"; +import { getVisibleTools, SLOT_TOOL_NAMES } from "./tools-registry.js"; +import { isSlotsEnabled } from "../functions/slots.js"; import { timingSafeCompare } from "../auth.js"; import { getAgentId, isAgentScopeIsolated } from "../config.js"; @@ -84,6 +85,26 @@ export function registerMcpEndpoints( const { name, arguments: args = {} } = req.body; + if (SLOT_TOOL_NAMES.has(name) && !isSlotsEnabled()) { + return { + status_code: 200, + body: { + content: [ + { + type: "text", + text: JSON.stringify({ + error: "Memory slots not enabled", + flag: "AGENTMEMORY_SLOTS", + enableHow: + "Set AGENTMEMORY_SLOTS=true (in ~/.agentmemory/.env or the shell) and restart.", + }), + }, + ], + isError: true, + }, + }; + } + try { switch (name) { case "memory_recall": { @@ -173,14 +194,8 @@ export function registerMcpEndpoints( }; } const type = (args.type as string) || "fact"; - const concepts = - typeof args.concepts === "string" - ? args.concepts.split(",").map((c: string) => c.trim()).filter(Boolean) - : []; - const files = - typeof args.files === "string" - ? args.files.split(",").map((f: string) => f.trim()).filter(Boolean) - : []; + const concepts = parseCsvList(args.concepts); + const files = parseCsvList(args.files); const project = typeof args.project === "string" && args.project.trim().length > 0 @@ -258,7 +273,12 @@ export function registerMcpEndpoints( } case "memory_sessions": { - const sessions = await kv.list(KV.sessions); + const requestedLimit = asNumber(args.limit, 20) ?? 20; + const limit = Math.max(1, Math.min(Math.floor(requestedLimit), 100)); + const all = await kv.list(KV.sessions); + const sessions = all + .sort((a, b) => b.startedAt.localeCompare(a.startedAt)) + .slice(0, limit); return { status_code: 200, body: { @@ -1282,7 +1302,7 @@ export function registerMcpEndpoints( return { status_code: 500, body: { - error: "Internal error", + error: `Internal error: ${err instanceof Error ? err.message : String(err)}`, }, }; } diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts index f425b159c4..8f6731a684 100644 --- a/src/mcp/standalone.ts +++ b/src/mcp/standalone.ts @@ -271,6 +271,8 @@ async function handleLocal( content: v.content, concepts: v.concepts, files: v.files, + ...(v.project !== undefined && { project: v.project }), + ...(v.agentId !== undefined && { agentId: v.agentId }), createdAt: isoNow, updatedAt: isoNow, strength: 7, diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts index 1225b4ce7d..2219489759 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -1,3 +1,5 @@ +import { isSlotsEnabled } from "../functions/slots.js"; + export type McpToolDef = { name: string; description: string; @@ -122,7 +124,15 @@ export const CORE_TOOLS: McpToolDef[] = [ name: "memory_sessions", description: "List recent sessions with their status and observation counts.", - inputSchema: { type: "object", properties: {} }, + inputSchema: { + type: "object", + properties: { + limit: { + type: "number", + description: "Max sessions to return (integer 1-100, default 20)", + }, + }, + }, }, { name: "memory_smart_search", @@ -943,6 +953,8 @@ export const V010_SLOTS_TOOLS: McpToolDef[] = [ }, ]; +export const SLOT_TOOL_NAMES = new Set(V010_SLOTS_TOOLS.map((t) => t.name)); + export const ESSENTIAL_TOOLS = new Set([ "memory_save", "memory_recall", @@ -974,6 +986,9 @@ export function getAllTools(): McpToolDef[] { // Users who want the lean essentials can still set AGENTMEMORY_TOOLS=core. export function getVisibleTools(): McpToolDef[] { const mode = process.env["AGENTMEMORY_TOOLS"] || "all"; - if (mode === "core") return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name)); - return getAllTools(); + const tools = isSlotsEnabled() + ? getAllTools() + : getAllTools().filter((t) => !SLOT_TOOL_NAMES.has(t.name)); + if (mode === "core") return tools.filter((t) => ESSENTIAL_TOOLS.has(t.name)); + return tools; } diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts index dc08a024ee..05eb2356b1 100644 --- a/test/mcp-standalone-proxy.test.ts +++ b/test/mcp-standalone-proxy.test.ts @@ -53,6 +53,27 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => { expect(calls.find((c) => c.url.includes("/sessions"))).toBeDefined(); }); + it("forwards trimmed project and agentId on memory_save", async () => { + let rememberBody: Record | undefined; + installFetch((url, init) => { + if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 }); + if (url.endsWith("/agentmemory/remember")) { + rememberBody = JSON.parse((init?.body as string) || "{}"); + return new Response(JSON.stringify({ saved: "mem_1" }), { status: 200 }); + } + return new Response("", { status: 404 }); + }); + + await handleToolCall("memory_save", { + content: "scoped memory", + project: " my-project ", + agentId: " codex-1 ", + }); + + expect(rememberBody?.project).toBe("my-project"); + expect(rememberBody?.agentId).toBe("codex-1"); + }); + it("proxies memory_smart_search to POST /agentmemory/smart-search", async () => { installFetch((url, init) => { if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 }); diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts index 3dcc80ae1b..4f73b09c34 100644 --- a/test/mcp-standalone.test.ts +++ b/test/mcp-standalone.test.ts @@ -263,6 +263,26 @@ describe("handleToolCall", () => { expect(mem?.files).toEqual(["src/auth.ts"]); }); + it("memory_save preserves trimmed project and agentId in local fallback", async () => { + const kv = new InMemoryKV(); + const result = await handleToolCall( + "memory_save", + { + content: "Scoped fallback memory", + project: " project-1 ", + agentId: " codex-1 ", + }, + kv, + ); + const saved = JSON.parse(result.content[0].text); + const memory = await kv.get<{ project?: string; agentId?: string }>( + "mem:memories", + saved.saved, + ); + + expect(memory).toMatchObject({ project: "project-1", agentId: "codex-1" }); + }); + it("memory_smart_search falls back to substring match in the standalone shim (#139)", async () => { const kv = new InMemoryKV(); await handleToolCall( diff --git a/test/mcp-surface-default.test.ts b/test/mcp-surface-default.test.ts index 161d2f426c..14ab737e20 100644 --- a/test/mcp-surface-default.test.ts +++ b/test/mcp-surface-default.test.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import { getAllTools, getVisibleTools, + SLOT_TOOL_NAMES, } from "../src/mcp/tools-registry.js"; // plugin manifests and README advertise 54 MCP tools. The old @@ -12,12 +13,16 @@ import { // AGENTMEMORY_TOOLS=core. describe("MCP tool surface default (#553)", () => { const ORIG = process.env["AGENTMEMORY_TOOLS"]; + const ORIG_SLOTS = process.env["AGENTMEMORY_SLOTS"]; beforeEach(() => { delete process.env["AGENTMEMORY_TOOLS"]; + process.env["AGENTMEMORY_SLOTS"] = "true"; }); afterEach(() => { if (ORIG === undefined) delete process.env["AGENTMEMORY_TOOLS"]; else process.env["AGENTMEMORY_TOOLS"] = ORIG; + if (ORIG_SLOTS === undefined) delete process.env["AGENTMEMORY_SLOTS"]; + else process.env["AGENTMEMORY_SLOTS"] = ORIG_SLOTS; }); it("default returns the full 54-tool surface, matching plugin advertising", () => { @@ -32,6 +37,16 @@ describe("MCP tool surface default (#553)", () => { expect(getVisibleTools().length).toBe(getAllTools().length); }); + it("slot tools are hidden when AGENTMEMORY_SLOTS is disabled", () => { + process.env["AGENTMEMORY_SLOTS"] = "false"; + const names = new Set(getVisibleTools().map((t) => t.name)); + expect(SLOT_TOOL_NAMES.size).toBe(6); + for (const slotTool of SLOT_TOOL_NAMES) { + expect(names.has(slotTool)).toBe(false); + } + expect(getVisibleTools().length).toBe(getAllTools().length - SLOT_TOOL_NAMES.size); + }); + it("AGENTMEMORY_TOOLS=core returns the 8 essential tools", () => { process.env["AGENTMEMORY_TOOLS"] = "core"; const names = new Set(getVisibleTools().map((t) => t.name)); diff --git a/test/mcp-tools-call.test.ts b/test/mcp-tools-call.test.ts new file mode 100644 index 0000000000..e7355bc82a --- /dev/null +++ b/test/mcp-tools-call.test.ts @@ -0,0 +1,218 @@ +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"; +import type { Session } from "../src/types.js"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => { + return (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 triggerOverrides = new Map(); + return { + registerFunction: (idOrOpts: string | { id: string }, handler: Function) => { + const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id; + functions.set(id, handler); + }, + registerTrigger: () => {}, + trigger: async ( + idOrInput: string | { function_id: string; payload: unknown }, + data?: unknown, + ) => { + const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id; + const payload = typeof idOrInput === "string" ? data : idOrInput.payload; + if (triggerOverrides.has(id)) { + return triggerOverrides.get(id)!(payload); + } + const fn = functions.get(id); + if (!fn) throw new Error(`No function: ${id}`); + return fn(payload); + }, + overrideTrigger: (id: string, handler: Function) => { + triggerOverrides.set(id, handler); + }, + getFunction: (id: string) => functions.get(id), + }; +} + +function makeCall(name: string, args: Record = {}) { + return { body: { name, arguments: args }, headers: {}, query_params: {} }; +} + +function makeSession(id: string, startedAt: string): Session { + return { + id, + project: "demo", + cwd: "/tmp/demo", + startedAt, + status: "completed", + observationCount: 0, + }; +} + +type CallResult = { + status_code: number; + body: { content?: Array<{ type: string; text: string }>; isError?: boolean; error?: string }; +}; + +describe("mcp::tools::call dispatch", () => { + let sdk: ReturnType; + let kv: ReturnType; + const ORIG_SLOTS = process.env["AGENTMEMORY_SLOTS"]; + + beforeEach(() => { + sdk = mockSdk(); + kv = mockKV(); + registerMcpEndpoints(sdk as never, kv as never); + }); + + afterEach(() => { + if (ORIG_SLOTS === undefined) delete process.env["AGENTMEMORY_SLOTS"]; + else process.env["AGENTMEMORY_SLOTS"] = ORIG_SLOTS; + }); + + it("slot tools return a structured enableHow error when slots are disabled", async () => { + process.env["AGENTMEMORY_SLOTS"] = "false"; + const slotTrigger = vi.fn(); + sdk.overrideTrigger("mem::slot-list", slotTrigger); + + const fn = sdk.getFunction("mcp::tools::call")!; + const result = (await fn(makeCall("memory_slot_list"))) as CallResult; + + expect(result.status_code).toBe(200); + expect(result.body.isError).toBe(true); + const payload = JSON.parse(result.body.content![0]!.text); + expect(payload.error).toBe("Memory slots not enabled"); + expect(payload.flag).toBe("AGENTMEMORY_SLOTS"); + expect(payload.enableHow).toContain("AGENTMEMORY_SLOTS=true"); + expect(slotTrigger).not.toHaveBeenCalled(); + }); + + it("slot tools dispatch to the slot functions when slots are enabled", async () => { + process.env["AGENTMEMORY_SLOTS"] = "true"; + sdk.overrideTrigger("mem::slot-list", async () => ({ slots: [] })); + + const fn = sdk.getFunction("mcp::tools::call")!; + const result = (await fn(makeCall("memory_slot_list"))) as CallResult; + + expect(result.status_code).toBe(200); + expect(result.body.isError).toBeUndefined(); + expect(result.body.content![0]!.text).toContain("slots"); + }); + + it("dispatch errors include the underlying message", async () => { + process.env["AGENTMEMORY_SLOTS"] = "true"; + sdk.overrideTrigger("mem::slot-list", async () => { + throw new Error("kv exploded"); + }); + + const fn = sdk.getFunction("mcp::tools::call")!; + const result = (await fn(makeCall("memory_slot_list"))) as CallResult; + + expect(result.status_code).toBe(500); + expect(result.body.error).toContain("Internal error"); + expect(result.body.error).toContain("kv exploded"); + }); + + it("memory_save forwards array-typed concepts and files", async () => { + let captured: Record | undefined; + sdk.overrideTrigger("mem::remember", async (payload: Record) => { + captured = payload; + return { saved: "mem_1" }; + }); + + const fn = sdk.getFunction("mcp::tools::call")!; + const result = (await fn( + makeCall("memory_save", { + content: "remember this", + concepts: ["auth", "jwt"], + files: ["src/auth.ts"], + }), + )) as CallResult; + + expect(result.status_code).toBe(200); + expect(captured?.concepts).toEqual(["auth", "jwt"]); + expect(captured?.files).toEqual(["src/auth.ts"]); + }); + + it("memory_save still accepts comma-separated string concepts", async () => { + let captured: Record | undefined; + sdk.overrideTrigger("mem::remember", async (payload: Record) => { + captured = payload; + return { saved: "mem_2" }; + }); + + const fn = sdk.getFunction("mcp::tools::call")!; + await fn(makeCall("memory_save", { content: "x", concepts: "a, b" })); + + expect(captured?.concepts).toEqual(["a", "b"]); + }); + + it("memory_sessions sorts by startedAt descending and honors limit", async () => { + await kv.set("mem:sessions", "s1", makeSession("s1", "2026-06-01T00:00:00Z")); + await kv.set("mem:sessions", "s2", makeSession("s2", "2026-06-03T00:00:00Z")); + await kv.set("mem:sessions", "s3", makeSession("s3", "2026-06-02T00:00:00Z")); + + const fn = sdk.getFunction("mcp::tools::call")!; + const result = (await fn(makeCall("memory_sessions", { limit: 2 }))) as CallResult; + + expect(result.status_code).toBe(200); + const payload = JSON.parse(result.body.content![0]!.text) as { sessions: Session[] }; + expect(payload.sessions.map((s) => s.id)).toEqual(["s2", "s3"]); + }); + + it("memory_sessions clamps limit to an integer from 1 through 100", async () => { + for (let i = 0; i < 105; i++) { + const startedAt = new Date(Date.UTC(2026, 0, 1, 0, 0, i)).toISOString(); + await kv.set("mem:sessions", `s${i}`, makeSession(`s${i}`, startedAt)); + } + + const fn = sdk.getFunction("mcp::tools::call")!; + for (const [limit, expected] of [ + [-3, 1], + [0, 1], + [2.9, 2], + [999, 100], + ] as const) { + const result = (await fn(makeCall("memory_sessions", { limit }))) as CallResult; + const payload = JSON.parse(result.body.content![0]!.text) as { sessions: Session[] }; + expect(payload.sessions, `limit=${limit}`).toHaveLength(expected); + } + }); + + it("memory_sessions defaults to 20 most recent sessions", async () => { + for (let i = 0; i < 25; i++) { + const day = String(i + 1).padStart(2, "0"); + await kv.set("mem:sessions", `s${i}`, makeSession(`s${i}`, `2026-05-${day}T00:00:00Z`)); + } + + const fn = sdk.getFunction("mcp::tools::call")!; + const result = (await fn(makeCall("memory_sessions"))) as CallResult; + + const payload = JSON.parse(result.body.content![0]!.text) as { sessions: Session[] }; + expect(payload.sessions).toHaveLength(20); + expect(payload.sessions[0]!.id).toBe("s24"); + }); +});