Skip to content

Commit 072505d

Browse files
committed
Merge origin/v2/main into v2/fix/4797-memory-cross-process-lock
Signed-off-by: cliffhall <cliff@futurescale.com> # Conflicts: # src/memory/__tests__/persistence.test.ts # src/memory/index.ts
2 parents ca465a1 + 1520a8b commit 072505d

8 files changed

Lines changed: 270 additions & 42 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-memory": patch
3+
---
4+
5+
`create_entities` now reports the entities it skipped because their name already exists (or repeats earlier in the same call): the structured result lists them in a new optional `skipped` array, a second text item names them and points to `add_observations`, and the tool description says so. Skipped entities are still not created and their observations are still not added (#4887).
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-memory": patch
3+
---
4+
5+
Lines in the memory file that the server cannot read (malformed JSON, an entity or relation that fails validation, an unknown record type) are no longer deleted by the next write. They are still left out of the graph, and are now written back unchanged after the graph's own lines.

‎src/memory/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ Example:
6262
- `name` (string): Entity identifier
6363
- `entityType` (string): Type classification
6464
- `observations` (string[]): Associated observations
65-
- Ignores entities with existing names
65+
- Ignores entities with existing names (and repeats of a name earlier in the same call); their observations are not added
66+
- Returns the created entities. When any were skipped, the structured result also lists their names in `skipped`, and a second text item says which were skipped (use `add_observations` to extend an existing entity)
6667

6768
- **create_relations**
6869
- Create multiple new relations between entities
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// Unit tests for the helpers behind create_entities' skip report (#4887).
2+
// create_entities ignores entities whose name already exists, as the README
3+
// documents. The agent only sees the tool description and the result, though,
4+
// so the result must say which entities were skipped: otherwise their
5+
// observations look stored when nothing was written.
6+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
7+
import { promises as fs } from "fs";
8+
import path from "path";
9+
import { fileURLToPath } from "url";
10+
import {
11+
KnowledgeGraphManager,
12+
Entity,
13+
skippedEntityNames,
14+
skippedEntitiesNotice,
15+
} from "../index.js";
16+
17+
describe("create reporting", () => {
18+
let manager: KnowledgeGraphManager;
19+
let testFilePath: string;
20+
21+
beforeEach(async () => {
22+
testFilePath = path.join(
23+
path.dirname(fileURLToPath(import.meta.url)),
24+
`test-create-reporting-${Date.now()}-${Math.random().toString(16).slice(2)}.jsonl`,
25+
);
26+
manager = new KnowledgeGraphManager(testFilePath);
27+
await manager.createEntities([
28+
{
29+
name: "Alice",
30+
entityType: "person",
31+
observations: ["works at Acme Corp"],
32+
},
33+
]);
34+
});
35+
36+
afterEach(async () => {
37+
try {
38+
await fs.unlink(testFilePath);
39+
} catch {
40+
// the file is gone already
41+
}
42+
});
43+
44+
it("names an entity skipped because it already exists", async () => {
45+
const requested: Entity[] = [
46+
{
47+
name: "Alice",
48+
entityType: "person",
49+
observations: ["allergic to penicillin"],
50+
},
51+
{ name: "Bob", entityType: "person", observations: [] },
52+
];
53+
const created = await manager.createEntities(requested);
54+
expect(created.map((e) => e.name)).toEqual(["Bob"]);
55+
expect(skippedEntityNames(requested, created)).toEqual(["Alice"]);
56+
});
57+
58+
it("names a repeat within the same batch", async () => {
59+
const requested: Entity[] = [
60+
{ name: "Carol", entityType: "person", observations: ["first"] },
61+
{ name: "Carol", entityType: "person", observations: ["second"] },
62+
];
63+
const created = await manager.createEntities(requested);
64+
expect(skippedEntityNames(requested, created)).toEqual(["Carol"]);
65+
});
66+
67+
it("reports nothing skipped when every entity is new", async () => {
68+
const requested: Entity[] = [
69+
{ name: "Dan", entityType: "person", observations: [] },
70+
];
71+
const created = await manager.createEntities(requested);
72+
expect(skippedEntityNames(requested, created)).toEqual([]);
73+
});
74+
75+
it("words the notice for one and for several skipped entities", () => {
76+
expect(skippedEntitiesNotice(["Alice"])).toBe(
77+
"Skipped 1 entity that already exists: Alice. Its observations were not added; " +
78+
"use add_observations for existing entities.",
79+
);
80+
expect(skippedEntitiesNotice(["Alice", "Bob"])).toBe(
81+
"Skipped 2 entities that already exist: Alice, Bob. Their observations were not added; " +
82+
"use add_observations for existing entities.",
83+
);
84+
});
85+
});

‎src/memory/__tests__/knowledge-graph.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,45 @@ describe("KnowledgeGraphManager", () => {
789789
expect(graph.entities).toHaveLength(2);
790790
expect(graph.entities.map((e) => e.name)).toEqual(["Alice", "Bob"]);
791791
});
792+
793+
it("keeps lines it cannot read when an unrelated write saves the graph", async () => {
794+
const unreadable = [
795+
JSON.stringify({
796+
type: "entity",
797+
name: "Broken",
798+
observations: ["missing entityType"],
799+
}),
800+
JSON.stringify({
801+
type: "entity",
802+
name: "BadObs",
803+
entityType: "person",
804+
observations: ["allergic to penicillin", null],
805+
}),
806+
"{this is not valid json",
807+
JSON.stringify({ type: "note", text: "written by another tool" }),
808+
];
809+
const lines = [
810+
JSON.stringify({
811+
type: "entity",
812+
name: "Alice",
813+
entityType: "person",
814+
observations: [],
815+
}),
816+
...unreadable,
817+
];
818+
await fs.writeFile(testFilePath, lines.join("\n") + "\n");
819+
820+
await manager.createEntities([
821+
{ name: "Carol", entityType: "person", observations: [] },
822+
]);
823+
824+
const saved = (await fs.readFile(testFilePath, "utf-8")).split("\n");
825+
for (const line of unreadable) {
826+
expect(saved).toContain(line);
827+
}
828+
const graph = await manager.readGraph();
829+
expect(graph.entities.map((e) => e.name)).toEqual(["Alice", "Carol"]);
830+
});
792831
});
793832

