stack-scout-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,128 @@
1
+ """Classify a repo's license: is it really free to build with?
2
+
3
+ Categories (and points toward the 0-100 health score):
4
+ permissive 20 MIT, Apache, BSD... use anywhere, even commercially
5
+ weak-copyleft 15 MPL, LGPL... free; changes to the library itself must be shared
6
+ open-core 14 free license plus some paid "enterprise" parts (found from LICENSE text)
7
+ copyleft 8 GPL/AGPL... free, but your app may have to be open-sourced too
8
+ unknown 0 no license detected: legally, no permission to use. Warn.
9
+ not-free -- source-available with use restrictions (BUSL, SSPL...). Reject.
10
+
11
+ CLI:
12
+ python -m stack_scout_mcp.tools.license_check MIT AGPL-3.0 BUSL-1.1 NOASSERTION
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ import sys
19
+
20
+ PERMISSIVE = {
21
+ "MIT", "MIT-0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "0BSD", "Unlicense",
22
+ "Zlib", "BSL-1.0", "CC0-1.0", "PostgreSQL", "Python-2.0", "UPL-1.0", "Artistic-2.0", "WTFPL",
23
+ }
24
+ WEAK_COPYLEFT = {"MPL-2.0", "LGPL-2.1", "LGPL-3.0", "EPL-1.0", "EPL-2.0", "CDDL-1.0"}
25
+ COPYLEFT = {"GPL-2.0", "GPL-3.0", "AGPL-3.0", "EUPL-1.2", "OSL-3.0"}
26
+ NOT_FREE = {
27
+ "BUSL-1.1", "SSPL-1.0", "Elastic-2.0", "CC-BY-NC-4.0", "CC-BY-NC-SA-4.0",
28
+ "PolyForm-Noncommercial-1.0.0", "PolyForm-Small-Business-1.0.0",
29
+ }
30
+
31
+ POINTS = {"permissive": 20, "open-core": 14, "weak-copyleft": 15, "copyleft": 8, "unknown": 0, "not-free": 0}
32
+
33
+ # For repos GitHub labels "Other": recognise the license from the LICENSE file text.
34
+ # Restrictive licenses come first so a "Commons Clause on top of MIT" file counts as not free.
35
+ _TEXT_RULES = [
36
+ ("Commons-Clause", r"commons clause"),
37
+ ("BUSL-1.1", r"business source license"),
38
+ ("SSPL-1.0", r"server side public license"),
39
+ ("Elastic-2.0", r"elastic license"),
40
+ ("FSL-1.1", r"functional source license"),
41
+ ("PolyForm-Noncommercial-1.0.0", r"polyform noncommercial"),
42
+ ("AGPL-3.0", r"gnu affero general public license"),
43
+ ("LGPL-3.0", r"gnu lesser general public license"),
44
+ ("GPL-3.0", r"gnu general public license"),
45
+ ("MPL-2.0", r"mozilla public license"),
46
+ ("Apache-2.0", r"apache license,?\s+version 2\.0"),
47
+ ("MIT", r"permission is hereby granted,\s+free of charge|\bmit licen[cs]e\b"),
48
+ ("ISC", r"permission to use, copy, modify,? and/or distribute this software for any purpose"),
49
+ ("BSD-3-Clause", r"redistribution and use in source and binary forms"),
50
+ ]
51
+ # Free license + paid extras. Phrases that only appear when a file splits the code into parts.
52
+ _OPEN_CORE = r"enterprise edition|enterprise license|commercial license|proprietary license|\bee/|\(ee\)"
53
+ _PARTS = r"part(?:s)? of this (?:work|software|repository|project)|portions of this software|other parts|enterprise edition|\bee/|\(ee\)"
54
+ # User may pick any one of several licenses (e.g. Elasticsearch: AGPL or SSPL or Elastic).
55
+ _CHOICE = r"dual[- ]licen|triple[- ]licen|at your (?:option|election)|your choice of"
56
+ # BUSL / FSL: each version turns into a free license after a delay.
57
+ _DELAYED = r"future license|change license|change date"
58
+ NOT_FREE.update({"Commons-Clause", "FSL-1.1"})
59
+ _FREE_CATEGORIES = ("permissive", "weak-copyleft", "copyleft")
60
+
61
+
62
+ def classify(spdx_id: str | None) -> dict:
63
+ spdx = (spdx_id or "").strip()
64
+ if spdx in PERMISSIVE:
65
+ category, note = "permissive", "Free to use, even commercially. Keep the copyright notice."
66
+ elif spdx in WEAK_COPYLEFT:
67
+ category, note = "weak-copyleft", "Free to use. If you modify this library's own files, share those changes."
68
+ elif spdx == "AGPL-3.0":
69
+ category, note = "copyleft", (
70
+ "Free, but if you modify it and run it as a web service, you must publish your changes. "
71
+ "Fine to self-host unmodified."
72
+ )
73
+ elif spdx in COPYLEFT:
74
+ category, note = "copyleft", "Free, but if you distribute an app that includes it, your app must be GPL too."
75
+ elif spdx in NOT_FREE:
76
+ category, note = "not-free", "Source-available, not open source: restricts commercial or SaaS use."
77
+ else:
78
+ category = "unknown"
79
+ note = (
80
+ "License not recognised by GitHub ('Other' or missing). Read the LICENSE file before using it: "
81
+ "no license means no permission."
82
+ )
83
+ return {"spdx": spdx or None, "category": category, "points": POINTS[category], "note": note}
84
+
85
+
86
+ def _open_core(free_spdx: str, paid: str) -> dict:
87
+ return {
88
+ "spdx": free_spdx, "category": "open-core", "points": POINTS["open-core"],
89
+ "note": (f"Open core: mostly {free_spdx}, but some parts (usually 'enterprise' features) are under "
90
+ f"{paid}. The free core is fine to use; check that the features you need are in it."),
91
+ }
92
+
93
+
94
+ def classify_text(text: str) -> dict:
95
+ """Classify a LICENSE file's text.
96
+
97
+ - only a restrictive license (BUSL, SSPL...) -> not-free
98
+ - a free license + a restrictive one for some parts -> open-core (e.g. MIT core, BUSL enterprise)
99
+ - a free license + 'enterprise edition' / ee/ folder -> open-core
100
+ - a free license alone -> its normal category
101
+ """
102
+ lowered = " ".join(text.lower().split())
103
+ found = [spdx for spdx, pattern in _TEXT_RULES if re.search(pattern, lowered)]
104
+ if not found:
105
+ return classify(None)
106
+ restrictive = [s for s in found if s in NOT_FREE]
107
+ free = [s for s in found if classify(s)["category"] in _FREE_CATEGORIES]
108
+ if restrictive and free and re.search(_CHOICE, lowered):
109
+ result = classify(free[0])
110
+ result["note"] = (f"You can choose {free[0]} (free) instead of the restrictive options "
111
+ f"({', '.join(restrictive)}). {result['note']}")
112
+ elif restrictive and free and re.search(_PARTS, lowered):
113
+ result = _open_core(free[-1], f"a restrictive license ({restrictive[0]})")
114
+ elif restrictive:
115
+ result = classify(restrictive[0])
116
+ if free and re.search(_DELAYED, lowered):
117
+ result["note"] += (f" Each version becomes {free[-1]} after a delay (FSL: 2 years, BUSL: up to 4); "
118
+ "until then, competing or commercial use is restricted.")
119
+ else:
120
+ result = classify(found[0])
121
+ if result["category"] in ("permissive", "weak-copyleft") and re.search(_OPEN_CORE, lowered):
122
+ result = _open_core(found[0], "a paid or proprietary license")
123
+ result["detected_from"] = "LICENSE file"
124
+ return result
125
+
126
+
127
+ if __name__ == "__main__":
128
+ print(json.dumps([classify(a) for a in sys.argv[1:]] or classify(None), indent=2))
@@ -0,0 +1,79 @@
1
+ """Backup planner: guess the building blocks of a request (auth, payments, cart...) from keywords.
2
+
3
+ The user's AI is the real planner. It splits any request into needs and passes them
4
+ to scout_stack. This file only runs when it doesn't. A request that matches no known
5
+ pattern ("a 2D game engine") is searched as typed. If it sounds like an app
6
+ ("...app", "...website"), common app blocks are added too.
7
+
8
+ CLI:
9
+ python -m stack_scout_mcp.tools.plan_components "I want to build an online shoe store"
10
+ python -m stack_scout_mcp.tools.plan_components --list
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ import sys
17
+ from functools import lru_cache
18
+ from pathlib import Path
19
+
20
+ from ._common import DATA_DIR
21
+
22
+
23
+ @lru_cache(maxsize=1)
24
+ def load_catalog() -> dict:
25
+ return json.loads((DATA_DIR / "components.json").read_text(encoding="utf-8"))
26
+
27
+
28
+ _APP_WORDS = ["app", "apps", "website", "web app", "platform", "portal", "saas", "service", "mobile app"]
29
+
30
+
31
+ def _matches(text: str, keyword: str) -> bool:
32
+ return re.search(rf"\b{re.escape(keyword.lower())}\b", text) is not None
33
+
34
+
35
+ def plan_components(idea: str) -> dict:
36
+ """Return {'archetypes': [...], 'components': [{'id', 'name', 'why'}...]} for an idea."""
37
+ catalog = load_catalog()
38
+ text = idea.lower()
39
+ picked: dict[str, str] = {} # component id -> reason (first reason wins, order preserved)
40
+ archetypes = []
41
+
42
+ for arch_name, arch in catalog["archetypes"].items():
43
+ hit = next((k for k in arch["keywords"] if _matches(text, k)), None)
44
+ if hit:
45
+ archetypes.append(arch_name)
46
+ for cid in arch["components"]:
47
+ picked.setdefault(cid, f"common in {arch_name} apps; you said '{hit}'")
48
+
49
+ for cid, comp in catalog["components"].items():
50
+ hit = next((k for k in comp["keywords"] if _matches(text, k)), None)
51
+ if hit:
52
+ picked.setdefault(cid, f"you mentioned '{hit}'")
53
+
54
+ components = [
55
+ {"id": cid, "name": catalog["components"][cid]["name"], "why": why} for cid, why in picked.items()
56
+ ]
57
+ if not picked:
58
+ # Not a pattern we know: search for the request itself, as typed.
59
+ components.append({"id": idea.strip(), "name": idea.strip(),
60
+ "why": "searched as you described it (no known building block matched)"})
61
+ if any(_matches(text, w) for w in _APP_WORDS):
62
+ for cid in catalog["default_components"]:
63
+ components.append({"id": cid, "name": catalog["components"][cid]["name"],
64
+ "why": "common building block for most apps"})
65
+
66
+ return {"idea": idea, "archetypes": archetypes, "components": components}
67
+
68
+
69
+ def list_components() -> list[dict]:
70
+ return [{"id": cid, "name": c["name"], "query": c["query"]} for cid, c in load_catalog()["components"].items()]
71
+
72
+
73
+ if __name__ == "__main__":
74
+ if len(sys.argv) < 2:
75
+ sys.exit('usage: python -m stack_scout_mcp.tools.plan_components "your app idea" | --list')
76
+ if sys.argv[1] == "--list":
77
+ print(json.dumps(list_components(), indent=2))
78
+ else:
79
+ print(json.dumps(plan_components(" ".join(sys.argv[1:])), indent=2))
@@ -0,0 +1,66 @@
1
+ """Filter and rank candidate repos for one building block.
2
+
3
+ Final rank = health score (0-100, see repo_health.py) + relevance bonus (0-15 or 0-25).
4
+ Catalog needs: bonus follows GitHub's best-match order (0-15).
5
+ Plain-language needs: bonus = share of the key words the repo mentions (0-25), so a
6
+ hugely popular but loosely related repo doesn't beat a focused, healthy one.
7
+
8
+ CLI (reads the JSON list printed by github_search.py):
9
+ python -m stack_scout_mcp.tools.github_search "topic:payments" > .tmp/payments.json
10
+ python -m stack_scout_mcp.tools.rank_tools .tmp/payments.json --top 3
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ from .repo_health import assess
20
+
21
+ RELEVANCE_MAX = 15
22
+ TERM_RELEVANCE_MAX = 25 # plain-language searches are noisier, so matching the words counts more
23
+
24
+
25
+ def _term_relevance(repo: dict, terms: list[str]) -> float:
26
+ """Share of search terms found in the repo's name, description and topics (0-1)."""
27
+ haystack = " ".join([repo["full_name"], repo.get("description") or "", " ".join(repo.get("topics") or [])]).lower()
28
+ return sum(t in haystack for t in terms) / len(terms)
29
+
30
+
31
+ def rank(candidates: list[dict], top_n: int = 3, terms: list[str] | None = None) -> dict:
32
+ """Return {'top': [...], 'rejected': [...], 'considered': int}. Each repo gains 'health' and 'rank_score'.
33
+
34
+ With `terms` (plain-language searches), relevance = share of terms the repo mentions.
35
+ Without (tuned catalog searches), relevance = GitHub's best-match position.
36
+ """
37
+ seen: set[str] = set()
38
+ kept, rejected = [], []
39
+ total = len(candidates) or 1
40
+ for position, repo in enumerate(candidates):
41
+ key = repo["full_name"].lower()
42
+ if key in seen:
43
+ continue
44
+ seen.add(key)
45
+ health = assess(repo)
46
+ if terms:
47
+ relevance = round(TERM_RELEVANCE_MAX * _term_relevance(repo, terms))
48
+ else:
49
+ relevance = round(RELEVANCE_MAX * (1 - position / total))
50
+ entry = {**repo, "health": health, "rank_score": health["score"] + relevance if health["score"] else 0}
51
+ (rejected if health["status"] == "rejected" else kept).append(entry)
52
+ kept.sort(key=lambda r: r["rank_score"], reverse=True)
53
+ return {"top": kept[:top_n], "rejected": rejected, "considered": len(seen)}
54
+
55
+
56
+ def main() -> None:
57
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
58
+ p.add_argument("candidates_json", help="File with a JSON list of repos (from github_search.py)")
59
+ p.add_argument("--top", type=int, default=3)
60
+ args = p.parse_args()
61
+ candidates = json.loads(Path(args.candidates_json).read_text(encoding="utf-8"))
62
+ print(json.dumps(rank(candidates, args.top), indent=2))
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
@@ -0,0 +1,114 @@
1
+ """Decide whether a repo is alive, free and trustworthy, and give it a 0-100 score.
2
+
3
+ Hard rejects (never recommended):
4
+ - reading material, not a tool (awesome-lists, tutorials, guides, courses)
5
+ - archived on GitHub
6
+ - no code pushed for over 2 years
7
+ - source-available / non-free license (see license_check.py)
8
+
9
+ Score = popularity (0-40) + recency (0-40) + license (0-20)
10
+ popularity: 8 * log10(stars + 1) -> 100 stars ~16, 1k ~24, 10k ~32, 100k = 40
11
+ recency: pushed <= 90 days 40, <= 180 32, <= 365 22, <= 730 10
12
+ license: see license_check.py (permissive 20 ... unknown 0). If the repo dict has
13
+ 'license_info' (read from the LICENSE file by research_tool.resolve_license),
14
+ that is used instead of GitHub's label.
15
+
16
+ CLI:
17
+ python -m stack_scout_mcp.tools.repo_health medusajs/medusa saleor/saleor
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import math
23
+ import re
24
+ import sys
25
+ from datetime import datetime, timezone
26
+ from pathlib import Path
27
+
28
+ from .license_check import classify
29
+
30
+ STALE_DAYS = 730
31
+
32
+ # Repos named like these are reading material (lists, courses), not tools you can build with.
33
+ _NOT_A_TOOL = re.compile(
34
+ r"(^awesome|awesome-|tutorial|guide|interview|roadmap|cheat-?sheet|\d+-days|^learn-|-course$|"
35
+ r"-examples?$|^examples?$|-book$|-notes$|-resources$)",
36
+ re.I,
37
+ )
38
+
39
+
40
+ def days_since(iso: str | None, now: datetime | None = None) -> int | None:
41
+ if not iso:
42
+ return None
43
+ then = datetime.fromisoformat(iso.replace("Z", "+00:00"))
44
+ return ((now or datetime.now(timezone.utc)) - then).days
45
+
46
+
47
+ def _recency_points(age: int) -> int:
48
+ if age <= 90:
49
+ return 40
50
+ if age <= 180:
51
+ return 32
52
+ if age <= 365:
53
+ return 22
54
+ return 10
55
+
56
+
57
+ def assess(repo: dict, now: datetime | None = None) -> dict:
58
+ """Return {'status': ok|caution|rejected, 'score', 'rejected_because', 'warnings', 'license', 'days_since_push'}."""
59
+ rejects: list[str] = []
60
+ warnings: list[str] = []
61
+ lic = repo.get("license_info") or classify(repo.get("license")) # license_info: read from LICENSE file
62
+ age = days_since(repo.get("pushed_at"), now)
63
+ stars = repo.get("stars", 0)
64
+
65
+ if _NOT_A_TOOL.search(repo.get("full_name", "").split("/")[-1]):
66
+ rejects.append("a list or tutorial, not a tool")
67
+ if repo.get("archived"):
68
+ rejects.append("archived (owner stopped maintaining it)")
69
+ if age is None or age > STALE_DAYS:
70
+ rejects.append(f"no code changes in {age} days" if age is not None else "no activity data")
71
+ if lic["category"] == "not-free":
72
+ rejects.append(f"{lic['spdx']} license is not open source")
73
+ if repo.get("fork"):
74
+ warnings.append("this is a fork; check whether the original is the better choice")
75
+ if age is not None and 365 < age <= STALE_DAYS:
76
+ warnings.append("slowing down: last code change over a year ago")
77
+ if lic["category"] == "unknown":
78
+ warnings.append("license unclear; read it before using")
79
+ elif lic["category"] == "copyleft":
80
+ warnings.append(f"{lic['spdx']}: {lic['note']}")
81
+ elif lic["category"] == "open-core":
82
+ warnings.append(lic["note"])
83
+ if stars < 100:
84
+ warnings.append("small community (under 100 stars)")
85
+
86
+ if rejects:
87
+ return {"status": "rejected", "score": 0, "rejected_because": rejects, "warnings": warnings,
88
+ "license": lic, "days_since_push": age}
89
+
90
+ score = min(40, round(8 * math.log10(stars + 1))) + _recency_points(age) + lic["points"]
91
+ return {
92
+ "status": "caution" if warnings else "ok",
93
+ "score": score,
94
+ "rejected_because": [],
95
+ "warnings": warnings,
96
+ "license": lic,
97
+ "days_since_push": age,
98
+ }
99
+
100
+
101
+ def main() -> None:
102
+ from .github_search import get_repo
103
+
104
+ if len(sys.argv) < 2:
105
+ sys.exit("usage: python -m stack_scout_mcp.tools.repo_health owner/repo [owner/repo ...]")
106
+ out = []
107
+ for name in sys.argv[1:]:
108
+ repo = get_repo(name)
109
+ out.append({**repo, "health": assess(repo)})
110
+ print(json.dumps(out, indent=2))
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()