narsil-mcp

作者 postrv已验证

Rust MCP server for comprehensive code intelligence - 90 tools, 32 languages, security scanning, call graphs, and more

181
Stars
26
Forks
Rust
语言
2026/8/23
添加时间

⚠️ 第三方软件声明

本 Skill 为第三方开源软件,独立托管于 GitHub。SkillTip 仅为信息目录,不控制或维护底层仓库。所显示的安全检查为自动化且范围有限,安装前请自行审查源码。

阅读服务条款

安装

添加到你的 Claude Code skills 目录:

# Add to your Claude Code skills
git clone https://github.com/postrv/narsil-mcp

快速入门

使用 narsil-mcp 等 Skills 的指南。

安全报告

已验证

上次扫描:—

{
  "status": "PASSED",
  "issues": []
}

README.md

narsil-mcp

The blazing-fast, privacy-first MCP server for deep code intelligence

License Rust Tests MCP

A Rust-powered MCP (Model Context Protocol) server providing AI assistants with deep code understanding through 90 specialized tools.

Why narsil-mcp?

Featurenarsil-mcpXRAYSerenaGitHub MCP
Languages32430+ (LSP)N/A
Neural SearchYesNoNoNo
Taint AnalysisYesNoNoNo
SBOM/LicensesYesNoNoPartial
Offline/LocalYesYesYesNo
WASM/BrowserYesNoNoNo
Call GraphsYesPartialNoNo
Type InferenceYesNoNoNo

Key Features

  • Code Intelligence - Symbol extraction, semantic search, call graph analysis
  • Neural Semantic Search - Find similar code using embeddings (Voyage AI, OpenAI)
  • Security Analysis - Taint analysis, vulnerability scanning, OWASP/CWE coverage
  • Supply Chain Security - SBOM generation, dependency auditing, license compliance
  • Advanced Analysis - Control flow graphs, data flow analysis, dead code detection

Why Choose narsil-mcp?

  • Written in Rust - Blazingly fast, memory-safe, single binary (~30MB)
  • Tree-sitter powered - Accurate, incremental parsing for 32 languages
  • Zero config - Point at repos and go
  • MCP compliant - Works with Claude, Cursor, VS Code Copilot, Zed, and any MCP client
  • Privacy-first - Fully local, no data leaves your machine
  • Parallel indexing - Uses all cores via Rayon
  • Smart excerpts - Expands to complete syntactic scopes
  • Security-first - Built-in vulnerability detection and taint analysis
  • Neural embeddings - Optional semantic search with Voyage AI or OpenAI
  • WASM support - Run in browser with WebAssembly build
  • Real-time streaming - Results as indexing progresses for large repos

Supported Languages

LanguageExtensionsSymbols Extracted
Rust.rsfunctions, structs, enums, traits, impls, mods
Python.py, .pyifunctions, classes
JavaScript.js, .jsx, .mjsfunctions, classes, methods, variables
TypeScript.ts, .tsxfunctions, classes, interfaces, types, enums
Go.gofunctions, methods, types
C.c, .hfunctions, structs, enums, typedefs
C++.cpp, .cc, .hppfunctions, classes, structs, namespaces
Java.javamethods, classes, interfaces, enums
C#.csmethods, classes, interfaces, structs, enums, delegates, namespaces
Bash.sh, .bash, .zshfunctions, variables
Ruby.rb, .rake, .gemspecmethods, classes, modules
Kotlin.kt, .ktsfunctions, classes, objects, interfaces
PHP.php, .phtmlfunctions, methods, classes, interfaces, traits
Swift.swiftclasses, structs, enums, protocols, functions
Verilog/SystemVerilog.v, .vh, .sv, .svhmodules, tasks, functions, interfaces, classes
Scala.scala, .scclasses, objects, traits, functions, vals
Lua.luafunctions, methods
Haskell.hs, .lhsfunctions, data types, type classes
Elixir.ex, .exsmodules, functions
Clojure.clj, .cljs, .cljc, .ednlists (basic AST)
Dart.dartfunctions, classes, methods
Julia.jlfunctions, modules, structs
R.R, .r, .Rmdfunctions
Perl.pl, .pm, .tfunctions, packages
Zig.zigfunctions, variables
Erlang.erl, .hrlfunctions, modules, records
Elm.elmfunctions, types
Fortran.f90, .f95, .f03, .f08, .f, .for, .fppprograms, subroutines, functions, modules
PowerShell.ps1, .psm1, .psd1functions, classes, enums
Nix.nixbindings
Groovy.groovy, .gradlemethods, classes, interfaces, enums, functions

Installation

Via Package Managers (Recommended)

macOS / Linux (Homebrew):

brew tap postrv/narsil
brew install narsil-mcp

Windows (Scoop):

scoop bucket add narsil https://github.com/postrv/scoop-narsil
scoop install narsil-mcp

Rust/Cargo (all platforms):

cargo install narsil-mcp

Node.js/npm (all platforms):

npm install -g narsil-mcp
# or
yarn global add narsil-mcp
# or
pnpm add -g narsil-mcp

Nix:

# Run directly without installing
nix run github:postrv/narsil-mcp -- --repos ./my-project

# Install to profile
nix profile install github:postrv/narsil-mcp

# With web visualization frontend
nix profile install github:postrv/narsil-mcp#with-frontend

