@davixlabs/h2i-mcp 0.0.0-stage → 1.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,10 @@
1
+ Davix H2I SDK License
2
+
3
+ Copyright (c) 2026 Davix Labs. All rights reserved.
4
+
5
+ You may install, copy and use this software, and include it unchanged or modified in your own applications, in order to
6
+ use the Davix H2I API with a Davix H2I account, under the Davix H2I terms of service (https://h2i.davixlabs.io/terms/).
7
+ You may not sell this software on its own, or use it to build or offer a service that competes with Davix H2I.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. TO THE EXTENT THE LAW ALLOWS,
10
+ DAVIX LABS IS NOT LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS USE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @davixlabs/h2i-mcp: the Davix H2I helper for AI agents
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lets an AI agent on your computer (Claude Code, Claude Desktop, Codex, OpenCode, Cursor, VS Code, Gemini CLI, and any other MCP app) work on your
4
+ **files and folders at full quality**. The agent never sees the bytes of your photos or documents: the helper reads each file from disk, sends it
5
+ to Davix H2I untouched, checks that the copy on the server is byte-identical (SHA-256), and saves the result next to the original.
6
+
7
+ It also works as a command line, and it has no dependencies. Needs Node.js 18 or newer and a Davix H2I plan that includes MCP.
8
+
9
+ ## Start here
10
+
11
+ ```bash
12
+ npx -y @davixlabs/h2i-mcp setup
13
+ ```
14
+
15
+ `setup` finds the AI apps on your computer, adds Davix H2I to their settings (the old file is saved as `*.bak-davix`; nothing else is changed; an
16
+ entry that is already there is updated, not doubled), and signs you in. A browser window opens on the Davix H2I website: check the name
17
+ (Davix H2I helper) and press **Allow access**. Then restart the app.
18
+
19
+ No browser on this machine (a server, SSH)? The sign-in prints a short code and an address: open the address on any device, enter the code, press Allow.
20
+
21
+ ```bash
22
+ npx -y @davixlabs/h2i-mcp setup --client codex # one app only: claude-code, claude-desktop, codex, opencode, cursor, vscode, gemini
23
+ npx -y @davixlabs/h2i-mcp setup --print # only show what would be written (paste it yourself)
24
+ npx -y @davixlabs/h2i-mcp login --no-browser # sign in with a code on another device
25
+ npx -y @davixlabs/h2i-mcp doctor # checks Node, the connection, the sign-in and each app's settings
26
+ ```
27
+
28
+ ## What the agent gets
29
+
30
+ The helper runs as a local MCP server. It shows the agent every Davix H2I tool (read live from the server, so the catalog is never out of date) and
31
+ four tools for files on your computer:
32
+
33
+ | Tool | What it does |
34
+ |---|---|
35
+ | `process_local_file` | Run an operation on one or more files (several for merging), save the result(s) next to the original or where you say |
36
+ | `process_folder` | The same operation on every matching file of a folder (optionally into another folder, optionally inside sub-folders) |
37
+ | `upload_local_file` | Send one file and get an `upload_id` (checked byte for byte) |
38
+ | `save_result_file` | Save a result link to a path |
39
+
40
+ Try: *"Use Davix H2I to resize every photo in my Pictures/Trip folder to 1600 px wide."* Results are named like `photo.davix.png`; an existing file
41
+ is never replaced unless you ask (`overwrite`).
42
+
43
+ ## Command line
44
+
45
+ ```bash
46
+ h2i ops resize # find an operation
47
+ h2i run images.resize photo.png --param width=1600 # run it on a file
48
+ h2i run pdfs.merge a.pdf b.pdf --out merged.pdf # several files in, one result
49
+ h2i folder images.optimize ./photos --out-dir ./small --recursive
50
+ ```
51
+
52
+ (`h2i` and `h2i-mcp` are the same program.)
53
+
54
+ ## Where things are kept
55
+
56
+ Your sign-in lives in `~/.davix-h2i/credentials.json`, readable only by you. It lasts about 90 days. `npx @davixlabs/h2i-mcp logout` ends it, on the
57
+ computer and on the server. For a script or server you can set `DAVIX_H2I_TOKEN` instead; `DAVIX_H2I_URL` points the helper at another Davix H2I address.
58
+
59
+ The Dashboard's **MCP** page lists every connected agent and lets you change its permissions or disconnect it at any time.
package/bin/h2i.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const { main } = require('../src/cli');
4
+ main(process.argv.slice(2)).then(code => { process.exitCode = code; });
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@davixlabs/h2i-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "description": "Davix H2I helper for AI agents (Claude, Codex, OpenCode, Cursor and more): a local MCP server that works with files on your computer at full quality, plus a command line. Sign in once through the Davix H2I website.",
5
+ "bin": {
6
+ "h2i-mcp": "bin/h2i.js",
7
+ "h2i": "bin/h2i.js"
8
+ },
9
+ "main": "src/index.js",
10
+ "license": "SEE LICENSE IN LICENSE",
11
+ "private": false,
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/Davixlabs/Davix-H2I-App.git",
15
+ "directory": "sdk/cli"
16
+ },
17
+ "publishConfig": {
18
+ "registry": "https://registry.npmjs.org",
19
+ "access": "public"
20
+ },
21
+ "engines": {
22
+ "node": ">=18"
23
+ },
24
+ "files": [
25
+ "LICENSE",
26
+ "bin",
27
+ "src",
28
+ "README.md"
29
+ ],
30
+ "keywords": [
31
+ "mcp",
32
+ "model-context-protocol",
33
+ "ai-agent",
34
+ "claude",
35
+ "codex",
36
+ "opencode",
37
+ "image",
38
+ "pdf",
39
+ "davix"
40
+ ],
41
+ "scripts": {
42
+ "test": "node --test test/*.test.js"
43
+ },
44
+ "dependencies": {},
45
+ "sideEffects": false
46
+ }
package/src/cli.js ADDED
@@ -0,0 +1,159 @@
1
+ 'use strict';
2
+ // The command line: `h2i-mcp` (or `h2i`). With no command it runs the local MCP server, which is what an AI app starts.
3
+ // setup [--client claude-code|claude-desktop|codex|opencode|cursor|vscode|gemini] [--all] [--yes] [--print]
4
+ // login [--no-browser] logout whoami doctor
5
+ // run <operation> <file...> [--param name=value] [--out path] [--out-dir folder] [--overwrite]
6
+ // folder <operation> <folder> [--ext jpg,png] [--recursive] [--out-dir folder] [--param name=value]
7
+ // ops [search] list the operations
8
+ const readline = require('readline');
9
+ const config = require('./config');
10
+ const setup = require('./setup');
11
+ const login = require('./login');
12
+ const proc = require('./process');
13
+ const remote = require('./remote');
14
+ const pkg = require('../package.json');
15
+
16
+ const out = line => process.stdout.write(`${line}\n`);
17
+ const err = line => process.stderr.write(`${line}\n`);
18
+
19
+ function parseArgs(argv) {
20
+ const flags = { _: [], param: [] };
21
+ for (let i = 0; i < argv.length; i += 1) {
22
+ const a = argv[i];
23
+ if (a.startsWith('--')) {
24
+ const [k, inline] = a.slice(2).split(/=(.*)/s);
25
+ const takesValue = ['client', 'out', 'out-dir', 'ext', 'param'].includes(k);
26
+ const value = takesValue ? (inline !== undefined ? inline : argv[++i]) : (inline !== undefined ? inline : true);
27
+ if (k === 'param') flags.param.push(value); else flags[k] = value;
28
+ } else if (a === '-y') flags.yes = true; else flags._.push(a);
29
+ }
30
+ return flags;
31
+ }
32
+
33
+ function paramsFrom(list) {
34
+ const params = {};
35
+ for (const item of list) {
36
+ const i = String(item).indexOf('=');
37
+ if (i < 1) throw new Error(`--param needs name=value, got "${item}".`);
38
+ const raw = item.slice(i + 1);
39
+ let value = raw;
40
+ if (raw === 'true' || raw === 'false') value = raw === 'true';
41
+ else if (raw !== '' && !Number.isNaN(Number(raw)) && /^-?\d+(\.\d+)?$/.test(raw)) value = Number(raw);
42
+ else if (/^[[{]/.test(raw)) { try { value = JSON.parse(raw); } catch (_) { /* keep the text */ } }
43
+ params[item.slice(0, i)] = value;
44
+ }
45
+ return params;
46
+ }
47
+
48
+ function ask(question) {
49
+ return new Promise(resolve => {
50
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
51
+ rl.question(question, answer => { rl.close(); resolve(answer.trim().toLowerCase()); });
52
+ });
53
+ }
54
+
55
+ async function cmdSetup(flags) {
56
+ const interactive = process.stdin.isTTY && !flags.yes;
57
+ let targets;
58
+ if (flags.client) {
59
+ const c = setup.byId(flags.client);
60
+ if (!c) { err(`Unknown app "${flags.client}". Choose one of: ${setup.CLIENTS.map(x => x.id).join(', ')}.`); return 2; }
61
+ targets = [c];
62
+ } else {
63
+ targets = setup.CLIENTS.filter(setup.detected);
64
+ if (!targets.length) {
65
+ err('I did not find a supported AI app on this computer. Pick one with --client, for example: npx @davixlabs/h2i-mcp setup --client claude-code');
66
+ err(`Supported: ${setup.CLIENTS.map(x => x.id).join(', ')}.`);
67
+ return 1;
68
+ }
69
+ err(`Found: ${targets.map(t => t.label).join(', ')}.`);
70
+ if (interactive && !flags.all) {
71
+ const answer = await ask(`Add Davix H2I to ${targets.length > 1 ? 'all of them' : targets[0].label}? [Y/n] `);
72
+ if (answer && !['y', 'yes'].includes(answer)) { err('Nothing was changed.'); return 0; }
73
+ }
74
+ }
75
+ if (flags.print) {
76
+ for (const c of targets) { out(`\n# ${c.label}\n${setup.snippet(c)}`); }
77
+ return 0;
78
+ }
79
+ let failures = 0;
80
+ const restart = [];
81
+ for (const c of targets) {
82
+ const r = setup.apply(c);
83
+ if (r.ok) {
84
+ err(`✓ ${c.label}: ${r.updated ? 'updated' : 'added'}${r.file ? ` (${r.file})` : ''}`);
85
+ restart.push(`${c.label}: ${c.restart}`);
86
+ } else {
87
+ failures += 1;
88
+ err(`✗ ${c.label}: ${r.reason}`);
89
+ err(' Paste this by hand instead:');
90
+ err(setup.snippet(c).split('\n').map(l => ` ${l}`).join('\n'));
91
+ }
92
+ }
93
+ if (!config.loadCredentials()) {
94
+ err('\nNow sign in to Davix H2I (a browser window opens; you approve it on the website):');
95
+ try { await login.login({ browser: !flags['no-browser'] }); } catch (e) { err(`Sign-in: ${e.message}\nYou can do it later with: npx ${setup.PACKAGE} login`); failures += 1; }
96
+ } else err('You are already signed in to Davix H2I.');
97
+ if (restart.length) { err('\nLast step:'); restart.forEach(l => err(` ${l}`)); }
98
+ err('\nThen ask your AI agent, for example: "Use Davix H2I to resize the photos in my Pictures folder to 1600 px wide."');
99
+ err('Check everything any time with: npx @davixlabs/h2i-mcp doctor');
100
+ return failures ? 1 : 0;
101
+ }
102
+
103
+ async function cmdWhoami() {
104
+ const creds = config.loadCredentials();
105
+ if (!creds) { err('Not signed in. Run: npx @davixlabs/h2i-mcp login'); return 1; }
106
+ out(`Server: ${config.serverUrl()}`);
107
+ out(`Sign-in: ${creds.source === 'environment' ? 'DAVIX_H2I_TOKEN' : config.credentialsFile()}`);
108
+ if (creds.expires_at) out(`Expires: ${creds.expires_at}${config.isExpired(creds) ? ' (expired: sign in again)' : ''}`);
109
+ return config.isExpired(creds) ? 1 : 0;
110
+ }
111
+
112
+ async function cmdOps(flags) {
113
+ const r = await remote.callData('list_operations', flags._[1] ? { query: flags._[1] } : {});
114
+ for (const op of r.operations || []) out(`${op.operation.padEnd(34)} ${op.name}`);
115
+ out(`\n${r.total || (r.operations || []).length} operations. Details: ask your AI agent, or run the operation with --param name=value.`);
116
+ return 0;
117
+ }
118
+
119
+ async function cmdRun(flags) {
120
+ const [, operation, ...inputs] = flags._;
121
+ if (!operation || !inputs.length) { err('Usage: h2i run <operation> <file...> [--param name=value] [--out path] [--out-dir folder] [--overwrite]'); return 2; }
122
+ const r = await proc.runOnFiles(operation, inputs, { parameters: paramsFrom(flags.param), outputPath: flags.out || null, outputDir: flags['out-dir'] || null, overwrite: Boolean(flags.overwrite), log: err });
123
+ if (!r.saved.length) { out(JSON.stringify(r.data, null, 2)); return 0; }
124
+ r.saved.forEach(s => out(s.path));
125
+ return 0;
126
+ }
127
+
128
+ async function cmdFolder(flags) {
129
+ const [, operation, folder] = flags._;
130
+ if (!operation || !folder) { err('Usage: h2i folder <operation> <folder> [--ext jpg,png] [--recursive] [--out-dir folder] [--param name=value]'); return 2; }
131
+ const r = await proc.runOnFolder(operation, folder, { parameters: paramsFrom(flags.param), outputFolder: flags['out-dir'] || null, extensions: flags.ext ? String(flags.ext).split(',') : null, recursive: Boolean(flags.recursive), overwrite: Boolean(flags.overwrite), log: err });
132
+ out(`${r.done.length} of ${r.total} done${r.failed.length ? `, ${r.failed.length} failed` : ''}.`);
133
+ r.failed.forEach(f => err(` failed: ${f.input}: ${f.error}`));
134
+ return r.failed.length ? 1 : 0;
135
+ }
136
+
137
+ async function main(argv) {
138
+ const flags = parseArgs(argv);
139
+ const command = flags._[0] || 'serve';
140
+ try {
141
+ if (command === 'serve' || command === 'mcp') { await require('./server').serve(); return 0; }
142
+ if (command === 'setup') return await cmdSetup(flags);
143
+ if (command === 'login') { await login.login({ browser: !flags['no-browser'] }); return 0; }
144
+ if (command === 'logout') { err(await login.logout() ? 'Signed out.' : 'You were not signed in.'); return 0; }
145
+ if (command === 'whoami') return await cmdWhoami();
146
+ if (command === 'doctor') return await require('./doctor').run({ say: out });
147
+ if (command === 'ops') return await cmdOps(flags);
148
+ if (command === 'run') return await cmdRun(flags);
149
+ if (command === 'folder') return await cmdFolder(flags);
150
+ if (command === 'version' || flags.version || flags.v) { out(pkg.version); return 0; }
151
+ out(`Davix H2I helper ${pkg.version}\n\nCommands:\n setup add Davix H2I to your AI apps and sign in\n login sign in (a browser opens; or use the code shown)\n logout sign out\n whoami show the sign-in\n doctor check that everything works\n ops list the operations\n run run an operation on files\n folder run an operation on a whole folder\n serve run the MCP server (this is what AI apps start)\n\nStart here: npx ${setup.PACKAGE} setup`);
152
+ return command === 'help' || flags.help ? 0 : 2;
153
+ } catch (e) {
154
+ err(e.message);
155
+ return 1;
156
+ }
157
+ }
158
+
159
+ module.exports = { main, parseArgs, paramsFrom };
package/src/config.js ADDED
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+ // Where things live: the server address, and the sign-in the helper keeps on this computer (one small file, readable only by you).
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+
7
+ const DEFAULT_SERVER = 'https://app.h2i.davixlabs.io';
8
+ const HELPER_CLIENT_ID = 'h2imcp_client_helper';
9
+
10
+ const serverUrl = () => String(process.env.DAVIX_H2I_URL || DEFAULT_SERVER).replace(/\/+$/, '');
11
+ const homeDir = () => process.env.DAVIX_H2I_HOME || path.join(os.homedir(), '.davix-h2i');
12
+ const credentialsFile = () => path.join(homeDir(), 'credentials.json');
13
+
14
+ /** What is saved, or null. A token in the DAVIX_H2I_TOKEN environment variable (for headless use) wins over the saved sign-in. */
15
+ function loadCredentials() {
16
+ if (process.env.DAVIX_H2I_TOKEN) {
17
+ return { server: serverUrl(), access_token: String(process.env.DAVIX_H2I_TOKEN).trim(), expires_at: null, source: 'environment' };
18
+ }
19
+ try {
20
+ const saved = JSON.parse(fs.readFileSync(credentialsFile(), 'utf8'));
21
+ if (saved && saved.access_token && saved.server === serverUrl()) return { ...saved, source: 'file' };
22
+ } catch (_) { /* nothing saved */ }
23
+ return null;
24
+ }
25
+
26
+ function saveCredentials(creds) {
27
+ fs.mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
28
+ fs.writeFileSync(credentialsFile(), JSON.stringify({ ...creds, server: serverUrl(), saved_at: new Date().toISOString() }, null, 2), { mode: 0o600 });
29
+ try { fs.chmodSync(credentialsFile(), 0o600); } catch (_) { /* Windows */ }
30
+ }
31
+
32
+ function clearCredentials() {
33
+ try { fs.unlinkSync(credentialsFile()); return true; } catch (_) { return false; }
34
+ }
35
+
36
+ const isExpired = creds => Boolean(creds && creds.expires_at && Date.parse(creds.expires_at) <= Date.now() + 60000);
37
+
38
+ module.exports = { DEFAULT_SERVER, HELPER_CLIENT_ID, serverUrl, homeDir, credentialsFile, loadCredentials, saveCredentials, clearCredentials, isExpired };
package/src/doctor.js ADDED
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+ // `doctor`: one command that checks the things that can go wrong and says what to do about each. Every check is independent, so one failure
3
+ // never hides the others.
4
+ const fs = require('fs');
5
+ const config = require('./config');
6
+ const setup = require('./setup');
7
+ const remote = require('./remote');
8
+
9
+ async function run({ say = line => process.stdout.write(`${line}\n`) } = {}) {
10
+ let problems = 0;
11
+ const ok = text => say(` ✓ ${text}`);
12
+ const bad = (text, fix) => { problems += 1; say(` ✗ ${text}`); if (fix) say(` → ${fix}`); };
13
+
14
+ say('Davix H2I helper check\n');
15
+ const major = Number(process.versions.node.split('.')[0]);
16
+ if (major >= 18) ok(`Node ${process.versions.node}`); else bad(`Node ${process.versions.node} is too old`, 'Install Node 18 or newer from https://nodejs.org');
17
+
18
+ try {
19
+ const res = await fetch(`${config.serverUrl()}/health`, { signal: AbortSignal.timeout(10000) });
20
+ if (res.ok) ok(`Davix H2I reachable (${config.serverUrl()})`); else bad(`Davix H2I answered HTTP ${res.status}`, 'Try again in a minute; check https://app.h2i.davixlabs.io for news.');
21
+ } catch (e) { bad(`Cannot reach ${config.serverUrl()} (${e.message})`, 'Check your internet connection, proxy or firewall.'); }
22
+
23
+ const creds = config.loadCredentials();
24
+ if (!creds) bad('Not signed in', 'Run: npx @davixlabs/h2i-mcp login');
25
+ else if (config.isExpired(creds)) bad('The sign-in has expired', 'Run: npx @davixlabs/h2i-mcp login');
26
+ else {
27
+ ok(`Signed in${creds.expires_at ? ` (valid until ${creds.expires_at.slice(0, 10)})` : ''}`);
28
+ try {
29
+ const tools = await remote.listTools();
30
+ ok(`The server answers and offers ${tools.length} tools`);
31
+ } catch (e) {
32
+ bad(`The server did not accept the sign-in: ${e.message}`, /plan|MCP/i.test(e.message) ? 'Your plan may not include MCP: see the MCP page in the Dashboard.' : 'Run: npx @davixlabs/h2i-mcp login');
33
+ }
34
+ }
35
+
36
+ const found = setup.CLIENTS.filter(setup.detected);
37
+ if (!found.length) say(' · No supported AI app found here (that is fine if you use a chat app with the hosted connector).');
38
+ for (const c of found) {
39
+ if (c.kind === 'command') { ok(`${c.label} found (check with: ${c.binary} mcp list)`); continue; }
40
+ const file = c.file();
41
+ let has = false;
42
+ try { has = fs.existsSync(file) && fs.readFileSync(file, 'utf8').includes(setup.NAME); } catch (_) { /* unreadable */ }
43
+ if (has) ok(`${c.label} is set up (${file})`); else bad(`${c.label} found, but Davix H2I is not added`, `Run: npx @davixlabs/h2i-mcp setup --client ${c.id}`);
44
+ }
45
+
46
+ say(problems ? `\n${problems} thing${problems === 1 ? '' : 's'} to fix (see the arrows above).` : '\nEverything looks good.');
47
+ return problems ? 1 : 0;
48
+ }
49
+
50
+ module.exports = { run };
package/src/files.js ADDED
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+ // Moving files between this computer and Davix H2I, byte for byte. A file is sent as it is (a streamed PUT, never read into the AI's
3
+ // conversation) and its SHA-256 is compared with the one the server reports, so "the original quality arrived" is checked, not assumed.
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const { Readable } = require('stream');
8
+ const remote = require('./remote');
9
+
10
+ function sha256File(file) {
11
+ return new Promise((resolve, reject) => {
12
+ const hash = crypto.createHash('sha256');
13
+ fs.createReadStream(file).on('data', c => hash.update(c)).on('end', () => resolve(hash.digest('hex'))).on('error', reject);
14
+ });
15
+ }
16
+
17
+ /** Sends one local file. Returns { upload_id, file_name, size_bytes, sha256 }. Throws when the copy on the server is not identical. */
18
+ async function uploadFile(file, { operation = null } = {}) {
19
+ const abs = path.resolve(file);
20
+ const stat = fs.statSync(abs);
21
+ if (!stat.isFile()) throw new Error(`${abs} is not a file.`);
22
+ const name = path.basename(abs);
23
+ const created = await remote.callData('create_upload', { file_name: name });
24
+ const body = Readable.toWeb(fs.createReadStream(abs));
25
+ const res = await fetch(created.upload_url, {
26
+ method: 'PUT',
27
+ headers: { 'content-type': 'application/octet-stream', 'x-file-name': encodeURIComponent(name), 'content-length': String(stat.size) },
28
+ body,
29
+ duplex: 'half',
30
+ });
31
+ const text = await res.text();
32
+ let info = null;
33
+ try { info = JSON.parse(text); } catch (_) { /* not JSON */ }
34
+ if (!res.ok) throw new Error(`The upload of ${name} failed: ${(info && info.error && info.error.message) || `HTTP ${res.status}`}`);
35
+ const local = await sha256File(abs);
36
+ if (info && info.sha256 && info.sha256 !== local) throw new Error(`${name} arrived changed (checksums differ). Nothing was processed; try again.`);
37
+ return { upload_id: info.upload_id || created.upload_id, file_name: name, size_bytes: stat.size, sha256: local };
38
+ }
39
+
40
+ /** Saves a result link to a path (folders are created). Refuses to replace an existing file unless overwrite is true. */
41
+ async function downloadTo(url, target, { overwrite = false } = {}) {
42
+ const abs = path.resolve(target);
43
+ if (!overwrite && fs.existsSync(abs)) throw new Error(`${abs} already exists. Choose another name or allow overwriting.`);
44
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
45
+ const res = await fetch(url);
46
+ if (!res.ok) throw new Error(`The result could not be downloaded (HTTP ${res.status}).`);
47
+ const tmp = `${abs}.part`;
48
+ await new Promise((resolve, reject) => {
49
+ const out = fs.createWriteStream(tmp);
50
+ Readable.fromWeb(res.body).pipe(out).on('finish', resolve).on('error', reject);
51
+ });
52
+ fs.renameSync(tmp, abs);
53
+ return { path: abs, size_bytes: fs.statSync(abs).size };
54
+ }
55
+
56
+ /** Every signed result link inside a tool answer, with the file name beside it when there is one. */
57
+ function findResultFiles(value, found = [], depth = 0) {
58
+ if (depth > 8 || value === null || value === undefined) return found;
59
+ if (Array.isArray(value)) { value.forEach(v => findResultFiles(v, found, depth + 1)); return found; }
60
+ if (typeof value === 'object') {
61
+ const url = ['url', 'download_url'].map(k => value[k]).find(u => typeof u === 'string' && /^https?:\/\//.test(u) && /[?&]sig=/.test(u));
62
+ if (url) found.push({ url, name: value.filename || value.file_name || value.name || null });
63
+ else Object.values(value).forEach(v => findResultFiles(v, found, depth + 1));
64
+ }
65
+ return found;
66
+ }
67
+
68
+ module.exports = { uploadFile, downloadTo, findResultFiles, sha256File };
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+ // Use the helper from your own code: const h2i = require('@davixlabs/h2i-mcp');
3
+ module.exports = { ...require('./process'), ...require('./files'), config: require('./config'), login: require('./login').login, remote: require('./remote') };
package/src/login.js ADDED
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+ // Signing in. The helper never sees a password: it asks Davix H2I for a short code, shows it, and the person approves it on the Davix H2I
3
+ // website (any device). If a browser can be opened here, it is opened for them; if not, they are told the address and the code to type.
4
+ // Messages go to stderr: stdout belongs to the MCP protocol when the helper runs as a server.
5
+ const { spawn } = require('child_process');
6
+ const config = require('./config');
7
+
8
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
9
+
10
+ function openCommand(url) {
11
+ if (process.platform === 'win32') return ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]];
12
+ if (process.platform === 'darwin') return ['open', [url]];
13
+ return ['xdg-open', [url]];
14
+ }
15
+
16
+ /** Tries to open the address in the default browser. Resolves true when a browser was started (not a promise that it worked). */
17
+ function openBrowser(url) {
18
+ if (process.env.DAVIX_H2I_NO_BROWSER === '1') return Promise.resolve(false);
19
+ if (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return Promise.resolve(false); // no screen: a remote shell
20
+ return new Promise(resolve => {
21
+ try {
22
+ const [cmd, args] = openCommand(url);
23
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: process.platform === 'win32' });
24
+ child.on('error', () => resolve(false));
25
+ child.on('spawn', () => { child.unref(); resolve(true); });
26
+ } catch (_) { resolve(false); }
27
+ });
28
+ }
29
+
30
+ async function post(path, body) {
31
+ const res = await fetch(`${config.serverUrl()}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
32
+ let data = null;
33
+ try { data = await res.json(); } catch (_) { /* not JSON */ }
34
+ return { status: res.status, data: data || {} };
35
+ }
36
+
37
+ /**
38
+ * The whole sign-in. `say` prints a line for the person. Resolves with the saved credentials.
39
+ * Options: browser (default true), timeoutSeconds (default: the code's own life).
40
+ */
41
+ async function login({ say = line => process.stderr.write(`${line}\n`), browser = true, sleepFn = sleep, openFn = openBrowser } = {}) {
42
+ const started = await post('/oauth/device_authorization', { client_id: config.HELPER_CLIENT_ID });
43
+ if (started.status !== 200 || !started.data.device_code) {
44
+ const message = (started.data && (started.data.error_description || started.data.message)) || `HTTP ${started.status}`;
45
+ throw new Error(`Could not start the sign-in: ${message}`);
46
+ }
47
+ const d = started.data;
48
+ const opened = browser ? await openFn(d.verification_uri_complete) : false;
49
+ say('');
50
+ say(opened ? 'A browser window should have opened for you to approve this sign-in.' : 'Open this address in any browser (on this computer or your phone):');
51
+ say(` ${d.verification_uri_complete}`);
52
+ say('');
53
+ say(`If the page asks for a code, it is: ${d.user_code}`);
54
+ say(`(or go to ${d.verification_uri} and type that code)`);
55
+ say('');
56
+ say('Waiting for you to approve it…');
57
+
58
+ const deadline = Date.now() + (Number(d.expires_in) || 600) * 1000;
59
+ let interval = Math.max(2, Number(d.interval) || 5) * 1000;
60
+ while (Date.now() < deadline) {
61
+ await sleepFn(interval);
62
+ const polled = await post('/oauth/token', { grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code: d.device_code, client_id: config.HELPER_CLIENT_ID });
63
+ if (polled.status === 200 && polled.data.access_token) {
64
+ const creds = {
65
+ access_token: polled.data.access_token,
66
+ expires_at: polled.data.expires_in ? new Date(Date.now() + Number(polled.data.expires_in) * 1000).toISOString() : null,
67
+ scope: polled.data.scope || '',
68
+ };
69
+ config.saveCredentials(creds);
70
+ say('You are signed in to Davix H2I.');
71
+ return creds;
72
+ }
73
+ const code = polled.data.error;
74
+ if (code === 'authorization_pending') continue;
75
+ if (code === 'slow_down') { interval += 5000; continue; }
76
+ if (code === 'access_denied') throw new Error('The sign-in was cancelled.');
77
+ if (code === 'expired_token') throw new Error('The code expired before it was approved. Run the sign-in again.');
78
+ throw new Error(`The sign-in failed: ${polled.data.error_description || code || `HTTP ${polled.status}`}`);
79
+ }
80
+ throw new Error('The code expired before it was approved. Run the sign-in again.');
81
+ }
82
+
83
+ async function logout() {
84
+ const creds = config.loadCredentials();
85
+ if (creds && creds.source === 'file') {
86
+ // best effort: end the connection on the server too, so the token stops working everywhere
87
+ await fetch(`${config.serverUrl()}/oauth/revoke`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ token: creds.access_token }) }).catch(() => {});
88
+ }
89
+ return config.clearCredentials();
90
+ }
91
+
92
+ module.exports = { login, logout, openBrowser, openCommand };
package/src/process.js ADDED
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+ // Running an operation on files that live on this computer: send them untouched, run the operation, wait for the job, save the results next to
3
+ // the originals (or where you say). Used by the MCP tools below and by the `h2i run` command, so both behave the same.
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const remote = require('./remote');
7
+ const files = require('./files');
8
+
9
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
10
+
11
+ const KIND_EXTENSIONS = {
12
+ images: ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif', 'tif', 'tiff', 'bmp', 'heic', 'heif'],
13
+ pdfs: ['pdf'],
14
+ documents: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', 'rtf', 'txt', 'md', 'html'],
15
+ data: ['csv', 'json', 'xml', 'yaml', 'yml', 'xlsx', 'tsv'],
16
+ };
17
+
18
+ /** The files a folder run takes when you do not say: what the operation's family usually works on. */
19
+ function defaultExtensions(operation) {
20
+ return KIND_EXTENSIONS[String(operation || '').split('.')[0]] || null;
21
+ }
22
+
23
+ /** Waits for a background job and returns the finished answer's data. */
24
+ async function finishJob(data, { timeoutSeconds = 600, log = () => {} } = {}) {
25
+ let current = data;
26
+ const deadline = Date.now() + timeoutSeconds * 1000;
27
+ while ((current.status === 'queued' || current.status === 'running') && current.job_id) {
28
+ if (Date.now() > deadline) throw new Error(`The job (${current.job_id}) is still running after ${timeoutSeconds} seconds. Check it later with the job id.`);
29
+ await sleep(2500);
30
+ const answer = await remote.callData('get_job', { id: Number(current.job_id) });
31
+ const job = answer.job || {};
32
+ log(`job ${current.job_id}: ${job.status}${job.progress_percent != null ? ` ${job.progress_percent}%` : ''}`);
33
+ current = { job_id: current.job_id, status: job.status, ...(job.result || {}), ...answer };
34
+ if (job.status === 'failed') throw new Error(job.error_message || 'The job failed.');
35
+ if (job.status === 'cancelled') throw new Error('The job was cancelled.');
36
+ if (job.status === 'completed') return { ...answer, ...(job.result || {}), status: 'completed' };
37
+ }
38
+ return current;
39
+ }
40
+
41
+ function outputName(input, resultName, index, count) {
42
+ const parsed = path.parse(input);
43
+ const ext = resultName ? path.extname(resultName) : parsed.ext;
44
+ const base = `${parsed.name}.davix${count > 1 ? `-${index + 1}` : ''}`;
45
+ return `${base}${ext || parsed.ext}`;
46
+ }
47
+
48
+ /**
49
+ * Runs `operation` on one or more local files (several files in one request, for operations like merging) and saves the results.
50
+ * Returns { saved: [{ path, size_bytes }], uploaded: [...], data }.
51
+ */
52
+ async function runOnFiles(operation, inputs, { parameters = {}, outputDir = null, outputPath = null, overwrite = false, log = () => {} } = {}) {
53
+ const list = Array.isArray(inputs) ? inputs : [inputs];
54
+ const uploaded = [];
55
+ for (const input of list) {
56
+ log(`sending ${path.basename(input)}…`);
57
+ uploaded.push(await files.uploadFile(input));
58
+ }
59
+ log(`running ${operation}…`);
60
+ let data = await remote.callData('run_operation', { operation, parameters, inputs: uploaded.map(u => ({ upload_id: u.upload_id })), wait_seconds: 30 });
61
+ data = await finishJob(data, { log });
62
+ const results = files.findResultFiles(data);
63
+ if (!results.length) return { saved: [], uploaded, data };
64
+ const first = path.resolve(list[0]);
65
+ const dir = outputDir ? path.resolve(outputDir) : path.dirname(first);
66
+ const saved = [];
67
+ for (let i = 0; i < results.length; i += 1) {
68
+ const target = outputPath && results.length === 1 ? path.resolve(outputPath) : path.join(dir, outputName(first, results[i].name, i, results.length));
69
+ log(`saving ${path.basename(target)}…`);
70
+ saved.push(await files.downloadTo(results[i].url, target, { overwrite }));
71
+ }
72
+ return { saved, uploaded, data };
73
+ }
74
+
75
+ /** The same operation on every matching file of a folder, one request per file, results into outputFolder (default: next to each file). */
76
+ async function runOnFolder(operation, folder, { parameters = {}, outputFolder = null, extensions = null, recursive = false, overwrite = false, log = () => {} } = {}) {
77
+ const root = path.resolve(folder);
78
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) throw new Error(`${root} is not a folder.`);
79
+ const wanted = (extensions && extensions.length ? extensions : defaultExtensions(operation) || []).map(e => String(e).replace(/^\./, '').toLowerCase());
80
+ const outDir = outputFolder ? path.resolve(outputFolder) : null;
81
+ const found = [];
82
+ const walk = dir => {
83
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
84
+ const full = path.join(dir, entry.name);
85
+ if (outDir && path.resolve(full).startsWith(outDir + path.sep)) continue;
86
+ if (entry.isDirectory()) { if (recursive) walk(full); continue; }
87
+ if (/\.davix(-\d+)?\./i.test(entry.name)) continue; // a result of an earlier run
88
+ if (!wanted.length || wanted.includes(path.extname(entry.name).slice(1).toLowerCase())) found.push(full);
89
+ }
90
+ };
91
+ walk(root);
92
+ const report = { operation, folder: root, total: found.length, done: [], failed: [] };
93
+ for (const file of found) {
94
+ try {
95
+ const target = outDir ? path.join(outDir, path.relative(root, path.dirname(file))) : null;
96
+ const r = await runOnFiles(operation, [file], { parameters, outputDir: target, overwrite, log });
97
+ report.done.push({ input: file, saved: r.saved.map(s => s.path) });
98
+ } catch (err) {
99
+ report.failed.push({ input: file, error: err.message });
100
+ if (err.code === 'not_signed_in' || /permission|plan|quota/i.test(err.message)) break; // the same thing will fail for every file
101
+ }
102
+ }
103
+ return report;
104
+ }
105
+
106
+ module.exports = { runOnFiles, runOnFolder, finishJob, defaultExtensions, outputName };
package/src/remote.js ADDED
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+ // Talks to the Davix H2I MCP server over HTTPS (stateless JSON-RPC, a bearer token). Nothing here touches your files.
3
+ const config = require('./config');
4
+
5
+ class AuthError extends Error {
6
+ constructor(message) { super(message); this.name = 'AuthError'; this.code = 'not_signed_in'; }
7
+ }
8
+
9
+ const SIGN_IN_HINT = 'Sign in first: run `npx @davixlabs/h2i-mcp login` and approve it in the browser.';
10
+
11
+ function token() {
12
+ const creds = config.loadCredentials();
13
+ if (!creds) throw new AuthError(`You are not signed in to Davix H2I. ${SIGN_IN_HINT}`);
14
+ if (config.isExpired(creds)) throw new AuthError(`Your Davix H2I sign-in has expired. ${SIGN_IN_HINT}`);
15
+ return creds.access_token;
16
+ }
17
+
18
+ /** The answer of the server may be plain JSON or a one-message event stream; both carry one JSON-RPC message. */
19
+ function parseBody(text) {
20
+ const trimmed = String(text || '').trim();
21
+ if (!trimmed) return null;
22
+ if (trimmed[0] === '{') return JSON.parse(trimmed);
23
+ const lines = trimmed.split(/\r?\n/).filter(l => l.startsWith('data:'));
24
+ for (const line of lines.reverse()) {
25
+ const body = line.slice(5).trim();
26
+ if (body && body[0] === '{') return JSON.parse(body);
27
+ }
28
+ return null;
29
+ }
30
+
31
+ let nextId = 1;
32
+ async function rpc(method, params, { signal } = {}) {
33
+ const res = await fetch(`${config.serverUrl()}/mcp`, {
34
+ method: 'POST',
35
+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${token()}`, 'user-agent': 'davix-h2i-helper' },
36
+ body: JSON.stringify({ jsonrpc: '2.0', id: nextId++, method, params: params || {} }),
37
+ signal,
38
+ });
39
+ if (res.status === 401) throw new AuthError(`Davix H2I did not accept your sign-in. ${SIGN_IN_HINT}`);
40
+ if (res.status === 403) {
41
+ const body = await res.text().catch(() => '');
42
+ throw new Error(`Davix H2I refused this request (${body.slice(0, 200) || 'forbidden'}). Check that your plan includes MCP.`);
43
+ }
44
+ if (!res.ok) throw new Error(`Davix H2I answered HTTP ${res.status}.`);
45
+ const message = parseBody(await res.text());
46
+ if (!message) throw new Error('Davix H2I sent an empty answer.');
47
+ if (message.error) throw new Error(message.error.message || 'The server reported an error.');
48
+ return message.result;
49
+ }
50
+
51
+ let toolCache = null;
52
+ async function listTools() {
53
+ if (toolCache && Date.now() - toolCache.at < 5 * 60 * 1000) return toolCache.tools;
54
+ const result = await rpc('tools/list', {});
55
+ toolCache = { at: Date.now(), tools: result.tools || [] };
56
+ return toolCache.tools;
57
+ }
58
+
59
+ /** Calls a server tool. Returns the MCP result ({ content, structuredContent, isError }). */
60
+ async function callTool(name, args) {
61
+ return rpc('tools/call', { name, arguments: args || {} });
62
+ }
63
+
64
+ /** The structured data of a tool result, or throws with the server's own message when the tool failed. */
65
+ async function callData(name, args) {
66
+ const r = await callTool(name, args);
67
+ if (r.isError) {
68
+ const err = (r.structuredContent && r.structuredContent.error) || {};
69
+ const e = new Error(err.message || (r.content && r.content[0] && r.content[0].text) || `${name} failed.`);
70
+ e.code = err.code; e.hint = err.hint;
71
+ throw e;
72
+ }
73
+ return r.structuredContent || {};
74
+ }
75
+
76
+ module.exports = { AuthError, rpc, listTools, callTool, callData, token, SIGN_IN_HINT };
package/src/server.js ADDED
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+ // The local MCP server (stdio). An AI agent starts it; it shows the agent every Davix H2I tool (read live from the server, so the catalog is never
3
+ // out of date) plus a few that work with files on THIS computer: they read the file straight from disk and write the results straight back, so the
4
+ // AI only ever sees names and results, never the picture's bytes. That is what keeps the original quality.
5
+ //
6
+ // Protocol: newline-delimited JSON-RPC 2.0 on stdin/stdout. Everything meant for a person goes to stderr.
7
+ const remote = require('./remote');
8
+ const proc = require('./process');
9
+ const files = require('./files');
10
+ const pkg = require('../package.json');
11
+
12
+ const PROTOCOL = '2025-06-18';
13
+
14
+ const LOCAL_TOOLS = [
15
+ {
16
+ name: 'process_local_file',
17
+ title: 'Run an operation on a file on this computer',
18
+ description: 'Takes a file (or several, for operations like merging) from this computer, sends it to Davix H2I untouched, runs the operation and saves the result(s) on this computer. Nothing passes through the chat, so quality is never reduced. Use list_operations / describe_operation for the operation name and its parameters. By default the result is saved next to the original, named like photo.davix.png.',
19
+ inputSchema: {
20
+ type: 'object',
21
+ properties: {
22
+ operation: { type: 'string', description: 'The operation, for example images.resize or pdfs.merge.' },
23
+ paths: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Full path(s) of the input file(s) on this computer. Several files for operations that combine them (pdfs.merge).' },
24
+ parameters: { type: 'object', description: 'The operation\'s parameters, as described by describe_operation.' },
25
+ output_path: { type: 'string', description: 'Optional: where to save the (single) result. Default: next to the original.' },
26
+ output_folder: { type: 'string', description: 'Optional: a folder to save the results in.' },
27
+ overwrite: { type: 'boolean', description: 'Replace an existing file with the same name. Default false.' },
28
+ },
29
+ required: ['operation', 'paths'],
30
+ },
31
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
32
+ async run(a) {
33
+ const r = await proc.runOnFiles(a.operation, a.paths, { parameters: a.parameters || {}, outputDir: a.output_folder || null, outputPath: a.output_path || null, overwrite: Boolean(a.overwrite), log: line => process.stderr.write(`${line}\n`) });
34
+ return { text: r.saved.length ? `Saved ${r.saved.length} file${r.saved.length === 1 ? '' : 's'}:\n${r.saved.map(s => `- ${s.path} (${s.size_bytes} bytes)`).join('\n')}` : 'The operation finished but produced no file to save. See the data below.', data: { saved: r.saved, result: r.data } };
35
+ },
36
+ },
37
+ {
38
+ name: 'process_folder',
39
+ title: 'Run an operation on every file of a folder',
40
+ description: 'Runs one operation on each matching file in a folder on this computer (one request per file) and saves the results next to them, or in output_folder. For example: resize every photo in a folder, or optimize every PDF. Files made by an earlier run (named like photo.davix.png) are skipped.',
41
+ inputSchema: {
42
+ type: 'object',
43
+ properties: {
44
+ operation: { type: 'string', description: 'The operation, for example images.optimize.' },
45
+ folder: { type: 'string', description: 'Full path of the folder.' },
46
+ parameters: { type: 'object', description: 'The operation\'s parameters.' },
47
+ output_folder: { type: 'string', description: 'Optional: save results here (the sub-folder layout is kept). Default: next to each file.' },
48
+ extensions: { type: 'array', items: { type: 'string' }, description: 'File types to take, for example ["jpg","png"]. Default: what the operation usually works on.' },
49
+ recursive: { type: 'boolean', description: 'Also look inside sub-folders. Default false.' },
50
+ overwrite: { type: 'boolean', description: 'Replace existing result files. Default false.' },
51
+ },
52
+ required: ['operation', 'folder'],
53
+ },
54
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
55
+ async run(a) {
56
+ const r = await proc.runOnFolder(a.operation, a.folder, { parameters: a.parameters || {}, outputFolder: a.output_folder || null, extensions: a.extensions || null, recursive: Boolean(a.recursive), overwrite: Boolean(a.overwrite), log: line => process.stderr.write(`${line}\n`) });
57
+ return { text: `${r.done.length} of ${r.total} file${r.total === 1 ? '' : 's'} done${r.failed.length ? `, ${r.failed.length} failed` : ''}.${r.failed.length ? `\nFailed:\n${r.failed.slice(0, 10).map(f => `- ${f.input}: ${f.error}`).join('\n')}` : ''}`, data: r };
58
+ },
59
+ },
60
+ {
61
+ name: 'upload_local_file',
62
+ title: 'Send a file from this computer to Davix H2I',
63
+ description: 'Sends one file from this computer to Davix H2I untouched and returns an upload_id to use as an input of run_operation. It checks that the copy on the server is byte-identical. Use process_local_file instead when you simply want an operation done and the result saved.',
64
+ inputSchema: { type: 'object', properties: { path: { type: 'string', description: 'Full path of the file.' } }, required: ['path'] },
65
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
66
+ async run(a) {
67
+ const u = await files.uploadFile(a.path);
68
+ return { text: `Uploaded ${u.file_name} (${u.size_bytes} bytes), identical to the original.`, data: u };
69
+ },
70
+ },
71
+ {
72
+ name: 'save_result_file',
73
+ title: 'Save a result link as a file on this computer',
74
+ description: 'Downloads a result link (from an operation) and saves it at a path on this computer. Refuses to replace an existing file unless overwrite is true.',
75
+ inputSchema: { type: 'object', properties: { url: { type: 'string' }, path: { type: 'string', description: 'Where to save it.' }, overwrite: { type: 'boolean' } }, required: ['url', 'path'] },
76
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
77
+ async run(a) {
78
+ const saved = await files.downloadTo(a.url, a.path, { overwrite: Boolean(a.overwrite) });
79
+ return { text: `Saved ${saved.path} (${saved.size_bytes} bytes).`, data: saved };
80
+ },
81
+ },
82
+ ];
83
+ const localByName = new Map(LOCAL_TOOLS.map(t => [t.name, t]));
84
+
85
+ // The server's own file-handoff tools would confuse an agent that has the local ones: it never needs the upload links here.
86
+ const HIDDEN_REMOTE = new Set(['upload_small_file', 'import_attached_file']);
87
+
88
+ async function toolList() {
89
+ let remoteTools = [];
90
+ try { remoteTools = (await remote.listTools()).filter(t => !HIDDEN_REMOTE.has(t.name)); } catch (err) {
91
+ // not signed in (yet): still answer, so the agent can tell the person what to do instead of the whole server failing to start
92
+ process.stderr.write(`${err.message}\n`);
93
+ }
94
+ return [...LOCAL_TOOLS.map(({ run, ...tool }) => tool), ...remoteTools];
95
+ }
96
+
97
+ async function callTool(name, args) {
98
+ const local = localByName.get(name);
99
+ try {
100
+ if (!local) return await remote.callTool(name, args);
101
+ const out = await local.run(args || {});
102
+ return { content: [{ type: 'text', text: `${out.text}\n\n${JSON.stringify(out.data, null, 2).slice(0, 20000)}` }], structuredContent: out.data };
103
+ } catch (err) {
104
+ const hint = err.hint ? `\nWhat to do: ${err.hint}` : '';
105
+ return { isError: true, content: [{ type: 'text', text: `${err.message}${hint}` }], structuredContent: { error: { code: err.code || 'helper_error', message: err.message } } };
106
+ }
107
+ }
108
+
109
+ async function handle(message) {
110
+ const { id, method, params } = message;
111
+ if (method === 'initialize') {
112
+ return { protocolVersion: (params && params.protocolVersion) || PROTOCOL, capabilities: { tools: {} }, serverInfo: { name: 'davix-h2i', title: 'Davix H2I', version: pkg.version }, instructions: 'Davix H2I processes images, PDFs, documents and data. For files on this computer use process_local_file or process_folder: they read and write the files directly, so quality is never reduced. Start with list_operations.' };
113
+ }
114
+ if (method === 'ping') return {};
115
+ if (method === 'tools/list') return { tools: await toolList() };
116
+ if (method === 'tools/call') return callTool(params && params.name, params && params.arguments);
117
+ if (id === undefined) return undefined; // a notification we do not need
118
+ const err = new Error(`Method not found: ${method}`); err.rpcCode = -32601; throw err;
119
+ }
120
+
121
+ function serve({ input = process.stdin, output = process.stdout } = {}) {
122
+ let buffer = '';
123
+ const send = obj => output.write(`${JSON.stringify(obj)}\n`);
124
+ input.setEncoding('utf8');
125
+ input.on('data', chunk => {
126
+ buffer += chunk;
127
+ let i;
128
+ while ((i = buffer.indexOf('\n')) >= 0) {
129
+ const line = buffer.slice(0, i).trim();
130
+ buffer = buffer.slice(i + 1);
131
+ if (!line) continue;
132
+ let message;
133
+ try { message = JSON.parse(line); } catch (_) { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); continue; }
134
+ Promise.resolve(handle(message)).then(result => {
135
+ if (message.id !== undefined && result !== undefined) send({ jsonrpc: '2.0', id: message.id, result });
136
+ }).catch(err => {
137
+ if (message.id !== undefined) send({ jsonrpc: '2.0', id: message.id, error: { code: err.rpcCode || -32603, message: err.message } });
138
+ });
139
+ }
140
+ });
141
+ return new Promise(resolve => input.on('end', resolve));
142
+ }
143
+
144
+ module.exports = { serve, handle, toolList, LOCAL_TOOLS };
package/src/setup.js ADDED
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+ // `setup`: adds Davix H2I to the AI apps found on this computer, by editing each app's own settings file. The old file is saved next to it first, an
3
+ // existing entry is updated rather than doubled, and nothing else in the file is touched. If a file cannot be read safely (comments, odd
4
+ // format) it is left alone and the exact lines to paste are shown instead: the manual way always works.
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const { spawnSync } = require('child_process');
9
+
10
+ const NAME = 'davix-h2i';
11
+ const PACKAGE = '@davixlabs/h2i-mcp';
12
+ const WIN = process.platform === 'win32';
13
+ const home = () => process.env.DAVIX_H2I_FAKE_HOME || os.homedir();
14
+ const appData = () => process.env.APPDATA || path.join(home(), 'AppData', 'Roaming');
15
+
16
+ /** The command an app runs to start the helper. On Windows `npx` is a script, so it goes through cmd. */
17
+ function launch() {
18
+ return WIN ? { command: 'cmd', args: ['/c', 'npx', '-y', PACKAGE] } : { command: 'npx', args: ['-y', PACKAGE] };
19
+ }
20
+
21
+ const onPath = cmd => { try { return spawnSync(WIN ? 'where' : 'which', [cmd], { stdio: 'ignore' }).status === 0; } catch (_) { return false; } };
22
+
23
+ const CLIENTS = [
24
+ {
25
+ id: 'claude-desktop', label: 'Claude Desktop', kind: 'json',
26
+ file: () => (WIN ? path.join(appData(), 'Claude', 'claude_desktop_config.json') : process.platform === 'darwin' ? path.join(home(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json') : path.join(home(), '.config', 'Claude', 'claude_desktop_config.json')),
27
+ key: 'mcpServers', entry: () => { const l = launch(); return { command: l.command, args: l.args }; },
28
+ restart: 'Quit Claude Desktop completely and open it again.',
29
+ },
30
+ {
31
+ id: 'claude-code', label: 'Claude Code', kind: 'command', binary: 'claude',
32
+ run: () => { const l = launch(); return ['claude', ['mcp', 'add', '--scope', 'user', NAME, '--', l.command, ...l.args]]; },
33
+ restart: 'Start a new Claude Code session (or run /mcp to reconnect).',
34
+ },
35
+ {
36
+ id: 'codex', label: 'Codex', kind: 'toml', binary: 'codex',
37
+ file: () => path.join(process.env.CODEX_HOME || path.join(home(), '.codex'), 'config.toml'),
38
+ restart: 'Start a new Codex session.',
39
+ },
40
+ {
41
+ id: 'opencode', label: 'OpenCode', kind: 'json', binary: 'opencode',
42
+ file: () => path.join(process.env.XDG_CONFIG_HOME || path.join(home(), '.config'), 'opencode', 'opencode.json'),
43
+ key: 'mcp', entry: () => { const l = launch(); return { type: 'local', command: [l.command, ...l.args], enabled: true }; },
44
+ restart: 'Restart OpenCode.',
45
+ },
46
+ {
47
+ id: 'cursor', label: 'Cursor', kind: 'json',
48
+ file: () => path.join(home(), '.cursor', 'mcp.json'),
49
+ key: 'mcpServers', entry: () => { const l = launch(); return { command: l.command, args: l.args }; },
50
+ restart: 'Restart Cursor.',
51
+ },
52
+ {
53
+ id: 'vscode', label: 'VS Code', kind: 'json',
54
+ file: () => (WIN ? path.join(appData(), 'Code', 'User', 'mcp.json') : process.platform === 'darwin' ? path.join(home(), 'Library', 'Application Support', 'Code', 'User', 'mcp.json') : path.join(home(), '.config', 'Code', 'User', 'mcp.json')),
55
+ key: 'servers', entry: () => { const l = launch(); return { type: 'stdio', command: l.command, args: l.args }; },
56
+ restart: 'Reload the VS Code window.',
57
+ },
58
+ {
59
+ id: 'gemini', label: 'Gemini CLI', kind: 'json', binary: 'gemini',
60
+ file: () => path.join(home(), '.gemini', 'settings.json'),
61
+ key: 'mcpServers', entry: () => { const l = launch(); return { command: l.command, args: l.args }; },
62
+ restart: 'Start a new Gemini CLI session.',
63
+ },
64
+ ];
65
+ const byId = id => CLIENTS.find(c => c.id === id) || null;
66
+
67
+ /** Is this app on the computer? The settings folder is there, or its command is on the PATH. */
68
+ function detected(client) {
69
+ if (client.kind === 'command') return onPath(client.binary);
70
+ const file = client.file();
71
+ return fs.existsSync(file) || fs.existsSync(path.dirname(file)) || Boolean(client.binary && onPath(client.binary));
72
+ }
73
+
74
+ /** The exact text to paste by hand (the sure way). */
75
+ function snippet(client) {
76
+ const l = launch();
77
+ if (client.kind === 'command') { const [cmd, args] = client.run(); return `${cmd} ${args.join(' ')}`; }
78
+ if (client.kind === 'toml') return `[mcp_servers.${NAME}]\ncommand = "${l.command}"\nargs = ${JSON.stringify(l.args)}\n`;
79
+ return JSON.stringify({ [client.key]: { [NAME]: client.entry() } }, null, 2);
80
+ }
81
+
82
+ const backup = file => { if (fs.existsSync(file)) fs.copyFileSync(file, `${file}.bak-davix`); };
83
+
84
+ function writeJson(client) {
85
+ const file = client.file();
86
+ let data = {};
87
+ if (fs.existsSync(file)) {
88
+ const text = fs.readFileSync(file, 'utf8');
89
+ try { data = text.trim() ? JSON.parse(text) : {}; } catch (_) { return { ok: false, reason: 'The file has comments or a format that cannot be edited safely.' }; }
90
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) return { ok: false, reason: 'The file is not a settings object.' };
91
+ }
92
+ const section = data[client.key] && typeof data[client.key] === 'object' ? data[client.key] : {};
93
+ const existed = Boolean(section[NAME]);
94
+ data[client.key] = { ...section, [NAME]: client.entry() };
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ backup(file);
97
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`);
98
+ return { ok: true, file, updated: existed };
99
+ }
100
+
101
+ function writeToml(client) {
102
+ const file = client.file();
103
+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
104
+ const block = snippet(client);
105
+ const header = `[mcp_servers.${NAME}]`;
106
+ let next;
107
+ let updated = false;
108
+ if (text.includes(header)) {
109
+ // replace our own block only: from its header to the next table header
110
+ next = text.replace(new RegExp(`\\[mcp_servers\\.${NAME}\\][\\s\\S]*?(?=\\n\\[|$)`), block.trimEnd());
111
+ updated = true;
112
+ } else {
113
+ next = `${text}${text && !text.endsWith('\n') ? '\n' : ''}${text ? '\n' : ''}${block}`;
114
+ }
115
+ fs.mkdirSync(path.dirname(file), { recursive: true });
116
+ backup(file);
117
+ fs.writeFileSync(file, next.endsWith('\n') ? next : `${next}\n`);
118
+ return { ok: true, file, updated };
119
+ }
120
+
121
+ function runCommand(client) {
122
+ const [cmd, args] = client.run();
123
+ const res = spawnSync(cmd, args, { encoding: 'utf8', shell: WIN });
124
+ if (res.status === 0) return { ok: true, file: null, updated: false };
125
+ const out = `${res.stdout || ''}${res.stderr || ''}`;
126
+ if (/already exists/i.test(out)) return { ok: true, file: null, updated: true };
127
+ return { ok: false, reason: out.trim().split('\n').slice(-2).join(' ') || `${cmd} exited with ${res.status}` };
128
+ }
129
+
130
+ /** Adds Davix H2I to one app. Returns { ok, file?, updated?, reason? }. */
131
+ function apply(client) {
132
+ try {
133
+ if (client.kind === 'json') return writeJson(client);
134
+ if (client.kind === 'toml') return writeToml(client);
135
+ return runCommand(client);
136
+ } catch (err) { return { ok: false, reason: err.message }; }
137
+ }
138
+
139
+ module.exports = { NAME, PACKAGE, CLIENTS, byId, detected, snippet, apply, launch, writeJson, writeToml };