Skip to main content
Glama

TIER

Layered context for AI coding agents: a 4-layer document and repository format, a code graph indexer, and a zero-dependency MCP server.

CI PyPI Python 3.10+ License: MIT


tier keeps an agent from loading whole repositories and documents into its context. Every document carries a small always-loadable index, one-line abstracts, structured bodies with symbol signatures and dependency edges, and exact source-line ranges it can fetch on demand. A hybrid retriever routes a question to the right section, an incremental repository map keeps fingerprints and line ranges current, and a reverse-dependency graph answers what an edit affects.

The core is pure Python standard library: dependencies = [], no network calls, no telemetry. It runs entirely offline on Python 3.10 and later. Optional extras add terminal styling, the official MCP SDK adapter, and Tree-sitter grammars.

Installation

Zero-clone installs, in order of least commitment:

uvx --from tier-ctx tier install     # run the installer once, leave nothing installed
uv tool install tier-ctx             # put `tier`, `tier-mcp`, and `tier-mcp-sdk` on PATH
pipx install tier-ctx                # the same, where pipx is preferred

Until the PyPI release is live, install from Git:

uv tool install git+https://github.com/000jd/tier
uv tool install "tier-ctx[all] @ git+https://github.com/000jd/tier"   # + rich UI, MCP SDK

From a checkout, inside a virtual environment:

git clone https://github.com/000jd/tier && cd tier
python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[all]"

The distribution is named tier-ctx; the import package and console scripts are tier, tier-mcp, and tier-mcp-sdk. The bare PyPI name tier belongs to an unrelated package.

Related MCP server: parecode

Example

An end-to-end session on a small project — install once, then one call per question:

$ tier install --clients claude-code --yes
Target: /home/me/myproject
Clients: claude-code
cache (.git/info/tier): /home/me/myproject/.git/info/tier/repo.tier (created)
Tokens: raw source 197 -> L0 130 (34.0% saved)
Instructions: /home/me/myproject/CLAUDE.md, /home/me/myproject/AGENTS.md

$ tier context . "how does the retry backoff work" --budget-tokens 800
## Context: how does the retry backoff work

@src-http-client.py src/http/client.py
? HTTP client with retry and backoff.; symbols: backoff_delay, request
|symbols[3]{kind,name,signature,lines}
function,backoff_delay,def backoff_delay(attempt: int) -> float,7-9
function,request,"def request(url: str, retries: int=DEFAULT_RETRIES)",12-19
function,_send,def _send(url: str),22-23
|calls[1]{caller,callee,module}
request,backoff_delay,.

@src-http-client.py#backoff_delay [L7-L9]
```python
def backoff_delay(attempt: int) -> float:
    """Exponential backoff, capped at 30 seconds."""
    return min(2 ** attempt, 30.0)
```

## Impact: @src-http-client.py#backoff_delay
Direct dependents: @src-api-client.py
Transitive dependents: @src-api-client.py
Symbol callers: src/http/client.py#request [12-19]

$ tier impact src/http/client.py#backoff_delay
Impact target: @src-http-client.py
Direct dependents: @src-api-client.py
Transitive dependents: @src-api-client.py
Dependencies: none
Transitive dependencies: none
Symbol: src/http/client.py#backoff_delay
Symbol callers: src/http/client.py#request [12-19]
Symbol calls: none

$ tier slice src/http/client.py backoff_delay
@src-http-client.py#backoff_delay [L7-L9]
```python
def backoff_delay(attempt: int) -> float:
    """Exponential backoff, capped at 30 seconds."""
    return min(2 ** attempt, 30.0)
```

How it works

TIER splits every document into four layers, and an agent reads only the ones it needs.

  • L0 — index. Document metadata, global rules, and one line per section carrying that section's token cost and rule count. Always loaded; a few hundred tokens.

  • L1 — abstracts. A one-line ? summary per section saying when to read it, folded into the L0 index.

  • L2 — bodies. Section contents; for codebases, a |symbols table with exact [start-end] line ranges and > edges to local dependencies.

  • L3 — slices. Exact source lines for one symbol, fetched by name.

tier_context collapses the whole loop into one call: resolve or build the repository index, route the query with the hybrid retriever, match symbol names, then pack L2 bodies, L3 slices, and a dependency summary until the token budget is spent. The granular commands remain available when you need a specific section id or symbol.

Architecture highlights

Header-once tables and indented key/value trees. A record set is a header plus exactly N CSV rows, and nested data is a two-space-indented tree. Both keep the schema and drop the repeated punctuation that JSON and Markdown tables spend tokens on.

Deterministic line-start sigils. Every line is classified by its first character: % header, @ section, ? abstract, ! rule, = key/value, | counted table, > reference, $ command. Fenced code, untrusted blocks, and table rows are opaque, so no sigil inside them is reinterpreted.

Untrusted content guards. Text from the outside world is wrapped in `<<<source #guard ...

guard`. The guards are chosen so that the payload cannot contain its own terminator, which makes embedded instructions, fake headers, and rule sigils inert data.