# Development shell
nix develop github:postrv/narsil-mcp

One-Click Install Script

macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/postrv/narsil-mcp/main/install.sh | bash

Windows (PowerShell):

irm https://raw.githubusercontent.com/postrv/narsil-mcp/main/install.ps1 | iex

Windows (Git Bash / MSYS2):

curl -fsSL https://raw.githubusercontent.com/postrv/narsil-mcp/main/install.sh | bash

Note for Windows users: The PowerShell installer provides better error messages and native Windows integration. It will automatically configure your PATH and check for required build tools if building from source.

From Source

Prerequisites:

# Clone and build
git clone git@github.com:postrv/narsil-mcp.git
cd narsil-mcp
cargo build --release

# Binary will be at:
# - macOS/Linux: target/release/narsil-mcp
# - Windows: target/release/narsil-mcp.exe

Feature Builds

narsil-mcp supports different feature sets for different use cases:

# Default build - native MCP server (~30MB)
cargo build --release

# With RDF knowledge graph and CCG tools (~35MB) - SPARQL queries, Code Context Graph
cargo build --release --features graph

# With neural vector search (~32MB) - adds TF-IDF similarity
cargo build --release --features neural

# With ONNX model support (~50MB) - adds local neural embeddings
cargo build --release --features neural-onnx

# With embedded visualization frontend (~31MB)
cargo build --release --features frontend

# Full-featured build with graph + frontend (~40MB)
cargo build --release --features graph,frontend

# For browser/WASM usage
cargo build --release --target wasm32-unknown-unknown --features wasm
FeatureDescriptionSize
native (default)Full MCP server with all tools~30MB
graph+ RDF knowledge graph, SPARQL, CCG tools~35MB
frontend+ Embedded visualization web UI~31MB
neural+ TF-IDF vector search, API embeddings~32MB
neural-onnx+ Local ONNX model inference~50MB
wasmBrowser build (no file system, git)~3MB

Important: The --graph CLI flag requires the binary to be built with --features graph. If you pass --graph to a binary built without this feature, you'll see a warning and SPARQL/CCG tools won't be available. See Troubleshooting below.

For detailed installation instructions, troubleshooting, and platform-specific guides, see docs/INSTALL.md.

Usage

Basic Usage

macOS / Linux:

# Index a single repository
narsil-mcp --repos /path/to/your/project

# Index multiple repositories
narsil-mcp --repos ~/projects/project1 --repos ~/projects/project2

# Enable verbose logging
narsil-mcp --repos /path/to/project --verbose

# Force re-index on startup
narsil-mcp --repos /path/to/project --reindex

Windows (PowerShell / CMD):

# Index a single repository
narsil-mcp --repos C:\Users\YourName\Projects\my-project

# Index multiple repositories
narsil-mcp --repos C:\Projects\project1 --repos C:\Projects\project2

# Enable verbose logging
narsil-mcp --repos C:\Projects\my-project --verbose

# Force re-index on startup
narsil-mcp --repos C:\Projects\my-project --reindex

Full Feature Set

narsil-mcp \
  --repos ~/projects/my-app \
  --git \           # Enable git blame, history, contributors
  --call-graph \    # Enable function call analysis
  --persist \       # Save index to disk for fast startup
  --watch \         # Auto-reindex on file changes
  --lsp \           # Enable LSP for hover, go-to-definition
  --streaming \     # Stream large result sets
  --remote \        # Enable GitHub remote repo support
  --neural \        # Enable neural semantic embeddings
  --neural-backend api \  # Backend: "api" (Voyage/OpenAI) or "onnx"
  --neural-model voyage-code-2 \  # Model to use
  --neural-dimension 3072 \  # Override embedding dimensions (auto-detected per model)
  --graph           # Enable SPARQL/RDF knowledge graph and CCG tools (requires --features graph build)

Note about --graph: This flag enables SPARQL queries and Code Context Graph (CCG) tools, but only if the binary was built with --features graph. The default binary does not include this feature. If you need SPARQL/CCG capabilities, build from source with:

cargo build --release --features graph

If you pass --graph to a binary without the feature, you'll see a warning at startup and the server will continue without SPARQL/CCG tools.

Note: Neural embeddings require an API key (or custom endpoint). The easiest way to set this up is with the interactive wizard:

# Run the neural API key setup wizard
narsil-mcp config init --neural

The wizard will:

  • Detect your editor (Claude Desktop, Claude Code, Zed, VS Code, JetBrains)
  • Prompt for your API provider (Voyage AI, OpenAI, or custom)
  • Validate your API key
  • Automatically add it to your editor's MCP config

Alternatively, you can manually set one of these environment variables:

  • EMBEDDING_API_KEY - Generic API key for any provider
  • VOYAGE_API_KEY - Voyage AI specific API key
  • OPENAI_API_KEY - OpenAI specific API key
  • EMBEDDING_SERVER_ENDPOINT - Custom embedding API endpoint URL (optional, allows using self-hosted models)

Configuration

v1.1.0+ introduces optional configuration for fine-grained control over tools and performance. All existing usage continues to work - configuration is completely optional!

Quick Start

# Generate default config interactively
narsil-mcp config init

# List available tools
narsil-mcp tools list

