pocketdex-mcp 0.2.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.
- pocketdex.py +810 -0
- pocketdex_mcp-0.2.0.dist-info/METADATA +226 -0
- pocketdex_mcp-0.2.0.dist-info/RECORD +7 -0
- pocketdex_mcp-0.2.0.dist-info/WHEEL +5 -0
- pocketdex_mcp-0.2.0.dist-info/entry_points.txt +2 -0
- pocketdex_mcp-0.2.0.dist-info/licenses/LICENSE +21 -0
- pocketdex_mcp-0.2.0.dist-info/top_level.txt +1 -0
pocketdex.py
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""pocketdex — a tiny local code index, one database per project.
|
|
3
|
+
|
|
4
|
+
One file, no dependencies, no background server. Each project gets its own
|
|
5
|
+
SQLite FTS5 database inside pocketdex's own data folder, so indexes never mix.
|
|
6
|
+
|
|
7
|
+
pocketdex index ~/Projects/my-app
|
|
8
|
+
pocketdex search "parse_amount_cents"
|
|
9
|
+
pocketdex stats
|
|
10
|
+
pocketdex serve # MCP stdio server
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import sqlite3
|
|
21
|
+
import sys
|
|
22
|
+
import time
|
|
23
|
+
from datetime import datetime, timezone
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any, Iterable, Iterator
|
|
26
|
+
|
|
27
|
+
VERSION = "0.2.0"
|
|
28
|
+
SCHEMA_VERSION = "1"
|
|
29
|
+
|
|
30
|
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def default_data_dir() -> Path:
|
|
34
|
+
"""Repo-local data for a clone; user data dir for an installed package."""
|
|
35
|
+
env = os.environ.get("POCKETDEX_DATA")
|
|
36
|
+
if env:
|
|
37
|
+
return Path(env).expanduser()
|
|
38
|
+
local = PACKAGE_DIR / "data" / "projects"
|
|
39
|
+
try:
|
|
40
|
+
local.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
if os.access(local.parent, os.W_OK):
|
|
42
|
+
return local
|
|
43
|
+
except OSError:
|
|
44
|
+
pass
|
|
45
|
+
return Path("~/.local/share/pocketdex/projects").expanduser()
|
|
46
|
+
|
|
47
|
+
# Directories that never contain hand-written source worth indexing.
|
|
48
|
+
IGNORE_DIRS = {
|
|
49
|
+
".git", ".hg", ".svn", ".idea", ".vscode", ".venv", "venv", "env",
|
|
50
|
+
"node_modules", "bower_components", "dist", "build", "out", "target",
|
|
51
|
+
"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox",
|
|
52
|
+
".nox", ".eggs", "coverage", "htmlcov", ".next", ".nuxt", ".cache",
|
|
53
|
+
"vendor", "third_party", "site-packages",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
# Lockfiles and generated maps are noise for code search.
|
|
57
|
+
IGNORE_NAMES = {
|
|
58
|
+
"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb",
|
|
59
|
+
"poetry.lock", "uv.lock", "Pipfile.lock", "Cargo.lock", "composer.lock",
|
|
60
|
+
"Gemfile.lock",
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
MAX_FILE_BYTES = 512 * 1024
|
|
64
|
+
MAX_LINE_LENGTH = 1000
|
|
65
|
+
CHUNK_LINES = 40
|
|
66
|
+
CHUNK_OVERLAP = 12
|
|
67
|
+
MAX_TOKENS_IN_QUERY = 8
|
|
68
|
+
|
|
69
|
+
TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|\d+")
|
|
70
|
+
|
|
71
|
+
SCHEMA = """
|
|
72
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
73
|
+
key TEXT PRIMARY KEY,
|
|
74
|
+
value TEXT NOT NULL
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
78
|
+
id INTEGER PRIMARY KEY,
|
|
79
|
+
root TEXT NOT NULL UNIQUE,
|
|
80
|
+
indexed_at TEXT NOT NULL
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
84
|
+
id INTEGER PRIMARY KEY,
|
|
85
|
+
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
86
|
+
path TEXT NOT NULL,
|
|
87
|
+
mtime_ns INTEGER NOT NULL,
|
|
88
|
+
size INTEGER NOT NULL,
|
|
89
|
+
UNIQUE (project_id, path)
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
CREATE TABLE IF NOT EXISTS chunks (
|
|
93
|
+
id INTEGER PRIMARY KEY,
|
|
94
|
+
file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
|
|
95
|
+
project_id INTEGER NOT NULL,
|
|
96
|
+
path TEXT NOT NULL,
|
|
97
|
+
start_line INTEGER NOT NULL,
|
|
98
|
+
end_line INTEGER NOT NULL,
|
|
99
|
+
content TEXT NOT NULL
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
|
|
103
|
+
content,
|
|
104
|
+
path,
|
|
105
|
+
content='chunks',
|
|
106
|
+
content_rowid='id',
|
|
107
|
+
tokenize="unicode61 remove_diacritics 2 tokenchars '_'",
|
|
108
|
+
prefix='2 3'
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN
|
|
112
|
+
INSERT INTO chunks_fts(rowid, content, path)
|
|
113
|
+
VALUES (new.id, new.content, new.path);
|
|
114
|
+
END;
|
|
115
|
+
|
|
116
|
+
CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN
|
|
117
|
+
INSERT INTO chunks_fts(chunks_fts, rowid, content, path)
|
|
118
|
+
VALUES ('delete', old.id, old.content, old.path);
|
|
119
|
+
END;
|
|
120
|
+
|
|
121
|
+
CREATE TRIGGER IF NOT EXISTS chunks_au AFTER UPDATE ON chunks BEGIN
|
|
122
|
+
INSERT INTO chunks_fts(chunks_fts, rowid, content, path)
|
|
123
|
+
VALUES ('delete', old.id, old.content, old.path);
|
|
124
|
+
INSERT INTO chunks_fts(rowid, content, path)
|
|
125
|
+
VALUES (new.id, new.content, new.path);
|
|
126
|
+
END;
|
|
127
|
+
|
|
128
|
+
CREATE INDEX IF NOT EXISTS idx_chunks_project_path
|
|
129
|
+
ON chunks(project_id, path);
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class PocketdexError(Exception):
|
|
134
|
+
"""A problem the user (or agent) can fix: no index, missing folder."""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# --------------------------------------------------------------------------
|
|
138
|
+
# storage
|
|
139
|
+
# --------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def connect(db_path: Path | str) -> sqlite3.Connection:
|
|
143
|
+
db_path = Path(db_path).expanduser()
|
|
144
|
+
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
145
|
+
conn = sqlite3.connect(str(db_path), timeout=10, isolation_level=None)
|
|
146
|
+
conn.row_factory = sqlite3.Row
|
|
147
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
148
|
+
conn.execute("PRAGMA foreign_keys=ON")
|
|
149
|
+
conn.executescript(SCHEMA)
|
|
150
|
+
|
|
151
|
+
row = conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()
|
|
152
|
+
if row is None:
|
|
153
|
+
conn.execute(
|
|
154
|
+
"INSERT INTO meta(key, value) VALUES('schema_version', ?)",
|
|
155
|
+
(SCHEMA_VERSION,),
|
|
156
|
+
)
|
|
157
|
+
elif row["value"] != SCHEMA_VERSION:
|
|
158
|
+
raise PocketdexError(
|
|
159
|
+
f"index schema {row['value']} is not version {SCHEMA_VERSION}; "
|
|
160
|
+
f"delete {db_path} and re-index"
|
|
161
|
+
)
|
|
162
|
+
return conn
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def utc_now() -> str:
|
|
166
|
+
return datetime.now(timezone.utc).isoformat(timespec="microseconds")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def normalize_root(root: str | Path) -> Path:
|
|
170
|
+
path = Path(root).expanduser().resolve()
|
|
171
|
+
if not path.is_dir():
|
|
172
|
+
raise PocketdexError(f"not a directory: {path}")
|
|
173
|
+
return path
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def data_dir_path(data_dir: Path | str | None) -> Path:
|
|
177
|
+
return Path(data_dir if data_dir is not None else default_data_dir()).expanduser()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def project_db_path(root: str | Path, data_dir: Path | str | None = None) -> Path:
|
|
181
|
+
"""One stable database file per absolute project path."""
|
|
182
|
+
root = normalize_root(root)
|
|
183
|
+
slug = re.sub(r"[^A-Za-z0-9._-]+", "-", root.name).strip(".-") or "project"
|
|
184
|
+
digest = hashlib.sha1(str(root).encode("utf-8")).hexdigest()[:8]
|
|
185
|
+
return data_dir_path(data_dir) / f"{slug}-{digest}.db"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def get_or_create_project(conn: sqlite3.Connection, root: Path) -> int:
|
|
189
|
+
row = conn.execute("SELECT id FROM projects WHERE root = ?", (str(root),)).fetchone()
|
|
190
|
+
if row:
|
|
191
|
+
return int(row["id"])
|
|
192
|
+
cur = conn.execute(
|
|
193
|
+
"INSERT INTO projects(root, indexed_at) VALUES(?, ?)", (str(root), utc_now())
|
|
194
|
+
)
|
|
195
|
+
return int(cur.lastrowid)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# --------------------------------------------------------------------------
|
|
199
|
+
# indexing
|
|
200
|
+
# --------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def iter_source_files(root: Path) -> Iterator[tuple[Path, os.stat_result]]:
|
|
204
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
205
|
+
dirnames[:] = sorted(
|
|
206
|
+
d for d in dirnames if d not in IGNORE_DIRS and not d.startswith(".")
|
|
207
|
+
)
|
|
208
|
+
for name in sorted(filenames):
|
|
209
|
+
if name in IGNORE_NAMES or name.endswith(".min.js"):
|
|
210
|
+
continue
|
|
211
|
+
path = Path(dirpath) / name
|
|
212
|
+
try:
|
|
213
|
+
stat = path.stat()
|
|
214
|
+
except OSError:
|
|
215
|
+
continue
|
|
216
|
+
if stat.st_size == 0 or stat.st_size > MAX_FILE_BYTES:
|
|
217
|
+
continue
|
|
218
|
+
yield path, stat
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def read_source(path: Path) -> str | None:
|
|
222
|
+
"""Return UTF-8 text, or None for binary / unreadable files."""
|
|
223
|
+
try:
|
|
224
|
+
data = path.read_bytes()
|
|
225
|
+
except OSError:
|
|
226
|
+
return None
|
|
227
|
+
if b"\x00" in data[:4096]:
|
|
228
|
+
return None
|
|
229
|
+
text = data.decode("utf-8", errors="replace")
|
|
230
|
+
lines = text.splitlines()
|
|
231
|
+
# Minified bundles: a couple of enormous lines, no structure.
|
|
232
|
+
if lines and len(lines) <= 3 and max(len(line) for line in lines) > MAX_LINE_LENGTH:
|
|
233
|
+
return None
|
|
234
|
+
return text
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def chunk_text(text: str) -> Iterator[tuple[int, int, str]]:
|
|
238
|
+
lines = text.splitlines()
|
|
239
|
+
if not lines:
|
|
240
|
+
return
|
|
241
|
+
step = CHUNK_LINES - CHUNK_OVERLAP
|
|
242
|
+
start = 0
|
|
243
|
+
while start < len(lines):
|
|
244
|
+
end = min(start + CHUNK_LINES, len(lines))
|
|
245
|
+
yield start + 1, end, "\n".join(lines[start:end])
|
|
246
|
+
if end == len(lines):
|
|
247
|
+
break
|
|
248
|
+
start += step
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def index_project(
|
|
252
|
+
root: str | Path,
|
|
253
|
+
force: bool = False,
|
|
254
|
+
data_dir: Path | str | None = None,
|
|
255
|
+
) -> dict[str, Any]:
|
|
256
|
+
root = normalize_root(root)
|
|
257
|
+
db_path = project_db_path(root, data_dir)
|
|
258
|
+
conn = connect(db_path)
|
|
259
|
+
started = time.perf_counter()
|
|
260
|
+
|
|
261
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
262
|
+
try:
|
|
263
|
+
project_id = get_or_create_project(conn, root)
|
|
264
|
+
existing = {
|
|
265
|
+
row["path"]: row
|
|
266
|
+
for row in conn.execute(
|
|
267
|
+
"SELECT id, path, mtime_ns, size FROM files WHERE project_id = ?",
|
|
268
|
+
(project_id,),
|
|
269
|
+
)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
seen: set[str] = set()
|
|
273
|
+
indexed = unchanged = skipped = removed = chunks_written = 0
|
|
274
|
+
|
|
275
|
+
for path, stat in iter_source_files(root):
|
|
276
|
+
rel = path.relative_to(root).as_posix()
|
|
277
|
+
seen.add(rel)
|
|
278
|
+
prior = existing.get(rel)
|
|
279
|
+
if (
|
|
280
|
+
not force
|
|
281
|
+
and prior is not None
|
|
282
|
+
and int(prior["mtime_ns"]) == stat.st_mtime_ns
|
|
283
|
+
and int(prior["size"]) == stat.st_size
|
|
284
|
+
):
|
|
285
|
+
unchanged += 1
|
|
286
|
+
continue
|
|
287
|
+
|
|
288
|
+
text = read_source(path)
|
|
289
|
+
if text is None:
|
|
290
|
+
if prior is not None:
|
|
291
|
+
conn.execute(
|
|
292
|
+
"DELETE FROM chunks WHERE project_id = ? AND path = ?",
|
|
293
|
+
(project_id, rel),
|
|
294
|
+
)
|
|
295
|
+
conn.execute(
|
|
296
|
+
"DELETE FROM files WHERE project_id = ? AND path = ?",
|
|
297
|
+
(project_id, rel),
|
|
298
|
+
)
|
|
299
|
+
removed += 1
|
|
300
|
+
skipped += 1
|
|
301
|
+
continue
|
|
302
|
+
|
|
303
|
+
# Delete old chunks first so the FTS triggers fire cleanly.
|
|
304
|
+
conn.execute(
|
|
305
|
+
"DELETE FROM chunks WHERE project_id = ? AND path = ?",
|
|
306
|
+
(project_id, rel),
|
|
307
|
+
)
|
|
308
|
+
conn.execute(
|
|
309
|
+
"DELETE FROM files WHERE project_id = ? AND path = ?",
|
|
310
|
+
(project_id, rel),
|
|
311
|
+
)
|
|
312
|
+
cur = conn.execute(
|
|
313
|
+
"INSERT INTO files(project_id, path, mtime_ns, size) VALUES(?,?,?,?)",
|
|
314
|
+
(project_id, rel, stat.st_mtime_ns, stat.st_size),
|
|
315
|
+
)
|
|
316
|
+
file_id = int(cur.lastrowid)
|
|
317
|
+
|
|
318
|
+
for start, end, content in chunk_text(text):
|
|
319
|
+
conn.execute(
|
|
320
|
+
"INSERT INTO chunks(file_id, project_id, path, start_line, "
|
|
321
|
+
"end_line, content) VALUES(?,?,?,?,?,?)",
|
|
322
|
+
(file_id, project_id, rel, start, end, content),
|
|
323
|
+
)
|
|
324
|
+
chunks_written += 1
|
|
325
|
+
indexed += 1
|
|
326
|
+
|
|
327
|
+
for rel, prior in existing.items():
|
|
328
|
+
if rel not in seen:
|
|
329
|
+
conn.execute("DELETE FROM files WHERE id = ?", (int(prior["id"]),))
|
|
330
|
+
removed += 1
|
|
331
|
+
|
|
332
|
+
conn.execute(
|
|
333
|
+
"UPDATE projects SET indexed_at = ? WHERE id = ?",
|
|
334
|
+
(utc_now(), project_id),
|
|
335
|
+
)
|
|
336
|
+
conn.execute("COMMIT")
|
|
337
|
+
except Exception:
|
|
338
|
+
conn.execute("ROLLBACK")
|
|
339
|
+
conn.close()
|
|
340
|
+
raise
|
|
341
|
+
|
|
342
|
+
result = {
|
|
343
|
+
"project": str(root),
|
|
344
|
+
"db": str(db_path),
|
|
345
|
+
"files_indexed": indexed,
|
|
346
|
+
"files_unchanged": unchanged,
|
|
347
|
+
"files_skipped": skipped,
|
|
348
|
+
"files_removed": removed,
|
|
349
|
+
"chunks": chunks_written,
|
|
350
|
+
"seconds": round(time.perf_counter() - started, 2),
|
|
351
|
+
}
|
|
352
|
+
conn.close()
|
|
353
|
+
return result
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
# --------------------------------------------------------------------------
|
|
357
|
+
# search
|
|
358
|
+
# --------------------------------------------------------------------------
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def build_match(query: str) -> str | None:
|
|
362
|
+
tokens = TOKEN_RE.findall(query)[:MAX_TOKENS_IN_QUERY]
|
|
363
|
+
if not tokens:
|
|
364
|
+
return None
|
|
365
|
+
return " AND ".join(f'"{token}"*' for token in tokens)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _rows_to_results(rows: Iterable[sqlite3.Row], limit: int) -> list[dict[str, Any]]:
|
|
369
|
+
results: list[dict[str, Any]] = []
|
|
370
|
+
per_file: dict[str, int] = {}
|
|
371
|
+
for row in rows:
|
|
372
|
+
path = str(row["path"])
|
|
373
|
+
if per_file.get(path, 0) >= 2:
|
|
374
|
+
continue
|
|
375
|
+
per_file[path] = per_file.get(path, 0) + 1
|
|
376
|
+
results.append(
|
|
377
|
+
{
|
|
378
|
+
"path": path,
|
|
379
|
+
"lines": f"{row['start_line']}-{row['end_line']}",
|
|
380
|
+
"score": round(float(-row["rank"]), 3),
|
|
381
|
+
"snippet": str(row["snippet"]),
|
|
382
|
+
}
|
|
383
|
+
)
|
|
384
|
+
if len(results) >= limit:
|
|
385
|
+
break
|
|
386
|
+
return results
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def latest_root(data_dir: Path | str | None = None) -> Path:
|
|
390
|
+
"""Most recently indexed project, read straight from the per-project DBs."""
|
|
391
|
+
directory = data_dir_path(data_dir)
|
|
392
|
+
best: tuple[str, str] | None = None
|
|
393
|
+
for db_path in sorted(directory.glob("*.db")) if directory.is_dir() else []:
|
|
394
|
+
try:
|
|
395
|
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
|
396
|
+
conn.row_factory = sqlite3.Row
|
|
397
|
+
row = conn.execute(
|
|
398
|
+
"SELECT root, indexed_at FROM projects ORDER BY indexed_at DESC LIMIT 1"
|
|
399
|
+
).fetchone()
|
|
400
|
+
conn.close()
|
|
401
|
+
except sqlite3.Error:
|
|
402
|
+
continue
|
|
403
|
+
if row is not None:
|
|
404
|
+
candidate = (str(row["root"]), str(row["indexed_at"]))
|
|
405
|
+
if best is None or candidate[1] > best[1]:
|
|
406
|
+
best = candidate
|
|
407
|
+
|
|
408
|
+
if best is None:
|
|
409
|
+
raise PocketdexError(
|
|
410
|
+
f"no projects indexed yet in {directory}; call index_project first"
|
|
411
|
+
)
|
|
412
|
+
return Path(best[0])
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def project_rows(conn: sqlite3.Connection) -> sqlite3.Row | None:
|
|
416
|
+
return conn.execute(
|
|
417
|
+
"SELECT id, root, indexed_at FROM projects ORDER BY id LIMIT 1"
|
|
418
|
+
).fetchone()
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def list_projects(data_dir: Path | str | None = None) -> list[dict[str, Any]]:
|
|
422
|
+
directory = data_dir_path(data_dir)
|
|
423
|
+
items: list[dict[str, Any]] = []
|
|
424
|
+
for db_path in sorted(directory.glob("*.db")) if directory.is_dir() else []:
|
|
425
|
+
try:
|
|
426
|
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
|
427
|
+
conn.row_factory = sqlite3.Row
|
|
428
|
+
row = project_rows(conn)
|
|
429
|
+
if row is None:
|
|
430
|
+
conn.close()
|
|
431
|
+
continue
|
|
432
|
+
pid = int(row["id"])
|
|
433
|
+
files = conn.execute(
|
|
434
|
+
"SELECT COUNT(*) AS n FROM files WHERE project_id=?", (pid,)
|
|
435
|
+
).fetchone()["n"]
|
|
436
|
+
chunks = conn.execute(
|
|
437
|
+
"SELECT COUNT(*) AS n FROM chunks WHERE project_id=?", (pid,)
|
|
438
|
+
).fetchone()["n"]
|
|
439
|
+
chars = conn.execute(
|
|
440
|
+
"SELECT COALESCE(SUM(LENGTH(content)),0) AS n FROM chunks WHERE project_id=?",
|
|
441
|
+
(pid,),
|
|
442
|
+
).fetchone()["n"]
|
|
443
|
+
conn.close()
|
|
444
|
+
except sqlite3.Error:
|
|
445
|
+
continue
|
|
446
|
+
|
|
447
|
+
items.append(
|
|
448
|
+
{
|
|
449
|
+
"project": str(row["root"]),
|
|
450
|
+
"db": str(db_path),
|
|
451
|
+
"db_bytes": db_path.stat().st_size,
|
|
452
|
+
"files": int(files),
|
|
453
|
+
"chunks": int(chunks),
|
|
454
|
+
"indexed_chars": int(chars),
|
|
455
|
+
"indexed_at": str(row["indexed_at"]),
|
|
456
|
+
}
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
items.sort(key=lambda item: item["indexed_at"], reverse=True)
|
|
460
|
+
return items
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def open_indexed(root: str | Path, data_dir: Path | str | None = None) -> sqlite3.Connection:
|
|
464
|
+
root = normalize_root(root)
|
|
465
|
+
db_path = project_db_path(root, data_dir)
|
|
466
|
+
if not db_path.exists():
|
|
467
|
+
raise PocketdexError(
|
|
468
|
+
f"{root} is not indexed yet; call index_project with that path first"
|
|
469
|
+
)
|
|
470
|
+
conn = connect(db_path)
|
|
471
|
+
if project_rows(conn) is None:
|
|
472
|
+
conn.close()
|
|
473
|
+
raise PocketdexError(f"{root} has an empty index; re-index it")
|
|
474
|
+
return conn
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def search(
|
|
478
|
+
root: str | Path | None,
|
|
479
|
+
query: str,
|
|
480
|
+
limit: int = 8,
|
|
481
|
+
path_prefix: str | None = None,
|
|
482
|
+
data_dir: Path | str | None = None,
|
|
483
|
+
) -> dict[str, Any]:
|
|
484
|
+
root = normalize_root(root) if root else latest_root(data_dir)
|
|
485
|
+
conn = open_indexed(root, data_dir)
|
|
486
|
+
limit = max(1, min(int(limit), 25))
|
|
487
|
+
match = build_match(query)
|
|
488
|
+
if match is None:
|
|
489
|
+
conn.close()
|
|
490
|
+
return {
|
|
491
|
+
"query": query,
|
|
492
|
+
"project": str(root),
|
|
493
|
+
"db": str(project_db_path(root, data_dir)),
|
|
494
|
+
"count": 0,
|
|
495
|
+
"results": [],
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
pid = int(project_rows(conn)["id"])
|
|
499
|
+
|
|
500
|
+
def run(match_expression: str) -> list[sqlite3.Row]:
|
|
501
|
+
where = ["chunks_fts MATCH ?", "c.project_id = ?"]
|
|
502
|
+
params: list[Any] = [match_expression, pid]
|
|
503
|
+
if path_prefix:
|
|
504
|
+
where.append("c.path LIKE ?")
|
|
505
|
+
params.append(path_prefix.rstrip("/") + "%")
|
|
506
|
+
sql = f"""
|
|
507
|
+
SELECT c.path, c.start_line, c.end_line,
|
|
508
|
+
snippet(chunks_fts, 0, '**', '**', '…', 12) AS snippet,
|
|
509
|
+
bm25(chunks_fts, 1.0, 0.4) AS rank
|
|
510
|
+
FROM chunks_fts
|
|
511
|
+
JOIN chunks c ON c.id = chunks_fts.rowid
|
|
512
|
+
WHERE {' AND '.join(where)}
|
|
513
|
+
ORDER BY rank
|
|
514
|
+
LIMIT ?
|
|
515
|
+
"""
|
|
516
|
+
return conn.execute(sql, (*params, limit * 6)).fetchall()
|
|
517
|
+
|
|
518
|
+
results = _rows_to_results(run(match), limit)
|
|
519
|
+
|
|
520
|
+
if not results:
|
|
521
|
+
# Second chance: split identifiers on _ and camelCase, match any part.
|
|
522
|
+
parts: list[str] = []
|
|
523
|
+
for token in TOKEN_RE.findall(query)[:MAX_TOKENS_IN_QUERY]:
|
|
524
|
+
parts.extend(p for p in re.split(r"_+|(?<=[a-z])(?=[A-Z])", token) if p)
|
|
525
|
+
if parts:
|
|
526
|
+
fallback = " OR ".join(f'"{part}"*' for part in dict.fromkeys(parts))
|
|
527
|
+
results = _rows_to_results(run(fallback), limit)
|
|
528
|
+
|
|
529
|
+
response = {
|
|
530
|
+
"query": query,
|
|
531
|
+
"project": str(root),
|
|
532
|
+
"db": str(project_db_path(root, data_dir)),
|
|
533
|
+
"count": len(results),
|
|
534
|
+
"results": results,
|
|
535
|
+
}
|
|
536
|
+
conn.close()
|
|
537
|
+
return response
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def stats(
|
|
541
|
+
project: str | Path | None = None,
|
|
542
|
+
data_dir: Path | str | None = None,
|
|
543
|
+
) -> dict[str, Any]:
|
|
544
|
+
directory = data_dir_path(data_dir)
|
|
545
|
+
if project:
|
|
546
|
+
root = normalize_root(project)
|
|
547
|
+
items = [item for item in list_projects(directory) if item["project"] == str(root)]
|
|
548
|
+
if not items:
|
|
549
|
+
raise PocketdexError(
|
|
550
|
+
f"{root} is not indexed yet; call index_project with that path first"
|
|
551
|
+
)
|
|
552
|
+
else:
|
|
553
|
+
items = list_projects(directory)
|
|
554
|
+
|
|
555
|
+
return {"data_dir": str(directory), "projects": items}
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
# --------------------------------------------------------------------------
|
|
559
|
+
# MCP server (stdio, newline-delimited JSON-RPC 2.0)
|
|
560
|
+
# --------------------------------------------------------------------------
|
|
561
|
+
|
|
562
|
+
TOOLS: list[dict[str, Any]] = [
|
|
563
|
+
{
|
|
564
|
+
"name": "index_project",
|
|
565
|
+
"description": (
|
|
566
|
+
"Index or refresh one project folder in its own private database. "
|
|
567
|
+
"Call once before searching an unfamiliar repository, and again "
|
|
568
|
+
"after large changes. Incremental: unchanged files are skipped."
|
|
569
|
+
),
|
|
570
|
+
"inputSchema": {
|
|
571
|
+
"type": "object",
|
|
572
|
+
"properties": {
|
|
573
|
+
"root": {"type": "string", "description": "Absolute path to the project folder."},
|
|
574
|
+
"force": {
|
|
575
|
+
"type": "boolean",
|
|
576
|
+
"description": "Re-index every file even if mtime and size match.",
|
|
577
|
+
"default": False,
|
|
578
|
+
},
|
|
579
|
+
},
|
|
580
|
+
"required": ["root"],
|
|
581
|
+
},
|
|
582
|
+
},
|
|
583
|
+
{
|
|
584
|
+
"name": "search",
|
|
585
|
+
"description": (
|
|
586
|
+
"Search one project's index by keyword or identifier. Returns file "
|
|
587
|
+
"paths, line ranges and short highlighted snippets, so use this "
|
|
588
|
+
"before opening whole files. Good for 'where is X', 'who calls Y', "
|
|
589
|
+
"'how is Z implemented'."
|
|
590
|
+
),
|
|
591
|
+
"inputSchema": {
|
|
592
|
+
"type": "object",
|
|
593
|
+
"properties": {
|
|
594
|
+
"query": {"type": "string", "description": "Words or identifiers to find."},
|
|
595
|
+
"project": {
|
|
596
|
+
"type": "string",
|
|
597
|
+
"description": "Project root. Defaults to the most recently indexed project.",
|
|
598
|
+
},
|
|
599
|
+
"path_prefix": {
|
|
600
|
+
"type": "string",
|
|
601
|
+
"description": "Only search files under this relative path, e.g. 'src/api'.",
|
|
602
|
+
},
|
|
603
|
+
"limit": {
|
|
604
|
+
"type": "integer",
|
|
605
|
+
"description": "Maximum results (1-25). Default 8.",
|
|
606
|
+
"minimum": 1,
|
|
607
|
+
"maximum": 25,
|
|
608
|
+
},
|
|
609
|
+
},
|
|
610
|
+
"required": ["query"],
|
|
611
|
+
},
|
|
612
|
+
},
|
|
613
|
+
{
|
|
614
|
+
"name": "stats",
|
|
615
|
+
"description": (
|
|
616
|
+
"Show indexed projects, their separate databases, file and chunk "
|
|
617
|
+
"counts, and index size. Use to check whether a folder is indexed."
|
|
618
|
+
),
|
|
619
|
+
"inputSchema": {
|
|
620
|
+
"type": "object",
|
|
621
|
+
"properties": {
|
|
622
|
+
"project": {"type": "string", "description": "Project root. Defaults to all projects."}
|
|
623
|
+
},
|
|
624
|
+
},
|
|
625
|
+
},
|
|
626
|
+
]
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def call_tool(data_dir: Path | str | None, name: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
630
|
+
if name == "index_project":
|
|
631
|
+
root = args.get("root")
|
|
632
|
+
if not isinstance(root, str) or not root.strip():
|
|
633
|
+
raise PocketdexError("root must be a non-empty string")
|
|
634
|
+
return index_project(root, bool(args.get("force", False)), data_dir)
|
|
635
|
+
|
|
636
|
+
if name == "search":
|
|
637
|
+
query = args.get("query")
|
|
638
|
+
if not isinstance(query, str) or not query.strip():
|
|
639
|
+
raise PocketdexError("query must be a non-empty string")
|
|
640
|
+
limit = args.get("limit", 8)
|
|
641
|
+
if not isinstance(limit, int):
|
|
642
|
+
raise PocketdexError("limit must be an integer")
|
|
643
|
+
prefix = args.get("path_prefix")
|
|
644
|
+
if prefix is not None and not isinstance(prefix, str):
|
|
645
|
+
raise PocketdexError("path_prefix must be a string")
|
|
646
|
+
project = args.get("project")
|
|
647
|
+
if project is not None and not isinstance(project, str):
|
|
648
|
+
raise PocketdexError("project must be a string")
|
|
649
|
+
return search(project, query, limit=limit, path_prefix=prefix, data_dir=data_dir)
|
|
650
|
+
|
|
651
|
+
if name == "stats":
|
|
652
|
+
project = args.get("project")
|
|
653
|
+
if project is not None and not isinstance(project, str):
|
|
654
|
+
raise PocketdexError("project must be a string")
|
|
655
|
+
return stats(project, data_dir)
|
|
656
|
+
|
|
657
|
+
raise PocketdexError(f"unknown tool: {name}")
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def mcp_response(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
|
|
661
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def mcp_error(req_id: Any, code: int, message: str) -> dict[str, Any]:
|
|
665
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def handle_request(
|
|
669
|
+
data_dir: Path | str | None, request: dict[str, Any]
|
|
670
|
+
) -> dict[str, Any] | None:
|
|
671
|
+
method = request.get("method")
|
|
672
|
+
req_id = request.get("id")
|
|
673
|
+
|
|
674
|
+
if req_id is None: # notification: never answer
|
|
675
|
+
return None
|
|
676
|
+
|
|
677
|
+
if method == "initialize":
|
|
678
|
+
params = request.get("params") or {}
|
|
679
|
+
requested = params.get("protocolVersion")
|
|
680
|
+
supported = {"2024-11-05", "2025-03-26", "2025-06-18"}
|
|
681
|
+
version = requested if requested in supported else "2025-06-18"
|
|
682
|
+
return mcp_response(
|
|
683
|
+
req_id,
|
|
684
|
+
{
|
|
685
|
+
"protocolVersion": version,
|
|
686
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
687
|
+
"serverInfo": {"name": "pocketdex", "version": VERSION},
|
|
688
|
+
},
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
if method == "ping":
|
|
692
|
+
return mcp_response(req_id, {})
|
|
693
|
+
|
|
694
|
+
if method == "tools/list":
|
|
695
|
+
return mcp_response(req_id, {"tools": TOOLS})
|
|
696
|
+
|
|
697
|
+
if method == "tools/call":
|
|
698
|
+
params = request.get("params") or {}
|
|
699
|
+
name = params.get("name")
|
|
700
|
+
args = params.get("arguments") or {}
|
|
701
|
+
try:
|
|
702
|
+
if not isinstance(name, str) or not isinstance(args, dict):
|
|
703
|
+
raise PocketdexError("tools/call needs a tool name and an object of arguments")
|
|
704
|
+
payload = call_tool(data_dir, name, args)
|
|
705
|
+
return mcp_response(
|
|
706
|
+
req_id,
|
|
707
|
+
{
|
|
708
|
+
"content": [
|
|
709
|
+
{"type": "text", "text": json.dumps(payload, ensure_ascii=False)}
|
|
710
|
+
],
|
|
711
|
+
"isError": False,
|
|
712
|
+
},
|
|
713
|
+
)
|
|
714
|
+
except PocketdexError as exc:
|
|
715
|
+
return mcp_response(
|
|
716
|
+
req_id,
|
|
717
|
+
{"content": [{"type": "text", "text": f"Error: {exc}"}], "isError": True},
|
|
718
|
+
)
|
|
719
|
+
except Exception as exc: # never leak a traceback into the protocol
|
|
720
|
+
print(f"pocketdex: tool {name} failed: {exc!r}", file=sys.stderr)
|
|
721
|
+
return mcp_response(
|
|
722
|
+
req_id,
|
|
723
|
+
{"content": [{"type": "text", "text": f"Internal error: {exc}"}], "isError": True},
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
return mcp_error(req_id, -32601, f"method not found: {method}")
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def serve(data_dir: Path | str | None = None) -> int:
|
|
730
|
+
directory = data_dir_path(data_dir)
|
|
731
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
732
|
+
print(f"pocketdex {VERSION} ready (data={directory})", file=sys.stderr, flush=True)
|
|
733
|
+
|
|
734
|
+
for line in sys.stdin:
|
|
735
|
+
line = line.strip()
|
|
736
|
+
if not line:
|
|
737
|
+
continue
|
|
738
|
+
try:
|
|
739
|
+
request = json.loads(line)
|
|
740
|
+
except json.JSONDecodeError as exc:
|
|
741
|
+
print(f"pocketdex: bad JSON: {exc}", file=sys.stderr, flush=True)
|
|
742
|
+
continue
|
|
743
|
+
if not isinstance(request, dict):
|
|
744
|
+
continue
|
|
745
|
+
response = handle_request(directory, request)
|
|
746
|
+
if response is not None:
|
|
747
|
+
sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
|
|
748
|
+
sys.stdout.flush()
|
|
749
|
+
return 0
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
# --------------------------------------------------------------------------
|
|
753
|
+
# CLI
|
|
754
|
+
# --------------------------------------------------------------------------
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def main(argv: list[str] | None = None) -> int:
|
|
758
|
+
parser = argparse.ArgumentParser(prog="pocketdex", description=__doc__)
|
|
759
|
+
parser.add_argument(
|
|
760
|
+
"--data-dir",
|
|
761
|
+
default=str(default_data_dir()),
|
|
762
|
+
help="where per-project index databases live",
|
|
763
|
+
)
|
|
764
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
765
|
+
|
|
766
|
+
p_index = sub.add_parser("index", help="index or refresh a project folder")
|
|
767
|
+
p_index.add_argument("root")
|
|
768
|
+
p_index.add_argument("--force", action="store_true")
|
|
769
|
+
|
|
770
|
+
p_search = sub.add_parser("search", help="search indexed code")
|
|
771
|
+
p_search.add_argument("query")
|
|
772
|
+
p_search.add_argument("--project")
|
|
773
|
+
p_search.add_argument("--path-prefix")
|
|
774
|
+
p_search.add_argument("--limit", type=int, default=8)
|
|
775
|
+
|
|
776
|
+
p_stats = sub.add_parser("stats", help="show index statistics")
|
|
777
|
+
p_stats.add_argument("--project")
|
|
778
|
+
|
|
779
|
+
sub.add_parser("serve", help="run the MCP stdio server")
|
|
780
|
+
|
|
781
|
+
args = parser.parse_args(argv)
|
|
782
|
+
try:
|
|
783
|
+
if args.command == "index":
|
|
784
|
+
print(json.dumps(index_project(args.root, args.force, args.data_dir), indent=2))
|
|
785
|
+
elif args.command == "search":
|
|
786
|
+
print(
|
|
787
|
+
json.dumps(
|
|
788
|
+
search(
|
|
789
|
+
args.project,
|
|
790
|
+
args.query,
|
|
791
|
+
limit=args.limit,
|
|
792
|
+
path_prefix=args.path_prefix,
|
|
793
|
+
data_dir=args.data_dir,
|
|
794
|
+
),
|
|
795
|
+
indent=2,
|
|
796
|
+
ensure_ascii=False,
|
|
797
|
+
)
|
|
798
|
+
)
|
|
799
|
+
elif args.command == "stats":
|
|
800
|
+
print(json.dumps(stats(args.project, args.data_dir), indent=2))
|
|
801
|
+
elif args.command == "serve":
|
|
802
|
+
return serve(args.data_dir)
|
|
803
|
+
except PocketdexError as exc:
|
|
804
|
+
print(f"pocketdex: {exc}", file=sys.stderr)
|
|
805
|
+
return 1
|
|
806
|
+
return 0
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
if __name__ == "__main__":
|
|
810
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pocketdex-mcp
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A tiny local code index served over MCP, built on SQLite FTS5
|
|
5
|
+
Author: Sujal Kumar
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/sujalkumar1029-gif/pocketdex-mcp
|
|
8
|
+
Project-URL: Issues, https://github.com/sujalkumar1029-gif/pocketdex-mcp/issues
|
|
9
|
+
Keywords: mcp,code-search,sqlite,fts5,ai-agents,llm
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
15
|
+
Classifier: Topic :: Text Processing :: Indexing
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# PocketDex MCP
|
|
22
|
+
|
|
23
|
+
[](https://github.com/sujalkumar1029-gif/pocketdex-mcp/actions/workflows/test.yml)
|
|
24
|
+
[](LICENSE)
|
|
25
|
+
[](https://www.python.org/)
|
|
26
|
+
[](https://glama.ai/mcp/servers/sujalkumar1029-gif/pocketdex-mcp)
|
|
27
|
+
[](https://m8ven.ai/mcp/sujalkumar1029-gif-pocketdex-mcp-93cdxx?s=readme)
|
|
28
|
+
|
|
29
|
+
A tiny local code index for AI agents, served over MCP. One Python file, no
|
|
30
|
+
dependencies, no background server, no vectors — just SQLite FTS5.
|
|
31
|
+
|
|
32
|
+
Ask an agent *"where are badge rules calculated?"* and it gets a file path, a
|
|
33
|
+
line range, and a short highlighted snippet instead of opening five files.
|
|
34
|
+
|
|
35
|
+

|
|
36
|
+
|
|
37
|
+
## Why
|
|
38
|
+
|
|
39
|
+
An agent exploring a repo opens file after file, and every file costs context.
|
|
40
|
+
PocketDex indexes the folder once, then answers `search` with the passage the
|
|
41
|
+
agent needs.
|
|
42
|
+
|
|
43
|
+
Measured on a 34-file Flask app:
|
|
44
|
+
|
|
45
|
+
| Query | Result size | `app.py` alone |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| `parse_amount_cents` | ~120 tokens | ~4,442 tokens |
|
|
48
|
+
| `badge rules` | ~69 tokens | ~4,442 tokens |
|
|
49
|
+
| `sqlite connection` | ~285 tokens | ~4,442 tokens |
|
|
50
|
+
|
|
51
|
+
Index time: 0.06 s. Index size: ~0.5 MB. Query latency: 8–29 ms.
|
|
52
|
+
(Token counts are `characters / 4`, an approximation.)
|
|
53
|
+
|
|
54
|
+
## Why it is different
|
|
55
|
+
|
|
56
|
+
| | PocketDex MCP | Shared code index | `grep` / `rg` |
|
|
57
|
+
|---|---|---|---|
|
|
58
|
+
| Dependencies | None (stdlib only) | Service + client | None |
|
|
59
|
+
| Setup | One file, no install | Install + run server | None |
|
|
60
|
+
| Storage | **One DB per project** | Often one shared index | None |
|
|
61
|
+
| Results | Ranked passages + lines | Ranked passages | Raw matching lines |
|
|
62
|
+
| Context cost | Low | Low | Low, but no ranking |
|
|
63
|
+
| Best at | 20–500 files | Large repos / corpora | One known symbol |
|
|
64
|
+
|
|
65
|
+
The important design choice is **isolation**. Each project gets its own
|
|
66
|
+
database inside PocketDex's folder:
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
PocketDex/
|
|
70
|
+
├── pocketdex.py
|
|
71
|
+
├── data/projects/
|
|
72
|
+
│ ├── my-app-3f2a1b9c.db
|
|
73
|
+
│ └── other-api-7d1e0c44.db
|
|
74
|
+
├── tests/
|
|
75
|
+
└── ARCHITECTURE.md
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- Nothing is written into the project being indexed.
|
|
79
|
+
- Two projects never share a database, so results cannot leak across them.
|
|
80
|
+
- Deleting a `.db` file removes that project's index completely.
|
|
81
|
+
- There is no central registry that can drift out of sync.
|
|
82
|
+
|
|
83
|
+
Override the location with `--data-dir` or `POCKETDEX_DATA`. Run from a clone,
|
|
84
|
+
data stays in `data/projects/` (gitignored). Installed as a package, it falls
|
|
85
|
+
back to `~/.local/share/pocketdex/projects/` because site-packages is not
|
|
86
|
+
writable.
|
|
87
|
+
|
|
88
|
+
`rg` is still the right tool for one known symbol. PocketDex is for exploring
|
|
89
|
+
an unfamiliar repo without paying for whole files.
|
|
90
|
+
|
|
91
|
+
## Install
|
|
92
|
+
|
|
93
|
+
There is nothing to install. Clone the repo and run it:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
git clone https://github.com/sujalkumar1029-gif/pocketdex-mcp.git
|
|
97
|
+
cd pocketdex-mcp
|
|
98
|
+
python3 pocketdex.py --help
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Or run it straight from Git with `uv`:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
uvx --from git+https://github.com/sujalkumar1029-gif/pocketdex-mcp pocketdex index ~/Projects/my-app
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Requirements: Python 3.10+ and SQLite built with FTS5 (standard in CPython
|
|
108
|
+
builds).
|
|
109
|
+
|
|
110
|
+
## Docker
|
|
111
|
+
|
|
112
|
+
Build the stdio server into a small image:
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
docker build -t pocketdex-mcp .
|
|
116
|
+
docker run --rm -i pocketdex-mcp
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The index lives under `/app/data` inside the container. To keep it between
|
|
120
|
+
runs, use a named volume:
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
docker run --rm -i -v pocketdex-data:/app/data pocketdex-mcp
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Quick start
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
# index or refresh a project (incremental)
|
|
130
|
+
python3 pocketdex.py index ~/Projects/my-app
|
|
131
|
+
|
|
132
|
+
# search
|
|
133
|
+
python3 pocketdex.py search "parse_amount_cents"
|
|
134
|
+
python3 pocketdex.py search "badge rules" --limit 5
|
|
135
|
+
python3 pocketdex.py search "connect" --path-prefix src/db
|
|
136
|
+
|
|
137
|
+
# inspect every project's separate index
|
|
138
|
+
python3 pocketdex.py stats
|
|
139
|
+
|
|
140
|
+
# MCP server (what the agent runs)
|
|
141
|
+
python3 pocketdex.py serve
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`search` without `--project` uses the most recently indexed project. Pass
|
|
145
|
+
`--project ~/Projects/other` when several are indexed.
|
|
146
|
+
|
|
147
|
+
## MCP configuration
|
|
148
|
+
|
|
149
|
+
Add this to your MCP client's config (for example
|
|
150
|
+
`~/.gemini/config/mcp_config.json` for Antigravity):
|
|
151
|
+
|
|
152
|
+
```json
|
|
153
|
+
{
|
|
154
|
+
"mcpServers": {
|
|
155
|
+
"pocketdex": {
|
|
156
|
+
"command": "python3",
|
|
157
|
+
"args": ["/absolute/path/to/pocketdex.py", "serve"]
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Tools exposed:
|
|
164
|
+
|
|
165
|
+
| Tool | Purpose |
|
|
166
|
+
|---|---|
|
|
167
|
+
| `index_project` | Index or refresh one folder into its own DB. Incremental. |
|
|
168
|
+
| `search` | Keyword/identifier search in one project, with snippets. |
|
|
169
|
+
| `stats` | Every indexed project, its DB path, file/chunk counts, size. |
|
|
170
|
+
|
|
171
|
+
## Reproduce the numbers
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
python3 benchmark.py ~/Projects/my-app
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
It indexes the folder, prints index time and database size, then measures the
|
|
178
|
+
approximate token cost of a few queries against the total source size.
|
|
179
|
+
|
|
180
|
+
## How it works
|
|
181
|
+
|
|
182
|
+
- Walks the folder, skipping `.git`, `node_modules`, `.venv`, `dist`, build
|
|
183
|
+
output, lockfiles, hidden folders, files over 512 KB, and binaries.
|
|
184
|
+
- Splits files into 40-line chunks with 12 lines of overlap.
|
|
185
|
+
- Stores chunks in SQLite FTS5 with `_` as a token character, so
|
|
186
|
+
`parse_amount_cents` stays one searchable token.
|
|
187
|
+
- BM25 ranking, at most two results per file, snippets capped at 12 tokens of
|
|
188
|
+
context.
|
|
189
|
+
- Re-indexing compares `mtime_ns` and size; unchanged files are skipped.
|
|
190
|
+
|
|
191
|
+
`ARCHITECTURE.md` explains the data model, indexing pipeline, ranking, MCP
|
|
192
|
+
lifecycle, failure modes, and extension points.
|
|
193
|
+
|
|
194
|
+
## Limits (on purpose)
|
|
195
|
+
|
|
196
|
+
- **No embeddings / vector search.** Keyword + prefix matching only. Code
|
|
197
|
+
search is dominated by exact identifiers.
|
|
198
|
+
- **No regex tool.** Add one only if a real need appears.
|
|
199
|
+
- **Small-to-medium projects.** A 20–500 file range is the target; a multi-GB
|
|
200
|
+
monorepo belongs on a dedicated search service.
|
|
201
|
+
- **No file watching.** Call `index_project` after large edits; unchanged
|
|
202
|
+
files are cheap to skip.
|
|
203
|
+
- **Plaintext index.** Treat the data folder with the same care as the source
|
|
204
|
+
it indexes.
|
|
205
|
+
|
|
206
|
+
## Tests
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
python3 -m pip install pytest
|
|
210
|
+
python3 -m pytest -q
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
11 tests: indexing, ignored dirs, binary skip, incremental re-index, deletion,
|
|
214
|
+
path filters, stats, per-project isolation, latest-project selection, and a
|
|
215
|
+
real MCP stdio handshake (initialize → tools/list → tools/call).
|
|
216
|
+
|
|
217
|
+
## Status
|
|
218
|
+
|
|
219
|
+
Early (0.x). The MCP contract and CLI are stable; internals may change.
|
|
220
|
+
Issues and pull requests are welcome.
|
|
221
|
+
|
|
222
|
+
If PocketDex saves you tokens, a star helps other agent builders find it.
|
|
223
|
+
|
|
224
|
+
## License
|
|
225
|
+
|
|
226
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
pocketdex.py,sha256=pLSexKT8VyoOZyxE1hgSleenIhSixTq-nSlI5l0xb10,27616
|
|
2
|
+
pocketdex_mcp-0.2.0.dist-info/licenses/LICENSE,sha256=E8amS4TESxgsnorUG9Kx9AVni-NrypQmbpVCYWJTfss,1068
|
|
3
|
+
pocketdex_mcp-0.2.0.dist-info/METADATA,sha256=CCY5cwnw8aIXcLX6fxdoBfxa12wOCeC2mvfiLoJKW5E,7539
|
|
4
|
+
pocketdex_mcp-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
pocketdex_mcp-0.2.0.dist-info/entry_points.txt,sha256=LaSVuTKFafYj6RlOeWoMKMzXSoJuhGJBzutt7u60XrA,45
|
|
6
|
+
pocketdex_mcp-0.2.0.dist-info/top_level.txt,sha256=AZj7xXPkPqCKD9eFkfwJSQjOZLJfCKevrfJvcz-UpTs,10
|
|
7
|
+
pocketdex_mcp-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sujal Kumar
|
|
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 @@
|
|
|
1
|
+
pocketdex
|