Sandbox
@marcoaapfortes/Mantic.sh

MCP server and CLI for structural code search

Mantic.sh searches a codebase by file structure, metadata, and dependency signals, then returns ranked context for agent tools. It can also expose that search through MCP so Claude Desktop, Cursor, VS Code, and similar clients can ask for files, definitions, references, and session context.

555 stars26 forksTypeScriptUpdated 2mo ago
Who it's for

Builders who want their agent to retrieve better code context before editing or reviewing a repository.

What it delivers

You can find the most relevant files, definitions, and references without manually hunting through the tree.

What it does

Structural file ranking

Ranks files by path, filename, directory signals, and code type instead of just keyword hits.

Semantic reranking

Adds local embedding-based reranking for queries that need conceptual matches.

Go to definition

Finds the line and file for a symbol across a repo with `mantic goto <symbol>`.

Find references

Lists usages of a symbol with `mantic references <symbol>`.

Session context carryover

Remembers viewed files and query history so later searches can reuse context.

Impact analysis

Shows dependency blast radius and related files for a change or query.

MCP tool surface

Exposes search, definition, references, context, and session tools to MCP clients.

Agent rules file

Includes `AGENT_RULES.md` for telling an agent to use Mantic before writing code.

How to get it

  1. 1Quick Start (no installation required)
    npx mantic.sh@latest "your search query"
  2. 2New Commands
    # Semantic Search (Neural Reranking)
    npx mantic.sh@latest "verify user identity" --semantic
    
    # Go to Definition
    npx mantic.sh@latest goto "UserService"
    
    # Find References
    npx mantic.sh@latest references "handleLogin"
  3. 3From Source
    git clone https://github.com/marcoaapfortes/Mantic.sh.git
    cd Mantic.sh
    npm install
    npm run build
    npm link
  4. 4Find files matching your intent
    mantic "stripe payment integration"
  5. 5Zero-Query Mode (proactive context)
    mantic ""
    # Shows modified files, related dependencies, impact analysis
  6. 6Context Carryover (session mode)
    mantic "auth logic" --session my-task
    # Previously viewed files get +150 boost

README

Mantic.sh

npm version Install in Cursor Install in VS Code Agent Rules Claude Desktop

Summary

Mantic is a context-aware code search engine that prioritizes relevance over raw speed. After testing across 5 repositories (cal.com, next.js, tensorflow, supabase, chromium), it demonstrates superior result quality compared to grep/ripgrep, despite some trade-offs in speed for very large codebases.

Overall Assessment: 4/5 - Excellent for AI agents, good for developers, needs speed optimization for 100K+ file repos.

What's New in v1.0.25

Enterprise-Grade Context Infrastructure

  • Semantic Reranking (Hybrid Intelligence): Combines heuristic speed with neural understanding. Uses local embeddings (transformers.js) to find "conceptually relevant" code even without exact keyword matches.
    • Usage: mantic "verify user" --semantic
  • Code Intelligence: Deep understanding of your codebase structure using Tree-sitter.
    • Go to Definition: mantic goto UserService returns the exact line number across your entire monorepo.
    • Find References: mantic references handleLogin finds every usage, respecting .gitignore.
  • Learned Context (Team Memories): Mantic now remembers which files solved previous queries. These patterns are saved locally (.mantic/search-patterns.json) and can be committed to git to share knowledge across your team.
  • Python Support: Now includes first-class support for Python imports in the dependency graph.
  • Security & Stability:
    • Regex DoS protection for user inputs.
    • Command injection mitigations for VS Code extension.
    • Safe fallback for non-git directories (scans allow-listed extensions).

Performance Update: v1.0.25 is ~2x faster than previous versions, scanning Chromium (481K files) in <2 seconds.

Tested on 481K files (Chromium) with 100% multi-repo accuracy.

See the CHANGELOG for detailed release notes.

Table of Contents

About the Project

Mantic is an infrastructure layer designed to remove unnecessary context retrieval overhead for AI agents. It infers intent from file structure and metadata rather than brute-force reading content, enabling retrieval speeds faster than human reaction time.

Key Benefits

  • Speed: Retrieval is consistently under 500ms for most repos, under 4s for massive monorepos (Chromium).
  • Efficiency: Reduces token usage by up to 63% by filtering irrelevant files before reading.
  • Privacy: Runs entirely locally with zero data egress.

Proprietary vs Mantic (Cost Analysis)

For a team of 100 developers performing 100 searches per day (approx. 3M searches/year):

ToolAnnual Cost (Est.)Per-Search CostPrivacy
Mantic$0$0Local-First
Vector Embeddings (DIY)$1,680 - $10,950*$0.0005 - $0.003Cloud
SaaS Alternatives$46,800+$0.015+Cloud

