codenav-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """codenav: MCP server exposing ty's language-server features as MCP tools."""
codenav_mcp/server.py ADDED
@@ -0,0 +1,906 @@
1
+ """codenav: MCP server exposing ty's language-server features (hover,
2
+ definition, references, workspace symbol search, diagnostics) as MCP tools.
3
+
4
+ Named "codenav" (not "ty") since ty is Astral's name for the underlying
5
+ type checker/language server this wraps — the MCP server itself is a
6
+ thin tool built on top of it.
7
+
8
+ Built specifically for ty rather than as a generic LSP bridge: see
9
+ docs/agent-tooling.md for why (mcp-language-server's name-based
10
+ definition/references tools don't resolve symbols against ty, even though
11
+ ty's own workspace/symbol implementation answers those same queries
12
+ correctly when asked directly over LSP).
13
+
14
+ Run standalone for manual testing:
15
+ uv run python -m codenav_mcp.server
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import ast
21
+ import asyncio
22
+ import logging
23
+ import re
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import mcp_nav_shared
29
+ from mcp.server.mcpserver import Context, MCPServer
30
+ from mcp_nav_shared.errors import TOOL_ERRORS, ToolInputError, format_tool_error
31
+ from mcp_nav_shared.exclude import is_excluded
32
+ from mcp_nav_shared.format import (
33
+ filter_symbols_by_kind_and_path,
34
+ format_callers,
35
+ format_diagnostics,
36
+ format_location,
37
+ format_outline,
38
+ format_references,
39
+ format_references_grouped,
40
+ format_workspace_symbols,
41
+ parse_kind_filter,
42
+ symbol_kind_label,
43
+ to_symbol_tree,
44
+ uri_to_path,
45
+ uri_to_relative,
46
+ )
47
+ from mcp_nav_shared.lsp_client import LspClient, LspRequestError
48
+ from mcp_nav_shared.notices import NoticeBoard, package_source_dirs
49
+ from mcp_nav_shared.params import resolve_name_query
50
+ from mcp_nav_shared.resolve import resolve_symbol
51
+ from mcp_nav_shared.workspace import WorkspaceSelector, resolve_extra_source_roots, resolve_source_root
52
+
53
+ import codenav_mcp
54
+ from codenav_mcp.ty_command import resolve_ty_command
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+ # Which checkout/worktree to navigate is decided per request (see
60
+ # `WorkspaceSelector`): the host starts this process once, usually from the
61
+ # main checkout, even when the session works in a linked worktree.
62
+ _selector = WorkspaceSelector("CODENAV_MCP_WORKSPACE")
63
+ WORKSPACE_ROOT = _selector.base
64
+ _workspace_source = _selector.base_source
65
+ # Root for import-path derivation and implementations' workspace-wide class
66
+ # scan. Defaults to the whole workspace; set CODENAV_MCP_SOURCE_ROOT (e.g. to
67
+ # "src") in a project's MCP config to scope/speed up the scan.
68
+ SOURCE_ROOT = resolve_source_root("CODENAV_MCP_SOURCE_ROOT", WORKSPACE_ROOT)
69
+ # Extra directories `implementations` also scans (e.g. "tests", for test
70
+ # doubles of a port); their matches are listed under a separate heading.
71
+ EXTRA_SOURCE_ROOTS = resolve_extra_source_roots("CODENAV_MCP_EXTRA_SOURCE_ROOTS", WORKSPACE_ROOT)
72
+
73
+ _POSITION_NOTE = (
74
+ "Positions are 1-indexed. `column` is a UTF-16 character offset on the "
75
+ "line (not a visual/display column): a leading tab counts as one "
76
+ "character, so after a single tab the next character starts at column 2."
77
+ )
78
+
79
+ mcp = MCPServer(
80
+ name="codenav",
81
+ instructions=(
82
+ "Code navigation for this Python codebase, backed by ty (Astral's type "
83
+ "checker/language server). Prefer this over grepping for symbol "
84
+ "definitions/usages: it resolves through type inference (imports, "
85
+ "dependency-injected parameters, dataclass fields, etc.), not just text "
86
+ "matching. Python files only (.py/.pyi) — other extensions are rejected. "
87
+ "Start with symbol_info (what is X, where is it used) or outline (what's "
88
+ "in this file) rather than chaining search_symbol → hover → definition → "
89
+ "references by hand; drop to the position tools (hover/definition/"
90
+ "references) once you have a specific line to inspect. " + _POSITION_NOTE
91
+ ),
92
+ )
93
+
94
+ _PYTHON_EXTENSIONS = {".py", ".pyi"}
95
+ # ty reads these once at startup; a change restarts it (see `LspClient.config_names`).
96
+ _TY_CONFIG_NAMES = frozenset({"pyproject.toml", "ty.toml", ".ty.toml"})
97
+
98
+ _notices = NoticeBoard("codenav", package_source_dirs(mcp_nav_shared, codenav_mcp))
99
+
100
+ _client: LspClient | None = None
101
+ _client_lock = asyncio.Lock()
102
+
103
+
104
+ _workspace_lock = asyncio.Lock()
105
+
106
+
107
+ async def _configure_workspace(root: Path, source: str) -> None:
108
+ """Re-target the server at `root`: the language server, probe verdicts and
109
+ every path derived from the old root belong to the previous tree."""
110
+ global WORKSPACE_ROOT, SOURCE_ROOT, EXTRA_SOURCE_ROOTS, _client, _workspace_source, _probe_cache_signature
111
+ if _client is not None:
112
+ try:
113
+ await _client.stop()
114
+ except Exception:
115
+ logger.debug("failed to stop ty server on workspace switch", exc_info=True)
116
+ _client = None
117
+ WORKSPACE_ROOT = root
118
+ SOURCE_ROOT = resolve_source_root("CODENAV_MCP_SOURCE_ROOT", root)
119
+ EXTRA_SOURCE_ROOTS = resolve_extra_source_roots("CODENAV_MCP_EXTRA_SOURCE_ROOTS", root)
120
+ _workspace_source = source
121
+ _probe_cache.clear()
122
+ _probe_cache_signature = ()
123
+ logger.info("workspace: %s (%s)", root, source)
124
+
125
+
126
+ async def _use_workspace(ctx: Context | None) -> None:
127
+ """Called first by every tool. `ctx` is None only when a tool is invoked
128
+ directly (tests), in which case the current workspace stays as is."""
129
+ if ctx is None:
130
+ return
131
+ async with _workspace_lock:
132
+ selection = await _selector.select(ctx.session)
133
+ if selection.root != WORKSPACE_ROOT:
134
+ await _configure_workspace(selection.root, selection.source)
135
+
136
+
137
+ def _check_python_file(file_path: str) -> None:
138
+ """ty only understands Python; without this, asking it to type-check or
139
+ navigate a non-Python file (e.g. diagnostics on a README) silently
140
+ mis-parses the file as Python instead of failing clearly."""
141
+ suffix = Path(file_path).suffix.lower()
142
+ if suffix not in _PYTHON_EXTENSIONS:
143
+ raise ToolInputError(f"codenav only supports Python files (.py/.pyi), got {file_path!r}")
144
+
145
+
146
+ async def _after_ty_restart(_client: LspClient) -> None:
147
+ """Probe verdicts were computed under the old project config."""
148
+ global _probe_cache_signature
149
+ _probe_cache.clear()
150
+ _probe_cache_signature = ()
151
+
152
+
153
+ async def get_client() -> LspClient:
154
+ global _client
155
+ async with _client_lock:
156
+ if _client is None or not _client.is_alive:
157
+ if _client is not None:
158
+ try:
159
+ await _client.stop() # reap the dead server instead of leaking it
160
+ except Exception:
161
+ logger.debug("failed to stop stale ty server", exc_info=True)
162
+ _client = LspClient(
163
+ workspace_root=WORKSPACE_ROOT,
164
+ command=resolve_ty_command(WORKSPACE_ROOT),
165
+ language_id="python",
166
+ watch_suffixes=frozenset(_PYTHON_EXTENSIONS),
167
+ config_names=_TY_CONFIG_NAMES,
168
+ on_restart=_after_ty_restart,
169
+ on_notice=_notices.post,
170
+ )
171
+ await _client.start()
172
+ await _after_ty_restart(_client) # verdicts from a previous server are suspect too
173
+ # Tell ty about anything created/edited/deleted on disk since the last call.
174
+ await _client.refresh()
175
+ return _client
176
+
177
+
178
+ # ty's hover on a variable/parameter is just its type ("AppServices", "list[str] | None").
179
+ # Two words in a row ("Return the value") is prose, not a type expression.
180
+ _BARE_TYPE_RE = re.compile(r"(?!.*\w\s+\w)[A-Za-z_][\w.\[\], |]*")
181
+ _MAX_TYPE_LOCATIONS = 3
182
+
183
+
184
+ def _describe_type_definition(loc: dict[str, Any], workspace_root: Path) -> str:
185
+ """Where a type is defined, its header line, and the first line of its docstring."""
186
+ uri = loc.get("uri") or loc.get("targetUri", "")
187
+ rng = loc.get("range") or loc.get("targetSelectionRange") or {}
188
+ line0 = rng.get("start", {}).get("line", 0)
189
+ start_col = rng.get("start", {}).get("character", 0)
190
+ described = [f"Type defined at {uri_to_relative(uri, workspace_root)}:{line0 + 1}:{start_col + 1}"]
191
+ try:
192
+ source = uri_to_path(uri).read_text(encoding="utf-8")
193
+ header = source.splitlines()[line0].strip()
194
+ tree = ast.parse(source)
195
+ except (OSError, UnicodeDecodeError, SyntaxError, IndexError):
196
+ return "\n".join(described)
197
+ described.append(f" {header}")
198
+ for node in ast.walk(tree):
199
+ if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and node.lineno == line0 + 1:
200
+ doc = ast.get_docstring(node)
201
+ if doc:
202
+ described.append(f' """{doc.splitlines()[0]}"""')
203
+ break
204
+ return "\n".join(described)
205
+
206
+
207
+ async def _enrich_bare_type(text: str, client: LspClient, file_path: str, line: int, column: int) -> str:
208
+ """A bare type name says nothing about where the type lives; add its definition."""
209
+ if "\n" in text or len(text) > 120 or not _BARE_TYPE_RE.fullmatch(text):
210
+ return text
211
+ try:
212
+ locations = await client.type_definition(file_path, line, column)
213
+ except LspRequestError:
214
+ return text # the hover itself is still good; the extra is optional
215
+ described = [
216
+ _describe_type_definition(loc, WORKSPACE_ROOT)
217
+ for loc in locations[:_MAX_TYPE_LOCATIONS]
218
+ if not _is_builtins_stub(loc)
219
+ ]
220
+ if not described:
221
+ return text
222
+ return "\n".join([text, *described])
223
+
224
+
225
+ def _is_builtins_stub(loc: dict[str, Any]) -> bool:
226
+ """`str`/`int`/`list` point into typeshed; that is noise on every plain variable."""
227
+ return uri_to_path(loc.get("uri") or loc.get("targetUri", "")).name == "builtins.pyi"
228
+
229
+
230
+ def _format_hover_contents(contents: Any) -> str:
231
+ if not contents:
232
+ return ""
233
+ if isinstance(contents, dict):
234
+ return contents.get("value", str(contents)).strip()
235
+ if isinstance(contents, list):
236
+ return "\n".join(c.get("value", str(c)) if isinstance(c, dict) else str(c) for c in contents).strip()
237
+ return str(contents).strip()
238
+
239
+
240
+ @mcp.tool()
241
+ @_notices.tool
242
+ async def workspace(ctx: Context | None = None) -> str:
243
+ """Which directory is codenav navigating, and why? Use when results look like they come from the wrong checkout/worktree."""
244
+ await _use_workspace(ctx)
245
+ return f"{WORKSPACE_ROOT}\nchosen because: {_selector.explain(_workspace_source)}\nsource root: {SOURCE_ROOT}"
246
+
247
+
248
+ @mcp.tool()
249
+ @_notices.tool
250
+ async def hover(file_path: str, line: int, column: int, ctx: Context | None = None) -> str:
251
+ """Get type/documentation info for the symbol at a position.
252
+
253
+ `line` and `column` are 1-indexed. `column` is a UTF-16 character offset
254
+ on the line (not a visual/display column): a leading tab counts as one
255
+ character.
256
+ """
257
+ await _use_workspace(ctx)
258
+ try:
259
+ _check_python_file(file_path)
260
+ client = await get_client()
261
+ result = await client.hover(file_path, line, column)
262
+ text = _format_hover_contents(result.get("contents"))
263
+ if text:
264
+ text = await _enrich_bare_type(text, client, file_path, line, column)
265
+ except TOOL_ERRORS as exc:
266
+ return format_tool_error(exc)
267
+ return text or "No hover information at that position."
268
+
269
+
270
+ @mcp.tool()
271
+ @_notices.tool
272
+ async def definition(file_path: str, line: int, column: int, ctx: Context | None = None) -> str:
273
+ """Go to the definition of the symbol at a position.
274
+
275
+ `line` and `column` are 1-indexed. `column` is a UTF-16 character offset
276
+ on the line (not a visual/display column): a leading tab counts as one
277
+ character.
278
+
279
+ Resolves through ty's type inference, so this works even when the call
280
+ site only has a typed parameter/attribute (e.g. `services.some_method()`
281
+ where `services: AppServices` is a constructor argument), not just
282
+ direct references to a name in scope.
283
+ """
284
+ await _use_workspace(ctx)
285
+ try:
286
+ _check_python_file(file_path)
287
+ client = await get_client()
288
+ locations = await client.definition(file_path, line, column)
289
+ except TOOL_ERRORS as exc:
290
+ return format_tool_error(exc)
291
+ if not locations:
292
+ return "No definition found at that position."
293
+ return "\n\n".join(format_location(loc, WORKSPACE_ROOT) for loc in locations)
294
+
295
+
296
+ @mcp.tool()
297
+ @_notices.tool
298
+ async def references(
299
+ file_path: str, line: int, column: int, include_declaration: bool = True, ctx: Context | None = None
300
+ ) -> str:
301
+ """Find all usages of the symbol at a position across the workspace.
302
+
303
+ `line` and `column` are 1-indexed. `column` is a UTF-16 character offset
304
+ on the line (not a visual/display column): a leading tab counts as one
305
+ character.
306
+ """
307
+ await _use_workspace(ctx)
308
+ try:
309
+ _check_python_file(file_path)
310
+ client = await get_client()
311
+ locations = await client.references(file_path, line, column, include_declaration=include_declaration)
312
+ except TOOL_ERRORS as exc:
313
+ return format_tool_error(exc)
314
+ return format_references(locations, WORKSPACE_ROOT)
315
+
316
+
317
+ @mcp.tool()
318
+ @_notices.tool
319
+ async def search_symbol(
320
+ query: str | None = None,
321
+ name: str | None = None,
322
+ kind: str | None = None,
323
+ path: str | None = None,
324
+ fuzzy: bool = False,
325
+ ctx: Context | None = None,
326
+ ) -> str:
327
+ """Search the whole workspace for a symbol by name (class, function, method, etc.).
328
+
329
+ Use this to find a symbol's file/position first, then pass that position
330
+ to definition/references/hover for precise, type-resolved navigation.
331
+ Returned positions point at the identifier name (not the `class`/`def`
332
+ keyword) and use the same character-offset column convention as the
333
+ other tools. Results include a SymbolKind label and are capped.
334
+ `name` is accepted as an alias for `query`. Narrow broad queries with
335
+ `kind` (SymbolKind labels, comma-separated: `class`, `function,method`,
336
+ `interface`, ...) and `path` (workspace-relative prefix such as `src/`,
337
+ or a glob such as `src/**/*.py`). Production code ranks before tests.
338
+ Loose fuzzy hits whose names don't contain the query are summarised as a
339
+ count when real matches exist; pass `fuzzy=true` to list them too.
340
+ """
341
+ await _use_workspace(ctx)
342
+ try:
343
+ kinds = parse_kind_filter(kind)
344
+ query = resolve_name_query(preferred="query", example="create_user", query=query, name=name)
345
+ client = await get_client()
346
+ symbols = await client.workspace_symbol(query)
347
+ except TOOL_ERRORS as exc:
348
+ return format_tool_error(exc)
349
+ if not symbols:
350
+ return f"No symbols matching {query!r}."
351
+ matching = filter_symbols_by_kind_and_path(symbols, WORKSPACE_ROOT, kinds=kinds, path=path)
352
+ if not matching:
353
+ filters = ", ".join(f"{k}={v!r}" for k, v in (("kind", kind), ("path", path)) if v)
354
+ return f"No symbols matching {query!r} with {filters} ({len(symbols)} without the filters)."
355
+ return format_workspace_symbols(matching, WORKSPACE_ROOT, query=query, fuzzy=fuzzy)
356
+
357
+
358
+ @mcp.tool()
359
+ @_notices.tool
360
+ async def diagnostics(file_path: str, ctx: Context | None = None) -> str:
361
+ """Get ty's type-check diagnostics (errors/warnings) for a single file."""
362
+ await _use_workspace(ctx)
363
+ try:
364
+ _check_python_file(file_path)
365
+ client = await get_client()
366
+ items = await client.diagnostics(file_path)
367
+ except TOOL_ERRORS as exc:
368
+ return format_tool_error(exc)
369
+ return format_diagnostics(items)
370
+
371
+
372
+ @mcp.tool()
373
+ @_notices.tool
374
+ async def symbol_info(
375
+ name: str | None = None,
376
+ query: str | None = None,
377
+ file_path: str | None = None,
378
+ include_references: bool = True,
379
+ ctx: Context | None = None,
380
+ ) -> str:
381
+ """What is X and where is it used? Example: `symbol_info(name="UserService.create_user")`.
382
+
383
+ One-call summary for a name: header, hover text, definition, and
384
+ references grouped by file — the usual first lookup instead of chaining search_symbol → hover →
385
+ definition → references by hand.
386
+
387
+ `name` is a symbol name, or a dotted `Class.method` to resolve a specific
388
+ method when the plain name is ambiguous. Pass `file_path` (relative to the
389
+ workspace root) to disambiguate when several symbols share a name
390
+ elsewhere in the workspace; if it's still ambiguous, the candidates are
391
+ listed back so you can retry with a narrower name or file_path.
392
+ `query` is accepted as an alias for `name`.
393
+ """
394
+ await _use_workspace(ctx)
395
+ try:
396
+ name = resolve_name_query(preferred="name", example="UserService.create_user", name=name, query=query)
397
+ client = await get_client()
398
+ resolved = await resolve_symbol(client, WORKSPACE_ROOT, name, file_path=file_path)
399
+ rel_path = uri_to_relative(resolved.uri, WORKSPACE_ROOT)
400
+ line, column = resolved.line + 1, resolved.column + 1
401
+ hover_result = await client.hover(rel_path, line, column)
402
+ definition_locations = await client.definition(rel_path, line, column)
403
+ reference_locations = await client.references(rel_path, line, column) if include_references else []
404
+ except TOOL_ERRORS as exc:
405
+ return format_tool_error(exc)
406
+ header = f"{resolved.name} [{symbol_kind_label(resolved.kind)}] ({rel_path}:{line}:{column})"
407
+ hover_text = _format_hover_contents(hover_result.get("contents")) or "No hover information."
408
+ definition_text = (
409
+ "\n\n".join(format_location(loc, WORKSPACE_ROOT) for loc in definition_locations)
410
+ if definition_locations
411
+ else "No definition found."
412
+ )
413
+ parts = [header, "", hover_text, "", "Definition:", definition_text]
414
+ if include_references:
415
+ parts += ["", "References:", format_references_grouped(reference_locations, WORKSPACE_ROOT)]
416
+ return "\n".join(parts)
417
+
418
+
419
+ @mcp.tool()
420
+ @_notices.tool
421
+ async def outline(file_path: str, ctx: Context | None = None) -> str:
422
+ """What's in this file? Example: `outline(file_path="src/app/services.py")`.
423
+
424
+ Indented outline (classes, methods, functions, with line numbers) of a
425
+ Python file, so you can navigate a large file without reading it in full.
426
+ Follow up with hover/definition/references at a listed line, or
427
+ symbol_info by name.
428
+ """
429
+ await _use_workspace(ctx)
430
+ try:
431
+ _check_python_file(file_path)
432
+ client = await get_client()
433
+ symbols = await client.document_symbol(file_path)
434
+ except TOOL_ERRORS as exc:
435
+ return format_tool_error(exc)
436
+ return format_outline(symbols)
437
+
438
+
439
+ @mcp.tool()
440
+ @_notices.tool
441
+ async def callers(
442
+ name: str | None = None,
443
+ query: str | None = None,
444
+ file_path: str | None = None,
445
+ ctx: Context | None = None,
446
+ ) -> str:
447
+ """Who calls this function? Example: `callers(name="create_user")`.
448
+
449
+ Narrower than references, since it
450
+ leaves out imports and type-only usages and only lists actual call sites.
451
+
452
+ `name` resolves the same way as symbol_info (dotted Class.method accepted;
453
+ pass file_path to disambiguate a common name). `query` is accepted as an
454
+ alias for `name`.
455
+ """
456
+ await _use_workspace(ctx)
457
+ try:
458
+ name = resolve_name_query(preferred="name", example="create_user", name=name, query=query)
459
+ client = await get_client()
460
+ resolved = await resolve_symbol(client, WORKSPACE_ROOT, name, file_path=file_path)
461
+ rel_path = uri_to_relative(resolved.uri, WORKSPACE_ROOT)
462
+ items = await client.prepare_call_hierarchy(rel_path, resolved.line + 1, resolved.column + 1)
463
+ if not items:
464
+ return f"{resolved.name} has no call hierarchy entry at that position (it may not be a callable)."
465
+ incoming = await client.incoming_calls(items[0])
466
+ except TOOL_ERRORS as exc:
467
+ return format_tool_error(exc)
468
+ return format_callers(incoming, WORKSPACE_ROOT)
469
+
470
+
471
+ def _module_path(abs_path: Path, base: Path | None = None) -> str:
472
+ """Dotted import path for a file under `base` (default `SOURCE_ROOT`)."""
473
+ base = SOURCE_ROOT if base is None else base
474
+ try:
475
+ rel = abs_path.relative_to(base)
476
+ except ValueError as exc:
477
+ raise ToolInputError(
478
+ f"{abs_path} is outside the source root ({base}); "
479
+ "set CODENAV_MCP_SOURCE_ROOT if this project's importable code "
480
+ "lives under a different directory."
481
+ ) from exc
482
+ parts = rel.with_suffix("").parts
483
+ if parts and parts[-1] == "__init__":
484
+ parts = parts[:-1]
485
+ if not parts:
486
+ raise ToolInputError(f"cannot derive an import path for {abs_path}")
487
+ return ".".join(parts)
488
+
489
+
490
+ def _is_protocol_base(base: ast.expr) -> bool:
491
+ """`Protocol`, `typing.Protocol`/`typing_extensions.Protocol`, or a
492
+ subscripted `Protocol[T]` — `documentSymbol` doesn't expose base classes,
493
+ so `implementations` parses the source directly to tell a Protocol port
494
+ apart from an ordinary class."""
495
+ if isinstance(base, ast.Subscript):
496
+ base = base.value
497
+ if isinstance(base, ast.Name):
498
+ return base.id == "Protocol"
499
+ if isinstance(base, ast.Attribute):
500
+ return base.attr == "Protocol"
501
+ return False
502
+
503
+
504
+ @dataclass(frozen=True)
505
+ class _ClassInfo:
506
+ """What `implementations` needs from a class's source: `documentSymbol`
507
+ exposes neither base classes nor `self.x = ...` attributes."""
508
+
509
+ name: str
510
+ bases: tuple[str, ...] # simple names of the base expressions
511
+ is_protocol: bool
512
+ members: frozenset[str] # methods, properties, class-level and `self.` attributes (no dunders)
513
+
514
+
515
+ def _base_simple_name(base: ast.expr) -> str | None:
516
+ if isinstance(base, ast.Subscript):
517
+ base = base.value
518
+ if isinstance(base, ast.Name):
519
+ return base.id
520
+ if isinstance(base, ast.Attribute):
521
+ return base.attr
522
+ return None
523
+
524
+
525
+ def _is_dunder(name: str) -> bool:
526
+ return name.startswith("__") and name.endswith("__")
527
+
528
+
529
+ def _own_members(cls: ast.ClassDef) -> frozenset[str]:
530
+ names: set[str] = set()
531
+
532
+ def add_target(target: ast.expr) -> None:
533
+ if isinstance(target, ast.Name):
534
+ names.add(target.id)
535
+ elif isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self":
536
+ names.add(target.attr)
537
+ elif isinstance(target, (ast.Tuple, ast.List)):
538
+ for element in target.elts:
539
+ add_target(element)
540
+
541
+ for stmt in cls.body:
542
+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
543
+ names.add(stmt.name)
544
+ for node in ast.walk(stmt):
545
+ if isinstance(node, ast.Assign):
546
+ for target in node.targets:
547
+ add_target(target)
548
+ elif isinstance(node, (ast.AnnAssign, ast.AugAssign)):
549
+ add_target(node.target)
550
+ elif isinstance(stmt, ast.AnnAssign):
551
+ add_target(stmt.target)
552
+ elif isinstance(stmt, ast.Assign):
553
+ for target in stmt.targets:
554
+ add_target(target)
555
+ return frozenset(n for n in names if not _is_dunder(n))
556
+
557
+
558
+ def _class_infos(source: str) -> list[_ClassInfo]:
559
+ """Every class in `source` (at any nesting level)."""
560
+ try:
561
+ tree = ast.parse(source)
562
+ except SyntaxError:
563
+ return []
564
+ return [
565
+ _ClassInfo(
566
+ name=node.name,
567
+ bases=tuple(n for n in map(_base_simple_name, node.bases) if n),
568
+ is_protocol=any(_is_protocol_base(base) for base in node.bases),
569
+ members=_own_members(node),
570
+ )
571
+ for node in ast.walk(tree)
572
+ if isinstance(node, ast.ClassDef)
573
+ ]
574
+
575
+
576
+ def _protocol_class_names(source: str) -> set[str]:
577
+ """Names of every class in `source` (at any nesting level) that subclasses
578
+ `Protocol`."""
579
+ return {info.name for info in _class_infos(source) if info.is_protocol}
580
+
581
+
582
+ # path -> ((mtime_ns, size), class infos): a pure function of the file's own
583
+ # text, so the stat pair is a sufficient key. Parsing every file's AST
584
+ # dominated `implementations`' warm cost before this.
585
+ _class_infos_cache: dict[Path, tuple[tuple[int, int], list[_ClassInfo]]] = {}
586
+
587
+
588
+ def _cached_class_infos(path: Path) -> list[_ClassInfo]:
589
+ stat = path.stat()
590
+ key = (stat.st_mtime_ns, stat.st_size)
591
+ hit = _class_infos_cache.get(path)
592
+ if hit is not None and hit[0] == key:
593
+ return hit[1]
594
+ infos = _class_infos(path.read_text(encoding="utf-8"))
595
+ _class_infos_cache[path] = (key, infos)
596
+ return infos
597
+
598
+
599
+ def _cached_protocol_class_names(path: Path) -> set[str]:
600
+ return {info.name for info in _cached_class_infos(path) if info.is_protocol}
601
+
602
+
603
+ def _symbol_members(cls_node: dict[str, Any]) -> set[str]:
604
+ """Method/property/field names (no dunders) directly under a `to_symbol_tree` class node."""
605
+ names: set[str] = set()
606
+ for child in cls_node["children"]:
607
+ if child["kind"] not in (6, 7, 8, 13): # Method, Property, Field, Variable
608
+ continue
609
+ if not _is_dunder(child["name"]):
610
+ names.add(child["name"])
611
+ return names
612
+
613
+
614
+ def _effective_members(
615
+ name: str,
616
+ own: set[str],
617
+ infos_by_name: dict[str, list[_ClassInfo]],
618
+ ) -> set[str]:
619
+ """`own` plus everything inherited through same-workspace base classes
620
+ (matched by simple name; a cycle or an unknown base just stops the walk).
621
+ A class with the right method via a mixin or parent still satisfies a
622
+ Protocol, so the name pre-filter has to see inherited members too."""
623
+ members = set(own)
624
+ seen = {name}
625
+ pending = [b for info in infos_by_name.get(name, []) for b in info.bases]
626
+ while pending:
627
+ base = pending.pop()
628
+ if base in seen:
629
+ continue
630
+ seen.add(base)
631
+ for info in infos_by_name.get(base, []):
632
+ members |= info.members
633
+ pending.extend(info.bases)
634
+ return members
635
+
636
+
637
+ # In-memory only (never written to disk). Its imports are absolute, so its
638
+ # directory doesn't affect resolution; the workspace root keeps it clear of
639
+ # path-scoped ty overrides (e.g. rules relaxed for `tests/**`) and of any
640
+ # project-specific layout.
641
+ _PROBE_RELATIVE_PATH = Path(".codenav_probe.py")
642
+
643
+
644
+ def _probe_source(port_module: str, port_name: str, candidate_module: str, candidate_name: str) -> str:
645
+ imports = f"from {port_module} import {port_name}\n"
646
+ if candidate_module != port_module:
647
+ imports += f"from {candidate_module} import {candidate_name}\n"
648
+ return f"{imports}\n\ndef _p(x: {candidate_name}) -> {port_name}:\n\treturn x\n"
649
+
650
+
651
+ # A probe verdict depends on the port and candidate files *and* whatever they
652
+ # import, so it can only be reused while nothing under SOURCE_ROOT has changed:
653
+ # the whole cache is keyed to one (path, mtime_ns, size) signature of every
654
+ # candidate file plus the dependency environment (see `_environment_paths`)
655
+ # and dropped wholesale when it differs. Verdicts are keyed by
656
+ # (port module, port name, candidate module, class name) -> (verified?, line).
657
+ _probe_cache: dict[tuple[str, str, str, str], tuple[bool, str]] = {}
658
+ _probe_cache_signature: tuple[tuple[str, int, int], ...] = ()
659
+ _probe_lock = asyncio.Lock()
660
+
661
+
662
+ def _environment_paths() -> list[Path]:
663
+ """Files/dirs whose change can alter a probe verdict without touching any
664
+ source file: dependency manifests and the venv's `site-packages` (its own
665
+ mtime moves whenever a package is installed, upgraded or removed — e.g. by
666
+ `uv sync`)."""
667
+ paths = [WORKSPACE_ROOT / "pyproject.toml", WORKSPACE_ROOT / "uv.lock"]
668
+ for pattern in ("lib/python*/site-packages", "Lib/site-packages"):
669
+ paths.extend((WORKSPACE_ROOT / ".venv").glob(pattern))
670
+ return paths
671
+
672
+
673
+ def _source_signature(files: list[Path]) -> tuple[tuple[str, int, int], ...]:
674
+ entries: list[tuple[str, int, int]] = []
675
+ for path in [*files, *_environment_paths()]:
676
+ try:
677
+ stat = path.stat()
678
+ except OSError:
679
+ continue
680
+ entries.append((str(path), stat.st_mtime_ns, stat.st_size))
681
+ return tuple(entries)
682
+
683
+
684
+ @mcp.tool()
685
+ @_notices.tool
686
+ async def implementations(
687
+ port_name: str | None = None,
688
+ name: str | None = None,
689
+ query: str | None = None,
690
+ file_path: str | None = None,
691
+ ctx: Context | None = None,
692
+ ) -> str:
693
+ """Find concrete classes that structurally satisfy a `Protocol` port.
694
+
695
+ Many hexagonal codebases define ports as `Protocol`s that adapters never
696
+ subclass explicitly, so ty's own `implementation`/`typeHierarchy` return
697
+ nothing for them. This scans classes under SOURCE_ROOT (the whole
698
+ workspace by default; see CODENAV_MCP_SOURCE_ROOT) whose method names
699
+ cover the protocol's, then verifies each candidate with ty's real type
700
+ checker via an in-memory probe file (never written to disk) — so a
701
+ result means "assignable", not just "same method names". `port_name`
702
+ must itself resolve to a `Protocol` class; other classes' subclasses are
703
+ better found with `references`/`symbol_info`. `name` and `query` are
704
+ accepted as aliases for `port_name`. `file_path` narrows the port lookup
705
+ to one file when the name exists in several. Members inherited from
706
+ same-workspace base classes, and fields/properties declared by the port,
707
+ count when matching names. Directories listed in
708
+ CODENAV_MCP_EXTRA_SOURCE_ROOTS (e.g. `tests`) are scanned too; their
709
+ matches (test doubles) are listed under a separate heading.
710
+ """
711
+ await _use_workspace(ctx)
712
+ try:
713
+ port_name = resolve_name_query(
714
+ preferred="port_name",
715
+ example="FileSystemPort",
716
+ port_name=port_name,
717
+ name=name,
718
+ query=query,
719
+ )
720
+ client = await get_client()
721
+ port = await resolve_symbol(client, WORKSPACE_ROOT, port_name, file_path=file_path)
722
+ port_rel_path = uri_to_relative(port.uri, WORKSPACE_ROOT)
723
+ port_symbols = await client.document_symbol(port_rel_path)
724
+ port_source = (WORKSPACE_ROOT / port_rel_path).read_text(encoding="utf-8")
725
+ except TOOL_ERRORS as exc:
726
+ return format_tool_error(exc)
727
+ if port.name not in _protocol_class_names(port_source):
728
+ return (
729
+ f"{port.name!r} is not a Protocol; implementations only finds structural "
730
+ "implementers of Protocol ports (use symbol_info/references for explicit subclasses)."
731
+ )
732
+ port_class = next(
733
+ (n for n in to_symbol_tree(port_symbols) if n["kind"] == 5 and n["name"] == port.name), # Class
734
+ None,
735
+ )
736
+ if port_class is None:
737
+ return f"{port_name!r} did not resolve to a class in {port_rel_path}."
738
+ port_own = _symbol_members(port_class)
739
+ for info in _class_infos(port_source):
740
+ if info.name == port.name:
741
+ port_own |= info.members
742
+ if not port_own:
743
+ return f"{port.name} has no members to match candidates against."
744
+
745
+ try:
746
+ port_module = _module_path(WORKSPACE_ROOT / port_rel_path)
747
+ except TOOL_ERRORS as exc:
748
+ return format_tool_error(exc)
749
+
750
+ # Vendored/generated/virtualenv trees are never this project's own source
751
+ # and can be enormous (a `.venv` alone can dwarf the real codebase) — skip
752
+ # them outright rather than walking (and failing to decode) thousands of
753
+ # irrelevant files.
754
+ primary_files = sorted(p for p in SOURCE_ROOT.rglob("*.py") if not is_excluded(p, SOURCE_ROOT))
755
+ primary_set = set(primary_files)
756
+ # Extra roots (tests, ...): scanned too, reported separately, imported relative to the workspace.
757
+ extra_files = sorted(
758
+ {
759
+ p
760
+ for root in EXTRA_SOURCE_ROOTS
761
+ for p in root.rglob("*.py")
762
+ if not is_excluded(p, root) and p not in primary_set
763
+ }
764
+ )
765
+ extra_set = set(extra_files)
766
+ all_candidate_files = [*primary_files, *extra_files]
767
+ port_abs_path = (WORKSPACE_ROOT / port_rel_path).resolve()
768
+ # Sequential, not `asyncio.gather`: firing ~90 concurrent documentSymbol
769
+ # requests at ty made it respond with a "content modified" LSP error;
770
+ # sequential stays fast (under a second for this codebase's size). Each
771
+ # file is fetched independently (not one list comprehension) so a single
772
+ # unreadable/undecodable candidate (binary file mis-suffixed `.py`,
773
+ # permission error, …) is skipped rather than aborting the whole scan.
774
+ candidate_files: list[Path] = []
775
+ symbol_lists: list[list[dict[str, Any]]] = []
776
+ unreadable: list[Path] = []
777
+ for path in all_candidate_files:
778
+ try:
779
+ symbols = await client.document_symbol(str(path))
780
+ except TOOL_ERRORS:
781
+ unreadable.append(path)
782
+ continue
783
+ candidate_files.append(path)
784
+ symbol_lists.append(symbols)
785
+
786
+ infos_by_path: dict[Path, list[_ClassInfo]] = {}
787
+ infos_by_name: dict[str, list[_ClassInfo]] = {}
788
+ for path in candidate_files:
789
+ try:
790
+ infos = _cached_class_infos(path)
791
+ except (OSError, UnicodeDecodeError):
792
+ unreadable.append(path)
793
+ continue
794
+ infos_by_path[path] = infos
795
+ for info in infos:
796
+ infos_by_name.setdefault(info.name, []).append(info)
797
+ port_required = _effective_members(port.name, port_own, infos_by_name)
798
+
799
+ name_matches: list[tuple[Path, str, str, bool]] = [] # (path, class name, module path, from extra root)
800
+ for path, symbols in zip(candidate_files, symbol_lists, strict=True):
801
+ if path not in infos_by_path:
802
+ continue
803
+ other_protocols = {info.name for info in infos_by_path[path] if info.is_protocol}
804
+ for cls_node in (n for n in to_symbol_tree(symbols) if n["kind"] == 5):
805
+ if path.resolve() == port_abs_path and cls_node["name"] == port.name:
806
+ continue # the port never "implements" itself
807
+ if cls_node["name"] in other_protocols:
808
+ continue # another Protocol, not a concrete implementer
809
+ try:
810
+ candidate_module = _module_path(path, WORKSPACE_ROOT if path in extra_set else None)
811
+ except ToolInputError:
812
+ continue # outside SOURCE_ROOT's import-path derivation; can't probe it
813
+ own = _symbol_members(cls_node)
814
+ for info in infos_by_path[path]:
815
+ if info.name == cls_node["name"]:
816
+ own |= info.members
817
+ if port_required <= _effective_members(cls_node["name"], own, infos_by_name):
818
+ name_matches.append((path, cls_node["name"], candidate_module, path in extra_set))
819
+
820
+ skipped_note = f" ({len(unreadable)} file(s) under {SOURCE_ROOT} skipped: unreadable)" if unreadable else ""
821
+ if not name_matches:
822
+ return (
823
+ f"No classes under {SOURCE_ROOT} cover {port.name}'s methods: "
824
+ f"{', '.join(sorted(port_required))}.{skipped_note}"
825
+ )
826
+
827
+ global _probe_cache_signature
828
+ probe_uri = (WORKSPACE_ROOT / _PROBE_RELATIVE_PATH).as_uri()
829
+ verified: list[str] = []
830
+ unverified: list[str] = []
831
+ verified_extra: list[str] = []
832
+ unverified_extra: list[str] = []
833
+ opened = False
834
+ # All calls share one scratch document, so concurrent runs would overwrite
835
+ # each other's probe (and close it under one another): serialize them.
836
+ await _probe_lock.acquire()
837
+ try:
838
+ signature = _source_signature(all_candidate_files)
839
+ if signature != _probe_cache_signature:
840
+ _probe_cache.clear()
841
+ _probe_cache_signature = signature
842
+ for path, cls_name, candidate_module, is_extra in name_matches:
843
+ cache_key = (port_module, port.name, candidate_module, cls_name)
844
+ rel = uri_to_relative(path.as_uri(), WORKSPACE_ROOT)
845
+ ok_bucket, bad_bucket = (verified_extra, unverified_extra) if is_extra else (verified, unverified)
846
+ cached = _probe_cache.get(cache_key)
847
+ if cached is not None:
848
+ (ok_bucket if cached[0] else bad_bucket).append(cached[1])
849
+ continue
850
+ code = _probe_source(port_module, port.name, candidate_module, cls_name)
851
+ if not opened:
852
+ await client.open_scratch_document(probe_uri, code)
853
+ opened = True
854
+ else:
855
+ await client.change_scratch_document(probe_uri, code)
856
+ items = await client.pull_diagnostics(probe_uri)
857
+ # Verified means the probe document has *no* diagnostics at all —
858
+ # not just none tagged `invalid-return-type`. A candidate module
859
+ # that fails to import (e.g. it lives outside where its own
860
+ # import path resolves, a common miss when SOURCE_ROOT doesn't
861
+ # match the project's real package layout) produces an
862
+ # `unresolved-import` diagnostic instead, and with only the
863
+ # narrower check that case was silently counted as verified even
864
+ # though ty never actually checked the assignment.
865
+ if not items:
866
+ line, is_verified = f"{cls_name} ({rel})", True
867
+ elif any(item.get("code") == "invalid-return-type" for item in items):
868
+ line = f"{cls_name} ({rel}) — method names match but ty rejects the assignment"
869
+ is_verified = False
870
+ else:
871
+ reasons = "; ".join(str(item.get("message", "")).splitlines()[0] for item in items[:3])
872
+ line = f"{cls_name} ({rel}) — could not verify: {reasons}"
873
+ is_verified = False
874
+ _probe_cache[cache_key] = (is_verified, line)
875
+ (ok_bucket if is_verified else bad_bucket).append(line)
876
+ except TOOL_ERRORS as exc:
877
+ return format_tool_error(exc)
878
+ finally:
879
+ try:
880
+ if opened:
881
+ await client.close_scratch_document(probe_uri)
882
+ finally:
883
+ _probe_lock.release()
884
+
885
+ lines = [f"{len(verified)} class(es) implement {port.name} (type-verified):{skipped_note}"]
886
+ lines += verified or ["(none)"]
887
+ if EXTRA_SOURCE_ROOTS:
888
+ roots = ", ".join(
889
+ str(r.relative_to(WORKSPACE_ROOT)) if r.is_relative_to(WORKSPACE_ROOT) else str(r)
890
+ for r in EXTRA_SOURCE_ROOTS
891
+ )
892
+ lines += ["", f"{len(verified_extra)} more in extra roots ({roots}), e.g. test doubles (type-verified):"]
893
+ lines += verified_extra or ["(none)"]
894
+ if unverified or unverified_extra:
895
+ lines += ["", "Method-name matches that don't type-check as the port:"]
896
+ lines += [*unverified, *unverified_extra]
897
+ return "\n".join(lines)
898
+
899
+
900
+ def main() -> None:
901
+ """Console entry point: serve over stdio."""
902
+ mcp.run(transport="stdio")
903
+
904
+
905
+ if __name__ == "__main__":
906
+ main()
@@ -0,0 +1,47 @@
1
+ """Resolves how to launch `ty server` for codenav's LspClient."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import shutil
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def _bundled_ty() -> str | None:
15
+ """The `ty` binary installed alongside codenav (it is a declared dependency).
16
+
17
+ Hosts typically launch codenav with `uvx`/`pipx`, whose environment's
18
+ scripts directory is not on the server's PATH, so `shutil.which` alone
19
+ misses it."""
20
+ try:
21
+ from ty import find_ty_bin # absent when running from a bare source tree
22
+
23
+ return find_ty_bin()
24
+ except (ImportError, FileNotFoundError):
25
+ return None
26
+
27
+
28
+ def resolve_ty_command(workspace_root: Path) -> list[str]:
29
+ """The project's own `ty` first (its pinned version matches its config), then
30
+ the one bundled with codenav, then PATH, then `uvx` as a last resort."""
31
+ venv_bin = "Scripts" if sys.platform == "win32" else "bin"
32
+ venv_exe = "ty.exe" if sys.platform == "win32" else "ty"
33
+ candidate = workspace_root / ".venv" / venv_bin / venv_exe
34
+ if candidate.is_file():
35
+ return [str(candidate), "server"]
36
+ bundled = _bundled_ty()
37
+ if bundled:
38
+ return [bundled, "server"]
39
+ on_path = shutil.which("ty")
40
+ if on_path:
41
+ return [on_path, "server"]
42
+ logger.warning(
43
+ "ty not found in %s/.venv, codenav's environment or on PATH; falling back to 'uvx ty server', "
44
+ "which downloads it on first use.",
45
+ workspace_root,
46
+ )
47
+ return ["uvx", "ty", "server"]
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: codenav-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server exposing ty's language-server features (hover, definition, references, workspace symbol search, diagnostics) as MCP tools
5
+ Keywords: mcp,model-context-protocol,ty,lsp,python,code-navigation,ai-agents
6
+ Author: Daniel Illescas Romero
7
+ Author-email: Daniel Illescas Romero <contact@daniel-ir.eu>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development
20
+ Requires-Dist: mcp>=2.2.0
21
+ Requires-Dist: ty>=0.0.75
22
+ Requires-Dist: mcp-nav-shared>=0.1.0,<0.2
23
+ Requires-Python: >=3.11
24
+ Project-URL: Homepage, https://github.com/illescasDaniel/SpaceMaker/tree/main/mcp-servers/codenav_mcp
25
+ Project-URL: Repository, https://github.com/illescasDaniel/SpaceMaker
26
+ Project-URL: Issues, https://github.com/illescasDaniel/SpaceMaker/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ # codenav-mcp
30
+
31
+ An MCP server that gives AI agents type-resolved Python navigation, backed by
32
+ [ty](https://github.com/astral-sh/ty)'s language server. Definitions,
33
+ references and call sites go through real type inference (imports,
34
+ dependency-injected parameters, dataclass fields), not text grep.
35
+
36
+ ## Quick start
37
+
38
+ `ty` is installed with the package, so all you need is
39
+ [uv](https://docs.astral.sh/uv/) (or `pipx`):
40
+
41
+ ```bash
42
+ uvx codenav-mcp
43
+ ```
44
+
45
+ Register it with your MCP host. For Claude Code, from the project root:
46
+
47
+ ```bash
48
+ claude mcp add codenav -- uvx codenav-mcp
49
+ ```
50
+
51
+ Or add it to a project `.mcp.json` (Claude Code) or `.cursor/mcp.json` (Cursor):
52
+
53
+ ```json
54
+ {
55
+ "mcpServers": {
56
+ "codenav": {
57
+ "command": "uvx",
58
+ "args": ["codenav-mcp"],
59
+ "env": {
60
+ "CODENAV_MCP_SOURCE_ROOT": "src"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ In Cursor, also set `"CODENAV_MCP_WORKSPACE": "${workspaceFolder}"`, because
68
+ Cursor may start MCP servers with your home directory as the working directory.
69
+
70
+ ## Tools
71
+
72
+ **Start with the name-based tools:**
73
+
74
+ | Tool | Answers |
75
+ |------|---------|
76
+ | `symbol_info` | What is this? Header, hover, definition and references in one call |
77
+ | `outline` | What's in this file? (classes, methods, functions) |
78
+ | `callers` | Who actually calls this function? (call hierarchy, not imports) |
79
+ | `implementations` | Which classes structurally implement this `Protocol`? (type-checked) |
80
+ | `search_symbol` | Workspace symbol search by name (ranked, capped; optional `kind=` / `path=` filters; production code before tests; fuzzy-only hits summarised unless `fuzzy=true`) |
81
+ | `workspace` | Which directory is being navigated, and why |
82
+
83
+ Then use the position tools once you have a `path:line:col`:
84
+
85
+ | Tool | Answers |
86
+ |------|---------|
87
+ | `hover` | Type and docs at a position |
88
+ | `definition` | Go to definition (resolves through injected parameters) |
89
+ | `references` | All usages across the workspace |
90
+ | `diagnostics` | ty type-check diagnostics for one file |
91
+
92
+ `name` and `query` are accepted as aliases on the name-based tools
93
+ (`port_name` / `name` / `query` on `implementations`). A missing or wrong
94
+ parameter gets a short hint back instead of a validation error. Dotted names
95
+ may nest (`Outer.Inner.method`). `implementations` also takes `file_path` to
96
+ pick one port when the name exists in several files, and counts inherited
97
+ members and dataclass/`self.x` fields toward a port's required names.
98
+
99
+ Positions are **1-indexed**. `column` is a UTF-16 character offset (a leading
100
+ tab counts as one character).
101
+
102
+ Python only (`.py` / `.pyi`).
103
+
104
+ ## Which `ty` runs
105
+
106
+ 1. The project's own `.venv/bin/ty` (`.venv\Scripts\ty.exe` on Windows), so
107
+ the ty version matches the project's pin and config.
108
+ 2. The `ty` installed alongside codenav-mcp.
109
+ 3. `ty` on `PATH`.
110
+ 4. `uvx ty server` as a last resort.
111
+
112
+ ## Environment
113
+
114
+ | Variable | Default | Purpose |
115
+ |----------|---------|---------|
116
+ | `CODENAV_MCP_WORKSPACE` | unset: follows the client's MCP roots when they name a worktree of the same git repository, else `CLAUDE_PROJECT_DIR`, else the working directory | Pins the project root (never overridden). See the `workspace` tool |
117
+ | `CODENAV_MCP_SOURCE_ROOT` | whole workspace | Directory scanned for `implementations` candidates and used to derive dotted import paths (e.g. `src`) |
118
+ | `CODENAV_MCP_EXTRA_SOURCE_ROOTS` | none | Comma-separated directories (e.g. `tests`) that `implementations` also scans; matches (test doubles) are listed under a separate heading |
119
+
120
+ ## Requirements
121
+
122
+ - Python ≥ 3.11
123
+ - Installed automatically: [`mcp`](https://pypi.org/project/mcp/),
124
+ [`ty`](https://pypi.org/project/ty/),
125
+ [`mcp-nav-shared`](https://pypi.org/project/mcp-nav-shared/)
126
+
127
+ ## Related
128
+
129
+ - [`webnav-mcp`](https://pypi.org/project/webnav-mcp/): the same kind of
130
+ navigation for JS/TS/HTML/CSS.
131
+ - Design notes (Protocol conformance probe, positioning, output formats):
132
+ [docs/agent-tooling.md](https://github.com/illescasDaniel/SpaceMaker/blob/main/docs/agent-tooling.md).
133
+
134
+ ## Development
135
+
136
+ Developed in the [SpaceMaker](https://github.com/illescasDaniel/SpaceMaker)
137
+ repository as a uv workspace member (`mcp-servers/codenav_mcp`). From a
138
+ checkout: `uv sync --group dev`, then `uv run codenav-mcp`.
139
+
140
+ ## License
141
+
142
+ MIT. See [LICENSE](https://github.com/illescasDaniel/SpaceMaker/blob/main/mcp-servers/codenav_mcp/LICENSE).
@@ -0,0 +1,8 @@
1
+ codenav_mcp/__init__.py,sha256=Af-BAUSWcVl66PYC3M6T3nvVBVre2X6-tdDaCS0LoTg,79
2
+ codenav_mcp/server.py,sha256=gqCp-BBcOQQoxs981JPqjR4tyIIbCUvmm10-kYTMJqQ,35057
3
+ codenav_mcp/ty_command.py,sha256=Tt1BQhFZ8zgWiL24BcACfZQ-p8btHU4CO1fesLcwTBk,1440
4
+ codenav_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=Q28OPpoy0LGWJN9HZyo1Qycs-YcPAMC5cmAZjPf7xbI,1079
5
+ codenav_mcp-0.1.0.dist-info/WHEEL,sha256=VOHKyukui3UMeyUkkBf5F7N5xN_6X6W7zHVvalNVVvI,81
6
+ codenav_mcp-0.1.0.dist-info/entry_points.txt,sha256=ZVRKYiSqstzrpJn4Vg-yxPnQEIT7ZgOp8sBCxG8SRjM,57
7
+ codenav_mcp-0.1.0.dist-info/METADATA,sha256=lBzm7oAydg-RkYOtn01-QnLasqtAzpId__LzGdLikM4,5606
8
+ codenav_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.21
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ codenav-mcp = codenav_mcp.server:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Illescas Romero
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.