vision-squeezer 0.8.0

Fit images to a vision-LLM token budget before you send them. Library, CLI and MCP server for code, agents and pipelines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#!/usr/bin/env node
'use strict';

/**
 * Interactive MCP installer for VisionSqueezer.
 *
 *   npx vision-squeezer install            # prompts for client + scope
 *   npx vision-squeezer install --scope user
 *   npx vision-squeezer install --client claude --scope project --yes
 *   npx vision-squeezer install --client cursor --yes
 */

const { spawnSync } = require('child_process');
const readline = require('readline');
const path = require('path');
const fs = require('fs');
const os = require('os');

// Pinning to an exact version in the MCP command line busts the npx cache on
// every upgrade. Without it, `npx -y vision-squeezer` silently reuses an old
// cached tarball even after `npm install -g vision-squeezer@latest` — users
// then see "MCP failed to connect" with a stale binary they can't update.
const PKG_VERSION = require(path.join(__dirname, '..', 'package.json')).version;

const SCOPES = [
  {
    key: 'user',
    label: 'user',
    description: 'All projects on this machine (recommended)',
  },
  {
    key: 'local',
    label: 'local',
    description: 'This project only, private to you (Claude Code default)',
  },
  {
    key: 'project',
    label: 'project',
    description: 'Shared via .mcp.json checked into the repo',
  },
];

// `scopes` lists the scopes a client supports (omitted = all). `kind: 'json'`
// clients have no non-interactive CLI, so the installer edits their JSON config
// (see JSON_TARGETS). Zed is not here: its settings.json allows comments, so a
// rewrite could destroy the user's file.
const CLIENTS = [
  { key: 'claude', label: 'Claude Code', cli: 'claude' },
  { key: 'codex', label: 'Codex CLI', cli: 'codex' },
  { key: 'qwen', label: 'Qwen Code', cli: 'qwen' },
  { key: 'opencode', label: 'OpenCode', cli: 'opencode', kind: 'json', scopes: ['user', 'project'] },
  { key: 'gemini', label: 'Gemini CLI', cli: 'gemini', scopes: ['user', 'project'] },
  { key: 'kimi', label: 'Kimi CLI', cli: 'kimi', scopes: ['user'] },
  { key: 'cursor', label: 'Cursor', kind: 'json', scopes: ['user', 'project'] },
  { key: 'windsurf', label: 'Windsurf', kind: 'json', scopes: ['user'] },
  { key: 'claude-desktop', label: 'Claude Desktop', kind: 'json', scopes: ['user'] },
  { key: 'vscode', label: 'VS Code', cli: 'code', scopes: ['user'] },
];

// Install methods available for Claude Code only. Codex/Qwen go straight to
// `mcp add`. OpenCode has no non-interactive `mcp add` — it only reads
// config files — so it gets CONFIG_METHOD below instead.
const METHODS = [
  {
    key: 'plugin',
    label: 'Claude plugin marketplace',
    description: 'One-command install via /plugin — bundles MCP server + stats/doctor/upgrade skills',
  },
  {
    key: 'mcp-add',
    label: 'claude mcp add',
    description: 'Register only the MCP server (no bundled skills) using `claude mcp add`',
  },
];

// Clients without a usable `mcp add` (OpenCode's is interactive-only; Cursor,
// Windsurf and Claude Desktop have none) get their JSON config written directly.
const CONFIG_METHOD = { key: 'config-file', label: 'config file' };

const NPX_ARGS = ['-y', `vision-squeezer@${PKG_VERSION}`];
const stdioEntry = () => ({ command: 'npx', args: NPX_ARGS });

