mason
Mason – el constructor de contexto para LLMs 👷
Mason proporciona a los LLMs un mapa persistente de tu base de código para que dejen de explorar desde cero en cada sesión.
El problema: Cada vez que un LLM inicia una nueva conversación sobre tu código, utiliza grep, lee archivos y reconstruye la arquitectura, consumiendo tokens en un contexto que ya entendía ayer. En un proyecto de 164 archivos, responder "¿qué funciones tiene esta aplicación?" requiere leer más de 8 archivos a través de múltiples llamadas a herramientas.
La solución de Mason: Un mapa conceptual que persiste entre sesiones. Una llamada a la herramienta devuelve una tabla de búsqueda de funciones a archivos: el LLM sabe exactamente dónde buscar, sin necesidad de explorar.
Resultado medido (deepeval, Claude Sonnet, proyecto KMP de 164 archivos):
Pregunta | Con Mason | Sin Mason | Ahorro de tokens |
Listar todas las funciones | 10,258 tok | 31,346 tok | 67% |
Rastrear flujo de datos | 12,010 tok | 15,258 tok | 21% |
Comparar plataformas | 10,897 tok | 19,353 tok | 44% |
Flujo de onboarding | 10,271 tok | 11,432 tok | 10% |
Promedio | 36% |
La misma calidad de respuesta (0.9/1.0 en todas las pruebas, ambos caminos). Reproducir: bench/.
Inicio rápido
claude mcp add mason --scope user -- npx -p mason-context mason-mcpReinicia Claude Code y luego pregunta: "use mason to analyze this project and create a snapshot."
Eso es todo: Mason analizará tu base de código y creará un mapa conceptual. En la siguiente sesión, cargará el mapa en lugar de volver a explorar todo.
Related MCP server: ontomics
Cómo funciona
Mapa conceptual
La función principal de Mason. Persiste un mapa de funciones a archivos en .mason/snapshot.json que sobrevive a las conversaciones. Cuando el LLM necesita entender tu proyecto, lee este mapa en lugar de buscar mediante grep en toda tu base de código:
{
"features": {
"home screen": {
"files": ["HomeScreen.kt", "HomeViewModel.kt", "GetWeatherDataUseCase.kt"]
}
},
"flows": {
"weather fetch": {
"chain": ["HomeViewModel.kt", "WeatherRepositoryImpl.kt", "WeatherServiceImpl.kt"]
}
}
}El mapa es generado por el propio LLM: Mason proporciona las herramientas de análisis y el LLM interpreta tu código para decidir cuáles son las funciones y los flujos. Esto significa que el mapa captura la comprensión arquitectónica, no solo listados de archivos.
Crea uno pidiéndole a tu asistente de IA que "create a mason snapshot", o mediante la CLI:
mason set-llm gemini # configure a provider (no API key needed)
mason snapshot ~/my-project # generate concept map
mason snapshot --install-hook # auto-update on every commitAnálisis de impacto de cambios
Antes de editar un archivo, Mason puede decirte qué más podría verse afectado. Combina tres señales que requerirían múltiples llamadas a herramientas para recopilar manualmente:
Historial de cambios conjuntos — archivos que históricamente cambian juntos en los commits de git
Referencias — archivos que importan o mencionan el objetivo por su nombre
Pruebas relacionadas — archivos de prueba emparejados con el objetivo por convención de nombres
mason impact WeatherRepository.kt -d ~/my-projectTambién disponible como la herramienta MCP get_impact: pídele a tu asistente "what would be affected if I changed WeatherRepository?"
Análisis del historial de Git
Mason agrega cientos de commits en estadísticas procesables: qué archivos cambian con más frecuencia (archivos "calientes" con los que debes tener cuidado), qué directorios no se han tocado en meses (código potencialmente obsoleto) y qué convenciones de commit sigue el equipo. Este es el tipo de análisis que requeriría docenas de llamadas a git log para calcular manualmente.
mason analyze ~/my-projectHerramientas MCP
Mason expone 6 herramientas a través del Protocolo de Contexto de Modelo (MCP). Cualquier cliente compatible con MCP (Claude Code, Cursor, etc.) puede usarlas:
Herramienta | Qué hace |
| Carga el mapa conceptual: mapea funciones/flujos a archivos |
| Persiste el mapa conceptual para futuras sesiones |
| Impacto de cambios: historial de cambios conjuntos, referencias, pruebas relacionadas |
| Historial de Git: patrones de commit, archivos calientes, directorios obsoletos |
| Todo en uno para la primera visita: estadísticas de git + estructura + muestras de código + mapa de pruebas |
| Vistas previas inteligentes de archivos seleccionadas por rol arquitectónico |
Uso de la CLI
Mason también funciona como una CLI independiente para generar archivos CLAUDE.md y ejecutar análisis sin un cliente MCP. Configura un proveedor de LLM una vez y luego usa cualquier comando:
mason set-llm claude|gemini|ollama|openai # configure provider
mason generate # analyze codebase + LLM -> CLAUDE.md
mason analyze # git stats only (no LLM needed)
mason impact File.kt # change impact analysis
mason snapshot # create/update concept mapLa mayoría de los proveedores funcionan sin una clave API: claude, gemini y ollama utilizan sus respectivas CLI directamente.
Seguridad
Qué contiene la instantánea: Nombres de funciones, rutas de archivos relativas y descripciones de flujos. Sin código fuente, secretos ni lógica de negocio.
Qué no toca: Mason respeta .gitignore (a través de git ls-files) y tiene una lista de denegación que bloquea .env, .pem, .key, credenciales y otros archivos confidenciales para que no sean muestreados. La protección contra el recorrido de rutas garantiza que todo el acceso a archivos permanezca dentro de la raíz del proyecto.
Flujo de datos del LLM: Generar una instantánea a través de la CLI envía contenidos de archivos muestreados a tu proveedor de LLM configurado, de la misma manera que cualquier asistente de codificación de IA lee tu código. Usa ollama para una generación totalmente local. Las herramientas del servidor MCP (get_snapshot, get_impact, etc.) solo leen archivos locales.
Soporte de idiomas
Mason es completamente agnóstico al lenguaje. Utiliza patrones de nombres de archivos e historial de git en lugar de análisis específico del lenguaje, por lo que funciona con cualquier proyecto que tenga archivos fuente y un repositorio git: TypeScript, Kotlin, Python, Go, Rust, Swift, Java, C#, Dart y más.
Licencia
MIT
Available Tools
12 toolsget_contextA
Assemble task context: matching decisions with rationale, approval, owner, sources, last review, and freshness, plus related tests, file impact, and any available map entries. Map verification is rechecked against sampled source contents; stale or unknown verification requires a fresh review, and recordedVerdict preserves the historical verdict. Proposals are suggestions; legacy records are unreviewed; accepted decisions are constraints subject to freshness. No initialization or map required. Pass task and optional files. map.status and diagnostics preserve missing or invalid knowledge. Impact covers up to three unique files, expanding directory anchors.
Inputs: dir (required), task (required), files.
get_impactA
Trace historical co-change partners, related tests, and references with evidence: resolved imports, explicit paths, or uncertain name candidates. Candidates are not proven dependencies. Deterministic and read-only; no initialization or concept map required.
Inputs: dir (required), files (required).
get_snapshotA
Return the optional feature-to-file architecture map with drift and trust evidence. Map verification is rechecked against sampled source contents; stale or unknown verification requires a fresh review, and recordedVerdict preserves the historical verdict. If no map exists, returns exists:false and points to decision context. Decision capture, get_context, and get_impact still work. No initialization required.
Inputs: dir (required).
mason_automationB
Inspect installed automation, observed host events, pending decision records and the notification baseline, or check all retained documentation findings across sessions. status is read-only; check saves local baselines and verification reports without editing source, approving advisories or consuming pending completion notices. Returns concise results with a full report path. Works without a map.
Inputs: dir (required), action (required).
mason_check_driftA
Check how far the concept map has drifted from HEAD. Deterministic (git + filesystem, no LLM). Returns which features/flows are stale and the changed files behind them, new source files not yet mapped, ghost files (mapped but deleted), renames, and a recommendation: up-to-date (nothing to do), incremental (update just the stale entries via save_snapshot), or full-rebuild (broad source review required). Call this before trusting the map in a long session, or when maintaining an existing map.
Inputs: dir (required).
mason_complete_initA
Record assistant instruction setup locally in ignored .mason/local/project.json, with feature settings in shared .mason/config.json. Other tools work without this marker. Repeated calls preserve the original setup time and existing settings.
Inputs: dir (required).
mason_initA
Inspect this project now: returns documentation audit findings, committed-diff review findings, decision/map status, and a quickstart playbook. Quickstart is read-only and deterministic. Explicit mode: setup validates shared configuration and activates locally without editing shared files; mode: init explicitly prepares MCP, instructions and lifecycle hooks for review and commit. Neither runs audits or prepares repairs; use only when requested. Optional host selects codex or claude. Optional base selects the review comparison; evidence imports CI manifests with check outcomes, commit freshness, and links to changed files and accepted decisions. Repeat calls refresh findings even after setup.
Inputs: dir (required), base, host, mode, +2 more.
review_decisionA
Prepare a decision review: returns the claim and any operative accepted revision, provenance, the latest inspection and history event (notes shortened), changed files with hunk and line counts and anchor commits since the latest valid inspection for both sets of anchors, and a reviewToken. Request the diff (optionally for specific diffFiles), source previews or full history with include; the token is unchanged. For accepted-guidance inspection use inspectionScope operative on both prepare and inspect; pending proposals remain unassessed. Default all scope covers both revisions. After source inspection, record inspect with inspector, note and token to report no contradiction found without human acceptance. For human review, prepare with all scope, then record accept, reaffirm, or retire with its token, the authorized reviewer, and a reason. Acceptance replaces the operative revision; retirement withdraws the entire record including its proposal. Acceptance requires owner, source, readable Git HEAD, and committed anchor changes. Changed records or code invalidate the token. Identities and approvals are recorded assertions for normal PR review, not authenticated proof.
Inputs: id (required), dir (required), note, action, +7 more.
save_decisionA
Capture or revise a decision proposal as soon as the lesson is supported by evidence, without waiting for implementation or merge. Keep unimplemented remedies tentative. Include rationale, anchors, optional owner, sources, and a known actor. Compare matching get_context records and pending proposals before saving. When new evidence changes the same lesson's assumptions, scope, or recommended action, pass its existing id, including for accepted records. Preserve supported rationale and sources and replace obsolete instructions. Create a new record for a genuinely distinct lesson; skip unchanged restatements. No setup or map required. Writes a local record and preserves content history. Changes create a pending proposal while the last accepted revision remains operative; unchanged content does not re-verify or refresh it. Use review_decision for authorized acceptance or reaffirmation. A proposal cannot supersede a record with an operative accepted revision; review its replacement and retire the original separately.
Inputs: dir (required), body (required), title (required), category (required), +7 more.
save_snapshotA
Save a concept-to-files map as a persistent project snapshot. Maps feature names and data flows to the files that implement them. Retained for direct maintenance of legacy maps; the managed map-build workflow has been removed. Persists across conversations — future sessions can call get_snapshot to instantly find relevant files. No API key needed — you are the LLM generating the map.
Inputs: dir (required), flows (required), features (required), removeFlows, +1 more.
save_verificationA
Record verify_snapshot verdicts using each entry’s kind and reviewToken. Missing tokens request a fresh review; changed or deleted entries return conflicts without being stamped. Entries judged ok are stamped verifiedAt; failures are flagged verificationFailed with your note and surface in get_context, get_snapshot, and mason_check_drift until corrected. Verdict notes are required for failures.
Inputs: dir (required), verdicts (required).
verify_snapshotA
Spot-check the concept map's CORRECTNESS (drift checks freshness; this checks entries were right to begin with). Returns a sample of entries — always the never-verified and least-recently-verified first — with skeletons of their claimed files, for you to judge whether the files actually implement what the entry claims. Report verdicts back via save_verification with each entry’s kind and reviewToken. Tokens bind the entry and bounded source evidence; changed evidence requires a fresh review. Run periodically, or after an automated refresh wrote entries no human reviewed.
Inputs: dir (required), sample.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 12 tools
Several clusters overlap: mason_init, mason_complete_init, and mason_automation all touch setup/inspection state, while get_snapshot, get_context, get_impact, and verify_snapshot all return map/context views that an agent could easily conflate. verify_snapshot with save_verification and check_drift form a defensible pairing, and the save/review decision tools are distinct, but the descriptions' dense terminology makes tool selection error-prone.
Most names follow a verb_noun pattern (get_snapshot, save_decision, review_decision, check_drift), but only some carry the mason_ prefix (mason_check_drift, mason_init, mason_automation, mason_complete_init) while others do not. 'mason_complete_init' also breaks the verb_noun reading and is easily confused with mason_init.
Twelve tools is within a reasonable band for a map plus decision-lifecycle server, and each cluster (drift, verification, decisions, setup) earns roughly its place. The setup triplet of mason_init, mason_complete_init, and mason_automation is the one area where consolidation would help.
The surface covers the full knowledge lifecycle: map save/get, drift checking, verification verdicts, decision save/review/accept/retire, context assembly, and impact analysis. Minor gaps exist — no tool to delete or clear a snapshot map, and no way to enumerate decisions beyond task-matched get_context lookups.
Maintenance
Related MCP Connectors
Codebase intelligence for AI coding agents: graph, git history, docs, decisions, code health.
Give your AI agent a persistent map of your project's structure, dependencies, and bugs.
Codebase intelligence for AI agents — dead code, blast radius, ownership.
Code-map tools for AI agents: see a repo's structure first, then edit only what matters.
Related MCP Servers
- FlicenseAqualityDmaintenanceA TypeScript tool that ranks files in your codebase by importance, tracks dependencies, and provides file summaries to help understand code structure through Cursor's Model Context Protocol.14302-
- AlicenseAqualityDmaintenanceExtract domain knowledge from codebases to reduce LLM token consumption by 20x and time in agentic search by 10x — gathers and makes concepts, naming conventions, and vocabulary queryable via MCP.1944MIT
- FlicenseBqualityBmaintenanceTurns local code repositories into a queryable dependency graph built from AST parsing and git co-edit history, then exposes it alongside an Obsidian vault as persistent memory. Enables context retrieval, impact analysis of proposed changes, and curation of durable prose knowledge through full-text search and Personalized PageRank classification—all fully offline without API keys or embeddings.30-
- AlicenseNot gradedqualityAmaintenanceTurns a codebase into a persistent knowledge graph so AI coding agents can answer structural questions about functions, call chains, routes, and cross-service links through graph queries instead of reading files one by one.MIT