794833
describe("concurrent mutations", () => {

‎src/memory/__tests__/persistence.test.ts‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// Characterization tests for how the memory server persists its graph, driven
22
// through an SDK Client over an in-memory transport (#4854): the JSONL file
3-
// format, how unreadable lines are loaded and then rewritten, read and write
3+
// format, how unreadable lines are loaded and then kept on write, read and write
44
// failures as tool errors, the atomic temp-file save, and two servers sharing
5-
// one file. Tests that pin a known bug cite its issue (#4885, #4827),
5+
// one file. Tests that pin a known bug cite its issue (#4827),
66
// so the PR that fixes it has a test to change.
77
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
88
import { promises as fs } from "fs";
@@ -167,12 +167,11 @@ describe("memory persistence over the protocol", () => {
167167
]);
168168
});
169169

170-
// KNOWN BUG #4885: pins current (wrong) behavior; the fix changes this assertion.
171-
// Characterizes #4885: the next write rewrites the file from the filtered
172-
// graph, so every unreadable line is deleted for good, and Bob loses two
173-
// valid observations because of one null. The relation to Bob now dangles.
174-
// The call reports success. The fix for #4885 changes this test.
175-
it("deletes the unreadable lines on the next unrelated write (#4885)", async () => {
170+
// #4885: the next write keeps the unreadable lines out of the graph but
171+
// writes them back verbatim, after the graph's own lines, so Bob keeps his
172+
// valid observations and the relation to him still has its entity on
173+
// disk. Blank lines carry no data and are not kept.
174+
it("keeps the unreadable lines on the next unrelated write (#4885)", async () => {
176175
await seed();
177176
vi.spyOn(console, "error").mockImplementation(() => {});
178177
const { client } = await open();
@@ -188,9 +187,22 @@ describe("memory persistence over the protocol", () => {
188187
'{"type":"entity","name":"Alice","entityType":"person","observations":["Works at Acme","Prefers email"]}',
189188
'{"type":"entity","name":"Carol","entityType":"person","observations":["New hire"]}',
190189
'{"type":"relation","from":"Alice","to":"Bob","relationType":"manages"}',
190+
'{"type":"entity","name":"Bob","entityType":"person","observations":["Allergic to penicillin","Lives in Haifa",null]}',
191+
'{"type":"entity","name":"Project X","observations":["Deadline 2026-10-01","Budget 40k"]}',
192+
'{"type":"relation","from":"Alice","to":"Bob"}',
193+
'{"type":"entity","name":"Trunc',
194+
'{"type":"entity","name":"A","entityType":"x","observations":[]}{"type":"entity","name":"B","entityType":"x","observations":[]}',
195+
"42",
196+
"null",
197+
'{"type":"note","text":"unknown type"}',
191198
"",
192199
].join("\n"),
193200
);
201+
// The kept lines stay out of the graph.
202+
expect((await call(client, "read_graph")).structuredContent).toEqual({
203+
entities: [alice, carol],
204+
relations: [aliceManagesBob],
205+
});
194206
});
195207
});
196208

