Skip to main content
Glama

⚡ RepoContext

CI npm version License: MIT MCP Compatible TypeScript

El motor de mapas de código AST, compresión de tokens y empaquetado de contexto de nueva generación para agentes de codificación con IA e IDEs.

English | 中文说明


🌟 ¿Por qué RepoContext?

Al introducir bases de código en los asistentes de codificación con IA modernos (Claude Code, Cursor, Windsurf, OpenAI Codex, Antigravity, Cline), los desarrolladores se enfrentan a tres cuellos de botella críticos:

  1. 💥 Explosión de tokens y altos costes de API: Los volcados de código en bruto superan rápidamente los límites de contexto o cuestan decenas de dólares por consulta.

  2. 📉 Baja relación señal-ruido: El 80% de las líneas son detalles de implementación rutinarios. Los LLM solo necesitan la superficie semántica de la API (firmas, tipos, interfaces, docstrings).

  3. 🔓 Fugas de seguridad: Exposición accidental de credenciales de .env, claves de API y URI de bases de datos en los prompts.

RepoContext resuelve los tres con poda inteligente de esquemas AST, clasificación semántica de archivos centrada en la tarea, redacción automática de credenciales e integración nativa con Model Context Protocol (MCP).


Related MCP server: AtlasMemory

🚀 Características principales

  • ⚡ Mapa AST de la base de código y esqueletizador: Comprime los archivos fuente en un 70%~85% conservando el 100% de las interfaces, tipos, funciones y JSDoc/docstrings.

  • 🎯 Poda de relevancia orientada a tareas: Pasa tu consulta de prompt (p. ej. repocontext pack -q "Fix JWT auth token expiry") para clasificar y empaquetar automáticamente solo los archivos más críticos.

  • 🛡️ Escáner automático de secretos y redacción: El escáner integrado de entropía y regex detecta y enmascara claves de OpenAI, tokens de GitHub, claves de AWS, JWT y URI de bases de datos.

  • 🔌 Servidor nativo de Model Context Protocol (MCP): Se integra directamente con Claude Desktop, Cursor, Windsurf y Antigravity mediante las herramientas estándar de MCP.

  • 📑 Exportación multiformato: Genera Markdown limpio con árboles de directorios, XML optimizado para Claude (<documents>) o JSON estructurado.

  • 📊 Analítica de tokens y costes multimodelo: Contador de tokens en tiempo real con estimaciones de coste para GPT-4o, GPT-5, Claude 3.5 Sonnet y Gemini 1.5 Pro.


📦 Inicio rápido

1. Ejecutar sin instalación mediante npx

# Pack entire repository into an optimized Markdown prompt
npx repocontext pack

# Pack only files relevant to a specific task prompt
npx repocontext pack -q "Implement Stripe payment webhook handler" -o prompt.md

# Generate lightweight AST skeleton map (75%+ token reduction)
npx repocontext map -o codebase-map.md

2. Instalación global

npm install -g repocontext

🛠️ Uso y opciones de la CLI

repocontext pack [dir] [options]

Options:
  -m, --mode <mode>         Packing mode: full | ast | relevant | hybrid (default: "full")
  -q, --query <query>       Filter and rank files relevant to a coding task prompt
  -f, --format <format>     Output format: markdown | xml | json (default: "markdown")
  -o, --output <file>       Output file path (default: "repocontext-output.md")
  -t, --max-tokens <number> Maximum token budget ceiling (default: 80000)
  --no-security             Disable secret scanning and auto-redaction
  -h, --help                Display help for command

🔌 Integración con Model Context Protocol (MCP)

RepoContext incluye soporte integrado de servidor MCP. Añádelo a tu claude_desktop_config.json o a la configuración MCP de Cursor/Windsurf:

{
  "mcpServers": {
    "repocontext": {
      "command": "npx",
      "args": ["-y", "repocontext", "mcp"]
    }
  }
}

Herramientas MCP expuestas:

  • get_codebase_map: Devuelve el mapa esquemático de símbolos AST del repositorio.

  • extract_relevant_context: Poda la base de código y devuelve solo los archivos necesarios para un prompt.

  • read_file_outline: Lee el esqueleto AST comprimido de un solo archivo.


📊 Benchmark y comparación

Característica

Concatenación en bruto

Repomix

