Skip to content

Commit c3d8e43

Browse files
fix(memory): validate knowledge graph entries when loading from disk (modelcontextprotocol#4717)
loadGraph() trusted the persisted memory file and pushed entities and relations without validating their fields. A corrupted or legacy entry (e.g. an entity missing entityType, or an observation that is not a string) would reach searchNodes and crash with "Cannot read properties of undefined (reading 'toLowerCase')". Validate each line against the existing EntitySchema/RelationSchema and skip malformed entries with a warning, so the in-memory graph only ever contains well-formed data. Malformed JSON lines are skipped as well. Fixes modelcontextprotocol#2044
1 parent abbbddb commit c3d8e43

2 files changed

Lines changed: 86 additions & 16 deletions

File tree

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,4 +617,51 @@ describe('KnowledgeGraphManager', () => {
617617
expect(result.relations[0]).not.toHaveProperty('type');
618618
});
619619
});
620+
621+
describe('loadGraph validation', () => {
622+
it('skips corrupt entities instead of crashing search', async () => {
623+
const lines = [
624+
JSON.stringify({ type: 'entity', name: 'Alice', entityType: 'person', observations: ['works at Acme Corp'] }),
625+
JSON.stringify({ type: 'entity', name: 'Broken', observations: ['missing entityType'] }),
626+
JSON.stringify({ type: 'entity', name: 'BadObs', entityType: 'person', observations: ['ok', null] }),
627+
];
628+
await fs.writeFile(testFilePath, lines.join('\n') + '\n');
629+
630+
const graph = await manager.readGraph();
631+
expect(graph.entities).toHaveLength(1);
632+
expect(graph.entities[0].name).toBe('Alice');
633+
634+
// searchNodes must not throw even though the file contains corrupt entries
635+
const result = await manager.searchNodes('Acme');
636+
expect(result.entities).toHaveLength(1);
637+
expect(result.entities[0].name).toBe('Alice');
638+
});
639+
640+
it('skips corrupt relations', async () => {
641+
const lines = [
642+
JSON.stringify({ type: 'entity', name: 'Alice', entityType: 'person', observations: [] }),
643+
JSON.stringify({ type: 'relation', from: 'Alice', to: 'Bob' }), // missing relationType
644+
JSON.stringify({ type: 'relation', from: 'Alice', to: 'Bob', relationType: 'knows' }),
645+
];
646+
await fs.writeFile(testFilePath, lines.join('\n') + '\n');
647+
648+
const graph = await manager.readGraph();
649+
expect(graph.entities).toHaveLength(1);
650+
expect(graph.relations).toHaveLength(1);
651+
expect(graph.relations[0].relationType).toBe('knows');
652+
});
653+
654+
it('skips malformed JSON lines', async () => {
655+
const lines = [
656+
JSON.stringify({ type: 'entity', name: 'Alice', entityType: 'person', observations: [] }),
657+
'{this is not valid json',
658+
JSON.stringify({ type: 'entity', name: 'Bob', entityType: 'person', observations: [] }),
659+
];
660+
await fs.writeFile(testFilePath, lines.join('\n') + '\n');
661+
662+
const graph = await manager.readGraph();
663+
expect(graph.entities).toHaveLength(2);
664+
expect(graph.entities.map(e => e.name)).toEqual(['Alice', 'Bob']);
665+
});
666+
});
620667
});

‎src/memory/index.ts‎

Lines changed: 39 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -90,24 +90,47 @@ export class KnowledgeGraphManager {
9090
try {
9191
const data = await fs.readFile(this.memoryFilePath, "utf-8");
9292
const lines = data.split("\n").filter(line => line.trim() !== "");
93-
return lines.reduce((graph: KnowledgeGraph, line) => {
94-
const item = JSON.parse(line);
95-
if (item.type === "entity") {
96-
graph.entities.push({
97-
name: item.name,
98-
entityType: item.entityType,
99-
observations: item.observations
100-
});
93+
const graph: KnowledgeGraph = { entities: [], relations: [] };
94+
95+
for (const line of lines) {
96+
let item: unknown;
97+
try {
98+
item = JSON.parse(line);
99+
} catch {
100+
console.error("Skipping malformed line in memory file");
101+
continue;
101102
}
102-
if (item.type === "relation") {
103-
graph.relations.push({
104-
from: item.from,
105-
to: item.to,
106-
relationType: item.relationType
107-
});
103+
104+
if (typeof item !== "object" || item === null) {
105+
console.error("Skipping non-object line in memory file");
106+
continue;
107+
}
108+
109+
const record = item as Record<string, unknown>;
110+
if (record.type === "entity") {
111+
const parsed = EntitySchema.safeParse(item);
112+
if (parsed.success) {
113+
graph.entities.push(parsed.data);
114+
} else {
115+
console.error(
116+
"Skipping invalid entity in memory file:",
117+
parsed.error.issues.map(issue => `${issue.path.join(".")}: ${issue.message}`).join(", ")
118+
);
119+
}
120+
} else if (record.type === "relation") {
121+
const parsed = RelationSchema.safeParse(item);
122+
if (parsed.success) {
123+
graph.relations.push(parsed.data);
124+
} else {
125+
console.error(
126+
"Skipping invalid relation in memory file:",
127+
parsed.error.issues.map(issue => `${issue.path.join(".")}: ${issue.message}`).join(", ")
128+
);
129+
}
108130
}
109-
return graph;
110-
}, { entities: [], relations: [] });
131+
}
132+
133+
return graph;
111134
} catch (error) {
112135
if (error instanceof Error && 'code' in error && (error as any).code === "ENOENT") {
113136
return { entities: [], relations: [] };

0 commit comments

Comments
 (0)