Skip to content

Commit 7b1170d

Browse files
RaidLZolaservo
andauthored
feat(memory): expose knowledge graph as MCP Resource (#3323)
* feat(memory): expose knowledge graph as MCP Resource Register the knowledge graph as a readable MCP Resource at memory://knowledge-graph, enabling clients to discover and read the graph via the Resources protocol without invoking a tool. Mutation tools (create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations) now emit notifications/resources/updated so subscribed clients see live graph changes. Resource registration is extracted into the exported registerKnowledgeGraphResource() function so it can be unit-tested in isolation, mirroring the everything server's registration pattern. New tests assert registerResource is called with the correct kebab-case name, URI, mime type, and that the handler returns the graph as JSON in the contents array. Addresses PR #3323 review feedback: - kebab-case resource name per CLAUDE.md style guide - single-line comment per CLAUDE.md style guide - title metadata for client discoverability - resource update notifications after mutations - test coverage matching everything/registrations.test.ts pattern - README documents the new Resource * feat(memory): support resources/subscribe for the knowledge-graph resource PR #3323 emitted notifications/resources/updated after every mutation but the server only advertised resources.listChanged, so resources/subscribe returned -32601 and a spec-compliant client could never actually subscribe. Declare resources.subscribe, add subscribe/unsubscribe request handlers that track subscribed URIs, and only emit notifications/resources/updated when the client has subscribed to that URI. Co-authored-by: Lazreg Raed <lazregraed222@gmail.com> --------- Co-authored-by: olaservo <olahungerford@gmail.com>
1 parent a96189b commit 7b1170d

3 files changed

Lines changed: 169 additions & 3 deletions

File tree

‎src/memory/README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,14 @@ Example:
125125
- Relations between requested entities
126126
- Silently skips non-existent nodes
127127

128+
### Resources
129+
130+
- **knowledge-graph** (`memory://knowledge-graph`)
131+
- The full knowledge graph as a readable MCP Resource
132+
- MIME type: `application/json`
133+
- Returns the same shape as `read_graph` (entities and relations)
134+
- Mutation tools (`create_entities`, `create_relations`, `add_observations`, `delete_entities`, `delete_observations`, `delete_relations`) emit `notifications/resources/updated` for this URI, so subscribed clients see live changes
135+
128136
# Usage with Claude Desktop
129137

130138
### Setup
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { describe, it, expect, vi } from 'vitest';
2+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3+
import { SubscribeRequestSchema, UnsubscribeRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4+
import {
5+
KnowledgeGraphManager,
6+
registerKnowledgeGraphResource,
7+
registerKnowledgeGraphSubscriptions,
8+
} from '../index.js';
9+
10+
describe('knowledge-graph resource', () => {
11+
it('registers with kebab-case name, correct URI, and JSON mime type', () => {
12+
const mockServer = { registerResource: vi.fn() } as unknown as McpServer;
13+
const manager = {} as KnowledgeGraphManager;
14+
15+
registerKnowledgeGraphResource(mockServer, manager);
16+
17+
expect(mockServer.registerResource).toHaveBeenCalledWith(
18+
'knowledge-graph',
19+
'memory://knowledge-graph',
20+
expect.objectContaining({
21+
title: 'Knowledge Graph',
22+
mimeType: 'application/json',
23+
}),
24+
expect.any(Function),
25+
);
26+
});
27+
28+
it('handler returns the graph as JSON in the contents array', async () => {
29+
const mockServer = { registerResource: vi.fn() } as unknown as McpServer;
30+
const fakeGraph = {
31+
entities: [{ name: 'Alice', entityType: 'person', observations: ['engineer'] }],
32+
relations: [{ from: 'Alice', to: 'Acme', relationType: 'works_at' }],
33+
};
34+
const manager = {
35+
readGraph: vi.fn().mockResolvedValue(fakeGraph),
36+
} as unknown as KnowledgeGraphManager;
37+
38+
registerKnowledgeGraphResource(mockServer, manager);
39+
40+
const handler = (mockServer.registerResource as ReturnType<typeof vi.fn>).mock.calls[0][3];
41+
const result = await handler(new URL('memory://knowledge-graph'));
42+
43+
expect(result.contents).toHaveLength(1);
44+
expect(result.contents[0].uri).toBe('memory://knowledge-graph');
45+
expect(result.contents[0].mimeType).toBe('application/json');
46+
expect(JSON.parse(result.contents[0].text)).toEqual(fakeGraph);
47+
expect(manager.readGraph).toHaveBeenCalledOnce();
48+
});
49+
});
50+
51+
describe('knowledge-graph resource subscriptions', () => {
52+
function makeMockServer() {
53+
const inner = {
54+
registerCapabilities: vi.fn(),
55+
setRequestHandler: vi.fn(),
56+
sendResourceUpdated: vi.fn(),
57+
};
58+
const mockServer = { server: inner } as unknown as McpServer;
59+
return { mockServer, inner };
60+
}
61+
62+
function handlerFor(inner: ReturnType<typeof makeMockServer>['inner'], schema: unknown) {
63+
const call = inner.setRequestHandler.mock.calls.find((c) => c[0] === schema);
64+
if (!call) throw new Error('handler not registered');
65+
return call[1] as (request: { params: { uri: string } }) => Promise<unknown>;
66+
}
67+
68+
it('declares the resources.subscribe capability', () => {
69+
const { mockServer, inner } = makeMockServer();
70+
71+
registerKnowledgeGraphSubscriptions(mockServer);
72+
73+
expect(inner.registerCapabilities).toHaveBeenCalledWith({
74+
resources: { subscribe: true },
75+
});
76+
});
77+
78+
it('registers subscribe and unsubscribe request handlers', () => {
79+
const { mockServer, inner } = makeMockServer();
80+
81+
registerKnowledgeGraphSubscriptions(mockServer);
82+
83+
const schemas = inner.setRequestHandler.mock.calls.map((c) => c[0]);
84+
expect(schemas).toContain(SubscribeRequestSchema);
85+
expect(schemas).toContain(UnsubscribeRequestSchema);
86+
});
87+
88+
it('subscribe and unsubscribe handlers acknowledge with an empty result', async () => {
89+
const { mockServer, inner } = makeMockServer();
90+
91+
registerKnowledgeGraphSubscriptions(mockServer);
92+
93+
const req = { params: { uri: 'memory://knowledge-graph' } };
94+
await expect(handlerFor(inner, SubscribeRequestSchema)(req)).resolves.toEqual({});
95+
await expect(handlerFor(inner, UnsubscribeRequestSchema)(req)).resolves.toEqual({});
96+
});
97+
});

‎src/memory/index.ts‎

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
44
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5+
import { SubscribeRequestSchema, UnsubscribeRequestSchema } from "@modelcontextprotocol/sdk/types.js";
56
import { z } from "zod";
67
import { promises as fs } from 'fs';
78
import path from 'path';
@@ -258,6 +259,20 @@ const server = new McpServer({
258259
version: "0.6.3",
259260
});
260261

262+
const RESOURCE_URI = "memory://knowledge-graph";
263+
264+
// Track which resource URIs the connected client has subscribed to, so we only
265+
// emit notifications/resources/updated to a client that asked for them.
266+
const resourceSubscribers = new Set<string>();
267+
268+
// Notify subscribers that the knowledge graph resource changed. No-op when the
269+
// client has not subscribed.
270+
function notifyGraphUpdated() {
271+
if (resourceSubscribers.has(RESOURCE_URI)) {
272+
server.server.sendResourceUpdated({ uri: RESOURCE_URI });
273+
}
274+
}
275+
261276
// Register create_entities tool
262277
server.registerTool(
263278
"create_entities",
@@ -279,6 +294,7 @@ server.registerTool(
279294
},
280295
async ({ entities }) => {
281296
const result = await knowledgeGraphManager.createEntities(entities);
297+
notifyGraphUpdated();
282298
return {
283299
content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
284300
structuredContent: { entities: result }
@@ -307,6 +323,7 @@ server.registerTool(
307323
},
308324
async ({ relations }) => {
309325
const result = await knowledgeGraphManager.createRelations(relations);
326+
notifyGraphUpdated();
310327
return {
311328
content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
312329
structuredContent: { relations: result }
@@ -341,6 +358,7 @@ server.registerTool(
341358
},
342359
async ({ observations }) => {
343360
const result = await knowledgeGraphManager.addObservations(observations);
361+
notifyGraphUpdated();
344362
return {
345363
content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
346364
structuredContent: { results: result }
@@ -370,6 +388,7 @@ server.registerTool(
370388
},
371389
async ({ entityNames }) => {
372390
await knowledgeGraphManager.deleteEntities(entityNames);
391+
notifyGraphUpdated();
373392
return {
374393
content: [{ type: "text" as const, text: "Entities deleted successfully" }],
375394
structuredContent: { success: true, message: "Entities deleted successfully" }
@@ -402,6 +421,7 @@ server.registerTool(
402421
},
403422
async ({ deletions }) => {
404423
await knowledgeGraphManager.deleteObservations(deletions);
424+
notifyGraphUpdated();
405425
return {
406426
content: [{ type: "text" as const, text: "Observations deleted successfully" }],
407427
structuredContent: { success: true, message: "Observations deleted successfully" }
@@ -431,6 +451,7 @@ server.registerTool(
431451
},
432452
async ({ relations }) => {
433453
await knowledgeGraphManager.deleteRelations(relations);
454+
notifyGraphUpdated();
434455
return {
435456
content: [{ type: "text" as const, text: "Relations deleted successfully" }],
436457
structuredContent: { success: true, message: "Relations deleted successfully" }
@@ -523,12 +544,52 @@ server.registerTool(
523544
}
524545
);
525546

547+
export function registerKnowledgeGraphResource(
548+
server: McpServer,
549+
manager: KnowledgeGraphManager,
550+
) {
551+
server.registerResource(
552+
"knowledge-graph",
553+
RESOURCE_URI,
554+
{
555+
title: "Knowledge Graph",
556+
description: "The full knowledge graph with all entities and relations",
557+
mimeType: "application/json",
558+
},
559+
async (uri) => {
560+
const graph = await manager.readGraph();
561+
return {
562+
contents: [
563+
{
564+
uri: uri.href,
565+
mimeType: "application/json",
566+
text: JSON.stringify(graph, null, 2),
567+
},
568+
],
569+
};
570+
},
571+
);
572+
}
573+
574+
// Enable clients to subscribe to the knowledge-graph resource and receive
575+
// notifications/resources/updated when mutation tools change the graph.
576+
export function registerKnowledgeGraphSubscriptions(server: McpServer) {
577+
server.server.registerCapabilities({ resources: { subscribe: true } });
578+
server.server.setRequestHandler(SubscribeRequestSchema, async (request) => {
579+
resourceSubscribers.add(request.params.uri);
580+
return {};
581+
});
582+
server.server.setRequestHandler(UnsubscribeRequestSchema, async (request) => {
583+
resourceSubscribers.delete(request.params.uri);
584+
return {};
585+
});
586+
}
587+
526588
async function main() {
527-
// Initialize memory file path with backward compatibility
528589
MEMORY_FILE_PATH = await ensureMemoryFilePath();
529-
530-
// Initialize knowledge graph manager with the memory file path
531590
knowledgeGraphManager = new KnowledgeGraphManager(MEMORY_FILE_PATH);
591+
registerKnowledgeGraphResource(server, knowledgeGraphManager);
592+
registerKnowledgeGraphSubscriptions(server);
532593

533594
const transport = new StdioServerTransport();
534595
await server.connect(transport);

0 commit comments

Comments
 (0)