RepoContext

Poda de esqueleto AST

❌ No

❌ No

✅ Sí (80% de ahorro de tokens)

Clasificador de relevancia de tareas

❌ No

❌ No

✅ Sí (poda guiada por consulta)

Redacción automática de secretos

❌ No

⚠️ Básico

✅ Sí (10+ reglas de seguridad)

Servidor MCP nativo

❌ No

❌ No

✅ Sí (Claude / Cursor / Windsurf)

Estimación de costes multimodelo

❌ No

❌ No

✅ Sí (GPT-4o/5, Claude, Gemini)


🤝 Contribuciones

¡Las contribuciones, las incidencias y las solicitudes de funcionalidades son bienvenidas! No dudes en consultar la página de incidencias.

📄 Licencia

Este proyecto está bajo licencia MIT.

Available Tools

4 tools
extract_relevant_contextA

Performs semantic relevance ranking to extract and package code files pertinent to a specific user coding task or bug report within a token budget.

Behavior: Read-only operation. Zero file modifications, zero persistent side-effects, and zero network calls. Applies automatic secret redaction. Returns formatted Markdown.

When to use: Use this when given a specific feature request, issue, or debugging objective to gather only the essential source code.

When NOT to use: Do NOT use this for full-repository structural overviews (use get_codebase_map instead), or to inspect single file outlines (use read_file_outline instead).

NameRequiredDescriptionDefault
queryYesNatural language task description, bug report, or feature prompt used for semantic and citation-based file scoring.
rootDirNoPath to repository root directory. Defaults to current working directory (".").
maxTokensNoMaximum token budget ceiling (1,000 to 128,000; default: 40000). Files with highest relevance scores are packed first until budget is exhausted.

TDQS

A4.7/5.0
Behavior5/5

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

With no annotations provided, the description carries the full burden and does so thoroughly. It explicitly discloses read-only behavior, zero file modifications, zero persistent side-effects, zero network calls, automatic secret redaction, and Markdown return format.

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?

The description is well-structured with clear Behavior, When to use, and When NOT to use sections. It is front-loaded with the core purpose, uses concise sentences, and every section adds actionable information without redundancy.

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?

For a moderately complex tool with no annotations and no output schema, the description covers operation, safety profile, return format, usage guidance, and exclusions. An agent has enough context to invoke the tool correctly and understand what to expect.

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

Parameters3/5

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

Schema description coverage is 100%, so the input schema already fully documents query, rootDir, and maxTokens. The description reinforces the token-budget concept but does not add substantial parameter-level meaning beyond what the schema provides, hence the baseline score.

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 states a specific verb ('extracts and packages'), a clear resource (code files relevant to a user task or bug report), and a limiting constraint (token budget). It is clearly differentiated from siblings by focusing on semantic relevance rather than repository maps or file outlines.

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 'When to use' and 'When NOT to use' sections explicitly state appropriate scenarios and name the exact sibling tools to use instead, such as get_codebase_map and read_file_outline. This gives an agent unambiguous selection criteria.

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

get_codebase_mapA

Extracts a token-efficient AST symbol outline map (classes, interfaces, functions, methods, exported types) across the repository.

Behavior: Read-only operation. Zero file modifications, zero persistent side-effects, and zero network calls. Returns structured Markdown.

When to use: Call this at the start of a coding task to inspect repository architecture, directory structure, and symbol hierarchies with 70%~85% token savings.

When NOT to use: Do NOT use this if you need full function implementations (use read_file_content instead), or if you already know the target task and want only relevant files (use extract_relevant_context instead).

NameRequiredDescriptionDefault
rootDirNoPath to repository root directory. Defaults to current working directory ("."). Respects .gitignore and built-in binary exclusions.

TDQS

A4.7/5.0
Behavior5/5

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

With no annotations provided, the description fully discloses behavior: read-only, zero modifications, zero side-effects, zero network calls, and returns structured Markdown. This is exactly the behavioral transparency needed for a tool with no annotation support.

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?

Well-structured with clear sections (purpose, behavior, usage). Every sentence adds value and the most critical information (read-only, usage guidance) is front-loaded.

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?

For a simple read-only tool with one optional parameter and no output schema, the description is complete: it explains what it returns, when to use it, and when not to. No essential information is missing.

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

