# archy MCP server

> Analyzes Python import graphs to detect architectural violations, dependency cycles, and the blast radius of code changes.

- Repository: https://github.com/hslee16/archy
- Page: https://hostedmcp.org/servers/hslee16/archy
- Transport: stdio
- Stars: 8
- License: MIT
- Latest version: 0.55.3

## Install

### Claude Code

```sh
claude mcp add archy -- uvx archy
```

### Cursor (`~/.cursor/mcp.json`)

```json
{
  "mcpServers": {
    "archy": {
      "command": "uvx",
      "args": [
        "archy"
      ]
    }
  }
}
```

### VS Code (`.vscode/mcp.json`)

```json
{
  "servers": {
    "archy": {
      "type": "stdio",
      "command": "uvx",
      "args": [
        "archy"
      ]
    }
  }
}
```

### VS Code CLI

```sh
code --add-mcp '{"name":"archy","type":"stdio","command":"uvx","args":["archy"]}'
```

### Claude Desktop (`claude_desktop_config.json`)

```json
{
  "mcpServers": {
    "archy": {
      "command": "uvx",
      "args": [
        "archy"
      ]
    }
  }
}
```

### Codex

```sh
codex mcp add archy -- uvx archy
```

### Codex config.toml (`~/.codex/config.toml`)

```toml
[mcp_servers.archy]
command = "uvx"
args = ["archy"]
```

### Gemini CLI

```sh
gemini mcp add -s user archy uvx -- archy
```

### Gemini settings.json (`~/.gemini/settings.json`)

```json
{
  "mcpServers": {
    "archy": {
      "command": "uvx",
      "args": [
        "archy"
      ]
    }
  }
}
```

## Tools (14)