Stateful session deduplication. A section or source slice already delivered in the conversation is replaced by a one-line stub on the next request. sync evicts exactly the sections whose files changed, and their slices.

Symbol-level blast radius. Repository maps record > edges between modules and a |calls table of caller/callee pairs. tier impact reports file-level importers and, given module#symbol, the exact functions that call it. tier_context filters |calls tables to the 1-hop neighbourhood of the sections it returns; pass include_calls="all" to see every edge.

Invisible repository cache. The map is a derived artifact, so it lives in .git/info/tier/repo.tier inside a worktree (which Git ignores) or in a user cache directory outside it. .git is followed when it is a pointer file rather than a directory, so linked worktrees and submodules resolve to their own git directory. A tracked repo.tier is still honoured when one exists. Nothing is written into your working tree, so git status stays clean.

Hybrid search with precomputed IDF. BM25-style term scoring over split identifiers, a compact synonym map, character 3-gram fallback for typos, and navigation priors. Document frequencies are computed once per query, which keeps a search over 800 sections near 200 ms with no index to build.

Performance

Measured with the o200k_base tokenizer. These are token counts and retrieval hit rates, not LLM answer accuracy. Methodology and reproduction steps are in benchmarks/README.md.

Workload

Measure

Result

Repository overview

raw source → full map → L0 → L0 + one module

72,859 → 14,375 → 828 → 1,784 tokens (−98%)

End-to-end 4-layer workflow

index, find, L2, L3 slices, impact + sync

5,003 tokens (−93.1%), 3/3 exact slices

36-file polyglot repository

surgical L0 + target L2 + 7 slices

3,008 vs 8,249 tokens (−64%), 116/116 symbols

197-section blind retrieval

15 queries

15/15 hit@1, mean top-1 fetch 134 tokens

benchmarks/BENCH.txt carries the full Track A–I breakdown, including the record-encoding and nested-config tracks, the per-query retrieval logs, and the raw output behind every row above.

Supported clients

tier install configures 25 agent clients across JSON, TOML, YAML, and SKILL.md schemas. It backs up every file it touches, merges instead of overwriting, supports --dry-run and --uninstall, and validates the result with tier doctor.

Client

Scope

Config

Claude Code

project / user

.mcp.json + .claude/settings.json, ~/.claude.json

Claude Desktop

user

claude_desktop_config.json

Command Code

project / user

.commandcode/mcp.json, ~/.commandcode/mcp.json

OpenCode

project / global

opencode.json, ~/.config/opencode/opencode.json

OpenAI Codex CLI

project / user

.codex/config.toml, ~/.codex/config.toml

Gemini CLI

project / user

.gemini/settings.json + GEMINI.md

Cursor

project / global

.cursor/mcp.json, ~/.cursor/mcp.json

VS Code Copilot

project

.vscode/mcp.json

Windsurf

user

~/.codeium/windsurf/mcp_config.json

Roo Code / Cline

project

.roo/mcp.json

Trae

project

.trae/mcp.json

JetBrains Junie

project / user

.junie/mcp/mcp.json, ~/.junie/mcp/mcp.json

Kiro

project

.kiro/settings/mcp.json

Warp

user

~/.warp/.mcp.json

Zed

user

~/.config/zed/settings.json (context_servers)

Continue.dev

project

.continue/mcpServers/tier.yaml

Agent Skills

project / user

.agents/skills/tier/SKILL.md

Any other client can be configured with --custom-config PATH --schema NAME, and tier config-snippet prints ready-to-copy JSON, TOML, YAML, and SKILL.md snippets plus native CLI one-liners.

uv tool install "tier-ctx[ui] @ git+https://github.com/000jd/tier"          # rich terminal UI
uv tool install "tier-ctx[mcp] @ git+https://github.com/000jd/tier"         # official MCP SDK
uv tool install "tier-ctx[treesitter] @ git+https://github.com/000jd/tier"  # multi-language AST
uv tool install "tier-ctx[all] @ git+https://github.com/000jd/tier"
  • [ui] adds rich rendering for tier install and tier doctor.

  • [mcp] adds the official SDK adapter (tier-mcp-sdk), Streamable HTTP, and MCP Inspector.

  • [treesitter] adds Tree-sitter grammars for TypeScript, JavaScript, Go, Rust, C, C++, Java, and Ruby. Without it the stdlib extractors are used, and repository maps are byte-identical.

Documentation

Limits

Only token counts, retrieval identifiers, and exact-slice coverage are measured — not LLM answer accuracy. Claude's tokenizer is not public, so counts use OpenAI o200k via a persistent Node worker when available, and a characters/4 estimate otherwise. tier hook treats its token budget as a contract: it skips a payload only when it is provably within budget, otherwise it counts exactly and verifies the output. tier sync trusts recorded mtime and size as a cache; use tier sync --rehash after tooling that restores timestamps. JS/TS/Go/Rust symbol extraction is heuristic without the [treesitter] extra.

License

MIT © 2026 000jd. See LICENSE.

Available Tools

