depradar 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.
- depradar/__init__.py +3 -0
- depradar/agent.py +96 -0
- depradar/cli.py +161 -0
- depradar/generator.py +19 -0
- depradar/graph.py +57 -0
- depradar/mcp.py +221 -0
- depradar/models.py +47 -0
- depradar/scanners/base.py +76 -0
- depradar/scanners/code_scanner.py +216 -0
- depradar/scanners/node_scanner.py +93 -0
- depradar/scanners/project_scanner.py +193 -0
- depradar/scanners/python_scanner.py +214 -0
- depradar/scanners/system_scanner.py +558 -0
- depradar/templates/viewer.html +1134 -0
- depradar-0.1.0.dist-info/METADATA +234 -0
- depradar-0.1.0.dist-info/RECORD +19 -0
- depradar-0.1.0.dist-info/WHEEL +4 -0
- depradar-0.1.0.dist-info/entry_points.txt +2 -0
- depradar-0.1.0.dist-info/licenses/LICENSE +21 -0
depradar/__init__.py
ADDED
depradar/agent.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""AI Agent Integration Utilities for DepRadar.
|
|
2
|
+
Provides prompt-ready Markdown contexts, dependency queries, and CLI helpers.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import platform
|
|
6
|
+
from typing import List, Dict, Any
|
|
7
|
+
from .models import GraphData, Node
|
|
8
|
+
|
|
9
|
+
def generate_agent_context(graph: GraphData) -> str:
|
|
10
|
+
"""Generates a compact, high-value Markdown briefing for an AI agent's system prompt or context window."""
|
|
11
|
+
os_name = platform.system()
|
|
12
|
+
nodes = graph.nodes
|
|
13
|
+
runtimes = [n for n in nodes if n.type == "runtime"]
|
|
14
|
+
venvs = [n for n in nodes if n.type == "python-venv"]
|
|
15
|
+
projects = [n for n in nodes if n.type == "project"]
|
|
16
|
+
heavy = sorted(nodes, key=lambda x: x.size_bytes, reverse=True)[:5]
|
|
17
|
+
stale = [n for n in nodes if n.status == "stale"]
|
|
18
|
+
|
|
19
|
+
lines = [
|
|
20
|
+
"# System & Environment Context (Generated by DepRadar)",
|
|
21
|
+
f"**Host OS**: {os_name} {platform.release()} ({platform.machine()})",
|
|
22
|
+
f"**Total Tracked Components**: {len(nodes)} nodes | {len(graph.links)} dependency connections",
|
|
23
|
+
"",
|
|
24
|
+
"## Active Host Runtimes & Interpreters",
|
|
25
|
+
]
|
|
26
|
+
for r in runtimes:
|
|
27
|
+
lines.append(f"- **{r.name}** (`{r.path}`): {r.notes}")
|
|
28
|
+
|
|
29
|
+
lines.append("\n## Detected Developer Workspaces & Projects")
|
|
30
|
+
for p in projects:
|
|
31
|
+
lines.append(f"- **{p.name}** (`{p.path}`): [{p.category}] {p.notes}")
|
|
32
|
+
|
|
33
|
+
lines.append("\n## Python Virtual Environments")
|
|
34
|
+
for v in venvs:
|
|
35
|
+
pkg_cnt = len(v.installed_packages) if v.installed_packages else "Unknown"
|
|
36
|
+
lines.append(f"- **{v.name}** (`{v.path}`): {v.size_human} | {pkg_cnt} installed packages | Status: `{v.status}`")
|
|
37
|
+
|
|
38
|
+
lines.append("\n## Top Disk Consumers")
|
|
39
|
+
for h in heavy:
|
|
40
|
+
lines.append(f"- **{h.name}**: {h.size_human} (`{h.path}`)")
|
|
41
|
+
|
|
42
|
+
if stale:
|
|
43
|
+
lines.append("\n## Stale / Cleanup Candidates")
|
|
44
|
+
for s in stale:
|
|
45
|
+
cmd = s.uninstall_cmd or f"rm -rf '{s.path}'"
|
|
46
|
+
lines.append(f"- **{s.name}** ({s.size_human}, {s.days_inactive}d inactive) -> Cleanup: `{cmd}`")
|
|
47
|
+
|
|
48
|
+
lines.append("\n*To query individual package details, run: `depradar query <package_name> --json`*")
|
|
49
|
+
return "\n".join(lines)
|
|
50
|
+
|
|
51
|
+
def query_dependencies(graph: GraphData, term: str) -> List[Dict[str, Any]]:
|
|
52
|
+
"""Searches graph for matching nodes and returns connectivity context."""
|
|
53
|
+
q = term.lower().strip()
|
|
54
|
+
results = []
|
|
55
|
+
for n in graph.nodes:
|
|
56
|
+
name_match = q in n.name.lower() or q in n.id.lower() or q in n.notes.lower()
|
|
57
|
+
pkg_match = any(q in p.get("name", "").lower() for p in n.installed_packages) if n.installed_packages else False
|
|
58
|
+
if name_match or pkg_match:
|
|
59
|
+
# Upstream & Downstream
|
|
60
|
+
up = [
|
|
61
|
+
{"source": (l.source if isinstance(l.source, str) else l.source.id), "rel": l.relationship, "desc": l.description}
|
|
62
|
+
for l in graph.links if (l.target == n.id or (isinstance(l.target, dict) and l.target.get("id") == n.id))
|
|
63
|
+
]
|
|
64
|
+
down = [
|
|
65
|
+
{"target": (l.target if isinstance(l.target, str) else l.target.id), "rel": l.relationship, "desc": l.description}
|
|
66
|
+
for l in graph.links if (l.source == n.id or (isinstance(l.source, dict) and l.source.get("id") == n.id))
|
|
67
|
+
]
|
|
68
|
+
results.append({
|
|
69
|
+
"name": n.name,
|
|
70
|
+
"id": n.id,
|
|
71
|
+
"category": n.category,
|
|
72
|
+
"type": n.type,
|
|
73
|
+
"status": n.status,
|
|
74
|
+
"size": n.size_human,
|
|
75
|
+
"path": n.path,
|
|
76
|
+
"notes": n.notes,
|
|
77
|
+
"required_by": up,
|
|
78
|
+
"requires": down,
|
|
79
|
+
"installed_packages": n.installed_packages[:15] if n.installed_packages else []
|
|
80
|
+
})
|
|
81
|
+
return results
|
|
82
|
+
|
|
83
|
+
def get_stale_items(graph: GraphData) -> List[Dict[str, Any]]:
|
|
84
|
+
"""Returns all stale/orphan items and cleanup commands."""
|
|
85
|
+
return [
|
|
86
|
+
{
|
|
87
|
+
"name": n.name,
|
|
88
|
+
"category": n.category,
|
|
89
|
+
"type": n.type,
|
|
90
|
+
"size": n.size_human,
|
|
91
|
+
"path": n.path,
|
|
92
|
+
"days_inactive": n.days_inactive,
|
|
93
|
+
"cleanup_cmd": n.uninstall_cmd or f"rm -rf '{n.path}'"
|
|
94
|
+
}
|
|
95
|
+
for n in graph.nodes if n.status == "stale"
|
|
96
|
+
]
|
depradar/cli.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Command-line interface for DepRadar.
|
|
2
|
+
Supports interactive visualization, cross-platform execution (Linux, macOS, Windows),
|
|
3
|
+
and AI Agent integrations (JSON output, query engine, stale package cleanup, and MCP server).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
import json
|
|
8
|
+
import argparse
|
|
9
|
+
import platform
|
|
10
|
+
import webbrowser
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from .graph import build_graph
|
|
13
|
+
from .generator import generate_html
|
|
14
|
+
from .agent import generate_agent_context, query_dependencies, get_stale_items
|
|
15
|
+
from .mcp import run_mcp_server
|
|
16
|
+
|
|
17
|
+
def get_default_output_dir() -> Path:
|
|
18
|
+
"""Returns cross-platform configuration and output directory."""
|
|
19
|
+
home = Path.home()
|
|
20
|
+
if platform.system() == "Windows":
|
|
21
|
+
appdata = Path(home / "AppData" / "Roaming")
|
|
22
|
+
return appdata / "depradar" if appdata.exists() else home / ".depradar"
|
|
23
|
+
elif platform.system() == "Darwin":
|
|
24
|
+
app_sup = home / "Library" / "Application Support"
|
|
25
|
+
return app_sup / "depradar" if app_sup.exists() else home / ".config" / "depradar"
|
|
26
|
+
else:
|
|
27
|
+
return home / ".config" / "depradar"
|
|
28
|
+
|
|
29
|
+
DEFAULT_OUTPUT_DIR = get_default_output_dir()
|
|
30
|
+
DEFAULT_HTML_PATH = DEFAULT_OUTPUT_DIR / "depradar_graph.html"
|
|
31
|
+
|
|
32
|
+
def main():
|
|
33
|
+
parser = argparse.ArgumentParser(
|
|
34
|
+
prog="depradar",
|
|
35
|
+
description="DepRadar: Cross-Platform System & Package Dependency Radar for Developers and AI Agents"
|
|
36
|
+
)
|
|
37
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
38
|
+
|
|
39
|
+
# scan
|
|
40
|
+
p_scan = subparsers.add_parser("scan", help="Scan system and generate interactive network graph")
|
|
41
|
+
p_scan.add_argument("-o", "--output", help="Output HTML file path")
|
|
42
|
+
p_scan.add_argument("--open", action="store_true", help="Automatically open graph in default browser")
|
|
43
|
+
p_scan.add_argument("--json", action="store_true", help="Print structured graph JSON to stdout (for AI agents)")
|
|
44
|
+
|
|
45
|
+
# query
|
|
46
|
+
p_query = subparsers.add_parser("query", help="Query a package, library, or tool to inspect dependencies and usage")
|
|
47
|
+
p_query.add_argument("term", help="Name or keyword to search (e.g. 'selenium', 'zarr', 'docker')")
|
|
48
|
+
p_query.add_argument("--json", action="store_true", help="Output machine-readable JSON for AI agents")
|
|
49
|
+
|
|
50
|
+
# stale
|
|
51
|
+
p_stale = subparsers.add_parser("stale", help="List stale, orphaned, and unused packages with cleanup commands")
|
|
52
|
+
p_stale.add_argument("--json", action="store_true", help="Output machine-readable JSON for AI agents")
|
|
53
|
+
|
|
54
|
+
# agent-context
|
|
55
|
+
p_ctx = subparsers.add_parser("agent-context", help="Export compact Markdown system context for AI agents")
|
|
56
|
+
p_ctx.add_argument("-o", "--output", help="Output Markdown file path (prints to stdout if omitted)")
|
|
57
|
+
|
|
58
|
+
# mcp
|
|
59
|
+
p_mcp = subparsers.add_parser("mcp", help="Run Model Context Protocol (MCP) server over stdio for AI agents")
|
|
60
|
+
|
|
61
|
+
# export
|
|
62
|
+
p_exp = subparsers.add_parser("export", help="Export dependency graph as JSON")
|
|
63
|
+
p_exp.add_argument("-o", "--output", help="Output JSON file path")
|
|
64
|
+
|
|
65
|
+
args = parser.parse_args()
|
|
66
|
+
|
|
67
|
+
# Default action: run scan and print quick summary
|
|
68
|
+
if args.command is None:
|
|
69
|
+
cmd_args = sys.argv[1:]
|
|
70
|
+
if not cmd_args:
|
|
71
|
+
print(f"🚀 DepRadar: Scanning your system ({platform.system()} {platform.machine()})...")
|
|
72
|
+
graph = build_graph()
|
|
73
|
+
out_file = generate_html(graph, DEFAULT_HTML_PATH)
|
|
74
|
+
print(f"✅ Generated interactive graph: {out_file}")
|
|
75
|
+
print(f"📊 Discovered {len(graph.nodes)} nodes and {len(graph.links)} connections ({graph.metadata['total_stale']} stale).")
|
|
76
|
+
print("💡 Tip: AI agents can run `depradar scan --json`, `depradar query <name>`, or `depradar mcp`")
|
|
77
|
+
webbrowser.open(f"file://{out_file.resolve()}")
|
|
78
|
+
return
|
|
79
|
+
else:
|
|
80
|
+
parser.print_help()
|
|
81
|
+
return
|
|
82
|
+
|
|
83
|
+
if args.command == "scan":
|
|
84
|
+
graph = build_graph()
|
|
85
|
+
if getattr(args, "json", False):
|
|
86
|
+
print(json.dumps(graph.to_dict(), indent=2))
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
out_path = Path(args.output) if args.output else DEFAULT_HTML_PATH
|
|
90
|
+
out_file = generate_html(graph, out_path)
|
|
91
|
+
print(f"✅ Interactive graph generated at: {out_file}")
|
|
92
|
+
print(f"📊 Summary: {len(graph.nodes)} nodes, {len(graph.links)} links, {graph.metadata['total_stale']} stale items.")
|
|
93
|
+
|
|
94
|
+
if getattr(args, "open", False):
|
|
95
|
+
print("🌐 Opening in your web browser...")
|
|
96
|
+
webbrowser.open(f"file://{out_file.resolve()}")
|
|
97
|
+
|
|
98
|
+
elif args.command == "query":
|
|
99
|
+
graph = build_graph()
|
|
100
|
+
results = query_dependencies(graph, args.term)
|
|
101
|
+
if getattr(args, "json", False):
|
|
102
|
+
print(json.dumps(results, indent=2))
|
|
103
|
+
else:
|
|
104
|
+
if not results:
|
|
105
|
+
print(f"❌ No package or tool matching '{args.term}' found.")
|
|
106
|
+
return
|
|
107
|
+
print(f"🔍 Found {len(results)} matching component(s) for '{args.term}':\n")
|
|
108
|
+
for r in results:
|
|
109
|
+
print(f"📦 {r['name']} [{r['category']} • {r['type']}]")
|
|
110
|
+
print(f" Status: {r['status'].upper()} | Size: {r['size']} | Path: {r['path']}")
|
|
111
|
+
if r['notes']:
|
|
112
|
+
print(f" Notes: {r['notes']}")
|
|
113
|
+
if r['requires']:
|
|
114
|
+
print(f" ──► Required by: {', '.join([d['target'] for d in r['requires']])}")
|
|
115
|
+
if r['required_by']:
|
|
116
|
+
print(f" ◄── Required by upstream: {', '.join([u['source'] for u in r['required_by']])}")
|
|
117
|
+
print()
|
|
118
|
+
|
|
119
|
+
elif args.command == "stale":
|
|
120
|
+
graph = build_graph()
|
|
121
|
+
stale_items = get_stale_items(graph)
|
|
122
|
+
if getattr(args, "json", False):
|
|
123
|
+
print(json.dumps(stale_items, indent=2))
|
|
124
|
+
else:
|
|
125
|
+
if not stale_items:
|
|
126
|
+
print("✨ No stale or orphaned items detected! System is clean.")
|
|
127
|
+
return
|
|
128
|
+
print(f"🔴 Found {len(stale_items)} Stale / Orphaned Item(s):\n")
|
|
129
|
+
for item in stale_items:
|
|
130
|
+
print(f"• {item['name']} ({item['size']}, {item['days_inactive']} days inactive)")
|
|
131
|
+
print(f" Path: {item['path']}")
|
|
132
|
+
print(f" Recommended Cleanup: {item['cleanup_cmd']}")
|
|
133
|
+
print()
|
|
134
|
+
|
|
135
|
+
elif args.command == "agent-context":
|
|
136
|
+
graph = build_graph()
|
|
137
|
+
ctx_md = generate_agent_context(graph)
|
|
138
|
+
if args.output:
|
|
139
|
+
out_p = Path(args.output)
|
|
140
|
+
out_p.parent.mkdir(parents=True, exist_ok=True)
|
|
141
|
+
out_p.write_text(ctx_md, encoding="utf-8")
|
|
142
|
+
print(f"✅ Exported AI agent system context to: {out_p}")
|
|
143
|
+
else:
|
|
144
|
+
print(ctx_md)
|
|
145
|
+
|
|
146
|
+
elif args.command == "mcp":
|
|
147
|
+
run_mcp_server()
|
|
148
|
+
|
|
149
|
+
elif args.command == "export":
|
|
150
|
+
graph = build_graph()
|
|
151
|
+
data = json.dumps(graph.to_dict(), indent=2)
|
|
152
|
+
if args.output:
|
|
153
|
+
out_p = Path(args.output)
|
|
154
|
+
out_p.parent.mkdir(parents=True, exist_ok=True)
|
|
155
|
+
out_p.write_text(data, encoding="utf-8")
|
|
156
|
+
print(f"✅ Exported graph JSON to: {args.output}")
|
|
157
|
+
else:
|
|
158
|
+
print(data)
|
|
159
|
+
|
|
160
|
+
if __name__ == "__main__":
|
|
161
|
+
main()
|
depradar/generator.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""HTML Generator for DepRadar."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from .models import GraphData
|
|
6
|
+
|
|
7
|
+
def generate_html(graph_data: GraphData, output_path: Path) -> Path:
|
|
8
|
+
template_file = Path(__file__).parent / "templates" / "viewer.html"
|
|
9
|
+
if not template_file.exists():
|
|
10
|
+
raise FileNotFoundError(f"Template not found at {template_file}")
|
|
11
|
+
|
|
12
|
+
template_content = template_file.read_text(encoding="utf-8")
|
|
13
|
+
json_str = json.dumps(graph_data.to_dict(), indent=2)
|
|
14
|
+
|
|
15
|
+
rendered = template_content.replace("/* __GRAPH_DATA__ */ { \"nodes\": [], \"links\": [], \"metadata\": {} }", json_str)
|
|
16
|
+
|
|
17
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
18
|
+
output_path.write_text(rendered, encoding="utf-8")
|
|
19
|
+
return output_path
|
depradar/graph.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Graph builder for DepRadar."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from .models import GraphData, Node, Link
|
|
6
|
+
from .scanners.node_scanner import scan_node
|
|
7
|
+
from .scanners.python_scanner import scan_python
|
|
8
|
+
from .scanners.system_scanner import scan_system
|
|
9
|
+
from .scanners.project_scanner import scan_projects
|
|
10
|
+
from .scanners.code_scanner import scan_code_imports
|
|
11
|
+
|
|
12
|
+
def build_graph(home: Path = None) -> GraphData:
|
|
13
|
+
if home is None:
|
|
14
|
+
home = Path.home()
|
|
15
|
+
|
|
16
|
+
all_nodes = []
|
|
17
|
+
all_links = []
|
|
18
|
+
seen_node_ids = set()
|
|
19
|
+
|
|
20
|
+
# Collect from standard scanners
|
|
21
|
+
scanners = [scan_node, scan_python, scan_system, scan_projects]
|
|
22
|
+
for scan_fn in scanners:
|
|
23
|
+
nodes, links = scan_fn(home)
|
|
24
|
+
for n in nodes:
|
|
25
|
+
if n.id not in seen_node_ids:
|
|
26
|
+
all_nodes.append(n)
|
|
27
|
+
seen_node_ids.add(n.id)
|
|
28
|
+
all_links.extend(links)
|
|
29
|
+
|
|
30
|
+
# Deep AST Code Analysis on all detected projects
|
|
31
|
+
projects_to_analyze = [
|
|
32
|
+
(n.id, n.category, Path(n.path))
|
|
33
|
+
for n in all_nodes
|
|
34
|
+
if n.type == "project" and Path(n.path).exists()
|
|
35
|
+
]
|
|
36
|
+
code_nodes, code_links = scan_code_imports(home, projects_to_analyze)
|
|
37
|
+
for cn in code_nodes:
|
|
38
|
+
if cn.id not in seen_node_ids:
|
|
39
|
+
all_nodes.append(cn)
|
|
40
|
+
seen_node_ids.add(cn.id)
|
|
41
|
+
all_links.extend(code_links)
|
|
42
|
+
|
|
43
|
+
# Filter links whose source or target does not exist in nodes
|
|
44
|
+
valid_links = []
|
|
45
|
+
for l in all_links:
|
|
46
|
+
if l.source in seen_node_ids and l.target in seen_node_ids:
|
|
47
|
+
valid_links.append(l)
|
|
48
|
+
|
|
49
|
+
metadata = {
|
|
50
|
+
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|
51
|
+
"total_nodes": len(all_nodes),
|
|
52
|
+
"total_links": len(valid_links),
|
|
53
|
+
"total_stale": sum(1 for n in all_nodes if n.status == "stale"),
|
|
54
|
+
"categories": sorted(list(set(n.category for n in all_nodes)))
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return GraphData(nodes=all_nodes, links=valid_links, metadata=metadata)
|
depradar/mcp.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Model Context Protocol (MCP) Server for DepRadar.
|
|
2
|
+
Enables AI Agents (Claude Desktop, Cursor, Antigravity, Windsurf) to inspect system dependencies via stdio.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import json
|
|
7
|
+
import platform
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, Any, List
|
|
10
|
+
from .graph import build_graph
|
|
11
|
+
|
|
12
|
+
def run_mcp_server():
|
|
13
|
+
"""Runs a zero-dependency JSON-RPC 2.0 stdio MCP server."""
|
|
14
|
+
# Build or cache graph data
|
|
15
|
+
cached_graph = None
|
|
16
|
+
|
|
17
|
+
def get_graph():
|
|
18
|
+
nonlocal cached_graph
|
|
19
|
+
if cached_graph is None:
|
|
20
|
+
cached_graph = build_graph()
|
|
21
|
+
return cached_graph
|
|
22
|
+
|
|
23
|
+
tools_definitions = [
|
|
24
|
+
{
|
|
25
|
+
"name": "depradar_get_system_overview",
|
|
26
|
+
"description": "Returns a high-level overview of installed developer runtimes, total package counts, disk footprints, and stale items on this machine.",
|
|
27
|
+
"inputSchema": {
|
|
28
|
+
"type": "object",
|
|
29
|
+
"properties": {},
|
|
30
|
+
"required": []
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"name": "depradar_query_dependency",
|
|
35
|
+
"description": "Look up any package, library, tool, or runtime to see who imports it, where it is installed on disk, its status, and what it is used for.",
|
|
36
|
+
"inputSchema": {
|
|
37
|
+
"type": "object",
|
|
38
|
+
"properties": {
|
|
39
|
+
"query": {
|
|
40
|
+
"type": "string",
|
|
41
|
+
"description": "Name or keyword of the library, package, or tool (e.g. 'selenium', 'zarr', 'docker', 'uv')"
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"required": ["query"]
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"name": "depradar_list_stale_dependencies",
|
|
49
|
+
"description": "Lists all stale, orphaned, or unreferenced packages and virtual environments with recommended cleanup commands.",
|
|
50
|
+
"inputSchema": {
|
|
51
|
+
"type": "object",
|
|
52
|
+
"properties": {},
|
|
53
|
+
"required": []
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
"name": "depradar_get_full_graph",
|
|
58
|
+
"description": "Returns the complete node and edge dependency graph of the host system.",
|
|
59
|
+
"inputSchema": {
|
|
60
|
+
"type": "object",
|
|
61
|
+
"properties": {},
|
|
62
|
+
"required": []
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
while True:
|
|
68
|
+
try:
|
|
69
|
+
line = sys.stdin.readline()
|
|
70
|
+
if not line:
|
|
71
|
+
break
|
|
72
|
+
line = line.strip()
|
|
73
|
+
if not line:
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
request = json.loads(line)
|
|
77
|
+
req_id = request.get("id")
|
|
78
|
+
method = request.get("method")
|
|
79
|
+
params = request.get("params", {})
|
|
80
|
+
|
|
81
|
+
if method == "initialize":
|
|
82
|
+
response = {
|
|
83
|
+
"jsonrpc": "2.0",
|
|
84
|
+
"id": req_id,
|
|
85
|
+
"result": {
|
|
86
|
+
"protocolVersion": "2024-11-05",
|
|
87
|
+
"capabilities": {
|
|
88
|
+
"tools": {}
|
|
89
|
+
},
|
|
90
|
+
"serverInfo": {
|
|
91
|
+
"name": "depradar",
|
|
92
|
+
"version": "0.1.0"
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
97
|
+
sys.stdout.flush()
|
|
98
|
+
|
|
99
|
+
elif method == "notifications/initialized":
|
|
100
|
+
pass # Notification, no response needed
|
|
101
|
+
|
|
102
|
+
elif method == "tools/list":
|
|
103
|
+
response = {
|
|
104
|
+
"jsonrpc": "2.0",
|
|
105
|
+
"id": req_id,
|
|
106
|
+
"result": {
|
|
107
|
+
"tools": tools_definitions
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
111
|
+
sys.stdout.flush()
|
|
112
|
+
|
|
113
|
+
elif method == "tools/call":
|
|
114
|
+
tool_name = params.get("name")
|
|
115
|
+
tool_args = params.get("arguments", {})
|
|
116
|
+
graph = get_graph()
|
|
117
|
+
|
|
118
|
+
if tool_name == "depradar_get_system_overview":
|
|
119
|
+
overview = {
|
|
120
|
+
"os": platform.system(),
|
|
121
|
+
"os_release": platform.release(),
|
|
122
|
+
"total_nodes": len(graph.nodes),
|
|
123
|
+
"total_links": len(graph.links),
|
|
124
|
+
"total_stale_items": graph.metadata.get("total_stale", 0),
|
|
125
|
+
"categories": graph.metadata.get("categories", []),
|
|
126
|
+
"key_runtimes": [n.name for n in graph.nodes if n.type == "runtime"],
|
|
127
|
+
"heavy_disk_consumers": [
|
|
128
|
+
{"name": n.name, "size": n.size_human, "path": n.path}
|
|
129
|
+
for n in sorted(graph.nodes, key=lambda x: x.size_bytes, reverse=True)[:5]
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
result_text = json.dumps(overview, indent=2)
|
|
133
|
+
|
|
134
|
+
elif tool_name == "depradar_query_dependency":
|
|
135
|
+
q = tool_args.get("query", "").lower()
|
|
136
|
+
matched_nodes = []
|
|
137
|
+
for n in graph.nodes:
|
|
138
|
+
if q in n.name.lower() or q in n.id.lower() or q in n.notes.lower():
|
|
139
|
+
upstream = [
|
|
140
|
+
{"source": (l.source if isinstance(l.source, str) else l.source.id), "relationship": l.relationship, "description": l.description}
|
|
141
|
+
for l in graph.links if (l.target == n.id or (isinstance(l.target, dict) and l.target.get("id") == n.id))
|
|
142
|
+
]
|
|
143
|
+
downstream = [
|
|
144
|
+
{"target": (l.target if isinstance(l.target, str) else l.target.id), "relationship": l.relationship, "description": l.description}
|
|
145
|
+
for l in graph.links if (l.source == n.id or (isinstance(l.source, dict) and l.source.get("id") == n.id))
|
|
146
|
+
]
|
|
147
|
+
matched_nodes.append({
|
|
148
|
+
"id": n.id,
|
|
149
|
+
"name": n.name,
|
|
150
|
+
"category": n.category,
|
|
151
|
+
"type": n.type,
|
|
152
|
+
"status": n.status,
|
|
153
|
+
"size": n.size_human,
|
|
154
|
+
"path": n.path,
|
|
155
|
+
"notes": n.notes,
|
|
156
|
+
"installed_packages_count": len(n.installed_packages) if n.installed_packages else 0,
|
|
157
|
+
"required_by": upstream,
|
|
158
|
+
"requires": downstream
|
|
159
|
+
})
|
|
160
|
+
result_text = json.dumps(matched_nodes, indent=2) if matched_nodes else f"No package or dependency matched query: '{q}'"
|
|
161
|
+
|
|
162
|
+
elif tool_name == "depradar_list_stale_dependencies":
|
|
163
|
+
stale_nodes = [
|
|
164
|
+
{
|
|
165
|
+
"name": n.name,
|
|
166
|
+
"category": n.category,
|
|
167
|
+
"type": n.type,
|
|
168
|
+
"size": n.size_human,
|
|
169
|
+
"path": n.path,
|
|
170
|
+
"days_inactive": n.days_inactive,
|
|
171
|
+
"cleanup_command": n.uninstall_cmd or f"rm -rf '{n.path}'"
|
|
172
|
+
}
|
|
173
|
+
for n in graph.nodes if n.status == "stale"
|
|
174
|
+
]
|
|
175
|
+
result_text = json.dumps(stale_nodes, indent=2)
|
|
176
|
+
|
|
177
|
+
elif tool_name == "depradar_get_full_graph":
|
|
178
|
+
result_text = json.dumps(graph.to_dict(), indent=2)
|
|
179
|
+
|
|
180
|
+
else:
|
|
181
|
+
result_text = f"Unknown tool: {tool_name}"
|
|
182
|
+
|
|
183
|
+
response = {
|
|
184
|
+
"jsonrpc": "2.0",
|
|
185
|
+
"id": req_id,
|
|
186
|
+
"result": {
|
|
187
|
+
"content": [
|
|
188
|
+
{
|
|
189
|
+
"type": "text",
|
|
190
|
+
"text": result_text
|
|
191
|
+
}
|
|
192
|
+
]
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
196
|
+
sys.stdout.flush()
|
|
197
|
+
|
|
198
|
+
else:
|
|
199
|
+
response = {
|
|
200
|
+
"jsonrpc": "2.0",
|
|
201
|
+
"id": req_id,
|
|
202
|
+
"error": {
|
|
203
|
+
"code": -32601,
|
|
204
|
+
"message": f"Method not found: {method}"
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
208
|
+
sys.stdout.flush()
|
|
209
|
+
|
|
210
|
+
except Exception as e:
|
|
211
|
+
if req_id is not None:
|
|
212
|
+
err_resp = {
|
|
213
|
+
"jsonrpc": "2.0",
|
|
214
|
+
"id": req_id,
|
|
215
|
+
"error": {
|
|
216
|
+
"code": -32603,
|
|
217
|
+
"message": f"Internal error: {str(e)}"
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
sys.stdout.write(json.dumps(err_resp) + "\n")
|
|
221
|
+
sys.stdout.flush()
|
depradar/models.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Data models for DepRadar graph nodes and edges."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field, asdict
|
|
4
|
+
from typing import List, Dict, Any, Optional
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class Node:
|
|
8
|
+
id: str
|
|
9
|
+
name: str
|
|
10
|
+
category: str # 'AI & Agents', 'Data Science & ML', 'Automation & Scraping', 'Fullstack Web', 'Desktop & System'
|
|
11
|
+
type: str # 'python-venv', 'npm-global', 'snap-app', 'snap-runtime', 'apt-pkg', 'git-repo', 'runtime'
|
|
12
|
+
path: str
|
|
13
|
+
size_bytes: int
|
|
14
|
+
size_human: str
|
|
15
|
+
last_used: str
|
|
16
|
+
days_inactive: int
|
|
17
|
+
status: str # 'active', 'inactive', 'stale'
|
|
18
|
+
uninstall_cmd: str = ""
|
|
19
|
+
notes: str = ""
|
|
20
|
+
val: float = 1.0 # Visual radius multiplier calculated from size
|
|
21
|
+
installed_packages: List[Dict[str, str]] = field(default_factory=list)
|
|
22
|
+
|
|
23
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
24
|
+
return asdict(self)
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Link:
|
|
28
|
+
source: str
|
|
29
|
+
target: str
|
|
30
|
+
relationship: str = "depends_on" # e.g. 'Imports', 'Runtime Host', 'Typesetting Engine'
|
|
31
|
+
description: str = "" # Detailed explanation of why & how it is used
|
|
32
|
+
|
|
33
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
34
|
+
return asdict(self)
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class GraphData:
|
|
38
|
+
nodes: List[Node] = field(default_factory=list)
|
|
39
|
+
links: List[Link] = field(default_factory=list)
|
|
40
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
43
|
+
return {
|
|
44
|
+
"nodes": [n.to_dict() for n in self.nodes],
|
|
45
|
+
"links": [l.to_dict() for l in self.links],
|
|
46
|
+
"metadata": self.metadata
|
|
47
|
+
}
|