Files
shared-memory/apps/web/lib/mcp/tools.integration.test.ts
T
shadowdaoandClaude Opus 5.5 a1cdfae0bd feat: return excerpts from memory.list / memory.search, full text via memory.get
Both tools returned every memory's full body, so one search across a few
dozen long memories could pour thousands of words into the caller's
context. The memory.get description already promised that list/search
"return summaries"; this makes it true.

Each list/search item now carries, instead of `content`:
- `excerpt`: ~200 chars, whitespace collapsed, cut on word boundaries.
  For search it is the window matching the most distinct query terms
  (stopwords ignored); for list, or a meaning-only hit with no term in
  the text, it is the memory's opening.
- `contentLength` and `truncated`, so the caller can tell a short note
  (excerpt is the whole thing) from a long document worth a memory.get.

`full: true` on either tool restores the whole `content`. Ids, tags,
scope, project, version, timestamps and search ranks are unchanged.
memory.get is unchanged. The web UI calls searchMemories directly and is
unaffected. Named `excerpt`, not `snippet`, to avoid confusion with the
snippet.* tools.

Tool descriptions now point callers at memory.get for full bodies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:03:33 -08:00

402 lines
14 KiB
TypeScript

import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
/**
* Integration tests for memory.get and memory.patch against a REAL
* Postgres (pgvector). See CONTRIBUTING/README for spinning up the test
* database; without it these tests fail to connect rather than silently
* passing.
*
* The embedder sidecar is the one thing stubbed — it's an external HTTP
* service running an ML model. The stub is deterministic per-text, which
* lets the re-embedding test assert on the STORED VECTOR CHANGING (real
* DB state) rather than on "was the mock called".
*/
vi.mock("@/lib/embedder", () => ({
embedText: async (text: string) => {
// Deterministic pseudo-vector: distinct texts produce distinct vectors.
let h = 0;
for (let i = 0; i < text.length; i++) h = (h * 31 + text.charCodeAt(i)) | 0;
return Array.from({ length: 384 }, (_, i) => ((h + i * 7919) % 1000) / 1000);
},
embedTexts: async (texts: string[]) => texts.map(() => Array(384).fill(0.1)),
embedderReady: async () => true,
EmbedderError: class extends Error {},
}));
const { db, pg } = await import("@/lib/db/client");
const { memories, projects, users } = await import("@/lib/db/schema");
const { toolMap } = await import("@/lib/mcp/tools");
const { eq } = await import("drizzle-orm");
type UserContext = import("@/lib/mcp/context").UserContext;
const ORIGINAL = [
"# Roadmap",
"",
"## RECENTLY SHIPPED",
"- v1.0 initial release",
"",
"## IN PROGRESS",
"- patch primitive",
"",
].join("\n");
let userId: string;
let projectId: string;
let memoryId: string;
let ctx: UserContext;
async function seedMemory(content = ORIGINAL): Promise<string> {
const row = await db
.insert(memories)
.values({
userId,
projectId,
scope: "project",
content,
tags: ["roadmap"],
embedding: Array(384).fill(0.5),
})
.returning({ id: memories.id });
return row[0]!.id;
}
async function readContent(id: string): Promise<string> {
const r = await db
.select({ content: memories.content })
.from(memories)
.where(eq(memories.id, id));
return r[0]!.content;
}
beforeAll(async () => {
const u = await db
.insert(users)
.values({ oidcSub: "test-sub", oidcIss: "http://test", email: "t@example.com" })
.onConflictDoNothing()
.returning({ id: users.id });
userId =
u[0]?.id ??
(await db.select({ id: users.id }).from(users).limit(1))[0]!.id;
const p = await db
.insert(projects)
.values({ userId, key: "test-project", displayName: "Test Project" })
.onConflictDoNothing()
.returning({ id: projects.id });
projectId =
p[0]?.id ??
(await db.select({ id: projects.id }).from(projects).limit(1))[0]!.id;
ctx = {
userId,
sub: "test-sub",
iss: "http://test",
email: null,
name: null,
groups: [],
};
});
beforeEach(async () => {
memoryId = await seedMemory();
});
afterAll(async () => {
await db.delete(memories);
await pg.end();
});
describe("memory.get response shape (P1)", () => {
test("does not leak the embedding or the tsvector to the caller", async () => {
const res = await toolMap["memory.get"]!.handler({ id: memoryId }, ctx);
const fields = Object.keys(res.structuredContent as object);
expect(fields).not.toContain("embedding");
expect(fields).not.toContain("contentTsv");
});
test("returns exactly the 9 memory fields, including the full content", async () => {
const res = await toolMap["memory.get"]!.handler({ id: memoryId }, ctx);
const fields = Object.keys(res.structuredContent as object).sort();
expect(fields).toEqual(
[
"content",
"createdAt",
"id",
"lastEditedBy",
"projectId",
"scope",
"tags",
"updatedAt",
"version",
].sort(),
);
});
test("still returns the full content", async () => {
const res = await toolMap["memory.get"]!.handler({ id: memoryId }, ctx);
expect((res.structuredContent as { content: string }).content).toBe(ORIGINAL);
});
});
describe("memory.patch (P2)", () => {
test("applies a unique patch and increments version by exactly 1", async () => {
const before = await db
.select({ version: memories.version })
.from(memories)
.where(eq(memories.id, memoryId));
const res = await toolMap["memory.patch"]!.handler(
{
id: memoryId,
old_string: "## RECENTLY SHIPPED",
new_string: "## RECENTLY SHIPPED\n- v1.1 patch primitive",
},
ctx,
);
expect(res.isError).toBeFalsy();
const after = res.structuredContent as { version: number };
expect(after.version).toBe(before[0]!.version + 1);
expect(await readContent(memoryId)).toContain("- v1.1 patch primitive");
// The rest of the document survived.
expect(await readContent(memoryId)).toContain("- v1.0 initial release");
expect(await readContent(memoryId)).toContain("## IN PROGRESS");
});
test("refuses an absent old_string and leaves content byte-identical", async () => {
const res = await toolMap["memory.patch"]!.handler(
{ id: memoryId, old_string: "## NOT PRESENT", new_string: "x" },
ctx,
);
expect(res.isError).toBe(true);
expect(await readContent(memoryId)).toBe(ORIGINAL);
});
test("refuses an ambiguous old_string, naming the count, leaving content unchanged", async () => {
const id = await seedMemory("alpha\nalpha\nbeta\n");
const res = await toolMap["memory.patch"]!.handler(
{ id, old_string: "alpha", new_string: "gamma" },
ctx,
);
expect(res.isError).toBe(true);
expect(res.content[0]!.text).toMatch(/2/);
expect(await readContent(id)).toBe("alpha\nalpha\nbeta\n");
});
test("refuses a stale version and leaves content unchanged", async () => {
const current = await db
.select({ version: memories.version })
.from(memories)
.where(eq(memories.id, memoryId));
const res = await toolMap["memory.patch"]!.handler(
{
id: memoryId,
old_string: "## IN PROGRESS",
new_string: "## DONE",
version: current[0]!.version + 99,
},
ctx,
);
expect(res.isError).toBe(true);
expect(await readContent(memoryId)).toBe(ORIGINAL);
});
test("rejects a patch that would push content past the 64,000-char limit", async () => {
const id = await seedMemory("A".repeat(63_950) + "ANCHOR");
const res = await toolMap["memory.patch"]!.handler(
{ id, old_string: "ANCHOR", new_string: "B".repeat(100) },
ctx,
);
expect(res.isError).toBe(true);
expect(await readContent(id)).toBe("A".repeat(63_950) + "ANCHOR");
});
test("re-embeds: the stored vector changes after a patch", async () => {
const before = await pg<{ embedding: string }[]>`
SELECT embedding::text AS embedding FROM memories WHERE id = ${memoryId}
`;
await toolMap["memory.patch"]!.handler(
{ id: memoryId, old_string: "- patch primitive", new_string: "- shipped it" },
ctx,
);
const after = await pg<{ embedding: string }[]>`
SELECT embedding::text AS embedding FROM memories WHERE id = ${memoryId}
`;
expect(after[0]!.embedding).not.toBe(before[0]!.embedding);
});
test("full-text index updates itself, because content_tsv is a generated column", async () => {
// This is the claim that a patch cannot rot FTS. Postgres maintains
// content_tsv; only the embedding needs an explicit recompute.
await toolMap["memory.patch"]!.handler(
{
id: memoryId,
old_string: "- patch primitive",
new_string: "- kumquat marmalade",
},
ctx,
);
const hit = await pg<{ n: number }[]>`
SELECT count(*)::int AS n FROM memories
WHERE id = ${memoryId} AND content_tsv @@ plainto_tsquery('english', 'kumquat')
`;
expect(hit[0]!.n).toBe(1);
});
});
/**
* Regression: claude.ai (and any client that ignores `structuredContent`
* when no `outputSchema` is declared) only renders the `content` text
* blocks. When `ok()` put just the summary there, memory.search returned
* "8 result(s)" with no ids, so the caller could not read or memory.get
* anything it found. Every read tool must carry its payload in the FIRST
* text block — some clients render only that one.
*/
describe("tool results carry their payload in the text content (claude.ai)", () => {
const firstText = (res: ToolResultLike) => res.content[0]!.text;
type ToolResultLike = { content: Array<{ text: string }>; isError?: boolean };
test("memory.list text includes each memory's id and an excerpt", async () => {
const res = await toolMap["memory.list"]!.handler({ project: "test-project" }, ctx);
expect(res.isError).toBeUndefined();
expect(firstText(res)).toContain(memoryId);
expect(firstText(res)).toContain("## RECENTLY SHIPPED");
});
test("memory.search text includes the hit's id, an excerpt and rank", async () => {
const res = await toolMap["memory.search"]!.handler(
{ query: "roadmap patch primitive", project: "test-project" },
ctx,
);
expect(res.isError).toBeUndefined();
expect(firstText(res)).toContain(memoryId);
expect(firstText(res)).toContain("## RECENTLY SHIPPED");
expect(firstText(res)).toContain("rrfScore");
});
test("memory.get text includes the full content", async () => {
const res = await toolMap["memory.get"]!.handler({ id: memoryId }, ctx);
expect(firstText(res)).toContain("- patch primitive");
});
test("snippet.list and snippet.get text include the snippet", async () => {
const name = `text-payload-${Date.now()}`;
const put = await toolMap["snippet.put"]!.handler(
{ name, body: "SNIPPET-BODY-MARKER", description: "when to use it" },
ctx,
);
expect(put.isError).toBeUndefined();
const list = await toolMap["snippet.list"]!.handler({}, ctx);
expect(firstText(list)).toContain(name);
expect(firstText(list)).toContain("when to use it");
const get = await toolMap["snippet.get"]!.handler({ name }, ctx);
expect(firstText(get)).toContain("SNIPPET-BODY-MARKER");
await toolMap["snippet.delete"]!.handler({ name }, ctx);
});
test("the text block is the summary line followed by the structured JSON", async () => {
const res = await toolMap["memory.get"]!.handler({ id: memoryId }, ctx);
const [summary, ...rest] = firstText(res).split("\n");
expect(summary).toBe(`memory ${memoryId}`);
expect(JSON.parse(rest.join("\n"))).toEqual(
JSON.parse(JSON.stringify(res.structuredContent)),
);
});
});
/**
* memory.list / memory.search return an excerpt instead of the full body,
* so a search across dozens of long memories doesn't flood the caller's
* context. memory.get (or `full: true`) returns the whole text.
*/
describe("memory.list / memory.search return excerpts, not full bodies", () => {
const LONG =
"Opening summary line. " +
"filler ".repeat(400) +
"The kumquat marmalade decision was made here. " +
"filler ".repeat(400);
type Item = {
id: string;
excerpt: string;
contentLength: number;
truncated: boolean;
content?: string;
tags: string[];
};
const itemsOf = (res: { structuredContent?: unknown }) =>
(res.structuredContent as { items: Item[] }).items;
test("memory.list returns excerpt + contentLength + truncated, and no content", async () => {
const longId = await seedMemory(LONG);
const res = await toolMap["memory.list"]!.handler({ project: "test-project" }, ctx);
const item = itemsOf(res).find((i) => i.id === longId)!;
expect(item.content).toBeUndefined();
expect(item.contentLength).toBe(LONG.length);
expect(item.truncated).toBe(true);
expect(item.excerpt.startsWith("Opening summary line.")).toBe(true);
expect(item.excerpt.length).toBeLessThanOrEqual(202);
expect(item.tags).toEqual(["roadmap"]);
// The text block the client renders doesn't carry the body either.
expect(res.content[0]!.text).not.toContain("filler ".repeat(50));
});
test("a short memory's excerpt is the whole thing and not truncated", async () => {
const res = await toolMap["memory.list"]!.handler({ project: "test-project" }, ctx);
const item = itemsOf(res).find((i) => i.id === memoryId)!;
expect(item.truncated).toBe(false);
expect(item.excerpt).toBe(ORIGINAL.replace(/\s+/g, " ").trim());
});
test("memory.search excerpts the passage that matched the query", async () => {
const longId = await seedMemory(LONG);
const res = await toolMap["memory.search"]!.handler(
{ query: "kumquat marmalade", project: "test-project" },
ctx,
);
const item = itemsOf(res).find((i) => i.id === longId)!;
expect(item.content).toBeUndefined();
expect(item.truncated).toBe(true);
expect(item.contentLength).toBe(LONG.length);
expect(item.excerpt).toContain("kumquat marmalade decision");
expect((item as unknown as { _rank: { rrfScore: number } })._rank.rrfScore).toBeGreaterThan(0);
});
test("full: true returns the whole content on both tools", async () => {
const longId = await seedMemory(LONG);
const list = await toolMap["memory.list"]!.handler({ project: "test-project", full: true }, ctx);
expect(itemsOf(list).find((i) => i.id === longId)!.content).toBe(LONG);
const search = await toolMap["memory.search"]!.handler(
{ query: "kumquat marmalade", project: "test-project", full: true },
ctx,
);
expect(itemsOf(search).find((i) => i.id === longId)!.content).toBe(LONG);
});
test("memory.get still returns the full content", async () => {
const longId = await seedMemory(LONG);
const res = await toolMap["memory.get"]!.handler({ id: longId }, ctx);
expect((res.structuredContent as { content: string }).content).toBe(LONG);
});
});