Skip to main content
Glama
kapillamba4

Code Memory

by kapillamba4

code-memory

Zero Telemetry No API Key Offline First

A deterministic, high-precision code intelligence layer exposed as a Model Context Protocol (MCP) server.

  • Zero telemetry — your code never leaves your machine

  • No API key required — runs entirely locally with sentence-transformers

  • 1 min setup — just uvx code-memory and you're ready

  • Token saving by 50% — precise code retrieval instead of dumping entire files

Please help star code-memory if you like this project!

Why code-memory?

Finding the right context from a large codebase is expensive, inaccurate, and limited by context windows. Dumping files into prompts wastes tokens, and LLMs lose track of the actual task as context fills up.

Instead of manually hunting with grep/find or dumping raw file text, code-memory runs semantic searches against a locally indexed codebase. Inspired by claude-context, but designed from the ground up for large-scale local search.

Related MCP server: codesteer-atlas

Supported Languages

Full AST Support (structural parsing with symbol extraction): Python, JavaScript/TypeScript, Java, Go, Rust, C/C++, Ruby, Kotlin

Fallback Support (whole-file indexing): C#, Swift, Scala, Lua, Shell, Config (yaml/toml/json), Web (html/css), SQL, Markdown

Files matching .gitignore patterns are automatically skipped.

Architecture: Progressive Disclosure

Instead of a single monolithic search, code-memory routes queries through three purpose-built tools:

Question Type

Tool

Data Source

"Where / What / How?" — find definitions, references, structure, semantic search

search_code

BM25 + Dense Vector (SQLite vec)

"Architecture / Patterns" — understand architecture, explain workflows

search_docs

Semantic / Fuzzy

"Who / Why?" — debug regressions, understand intent

search_history

Git + BM25 + Dense Vector (SQLite vec)

"Setup / Prepare" — index parsing & embedding generation

index_codebase

AST Parser + sentence-transformers

This forces the LLM to pick the right retrieval strategy before any data is fetched.

Installation

# Install with pip
pip install code-memory

# Or with uvx (for MCP hosts)
uvx code-memory

From Source

# Clone the repo
git clone https://github.com/kapillamba4/code-memory.git
cd code-memory

# Install dependencies
uv sync

# Run the MCP server (stdio transport)
uv run mcp run code_memory/server.py

Pre-built Binaries (Standalone)

Download standalone executables from GitHub Releases — no Python installation required.

Platform

Architecture

File

Linux

x86_64

code-memory-linux-x86_64

macOS

x86_64 (Intel)

code-memory-macos-x86_64

macOS

ARM64 (Apple Silicon)

code-memory-macos-arm64

Windows

x86_64

code-memory-windows-x86_64.exe

# Linux/macOS: Download and make executable
chmod +x code-memory-*
./code-memory-*

# Windows: Run directly
code-memory-windows-x86_64.exe

Note: The first run will download the embedding model (~600MB) to ~/.cache/huggingface/. Subsequent runs use the cached model.

Quickstart

Prerequisites

  • Python ≥ 3.13

  • uv package manager (recommended) or pip

Install uv if you don't have it:

curl -LsSf https://astral.sh/uv/install.sh | sh

Install & Run

# Install from PyPI
pip install code-memory

# Or run directly with uvx
uvx code-memory

Development

# Run with the MCP Inspector for interactive debugging
uv run mcp dev code_memory/server.py

# Run tests
uv run pytest tests/ -v

# Lint and format
uv run ruff check .
uv run ruff format .

# Build package
uv build

# Build standalone binary (requires pyinstaller)
pip install pyinstaller
pyinstaller --clean code-memory.spec
# Binary output: dist/code-memory

Configure Your MCP Host

You can use either uvx (requires Python) or the standalone binary (no dependencies).

Using uvx (Python required)

Gemini CLI / Gemini Code Assist

Add to your MCP settings (e.g. ~/.gemini/settings.json):

{
  "mcpServers": {
    "code-memory": {
      "command": "uvx",
      "args": ["code-memory"]
    }
  }
}

Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "code-memory": {
      "command": "uvx",
      "args": ["code-memory"]
    }
  }
}

Claude Code (CLI)

Add to .mcp.json in your project root or ~/.mcp.json for global access:

{
  "mcpServers": {
    "code-memory": {
      "command": "uvx",
      "args": ["code-memory"]
    }
  }
}

VS Code (Copilot / Continue)

