Implementation:0xK3vin MegaMemory MCP Tools Core
| Knowledge Sources | |
|---|---|
| Domains | Knowledge_Graph, MCP, Semantic_Search |
| Last Updated | 2026-10-27 12:00 GMT |
Overview
Concrete tool handlers for reading and writing the project knowledge graph provided by the MegaMemory MCP server.
Description
The MCP Tools Core (src/tools.ts) implements the six graph-reading and graph-writing tool handlers that the MegaMemory MCP server exposes to coding agents: understand, createConcept, updateConcept, link, removeConcept, and listRoots. Each handler is a plain async function taking a KnowledgeDB and a typed input; the MCP layer in src/index.ts wraps it with zod validation, timeline logging, and error formatting. The module also exports buildNodeWithContext (assembles a node with its children/edges/parent), makeId (slug generator), and formatError (MCP error envelope).
Key handlers:
- understand — embed a query, brute-force rank all active nodes, return top-K with full context
- createConcept — generate a slug ID, validate parent, embed, insert node + edges atomically
- updateConcept — apply changes; re-embeds when name or summary changes
- link — validate both endpoints, insert edge (INSERT OR IGNORE for idempotency)
- removeConcept — soft-delete node + cascade-delete incident edges
- listRoots — list root concepts and their direct children; hints bootstrap if empty
Usage
Import these handlers when you need to:
- Session orientation: call listRoots to see the current project's top-level concepts
- Pre-task context loading: call understand with a natural-language query before reading source files
- Post-task recording: call createConcept for new concepts, updateConcept for changes, link for new relationships, removeConcept for obsolete concepts
- Building rich context: call buildNodeWithContext to assemble a node with its edges and parent
Code Reference
Source Location
- Repository: 0xK3vin_MegaMemory
- File: src/tools.ts
- Key functions:
- formatError: L21-27
- makeId: L33-41
- buildNodeWithContext: L58-105
- understand: L109-137
- getConcept: L139-148
- createConcept: L150-191
- updateConcept: L193-223
- link: L225-253
- removeConcept: L255-275
- listRoots: L277-299
Signature
export function formatError(err: unknown): {
content: Array<{ type: "text"; text: string }>;
isError: true;
};
export function makeId(name: string, parentId?: string): string;
export function buildNodeWithContext(
db: KnowledgeDB,
node: NodeRow,
similarity?: number
): NodeWithContext;
export async function understand(
db: KnowledgeDB,
input: UnderstandInput // { query: string; top_k?: number }
): Promise<UnderstandOutput>; // { matches: NodeWithContext[] }
export function getConcept(
db: KnowledgeDB,
input: GetConceptInput // { id: string }
): NodeWithContext;
export async function createConcept(
db: KnowledgeDB,
input: CreateConceptInput
): Promise<{ id: string; message: string }>;
export async function updateConcept(
db: KnowledgeDB,
input: UpdateConceptInput
): Promise<{ message: string }>;
export function link(
db: KnowledgeDB,
input: LinkInput
): { message: string };
export function removeConcept(
db: KnowledgeDB,
input: RemoveConceptInput
): { message: string };
export function listRoots(db: KnowledgeDB): ListRootsOutput & { hint?: string };
Import
import {
understand, getConcept, createConcept, updateConcept,
link, removeConcept, listRoots,
buildNodeWithContext, makeId, formatError,
} from "./tools.js";
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| db | KnowledgeDB | Yes | Open SQLite handle to .megamemory/knowledge.db |
| query | string | Yes (understand) | Natural-language query to embed |
| top_k | number | No (understand) | Max matches; default 10, clamped 1–50 by MCP layer |
| name | string | Yes (createConcept) | Concept display name |
| kind | NodeKind | Yes (createConcept) | feature, module, pattern, config, decision, component |
| summary | string | Yes (createConcept) | One-sentence description |
| why | string | No (createConcept) | Rationale for decisions |
| parent_id | string | No (createConcept) | Parent concept ID; empty string = root |
| file_refs | string[] | No | File paths referencing this concept |
| edges | Array | No (createConcept) | Outgoing edges { to, relation, description? } |
| id | string | Yes (update/link/remove/get) | Existing concept ID |
| changes | object | Yes (updateConcept) | { name?, kind?, summary?, why?, file_refs? } |
| from | string | Yes (link) | Source concept ID |
| to | string | Yes (link) | Target concept ID |
| relation | RelationType | Yes (link) | connects_to, depends_on, implements, calls, configured_by |
| reason | string | Yes (removeConcept) | Why this concept was removed |
Outputs
| Name | Type | Description |
|---|---|---|
| understand() returns | UnderstandOutput | { matches: NodeWithContext[] } with similarity scores |
| createConcept() returns | { id, message } | Generated slug ID and confirmation |
| updateConcept() returns | { message } | Confirmation or "No changes applied" |
| link() returns | { message } | Edge ID in message, or "already exists" |
| removeConcept() returns | { message } | Soft-delete confirmation with reason |
| listRoots() returns | ListRootsOutput | Roots with children; hint if empty graph |
| Side effects | DB writes | Nodes/edges written via db.insertNodeAndEdges, db.updateNode, db.insertEdge, db.softDeleteNode; each logged to timeline |
Usage Examples
Session Orientation (list_roots)
import { listRoots } from "./tools.js";
const result = listRoots(db);
// => { roots: [{ id: "merge-engine", name: "Merge Engine", kind: "module", summary: "...", children: ["merge-engine/two-pass-algorithm"] }] }
// Empty graph: { roots: [], hint: "Graph is empty. Run /user:bootstrap-memory..." }
Pre-Task Context Loading (understand)
import { understand } from "./tools.js";
// Query the graph before reading source files
const { matches } = await understand(db, {
query: "how does the merge algorithm handle conflicting edges?",
top_k: 10,
});
for (const match of matches) {
console.log(`${match.similarity.toFixed(2)} ${match.id}: ${match.summary}`);
// 0.78 merge-engine: Two-pass graph merge with conflict tracking
// 0.65 merge-engine/edge-remapping: Deferred edges remapped by origin side
}
Create a New Concept (create_concept)
import { createConcept } from "./tools.js";
// Create a root concept
const { id } = await createConcept(db, {
name: "Merge Engine",
kind: "module",
summary: "Two-pass graph merge with ::left/::right conflict tracking",
why: "SQLite DBs are unmergeable by git; this provides a structured merge",
file_refs: ["src/merge.ts"],
edges: [
{ to: "knowledge-db", relation: "depends_on", description: "reads raw rows via getAllNodesRaw" },
],
});
// => id = "merge-engine"
Create a Child Concept
import { createConcept } from "./tools.js";
// Create a child concept under the root above
const { id } = await createConcept(db, {
name: "Two Pass Algorithm",
kind: "pattern",
summary: "Pass 1 inserts all nodes; Pass 2 inserts deferred edges with remapped IDs",
parent_id: "merge-engine",
});
// => id = "merge-engine/two-pass-algorithm"
Update an Existing Concept (update_concept)
import { updateConcept } from "./tools.ts";
// Update the summary; embedding is regenerated automatically
await updateConcept(db, {
id: "merge-engine",
changes: {
summary: "Two-pass graph merge with conflict tracking and edge remapping",
why: "SQLite DBs are unmergeable by git; structured merge prevents data loss",
},
});
// Embedding regenerated because summary changed
Link Two Concepts (link)
import { link } from "./tools.js";
link(db, {
from: "merge-engine",
to: "embeddings-module",
relation: "depends_on",
description: "uses embed() to regenerate resolved conflict embeddings",
});
// => { message: 'Created depends_on link from "merge-engine" to "embeddings-module" (edge #42)' }
Remove an Obsolete Concept (remove_concept)
import { removeConcept } from "./tools.js";
removeConcept(db, {
id: "old-approach",
reason: "Replaced by MergeEngine in v1.2.0",
});
// => { message: 'Removed concept "old-approach". Reason: Replaced by MergeEngine in v1.2.0' }
// Incident edges are cascade-deleted; node row preserved with removed_at timestamp
Related Pages
Implements Principle
- Principle:0xK3vin_MegaMemory_Semantic_Search
- Principle:0xK3vin_MegaMemory_Knowledge_Graph_Recording
- Principle:0xK3vin_MegaMemory_Graph_Hierarchy_Organization
- Principle:0xK3vin_MegaMemory_Agent_Memory_Loop