function claudeDesktopPath() {
  if (process.platform === 'darwin') {
    return path.join(os.homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
  }
  if (process.platform === 'win32' && process.env.APPDATA) {
    return path.join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
  }
  return null; // no Linux build of Claude Desktop
}

const JSON_TARGETS = {
  opencode: {
    file: (scope) => scope.key === 'user'
      ? path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
      : path.join(process.cwd(), 'opencode.json'),
    root: 'mcp',
    entry: () => ({ type: 'local', command: ['npx', ...NPX_ARGS], enabled: true }),
    schema: 'https://opencode.ai/config.json',
  },
  cursor: {
    file: (scope) => scope.key === 'user'
      ? path.join(os.homedir(), '.cursor', 'mcp.json')
      : path.join(process.cwd(), '.cursor', 'mcp.json'),
    root: 'mcpServers',
    entry: stdioEntry,
  },
  windsurf: {
    file: () => path.join(os.homedir(), '.codeium', 'windsurf', 'mcp_config.json'),
    root: 'mcpServers',
    entry: stdioEntry,
  },
  'claude-desktop': {
    file: claudeDesktopPath,
    root: 'mcpServers',
    entry: stdioEntry,
  },
};

const MARKETPLACE_REPO = 'eralpozcan/vision-squeezer';
const PLUGIN_NAME = 'vision-squeezer-mcp';

function parseArgs(argv) {
  const out = { scope: null, client: null, method: null, yes: false, hook: true };
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === '--scope' || a === '-s') out.scope = argv[++i];
    else if (a === '--client' || a === '-c') out.client = argv[++i];
    else if (a === '--method' || a === '-m') out.method = argv[++i];
    else if (a === '--yes' || a === '-y') out.yes = true;
    else if (a === '--no-hook') out.hook = false;
    else if (a === '--help' || a === '-h') out.help = true;
  }
  return out;
}

function printHelp() {
  console.log(`vision-squeezer install — register the MCP server with an AI CLI

Usage:
  npx vision-squeezer install [options]

Options:
  -c, --client <name>   Target (claude | codex | qwen | opencode | gemini | kimi | cursor | windsurf | claude-desktop | vscode)
  -m, --method <name>   Install method for Claude Code (plugin | mcp-add)
  -s, --scope <name>    Install scope for 'mcp-add' (user | local | project)
  -y, --yes             Skip confirmation prompt
      --no-hook         Claude Code mcp-add: do not add the image-read hook
  -h, --help            Show this help

Methods (Claude Code only):
  plugin    /plugin marketplace add eralpozcan/vision-squeezer
            /plugin install vision-squeezer-mcp@vision-squeezer
            Bundles MCP server + stats/doctor/upgrade skills.

  mcp-add   claude mcp add [--scope X] vision-squeezer -- npx -y vision-squeezer@<version>
            Server only, no skills bundled. The version is pinned to the
            installer's package version so the npx cache busts on upgrade.

Image-read hook (Claude Code):
  With mcp-add the installer also adds a PreToolUse hook to Claude Code's
  settings.json (user: ~/.claude, project: .claude/settings.json, local:
  .claude/settings.local.json). When Claude reads an image inside the project,
  the hook hands it the token-optimized copy. The plugin method ships the same
  hook. Pass --no-hook to skip it. Pasted images and @-files are not covered.

Scopes (mcp-add):
  user      All projects on this machine (recommended)
  local     This project only, private to you (default for Claude Code)
  project   Shared via .mcp.json checked into the repo

OpenCode:
  \`opencode mcp add\` is interactive-only (no flags), so this installer
  writes the MCP entry directly into OpenCode's JSON config instead:
    user      ~/.config/opencode/opencode.json (global)
    project   ./opencode.json (repo root)
  OpenCode has no 'local' scope.

Gemini CLI:
  gemini mcp add --scope X vision-squeezer -- npx -y vision-squeezer@<version>
  Scope writes to ~/.gemini/settings.json (user) or .gemini/settings.json
  (project). Gemini CLI has no 'local' scope.

Kimi CLI:
  kimi mcp add vision-squeezer -- npx -y vision-squeezer@<version>
  Always writes the single global ~/.kimi/mcp.json — no scope flag exists.

Cursor:
  Adds an "mcpServers" entry to a JSON file (existing servers are kept):
    user      ~/.cursor/mcp.json
    project   ./.cursor/mcp.json

Windsurf:
  Adds an "mcpServers" entry to ~/.codeium/windsurf/mcp_config.json (user only).

Claude Desktop:
  Adds an "mcpServers" entry to claude_desktop_config.json (user only;
  macOS: ~/Library/Application Support/Claude, Windows: %APPDATA%\\Claude).

VS Code:
  code --add-mcp '{"name":"vision-squeezer","command":"npx","args":[...]}'
  Adds the server to your VS Code user profile (user only).

JSON config files that cannot be parsed (for example with comments) are left
untouched; add the entry by hand (see https://visionsqueezer.com/getting-started/mcp-setup).
`);
}