# Apply a preset via CLI
narsil-mcp --repos ~/project --preset minimal

Automatic Editor Detection

narsil-mcp detects your editor and applies an optimal preset automatically:

EditorPresetToolsContext TokensWhy
ZedMinimal26~4,686Fast startup, minimal context
VS CodeBalanced51~8,948Good feature balance
Claude DesktopFull90~12,001Maximum capabilities

Token Savings:

  • Minimal preset: 61% fewer tokens vs Full
  • Balanced preset: 25% fewer tokens vs Full

Presets

Choose a preset based on your use case:

# Minimal - Fast, lightweight (Zed, Cursor)
narsil-mcp --repos ~/project --preset minimal

# Balanced - Good defaults (VS Code, IntelliJ)
narsil-mcp --repos ~/project --preset balanced --git --call-graph

# Full - All features (Claude Desktop, comprehensive analysis)
narsil-mcp --repos ~/project --preset full --git --call-graph

# Security-focused - Security and supply chain tools
narsil-mcp --repos ~/project --preset security-focused

Configuration Files

User config (~/.config/narsil-mcp/config.yaml):

version: "1.0"
preset: "balanced"

tools:
  # Disable slow tools
  overrides:
    neural_search:
      enabled: false
      reason: "Too slow for interactive use"

performance:
  max_tool_count: 50  # Limit total tools

Project config (.narsil.yaml in repo root):

version: "1.0"
preset: "security-focused"  # Override user preset

tools:
  categories:
    Security:
      enabled: true
    SupplyChain:
      enabled: true

Named repository profiles are useful for multi-repo workspaces:

version: "1.0"
profiles:
  platform:
    repos:
      - ~/src/api
      - ~/src/web
    git: true
    call_graph: true
    persist: true
    preset: balanced
narsil-mcp --profile platform
narsil-mcp config profiles

Priority: CLI flags > Environment vars > Project config > User config > Defaults

Environment Variables

# Select repos/profile
export NARSIL_REPOS=~/src/api,~/src/web
export NARSIL_PROFILE=platform

# Apply preset
export NARSIL_PRESET=minimal

# Enable specific categories
export NARSIL_ENABLED_CATEGORIES=Repository,Symbols,Search

# Disable specific tools
export NARSIL_DISABLED_TOOLS=neural_search,generate_sbom

CLI Commands

# View effective config
narsil-mcp config show

# Validate config file
narsil-mcp config validate ~/.config/narsil-mcp/config.yaml

# List tools by category
narsil-mcp tools list --category Search

# Search for tools
narsil-mcp tools search "git"

# Export config
narsil-mcp config export > my-config.yaml

# List named repository profiles
narsil-mcp config profiles

Learn More:

Visualization Frontend

Explore call graphs, imports, symbol references, and control flow interactively in your browser.

# Build with embedded frontend
cargo build --release --features frontend

# Run with HTTP server
narsil-mcp --repos ~/project --http --call-graph
# Open http://localhost:3000

Five graph views:

ViewDescription
Call GraphFunction call relationships with depth control and direction filtering
Import GraphFile-level import dependencies across the codebase
Symbol GraphAll references to a symbol, with file clustering
HybridCombined call + import graph with split budget
Control FlowReal CFG with basic blocks, branches, and loop back-edges

Features:

  • Interactive Cytoscape.js graphs with drag, zoom, and double-click drill-down
  • Complexity metrics overlay with color coding (green/yellow/orange/red)
  • Security vulnerability overlay highlighting taint sources and sinks
  • Six layout algorithms (dagre, force-directed, breadthfirst, concentric, circle, grid)
  • File tree sidebar with syntax-highlighted code viewer
  • URL-driven state (shareable links, browser back/forward)
  • Dark mode support
  • Node detail panel with code excerpts and navigation to source

Full documentation: See docs/frontend.md for setup, API endpoints, and development mode.

Neural Semantic Search

Find similar code using neural embeddings - even when variable names and structure differ.

# Quick setup with wizard
narsil-mcp config init --neural

# Or manually with Voyage AI
export VOYAGE_API_KEY="your-key"
narsil-mcp --repos ~/project --neural --neural-model voyage-code-2

Supports Voyage AI, OpenAI, custom endpoints, and local ONNX models.

Full documentation: See docs/neural-search.md for setup, backends, and use cases.

Type Inference

Built-in type inference for Python, JavaScript, and TypeScript - no mypy or tsc required.

ToolDescription
infer_typesGet inferred types for all variables in a function
check_type_errorsFind potential type mismatches
get_typed_taint_flowEnhanced security analysis with type info
def process(data):
    result = data.split(",")  # result: list[str]
    count = len(result)       # count: int
    return count * 2          # returns: int

Forgemax Integration (Experimental)

For large-scale agentic workflows, narsil-mcp can be used through Forgemax — a Code Mode MCP gateway that collapses all 90 tools into just 2 (search + execute), reducing tool schema overhead from ~12,000 tokens to ~1,000.

# Install Forgemax
cargo install forgemax

# Run narsil-mcp through Forgemax (uses forge.toml in repo root)
forgemax

The included forge.toml configures narsil-mcp with sensible defaults:

[servers.narsil]
command = "narsil-mcp"
args = ["--repos", ".", "--git", "--call-graph", "--persist", "--watch"]
transport = "stdio"

