Skip to main content
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:
  1. Dynamic tool generation: Define a JSON schema file → system auto-generates add_*, update_*, delete_* MCP tools
  2. Schema-enforced properties: Each node type has required/optional fields with enum constraints
  3. Relationship-aware schemas: Schema properties can define edges that auto-create when nodes are created
  4. Metadata as flat string arrays: Structured data stored as "Key: Value" strings for maximum flexibility
  5. Edge weights: Confidence/strength scoring on relationships (0.0–1.0 range)
  6. Transaction support: Atomic multi-step operations with rollback
  7. Neighbor-inclusive queries: Search and open operations always return immediate graph neighbors for richer context

1.2 Core Architecture

1.3 Key Design Decisions

  1. Schema-first design: All node types are defined by JSON schema files. No free-form entity creation.
  2. Metadata as string arrays: Instead of typed objects, metadata is ["Role: Wizard", "Status: Active"] — parsed on demand.
  3. Relationship properties in schemas: A schema property can declare it creates an edge, making relationship creation automatic.
  4. Edge weights: Optional 0–1 float on edges representing confidence/strength. Default 1.0.
  5. Weight averaging: When updating weights, new evidence is averaged with current: (current + new) / 2.
  6. Neighbor-inclusive search: searchNodes and openNodes always include immediate neighbor nodes and connecting edges.
  7. Transaction wrapping: Multi-step operations (create node + edges) are wrapped in transactions with rollback support.
  8. Event system: Before/after events emitted on all graph operations for extensibility.

2. Data Model

2.1 Node

Rules:
  • name is the UNIQUE key. Two nodes cannot have the same name regardless of nodeType.
  • nodeType references a loaded schema name (without “add_” prefix in storage).
  • metadata is a flat array of strings in “Key: Value” format (colon-space separator).

2.2 Edge

Rules:
  • Edges are UNIQUE by the triple (from, to, edgeType). No duplicate edges.
  • Both from and to must 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:
Loading/saving follows the same pattern as Spec 01: full file read on load, full file write on save, 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 a schemas/ 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 name field 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 a relationship block:
On creation: If currentLocation is provided with value “Rivendell”:
  1. A metadata entry "Current Location: Rivendell" is added to the node
On update: If currentLocation changes from “Rivendell” to “Mordor”:
  1. 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:
Validation on load:
  • File must be valid JSON
  • Must have name (string), description (string), properties (object)
  • Name must start with "add_"
  • Properties must have type and description

3.7 SchemaProcessor — Node Creation from Schema

Algorithm:
PropertyDisplayName conversion: Convert camelCase property name to Title Case with spaces:
  • 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>
CRITICAL: Search returns BOTH the directly matching nodes AND their immediate neighbors. This provides richer context for the AI. openNodes(names: string[]): Promise<Graph>

4.6 TransactionManager

Key behavior:
  • 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:
  1. add_<type>: Creates a new node of this type with schema-validated properties
  2. update_<type>: Updates an existing node (all properties optional except name)
  3. delete_<type>: Deletes a node by name and type

5.2 Tool Schema Generation

Given an NPC schema with properties name, role, status, currentLocation, description, traits: Generated add_npc tool input schema:
Generated update_npc tool input schema:
  • Same structure but required only includes ["name"]
  • All other properties are optional for partial updates
Generated delete_npc tool input schema:

5.3 Dynamic Tool Execution Flow

Add operation (add_npc):
Update operation (update_npc):
Delete operation (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

Routing logic:

7.2 Response Format

All tool responses follow this structure: Success response:
Error 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

Example of weight evolution:

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
Test: Reject schema without “add_” prefix
  • Input: Schema with name “npc” (no prefix)
  • Expected: Validation error thrown
Test: Load all schemas from directory
  • 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"]
Test: Create node with relationship property
Test: Update node via schema tool
  • Setup: NPC “Gandalf” with currentLocation “Rivendell”
  • Expected: Old edge to Rivendell deleted. New edge to Mordor created. Metadata updated.
Test: Delete node via schema tool
  • Setup: NPC “Gandalf” with edges
  • Expected: Node and all connected edges removed
Test: Enum validation
  • Input: add_npc with 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]
Test: Open nodes returns neighbors
  • 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
Test: Failed transaction rolls back
  • Begin transaction → Add node → Fail on edge (bad reference) → Rollback
  • Expected: Node is also removed (rolled back)
Test: withTransaction auto-commits on success
  • Expected: Both persisted
Test: withTransaction auto-rolls-back on error
  • Expected: Node not persisted

14.5 Edge Weight Tests

Test: Default weight is 1.0
  • Create edge without weight
  • Expected: edge.weight === 1.0
Test: Weight averaging on update
  • Setup: Edge with weight 0.8
  • Update with weight 0.6
  • Expected: New weight = (0.8 + 0.6) / 2 = 0.7
Test: Weight out of range rejected
  • Create edge with weight 1.5
  • Expected: Validation error

15. Implementation Checklist

  1. Core data types: Node, Edge, Graph interfaces
  2. JSONL storage: Load/save with type discriminator
  3. MetadataProcessor: Parse, format, merge, query metadata strings
  4. EdgeWeightUtils: Validate, default, average, combine weights
  5. GraphValidator: Node/edge property and uniqueness validation
  6. NodeManager: CRUD with cascade deletes
  7. EdgeManager: CRUD with weight handling and node reference validation
  8. MetadataManager: Add/delete metadata entries with deduplication
  9. SearchManager: Case-insensitive search + neighbor expansion; exact open + neighbor expansion
  10. TransactionManager: Begin/commit/rollback with LIFO action queue
  11. ApplicationManager: Facade delegating to all managers
  12. EventEmitter: Simple pub-sub for before/after hooks
  13. SchemaBuilder: Programmatic schema construction
  14. SchemaLoader: Load .schema.json files from disk
  15. SchemaProcessor: Create/update nodes from schema definitions with automatic edge generation
  16. DynamicSchemaToolRegistry: Generate add/update/delete tools per schema
  17. Static tools: Register 11 always-available MCP tools
  18. Tool routing: Factory pattern to route tool calls to correct handler
  19. Response formatting: Success, error, and partial success response builders
  20. MCP server setup: Server initialization, tool registration, stdio transport
  21. Configuration: Centralized paths and server metadata
  22. Sample schemas: At minimum one example schema file (npc.schema.json)
Total expected implementation: ~2000 lines TypeScript across ~25 files in a layered architecture.