Skip to main content
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:

Tool Operation Flow

The knowledge graph tools follow a systematic approach to entity and relationship management:

Available Tools

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 AddNodeInput {
  id: string;              // Unique identifier
  labels: string[];        // Array of labels/types
  properties?: Record<string, any>; // Optional properties
}
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 AddEdgeInput {
  sourceId: string;        // Source node ID
  targetId: string;        // Target node ID
  edgeType: string;        // Relationship type
  properties?: Record<string, any>; // Optional properties
}
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.
interface UpdateNodeInput {
  nodeId: string;          // Node ID to update
  properties: Record<string, any>; // Properties to update/merge
  labels?: string[];       // Optional new labels
}
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.
interface DeleteNodeInput {
  id: string;              // Node ID to delete
}
await cipher_delete_node({
  id: "deprecated_function"
});

Search and Query Operations

cipher_search_graph

Searches for nodes and edges with filtering capabilities.
interface SearchGraphInput {
  searchType?: 'nodes' | 'edges' | 'both'; // Default: 'both'
  nodeLabels?: string[];    // Filter by node labels
  edgeTypes?: string[];     // Filter by edge types
  properties?: Record<string, any>; // Property filters
  textSearch?: string;      // Full-text search
  limit?: number;           // Max results (1-1000, default: 50)
}
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 GetNeighborsInput {
  nodeId: string;          // Node to get neighbors for
  direction?: 'in' | 'out' | 'both'; // Default: 'both'
  edgeTypes?: string[];    // Filter by edge types
  limit?: number;          // Max neighbors (1-100, default: 10)
}
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.
interface QueryGraphInput {
  query: string;           // Query string
  queryType?: 'node' | 'edge' | 'path' | 'cypher'; // Default: 'cypher'
  parameters?: Record<string, any>; // Query parameters
  limit?: number;          // Max results (1-1000, default: 100)
}
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
});
await cipher_query_graph({
  query: "labels: [Function], properties: {optimized: true}",
  queryType: "node",
  limit: 25
});

Advanced Operations

cipher_extract_entities

Extracts entities from text and adds them to the knowledge graph.
interface ExtractEntitiesInput {
  text: string;            // Text to extract entities from
  options?: {
    entityTypes?: string[]; // Focus on specific entity types
    autoLink?: boolean;     // Auto-create relationships (default: true)
    linkTypes?: string[];   // Relationship types to create
  };
}
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"]
  }
});
Advanced search with semantic capabilities and fuzzy matching.
interface EnhancedSearchInput {
  query: string;           // Search query (natural language supported)
  searchType?: 'nodes' | 'edges' | 'both' | 'auto'; // Default: 'auto'
  options?: {
    semanticSearch?: boolean;     // Enable LLM-powered search (default: true)
    fuzzyMatching?: boolean;      // Enable fuzzy matching (default: true)
    fuzzyThreshold?: number;      // Fuzzy threshold 0.0-1.0 (default: 0.6)
    includeRelated?: boolean;     // Include related entities (default: true)
    relationDepth?: number;       // Relation depth 1-3 (default: 2)
    searchProperties?: string[];  // Properties to search
    naturalLanguage?: boolean;    // Natural language understanding (default: true)
  };
  limit?: number;          // Max results (1-1000, default: 50)
}
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.
interface IntelligentProcessorInput {
  text: string;            // Natural language text to process
  options?: {
    autoResolve?: boolean;           // Auto-resolve conflicts (default: true)
    confidenceThreshold?: number;   // Confidence threshold 0.0-1.0 (default: 0.7)
    autoCreateRelationships?: boolean; // Auto-create relationships (default: true)
    context?: string;                // Additional context
    previousContext?: string;        // Previous conversation context
  };
}
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.
interface RelationshipManagerInput {
  instruction: string;     // Natural language instruction
  operation?: 'replace_entity' | 'update_relationship' | 'merge_entities' | 
             'delete_relationships' | 'bulk_update' | 'conditional_update' | 'auto';
  targets?: {
    sourceEntity?: string;
    targetEntity?: string;
    relationshipType?: string;
    criteria?: Record<string, any>;
  };
  options?: {
    preserveHistory?: boolean;       // Preserve operation history (default: true)
    confidenceThreshold?: number;   // Confidence threshold (default: 0.8)
    autoResolveConflicts?: boolean; // Auto-resolve conflicts (default: true)
    bulkLimit?: number;             // Bulk operation limit (default: 100)
    validateRelationships?: boolean; // Validate relationships (default: true)
  };
}
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

// 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
  }
});
// 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"
  }
});
// 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

Tool Selection

  • 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)

Performance

  • 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.
I