[sandbox]
timeout_secs = 10
max_heap_mb = 64
max_concurrent = 8

The LLM writes JavaScript that calls through typed proxy objects inside a sandboxed V8 isolate — credentials, file paths, and internal state never leave the host. This approach is particularly useful when working with multiple MCP servers simultaneously, as it keeps the total tool context small and predictable.

MCP Configuration

Add narsil-mcp to your AI assistant by creating a configuration file. Here are the recommended setups:


Claude Code (.mcp.json in project root - Recommended):

Create .mcp.json in your project directory for per-project configuration:

{
  "mcpServers": {
    "narsil-mcp": {
      "command": "narsil-mcp",
      "args": ["--repos", ".", "--git", "--call-graph"]
    }
  }
}

Then start Claude Code in your project:

cd /path/to/project
claude

Using . for --repos automatically indexes the current directory. Claude now has access to 90 code intelligence tools.

Tip: Add --persist --index-path .claude/cache for faster startup on subsequent runs.

For global configuration, edit ~/.claude/settings.json instead. See Claude Code Integration for advanced setups.


Cursor (.cursor/mcp.json):

{
  "mcpServers": {
    "narsil-mcp": {
      "command": "narsil-mcp",
      "args": ["--repos", ".", "--git", "--call-graph"]
    }
  }
}

VS Code + GitHub Copilot (.vscode/mcp.json):

{
  "servers": {
    "narsil-mcp": {
      "command": "narsil-mcp",
      "args": ["--repos", ".", "--git", "--call-graph"]
    }
  }
}

Note for Copilot Enterprise: MCP support requires VS Code 1.102+ and must be enabled by your organization administrator.


Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "narsil-mcp": {
      "command": "narsil-mcp",
      "args": ["--repos", "/path/to/your/projects", "--git"]
    }
  }
}

Zed (settings.json → Context Servers):

{
  "context_servers": {
    "narsil-mcp": {
      "command": "narsil-mcp",
      "args": ["--repos", ".", "--git"]
    }
  }
}

Note for Zed: narsil-mcp starts immediately and indexes in the background, preventing initialization timeouts.


Claude Code Plugin

For Claude Code users, we provide a plugin with slash commands and a skill for effective tool usage.

Install via Marketplace (Recommended):

# Add the narsil-mcp marketplace
/plugin marketplace add postrv/narsil-mcp

# Install the plugin
/plugin install narsil@narsil-mcp

Or install directly from GitHub:

/plugin install github:postrv/narsil-mcp/narsil-plugin

What's included:

ComponentDescription
/narsil:security-scanRun comprehensive security audits
/narsil:exploreExplore unfamiliar codebases
/narsil:analyze-functionDeep dive on specific functions
/narsil:find-featureFind where features are implemented
/narsil:supply-chainAnalyze supply chain security
SkillGuides Claude on using 90 tools effectively
MCP ConfigAuto-starts narsil-mcp with sensible defaults

See narsil-plugin/README.md for full documentation.

Ralph Automation Integration

Ralph is a Claude Code automation suite for autonomous code development. When narsil-mcp is available, Ralph gains enhanced code intelligence capabilities:

FeatureWithout narsil-mcpWith narsil-mcp
Security scanningBasic (clippy)OWASP/CWE vulnerability detection
Code understandingFile-basedCall graphs, symbol references
Architecture analysisManualCCG L0/L1/L2 automatic layers
Dependency analysiscargo treeImport graphs, circular detection

Setup:

# Install narsil-mcp (Ralph auto-detects it)
cargo install narsil-mcp

# Ralph's quality gates use these tools:
narsil-mcp scan_security --repo <name>
narsil-mcp check_type_errors --repo <name> --path src
narsil-mcp find_injection_vulnerabilities --repo <name>

Ralph gracefully degrades when narsil-mcp is unavailable - all core automation features work without it.

Documentation: See Ralph README for full integration details.

Playbooks & Tutorials

See docs/playbooks for practical usage guides:

GuideDescription
Getting StartedQuick setup and first tool calls
Understand a CodebaseExplore unfamiliar projects
Fix a BugDebug with call graphs and taint analysis
Security AuditFind vulnerabilities with OWASP/CWE scanning
Code ReviewReview changes effectively

Each playbook shows the exact tool chains Claude uses to answer your questions.

WebAssembly (Browser) Usage

narsil-mcp can run entirely in the browser via WebAssembly - perfect for browser-based IDEs, code review tools, or educational platforms.

npm install @narsil-mcp/wasm
import { CodeIntelClient } from '@narsil-mcp/wasm';

const client = new CodeIntelClient();
await client.init();
client.indexFile('src/main.rs', rustSourceCode);
const symbols = client.findSymbols('Handler');

Full documentation: See docs/wasm.md for build instructions, React examples, and API reference.

Available Tools (90)

Repository & File Management

ToolDescription
list_reposList all indexed repositories with metadata
get_project_structureGet directory tree with file icons and sizes
get_fileGet file contents with optional line range
get_excerptExtract code around specific lines with context
reindexTrigger re-indexing of repositories
discover_reposAuto-discover repositories in a directory
validate_repoCheck if path is a valid repository
get_index_statusShow index stats and enabled features

Symbol Search & Navigation

