mcp-obs-studio-tools 0.1.1 → 0.1.3

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/.env.example CHANGED
@@ -5,3 +5,7 @@ OBS_PASSWORD=
5
5
  # OBS_STATE_DIR=E:/obs-mcp-state
6
6
  # OBS_MCP_RUNNER=auto
7
7
  # OBS_WORKER_IDLE_MS=1800000
8
+ # OBS_WORKER_DISCOVERY_IDLE_MS=60000
9
+ # OBS_DISCOVERY_CACHE_MS=600000
10
+ # OBS_DISCOVERY_CACHE_EXCLUDE_ENV=TRACE_ID
11
+ # OBS_MCP_REQUEST_TIMEOUT_MS=180000
package/README.md CHANGED
@@ -81,7 +81,12 @@ Sequences validate all commands before execution and stop on failure by default.
81
81
  | `OBS_ENV_FILE` | `.env` in the startup working directory |
82
82
  | `OBS_EXECUTABLE` | Detected or configured absolute OBS executable path |
83
83
  | `OBS_TIMEOUT_MS` | `15000`, per OBS operation |
84
- | `OBS_WORKER_IDLE_MS` | `1800000`, worker idle interval |
84
+ | `OBS_WORKER_IDLE_MS` | `1800000`, retention after a completed tool call |
85
+ | `OBS_WORKER_DISCOVERY_IDLE_MS` | `60000`, retention after backend discovery |
86
+ | `OBS_DISCOVERY_CACHE_MS` | `600000`, shared discovery cache lifetime; `0` disables it |
87
+ | `OBS_DISCOVERY_CACHE_DIR` | System temporary directory under `obs-mcp/discovery` |
88
+ | `OBS_DISCOVERY_CACHE_EXCLUDE_ENV` | Comma-separated additional environment names excluded from the cache key; `CODEX_TOOL_CALL_ID` is always excluded |
89
+ | `OBS_MCP_REQUEST_TIMEOUT_MS` | `180000`, MCP response deadline |
85
90
  | `OBS_STATE_DIR` | Recording history; defaults to the system temporary directory under `obs-mcp` |
86
91
  | `OBS_MCP_RUNNER` | `auto`, `local` or `latest` |
87
92
 
@@ -91,7 +96,13 @@ Outputs include JSON status/results, PNG screenshots and recording file paths. R
91
96
 
92
97
  ## Worker lifecycle
93
98
 
94
- The stdio wrapper starts a worker on demand and reuses its MCP stdio connection. The worker exits itself after 30 minutes of inactivity; active requests suspend its idle timer. The next request starts another worker. OBS continues running independently.
99
+ The wrapper serves discovery from a shared file cache in the user's temporary directory, including initialization in another wrapper and discovery after worker expiry. Cache hits preserve the original expiry and leave the worker lifecycle untouched. The cache key hashes the target command, arguments, working directory and sorted environment, with case-insensitive environment names on Windows. Exclusions affect only the key; the full environment reaches the worker. Files contain tool metadata and hashed context fingerprints, with atomic writes and a default lifetime of 10 minutes. Cache age, changes to the selected env file or local source files, tool-list notifications and detected backend identity changes trigger a metadata refresh. Ordinary tool results are executed live.
100
+
101
+ Legacy MCP ping receives a local response from the wrapper's SDK handler. Modern MCP uses its negotiated protocol without adding the removed ping RPC. Initialization and discovery negotiate capabilities through the SDK; cached records contain tool definitions and server identity, independent of client sessions.
102
+
103
+ The worker owns one active-request counter, one expiry deadline and one idle timer. Backend discovery retains it for 1 minute; completed tool calls retain it for 30 minutes. Each completion extends the deadline using the greater of its current value and the new retention window, so discovery preserves any longer tool-call deadline. Active requests suspend expiry until their application work settles, including cancellation cleanup. The worker exits itself at the deadline, and the next backend operation starts another. OBS continues running independently.
104
+
105
+ MCP response deadlines limit client waiting separately from worker activity. Lifecycle diagnostics on stderr report methods, cache hits/misses, activity, expiry and close reasons. Set `OBS_MCP_DIAGNOSTICS=0` in the launching environment to disable diagnostics.
95
106
 
