mcp-obs-studio-tools 0.1.2 → 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 +2 -1
- package/README.md +6 -2
- package/package.json +1 -1
- package/src/discovery-cache.js +24 -6
- package/src/discovery-store.js +68 -0
- package/src/runner.js +7 -4
package/.env.example
CHANGED
package/README.md
CHANGED
|
@@ -83,7 +83,9 @@ Sequences validate all commands before execution and stop on failure by default.
|
|
|
83
83
|
| `OBS_TIMEOUT_MS` | `15000`, per OBS operation |
|
|
84
84
|
| `OBS_WORKER_IDLE_MS` | `1800000`, retention after a completed tool call |
|
|
85
85
|
| `OBS_WORKER_DISCOVERY_IDLE_MS` | `60000`, retention after backend discovery |
|
|
86
|
-
| `OBS_DISCOVERY_CACHE_MS` | `
|
|
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 |
|
|
87
89
|
| `OBS_MCP_REQUEST_TIMEOUT_MS` | `180000`, MCP response deadline |
|
|
88
90
|
| `OBS_STATE_DIR` | Recording history; defaults to the system temporary directory under `obs-mcp` |
|
|
89
91
|
| `OBS_MCP_RUNNER` | `auto`, `local` or `latest` |
|
|
@@ -94,7 +96,9 @@ Outputs include JSON status/results, PNG screenshots and recording file paths. R
|
|
|
94
96
|
|
|
95
97
|
## Worker lifecycle
|
|
96
98
|
|
|
97
|
-
The wrapper serves
|
|
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.
|
|
98
102
|
|
|
99
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.
|
|
100
104
|
|
package/package.json
CHANGED
package/src/discovery-cache.js
CHANGED
|
@@ -1,18 +1,32 @@
|
|
|
1
1
|
import { diagnostic } from './diagnostics.js';
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/** Metadata cache. Shared-store hits never contact or keep alive a worker.
|
|
4
4
|
* @template T
|
|
5
|
-
* @param {{load: () => Promise<T>, context: () => string, ttlMs: number, log?: typeof diagnostic, now?: () => number}} options
|
|
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
6
|
*/
|
|
7
|
-
export function createDiscoveryCache({ load, context, ttlMs, log = diagnostic, now = Date.now }) {
|
|
7
|
+
export function createDiscoveryCache({ load, context, ttlMs, store, log = diagnostic, now = Date.now }) {
|
|
8
8
|
/** @type {{key: string, until: number, value: T}|undefined} */
|
|
9
9
|
let entry;
|
|
10
10
|
/** @type {{key: string, promise: Promise<T>}|undefined} */
|
|
11
11
|
let pending;
|
|
12
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
|
+
};
|
|
13
20
|
return {
|
|
14
21
|
async get() {
|
|
15
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
|
+
}
|
|
16
30
|
if (entry?.key === key && now() < entry.until) {
|
|
17
31
|
log({ role: 'wrapper', method: 'tools/list', cache: 'hit' });
|
|
18
32
|
return structuredClone(entry.value);
|
|
@@ -21,14 +35,18 @@ export function createDiscoveryCache({ load, context, ttlMs, log = diagnostic, n
|
|
|
21
35
|
if (pending?.key === key) return structuredClone(await pending.promise);
|
|
22
36
|
const startedGeneration = generation;
|
|
23
37
|
/** @type {{key: string, promise: Promise<T>}} */
|
|
24
|
-
const current = { key, promise: Promise.resolve().then(load).then(value => {
|
|
25
|
-
if (generation === startedGeneration && context() === key)
|
|
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
|
+
}
|
|
26
44
|
return value;
|
|
27
45
|
}).finally(() => { if (pending === current) pending = undefined; }) };
|
|
28
46
|
pending = current;
|
|
29
47
|
return structuredClone(await current.promise);
|
|
30
48
|
},
|
|
31
|
-
invalidate() { entry = undefined; generation++; },
|
|
49
|
+
async invalidate() { entry = undefined; generation++; if (store) await persist(() => store.remove()); },
|
|
32
50
|
peek: () => entry?.value,
|
|
33
51
|
};
|
|
34
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/runner.js
CHANGED
|
@@ -6,6 +6,7 @@ import { readFileSync, readdirSync } from 'node:fs';
|
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
7
|
import { z } from 'zod';
|
|
8
8
|
import { createDiscoveryCache } from './discovery-cache.js';
|
|
9
|
+
import { createDiscoveryStore, discoveryKey } from './discovery-store.js';
|
|
9
10
|
import { loadEnvironment } from './config.js';
|
|
10
11
|
import { diagnostic } from './diagnostics.js';
|
|
11
12
|
|
|
@@ -28,7 +29,7 @@ export function createRunner(packageName, env = process.env) {
|
|
|
28
29
|
// Resolve this once at adapter startup, not separately in child processes.
|
|
29
30
|
const configured = loadEnvironment(env);
|
|
30
31
|
const mode = runnerMode(configured);
|
|
31
|
-
const cacheMs = z.coerce.number().int().min(0).max(86400000).parse(configured.OBS_DISCOVERY_CACHE_MS ??
|
|
32
|
+
const cacheMs = z.coerce.number().int().min(0).max(86400000).parse(configured.OBS_DISCOVERY_CACHE_MS ?? 600000);
|
|
32
33
|
const requestMs = z.coerce.number().int().min(20).max(86400000).parse(configured.OBS_MCP_REQUEST_TIMEOUT_MS ?? 180000);
|
|
33
34
|
const command = mode === 'latest' ? 'npx' : process.execPath;
|
|
34
35
|
const args = mode === 'latest' ? ['-y', '--prefer-online', `${packageName}@latest`, '--worker'] : [fileURLToPath(new URL('./cli.js', import.meta.url)), '--worker'];
|
|
@@ -59,11 +60,11 @@ export function createRunner(packageName, env = process.env) {
|
|
|
59
60
|
await current.ready;
|
|
60
61
|
if (closed || connection !== current) throw new Error('Worker disconnected before the operation was sent. Retry the request.');
|
|
61
62
|
const previous = cache.peek();
|
|
62
|
-
if (previous && JSON.stringify(previous.serverInfo) !== JSON.stringify(current.client.getServerVersion())) cache.invalidate();
|
|
63
|
+
if (previous && JSON.stringify(previous.serverInfo) !== JSON.stringify(current.client.getServerVersion())) await cache.invalidate();
|
|
63
64
|
return current.client;
|
|
64
65
|
}
|
|
65
66
|
const context = () => {
|
|
66
|
-
const hash = createHash('sha256')
|
|
67
|
+
const hash = createHash('sha256');
|
|
67
68
|
// File contents are hashed locally; secrets and fingerprints are never logged.
|
|
68
69
|
const paths = [childEnv.OBS_ENV_FILE];
|
|
69
70
|
if (mode === 'local') {
|
|
@@ -79,7 +80,9 @@ export function createRunner(packageName, env = process.env) {
|
|
|
79
80
|
}
|
|
80
81
|
return hash.digest('hex');
|
|
81
82
|
};
|
|
82
|
-
const
|
|
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 () => {
|
|
83
86
|
const client = await getClient();
|
|
84
87
|
const result = await client.listTools({}, { timeout: requestMs });
|
|
85
88
|
return { protocol: 1, serverInfo: client.getServerVersion(), tools: result.tools };
|