- `archy_score`: Compute the composite quality score (modularity, acyclicity, depth, equality, complexity - geometric mean of five axes) for a Python project. `view='current'` (the DEFAULT) returns the five-axis score payload; optionally append the result to .archy/history.jsonl (record=True) and/or compare against the most recent recorded run as a regression gate (strict=True). `strict_tolerance` must be in [0, 1] (default 0.02). Pass record=True to record a baseline at session start (replaces the removed archy_record_baseline). `view='history'` instead reads the recent score history (.archy/history.jsonl), returning up to `last_n` rows oldest-first so you can compare deltas over time (replaces the removed archy_trend); last_n must be >= 1, and record/strict/strict_tolerance do not apply. (read-only)
- `archy_cycles`: Find import cycles (Tarjan SCCs of size >= min_size, plus self-loops) in a Python project. Returns cycles sorted largest-first. Each cycle's `type_checking_edges` counts edges that exist only under `if TYPE_CHECKING:` (they never run); when it is non-zero, pass `exclude_type_checking=true` to leave them out. With it on the result is an object, `{cycles, excluded_type_checking_edges}`, so a clean result that is clean only because of the exclusion says so. Unset, it follows archy.yaml's `exclude_type_checking_imports`, else off. (read-only)
- `archy_check`: **Call after any Python edit that adds, removes, or changes an import statement.** Returns forbidden direct edges between layers declared in archy.yaml under `violations`, plus Stable Dependencies Principle violations (when `sdp.enabled: true` in archy.yaml) under `sdp_violations`. Empty lists on both mean no direct boundary crossings. `required_violations` reports the INVERSE constraint: `required:` rules in archy.yaml declare that every module matching `source` must TRANSITIVELY reach `must_reach` (e.g. every standalone entrypoint must reach a model registry that has to be imported before the framework configures itself). Reach counts indirect paths and the implicit package-`__init__` import, so satisfying such a rule once in a package `__init__.py` covers its submodules; each violation carries a `detail` saying which module fails and why, and a rule whose patterns match nothing is reported as a violation rather than passing silently. Fix by adding the missing import, not by deleting the rule. Pass `contracts=True` to ALSO run the transitive (multi-hop) import-linter contracts (Layers, Forbidden, Independence, Protected, AcyclicSiblings) - stricter than the direct archy.yaml edges - nested under the `contracts` field; a failed contract means an indirect import path violates the architecture, so restructure rather than weaken the rule. That path reads .importlinter (or pyproject.toml, override with `contracts_config_path`, relative to `path`) and needs `pip install archy[contracts]`; if the extra is absent, `contracts` comes back with `available=false` and an advisory rather than raising (replaces the removed archy_contracts tool). If no archy.yaml is found, returns an in-band CheckErrorPayload (an `error` field, not a raised error) so you can create one or pass `config_path` (relative to `path`), and contracts are not run in that case; a malformed archy.yaml instead raises (it cannot be checked against). (read-only)
- `archy_impact`: Given a list of changed file paths, return what they affect. Relative `files` are tried under `path` first; missing paths are retried at its git work-tree root and used if they exist there, inside `path`. `mode='blast'` (the DEFAULT) returns the internal modules that transitively import any of them (the blast radius): use before refactoring or removing a module to see what would break. An empty `impacted` means no STATIC importer was found, not that removal is safe: archy cannot see importlib.import_module / __import__, entry points and plugin registries, Django INSTALLED_APPS, pytest plugins, config-driven dispatch, module __getattr__ hooks or string-keyed factories, so `rg` for those before deleting (`empty_caveat` is set whenever this applies). `propagation_cost` is the MacCormack-style scalar (fraction of internal modules the edit set can reach); `chains` explains *why* each impacted module is reachable (the shortest import path back to a changed module, hop by hop with the line numbers where each import lives) so you can cite the specific edge(s) to preserve. Chains are ranked closest-first and capped at `max_chains` (negative for all); `chains_omitted` reports how many were left out. `mode='affected'` (replaces the removed archy_affected) is the CI-shaped lookup instead: it returns the impact pre-classified into `impacted_tests` and `impacted_modules`, with traversal depth-capped (`depth`, default 5) so a single-line edit doesn't fan out to thousands of nodes; an empty `impacted_tests` carries the same static-only `empty_caveat` (no test imports it statically, not that no test exercises it). Test detection uses pytest conventions (test_*.py, *_test.py, files under tests/) unless `test_filter` overrides with a recursive glob; a `test_filter` that matches no file in the graph is an error, not an empty `impacted_tests`, and ends with a `did you mean` when a directory is close. Files that resolve to no module are returned in `unresolved`, except a `.py` path that is missing inside the project, which is `deleted` with `deleted_reason` (the scan sees only the current tree, so its dependents are not selected). Internal modules only. `co_change=true` (blast mode only, opt-in) adds a `co_changed` list: modules that historically co-change with the edited set in git but have NO import/call edge to it, so the structural blast radius above misses them (the behavioral complement, `archy coupling` scoped to your edit - 'you changed X; historically Y changes with it, check Y'). Source-only and best-effort (empty without git); the only path that makes this tool read git history. (read-only)
- `archy_snapshot`: Capture score, cycles, and layer violations to .archy/baseline.json as a baseline that archy_diff will compare against. Call at the start of an editing session. Also returns `invariant_brief`: the constraints to know before your first edit (declared layers, forbidden inter-layer edges, whether the graph is acyclic, the baseline score per axis, and the top load-bearing / highest-risk modules). Read it up front to avoid proposing a cross-layer or cycle-introducing edit, rather than being told after the diff. See the `loop` prompt for full usage.
- `archy_diff`: Compare the current project state to the last snapshot. Returns a risk-weighted `summary` (headline + top regressions / improvements), per-component score deltas, and the cycles and layer violations that have been added or resolved since the baseline. Use after edits to localize regressions; see the `loop` prompt. `strict=True` with `baseline` (a committed file, relative to `path`) adds `strict`. `passed` is false when a cycle or layer violation is new, or when archy.yaml removes or narrows a rule the baseline fingerprint records. `reason` names it. A baseline with no fingerprint still checks cycles and violations. (read-only)
- `archy_simulate`: Counterfactual pre-edit check: given a proposed import-edge delta (`add` / `remove` lists of {from, to} module-or-path pairs), return the structural consequence BEFORE any file is written -- new/resolved cycles, new back-edges, new layer/SDP violations, per-axis score delta, and the propagation_cost change -- with a risk-ranked `summary` phrased conditionally ('would form a cycle'). Use it to test a refactoring hypothesis and reshape the plan before editing. Endpoints matching no internal module are returned in `applied.unresolved` with a `did you mean` in `applied.unresolved_hints`; a spec that could not be applied is listed in `applied.skipped`, and `applied.coverage` is `none` when no requested edge was simulated (the zero deltas then describe an unchanged graph, not a free edit) or `partial` when some were. Caveat: it models the graph delta you describe, not arbitrary code edits (it cannot move the complexity axis), and one submodule import (`a.b.c`) also implies edges to its ancestor packages -- include them in `add` to model it exactly (a lone submodule edge is a lower bound; see docs/research/SIMULATE_ORACLE_EMPIRICS.md). (read-only)
- `archy_graph`: Inspect the dependency graph. With no `focus`, `response_format='summary'` (the DEFAULT, replaces the removed archy_graph_summary) returns a compact top-N overview (modules by fan-in, fan-out, PageRank, and edit-risk, plus top external deps; `top_n` controls N) so a routine call doesn't dump the whole graph into context; `response_format='full'` returns the complete node/edge dump matching `archy graph --format json`, but refuses graphs larger than `max_nodes` (default 500, must be >= 1) with a GraphTooLargePayload (bump it explicitly, or narrow with `focus`). Pass `focus=[<qualname or path>]` (replaces the removed archy_graph_focus) for a bounded subgraph centered on those modules: `depth` caps hop distance and `direction` is 'in' (who depends on me), 'out' (my dependencies), or 'both'; each edge carries the source line numbers of the import statements. With `focus` set, `response_format`/`max_nodes`/`top_n` do not apply (the neighborhood is already bounded). (read-only)
- `archy_what_to_refactor_next`: Ranked refactor-priority list (replaces the removed archy_hotspots and archy_high_risk_modules via `lens`). `lens='fused'` (the DEFAULT) merges the behavioral lens (cyclomatic complexity x git churn) and the structural lens (the edit-risk composite: central and fragile) into one summed priority, so a module flagged by both generally outranks a single-lens one. `lens='behavioral'` ranks CC x churn hotspots only, those scoring at least 5% of the project maximum (needs git; answers 'where is the refactoring leverage?'); `lens='structural'` ranks the edit-risk composite only (git-free; answers 'is this edit dangerous?'). A structural-lens call reports git_available, cc_sum, churn, and hotspot_score as null (git history not consulted). Each entry says which lenses fired and carries a one-line `rationale`. `min_risk` (default 0.15) is the structural floor; pass 0 to surface every module on the structural lens. `since` restricts the behavioral (churn) lens to commits after a date (e.g. 2024-01-01, 2 weeks ago) or a git ref (tag/branch/SHA); a value that is neither is refused. An empty `priorities` with a `note` is a real answer: there is genuinely nothing to prioritize. (read-only)
- `archy_dsm`: Design Structure Matrix view of the import graph. `response_format='summary'` (the DEFAULT) returns a compact overview -- block structure (group labels + sizes), counts, the back-edges (source later than target in the ordering = the cycle signal), and inter-block coupling -- without the full cell list, so a routine call stays small. `response_format='full'` returns the full matrix the agent reads positionally: cell (row=source, col=target) is non-empty when source imports target; it refuses matrices with more than 2000 cells with a DSMTooLargePayload (narrow with `focus`/`package`, or read the summary). Use `group_by='community'` for block-diagonal cohesion, `group_by='layer'` for layer-violation forensics, or `group_by='topological'` to localize back-edges. Narrow large projects with `focus` (qualname + focus_depth-hop neighborhood) or `package` (qualname prefix). When `baseline_path` (relative to `path`) is provided, returns a DSMDiff regardless of response_format (`new_back_edges` flags cycles the edit just introduced). (read-only)
- `archy_duplicates`: Cluster functions with an identical normalized body shape (identifiers/literals folded to placeholders). Returns two tiers: `duplicates` (the primary 'likely duplicate' list to investigate) and `variants` (demoted clusters that are likely intentional: same-class siblings, boilerplate, copies wholly in test suites or vendoring/isolation dirs, and - with `co_change` (the DEFAULT) - `independent` copies whose files are actively maintained yet never co-change in git, i.e. deliberately parallel implementations; each carries a `variant_reason`). Within the primary tier, `exact=true` marks byte-identical (Type-1) clusters, the highest-confidence 'definitely refactor these' subset. `min_nodes` (default 30) is the minimum normalized AST-node count, skipping trivial getters/stubs. This is an advisory SURFACER, never a score axis: refactorability is a semantic call the reader (you) makes, so a cluster means 'investigate,' not 'provably identical' (the co-change demotion lifts primary precision above the ~50% syntactic ceiling by moving benign parallel copies to variants). `near_miss=true` (opt-in, slower) adds a `near_miss` tier: Type-3 (gapped) clones - a copy with statements inserted/removed that the exact shape-hash cannot see - found by token-multiset overlap, each with a `similarity`. LOWER confidence than the shape tiers; use it for recall (the exact hash finds ~0% of Type-3). `response_format='summary'` (the DEFAULT) returns each cluster's ranking fields plus one sample member; `response_format='full'` returns the complete member lists. `co_change=false` skips the git pass. An empty `duplicates` with a `note` is a real answer. (read-only)
- `archy_conventions`: **Call before adding a new class, field, or command to an unfamiliar project.** Derives the repository's own conventions from its source instead of leaving you to infer them by reading. Returns five censuses: `naming` (class-name suffix families GROUPED BY HOME MODULE, so the module you are about to edit shows its own patterns - the answer to 'what do I call a new one and where does it go'), `surfaces` (mirrored helper sets like `_x_to_text`/`_x_to_json` and names defined in several modules - the answer to 'how many places must I wire a new field'), `gates` (sites where a FAILED FINDING exits non-zero, each with its literal exit `code` and the lever that controls it: `flag:--strict`, `config:<attr>`, `param:<name>`, or `hardcoded` - the answer to 'should my new finding fail the build or only warn'), `errors` (the separate, usually much larger set of USER-ERROR exits - bad config, missing file - which say nothing about gating and are kept apart so the gate count stays meaningful), `models` (base-class, frozen, and tuple-vs-list census over the value types), `bases` (kind families grouped by what they derive from TRANSITIVELY, counting only bases this project defines - a family reached through an intermediate class is reported under the base that names it, and suffix agreement is stated so a family whose name is not the rule says so), `registries` (`NAME = Ctor(...)` families with the distribution of every keyword passed - how a project declares codes, messages, or flags when it does not use classes), `export_gaps` (family members absent from an `__all__`, or from a `from .x import Y as Y` block, that already lists their siblings) and `doc_gaps` (members the project's own `.rst`/`.md` surface does not name, where it already documents most of the family). Advisory only; it never fails and mutates nothing. `min_family` raises the floor for reporting a family (default 2, raise it on a large project to cut noise). `include_tests` censuses test modules too (default false: test fixtures dilute a real family). This report is RANKED and truncated, so absence from it proves nothing; for a negative (`does risk import hotspots`) call `archy_module_view` instead. (read-only)
- `archy_module_view`: **Call when the question is a NEGATIVE.** `archy_conventions` ranks and truncates, so a module's absence from it means nothing; every list here is COMPLETE for the one `module` named, so absence IS the answer, about STATIC edges only: an empty `imported_by` does not rule out importlib.import_module / __import__, entry points, plugin registries, INSTALLED_APPS, pytest plugins or config-driven dispatch, so `rg` for those before calling a module dead. Use it for `does risk import hotspots`, `does anything still reach layers`, `is this module dead`. Returns `imports_internal` (the project modules this one imports, with relative imports resolved), `imported_by` (every project module that imports it, tests included even when they are otherwise set aside, because a module imported only by tests IS imported), `classes`, `functions`, `exports` (null when the module declares no `__all__` and no explicit re-exports, which is different from an empty one), `suffix_families`, `gates` (its exit sites) and `status` - which says whether the module was censused or set aside and why, so an empty result is never mistaken for `nothing to report`. Raises on an unknown module name rather than returning an empty view. Advisory: mutates nothing. (read-only)
- `archy_brief`: **Call once, before starting on an unfamiliar repository.** Composes `archy_conventions` (naming, mirrored surfaces, gates, export and doc gaps), the layer `coverage` of `archy.yaml` and, with `contracts=True`, the transitive import-linter verdict, into one answer to 'what do I need to know before I touch this'. `top_n` (default 8) bounds the ranked sections and `conventions.totals` says how many were dropped; `gates`, `errors`, `export_gaps` and `doc_gaps` are never truncated. `coverage` is null when there is no usable archy.yaml; `coverage_error` carries the error when one parsed but its layer coverage failed validation (such as overlapping layer patterns), otherwise null; a config that does not parse is an error, as before. This tool does NOT run the direct-edge check, so `transitive_checked=false` with a `transitive_unverified_reason` means the `forbid` rules are unverified, not that they hold; pass `contracts=True` to settle it. It is ranked and truncated like `archy_conventions`, so for a negative call `archy_module_view`. Advisory: mutates nothing. (read-only)

## FAQ

### What does archy do?

It parses a Python project's imports and calls to answer questions about change reach, affected tests, dependency cycles, and adherence to declared architectural layers.

### How does archy handle architectural rules?

Users define their architectural facts, such as which module belongs to which layer and which directions are forbidden, in an archy.yaml file.

### Can archy be used in a CI/CD pipeline?

Yes, it runs as a CLI that can be used in CI to enforce layer governance and catch violations.