Note: Mantic costs are zero. Vector/SaaS costs are estimates based on standard managed infrastructure (e.g. Pinecone/Weaviate managed pods + compute) or per-seat Enterprise licensing (e.g. GitHub Copilot Enterprise).

Performance Benchmarks

Speed Comparison (Real-world queries)

RepositoryFilesQueryMantic v1.0.25ripgrepfzfVerdict
cal.com9.7K"stripe payment"0.288s0.121s0.534sFast
next.js25K"router server"0.440s0.034s0.049sFast
tensorflow35K"gpu"0.550s0.022sN/AFast
chromium481K"ScriptController"1.961s0.380s0.336s<2s (Massive)

Speed Verdict:

  • Caching works well for most repos (4-17% improvement on second run).
  • Large repos (Chromium) show modest but consistent improvements.
  • Mantic is slower than ripgrep/fzf on raw speed but prioritizes ranking.

Accuracy & Relevance Analysis

Major Strengths

1. Exact Path Matching

  • Query: "router server" in next.js
  • Mantic: Found packages/next/src/server/lib/router-server.ts (Score: 220)
  • ripgrep: Found files mentioning "router" and "server" separately (many false positives)
  • Verdict: Mantic found the exact file that matches the intent.

2. CamelCase Detection

  • Query: "ScriptController" in chromium
  • Mantic: Found script_controller.h, script_controller.cc (Score: 200)
  • ripgrep: Requires manual regex script.*controller
  • Verdict: Mantic's CamelCase detection is production-ready.

3. Directory Boosting for Acronyms

  • Query: "gpu" in tensorflow
  • Mantic: Prioritized files in tensorflow/lite/delegates/gpu/
  • Verdict: Mantic correctly prioritizes structural relevance.

4. Path Sequence Matching

  • Query: "blink renderer core dom" in chromium
  • Mantic: Found third_party/blink/renderer/core/dom/README.md
  • Verdict: Mantic matches multi-term path queries perfectly.

Feature Comparison Matrix

FeatureManticripgrepagfzf
Text Search Speed2-10x slowerFastestSlow (large repos)Very Fast
Relevance RankingExcellentNoneNoneBasic
Path Structure AwarenessPerfectNoneNonePartial
CamelCase DetectionYesNoNoNo
Exact Filename MatchingYesNoNoYes
Multi-Word QueriesSemanticRegex neededRegex neededAND logic
Go to DefinitionYes (Cross-Repo)NoNoNo
Find ReferencesYesNoNoNo
Impact AnalysisYesNoNoNo
Zero-Query ModeYesNoNoNo

Use Case Recommendations

Best For

  1. AI Agents (Context-aware search with metadata)
  2. Finding Files by Intent ("Where is payment code?")
  3. Understanding Code Structure (Path sequence queries)
  4. Code Reviews (Impact analysis shows blast radius)

Not Ideal For

  1. Quick Text Searches ("Find all TODOs" -> Use ripgrep)
  2. Very Large Repos (100K+) (Speed tradeoff: 4s vs 0.3s)
  3. Exact String Matching (Use ripgrep with -F)
  4. Interactive File Browsing (Use fzf)

Installation

CLI Installation

Quick Start (no installation required):

npx mantic.sh@latest "your search query"

New Commands:

# Semantic Search (Neural Reranking)
npx mantic.sh@latest "verify user identity" --semantic

# Go to Definition
npx mantic.sh@latest goto "UserService"

# Find References
npx mantic.sh@latest references "handleLogin"

From Source:

git clone https://github.com/marcoaapfortes/Mantic.sh.git
cd Mantic.sh
npm install
npm run build
npm link

MCP Server Installation

Mantic works as an MCP (Model Context Protocol) server for Claude Desktop, Cursor, VS Code, and other MCP-compatible tools.

One-Click Install:

Manual Configuration (for Claude Desktop or other MCP clients):

Add this to your MCP settings file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "mantic": {
      "command": "npx",
      "args": ["-y", "mantic.sh@latest", "server"]
    }
  }
}

Usage

Basic Search

Find files matching your intent:

mantic "stripe payment integration"

Returns JSON with ranked files, confidence scores, and token estimates.

Advanced Usage

Zero-Query Mode (proactive context):

mantic ""
# Shows modified files, related dependencies, impact analysis

Context Carryover (session mode):

mantic "auth logic" --session my-task
# Previously viewed files get +150 boost

Impact Analysis:

mantic "payment processing" --impact
# Shows blast radius and dependents

### Session Management (CLI)

You can manage sessions directly from the terminal to persist context across multiple runs:

```bash
# Start a named session with an intent
mantic session start my-feature --intent "implement payment webhook"

# List all active sessions
mantic session list

# Get detailed info (viewed files, query history)
mantic session info <sessionId>

# End a session
mantic session end <sessionId>

### CLI Options

```bash
mantic <query> [options]

