### Setup Joern for Code Analysis Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Installs Joern, a tool for code analysis, which is recommended for advanced features like security scanning and dead code detection. This command checks for JDK, downloads Joern, and verifies the installation. ```bash knowgraph-setup-joern ``` -------------------------------- ### Install and Setup KnowGraph Source: https://context7.com/yunusgungor/knowgraph/llms.txt Installs the KnowGraph Python package and optionally sets up Joern for advanced code analysis. It also shows how to verify the installation and set the API key for LLM features. ```bash pip install knowgraph knowgraph --version # Output: KnowGraph 1.0.0 knowgraph-setup-joern export KNOWGRAPH_API_KEY="sk-your-openai-key-here" ``` -------------------------------- ### Development Installation Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Instructions for setting up KnowGraph for development purposes, including cloning the repository, installing development dependencies, setting up Joern, and running tests and code quality checks. ```bash git clone https://github.com/yunusgungor/knowgraph.git cd knowgraph pip install -e ".[dev]" knowgraph-setup-joern # Run tests pytest # Check code quality ruff check . mypy . ``` -------------------------------- ### Install and Verify MCP Server Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Installs the KnowGraph MCP server using pip and verifies the installation by checking the version. This is the recommended method for setting up the server. ```bash pip install knowgraph knowgraph --version # Output: KnowGraph 1.0.0 ``` -------------------------------- ### OpenRouter Configuration Example Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Example environment variable settings for configuring KnowGraph to use OpenRouter as the API base URL, specifying a model, and setting the API key. ```bash export KNOWGRAPH_API_BASE_URL="https://openrouter.ai/api/v1" export KNOWGRAPH_LLM_MODEL="x-ai/grok-2-1212" export KNOWGRAPH_API_KEY="sk-or-v1-your-key-here" ``` -------------------------------- ### Installation and Setup Source: https://context7.com/yunusgungor/knowgraph/llms.txt Instructions for installing KnowGraph via pip and setting up Joern for advanced code analysis. Also includes setting the API key for LLM features. ```APIDOC ## Installation and Setup Install KnowGraph via pip and optionally set up Joern for advanced code analysis. ```bash # Install KnowGraph pip install knowgraph # Verify installation knowgraph --version # Output: KnowGraph 1.0.0 # Setup Joern for advanced code analysis (recommended) knowgraph-setup-joern # Set API key for LLM features export KNOWGRAPH_API_KEY="sk-your-openai-key-here" ``` ``` -------------------------------- ### Install JDK 11 for Joern Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Provides commands to install OpenJDK 11 on macOS and Ubuntu/Debian systems, which is a prerequisite for Joern code analysis. Includes verification step. ```bash # macOS brew install openjdk@11 # Ubuntu/Debian sudo apt-get install openjdk-11-jdk # Verify java -version ``` -------------------------------- ### Install KnowGraph and Setup Joern Source: https://github.com/yunusgungor/knowgraph/blob/main/README.md Installs the KnowGraph Python package and sets up the Joern tool for advanced code analysis. Joern is a prerequisite for deep code understanding and security analysis features. ```bash pip install knowgraph # Setup Joern for advanced code analysis (recommended) knowgraph-setup-joern ``` -------------------------------- ### AI Client Configuration Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Configuration examples for integrating KnowGraph with AI clients like Claude Desktop and Cursor. ```APIDOC ## AI Client Configuration ### Description Examples of how to configure AI clients to use the KnowGraph MCP server. ### Claude Desktop (`claude_desktop_config.json`) ```json { "mcpServers": { "knowgraph": { "command": "knowgraph", "args": ["serve"], "env": { "KNOWGRAPH_API_KEY": "sk-your-openai-key-here" } } } } ``` ### Cursor (`.cursor/mcp.json`) ```json { "mcpServers": { "knowgraph": { "command": "knowgraph", "args": ["serve"], "env": { "KNOWGRAPH_API_KEY": "sk-your-openai-key-here" } } } } ``` ``` -------------------------------- ### Standalone CLI Usage Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Demonstrates how to use KnowGraph as a standalone CLI tool without an AI editor. This includes setting the API key, indexing a project, querying the knowledge base, and starting the MCP server. ```bash # Set API key export KNOWGRAPH_API_KEY="sk-..." # Index a project knowgraph index ./my-project # Query from CLI knowgraph query "How does authentication work?" # Start standalone MCP server knowgraph serve ``` -------------------------------- ### Environment Variable Configuration (Future) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/CONFIGURATION.md Example of environment variables for configuring KnowGraph parameters. This section outlines future enhancements where settings like maximum workers, cache size, and memory warning thresholds can be managed externally via a `.env` file. ```bash # .env (not yet implemented - future enhancement) KNOWGRAPH_MAX_WORKERS=10 KNOWGRAPH_CACHE_SIZE=1000 KNOWGRAPH_MEMORY_WARNING_MB=500 KNOWGRAPH_MEMORY_CRITICAL_MB=1000 ``` -------------------------------- ### Balanced Configuration Template Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/CONFIGURATION.md A balanced configuration suitable for most deployments, including development machines and general-purpose servers (16GB RAM). This template provides moderate values for memory thresholds, concurrency, batch sizes, and cache size, offering a good starting point for various use cases. ```python # memory_profiler (defaults) WARNING_THRESHOLD_MB = 500 CRITICAL_THRESHOLD_MB = 1000 # concurrency (defaults) MAX_CONCURRENT_CONVERSATIONS = 10 BOOKMARK_BATCH_SIZE = 10 # cache (default) LRU_CACHE_SIZE = 1000 # parallel (default) MAX_NODE_LOADING_WORKERS = 10 ``` -------------------------------- ### Python: Execute Batch Queries with KnowGraph Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This Python example illustrates how to efficiently execute multiple queries simultaneously using KnowGraph's `batch_query` method. This approach significantly reduces latency compared to sequential querying by sharing context loading. ```python from knowgraph.application.querying.engine import QueryEngine engine = QueryEngine() results = engine.batch_query([ "How does authentication work?", "What are the security policies?", "Explain the rate limiting logic", "Show me the caching strategy", "What's the database schema?" ]) for query, result in zip(queries, results): print(f"Q: {query}") print(f"A: {result.answer}\n") ``` -------------------------------- ### Index Project with KnowGraph CLI Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Indexes the current project using the KnowGraph command-line interface. This command requires setting the KNOWGRAPH_API_KEY environment variable and specifies the path to the project to be indexed. ```bash export KNOWGRAPH_API_KEY="sk-your-openai-key-here" knowgraph index ./your-project ``` -------------------------------- ### Post-Indexing Automation (Hooks) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Understand and leverage the automated 'Hooks' that run after successful indexing operations to enrich your knowledge graph. ```APIDOC ## Post-Indexing Automation KnowGraph runs a series of "Hooks" after every successful indexing job. ### How Hooks Work Hooks are Python scripts that subscribe to the `INDEXING_COMPLETE` event. They run in the background to enrich the graph. ### Available Hooks 1. **ConversationLinker**: * Scans indexed conversations. * Finds file references (e.g., `src/auth.py`). * Creates semantic edges between the *Conversation Node* and the *Code Node*. * *Benefit*: When you query `auth.py`, you also get the discussions regarding `auth.py`. 2. **AutoTagger**: * Analyzes the content of new nodes. * Assigns tags like `security`, `database`, `api`, `frontend` based on keywords and embeddings. * *Benefit*: Enables filtered queries like "Show me all security-related nodes". 3. **AnalyticsGenerator**: * Calculates graph statistics (density, diameter). * Updates the dashboard metrics. ### Configuration Hooks are enabled by default. You can disable them in `knowgraph.json` configuration (future feature). ``` -------------------------------- ### Basic Query with QueryEngine in Python Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This Python snippet demonstrates how to perform a basic query using the KnowGraph QueryEngine. It initializes the engine and sends a natural language query, then prints the AI-generated answer. ```python from knowgraph.application.querying.engine import QueryEngine engine = QueryEngine() result = engine.query("How does auth work?") print(result.answer) ``` -------------------------------- ### Python API: QueryEngine - Synchronous Query Source: https://context7.com/yunusgungor/knowgraph/llms.txt Use the QueryEngine class for programmatic querying with full control over parameters. This example demonstrates a synchronous query. ```APIDOC ## Python API: QueryEngine - Synchronous Query ### Description Use the QueryEngine class for programmatic querying with full control over parameters. This example demonstrates a synchronous query. ### Method Not Applicable (Python Class Method) ### Endpoint Not Applicable (Python Class Method) ### Parameters #### Initialization - **graph_store_path** (Path) - Required - The path to the graph store directory. #### Query Method Parameters - **query_text** (string) - Required - The natural language query to execute. - **top_k** (integer) - Optional - The number of top results to retrieve. Defaults to 10. - **max_hops** (integer) - Optional - The maximum number of hops to traverse in the graph. Defaults to 4. - **max_tokens** (integer) - Optional - The maximum number of tokens for the answer. Defaults to 1000. - **with_explanation** (boolean) - Optional - Whether to include an explanation for the answer. Defaults to False. - **enable_hierarchical_lifting** (boolean) - Optional - Whether to enable hierarchical lifting. Defaults to False. - **lift_levels** (integer) - Optional - The number of levels to lift for hierarchical lifting. Defaults to 1. ### Request Example ```python from knowgraph.application.querying.query_engine import QueryEngine from pathlib import Path # Initialize engine with graph store path engine = QueryEngine(Path("./graphstore")) # Synchronous query result = engine.query( query_text="How does authentication work?", top_k=20, max_hops=4, max_tokens=3000, with_explanation=True, enable_hierarchical_lifting=True, lift_levels=2 ) print(f"Answer: {result.answer}") print(f"Nodes retrieved: {result.active_subgraph_size}") print(f"Execution time: {result.execution_time:.2f}s") print(f"Cache hit: {result.sparse_search_time < 0.01}") # Access explanation if requested if result.explanation: print(f"Reasoning: {result.explanation.to_dict()}") ``` ### Response #### Success Response (200) - **answer** (string) - The answer to the query. - **active_subgraph_size** (integer) - The number of nodes in the active subgraph. - **execution_time** (float) - The time taken to execute the query in seconds. - **sparse_search_time** (float) - The time taken for sparse search. - **explanation** (object, optional) - An object containing the reasoning for the answer, if requested. - **to_dict** (method) - Method to convert the explanation to a dictionary. #### Response Example ```json { "answer": "Authentication works by verifying user credentials against a stored record.", "active_subgraph_size": 15, "execution_time": 0.52, "sparse_search_time": 0.005, "explanation": { "reasoning": "User credentials are checked against the database." } } ``` ``` -------------------------------- ### KnowGraph Versioning and History Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Manage and inspect different versions of the knowledge graph. ```APIDOC ## GET /knowgraph/list_versions ### Description Shows the complete version history of the knowledge graph. ### Method GET ### Endpoint /knowgraph/list_versions ### Response #### Success Response (200) - **versions** (array) - A list of version IDs and associated metadata. #### Response Example ```json { "versions": [ {"id": "v1.0.0", "timestamp": "2023-10-27T10:00:00Z"}, {"id": "v1.0.1", "timestamp": "2023-10-27T11:00:00Z"} ] } ``` ``` ```APIDOC ## GET /knowgraph/version_info ### Description Gets detailed metadata for a specific version ID. ### Method GET ### Endpoint /knowgraph/version_info ### Parameters #### Query Parameters - **version_id** (string) - Required - The ID of the version to retrieve information for. ### Response #### Success Response (200) - **version_details** (object) - Detailed metadata for the specified version. #### Response Example ```json { "version_details": { "id": "v1.0.1", "timestamp": "2023-10-27T11:00:00Z", "commit_hash": "abcdef12345" } } ``` ``` ```APIDOC ## POST /knowgraph/diff_versions ### Description Compares nodes and edges between two specified commits. ### Method POST ### Endpoint /knowgraph/diff_versions ### Parameters #### Request Body - **version1_id** (string) - Required - The ID of the first version. - **version2_id** (string) - Required - The ID of the second version. ### Response #### Success Response (200) - **diff_report** (string) - A report detailing the differences between the two versions. #### Response Example ```json { "diff_report": "Version v1.0.1 has 10 new nodes and 5 removed edges compared to v1.0.0." } ``` ``` ```APIDOC ## POST /knowgraph/rollback ### Description Reverts the knowledge graph state to a previous snapshot identified by a version ID. ### Method POST ### Endpoint /knowgraph/rollback ### Parameters #### Request Body - **version_id** (string) - Required - The ID of the version to roll back to. ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the rollback operation. #### Response Example ```json { "message": "Successfully rolled back to version v1.0.0." } ``` ``` -------------------------------- ### Basic Project Indexing Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Command to perform basic indexing of a project directory using KnowGraph. This command initiates the process of analyzing and storing the project's knowledge. ```bash knowgraph index /path/to/project ``` -------------------------------- ### Performance Optimization Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Information on KnowGraph's caching system and strategies for optimizing performance based on your specific workload. ```APIDOC ## Performance Optimization KnowGraph is designed for high performance, but you can tune it further based on your workload. ### Caching System KnowGraph uses multiple caching layers for optimal performance. ``` -------------------------------- ### KnowGraph Graph Versioning Commands Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Commands for managing graph versions in KnowGraph, enabling Git-like version control for the knowledge graph. This includes listing, diffing, and rolling back to previous states. ```bash $ knowgraph version list knowgraph version diff v0.6.0-a1 v0.6.1-b2 # Dry run to see what will happen knowgraph version rollback v0.6.0-a1 --dry-run # Execute rollback knowgraph version rollback v0.6.0-a1 ``` -------------------------------- ### Restore Manifest from Backup Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This command restores the KnowGraph manifest file from a backup. It is a solution for corrupted manifest files, ensuring the integrity of versioning information. ```bash cp ./graphstore/metadata/manifest.json.backup ./graphstore/metadata/manifest.json ``` -------------------------------- ### Perform Incremental Indexing (Bash) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Bash commands illustrating the process of incremental indexing in KnowGraph. Shows a full initial index followed by a much faster re-index after modifying a file, highlighting the efficiency of only processing changed files. ```bash # First index (full) knowgraph index ./project # 30s # Modify 2 files echo "# New content" >> ./project/auth.py # Re-index (incremental) knowgraph index ./project # 3s (only processes auth.py) ``` -------------------------------- ### Perform Batch Queries Asynchronously (Python) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Python code demonstrating how to perform multiple queries concurrently using `QueryEngine.batch_query_async`. This asynchronous approach significantly speeds up query processing compared to sequential execution. ```python import asyncio from knowgraph.application.querying.engine import QueryEngine async def main(): engine = QueryEngine() # Parallel execution (4x faster) results = await engine.batch_query_async([ "How does auth work?", "What are the API endpoints?", "Explain the database schema", "Show me error handling" ]) for result in results: print(result.answer) asyncio.run(main()) ``` -------------------------------- ### KnowGraph System Diagnostics Expected Output Source: https://context7.com/yunusgungor/knowgraph/llms.txt Example output from the 'knowgraph diagnostic' command, indicating the status of various system components. This helps in verifying the health and operational readiness of the KnowGraph instance. ```text Graph Store: OK LLM Provider: OK (OpenAI) Joern: OK (v2.0.0) Configuration: Valid ``` -------------------------------- ### Monitor Query Performance (Python) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Python code to retrieve and display performance metrics for a specific query using `QueryEngine`. It shows how to access query time, the number of nodes retrieved, and whether the cache was hit. ```python from knowgraph.application.querying.engine import QueryEngine engine = QueryEngine() result = engine.query("How does caching work?") print(f"Query time: {result.metadata['query_time_ms']}ms") print(f"Nodes retrieved: {result.metadata['nodes_count']}") print(f"Cache hit: {result.metadata['cache_hit']}") ``` -------------------------------- ### Environment Variable Loading in Python Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/CONFIGURATION.md Python code demonstrating how to load configuration values from environment variables, with default fallbacks. This approach allows for dynamic configuration without modifying the codebase directly, enhancing flexibility for production deployments. ```python import os MAX_WORKERS = int(os.getenv("KNOWGRAPH_MAX_WORKERS", "10")) CACHE_SIZE = int(os.getenv("KNOWGRAPH_CACHE_SIZE", "1000")) ``` -------------------------------- ### Index and Query Endpoints for MCP Server Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/ARCHITECTURE.md Demonstrates how to use the index and query endpoints of the MCP server for graph indexing and query handling. It shows asynchronous method calls for processing code directories and handling user queries. ```python import methods # Index endpoint await methods.index_graph( input_path=path, graph_path=graph, provider=provider, resume_mode=False, gc=True ) # Query endpoint result = await methods.handle_query({ 'query': query_text, 'graph_path': graph_path }) ``` -------------------------------- ### JSON: Default and Custom Edge Type Weights in KnowGraph Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This example shows default edge type weights used in KnowGraph for graph traversal, where each relationship type has a standard weight of 1.0. It also provides a custom weighting example, prioritizing 'inherit' relationships and de-prioritizing 'import' relationships. ```json { "import": 1.0, # Standard import relationships "call": 1.0, # Function calls "inherit": 1.0, # Class inheritance "data_flow": 1.0, # Data dependencies "reference": 1.0 # Documentation references } ``` ```json { "query": "Find inheritance structure of BaseClass", "edge_type_weights": { "inherit": 2.0, # Prioritize inheritance (2x weight) "import": 0.5, # De-prioritize imports "call": 1.0 # Normal weight for calls } } ``` -------------------------------- ### Kill Joern Process Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This command forcefully terminates any running Joern processes. It is a solution for issues where the Joern daemon fails to start, ensuring a clean restart. ```bash pkill -f joern ``` -------------------------------- ### MCP Server Configuration for Cursor Source: https://context7.com/yunusgungor/knowgraph/llms.txt Configuration details for setting up KnowGraph in Cursor IDE. ```APIDOC ## MCP Server Configuration for Cursor Configure KnowGraph in Cursor IDE by adding to `.cursor/mcp.json` in your project. ```json { "mcpServers": { "knowgraph": { "command": "knowgraph", "args": ["serve"], "env": { "KNOWGRAPH_API_BASE_URL": "https://openrouter.ai/api/v1", "KNOWGRAPH_LLM_MODEL": "x-ai/grok-4.1-fast", "KNOWGRAPH_API_KEY": "sk-or-v1-your-openrouter-key-here" } } } } ``` ``` -------------------------------- ### KnowGraph Querying Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Perform semantic searches and advanced queries on the knowledge graph. Supports fine-tuning with weighting parameters. ```APIDOC ## POST /knowgraph/query ### Description Performs semantic search on the knowledge graph. Allows for advanced query tuning using parameters like `top_k`, `max_hops`, and `edge_type_weights`. ### Method POST ### Endpoint /knowgraph/query ### Parameters #### Request Body - **query** (string) - Required - The natural language query to execute. - **top_k** (integer) - Optional - The number of top results to return. - **max_hops** (integer) - Optional - The maximum number of hops to traverse in the graph. - **edge_type_weights** (object) - Optional - Custom weights for different edge types. - **inherit** (float) - Weight for inheritance edges. - **import** (float) - Weight for import edges. - **call** (float) - Weight for call edges. - **prioritize_reference_edges** (boolean) - Optional - Whether to prioritize reference edges. - **enable_hierarchical_lifting** (boolean) - Optional - Whether to enable hierarchical lifting. - **lift_levels** (integer) - Optional - The number of levels for hierarchical lifting. ### Request Example ```json { "query": "Find inheritance structure of BaseClass", "top_k": 20, "max_hops": 4, "edge_type_weights": { "inherit": 1.5, "import": 0.8, "call": 1.0 }, "prioritize_reference_edges": true, "enable_hierarchical_lifting": true, "lift_levels": 3 } ``` ### Response #### Success Response (200) - **answer** (string) - The answer to the query. #### Response Example ```json { "answer": "The inheritance structure of BaseClass includes..." } ``` ``` ```APIDOC ## POST /knowgraph/batch_query ### Description Executes multiple queries efficiently for context gathering. ### Method POST ### Endpoint /knowgraph/batch_query ### Parameters #### Request Body - **queries** (array) - Required - An array of query strings. ### Request Example ```json { "queries": [ "How does auth work?", "Explain caching mechanism." ] } ``` ### Response #### Success Response (200) - **results** (array) - An array of answers corresponding to the input queries. #### Response Example ```json { "results": [ "Auth works by...", "Caching works by..." ] } ``` ``` -------------------------------- ### Synchronous Query with QueryEngine (Python) Source: https://context7.com/yunusgungor/knowgraph/llms.txt Demonstrates synchronous querying using the QueryEngine class. It initializes the engine with a graph store path and performs a query with various parameters like 'query_text', 'top_k', 'max_hops', and 'with_explanation'. ```python from knowgraph.application.querying.query_engine import QueryEngine from pathlib import Path # Initialize engine with graph store path engine = QueryEngine(Path("./graphstore")) # Synchronous query result = engine.query( query_text="How does authentication work?", top_k=20, max_hops=4, max_tokens=3000, with_explanation=True, enable_hierarchical_lifting=True, lift_levels=2 ) print(f"Answer: {result.answer}") print(f"Nodes retrieved: {result.active_subgraph_size}") print(f"Execution time: {result.execution_time:.2f}s") print(f"Cache hit: {result.sparse_search_time < 0.01}") # Access explanation if requested if result.explanation: print(f"Reasoning: {result.explanation.to_dict()}") ``` -------------------------------- ### Pro Tips for the AI Agent Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/AI_EDITOR_RULES.md Advanced usage tips for AI agents interacting with the KnowGraph system, including querying strategies, topic modeling, pattern matching, and indexing efficiency. ```APIDOC ## 💎 6. Pro Tips for the AI Agent ### Description Tips for optimizing AI agent interactions with KnowGraph. ### Tips - **The "Double-Tap"**: For critical questions, query twice with different phrasings (conceptual then literal). - **Topic Modeling**: Use `knowgraph_analyze_conversations(topic="security")` to track concept evolution. - **Pattern Matching**: Use `knowgraph_analyze_impact(element="User Authentication", mode="semantic")` for logical concept matching. - **Live Indexing**: Proactively call `knowgraph_index(input_path=file_path)` when a file is significantly edited. - **Incremental Intelligence**: Caching and MD5 checks are automatic; manual CPG regeneration is rarely needed. - **Daemon Awareness**: Monitor `JoernDaemon` for query performance; the first query may take longer. - **Noise Filtering**: Use `exclude_patterns` in `knowgraph_index` for large repos (e.g., `exclude_patterns=["*.lock", "node_modules/*"]`). - **Batch Efficiency**: Use `knowgraph_batch_query` for multiple related questions (~15x faster). ``` -------------------------------- ### KnowGraph Indexing Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Index local or remote codebases to build the knowledge graph. Caching is used for faster re-indexing. ```APIDOC ## POST /knowgraph/index ### Description Triggers indexing of local or remote codebases to build the knowledge graph. Supports caching for incremental updates and parallel generation for large repositories. ### Method POST ### Endpoint /knowgraph/index ### Parameters #### Query Parameters - **path** (string) - Required - The path to the codebase to index. ### Request Example ```bash knowgraph index ./my-app ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the indexing process has started or completed. #### Response Example ```json { "message": "Indexing started for ./my-app" } ``` ``` -------------------------------- ### KnowGraph Diagnostic and Health Checks Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Perform diagnostic checks on the KnowGraph system, including the graph store, LLM, and configuration. ```APIDOC ## GET /knowgraph/diagnostic ### Description Runs system health checks on the Graph Store, LLM, and configuration. ### Method GET ### Endpoint /knowgraph/diagnostic ### Response #### Success Response (200) - **diagnostic_results** (object) - Results of the diagnostic checks. #### Response Example ```json { "diagnostic_results": { "graph_store": "OK", "llm": "Connected", "config": "Valid" } } ``` ``` -------------------------------- ### Asynchronous Query Execution with QueryEngine (Python) Source: https://context7.com/yunusgungor/knowgraph/llms.txt Shows how to execute queries asynchronously using QueryEngine. It covers single async queries with timeouts and batch queries for improved performance, including a progress callback. ```python import asyncio from knowgraph.application.querying.query_engine import QueryEngine from pathlib import Path async def main(): engine = QueryEngine(Path("./graphstore")) # Single async query with timeout result = await engine.query_async( query_text="Explain the caching strategy", top_k=20, max_hops=4, timeout=30.0 ) print(f"Answer: {result.answer}") # Batch queries for 4x faster performance results = await engine.batch_query_async( queries=[ "How does auth work?", "What are the API endpoints?", "Explain the database schema", "Show me error handling patterns" ], batch_size=5, progress_callback=lambda current, total: print(f"Progress: {current}/{total}") ) for i, r in enumerate(results): print(f"Query {i+1}: {r.active_subgraph_size} nodes, {r.execution_time:.2f}s") asyncio.run(main()) ``` -------------------------------- ### MCP Server Configuration for Claude Desktop Source: https://context7.com/yunusgungor/knowgraph/llms.txt Configuration details for setting up KnowGraph as an MCP server in Claude Desktop. ```APIDOC ## MCP Server Configuration for Claude Desktop Configure KnowGraph as an MCP server in Claude Desktop for AI-assisted code understanding. ```json { "mcpServers": { "knowgraph": { "command": "knowgraph", "args": ["serve"], "env": { "KNOWGRAPH_API_KEY": "sk-your-openai-key-here" } } } } ``` Save this configuration to `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS. ``` -------------------------------- ### KnowGraph Analysis Tools Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Provides various tools for code analysis, including security scanning, dead code detection, and call graph analysis. ```APIDOC ## POST /knowgraph/analyze_impact ### Description Predicts the effects of code changes using Semantic or Path mode. ### Method POST ### Endpoint /knowgraph/analyze_impact ### Parameters #### Request Body - **mode** (string) - Required - Analysis mode ('Semantic' or 'Path'). - **changes** (object) - Required - Details of code changes. ### Response #### Success Response (200) - **impact_report** (string) - A report detailing the predicted impact of the code changes. #### Response Example ```json { "impact_report": "The changes may affect the following modules..." } ``` ``` ```APIDOC ## GET /knowgraph/validate ### Description Checks the health and consistency of the knowledge graph. ### Method GET ### Endpoint /knowgraph/validate ### Response #### Success Response (200) - **validation_status** (string) - The status of the graph validation (e.g., 'Healthy', 'Inconsistent'). #### Response Example ```json { "validation_status": "Healthy" } ``` ``` ```APIDOC ## GET /knowgraph/get_stats ### Description Retrieves statistics about the knowledge graph, including node and edge counts and density metrics. ### Method GET ### Endpoint /knowgraph/get_stats ### Response #### Success Response (200) - **stats** (object) - An object containing graph statistics. - **node_count** (integer) - Total number of nodes. - **edge_count** (integer) - Total number of edges. - **density** (float) - Graph density. #### Response Example ```json { "stats": { "node_count": 150000, "edge_count": 500000, "density": 0.00002 } } ``` ``` ```APIDOC ## POST /knowgraph/joern_query ### Description Executes native Joern DSL queries against the code's CPG. ### Method POST ### Endpoint /knowgraph/joern_query ### Parameters #### Request Body - **query** (string) - Required - The Joern query string. ### Request Example ```json { "query": "cfg.nodes.name(\"main\").cfgNext.l" } ``` ### Response #### Success Response (200) - **results** (array) - The results of the Joern query. #### Response Example ```json { "results": [ "node1", "node2" ] } ``` ``` ```APIDOC ## POST /knowgraph/security_scan ### Description Scans for security vulnerabilities using Joern policies. ### Method POST ### Endpoint /knowgraph/security_scan ### Parameters #### Request Body - **policy** (string) - Optional - The Joern policy to use for scanning. ### Response #### Success Response (200) - **vulnerabilities** (array) - A list of detected security vulnerabilities. #### Response Example ```json { "vulnerabilities": [ { "type": "SQL Injection", "location": "src/user.py:123" } ] } ``` ``` ```APIDOC ## POST /knowgraph/find_dead_code ### Description Detects unreachable methods using dominance analysis. ### Method POST ### Endpoint /knowgraph/find_dead_code ### Response #### Success Response (200) - **dead_code_report** (string) - A report listing detected dead code. #### Response Example ```json { "dead_code_report": "The following methods are unreachable: methodA, methodB" } ``` ``` ```APIDOC ## POST /knowgraph/analyze_call_graph ### Description Analyzes call paths and recursion within the codebase. ### Method POST ### Endpoint /knowgraph/analyze_call_graph ### Response #### Success Response (200) - **call_graph_analysis** (string) - An analysis of the call graph. #### Response Example ```json { "call_graph_analysis": "Call graph analysis complete. Found 5 recursive calls." } ``` ``` ```APIDOC ## POST /knowgraph/export_cpg ### Description Exports the Code Property Graph (CPG) to various formats like JSON, DOT, Neo4j, or SARIF. ### Method POST ### Endpoint /knowgraph/export_cpg ### Parameters #### Request Body - **format** (string) - Required - The desired export format (e.g., 'JSON', 'DOT', 'Neo4j', 'SARIF'). - **output_path** (string) - Required - The path to save the exported CPG. ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the export process. #### Response Example ```json { "message": "CPG exported successfully to output.json" } ``` ``` ```APIDOC ## POST /knowgraph/generate_cpg ### Description Manually triggers CPG generation for a specified path. ### Method POST ### Endpoint /knowgraph/generate_cpg ### Parameters #### Request Body - **path** (string) - Required - The path for which to generate the CPG. ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating CPG generation has started. #### Response Example ```json { "message": "CPG generation started for path: /path/to/code" } ``` ``` -------------------------------- ### Memory-Constrained Configuration Template Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/CONFIGURATION.md Configuration settings designed for memory-constrained environments (2GB RAM), such as Docker containers, Lambda functions, or edge devices. This template features significantly reduced memory thresholds, lower concurrency limits, smaller batch sizes, and a minimal LRU cache size to conserve resources. ```python # memory_profiler WARNING_THRESHOLD_MB = 200 CRITICAL_THRESHOLD_MB = 500 # concurrency MAX_CONCURRENT_CONVERSATIONS = 5 BOOKMARK_BATCH_SIZE = 5 # cache LRU_CACHE_SIZE = 500 # parallel MAX_NODE_LOADING_WORKERS = 5 ``` -------------------------------- ### Validate KnowGraph Index Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This command validates the integrity of the KnowGraph index. It can help identify issues like orphaned nodes, which may require re-indexing to resolve. ```bash knowgraph validate ``` -------------------------------- ### High-Memory Server Configuration Template Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/CONFIGURATION.md Configuration settings optimized for a high-memory server (64GB RAM). This template includes higher thresholds for memory warnings and critical errors, increased concurrent conversations, larger batch sizes, and a substantial LRU cache size, suitable for high-traffic production environments. ```python # memory_profiler WARNING_THRESHOLD_MB = 2000 CRITICAL_THRESHOLD_MB = 5000 # concurrency MAX_CONCURRENT_CONVERSATIONS = 20 BOOKMARK_BATCH_SIZE = 20 # cache LRU_CACHE_SIZE = 5000 # parallel MAX_NODE_LOADING_WORKERS = 20 ``` -------------------------------- ### Conversational Memory Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Integrate AI assistant conversations into your knowledge graph. KnowGraph supports various conversation formats and allows for semantic tagging of important responses. ```APIDOC ## Conversational Memory KnowGraph can now "read" your conversations with AI assistants and link them to your code. ### Supported Formats - **Antigravity**: Task and Walkthrough artifacts. - **Cursor**: `.aichat` files in your project. - **VS Code**: GitHub Copilot chat exports. - **Claude**: JSON export files. ### Auto-Discovery Scan your project for conversation files and index them. #### Method POST #### Endpoint `/conversations/discover` #### Query Parameters - **editor** (string) - Optional - Filter by editor type ('all', 'cursor', 'antigravity'). - **min_date** (string) - Optional - Filter conversations from this date onwards (YYYY-MM-DD). - **output** (string) - Optional - Directory to output indexed conversations. #### Request Body None #### Response ##### Success Response (200) - **message** (string) - Confirmation message indicating the discovery and indexing process. ##### Response Example ```json { "message": "Found and indexed 5 conversation files." } ``` ### Semantic Tagging You can manually tag important AI responses using the MCP tool `knowgraph_tag_snippet` or CLI. **Example Use Case:** You ask Claude "How do I implement specific Retry Logic?". Claude gives a perfect answer. You don't want to lose this. **In Claude:** "Tag this response as 'Retry Logic Pattern' for future reference." Claude will call: ```json { "tool": "knowgraph_tag_snippet", "arguments": { "tag": "Retry Logic Pattern", "snippet": "...", "user_question": "How do I implement specific Retry Logic?" } } ``` Later, you can query: "Show me the Retry Logic Pattern we discussed." #### Method POST #### Endpoint `/snippets/tag` #### Request Body - **tag** (string) - Required - The tag to assign to the snippet. - **snippet** (string) - Required - The content of the AI response snippet. - **user_question** (string) - Required - The original user question that prompted the response. #### Response ##### Success Response (200) - **message** (string) - Confirmation message that the snippet has been tagged. ##### Response Example ```json { "message": "Snippet successfully tagged with 'Retry Logic Pattern'." } ``` ``` -------------------------------- ### KnowGraph Discover Conversations Command Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Command to automatically discover and index conversational data from various AI assistant formats. Supports filtering by editor type and date. ```bash knowgraph discover-conversations \ --editor all # or 'cursor', 'antigravity' --min-date 2024-01-01 # Optional date filter --output ./graphstore ``` -------------------------------- ### Repository Indexing with Include Filter Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Command to index a remote Git repository, specifying an include filter to process only specific file types (e.g., Python files). ```bash knowgraph index https://github.com/user/repo --include "*.py" ``` -------------------------------- ### CLI: Index Codebase to Build Knowledge Graph Source: https://context7.com/yunusgungor/knowgraph/llms.txt Builds a knowledge graph from local directories or Git repositories. Supports filtering files using include patterns and resuming incremental indexing for efficiency. ```bash # Index a local project directory knowgraph index ./my-project # Index a GitHub repository with file filtering knowgraph index https://github.com/user/repo --include "*.py" --include "*.js" # Index with custom output path knowgraph index ./my-project --output ./custom-graphstore # Resume incremental indexing (only processes changed files) knowgraph index ./my-project --resume ``` -------------------------------- ### Direct API for Code Indexing and Query Routing Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/ARCHITECTURE.md Illustrates the direct API usage for code analysis and query routing within the KnowGraph project. It shows instantiating and using `CodeIndexIntegration` for processing directories and `QueryClassifier` with `CodeQueryHandler` for query management. ```python from knowgraph.infrastructure.indexing import CodeIndexIntegration integration = CodeIndexIntegration() result = integration.process_code_directory(source_dir, graph_dir) from knowgraph.application.query import QueryClassifier, CodeQueryHandler classifier = QueryClassifier() query_type = classifier.classify(query) if query_type == QueryType.CODE: handler = CodeQueryHandler(graph_path) result = await handler.handle(query) ``` -------------------------------- ### Advanced Query Parameters Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This section details the advanced query parameters available for fine-tuning graph queries, including search depth, result count, and AI-driven query expansion. ```APIDOC ## Advanced Query Parameters Reference This section details the advanced query parameters available for fine-tuning graph queries. ### Parameters #### Query Parameters - **query** (string) - Required - Natural language query - **top_k** (int) - Optional - Number of results to return (default: 20) - **max_hops** (int) - Optional - Graph traversal depth (default: 4) - **max_tokens** (int) - Optional - Context window size (default: 3000) - **expand_query** (bool) - Optional - Enable AI query expansion (default: false) - **enable_hierarchical_lifting** (bool) - Optional - Include parent context (default: true) - **lift_levels** (int) - Optional - Parent directory levels (default: 2) - **with_explanation** (bool) - Optional - Include reasoning path (default: false) - **edge_type_weights** (dict) - Optional - Custom edge priorities (default: {}) - **prioritize_reference_edges** (bool) - Optional - Prefer documented code (default: false) ### Request Example ```json { "query": "What are the main components of the authentication system?", "top_k": 10, "max_hops": 5, "expand_query": true } ``` ### Response Example ```json { "results": [ { "node_id": "node123", "name": "Authentication Module", "description": "Handles user login and session management." } ], "explanation": "Traversed through the 'depends_on' edge from the main application to the authentication module." } ``` ``` -------------------------------- ### Python: Perform AI-powered Query Expansion in KnowGraph Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This Python snippet shows how to use the KnowGraph QueryEngine to expand a user's query with synonyms and technical terms. Setting `expand_query=True` enhances retrieval by broadening the search context, with a slight increase in query time. ```python from knowgraph.application.querying.engine import QueryEngine engine = QueryEngine() result = engine.query( "authentication mechanism", expand_query=True # Expands to: "auth, login, JWT, OAuth, session, token..." ) ``` -------------------------------- ### Automatic Code Analysis during Indexing Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Demonstrates how KnowGraph automatically detects and analyzes code in multiple languages when indexing a code directory. No explicit configuration is needed for supported languages. ```bash # Index any code directory - automatic code analysis knowgraph index ./my-project ``` -------------------------------- ### KnowGraph Performance Tunables (v1.0.0) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/CONFIGURATION.md Configuration constants for parallel processing and caching within KnowGraph. These include thresholds for file and language counts to trigger parallel generation, the maximum number of workers for parallel tasks, and the time-to-live for cached CPGs. ```python # Parallel Processing Thresholds (code_index_integration.py) PARALLEL_FILE_THRESHOLD = 50 # Use parallel gen if >50 files PARALLEL_LANG_THRESHOLD = 3 # Use parallel gen if >3 languages MAX_WORKERS = 4 # CPU cores for parallel generation # Cache Configuration CPG_CACHE_TTL_HOURS = 24 # Keep CPGs for 24 hours ``` -------------------------------- ### KnowGraph Query Parameters Reference Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Reference for advanced query parameters used in KnowGraph. These parameters allow fine-grained control over search results, graph traversal, and AI query expansion. ```text query (string, required): Natural language query. top_k (int, default 20): Number of results to return. max_hops (int, default 4): Graph traversal depth. max_tokens (int, default 3000): Context window size. expand_query (bool, default false): Enable AI query expansion. enable_hierarchical_lifting (bool, default true): Include parent context. lift_levels (int, default 2): Parent directory levels. with_explanation (bool, default false): Include reasoning path. edge_type_weights (dict, default {}): Custom edge priorities. prioritize_reference_edges (bool, default false): Prefer documented code. ``` -------------------------------- ### Dataflow Analysis with QueryEngine (Python) Source: https://context7.com/yunusgungor/knowgraph/llms.txt Demonstrates dataflow analysis using QueryEngine to trace paths between source and sink patterns, useful for security analysis. It allows specifying 'edge_types' and 'max_path_length'. ```python import asyncio from knowgraph.application.querying.query_engine import QueryEngine from pathlib import Path async def analyze_dataflow(): engine = QueryEngine(Path("./graphstore")) # Find how user input flows to database queries result = await engine.query_dataflow( source_pattern="user input from HTTP request", sink_pattern="SQL query execution", max_path_length=10, edge_types=["data_flow", "taint"] ) print(f"Source: {result.source_pattern}") print(f"Sink: {result.sink_pattern}") print(f"Paths found: {result.path_count}") for i, path in enumerate(result.paths[:5]): path_str = " -> ".join([str(node_id)[:8] for node_id in path]) print(f"Path {i+1}: {path_str}") asyncio.run(analyze_dataflow()) ``` -------------------------------- ### Delete and Regenerate CPG Cache Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md This command removes the existing CPG cache and then re-indexes the project. It is a solution for issues related to corrupted CPGs, ensuring a fresh generation of the Code Property Graph. ```bash rm ~/.knowgraph/cpg_cache/*.bin && knowgraph index ./project ``` -------------------------------- ### Control Worker Parallelism (Bash) Source: https://github.com/yunusgungor/knowgraph/blob/main/docs/USER_GUIDE.md Environment variables to control the number of worker processes for indexing and querying in KnowGraph. Options include automatic detection, manual override, and single-threaded mode for debugging. ```bash # Auto-detect (default, max 30) export KNOWGRAPH_WORKERS=auto # Manual override export KNOWGRAPH_WORKERS=10 # Single-threaded (debugging) export KNOWGRAPH_WORKERS=1 ```