Normalized for Mintlify from
knowledge-base/neurigraph-memory-architecture/neurigraph-tool-references/03-Temporal-Knowledge-Graph-Adaptive-Decay.mdx.Clean-Room Specification 03: Schema-Driven Knowledge Graph with Dynamic Tool Generation
Document Purpose
This specification describes a schema-driven knowledge graph MCP server that automatically generates CRUD tools from JSON schema definitions. Unlike basic knowledge graphs with fixed tool sets, this system allows users to define custom entity schemas (e.g., NPCs, locations, artifacts) that automatically become MCP tools with full validation, relationship management, and transactional operations. An AI coding model should be able to produce a functionally identical implementation from this document alone.1. System Overview
1.1 What This System Does
This is a TypeScript MCP server that provides a schema-governed knowledge graph with these key innovations:- Dynamic tool generation: Define a JSON schema file → system auto-generates
add_*,update_*,delete_*MCP tools - Schema-enforced properties: Each node type has required/optional fields with enum constraints
- Relationship-aware schemas: Schema properties can define edges that auto-create when nodes are created
- Metadata as flat string arrays: Structured data stored as
"Key: Value"strings for maximum flexibility - Edge weights: Confidence/strength scoring on relationships (0.0–1.0 range)
- Transaction support: Atomic multi-step operations with rollback
- Neighbor-inclusive queries: Search and open operations always return immediate graph neighbors for richer context
1.2 Core Architecture
1.3 Key Design Decisions
- Schema-first design: All node types are defined by JSON schema files. No free-form entity creation.
- Metadata as string arrays: Instead of typed objects, metadata is
["Role: Wizard", "Status: Active"]— parsed on demand. - Relationship properties in schemas: A schema property can declare it creates an edge, making relationship creation automatic.
- Edge weights: Optional 0–1 float on edges representing confidence/strength. Default 1.0.
- Weight averaging: When updating weights, new evidence is averaged with current:
(current + new) / 2. - Neighbor-inclusive search:
searchNodesandopenNodesalways include immediate neighbor nodes and connecting edges. - Transaction wrapping: Multi-step operations (create node + edges) are wrapped in transactions with rollback support.
- Event system: Before/after events emitted on all graph operations for extensibility.
2. Data Model
2.1 Node
nameis the UNIQUE key. Two nodes cannot have the same name regardless of nodeType.nodeTypereferences a loaded schema name (without “add_” prefix in storage).metadatais a flat array of strings in “Key: Value” format (colon-space separator).
2.2 Edge
- Edges are UNIQUE by the triple
(from, to, edgeType). No duplicate edges. - Both
fromandtomust reference existing nodes (validated on creation). - Weight must be in range [0.0, 1.0]. Default is 1.0 (maximum confidence).
- Edges are directional: A→B ≠ B→A.
2.3 Graph
2.4 JSONL Storage Format
One JSON object per line. All nodes first, then all edges:type field stripped from in-memory objects and re-added on serialization.
3. Schema System — The Core Innovation
3.1 Schema File Format
Schemas are JSON files stored in aschemas/ directory with the naming convention <entitytype>.schema.json.
Complete schema example (npc.schema.json):
3.2 Schema Property Types
3.3 Schema Name Convention
- Schema file
namefield MUST start with"add_"prefix (e.g.,"add_npc") - The entity type is derived by removing the prefix:
"add_npc"→"npc" - Dynamic tools generated:
add_npc,update_npc,delete_npc
3.4 Relationship Properties
When a schema property includes arelationship block:
currentLocation is provided with value “Rivendell”:
- A metadata entry
"Current Location: Rivendell"is added to the node
currentLocation changes from “Rivendell” to “Mordor”:
- Update metadata: replace
"Current Location: Rivendell"with"Current Location: Mordor"
3.5 SchemaBuilder Class
Programmatically constructs schemas:createUpdateSchema(): Creates a variant where ALL properties are optional (for partial updates). The name property becomes required (to identify which node to update).
3.6 SchemaLoader Class
Loads schemas from disk:- File must be valid JSON
- Must have
name(string),description(string),properties(object) - Name must start with
"add_" - Properties must have
typeanddescription
3.7 SchemaProcessor — Node Creation from Schema
currentLocation→"Current Location"role→"Role"
4. Manager Classes — Complete Specifications
4.1 ApplicationManager (Facade)
Central entry point that delegates to specialized managers:4.2 NodeManager
addNodes(nodes: Node[]): Promise<void>
deleteNodes(names: string[]): Promise<void>
4.3 EdgeManager
addEdges(edges: Edge[]): Promise<void>
4.4 MetadataManager
addMetadata(nodeName: string, entries: string[]): Promise<void>
deleteMetadata(nodeName: string, entries: string[]): Promise<void>
4.5 SearchManager
readGraph(): Promise<Graph>
searchNodes(query: string): Promise<Graph>
openNodes(names: string[]): Promise<Graph>
4.6 TransactionManager
- Rollback actions execute in LIFO order (last registered, first executed)
- A failing rollback action does NOT prevent remaining rollback actions from executing
withTransaction()provides auto-commit on success, auto-rollback on failure
5. Dynamic Tool Generation
5.1 How It Works
For each.schema.json file loaded, the system generates THREE MCP tools:
add_<type>: Creates a new node of this type with schema-validated propertiesupdate_<type>: Updates an existing node (all properties optional exceptname)delete_<type>: Deletes a node by name and type
5.2 Tool Schema Generation
Given an NPC schema with propertiesname, role, status, currentLocation, description, traits:
Generated add_npc tool input schema:
update_npc tool input schema:
- Same structure but
requiredonly includes["name"] - All other properties are optional for partial updates
delete_npc tool input schema:
5.3 Dynamic Tool Execution Flow
Add operation (add_npc):
update_npc):
delete_npc):
6. Static MCP Tools (11 Tools)
In addition to dynamic schema tools, the server provides 11 always-available tools:6.1 Graph Mutation Tools
add_nodes
- Action: Add nodes to graph (validates uniqueness)
update_nodes
- Action: Update existing nodes by name
delete_nodes
- Action: Delete nodes and cascade-delete connected edges
add_edges
- Action: Add edges (validates node existence, uniqueness, weight range)
update_edges
- Action: Update edge weights using averaging formula
delete_edges
- Action: Remove edges by exact triple match
6.2 Metadata Tools
add_metadata
- Action: Append metadata entries to node (deduplicated)
delete_metadata
- Action: Remove specific metadata entries from node
6.3 Search Tools
read_graph
- Action: Return complete graph
search_nodes
- Action: Case-insensitive substring search + neighbor expansion
open_nodes
- Action: Exact name lookup + neighbor expansion
7. Tool Handler Routing
7.1 Handler Architecture
7.2 Response Format
All tool responses follow this structure: Success response:8. Event System
8.1 EventEmitter
Simple publish-subscribe system:8.2 Events Emitted
beforeBeginTransaction | Before transaction starts | {} |
| afterCommit | After transaction commits | {} |
| beforeRollback | Before rollback executes | {} |
| afterRollback | After rollback completes | {} |
9. Metadata Processing
9.1 Metadata Format
All metadata entries are strings in"Key: Value" format:
9.2 MetadataProcessor Utilities
10. Edge Weight System
10.1 Weight Properties
- Range: 0.0 (no confidence) to 1.0 (maximum confidence)
- Default: 1.0 when not specified
- Meaning: Strength or confidence of the relationship
10.2 Weight Utilities
11. Validation Rules
11.1 Node Validation
11.2 Edge Validation
12. Configuration
13. Example Schema Set
The system ships with 11 pre-built schemas (designed for RPG/storytelling use cases):
These schemas are customizable and replaceable. Users can add their own schemas for any domain.
14. Complete Behavioral Test Specifications
14.1 Schema Loading Tests
Test: Load valid schema- Input: Valid npc.schema.json
- Expected: SchemaBuilder created with correct properties and relationships
- Input: Schema with name “npc” (no prefix)
- Expected: Validation error thrown
- Input: Directory with 3 schema files
- Expected: 3 SchemaBuilder instances, 9 dynamic tools registered
14.2 Dynamic Tool Tests
Test: Create node via schema tool- Expected: Node created with metadata
["Role: Wizard", "Status: Active"]
- Setup: NPC “Gandalf” with currentLocation “Rivendell”
- Expected: Old edge to Rivendell deleted. New edge to Mordor created. Metadata updated.
- Setup: NPC “Gandalf” with edges
- Expected: Node and all connected edges removed
- Input:
add_npcwith role “Dragon” (not in enum) - Expected: Validation error
14.3 Search with Neighbor Expansion
Test: Search returns neighbors- Setup: Nodes A, B, C. Edge A→B. Search matches only A.
- Expected: Returns nodes [A, B], edges [A→B]
- Setup: Nodes A, B, C. Edges: A→B, B→C.
- Input: openNodes([“A”])
- Expected: Returns nodes [A, B], edges [A→B]
14.4 Transaction Tests
Test: Successful transaction commits- Begin transaction → Add node → Add edge → Commit
- Expected: Both node and edge persisted
- Begin transaction → Add node → Fail on edge (bad reference) → Rollback
- Expected: Node is also removed (rolled back)
- Expected: Both persisted
- Expected: Node not persisted
14.5 Edge Weight Tests
Test: Default weight is 1.0- Create edge without weight
- Expected: edge.weight === 1.0
- Setup: Edge with weight 0.8
- Update with weight 0.6
- Expected: New weight = (0.8 + 0.6) / 2 = 0.7
- Create edge with weight 1.5
- Expected: Validation error
15. Implementation Checklist
- Core data types: Node, Edge, Graph interfaces
- JSONL storage: Load/save with type discriminator
- MetadataProcessor: Parse, format, merge, query metadata strings
- EdgeWeightUtils: Validate, default, average, combine weights
- GraphValidator: Node/edge property and uniqueness validation
- NodeManager: CRUD with cascade deletes
- EdgeManager: CRUD with weight handling and node reference validation
- MetadataManager: Add/delete metadata entries with deduplication
- SearchManager: Case-insensitive search + neighbor expansion; exact open + neighbor expansion
- TransactionManager: Begin/commit/rollback with LIFO action queue
- ApplicationManager: Facade delegating to all managers
- EventEmitter: Simple pub-sub for before/after hooks
- SchemaBuilder: Programmatic schema construction
- SchemaLoader: Load .schema.json files from disk
- SchemaProcessor: Create/update nodes from schema definitions with automatic edge generation
- DynamicSchemaToolRegistry: Generate add/update/delete tools per schema
- Static tools: Register 11 always-available MCP tools
- Tool routing: Factory pattern to route tool calls to correct handler
- Response formatting: Success, error, and partial success response builders
- MCP server setup: Server initialization, tool registration, stdio transport
- Configuration: Centralized paths and server metadata
- Sample schemas: At minimum one example schema file (npc.schema.json)