12 tools
tier_contextA

PRIMARY ENTRY POINT: answer a question about a codebase or document in ONE call. Resolves (and auto-builds/syncs) the repository index, routes with hybrid search, matches symbol names, then packs L2 section bodies, L3 source slices, and a dependency summary until budget_tokens is reached. Use this first; fall back to the granular tier_* tools only when you need a specific section id, symbol, or lint check.

Inputs: query (required), path, budget_tokens, include_calls, +1 more.

tier_findC

Hybrid search over a doc: identifier splitting, synonyms, and character n-gram fallback. Returns best-matching section ids with scores.

Inputs: path (required), query (required), k.

tier_getA

Fetch one or more sections by id. Set follow=true to also pull sections they reference. Sections already returned earlier in this session are replaced by a one-line stub; set force=true to resend them, or reset=true to clear the session cache for this doc first. table_format=anchored renders tables with row anchors and column labels for better field retrieval.

Inputs: ids (required), path (required), force, reset, +2 more.

tier_impactB

Analyze direct/transitive dependents and dependencies for a section or symbol. With git=true, includes changed modules, changed symbols, and downstream blast radius.

Inputs: path (required), target (required), git.

tier_indexA

Get a doc's summary, global rules, and section index (id, token cost, rule count, abstract). Read this BEFORE fetching sections; then fetch only what you need with tier_get.

Inputs: path (required).

tier_ingestA

Compress raw Markdown, JSON, or command/log output into TIER on the fly. Auto-detects the format. Returns the full TIER document, its L0 index, or a budgeted view with only priority sections. Use max_tokens to cap context; save_as persists the full artifact.

Inputs: content (required), format, save_as, index_only, +1 more.

tier_lintC

Validate a TIER doc (table row counts, dangling refs, duplicate ids).

Inputs: path (required).

tier_listA

List available TIER docs with a one-line summary each. Call first to discover docs.

Inputs: no named parameters.

tier_rememberC

Persist verified agent memory into a .tier file. Actions: rule (global rule), section (upsert a section with abstract/body), append-rule, append-kv, or append-ref. The write is lint-checked and atomic; the section is invalidated in the session cache.

Inputs: path (required), action (required), key, body, +7 more.

tier_repoA

Index a repository directory into a layered TIER architecture map. Each module section contains exported symbol signatures with line ranges and '>' edges to local dependencies. Use index_only=true for just the L0 map.

Inputs: path, index_only.

tier_sliceA

Fetch exact L3 source lines for one or more symbols recorded in a repo.tier symbol table. Returns @module#symbol [Lstart-Lend] plus a fenced source slice. Already-served slices are stubbed unless force=true.

Inputs: path (required), module (required), symbols (required), force, +1 more.

tier_syncB

Incrementally refresh a repo.tier from disk: re-parse only changed or added files, remove deleted modules, and invalidate changed sections and L3 slices in the session cache. Set rehash=true to compare content hashes instead of trusting recorded mtime+size.

Inputs: path (required), rehash.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 12 tools

    Disambiguation4/5

    Most tools target distinct operations (find, get, slice, impact, sync, lint, ingest, repo, remember), and the description of tier_context explicitly establishes a primary/granular hierarchy that reduces selection risk. The only mild overlaps are tier_list vs tier_index (doc discovery vs per-doc index) and tier_context vs the find/get/slice chain, but descriptions disambiguate these adequately.

    Naming Consistency4/5

    All 12 tools share a uniform 'tier_' namespace prefix with short single-word suffixes, which is highly predictable. Minor inconsistency: some suffixes are verbs (list, find, get, sync, lint, ingest) while others are nouns or noun-like (context, index, slice, impact, repo), though each remains readable.

    Tool Count5/5

    Twelve tools sit in the sweet spot and each maps to a real function of the system: discovery, indexing, retrieval, search, dependency analysis, sync, validation, ingestion, and memory persistence. Nothing appears redundant or bolted on.

    Completeness4/5

    The surface covers the full lifecycle: discover, index/sync, search, fetch, slice source, analyze impact, lint, ingest, and write memory. Minor gaps remain — there is no delete/prune operation for stale docs, sections, or symbols, and no export/round-trip back to Markdown, which agents may need to work around.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      C
      quality
      A
      maintenance
      An MCP server that provides structural codebase indexing and surgical query tools to drastically reduce token usage through symbol-level searches and transitive impact analysis. It supports multiple languages and integrates with git to help AI agents understand code dependencies and the impact of changes in sub-millisecond time.
      72
      660 PyPI
      1,229
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      An MCP server giving coding agents context-window-aware code search and safe, atomic multi-file edits — built to cut token usage on large codebases without sacrificing correctness.
      3
      56 npm
      6
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Serves structured code context via MCP, enabling AI agents to understand codebases with dependency graphs and significantly reduce token usage.
      16 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server that indexes codebases into a local graph and provides on-demand context retrieval for AI coding agents, reducing token usage by tracking session history and delivering only relevant code subgraphs.
      10 npm
      MIT