ToolDescription
find_symbolsFind structs, classes, functions by type/pattern
get_symbol_definitionGet symbol source with surrounding context
find_referencesFind all references to a symbol
get_dependenciesAnalyze imports and dependents
workspace_symbol_searchFuzzy search symbols across workspace
find_symbol_usagesCross-file symbol usage with imports
get_export_mapGet exported symbols from a file/module

Code Search

ToolDescription
search_codeKeyword search with relevance ranking
semantic_searchBM25-ranked semantic search
hybrid_searchCombined BM25 + TF-IDF with rank fusion
search_chunksSearch over AST-aware code chunks
find_similar_codeFind code similar to a snippet (TF-IDF)
find_similar_to_symbolFind code similar to a symbol

AST-Aware Chunking

ToolDescription
get_chunksGet AST-aware chunks for a file
get_chunk_statsStatistics about code chunks
get_embedding_statsEmbedding index statistics

Neural Semantic Search (requires --neural)

ToolDescription
neural_searchSemantic search using neural embeddings (finds similar code even with different names)
find_semantic_clonesFind Type-3/4 semantic clones of a function
get_neural_statsNeural embedding index statistics

Call Graph Analysis (requires --call-graph)

ToolDescription
get_call_graphGet call graph for repository/function
get_callersFind functions that call a function
get_calleesFind functions called by a function
find_call_pathFind path between two functions
get_complexityGet cyclomatic/cognitive complexity
get_function_hotspotsFind highly connected functions

Control Flow Analysis

ToolDescription
get_control_flowGet CFG showing basic blocks and branches
find_dead_codeFind unreachable code blocks

Data Flow Analysis

ToolDescription
get_data_flowVariable definitions and uses
get_reaching_definitionsWhich assignments reach each point
find_uninitializedVariables used before initialization
find_dead_storesAssignments that are never read

Type Inference (Python/JavaScript/TypeScript)

ToolDescription
infer_typesInfer types for variables in a function without external type checkers
check_type_errorsFind potential type errors without running mypy/tsc
get_typed_taint_flowEnhanced taint analysis combining data flow with type inference

Import/Dependency Graph

ToolDescription
get_import_graphBuild and analyze import graph
find_circular_importsDetect circular dependencies
get_incremental_statusMerkle tree and change statistics

Security Analysis - Taint Tracking

ToolDescription
find_injection_vulnerabilitiesFind SQL injection, XSS, command injection, path traversal
trace_taintTrace tainted data flow from a source
get_taint_sourcesList taint sources (user input, files, network)
get_security_summaryComprehensive security risk assessment

Security Analysis - Rules Engine

ToolDescription
scan_securityScan with security rules (OWASP, CWE, crypto, secrets)
check_owasp_top10Scan for OWASP Top 10 2021 vulnerabilities
check_cwe_top25Scan for CWE Top 25 weaknesses
explain_vulnerabilityGet detailed vulnerability explanation
suggest_fixGet remediation suggestions for findings

Supply Chain Security

ToolDescription
generate_sbomGenerate SBOM (CycloneDX/SPDX/JSON)
check_dependenciesCheck for known vulnerabilities (OSV database)
check_licensesAnalyze licenses for compliance issues
find_upgrade_pathFind safe upgrade paths for vulnerable deps

Git Integration (requires --git)

ToolDescription
get_blameGit blame for file
get_file_historyCommit history for file
get_recent_changesRecent commits in repository
get_hotspotsFiles with high churn and complexity
get_contributorsRepository/file contributors
get_commit_diffDiff for specific commit
get_symbol_historyCommits that changed a symbol
get_branch_infoCurrent branch and status
get_modified_filesWorking tree changes

LSP Integration (requires --lsp)

ToolDescription
get_hover_infoType info and documentation
get_type_infoPrecise type information
go_to_definitionFind definition location

Remote Repository Support (requires --remote)

ToolDescription
add_remote_repoClone and index GitHub repository
list_remote_filesList files via GitHub API
get_remote_fileFetch file via GitHub API

Metrics

ToolDescription
get_metricsPerformance stats and timing

SPARQL / Knowledge Graph (requires --graph)

ToolDescription
sparql_queryExecute SPARQL query against RDF knowledge graph
list_sparql_templatesList available SPARQL query templates
run_sparql_templateExecute predefined SPARQL template with parameters

Code Context Graph (CCG) (requires --graph)

CCG provides standardized, AI-consumable representations of codebases in tiered layers.

ToolDescription
get_ccg_manifestLayer 0 manifest (~1-2KB JSON-LD) - repo identity, counts
export_ccg_manifestExport Layer 0 manifest to file
export_ccg_architectureLayer 1 architecture (~10-50KB JSON-LD) - modules, API
export_ccg_indexLayer 2 symbol index (~100-500KB N-Quads gzipped)
export_ccg_fullLayer 3 full detail (~1-20MB N-Quads gzipped)
export_ccgExport all CCG layers as a bundle
query_ccgQuery CCG using SPARQL
get_ccg_aclGenerate WebACL access control for CCG layers
get_ccg_access_infoGet CCG access tier information
import_ccgImport CCG layer from URL or file
import_ccg_from_registryImport CCG from codecontextgraph.com registry

Security Rules

narsil-mcp includes built-in security rules in rules/:

