A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Command-line interface for agent-context.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import argparse |
| 6 | import json |
| 7 | import sys |
| 8 | from pathlib import Path |
| 9 | from typing import Any, Sequence, TextIO |
| 10 | |
| 11 | from agent_context import __version__ |
| 12 | from agent_context.config import ConfigError, load_config |
| 13 | from agent_context.explain import explain_repository, format_repo_map |
| 14 | from agent_context.packer import ( |
| 15 | format_pack_summary, |
| 16 | pack_context, |
| 17 | write_context, |
| 18 | ) |
| 19 | from agent_context.scanner import find_repo_root, format_analysis, scan_repository |
| 20 | from agent_context.tokens import ( |
| 21 | estimate_tokens_from_file, |
| 22 | estimate_tokens_from_text, |
| 23 | format_int, |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | def build_parser() -> argparse.ArgumentParser: |
| 28 | parser = argparse.ArgumentParser( |
| 29 | prog="agent-context", |
| 30 | description=( |
| 31 | "Give your AI agent a map before it touches your code. " |
| 32 | "Local-first context packing - no API keys, no cloud, no embeddings." |
| 33 | ), |
| 34 | ) |
| 35 | parser.add_argument( |
| 36 | "--version", |
| 37 | action="version", |
| 38 | version=f"agent-context {__version__}", |
| 39 | ) |
| 40 | |
| 41 | sub = parser.add_subparsers(dest="command", required=True) |
| 42 | |
| 43 | # analyze |
| 44 | p_analyze = sub.add_parser("analyze", help="Analyze a repository") |
| 45 | p_analyze.add_argument( |
| 46 | "path", |
| 47 | nargs="?", |
| 48 | default=".", |
| 49 | help="Repository path (default: current directory)", |
| 50 | ) |
| 51 | p_analyze.add_argument("--json", action="store_true", help="Machine-readable JSON") |
| 52 | |
| 53 | # pack |
| 54 | p_pack = sub.add_parser("pack", help="Pack relevant context for a task") |
| 55 | p_pack.add_argument("task", help="Natural-language task description") |
| 56 | p_pack.add_argument( |
| 57 | "path", |
| 58 | nargs="?", |
| 59 | default=".", |
| 60 | help="Repository path (default: current directory)", |
| 61 | ) |
| 62 | p_pack.add_argument( |
| 63 | "--tokens", |
| 64 | type=int, |
| 65 | default=None, |
| 66 | help="Approximate token budget (default: 12000 or config)", |
| 67 | ) |
| 68 | p_pack.add_argument( |
| 69 | "-o", |
| 70 | "--output", |
| 71 | type=str, |
| 72 | default=None, |
| 73 | help="Output markdown path (default: .agent-context/context.md)", |
| 74 | ) |
| 75 | p_pack.add_argument( |
| 76 | "--stdout", |
| 77 | action="store_true", |
| 78 | help="Print context markdown to stdout instead of writing a file", |
| 79 | ) |
| 80 | p_pack.add_argument("--json", action="store_true", help="Machine-readable JSON") |
| 81 | p_pack.add_argument( |
| 82 | "--verbose", |
| 83 | "-v", |
| 84 | action="store_true", |
| 85 | help="Show explainable score signals", |
| 86 | ) |
| 87 | |
| 88 | # explain |
| 89 | p_explain = sub.add_parser("explain", help="Heuristic repository map") |
| 90 | p_explain.add_argument("path", nargs="?", default=".") |
| 91 | p_explain.add_argument("--json", action="store_true") |
| 92 | |
| 93 | # tokens |
| 94 | p_tokens = sub.add_parser("tokens", help="Estimate tokens for a file or stdin") |
| 95 | p_tokens.add_argument( |
| 96 | "file", |
| 97 | nargs="?", |
| 98 | default=None, |
| 99 | help="File path (omit to read stdin)", |
| 100 | ) |
| 101 | p_tokens.add_argument("--json", action="store_true") |
| 102 | |
| 103 | # mcp |
| 104 | p_mcp = sub.add_parser( |
| 105 | "mcp", |
| 106 | help="Run a read-only MCP server on stdio (optional integration)", |
| 107 | ) |
| 108 | p_mcp.add_argument( |
| 109 | "--cwd", |
| 110 | type=str, |
| 111 | default=None, |
| 112 | help="Working directory for repository operations", |
| 113 | ) |
| 114 | |
| 115 | return parser |
| 116 | |
| 117 | |
| 118 | def main(argv: Sequence[str] | None = None) -> int: |
| 119 | parser = build_parser() |
| 120 | args = parser.parse_args(list(argv) if argv is not None else None) |
| 121 | |
| 122 | try: |
| 123 | if args.command == "analyze": |
| 124 | return cmd_analyze(args) |
| 125 | if args.command == "pack": |
| 126 | return cmd_pack(args) |
| 127 | if args.command == "explain": |
| 128 | return cmd_explain(args) |
| 129 | if args.command == "tokens": |
| 130 | return cmd_tokens(args) |
| 131 | if args.command == "mcp": |
| 132 | return cmd_mcp(args) |
| 133 | except ConfigError as exc: |
| 134 | print(f"Error: {exc}", file=sys.stderr) |
| 135 | return 2 |
| 136 | except FileNotFoundError as exc: |
| 137 | print(f"Error: {exc}", file=sys.stderr) |
| 138 | return 2 |
| 139 | except ValueError as exc: |
| 140 | print(f"Error: {exc}", file=sys.stderr) |
| 141 | return 2 |
| 142 | except KeyboardInterrupt: |
| 143 | print("Interrupted.", file=sys.stderr) |
| 144 | return 130 |
| 145 | |
| 146 | parser.error(f"Unknown command: {args.command}") |
| 147 | return 2 |
| 148 | |
| 149 | |
| 150 | def _resolve_path(raw: str) -> Path: |
| 151 | path = Path(raw).expanduser() |
| 152 | if not path.exists(): |
| 153 | raise FileNotFoundError(f"Path not found: {raw}") |
| 154 | return find_repo_root(path) |
| 155 | |
| 156 | |
| 157 | def _emit_json(data: Any, stream: TextIO | None = None) -> None: |
| 158 | out = stream or sys.stdout |
| 159 | out.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n") |
| 160 | |
| 161 | |
| 162 | def cmd_analyze(args: argparse.Namespace) -> int: |
| 163 | root = _resolve_path(args.path) |
| 164 | config = load_config(root) |
| 165 | result = scan_repository(root, config=config) |
| 166 | |
| 167 | # Warnings to stderr always. |
| 168 | for w in result.warnings: |
| 169 | print(w, file=sys.stderr) |
| 170 | |
| 171 | if args.json: |
| 172 | _emit_json(result.to_dict()) |
| 173 | else: |
| 174 | sys.stdout.write(format_analysis(result)) |
| 175 | return 0 |
| 176 | |
| 177 | |
| 178 | def cmd_pack(args: argparse.Namespace) -> int: |
| 179 | root = _resolve_path(args.path) |
| 180 | config = load_config(root) |
| 181 | |
| 182 | if args.tokens is not None and args.tokens <= 0: |
| 183 | print("Error: --tokens must be a positive integer", file=sys.stderr) |
| 184 | return 2 |
| 185 | |
| 186 | result = pack_context( |
| 187 | root, |
| 188 | args.task, |
| 189 | config=config, |
| 190 | token_budget=args.tokens, |
| 191 | ) |
| 192 | |
| 193 | for w in result.warnings: |
| 194 | print(w, file=sys.stderr) |
| 195 | |
| 196 | output_path = Path(args.output) if args.output else None |
| 197 | |
| 198 | if args.stdout or (args.json and not args.output): |
| 199 | # JSON mode: summary JSON on stdout; markdown only if --stdout without --json |
| 200 | if args.json: |
| 201 | data = result.to_dict() |
| 202 | if args.stdout: |
| 203 | data["markdown"] = result.markdown |
| 204 | _emit_json(data) |
| 205 | if args.output: |
| 206 | write_context(result, output=output_path, stdout=False) |
| 207 | return 0 |
| 208 | |
| 209 | # Human markdown to stdout |
| 210 | sys.stdout.write(result.markdown) |
| 211 | if not result.markdown.endswith("\n"): |
| 212 | sys.stdout.write("\n") |
| 213 | return 0 |
| 214 | |
| 215 | written = write_context(result, output=output_path, stdout=False) |
| 216 | |
| 217 | if args.json: |
| 218 | data = result.to_dict() |
| 219 | data["output"] = str(written) if written else None |
| 220 | _emit_json(data) |
| 221 | else: |
| 222 | sys.stdout.write(format_pack_summary(result, verbose=args.verbose)) |
| 223 | return 0 |
| 224 | |
| 225 | |
| 226 | def cmd_explain(args: argparse.Namespace) -> int: |
| 227 | root = _resolve_path(args.path) |
| 228 | config = load_config(root) |
| 229 | repo_map = explain_repository(root, config=config) |
| 230 | if args.json: |
| 231 | _emit_json(repo_map.to_dict()) |
| 232 | else: |
| 233 | sys.stdout.write(format_repo_map(repo_map)) |
| 234 | return 0 |
| 235 | |
| 236 | |
| 237 | def cmd_tokens(args: argparse.Namespace) -> int: |
| 238 | if args.file: |
| 239 | path = Path(args.file).expanduser() |
| 240 | if not path.is_file(): |
| 241 | print(f"Error: not a file: {args.file}", file=sys.stderr) |
| 242 | return 2 |
| 243 | try: |
| 244 | text = path.read_text(encoding="utf-8", errors="replace") |
| 245 | except OSError as exc: |
| 246 | print(f"Error: cannot read {args.file}: {exc}", file=sys.stderr) |
| 247 | return 2 |
| 248 | chars = len(text) |
| 249 | tokens = estimate_tokens_from_text(text) |
| 250 | label = str(path) |
| 251 | else: |
| 252 | text = sys.stdin.read() |
| 253 | chars = len(text) |
| 254 | tokens = estimate_tokens_from_text(text) |
| 255 | label = "(stdin)" |
| 256 | |
| 257 | if args.json: |
| 258 | _emit_json( |
| 259 | { |
| 260 | "file": label, |
| 261 | "characters": chars, |
| 262 | "estimated_tokens": tokens, |
| 263 | "note": "Approximate estimate (characters ÷ 4). Not a real tokenizer.", |
| 264 | } |
| 265 | ) |
| 266 | else: |
| 267 | sys.stdout.write( |
| 268 | f"File:\n{label}\n\n" |
| 269 | f"Characters:\n{format_int(chars)}\n\n" |
| 270 | f"Estimated tokens:\n{format_int(tokens)}\n" |
| 271 | ) |
| 272 | return 0 |
| 273 | |
| 274 | |
| 275 | def cmd_mcp(args: argparse.Namespace) -> int: |
| 276 | from agent_context.mcp import run_mcp_server |
| 277 | |
| 278 | cwd = Path(args.cwd).resolve() if args.cwd else Path.cwd() |
| 279 | return run_mcp_server(cwd=cwd) |
| 280 | |
| 281 | |
| 282 | if __name__ == "__main__": |
| 283 | raise SystemExit(main()) |