拉格斯
多语言代码库的混合检索增强生成
Ragex是一个MCP(模型上下文协议)服务器,它使用编译器输出和语言原生工具分析代码库,以构建全面的知识图。它支持对代码结构、关系和语义的自然语言查询。
特性
Foundation ▸ MCP Server Protocol: Full JSON-RPC 2.0 implementation over both stdio and socket
▸ Elixir Code Analyzer: AST-based parser extracting modules, functions, calls, and dependencies
▸ Knowledge Graph: ETS-based storage for code entities and relationships
▸ MCP Tools:
▹ analyze_file: Parse and index source files
▹ query_graph: Search for modules, functions, and relationships
▹ list_nodes: Browse indexed code entities
Multi-Language Support ▸ Erlang Analyzer: Uses :erl_scan and :erl_parse for native Erlang AST parsing
▸ Python Analyzer: Shells out to Python's ast module for comprehensive analysis
▸ Ruby Analyzer: Uses Metastatic Ruby adapter (parser gem) with native fallback
▸ JavaScript/TypeScript Analyzer: Regex-based parsing for common JS/TS patterns
▸ Auto-detection: Automatically detects language from file extension
▸ Directory Analysis: Batch analyze entire projects with parallel processing
▸ File Watching: Auto-reindex on file changes
▸ Supported Extensions: .ex, .exs, .erl, .hrl, .py, .rb, .js, .jsx, .ts, .tsx, .mjs
Semantic Search & Hybrid Retrieval ▸ Embeddings Foundation
▹ Local ML Model: Bumblebee integration with sentence-transformers/all-MiniLM-L6-v2
▹ Vector Embeddings: 384-dimensional embeddings for code entities
▹ Automatic Generation: Embeddings created during code analysis
▹ Text Descriptions: Natural language descriptions for modules and functions
▹ ETS Storage: Embeddings stored alongside graph entities
▹ No External APIs: Fully local model inference (~400MB memory)
▸ Vector Store
▹ Cosine Similarity: Fast vector similarity search (less than 50ms for 100 entities)
▹ Parallel Search: Concurrent similarity calculations
▹ Filtering: By node type, similarity threshold, and result limit
▹ k-NN Search: Nearest neighbor queries
▹ Statistics API: Vector store metrics and monitoring
▸ Semantic Search Tools
▹ Semantic Search: Natural language code queries (“function to parse JSON”)
▹ Getting Embeddings Stats: ML model and vector store statistics
▹ Result Enrichment: Context with callers, callees, file locations
▹ Flexible Filtering: By type, threshold, limit, with context inclusion
▸ Hybrid Retrieval
▹ Hybrid Search: Combines symbolic and semantic approaches
▹ Three Strategies: Fusion (RRF), semantic-first, graph-first
▹ Reciprocal Rank Fusion: Intelligent ranking combination (k is 60)
▹ Graph Constraints: Optional symbolic filtering
▹ Performance:
Production Features ▸ Custom Embedding Models
▹ Model Registry: 4 pre-configured embedding models
▹ Flexible Configuration: Config file, environment variable, or default
▹ Model Compatibility: Automatic detection of compatible models (same dimensions)
▹ Migration Tool: mix ragex.embeddings.migrate for model changes
▹ Validation: Startup checks for model compatibility
▸ Embedding Persistence
▹ Automatic Cache: Save on shutdown, load on startup
▹ Model Validation: Ensures cache matches current model
▹ Project-Specific: Isolated caches per project directory
▹ Cache Management: Mix tasks for stats and cleanup (mix ragex.cache.*)
▹ Performance: Cold start
Code Editing Capabilities ▸ Core Editor Infrastructure
▹ Editor Types: Change types (replace, insert, delete) with validation
▹ Backup Management: Automatic backups with timestamps and project-specific directories
▹ Core Editor: Atomic operations with concurrent modification detection
▹ Rollback Support: Restore previous versions from backup history
▹ Configuration: Backup retention, compression, and directory settings
▸ Validation Pipeline
▹ Validator Behavior: Behavior definition with callbacks and orchestration
▹ Elixir Validator: Syntax validation using Code.string_to_quoted/2
▹ Erlang Validator: Validation using :erl_scan and :erl_parse
▹ Python Validator: Shell-out to Python's ast.parse() for syntax checking
▹ Ruby Validator: ruby -c for Ruby syntax checking
▹ JavaScript Validator: Node.js vm.Script for JS/TS validation
▹ Automatic Detection: Language detection from file extension
▹ Core Integration: Validators integrated with Core.edit_file
▸ MCP Edit Tools
▹ edit_file: MCP tool for safe file editing with validation
▹ validate_edit: Preview validation before applying changes
▹ rollback_edit: Undo recent edits via MCP
▹ edit_history: Query backup history
▸ Advanced Editing
▹ Format Integration: Auto-format after edits with language-specific formatters
▹ Formatter Detection: Automatic formatter discovery (mix, rebar3, black, rubocop, prettier)
▹ Core Integration: :format option in Core.edit_file
▹ Multi-file Transactions: Atomic cross-file changes with automatic rollback
▹ Transaction Validation: Pre-validate all files before applying changes
▹ MCP Integration: edit_files tool for coordinated multi-file edits
▸ Semantic Refactoring
▹ AST Manipulation: Elixir-specific AST parsing and transformation
▹ Rename Function: Rename functions with automatic call site updates
▹ Rename Module: Rename modules with reference updates
▹ Graph Integration: Use knowledge graph to find all affected files
▹ Arity Support: Handle functions with multiple arities correctly
▹ Scope Control: Module-level or project-wide refactoring
▹ MCP Integration: refactor_code tool for semantic refactoring
▸ Advanced Refactoring
▹ Extract Function: Extract code range into new function (basic support)
▹ Inline Function: Replace all calls with function body, remove definition (fully working)
▹ Convert Visibility: Toggle between def and defp (fully working)
▹ Rename Parameter: Rename parameter within function scope (fully working)
▹ Modify Attributes: Add/remove/update module attributes (fully working)
▹ Change Signature: Add/remove/reorder/rename parameters with call site updates (fully working)
▹ Move Function: Move function between modules (deferred - requires advanced semantic analysis)
▹ Extract Module: Extract multiple functions into new module (deferred - requires advanced semantic analysis)
▹ MCP Integration: advanced_refactor tool with 8 operation types
▹ Status: 6 of 8 operations fully functional, 2 deferred pending semantic analysis enhancements
Advanced Graph Algorithms ▸ Centrality Metrics
▹ Betweenness Centrality: Identify bridge/bottleneck functions using Brandes’ algorithm
▹ Closeness Centrality: Identify central functions based on average distance
▹ Normalized Scores: Configurable 0-1 normalization
▹ Performance Limits: max_nodes parameter for large graphs
▹ MCP Tools: betweenness_centrality and closeness_centrality
▸ Community Detection
▹ Louvain Method: Modularity optimization for discovering architectural modules
▹ Label Propagation: Fast alternative algorithm (O(m) per iteration)
▹ Hierarchical Structure: Multi-level community detection support
▹ Weighted Edges: Support for edge weights (call frequency)
▹ MCP Tool: detect_communities with algorithm selection
▸ Weighted Graph Support
▹ Edge Weights: Store call frequency in edge metadata (default: 1.0)
▹ Weighted Algorithms: Modularity computation with weights
▹ Store Integration: get_edge_weight helper function
▸ Graph Visualization
▹ Graphviz DOT Export: Community clustering, colored nodes, weighted edges
▹ D3.js JSON Export: Force-directed graph format with metadata
▹ Node Coloring: By PageRank, betweenness, or degree centrality
▹ Edge Thickness: Proportional to edge weight
▹ MCP Tool: export_graph with format selection
MCP Resources & Prompts ▸ Resources (Read-only State Access)
▹ Graph Statistics: Node/edge counts, PageRank scores, centrality metrics
▹ Cache Status: Embedding cache health, file tracking, stale entities
▹ Model Configuration: Active model details, capabilities, readiness
▹ Project Index: Tracked files, language distribution, entity counts
▹ Algorithm Catalog: Available algorithms with parameters and complexity
▹ Analysis Summary: Pre-computed architectural insights and communities
▹ URI Format: ragex:///
▹ Documentation: See RESOURCES.md
▸ Prompts (High-level Workflows)
▹ Analyze Architecture: Comprehensive architectural analysis (shallow/deep)
▹ Find Impact: Function importance and refactoring risk assessment
▹ Explain Code Flow: Narrative execution flow between functions
▹ Find Similar Code: Hybrid search with natural language descriptions
▹ Suggest Refactoring: Modularity, coupling, and complexity analysis
▹ Safe Rename: Impact preview for semantic refactoring operations
▹ Tool Composition: Each prompt suggests sequence of tools to use
▹ Documentation: See PROMPTS.md
RAG System (🔥) ▸ AI Provider Abstraction
▹ Provider Behaviour: Clean interface for multiple AI providers
▹ DeepSeek R1: Full integration with deepseek-chat and deepseek-reasoner models
▹ Streaming Support: All providers support streaming responses (SSE/NDJSON)
▹ Real-time Responses: Progressive content delivery with token usage tracking
▹ OpenAI: GPT-4, GPT-4-turbo, GPT-3.5-turbo support
▹ Anthropic: Claude 3 Opus, Sonnet, and Haiku models
▹ Ollama: Local LLM support (llama2, mistral, codellama, phi)
▹ Configuration System: Multi-provider with fallback support
▹ Provider Registry: GenServer for runtime provider management
▸ AI Response Caching
▹ ETS-based Cache: SHA256 key generation with TTL expiration
▹ LRU Eviction: Automatic eviction when max size reached
▹ Operation-specific TTL: Configurable per operation type
▹ Cache Statistics: Hit rate, misses, puts, evictions tracking
▹ Mix Tasks: mix ragex.ai.cache.stats and mix ragex.ai.cache.clear
▹ Performance: >50% cache hit rate for repeated queries
▸ Usage Tracking & Rate Limiting
▹ Per-provider Tracking: Requests, tokens, and cost estimation
▹ Real-time Costs: Accurate pricing for OpenAI, Anthropic, DeepSeek
▹ Time-windowed Limits: Per-minute, per-hour, per-day controls
▹ Automatic Enforcement: Rate limit checks before API calls
▹ Mix Tasks: mix ragex.ai.usage.stats for monitoring
▹ MCP Tools: get_ai_usage, get_ai_cache_stats
▸ Metastatic Integration
▹ MetaAST Analyzer: Enhanced cross-language analysis via Metastatic library
▹ Supported Languages: Elixir, Erlang, Python, Ruby, Haskell
▹ Fallback Strategy: Graceful degradation to native analyzers
▹ Feature Flags: Configurable use_metastatic option
▸ RAG Pipeline
▹ Context Builder: Format retrieval results for AI consumption (8000 char max)
▹ Prompt Templates: Query, explain, and suggest operations
▹ Full Pipeline: Retrieval → Context → Prompting → Generation → Post-processing
▹ Hybrid Retrieval: Leverages semantic + graph-based search
▹ Cache Integration: Automatic caching of AI responses
▹ Usage Tracking: All requests tracked with cost estimation
▸ Agent-Based RAG (chat & audit)
▹ The AI drives retrieval: agent calls Ragex MCP tools directly instead of receiving pre-fetched context
▹ mix ragex.chat: every question answered via ReAct loop with hybrid_search, semantic_search, read_file, query_graph, etc.
▹ mix ragex.audit: AI report enriched by read-only RAG tool calls for concrete evidence (ToolSchema.rag_query_tools/1)
▹ Evidence-based findings: AI can quote actual function bodies, confirm dependency paths, and check coupling metrics
▹ Safe scoping: heavy re-analysis tools excluded so the analysis pipeline is never re-triggered during report writing
▸ MCP RAG Tools
▹ rag_query: Answer general codebase questions with AI
▹ rag_explain: Explain code with aspect focus (purpose, complexity, dependencies, all)
▹ rag_suggest: Suggest improvements (performance, readability, testing, security, all)
▹ rag_query_stream: Streaming version of rag_query (internally uses streaming)
▹ rag_explain_stream: Streaming version of rag_explain (internally uses streaming)
▹ rag_suggest_stream: Streaming version of rag_suggest (internally uses streaming)
▹ get_ai_usage: Query usage statistics and costs per provider
▹ get_ai_cache_stats: View cache performance metrics
▹ clear_ai_cache: Clear cache via MCP
▹ Provider Override: Select provider per-query (openai, anthropic, deepseek_r1, ollama)
▸ MetaAST-Enhanced Retrieval
▹ Context-Aware Ranking: Query intent detection (explain, refactor, example, debug)
▹ Purity Analysis: Boost pure functions, penalize side effects
▹ Complexity Scoring: Favor simple code for explanations, complex code for refactoring
▹ Cross-Language Search: Find equivalent constructs across languages via MetaAST
▹ Query Expansion: Automatic synonym injection and cross-language terms
▹ Pattern Search: Find all implementations of MetaAST patterns (map, filter, lambda, etc.)
▹ Hybrid Integration: MetaAST ranking applied to all search strategies
▹ MCP Tools: metaast_search, cross_language_alternatives, expand_query, find_metaast_pattern
AI Features (🔥) ▸ Foundation Layer
▹ Features.Config: Per-feature flags with master switch
▹ Features.Context: Rich context builders (6 context types)
▹ Features.Cache: Automatic caching with TTL policies (3-7 days)
▹ Graceful degradation when AI disabled
▸ High-Priority Features
▹ ValidationAI: AI-enhanced validation error explanations
▹ AIPreview: Refactoring preview with risk assessment and recommendations
▸ Analysis Features
▹ AIRefiner: Dead code false positive reduction (50%+ target)
▹ AIAnalyzer: Semantic Type IV clone detection (>70% accuracy target)
▹ AIInsights: Architectural insights for coupling and circular dependencies
▹ Context-aware recommendations with technical debt scoring
▸ Configuration
▹ Opt-in via :ai_features config (dead_code_refinement, duplication_semantic_analysis, etc.)
▹ Master switch with per-feature overrides
▹ Integrates with existing analysis modules (DeadCode, Duplication, DependencyGraph)
▹ MCP tools: validate_with_ai, enhanced preview_refactor
Code Analysis & Quality ▸ Dead Code Detection
▹ Graph-Based Analysis: Find unused functions via call graph traversal
▹ Confidence Scoring: 0.0-1.0 score to distinguish callbacks from dead code
▹ Pattern Detection: AST-based unreachable code detection via Metastatic
▹ Intraprocedural Analysis: Constant conditionals, unreachable branches
▹ Interprocedural Analysis: Unused exports, private functions
▹ Callback Recognition: GenServer, Phoenix, and other framework callbacks
▹ MCP Tools: find_dead_code, analyze_dead_code_patterns
▸ Dependency Analysis
▹ Coupling Metrics: Afferent (Ca) and Efferent (Ce) coupling
▹ Instability: I = Ce / (Ca + Ce) ranges from 0 (stable) to 1 (unstable)
▹ Circular Dependencies: Detect cycles at module and function levels
▹ Transitive Dependencies: Optional deep dependency traversal
▹ God Module Detection: Find modules with high coupling
▹ MCP Tools: analyze_dependencies, find_circular_dependencies, coupling_report
▸ Code Duplication Detection
▹ AST-Based Clones: Type I-IV clone detection via Metastatic
▹ Type I: Exact clones (whitespace/comment differences only)
▹ Type II: Renamed clones (same structure, different identifiers)
▹ Type III: Near-miss clones (similar with modifications, configurable threshold)
▹ Type IV: Semantic clones (different syntax, same behavior)
▹ Embedding-Based Similarity: Semantic code similarity using ML embeddings
▹ Directory Scanning: Recursive multi-file analysis with exclusion patterns
▹ Reports: Summary, detailed, and JSON formats
▹ MCP Tools: find_duplicates, find_similar_code
▸ Impact Analysis
▹ Change Impact: Predict affected code via graph traversal
▹ Risk Scoring: Combine importance (PageRank) + coupling + complexity
▹ Test Discovery: Find affected tests automatically
▹ Effort Estimation: Estimate refactoring time/complexity for 6 operations
▹ Risk Levels: Low (50)
▹ Deep Nesting: Excessive nesting depth (default: >4 levels)
▹ Magic Numbers: Unexplained numeric literals in expressions
▹ Complex Conditionals: Deeply nested boolean operations
▹ Long Parameter List: Too many parameters (default: >5)
▹ Configurable Thresholds: Custom limits per project
▹ Severity Levels: Critical, high, medium, low
▹ Actionable Suggestions: Refactoring recommendations for each smell
▹ Directory Scanning: Recursive analysis with parallel processing
▹ Filtering: By severity or smell type
▹ MCP Tool: detect_smells
▸ Business Logic Analysis (20 Metastatic Analyzers)
▹ Control Flow Issues:
• Callback Hell: Excessive nested callbacks (default: >3 levels)
• Missing Error Handling: Functions without try/rescue or error tuples
• Silent Error Case: Pattern matches that ignore error tuples
• Swallowing Exception: Rescue clauses without re-raising or logging
▹ Data & Configuration:
• Hardcoded Value: URLs, secrets, or config values in code
• Direct Struct Update: Using %{struct | ...} instead of changesets/contexts
• Missing Preload: Ecto queries without required preloads
▹ Performance & Scalability:
• N+1 Query: Multiple database queries in iterations
• Inefficient Filter: Filtering after fetching instead of in query
• Unmanaged Task: Task.start without supervision
• Blocking in Plug: Slow synchronous operations in plug pipeline
• Sync Over Async: Using sync calls when async is available
▹ Observability:
• Missing Telemetry for External HTTP: External API calls without telemetry
• Missing Telemetry in Auth Plug: Auth operations without metrics
• Missing Telemetry in LiveView Mount: LiveView lifecycle without tracking
• Missing Telemetry in Oban Worker: Background jobs without observability
• Telemetry in Recursive Function: Performance overhead from recursive telemetry
▹ Framework-Specific:
• Missing Handle Async: LiveView async results without handlers
• Inline JavaScript: JavaScript in Phoenix templates/LiveView
• Missing Throttle: User-facing actions without rate limiting
▹ Tier Classification: 4 tiers from pure MetaAST to content analysis
▹ Actionable Recommendations: Specific fixes for each issue type
▹ Severity Levels: Critical, high, medium, low, info
▹ Directory Scanning: Recursive analysis with file type detection
▹ Filtering: By analyzer, minimum severity, or file patterns
▹ Reports: Summary with counts by analyzer and severity
▹ MCP Tool: analyze_business_logic
▹ Mix Task: mix ragex.analyze --business-logic
▸ Quality Metrics (Metastatic Integration)
▹ Complexity Metrics (Full Suite):
• Cyclomatic Complexity: McCabe metric (decision points + 1)
• Cognitive Complexity: Structural complexity with nesting penalties
• Nesting Depth: Maximum nesting level tracking
▹ Halstead Metrics (Comprehensive):
• Vocabulary: distinct_operators + distinct_operands
• Length: total_operators + total_operands
• Volume: length × log₂(vocabulary)
• Difficulty: (distinct_operators / 2) × (total_operands / distinct_operands)
• Effort: volume × difficulty
▹ Lines of Code (Detailed):
• Physical Lines: Total lines including blank/comments
• Logical Lines: Executable statements only
• Comments: Comment lines count
• Blank Lines: Whitespace-only lines
▹ Function Metrics:
• Statement Count: Number of executable statements
• Return Points: Multiple return analysis
• Variable Count: Local variable tracking
• Parameter Count: Function signature complexity
▹ Purity Analysis: Function purity and side-effect detection
▹ Per-Function Analysis: Individual function breakdown with all metrics
▹ Project-wide Reports: Aggregated statistics by language
▹ MCP Tools: analyze_quality, quality_report, find_complex_code
▸ Documentation
▹ Comprehensive Guide: See ANALYSIS for complete API documentation
▹ Analysis Approaches: AST-based vs embedding-based strategies
▹ Usage Examples: API and MCP tool examples with code snippets
▹ Best Practices: Threshold recommendations, workflow tips
▹ Troubleshooting: Common issues and solutions
▹ CI/CD Integration: Pre-commit hooks, pipeline examples
CLI Improvements ▸ CLI Foundation
▹ Colors: ANSI color helpers with NO_COLOR support
▹ Output: Rich formatting (sections, lists, tables, key-value pairs, diffs)
▹ Progress: Spinners and progress indicators
▹ Prompt: Interactive prompts (confirm, select, input, number with validation)
▸ Enhanced Mix Tasks (7 upgraded)
▹ mix ragex.cache.{stats,refresh,clear} - Colored output, spinners, confirmations
▹ mix ragex.embeddings.migrate - Sections, formatted output, interactive confirmations
▹ mix ragex.ai.{usage.stats,cache.stats,cache.clear} - Rich formatting, color-coded metrics
▸ Interactive Wizards
▹ mix ragex.chat - AI-powered codebase Q&A via Ragex MCP tools:
• Agent ReAct loop — AI calls hybrid_search, semantic_search, read_file, query_graph, etc.
• Initial analysis + streaming audit report on first run
• Multi-turn conversation with session memory
• --provider / --model overrides; --skip-analysis to reuse existing graph
• --debug to print tool-call traces to stderr
▹ mix ragex.audit - AI-powered code audit report:
• Static analysis + AI report with optional RAG evidence retrieval
• JSON (default) or Markdown output; --output FILE to save
• --format markdown renders the report directly in the terminal
• --verbose shows progress; --dead-code enables dead-code section
▹ mix ragex.refactor - Interactive refactoring wizard:
• 5 operations: rename_function, rename_module, change_signature, extract_function, inline_function
• Parameter gathering with validation
• Knowledge graph integration
• Preview and confirmation before applying
• Both interactive and direct CLI modes
▹ mix ragex.configure - Configuration wizard:
• Smart project type detection
• Embedding model comparison and selection
• AI provider configuration with environment detection
• Analysis options and cache settings
• Generates complete .ragex.exs configuration file
▸ Live Dashboard
▹ mix ragex.dashboard - Real-time monitoring:
• 4 stat panels: Graph, Embeddings, Cache, AI Usage
• Live updating display (customizable refresh interval)
• Color-coded metrics with thresholds
• Activity log
▸ Shell Completions
▹ Bash, Zsh, Fish completion scripts
▹ mix ragex.completions - Auto-detect and install completions
▹ Task name completion with descriptions
▹ Context-aware argument completion
▸ Documentation
▹ Man pages in groff format (ragex.1)
▹ mix ragex.install_man - System-wide man page installation
▹ Complete command reference (10 Mix tasks)
▹ Configuration guide and usage examples
计划的功能
- \[✓\] 流式RAG响应
- \[✓\] MCP流式通知
- \[✓\] MetaAST增强检索
- \[✓\] 代码质量分析
- \[✓\] 影响分析和风险评估
- \[✓\] CLI改进(交互式向导、仪表板、补全、手册页)
- \[±\]CI任务
- \[✗\] 提供商健康检查和自动故障转移
- \[✗\] 生产优化
- \[±\]额外的语言支持
- \[±\]通过Metastic进行跨语言重构
- \[✓\] 增强的编辑器集成(Zed、Claude Desktop、Cursor、LunarVim)
建筑
graph TD
MCP["MCP Server (stdio)
~50 Tools + 6 Resources + 6 Prompts"]
MCP --> Tools["Tools Handler"]
MCP --> Resources["Resources Handler"]
MCP --> Prompts["Prompts Handler"]
MCP --> Analyzers["Analyzers
(Elixir, Erlang, Metastatic)"]
MCP --> Graph["Graph Store
(ETS Knowledge Graph)"]
MCP --> Vector["Vector Store
(Cosine Similarity)"]
MCP --> Bumblebee["Bumblebee Embedding
(all-MiniLM-L6-v2)"]
Tools Analyzers
Analyzers Graph
Resources --> Graph
Resources --> Vector
Resources --> Bumblebee
Prompts --> Tools
Tools --> Hybrid["Hybrid Retrieval (RRF)
Semantic + Graph + Fusion"]
Graph --> Hybrid
Vector --> Hybrid
Tools --> RAG["RAG Pipeline
Cache → Context → Prompts → AI"]
Hybrid --> RAG
RAG --> Cache["AI Cache
(TTL + LRU)"]
RAG --> Usage["Usage Tracker
(Costs + Limits)"]
RAG --> AIProvider["AI Providers
(OpenAI, Anthropic, DeepSeek, Ollama)"]
style MCP fill:#e1f5ff,color:#01579b,stroke:#01579b,stroke-width:2px
style Hybrid fill:#f3e5f5,color:#4a148c,stroke:#4a148c,stroke-width:2px
style Graph fill:#e8f5e9,color:#1b5e20,stroke:#1b5e20,stroke-width:2px
style Vector fill:#fff3e0,color:#e65100,stroke:#e65100,stroke-width:2px
style Bumblebee fill:#fce4ec,color:#880e4f,stroke:#880e4f,stroke-width:2px
style Resources fill:#e0f2f1,color:#004d40,stroke:#004d40,stroke-width:2px
style Prompts fill:#fff9c4,color:#f57f17,stroke:#f57f17,stroke-width:2px
style RAG fill:#ffebee,color:#b71c1c,stroke:#b71c1c,stroke-width:2px
style AIProvider fill:#e8eaf6,color:#1a237e,stroke:#1a237e,stroke-width:2px
style Cache fill:#e0f7fa,color:#006064,stroke:#006064,stroke-width:2px
style Usage fill:#fff8e1,color:#f57c00,stroke:#f57c00,stroke-width:2px安装
先决条件
- Elixir 1.18或更高版本
- Erlang/OTP 27或更高版本
- Python 3.x(可选,用于Python代码分析)
- 节点。JS(可选,用于Javascript代码分析)
- 约500MB RAM用于嵌入模型(首次运行下载约90MB)
构建
cd ragex
mix deps.get
mix compile备注:由于ML依赖关系,第一次编译需要更长的时间。嵌入模型(~90MB)将在首次运行时下载并缓存在 ~/.cache/huggingface/.
演示
展示Ragex所有功能的全面演示可在 examples/product_cart/.
该演示使用了一个故意平庸的电子商务购物车应用程序来演示:
- 安全漏洞扫描(检测到8+个问题)
- 代码复杂性分析(圈、认知、霍尔斯特德度量)
- 代码气味检测(长函数、深度嵌套、幻数)
- 代码重复检测(I-IV型克隆)
- 死代码分析(4个未使用的函数)
- 依赖与耦合分析
- 影响分析和重构建议
- AI增强功能(ValidationAI、AIPreview、AIRefiner、AIAnalyzer、AIInsights)
快速入门:
cd examples/product_cart
./run_demo.sh演示生成了11份详细报告,显示:
- 8个安全漏洞(2个严重,3个高)
- 5种类型的18种代码气味
- 52行重复代码(占代码库的10%)
- 28行死代码(占代码库的7%)
- 8条优先重构建议
- 预期改进:可维护性提高65%
看 制作购物车自述文件 了解完整细节和 产品购物车演示 用于逐步演练。
用法
作为MCP服务器
建议的切入点是 bin/ragex-mcp,一个自包含的启动器,处理编译,检测正在运行的实例并桥接到它,而不是启动第二个VM,并为stdio MCP通信设置正确的环境:
bin/ragex-mcp
# Auto-analyze a project on startup
bin/ragex-mcp --project /path/to/your/project
# Override log verbosity
bin/ragex-mcp --log-level debug或者,可以使用裸服务器启动(不带网桥逻辑):
./start_mcp.sh有关详细的安装说明和特定于客户端的配置(Claude Desktop、Cursor、Zed、LunarVim、通用stdio),请参阅 使用Ragex作为MCP服务器.
启动时自动分析目录
您可以将Ragex配置为在启动时自动分析特定目录。添加 config/config.exs:
config :ragex, :auto_analyze_dirs, [
"/opt/Proyectos/MyProject",
"~/workspace/important-lib"
]这会将您经常使用的代码库预加载到知识图中,使其立即可供查询。看 配置 了解详情。
MCP协议示例
初始化服务器:
{"jsonrpc":"2.0","method":"initialize","params":{"clientInfo":{"name":"test-client","version":"1.0"}},"id":1}列出可用工具:
{"jsonrpc":"2.0","method":"tools/list","id":2}分析文件(自动检测):
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "analyze_file",
"arguments": {
"path": "lib/ragex.ex"
}
},
"id": 3
}或者明确指定语言:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "analyze_file",
"arguments": {
"path": "script.py",
"language": "python"
}
},
"id": 3
}查询图表:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "query_graph",
"arguments": {
"query_type": "find_module",
"params": {"name": "Ragex"}
}
},
"id": 4
}发展
运行测试
mix test交互式开发
RAGEX_NO_SERVER=1 iex -S mix# Analyze a file
{:ok, content} = File.read("lib/ragex.ex")
{:ok, analysis} = Ragex.Analyzers.Elixir.analyze(content, "lib/ragex.ex")
# Check graph stats, it’s expected to be empty for this single file
Ragex.stats()MCP工具参考
岩心分析工具
analyze_file
分析源文件并将代码结构提取到知识图中。
参数:
path(string,必填):文件路径language(字符串,可选):编程语言-elixir,erlang,python,javascript,typescript,或auto(默认:从扩展自动检测)generate_embeddings(布尔值,可选):为语义搜索生成嵌入(默认值:true)
analyze_directory
批处理分析目录中的所有源文件。
参数:
path(字符串,必填):目录路径language(字符串,可选):过滤文件的语言(默认:自动检测)recursive(布尔值,可选):递归分析子目录(默认值:true)generate_embeddings(boolean,可选):生成嵌入(默认值:true)
query_graph
查询知识图中的代码实体和关系(符号搜索)。
参数:
query_type(字符串,必填):查询类型
- find_module:按名称查找模块 - find_function:按模块和名称查找函数 - get_calls:获取函数调用关系 - get_dependencies:获取模块依赖关系
params(object,必填):查询特定参数
list_nodes
列出知识图中所有具有可选过滤功能的节点。
参数:
node_type(字符串,可选):按类型(模块、函数等)筛选limit(整数,可选):最大结果(默认值:100)
文件监视工具
watch_directory
文件更改时自动重新索引。
参数:
path(string,必填):要查看的目录
unwatch_directory
停止查看目录。
参数:
path(string,必填):停止观看的目录
list_watched
列出所有关注的目录。
参数: 无
语义搜索工具
semantic_search
使用向量嵌入执行自然语言代码搜索。
参数:
query(字符串,必填):自然语言查询(例如,“解析JSON的函数”)limit(整数,可选):最大结果(默认值:10)threshold(数字,可选):最小相似性得分0.0-1.0(默认值:0.7)node_type(字符串,可选):按类型(模块、函数)筛选include_context(布尔值,可选):包括调用者/被调用者上下文(默认值:false)
例子:
{
"query": "HTTP request handler",
"limit": 5,
"threshold": 0.75,
"node_type": "function"
}hybrid_search
将符号图查询与语义搜索相结合,以获得最佳结果。
参数:
query(字符串,必填):搜索查询strategy(字符串,可选):搜索策略:
- fusion (默认):两种方法的RRF融合 - semantic_first:语义搜索然后图形过滤 - graph_first:图形查询,然后进行语义排名
limit(整数,可选):最大结果(默认值:10)threshold(数字,可选):最小相似度(默认值:0.7)graph_filter(对象,可选):可选符号约束include_context(布尔值,可选):包含上下文(默认值:false)
例子:
{
"query": "database connection",
"strategy": "fusion",
"limit": 10,
"graph_filter": {"module": "DB"}
}get_embeddings_stats
返回ML模型和向量存储统计信息。
参数: 无
退货:
- 型号信息(名称、尺寸、状态)
- 矢量存储度量(按类型划分的总嵌入量)
- 图形统计(节点、边)
代码编辑工具
edit_file
通过自动备份、验证和原子操作安全地编辑单个文件。
参数:
path(string,必填):要编辑的文件的路径changes(数组,必填):要应用的更改列表
- type (字符串): replace, insert,或 delete - line_start (整数):起始行号(1-索引) - line_end (整数):结束行号(用于替换/删除) - content (string):新内容(用于替换/插入)
validate(布尔值,可选):应用前验证语法(默认值:true)create_backup(布尔值,可选):编辑前创建备份(默认值:true)format(布尔值,可选):编辑后格式化代码(默认值:false)language(字符串,可选):用于验证的显式语言(从扩展中自动检测)
例子:
{
"path": "lib/my_module.ex",
"changes": [
{
"type": "replace",
"line_start": 10,
"line_end": 15,
"content": "def new_function do\n :ok\nend"
}
],
"validate": true,
"format": true
}edit_files
原子编辑多个文件,并在失败时进行协调回滚。
参数:
files(数组,必填):要编辑的文件列表
- path (string):文件的路径 - changes (array):更改列表(格式与 edit_file) - validate (布尔值,可选):覆盖事务级别验证 - format (布尔值,可选):覆盖事务级别格式 - language (字符串,可选):此文件的显式语言
validate(布尔值,可选):在应用之前验证所有文件(默认值:true)create_backup(布尔值,可选):为所有文件创建备份(默认值:true)format(布尔值,可选):编辑后格式化所有文件(默认值:false)
例子:
{
"files": [
{
"path": "lib/module_a.ex",
"changes": [{"type": "replace", "line_start": 5, "line_end": 5, "content": "@version \"2.0.0\""}]
},
{
"path": "lib/module_b.ex",
"changes": [{"type": "replace", "line_start": 10, "line_end": 12, "content": "# Updated"}]
}
],
"validate": true,
"format": true
}validate_edit
预览更改的验证,而不应用它们。
参数:
path(string,必填):文件路径changes(数组,必填):要验证的更改列表language(字符串,可选):用于验证的显式语言
rollback_edit
通过从备份还原来撤消最近的编辑。
参数:
path(string,必填):要回滚的文件的路径backup_id(字符串,可选):要还原的特定备份(默认值:最新)
edit_history
查询文件的备份历史记录。
参数:
path(string,必填):文件路径limit(整数,可选):要返回的最大备份数(默认值:10)
refactor_code
使用AST分析和知识图进行语义重构操作。
参数:
operation(字符串,必填):重构类型-rename_function或rename_moduleparams(object,必填):操作特定参数
- 对于 rename_function: - module (string):包含函数的模块 - old_name (string):当前函数名 - new_name (string):新函数名 - arity (整数):函数性 - 对于 rename_module: - old_name (string):当前模块名称 - new_name (string):新模块名称
scope(字符串,可选):module(仅限同一文件)或project(所有文件,默认值:项目)validate(布尔值,可选):在之前/之后验证(默认值:true)format(布尔值,可选):设置代码后的格式(默认值:true)
示例-重命名函数:
{
"operation": "rename_function",
"params": {
"module": "MyModule",
"old_name": "old_function",
"new_name": "new_function",
"arity": 2
},
"scope": "project",
"validate": true,
"format": true
}示例-重命名模块:
{
"operation": "rename_module",
"params": {
"old_name": "OldModule",
"new_name": "NewModule"
},
"validate": true
}RAG(AI驱动)工具
rag_query
使用人工智能辅助的检索增强生成查询代码库。
参数:
query(string,必填):关于代码库的自然语言查询limit(整数,可选):要检索的最大代码段数(默认值:10)include_code(布尔值,可选):在上下文中包含完整的代码片段(默认值:true)provider(字符串,可选):AI提供者覆盖(deepseek_r1)
例子:
{
"query": "How does authentication work in this codebase?",
"limit": 15,
"include_code": true
}退货:
- 基于检索到的代码上下文的AI生成响应
- 来源计数和型号信息
rag_explain
在人工智能的帮助下,使用RAG和面向方面的分析来解释代码。
参数:
target(string,必填):文件路径或函数标识符(例如。,MyModule.function/2)aspect(字符串,可选):解释什么-purpose,complexity,dependencies,或all(默认值:all)
例子:
{
"target": "Ragex.Graph.Store.add_node/3",
"aspect": "complexity"
}退货:
- 基于代码分析的AI生成解释
- 相关代码上下文和依赖关系
rag_suggest
使用RAG和AI分析提出代码改进建议。
参数:
target(string,必填):文件路径或函数标识符focus(字符串,可选):改进重点-performance,readability,testing,security,或all(默认值:all)
例子:
{
"target": "lib/ragex/editor/core.ex",
"focus": "performance"
}退货:
- 人工智能生成的改进建议
- 代码上下文和基本原理
配置:
RAG工具需要 DEEPSEEK_API_KEY 环境变量:
export DEEPSEEK_API_KEY="sk-xxxxxxxxxxxxx"文档
- 使用Ragex作为MCP服务器 -安装、客户端设置、RAG查询、配置
- 使用指南 -编辑器特定集成(VIM、LunarVim)
- Zed编辑器集成 -具有任务和键绑定的一流Zed支持
- 配置 -嵌入模型配置和迁移
- MCP工具参考 -完整的刀具参数参考
- 算法 -图算法和复杂性
- 分析 -代码分析功能和工具
- 重构建议 -自动重构建议引擎
- 坚持 -嵌入缓存管理和性能
- MCP提示 -预构建的高级工作流
- MCP资源 -只读状态访问
- 流媒体通知 -实时进度事件
- 故障排除 -常见问题和错误消息
缓存管理
Ragex会自动缓存嵌入,以加快启动速度:
# View cache statistics
mix ragex.cache.stats
# Clear current project cache
mix ragex.cache.clear --current
# Clear all caches
mix ragex.cache.clear --all --forceTODO:流媒体增强功能
以下流媒体改进已计划但尚未实施:
- 提供程序中的工具调用增量解析:目前,所有四个提供商(DeepSeek、OpenAI、Anthropic、Ollama)的流式解析器都在默默地跳过
tool_callsSSE河三角洲。添加基于索引function.arguments即使在代理循环中的中间工具调用步骤期间,累积也将允许实时思考令牌。这需要每个提供者的工作(OpenAI/DeepSeek:delta.tool_calls[i];人类学:content_block_start+input_json_delta;Ollama:API不支持)。
- 完整的MCP流协议:每个块发出单独的JSON-RPC流式响应(不仅仅是通知),允许MCP客户端增量呈现响应。包括通过MCP协议的取消支持。
- 流缓存和回放:缓存来自已消耗流的重建响应,以便可以从缓存中提供重复查询,而无需重新调用AI提供者。
支持的语言
| 语言 | 扩展 | 分析器 | 状态 |
|---|---|---|---|
| 灵丹妙药 | .ex, .exs | 天然AST(Code.string_to_quoted) | ✓ 满 |
| 二郎 | .erl, .hrl | 天然AST(:erl_scan, :erl_parse) | ✓ 满 |
python .py python ast 模块(子流程) | ✓ 满 | ||
| JavaScript/TypeScript | .js, .jsx, .ts, .tsx, .mjs | 基于正则表达式 | ✗ 基础 |