Parameters3/5

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

Schema description coverage is 100% for the single parameter rootDir, which already explains its purpose and defaults. The description does not add additional parameter semantics, so the baseline of 3 is appropriate.

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?

Clearly states the verb 'Extracts' and the resource 'AST symbol outline map' with specific contents (classes, interfaces, functions, methods, exported types). It also differentiates itself from siblings by mentioning token savings and scope.

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 'When to use' and 'When NOT to use' sections, naming alternatives (read_file_content and extract_relevant_context) and the conditions that select them. This leaves no ambiguity for the agent.

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

read_file_contentA

Reads raw source code from a single file, with optional line-range slicing and automatic security redaction for secrets and sensitive keys.

Behavior: Read-only operation. Zero file modifications and zero network calls. Automatically masks detected credentials. Returns formatted Markdown code block with line indicators.

When to use: Use this when you must inspect, debug, or verify exact line-by-line implementation logic of a specific file identified through previous outline or mapping steps.

When NOT to use: Do NOT use this for blind exploration of unfamiliar files (use read_file_outline or get_codebase_map first to conserve token budget).

NameRequiredDescriptionDefault
endLineNo1-indexed ending line number, inclusive (optional, default: end of file).
rootDirNoBase directory used to resolve relative filePath. Defaults to current working directory (".").
filePathYesRelative or absolute path to the file to inspect.
startLineNo1-indexed starting line number (optional, default: 1). Useful for viewing specific functions or ranges in large files.

TDQS

A4.7/5.0
Behavior5/5

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

No annotations are provided, so the description carries the full burden—and it does so thoroughly. It states read-only operation, zero file modifications, zero network calls, automatic masking of credentials, and the Markdown code-block output format with line indicators. This is unusually complete behavioral disclosure.

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?

The description is organized into short labeled sections: Behavior, When to use, and When NOT to use, plus a one-sentence opener. Every sentence earns its place, and the most important facts—single file, raw source, redaction—are front-loaded.

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?

Despite having no annotations and no output schema, the description covers the safety profile (read-only, no network), the return format (Markdown code block with line indicators), and the appropriate usage boundaries. The schema fully covers all four parameters, so nothing essential is missing for correct invocation.

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

Parameters3/5

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

Schema description coverage is 100%, so the baseline is 3. The description mentions 'optional line-range slicing,' which conceptually maps to startLine/endLine, but it does not add meaning beyond the schema's own parameter descriptions. The schema already documents defaults and 1-indexed behavior.

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 opens with a specific verb-resource pair: 'Reads raw source code from a single file,' and further clarifies it supports line-range slicing and redaction. It is clearly distinguished from sibling outline/map tools by emphasizing exact line-by-line content rather than structural overviews.

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?

An explicit 'When to use' block says to use it for inspecting, debugging, or verifying line-by-line implementation of a specific file. An explicit 'When NOT to use' block warns against blind exploration and names read_file_outline and get_codebase_map as token-saving alternatives, giving the agent concrete decision rules.

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

read_file_outlineA

Extracts the semantic AST skeleton outline of a single source file, preserving all class declarations, function signatures, interfaces, and docstrings while stripping function bodies.

Behavior: Read-only operation. Zero file modifications and zero network calls. Returns syntax-highlighted code block.

When to use: Use this to understand API contracts, public types, and method signatures of an individual file without consuming tokens on implementation details.

When NOT to use: Do NOT use this if you need complete implementation logic (use read_file_content instead), or if you need an overview of multiple repository files (use get_codebase_map instead).

NameRequiredDescriptionDefault
rootDirNoBase directory used to resolve relative filePath. Defaults to current working directory (".").
filePathYesRelative or absolute path to the target source file.

TDQS

A4.7/5.0
Behavior5/5

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

With no annotations provided, the description carries the full behavioral disclosure burden. It explicitly states it is read-only, makes zero file modifications, zero network calls, and returns a syntax-highlighted code block, while also describing the transformation (stripping bodies, preserving signatures). This is comprehensive and unambiguous.

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?

The description is organized into purpose, behavior, and usage guidance sections, with each sentence contributing value. The core functionality and safety profile are front-loaded, and the alternative tools are mentioned in a dedicated 'when NOT to use' clause. No fluff or redundancy.

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?

