fossick-mcp 0.1.2__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.
- fossick/__init__.py +0 -0
- fossick/__main__.py +9 -0
- fossick/cache.py +74 -0
- fossick/github_client.py +292 -0
- fossick/hints.py +92 -0
- fossick/server.py +57 -0
- fossick/tools/__init__.py +11 -0
- fossick/tools/_common.py +425 -0
- fossick/tools/_tree_sitter.py +255 -0
- fossick/tools/find_symbol.py +557 -0
- fossick/tools/get_file.py +140 -0
- fossick/tools/list_tags.py +129 -0
- fossick/tools/repo_tree.py +186 -0
- fossick/tools/search_code.py +244 -0
- fossick/tools/search_packages.py +213 -0
- fossick/tools/search_repos.py +784 -0
- fossick_mcp-0.1.2.dist-info/METADATA +233 -0
- fossick_mcp-0.1.2.dist-info/RECORD +21 -0
- fossick_mcp-0.1.2.dist-info/WHEEL +4 -0
- fossick_mcp-0.1.2.dist-info/entry_points.txt +2 -0
- fossick_mcp-0.1.2.dist-info/licenses/LICENSE +21 -0
fossick/__init__.py
ADDED
|
File without changes
|
fossick/__main__.py
ADDED
fossick/cache.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Simple async TTL cache with LRU eviction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import time
|
|
9
|
+
from collections import OrderedDict
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
_DEFAULT_MAX_SIZE = 500
|
|
13
|
+
_DEFAULT_TTL = 300 # seconds
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _Entry:
|
|
17
|
+
__slots__ = ("value", "expires_at")
|
|
18
|
+
|
|
19
|
+
def __init__(self, value: Any, expires_at: float) -> None:
|
|
20
|
+
self.value = value
|
|
21
|
+
self.expires_at = expires_at
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TTLCache:
|
|
25
|
+
"""In-memory TTL cache with LRU eviction."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, max_size: int = _DEFAULT_MAX_SIZE) -> None:
|
|
28
|
+
self._store: OrderedDict[str, _Entry] = OrderedDict()
|
|
29
|
+
self._max_size = max_size
|
|
30
|
+
|
|
31
|
+
async def get(self, key: str) -> Any | None:
|
|
32
|
+
"""Return cached value or ``None`` if missing/expired."""
|
|
33
|
+
entry = self._store.get(key)
|
|
34
|
+
if entry is None:
|
|
35
|
+
return None
|
|
36
|
+
if time.monotonic() > entry.expires_at:
|
|
37
|
+
del self._store[key]
|
|
38
|
+
return None
|
|
39
|
+
# Mark as recently used
|
|
40
|
+
self._store.move_to_end(key)
|
|
41
|
+
return entry.value
|
|
42
|
+
|
|
43
|
+
async def set(self, key: str, value: Any, ttl: int = _DEFAULT_TTL) -> None:
|
|
44
|
+
"""Store a value with a TTL in seconds."""
|
|
45
|
+
if key in self._store:
|
|
46
|
+
del self._store[key]
|
|
47
|
+
self._store[key] = _Entry(value, time.monotonic() + ttl)
|
|
48
|
+
self._evict()
|
|
49
|
+
|
|
50
|
+
def invalidate(self, pattern: str) -> int:
|
|
51
|
+
"""Remove all keys matching a regex *pattern*. Returns count removed."""
|
|
52
|
+
regex = re.compile(pattern)
|
|
53
|
+
to_delete = [k for k in self._store if regex.search(k)]
|
|
54
|
+
for k in to_delete:
|
|
55
|
+
del self._store[k]
|
|
56
|
+
return len(to_delete)
|
|
57
|
+
|
|
58
|
+
def _evict(self) -> None:
|
|
59
|
+
"""Evict oldest entries until we're within max_size."""
|
|
60
|
+
while len(self._store) > self._max_size:
|
|
61
|
+
self._store.popitem(last=False)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ---------------------------------------------------------------------------
|
|
65
|
+
# Module-level singleton
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
cache = TTLCache()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def cache_key(endpoint: str, **params: Any) -> str:
|
|
72
|
+
"""Build a deterministic cache key from an endpoint and parameters."""
|
|
73
|
+
raw = json.dumps({"endpoint": endpoint, **params}, sort_keys=True)
|
|
74
|
+
return hashlib.sha256(raw.encode()).hexdigest()
|
fossick/github_client.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Async GitHub API client with rate-limit handling and retry logic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
_BASE_URL = "https://api.github.com"
|
|
18
|
+
|
|
19
|
+
# Rate-limit thresholds
|
|
20
|
+
_REMAINING_THRESHOLD = 5
|
|
21
|
+
_MAX_RETRIES = 3
|
|
22
|
+
_RETRY_BASE_DELAY = 1.0 # seconds
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _RateBucket:
|
|
26
|
+
"""Tracks rate-limit state for one API category."""
|
|
27
|
+
|
|
28
|
+
__slots__ = ("remaining", "reset_at")
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
self.remaining: int | None = None
|
|
32
|
+
self.reset_at: float = 0.0
|
|
33
|
+
|
|
34
|
+
def update(self, headers: httpx.Headers) -> None:
|
|
35
|
+
"""Read rate-limit headers from a GitHub response."""
|
|
36
|
+
if "x-ratelimit-remaining" in headers:
|
|
37
|
+
self.remaining = int(headers["x-ratelimit-remaining"])
|
|
38
|
+
if "x-ratelimit-reset" in headers:
|
|
39
|
+
self.reset_at = float(headers["x-ratelimit-reset"])
|
|
40
|
+
|
|
41
|
+
async def wait_if_needed(self) -> None:
|
|
42
|
+
"""Sleep until the reset window if remaining requests are low."""
|
|
43
|
+
if self.remaining is not None and self.remaining < _REMAINING_THRESHOLD:
|
|
44
|
+
sleep_for = max(self.reset_at - time.time(), 0) + 1
|
|
45
|
+
logger.warning(
|
|
46
|
+
"Rate limit nearly exhausted (remaining=%s). Sleeping %.1fs.",
|
|
47
|
+
self.remaining,
|
|
48
|
+
sleep_for,
|
|
49
|
+
)
|
|
50
|
+
await asyncio.sleep(sleep_for)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class GitHubClient:
|
|
54
|
+
"""Thin async wrapper around the GitHub REST API."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, token: str) -> None:
|
|
57
|
+
self._token = token
|
|
58
|
+
self._http = httpx.AsyncClient(
|
|
59
|
+
base_url=_BASE_URL,
|
|
60
|
+
headers={
|
|
61
|
+
"Authorization": f"Bearer {token}",
|
|
62
|
+
"Accept": "application/vnd.github+json",
|
|
63
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
64
|
+
},
|
|
65
|
+
timeout=30.0,
|
|
66
|
+
# Follow redirects so renamed/transferred repos resolve
|
|
67
|
+
# transparently. GitHub issues a 301 Moved Permanently
|
|
68
|
+
# with a `Location: https://api.github.com/...` pointing
|
|
69
|
+
# at the new owner when a repo has been transferred
|
|
70
|
+
# (e.g. encode/starlette → Kludex/starlette). Without
|
|
71
|
+
# this, every tool call against the old slug surfaces
|
|
72
|
+
# an opaque `HTTP 301 from GitHub during <tool>:
|
|
73
|
+
# {"message":"Moved Permanently","url":"..."}` error
|
|
74
|
+
# through the classifier, which is actionable only if
|
|
75
|
+
# the caller reads the JSON body and extracts the new
|
|
76
|
+
# URL — basically never. With follow_redirects=True,
|
|
77
|
+
# httpx re-issues the request against the new URL
|
|
78
|
+
# automatically and returns the final 200 response,
|
|
79
|
+
# so the caller sees the correct data from the moved
|
|
80
|
+
# repo without any awareness that a redirect happened.
|
|
81
|
+
follow_redirects=True,
|
|
82
|
+
)
|
|
83
|
+
self._search_bucket = _RateBucket()
|
|
84
|
+
self._core_bucket = _RateBucket()
|
|
85
|
+
|
|
86
|
+
# -- internal helpers -----------------------------------------------------
|
|
87
|
+
|
|
88
|
+
def _bucket_for(self, path: str) -> _RateBucket:
|
|
89
|
+
return self._search_bucket if path.startswith("/search/") else self._core_bucket
|
|
90
|
+
|
|
91
|
+
async def _request(
|
|
92
|
+
self,
|
|
93
|
+
method: str,
|
|
94
|
+
path: str,
|
|
95
|
+
*,
|
|
96
|
+
params: dict[str, Any] | None = None,
|
|
97
|
+
json: dict[str, Any] | None = None,
|
|
98
|
+
headers: dict[str, str] | None = None,
|
|
99
|
+
) -> httpx.Response:
|
|
100
|
+
"""Issue a request with rate-limit awareness and exponential backoff."""
|
|
101
|
+
bucket = self._bucket_for(path)
|
|
102
|
+
|
|
103
|
+
for attempt in range(_MAX_RETRIES):
|
|
104
|
+
await bucket.wait_if_needed()
|
|
105
|
+
|
|
106
|
+
response = await self._http.request(
|
|
107
|
+
method, path, params=params, json=json, headers=headers
|
|
108
|
+
)
|
|
109
|
+
bucket.update(response.headers)
|
|
110
|
+
|
|
111
|
+
if response.status_code in (403, 429, 502, 503):
|
|
112
|
+
delay = _RETRY_BASE_DELAY * (2**attempt)
|
|
113
|
+
logger.warning(
|
|
114
|
+
"Retryable status %s on %s %s (attempt %d/%d). Sleeping %.1fs.",
|
|
115
|
+
response.status_code,
|
|
116
|
+
method,
|
|
117
|
+
path,
|
|
118
|
+
attempt + 1,
|
|
119
|
+
_MAX_RETRIES,
|
|
120
|
+
delay,
|
|
121
|
+
)
|
|
122
|
+
await asyncio.sleep(delay)
|
|
123
|
+
continue
|
|
124
|
+
|
|
125
|
+
response.raise_for_status()
|
|
126
|
+
return response
|
|
127
|
+
|
|
128
|
+
# Final attempt already failed; raise
|
|
129
|
+
response.raise_for_status()
|
|
130
|
+
return response # unreachable, but keeps the type checker happy
|
|
131
|
+
|
|
132
|
+
async def _get(
|
|
133
|
+
self,
|
|
134
|
+
path: str,
|
|
135
|
+
*,
|
|
136
|
+
params: dict[str, Any] | None = None,
|
|
137
|
+
headers: dict[str, str] | None = None,
|
|
138
|
+
) -> Any:
|
|
139
|
+
resp = await self._request("GET", path, params=params, headers=headers)
|
|
140
|
+
return resp.json()
|
|
141
|
+
|
|
142
|
+
# -- Search API -----------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
async def search_code(
|
|
145
|
+
self, query: str, *, page: int = 1, per_page: int = 30
|
|
146
|
+
) -> dict[str, Any]:
|
|
147
|
+
"""Search code across GitHub (uses text-match fragment headers)."""
|
|
148
|
+
return await self._get(
|
|
149
|
+
"/search/code",
|
|
150
|
+
params={"q": query, "page": page, "per_page": per_page},
|
|
151
|
+
headers={"Accept": "application/vnd.github.text-match+json"},
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
async def search_repos(
|
|
155
|
+
self,
|
|
156
|
+
query: str,
|
|
157
|
+
*,
|
|
158
|
+
sort: str = "best match",
|
|
159
|
+
order: str = "desc",
|
|
160
|
+
page: int = 1,
|
|
161
|
+
per_page: int = 30,
|
|
162
|
+
) -> dict[str, Any]:
|
|
163
|
+
"""Search repositories."""
|
|
164
|
+
params: dict[str, Any] = {"q": query, "page": page, "per_page": per_page}
|
|
165
|
+
if sort != "best match":
|
|
166
|
+
params["sort"] = sort
|
|
167
|
+
params["order"] = order
|
|
168
|
+
return await self._get("/search/repositories", params=params)
|
|
169
|
+
|
|
170
|
+
# -- Repos / Contents -----------------------------------------------------
|
|
171
|
+
|
|
172
|
+
async def get_repo(
|
|
173
|
+
self, owner: str, repo: str
|
|
174
|
+
) -> dict[str, Any]:
|
|
175
|
+
"""Get repository metadata (includes default_branch)."""
|
|
176
|
+
return await self._get(f"/repos/{owner}/{repo}")
|
|
177
|
+
|
|
178
|
+
async def get_contents(
|
|
179
|
+
self, owner: str, repo: str, path: str, *, ref: str | None = None
|
|
180
|
+
) -> dict[str, Any]:
|
|
181
|
+
"""Get repository file or directory contents."""
|
|
182
|
+
params = {"ref": ref} if ref else None
|
|
183
|
+
return await self._get(f"/repos/{owner}/{repo}/contents/{path}", params=params)
|
|
184
|
+
|
|
185
|
+
async def get_tree(
|
|
186
|
+
self, owner: str, repo: str, sha: str, *, recursive: bool = False
|
|
187
|
+
) -> dict[str, Any]:
|
|
188
|
+
"""Get a Git tree."""
|
|
189
|
+
params = {"recursive": "1"} if recursive else None
|
|
190
|
+
return await self._get(f"/repos/{owner}/{repo}/git/trees/{sha}", params=params)
|
|
191
|
+
|
|
192
|
+
# -- Commits / Compare ----------------------------------------------------
|
|
193
|
+
|
|
194
|
+
async def get_commits(
|
|
195
|
+
self,
|
|
196
|
+
owner: str,
|
|
197
|
+
repo: str,
|
|
198
|
+
*,
|
|
199
|
+
path: str | None = None,
|
|
200
|
+
author: str | None = None,
|
|
201
|
+
since: str | None = None,
|
|
202
|
+
until: str | None = None,
|
|
203
|
+
sha: str | None = None,
|
|
204
|
+
page: int = 1,
|
|
205
|
+
per_page: int = 30,
|
|
206
|
+
) -> list[dict[str, Any]]:
|
|
207
|
+
"""List commits for a repository."""
|
|
208
|
+
params: dict[str, Any] = {"page": page, "per_page": per_page}
|
|
209
|
+
if path:
|
|
210
|
+
params["path"] = path
|
|
211
|
+
if author:
|
|
212
|
+
params["author"] = author
|
|
213
|
+
if since:
|
|
214
|
+
params["since"] = since
|
|
215
|
+
if until:
|
|
216
|
+
params["until"] = until
|
|
217
|
+
if sha:
|
|
218
|
+
params["sha"] = sha
|
|
219
|
+
return await self._get(f"/repos/{owner}/{repo}/commits", params=params)
|
|
220
|
+
|
|
221
|
+
# -- Tags / Releases ------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
async def get_tags(
|
|
224
|
+
self, owner: str, repo: str, *, page: int = 1, per_page: int = 30
|
|
225
|
+
) -> list[dict[str, Any]]:
|
|
226
|
+
"""List repository tags."""
|
|
227
|
+
return await self._get(
|
|
228
|
+
f"/repos/{owner}/{repo}/tags",
|
|
229
|
+
params={"page": page, "per_page": per_page},
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
async def get_releases(
|
|
233
|
+
self, owner: str, repo: str, *, page: int = 1, per_page: int = 30
|
|
234
|
+
) -> list[dict[str, Any]]:
|
|
235
|
+
"""List repository releases."""
|
|
236
|
+
return await self._get(
|
|
237
|
+
f"/repos/{owner}/{repo}/releases",
|
|
238
|
+
params={"page": page, "per_page": per_page},
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
# -- Lifecycle ------------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
async def close(self) -> None:
|
|
244
|
+
await self._http.aclose()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ---------------------------------------------------------------------------
|
|
248
|
+
# Module-level singleton
|
|
249
|
+
# ---------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
_client: GitHubClient | None = None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _resolve_token() -> str:
|
|
255
|
+
"""Try multiple sources to find a GitHub token.
|
|
256
|
+
|
|
257
|
+
Preference order:
|
|
258
|
+
1. GH_TOKEN / GITHUB_TOKEN / GITHUB_PERSONAL_ACCESS_TOKEN env vars
|
|
259
|
+
2. `gh auth token` (GitHub CLI)
|
|
260
|
+
"""
|
|
261
|
+
for var in ("GH_TOKEN", "GITHUB_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN"):
|
|
262
|
+
token = os.environ.get(var, "").strip()
|
|
263
|
+
if token:
|
|
264
|
+
return token
|
|
265
|
+
# Fall back to GitHub CLI
|
|
266
|
+
if shutil.which("gh"):
|
|
267
|
+
try:
|
|
268
|
+
result = subprocess.run(
|
|
269
|
+
["gh", "auth", "token"],
|
|
270
|
+
capture_output=True, text=True, timeout=5,
|
|
271
|
+
)
|
|
272
|
+
if result.returncode == 0:
|
|
273
|
+
token = result.stdout.strip()
|
|
274
|
+
if token:
|
|
275
|
+
return token
|
|
276
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
277
|
+
pass
|
|
278
|
+
return ""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def get_client() -> GitHubClient:
|
|
282
|
+
"""Return the shared GitHubClient, creating it lazily on first call."""
|
|
283
|
+
global _client
|
|
284
|
+
if _client is None:
|
|
285
|
+
token = _resolve_token()
|
|
286
|
+
if not token:
|
|
287
|
+
raise RuntimeError(
|
|
288
|
+
"No GitHub token found. Set GITHUB_TOKEN env var, "
|
|
289
|
+
"run `gh auth login`, or add to macOS Keychain."
|
|
290
|
+
)
|
|
291
|
+
_client = GitHubClient(token)
|
|
292
|
+
return _client
|
fossick/hints.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Hint generation engine — suggests logical next steps after each tool call.
|
|
2
|
+
|
|
3
|
+
Fossick v2 is discovery-focused (7 tools, no archaeology tools like
|
|
4
|
+
blame/compare/search_prs/find_references). Hint rules only chain between
|
|
5
|
+
discovery tools.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
# Each rule: (tool_name, condition, template, priority)
|
|
13
|
+
# Lower priority number = higher importance.
|
|
14
|
+
_Rule = tuple[str, Callable[[dict[str, Any], dict[str, Any]], bool], str, int]
|
|
15
|
+
|
|
16
|
+
_RULES: list[_Rule] = [
|
|
17
|
+
# search_code
|
|
18
|
+
("search_code", lambda p, r: r.get("total_count", 0) > 0,
|
|
19
|
+
"`get_file` — read a matched file", 1),
|
|
20
|
+
("search_code", lambda p, r: r.get("total_count", 0) > int(p.get("per_page", 30)),
|
|
21
|
+
"`page=N` — more results available", 2),
|
|
22
|
+
("search_code", lambda p, r: r.get("total_count", 0) > 0,
|
|
23
|
+
"`find_symbol` — find where it's defined", 3),
|
|
24
|
+
# search_repos — in single-query mode the top hint nudges toward
|
|
25
|
+
# multi-phrasing, because description-phrase matching is sharp but
|
|
26
|
+
# narrow: single queries routinely miss popular options that
|
|
27
|
+
# describe themselves with different wording (e.g. searching
|
|
28
|
+
# "Postgres operator" misses CloudNativePG, which says
|
|
29
|
+
# "Kubernetes-native PostgreSQL"). The nudge drops off automatically
|
|
30
|
+
# once `queries=` is used (num_queries >= 2), so the old
|
|
31
|
+
# repo_tree/search_code hints float up in multi-query mode.
|
|
32
|
+
("search_repos",
|
|
33
|
+
lambda p, r: p.get("num_queries", 1) <= 1 and r.get("total_count", 0) > 0,
|
|
34
|
+
"`queries=[...]` — shortlisting? rerun with 2-4 phrasings; single-phrase `in:description` routinely misses popular options that describe themselves differently",
|
|
35
|
+
1),
|
|
36
|
+
("search_repos", lambda p, r: r.get("total_count", 0) > 0,
|
|
37
|
+
"`repo_tree` — explore repo structure", 2),
|
|
38
|
+
("search_repos", lambda p, r: r.get("total_count", 0) > 0,
|
|
39
|
+
"`search_code` — search code in the repo", 3),
|
|
40
|
+
# get_file
|
|
41
|
+
("get_file", lambda p, r: True,
|
|
42
|
+
"`find_symbol` — locate a class/function definition", 1),
|
|
43
|
+
("get_file", lambda p, r: True,
|
|
44
|
+
"`search_code` — find usage patterns for something in this file", 2),
|
|
45
|
+
# repo_tree
|
|
46
|
+
("repo_tree", lambda p, r: True,
|
|
47
|
+
"`get_file` — read a file from the tree", 1),
|
|
48
|
+
("repo_tree", lambda p, r: True,
|
|
49
|
+
"`search_code` — search within repo", 2),
|
|
50
|
+
# find_symbol
|
|
51
|
+
("find_symbol", lambda p, r: r.get("total_count", 0) > 0,
|
|
52
|
+
"`get_file` — read the definition with surrounding context", 1),
|
|
53
|
+
("find_symbol", lambda p, r: r.get("total_count", 0) > 0,
|
|
54
|
+
"`search_code` — find real-world usages of this symbol", 2),
|
|
55
|
+
# search_packages
|
|
56
|
+
("search_packages", lambda p, r: True,
|
|
57
|
+
"`search_repos` — find the source repo", 1),
|
|
58
|
+
("search_packages", lambda p, r: True,
|
|
59
|
+
"`search_code` — find where it's imported in other projects", 2),
|
|
60
|
+
# list_tags
|
|
61
|
+
("list_tags", lambda p, r: True,
|
|
62
|
+
"`get_file(ref=<tag>)` — read a file at a specific release", 1),
|
|
63
|
+
("list_tags", lambda p, r: True,
|
|
64
|
+
"`repo_tree(ref=<tag>)` — browse the repo layout at a specific release", 2),
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def generate_hints(
|
|
69
|
+
tool_name: str, params: dict[str, Any], result: dict[str, Any]
|
|
70
|
+
) -> list[str]:
|
|
71
|
+
"""Return up to 2 contextual hints sorted by priority."""
|
|
72
|
+
matched: list[tuple[int, str]] = []
|
|
73
|
+
for rule_tool, condition, template, priority in _RULES:
|
|
74
|
+
if rule_tool != tool_name:
|
|
75
|
+
continue
|
|
76
|
+
try:
|
|
77
|
+
if condition(params, result):
|
|
78
|
+
matched.append((priority, template))
|
|
79
|
+
except Exception: # noqa: BLE001
|
|
80
|
+
continue
|
|
81
|
+
matched.sort(key=lambda t: t[0])
|
|
82
|
+
return [text for _, text in matched[:2]]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def format_hints(hints: list[str]) -> str:
|
|
86
|
+
"""Format a list of hint strings as a Markdown section."""
|
|
87
|
+
if not hints:
|
|
88
|
+
return ""
|
|
89
|
+
lines = ["", "---", "**Suggested next steps:**"]
|
|
90
|
+
for hint in hints:
|
|
91
|
+
lines.append(f"- {hint}")
|
|
92
|
+
return "\n".join(lines)
|
fossick/server.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""FastMCP server definition for fossick."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
from contextlib import asynccontextmanager
|
|
5
|
+
|
|
6
|
+
from mcp.server.fastmcp import FastMCP
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@asynccontextmanager
|
|
10
|
+
async def _lifespan(server: FastMCP) -> AsyncIterator[dict]:
|
|
11
|
+
"""Manage the httpx client lifecycle."""
|
|
12
|
+
from fossick.github_client import get_client
|
|
13
|
+
client = get_client()
|
|
14
|
+
try:
|
|
15
|
+
yield {"github_client": client}
|
|
16
|
+
finally:
|
|
17
|
+
await client.close()
|
|
18
|
+
|
|
19
|
+
_INSTRUCTIONS = (
|
|
20
|
+
"Fossick helps you discover and evaluate new libraries, frameworks, "
|
|
21
|
+
"and packages to adopt in new projects. Its seven tools cover the "
|
|
22
|
+
"'I'm starting a project and need to find the right dependency' "
|
|
23
|
+
"workflow end-to-end, across all 200M+ GitHub repos plus PyPI and npm. "
|
|
24
|
+
"NOT for code archaeology (git history, blame, PR tracking, version diffing) — "
|
|
25
|
+
"use git / gh CLI via Bash for that. "
|
|
26
|
+
"Tool selection: "
|
|
27
|
+
"1. Use 'search_repos' to discover libraries by topic, stars, language, or trending — "
|
|
28
|
+
"this is where most discovery sessions start. "
|
|
29
|
+
"2. Use 'search_packages' for direct PyPI/npm lookups when you already know the package name. "
|
|
30
|
+
"3. Use 'search_code' to find real-world usage patterns — how do other projects "
|
|
31
|
+
"actually import and call library X? Supports regex, boolean operators, and qualifiers like "
|
|
32
|
+
"repo:, language:, path:. "
|
|
33
|
+
"4. Use 'find_symbol' to locate a class/function/type definition — 'where is "
|
|
34
|
+
"X defined?' — so you can read its declaration and understand the API surface. "
|
|
35
|
+
"5. Use 'repo_tree' to browse a repository's layout and 'get_file' to read "
|
|
36
|
+
"specific files (READMEs, examples, the main module). "
|
|
37
|
+
"6. Use 'list_tags' to check freshness — 'is this library actively maintained?' — "
|
|
38
|
+
"and see recent releases. "
|
|
39
|
+
"Usage guidance: "
|
|
40
|
+
"Use the convenience params (repo, language, path) instead of embedding qualifiers in the query string. "
|
|
41
|
+
"Use pagination — results default to page 1, request more with page=2. "
|
|
42
|
+
"Chain tools: search_repos → repo_tree → get_file to evaluate a candidate library; "
|
|
43
|
+
"search_code → get_file → find_symbol to understand how an API is used in the wild."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
mcp = FastMCP("fossick", instructions=_INSTRUCTIONS, lifespan=_lifespan)
|
|
47
|
+
|
|
48
|
+
# Import tool modules to trigger @mcp.tool() registration
|
|
49
|
+
from fossick.tools import ( # noqa: F401, E402
|
|
50
|
+
find_symbol,
|
|
51
|
+
get_file,
|
|
52
|
+
list_tags,
|
|
53
|
+
repo_tree,
|
|
54
|
+
search_code,
|
|
55
|
+
search_packages,
|
|
56
|
+
search_repos,
|
|
57
|
+
)
|