Core Rulesets:

  • owasp-top10.yaml - OWASP Top 10 2021 vulnerability patterns
  • cwe-top25.yaml - CWE Top 25 Most Dangerous Weaknesses
  • crypto.yaml - Cryptographic issues (weak algorithms, hardcoded keys)
  • secrets.yaml - Secret detection (API keys, passwords, tokens)

Language-Specific Rules:

  • rust.yaml - Rust security patterns (unsafe transmute, FFI boundaries, command injection, TOCTOU)
  • elixir.yaml - Elixir/BEAM patterns (atom exhaustion, binary_to_term, Code.eval, Ecto SQL injection)
  • go.yaml - Go security patterns (SQL injection, TLS, command injection)
  • java.yaml - Java vulnerabilities (XXE, deserialization, LDAP injection)
  • csharp.yaml - C# security issues (deserialization, XSS, path traversal)
  • kotlin.yaml - Kotlin/Android patterns (WebView, intents, secrets)
  • bash.yaml - Shell script vulnerabilities (command injection, eval)

Infrastructure & Configuration:

  • iac.yaml - Infrastructure as Code (Terraform, CloudFormation, Kubernetes)
  • config.yaml - Configuration file security (hardcoded credentials, insecure settings)

Custom rules can be loaded with scan_security --ruleset /path/to/rules.yaml.

Architecture

+-----------------------------------------------------------------+
|                         MCP Server                               |
|  +-----------------------------------------------------------+  |
|  |                   JSON-RPC over stdio                      |  |
|  +-----------------------------------------------------------+  |
|                              |                                   |
|  +---------------------------v-------------------------------+  |
|  |                   Code Intel Engine                        |  |
|  |  +------------+ +------------+ +------------------------+  |  |
|  |  |  Symbol    | |   File     | |    Search Engine       |  |  |
|  |  |  Index     | |   Cache    | |  (Tantivy + TF-IDF)    |  |  |
|  |  | (DashMap)  | | (DashMap)  | +------------------------+  |  |
|  |  +------------+ +------------+                              |  |
|  |  +------------+ +------------+ +------------------------+  |  |
|  |  | Call Graph | |  Taint     | |   Security Rules       |  |  |
|  |  |  Analysis  | |  Tracker   | |   Engine               |  |  |
|  |  +------------+ +------------+ +------------------------+  |  |
|  +-----------------------------------------------------------+  |
|                              |                                   |
|  +---------------------------v-------------------------------+  |
|  |                Tree-sitter Parser                          |  |
|  |  +------+ +------+ +------+ +------+ +------+             |  |
|  |  | Rust | |Python| |  JS  | |  TS  | | Go   | ...         |  |
|  |  +------+ +------+ +------+ +------+ +------+             |  |
|  +-----------------------------------------------------------+  |
|                              |                                   |
|  +---------------------------v-------------------------------+  |
|  |                Repository Walker                           |  |
|  |           (ignore crate - respects .gitignore)             |  |
|  +-----------------------------------------------------------+  |
+-----------------------------------------------------------------+

Performance

Benchmarked on Apple M1 (criterion.rs):

Parsing Throughput

LanguageInput SizeTimeThroughput
Rust (large file)278 KB131 µs1.98 GiB/s
Rust (medium file)27 KB13.5 µs1.89 GiB/s
Python~4 KB16.7 µs-
TypeScript~5 KB13.9 µs-
Mixed (5 files)~15 KB57 µs-

Search Latency

OperationCorpus SizeTime
Symbol exact match1,000 symbols483 ns
Symbol prefix match1,000 symbols2.7 µs
Symbol fuzzy match1,000 symbols16.5 µs
BM25 full-text1,000 docs80 µs
TF-IDF similarity1,000 docs130 µs
Hybrid (BM25+TF-IDF)1,000 docs151 µs

End-to-End Indexing

RepositoryFilesSymbolsTimeMemory
narsil-mcp (this repo)531,733220 ms~50 MB
rust-analyzer2,847~50K2.1s89 MB
linux kernel78,000+~500K45s2.1 GB

Key metrics:

  • Tree-sitter parsing: ~2 GiB/s sustained throughput
  • Symbol lookup: <1µs for exact match
  • Full-text search: <1ms for most queries
  • Hybrid search runs BM25 + TF-IDF in parallel via rayon

Development

# Run the full test suite
cargo test

# Run benchmarks (criterion.rs)
cargo bench

# Run with debug logging
RUST_LOG=debug cargo run -- --repos ./test-fixtures

# Format code
cargo fmt

# Lint
cargo clippy

# Test with MCP Inspector
npx @modelcontextprotocol/inspector ./target/release/narsil-mcp --repos ./path/to/repo

Troubleshooting

Tree-sitter Build Errors

If you see errors about missing C compilers or tree-sitter during build:

# macOS
xcode-select --install

# Ubuntu/Debian
sudo apt install build-essential

# For WASM builds
brew install emscripten  # macOS

Neural Search API Errors

# Check your API key is set
echo $VOYAGE_API_KEY  # or $OPENAI_API_KEY

# Common issue: wrong key format
export VOYAGE_API_KEY="pa-..."  # Voyage keys start with "pa-"
export OPENAI_API_KEY="sk-..."  # OpenAI keys start with "sk-"