For a two-parameter, read-only tool with no output schema, the description covers purpose, behavior, return format, and usage boundaries explicitly. An agent has all the information needed to decide when to call it and what to expect in return, making the description complete given the tool's simplicity.

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

Parameters3/5

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

Schema description coverage is 100% for both parameters, with clear meanings for filePath and rootDir. The description does not add parameter-specific details beyond what the schema already provides, so the baseline of 3 applies.

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?

Description states a specific verb ('extracts') and resource ('semantic AST skeleton outline of a single source file'), and details what is preserved (class declarations, function signatures, interfaces, docstrings) and what is stripped (function bodies). It clearly differentiates from siblings by specifying single-file scope and the outline nature.

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?

Explicit 'When to use' and 'When NOT to use' sections name the exact alternatives (read_file_content for implementation logic, get_codebase_map for multi-file overview) and the conditions that select this tool. Nothing is left to inference.

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.

  1. 4 tool updatesv1.2.0
    • Changedextract_relevant_context3 fields changed
      • changedInput schema / properties / maxTokens / description
        Previous value: -"Token budget ceiling (default: 40000)"New value: +"Maximum token budget ceiling (1,000 to 128,000; default: 40000). Files with highest relevance scores are packed first until budget is exhausted."
      • changedInput schema / properties / query / description
        Previous value: -"Task description or coding prompt (e.g., \"Fix JWT authentication token expiration error\")"New value: +"Natural language task description, bug report, or feature prompt used for semantic and citation-based file scoring."
      • changedInput schema / properties / rootDir / description
        Previous value: -"Path to repository root directory"New value: +"Path to repository root directory. Defaults to current working directory (\".\")."
    • Changedget_codebase_map1 field changed
      • changedInput schema / properties / rootDir / description
        Previous value: -"Path to repository root directory (default: current working directory)"New value: +"Path to repository root directory. Defaults to current working directory (\".\"). Respects .gitignore and built-in binary exclusions."
    • Addedread_file_content
    • Changedread_file_outline2 fields changed
      • changedInput schema / properties / filePath / description
        Previous value: -"Relative or absolute path to the file"New value: +"Relative or absolute path to the target source file."
      • addedInput schema / properties / rootDir
        Added value: +{
        +  "description": "Base directory used to resolve relative filePath. Defaults to current working directory (\".\").",
        +  "type": "string"
        +}
  2. 3 tool updatesv0.1.0
    • First observedextract_relevant_context
    • First observedget_codebase_map
    • First observedread_file_outline

TDQS

A4.8/5.0

Scored across 4 tools

Disambiguation5/5

Each tool serves a clearly distinct purpose: repo-wide symbol map, task-specific file extraction, single-file outline, and full file content. The descriptions include explicit 'when to use' and 'when NOT to use' guidance, eliminating any potential for misselection.

Naming Consistency5/5

All four tools follow the verb_noun snake_case pattern (get_codebase_map, extract_relevant_context, read_file_outline, read_file_content). While the verbs differ (get, extract, read), the structure is consistent and the names accurately reflect each tool's function.

Tool Count5/5

With exactly 4 tools, the server is well-scoped for its purpose of repository context exploration. Each tool fills a distinct role in the workflow, and there is no redundancy or unnecessary bloat.

Completeness5/5

The tool set covers the full lifecycle of code exploration: repo-wide mapping, semantic relevance filtering for tasks, single-file outlines, and raw content access. This provides a complete read-only context-gathering workflow with no obvious dead ends or missing operations.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Provides intelligent code context and analysis through semantic compression, AST parsing, and multi-language support. Offers 60-80% token reduction while enabling AI assistants to understand codebases through local analysis, OpenAI-enhanced insights, and GitHub repository integration.
    6
    14 npm
    3
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Turn any codebase into an AI-readable neural map — with proof. Every claim linked to code anchors (line + SHA-256 hash), every context window optimized with greedy token budgeting, every session protected by drift detection. Tree-sitter indexing across 11 languages, cross-session learning, AI enrichment, and 28 MCP tools. Zero config — just connect and your AI agent remembers everything.
    1 npm
    14
    GPL 3.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    Make any LLM a codebase expert instantly. Provides deep code intelligence through semantic search, architecture mapping, security analysis, and smart context that fits perfectly in token windows.
    MIT