function prompt(rl, question) {
  return new Promise((resolve) => rl.question(question, (a) => resolve(a.trim())));
}

async function pickFromList(rl, label, items, fallbackKey) {
  console.log(`\n${label}:`);
  items.forEach((it, i) => {
    const desc = it.description ? `  — ${it.description}` : '';
    console.log(`  ${i + 1}) ${it.label}${desc}`);
  });
  const def = items.findIndex((it) => it.key === fallbackKey);
  const defLabel = def >= 0 ? def + 1 : 1;
  const ans = await prompt(rl, `Choice [${defLabel}]: `);
  if (!ans) return items[def >= 0 ? def : 0];
  const n = parseInt(ans, 10);
  if (Number.isFinite(n) && n >= 1 && n <= items.length) return items[n - 1];
  const byKey = items.find((it) => it.key === ans.toLowerCase());
  if (byKey) return byKey;
  console.error(`Invalid choice: ${ans}`);
  return pickFromList(rl, label, items, fallbackKey);
}

function commandExists(cmd) {
  const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [cmd], {
    stdio: 'ignore',
  });
  return r.status === 0;
}

// ── Claude Code image-read hook ──────────────────────────────────────────────

const HOOK_COMMAND = `npx -y vision-squeezer@${PKG_VERSION} hook`;
const HOOK_IMAGE_GLOBS = ['*.png', '*.jpg', '*.jpeg', '*.webp', '*.gif'];

// One handler per extension: the `if` filter keeps the hook from spawning on
// every Read of a source file.
function hookEntry() {
  return {
    matcher: 'Read',
    hooks: HOOK_IMAGE_GLOBS.map((g) => ({ type: 'command', if: `Read(${g})`, command: HOOK_COMMAND })),
  };
}

function isOurHook(entry) {
  return Array.isArray(entry && entry.hooks)
    && entry.hooks.some((h) => typeof h.command === 'string' && /vision-squeezer@\S+ hook$/.test(h.command));
}

function claudeSettingsPath(scope) {
  if (scope.key === 'user') return path.join(os.homedir(), '.claude', 'settings.json');
  return path.join(process.cwd(), '.claude', scope.key === 'project' ? 'settings.json' : 'settings.local.json');
}

// Merge our hook into Claude Code's settings. Other settings and hooks are kept,
// an older copy of ours is replaced (so upgrades re-pin the version), and a file
// that cannot be parsed is left untouched.
function installClaudeHook(scope) {
  const file = claudeSettingsPath(scope);
  let settings = {};
  if (fs.existsSync(file)) {
    try {
      settings = JSON.parse(fs.readFileSync(file, 'utf8'));
    } catch (err) {
      console.error(`Could not add the image-read hook: cannot parse ${file} (${err.message}). Left untouched.`);
      return false;
    }
  } else {
    fs.mkdirSync(path.dirname(file), { recursive: true });
  }
  settings.hooks = settings.hooks || {};
  const pre = Array.isArray(settings.hooks.PreToolUse) ? settings.hooks.PreToolUse : [];
  settings.hooks.PreToolUse = [...pre.filter((e) => !isOurHook(e)), hookEntry()];
  fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  console.log(`Added the image-read hook to ${file}. Claude Code now reads project images at their optimized size.`);
  return true;
}

function buildArgs(client, scope) {
  // claude/codex/qwen/gemini accept the same shape: `<cli> mcp add [--scope X] NAME -- npx -y vision-squeezer@<version>`
  // `local` is the Claude Code default — omit the flag to keep behavior identical to docs.
  // Kimi CLI has no scope concept (single global ~/.kimi/mcp.json) — never pass --scope.
  if (client.key === 'vscode') {
    return ['--add-mcp', JSON.stringify({ name: 'vision-squeezer', ...stdioEntry() })];
  }
  const args = ['mcp', 'add'];
  if (client.key !== 'kimi' && scope.key !== 'local') {
    args.push('--scope', scope.key);
  }
  args.push('vision-squeezer', '--', 'npx', ...NPX_ARGS);
  return args;
}

