mcp-compress-router 3.2.0 → 3.2.1

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.
@@ -0,0 +1,167 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ const DEFAULT_TIMEOUT_MS = 15_000;
4
+ const DEFAULT_STALE_MS = 10_000;
5
+ const DEFAULT_RETRY_DELAY_MS = 25;
6
+ /**
7
+ * Type guard for Node.js system errors that carry a `code` property.
8
+ */
9
+ function isNodeError(err) {
10
+ return err instanceof Error && typeof err.code === 'string';
11
+ }
12
+ /**
13
+ * Runs `task` while holding an exclusive lock at `lockPath`.
14
+ *
15
+ * The lock is a file created with the exclusive `wx` flag, so it works
16
+ * across processes on the same host: every process that shares the path
17
+ * contends on the same inode and the OS grants it to exactly one holder.
18
+ * The file is removed when the task settles, even when it throws.
19
+ *
20
+ * A holder renews the lock file's mtime while its task runs; a lock whose
21
+ * mtime stops advancing for `staleMs` is treated as abandoned (the holder
22
+ * crashed or was killed) and is reclaimed by a waiter. Waiters give up
23
+ * with a descriptive error after `timeoutMs`.
24
+ *
25
+ * Locking is advisory: it only coordinates code that goes through this
26
+ * helper, and the critical section should stay short because other
27
+ * processes wait for it.
28
+ *
29
+ * @param lockPath - Absolute path of the lock file (created on demand).
30
+ * @param task - The operation to run while holding the lock.
31
+ * @param options - Wait, staleness, and retry tuning.
32
+ * @returns The task's result.
33
+ * @throws When the lock cannot be acquired before `timeoutMs`, or the
34
+ * task throws (the lock is released first).
35
+ */
36
+ export async function withFileLock(lockPath, task, options) {
37
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
38
+ const staleMs = options?.staleMs ?? DEFAULT_STALE_MS;
39
+ const retryDelayMs = options?.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
40
+ const token = await acquireLock(lockPath, timeoutMs, staleMs, retryDelayMs);
41
+ const heartbeat = setInterval(() => {
42
+ void fs.utimes(lockPath, new Date(), new Date()).catch(() => { });
43
+ }, Math.max(1, Math.floor(staleMs / 2)));
44
+ heartbeat.unref?.();
45
+ try {
46
+ return await task();
47
+ }
48
+ finally {
49
+ clearInterval(heartbeat);
50
+ await releaseLock(lockPath, token);
51
+ }
52
+ }
53
+ /**
54
+ * Creates the lock file, retrying with jittered delays until the timeout
55
+ * elapses. An existing lock whose mtime is older than `staleMs` is
56
+ * reclaimed and retried immediately: the stale file is atomically
57
+ * renamed to a unique per-attempt path before removal, so when several
58
+ * waiters observe the same abandoned lock exactly one rename succeeds
59
+ * and the losers retry without touching a freshly created lock.
60
+ *
61
+ * @param lockPath - Absolute path of the lock file.
62
+ * @param timeoutMs - Overall acquisition deadline.
63
+ * @param staleMs - Age after which an existing lock is abandoned.
64
+ * @param retryDelayMs - Base retry delay, jittered.
65
+ * @returns A unique token identifying this holder, for safe release.
66
+ * @throws When the lock is held by a live process past the deadline.
67
+ */
68
+ async function acquireLock(lockPath, timeoutMs, staleMs, retryDelayMs) {
69
+ const deadline = Date.now() + timeoutMs;
70
+ for (;;) {
71
+ const token = randomUUID();
72
+ try {
73
+ const handle = await fs.open(lockPath, 'wx', 0o600);
74
+ try {
75
+ await handle.writeFile(`${process.pid} ${Date.now()} ${token}\n`);
76
+ }
77
+ finally {
78
+ await handle.close();
79
+ }
80
+ return token;
81
+ }
82
+ catch (err) {
83
+ if (!isNodeError(err) || err.code !== 'EEXIST') {
84
+ throw err;
85
+ }
86
+ }
87
+ if (Date.now() >= deadline) {
88
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for lock: ${lockPath}`);
89
+ }
90
+ if (await isStale(lockPath, staleMs)) {
91
+ // The holder crashed without releasing. Reclaim the abandoned
92
+ // lock with an atomic rename: rename(2) fails with ENOENT once
93
+ // another waiter has already reclaimed it, so exactly one waiter
94
+ // wins and no waiter can delete a freshly created lock.
95
+ const reclaimPath = `${lockPath}.reclaim-${token}`;
96
+ try {
97
+ await fs.rename(lockPath, reclaimPath);
98
+ }
99
+ catch (err) {
100
+ if (isNodeError(err) && err.code === 'ENOENT') {
101
+ // Another waiter reclaimed the stale lock first; retry now.
102
+ continue;
103
+ }
104
+ throw err;
105
+ }
106
+ await fs.unlink(reclaimPath).catch(() => { });
107
+ continue;
108
+ }
109
+ await sleep(retryDelayMs + Math.floor(Math.random() * retryDelayMs));
110
+ }
111
+ }
112
+ /**
113
+ * Whether an existing lock file is abandoned: its mtime has not been
114
+ * renewed for longer than `staleMs`. A lock that disappeared between the
115
+ * failed create and this check is also considered reclaimable.
116
+ *
117
+ * @param lockPath - Absolute path of the lock file.
118
+ * @param staleMs - Age after which the lock is abandoned.
119
+ * @returns True when the lock may be removed and retried.
120
+ */
121
+ async function isStale(lockPath, staleMs) {
122
+ try {
123
+ const stat = await fs.stat(lockPath);
124
+ return Date.now() - stat.mtimeMs > staleMs;
125
+ }
126
+ catch (err) {
127
+ if (isNodeError(err) && err.code === 'ENOENT') {
128
+ return true;
129
+ }
130
+ throw err;
131
+ }
132
+ }
133
+ /**
134
+ * Releases the lock, but only when the file still carries this holder's
135
+ * token: if the lock went stale and another process reclaimed it, that
136
+ * process's lock must not be deleted.
137
+ *
138
+ * A holder frozen mid-critical-section for longer than `staleMs` is
139
+ * inherently reclaimable, because its heartbeat is frozen too: waiters
140
+ * then legitimately treat the lock as abandoned and reclaim it while
141
+ * the frozen holder still considers itself the owner. That is accepted
142
+ * for this advisory scheme — the critical sections are short, and a
143
+ * frozen process cannot be trusted to release anyway.
144
+ *
145
+ * @param lockPath - Absolute path of the lock file.
146
+ * @param token - The token returned by {@link acquireLock}.
147
+ */
148
+ async function releaseLock(lockPath, token) {
149
+ try {
150
+ const raw = await fs.readFile(lockPath, 'utf-8');
151
+ if (!raw.includes(token)) {
152
+ return;
153
+ }
154
+ await fs.unlink(lockPath);
155
+ }
156
+ catch {
157
+ // The lock file is already gone; nothing to release.
158
+ }
159
+ }
160
+ /**
161
+ * Waits for the given number of milliseconds.
162
+ *
163
+ * @param ms - Delay in milliseconds.
164
+ */
165
+ function sleep(ms) {
166
+ return new Promise((resolve) => setTimeout(resolve, ms));
167
+ }
@@ -9,5 +9,6 @@ export { expandEnvField } from './expand-env.js';
9
9
  export { Logger } from './logger.js';
10
10
  export { parseJsonc } from './parse-jsonc.js';
11
11
  export { atomicWriteFile } from './atomic-write.js';
12
+ export { withFileLock } from './file-lock.js';
12
13
  export { killProcessTree } from './process-tree.js';
13
14
  export { getDownstreamTimeoutMs, getAuthDiscoveryTimeoutMs, createTimeoutFetch, } from './timeout.js';
@@ -62,9 +62,11 @@ export async function openBrowser(url) {
62
62
  return spawnBrowser('open', [url]);
63
63
  }
64
64
  if (platform === 'win32') {
65
- // `start` is a shell built-in, so shell: true is unavoidable on Windows.
66
- // No user-controlled string is interpolated into the command template.
67
- return spawnBrowser('start', ['""', url], { shell: true });
65
+ // `start` is a cmd.exe built-in, so using it would require a shell, and
66
+ // cmd.exe treats the `&` separators of an authorization URL as command
67
+ // separators, truncating the URL. Hand the URL to the protocol handler
68
+ // directly instead: no shell is involved and the URL arrives intact.
69
+ return spawnBrowser('rundll32.exe', ['url.dll,FileProtocolHandler', url]);
68
70
  }
69
71
  return spawnBrowser('xdg-open', [url]);
70
72
  }
@@ -72,16 +74,16 @@ export async function openBrowser(url) {
72
74
  * Spawns a browser command and resolves once it has spawned.
73
75
  *
74
76
  * The browser process is fire-and-forget; this only waits for a successful
75
- * spawn, not for the process to exit.
77
+ * spawn, not for the process to exit. The command is spawned directly, with
78
+ * no shell in between, so shell metacharacters in the arguments stay literal.
76
79
  *
77
80
  * @param command - The executable to run.
78
81
  * @param args - Arguments to pass to the executable (including the URL).
79
- * @param options - Optional spawn options (e.g. `shell: true` on Windows).
80
82
  * @throws If the process fails to spawn.
81
83
  */
82
- function spawnBrowser(command, args, options) {
84
+ function spawnBrowser(command, args) {
83
85
  return new Promise((resolve, reject) => {
84
- const child = options ? spawn(command, args, options) : spawn(command, args);
86
+ const child = spawn(command, args);
85
87
  child.on('error', reject);
86
88
  child.on('spawn', () => resolve());
87
89
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-compress-router",
3
- "version": "3.2.0",
3
+ "version": "3.2.1",
4
4
  "description": "Compress all connected MCP servers into a single router MCP to save tokens",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -40,6 +40,7 @@
40
40
  "qa:long-description": "tsx qa/scripts/qa-long-description.ts",
41
41
  "qa:router": "tsx qa/scripts/qa-router.ts",
42
42
  "qa:probe": "tsx qa/scripts/qa-probe.ts",
43
+ "qa:reject-token": "tsx qa/scripts/qa-reject-token.ts",
43
44
  "qa:llm": "tsx qa/scripts/qa-llm.ts",
44
45
  "qa:agent": "tsx qa/scripts/qa-agent.ts",
45
46
  "qa:run": "tsx qa/scripts/bdd/run-tests.ts",