local-mcp-bridge-server 0.0.0-stage → 0.8.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 +21 -0
- package/README.md +115 -2
- package/dist/cli.js +1027 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 somebodil
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
1
|
+
# local-mcp-bridge-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The local MCP server for [Gemini MCP Bridge](https://github.com/somebodil/gemini-mcp-bridge), the Chrome extension that lets Gemini on the web ([gemini.google.com](https://gemini.google.com)) use the tools of your computer. Until 0.6.0 this server was called `gemini-mcp-bridge-server`: see [From gemini-mcp-bridge-server](#from-gemini-mcp-bridge-server).
|
|
4
|
+
|
|
5
|
+
The extension runs in Chrome and cannot touch your computer by itself. This server is the part that can: it runs commands, reads and writes files, and passes calls through to the other MCP servers you list. The extension reaches it at `http://127.0.0.1:7341/mcp`, or at the address of the computer the server runs on.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx local-mcp-bridge-server
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Node.js 20 or later. The first start creates the config file with a random token, then prints what to enter in the extension's options:
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
local-mcp-bridge-server 0.8.0
|
|
15
|
+
URL: http://127.0.0.1:7341/mcp
|
|
16
|
+
Token: 3q2-...
|
|
17
|
+
Config: /home/you/.config/local-mcp-bridge-server/config.json (new)
|
|
18
|
+
Perf: /home/you/.config/local-mcp-bridge-server/perf.log (when the extension's performance log is on)
|
|
19
|
+
Tools: run_command, read_file, list_directory
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Leave the window open while you use the extension. Every request shows up there as it comes (see *Log* below).
|
|
23
|
+
|
|
24
|
+
## From gemini-mcp-bridge-server
|
|
25
|
+
|
|
26
|
+
Until 0.6.0 this server was called `gemini-mcp-bridge-server`. Without `--config`, the first start (or `token`) copies the old config file (`~/.config/gemini-mcp-bridge-server/config.json`, on Windows `%APPDATA%\gemini-mcp-bridge-server\config.json`) to the new place, with its token, port and servers: the URL and the token in the extension stay as they are.
|
|
27
|
+
|
|
28
|
+
A service that an earlier version installed (`install-service`, until 0.7.0) starts that version at every login and holds the port. Remove it once:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npx local-mcp-bridge-server@0.7.0 uninstall-service # removes the service of either name
|
|
32
|
+
npm uninstall -g gemini-mcp-bridge-server # if you had installed it
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Tools
|
|
36
|
+
|
|
37
|
+
| Tool | What it does |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `run_command` | Runs a command line with `bash -c` (`cmd.exe` on Windows; `$SHELL` only when there is no bash), with a time limit (60 s by default, at most 600 s). Returns the exit code, stdout and stderr. Gemini is told to write bash syntax only. It writes files with it too: a here-document (`cat > FILE <<'GMB_EOF'` ... `GMB_EOF`) writes each line as it is, and code in another language goes into a file this way and runs in the same command, one round instead of two. A command line over 100 KB runs from a temporary script file (Linux takes at most 128 KiB in one argument). |
|
|
40
|
+
| `read_file` | Reads a text file, whole or some of its lines. |
|
|
41
|
+
| `list_directory` | Lists a folder (at most 1000 entries); links show as what they point to. |
|
|
42
|
+
| `write_file` | Only where `run_command` cannot write a file: without bash (`cmd.exe` on Windows) and with `--no-shell`. Writes a text file, or adds to its end. Missing folders are created. |
|
|
43
|
+
|
|
44
|
+
Paths may be absolute, start with `~`, or be relative to your home folder. The server also tells Gemini, in its MCP instructions, your operating system, your home folder and your shell, so that Gemini writes paths and commands that work.
|
|
45
|
+
|
|
46
|
+
## Options
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
local-mcp-bridge-server [--port <n>] [--config <file>] [--no-shell] [--no-files] [--new-token]
|
|
50
|
+
local-mcp-bridge-server token | perf-log
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`token` shows the URL and the token again, `perf-log` the extension's performance log (below).
|
|
54
|
+
|
|
55
|
+
The config file is `~/.config/local-mcp-bridge-server/config.json` (on Windows `%APPDATA%\local-mcp-bridge-server\config.json`). Only your user can read it.
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"port": 7341,
|
|
60
|
+
"token": "…",
|
|
61
|
+
"tools": { "shell": true, "files": true },
|
|
62
|
+
"mcpServers": {
|
|
63
|
+
"playwright": { "command": "npx", "args": ["@playwright/mcp@latest"] },
|
|
64
|
+
"other": { "url": "http://127.0.0.1:9000/mcp", "headers": { "Authorization": "Bearer …" } }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The server writes this file only on the first start and with a new token; keys it does not know stay in it. A wrong value (a port that is not a number, a server without `command` or `url`) stops the start with a message that names it.
|
|
70
|
+
|
|
71
|
+
`mcpServers` has the shape other MCP clients use, so an existing list can be copied in: stdio servers (`command`, `args`, `env`, `cwd`) and Streamable HTTP servers (`url`, `headers`). Their tools appear with the server's name in front, as `playwright__browser_navigate`. `"disabled": true` leaves one out. A server that stops is started again at its next call (after a short wait that grows while it keeps failing).
|
|
72
|
+
|
|
73
|
+
## Log
|
|
74
|
+
|
|
75
|
+
While it runs, the server writes to stdout each request as it comes, each step of the work, and the reply as it goes out, all under the number of the request. Something going wrong is a `WARN` or `ERROR` line at once: a tool that failed (with why), wrong arguments, a body that is not JSON (HTTP 400), any reply with an error status (with what it said), a refused request, a file tool still running after 5 seconds, a call the extension gave up on, a reply that had nowhere to go.
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
14:33:50.923 INFO #1 ← tools/call run_command {"command":"mkdir -p /tmp/job && cat > /tmp/job/main.py <<'GMB_EOF' && python3 /tmp/job/main.py\nprint(\"hello\")\nGMB_EOF"} · 215 bytes from 127.0.0.1
|
|
79
|
+
14:33:50.929 INFO #1 running with /bin/bash in /home/you, time limit 60 s: mkdir -p /tmp/job && cat > /tmp/job/main.py <<'GMB_EOF' && python3 /tmp/job/main.py print("hello") GMB_EOF
|
|
80
|
+
14:33:50.930 INFO #1 started: process 49314
|
|
81
|
+
14:33:51.084 INFO #1 run_command done (155 ms): 33 characters: exit code: 0 --- stdout --- hello
|
|
82
|
+
14:33:51.086 INFO #1 → HTTP 200, 108 bytes, 164 ms
|
|
83
|
+
14:33:51.090 INFO #2 ← tools/call read_file {} · 91 bytes from 127.0.0.1
|
|
84
|
+
14:33:51.090 ERROR #2 read_file failed (0 ms): "path" must be a string; it was nothing.
|
|
85
|
+
14:33:52.143 ERROR #8 the connection closed after 1011 ms, before the reply was sent: the extension gave up or went away
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A string argument over 200 characters (the content of a file) shows as its start and its length; a result, as its length and its start.
|
|
89
|
+
|
|
90
|
+
## Performance log
|
|
91
|
+
|
|
92
|
+
When the extension's *Performance log* option is on (off by default; it is for finding out why a page is slow), the extension sends its lines to this server every ten seconds, and the server appends them to `perf.log` next to the config file. `local-mcp-bridge-server perf-log` shows the file. Past 1 MB it becomes `perf.log.1` and a new one begins. Only your user can read it.
|
|
93
|
+
|
|
94
|
+
The lines say which clicks, keys and frames took long on the page and how much of that time was the extension's own work, and every minute how much time the extension took. They carry names and numbers only, no text of the page. The same lines are on the extension's options page, with **Copy**.
|
|
95
|
+
|
|
96
|
+
## Safety
|
|
97
|
+
|
|
98
|
+
- The server listens on every address of the computer, not on `127.0.0.1` alone: a browser elsewhere reaches it too (on the host of a virtual machine through a forwarded port, through an SSH tunnel, on another computer of your network). It does not look at where a request comes from. It refuses a request unless both hold:
|
|
99
|
+
- It carries the token: `Authorization: Bearer <token>`.
|
|
100
|
+
- It has no `Origin`, or a `chrome-extension://` one. Web pages always send their own `Origin`.
|
|
101
|
+
- Whoever has the token can run commands as you. Keep it like a password. `--new-token` replaces it.
|
|
102
|
+
- The token is the only lock, and it travels unencrypted. On a network you do not trust (a café, a shared office), close the port to other computers with the firewall of your system, or send it through an SSH tunnel.
|
|
103
|
+
- The extension asks before each call by default. What Gemini writes can come from a web page or a document it read ("prompt injection"): keep `run_command` (and `write_file`, where it is there) on *Ask* in the extension unless you watch closely. `--no-shell` and `--no-files` turn the tools off on this side.
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
npm install
|
|
109
|
+
npm run check # types, lint, tests (tools, HTTP checks, pass-through servers, config, command line)
|
|
110
|
+
npm run smoke # build, then run dist/cli.js as users do: --version, token, start, tools/list
|
|
111
|
+
npm start # build and run dist/cli.js
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { resolve as resolve2 } from "node:path";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
|
|
7
|
+
// src/builtin.ts
|
|
8
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
9
|
+
import { accessSync, constants } from "node:fs";
|
|
10
|
+
import { appendFile, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
11
|
+
import { arch, homedir, platform, release, tmpdir } from "node:os";
|
|
12
|
+
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
13
|
+
|
|
14
|
+
// src/log.ts
|
|
15
|
+
var silent = { info: () => void 0, warn: () => void 0, error: () => void 0 };
|
|
16
|
+
function stamp(d = /* @__PURE__ */ new Date()) {
|
|
17
|
+
const p = (n, w = 2) => String(n).padStart(w, "0");
|
|
18
|
+
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}.${p(d.getMilliseconds(), 3)}`;
|
|
19
|
+
}
|
|
20
|
+
function consoleLogger(write = (t) => void process.stdout.write(t)) {
|
|
21
|
+
const at = (level) => (line) => write(`${stamp()} ${level} ${line}
|
|
22
|
+
`);
|
|
23
|
+
return { info: at("INFO "), warn: at("WARN "), error: at("ERROR") };
|
|
24
|
+
}
|
|
25
|
+
function tagged(log, tag) {
|
|
26
|
+
return { info: (l) => log.info(`${tag} ${l}`), warn: (l) => log.warn(`${tag} ${l}`), error: (l) => log.error(`${tag} ${l}`) };
|
|
27
|
+
}
|
|
28
|
+
function short(v) {
|
|
29
|
+
const s = JSON.stringify(v, (_k, x) => typeof x === "string" && x.length > 200 ? `${x.slice(0, 120)}\u2026(${x.length} chars)` : x) ?? String(v);
|
|
30
|
+
return s.length > 400 ? `${s.slice(0, 397)}...` : s;
|
|
31
|
+
}
|
|
32
|
+
function oneLine(s, max = 300) {
|
|
33
|
+
const t = s.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, " ").replace(/\s+/g, " ").trim();
|
|
34
|
+
return t.length > max ? `${t.slice(0, max - 3)}...` : t;
|
|
35
|
+
}
|
|
36
|
+
var message = (e) => e instanceof Error ? e.message : String(e);
|
|
37
|
+
|
|
38
|
+
// src/builtin.ts
|
|
39
|
+
var OUTPUT_LIMIT = 2e5;
|
|
40
|
+
var READ_LIMIT = 4 * 1024 * 1024;
|
|
41
|
+
var LIST_LIMIT = 1e3;
|
|
42
|
+
var ARG_BYTES = 1e5;
|
|
43
|
+
var WIN = process.platform === "win32";
|
|
44
|
+
var END_WORD = "GMB_EOF";
|
|
45
|
+
function findBash() {
|
|
46
|
+
const dirs = [...(process.env.PATH ?? "").split(delimiter), "/bin", "/usr/bin", "/usr/local/bin", "/opt/homebrew/bin"];
|
|
47
|
+
for (const dir of dirs) {
|
|
48
|
+
if (!dir) continue;
|
|
49
|
+
const path = join(dir, "bash");
|
|
50
|
+
try {
|
|
51
|
+
accessSync(path, constants.X_OK);
|
|
52
|
+
return path;
|
|
53
|
+
} catch {
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return void 0;
|
|
57
|
+
}
|
|
58
|
+
var SHELL = WIN ? process.env.ComSpec || "cmd.exe" : findBash() ?? (process.env.SHELL || "/bin/sh");
|
|
59
|
+
var RUNS_BASH = !WIN && /(^|\/)bash$/.test(SHELL);
|
|
60
|
+
function bashVersion() {
|
|
61
|
+
try {
|
|
62
|
+
const [major, minor] = execFileSync(SHELL, ["-c", 'echo "${BASH_VERSINFO[0]} ${BASH_VERSINFO[1]}"'], { encoding: "utf8", timeout: 5e3 }).trim().split(" ").map(Number);
|
|
63
|
+
return [major || 0, minor || 0];
|
|
64
|
+
} catch {
|
|
65
|
+
return [0, 0];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
var writes = (tools) => tools.files && !(tools.shell && RUNS_BASH);
|
|
69
|
+
function systemNote(tools) {
|
|
70
|
+
const os = { darwin: "macOS", win32: "Windows", linux: "Linux" }[platform()] ?? platform();
|
|
71
|
+
const lines = [`Computer: ${os} ${release()} (${arch()}).`, `Home folder: ${homedir()}.`];
|
|
72
|
+
if (tools.files || tools.shell) lines[1] += " Relative paths in the tools start there; ~ works too.";
|
|
73
|
+
if (tools.shell && RUNS_BASH) {
|
|
74
|
+
const [major, minor] = bashVersion();
|
|
75
|
+
lines.push(
|
|
76
|
+
`run_command runs its "command" with ${SHELL} -c${major ? ` (bash ${major}.${minor})` : ""}, so "command" must be bash syntax only: a command line as typed in a bash terminal. Never run Python or the code of any other language as bash commands.`,
|
|
77
|
+
`run_command also writes files: a here-document whose end word is in single quotes writes each line as it is ($, backticks, backslashes and quotes too) until a line that is only the end word; cat >> adds to the end of a file. Code in another language goes into a file this way, and runs in the same command, for example:`,
|
|
78
|
+
`mkdir -p /tmp/job && cat > /tmp/job/main.py <<'${END_WORD}' && python3 /tmp/job/main.py`,
|
|
79
|
+
'print("hello")',
|
|
80
|
+
END_WORD
|
|
81
|
+
);
|
|
82
|
+
if (major && major < 4) lines.push("This bash is older than 4: ${var^^} and ${var,,}, associative arrays (declare -A), mapfile, |& and ** do not work in it.");
|
|
83
|
+
} else if (tools.shell) lines.push(`run_command uses ${SHELL}.`);
|
|
84
|
+
return lines.join("\n");
|
|
85
|
+
}
|
|
86
|
+
function builtinTools(tools) {
|
|
87
|
+
const list = [];
|
|
88
|
+
if (tools.shell)
|
|
89
|
+
list.push({
|
|
90
|
+
name: "run_command",
|
|
91
|
+
description: RUNS_BASH ? `Run a bash command line on the user's computer (${SHELL} -c) and return its exit code and output. Bash syntax only: code of another language goes into a file with a here-document (cat > FILE <<'${END_WORD}'), which can run in the same command.` : `Run a command in the shell of the user's computer (${SHELL}) and return its exit code and output.`,
|
|
92
|
+
inputSchema: {
|
|
93
|
+
type: "object",
|
|
94
|
+
properties: {
|
|
95
|
+
command: { type: "string", description: RUNS_BASH ? "The command line, in bash syntax only." : "The command line." },
|
|
96
|
+
cwd: { type: "string", description: "Folder to run in. Default: the home folder." },
|
|
97
|
+
timeout_seconds: { type: "number", description: "Stop the command after this long. Default 60, at most 600." }
|
|
98
|
+
},
|
|
99
|
+
required: ["command"]
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
if (tools.files)
|
|
103
|
+
list.push({
|
|
104
|
+
name: "read_file",
|
|
105
|
+
description: "Read a text file.",
|
|
106
|
+
inputSchema: {
|
|
107
|
+
type: "object",
|
|
108
|
+
properties: {
|
|
109
|
+
path: { type: "string" },
|
|
110
|
+
offset: { type: "integer", description: "First line to read, from 1." },
|
|
111
|
+
limit: { type: "integer", description: "Number of lines to read." }
|
|
112
|
+
},
|
|
113
|
+
required: ["path"]
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
if (writes(tools))
|
|
117
|
+
list.push({
|
|
118
|
+
name: "write_file",
|
|
119
|
+
description: "Write a text file, replacing it, or add to its end. Missing folders are created.",
|
|
120
|
+
inputSchema: {
|
|
121
|
+
type: "object",
|
|
122
|
+
properties: {
|
|
123
|
+
path: { type: "string" },
|
|
124
|
+
content: { type: "string" },
|
|
125
|
+
append: { type: "boolean", description: "Add to the end instead of replacing." }
|
|
126
|
+
},
|
|
127
|
+
required: ["path", "content"]
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
if (tools.files)
|
|
131
|
+
list.push({
|
|
132
|
+
name: "list_directory",
|
|
133
|
+
description: "List the files and folders in a folder.",
|
|
134
|
+
inputSchema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] }
|
|
135
|
+
});
|
|
136
|
+
return list;
|
|
137
|
+
}
|
|
138
|
+
function resolvePath(p) {
|
|
139
|
+
const s = p.trim();
|
|
140
|
+
if (s === "~") return homedir();
|
|
141
|
+
if (s.startsWith("~/") || s.startsWith("~\\")) return join(homedir(), s.slice(2));
|
|
142
|
+
return isAbsolute(s) ? s : resolve(homedir(), s);
|
|
143
|
+
}
|
|
144
|
+
var text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...isError ? { isError: true } : {} });
|
|
145
|
+
function kind(v) {
|
|
146
|
+
if (v === void 0) return "nothing";
|
|
147
|
+
if (v === null) return "null";
|
|
148
|
+
if (Array.isArray(v)) return "an array";
|
|
149
|
+
return typeof v === "object" ? "an object" : `a ${typeof v}`;
|
|
150
|
+
}
|
|
151
|
+
function required(args, key) {
|
|
152
|
+
const v = args[key];
|
|
153
|
+
if (typeof v !== "string") throw new Error(`"${key}" must be a string; it was ${kind(v)}.`);
|
|
154
|
+
return v;
|
|
155
|
+
}
|
|
156
|
+
function optional(args, key) {
|
|
157
|
+
return args[key] === void 0 ? void 0 : required(args, key);
|
|
158
|
+
}
|
|
159
|
+
function int(v) {
|
|
160
|
+
const n = typeof v === "string" && v.trim() ? Number(v) : v;
|
|
161
|
+
return typeof n === "number" && Number.isFinite(n) ? Math.floor(n) : void 0;
|
|
162
|
+
}
|
|
163
|
+
async function callBuiltin(name, args, signal, log = silent) {
|
|
164
|
+
try {
|
|
165
|
+
switch (name) {
|
|
166
|
+
case "run_command":
|
|
167
|
+
return await runCommand(required(args, "command"), optional(args, "cwd"), int(args.timeout_seconds) ?? 60, signal, log);
|
|
168
|
+
case "read_file": {
|
|
169
|
+
const path = resolvePath(required(args, "path"));
|
|
170
|
+
const offset = int(args.offset);
|
|
171
|
+
const limit = int(args.limit);
|
|
172
|
+
log.info(`reading ${path}${offset !== void 0 || limit !== void 0 ? ` (offset ${offset ?? 1}, limit ${limit ?? "none"})` : ""}`);
|
|
173
|
+
return await readText(path, offset, limit);
|
|
174
|
+
}
|
|
175
|
+
case "write_file": {
|
|
176
|
+
const path = resolvePath(required(args, "path"));
|
|
177
|
+
const content = required(args, "content");
|
|
178
|
+
const bytes = Buffer.byteLength(content);
|
|
179
|
+
log.info(`creating the folders of ${path} if missing`);
|
|
180
|
+
await mkdir(dirname(path), { recursive: true });
|
|
181
|
+
log.info(`${args.append === true ? "appending" : "writing"} ${bytes} bytes to ${path}`);
|
|
182
|
+
await (args.append === true ? appendFile : writeFile)(path, content);
|
|
183
|
+
return text(`${args.append === true ? "Added" : "Wrote"} ${bytes} bytes to ${path}.`);
|
|
184
|
+
}
|
|
185
|
+
case "list_directory": {
|
|
186
|
+
const path = resolvePath(required(args, "path"));
|
|
187
|
+
log.info(`listing ${path}`);
|
|
188
|
+
return await listDirectory(path);
|
|
189
|
+
}
|
|
190
|
+
default:
|
|
191
|
+
return text(`Unknown tool: ${name}`, true);
|
|
192
|
+
}
|
|
193
|
+
} catch (e) {
|
|
194
|
+
return text(e instanceof Error ? e.message : String(e), true);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async function readText(path, offset, limit) {
|
|
198
|
+
const info = await stat(path);
|
|
199
|
+
if (info.isDirectory()) return text(`${path} is a folder; use list_directory.`, true);
|
|
200
|
+
if (!info.isFile()) return text(`${path} is not a regular file.`, true);
|
|
201
|
+
if (info.size > READ_LIMIT) return text(`${path} has ${info.size} bytes; files over ${READ_LIMIT} bytes are not read. Use run_command (head, tail, grep).`, true);
|
|
202
|
+
const buf = await readFile(path);
|
|
203
|
+
if (buf.subarray(0, 8192).includes(0)) return text(`${path} is a binary file (${info.size} bytes).`, true);
|
|
204
|
+
const content = buf.toString("utf8");
|
|
205
|
+
if (offset === void 0 && limit === void 0) return text(content);
|
|
206
|
+
const lines = content.endsWith("\n") ? content.slice(0, -1).split("\n") : content.split("\n");
|
|
207
|
+
if (limit !== void 0 && limit < 1) return text('"limit" must be 1 or more.', true);
|
|
208
|
+
const from2 = Math.max(1, offset ?? 1);
|
|
209
|
+
if (from2 > lines.length) return text(`${path} has ${lines.length} lines; there is no line ${from2}.`, true);
|
|
210
|
+
const to = limit === void 0 ? lines.length : Math.min(lines.length, from2 + limit - 1);
|
|
211
|
+
return text(`[lines ${from2}-${to} of ${lines.length}]
|
|
212
|
+
${lines.slice(from2 - 1, to).join("\n")}`);
|
|
213
|
+
}
|
|
214
|
+
async function listDirectory(path) {
|
|
215
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
216
|
+
const shown = entries.slice(0, LIST_LIMIT);
|
|
217
|
+
const infos = await Promise.all(shown.map((e) => e.isDirectory() ? Promise.resolve(void 0) : stat(join(path, e.name)).catch(() => null)));
|
|
218
|
+
const rows = shown.map((e, i) => {
|
|
219
|
+
const info = infos[i];
|
|
220
|
+
const link = e.isSymbolicLink() ? " (link)" : "";
|
|
221
|
+
if (e.isDirectory() || info?.isDirectory()) return { dir: true, line: `[DIR] ${e.name}/${link}` };
|
|
222
|
+
if (info === null) return { dir: false, line: `[LINK] ${e.name} (broken)` };
|
|
223
|
+
return { dir: false, line: `[FILE] ${e.name} (${info?.size ?? 0} bytes)${link}` };
|
|
224
|
+
});
|
|
225
|
+
rows.sort((a, b) => Number(b.dir) - Number(a.dir) || a.line.localeCompare(b.line));
|
|
226
|
+
const lines = rows.map((r) => r.line);
|
|
227
|
+
if (entries.length > LIST_LIMIT) lines.push(`... and ${entries.length - LIST_LIMIT} more`);
|
|
228
|
+
return text(lines.length ? `${path}
|
|
229
|
+
${lines.join("\n")}` : `${path} is empty.`);
|
|
230
|
+
}
|
|
231
|
+
var running = /* @__PURE__ */ new Set();
|
|
232
|
+
function killTree(child) {
|
|
233
|
+
if (!child.pid) return;
|
|
234
|
+
try {
|
|
235
|
+
if (WIN) spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true }).on("error", () => void 0);
|
|
236
|
+
else process.kill(-child.pid, "SIGKILL");
|
|
237
|
+
} catch {
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function stopAllCommands() {
|
|
241
|
+
for (const child of running) killTree(child);
|
|
242
|
+
running.clear();
|
|
243
|
+
}
|
|
244
|
+
async function runCommand(command, cwd, timeoutSec, signal, log) {
|
|
245
|
+
const dir = cwd ? resolvePath(cwd) : homedir();
|
|
246
|
+
if (cwd && !(await stat(dir).catch(() => null))?.isDirectory()) return text(`The folder ${dir} does not exist.`, true);
|
|
247
|
+
if (signal?.aborted) return text("Cancelled before it started.", true);
|
|
248
|
+
const limitMs = Math.min(600, Math.max(1, timeoutSec)) * 1e3;
|
|
249
|
+
log.info(`running with ${SHELL} in ${dir}, time limit ${limitMs / 1e3} s: ${oneLine(command, 200)}`);
|
|
250
|
+
const bytes = Buffer.byteLength(command);
|
|
251
|
+
const script = !WIN && bytes > ARG_BYTES ? join(await mkdtemp(join(tmpdir(), "gmb-command-")), "command.sh") : void 0;
|
|
252
|
+
if (script) {
|
|
253
|
+
log.info(`the command line has ${bytes} bytes, more than one argument may hold: it runs from ${script}`);
|
|
254
|
+
await writeFile(script, command, { mode: 384 });
|
|
255
|
+
}
|
|
256
|
+
return new Promise((done) => {
|
|
257
|
+
const child = spawn(SHELL, WIN ? ["/d", "/s", "/c", `"${command}"`] : script ? [script] : ["-c", command], {
|
|
258
|
+
cwd: dir,
|
|
259
|
+
detached: !WIN,
|
|
260
|
+
windowsHide: true,
|
|
261
|
+
windowsVerbatimArguments: WIN,
|
|
262
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
263
|
+
});
|
|
264
|
+
running.add(child);
|
|
265
|
+
if (child.pid) log.info(`started: process ${child.pid}`);
|
|
266
|
+
let out = "";
|
|
267
|
+
let err = "";
|
|
268
|
+
let total = 0;
|
|
269
|
+
let stopped = "";
|
|
270
|
+
let finished = false;
|
|
271
|
+
child.stdout.setEncoding("utf8");
|
|
272
|
+
child.stderr.setEncoding("utf8");
|
|
273
|
+
const take = (cur, chunk) => {
|
|
274
|
+
total += chunk.length;
|
|
275
|
+
return cur.length < OUTPUT_LIMIT ? cur + chunk : cur;
|
|
276
|
+
};
|
|
277
|
+
child.stdout.on("data", (c) => out = take(out, c));
|
|
278
|
+
child.stderr.on("data", (c) => err = take(err, c));
|
|
279
|
+
const finish = (result) => {
|
|
280
|
+
if (finished) return;
|
|
281
|
+
finished = true;
|
|
282
|
+
clearTimeout(timer);
|
|
283
|
+
signal?.removeEventListener("abort", onAbort);
|
|
284
|
+
running.delete(child);
|
|
285
|
+
child.stdout.destroy();
|
|
286
|
+
child.stderr.destroy();
|
|
287
|
+
if (script) void rm(dirname(script), { recursive: true, force: true }).catch((e) => log.warn(`could not delete ${script}: ${message(e)}`));
|
|
288
|
+
done(result);
|
|
289
|
+
};
|
|
290
|
+
const report = (code, sig) => {
|
|
291
|
+
const cut = (s) => s.length > OUTPUT_LIMIT ? `${s.slice(0, OUTPUT_LIMIT)}
|
|
292
|
+
...[output cut at ${OUTPUT_LIMIT} of ${total} characters]` : s;
|
|
293
|
+
const head = stopped === "time" ? `Stopped after ${limitMs / 1e3} s (time limit).` : stopped === "cancel" ? "Stopped: the call was cancelled." : `exit code: ${code ?? sig}`;
|
|
294
|
+
const parts = [head];
|
|
295
|
+
if (out) parts.push(`--- stdout ---
|
|
296
|
+
${cut(out).replace(/\n$/, "")}`);
|
|
297
|
+
if (err) parts.push(`--- stderr ---
|
|
298
|
+
${cut(err).replace(/\n$/, "")}`);
|
|
299
|
+
if (!out && !err) parts.push("(no output)");
|
|
300
|
+
finish(text(parts.join("\n"), stopped !== ""));
|
|
301
|
+
};
|
|
302
|
+
const stop = (why) => {
|
|
303
|
+
stopped = why;
|
|
304
|
+
log.warn(`${why === "time" ? `time limit of ${limitMs / 1e3} s reached` : "cancelled"}: stopping process ${child.pid ?? "?"} and the processes it started`);
|
|
305
|
+
killTree(child);
|
|
306
|
+
setTimeout(() => {
|
|
307
|
+
if (!finished) log.warn("its output was still open 1 s after the stop (a process that left its group): answering without the rest");
|
|
308
|
+
report(null, "SIGKILL");
|
|
309
|
+
}, 1e3);
|
|
310
|
+
};
|
|
311
|
+
const timer = setTimeout(() => stop("time"), limitMs);
|
|
312
|
+
const onAbort = () => stop("cancel");
|
|
313
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
314
|
+
child.on("error", (e) => finish(text(`Could not start ${SHELL}: ${e.message}`, true)));
|
|
315
|
+
child.on(
|
|
316
|
+
"exit",
|
|
317
|
+
(code, sig) => setTimeout(() => {
|
|
318
|
+
if (!finished) log.info(`the shell exited (${code ?? sig}) but a process it started still holds its output: answering now`);
|
|
319
|
+
report(code, sig);
|
|
320
|
+
}, 200)
|
|
321
|
+
);
|
|
322
|
+
child.on("close", report);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// src/config.ts
|
|
327
|
+
import { randomBytes } from "node:crypto";
|
|
328
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
329
|
+
import { homedir as homedir2 } from "node:os";
|
|
330
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
331
|
+
|
|
332
|
+
// package.json
|
|
333
|
+
var package_default = {
|
|
334
|
+
name: "local-mcp-bridge-server",
|
|
335
|
+
version: "0.8.0",
|
|
336
|
+
description: "Local MCP server for the Gemini MCP Bridge Chrome extension: your computer's shell and files, plus the MCP servers you list",
|
|
337
|
+
type: "module",
|
|
338
|
+
license: "MIT",
|
|
339
|
+
repository: {
|
|
340
|
+
type: "git",
|
|
341
|
+
url: "git+https://github.com/somebodil/local-mcp-bridge-server.git"
|
|
342
|
+
},
|
|
343
|
+
homepage: "https://github.com/somebodil/local-mcp-bridge-server#readme",
|
|
344
|
+
bugs: {
|
|
345
|
+
url: "https://github.com/somebodil/local-mcp-bridge-server/issues"
|
|
346
|
+
},
|
|
347
|
+
bin: {
|
|
348
|
+
"local-mcp-bridge-server": "dist/cli.js"
|
|
349
|
+
},
|
|
350
|
+
files: [
|
|
351
|
+
"dist"
|
|
352
|
+
],
|
|
353
|
+
engines: {
|
|
354
|
+
node: ">=20"
|
|
355
|
+
},
|
|
356
|
+
keywords: [
|
|
357
|
+
"mcp",
|
|
358
|
+
"model-context-protocol",
|
|
359
|
+
"mcp-server",
|
|
360
|
+
"gemini",
|
|
361
|
+
"chrome-extension"
|
|
362
|
+
],
|
|
363
|
+
scripts: {
|
|
364
|
+
build: "tsc --noEmit && node scripts/build.mjs",
|
|
365
|
+
typecheck: "tsc --noEmit",
|
|
366
|
+
lint: "eslint .",
|
|
367
|
+
test: 'node --test "src/**/*.test.ts"',
|
|
368
|
+
check: "npm run typecheck && npm run lint && npm test",
|
|
369
|
+
start: "node scripts/build.mjs && node dist/cli.js",
|
|
370
|
+
smoke: "node scripts/build.mjs && node scripts/smoke.mjs",
|
|
371
|
+
prepack: "node scripts/build.mjs"
|
|
372
|
+
},
|
|
373
|
+
dependencies: {
|
|
374
|
+
"@modelcontextprotocol/sdk": "1.32.2"
|
|
375
|
+
},
|
|
376
|
+
devDependencies: {
|
|
377
|
+
"@types/node": "26.6.6",
|
|
378
|
+
esbuild: "0.28.2",
|
|
379
|
+
eslint: "9.39.5",
|
|
380
|
+
typescript: "6.0.3",
|
|
381
|
+
"typescript-eslint": "8.73.0",
|
|
382
|
+
zod: "4.6.7"
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
// src/name.ts
|
|
387
|
+
var NAME = package_default.name;
|
|
388
|
+
var FORMER_NAME = "gemini-mcp-bridge-server";
|
|
389
|
+
|
|
390
|
+
// src/config.ts
|
|
391
|
+
var DEFAULT_PORT = 7341;
|
|
392
|
+
function defaultConfigPath(name = NAME) {
|
|
393
|
+
if (process.platform === "win32") return join2(process.env.APPDATA ?? join2(homedir2(), "AppData", "Roaming"), name, "config.json");
|
|
394
|
+
return join2(process.env.XDG_CONFIG_HOME || join2(homedir2(), ".config"), name, "config.json");
|
|
395
|
+
}
|
|
396
|
+
function takeOverFormerConfig(path, former = defaultConfigPath(FORMER_NAME)) {
|
|
397
|
+
if (existsSync(path) || !existsSync(former)) return void 0;
|
|
398
|
+
mkdirSync(dirname2(path), { recursive: true });
|
|
399
|
+
writeFileSync(path, readFileSync(former), { mode: 384 });
|
|
400
|
+
if (process.platform !== "win32") chmodSync(path, 384);
|
|
401
|
+
return former;
|
|
402
|
+
}
|
|
403
|
+
function validPort(v) {
|
|
404
|
+
return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 65535;
|
|
405
|
+
}
|
|
406
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
407
|
+
function check(raw, path) {
|
|
408
|
+
const bad = (what) => {
|
|
409
|
+
throw new Error(`${path}: ${what}`);
|
|
410
|
+
};
|
|
411
|
+
if (raw.port !== void 0 && !validPort(raw.port)) bad(`"port" must be a number from 1 to 65535, not ${JSON.stringify(raw.port)}`);
|
|
412
|
+
if (raw.token !== void 0 && typeof raw.token !== "string") bad('"token" must be a string');
|
|
413
|
+
if (raw.tools !== void 0) {
|
|
414
|
+
if (!isRecord(raw.tools)) bad('"tools" must be an object like {"shell": true, "files": true}');
|
|
415
|
+
for (const k of ["shell", "files"]) {
|
|
416
|
+
const v = raw.tools[k];
|
|
417
|
+
if (v !== void 0 && typeof v !== "boolean") bad(`"tools.${k}" must be true or false`);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (raw.mcpServers !== void 0) {
|
|
421
|
+
if (!isRecord(raw.mcpServers)) bad('"mcpServers" must be an object of named servers');
|
|
422
|
+
for (const [name, s] of Object.entries(raw.mcpServers)) {
|
|
423
|
+
if (!isRecord(s)) bad(`"mcpServers.${name}" must be an object`);
|
|
424
|
+
const entry = s;
|
|
425
|
+
if (typeof entry.command !== "string" && typeof entry.url !== "string") bad(`"mcpServers.${name}" needs "command" (a program to start) or "url"`);
|
|
426
|
+
if (entry.args !== void 0 && !(Array.isArray(entry.args) && entry.args.every((a) => typeof a === "string"))) bad(`"mcpServers.${name}.args" must be a list of strings`);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
function loadConfig(path, opts = {}) {
|
|
431
|
+
const created = !existsSync(path);
|
|
432
|
+
let raw = {};
|
|
433
|
+
if (!created) {
|
|
434
|
+
try {
|
|
435
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
436
|
+
if (!isRecord(parsed)) throw new Error("the file must hold one JSON object");
|
|
437
|
+
raw = parsed;
|
|
438
|
+
} catch (e) {
|
|
439
|
+
throw new Error(`Cannot read ${path}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
440
|
+
}
|
|
441
|
+
check(raw, path);
|
|
442
|
+
}
|
|
443
|
+
const tools = raw.tools ?? {};
|
|
444
|
+
const keepToken = typeof raw.token === "string" && raw.token.length >= 16 && !opts.newToken;
|
|
445
|
+
const config = {
|
|
446
|
+
port: raw.port ?? DEFAULT_PORT,
|
|
447
|
+
token: keepToken ? raw.token : randomBytes(24).toString("base64url"),
|
|
448
|
+
tools: { shell: tools.shell !== false, files: tools.files !== false },
|
|
449
|
+
mcpServers: raw.mcpServers ?? {}
|
|
450
|
+
};
|
|
451
|
+
if (created || !keepToken) saveConfig(path, { ...raw, ...config });
|
|
452
|
+
else if (process.platform !== "win32" && (statSync(path).mode & 63) !== 0) chmodSync(path, 384);
|
|
453
|
+
return { config, created, raw };
|
|
454
|
+
}
|
|
455
|
+
function saveConfig(path, config) {
|
|
456
|
+
mkdirSync(dirname2(path), { recursive: true });
|
|
457
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}
|
|
458
|
+
`, { mode: 384 });
|
|
459
|
+
if (process.platform !== "win32") chmodSync(path, 384);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// src/http.ts
|
|
463
|
+
import { timingSafeEqual } from "node:crypto";
|
|
464
|
+
import { createServer } from "node:http";
|
|
465
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
466
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
467
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
468
|
+
|
|
469
|
+
// src/hub.ts
|
|
470
|
+
import { createInterface } from "node:readline";
|
|
471
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
472
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
473
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
474
|
+
import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
475
|
+
var VERSION = package_default.version;
|
|
476
|
+
var SEPARATOR = "__";
|
|
477
|
+
var CALL_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
478
|
+
var CONNECT_TIMEOUT_MS = 2e4;
|
|
479
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
480
|
+
var HEALTHY_MS = 3e4;
|
|
481
|
+
var START_WAIT_MS = 5e3;
|
|
482
|
+
var QUICK_TOOL_WARN_MS = 5e3;
|
|
483
|
+
var LONG_CALL_NOTE_MS = 3e4;
|
|
484
|
+
var Upstream = class {
|
|
485
|
+
name;
|
|
486
|
+
cfg;
|
|
487
|
+
log;
|
|
488
|
+
client;
|
|
489
|
+
/** The client being connected, so that close() can stop a server that is still starting. */
|
|
490
|
+
pending;
|
|
491
|
+
closed = false;
|
|
492
|
+
starting;
|
|
493
|
+
failures = 0;
|
|
494
|
+
failedAt = 0;
|
|
495
|
+
connectedAt = 0;
|
|
496
|
+
/** The last tools the server listed; kept while it restarts, so that a call reaches it again. */
|
|
497
|
+
tools = [];
|
|
498
|
+
instructions = "";
|
|
499
|
+
error = "";
|
|
500
|
+
constructor(name, cfg, log) {
|
|
501
|
+
this.name = name;
|
|
502
|
+
this.cfg = cfg;
|
|
503
|
+
this.log = log;
|
|
504
|
+
}
|
|
505
|
+
get ok() {
|
|
506
|
+
return this.client !== void 0;
|
|
507
|
+
}
|
|
508
|
+
/** Connects when not connected; after failures, waits longer each time before trying again. */
|
|
509
|
+
ensure() {
|
|
510
|
+
if (this.client || this.closed) return Promise.resolve();
|
|
511
|
+
const backoff = this.failures ? Math.min(MAX_BACKOFF_MS, 250 * 2 ** (this.failures - 1)) : 0;
|
|
512
|
+
if (Date.now() - this.failedAt < backoff) return Promise.resolve();
|
|
513
|
+
return this.starting ??= this.start().finally(() => this.starting = void 0);
|
|
514
|
+
}
|
|
515
|
+
/** `lostConnection`: it ran and stopped (a long healthy run starts the backoff over); else it could not start. */
|
|
516
|
+
failed(lostConnection) {
|
|
517
|
+
this.failures = lostConnection && Date.now() - this.connectedAt > HEALTHY_MS ? 1 : this.failures + 1;
|
|
518
|
+
this.failedAt = Date.now();
|
|
519
|
+
}
|
|
520
|
+
async start() {
|
|
521
|
+
const client = new Client({ name: NAME, version: VERSION });
|
|
522
|
+
this.pending = client;
|
|
523
|
+
try {
|
|
524
|
+
let transport;
|
|
525
|
+
if ("url" in this.cfg) {
|
|
526
|
+
transport = new StreamableHTTPClientTransport(new URL(this.cfg.url), { requestInit: { headers: this.cfg.headers ?? {} } });
|
|
527
|
+
} else {
|
|
528
|
+
const stdio = new StdioClientTransport({ command: this.cfg.command, args: this.cfg.args, env: this.cfg.env, cwd: this.cfg.cwd, stderr: "pipe" });
|
|
529
|
+
if (stdio.stderr) createInterface({ input: stdio.stderr }).on("line", (line) => line.trim() && this.log.info(`[${this.name}] ${line}`));
|
|
530
|
+
transport = stdio;
|
|
531
|
+
}
|
|
532
|
+
client.onclose = () => {
|
|
533
|
+
if (this.client !== client) return;
|
|
534
|
+
this.client = void 0;
|
|
535
|
+
this.error = "disconnected";
|
|
536
|
+
this.failed(true);
|
|
537
|
+
if (!this.closed) this.log.warn(`[${this.name}] disconnected: it is started again when a tool of it is needed`);
|
|
538
|
+
};
|
|
539
|
+
await client.connect(transport, { timeout: CONNECT_TIMEOUT_MS });
|
|
540
|
+
client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
|
|
541
|
+
this.tools = await this.listAll(client).catch(() => this.tools);
|
|
542
|
+
});
|
|
543
|
+
this.tools = await this.listAll(client);
|
|
544
|
+
if (this.closed) throw new Error("closed");
|
|
545
|
+
this.instructions = client.getInstructions() ?? "";
|
|
546
|
+
this.client = client;
|
|
547
|
+
this.connectedAt = Date.now();
|
|
548
|
+
this.error = "";
|
|
549
|
+
this.log.info(`[${this.name}] connected: ${this.tools.length} tools`);
|
|
550
|
+
} catch (e) {
|
|
551
|
+
this.failed(false);
|
|
552
|
+
this.error = message(e);
|
|
553
|
+
if (!this.closed) this.log.error(`[${this.name}] cannot start: ${this.error}`);
|
|
554
|
+
await client.close().catch(() => void 0);
|
|
555
|
+
} finally {
|
|
556
|
+
if (this.pending === client) this.pending = void 0;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
async listAll(client) {
|
|
560
|
+
const all = [];
|
|
561
|
+
let cursor;
|
|
562
|
+
do {
|
|
563
|
+
const r = await client.listTools(cursor ? { cursor } : {});
|
|
564
|
+
all.push(...r.tools);
|
|
565
|
+
cursor = r.nextCursor;
|
|
566
|
+
} while (cursor);
|
|
567
|
+
return all;
|
|
568
|
+
}
|
|
569
|
+
async call(tool, args, signal) {
|
|
570
|
+
await this.ensure();
|
|
571
|
+
if (!this.client) throw new Error(`The MCP server "${this.name}" is not running: ${this.error || "starting"}`);
|
|
572
|
+
return await this.client.callTool({ name: tool, arguments: args }, void 0, { timeout: CALL_TIMEOUT_MS, resetTimeoutOnProgress: true, signal });
|
|
573
|
+
}
|
|
574
|
+
async close() {
|
|
575
|
+
this.closed = true;
|
|
576
|
+
const clients = [this.client, this.pending].filter((c) => c !== void 0);
|
|
577
|
+
this.client = void 0;
|
|
578
|
+
this.pending = void 0;
|
|
579
|
+
await Promise.all(clients.map((c) => c.close().catch(() => void 0)));
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
var Hub = class {
|
|
583
|
+
builtin;
|
|
584
|
+
builtinNames;
|
|
585
|
+
note;
|
|
586
|
+
upstreams;
|
|
587
|
+
log;
|
|
588
|
+
constructor(config, log = silent) {
|
|
589
|
+
this.log = log;
|
|
590
|
+
this.builtin = builtinTools(config.tools);
|
|
591
|
+
this.builtinNames = new Set(this.builtin.map((t) => t.name));
|
|
592
|
+
this.note = systemNote(config.tools);
|
|
593
|
+
this.upstreams = Object.entries(config.mcpServers).filter(([, c]) => !c.disabled).map(([name, c]) => new Upstream(name, c, log));
|
|
594
|
+
}
|
|
595
|
+
/** Starts the pass-through servers; waits a few seconds for them, so that the first report is complete. */
|
|
596
|
+
async start() {
|
|
597
|
+
const all = Promise.all(this.upstreams.map((u) => u.ensure()));
|
|
598
|
+
await Promise.race([all, new Promise((r) => setTimeout(r, START_WAIT_MS).unref())]);
|
|
599
|
+
}
|
|
600
|
+
/** The tools there are now. A pass-through server that is (re)starting is not waited for: it joins the list once it runs. */
|
|
601
|
+
listTools() {
|
|
602
|
+
for (const u of this.upstreams) void u.ensure();
|
|
603
|
+
return [...this.builtin, ...this.passThrough().map((p) => ({ ...p.tool, name: p.name }))];
|
|
604
|
+
}
|
|
605
|
+
passThrough() {
|
|
606
|
+
return this.upstreams.flatMap((u) => u.tools.map((t) => ({ name: `${u.name}${SEPARATOR}${t.name}`, upstream: u, tool: t })));
|
|
607
|
+
}
|
|
608
|
+
instructions() {
|
|
609
|
+
const parts = [this.note];
|
|
610
|
+
for (const u of this.upstreams) if (u.ok && u.instructions.trim()) parts.push(`Tools named ${u.name}${SEPARATOR}*: ${u.instructions.trim()}`);
|
|
611
|
+
return parts.join("\n");
|
|
612
|
+
}
|
|
613
|
+
/** The pass-through servers that are not running, for the start report. */
|
|
614
|
+
notRunning() {
|
|
615
|
+
return this.upstreams.filter((u) => !u.ok).map((u) => ({ name: u.name, error: u.error }));
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Runs a tool and says in `log` what it does: each step, that it still runs (a warning for a file tool, which
|
|
619
|
+
* should take milliseconds), that the extension gave up on it, and how it ended: a failure as an error, with why.
|
|
620
|
+
*/
|
|
621
|
+
async callTool(name, args, signal, log = this.log) {
|
|
622
|
+
const started = Date.now();
|
|
623
|
+
let last = "none yet";
|
|
624
|
+
const steps = {
|
|
625
|
+
info: (line) => {
|
|
626
|
+
last = line;
|
|
627
|
+
log.info(line);
|
|
628
|
+
},
|
|
629
|
+
warn: (line) => {
|
|
630
|
+
last = line;
|
|
631
|
+
log.warn(line);
|
|
632
|
+
},
|
|
633
|
+
error: log.error
|
|
634
|
+
};
|
|
635
|
+
const quick = name !== "run_command" && this.builtinNames.has(name);
|
|
636
|
+
const tick = setInterval(
|
|
637
|
+
() => (quick ? log.warn : log.info)(`${name} still running after ${Math.round((Date.now() - started) / 1e3)} s (last step: ${last})`),
|
|
638
|
+
quick ? QUICK_TOOL_WARN_MS : LONG_CALL_NOTE_MS
|
|
639
|
+
);
|
|
640
|
+
tick.unref();
|
|
641
|
+
const cancelled = () => log.warn(`${name}: the extension gave up on the call or closed the connection after ${Date.now() - started} ms; it is stopped`);
|
|
642
|
+
signal?.addEventListener("abort", cancelled, { once: true });
|
|
643
|
+
let result;
|
|
644
|
+
try {
|
|
645
|
+
result = await this.route(name, args, signal, steps);
|
|
646
|
+
} catch (e) {
|
|
647
|
+
result = { content: [{ type: "text", text: message(e) }], isError: true };
|
|
648
|
+
} finally {
|
|
649
|
+
clearInterval(tick);
|
|
650
|
+
signal?.removeEventListener("abort", cancelled);
|
|
651
|
+
}
|
|
652
|
+
const ms = Date.now() - started;
|
|
653
|
+
if (result.isError) log.error(`${name} failed (${ms} ms): ${errorText(result)}`);
|
|
654
|
+
else log.info(`${name} done (${ms} ms): ${resultText(result)}`);
|
|
655
|
+
return result;
|
|
656
|
+
}
|
|
657
|
+
async route(name, args, signal, log) {
|
|
658
|
+
if (this.builtinNames.has(name)) return await callBuiltin(name, args, signal, log);
|
|
659
|
+
const p = this.passThrough().find((x) => x.name === name);
|
|
660
|
+
if (!p) throw new Error(`Unknown tool: ${name}`);
|
|
661
|
+
log.info(`passing it to the MCP server "${p.upstream.name}" as ${p.tool.name}`);
|
|
662
|
+
return await p.upstream.call(p.tool.name, args, signal);
|
|
663
|
+
}
|
|
664
|
+
async close() {
|
|
665
|
+
await Promise.all(this.upstreams.map((u) => u.close()));
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
function contentText(result) {
|
|
669
|
+
const parts = Array.isArray(result.content) ? result.content : [];
|
|
670
|
+
return parts.map((c) => c.type === "text" ? c.text : `[${c.type}]`).join(" ");
|
|
671
|
+
}
|
|
672
|
+
function errorText(result) {
|
|
673
|
+
return oneLine(contentText(result)) || "(no message)";
|
|
674
|
+
}
|
|
675
|
+
function resultText(result) {
|
|
676
|
+
const s = contentText(result);
|
|
677
|
+
return `${s.length} characters: ${oneLine(s, 200) || "(empty)"}`;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// src/perf.ts
|
|
681
|
+
import { appendFileSync, readFileSync as readFileSync2, renameSync, statSync as statSync2 } from "node:fs";
|
|
682
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
683
|
+
var PERF_MAX_BYTES = 1024 * 1024;
|
|
684
|
+
var PERF_BODY_LIMIT = 64 * 1024;
|
|
685
|
+
var MAX_LINE = 2e3;
|
|
686
|
+
var MAX_LINES = 500;
|
|
687
|
+
function perfLogPath(configPath) {
|
|
688
|
+
return join3(dirname3(configPath), "perf.log");
|
|
689
|
+
}
|
|
690
|
+
function cleanLines(body) {
|
|
691
|
+
return body.split(/\r\n|\r|\n/).map((l) => l.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, " ").trimEnd().slice(0, MAX_LINE)).filter(Boolean).slice(0, MAX_LINES);
|
|
692
|
+
}
|
|
693
|
+
function appendPerf(path, lines, maxBytes = PERF_MAX_BYTES) {
|
|
694
|
+
if (!lines.length) return;
|
|
695
|
+
const st = statSync2(path, { throwIfNoEntry: false });
|
|
696
|
+
if (st && st.size > maxBytes) renameSync(path, `${path}.1`);
|
|
697
|
+
appendFileSync(path, `${lines.join("\n")}
|
|
698
|
+
`, { mode: 384 });
|
|
699
|
+
}
|
|
700
|
+
function showPerf(path) {
|
|
701
|
+
let text2 = "";
|
|
702
|
+
try {
|
|
703
|
+
text2 = readFileSync2(path, "utf8");
|
|
704
|
+
} catch {
|
|
705
|
+
}
|
|
706
|
+
if (text2) return text2;
|
|
707
|
+
return `Nothing in ${path} yet. Turn on "Write the performance log" in the extension's options, and use the page in a tab where the extension is on.
|
|
708
|
+
`;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// src/http.ts
|
|
712
|
+
var BODY_LIMIT = 8 * 1024 * 1024;
|
|
713
|
+
var SLOW_BODY_MS = 5e3;
|
|
714
|
+
var REPLY_KEEP = 64 * 1024;
|
|
715
|
+
function mcpServerFor(hub, log) {
|
|
716
|
+
const server = new Server({ name: NAME, version: VERSION }, { capabilities: { tools: {} }, instructions: hub.instructions() });
|
|
717
|
+
server.setRequestHandler(ListToolsRequestSchema, () => {
|
|
718
|
+
const tools = hub.listTools();
|
|
719
|
+
log.info(`listed ${tools.length} tools`);
|
|
720
|
+
return { tools };
|
|
721
|
+
});
|
|
722
|
+
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => hub.callTool(req.params.name, req.params.arguments ?? {}, extra.signal, log));
|
|
723
|
+
server.onerror = (e) => log.error(`MCP: ${message(e)}`);
|
|
724
|
+
return server;
|
|
725
|
+
}
|
|
726
|
+
function checkRequest(req, token) {
|
|
727
|
+
const origin = req.headers.origin;
|
|
728
|
+
if (origin && !origin.startsWith("chrome-extension://")) return { status: 403, message: "Origin not allowed" };
|
|
729
|
+
const auth = req.headers.authorization ?? "";
|
|
730
|
+
const given = Buffer.from(auth.startsWith("Bearer ") ? auth.slice(7).trim() : "");
|
|
731
|
+
const want = Buffer.from(token);
|
|
732
|
+
if (given.length !== want.length || !timingSafeEqual(given, want)) return { status: 401, message: "Missing or wrong token" };
|
|
733
|
+
return null;
|
|
734
|
+
}
|
|
735
|
+
function reply(res, status, message2) {
|
|
736
|
+
res.writeHead(status, { "content-type": "text/plain; charset=utf-8" }).end(message2);
|
|
737
|
+
}
|
|
738
|
+
function replyRpcError(res, status, code, message2) {
|
|
739
|
+
res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", error: { code, message: message2 }, id: null }));
|
|
740
|
+
}
|
|
741
|
+
var from = (req) => (req.socket.remoteAddress ?? "?").replace(/^::ffff:/, "");
|
|
742
|
+
async function readBody(req, limit) {
|
|
743
|
+
const chunks = [];
|
|
744
|
+
let size = 0;
|
|
745
|
+
for await (const c of req) {
|
|
746
|
+
size += c.length;
|
|
747
|
+
if (size <= limit) chunks.push(c);
|
|
748
|
+
}
|
|
749
|
+
return size > limit ? null : Buffer.concat(chunks).toString("utf8");
|
|
750
|
+
}
|
|
751
|
+
function describe(body) {
|
|
752
|
+
return (Array.isArray(body) ? body : [body]).map((m) => {
|
|
753
|
+
if (typeof m !== "object" || m === null) return "not a JSON-RPC message";
|
|
754
|
+
const { method, params } = m;
|
|
755
|
+
if (method === "tools/call") return `tools/call ${String(params?.name)} ${short(params?.arguments ?? {})}`;
|
|
756
|
+
if (method === "initialize") {
|
|
757
|
+
const client = params?.clientInfo;
|
|
758
|
+
return `initialize from ${String(client?.name)} ${String(client?.version)}`;
|
|
759
|
+
}
|
|
760
|
+
return typeof method === "string" ? method : "a reply to the server";
|
|
761
|
+
}).join(", ");
|
|
762
|
+
}
|
|
763
|
+
function rpcErrors(text2) {
|
|
764
|
+
const start = text2.trimStart()[0];
|
|
765
|
+
const parts = start === "{" || start === "[" ? [text2] : text2.split("\n").flatMap((l) => l.startsWith("data:") ? [l.slice(5)] : []);
|
|
766
|
+
const out = [];
|
|
767
|
+
for (const part of parts) {
|
|
768
|
+
let v;
|
|
769
|
+
try {
|
|
770
|
+
v = JSON.parse(part);
|
|
771
|
+
} catch {
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
for (const m of Array.isArray(v) ? v : [v]) {
|
|
775
|
+
const e = m?.error;
|
|
776
|
+
if (e) out.push(`${String(e.code)} ${oneLine(String(e.message), 200)}`);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return out;
|
|
780
|
+
}
|
|
781
|
+
function watchReply(res) {
|
|
782
|
+
const kept = [];
|
|
783
|
+
let bytes = 0;
|
|
784
|
+
const take = (chunk, encoding) => {
|
|
785
|
+
if (typeof chunk !== "string" && !(chunk instanceof Uint8Array)) return;
|
|
786
|
+
const b = typeof chunk === "string" ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8") : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
787
|
+
bytes += b.length;
|
|
788
|
+
if (bytes <= REPLY_KEEP) kept.push(b);
|
|
789
|
+
};
|
|
790
|
+
const write = res.write.bind(res);
|
|
791
|
+
const end = res.end.bind(res);
|
|
792
|
+
res.write = ((...a) => {
|
|
793
|
+
take(a[0], a[1]);
|
|
794
|
+
return write(...a);
|
|
795
|
+
});
|
|
796
|
+
res.end = ((...a) => {
|
|
797
|
+
take(a[0], a[1]);
|
|
798
|
+
return end(...a);
|
|
799
|
+
});
|
|
800
|
+
return () => ({ bytes, text: Buffer.concat(kept).toString("utf8") });
|
|
801
|
+
}
|
|
802
|
+
async function mcpRequest(hub, req, res, log, ms) {
|
|
803
|
+
const slow = setTimeout(() => log.warn(`the body is still coming in after ${SLOW_BODY_MS / 1e3} s`), SLOW_BODY_MS);
|
|
804
|
+
let body;
|
|
805
|
+
try {
|
|
806
|
+
body = await readBody(req, BODY_LIMIT);
|
|
807
|
+
} catch (e) {
|
|
808
|
+
return log.error(`the upload broke off after ${ms()} ms (${message(e)}): the extension gave up or went away`);
|
|
809
|
+
} finally {
|
|
810
|
+
clearTimeout(slow);
|
|
811
|
+
}
|
|
812
|
+
if (body === null) {
|
|
813
|
+
log.error(`refused: the body is over ${BODY_LIMIT} bytes`);
|
|
814
|
+
return replyRpcError(res, 413, -32e3, `Payload too large: the limit is ${BODY_LIMIT} bytes`);
|
|
815
|
+
}
|
|
816
|
+
let parsed;
|
|
817
|
+
try {
|
|
818
|
+
parsed = JSON.parse(body);
|
|
819
|
+
} catch (e) {
|
|
820
|
+
log.error(`the body is not JSON (${message(e)}): ${oneLine(body, 200)}`);
|
|
821
|
+
return replyRpcError(res, 400, -32700, "Parse error: Invalid JSON");
|
|
822
|
+
}
|
|
823
|
+
log.info(`\u2190 ${describe(parsed)} \xB7 ${Buffer.byteLength(body)} bytes from ${from(req)}`);
|
|
824
|
+
const sent = watchReply(res);
|
|
825
|
+
const server = mcpServerFor(hub, log);
|
|
826
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0, enableJsonResponse: true });
|
|
827
|
+
transport.onerror = (e) => log.error(`transport: ${message(e)}`);
|
|
828
|
+
res.on("finish", () => {
|
|
829
|
+
const { bytes, text: text2 } = sent();
|
|
830
|
+
const errors = bytes <= REPLY_KEEP && text2.includes('"error"') ? rpcErrors(text2) : [];
|
|
831
|
+
const what = `\u2192 HTTP ${res.statusCode}, ${bytes} bytes, ${ms()} ms`;
|
|
832
|
+
if (errors.length) log.error(`${what}: JSON-RPC error ${errors.join("; ")}`);
|
|
833
|
+
else if (res.statusCode >= 400) log.error(`${what}${text2 ? `: ${oneLine(text2, 300)}` : ""}`);
|
|
834
|
+
else log.info(what);
|
|
835
|
+
});
|
|
836
|
+
res.on("close", () => {
|
|
837
|
+
if (!res.writableFinished) log.error(`the connection closed after ${ms()} ms, before the reply was sent: the extension gave up or went away`);
|
|
838
|
+
void server.close();
|
|
839
|
+
});
|
|
840
|
+
await server.connect(transport);
|
|
841
|
+
await transport.handleRequest(req, res, parsed);
|
|
842
|
+
}
|
|
843
|
+
async function perfRequest(req, res, file, log, first) {
|
|
844
|
+
let body;
|
|
845
|
+
try {
|
|
846
|
+
body = await readBody(req, PERF_BODY_LIMIT);
|
|
847
|
+
} catch (e) {
|
|
848
|
+
return log.warn(`a performance log upload broke off (${message(e)})`);
|
|
849
|
+
}
|
|
850
|
+
if (body === null) {
|
|
851
|
+
log.warn(`refused a performance log upload over ${PERF_BODY_LIMIT} bytes`);
|
|
852
|
+
return reply(res, 413, "Too large");
|
|
853
|
+
}
|
|
854
|
+
try {
|
|
855
|
+
appendPerf(file, cleanLines(body));
|
|
856
|
+
} catch (e) {
|
|
857
|
+
log.error(`cannot write ${file}: ${message(e)}`);
|
|
858
|
+
return reply(res, 500, "Cannot write the performance log");
|
|
859
|
+
}
|
|
860
|
+
if (!first.told) {
|
|
861
|
+
first.told = true;
|
|
862
|
+
log.info(`the extension's performance log goes to ${file}`);
|
|
863
|
+
}
|
|
864
|
+
reply(res, 200, file);
|
|
865
|
+
}
|
|
866
|
+
function listen(hub, opts) {
|
|
867
|
+
const root = opts.log ?? silent;
|
|
868
|
+
const perfTold = { told: false };
|
|
869
|
+
let count = 0;
|
|
870
|
+
const http = createServer((req, res) => {
|
|
871
|
+
const log = tagged(root, `#${++count}`);
|
|
872
|
+
const started = Date.now();
|
|
873
|
+
const ms = () => Date.now() - started;
|
|
874
|
+
void (async () => {
|
|
875
|
+
const path = (req.url ?? "/").split("?")[0];
|
|
876
|
+
const perfFile = path === "/perf" ? opts.perfLog : void 0;
|
|
877
|
+
if (path !== "/mcp" && perfFile === void 0) {
|
|
878
|
+
if (path === "/" && req.method === "GET") return reply(res, 200, `${NAME} ${VERSION} is running. MCP endpoint: /mcp
|
|
879
|
+
`);
|
|
880
|
+
log.warn(`${req.method} ${path} from ${from(req)}: not found`);
|
|
881
|
+
return reply(res, 404, "Not found");
|
|
882
|
+
}
|
|
883
|
+
const refused = checkRequest(req, opts.token);
|
|
884
|
+
if (refused) {
|
|
885
|
+
log.warn(`refused ${req.method} ${path} from ${from(req)} (origin ${req.headers.origin ?? "none"}): ${refused.message}`);
|
|
886
|
+
return reply(res, refused.status, refused.message);
|
|
887
|
+
}
|
|
888
|
+
if (req.method !== "POST") {
|
|
889
|
+
log.warn(`refused ${req.method} ${path}: only POST is answered`);
|
|
890
|
+
res.setHeader("allow", "POST");
|
|
891
|
+
return reply(res, 405, perfFile ? "Only POST" : "Only POST: this server keeps no sessions");
|
|
892
|
+
}
|
|
893
|
+
if (perfFile) return await perfRequest(req, res, perfFile, log, perfTold);
|
|
894
|
+
await mcpRequest(hub, req, res, log, ms);
|
|
895
|
+
})().catch((e) => {
|
|
896
|
+
log.error(`internal error: ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
|
|
897
|
+
if (!res.headersSent) reply(res, 500, "Internal error");
|
|
898
|
+
});
|
|
899
|
+
});
|
|
900
|
+
http.on("clientError", (e, socket) => {
|
|
901
|
+
if (e.code === "ECONNRESET" || !socket.writable) return void socket.destroy();
|
|
902
|
+
root.warn(`closed a connection that sent what is not HTTP or came too slowly (${e.code ?? message(e)})`);
|
|
903
|
+
socket.end(`HTTP/1.1 ${e.code === "ERR_HTTP_REQUEST_TIMEOUT" ? "408 Request Timeout" : "400 Bad Request"}\r
|
|
904
|
+
Connection: close\r
|
|
905
|
+
\r
|
|
906
|
+
`);
|
|
907
|
+
});
|
|
908
|
+
return new Promise((resolve3, reject) => {
|
|
909
|
+
http.once("error", reject);
|
|
910
|
+
http.listen(opts.port, () => {
|
|
911
|
+
http.off("error", reject);
|
|
912
|
+
resolve3(http);
|
|
913
|
+
});
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// src/cli.ts
|
|
918
|
+
var HELP = `${NAME} ${VERSION}: your computer's tools for chats on the web, through the Gemini MCP Bridge extension
|
|
919
|
+
|
|
920
|
+
Usage:
|
|
921
|
+
${NAME} [options] Start the server
|
|
922
|
+
${NAME} token [--config <file>] Show the URL and the token for the extension
|
|
923
|
+
${NAME} perf-log [--config <file>] Show the extension's performance log (an option of the extension)
|
|
924
|
+
|
|
925
|
+
Options:
|
|
926
|
+
--port <n> Port (default: from the config, 7341)
|
|
927
|
+
--config <file> Config file (default: ${defaultConfigPath()})
|
|
928
|
+
--no-shell Without the run_command tool
|
|
929
|
+
--no-files Without read_file, list_directory (and write_file, there without bash or the shell)
|
|
930
|
+
--new-token Make a new token (the extension then needs the new one)
|
|
931
|
+
-h, --help This text
|
|
932
|
+
-v, --version The version
|
|
933
|
+
|
|
934
|
+
While it runs, it writes each request to stdout as it comes: the call and its arguments, each step of the
|
|
935
|
+
work, and the reply; WARN and ERROR lines when something goes wrong.
|
|
936
|
+
|
|
937
|
+
The config file also lists MCP servers to pass through, in the usual "mcpServers" shape:
|
|
938
|
+
"mcpServers": { "playwright": { "command": "npx", "args": ["@playwright/mcp@latest"] } }
|
|
939
|
+
|
|
940
|
+
Until 0.6.0 its name was ${FORMER_NAME}: without --config, the first start (or token) copies that name's config
|
|
941
|
+
file (the token, the port, the servers).
|
|
942
|
+
`;
|
|
943
|
+
function port(value, fallback) {
|
|
944
|
+
if (value === void 0) return fallback;
|
|
945
|
+
const p = Number(value);
|
|
946
|
+
if (!validPort(p)) throw new Error(`--port must be a number from 1 to 65535, not ${value}`);
|
|
947
|
+
return p;
|
|
948
|
+
}
|
|
949
|
+
async function main() {
|
|
950
|
+
const { values, positionals } = parseArgs({
|
|
951
|
+
allowPositionals: true,
|
|
952
|
+
options: {
|
|
953
|
+
port: { type: "string" },
|
|
954
|
+
config: { type: "string" },
|
|
955
|
+
"no-shell": { type: "boolean" },
|
|
956
|
+
"no-files": { type: "boolean" },
|
|
957
|
+
"new-token": { type: "boolean" },
|
|
958
|
+
help: { type: "boolean", short: "h" },
|
|
959
|
+
version: { type: "boolean", short: "v" }
|
|
960
|
+
},
|
|
961
|
+
strict: true
|
|
962
|
+
});
|
|
963
|
+
const command = positionals[0] ?? "serve";
|
|
964
|
+
if (values.help) return void process.stdout.write(HELP);
|
|
965
|
+
if (values.version) return void process.stdout.write(`${VERSION}
|
|
966
|
+
`);
|
|
967
|
+
const path = values.config ? resolve2(values.config) : defaultConfigPath();
|
|
968
|
+
if (command === "perf-log") return void process.stdout.write(showPerf(perfLogPath(path)));
|
|
969
|
+
const copied = values.config ? void 0 : takeOverFormerConfig(path);
|
|
970
|
+
if (command === "token") {
|
|
971
|
+
const { config: config2 } = loadConfig(path);
|
|
972
|
+
return void process.stdout.write(`URL: http://127.0.0.1:${config2.port}/mcp
|
|
973
|
+
Token: ${config2.token}
|
|
974
|
+
`);
|
|
975
|
+
}
|
|
976
|
+
if (command !== "serve") throw new Error(`Unknown command: ${command}. See ${NAME} --help`);
|
|
977
|
+
const { config, created } = loadConfig(path, { newToken: values["new-token"] });
|
|
978
|
+
const listenPort = port(values.port, config.port);
|
|
979
|
+
const tools = { shell: config.tools.shell && !values["no-shell"], files: config.tools.files && !values["no-files"] };
|
|
980
|
+
const log = consoleLogger();
|
|
981
|
+
process.stdout.on("error", () => void 0);
|
|
982
|
+
process.on("unhandledRejection", (e) => log.error(`unexpected failure: ${e instanceof Error ? e.stack ?? e.message : String(e)}`));
|
|
983
|
+
process.on("uncaughtExceptionMonitor", (e) => log.error(`the server stops on an error of its own: ${e.stack ?? e.message}`));
|
|
984
|
+
const hub = new Hub({ ...config, tools }, log);
|
|
985
|
+
const perfLog = perfLogPath(path);
|
|
986
|
+
const http = await listen(hub, { port: listenPort, token: config.token, log, perfLog }).catch(async (e) => {
|
|
987
|
+
await hub.close();
|
|
988
|
+
if (e.code === "EADDRINUSE") throw new Error(`Port ${listenPort} is in use: is ${NAME} already running in another window? Another port: --port <n>`, { cause: e });
|
|
989
|
+
throw e;
|
|
990
|
+
});
|
|
991
|
+
let stopping = false;
|
|
992
|
+
const stop = async () => {
|
|
993
|
+
if (stopping) process.exit(1);
|
|
994
|
+
stopping = true;
|
|
995
|
+
log.info("stopping");
|
|
996
|
+
stopAllCommands();
|
|
997
|
+
http.close();
|
|
998
|
+
await hub.close();
|
|
999
|
+
process.exit(0);
|
|
1000
|
+
};
|
|
1001
|
+
process.on("SIGINT", () => void stop());
|
|
1002
|
+
process.on("SIGTERM", () => void stop());
|
|
1003
|
+
await hub.start();
|
|
1004
|
+
const names = hub.listTools().map((t) => t.name);
|
|
1005
|
+
const token = process.stdout.isTTY ? config.token : `(not printed here; run: ${NAME} token)`;
|
|
1006
|
+
const out = [
|
|
1007
|
+
`${NAME} ${VERSION}`,
|
|
1008
|
+
` URL: http://127.0.0.1:${listenPort}/mcp`,
|
|
1009
|
+
` Token: ${token}`,
|
|
1010
|
+
` Config: ${path}${created ? " (new)" : copied ? ` (copied from ${copied})` : ""}`,
|
|
1011
|
+
` Perf: ${perfLog} (when the extension's performance log is on)`,
|
|
1012
|
+
` Tools: ${names.length ? names.join(", ") : "none"}`,
|
|
1013
|
+
...hub.notRunning().map((s) => ` Not running yet: ${s.name}${s.error ? ` (${s.error})` : " (starting)"}`),
|
|
1014
|
+
"",
|
|
1015
|
+
"In Chrome: click the Gemini MCP Bridge icon > Settings, and enter the URL and the token.",
|
|
1016
|
+
"From another computer, or through a forwarded port: the same URL with that address and port.",
|
|
1017
|
+
"Leave this window open while you use the extension; Ctrl+C stops the server.",
|
|
1018
|
+
"Each request is written below as it comes: the call, each step of the work, and the reply (WARN and ERROR when something goes wrong).",
|
|
1019
|
+
""
|
|
1020
|
+
];
|
|
1021
|
+
process.stdout.write(out.join("\n"));
|
|
1022
|
+
}
|
|
1023
|
+
main().catch((e) => {
|
|
1024
|
+
process.stderr.write(`${NAME}: ${e instanceof Error ? e.message : String(e)}
|
|
1025
|
+
`);
|
|
1026
|
+
process.exit(1);
|
|
1027
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-mcp-bridge-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.8.0",
|
|
4
|
+
"description": "Local MCP server for the Gemini MCP Bridge Chrome extension: your computer's shell and files, plus the MCP servers you list",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/somebodil/local-mcp-bridge-server.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/somebodil/local-mcp-bridge-server#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/somebodil/local-mcp-bridge-server/issues"
|
|
14
|
+
},
|
|
15
|
+
"bin": {
|
|
16
|
+
"local-mcp-bridge-server": "dist/cli.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"mcp",
|
|
26
|
+
"model-context-protocol",
|
|
27
|
+
"mcp-server",
|
|
28
|
+
"gemini",
|
|
29
|
+
"chrome-extension"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc --noEmit && node scripts/build.mjs",
|
|
33
|
+
"typecheck": "tsc --noEmit",
|
|
34
|
+
"lint": "eslint .",
|
|
35
|
+
"test": "node --test \"src/**/*.test.ts\"",
|
|
36
|
+
"check": "npm run typecheck && npm run lint && npm test",
|
|
37
|
+
"start": "node scripts/build.mjs && node dist/cli.js",
|
|
38
|
+
"smoke": "node scripts/build.mjs && node scripts/smoke.mjs",
|
|
39
|
+
"prepack": "node scripts/build.mjs"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@modelcontextprotocol/sdk": "1.32.2"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "26.6.6",
|
|
46
|
+
"esbuild": "0.28.2",
|
|
47
|
+
"eslint": "9.39.5",
|
|
48
|
+
"typescript": "6.0.3",
|
|
49
|
+
"typescript-eslint": "8.73.0",
|
|
50
|
+
"zod": "4.6.7"
|
|
51
|
+
}
|
|
52
|
+
}
|