async function main() {
  const argv = process.argv.slice(2);
  const opts = parseArgs(argv);
  if (opts.help) {
    printHelp();
    return 0;
  }

  console.log('VisionSqueezer MCP installer\n');

  let client;
  if (opts.client) {
    client = CLIENTS.find((c) => c.key === opts.client.toLowerCase());
    if (!client) {
      console.error(`Unknown client: ${opts.client}. Expected one of: ${CLIENTS.map((c) => c.key).join(', ')}`);
      return 1;
    }
  }
  let scope;
  if (opts.scope) {
    scope = SCOPES.find((s) => s.key === opts.scope.toLowerCase());
    if (!scope) {
      console.error(`Unknown scope: ${opts.scope}. Expected one of: ${SCOPES.map((s) => s.key).join(', ')}`);
      return 1;
    }
  }
  if (client && client.scopes && scope && !client.scopes.includes(scope.key)) {
    console.error(`${client.label} supports only: ${client.scopes.join(', ')} (got '${scope.key}').`);
    return 1;
  }

  let method;
  if (opts.method) {
    method = METHODS.find((m) => m.key === opts.method.toLowerCase());
    if (!method) {
      console.error(`Unknown method: ${opts.method}. Expected one of: ${METHODS.map((m) => m.key).join(', ')}`);
      return 1;
    }
  }

  // For non-Claude clients there is no /plugin equivalent — auto-force mcp-add.
  if (client && client.key !== 'claude' && !method) {
    method = METHODS.find((m) => m.key === 'mcp-add');
  }
  const needsMethodPrompt = () => {
    if (!client) return true; // client unknown → maybe claude → may need method
    if (client.key !== 'claude') return false;
    return !method;
  };
  const needsScopePrompt = () => {
    if (method && method.key === 'plugin') return false;
    if (client && client.scopes && client.scopes.length === 1) return false; // single fixed scope
    return !scope;
  };

  const interactive = !client || needsMethodPrompt() || needsScopePrompt();
  let rl;
  if (interactive) {
    if (!process.stdin.isTTY) {
      console.error('Non-interactive shell detected. Pass --client (and --method / --scope) explicitly.');
      printHelp();
      return 1;
    }
    rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  }

  try {
    if (!client) client = await pickFromList(rl, 'Pick an AI CLI', CLIENTS, 'claude');

    if (client.key === 'claude') {
      if (!method) method = await pickFromList(rl, 'Pick install method', METHODS, 'plugin');
    } else if (client.kind === 'json') {
      method = CONFIG_METHOD;
    } else {
      // codex / qwen / gemini / kimi / vscode have no plugin marketplace concept
      method = METHODS.find((m) => m.key === 'mcp-add');
    }
    // A single supported scope (kimi, windsurf, claude-desktop, vscode) is not a choice.
    if (!scope && client.scopes && client.scopes.length === 1) {
      scope = SCOPES.find((s) => s.key === client.scopes[0]);
    }

    if ((method.key === 'mcp-add' || method.key === 'config-file') && !scope) {
      const scopeList = client.scopes ? SCOPES.filter((s) => client.scopes.includes(s.key)) : SCOPES;
      scope = await pickFromList(rl, 'Pick install scope', scopeList, 'user');
    }

    if (!commandExists(client.cli) && method.key !== 'config-file') {
      console.error(`\n'${client.cli}' CLI not found in PATH.`);
      const flags = method.key === 'plugin'
        ? `--client ${client.key} --method plugin`
        : `--client ${client.key} --method mcp-add --scope ${scope.key}`;
      console.error(`Install it first, then re-run: npx vision-squeezer install ${flags}`);
      return 1;
    }

    if (method.key === 'plugin') {
      return await runPluginInstall(rl, opts.yes);
    }

    if (method.key === 'config-file') {
      return await runJsonInstall(client, rl, scope, opts.yes);
    }

    const args = buildArgs(client, scope);
    console.log(`\nWill run: ${client.cli} ${args.join(' ')}`);

    if (interactive && !opts.yes) {
      const confirm = await prompt(rl, 'Proceed? [Y/n]: ');
      if (confirm && !/^y(es)?$/i.test(confirm)) {
        console.log('Cancelled.');
        return 0;
      }
    }
    if (rl) rl.close();

    const result = spawnSync(client.cli, args, { stdio: 'inherit' });
    if (result.error) {
      console.error(result.error.message);
      return 1;
    }
    if ((result.status ?? 0) !== 0) {
      return result.status ?? 1;
    }
    console.log(`\nDone. VisionSqueezer registered with ${client.label} (scope: ${scope.key}).`);
    if (client.key === 'claude' && opts.hook) installClaudeHook(scope);
    return 0;
  } finally {
    if (rl && !rl.closed) rl.close();
  }
}