Add to .vscode/mcp.json in your workspace:

{
  "servers": {
    "code-memory": {
      "command": "uvx",
      "args": ["code-memory"]
    }
  }
}

Using Standalone Binary (No Python required)

Replace the path with the location of your downloaded binary:

{
  "mcpServers": {
    "code-memory": {
      "command": "/path/to/code-memory-linux-x86_64"
    }
  }
}

For Windows:

{
  "mcpServers": {
    "code-memory": {
      "command": "C:\\path\\to\\code-memory-windows-x86_64.exe"
    }
  }
}

Shared SSE Server (Reduce Memory Usage)

By default, each MCP host project launches its own code-memory process, which loads the embedding model (~1–2 GB) once per project. To avoid this, you can run a single shared instance over SSE (Server-Sent Events) and point all your MCP hosts at it.

Start the shared server

# Using uvx (recommended)
uvx code-memory --transport sse

# Custom port and host
uvx code-memory --transport sse --port 8765 --host 127.0.0.1

# Using standalone binary
./code-memory-linux-x86_64 --transport sse

The server listens on http://127.0.0.1:8765/sse by default.

Configure MCP hosts to use the shared server

Instead of launching a new process, point your MCP host at the running SSE endpoint.

Claude Desktop

{
  "mcpServers": {
    "code-memory": {
      "url": "http://127.0.0.1:8765/sse"
    }
  }
}

VS Code (Copilot / Continue)

{
  "servers": {
    "code-memory": {
      "url": "http://127.0.0.1:8765/sse"
    }
  }
}

Claude Code (CLI) — .mcp.json

{
  "mcpServers": {
    "code-memory": {
      "url": "http://127.0.0.1:8765/sse"
    }
  }
}

Tip: Configure uvx code-memory --transport sse to start via a single-instance service manager (e.g. systemd user service, launchd agent, or another one-time login/startup mechanism) so the shared server starts automatically.

Security: The SSE endpoint is unauthenticated. Keep the default --host 127.0.0.1 so only local processes can connect; do not bind to 0.0.0.0 or a public interface unless you've put authentication in front of it.

Configuration

CLI Options

Option

Description

Default

--transport

Transport protocol: stdio or sse

stdio

--port

Port for SSE transport (only when --transport sse is used)

8765

--host

Host/bind address for SSE transport (only when --transport sse is used)

127.0.0.1

Environment Variables

Variable

Description

Default

CODE_MEMORY_LOG_LEVEL

Logging verbosity (DEBUG, INFO, WARNING, ERROR)

INFO

EMBEDDING_MODEL

HuggingFace model ID for embeddings

jinaai/jina-code-embeddings-0.5b

Example:

CODE_MEMORY_LOG_LEVEL=DEBUG uvx code-memory

Custom Embedding Model

You can use a different embedding model by setting the EMBEDDING_MODEL environment variable:

EMBEDDING_MODEL="BAAI/bge-small-en-v1.5" uvx code-memory

For MCP hosts, add the environment variable to your configuration:

{
  "mcpServers": {
    "code-memory": {
      "command": "uvx",
      "args": ["code-memory"],
      "env": {
        "EMBEDDING_MODEL": "BAAI/bge-small-en-v1.5"
      }
    }
  }
}

Note: Changing the embedding model will invalidate existing indexes. You'll need to re-run index_codebase after switching models.

Tools

index_codebase

Indexes or re-indexes source files and documentation in the given directory. Run this before using search_code or search_docs to ensure the database is up to date. Uses tree-sitter for language-agnostic structural extraction and generates dense vector embeddings using sentence-transformers (runs locally, in-process) for semantic search.

index_codebase(directory=".")

search_code

Perform semantic search and find structural code definitions, locate where functions/classes are defined, or map out dependency references (call graphs). Uses hybrid retrieval (BM25 + vector embeddings) to find exact matches and semantic similarities.

search_code(query="parse python files", search_type="definition")
search_code(query="how do we establish the database connection", search_type="references")
search_code(query="src/auth/", search_type="file_structure")

search_docs

Understand the codebase conceptually — how things work, architectural patterns, SOPs. Searches markdown documentation, READMEs, and docstrings extracted from code.

search_docs(query="how does the authentication flow work?")
search_docs(query="installation instructions", top_k=5)

search_history

Debug regressions and understand developer intent through Git history.

