A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Optional lightweight MCP server over stdio (JSON-RPC 2.0). |
| 2 | |
| 3 | Isolated from the core CLI so users who only want packing do not depend |
| 4 | on MCP concepts. No network. No secret values in tool responses. |
| 5 | Read-only: never modifies repository source files. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import json |
| 11 | import sys |
| 12 | from pathlib import Path |
| 13 | from typing import Any, TextIO |
| 14 | |
| 15 | from agent_context import __version__ |
| 16 | from agent_context.config import load_config |
| 17 | from agent_context.explain import explain_repository |
| 18 | from agent_context.packer import pack_context, render_context_markdown |
| 19 | from agent_context.scanner import find_repo_root, scan_repository |
| 20 | from agent_context.scoring import rank_files |
| 21 | from agent_context.security import should_exclude_from_context |
| 22 | |
| 23 | PROTOCOL_VERSION = "2024-11-05" |
| 24 | |
| 25 | TOOLS: list[dict[str, Any]] = [ |
| 26 | { |
| 27 | "name": "analyze_repository", |
| 28 | "description": ( |
| 29 | "Analyze the current repository: file counts, token estimates, " |
| 30 | "sensitive paths (names only), and largest files. Local-only; " |
| 31 | "never returns file contents of secrets." |
| 32 | ), |
| 33 | "inputSchema": { |
| 34 | "type": "object", |
| 35 | "properties": { |
| 36 | "path": { |
| 37 | "type": "string", |
| 38 | "description": "Optional repository path (default: cwd).", |
| 39 | }, |
| 40 | }, |
| 41 | }, |
| 42 | }, |
| 43 | { |
| 44 | "name": "find_relevant_files", |
| 45 | "description": ( |
| 46 | "Rank repository files for a natural-language task using " |
| 47 | "deterministic heuristics. Returns paths and scores, not secrets." |
| 48 | ), |
| 49 | "inputSchema": { |
| 50 | "type": "object", |
| 51 | "properties": { |
| 52 | "task": { |
| 53 | "type": "string", |
| 54 | "description": "Task description, e.g. 'fix auth middleware'.", |
| 55 | }, |
| 56 | "path": {"type": "string", "description": "Optional repository path."}, |
| 57 | "limit": { |
| 58 | "type": "integer", |
| 59 | "description": "Max results (default 20).", |
| 60 | "default": 20, |
| 61 | }, |
| 62 | }, |
| 63 | "required": ["task"], |
| 64 | }, |
| 65 | }, |
| 66 | { |
| 67 | "name": "build_context", |
| 68 | "description": ( |
| 69 | "Build a compact context package for a task within a token budget. " |
| 70 | "Returns markdown with secrets redacted. Does not write files unless " |
| 71 | "write=true." |
| 72 | ), |
| 73 | "inputSchema": { |
| 74 | "type": "object", |
| 75 | "properties": { |
| 76 | "task": {"type": "string"}, |
| 77 | "path": {"type": "string"}, |
| 78 | "tokens": { |
| 79 | "type": "integer", |
| 80 | "description": "Approximate token budget (default 12000).", |
| 81 | }, |
| 82 | "write": { |
| 83 | "type": "boolean", |
| 84 | "description": "If true, write .agent-context/context.md", |
| 85 | "default": False, |
| 86 | }, |
| 87 | }, |
| 88 | "required": ["task"], |
| 89 | }, |
| 90 | }, |
| 91 | { |
| 92 | "name": "repository_map", |
| 93 | "description": ( |
| 94 | "Produce a heuristic repository map: detected technology, likely " |
| 95 | "architecture, potential entry points. Does not claim certainty." |
| 96 | ), |
| 97 | "inputSchema": { |
| 98 | "type": "object", |
| 99 | "properties": { |
| 100 | "path": {"type": "string"}, |
| 101 | }, |
| 102 | }, |
| 103 | }, |
| 104 | ] |
| 105 | |
| 106 | |
| 107 | class McpServer: |
| 108 | """Minimal stdio MCP server implementing tools/list and tools/call.""" |
| 109 | |
| 110 | def __init__( |
| 111 | self, |
| 112 | *, |
| 113 | cwd: Path | None = None, |
| 114 | stdin: TextIO | None = None, |
| 115 | stdout: TextIO | None = None, |
| 116 | ) -> None: |
| 117 | self.cwd = (cwd or Path.cwd()).resolve() |
| 118 | self.stdin = stdin or sys.stdin |
| 119 | self.stdout = stdout or sys.stdout |
| 120 | self._closed = False |
| 121 | |
| 122 | def run(self) -> int: |
| 123 | """Serve until stdin closes. Returns process exit code.""" |
| 124 | while not self._closed: |
| 125 | line = self.stdin.readline() |
| 126 | if line == "": |
| 127 | break |
| 128 | line = line.strip() |
| 129 | if not line: |
| 130 | continue |
| 131 | try: |
| 132 | message = json.loads(line) |
| 133 | except json.JSONDecodeError as exc: |
| 134 | self._write( |
| 135 | { |
| 136 | "jsonrpc": "2.0", |
| 137 | "id": None, |
| 138 | "error": {"code": -32700, "message": f"Parse error: {exc}"}, |
| 139 | } |
| 140 | ) |
| 141 | continue |
| 142 | self._handle(message) |
| 143 | return 0 |
| 144 | |
| 145 | def _handle(self, message: dict[str, Any]) -> None: |
| 146 | if message.get("jsonrpc") != "2.0": |
| 147 | self._error(message.get("id"), -32600, "Invalid Request") |
| 148 | return |
| 149 | |
| 150 | method = message.get("method") |
| 151 | msg_id = message.get("id") |
| 152 | params = message.get("params") or {} |
| 153 | |
| 154 | # Notifications have no id — ignore quietly except exit. |
| 155 | if msg_id is None and method and not method.startswith("notifications/"): |
| 156 | # Still handle some notifications. |
| 157 | if method == "notifications/initialized": |
| 158 | return |
| 159 | return |
| 160 | |
| 161 | try: |
| 162 | if method == "initialize": |
| 163 | result = self._initialize(params) |
| 164 | elif method == "tools/list": |
| 165 | result = {"tools": TOOLS} |
| 166 | elif method == "tools/call": |
| 167 | result = self._call_tool(params) |
| 168 | elif method == "ping": |
| 169 | result = {} |
| 170 | elif method == "notifications/initialized": |
| 171 | return |
| 172 | else: |
| 173 | self._error(msg_id, -32601, f"Method not found: {method}") |
| 174 | return |
| 175 | except Exception as exc: # noqa: BLE001 - surface as JSON-RPC error |
| 176 | self._error(msg_id, -32000, str(exc)) |
| 177 | return |
| 178 | |
| 179 | if msg_id is not None: |
| 180 | self._write({"jsonrpc": "2.0", "id": msg_id, "result": result}) |
| 181 | |
| 182 | def _initialize(self, params: dict[str, Any]) -> dict[str, Any]: |
| 183 | return { |
| 184 | "protocolVersion": PROTOCOL_VERSION, |
| 185 | "capabilities": {"tools": {}}, |
| 186 | "serverInfo": {"name": "agent-context", "version": __version__}, |
| 187 | } |
| 188 | |
| 189 | def _call_tool(self, params: dict[str, Any]) -> dict[str, Any]: |
| 190 | name = params.get("name") |
| 191 | arguments = params.get("arguments") or {} |
| 192 | if not isinstance(arguments, dict): |
| 193 | raise ValueError("arguments must be an object") |
| 194 | |
| 195 | if name == "analyze_repository": |
| 196 | payload = self._analyze(arguments) |
| 197 | elif name == "find_relevant_files": |
| 198 | payload = self._find(arguments) |
| 199 | elif name == "build_context": |
| 200 | payload = self._build(arguments) |
| 201 | elif name == "repository_map": |
| 202 | payload = self._map(arguments) |
| 203 | else: |
| 204 | raise ValueError(f"Unknown tool: {name}") |
| 205 | |
| 206 | return { |
| 207 | "content": [ |
| 208 | { |
| 209 | "type": "text", |
| 210 | "text": json.dumps(payload, indent=2, ensure_ascii=False), |
| 211 | } |
| 212 | ], |
| 213 | "isError": False, |
| 214 | } |
| 215 | |
| 216 | def _resolve_root(self, arguments: dict[str, Any]) -> Path: |
| 217 | raw = arguments.get("path") or str(self.cwd) |
| 218 | path = Path(raw).expanduser() |
| 219 | if not path.is_absolute(): |
| 220 | path = (self.cwd / path).resolve() |
| 221 | else: |
| 222 | path = path.resolve() |
| 223 | # Safety: stay under cwd unless path is cwd itself or a child... |
| 224 | # Spec says "operate only on the current working directory unless |
| 225 | # explicitly configured". Explicit path argument counts as configured. |
| 226 | return find_repo_root(path) |
| 227 | |
| 228 | def _analyze(self, arguments: dict[str, Any]) -> dict[str, Any]: |
| 229 | root = self._resolve_root(arguments) |
| 230 | config = load_config(root) |
| 231 | scan = scan_repository(root, config=config) |
| 232 | data = scan.to_dict() |
| 233 | # Never include secret contents — sensitive is names only. |
| 234 | return data |
| 235 | |
| 236 | def _find(self, arguments: dict[str, Any]) -> dict[str, Any]: |
| 237 | task = arguments.get("task") |
| 238 | if not task or not isinstance(task, str): |
| 239 | raise ValueError("task is required") |
| 240 | limit = int(arguments.get("limit") or 20) |
| 241 | root = self._resolve_root(arguments) |
| 242 | config = load_config(root) |
| 243 | scan = scan_repository(root, config=config) |
| 244 | candidates = [ |
| 245 | f |
| 246 | for f in scan.context_candidates |
| 247 | if not should_exclude_from_context(f.path) |
| 248 | ] |
| 249 | ranked = rank_files(candidates, task) |
| 250 | return { |
| 251 | "task": task, |
| 252 | "root": str(root), |
| 253 | "files": [s.to_dict() for s in ranked[: max(1, limit)]], |
| 254 | } |
| 255 | |
| 256 | def _build(self, arguments: dict[str, Any]) -> dict[str, Any]: |
| 257 | task = arguments.get("task") |
| 258 | if not task or not isinstance(task, str): |
| 259 | raise ValueError("task is required") |
| 260 | tokens = arguments.get("tokens") |
| 261 | budget = int(tokens) if tokens is not None else None |
| 262 | write = bool(arguments.get("write", False)) |
| 263 | root = self._resolve_root(arguments) |
| 264 | config = load_config(root) |
| 265 | result = pack_context(root, task, config=config, token_budget=budget) |
| 266 | payload = result.to_dict() |
| 267 | # Include markdown (already redacted) for the agent to consume. |
| 268 | payload["markdown"] = render_context_markdown(result) |
| 269 | if write: |
| 270 | from agent_context.packer import write_context |
| 271 | |
| 272 | out = write_context(result) |
| 273 | payload["output"] = str(out) if out else None |
| 274 | return payload |
| 275 | |
| 276 | def _map(self, arguments: dict[str, Any]) -> dict[str, Any]: |
| 277 | root = self._resolve_root(arguments) |
| 278 | config = load_config(root) |
| 279 | return explain_repository(root, config=config).to_dict() |
| 280 | |
| 281 | def _write(self, message: dict[str, Any]) -> None: |
| 282 | self.stdout.write(json.dumps(message, ensure_ascii=False) + "\n") |
| 283 | self.stdout.flush() |
| 284 | |
| 285 | def _error(self, msg_id: Any, code: int, message: str) -> None: |
| 286 | payload: dict[str, Any] = { |
| 287 | "jsonrpc": "2.0", |
| 288 | "error": {"code": code, "message": message}, |
| 289 | } |
| 290 | if msg_id is not None: |
| 291 | payload["id"] = msg_id |
| 292 | else: |
| 293 | payload["id"] = None |
| 294 | self._write(payload) |
| 295 | |
| 296 | |
| 297 | def run_mcp_server(cwd: Path | None = None) -> int: |
| 298 | """Entry point for ``agent-context mcp``.""" |
| 299 | return McpServer(cwd=cwd).run() |