Persistent project knowledge graph for coding agents. MCP server with semantic search, in-process embeddings, and web explorer.
TypeScript agentic-codingaiai-agentsclaude-codecode-contextcoding-agentembeddingsknowledge-graphllmmcpmcp-serveropencodepersistent-memorysqlitetypescript
feat(mcp): add get_concept tool for exact ID lookup
Mikael Jansson9d0347902980
diff --git a/README.md b/README.mdindex c1afcfe..99772d5 100644--- a/README.md+++ b/README.md@@ -29,7 +29,7 @@ The LLM is the indexer. No AST parsing. No static analysis. Your agent reads cod`understand → work → update`1. **Session start** — agent calls `list_roots` to orient itself-2. **Before a task** — agent calls `understand` with a natural language query+2. **Before a task** — agent calls `understand` with a natural language query (or `get_concept` for exact ID lookup)3. **After a task** — agent calls `create_concept` or `update_concept` to record what it builtEverything persists in a per-project SQLite database at `.megamemory/knowledge.db`.@@ -119,6 +119,7 @@ Add megamemory as a stdio MCP server. The command is just `megamemory` (no argum| Tool | Description ||------|-------------|| `understand` | Semantic search over the knowledge graph. Returns matched concepts with children, edges, and parent context. |+| `get_concept` | Look up a concept by its exact ID. Returns full context including children, edges, incoming edges, and parent. || `create_concept` | Add a new concept with optional edges and file references. || `update_concept` | Update fields on an existing concept. Regenerates embeddings automatically. || `link` | Create a typed relationship between two concepts. |@@ -167,8 +168,8 @@ megamemory serve --port 8080 # custom port```src/- index.ts CLI entry + MCP server (8 tools)- tools.ts Tool handlers (understand, create, update, link, remove, list_conflicts, resolve_conflict)+ index.ts CLI entry + MCP server (9 tools)+ tools.ts Tool handlers (understand, get_concept, create, update, link, remove, list_conflicts, resolve_conflict)db.ts SQLite persistence (libsql, WAL mode, schema v3)embeddings.ts In-process embeddings (all-MiniLM-L6-v2, 384 dims)merge.ts Two-way merge engine for knowledge.db filesdiff --git a/src/__tests__/get-concept.test.ts b/src/__tests__/get-concept.test.tsnew file mode 100644index 0000000..2bf1d00--- /dev/null+++ b/src/__tests__/get-concept.test.ts@@ -0,0 +1,212 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import { KnowledgeDB } from "../db.js";+import { getConcept } from "../tools.js";+import fs from "fs";+import path from "path";+import os from "os";++let tmpDir: string;++function createTmpDb(name: string): { db: KnowledgeDB; path: string } {+ const dbPath = path.join(tmpDir, name);+ const db = new KnowledgeDB(dbPath);+ return { db, path: dbPath };+}++function insertTestNode(+ db: KnowledgeDB,+ id: string,+ overrides: Partial<{+ name: string;+ kind: string;+ summary: string;+ why: string | null;+ file_refs: string[] | null;+ parent_id: string | null;+ }> = {}+): void {+ db.insertNode({+ id,+ name: overrides.name ?? id,+ kind: overrides.kind ?? "feature",+ summary: overrides.summary ?? `Summary for ${id}`,+ why: overrides.why ?? null,+ file_refs: overrides.file_refs ?? null,+ parent_id: overrides.parent_id ?? null,+ created_by_task: null,+ embedding: null,+ });+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "megamemory-get-concept-test-"));+});++afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++describe("getConcept tool", () => {+ it("returns full NodeWithContext for an existing node", () => {+ const { db } = createTmpDb("basic.db");+ insertTestNode(db, "test-node", {+ name: "Test Node",+ kind: "module",+ summary: "A test node summary",+ why: "For testing purposes",+ file_refs: ["src/test.ts"],+ });++ const result = getConcept(db, { id: "test-node" });++ expect(result.id).toBe("test-node");+ expect(result.name).toBe("Test Node");+ expect(result.kind).toBe("module");+ expect(result.summary).toBe("A test node summary");+ expect(result.why).toBe("For testing purposes");+ expect(result.file_refs).toEqual(["src/test.ts"]);++ db.close();+ });++ it("throws when concept ID does not exist", () => {+ const { db } = createTmpDb("missing.db");++ expect(() => getConcept(db, { id: "non-existent" })).toThrow(+ /not found/+ );++ db.close();+ });++ it("throws for soft-deleted nodes", () => {+ const { db } = createTmpDb("deleted.db");+ insertTestNode(db, "doomed-node");+ db.softDeleteNode("doomed-node", "no longer needed");++ expect(() => getConcept(db, { id: "doomed-node" })).toThrow(/not found/);++ db.close();+ });++ it("includes children when child nodes exist", () => {+ const { db } = createTmpDb("children.db");+ insertTestNode(db, "parent-node", { name: "Parent" });+ insertTestNode(db, "child-a", {+ name: "Child A",+ parent_id: "parent-node",+ });+ insertTestNode(db, "child-b", {+ name: "Child B",+ kind: "pattern",+ parent_id: "parent-node",+ });++ const result = getConcept(db, { id: "parent-node" });++ expect(result.children).toHaveLength(2);+ expect(result.children.map((c) => c.id).sort()).toEqual([+ "child-a",+ "child-b",+ ]);+ const childA = result.children.find((c) => c.id === "child-a")!;+ expect(childA.name).toBe("Child A");+ expect(childA.kind).toBe("feature");++ db.close();+ });++ it("includes outgoing edges", () => {+ const { db } = createTmpDb("edges-out.db");+ insertTestNode(db, "node-a");+ insertTestNode(db, "node-b");+ db.insertEdge({+ from_id: "node-a",+ to_id: "node-b",+ relation: "depends_on",+ description: "A depends on B",+ });++ const result = getConcept(db, { id: "node-a" });++ expect(result.edges).toHaveLength(1);+ expect(result.edges[0].to).toBe("node-b");+ expect(result.edges[0].relation).toBe("depends_on");+ expect(result.edges[0].description).toBe("A depends on B");++ db.close();+ });++ it("includes incoming edges", () => {+ const { db } = createTmpDb("edges-in.db");+ insertTestNode(db, "node-a");+ insertTestNode(db, "node-b");+ db.insertEdge({+ from_id: "node-a",+ to_id: "node-b",+ relation: "connects_to",+ description: "A connects to B",+ });++ const result = getConcept(db, { id: "node-b" });++ expect(result.incoming_edges).toHaveLength(1);+ expect(result.incoming_edges[0].from).toBe("node-a");+ expect(result.incoming_edges[0].relation).toBe("connects_to");++ db.close();+ });++ it("includes parent when parent_id is set", () => {+ const { db } = createTmpDb("parent.db");+ insertTestNode(db, "parent-node", { name: "Parent" });+ insertTestNode(db, "child-node", {+ name: "Child",+ parent_id: "parent-node",+ });++ const result = getConcept(db, { id: "child-node" });++ expect(result.parent).not.toBeNull();+ expect(result.parent!.id).toBe("parent-node");+ expect(result.parent!.name).toBe("Parent");++ db.close();+ });++ it("parent is null when parent_id is null", () => {+ const { db } = createTmpDb("no-parent.db");+ insertTestNode(db, "orphan-node");++ const result = getConcept(db, { id: "orphan-node" });++ expect(result.parent).toBeNull();++ db.close();+ });++ it("does not include similarity field", () => {+ const { db } = createTmpDb("no-similarity.db");+ insertTestNode(db, "plain-node");++ const result = getConcept(db, { id: "plain-node" });++ expect("similarity" in result).toBe(false);++ db.close();+ });++ it("file_refs is parsed from JSON to array", () => {+ const { db } = createTmpDb("filerefs.db");+ insertTestNode(db, "refs-node", {+ file_refs: ["src/a.ts", "src/b.ts", "src/c.ts"],+ });++ const result = getConcept(db, { id: "refs-node" });++ expect(result.file_refs).toHaveLength(3);+ expect(result.file_refs).toEqual(["src/a.ts", "src/b.ts", "src/c.ts"]);++ db.close();+ });+});diff --git a/src/index.ts b/src/index.tsindex 10db025..ef11bd8 100644--- a/src/index.ts+++ b/src/index.ts@@ -154,7 +154,7 @@ async function startMcpServer() {const { z } = await import("zod");const path = await import("path");const { KnowledgeDB } = await import("./db.js");- const { understand, createConcept, updateConcept, link, removeConcept, listRoots, listConflicts, resolveConflict, formatError } =+ const { understand, getConcept, createConcept, updateConcept, link, removeConcept, listRoots, listConflicts, resolveConflict, formatError } =await import("./tools.js");type NodeKind = import("./types.js").NodeKind;@@ -235,6 +235,38 @@ async function startMcpServer() {});+ server.tool(+ "get_concept",+ "Look up a concept by its exact ID. Returns the concept with its full context including children, edges, incoming edges, and parent. Unlike 'understand' which uses semantic search, this does exact ID matching. Use this when you know the specific concept ID.",+ {+ id: z.string().describe("Exact concept ID to look up (e.g., 'chapter-03-main-c-god-object-split')"),+ },+ async (params) => {+ try {+ const result = getConcept(db, { id: params.id });+ timeline.log({+ tool: "get_concept",+ params: { id: params.id },+ result_summary: `found ${result.id}`,+ is_write: false,+ is_error: false,+ affected_ids: [result.id],+ });+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };+ } catch (err) {+ timeline.log({+ tool: "get_concept",+ params: { id: params.id },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: false,+ is_error: true,+ affected_ids: [],+ });+ return formatError(err);+ }+ }+ );+server.tool("create_concept","Add a new concept to the knowledge graph. Call this after completing a task to record new features, components, patterns, or decisions you built. Include specific details: parameter names, defaults, file locations, and rationale.",diff --git a/src/tools.ts b/src/tools.tsindex 79b3655..241d3ad 100644--- a/src/tools.ts+++ b/src/tools.ts@@ -2,6 +2,7 @@ import { KnowledgeDB } from "./db.js";import { embed, embeddingText, findTopK } from "./embeddings.js";import type {UnderstandInput,+ GetConceptInput,CreateConceptInput,UpdateConceptInput,LinkInput,@@ -135,6 +136,17 @@ export async function understand(return { matches };}+export function getConcept(+ db: KnowledgeDB,+ input: GetConceptInput+): NodeWithContext {+ const node = db.getNode(input.id);+ if (!node) {+ throw new Error(`Concept "${input.id}" not found.`);+ }+ return buildNodeWithContext(db, node);+}+export async function createConcept(db: KnowledgeDB,input: CreateConceptInputdiff --git a/src/types.ts b/src/types.tsindex 3b4dbb8..1df2a83 100644--- a/src/types.ts+++ b/src/types.ts@@ -127,6 +127,10 @@ export interface UnderstandOutput {matches: NodeWithContext[];}+export interface GetConceptInput {+ id: string;+}+export interface ListRootsOutput {roots: Array<{id: string;