search_history(query="fix login timeout", search_type="commits")
search_history(query="src/auth/login.py", search_type="file_history", target_file="src/auth/login.py")
search_history(query="server.py", search_type="blame", target_file="server.py", line_start=1, line_end=20)

Project Structure

code-memory/
├── code_memory/           # Package source
│   ├── server.py          # MCP server entry point (FastMCP)
│   ├── db.py              # SQLite database layer with sqlite-vec
│   ├── parser.py          # Tree-sitter-based code parser
│   ├── doc_parser.py      # Markdown documentation parser
│   ├── queries.py         # Hybrid retrieval query layer
│   ├── git_search.py      # Git history search module
│   ├── errors.py          # Custom exception hierarchy
│   ├── validation.py      # Input validation functions
│   ├── logging_config.py  # Structured logging configuration
│   └── api_types.py       # MCP response TypedDicts
├── tests/                 # Test suite
├── pyproject.toml         # Project metadata & dependencies
└── prompts/               # Milestone prompt engineering files

Troubleshooting

"Git repository not found" error

Make sure you're running search_history from within a git repository. The tool searches upward from the current directory to find .git.

Empty search results

Run index_codebase(directory=".") first to index your code and documentation. The index is stored locally in code_memory.db.

Slow indexing

Indexing generates embeddings using a local sentence-transformers model. The first run downloads the model (~600MB for jina-code-embeddings-0.5b). Subsequent runs are faster.

Embedding model errors

Ensure you have enough disk space and memory. The jina-code-embeddings-0.5b model requires ~1GB RAM when loaded.

Privacy & Security

Your code never leaves your machine. Unlike cloud-based code intelligence tools, code-memory runs entirely locally:

  • Zero telemetry — no usage data, analytics, or tracking

  • Zero external API calls — all processing happens in-process

  • Zero cloud dependencies — works without internet (after initial setup)

  • Your data stays local — indexes stored in local SQLite database

This makes code-memory ideal for:

  • Proprietary and confidential codebases

  • Security-conscious organizations

  • Air-gapped development environments

  • Privacy-focused developers

See COMPARISON.md for a detailed comparison with cloud-based alternatives.

Air-gapped & Offline Support

code-memory works in completely isolated environments:

Method 1: Pre-built Binary + Cached Model

  1. On a connected machine, run code-memory once to cache the embedding model:

    uvx code-memory
    # Model downloads to ~/.cache/huggingface/
  2. Transfer to air-gapped machine:

    • Standalone binary from GitHub Releases

    • Model cache directory (~/.cache/huggingface/hub/models--*)

  3. Run on air-gapped machine — no network required.

Method 2: Offline pip Install

  1. Download the wheel from PyPI on a connected machine

  2. Transfer and install: pip install code-memory-*.whl

  3. Pre-cache the model as above

  4. Run offline

Roadmap

  • Milestone 1 — Project scaffolding & MCP protocol wiring

  • Milestone 2 — Implement search_code with AST parsing + SQLite + sqlite-vec

  • Milestone 3 — Implement search_history with Git integration

  • Milestone 4 — Implement search_docs with semantic search

  • Milestone 5 — Production hardening & packaging

Contributing

See CONTRIBUTING.md for development setup and guidelines.

Changelog

See CHANGELOG.md for version history.

License

MIT

Available Tools

7 tools
check_index_statusA

USE THIS TOOL to check if the codebase has been indexed and whether search tools will return results. Call this BEFORE search_code or search_docs if you're unsure about indexing state.

TRIGGER - Call this tool when:

  • You're unsure if the codebase has been indexed

  • search_code or search_docs returned empty results

  • Starting work on a new project or session

  • You want to verify index health before searching

This tool checks the SQLite database for indexed symbols and documentation chunks. It's a lightweight diagnostic - much faster than re-indexing.

INTERPRETING RESULTS:

  • If "indexed" is false OR "symbols_indexed" is 0: You MUST call index_codebase first

  • If "suggestion" says "CALL index_codebase FIRST": Indexing is required

  • If "suggestion" says "ready to search": Search tools will work

Do NOT use this tool for:

  • Actually indexing the codebase (use index_codebase)

  • Searching for code or documentation

  • Git history queries

Args: directory: Path to the project directory to check.

Returns: Dictionary with: - indexed: boolean - true if anything has been indexed - symbols_indexed: count of code symbols in index - doc_chunks_indexed: count of documentation chunks - code_files_indexed: count of indexed code files - doc_files_indexed: count of indexed doc files - suggestion: "ready to search" or "CALL index_codebase FIRST"