Index Not Finding Files

# Check .gitignore isn't excluding files
narsil-mcp --repos /path --verbose  # Shows skipped files

# Force reindex
narsil-mcp --repos /path --reindex

Memory Issues with Large Repos

# For very large repos (>50K files), increase stack size
RUST_MIN_STACK=8388608 narsil-mcp --repos /path/to/huge-repo

# Or index specific subdirectories
narsil-mcp --repos /path/to/repo/src --repos /path/to/repo/lib

Graph Feature Not Working

If you pass --graph and see a warning like:

WARN: --graph flag was passed but the binary was built without the 'graph' feature.
SPARQL and CCG tools will not be available.

This means you're using a binary that wasn't compiled with the graph feature. To fix:

# Build from source with the graph feature
cargo build --release --features graph

# Or with multiple features
cargo build --release --features graph,frontend

# Then run with --graph
./target/release/narsil-mcp --repos ~/project --graph

Why is this a separate feature? The graph feature adds the Oxigraph RDF database (~5MB additional binary size) which isn't needed for most use cases. It's kept optional to keep the default binary smaller.

How to check if graph is enabled: Look at the startup logs:

  • graph=true means the feature is compiled in AND enabled
  • graph=false means either the feature isn't compiled, OR --graph wasn't passed

Roadmap

Completed

  • Multi-language symbol extraction (32 languages)
  • Full-text search with Tantivy (BM25 ranking)
  • Hybrid search (BM25 + TF-IDF with RRF)
  • AST-aware code chunking
  • Git blame/history integration
  • Call graph analysis with complexity metrics
  • Control flow graph (CFG) analysis
  • Data flow analysis (DFG) with reaching definitions
  • Dead code and dead store detection
  • Taint analysis for injection vulnerabilities
  • Security rules engine (OWASP, CWE, crypto, secrets)
  • SBOM generation (CycloneDX, SPDX)
  • Dependency vulnerability checking (OSV)
  • License compliance analysis
  • Import graph with circular dependency detection
  • Cross-language symbol resolution
  • Incremental indexing with Merkle trees
  • Index persistence
  • Watch mode for file changes
  • LSP integration
  • Remote repository support
  • Streaming responses

What's New

v1.6.x (Current)

  • Crash-proof chunking - Fixed unsafe byte-level string slicing in chunk_file() and extract_signature() that caused hybrid_search, search_chunks, and get_chunk_stats to crash when processing files with multi-byte UTF-8 characters (emoji, CJK, accented chars). All byte slicing now uses safe content.get() with fallback.
  • NaN-safe sort operations - Fixed 5 locations across search, embeddings, git, index, and extract modules where partial_cmp().unwrap() would panic on NaN float values. All sorts now use unwrap_or(Ordering::Equal).
  • Defense-in-depth chunking - Added catch_unwind wrappers around all repo-wide chunk_file() loops so a panic in one file skips it instead of crashing the entire MCP server.
  • Visualization frontend overhaul - Full SPA with HashRouter routing, file tree sidebar, syntax-highlighted code viewer, dashboard, and per-repo overview pages
  • Graph view performance - Import graph now uses cached index data instead of filesystem walks; symbol graph iterates file cache directly instead of markdown round-trips; all views respect max_nodes for early termination
  • Real control flow graphs - Flow view now uses the real CFG builder (cfg::analyze_function) with proper basic blocks, branch conditions, and loop back-edges instead of the single-block stub
  • Hybrid graph budget splitting - Hybrid view allocates 60/40 node budget between call and import graphs for balanced results
  • Fix #14: configurable embedding dimensions - Added --neural-dimension CLI arg and default_dimension_for_model() lookup so models like text-embedding-3-large use correct dimensions (3072) instead of hardcoded 1536
  • Fix #13: Nix frontend build - Added frontendDist derivation in flake.nix using buildNpmPackage so nix profile install github:postrv/narsil-mcp#with-frontend works
  • Rust security rules - 18 new rules (RUST-004 to RUST-021) covering command injection, transmute, FFI boundaries, TOCTOU, ReDoS, static mut, SSRF, and more
  • Elixir security rules - 18 new rules (EX-001 to EX-018) covering atom exhaustion, binary_to_term deserialization, Code.eval injection, Ecto SQL injection, Phoenix XSS, Erlang distribution security
  • Migrated from serde_yaml to serde-saphyr - Deprecated serde_yaml replaced with actively maintained, panic-free YAML library
  • Custom favicon - Frontend now uses narsil-mcp branding icon instead of default Vite logo
  • Dependency security - Updated time to 0.3.47 (RUSTSEC-2026-0009), bytes to 1.11.1 (RUSTSEC-2026-0007)
  • Test count increased from 1,611 to 1,763 (+152 tests)

v1.5.x

  • Deterministic call graph resolution - Scope-hint propagation disambiguates callee resolution (e.g., App::run() correctly resolves to src/app/mod.rs::run)
  • 8 graph analysis fixes - Qualified node keys, hotspot filtering, CFG expression handling, import path parsing
  • Nix flake improvements - DRY mkPkg helper, removed unnecessary macOS frameworks, --lib test strategy for sandbox builds