‎src/memory/__tests__/tools.test.ts‎

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ const expectedTools = [
9292
{
9393
name: "create_entities",
9494
title: "Create Entities",
95-
description: "Create multiple new entities in the knowledge graph",
95+
description:
96+
"Create multiple new entities in the knowledge graph. An entity whose name already exists, or repeats an earlier entity in the same call, is skipped and its observations are not added; the result lists the skipped names in `skipped`. Use add_observations to add observations to an existing entity.",
9697
inputSchema: {
9798
type: "object",
9899
properties: { entities: { type: "array", items: entityItem(false) } },
@@ -101,7 +102,10 @@ const expectedTools = [
101102
},
102103
outputSchema: {
103104
type: "object",
104-
properties: { entities: { type: "array", items: entityItem(true) } },
105+
properties: {
106+
entities: { type: "array", items: entityItem(true) },
107+
skipped: { type: "array", items: { type: "string" } },
108+
},
105109
required: ["entities"],
106110
$schema: DRAFT_07,
107111
additionalProperties: false,
@@ -419,22 +423,30 @@ describe("memory tools over the protocol", () => {
419423
expect(textOf(result)).toBe("[]");
420424
});
421425

422-
// KNOWN BUG #4887: pins current (wrong) behavior; the fix changes this assertion.
423-
it("keeps only the first of two same-named entities in one batch", async () => {
426+
it("keeps the first of two same-named entities in one batch and reports the second as skipped (#4887)", async () => {
424427
const second = { ...alice, entityType: "robot", observations: ["beeps"] };
425428
const result = await call(client, "create_entities", {
426429
entities: [alice, second],
427430
});
428-
expect(result.structuredContent).toEqual({ entities: [alice] });
431+
expect(result.isError).toBeUndefined();
432+
expect(result.structuredContent).toEqual({
433+
entities: [alice],
434+
skipped: ["Alice"],
435+
});
436+
expect(result.content).toEqual([
437+
{ type: "text", text: JSON.stringify([alice], null, 2) },
438+
{
439+
type: "text",
440+
text: "Skipped 1 entity that already exists: Alice. Its observations were not added; use add_observations for existing entities.",
441+
},
442+
]);
429443
expect(await readGraph()).toEqual({ entities: [alice], relations: [] });
430444
});
431445

432-
// KNOWN BUG #4887: pins current (wrong) behavior; the fix changes this assertion.
433-
// Characterizes #4887: create_entities silently drops the observations of
434-
// an entity whose name already exists. The call succeeds, reports nothing
435-
// created, and the new observation is lost. The fix for #4887 changes this
436-
// test.
437-
it("drops observations for an entity that already exists (#4887)", async () => {
446+
// #4887: create_entities still ignores an entity whose name already
447+
// exists, as documented, but now reports it as skipped so the caller
448+
// knows its observations were not stored.
449+
it("reports an entity that already exists as skipped (#4887)", async () => {
438450
await call(client, "create_entities", {
439451
entities: [
440452
{
@@ -452,12 +464,22 @@ describe("memory tools over the protocol", () => {
452464
entityType: "person",
453465
observations: ["Allergic to penicillin"],
454466
},
467+
bob,
455468
],
456469
});
457470

458471
expect(result.isError).toBeUndefined();
459-
expect(result.structuredContent).toEqual({ entities: [] });
460-
expect(textOf(result)).toBe("[]");
472+
expect(result.structuredContent).toEqual({
473+
entities: [bob],
474+
skipped: ["Alice"],
475+
});
476+
expect(result.content).toEqual([
477+
{ type: "text", text: JSON.stringify([bob], null, 2) },
478+
{
479+
type: "text",
480+
text: "Skipped 1 entity that already exists: Alice. Its observations were not added; use add_observations for existing entities.",
481+
},
482+
]);
461483
const opened = await call(client, "open_nodes", { names: ["Alice"] });
462484
expect(opened.structuredContent).toEqual({
463485
entities: [

0 commit comments

Comments
 (0)