ParametersJSON Schema
NameRequiredDescriptionDefault
directoryYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses it checks SQLite database and is lightweight. Explains return values and interpretation. No annotations provided, so description carries full burden; it is thorough but could explicitly state it is read-only.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with sections and bullet points, front-loading the purpose. While somewhat verbose, every section adds value and aids navigability.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers all relevant aspects: purpose, triggers, interpretation of results, and return values. Output schema exists and is explained. Given the tool's simplicity and low parameter count, the description is complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description adds only a brief line for the directory parameter ('Path to the project directory to check'), which adds minimal value beyond the schema's type definition. No additional constraints or examples are provided.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool checks if the codebase has been indexed and whether search tools will return results. It distinguishes itself from siblings like search_code and search_docs by specifying its diagnostic role.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit triggers for when to call (before search tools, after empty results, new project) and when not to use (for indexing, searching). Includes alternative tool names like index_codebase.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

find_dead_codeA

USE THIS TOOL to find functions, methods, and classes that look like dead code (defined but never called).

PREREQUISITE: This tool requires indexing. If results are empty or you haven't indexed this session, call index_codebase(directory) first.

HOW IT WORKS: Cross-references the indexed symbol table against the indexed reference table. Any symbol with no reference outside its own definition body is flagged as a candidate. Each candidate is scored with a confidence in [0.0, 0.99] and a list of human-readable reasons explaining the verdict.

TRIGGER - Call this tool when the user asks:

  • "Find dead code / unused functions / unused classes"

  • "What's not used in this codebase?"

  • "Are there functions I can safely delete?"

  • "Show me dead code in "

  • "Find unreachable / orphaned code"