async function runJsonInstall(client, rl, scope, yes) {
  const target = JSON_TARGETS[client.key];
  const configPath = target.file(scope);
  if (!configPath) {
    console.error(`${client.label} is not available on this platform.`);
    return 1;
  }
  console.log(`\nWill write MCP entry to: ${configPath}`);

  if (rl && !yes) {
    const confirm = await prompt(rl, 'Proceed? [Y/n]: ');
    if (confirm && !/^y(es)?$/i.test(confirm)) {
      console.log('Cancelled.');
      return 0;
    }
  }
  if (rl) rl.close();

  let config = {};
  if (fs.existsSync(configPath)) {
    try {
      config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    } catch (err) {
      console.error(`Cannot parse ${configPath}: ${err.message}`);
      console.error('Left untouched. It may contain comments; add the entry by hand (see --help).');
      return 1;
    }
  } else {
    fs.mkdirSync(path.dirname(configPath), { recursive: true });
    if (target.schema) config.$schema = target.schema;
  }
  config[target.root] = config[target.root] || {};
  config[target.root]['vision-squeezer'] = target.entry();
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');

  console.log(`\nDone. VisionSqueezer registered with ${client.label} (scope: ${scope.key}) at ${configPath}.`);
  if (client.key !== 'opencode') console.log(`Restart ${client.label} to load it.`);
  return 0;
}

async function runPluginInstall(rl, yes) {
  // /plugin commands run inside Claude Code's TUI — they aren't shell-callable.
  // Print copy-paste instructions instead of trying to spawn a slash command.
  console.log(`
Claude plugin marketplace install
─────────────────────────────────
Open Claude Code and run these two commands:

  /plugin marketplace add ${MARKETPLACE_REPO}
  /plugin install ${PLUGIN_NAME}@vision-squeezer

The first command registers the marketplace; the second installs the bundled
MCP server. After install, restart any open Claude Code session for the MCP
server to attach.
`);

  if (rl && !yes) {
    const ans = await prompt(rl, 'Copy the marketplace add command to clipboard? [Y/n]: ');
    if (!ans || /^y(es)?$/i.test(ans)) {
      const text = `/plugin marketplace add ${MARKETPLACE_REPO}`;
      const ok = copyToClipboard(text);
      console.log(ok ? 'Copied. Paste in Claude Code.' : 'Clipboard unavailable — copy manually.');
    }
    rl.close();
  }
  return 0;
}

function copyToClipboard(text) {
  const candidates = process.platform === 'darwin'
    ? [['pbcopy', []]]
    : process.platform === 'win32'
      ? [['clip', []]]
      : [['xclip', ['-selection', 'clipboard']], ['xsel', ['--clipboard', '--input']], ['wl-copy', []]];
  for (const [cmd, args] of candidates) {
    const r = spawnSync(cmd, args, { input: text, stdio: ['pipe', 'ignore', 'ignore'] });
    if (!r.error && (r.status ?? 0) === 0) return true;
  }
  return false;
}

main().then((code) => process.exit(code)).catch((err) => {
  console.error(err.message || err);
  process.exit(1);
});