96
107
  An npx wrapper starts workers through `npx ...@latest`, resolving updates at each worker startup. Direct Node.js or installed-binary launches use the same local installation. The wrapper passes through the selected env-file path. Updating the wrapper itself takes effect when its MCP connection restarts.
97
108
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-obs-studio-tools",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "OBS Studio CLI and transparent stdio MCP adapter",
5
5
  "repository": {
6
6
  "type": "git",
package/src/config.js CHANGED
@@ -57,8 +57,9 @@ export async function saveEnvValues(values, env = process.env) {
57
57
  }
58
58
 
59
59
  /** Load configuration per invocation so a running adapter sees file changes. */
60
- export function loadEnvironment() {
61
- const env = { ...process.env };
60
+ /** @param {NodeJS.ProcessEnv} [source] */
61
+ export function loadEnvironment(source = process.env) {
62
+ const env = { ...source };
62
63
  const loaded = dotenv.config({ path: envFilePath(env), processEnv: env, quiet: true });
63
64
  if (loaded.error && /** @type {NodeJS.ErrnoException} */ (loaded.error).code !== 'ENOENT') throw loaded.error;
64
65
  return env;
@@ -72,9 +73,11 @@ export function config() {
72
73
  return { url: url.href, password: env.OBS_PASSWORD || undefined, executable: env.OBS_EXECUTABLE, stateDir: env.OBS_STATE_DIR, timeout };
73
74
  }
74
75
 
75
- /** Worker-owned idle deadline, independent of operation duration. */
76
- export function workerIdleMs() {
77
- return z.coerce.number().int().min(20).max(86400000).parse(loadEnvironment().OBS_WORKER_IDLE_MS ?? 1800000);
76
+ /** Worker-owned retention windows, independent of client response deadlines. */
77
+ export function workerRetention() {
78
+ const env = loadEnvironment();
79
+ const duration = z.coerce.number().int().min(20).max(86400000);
80
+ return { callMs: duration.parse(env.OBS_WORKER_IDLE_MS ?? 1800000), discoveryMs: duration.parse(env.OBS_WORKER_DISCOVERY_IDLE_MS ?? 60000) };
78
81
  }
79
82
 
80
83
  /** Apply and persist only supplied connection settings. Configuration merging is shared by callers.
@@ -0,0 +1,6 @@
1
+ /** Lifecycle diagnostics contain transport state only, never arguments or configuration values.
2
+ * @param {Record<string, unknown>} event
3
+ */
4
+ export function diagnostic(event) {
5
+ if (process.env.OBS_MCP_DIAGNOSTICS !== '0') console.error(JSON.stringify({ component: 'obs-mcp', time: new Date().toISOString(), pid: process.pid, ...event }));
6
+ }
@@ -0,0 +1,52 @@
1
+ import { diagnostic } from './diagnostics.js';
2
+
3
+ /** Metadata cache. Shared-store hits never contact or keep alive a worker.
4
+ * @template T
5
+ * @param {{load: () => Promise<T>, context: () => string, ttlMs: number, store?: {read: (context: string) => Promise<any>, write: (entry: {key: string, until: number, value: T}) => Promise<void>, remove: () => Promise<void>}, log?: typeof diagnostic, now?: () => number}} options
6
+ */
7
+ export function createDiscoveryCache({ load, context, ttlMs, store, log = diagnostic, now = Date.now }) {
8
+ /** @type {{key: string, until: number, value: T}|undefined} */
9
+ let entry;
10
+ /** @type {{key: string, promise: Promise<T>}|undefined} */
11
+ let pending;
12
+ let generation = 0;
13
+ let persistence = Promise.resolve();
14
+ /** Serialize local writes/removals so an invalidated in-flight refresh cannot restore stale metadata.
15
+ * @param {() => Promise<void>} action */
16
+ const persist = (action) => {
17
+ persistence = persistence.then(action).catch(() => { log({ role: 'wrapper', method: 'tools/list', reason: 'cache-storage-unavailable' }); });
18
+ return persistence;
19
+ };
20
+ return {
21
+ async get() {
22
+ const key = context();
23
+ if (store) {
24
+ await persistence;
25
+ const readingGeneration = generation;
26
+ // Read through on every lookup so invalidation by another replica is visible.
27
+ const record = await store.read(key);
28
+ entry = record && generation === readingGeneration ? { key, until: record.until, value: record.value } : undefined;
29
+ }
30
+ if (entry?.key === key && now() < entry.until) {
31
+ log({ role: 'wrapper', method: 'tools/list', cache: 'hit' });
32
+ return structuredClone(entry.value);
33
+ }
34
+ log({ role: 'wrapper', method: 'tools/list', cache: 'miss' });
35
+ if (pending?.key === key) return structuredClone(await pending.promise);
36
+ const startedGeneration = generation;
37
+ /** @type {{key: string, promise: Promise<T>}} */
38
+ const current = { key, promise: Promise.resolve().then(load).then(async value => {
39
+ if (generation === startedGeneration && context() === key) {
40
+ entry = { key, until: now() + ttlMs, value: structuredClone(value) };
41
+ const completed = entry;
42
+ if (store && ttlMs > 0) await persist(async () => { if (generation === startedGeneration) await store.write(completed); });
43
+ }
44
+ return value;
45
+ }).finally(() => { if (pending === current) pending = undefined; }) };
46
+ pending = current;
47
+ return structuredClone(await current.promise);
48
+ },
49
+ async invalidate() { entry = undefined; generation++; if (store) await persist(() => store.remove()); },
50
+ peek: () => entry?.value,
51
+ };
52
+ }
@@ -0,0 +1,68 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+ import lockfile from 'proper-lockfile';
6
+ import writeFileAtomic from 'write-file-atomic';
7
+ import { z } from 'zod';
8
+
9
+ const manifestSchema = z.object({
10
+ protocol: z.literal(1),
11
+ serverInfo: z.object({ name: z.string(), version: z.string() }).passthrough(),
12
+ tools: z.array(z.object({ name: z.string(), inputSchema: z.object({ type: z.literal('object') }).passthrough() }).passthrough()),
13
+ });
14
+ const recordSchema = z.object({
15
+ format: z.literal(1), key: z.string(), context: z.string(),
16
+ createdAt: z.number().finite(), expiresAt: z.number().finite(), value: manifestSchema,
17
+ });
18
+
19
+ /** Hash only the target invocation. Exclusions never change the environment sent to it.
20
+ * @param {{command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, exclude?: string[], platform?: string}} invocation
21
+ */
22
+ export function discoveryKey({ command, args, cwd, env, exclude = [], platform = process.platform }) {
23
+ const normalize = (/** @type {string} */ name) => platform === 'win32' ? name.toUpperCase() : name;
24
+ const excluded = new Set(['CODEX_TOOL_CALL_ID', ...exclude].map(normalize));
25
+ const canonical = new Map();
26
+ for (const [name, value] of Object.entries(env)) if (value !== undefined && !excluded.has(normalize(name))) canonical.set(normalize(name), value);
27
+ const entries = [...canonical.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
28
+ return createHash('sha256').update(JSON.stringify([command, args, cwd, entries])).digest('hex');
29
+ }
30
+
31
+ /** Shared metadata only; keys and freshness fingerprints contain no readable environment.
32
+ * Atomic replacement plus a per-key write lock protects concurrent writers/removers.
33
+ * @param {{key: string, directory?: string, ttlMs: number, now?: () => number}} options
34
+ */
35
+ export function createDiscoveryStore({ key, directory = join(tmpdir(), 'obs-mcp', 'discovery'), ttlMs, now = Date.now }) {
36
+ if (!/^[a-f0-9]{64}$/.test(key)) throw new Error('Invalid discovery cache key');
37
+ const path = join(directory, `${key}.json`);
38
+ /** @param {() => Promise<void>} action */
39
+ async function mutate(action) {
40
+ await mkdir(directory, { recursive: true, mode: 0o700 });
41
+ const release = await lockfile.lock(path, { realpath: false, retries: { retries: 20, minTimeout: 10, maxTimeout: 100 } });
42
+ try { await action(); } finally { await release(); }
43
+ }
44
+ return {
45
+ path,
46
+ /** @param {string} context */
47
+ async read(context) {
48
+ try {
49
+ const bytes = await readFile(path, 'utf8');
50
+ if (bytes.length > 8 * 1024 * 1024) return undefined;
51
+ const parsed = recordSchema.safeParse(JSON.parse(bytes));
52
+ if (!parsed.success) return undefined;
53
+ const record = parsed.data;
54
+ if (record.key !== key || record.context !== context || record.createdAt > now() || record.expiresAt <= now() || record.expiresAt > record.createdAt + ttlMs) return undefined;
55
+ return { ...record, until: record.expiresAt };
56
+ } catch { return undefined; }
57
+ },
58
+ /** @param {{key: string, until: number, value: any}} entry */
59
+ async write(entry) {
60
+ const value = manifestSchema.parse(entry.value);
61
+ await mutate(() => {
62
+ const createdAt = now();
63
+ return writeFileAtomic(path, JSON.stringify({ format: 1, key, context: entry.key, createdAt, expiresAt: createdAt + ttlMs, value }), { mode: 0o600 });
64
+ });
65
+ },
66
+ async remove() { await mutate(() => rm(path, { force: true })); },
67
+ };
68
+ }
package/src/idle.js ADDED
@@ -0,0 +1,49 @@
1
+ import { diagnostic } from './diagnostics.js';
2
+
3
+ /** One worker-owned counter, deadline and timer for all backend requests.
4
+ * @param {{discoveryMs: number, callMs: number, close: (reason: string) => void|Promise<void>, log?: typeof diagnostic, now?: () => number}} options
5
+ */
6
+ export function createIdleLifecycle({ discoveryMs, callMs, close, log = diagnostic, now = Date.now }) {
7
+ let active = 0;
8
+ let expiresAt = now() + discoveryMs;
9
+ let closing = false;
10
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
11
+ let timer;
12
+ /** @param {string} method @param {string} reason */
13
+ const report = (method, reason) => log({ role: 'worker', method, active, expiresAt, reason });
14
+ const arm = () => {
15
+ clearTimeout(timer);
16
+ if (!closing && active === 0) timer = setTimeout(() => {
17
+ if (active !== 0 || closing) return;
18
+ if (now() < expiresAt) { arm(); return; }
19
+ closing = true;
20
+ report('lifecycle', 'idle-expired');
21
+ void close('idle-expired');
22
+ }, Math.max(0, expiresAt - now()));
23
+ };
24
+ arm();
25
+ return {
26
+ /** @template T @param {'tools/list'|'tools/call'} method @param {() => T|Promise<T>} action */
27
+ async during(method, action) {
28
+ if (closing) throw new Error('Worker is shutting down');
29
+ active++;
30
+ clearTimeout(timer);
31
+ report(method, 'request-start');
32
+ try { return await action(); }
33
+ finally {
34
+ active--;
35
+ expiresAt = Math.max(expiresAt, now() + (method === 'tools/list' ? discoveryMs : callMs));
36
+ report(method, 'request-complete');
37
+ arm();
38
+ }
39
+ },
40
+ snapshot: () => ({ active, expiresAt, closing }),
41
+ /** @param {string} reason */
42
+ stop(reason) {
43
+ clearTimeout(timer);
44
+ const alreadyClosing = closing;
45
+ closing = true;
46
+ if (!alreadyClosing) report('lifecycle', reason);
47
+ },
48
+ };
49
+ }
package/src/obs.js CHANGED
@@ -31,11 +31,29 @@ export function connectionFailure(error, hasPassword = Boolean(config().password
31
31
  /** @template T @param {(obs: OBSWebSocket, settings: ReturnType<typeof config>) => Promise<T>} action @param {AbortSignal} [signal] @param {ReturnType<typeof config>} [settings] */
32
32
  export async function withObs(action, signal, settings = config()) {
33
33
  const obs = new OBSWebSocket();
34
+ // The library leaves pending call() promises unresolved on socket closure.
35
+ // Settle our request wrappers on disconnect while still awaiting actual local
36
+ // application cleanup below, rather than releasing worker activity on timeout.
37
+ const disconnected = new Promise((_, reject) => {
38
+ obs.once('ConnectionClosed', () => reject(new Error('OBS WebSocket disconnected; the request may already have taken effect. Check status before retrying.')));
39
+ });
40
+ void disconnected.catch(() => {});
41
+ const requests = new Proxy(obs, { get(target, property) {
42
+ const value = Reflect.get(target, property);
43
+ if (property === 'call' || property === 'callBatch') {
44
+ /** @param {...unknown} args */
45
+ const call = (...args) => Promise.race([Reflect.apply(value, target, args), disconnected]);
46
+ return call;
47
+ }
48
+ return typeof value === 'function' ? value.bind(target) : value;
49
+ } });
34
50
  const abort = () => { void obs.disconnect().catch(() => {}); };
35
51
  const timeout = AbortSignal.timeout(settings.timeout);
36
52
  const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
37
53
  /** @type {(() => void)|undefined} */
38
54
  let removeReject;
55
+ /** @type {Promise<T>|undefined} */
56
+ let operation;
39
57
  const cancelled = new Promise((_, reject) => {
40
58
  const handler = () => { abort(); reject(new Error('OBS operation cancelled or timed out; it may already have taken effect. Check obs_status before retrying.')); };
41
59
  combined.addEventListener('abort', handler, { once: true });
@@ -43,14 +61,18 @@ export async function withObs(action, signal, settings = config()) {
43
61
  });
44
62
  try {
45
63
  combined.throwIfAborted();
46
- return await Promise.race([(async () => {
64
+ operation = (async () => {
47
65
  await obs.connect(settings.url, settings.password, { rpcVersion: 1, eventSubscriptions: 0 });
48
66
  combined.throwIfAborted();
49
- return action(obs, settings);
50
- })(), cancelled]);
67
+ return action(requests, settings);
68
+ })();
69
+ return await Promise.race([operation, cancelled]);
51
70
  } finally {
52
71
  removeReject?.();
53
72
  await obs.disconnect().catch(() => {});
73
+ // A client timeout/cancellation is not completion. Keep the handler active
74
+ // until its application work has settled after the socket is disconnected.
75
+ await operation?.catch(() => {});
54
76
  }
55
77
  }
56
78
 
package/src/runner.js CHANGED
@@ -2,6 +2,13 @@ import { Client } from '@modelcontextprotocol/client';
2
2
  import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { resolve } from 'node:path';
5
+ import { readFileSync, readdirSync } from 'node:fs';
6
+ import { createHash } from 'node:crypto';
7
+ import { z } from 'zod';
8
+ import { createDiscoveryCache } from './discovery-cache.js';
9
+ import { createDiscoveryStore, discoveryKey } from './discovery-store.js';
10
+ import { loadEnvironment } from './config.js';
11
+ import { diagnostic } from './diagnostics.js';
5
12
 
6
13
  /** Detect npm exec/npx using npm's execution metadata, never just an inherited PATH entry.
7
14
  * Direct node/bin and npm run launches use the installed CLI. Explicit override is available.
@@ -20,7 +27,10 @@ export function runnerMode(env = process.env) {
20
27
  */
21
28
  export function createRunner(packageName, env = process.env) {
22
29
  // Resolve this once at adapter startup, not separately in child processes.
23
- const mode = runnerMode(env);
30
+ const configured = loadEnvironment(env);
31
+ const mode = runnerMode(configured);
32
+ const cacheMs = z.coerce.number().int().min(0).max(86400000).parse(configured.OBS_DISCOVERY_CACHE_MS ?? 600000);
33
+ const requestMs = z.coerce.number().int().min(20).max(86400000).parse(configured.OBS_MCP_REQUEST_TIMEOUT_MS ?? 180000);
24
34
  const command = mode === 'latest' ? 'npx' : process.execPath;
25
35
  const args = mode === 'latest' ? ['-y', '--prefer-online', `${packageName}@latest`, '--worker'] : [fileURLToPath(new URL('./cli.js', import.meta.url)), '--worker'];
26
36
  const childEnv = Object.fromEntries(Object.entries({ ...env, OBS_ENV_FILE: resolve(env.OBS_ENV_FILE ?? '.env') }).filter((entry) => entry[1] !== undefined));
@@ -34,7 +44,12 @@ export function createRunner(packageName, env = process.env) {
34
44
  const client = new Client({ name: `${packageName}-adapter`, version: '1.0.0' });
35
45
  const current = { client, transport, ready: Promise.resolve() };
36
46
  connection = current;
37
- client.onclose = () => { if (connection === current) connection = undefined; };
47
+ client.onclose = () => {
48
+ if (connection === current) connection = undefined;
49
+ diagnostic({ role: 'wrapper', method: 'lifecycle', reason: 'worker-disconnected' });
50
+ };
51
+ client.setNotificationHandler('notifications/tools/list_changed', () => cache.invalidate());
52
+ diagnostic({ role: 'wrapper', method: 'lifecycle', reason: 'worker-start', mode });
38
53
  current.ready = client.connect(transport, { timeout: 180000 }).catch(async error => {
39
54
  if (connection === current) connection = undefined;
40
55
  await client.close().catch(() => {});
@@ -44,18 +59,49 @@ export function createRunner(packageName, env = process.env) {
44
59
  const current = connection;
45
60
  await current.ready;
46
61
  if (closed || connection !== current) throw new Error('Worker disconnected before the operation was sent. Retry the request.');
62
+ const previous = cache.peek();
63
+ if (previous && JSON.stringify(previous.serverInfo) !== JSON.stringify(current.client.getServerVersion())) await cache.invalidate();
47
64
  return current.client;
48
65
  }
66
+ const context = () => {
67
+ const hash = createHash('sha256');
68
+ // File contents are hashed locally; secrets and fingerprints are never logged.
69
+ const paths = [childEnv.OBS_ENV_FILE];
70
+ if (mode === 'local') {
71
+ const src = fileURLToPath(new URL('.', import.meta.url));
72
+ paths.push(...readdirSync(src).filter(name => name.endsWith('.js')).sort().map(name => resolve(src, name)), fileURLToPath(new URL('../package.json', import.meta.url)), fileURLToPath(new URL('../data/protocol.json', import.meta.url)));
73
+ }
74
+ for (const path of paths) {
75
+ hash.update(String(path));
76
+ try { hash.update(readFileSync(path)); } catch (error) {
77
+ if (/** @type {NodeJS.ErrnoException} */ (error).code !== 'ENOENT') throw error;
78
+ hash.update('missing');
79
+ }
80
+ }
81
+ return hash.digest('hex');
82
+ };
83
+ const key = discoveryKey({ command, args, cwd: process.cwd(), env: childEnv, exclude: configured.OBS_DISCOVERY_CACHE_EXCLUDE_ENV?.split(',').map(name => name.trim()).filter(Boolean) });
84
+ const store = createDiscoveryStore({ key, ttlMs: cacheMs, directory: configured.OBS_DISCOVERY_CACHE_DIR });
85
+ const cache = createDiscoveryCache({ ttlMs: cacheMs, context, store, load: async () => {
86
+ const client = await getClient();
87
+ const result = await client.listTools({}, { timeout: requestMs });
88
+ return { protocol: 1, serverInfo: client.getServerVersion(), tools: result.tools };
89
+ } });
49
90
  /** @param {string[]} options @param {unknown} [input] @param {AbortSignal} [signal] */
50
91
  const run = async (options, input, signal) => {
51
92
  signal?.throwIfAborted();
93
+ if (closed) throw new Error('MCP runner is closed');
94
+ if (options[0] === '--tool-manifest' && options.length === 1) {
95
+ const result = await cache.get();
96
+ signal?.throwIfAborted();
97
+ return result;
98
+ }
52
99
  const client = await getClient();
53
100
  signal?.throwIfAborted();
54
- if (options[0] === '--tool-manifest' && options.length === 1) {
55
- const result = await client.listTools({}, { signal, timeout: 180000 });
56
- return { protocol: 1, serverInfo: client.getServerVersion(), tools: result.tools };
101
+ if (options[0] === '--execute-tool' && options.length === 2) {
102
+ diagnostic({ role: 'wrapper', method: 'tools/call', cache: 'bypass' });
103
+ return client.callTool({ name: options[1], arguments: /** @type {Record<string, unknown>} */ (input ?? {}) }, { signal, timeout: requestMs });
57
104
  }
58
- if (options[0] === '--execute-tool' && options.length === 2) return client.callTool({ name: options[1], arguments: /** @type {Record<string, unknown>} */ (input ?? {}) }, { signal, timeout: 180000 });
59
105
  throw new Error('Unsupported CLI operation');
60
106
  };
61
107
  // Only wrapper shutdown closes this side. Request timeouts do not kill workers.
package/src/worker.js CHANGED
@@ -2,44 +2,30 @@ import { Server } from '@modelcontextprotocol/server';
2
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
3
  import { manifest, executeTool } from './tools.js';
4
4
  import { serverInfo } from './package.js';
5
- import { workerIdleMs } from './config.js';
5
+ import { workerRetention } from './config.js';
6
+ import { createIdleLifecycle } from './idle.js';
6
7
 
7
8
  /** Self-expiring stdio server using the same application methods as the CLI. */
8
9
  export function startWorker() {
9
- const idleMs = workerIdleMs();
10
- let active = 0;
11
10
  let closing = false;
12
- /** @type {ReturnType<typeof setTimeout>|undefined} */
13
- let timer;
14
11
  /** @type {ReturnType<typeof serveStdio>|undefined} */
15
12
  let handle;
16
- const close = async () => {
13
+ /** @param {string} reason */
14
+ const close = async reason => {
17
15
  if (closing) return;
18
16
  closing = true;
19
- clearTimeout(timer);
17
+ lifecycle.stop(reason);
20
18
  await handle?.close();
21
19
  process.exit(0);
22
20
  };
23
- const arm = () => {
24
- clearTimeout(timer);
25
- if (!closing && active === 0) timer = setTimeout(() => { void close(); }, idleMs);
26
- };
27
- /** @template T @param {() => Promise<T>|T} action */
28
- const during = async action => {
29
- if (closing) throw new Error('Worker is shutting down');
30
- active++;
31
- clearTimeout(timer);
32
- try { return await action(); }
33
- finally { active--; arm(); }
34
- };
21
+ const lifecycle = createIdleLifecycle({ ...workerRetention(), close });
35
22
  handle = serveStdio(() => {
36
23
  const server = new Server(serverInfo, { capabilities: { tools: {} } });
37
- server.setRequestHandler('tools/list', () => during(() => ({ tools: manifest().tools })));
38
- server.setRequestHandler('tools/call', (request, context) => during(() => executeTool(request.params.name, request.params.arguments ?? {}, context.mcpReq.signal)));
24
+ server.setRequestHandler('tools/list', () => lifecycle.during('tools/list', () => ({ tools: manifest().tools })));
25
+ server.setRequestHandler('tools/call', (request, context) => lifecycle.during('tools/call', () => executeTool(request.params.name, request.params.arguments ?? {}, context.mcpReq.signal)));
39
26
  return server;
40
27
  });
41
- process.stdin.once('end', () => { void close(); });
42
- process.once('SIGINT', () => { void close(); });
43
- process.once('SIGTERM', () => { void close(); });
44
- arm();
28
+ process.stdin.once('end', () => { void close('stdin-ended'); });
29
+ process.once('SIGINT', () => { void close('SIGINT'); });
30
+ process.once('SIGTERM', () => { void close('SIGTERM'); });
45
31
  }