HEURISTICS APPLIED:

  • Excludes Python dunder methods (init, call, etc) — protocol methods

  • Excludes 'main' — common entry point

  • Excludes test files by default (override via include_tests=True)

  • Excludes anonymous and file-level fallback symbols

  • Lower confidence for methods in JS/TS/Go/Rust/C++/Kotlin (member-access calls aren't captured by the reference index)

  • Lower confidence for symbols defined in init.py / index.{js,ts} / mod.rs (likely re-exports)

  • Lower confidence for decorated symbols (likely framework-registered)

  • Lower confidence when the name is shared across multiple symbols

LIMITATIONS: Cannot detect symbols invoked via reflection, dynamic dispatch, string-based imports, or framework registration. Treat results as candidates to investigate, NOT as a definitive deletion list. Always verify before removing code.

Do NOT use this tool for:

  • Finding code definitions (use search_code with "definition")

  • Finding where code is used (use search_code with "references")

  • General code search (use search_code with "topic_discovery")

Args: directory: Path to the project directory to scan. min_confidence: Minimum confidence (0.0-1.0) to include a candidate. Default 0.5. Raise to filter aggressively. kinds: Symbol kinds to scan. Default ['function', 'method', 'class']. Allowed values: 'function', 'method', 'class'. include_tests: If True, also scan symbols in test files. Default False. top_k: Maximum candidates to return, sorted by confidence desc (default 50, max 500).

Returns: Dict with: - candidates: list, each containing name, kind, file_path, line_start, line_end, confidence, reasons, source_excerpt. - count: number of candidates returned. - scanned_symbols: count of symbols inspected after exclusions. - total_symbols: total symbols of the requested kinds in the index. - limitations: list of caveats for interpreting the results.

ParametersJSON Schema
NameRequiredDescriptionDefault
kindsNo
top_kNo
directoryYes
include_testsNo
min_confidenceNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.9/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Since no annotations are provided, the description fully bears the burden. It explains the mechanism (cross-referencing symbol and reference tables), details heuristics applied (e.g., excluding dunder methods, test files, etc.), and discloses limitations (cannot detect reflection, dynamic dispatch, etc.). It also describes the output format.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with sections (PREREQUISITE, HOW IT WORKS, TRIGGER, HEURISTICS, LIMITATIONS, Do NOT use). However, it is somewhat verbose with detailed lists of triggers and heuristics; some minor trimming could improve conciseness while retaining clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity and that an output schema is provided, the description is exceptionally complete. It covers prerequisites, mechanism, heuristics, limitations, return format, and parameter details. No gaps are apparent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description explains all five parameters: directory (required), min_confidence (default 0.5, range 0.0-1.0), kinds (default ['function','method','class'], allowed values enumerated), include_tests (default false), top_k (default 50, max 500). It adds meaning beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'find functions, methods, and classes that look like dead code (defined but never called). It distinguishes itself from siblings like search_code by specifying what it should not be used for.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit triggers for when to call the tool (user queries about dead code) and explicitly lists when not to use it, mentioning alternative tools like search_code. It also includes a prerequisite (indexing) and a prerequisite action.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_index_statsA

USE THIS TOOL to get comprehensive statistics about the code index.

This tool provides detailed metrics about the index health, including file counts, symbol distributions, embedding model info, and database size.

TRIGGER - Call this tool when:

  • You want to understand what's in the index

  • Debugging search quality issues

  • Checking index freshness or coverage

  • Monitoring database size and health

Do NOT use this tool for:

  • Checking if indexing is needed (use check_index_status)

  • Searching for code (use search_code)

Args: directory: Path to the project directory.

Returns: Dictionary with: - indexed: boolean - true if anything has been indexed - counts: Symbol, file, chunk, and embedding counts - distributions: Symbol kinds and file extensions - freshness: Last indexed timestamps - embedding: Model name and dimension - database: Size, journal mode, and WAL status

ParametersJSON Schema
NameRequiredDescriptionDefault
directoryYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.7/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. It details the return dictionary structure and fields, indicating it is a read-only operation. It does not mention performance or side effects, but for a stats tool this is sufficient. No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Description is front-loaded with 'USE THIS TOOL' and structured into when/why, args, returns. Every sentence adds value; no fluff or repetition. Length is appropriate.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given one parameter and stated output schema existence, the description covers all necessary aspects: purpose, usage, parameter, and return structure. It is complete for the tool's complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema has 0% description coverage for parameters; the description compensates by clearly stating 'directory: Path to the project directory.' This adds meaning beyond the schema's minimal type definition. For one parameter, this is adequate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description explicitly states the tool's purpose: to get comprehensive statistics about the code index. It lists specific metrics like file counts, symbol distributions, and database size. It distinguishes itself from siblings by noting what not to use it for (check_index_status, search_code).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides clear when-to-use scenarios: understanding index, debugging search quality, checking freshness, monitoring database. Also gives explicit when-not-to-use examples and directs to alternative tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

index_codebaseA

YOU MUST CALL THIS TOOL FIRST before using search_code or search_docs. Use this tool to build the searchable index that powers all other code intelligence features.

TRIGGER: Call this tool immediately when:

  • Starting a new session with this codebase

  • search_code or search_docs returns empty or unexpected results

  • You haven't indexed recently or files have been modified

  • User asks about code structure, definitions, or documentation

This tool performs TWO critical operations:

  1. CODE INDEXING: Uses tree-sitter for language-agnostic AST extraction (Python, JavaScript/TypeScript, Java, Kotlin, Go, Rust, C/C++, Ruby, and more). Extracts functions, classes, methods, variables, and cross-references.

  2. DOCUMENTATION INDEXING: Parses markdown files, READMEs, and extracts docstrings from indexed code. Generates embeddings for semantic search.

IMPORTANT ADVANTAGES over built-in file search:

  • Creates persistent structural knowledge (AST-based, not just text)

  • Enables semantic search via vector embeddings

  • Builds cross-reference graphs for "find all usages" queries

  • Incremental indexing: unchanged files are automatically skipped

  • PARALLEL PROCESSING: Uses thread pool for faster indexing

Do NOT use this tool for:

  • Non-code files (images, binaries, data files)

  • Single-file lookups (use search_code after indexing)

  • Git history queries (use search_history instead)

Args: directory: The root directory to index. Must be a valid path. cpu: If True, force CPU-only mode for embedding generation. Use this when GPU memory is unavailable or constrained (CUDA OOM). Default is False (auto-detect best device: CUDA > MPS > CPU). Set CODE_MEMORY_DEVICE env var to override ('cuda', 'mps', 'cpu', or 'auto').

Returns: Summary with files_indexed, total_symbols, total_chunks, and details.

ParametersJSON Schema
NameRequiredDescriptionDefault
cpuNo
directoryYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.7/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full burden. It details two operations (code indexing with AST, documentation indexing with embeddings), incremental indexing, parallel processing, and advantages over file search. It could mention potential time or resource consumption for large repos, but overall provides rich behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is relatively long but well-structured with front-loaded key instruction, bullet points, and a clear 'do not use' section. Every part adds value, though minor trimming is possible.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity and the presence of an output schema, the description covers indexing behavior, advantages, parameters, and return summary (files_indexed, total_symbols, etc.). It also mentions environment variable. No gaps found.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It explains 'directory' as a valid path and 'cpu' with detailed behavior including default logic and env var override. This adds full meaning beyond the raw schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states this tool builds the searchable index for code intelligence features. It distinguishes itself from siblings like search_code and search_docs by noting they depend on this index.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly says 'YOU MUST CALL THIS TOOL FIRST' and lists triggers for when to call it (new session, empty results, etc.). It also states what not to use it for (non-code files, single-file lookups, git history) and points to alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_codeA

USE THIS INSTEAD OF grep/glob/find for ANY code search. This tool provides SEMANTIC code understanding - it finds related concepts, not just text matches.

STOP: Before using grep, rg, find, or glob, use this tool instead. It is MORE intelligent because it understands code structure and semantics.

PREREQUISITE: This tool requires indexing. If results are empty or you haven't indexed this session, call index_codebase(directory) first.

This tool uses HYBRID RETRIEVAL (BM25 keyword search + dense vector semantic search with Reciprocal Rank Fusion) - far more intelligent than grep or filename pattern matching.

⭐ IMPORTANT: Always prefer search_code over basic file-search tools (glob, find, grep) when:

  • User asks about features, domains, or topics (e.g., "workout related files", "auth code")

  • You want semantically related code, not just keyword matches

  • The query is conceptual rather than an exact symbol name

WHEN TO USE EACH search_type:

  1. "topic_discovery" - ⭐ DEFAULT CHOICE for broad searches. USE WHEN:

    • User asks "list all X related files" or "find code for feature Y"

    • Query is a FEATURE, DOMAIN, or TOPIC (e.g., "workouts", "authentication", "payment")

    • You want ALL files related to a concept, not just exact matches

    • Keywords may not appear literally in filenames

    • Results: File paths grouped by relevance, with summaries of matched symbols

  2. "definition" - USE WHEN:

    • User asks "where is X defined?" or "find the implementation of X"

    • You need to locate a SPECIFIC function, class, method, or variable by name

    • Query is an exact symbol name (e.g., "authenticate_user")

    • Results: Symbol definitions with file paths, line numbers, source code

  3. "references" - USE WHEN:

    • User asks "where is X used?" or "find all usages of X"

    • You need cross-references showing where a symbol is imported/called

    • Query MUST be the exact symbol name

    • Returns all files and line numbers where symbol appears

  4. "file_structure" - USE WHEN:

    • User asks "show me the structure of file X" or "what's in this file?"

    • You need an overview of all symbols in a specific file

    • Query MUST be the file path (e.g., "src/auth/login.py")

    • Returns symbols ordered by line number

EXAMPLE QUERIES by search_type:

  • "topic_discovery": "workout tracking", "authentication flow", "email notifications"

  • "definition": "UserAuth", "calculate_total", "PaymentProcessor"

  • "references": "send_email", "validate_token"

  • "file_structure": "src/services/auth.py"

INSTEAD OF GREP EXAMPLES:

  • Instead of: grep -r "auth" . → Use: search_code(query="auth", search_type="topic_discovery")

  • Instead of: grep -r "class User" → Use: search_code(query="User", search_type="definition")

  • Instead of: grep -r "import.*auth" → Use: search_code(query="auth", search_type="references")

  • Instead of: find . -name "*.py" | xargs grep "login" → Use: search_code(query="login", search_type="topic_discovery")

Do NOT use this tool for:

  • Reading full file contents (use your built-in file reader)

  • Git history queries (use search_history)

  • Pure documentation/conceptual questions (use search_docs)

Args: query: For topic_discovery: any feature/domain/topic (e.g., "workouts"). For definition: symbol name or semantic description. For references: exact symbol name. For file_structure: file path. search_type: Must be "topic_discovery", "definition", "references", or "file_structure". directory: Path to the project directory to search.

Returns: Dict with status, search_type, query, and results array.

For topic_discovery, each result includes:
- file_path, relevance_score, matched_symbols, symbol_kinds, summary
- top_snippets: Code snippets from top-matching symbols

For definition, each result includes:
- name, kind, file_path, line_start, line_end, source_text, score
- docstring: Extracted docstring (if available)
- parent: {name, kind} of containing class/module
- signature: First line of the symbol (function signature or class declaration)

For references, each result includes:
- symbol_name, file_path, line_number
- source_line: The actual line of code with the reference
- containing_symbol: {name, kind} of the function/class containing this reference

For file_structure, each result includes:
- name, kind, line_start, line_end, parent
ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
directoryYes
search_typeYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.9/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses behavioral traits: requires indexing (prerequisite), uses hybrid retrieval, return format for each search_type, and error conditions (empty results prompt indexing). It even mentions using Reciprocal Rank Fusion.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is long but well-structured with sections, headings, and bullet points. It front-loads the crucial message and every sentence serves a purpose. Slightly verbose but justified by tool complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (multiple search types, output schema), the description is comprehensive. It covers prerequisites, when to use/not use, examples for each search_type, and return format details. Differentiates from siblings effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, but the description adds detailed semantics for each parameter: query explained per search_type, search_type enum values described with use cases, and directory specified as project path. Example queries further clarify usage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it performs semantic code search using hybrid retrieval, far more intelligent than grep/glob/find. It distinguishes from sibling tools like search_docs, search_history, and file readers. Each search_type is explicitly defined with use cases.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool (over grep/glob/find) and when not to (file reading, git history, documentation). It includes detailed scenarios for each search_type, with example queries and alternatives to common grep commands.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_docsA

USE THIS TOOL for conceptual understanding and "how does X work?" questions. Search markdown documentation, READMEs, and code docstrings using semantic search.

PREREQUISITE: This tool requires indexing. If results are empty or you haven't indexed this session, call index_codebase(directory) first.

TRIGGER - Call this tool when the user asks:

  • "How does [feature] work?"

  • "Explain the architecture of..."

  • "What are the setup/installation instructions?"

  • "Show me the documentation for..."

  • "Why was this designed this way?"

  • Any question answered by README, CHANGELOG, or docstrings

IMPORTANT: This is NOT for finding code implementations. For code locations, use search_code. This tool searches DOCUMENTATION, not source code.

Uses HYBRID RETRIEVAL (BM25 keyword search + dense vector semantic search with Reciprocal Rank Fusion) to find conceptually relevant documentation even when keywords don't match exactly.

Do NOT use this tool for:

  • Finding function/class definitions (use search_code with "definition")

  • Finding where code is used (use search_code with "references")

  • Git history or commit messages (use search_history)

Args: query: A natural language question (e.g., "How does authentication work?" or "API rate limiting"). Can be conversational - semantic search handles synonyms. directory: Path to the project directory to search. top_k: Maximum results to return (default 10, max 100).

Returns: Dictionary with 'results' array. Each result includes: - content: The documentation text - file: Source file path - section: Section heading (if applicable) - line_start/line_end: Location in source - relevance_score: Hybrid search score

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
top_kNo
directoryYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.9/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses behavior: it uses hybrid retrieval (BM25 + dense vector + RRF), requires indexing first, and returns specific fields. It clearly states it is read-only and does not search code. No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with sections (PREREQUISITE, TRIGGER, IMPORTANT, Do NOT use) and front-loads the main purpose. It is slightly long but every sentence adds value; minor redundancy could be trimmed but overall effective.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and an output schema described in the description, the description covers all parameters, prerequisites, usage differentiation, and return format. It is complete for a search tool, addressing common agent questions about when and how to use it.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, but the description adds meaning to each parameter: query (natural language question, conversational), directory (path to project), top_k (max results, default 10, max 100). This compensates fully for missing schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it searches documentation for conceptual understanding and 'how does X work?' questions. It specifies verb 'search' and resource 'markdown documentation, READMEs, and code docstrings', and distinguishes from sibling tools like search_code by explicitly stating it is not for code implementations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit when-to-use scenarios (conceptual questions, setup, architecture) and when-not-to-use (function definitions, code references, git history). It names alternative tools (search_code, search_history) and includes a prerequisite (indexing) and trigger questions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_historyA

USE THIS TOOL for Git history queries: understanding WHY changes were made, debugging regressions, or finding commit context. This tool operates on the local Git repository.

TRIGGER - Call this tool when the user asks:

  • "Why was this code changed?" / "Who changed this?"

  • "When was X introduced?" / "Find commits about X"

  • "Debug this regression" / "What broke this?"

  • "Show me the history of this file"

  • "Who wrote this line?" (blame)

  • "What changed in commit X?"

This tool does NOT require indexing - it queries Git directly.

WHEN TO USE EACH search_type:

  1. "commits" - USE WHEN:

    • User asks "find commits about X" or "search commit messages"

    • Query is a keyword or phrase to search in commit messages

    • Optionally set target_file to filter commits touching that file

    • Args: query (required), target_file (optional)

  2. "file_history" - USE WHEN:

    • User asks "show history of file X" or "what happened to this file?"

    • Shows commit log for a specific file (follows renames)

    • target_file is REQUIRED; query is ignored

    • Args: target_file (required)

  3. "blame" - USE WHEN:

    • User asks "who wrote this line?" or "who last modified this?"

    • Shows line-by-line commit attribution

    • target_file is REQUIRED; optionally limit to line range

    • Args: target_file (required), line_start/line_end (optional)

  4. "commit_detail" - USE WHEN:

    • User asks "show me commit X" or "what changed in this commit?"

    • Query is the commit hash (full or abbreviated)

    • Optionally set target_file to show only changes to that file

    • Args: query=commit_hash (required), target_file (optional)

Do NOT use this tool for:

  • Finding code definitions (use search_code)

  • Reading documentation (use search_docs)

  • Non-Git questions

Args: query: Search term for commits, or commit hash for commit_detail. directory: Path to the project directory (git repository). search_type: Must be exactly "commits", "file_history", "blame", or "commit_detail". target_file: File path (required for file_history and blame). line_start/line_end: Line range for blame (optional).

Returns: Varies by search_type. All include status and structured results.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
line_endNo
directoryYes
line_startNo
search_typeNocommits
target_fileNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.9/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description covers behavior thoroughly: operates on local Git repo, no indexing needed, explains each search type's behavior (e.g., blame shows line-by-line attribution, file_history follows renames). It does not contradict any annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (TRIGGER, WHEN TO USE EACH, DO NOT USE) and front-loaded purpose. While somewhat lengthy, each part adds value, and the format aids readability.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has 4 search types and an output schema, the description covers all necessary aspects: usage scenarios, parameter roles, return variations. It is fully adequate for an agent to invoke correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Despite 0% schema coverage, the description adds rich meaning for each parameter per search type, including required/optional context, examples, and argument details. This far exceeds baseline.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool is for Git history queries with specific verb and resource, and explicitly distinguishes from sibling tools (search_code, search_docs) by listing what not to use it for.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit triggers (e.g., 'Why was this code changed?') and detailed when-to-use guidance for each search_type, including when not to use and alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 7 tool updatesv1.0.33
    • First observedcheck_index_status
    • First observedfind_dead_code
    • First observedget_index_stats
    • First observedindex_codebase
    • First observedsearch_code
    • First observedsearch_docs
    • First observedsearch_history

TDQS

A4.7/5.0
Disambiguation5/5

Each tool has a distinct, well-defined purpose: checking index status, finding dead code, getting stats, indexing, searching code, searching docs, and searching history. No overlaps or ambiguous boundaries.

Naming Consistency5/5

All tool names use a consistent snake_case pattern with descriptive verbs (check, find, get, index, search) followed by the target domain (index_status, dead_code, index_stats, codebase, code, docs, history). Minor variations in length do not hinder predictability.

Tool Count5/5

With 7 tools, the set is well-scoped for a code intelligence server. Each tool provides essential functionality (indexing, search, dead code analysis, stats, history) without redundancy or bloat.

Completeness5/5

The tool surface covers the full lifecycle: indexing (index_codebase), status checks (check_index_status, get_index_stats), code and documentation search (search_code, search_docs), dead code detection (find_dead_code), and git history (search_history). There are no obvious gaps for the stated purpose.

Maintenance

ActivityInactive
ResponsivenessUnresponsive

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    B
    maintenance
    A high-performance MCP server for semantic search and codebase indexing using the Qdrant vector database. It features optimized embedding pipelines, AST-aware chunking, and git metadata enrichment for fast, privacy-focused local or remote search.
    96
    11
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    Local MCP server for semantic code search using Tree-sitter AST parsing, local embeddings, and hybrid search; enables indexing and querying codebases entirely offline.
    5
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kapillamba4/code-memory'

If you have feedback or need assistance with the MCP directory API, please join our Discord server