shrink-mcp 0.4.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.
shrink.py
ADDED
|
@@ -0,0 +1,1100 @@
|
|
|
1
|
+
# shrink-mcp: cuts diffs, logs and file trees before they land in a chat.
|
|
2
|
+
# runs on its own (cli, pipe, serve, watch) and as mcp.
|
|
3
|
+
# cursor, vscode, claude code, claude desktop all eat the same stdio.
|
|
4
|
+
#
|
|
5
|
+
# py -3 shrink.py diff
|
|
6
|
+
# py -3 shrink.py log build.log
|
|
7
|
+
# py -3 shrink.py tree
|
|
8
|
+
# py -3 shrink.py serve
|
|
9
|
+
# py -3 shrink.py setup cursor --write
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
# 0.2 was mcp only. 0.3.1 was the laptop script. 0.4.2 after another pass on real logs
|
|
21
|
+
VER = "0.4.2"
|
|
22
|
+
|
|
23
|
+
# a huge log hung the process once. stop reading past this
|
|
24
|
+
MAX_BYTES = 2_000_000
|
|
25
|
+
|
|
26
|
+
junk_dirs = {
|
|
27
|
+
".git",
|
|
28
|
+
".venv",
|
|
29
|
+
"venv",
|
|
30
|
+
"node_modules",
|
|
31
|
+
"dist",
|
|
32
|
+
"build",
|
|
33
|
+
"target",
|
|
34
|
+
"__pycache__",
|
|
35
|
+
".next",
|
|
36
|
+
"coverage",
|
|
37
|
+
".shrink",
|
|
38
|
+
}
|
|
39
|
+
lockfiles = {
|
|
40
|
+
"package-lock.json",
|
|
41
|
+
"yarn.lock",
|
|
42
|
+
"pnpm-lock.yaml",
|
|
43
|
+
"cargo.lock",
|
|
44
|
+
"poetry.lock",
|
|
45
|
+
"uv.lock",
|
|
46
|
+
"bun.lock",
|
|
47
|
+
"composer.lock",
|
|
48
|
+
"gemfile.lock",
|
|
49
|
+
}
|
|
50
|
+
# images and minified junk just add noise to a diff
|
|
51
|
+
bin_suffixes = (
|
|
52
|
+
".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico",
|
|
53
|
+
".pdf", ".zip", ".gz", ".woff", ".woff2",
|
|
54
|
+
".min.js", ".min.css", ".map",
|
|
55
|
+
)
|
|
56
|
+
# lines with these stay. left "warn" out on purpose, there are too many of them
|
|
57
|
+
hot_words = ("error", "exception", "traceback", "fail", "fatal", "panic", "assert")
|
|
58
|
+
|
|
59
|
+
HERE = Path(__file__).resolve()
|
|
60
|
+
|
|
61
|
+
HELP = """\
|
|
62
|
+
shrink cuts long text. the first line is a rough before -> after guess.
|
|
63
|
+
|
|
64
|
+
on its own:
|
|
65
|
+
py -3 shrink.py diff git changes
|
|
66
|
+
py -3 shrink.py log build.log long log. no file means stdin
|
|
67
|
+
py -3 shrink.py tree [folder]
|
|
68
|
+
type build.log | py -3 shrink.py a pipe is a log, no subcommand needed
|
|
69
|
+
py -3 shrink.py serve [port] http://127.0.0.1:8765 this machine only
|
|
70
|
+
py -3 shrink.py watch rewrites .shrink/last.txt every 2s
|
|
71
|
+
|
|
72
|
+
hook up an editor (cursor / vscode / claude / codex, same protocol):
|
|
73
|
+
py -3 shrink.py setup
|
|
74
|
+
py -3 shrink.py setup vscode --write
|
|
75
|
+
py -3 shrink.py setup codex
|
|
76
|
+
py -3 shrink.py mcp the editor starts this, don't run it by hand
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class GiveUp(Exception):
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def fix_stdio():
|
|
85
|
+
for stream in (sys.stdout, sys.stderr):
|
|
86
|
+
if hasattr(stream, "reconfigure"):
|
|
87
|
+
# newline=\n so a piped line is not "\r\n". mcp used to break on the \r
|
|
88
|
+
stream.reconfigure(encoding="utf-8", errors="replace", newline="\n")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# False = haven't looked yet. None = tiktoken isn't installed, keep going.
|
|
92
|
+
_enc = False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def tok_encoder():
|
|
96
|
+
global _enc
|
|
97
|
+
if _enc is not False:
|
|
98
|
+
return _enc
|
|
99
|
+
try:
|
|
100
|
+
import tiktoken
|
|
101
|
+
_enc = tiktoken.get_encoding("cl100k_base")
|
|
102
|
+
except Exception:
|
|
103
|
+
_enc = None
|
|
104
|
+
return _enc
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def rough_tokens(text):
|
|
108
|
+
# words = len(text.split())
|
|
109
|
+
# return max(1, (len(text) + 3) // 4) if text else 0
|
|
110
|
+
# chars/4 drifted from the bill. cl100k when tiktoken is there, else a split
|
|
111
|
+
if not text:
|
|
112
|
+
return 0
|
|
113
|
+
enc = tok_encoder()
|
|
114
|
+
if enc is not None:
|
|
115
|
+
try:
|
|
116
|
+
return len(enc.encode(text))
|
|
117
|
+
except Exception:
|
|
118
|
+
pass
|
|
119
|
+
bits = re.findall(r"\w+|[^\w\s]", text)
|
|
120
|
+
return max(1, len(bits))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def report(before, body, note=""):
|
|
124
|
+
tail = f" ({note})" if note else ""
|
|
125
|
+
head = f"rough tokens: {rough_tokens(before)} -> {rough_tokens(body)}{tail}\n\n"
|
|
126
|
+
return head + body.rstrip() + "\n"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
_ansi = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def decode_bytes(raw):
|
|
133
|
+
# text = raw.decode("utf-8", "replace")
|
|
134
|
+
# notepad on windows saves "unicode" which is utf-16, and that came out as garbage
|
|
135
|
+
if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
|
|
136
|
+
return raw.decode("utf-16", "replace")
|
|
137
|
+
if b"\x00" in raw[:2048]:
|
|
138
|
+
raise GiveUp("looks like a binary file, not a log")
|
|
139
|
+
if raw.startswith(b"\xef\xbb\xbf"):
|
|
140
|
+
return raw.decode("utf-8-sig", "replace")
|
|
141
|
+
return raw.decode("utf-8", "replace")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def read_capped(path, limit=MAX_BYTES):
|
|
145
|
+
# raw = Path(path).read_bytes()
|
|
146
|
+
# the cap checked the length after the whole file was already in ram
|
|
147
|
+
with open(path, "rb") as fh:
|
|
148
|
+
raw = fh.read(limit + 1)
|
|
149
|
+
cut = len(raw) > limit
|
|
150
|
+
return decode_bytes(raw[:limit]), cut
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def read_stdin_capped():
|
|
154
|
+
raw = sys.stdin.buffer.read(MAX_BYTES + 1)
|
|
155
|
+
cut = len(raw) > MAX_BYTES
|
|
156
|
+
return decode_bytes(raw[:MAX_BYTES]), cut
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def git_root(start):
|
|
160
|
+
cur = Path(start).resolve()
|
|
161
|
+
for folder in (cur, *cur.parents):
|
|
162
|
+
if (folder / ".git").exists():
|
|
163
|
+
return folder
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def skip_dir(name):
|
|
168
|
+
if name in junk_dirs:
|
|
169
|
+
return True
|
|
170
|
+
# setuptools leaves shrink.egg-info next to the code. not part of the tree
|
|
171
|
+
return name.endswith(".egg-info")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def git_argv(root, args):
|
|
175
|
+
# git config stays alone. a repo on a drive with no owner (this W:) is "dubious"
|
|
176
|
+
# and diff died before it printed anything. the -c flag is just for this call
|
|
177
|
+
folder = str(Path(root).resolve()).replace("\\", "/")
|
|
178
|
+
return ["git", "-c", "safe.directory=" + folder, *args]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def run_git(root, args):
|
|
182
|
+
try:
|
|
183
|
+
proc = subprocess.run(
|
|
184
|
+
git_argv(root, args),
|
|
185
|
+
cwd=root,
|
|
186
|
+
capture_output=True,
|
|
187
|
+
text=True,
|
|
188
|
+
encoding="utf-8",
|
|
189
|
+
errors="replace",
|
|
190
|
+
)
|
|
191
|
+
except FileNotFoundError:
|
|
192
|
+
raise GiveUp("git is not on PATH")
|
|
193
|
+
if proc.returncode != 0:
|
|
194
|
+
err = (proc.stderr or "git failed").strip()
|
|
195
|
+
raise GiveUp(err)
|
|
196
|
+
return proc.stdout
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def has_head(root):
|
|
200
|
+
try:
|
|
201
|
+
proc = subprocess.run(
|
|
202
|
+
git_argv(root, ["rev-parse", "--verify", "HEAD"]),
|
|
203
|
+
cwd=root,
|
|
204
|
+
capture_output=True,
|
|
205
|
+
text=True,
|
|
206
|
+
encoding="utf-8",
|
|
207
|
+
errors="replace",
|
|
208
|
+
)
|
|
209
|
+
except FileNotFoundError:
|
|
210
|
+
raise GiveUp("git is not on PATH")
|
|
211
|
+
return proc.returncode == 0
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def format_untracked(raw):
|
|
215
|
+
files = [name for name in raw.splitlines() if name.strip()]
|
|
216
|
+
if not files:
|
|
217
|
+
return ""
|
|
218
|
+
# was: "\n".join(files) with no cap. an un-ignored dump was longer than the diff
|
|
219
|
+
shown = files[:40]
|
|
220
|
+
lines = ["Untracked files, contents left out:", *shown]
|
|
221
|
+
if len(files) > 40:
|
|
222
|
+
lines.append("# more untracked not listed: %s" % (len(files) - 40))
|
|
223
|
+
return "\n".join(lines)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def grab_diff(root):
|
|
227
|
+
# was: text = run_git(root, ["diff", "HEAD"])
|
|
228
|
+
# no commit yet and git says "ambiguous argument HEAD"
|
|
229
|
+
text = run_git(root, ["diff", "HEAD"]) if has_head(root) else ""
|
|
230
|
+
names = run_git(root, ["ls-files", "--others", "--exclude-standard"])
|
|
231
|
+
return text, format_untracked(names)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def show_diff(root):
|
|
235
|
+
diff, extra = grab_diff(root)
|
|
236
|
+
# extra used to be glued onto the diff, then the squasher hid those lines
|
|
237
|
+
if diff.strip():
|
|
238
|
+
body = squash_diff(diff)
|
|
239
|
+
elif extra:
|
|
240
|
+
body = extra
|
|
241
|
+
extra = ""
|
|
242
|
+
else:
|
|
243
|
+
body = "No changes."
|
|
244
|
+
if extra:
|
|
245
|
+
body = body.rstrip() + "\n\n" + extra
|
|
246
|
+
before = diff if not extra else (diff.rstrip() + "\n" + extra).strip()
|
|
247
|
+
return report(before, body)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def path_from_block(lines):
|
|
251
|
+
for line in lines:
|
|
252
|
+
if not line.startswith("diff --git "):
|
|
253
|
+
continue
|
|
254
|
+
rest = line[len("diff --git "):].strip()
|
|
255
|
+
# was: rest.split(" b/", 1)[-1].strip('"')
|
|
256
|
+
# git quotes a path that has a space, and that split missed it
|
|
257
|
+
if rest.startswith('"'):
|
|
258
|
+
names = [part for part in rest.split('"') if part and not part.isspace()]
|
|
259
|
+
if not names:
|
|
260
|
+
return ""
|
|
261
|
+
name = names[-1]
|
|
262
|
+
if name.startswith("b/"):
|
|
263
|
+
name = name[2:]
|
|
264
|
+
return name
|
|
265
|
+
parts = rest.split(" b/", 1)
|
|
266
|
+
if len(parts) == 2:
|
|
267
|
+
return parts[1].strip()
|
|
268
|
+
return ""
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def boring(path):
|
|
272
|
+
name = Path(path).name.lower()
|
|
273
|
+
if name in lockfiles:
|
|
274
|
+
return True
|
|
275
|
+
return name.endswith(bin_suffixes)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def split_diff(diff):
|
|
279
|
+
blocks = []
|
|
280
|
+
cur = []
|
|
281
|
+
for line in diff.splitlines():
|
|
282
|
+
if line.startswith("diff --git ") and cur:
|
|
283
|
+
blocks.append(cur)
|
|
284
|
+
cur = [line]
|
|
285
|
+
else:
|
|
286
|
+
cur.append(line)
|
|
287
|
+
if cur:
|
|
288
|
+
blocks.append(cur)
|
|
289
|
+
return blocks
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def clip_line(line, n=500):
|
|
293
|
+
if len(line) <= n:
|
|
294
|
+
return line
|
|
295
|
+
return line[:n] + " ... clipped"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def squash_diff(diff):
|
|
299
|
+
if not diff.strip():
|
|
300
|
+
return "No changes."
|
|
301
|
+
blocks = split_diff(diff)
|
|
302
|
+
# short patches stay whole. the first cut mangled tiny edits.
|
|
303
|
+
# a 40-line lockfile and one minified line also counted as "short", so this
|
|
304
|
+
# only bails out when the patch is small and not junk
|
|
305
|
+
if (
|
|
306
|
+
len(blocks) == 1
|
|
307
|
+
and len(diff.splitlines()) <= 80
|
|
308
|
+
and len(diff) <= 8000
|
|
309
|
+
):
|
|
310
|
+
path = path_from_block(blocks[0])
|
|
311
|
+
if not (path and boring(path)):
|
|
312
|
+
return diff.rstrip()
|
|
313
|
+
|
|
314
|
+
pieces = []
|
|
315
|
+
blocks = split_diff(diff)
|
|
316
|
+
hidden_files = 0
|
|
317
|
+
for lines in blocks:
|
|
318
|
+
if len(pieces) >= 40:
|
|
319
|
+
hidden_files += 1
|
|
320
|
+
continue
|
|
321
|
+
path = path_from_block(lines)
|
|
322
|
+
if path and boring(path):
|
|
323
|
+
pieces.append(f"# skipped junk file: {path}")
|
|
324
|
+
continue
|
|
325
|
+
# a git binary patch explodes into thousands of garbage lines
|
|
326
|
+
if any(line.startswith("GIT binary patch") for line in lines):
|
|
327
|
+
pieces.append(f"# binary patch, dropped the body: {path or '?'}")
|
|
328
|
+
continue
|
|
329
|
+
|
|
330
|
+
kept = []
|
|
331
|
+
hidden = 0
|
|
332
|
+
changes = 0
|
|
333
|
+
for line in lines:
|
|
334
|
+
header = line.startswith((
|
|
335
|
+
"diff --git", "index ", "---", "+++", "@@",
|
|
336
|
+
"new file", "deleted file", "rename ", "similarity ",
|
|
337
|
+
"Binary files", "Untracked files",
|
|
338
|
+
"old mode", "new mode", "deleted file mode", "new file mode",
|
|
339
|
+
))
|
|
340
|
+
changed = (
|
|
341
|
+
line.startswith(("+", "-"))
|
|
342
|
+
and not line.startswith(("+++", "---"))
|
|
343
|
+
)
|
|
344
|
+
if header or (changed and changes < 80):
|
|
345
|
+
kept.append(clip_line(line))
|
|
346
|
+
if changed:
|
|
347
|
+
changes += 1
|
|
348
|
+
else:
|
|
349
|
+
hidden += 1
|
|
350
|
+
if hidden:
|
|
351
|
+
kept.append(f"# lines hidden: {hidden}")
|
|
352
|
+
pieces.append("\n".join(kept))
|
|
353
|
+
|
|
354
|
+
if hidden_files:
|
|
355
|
+
pieces.append(f"# more files not expanded: {hidden_files}")
|
|
356
|
+
return "\n\n".join(pieces)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def line_is_hot(line):
|
|
360
|
+
low = _ansi.sub("", line).lower()
|
|
361
|
+
# if any(w in low for w in hot_words):
|
|
362
|
+
# "failover" contains "fail". a k8s log looked like a crash.
|
|
363
|
+
# "0 errors" from tsc did the same
|
|
364
|
+
low = low.replace("failover", " ").replace("exceptional", " ")
|
|
365
|
+
low = re.sub(r"\b0 errors?\b", " ", low)
|
|
366
|
+
low = re.sub(r"\bno errors?\b", " ", low)
|
|
367
|
+
low = re.sub(r"\b0 failed\b", " ", low)
|
|
368
|
+
low = re.sub(r"\bfailed:\s*0\b", " ", low)
|
|
369
|
+
# "errors: 0" and "0 failures" still contain the word. tsc and jest print that when green
|
|
370
|
+
low = re.sub(r"\berrors?:\s*0\b", " ", low)
|
|
371
|
+
low = re.sub(r"\b0 failures?\b", " ", low)
|
|
372
|
+
low = re.sub(r"\bfailures?:\s*0\b", " ", low)
|
|
373
|
+
low = re.sub(r"\bno failures?\b", " ", low)
|
|
374
|
+
# npm says "npm ERR!" and never the word error
|
|
375
|
+
if "err!" in low:
|
|
376
|
+
return True
|
|
377
|
+
# a shell crash doesn't say "error"
|
|
378
|
+
if "segmentation fault" in low or "segfault" in low or "core dumped" in low:
|
|
379
|
+
return True
|
|
380
|
+
if "out of memory" in low or "oomkilled" in low:
|
|
381
|
+
return True
|
|
382
|
+
return any(word in low for word in hot_words)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def hot_span(lines, n):
|
|
386
|
+
# return range(max(0, n - 2), min(len(lines), n + 4))
|
|
387
|
+
# that kept "Traceback" and three frames, and dropped SystemExit
|
|
388
|
+
low = lines[n].lower()
|
|
389
|
+
if "traceback" in low:
|
|
390
|
+
end = n
|
|
391
|
+
limit = min(len(lines), n + 48)
|
|
392
|
+
i = n + 1
|
|
393
|
+
while i < limit:
|
|
394
|
+
s = lines[i]
|
|
395
|
+
stripped = s.strip()
|
|
396
|
+
if not stripped:
|
|
397
|
+
i += 1
|
|
398
|
+
continue
|
|
399
|
+
frame = (
|
|
400
|
+
s[:1].isspace()
|
|
401
|
+
or stripped.startswith((
|
|
402
|
+
"File ", "...", "During handling", "The above exception",
|
|
403
|
+
"Traceback", "at ",
|
|
404
|
+
))
|
|
405
|
+
or stripped[0] in "^~|"
|
|
406
|
+
)
|
|
407
|
+
end = i
|
|
408
|
+
i += 1
|
|
409
|
+
if not frame:
|
|
410
|
+
break
|
|
411
|
+
return range(max(0, n - 1), end + 1)
|
|
412
|
+
# a jest/go failure is a few lines under the FAIL header, not one line
|
|
413
|
+
return range(max(0, n - 2), min(len(lines), n + 8))
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def squash_log(text):
|
|
417
|
+
raw = text.splitlines()
|
|
418
|
+
lines = []
|
|
419
|
+
i = 0
|
|
420
|
+
while i < len(raw):
|
|
421
|
+
j = i + 1
|
|
422
|
+
while j < len(raw) and raw[j] == raw[i]:
|
|
423
|
+
j += 1
|
|
424
|
+
n = j - i
|
|
425
|
+
if n > 2:
|
|
426
|
+
lines.append(f"{raw[i]} x{n}")
|
|
427
|
+
else:
|
|
428
|
+
lines.extend(raw[i:j])
|
|
429
|
+
i = j
|
|
430
|
+
|
|
431
|
+
# if len(lines) <= 80: return "\n".join(lines)
|
|
432
|
+
# one of those "lines" was 2MB of base64
|
|
433
|
+
if len(lines) <= 80 and sum(len(line) for line in lines) <= 8000:
|
|
434
|
+
return "\n".join(lines)
|
|
435
|
+
|
|
436
|
+
hot = []
|
|
437
|
+
for n, line in enumerate(lines):
|
|
438
|
+
if line_is_hot(line):
|
|
439
|
+
hot.append(n)
|
|
440
|
+
|
|
441
|
+
keep = set()
|
|
442
|
+
if hot:
|
|
443
|
+
for n in hot:
|
|
444
|
+
keep.update(hot_span(lines, n))
|
|
445
|
+
keep.update(range(max(0, len(lines) - 15), len(lines)))
|
|
446
|
+
else:
|
|
447
|
+
# no errors found. keep the start (usually the command) and the tail (usually the summary)
|
|
448
|
+
keep.update(range(min(20, len(lines))))
|
|
449
|
+
keep.update(range(max(0, len(lines) - 40), len(lines)))
|
|
450
|
+
|
|
451
|
+
out = []
|
|
452
|
+
hidden = 0
|
|
453
|
+
for n, line in enumerate(lines):
|
|
454
|
+
if n in keep:
|
|
455
|
+
if hidden:
|
|
456
|
+
out.append(f"... lines hidden: {hidden}")
|
|
457
|
+
hidden = 0
|
|
458
|
+
out.append(clip_line(line))
|
|
459
|
+
else:
|
|
460
|
+
hidden += 1
|
|
461
|
+
if hidden:
|
|
462
|
+
out.append(f"... lines hidden: {hidden}")
|
|
463
|
+
return "\n".join(out)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def squash_tree(root, depth_limit=3, per_dir=12):
|
|
467
|
+
root = Path(root).resolve()
|
|
468
|
+
lines = [root.name + "/"]
|
|
469
|
+
seen = 0
|
|
470
|
+
cut_deep = False
|
|
471
|
+
|
|
472
|
+
def walk(folder, depth):
|
|
473
|
+
nonlocal seen, cut_deep
|
|
474
|
+
if depth > depth_limit:
|
|
475
|
+
cut_deep = True
|
|
476
|
+
return
|
|
477
|
+
try:
|
|
478
|
+
entries = list(folder.iterdir())
|
|
479
|
+
except OSError:
|
|
480
|
+
return
|
|
481
|
+
dirs, files = [], []
|
|
482
|
+
for entry in entries:
|
|
483
|
+
if skip_dir(entry.name):
|
|
484
|
+
continue
|
|
485
|
+
# if entry.name.startswith("."):
|
|
486
|
+
# continue
|
|
487
|
+
# that dropped .github. don't blanket-skip dotted folders anymore
|
|
488
|
+
if entry.is_dir():
|
|
489
|
+
dirs.append(entry)
|
|
490
|
+
elif entry.is_file():
|
|
491
|
+
files.append(entry)
|
|
492
|
+
dirs.sort(key=lambda p: p.name.lower())
|
|
493
|
+
files.sort(key=lambda p: p.name.lower())
|
|
494
|
+
pad = " " * depth
|
|
495
|
+
for entry in files[:per_dir]:
|
|
496
|
+
seen += 1
|
|
497
|
+
lines.append(f"{pad}{entry.name}")
|
|
498
|
+
rest = len(files) - per_dir
|
|
499
|
+
if rest > 0:
|
|
500
|
+
seen += rest
|
|
501
|
+
lines.append(f"{pad}... more files: {rest}")
|
|
502
|
+
for entry in dirs:
|
|
503
|
+
lines.append(f"{pad}{entry.name}/")
|
|
504
|
+
walk(entry, depth + 1)
|
|
505
|
+
|
|
506
|
+
walk(root, 1)
|
|
507
|
+
if cut_deep:
|
|
508
|
+
lines.append("deeper folders not opened")
|
|
509
|
+
lines.append(f"\nfiles in this list: {seen}")
|
|
510
|
+
return "\n".join(lines)
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def file_dump(folder, limit=4000):
|
|
514
|
+
# names = [str(p) for p in Path(folder).rglob("*") if p.is_file()]
|
|
515
|
+
# rglob wandered into node_modules and sat there for a minute. walk + skip
|
|
516
|
+
names = []
|
|
517
|
+
for dirpath, dirnames, filenames in os.walk(folder):
|
|
518
|
+
dirnames[:] = [n for n in dirnames if not skip_dir(n)]
|
|
519
|
+
for name in filenames:
|
|
520
|
+
names.append(str(Path(dirpath) / name))
|
|
521
|
+
if len(names) >= limit:
|
|
522
|
+
names.append(f"... stopped after {limit}, not going further")
|
|
523
|
+
return "\n".join(names)
|
|
524
|
+
return "\n".join(names)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def do_diff(path=None):
|
|
528
|
+
start = Path(path) if path else Path.cwd()
|
|
529
|
+
if path and not start.exists():
|
|
530
|
+
raise GiveUp(f"folder not found: {path}")
|
|
531
|
+
root = git_root(start)
|
|
532
|
+
if root is None:
|
|
533
|
+
raise GiveUp("not a git repo. cd into the project and run it again")
|
|
534
|
+
return show_diff(root)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def do_log(path=""):
|
|
538
|
+
note = ""
|
|
539
|
+
if path:
|
|
540
|
+
fp = Path(path)
|
|
541
|
+
if not fp.is_file():
|
|
542
|
+
raise GiveUp(f"file not found: {path}")
|
|
543
|
+
before, cut = read_capped(fp)
|
|
544
|
+
else:
|
|
545
|
+
before, cut = read_stdin_capped()
|
|
546
|
+
if cut:
|
|
547
|
+
note = "input truncated"
|
|
548
|
+
return report(before, squash_log(before), note)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def do_tree(path=""):
|
|
552
|
+
folder = Path(path) if path else Path.cwd()
|
|
553
|
+
if not folder.is_dir():
|
|
554
|
+
raise GiveUp(f"folder not found: {path}")
|
|
555
|
+
return report(file_dump(folder), squash_tree(folder))
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
# --- mcp ---
|
|
559
|
+
# stdout here is json only, one line per reply. debug goes to stderr.
|
|
560
|
+
# cursor sends a json line. one old fork sent Content-Length like lsp,
|
|
561
|
+
# so the second branch is still here. not ripping it out in case it shows up again.
|
|
562
|
+
|
|
563
|
+
def tool_text(text, is_error=False):
|
|
564
|
+
return {"content": [{"type": "text", "text": text}], "isError": is_error}
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def as_args(args):
|
|
568
|
+
if isinstance(args, str):
|
|
569
|
+
# one client sent the object already stringified
|
|
570
|
+
try:
|
|
571
|
+
args = json.loads(args)
|
|
572
|
+
except json.JSONDecodeError:
|
|
573
|
+
return {}
|
|
574
|
+
if not isinstance(args, dict):
|
|
575
|
+
return {}
|
|
576
|
+
return args
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def as_text(value):
|
|
580
|
+
if value is None:
|
|
581
|
+
return ""
|
|
582
|
+
if isinstance(value, str):
|
|
583
|
+
return value
|
|
584
|
+
return str(value)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def call_tool(name, args):
|
|
588
|
+
args = as_args(args)
|
|
589
|
+
try:
|
|
590
|
+
if name == "shrink_diff":
|
|
591
|
+
return tool_text(do_diff(as_text(args.get("path"))))
|
|
592
|
+
if name == "shrink_log":
|
|
593
|
+
text = as_text(args.get("text"))
|
|
594
|
+
note = ""
|
|
595
|
+
raw = text.encode("utf-8")
|
|
596
|
+
if len(raw) > MAX_BYTES:
|
|
597
|
+
text = raw[:MAX_BYTES].decode("utf-8", "replace")
|
|
598
|
+
note = "input truncated"
|
|
599
|
+
return tool_text(report(text, squash_log(text), note))
|
|
600
|
+
if name == "shrink_tree":
|
|
601
|
+
return tool_text(do_tree(as_text(args.get("path"))))
|
|
602
|
+
except GiveUp as err:
|
|
603
|
+
return tool_text(str(err), True)
|
|
604
|
+
except Exception as err:
|
|
605
|
+
return tool_text(str(err), True)
|
|
606
|
+
return tool_text(f"no such tool: {name}", True)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
TOOLS = [
|
|
610
|
+
{
|
|
611
|
+
"name": "shrink_diff",
|
|
612
|
+
"description": "Short git diff plus a rough guess of how much text was cut.",
|
|
613
|
+
"inputSchema": {
|
|
614
|
+
"type": "object",
|
|
615
|
+
"properties": {
|
|
616
|
+
"path": {"type": "string", "description": "project folder, can be empty"},
|
|
617
|
+
},
|
|
618
|
+
},
|
|
619
|
+
},
|
|
620
|
+
{
|
|
621
|
+
"name": "shrink_log",
|
|
622
|
+
"description": "Keeps errors and the tail of a long log.",
|
|
623
|
+
"inputSchema": {
|
|
624
|
+
"type": "object",
|
|
625
|
+
"properties": {"text": {"type": "string"}},
|
|
626
|
+
"required": ["text"],
|
|
627
|
+
},
|
|
628
|
+
},
|
|
629
|
+
{
|
|
630
|
+
"name": "shrink_tree",
|
|
631
|
+
"description": "Short folder tree, node_modules and other junk left out.",
|
|
632
|
+
"inputSchema": {
|
|
633
|
+
"type": "object",
|
|
634
|
+
"properties": {"path": {"type": "string"}},
|
|
635
|
+
},
|
|
636
|
+
},
|
|
637
|
+
]
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def mcp_reply(msg):
|
|
641
|
+
method = msg.get("method", "")
|
|
642
|
+
mid = msg.get("id")
|
|
643
|
+
if method == "initialize":
|
|
644
|
+
ver = (msg.get("params") or {}).get("protocolVersion") or "2024-11-05"
|
|
645
|
+
return {
|
|
646
|
+
"jsonrpc": "2.0",
|
|
647
|
+
"id": mid,
|
|
648
|
+
"result": {
|
|
649
|
+
"protocolVersion": ver,
|
|
650
|
+
"capabilities": {"tools": {}},
|
|
651
|
+
"serverInfo": {"name": "shrink-mcp", "version": VER},
|
|
652
|
+
},
|
|
653
|
+
}
|
|
654
|
+
if method == "ping":
|
|
655
|
+
return {"jsonrpc": "2.0", "id": mid, "result": {}}
|
|
656
|
+
# vscode and claude ask for these. answering -32601 made the server look dead
|
|
657
|
+
if method == "prompts/list":
|
|
658
|
+
return {"jsonrpc": "2.0", "id": mid, "result": {"prompts": []}}
|
|
659
|
+
if method == "resources/list":
|
|
660
|
+
return {"jsonrpc": "2.0", "id": mid, "result": {"resources": []}}
|
|
661
|
+
if method == "resources/templates/list":
|
|
662
|
+
return {"jsonrpc": "2.0", "id": mid, "result": {"resourceTemplates": []}}
|
|
663
|
+
if method == "logging/setLevel":
|
|
664
|
+
if mid is None:
|
|
665
|
+
return None
|
|
666
|
+
return {"jsonrpc": "2.0", "id": mid, "result": {}}
|
|
667
|
+
if method == "tools/list":
|
|
668
|
+
return {"jsonrpc": "2.0", "id": mid, "result": {"tools": TOOLS}}
|
|
669
|
+
if method == "tools/call":
|
|
670
|
+
params = msg.get("params") or {}
|
|
671
|
+
return {
|
|
672
|
+
"jsonrpc": "2.0",
|
|
673
|
+
"id": mid,
|
|
674
|
+
"result": call_tool(params.get("name"), params.get("arguments")),
|
|
675
|
+
}
|
|
676
|
+
if mid is None:
|
|
677
|
+
return None
|
|
678
|
+
return {
|
|
679
|
+
"jsonrpc": "2.0",
|
|
680
|
+
"id": mid,
|
|
681
|
+
"error": {"code": -32601, "message": "not implemented: %s" % method},
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def write_mcp(obj):
|
|
686
|
+
raw = json.dumps(obj, ensure_ascii=False).encode("utf-8") + b"\n"
|
|
687
|
+
# sys.stdout.write(json.dumps(obj) + "\n")
|
|
688
|
+
# text mode on windows turned that into \r\n. cursor split on \n and json.loads died
|
|
689
|
+
sys.stdout.buffer.write(raw)
|
|
690
|
+
sys.stdout.buffer.flush()
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def read_framed(first_line, stream):
|
|
694
|
+
# Content-Length: 123\r\n
|
|
695
|
+
# \r\n
|
|
696
|
+
# {json}
|
|
697
|
+
try:
|
|
698
|
+
n = int(first_line.split(b":", 1)[1].strip())
|
|
699
|
+
except ValueError:
|
|
700
|
+
return ""
|
|
701
|
+
while True:
|
|
702
|
+
extra = stream.readline()
|
|
703
|
+
if extra == b"" or extra.strip() == b"":
|
|
704
|
+
break
|
|
705
|
+
return stream.read(n).decode("utf-8", "replace")
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def mcp_loop():
|
|
709
|
+
# binary. the text wrapper ate \r and then a framed body came up short and we blocked
|
|
710
|
+
stream = sys.stdin.buffer
|
|
711
|
+
while True:
|
|
712
|
+
line = stream.readline()
|
|
713
|
+
if line == b"":
|
|
714
|
+
return
|
|
715
|
+
if line.lower().startswith(b"content-length:"):
|
|
716
|
+
raw = read_framed(line, stream)
|
|
717
|
+
else:
|
|
718
|
+
raw = line.strip().decode("utf-8", "replace")
|
|
719
|
+
if not raw:
|
|
720
|
+
continue
|
|
721
|
+
try:
|
|
722
|
+
msg = json.loads(raw)
|
|
723
|
+
except json.JSONDecodeError:
|
|
724
|
+
sys.stderr.write("bad json, skipped the line\n")
|
|
725
|
+
continue
|
|
726
|
+
ans = mcp_reply(msg)
|
|
727
|
+
if ans is not None:
|
|
728
|
+
write_mcp(ans)
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
# --- local http, for anything that can't speak mcp ---
|
|
732
|
+
|
|
733
|
+
class Handler(BaseHTTPRequestHandler):
|
|
734
|
+
protocol_version = "HTTP/1.1"
|
|
735
|
+
server_version = "shrink-mcp/" + VER
|
|
736
|
+
# was: leave Python/x.y.z in the header. no reason to advertise the interpreter
|
|
737
|
+
sys_version = ""
|
|
738
|
+
|
|
739
|
+
def log_message(self, fmt, *args):
|
|
740
|
+
sys.stderr.write((fmt % args) + "\n")
|
|
741
|
+
|
|
742
|
+
def _send(self, code, body, ctype="text/plain; charset=utf-8"):
|
|
743
|
+
raw = body if isinstance(body, bytes) else body.encode("utf-8")
|
|
744
|
+
self.send_response(code)
|
|
745
|
+
self.send_header("Content-Type", ctype)
|
|
746
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
747
|
+
# browser chats on localhost get blocked without this
|
|
748
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
749
|
+
self.end_headers()
|
|
750
|
+
try:
|
|
751
|
+
self.wfile.write(raw)
|
|
752
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
753
|
+
return
|
|
754
|
+
|
|
755
|
+
def do_OPTIONS(self):
|
|
756
|
+
self.send_response(204)
|
|
757
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
758
|
+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
759
|
+
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
|
760
|
+
self.send_header("Content-Length", "0")
|
|
761
|
+
self.end_headers()
|
|
762
|
+
|
|
763
|
+
def do_GET(self):
|
|
764
|
+
path = self.path.split("?", 1)[0]
|
|
765
|
+
if path != "/health":
|
|
766
|
+
self._send(404, "nope\n")
|
|
767
|
+
return
|
|
768
|
+
body = json.dumps({"ok": True, "ver": VER})
|
|
769
|
+
self._send(200, body, "application/json; charset=utf-8")
|
|
770
|
+
|
|
771
|
+
def do_POST(self):
|
|
772
|
+
try:
|
|
773
|
+
n = int(self.headers.get("Content-Length") or "0")
|
|
774
|
+
except ValueError:
|
|
775
|
+
self._send(400, "bad Content-Length\n")
|
|
776
|
+
return
|
|
777
|
+
if n > MAX_BYTES:
|
|
778
|
+
self._send(413, "request too big\n")
|
|
779
|
+
return
|
|
780
|
+
raw = self.rfile.read(n)
|
|
781
|
+
path = self.path.split("?", 1)[0]
|
|
782
|
+
try:
|
|
783
|
+
if path == "/log":
|
|
784
|
+
# text = raw.decode("utf-8", "replace")
|
|
785
|
+
# a utf-16 body (notepad) came out as garbage on this route
|
|
786
|
+
text = decode_bytes(raw)
|
|
787
|
+
self._send(200, report(text, squash_log(text)))
|
|
788
|
+
return
|
|
789
|
+
if path != "/shrink":
|
|
790
|
+
self._send(404, "nope\n")
|
|
791
|
+
return
|
|
792
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
793
|
+
# op = payload["kind"]
|
|
794
|
+
op = payload.get("op") or payload.get("kind") or ""
|
|
795
|
+
if op == "log":
|
|
796
|
+
text = payload.get("text") or ""
|
|
797
|
+
self._send(200, report(text, squash_log(text)))
|
|
798
|
+
elif op == "diff":
|
|
799
|
+
self._send(200, do_diff(payload.get("path") or ""))
|
|
800
|
+
elif op == "tree":
|
|
801
|
+
self._send(200, do_tree(payload.get("path") or ""))
|
|
802
|
+
else:
|
|
803
|
+
self._send(400, "op must be log, diff or tree\n")
|
|
804
|
+
except GiveUp as err:
|
|
805
|
+
self._send(400, str(err) + "\n")
|
|
806
|
+
except json.JSONDecodeError:
|
|
807
|
+
self._send(400, "not json. raw text goes to /log\n")
|
|
808
|
+
except Exception as err:
|
|
809
|
+
self._send(500, str(err) + "\n")
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def make_server(port):
|
|
813
|
+
# ThreadingHTTPServer.allow_reuse_address = True
|
|
814
|
+
# on windows the port stuck around after tests. serve stays as-is, tests use port 0
|
|
815
|
+
httpd = ThreadingHTTPServer(("127.0.0.1", port), Handler)
|
|
816
|
+
return httpd
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def serve(port):
|
|
820
|
+
# httpd = ThreadingHTTPServer(("0.0.0.0", port), Handler)
|
|
821
|
+
# once this was reachable from a cafe wifi. localhost only
|
|
822
|
+
try:
|
|
823
|
+
port = int(port)
|
|
824
|
+
except (TypeError, ValueError):
|
|
825
|
+
raise GiveUp("port has to be 0..65535")
|
|
826
|
+
if port < 0 or port > 65535:
|
|
827
|
+
raise GiveUp("port has to be 0..65535")
|
|
828
|
+
try:
|
|
829
|
+
httpd = make_server(port)
|
|
830
|
+
except (OSError, OverflowError) as err:
|
|
831
|
+
raise GiveUp("can't listen: %s" % err)
|
|
832
|
+
bound = httpd.server_address[1]
|
|
833
|
+
sys.stderr.write(f"listening on http://127.0.0.1:{bound}\n")
|
|
834
|
+
sys.stderr.write("POST /log with raw text, POST /shrink json {op,text|path}, GET /health\n")
|
|
835
|
+
try:
|
|
836
|
+
httpd.serve_forever()
|
|
837
|
+
except KeyboardInterrupt:
|
|
838
|
+
sys.stderr.write("\nstopped\n")
|
|
839
|
+
finally:
|
|
840
|
+
httpd.server_close()
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def snapshot(root, prev=None):
|
|
844
|
+
body = show_diff(root)
|
|
845
|
+
out = Path(root) / ".shrink" / "last.txt"
|
|
846
|
+
if body == prev and out.exists():
|
|
847
|
+
return out, body
|
|
848
|
+
out.parent.mkdir(exist_ok=True)
|
|
849
|
+
# out.write_text(body, encoding="utf-8")
|
|
850
|
+
# the agent read a half file once. write aside, then rename
|
|
851
|
+
tmp = out.with_suffix(".txt.tmp")
|
|
852
|
+
tmp.write_text(body, encoding="utf-8")
|
|
853
|
+
tmp.replace(out)
|
|
854
|
+
return out, body
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def watch(path, every):
|
|
858
|
+
root = git_root(Path(path) if path else Path.cwd())
|
|
859
|
+
if root is None:
|
|
860
|
+
raise GiveUp("watch only works inside a git repo")
|
|
861
|
+
sys.stderr.write("writing %s every %ss, ctrl+c to stop\n" % (root / ".shrink" / "last.txt", every))
|
|
862
|
+
prev = None
|
|
863
|
+
try:
|
|
864
|
+
while True:
|
|
865
|
+
_out, body = snapshot(root, prev)
|
|
866
|
+
if body != prev:
|
|
867
|
+
prev = body
|
|
868
|
+
sys.stderr.write("updated\n")
|
|
869
|
+
time.sleep(every)
|
|
870
|
+
except KeyboardInterrupt:
|
|
871
|
+
sys.stderr.write("\nstopped\n")
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def launcher():
|
|
875
|
+
# C:\Windows\System32\python is the store stub. cursor launched it and sat there silent
|
|
876
|
+
if os.name == "nt":
|
|
877
|
+
return ["py", "-3"]
|
|
878
|
+
return [sys.executable]
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
def snippet(kind):
|
|
882
|
+
cmd = launcher()
|
|
883
|
+
script = str(HERE)
|
|
884
|
+
if kind == "vscode":
|
|
885
|
+
return {
|
|
886
|
+
"servers": {
|
|
887
|
+
"shrink-mcp": {
|
|
888
|
+
"type": "stdio",
|
|
889
|
+
"command": cmd[0],
|
|
890
|
+
"args": [*cmd[1:], script, "mcp"],
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
block = {
|
|
895
|
+
"mcpServers": {
|
|
896
|
+
"shrink-mcp": {
|
|
897
|
+
"command": cmd[0],
|
|
898
|
+
"args": [*cmd[1:], script, "mcp"],
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
return block
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def codex_text():
|
|
906
|
+
# codex reads toml, not the json the others use
|
|
907
|
+
cmd = launcher()
|
|
908
|
+
script = str(HERE).replace("\\", "/")
|
|
909
|
+
args = [*cmd[1:], script, "mcp"]
|
|
910
|
+
quoted = ", ".join('"%s"' % a for a in args)
|
|
911
|
+
return "[mcp_servers.\"shrink-mcp\"]\ncommand = \"%s\"\nargs = [%s]\n" % (cmd[0], quoted)
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
def config_path(kind):
|
|
915
|
+
home = Path.home()
|
|
916
|
+
if kind == "cursor":
|
|
917
|
+
return home / ".cursor" / "mcp.json"
|
|
918
|
+
if kind == "vscode":
|
|
919
|
+
return Path.cwd() / ".vscode" / "mcp.json"
|
|
920
|
+
if kind == "claude":
|
|
921
|
+
return Path.cwd() / ".mcp.json"
|
|
922
|
+
if kind == "claude-desktop":
|
|
923
|
+
appdata = os.environ.get("APPDATA") or str(home / "AppData" / "Roaming")
|
|
924
|
+
return Path(appdata) / "Claude" / "claude_desktop_config.json"
|
|
925
|
+
if kind == "codex":
|
|
926
|
+
return home / ".codex" / "config.toml"
|
|
927
|
+
raise GiveUp("unknown target: " + kind + ". use cursor, vscode, claude, claude-desktop, codex")
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def merge_codex(path, block):
|
|
931
|
+
old = ""
|
|
932
|
+
if path.exists():
|
|
933
|
+
old = path.read_text(encoding="utf-8")
|
|
934
|
+
if "[mcp_servers.\"shrink-mcp\"]" in old:
|
|
935
|
+
return False
|
|
936
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
937
|
+
# append. rewriting the file would eat the rest of the user's config
|
|
938
|
+
extra = block
|
|
939
|
+
if old and not old.endswith("\n"):
|
|
940
|
+
extra = "\n" + extra
|
|
941
|
+
if old and not old.endswith("\n\n"):
|
|
942
|
+
extra = "\n" + extra
|
|
943
|
+
path.write_text(old + extra, encoding="utf-8")
|
|
944
|
+
return True
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def merge_json(path, fresh):
|
|
948
|
+
data = {}
|
|
949
|
+
if path.exists():
|
|
950
|
+
try:
|
|
951
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
952
|
+
except json.JSONDecodeError:
|
|
953
|
+
raise GiveUp(f"{path} is broken json, fix it yourself, I won't touch it")
|
|
954
|
+
if not isinstance(data, dict):
|
|
955
|
+
raise GiveUp(f"{path} is not a json object")
|
|
956
|
+
# used to write the fresh blob over the file and wipe other servers. not doing that again
|
|
957
|
+
for key, val in fresh.items():
|
|
958
|
+
if isinstance(val, dict):
|
|
959
|
+
slot = data.get(key)
|
|
960
|
+
if not isinstance(slot, dict):
|
|
961
|
+
slot = {}
|
|
962
|
+
slot.update(val)
|
|
963
|
+
data[key] = slot
|
|
964
|
+
else:
|
|
965
|
+
data[key] = val
|
|
966
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
967
|
+
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def setup(kind, write):
|
|
971
|
+
kind = kind or "cursor"
|
|
972
|
+
if kind == "codex":
|
|
973
|
+
text = codex_text()
|
|
974
|
+
where = config_path(kind)
|
|
975
|
+
if not write:
|
|
976
|
+
sys.stdout.write(text)
|
|
977
|
+
sys.stdout.flush()
|
|
978
|
+
sys.stderr.write("\nthis is for codex. the file usually lives at: %s\n" % where)
|
|
979
|
+
sys.stderr.write("to append it, add --write. an existing shrink block is left alone\n")
|
|
980
|
+
return
|
|
981
|
+
if merge_codex(where, text):
|
|
982
|
+
sys.stderr.write("added shrink to %s\n" % where)
|
|
983
|
+
else:
|
|
984
|
+
sys.stderr.write("shrink is already in %s\n" % where)
|
|
985
|
+
sys.stderr.write("restart codex, it does not always pick the config up live\n")
|
|
986
|
+
return
|
|
987
|
+
body = snippet(kind)
|
|
988
|
+
text = json.dumps(body, ensure_ascii=False, indent=2)
|
|
989
|
+
if not write:
|
|
990
|
+
sys.stdout.write(text + "\n")
|
|
991
|
+
sys.stdout.flush()
|
|
992
|
+
where = config_path(kind)
|
|
993
|
+
sys.stderr.write(f"\nthis is for {kind}. the file usually lives at: {where}\n")
|
|
994
|
+
sys.stderr.write("to merge it in with the other servers, add --write\n")
|
|
995
|
+
return
|
|
996
|
+
path = config_path(kind)
|
|
997
|
+
merge_json(path, body)
|
|
998
|
+
sys.stderr.write(f"added shrink to {path}\n")
|
|
999
|
+
sys.stderr.write("restart the editor, it does not always pick the config up live\n")
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def every_from(argv):
|
|
1003
|
+
if "--every" not in argv:
|
|
1004
|
+
return 2.0
|
|
1005
|
+
i = argv.index("--every")
|
|
1006
|
+
try:
|
|
1007
|
+
n = float(argv[i + 1])
|
|
1008
|
+
except (IndexError, ValueError):
|
|
1009
|
+
raise GiveUp("--every needs a number of seconds")
|
|
1010
|
+
if n <= 0:
|
|
1011
|
+
raise GiveUp("--every needs a number of seconds")
|
|
1012
|
+
return n
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def pick_port(argv):
|
|
1016
|
+
if "--port" in argv:
|
|
1017
|
+
i = argv.index("--port")
|
|
1018
|
+
try:
|
|
1019
|
+
return int(argv[i + 1])
|
|
1020
|
+
except (IndexError, ValueError):
|
|
1021
|
+
raise GiveUp("--port needs a number")
|
|
1022
|
+
if len(argv) >= 3 and argv[2].isdigit():
|
|
1023
|
+
return int(argv[2])
|
|
1024
|
+
return 8765
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def emit(text):
|
|
1028
|
+
sys.stdout.write(text if text.endswith("\n") else text + "\n")
|
|
1029
|
+
sys.stdout.flush()
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def main(argv=None):
|
|
1033
|
+
if argv is None:
|
|
1034
|
+
argv = sys.argv
|
|
1035
|
+
argv = list(argv)
|
|
1036
|
+
fix_stdio()
|
|
1037
|
+
|
|
1038
|
+
try:
|
|
1039
|
+
if len(argv) < 2:
|
|
1040
|
+
if not sys.stdin.isatty():
|
|
1041
|
+
emit(do_log(""))
|
|
1042
|
+
return 0
|
|
1043
|
+
sys.stdout.write(HELP)
|
|
1044
|
+
return 0
|
|
1045
|
+
|
|
1046
|
+
cmd = argv[1]
|
|
1047
|
+
if cmd in ("-v", "--version", "version"):
|
|
1048
|
+
sys.stdout.write(VER + "\n")
|
|
1049
|
+
return 0
|
|
1050
|
+
if cmd in ("-h", "--help", "help"):
|
|
1051
|
+
sys.stdout.write(HELP)
|
|
1052
|
+
return 0
|
|
1053
|
+
if cmd == "diff":
|
|
1054
|
+
emit(do_diff(argv[2] if len(argv) > 2 else ""))
|
|
1055
|
+
elif cmd == "log":
|
|
1056
|
+
path = argv[2] if len(argv) > 2 else ""
|
|
1057
|
+
# used to read stdin anyway. on a terminal that just sat there
|
|
1058
|
+
if not path and sys.stdin.isatty():
|
|
1059
|
+
raise GiveUp("nothing piped in. shrink log build.log")
|
|
1060
|
+
emit(do_log(path))
|
|
1061
|
+
elif cmd == "tree":
|
|
1062
|
+
emit(do_tree(argv[2] if len(argv) > 2 else ""))
|
|
1063
|
+
elif cmd == "mcp":
|
|
1064
|
+
mcp_loop()
|
|
1065
|
+
elif cmd == "serve":
|
|
1066
|
+
serve(pick_port(argv))
|
|
1067
|
+
elif cmd == "watch":
|
|
1068
|
+
every = every_from(argv)
|
|
1069
|
+
target = ""
|
|
1070
|
+
for item in argv[2:]:
|
|
1071
|
+
if item.startswith("--"):
|
|
1072
|
+
break
|
|
1073
|
+
if item.isdigit():
|
|
1074
|
+
continue
|
|
1075
|
+
target = item
|
|
1076
|
+
break
|
|
1077
|
+
watch(target, every)
|
|
1078
|
+
elif cmd == "setup":
|
|
1079
|
+
kind = "cursor"
|
|
1080
|
+
write = False
|
|
1081
|
+
for item in argv[2:]:
|
|
1082
|
+
if item == "--write":
|
|
1083
|
+
write = True
|
|
1084
|
+
elif not item.startswith("-"):
|
|
1085
|
+
kind = item
|
|
1086
|
+
setup(kind, write)
|
|
1087
|
+
else:
|
|
1088
|
+
sys.stderr.write(f"unknown command {cmd}\n\n")
|
|
1089
|
+
sys.stdout.write(HELP)
|
|
1090
|
+
return 1
|
|
1091
|
+
except GiveUp as err:
|
|
1092
|
+
sys.stderr.write(str(err) + "\n")
|
|
1093
|
+
return 1
|
|
1094
|
+
except KeyboardInterrupt:
|
|
1095
|
+
return 130
|
|
1096
|
+
return 0
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
if __name__ == "__main__":
|
|
1100
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: shrink-mcp
|
|
3
|
+
Version: 0.4.2
|
|
4
|
+
Summary: Fewer tokens for coding agents. Shrink git diffs, test logs, and repo trees. MCP for Cursor, Claude Code, Codex, and VS Code.
|
|
5
|
+
Author: humer90000
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 humer90000
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Requires-Python: >=3.9
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Provides-Extra: tokens
|
|
32
|
+
Requires-Dist: tiktoken; extra == "tokens"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# shrink-mcp
|
|
36
|
+
|
|
37
|
+
Experimental project. The package name is shrink-mcp. The command is still `shrink`. Fewer tokens for coding agents. Shrinks a git diff, a test log, or a repo tree when the context window is getting fat and the model starts forgetting. The first line is a rough before -> after token count. It is useful, and it is not a finished product.
|
|
38
|
+
|
|
39
|
+
Use it from a terminal, over localhost HTTP, or as an MCP server. Cursor, Claude Code, Codex, VS Code, and Claude Desktop can all call it. Only the config file changes.
|
|
40
|
+
|
|
41
|
+
Python 3.9 or newer. No required packages. MIT license.
|
|
42
|
+
|
|
43
|
+
On this Windows box `python` is the store stub and does nothing. Use `py -3`. If your `python` actually runs, use that instead.
|
|
44
|
+
|
|
45
|
+
## examples
|
|
46
|
+
|
|
47
|
+
Both were `py -3 shrink.py log build.log` on this machine, no tiktoken. The first line of the answer is the before -> after count.
|
|
48
|
+
|
|
49
|
+
### Same line, 200 times
|
|
50
|
+
|
|
51
|
+
The file had 201 lines. Line 1 through 200 were identical. Line 201 was the error.
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
compile ok
|
|
55
|
+
compile ok
|
|
56
|
+
compile ok
|
|
57
|
+
... 197 more "compile ok" ...
|
|
58
|
+
Error: disk full, cannot write C:/build/out.bin
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
415 tokens in. The program printed only this:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
rough tokens: 415 -> 18
|
|
65
|
+
|
|
66
|
+
compile ok x200
|
|
67
|
+
Error: disk full, cannot write C:/build/out.bin
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`x200` means the line was there 200 times. The error sentence is unchanged.
|
|
71
|
+
|
|
72
|
+
### 120 different lines, one error in the middle
|
|
73
|
+
|
|
74
|
+
Nothing repeats. `file_001` through `file_120`, and at `file_071` the compiler error:
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
compiled src/file_001.ts
|
|
78
|
+
compiled src/file_002.ts
|
|
79
|
+
compiled src/file_003.ts
|
|
80
|
+
... file_004 through file_070, each name different ...
|
|
81
|
+
src/pay.ts(40,12): error TS2304: Cannot find name total
|
|
82
|
+
compiled src/file_072.ts
|
|
83
|
+
... file_073 through file_120 ...
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
732 tokens in, 176 back. `file_001` through `file_068` are gone. The error is still there, with the two lines above it, and the end of the file is still there:
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
rough tokens: 732 -> 176
|
|
90
|
+
|
|
91
|
+
... lines hidden: 68
|
|
92
|
+
compiled src/file_069.ts
|
|
93
|
+
compiled src/file_070.ts
|
|
94
|
+
src/pay.ts(40,12): error TS2304: Cannot find name total
|
|
95
|
+
compiled src/file_072.ts
|
|
96
|
+
compiled src/file_073.ts
|
|
97
|
+
compiled src/file_074.ts
|
|
98
|
+
compiled src/file_075.ts
|
|
99
|
+
compiled src/file_076.ts
|
|
100
|
+
compiled src/file_077.ts
|
|
101
|
+
compiled src/file_078.ts
|
|
102
|
+
... lines hidden: 27
|
|
103
|
+
compiled src/file_106.ts
|
|
104
|
+
compiled src/file_107.ts
|
|
105
|
+
compiled src/file_108.ts
|
|
106
|
+
compiled src/file_109.ts
|
|
107
|
+
compiled src/file_110.ts
|
|
108
|
+
compiled src/file_111.ts
|
|
109
|
+
compiled src/file_112.ts
|
|
110
|
+
compiled src/file_113.ts
|
|
111
|
+
compiled src/file_114.ts
|
|
112
|
+
compiled src/file_115.ts
|
|
113
|
+
compiled src/file_116.ts
|
|
114
|
+
compiled src/file_117.ts
|
|
115
|
+
compiled src/file_118.ts
|
|
116
|
+
compiled src/file_119.ts
|
|
117
|
+
compiled src/file_120.ts
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`... lines hidden: 68` is `file_001` to `file_068`. The second hidden block is `file_079` to `file_105`. What a person needs from this log is the `TS2304` line, and it survived.
|
|
121
|
+
|
|
122
|
+
## install
|
|
123
|
+
|
|
124
|
+
From PyPI:
|
|
125
|
+
|
|
126
|
+
```
|
|
127
|
+
py -3 -m pip install shrink-mcp
|
|
128
|
+
shrink --version
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
From a checkout of this repo:
|
|
132
|
+
|
|
133
|
+
```
|
|
134
|
+
py -3 -m pip install -e .
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
# was: python setup.py install
|
|
138
|
+
# there is no setup.py anymore
|
|
139
|
+
|
|
140
|
+
Without installing, the same thing is `py -3 shrink.py ...` from this folder.
|
|
141
|
+
|
|
142
|
+
Optional, closer token counts (cl100k, same family most chat APIs use):
|
|
143
|
+
|
|
144
|
+
```
|
|
145
|
+
py -3 -m pip install "shrink-mcp[tokens]"
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Without that extra the count is a split on words and punctuation. It is still a guess, not the invoice.
|
|
149
|
+
|
|
150
|
+
## use it
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
shrink diff
|
|
154
|
+
shrink log build.log
|
|
155
|
+
shrink tree
|
|
156
|
+
type build.log | shrink
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`shrink log` with no file and no pipe used to wait forever. It now says so. A UTF-16 log from Notepad is read, including when it is posted to `/log`. Repeated lines collapse (`compile ok x200`). When the lines are all different and the file is long, it keeps the error, a few lines around it, and the tail. That is the second example above.
|
|
160
|
+
|
|
161
|
+
A line counts as an error for pytest (`FAIL`, `assert`), npm (`npm ERR!`), Rust (`error[E0308]`, `panicked`), Go (`FAIL`), a Python traceback (the exception at the bottom stays, not just the word Traceback), and a shell crash (`segmentation fault`). A line that only says `0 errors` or `errors: 0` does not.
|
|
162
|
+
|
|
163
|
+
`diff` has to run inside a git repo. Lockfiles, images and binary patches are not expanded, even when the diff is short. A long file keeps the header and the first chunk of changes, then a line saying how many were hidden. A repo that has no commit yet lists the new files instead of dying on `HEAD`. A short normal diff is left alone. Cutting those made small edits worse.
|
|
164
|
+
|
|
165
|
+
`tree` skips `node_modules`, `.git`, `.venv`, `venv`, `dist`, `build`, `target`, `__pycache__`, `.next`, `coverage` and `*.egg-info`. It opens three levels. Anything deeper is one note, `deeper folders not opened`, not a list of names. A directory with a lot of files shows the first dozen and a count of the rest.
|
|
166
|
+
|
|
167
|
+
```
|
|
168
|
+
shrink serve
|
|
169
|
+
curl.exe -s --data-binary @build.log http://127.0.0.1:8765/log
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Listens on 127.0.0.1 only. `GET /health`. `POST /shrink` takes `{"op":"log","text":"..."}` or `diff` / `tree` with `path`. The field `kind` still works. The draft called it that.
|
|
173
|
+
|
|
174
|
+
Other port: `shrink serve 9000`.
|
|
175
|
+
|
|
176
|
+
`shrink watch` rewrites `.shrink/last.txt` every two seconds, for an agent that can read a file and cannot start MCP. Don't commit `.shrink`.
|
|
177
|
+
|
|
178
|
+
## editor
|
|
179
|
+
|
|
180
|
+
Print the snippet:
|
|
181
|
+
|
|
182
|
+
```
|
|
183
|
+
shrink setup
|
|
184
|
+
shrink setup vscode
|
|
185
|
+
shrink setup claude
|
|
186
|
+
shrink setup claude-desktop
|
|
187
|
+
shrink setup codex
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Merge it in. Other servers in that file stay put. Codex is toml, so `--write` appends a block and will not add a second one:
|
|
191
|
+
|
|
192
|
+
```
|
|
193
|
+
shrink setup cursor --write
|
|
194
|
+
shrink setup vscode --write
|
|
195
|
+
shrink setup claude --write
|
|
196
|
+
shrink setup claude-desktop --write
|
|
197
|
+
shrink setup codex --write
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Where `--write` goes:
|
|
201
|
+
|
|
202
|
+
- cursor: `%USERPROFILE%\.cursor\mcp.json`
|
|
203
|
+
- vscode: `.vscode/mcp.json` in the current folder
|
|
204
|
+
- claude code: `.mcp.json` in the current folder
|
|
205
|
+
- claude desktop: `%APPDATA%\Claude\claude_desktop_config.json`
|
|
206
|
+
- codex: `%USERPROFILE%\.codex\config.toml`
|
|
207
|
+
|
|
208
|
+
Restart the editor after that. It does not always reload a config that is already open.
|
|
209
|
+
|
|
210
|
+
The tools are `shrink_diff`, `shrink_log`, `shrink_tree`. Don't start `shrink mcp` yourself. The editor does.
|
|
211
|
+
|
|
212
|
+
## what it will not do
|
|
213
|
+
|
|
214
|
+
It does not call a model. It does not apply the diff back. It does not open a port on the network. A log bigger than about 2 MB is cut. The token line is an estimate unless you installed the `tokens` extra.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
shrink.py,sha256=AplWcFPZZ-4rVbjpUt52tDTR55MKg5fRT42FDKZzHSw,35752
|
|
2
|
+
shrink_mcp-0.4.2.dist-info/licenses/LICENSE,sha256=AJrhKbJ35vW1uZlatTMDZldbJQfNjvtB_lFc7Y3j-pE,1088
|
|
3
|
+
shrink_mcp-0.4.2.dist-info/METADATA,sha256=Hc4z87jBDUUXq8nhoQtU1NHJuzCTf24n8Q2z4GQJgFo,8134
|
|
4
|
+
shrink_mcp-0.4.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
shrink_mcp-0.4.2.dist-info/entry_points.txt,sha256=C5AyOMNNhrhG5F3T42b0QHUgy1-ew3ew3rrVsmGaIKc,39
|
|
6
|
+
shrink_mcp-0.4.2.dist-info/top_level.txt,sha256=_pbFvypkiBHrIqpziPs3j20jp2TacBX7v1m7X9FSfcw,7
|
|
7
|
+
shrink_mcp-0.4.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 humer90000
|
|
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
|
+
shrink
|