Skip to main content
Glama

Mason – LLM 的上下文构建器 👷

npm version CI npm downloads license issues

Mason 为 LLM 提供了一个持久的代码库映射,这样它们就不必在每次会话时都从头开始探索。

问题: 每当 LLM 开始关于您的代码的新对话时,它都会进行 grep、读取文件并拼凑架构——在昨天已经理解的上下文上浪费 token。在一个包含 164 个文件的项目中,回答“这个应用有哪些功能?”需要通过多次工具调用读取 8 个以上的文件。

Mason 的解决方案: 一个跨会话持久存在的概念图。一次工具调用即可返回功能到文件的查找表——LLM 无需探索即可准确知道去哪里查找。

测量结果 (deepeval, Claude Sonnet, 164 个文件的 KMP 项目):

问题

使用 Mason

不使用 Mason

Token 节省

列出所有功能

10,258 tok

31,346 tok

67%

追踪数据流

12,010 tok

15,258 tok

21%

比较平台

10,897 tok

19,353 tok

44%

入门流程

10,271 tok

11,432 tok

10%

平均

36%

相同的回答质量(所有测试中均为 0.9/1.0,两条路径相同)。复现:bench/。

快速开始

claude mcp add mason --scope user -- npx -p mason-context mason-mcp

重启 Claude Code,然后询问:"use mason to analyze this project and create a snapshot."

就是这样——Mason 将分析您的代码库并创建一个概念图。在下一次会话中,它会加载该映射,而不是重新探索所有内容。

Related MCP server: ontomics

工作原理

概念图

Mason 的核心功能。它在 .mason/snapshot.json 中持久化一个功能到文件的映射,该映射在对话之间保持有效。当 LLM 需要了解您的项目时,它会读取此映射,而不是在整个代码库中进行 grep:

{
  "features": {
    "home screen": {
      "files": ["HomeScreen.kt", "HomeViewModel.kt", "GetWeatherDataUseCase.kt"]
    }
  },
  "flows": {
    "weather fetch": {
      "chain": ["HomeViewModel.kt", "WeatherRepositoryImpl.kt", "WeatherServiceImpl.kt"]
    }
  }
}

该映射由 LLM 本身生成——Mason 提供分析工具,LLM 解释您的代码以确定功能和流程是什么。这意味着该映射捕获的是架构理解,而不仅仅是文件列表。

通过让您的 AI 助手执行 "create a mason snapshot" 或通过 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 commit

变更影响分析

在编辑文件之前,Mason 可以告诉您还有什么可能受到影响。它结合了三个信号,每个信号都需要多次工具调用才能手动收集:

  • 共同变更历史 — 在 git 提交中历史上一起变更的文件

  • 引用 — 导入或按名称提及目标的文件

  • 相关测试 — 通过命名约定与目标配对的测试文件

mason impact WeatherRepository.kt -d ~/my-project

也可作为 get_impact MCP 工具使用——询问您的助手 "what would be affected if I changed WeatherRepository?"

Git 历史分析

Mason 将数百次提交汇总为可操作的统计数据:哪些文件变更最频繁(您应该小心处理的热点文件),哪些目录几个月没动过(可能是陈旧代码),以及团队遵循什么提交约定。这种分析如果手动计算,需要数十次 git log 调用。

mason analyze ~/my-project

MCP 工具

Mason 通过模型上下文协议 (Model Context Protocol) 公开 6 个工具。任何兼容 MCP 的客户端(Claude Code、Cursor 等)都可以使用它们:

工具

功能

get_snapshot

加载概念图 — 将功能/流程映射到文件

save_snapshot

为未来的会话持久化概念图

get_impact

变更影响:共同变更历史、引用、相关测试

analyze_project

Git 历史:提交模式、热点文件、陈旧目录

full_analysis

一体化首次访问:git 统计 + 结构 + 代码示例 + 测试映射

get_code_samples

按架构角色选择的智能文件预览

CLI 使用

Mason 也可作为独立的 CLI 使用,用于生成 CLAUDE.md 文件并在没有 MCP 客户端的情况下运行分析。配置一次 LLM 提供程序,然后使用任何命令:

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 map

大多数提供程序无需 API 密钥即可工作 — claude、gemini 和 ollama 都直接使用它们各自的 CLI。

安全性

快照包含的内容: 功能名称、相对文件路径和流程描述。不包含源代码、密钥或业务逻辑。

不涉及的内容: Mason 尊重 .gitignore(通过 git ls-files),并有一个拒绝列表,阻止 .env、.pem、.key、凭据和其他敏感文件被采样。路径遍历保护确保所有文件访问都保持在项目根目录内。

LLM 数据流: 通过 CLI 生成快照会将采样的文件内容发送到您配置的 LLM 提供程序 — 这与任何 AI 编码助手读取您代码的方式相同。使用 ollama 进行完全本地生成。MCP 服务器工具(get_snapshot、get_impact 等)仅读取本地文件。

语言支持

Mason 完全与语言无关。它使用文件命名模式和 git 历史记录,而不是特定于语言的解析,因此它适用于任何拥有源文件和 git 存储库的项目 — TypeScript、Kotlin、Python、Go、Rust、Swift、Java、C#、Dart 等。

许可证

MIT

Available Tools

12 tools
get_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

    A3.6/5.0

    Scored across 12 tools

    Disambiguation3/5

    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.

    Naming Consistency3/5

    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.

    Tool Count4/5

    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.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      A
      quality
      D
      maintenance
      A 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.
      14
      302
      -
    • A
      license
      A
      quality
      D
      maintenance
      Extract 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.
      19
      44
      MIT
    • F
      license
      B
      quality
      B
      maintenance
      Turns 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
      -
    • A
      license
      Not graded
      quality
      A
      maintenance
      Turns 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