Knowledge graph is disabled by default . Set KNOWLEDGE_GRAPH_ENABLED=true
to enable it.
Configuration
Environment Variables
Basic Configuration:
# Enable knowledge graph
KNOWLEDGE_GRAPH_ENABLED = true
# Backend type (neo4j or in-memory)
KNOWLEDGE_GRAPH_TYPE = neo4j
# Database name (for Neo4j)
KNOWLEDGE_GRAPH_DATABASE = cipher_knowledge
Neo4j Production Setup:
# Connection via host/port
KNOWLEDGE_GRAPH_HOST = localhost
KNOWLEDGE_GRAPH_PORT = 7687
KNOWLEDGE_GRAPH_USERNAME = neo4j
KNOWLEDGE_GRAPH_PASSWORD = your_password
# Or connection via URI
KNOWLEDGE_GRAPH_URI = neo4j://localhost:7687
KNOWLEDGE_GRAPH_USERNAME = neo4j
KNOWLEDGE_GRAPH_PASSWORD = your_password
In-Memory Development Setup:
# Simple setup for development
KNOWLEDGE_GRAPH_ENABLED = true
KNOWLEDGE_GRAPH_TYPE = in-memory
# No additional configuration needed
cipher.yml Configuration
Neo4j Configuration:
memAgent :
knowledgeGraph :
type : neo4j
host : localhost
port : 7687
username : neo4j
password : your_password
database : cipher_knowledge
enableAutoIndexing : true
enableMetrics : true
enableQueryCache : true
maxRetries : 3
timeout : 30000
In-Memory Configuration:
memAgent :
knowledgeGraph :
type : in-memory
maxNodes : 10000
maxEdges : 50000
enableIndexing : true
enableGarbageCollection : false
enableAutoIndexing : true
defaultBatchSize : 1000
Knowledge Graph Architecture
The knowledge graph system manages complex entity-relationship structures through a sophisticated multi-layer architecture:
The knowledge graph tools follow a systematic approach to entity and relationship management:
The knowledge graph system provides 11 specialized tools for entity and relationship management:
Basic Operations
cipher_add_node
Creates new entities in the knowledge graph.
interface AddNodeResult {
success : boolean ;
message : string ;
nodeId ?: string ;
timestamp : string ;
}
await cipher_add_node ({
id: "func_calculate_total" ,
labels: [ "Function" , "Code" ],
properties: {
name: "calculateTotal" ,
language: "typescript" ,
file_path: "src/utils/math.ts" ,
line_number: 42 ,
created_at: Date . now ()
}
});
cipher_add_edge
Creates relationships between existing nodes.
interface AddEdgeResult {
success : boolean ;
message : string ;
edgeId ?: string ;
timestamp : string ;
}
await cipher_add_edge ({
sourceId: "func_calculate_total" ,
targetId: "func_validate_input" ,
edgeType: "CALLS" ,
properties: {
strength: 0.9 ,
context: "input validation" ,
frequency: 5
}
});
cipher_update_node
Updates properties and labels of existing nodes.
await cipher_update_node ({
nodeId: "func_calculate_total" ,
properties: {
version: "2.0" ,
optimized: true ,
last_modified: Date . now ()
},
labels: [ "Function" , "Code" , "Optimized" ]
});
cipher_delete_node
Removes nodes and their relationships from the graph.
await cipher_delete_node ({
id: "deprecated_function"
});
Search and Query Operations
cipher_search_graph
Searches for nodes and edges with filtering capabilities.
interface SearchGraphResult {
success : boolean ;
message : string ;
results : {
nodes : GraphNode [];
edges : GraphEdge [];
totalCount : number ;
searchMetadata : {
searchType : string ;
appliedFilters : any ;
executionTime : number ;
limit : number ;
};
};
timestamp : string ;
}
await cipher_search_graph ({
searchType: "nodes" ,
nodeLabels: [ "Function" ],
properties: { language: "typescript" },
textSearch: "calculate" ,
limit: 20
});
cipher_get_neighbors
Gets neighboring nodes with relationship information.
interface GetNeighborsResult {
success : boolean ;
message : string ;
neighbors : Array <{
node : GraphNode ;
edge : GraphEdge ;
}>;
timestamp : string ;
}
await cipher_get_neighbors ({
nodeId: "func_calculate_total" ,
direction: "out" ,
edgeTypes: [ "CALLS" , "DEPENDS_ON" ],
limit: 15
});
cipher_query_graph
Executes custom queries against the knowledge graph.
Usage Example - Cypher Query
await cipher_query_graph ({
query: `
MATCH (f:Function)-[r:CALLS]->(target:Function)
WHERE f.language = $lang AND r.strength > $minStrength
RETURN f, r, target
ORDER BY r.strength DESC
` ,
queryType: "cypher" ,
parameters: { lang: "typescript" , minStrength: 0.7 },
limit: 50
});
Usage Example - Structured Query
await cipher_query_graph ({
query: "labels: [Function], properties: {optimized: true}" ,
queryType: "node" ,
limit: 25
});
Advanced Operations
Extracts entities from text and adds them to the knowledge graph.
interface ExtractEntitiesResult {
success : boolean ;
message : string ;
entities : Array <{
name : string ;
type : string ;
confidence : number ;
context ?: string ;
}>;
relationships : Array <{
source : string ;
target : string ;
type : string ;
confidence : number ;
}>;
extracted : number ; // Number of entities extracted
linked : number ; // Number of relationships created
timestamp : string ;
}
await cipher_extract_entities ({
text: "The calculateTotal function calls validateInput and uses MathUtils class" ,
options: {
entityTypes: [ "Function" , "Class" ],
autoLink: true ,
linkTypes: [ "CALLS" , "USES" , "DEPENDS_ON" ]
}
});
cipher_enhanced_search
Advanced search with semantic capabilities and fuzzy matching.
await cipher_enhanced_search ({
query: "functions that handle mathematical calculations" ,
searchType: "auto" ,
options: {
semanticSearch: true ,
fuzzyMatching: true ,
includeRelated: true ,
relationDepth: 2
},
limit: 30
});
cipher_intelligent_processor
Intelligently processes natural language to manage entities and relationships.
await cipher_intelligent_processor ({
text: "John works at Google as a software engineer" ,
options: {
autoResolve: true ,
confidenceThreshold: 0.8 ,
autoCreateRelationships: true
}
});
cipher_relationship_manager
Manages complex relationship operations like entity replacement and merging.
await cipher_relationship_manager ({
instruction: "Replace all references to 'oldFunction' with 'newFunction'" ,
operation: "replace_entity" ,
targets: {
sourceEntity: "oldFunction" ,
targetEntity: "newFunction"
}
});
Data Structures
GraphNode Structure
interface GraphNode {
id : string ; // Unique identifier
labels : string []; // Array of labels/types
properties : Record < string , any >; // Node properties
}
{
id : "func_calculate_total" ,
labels : [ "Function" , "Code" , "TypeScript" ],
properties : {
name : "calculateTotal" ,
language : "typescript" ,
file_path : "src/utils/math.ts" ,
line_number : 42 ,
complexity : "medium" ,
test_coverage : 0.95 ,
created_at : 1704067200000 ,
updated_at : 1704067800000
}
}
GraphEdge Structure
interface GraphEdge {
id : string ; // Unique identifier
type : string ; // Relationship type
startNodeId : string ; // Source node ID
endNodeId : string ; // Target node ID
properties : Record < string , any >; // Edge properties
}
{
id : "edge_func_calc_validates" ,
type : "CALLS" ,
startNodeId : "func_calculate_total" ,
endNodeId : "func_validate_input" ,
properties : {
strength : 0.9 ,
context : "input validation" ,
frequency : 5 ,
call_type : "synchronous" ,
created_at : 1704067300000
}
}
Common Labels and Edge Types
// Common entity types
const NODE_LABELS = {
FUNCTION: 'Function' ,
CLASS: 'Class' ,
VARIABLE: 'Variable' ,
MODULE: 'Module' ,
FILE: 'File' ,
CONCEPT: 'Concept' ,
ENTITY: 'Entity'
};
// Common relationship types
const EDGE_TYPES = {
DEPENDS_ON: 'DEPENDS_ON' ,
CALLS: 'CALLS' ,
USES: 'USES' ,
BELONGS_TO: 'BELONGS_TO' ,
EXTENDS: 'EXTENDS' ,
IMPLEMENTS: 'IMPLEMENTS' ,
CONTAINS: 'CONTAINS' ,
REFERENCES: 'REFERENCES' ,
RELATES_TO: 'RELATES_TO'
};
Examples
Building a Code Knowledge Base
// 1. Extract entities from code documentation
await cipher_extract_entities ({
text: "The AuthService class handles user authentication using JWT tokens and integrates with Redis cache" ,
options: {
entityTypes: [ "Class" , "Technology" , "Concept" ],
autoLink: true
}
});
// 2. Add specific function with detailed metadata
await cipher_add_node ({
id: "func_authenticate_user" ,
labels: [ "Function" , "Authentication" ],
properties: {
name: "authenticateUser" ,
class: "AuthService" ,
file_path: "src/auth/AuthService.ts" ,
parameters: [ "username" , "password" ],
returns: "Promise<AuthResult>" ,
complexity: "medium"
}
});
// 3. Create dependency relationship
await cipher_add_edge ({
sourceId: "func_authenticate_user" ,
targetId: "class_jwt_utils" ,
edgeType: "USES" ,
properties: {
context: "token generation" ,
strength: 0.9
}
});
Intelligent Content Processing
// Process natural language requirements
await cipher_intelligent_processor ({
text: "The payment service should validate credit cards and integrate with Stripe API" ,
options: {
autoCreateRelationships: true ,
confidenceThreshold: 0.8
}
});
// Search for related functionality
await cipher_enhanced_search ({
query: "payment processing and validation functions" ,
options: {
semanticSearch: true ,
includeRelated: true ,
relationDepth: 2
}
});
// Find implementation dependencies
await cipher_get_neighbors ({
nodeId: "service_payment" ,
direction: "out" ,
edgeTypes: [ "USES" , "DEPENDS_ON" ],
limit: 10
});
// Advanced Cypher query for Neo4j backend
await cipher_query_graph ({
query: `
MATCH (service:Service)-[r:USES]->(api:API)
WHERE api.type = 'external' AND r.frequency > $minFreq
RETURN service.name, api.name, r.frequency
ORDER BY r.frequency DESC
` ,
parameters: { minFreq: 10 },
queryType: "cypher" ,
limit: 20
});
// Bulk relationship management
await cipher_relationship_manager ({
instruction: "Replace all references to 'oldPaymentAPI' with 'newStripeAPI'" ,
operation: "replace_entity" ,
targets: {
sourceEntity: "oldPaymentAPI" ,
targetEntity: "newStripeAPI"
}
});
Development Workflow Integration
// 1. Extract entities from commit messages
await cipher_extract_entities ({
text: "feat: implement user profile service with MongoDB integration" ,
options: {
entityTypes: [ "Service" , "Database" , "Feature" ],
autoLink: true
}
});
// 2. Search for similar implementations
await cipher_search_graph ({
searchType: "nodes" ,
nodeLabels: [ "Service" ],
properties: { database: "MongoDB" },
textSearch: "profile"
});
// 3. Track architectural changes over time
await cipher_update_node ({
nodeId: "service_user_profile" ,
properties: {
version: "2.1.0" ,
last_updated: Date . now (),
migration_status: "completed"
}
});
Best Practices
Use cipher_enhanced_search
for natural language queries, cipher_search_graph
for structured searches
Use cipher_extract_entities
for automatic entity extraction from text content
Use cipher_intelligent_processor
for complex natural language operations
Entity Design
Meaningful IDs : Use descriptive identifiers (e.g., func_calculate_total
, class_math_utils
)
Multiple labels : Assign relevant labels for categorization (["Function", "Code", "TypeScript"]
)
Rich properties : Include metadata (file paths, timestamps, confidence scores)
Set limits : Always use appropriate limits (50-100 for searches, 10-25 for neighbors)
Neo4j for production : Use Neo4j backend for >1000 entities, in-memory for development
Enable debug logging : Set CIPHER_LOG_LEVEL=debug
for detailed tool execution logs
Knowledge graph operations require both source and target nodes to exist before creating edges. Always verify node existence or use cipher_intelligent_processor
for automatic entity creation.