### Start ContextWeaver MCP Server Source: https://context7.com/bayu605/contextweaver/llms.txt Use the `mcp` command to start the Model Context Protocol server, which communicates via stdio for integration with AI assistants. ```bash # Start MCP server (communicates via stdio) contextweaver mcp ``` -------------------------------- ### Initialize ContextWeaver Configuration Source: https://context7.com/bayu605/contextweaver/llms.txt Use the `init` command to create the configuration directory and default environment file. A short alias `cw` is also available. ```bash # Initialize ContextWeaver configuration contextweaver init # Or use the short alias cw init ``` -------------------------------- ### Initialize and Use SearchService Source: https://context7.com/bayu605/contextweaver/llms.txt Initializes the SearchService with custom configurations for retrieval, reranking, and context expansion. Use this to build context packs for complex queries. ```typescript import { SearchService } from '@hsingjui/contextweaver'; import { generateProjectId } from '@hsingjui/contextweaver'; // Initialize search service const projectPath = '/path/to/project'; const projectId = generateProjectId(projectPath); const searchService = new SearchService(projectId, projectPath, { // Optional: Override default search configuration vectorTopK: 200, // Initial vector retrieval count fusedTopM: 50, // Candidates after RRF fusion rerankTopN: 20, // Results after reranking neighborHops: 2, // Adjacent chunks to include breadcrumbExpandLimit: 3, // Related chunks per breadcrumb importFilesPerSeed: 3, // Cross-file imports to resolve }); await searchService.init(); // Build context pack for a query const contextPack = await searchService.buildContextPack( 'How does the authentication middleware validate JWT tokens?' ); console.log(contextPack); ``` -------------------------------- ### Index a Codebase with ContextWeaver Source: https://context7.com/bayu605/contextweaver/llms.txt The `index` command scans a codebase and builds semantic indexes. You can index the current directory, a specific path, or force a re-index ignoring the cache. ```bash # Index current directory contextweaver index # Index a specific path contextweaver index /path/to/project # Force re-index all files (ignores cache) contextweaver index --force contextweaver index -f /path/to/project ``` -------------------------------- ### Configure Embedding and Reranker Settings Source: https://context7.com/bayu605/contextweaver/llms.txt Set environment variables in `~/.contextweaver/.env` to configure embedding and reranker APIs. This includes API keys, base URLs, models, concurrency, dimensions, and top N values for reranking. Optional custom ignore patterns can also be specified. ```bash # Embedding API Configuration (Required) EMBEDDINGS_API_KEY=your-api-key-here EMBEDDINGS_BASE_URL=https://api.siliconflow.cn/v1/embeddings EMBEDDINGS_MODEL=BAAI/bge-m3 EMBEDDINGS_MAX_CONCURRENCY=10 EMBEDDINGS_DIMENSIONS=1024 # Reranker Configuration (Required) RERANK_API_KEY=your-api-key-here RERANK_BASE_URL=https://api.siliconflow.cn/v1/rerank RERANK_MODEL=BAAI/bge-reranker-v2-m3 RERANK_TOP_N=20 # Custom Ignore Patterns (Optional, comma-separated) IGNORE_PATTERNS=.venv,node_modules,custom_folder ``` -------------------------------- ### Manage Database Operations Source: https://context7.com/bayu605/contextweaver/llms.txt Handles project ID generation, SQLite database initialization, and batch file metadata operations. ```typescript import { generateProjectId, initDb, closeDb, getAllFileMeta, batchUpsert, batchDelete } from '@hsingjui/contextweaver'; // Generate unique project ID based on path and directory birthtime const projectId = generateProjectId('/path/to/project'); // Returns: '8a3f2b1c9d' (MD5 hash prefix) // Initialize SQLite database const db = initDb(projectId); // Creates ~/.contextweaver/{projectId}/index.db // Get all indexed file metadata const fileMeta = getAllFileMeta(db); // Map // Batch insert/update files batchUpsert(db, [ { path: 'src/index.ts', hash: 'abc123...', mtime: Date.now(), size: 1024, content: 'export * from "./api";', language: 'typescript', vectorIndexHash: null } ]); // Batch delete files batchDelete(db, ['src/old-file.ts', 'src/deprecated.ts']); // Close database connection closeDb(db); ``` -------------------------------- ### Search Codebase with ContextWeaver Source: https://context7.com/bayu605/contextweaver/llms.txt The `search` command performs semantic code retrieval using natural language queries. It supports filtering with technical terms, specifying a repository path, and disabling Zen mode for more cross-file context. ```bash # Search with semantic query contextweaver search --information-request "How is user authentication handled?" # Search with technical terms for precise filtering contextweaver search \ --information-request "Logic for database connection pooling" \ --technical-terms "PoolConfig,Connection,release" # Search in a specific repository contextweaver search \ --repo-path /path/to/project \ --information-request "How does the payment processing work?" # Disable Zen mode (includes more cross-file context) contextweaver search --no-zen --information-request "Error handling patterns" ``` -------------------------------- ### MCP Server Configuration for ContextWeaver Source: https://context7.com/bayu605/contextweaver/llms.txt Configuration for the MCP server within an AI assistant's settings. Specifies the command and arguments to run the ContextWeaver MCP service. ```json { "mcpServers": { "contextweaver": { "command": "npx", "args": ["@hsingjui/contextweaver", "mcp"] } } } ``` -------------------------------- ### Handle Codebase Retrieval for AI Assistants Source: https://context7.com/bayu605/contextweaver/llms.txt Integrates with MCP servers to provide a codebase retrieval tool for AI assistants. Call the retrieval handler directly with repository path, information request, and technical terms. ```typescript import { handleCodebaseRetrieval } from '@hsingjui/contextweaver'; // Call the retrieval handler directly const response = await handleCodebaseRetrieval({ repo_path: '/path/to/project', information_request: 'How is user session management implemented?', technical_terms: ['SessionStore', 'createSession', 'validateSession'] }); console.log(response.content[0].text); ``` -------------------------------- ### Initialize and Use SemanticSplitter with AST Source: https://context7.com/bayu605/contextweaver/llms.txt Initializes the SemanticSplitter using Tree-sitter for AST parsing to create semantically meaningful code chunks. Requires a parser and language definition. ```typescript import { SemanticSplitter } from '@hsingjui/contextweaver'; import Parser from '@keqingmoe/tree-sitter'; import TypeScript from 'tree-sitter-typescript'; // Initialize parser const parser = new Parser(); parser.setLanguage(TypeScript.typescript); // Create splitter with custom configuration const splitter = new SemanticSplitter({ maxChunkSize: 2500, // Max tokens per chunk minChunkSize: 100, // Min tokens per chunk chunkOverlap: 200, // Overlap for context continuity maxRawChars: 10000, // Physical character limit }); // Split code into semantic chunks const code = "\nexport class UserService {\n private db: Database;\n\n constructor(db: Database) {\n this.db = db;\n }\n\n async findById(id: string): Promise {\n return this.db.users.findUnique({ where: { id } });\n }\n\n async createUser(data: CreateUserDto): Promise {\n return this.db.users.create({ data });\n }\n} "; const tree = parser.parse(code); const chunks = splitter.split(tree, code, 'src/services/user.ts', 'typescript'); console.log(chunks); ``` -------------------------------- ### Scan Codebase with ContextWeaver Source: https://context7.com/bayu605/contextweaver/llms.txt The `scan` function crawls a codebase, processes files, generates embeddings, and builds the search index. It can be used with basic options or advanced options including a progress callback. ```typescript import { scan, type ScanStats, type ScanOptions } from '@hsingjui/contextweaver'; // Basic scan const stats: ScanStats = await scan('/path/to/project'); console.log(stats); // { // totalFiles: 150, // added: 120, // modified: 10, // unchanged: 15, // deleted: 5, // skipped: 0, // errors: 0, // vectorIndex: { indexed: 130, deleted: 5, errors: 0 } // } // Scan with options and progress callback const options: ScanOptions = { force: false, // Set true to re-index all files vectorIndex: true, // Enable vector indexing (default: true) onProgress: (current, total, message) => { console.log(`Progress: ${current}/${total} - ${message}`); } }; const result = await scan('/path/to/project', options); ``` -------------------------------- ### TypeScript Configuration Functions Source: https://context7.com/bayu605/contextweaver/llms.txt Import and use functions like `getEmbeddingConfig`, `getRerankerConfig`, `checkEmbeddingEnv`, `checkRerankerEnv`, and `getExcludePatterns` to manage ContextWeaver's configuration in TypeScript projects. These functions help validate environment variables and retrieve configuration objects. ```typescript import { getEmbeddingConfig, getRerankerConfig, checkEmbeddingEnv, checkRerankerEnv, getExcludePatterns } from '@hsingjui/contextweaver'; // Check if environment is properly configured const embeddingCheck = checkEmbeddingEnv(); if (!embeddingCheck.isValid) { console.log('Missing variables:', embeddingCheck.missingVars); } // Get embedding configuration const embeddingConfig = getEmbeddingConfig(); console.log(embeddingConfig); // { // apiKey: 'your-api-key', // baseUrl: 'https://api.siliconflow.cn/v1/embeddings', // model: 'BAAI/bge-m3', // maxConcurrency: 10, // dimensions: 1024 // } // Get reranker configuration const rerankerConfig = getRerankerConfig(); console.log(rerankerConfig); // { // apiKey: 'your-api-key', // baseUrl: 'https://api.siliconflow.cn/v1/rerank', // model: 'BAAI/bge-reranker-v2-m3', // topN: 20 // } // Get exclude patterns for file scanning const patterns = getExcludePatterns(); // ['node_modules', '.venv', 'dist', '*.min.js', ...] ``` -------------------------------- ### Pack Context with ContextPacker Source: https://context7.com/bayu605/contextweaver/llms.txt Merges overlapping code chunks and enforces token limits to prepare data for LLM consumption. ```typescript import { ContextPacker } from '@hsingjui/contextweaver'; import type { SearchConfig, ScoredChunk } from '@hsingjui/contextweaver'; const config: Partial = { maxSegmentsPerFile: 5, // Max segments per file in output maxTotalChars: 50000, // Total character budget }; const packer = new ContextPacker(projectId, config as SearchConfig); // Pack scored chunks into final context const chunks: ScoredChunk[] = [ { filePath: 'src/auth.ts', chunkIndex: 2, score: 0.95, record: { raw_start: 100, raw_end: 500, ... } }, { filePath: 'src/auth.ts', chunkIndex: 3, score: 0.88, record: { raw_start: 450, raw_end: 800, ... } }, { filePath: 'src/utils.ts', chunkIndex: 1, score: 0.75, record: { raw_start: 0, raw_end: 300, ... } }, ]; const files = await packer.pack(chunks); console.log(files); // [ // { // filePath: 'src/auth.ts', // segments: [ // { // filePath: 'src/auth.ts', // rawStart: 100, // rawEnd: 800, // Merged overlapping chunks // startLine: 5, // endLine: 35, // score: 0.95, // breadcrumb: 'src/auth.ts > validateToken', // text: '...' // } // ] // }, // { // filePath: 'src/utils.ts', // segments: [...] // } // ] ``` -------------------------------- ### Expand Graph Context with GraphExpander Source: https://context7.com/bayu605/contextweaver/llms.txt Uses neighbor expansion, breadcrumb matching, and import resolution to enrich seed chunks with related code context. ```typescript import { getGraphExpander } from '@hsingjui/contextweaver'; import type { ScoredChunk, SearchConfig } from '@hsingjui/contextweaver'; const config: Partial = { neighborHops: 2, // Include ±2 adjacent chunks breadcrumbExpandLimit: 3, // Max chunks per breadcrumb prefix importFilesPerSeed: 3, // Max import files to resolve per seed chunksPerImportFile: 2, // Chunks per imported file decayNeighbor: 0.9, // Score decay for neighbors decayBreadcrumb: 0.8, // Score decay for breadcrumb matches decayImport: 0.7, // Score decay for imports }; const expander = await getGraphExpander(projectId, config as SearchConfig); // Expand seed chunks with related context const seeds: ScoredChunk[] = [ { filePath: 'src/api/handler.ts', chunkIndex: 5, score: 0.95, source: 'vector', record: {...} } ]; const queryTokens = new Set(['handler', 'request', 'response']); const { chunks, stats } = await expander.expand(seeds, queryTokens); console.log(stats); // { // neighborCount: 4, // Adjacent chunks added // breadcrumbCount: 2, // Related function chunks // importCount: 3, // Cross-file imports resolved // importDepth1Count: 1 // Barrel file re-exports followed // } ``` -------------------------------- ### Split Plain Text with SemanticSplitter Source: https://context7.com/bayu605/contextweaver/llms.txt Uses the SemanticSplitter for plain text splitting when AST parsing is not applicable. Specify the text, file path, and language. ```typescript // For non-AST languages, use plain text splitting const plainChunks = splitter.splitPlainText( 'some plain text content...', 'README.md', 'markdown' ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.