importlens-mcp 0.1.0__tar.gz
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.
- importlens_mcp-0.1.0/.claude/settings.local.json +9 -0
- importlens_mcp-0.1.0/.gitignore +14 -0
- importlens_mcp-0.1.0/LICENSE +21 -0
- importlens_mcp-0.1.0/PKG-INFO +123 -0
- importlens_mcp-0.1.0/README.md +107 -0
- importlens_mcp-0.1.0/docs/demo.gif +0 -0
- importlens_mcp-0.1.0/pyproject.toml +29 -0
- importlens_mcp-0.1.0/src/importlens_mcp/__init__.py +3 -0
- importlens_mcp-0.1.0/src/importlens_mcp/__main__.py +33 -0
- importlens_mcp-0.1.0/src/importlens_mcp/graph.py +170 -0
- importlens_mcp-0.1.0/src/importlens_mcp/server.py +161 -0
- importlens_mcp-0.1.0/tests/test_codeindex.py +117 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matheos
|
|
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.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: importlens-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Import-aware context for coding agents on Python repos. Feeds your agent only the files that matter, not the whole repo.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Matheos13/importlens-mcp
|
|
6
|
+
Project-URL: Issues, https://github.com/Matheos13/importlens-mcp/issues
|
|
7
|
+
Author-email: Matheos <mathaiou.agency@gmail.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agent,claude-code,codebase,context,llm,mcp,python
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: mcp>=1.2.0
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# importlens-mcp
|
|
18
|
+
|
|
19
|
+
**Stop feeding your coding agent the whole repo. Feed it the files that actually matter.**
|
|
20
|
+
|
|
21
|
+
importlens-mcp is a tiny [MCP](https://modelcontextprotocol.io) server that reads your Python project's *import graph* and hands your agent only the slice of code relevant to what it's working on — the file that defines a symbol, the files that use it, and the files it depends on. No embeddings, no vector DB, no re-reading the tree on every question.
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
npx-style one-liner for python: uvx importlens-mcp
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
> **Why:** on a big repo, agents burn tokens (and get confused) re-reading files that have nothing to do with the task. importlens-mcp answers *"which files matter for `UserService`?"* in one call, using nothing but Python's own `ast`.
|
|
28
|
+
|
|
29
|
+
<!-- TODO: drop a 10-second demo gif here before launch -->
|
|
30
|
+

|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
# with uv (recommended)
|
|
38
|
+
uvx importlens-mcp # run straight from PyPI, no install
|
|
39
|
+
|
|
40
|
+
# or pip
|
|
41
|
+
pip install importlens-mcp
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Add it to your agent. For(what I use) **Claude Code**:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
claude mcp add importlens-mcp -- uvx importlens-mcp
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
For any MCP client, point it at the `importlens-mcp` command (stdio transport). It indexes the current working directory by default, or set `IMPORTLENS_ROOT`.
|
|
51
|
+
|
|
52
|
+
## What your agent gets
|
|
53
|
+
|
|
54
|
+
Four tools, all returning plain readable text:
|
|
55
|
+
|
|
56
|
+
| tool | what it does |
|
|
57
|
+
|------|--------------|
|
|
58
|
+
| `project_map` | one-glance summary: files, modules, symbols, line count |
|
|
59
|
+
| `relevant_files(symbol)` | the files that define a symbol + its dependents + its dependencies |
|
|
60
|
+
| `file_context(path)` | one file's source plus the paths of its local imports |
|
|
61
|
+
| `reindex` | rebuild after you change files on disk |
|
|
62
|
+
|
|
63
|
+
### Example
|
|
64
|
+
|
|
65
|
+
Ask your agent *"how does `CodeIndex` fit together?"* and under the hood it calls:
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
relevant_files("CodeIndex")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
# Relevant files for `CodeIndex`
|
|
73
|
+
|
|
74
|
+
## Defined in
|
|
75
|
+
- src/importlens_mcp/graph.py
|
|
76
|
+
|
|
77
|
+
## Used by (dependents)
|
|
78
|
+
- src/importlens_mcp/__main__.py
|
|
79
|
+
- src/importlens_mcp/server.py
|
|
80
|
+
|
|
81
|
+
## Depends on (local imports)
|
|
82
|
+
- (none)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Three files instead of thirty. That's the whole idea.
|
|
86
|
+
|
|
87
|
+
## Quick look without an agent
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
importlens-mcp map .
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
importlens-mcp: 4 files, 4 modules, 10 symbols, 371 lines
|
|
95
|
+
importlens_mcp src/importlens_mcp/__init__.py
|
|
96
|
+
importlens_mcp.graph src/importlens_mcp/graph.py
|
|
97
|
+
importlens_mcp.server src/importlens_mcp/server.py
|
|
98
|
+
...
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## How it works
|
|
102
|
+
|
|
103
|
+
1. Walk the repo, skipping the usual noise (`.venv`, `node_modules`, `__pycache__`, …).
|
|
104
|
+
2. Parse each `.py` file with the standard-library `ast` module — top-level functions/classes become *symbols*, `import` statements become *edges*.
|
|
105
|
+
3. Build two maps: `symbol -> files that define it` and `module -> files that import it`.
|
|
106
|
+
4. Answer queries by walking those maps. No network, no model calls, runs in milliseconds.
|
|
107
|
+
|
|
108
|
+
Import resolution is best-effort and handles `src/` layouts and relative imports. It won't catch dynamic imports or runtime magic — and that's a fine tradeoff for a v0.
|
|
109
|
+
|
|
110
|
+
## Roadmap
|
|
111
|
+
|
|
112
|
+
- [ ] call-graph edges (who calls this function), not just imports
|
|
113
|
+
- [ ] respect `.gitignore`
|
|
114
|
+
- [ ] method-level symbols, not just top-level
|
|
115
|
+
- [ ] `tree-sitter` backend for speed on huge repos
|
|
116
|
+
|
|
117
|
+
## Contributing
|
|
118
|
+
|
|
119
|
+
It's ~370 lines of plain Python. Read it, break it, send a PR. Good first issues are labeled.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# importlens-mcp
|
|
2
|
+
|
|
3
|
+
**Stop feeding your coding agent the whole repo. Feed it the files that actually matter.**
|
|
4
|
+
|
|
5
|
+
importlens-mcp is a tiny [MCP](https://modelcontextprotocol.io) server that reads your Python project's *import graph* and hands your agent only the slice of code relevant to what it's working on — the file that defines a symbol, the files that use it, and the files it depends on. No embeddings, no vector DB, no re-reading the tree on every question.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
npx-style one-liner for python: uvx importlens-mcp
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
> **Why:** on a big repo, agents burn tokens (and get confused) re-reading files that have nothing to do with the task. importlens-mcp answers *"which files matter for `UserService`?"* in one call, using nothing but Python's own `ast`.
|
|
12
|
+
|
|
13
|
+
<!-- TODO: drop a 10-second demo gif here before launch -->
|
|
14
|
+

|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
# with uv (recommended)
|
|
22
|
+
uvx importlens-mcp # run straight from PyPI, no install
|
|
23
|
+
|
|
24
|
+
# or pip
|
|
25
|
+
pip install importlens-mcp
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Add it to your agent. For(what I use) **Claude Code**:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
claude mcp add importlens-mcp -- uvx importlens-mcp
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
For any MCP client, point it at the `importlens-mcp` command (stdio transport). It indexes the current working directory by default, or set `IMPORTLENS_ROOT`.
|
|
35
|
+
|
|
36
|
+
## What your agent gets
|
|
37
|
+
|
|
38
|
+
Four tools, all returning plain readable text:
|
|
39
|
+
|
|
40
|
+
| tool | what it does |
|
|
41
|
+
|------|--------------|
|
|
42
|
+
| `project_map` | one-glance summary: files, modules, symbols, line count |
|
|
43
|
+
| `relevant_files(symbol)` | the files that define a symbol + its dependents + its dependencies |
|
|
44
|
+
| `file_context(path)` | one file's source plus the paths of its local imports |
|
|
45
|
+
| `reindex` | rebuild after you change files on disk |
|
|
46
|
+
|
|
47
|
+
### Example
|
|
48
|
+
|
|
49
|
+
Ask your agent *"how does `CodeIndex` fit together?"* and under the hood it calls:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
relevant_files("CodeIndex")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
# Relevant files for `CodeIndex`
|
|
57
|
+
|
|
58
|
+
## Defined in
|
|
59
|
+
- src/importlens_mcp/graph.py
|
|
60
|
+
|
|
61
|
+
## Used by (dependents)
|
|
62
|
+
- src/importlens_mcp/__main__.py
|
|
63
|
+
- src/importlens_mcp/server.py
|
|
64
|
+
|
|
65
|
+
## Depends on (local imports)
|
|
66
|
+
- (none)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Three files instead of thirty. That's the whole idea.
|
|
70
|
+
|
|
71
|
+
## Quick look without an agent
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
importlens-mcp map .
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
importlens-mcp: 4 files, 4 modules, 10 symbols, 371 lines
|
|
79
|
+
importlens_mcp src/importlens_mcp/__init__.py
|
|
80
|
+
importlens_mcp.graph src/importlens_mcp/graph.py
|
|
81
|
+
importlens_mcp.server src/importlens_mcp/server.py
|
|
82
|
+
...
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## How it works
|
|
86
|
+
|
|
87
|
+
1. Walk the repo, skipping the usual noise (`.venv`, `node_modules`, `__pycache__`, …).
|
|
88
|
+
2. Parse each `.py` file with the standard-library `ast` module — top-level functions/classes become *symbols*, `import` statements become *edges*.
|
|
89
|
+
3. Build two maps: `symbol -> files that define it` and `module -> files that import it`.
|
|
90
|
+
4. Answer queries by walking those maps. No network, no model calls, runs in milliseconds.
|
|
91
|
+
|
|
92
|
+
Import resolution is best-effort and handles `src/` layouts and relative imports. It won't catch dynamic imports or runtime magic — and that's a fine tradeoff for a v0.
|
|
93
|
+
|
|
94
|
+
## Roadmap
|
|
95
|
+
|
|
96
|
+
- [ ] call-graph edges (who calls this function), not just imports
|
|
97
|
+
- [ ] respect `.gitignore`
|
|
98
|
+
- [ ] method-level symbols, not just top-level
|
|
99
|
+
- [ ] `tree-sitter` backend for speed on huge repos
|
|
100
|
+
|
|
101
|
+
## Contributing
|
|
102
|
+
|
|
103
|
+
It's ~370 lines of plain Python. Read it, break it, send a PR. Good first issues are labeled.
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
|
Binary file
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "importlens-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Import-aware context for coding agents on Python repos. Feeds your agent only the files that matter, not the whole repo."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = { text = "MIT" }
|
|
8
|
+
authors = [{ name = "Matheos", email = "mathaiou.agency@gmail.com" }]
|
|
9
|
+
keywords = ["mcp", "claude-code", "agent", "python", "codebase", "context", "llm"]
|
|
10
|
+
dependencies = [
|
|
11
|
+
"mcp>=1.2.0",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
importlens-mcp = "importlens_mcp.__main__:main"
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://github.com/Matheos13/importlens-mcp"
|
|
19
|
+
Issues = "https://github.com/Matheos13/importlens-mcp/issues"
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = ["pytest>=7"]
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["hatchling"]
|
|
26
|
+
build-backend = "hatchling.build"
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/importlens_mcp"]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Entry point: `importlens-mcp` runs the MCP server over stdio.
|
|
2
|
+
|
|
3
|
+
`importlens-mcp map [path]` prints the project map to the terminal — handy for a
|
|
4
|
+
quick look or a README gif without wiring up an agent.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def main() -> None:
|
|
14
|
+
args = sys.argv[1:]
|
|
15
|
+
if args and args[0] == "map":
|
|
16
|
+
from .graph import CodeIndex
|
|
17
|
+
root = args[1] if len(args) > 1 else "."
|
|
18
|
+
idx = CodeIndex(root).build()
|
|
19
|
+
s = idx.stats()
|
|
20
|
+
print(f"importlens-mcp: {s['files']} files, {s['modules']} modules, "
|
|
21
|
+
f"{s['symbols']} symbols, {s['total_lines']} lines")
|
|
22
|
+
for mod, path in sorted(idx.module_to_path.items()):
|
|
23
|
+
print(f" {mod:<40} {path}")
|
|
24
|
+
return
|
|
25
|
+
|
|
26
|
+
# Default: run the MCP server. Index the cwd unless told otherwise.
|
|
27
|
+
os.environ.setdefault("IMPORTLENS_ROOT", os.getcwd())
|
|
28
|
+
from .server import run
|
|
29
|
+
run()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
if __name__ == "__main__":
|
|
33
|
+
main()
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Build an import graph of a Python project using the standard-library ast module.
|
|
2
|
+
|
|
3
|
+
No third-party parsers, no embeddings, no magic. Just walk the tree, parse each
|
|
4
|
+
file, and record who defines what and who imports what. That graph is enough to
|
|
5
|
+
answer "which files actually matter for this symbol?" without dumping the repo.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
# Directories we never want to crawl. These are noise for an agent.
|
|
15
|
+
IGNORE_DIRS = {
|
|
16
|
+
".git", ".hg", ".svn", "__pycache__", ".venv", "venv", "env",
|
|
17
|
+
"node_modules", "build", "dist", ".mypy_cache", ".pytest_cache",
|
|
18
|
+
".ruff_cache", ".tox", "site-packages", ".eggs",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class FileInfo:
|
|
24
|
+
"""What we learned from one .py file."""
|
|
25
|
+
path: str # repo-relative path, posix style
|
|
26
|
+
module: str # dotted module name, e.g. importlens_mcp.graph
|
|
27
|
+
defines: set[str] = field(default_factory=set) # top-level func/class names
|
|
28
|
+
imports: set[str] = field(default_factory=set) # dotted modules it imports
|
|
29
|
+
lines: int = 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CodeIndex:
|
|
33
|
+
"""An index of a Python project: symbols, modules, and the import graph."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, root: str):
|
|
36
|
+
self.root = os.path.abspath(root)
|
|
37
|
+
self.files: dict[str, FileInfo] = {} # path -> FileInfo
|
|
38
|
+
self.module_to_path: dict[str, str] = {} # dotted module -> path
|
|
39
|
+
self.symbol_to_paths: dict[str, set[str]] = {} # name -> defining paths
|
|
40
|
+
self._built = False
|
|
41
|
+
|
|
42
|
+
# ---- building -------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
def build(self) -> "CodeIndex":
|
|
45
|
+
for path in self._walk():
|
|
46
|
+
info = self._parse(path)
|
|
47
|
+
if info is None:
|
|
48
|
+
continue
|
|
49
|
+
self.files[info.path] = info
|
|
50
|
+
self.module_to_path[info.module] = info.path
|
|
51
|
+
for name in info.defines:
|
|
52
|
+
self.symbol_to_paths.setdefault(name, set()).add(info.path)
|
|
53
|
+
self._built = True
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
def _walk(self):
|
|
57
|
+
for dirpath, dirnames, filenames in os.walk(self.root):
|
|
58
|
+
dirnames[:] = [d for d in dirnames if d not in IGNORE_DIRS]
|
|
59
|
+
for fn in filenames:
|
|
60
|
+
if fn.endswith(".py"):
|
|
61
|
+
yield os.path.join(dirpath, fn)
|
|
62
|
+
|
|
63
|
+
def _rel(self, abspath: str) -> str:
|
|
64
|
+
return os.path.relpath(abspath, self.root).replace(os.sep, "/")
|
|
65
|
+
|
|
66
|
+
def _module_name(self, rel: str) -> str:
|
|
67
|
+
parts = rel[:-3].split("/") # drop .py
|
|
68
|
+
if parts and parts[-1] == "__init__":
|
|
69
|
+
parts = parts[:-1]
|
|
70
|
+
# a leading src/ is a layout convention, not part of the module path
|
|
71
|
+
if parts and parts[0] == "src":
|
|
72
|
+
parts = parts[1:]
|
|
73
|
+
return ".".join(parts)
|
|
74
|
+
|
|
75
|
+
def _parse(self, abspath: str) -> FileInfo | None:
|
|
76
|
+
rel = self._rel(abspath)
|
|
77
|
+
try:
|
|
78
|
+
with open(abspath, "r", encoding="utf-8") as fh:
|
|
79
|
+
source = fh.read()
|
|
80
|
+
except (OSError, UnicodeDecodeError):
|
|
81
|
+
return None
|
|
82
|
+
try:
|
|
83
|
+
tree = ast.parse(source, filename=rel)
|
|
84
|
+
except SyntaxError:
|
|
85
|
+
# A file we can't parse still exists; record it with no detail.
|
|
86
|
+
return FileInfo(path=rel, module=self._module_name(rel),
|
|
87
|
+
lines=source.count("\n") + 1)
|
|
88
|
+
|
|
89
|
+
info = FileInfo(path=rel, module=self._module_name(rel),
|
|
90
|
+
lines=source.count("\n") + 1)
|
|
91
|
+
for node in tree.body:
|
|
92
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
93
|
+
info.defines.add(node.name)
|
|
94
|
+
for node in ast.walk(tree):
|
|
95
|
+
if isinstance(node, ast.Import):
|
|
96
|
+
for alias in node.names:
|
|
97
|
+
info.imports.add(alias.name)
|
|
98
|
+
elif isinstance(node, ast.ImportFrom):
|
|
99
|
+
if node.module and node.level == 0:
|
|
100
|
+
info.imports.add(node.module)
|
|
101
|
+
elif node.level:
|
|
102
|
+
# relative import: resolve against this file's package
|
|
103
|
+
info.imports.add(self._resolve_relative(info.module, node))
|
|
104
|
+
return info
|
|
105
|
+
|
|
106
|
+
def _resolve_relative(self, module: str, node: ast.ImportFrom) -> str:
|
|
107
|
+
pkg_parts = module.split(".")[:-1] # package of current module
|
|
108
|
+
if node.level > 1:
|
|
109
|
+
pkg_parts = pkg_parts[: -(node.level - 1)] or []
|
|
110
|
+
base = ".".join(pkg_parts)
|
|
111
|
+
if node.module:
|
|
112
|
+
return f"{base}.{node.module}" if base else node.module
|
|
113
|
+
return base
|
|
114
|
+
|
|
115
|
+
# ---- querying -------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
def local_imports(self, path: str) -> list[str]:
|
|
118
|
+
"""Imports of `path` that resolve to files inside this project."""
|
|
119
|
+
info = self.files.get(path)
|
|
120
|
+
if not info:
|
|
121
|
+
return []
|
|
122
|
+
out = []
|
|
123
|
+
for mod in info.imports:
|
|
124
|
+
resolved = self._resolve_module(mod)
|
|
125
|
+
if resolved and resolved != path:
|
|
126
|
+
out.append(resolved)
|
|
127
|
+
return sorted(set(out))
|
|
128
|
+
|
|
129
|
+
def _resolve_module(self, dotted: str) -> str | None:
|
|
130
|
+
"""Best-effort map a dotted import to a local file path."""
|
|
131
|
+
if dotted in self.module_to_path:
|
|
132
|
+
return self.module_to_path[dotted]
|
|
133
|
+
# `from pkg.mod import thing` — thing may be a symbol, not a module,
|
|
134
|
+
# so also try the parent module.
|
|
135
|
+
parent = dotted.rsplit(".", 1)[0]
|
|
136
|
+
if parent in self.module_to_path:
|
|
137
|
+
return self.module_to_path[parent]
|
|
138
|
+
# suffix match for odd layouts (src/, namespace packages, etc.)
|
|
139
|
+
for mod, path in self.module_to_path.items():
|
|
140
|
+
if mod.endswith("." + dotted) or mod == dotted:
|
|
141
|
+
return path
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
def dependents(self, path: str) -> list[str]:
|
|
145
|
+
"""Files that import the module defined by `path`."""
|
|
146
|
+
info = self.files.get(path)
|
|
147
|
+
if not info:
|
|
148
|
+
return []
|
|
149
|
+
target = info.module
|
|
150
|
+
out = []
|
|
151
|
+
for other_path, other in self.files.items():
|
|
152
|
+
if other_path == path:
|
|
153
|
+
continue
|
|
154
|
+
for mod in other.imports:
|
|
155
|
+
if mod == target or mod.startswith(target + ".") \
|
|
156
|
+
or target.endswith("." + mod):
|
|
157
|
+
out.append(other_path)
|
|
158
|
+
break
|
|
159
|
+
return sorted(set(out))
|
|
160
|
+
|
|
161
|
+
def find_symbol(self, name: str) -> list[str]:
|
|
162
|
+
return sorted(self.symbol_to_paths.get(name, set()))
|
|
163
|
+
|
|
164
|
+
def stats(self) -> dict:
|
|
165
|
+
return {
|
|
166
|
+
"files": len(self.files),
|
|
167
|
+
"modules": len(self.module_to_path),
|
|
168
|
+
"symbols": len(self.symbol_to_paths),
|
|
169
|
+
"total_lines": sum(f.lines for f in self.files.values()),
|
|
170
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""importlens-mcp MCP server.
|
|
2
|
+
|
|
3
|
+
Exposes a handful of tools that let a coding agent pull *just* the relevant
|
|
4
|
+
slice of a Python repo into context, instead of re-reading the whole tree.
|
|
5
|
+
|
|
6
|
+
Tools:
|
|
7
|
+
- project_map : one-glance summary of the repo
|
|
8
|
+
- relevant_files : given a symbol, return the files that matter for it
|
|
9
|
+
- file_context : a file plus its local dependencies, ready to read
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
|
|
16
|
+
from .graph import CodeIndex
|
|
17
|
+
|
|
18
|
+
# The MCP Python SDK renamed FastMCP -> MCPServer in v2. Support both so the
|
|
19
|
+
# server runs whether the user is on the old or new SDK.
|
|
20
|
+
try:
|
|
21
|
+
from mcp.server.mcpserver import MCPServer as _Server # SDK v2+
|
|
22
|
+
except ModuleNotFoundError: # pragma: no cover - depends on installed version
|
|
23
|
+
from mcp.server.fastmcp import FastMCP as _Server # SDK v1
|
|
24
|
+
|
|
25
|
+
mcp = _Server("importlens-mcp")
|
|
26
|
+
|
|
27
|
+
_ROOT = os.environ.get("IMPORTLENS_ROOT", os.getcwd())
|
|
28
|
+
_index: CodeIndex | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _get_index(refresh: bool = False) -> CodeIndex:
|
|
32
|
+
global _index
|
|
33
|
+
if _index is None or refresh:
|
|
34
|
+
_index = CodeIndex(_ROOT).build()
|
|
35
|
+
return _index
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _read(path: str, max_lines: int = 400) -> str:
|
|
39
|
+
abspath = os.path.join(_ROOT, path)
|
|
40
|
+
try:
|
|
41
|
+
with open(abspath, "r", encoding="utf-8") as fh:
|
|
42
|
+
lines = fh.read().splitlines()
|
|
43
|
+
except (OSError, UnicodeDecodeError):
|
|
44
|
+
return f"[could not read {path}]"
|
|
45
|
+
if len(lines) > max_lines:
|
|
46
|
+
body = "\n".join(lines[:max_lines])
|
|
47
|
+
return f"{body}\n... [truncated, {len(lines) - max_lines} more lines]"
|
|
48
|
+
return "\n".join(lines)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@mcp.tool()
|
|
52
|
+
def project_map() -> str:
|
|
53
|
+
"""Summarize the Python project: file count, modules, symbols, lines.
|
|
54
|
+
|
|
55
|
+
Call this first to understand the shape of the repo before drilling in.
|
|
56
|
+
"""
|
|
57
|
+
idx = _get_index()
|
|
58
|
+
s = idx.stats()
|
|
59
|
+
lines = [
|
|
60
|
+
f"# Project map ({os.path.basename(_ROOT) or _ROOT})",
|
|
61
|
+
"",
|
|
62
|
+
f"- files: {s['files']}",
|
|
63
|
+
f"- modules: {s['modules']}",
|
|
64
|
+
f"- top-level symbols: {s['symbols']}",
|
|
65
|
+
f"- total lines: {s['total_lines']}",
|
|
66
|
+
"",
|
|
67
|
+
"## Modules",
|
|
68
|
+
]
|
|
69
|
+
for mod, path in sorted(idx.module_to_path.items()):
|
|
70
|
+
lines.append(f"- `{mod}` -> {path}")
|
|
71
|
+
return "\n".join(lines)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@mcp.tool()
|
|
75
|
+
def relevant_files(symbol: str, include_source: bool = False) -> str:
|
|
76
|
+
"""Find the files that matter for a given symbol (function or class name).
|
|
77
|
+
|
|
78
|
+
Returns the file(s) that define it, the files that import those modules
|
|
79
|
+
(dependents), and the local modules they depend on. This is the slice of
|
|
80
|
+
the repo an agent needs to reason about `symbol` — usually a handful of
|
|
81
|
+
files instead of the whole tree.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
symbol: a top-level function or class name, e.g. "CodeIndex".
|
|
85
|
+
include_source: if true, also inline the defining files' source.
|
|
86
|
+
"""
|
|
87
|
+
idx = _get_index()
|
|
88
|
+
defs = idx.find_symbol(symbol)
|
|
89
|
+
if not defs:
|
|
90
|
+
return (f"No top-level definition of `{symbol}` found. "
|
|
91
|
+
"Try project_map to see available symbols.")
|
|
92
|
+
|
|
93
|
+
out = [f"# Relevant files for `{symbol}`", ""]
|
|
94
|
+
seen: set[str] = set()
|
|
95
|
+
|
|
96
|
+
out.append("## Defined in")
|
|
97
|
+
for path in defs:
|
|
98
|
+
out.append(f"- {path}")
|
|
99
|
+
seen.add(path)
|
|
100
|
+
|
|
101
|
+
deps: set[str] = set()
|
|
102
|
+
dependents: set[str] = set()
|
|
103
|
+
for path in defs:
|
|
104
|
+
deps.update(idx.local_imports(path))
|
|
105
|
+
dependents.update(idx.dependents(path))
|
|
106
|
+
|
|
107
|
+
if dependents:
|
|
108
|
+
out.append("\n## Used by (dependents)")
|
|
109
|
+
for path in sorted(dependents - seen):
|
|
110
|
+
out.append(f"- {path}")
|
|
111
|
+
seen.add(path)
|
|
112
|
+
|
|
113
|
+
if deps:
|
|
114
|
+
out.append("\n## Depends on (local imports)")
|
|
115
|
+
for path in sorted(deps - set(defs)):
|
|
116
|
+
out.append(f"- {path}")
|
|
117
|
+
|
|
118
|
+
if include_source:
|
|
119
|
+
out.append("\n## Source of defining files")
|
|
120
|
+
for path in defs:
|
|
121
|
+
out.append(f"\n### {path}\n```python\n{_read(path)}\n```")
|
|
122
|
+
|
|
123
|
+
return "\n".join(out)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@mcp.tool()
|
|
127
|
+
def file_context(path: str) -> str:
|
|
128
|
+
"""Return a file's source plus the paths of its local dependencies.
|
|
129
|
+
|
|
130
|
+
Use this to read one file with awareness of what it pulls in, without
|
|
131
|
+
loading the whole project.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
path: repo-relative path, e.g. "src/importlens_mcp/server.py".
|
|
135
|
+
"""
|
|
136
|
+
idx = _get_index()
|
|
137
|
+
deps = idx.local_imports(path)
|
|
138
|
+
header = [f"# {path}", ""]
|
|
139
|
+
if deps:
|
|
140
|
+
header.append("Local dependencies:")
|
|
141
|
+
header.extend(f"- {d}" for d in deps)
|
|
142
|
+
else:
|
|
143
|
+
header.append("Local dependencies: none")
|
|
144
|
+
header.append("\n## Source\n```python")
|
|
145
|
+
return "\n".join(header) + "\n" + _read(path) + "\n```"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@mcp.tool()
|
|
149
|
+
def reindex() -> str:
|
|
150
|
+
"""Rebuild the index. Call after you've changed files on disk."""
|
|
151
|
+
idx = _get_index(refresh=True)
|
|
152
|
+
s = idx.stats()
|
|
153
|
+
return f"Reindexed: {s['files']} files, {s['symbols']} symbols."
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def run() -> None:
|
|
157
|
+
mcp.run()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
if __name__ == "__main__":
|
|
161
|
+
run()
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Tests for CodeIndex: modules, symbols, dependents, local imports, and CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import textwrap
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from importlens_mcp.graph import CodeIndex
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture()
|
|
15
|
+
def fake_repo(tmp_path):
|
|
16
|
+
"""Minimal two-file Python project: utils.py + main.py that imports from it."""
|
|
17
|
+
(tmp_path / "utils.py").write_text(textwrap.dedent("""\
|
|
18
|
+
def helper():
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
class Config:
|
|
22
|
+
pass
|
|
23
|
+
"""))
|
|
24
|
+
(tmp_path / "main.py").write_text(textwrap.dedent("""\
|
|
25
|
+
from utils import helper
|
|
26
|
+
|
|
27
|
+
def run():
|
|
28
|
+
helper()
|
|
29
|
+
"""))
|
|
30
|
+
return tmp_path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---- module discovery -------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
def test_modules_found(fake_repo):
|
|
36
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
37
|
+
assert "utils" in idx.module_to_path
|
|
38
|
+
assert "main" in idx.module_to_path
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_module_paths_are_relative(fake_repo):
|
|
42
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
43
|
+
assert idx.module_to_path["utils"] == "utils.py"
|
|
44
|
+
assert idx.module_to_path["main"] == "main.py"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# ---- symbol discovery -------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
def test_symbols_found(fake_repo):
|
|
50
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
51
|
+
assert "helper" in idx.symbol_to_paths
|
|
52
|
+
assert "Config" in idx.symbol_to_paths
|
|
53
|
+
assert "run" in idx.symbol_to_paths
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_symbol_resolves_to_correct_file(fake_repo):
|
|
57
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
58
|
+
assert idx.symbol_to_paths["helper"] == {"utils.py"}
|
|
59
|
+
assert idx.symbol_to_paths["Config"] == {"utils.py"}
|
|
60
|
+
assert idx.symbol_to_paths["run"] == {"main.py"}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# ---- local imports ----------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
def test_local_imports(fake_repo):
|
|
66
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
67
|
+
assert "utils.py" in idx.local_imports("main.py")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_no_local_imports_for_leaf(fake_repo):
|
|
71
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
72
|
+
assert idx.local_imports("utils.py") == []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ---- dependents -------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
def test_dependents(fake_repo):
|
|
78
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
79
|
+
assert "main.py" in idx.dependents("utils.py")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_no_dependents_for_root(fake_repo):
|
|
83
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
84
|
+
assert idx.dependents("main.py") == []
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ---- stats ------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
def test_stats(fake_repo):
|
|
90
|
+
idx = CodeIndex(str(fake_repo)).build()
|
|
91
|
+
s = idx.stats()
|
|
92
|
+
assert s["files"] == 2
|
|
93
|
+
assert s["modules"] == 2
|
|
94
|
+
assert s["symbols"] >= 3 # helper, Config, run
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ---- CLI: importlens-mcp map ------------------------------------------------
|
|
98
|
+
|
|
99
|
+
def test_map_cli_runs(fake_repo):
|
|
100
|
+
result = subprocess.run(
|
|
101
|
+
[sys.executable, "-m", "importlens_mcp", "map", str(fake_repo)],
|
|
102
|
+
capture_output=True,
|
|
103
|
+
text=True,
|
|
104
|
+
)
|
|
105
|
+
assert result.returncode == 0
|
|
106
|
+
assert "files" in result.stdout
|
|
107
|
+
assert "modules" in result.stdout
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_map_cli_lists_modules(fake_repo):
|
|
111
|
+
result = subprocess.run(
|
|
112
|
+
[sys.executable, "-m", "importlens_mcp", "map", str(fake_repo)],
|
|
113
|
+
capture_output=True,
|
|
114
|
+
text=True,
|
|
115
|
+
)
|
|
116
|
+
assert "utils" in result.stdout
|
|
117
|
+
assert "main" in result.stdout
|