v1.4.x

  • SPARQL / RDF Knowledge Graph - Query code intelligence data with SPARQL via Oxigraph
  • Code Context Graph (CCG) - 12 tools for standardized, AI-consumable codebase representations with tiered layers (L0-L3)
  • Type-aware security analysis - Enhanced taint tracking with type inference and trait implementations
  • Multi-language CFG/DFG - Control flow and data flow analysis extended to Go, Java, C#, Kotlin
  • Infrastructure as Code scanning - New iac.yaml rules for Terraform, CloudFormation, Kubernetes
  • Language-specific security rules - New rules for Go, Java, C#, Kotlin, Bash
  • 6 new languages - Erlang, Elm, Fortran, PowerShell, Nix, Groovy
  • 90 tools total - Up from 79 with new SPARQL, CCG, and analysis capabilities

v1.2.x

  • exclude_tests parameter - 22 tools support filtering out test files
  • npm package - Install via npm install -g narsil-mcp

v1.1.x

  • Multi-platform distribution - Install via Homebrew, Scoop, npm, Cargo, or direct download
  • Configurable tool presets - Minimal, balanced, full, and security-focused presets
  • Automatic editor detection - Optimal defaults for Zed, VS Code, Claude Desktop
  • Interactive setup wizard - narsil-mcp config init for easy configuration
  • 32 language support - Added Dart, Julia, R, Perl, Zig, and more
  • Improved performance - Faster startup with background indexing

v1.0.x

  • Neural semantic search - Find similar code using Voyage AI or OpenAI embeddings
  • Type inference - Infer types in Python/JavaScript/TypeScript without external tools
  • Multi-language taint analysis - Security scanning for PHP, Java, C#, Ruby, Kotlin
  • WASM build - Run in browser for code playgrounds and educational tools
  • 147 bundled security rules - OWASP, CWE, crypto, secrets, Rust, Elixir detection
  • IDE configs included - Claude Desktop, Cursor, VS Code, Zed templates

License

Licensed under either of:

at your option.

Credits

Built with:

常见问题

What is narsil-mcp?

narsil-mcp is an open-source mcp servers skill for AI coding assistants such as Claude Code, Codex CLI, and ChatGPT, built by postrv. Rust MCP server for comprehensive code intelligence - 90 tools, 32 languages, security scanning, call graphs, and more. It has 181 GitHub stars.

Is narsil-mcp safe to use?

Yes. narsil-mcp passed SkillsLLM's automated security scan — a dependency vulnerability audit plus prompt-injection heuristics — with no high-severity issues. You can read the full report in the Security Report section on this page.

How do I install narsil-mcp?

Clone the repository with "git clone https://github.com/postrv/narsil-mcp" and add it to your Claude Code skills directory (see the Installation section above).

What programming language is narsil-mcp written in?

narsil-mcp is primarily written in Rust. It is open-source under postrv on GitHub, so you can review or fork the full source.

Are there alternatives to narsil-mcp?

Yes. SkillsLLM lists many other MCP Servers skills you can browse and compare side by side. Open the MCP Servers category from the badge at the top of this page, or use the Related Skills and comparison links further down to weigh narsil-mcp against similar tools.

评论 (0)

暂无评论,成为第一个分享想法的人!

n8n

by n8n-io

12

Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.

201,88160,308TypeScript
MCP 服务器apisai-tools
查看详情

Scrapling

by D4Vinci

🕷️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!

75,9137,581Python
MCP 服务器
查看详情

TrendRadar

by sansan0

⭐AI-driven public opinion & trend monitor with multi-platform aggregation, RSS, and smart alerts.🎯 告别信息过载,你的 AI 舆情监控助手与热点筛选工具!聚合多平台热点 + RSS 订阅,支持关键词精准筛选。AI 智能筛选新闻 + AI 翻译 + AI 分析简报直推手机,也支持接入 MCP 架构,赋能 AI 自然语言对话分析、情感洞察与趋势预测等。支持 Docker ,数据本地/云端自持。集成微信/飞书/钉钉/Telegram/邮件/ntfy/bark/slack 等渠道智能推送。

61,65224,883Python
MCP 服务器
查看详情

context7

by upstash

Context7 Platform -- Up-to-date code documentation for LLMs and AI code editors

61,0602,938TypeScript
MCP 服务器
查看详情

High-performance code intelligence MCP server. Indexes codebases into a persistent knowledge graph — average repo in milliseconds. 158 languages, sub-ms queries, 99% fewer tokens. Single static binary, zero dependencies.

39,9393,219C
MCP 服务器
查看详情

开发者还喜欢

基于喜欢此 Skill 的开发者投票和收藏

ECC

by affaan-m

10

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

242,21936,702JavaScript
AI 智能体ai-agentsanthropicclaude-code
查看详情
15

An agentic skills framework & software development methodology that works.

234,96620,863Shell
AI 智能体ai-agentsbrainstorming
查看详情

hermes-agent

by NousResearch

10

The agent that grows with you

234,43747,175Python
AI 智能体ai-agentsagent-orchestration
查看详情

n8n

by n8n-io

12

Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.

201,88160,308TypeScript
MCP 服务器apisai-tools
查看详情

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

185,94028,768JavaScript
AI 智能体ai-agentsanthropicclaude-code
查看详情

cc-switch

by farion1231

3

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

128,8688,826Rust
AI 智能体claude-codeai-tools
查看详情