Options:
  --code          Only search code files (.ts, .js, etc)
  --config        Only search config files
  --test          Only search test files
  --json          Output as JSON (default, includes metadata)
  --files         Output as newline-separated file paths
  --markdown      Pretty terminal output
  --impact        Include dependency analysis and blast radius
  --session <id>  Use session for context carryover
  --path <dir>    Restrict search to specific directory
  --include-generated  Include generated files (.lock, dist/, etc)
  --quiet, -q     Minimal output mode
  --semantic      Enable neural reranking (slower, but "smarter")

Code Intelligence Commands:

mantic goto <symbol>        # Find definition of a symbol
mantic references <symbol>  # Find all usages of a symbol

MCP Tools

When using Mantic through MCP (Claude Desktop, Cursor):

  • search_files - Primary search (supports semantic: true for neural reranking)
  • get_definition - Go to definition of a symbol
  • find_references - Find usages of a symbol
  • get_context - Zero-query mode for proactive context
  • session_start/end - Manage coding sessions
  • session_record_view - Track viewed files
  • session_list/info - View session history
  • analyze_intent - Understand query intent

Agent Rules (Auto-Pilot)

Want Cursor or Claude to use Mantic automatically?

  1. Copy the Agent Rules.
  2. Paste them into your AI tool's system prompt or "Rules for AI" section.
  3. The Agent will now automatically use mantic to find context before writing code.

How It Works

Architecture Overview

User Query
    ↓
Intent Analyzer (categorizes: UI/backend/auth/etc)
    ↓
Brain Scorer (ranks files using metadata)
    ↓
File Classifier (filters by type: code/config/test)
    ↓
Impact Analyzer (calculates blast radius)
    ↓
Output (JSON/Files/Markdown/MCP)

Core Algorithm (v1.0.21)

  1. Intent Recognition: Analyzes query to determine code category (e.g., "auth", "ui")
  2. File Enumeration: Uses git ls-files for tracked files (significantly faster than traversals)
  3. Normalization & Matching:
    • CamelCase detection: "ScriptController" -> "script controller" for matching
    • Word-boundary matching: "script" won't match "javascript"
    • Path sequence matching: Multi-term queries match consecutive path components
    • Directory boosting: Single-term queries prioritize files in matching directories
  4. Structural Scoring: Ranks files based on:
    • Exact filename match: +10,000 points for perfect matches
    • Path relevance: packages/features/payments indicates high signal
    • Filename matching: stripe.service.ts > stripe.txt
    • Business logic awareness: .service.ts boosted over .test.ts
    • Boilerplate penalties: index.ts or page.tsx ranked lower
  5. Progressive Disclosure: Calculates metadata (size, tokens, confidence, timestamps)
  6. Context Carryover: Applies +150 boost to session-viewed files
  7. Learning: Caches successful patterns for future queries

Configuration

Mantic works out of the box with zero configuration for most projects.

Environment Variables

MANTIC_MAX_FILES=5000         # Maximum files to scan
MANTIC_TIMEOUT=30000          # Search timeout in ms (default: 30000)
MANTIC_IGNORE_PATTERNS=...    # Custom glob patterns to ignore
MANTIC_FUNCTION_SCAN_LIMIT=30 # Top files to scan for function names (default: dynamic, max 50)

License

Mantic.sh is released under the MIT License.

You can use, copy, modify, merge, publish, distribute, sublicense, and sell copies of the software as long as the copyright notice and license text are included.

See LICENSE for the full MIT terms.

Note: earlier releases published under AGPL-3.0 remain available under the terms they were originally shipped with. The repository is MIT-licensed going forward.

Files in the repo

Repository payload12 top-level entries
  • src
  • vscode-extension
  • .gitattributes
  • .gitignore
  • .npmignore
  • AGENT_RULES.md
  • CHANGELOG.md
  • LICENSE
  • package-lock.json
  • package.json
  • README.md
  • tsconfig.json

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More connectors

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.

43k

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM (Claude, Gemini, Grok, DeepSeek, Ollama…) with Codex CLI, App, SDK, and Claude Code

14k
okf-memory/
okf-agent-memory

Git-native persistent memory for AI coding agents. Implements Google OKF v0.2 with sub-300µs in-memory BM25 search, embedded MCP server, and progressive disclosure. Slashes token bloat by 80% with zero external databases or dependencies. Built in pure Go.

547
tirth8205/
code-review-graph

Local-first code intelligence graph for MCP and CLI. Builds a persistent map of your codebase so AI coding tools read only what matters, with benchmarked context reductions on reviews and large-repo workflows.

31k
2akouwu/
reverify

Stop your AI from making things up — it proposes, deterministic tools decide, every claim checked against ground truth with evidence. Grounded facts and context survive resets. Reverse engineering is the proving ground. MCP server + CLI.

1.1k
t8y2/dbxConnectors

20 MB lightweight cross-platform database client for 90+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 90+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP Server。

19k