mcp-comfyui-proxy 0.0.0-stage → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +171 -2
- package/extension/bridge.js +305 -0
- package/extension/validation.js +133 -0
- package/package.json +46 -4
- package/src/adapter.js +25 -0
- package/src/backend.js +176 -0
- package/src/browser.js +156 -0
- package/src/cache-promise.js +46 -0
- package/src/cli-runner.js +31 -0
- package/src/cli.js +57 -0
- package/src/daemon.js +85 -0
- package/src/files.js +66 -0
- package/src/index.js +9 -0
- package/src/inject.js +74 -0
- package/src/log.js +41 -0
- package/src/mcp.js +97 -0
- package/src/nodes.js +55 -0
- package/src/ports.js +39 -0
- package/src/proxy.js +197 -0
- package/src/retry-promise.js +11 -0
- package/src/sessions.js +209 -0
- package/src/settings.js +12 -0
- package/src/stdio.js +16 -0
- package/src/tools.js +48 -0
- package/src/workflow.js +44 -0
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-comfyui-proxy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"src/",
|
|
8
|
+
"extension/"
|
|
9
|
+
],
|
|
10
|
+
"bin": {
|
|
11
|
+
"comfyui-mcp": "src/cli.js"
|
|
12
|
+
},
|
|
13
|
+
"description": "Local HTTP MCP with isolated ComfyUI reverse-proxy sessions",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/kucharskill/mcp-comfyui-proxy.git"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/kucharskill/mcp-comfyui-proxy#readme",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/kucharskill/mcp-comfyui-proxy/issues"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=24.12.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"start": "node src/index.js",
|
|
30
|
+
"start:stdio": "node src/stdio.js --local",
|
|
31
|
+
"cli": "node src/cli.js",
|
|
32
|
+
"test": "node --test test/*.test.js"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@modelcontextprotocol/client": "^2.4.0",
|
|
36
|
+
"@modelcontextprotocol/node": "^2.1.2",
|
|
37
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
38
|
+
"cross-spawn": "^7.0.6",
|
|
39
|
+
"http-proxy-middleware": "^4.2.1",
|
|
40
|
+
"httpxy": "^0.5.6",
|
|
41
|
+
"open": "^11.0.4",
|
|
42
|
+
"p-memoize": "^9.0.0",
|
|
43
|
+
"p-retry": "^9.0.0",
|
|
44
|
+
"tough-cookie": "^6.1.0",
|
|
45
|
+
"ws": "^8.22.2",
|
|
46
|
+
"zod": "^4.0.0"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/adapter.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/server';
|
|
2
|
+
import { serverInfo } from './settings.js';
|
|
3
|
+
|
|
4
|
+
/** @param {(args: string[], input?: unknown, signal?: AbortSignal) => Promise<unknown>} runCli */
|
|
5
|
+
export async function createAdapter(runCli) {
|
|
6
|
+
const mcp = new Server(serverInfo, { capabilities: { tools: { listChanged: true } } });
|
|
7
|
+
let previous;
|
|
8
|
+
const refresh = async (signal) => {
|
|
9
|
+
const manifest = await runCli(['--tool-manifest'], undefined, signal);
|
|
10
|
+
const current = JSON.stringify(manifest);
|
|
11
|
+
if (previous !== undefined && previous !== current) await mcp.sendToolListChanged();
|
|
12
|
+
previous = current;
|
|
13
|
+
return manifest;
|
|
14
|
+
};
|
|
15
|
+
await refresh();
|
|
16
|
+
mcp.setRequestHandler('tools/list', (_request, context) => refresh(context.mcpReq.signal));
|
|
17
|
+
mcp.setRequestHandler('tools/call', async (request, context) => {
|
|
18
|
+
try {
|
|
19
|
+
return await runCli(['--execute-tool', request.params.name], request.params.arguments ?? {}, context.mcpReq.signal);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : 'CLI_REQUEST_FAILED' }] };
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
return mcp;
|
|
25
|
+
}
|
package/src/backend.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import * as z from 'zod/v4';
|
|
2
|
+
import { workflowPath } from './workflow.js';
|
|
3
|
+
|
|
4
|
+
const jobSchema = z.object({
|
|
5
|
+
id: z.string(), status: z.string(), workflow_id: z.string().nullish(), priority: z.number().nullish(),
|
|
6
|
+
create_time: z.number().nullish(), execution_start_time: z.number().nullish(), execution_end_time: z.number().nullish(),
|
|
7
|
+
outputs_count: z.number().optional(),
|
|
8
|
+
execution_error: z.object({ exception_type: z.string().optional(), exception_message: z.string().optional(),
|
|
9
|
+
node_id: z.union([z.string(), z.number()]).optional(), node_type: z.string().optional() }).nullish(),
|
|
10
|
+
});
|
|
11
|
+
const jobsSchema = z.object({ jobs: z.array(jobSchema) });
|
|
12
|
+
/** @typedef {z.infer<typeof jobSchema>} Job */
|
|
13
|
+
|
|
14
|
+
const fileSchema = z.object({ filename: z.string().min(1), subfolder: z.string().default(''), type: z.enum(['input', 'output', 'temp']).default('output') });
|
|
15
|
+
|
|
16
|
+
/** @param {URL} url @param {string} [invalidResponse] @param {RequestInit} [options] @returns {Promise<unknown>} */
|
|
17
|
+
export async function readJson(url, invalidResponse = 'BACKEND_INVALID_JOBS_RESPONSE', options = {}) {
|
|
18
|
+
let response;
|
|
19
|
+
try { response = await fetch(url, { ...options, redirect: 'manual', signal: options.signal ?? AbortSignal.timeout(30_000) }); }
|
|
20
|
+
catch (cause) { throw new Error('BACKEND_UNREACHABLE', { cause }); }
|
|
21
|
+
if (!response.ok) { await response.body?.cancel(); throw new Error(`BACKEND_HTTP_${response.status}`); }
|
|
22
|
+
try { return await response.json(); }
|
|
23
|
+
catch { throw new Error(invalidResponse); }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {Error} error */
|
|
27
|
+
export function retryableBackendRead(error) {
|
|
28
|
+
if (/^BACKEND_HTTP_(408|429|500|502|503|504)$/.test(error.message)) return true;
|
|
29
|
+
return error.message === 'BACKEND_UNREACHABLE' && !(error.cause instanceof Error && error.cause.name === 'AbortError');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param {string} proxyUrl */
|
|
33
|
+
export async function backendInputsList(proxyUrl) {
|
|
34
|
+
const result = z.array(z.string()).safeParse(await readJson(
|
|
35
|
+
new URL('internal/files/input', proxyUrl), 'BACKEND_INVALID_INPUTS_RESPONSE'));
|
|
36
|
+
if (!result.success) throw new Error('BACKEND_INVALID_INPUTS_RESPONSE');
|
|
37
|
+
return { root_only: result.data.every(file => !/[\\/]/.test(file)), files: result.data };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** @param {string} proxyUrl */
|
|
41
|
+
export async function backendWorkflowList(proxyUrl) {
|
|
42
|
+
const url = new URL('userdata', proxyUrl);
|
|
43
|
+
url.search = new URLSearchParams({ dir: 'workflows', recurse: 'true', full_info: 'true' }).toString();
|
|
44
|
+
const result = z.array(z.object({ path: z.string(), size: z.number().nonnegative(), modified: z.number(), created: z.number().optional() })).safeParse(
|
|
45
|
+
await readJson(url, 'BACKEND_INVALID_WORKFLOW_LIST'));
|
|
46
|
+
if (!result.success) throw new Error('BACKEND_INVALID_WORKFLOW_LIST');
|
|
47
|
+
return { workflows: result.data.filter(file => /\.json$/i.test(file.path)).map(file => ({ ...file, path: workflowPath('workflows/' + file.path) })) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @param {string} proxyUrl @param {string} statuses */
|
|
51
|
+
async function jobs(proxyUrl, statuses) {
|
|
52
|
+
const url = new URL('api/jobs', proxyUrl);
|
|
53
|
+
url.searchParams.set('status', statuses);
|
|
54
|
+
url.searchParams.set('sort_by', 'created_at');
|
|
55
|
+
url.searchParams.set('sort_order', 'desc');
|
|
56
|
+
const result = jobsSchema.safeParse(await readJson(url));
|
|
57
|
+
if (!result.success) throw new Error('BACKEND_INVALID_JOBS_RESPONSE');
|
|
58
|
+
return result.data.jobs;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {string} proxyUrl @param {Job} job */
|
|
62
|
+
async function outputs(proxyUrl, job) {
|
|
63
|
+
if (!job.outputs_count) return { outputs: [] };
|
|
64
|
+
try {
|
|
65
|
+
const detail = z.object({ outputs: z.record(z.string(), z.unknown()) }).safeParse(
|
|
66
|
+
await readJson(new URL(`api/jobs/${encodeURIComponent(job.id)}`, proxyUrl)));
|
|
67
|
+
if (!detail.success) throw new Error('BACKEND_INVALID_JOB_OUTPUTS');
|
|
68
|
+
return { outputs: outputFiles(detail.data.outputs) };
|
|
69
|
+
} catch (error) {
|
|
70
|
+
return { outputs: [], outputs_error: error instanceof Error ? error.message : 'BACKEND_OUTPUTS_FAILED' };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @param {Record<string, unknown>} outputs */
|
|
75
|
+
function outputFiles(outputs) {
|
|
76
|
+
const files = [];
|
|
77
|
+
for (const node of Object.values(outputs)) {
|
|
78
|
+
if (!node || typeof node !== 'object' || Array.isArray(node)) continue;
|
|
79
|
+
for (const items of Object.values(node)) {
|
|
80
|
+
if (!Array.isArray(items)) continue;
|
|
81
|
+
for (const item of items) {
|
|
82
|
+
const file = fileSchema.safeParse(item);
|
|
83
|
+
if (!file.success) continue;
|
|
84
|
+
files.push({ ...file.data, path: [file.data.subfolder, file.data.filename].filter(Boolean).join('/') });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return files;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** @param {Job} job @param {number} now */
|
|
92
|
+
function summary(job, now) {
|
|
93
|
+
return {
|
|
94
|
+
prompt_id: job.id, workflow_uuid: job.workflow_id ?? null, status: job.status, priority: job.priority ?? null,
|
|
95
|
+
create_time: job.create_time ?? null, execution_start_time: job.execution_start_time ?? null,
|
|
96
|
+
execution_end_time: job.execution_end_time ?? null,
|
|
97
|
+
elapsed_seconds: job.execution_start_time == null ? null : Math.max(0, ((job.execution_end_time ?? now) - job.execution_start_time) / 1000),
|
|
98
|
+
error: job.execution_error ? { ...job.execution_error, exception_message: job.execution_error.exception_message?.slice(0, 1000) } : null,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param {string} proxyUrl @param {number} [now] */
|
|
103
|
+
export async function backendHistory(proxyUrl, now = Date.now()) {
|
|
104
|
+
const [active, history] = await Promise.all([
|
|
105
|
+
jobs(proxyUrl, 'pending,in_progress'), jobs(proxyUrl, 'completed,failed,cancelled'),
|
|
106
|
+
]);
|
|
107
|
+
const cutoff = now - 12 * 60 * 60 * 1000;
|
|
108
|
+
const recent = history.filter(job => (job.execution_end_time ?? -Infinity) >= cutoff);
|
|
109
|
+
const results = [];
|
|
110
|
+
// The list endpoint has only one preview. Fetch full file metadata in small batches.
|
|
111
|
+
for (let i = 0; i < recent.length; i += 8) {
|
|
112
|
+
results.push(...await Promise.all(recent.slice(i, i + 8).map(async job => ({
|
|
113
|
+
...summary(job, now), ...await outputs(proxyUrl, job),
|
|
114
|
+
}))));
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
checked_at: new Date(now).toISOString(), history_since: new Date(cutoff).toISOString(),
|
|
118
|
+
active: active.map(job => summary(job, now)),
|
|
119
|
+
recent: results,
|
|
120
|
+
undated_history_count: history.filter(job => job.execution_end_time == null).length,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const historyWindow = 12 * 60 * 60 * 1000;
|
|
125
|
+
const terminal = new Set(['completed', 'failed', 'cancelled']);
|
|
126
|
+
const detailSchema = jobSchema.extend({ outputs: z.record(z.string(), z.unknown()).default({}) });
|
|
127
|
+
|
|
128
|
+
// Only IDs accepted through this proxy belong to the session. No graph bodies are retained.
|
|
129
|
+
export class SessionJobs {
|
|
130
|
+
/** @private @type {Map<string, {acceptedAt: number, finished?: {job: Job, outputs: ReturnType<typeof outputFiles>}}>} */
|
|
131
|
+
entries = new Map();
|
|
132
|
+
/** @param {string} id */
|
|
133
|
+
track(id) {
|
|
134
|
+
if (!this.entries.has(id)) this.entries.set(id, { acceptedAt: Date.now() });
|
|
135
|
+
}
|
|
136
|
+
/** @param {string} proxyUrl @param {number} [now] */
|
|
137
|
+
async status(proxyUrl, now = Date.now()) {
|
|
138
|
+
const cutoff = now - historyWindow;
|
|
139
|
+
const active = [];
|
|
140
|
+
const recent = [];
|
|
141
|
+
const unavailable = [];
|
|
142
|
+
let undated = 0;
|
|
143
|
+
const entries = [...this.entries];
|
|
144
|
+
for (let i = 0; i < entries.length; i += 8) {
|
|
145
|
+
await Promise.all(entries.slice(i, i + 8).map(async ([id, entry]) => {
|
|
146
|
+
if (entry.finished && (entry.finished.job.execution_end_time ?? entry.acceptedAt) < cutoff) {
|
|
147
|
+
this.entries.delete(id); return;
|
|
148
|
+
}
|
|
149
|
+
let data = entry.finished;
|
|
150
|
+
if (!data) {
|
|
151
|
+
let raw;
|
|
152
|
+
try { raw = await readJson(new URL(`api/jobs/${encodeURIComponent(id)}`, proxyUrl)); }
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (!(error instanceof Error) || error.message !== 'BACKEND_HTTP_404') throw error;
|
|
155
|
+
if (entry.acceptedAt < cutoff) this.entries.delete(id);
|
|
156
|
+
else unavailable.push({ prompt_id: id, error: error.message });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const detail = detailSchema.safeParse(raw);
|
|
160
|
+
if (!detail.success || detail.data.id !== id) throw new Error('BACKEND_INVALID_JOBS_RESPONSE');
|
|
161
|
+
const { outputs, ...job } = detail.data;
|
|
162
|
+
data = { job, outputs: outputFiles(outputs) };
|
|
163
|
+
if (terminal.has(job.status)) entry.finished = data;
|
|
164
|
+
}
|
|
165
|
+
if (!terminal.has(data.job.status)) active.push(summary(data.job, now));
|
|
166
|
+
else if (data.job.execution_end_time == null) undated++;
|
|
167
|
+
else if (data.job.execution_end_time >= cutoff) recent.push({ ...summary(data.job, now), outputs: data.outputs });
|
|
168
|
+
else this.entries.delete(id);
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
active.sort((a, b) => (b.create_time ?? 0) - (a.create_time ?? 0));
|
|
172
|
+
recent.sort((a, b) => b.execution_end_time - a.execution_end_time);
|
|
173
|
+
return { checked_at: new Date(now).toISOString(), history_since: new Date(cutoff).toISOString(),
|
|
174
|
+
active, recent, undated_history_count: undated, unavailable };
|
|
175
|
+
}
|
|
176
|
+
}
|
package/src/browser.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
3
|
+
import * as z from 'zod/v4';
|
|
4
|
+
|
|
5
|
+
export const bridgePath = '/_comfy_mcp/ws';
|
|
6
|
+
const tabsSchema = z.array(z.object({ workflow_tab_id: z.string().min(1).max(100), name: z.string().max(1000),
|
|
7
|
+
active: z.boolean(), modified: z.boolean(), temporary: z.boolean(), path: z.string().max(4000).nullable().default(null), workflow_uuid: z.string().max(100).nullable().default(null) })).max(1000);
|
|
8
|
+
|
|
9
|
+
/** @typedef {z.infer<typeof tabsSchema>[number]} Tab */
|
|
10
|
+
/** @typedef {'read' | 'replace' | 'run' | 'save'} WorkflowMethod */
|
|
11
|
+
/** @typedef {{tab?: string, allowNewTab: boolean, resolve: (value: unknown) => void, reject: (error: Error) => void, timer: ReturnType<typeof setTimeout>}} Pending */
|
|
12
|
+
/** @typedef {{tabs: (Tab & {id: string})[], pending: Map<string, Pending>, alive: boolean, focus: number}} Connection */
|
|
13
|
+
|
|
14
|
+
export class BrowserBridge {
|
|
15
|
+
server = new WebSocketServer({ noServer: true, maxPayload: 32 * 1024 * 1024 });
|
|
16
|
+
/** @private @type {Map<WebSocket, Connection>} */
|
|
17
|
+
connections = new Map();
|
|
18
|
+
focusCounter = 0;
|
|
19
|
+
nextWorkflowId = 1;
|
|
20
|
+
/** @private @type {ReturnType<typeof setInterval>} */
|
|
21
|
+
heartbeat;
|
|
22
|
+
log;
|
|
23
|
+
timeout;
|
|
24
|
+
backendUrl;
|
|
25
|
+
idPrefix;
|
|
26
|
+
/** @param {import('./log.js').LogEvent} log @param {number} [timeout] @param {string} [backendUrl] @param {string} [idPrefix] */
|
|
27
|
+
constructor(log, timeout = 30_000, backendUrl, idPrefix = randomUUID().slice(0, 8)) {
|
|
28
|
+
this.log = log; this.timeout = timeout; this.backendUrl = backendUrl; this.idPrefix = idPrefix;
|
|
29
|
+
this.heartbeat = setInterval(() => {
|
|
30
|
+
for (const [socket, connection] of this.connections) {
|
|
31
|
+
if (!connection.alive) { socket.terminate(); continue; }
|
|
32
|
+
connection.alive = false; socket.ping();
|
|
33
|
+
}
|
|
34
|
+
}, 15_000);
|
|
35
|
+
this.heartbeat.unref();
|
|
36
|
+
}
|
|
37
|
+
/** @param {import('node:http').IncomingMessage} req @param {import('node:net').Socket} socket @param {Buffer} head @param {string} origin */
|
|
38
|
+
upgrade(req, socket, head, origin) {
|
|
39
|
+
if (req.headers.origin !== origin) { socket.destroy(); return; }
|
|
40
|
+
this.server.handleUpgrade(req, socket, head, ws => this.connect(ws));
|
|
41
|
+
}
|
|
42
|
+
/** @private @param {WebSocket} socket */
|
|
43
|
+
connect(socket) {
|
|
44
|
+
const connection = { tabs: [], pending: new Map(), alive: true, focus: 0 };
|
|
45
|
+
this.connections.set(socket, connection);
|
|
46
|
+
this.log('bridge.connected');
|
|
47
|
+
socket.on('pong', () => { connection.alive = true; });
|
|
48
|
+
socket.on('error', () => { this.log('bridge.error'); });
|
|
49
|
+
socket.on('close', () => {
|
|
50
|
+
this.connections.delete(socket);
|
|
51
|
+
for (const pending of connection.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('BROWSER_DISCONNECTED')); }
|
|
52
|
+
connection.pending.clear(); connection.tabs = [];
|
|
53
|
+
this.log('bridge.disconnected');
|
|
54
|
+
});
|
|
55
|
+
socket.on('message', data => {
|
|
56
|
+
try {
|
|
57
|
+
const message = JSON.parse(data.toString());
|
|
58
|
+
if (message.type === 'ping' && typeof message.id === 'string' && message.id.length > 0 && message.id.length <= 100) {
|
|
59
|
+
socket.send(JSON.stringify({ type: 'pong', id: message.id }));
|
|
60
|
+
} else if (message.type === 'tabs') {
|
|
61
|
+
const tabs = tabsSchema.parse(message.tabs);
|
|
62
|
+
if (new Set(tabs.map(t => t.workflow_tab_id)).size !== tabs.length) throw new Error('DUPLICATE_TAB');
|
|
63
|
+
connection.tabs = tabs.map(tab => ({ ...tab,
|
|
64
|
+
id: connection.tabs.find(t => t.workflow_tab_id === tab.workflow_tab_id)?.id ?? `${this.idPrefix}-w${this.nextWorkflowId++}` }));
|
|
65
|
+
for (const [id, pending] of connection.pending) if (pending.tab && !tabs.some(tab => tab.workflow_tab_id === pending.tab)) {
|
|
66
|
+
clearTimeout(pending.timer); connection.pending.delete(id); pending.reject(new Error('TAB_CLOSED'));
|
|
67
|
+
}
|
|
68
|
+
this.log('bridge.tabs', { count: tabs.length });
|
|
69
|
+
} else if (message.type === 'focus') {
|
|
70
|
+
connection.focus = ++this.focusCounter;
|
|
71
|
+
} else if (message.type === 'result') {
|
|
72
|
+
const pending = connection.pending.get(message.request_id);
|
|
73
|
+
if (!pending) return;
|
|
74
|
+
clearTimeout(pending.timer); connection.pending.delete(message.request_id);
|
|
75
|
+
const tab = message.result?.workflow_tab_id;
|
|
76
|
+
if (message.ok === true && typeof tab === 'string' && (tab === pending.tab ||
|
|
77
|
+
pending.allowNewTab && connection.tabs.some(t => t.workflow_tab_id === tab))) pending.resolve(message.result);
|
|
78
|
+
else pending.reject(new Error(typeof message.error?.code === 'string' && /^[A-Z_]+$/.test(message.error.code) ? message.error.code : 'BROWSER_OPERATION_FAILED'));
|
|
79
|
+
} else throw new Error('UNKNOWN_MESSAGE');
|
|
80
|
+
} catch { socket.close(1008, 'Invalid bridge message'); }
|
|
81
|
+
});
|
|
82
|
+
socket.send(JSON.stringify({ type: 'welcome', protocol: 1, backend_url: this.backendUrl }));
|
|
83
|
+
}
|
|
84
|
+
status() {
|
|
85
|
+
return { browser_connections: this.connections.size, workflows_opened: [...this.connections.values()].flatMap(c =>
|
|
86
|
+
c.tabs.map(({ workflow_tab_id: _internal, ...tab }) => tab)) };
|
|
87
|
+
}
|
|
88
|
+
/** @param {string} id */
|
|
89
|
+
hasWorkflow(id) {
|
|
90
|
+
return [...this.connections].some(([socket, c]) => socket.readyState === WebSocket.OPEN && c.tabs.some(t => t.id === id));
|
|
91
|
+
}
|
|
92
|
+
/** @param {string} path */
|
|
93
|
+
openedWorkflow(path) {
|
|
94
|
+
for (const [socket, connection] of this.connections) if (socket.readyState === WebSocket.OPEN) {
|
|
95
|
+
const found = connection.tabs.find(tab => !tab.temporary && tab.path === path);
|
|
96
|
+
if (found) return found.id;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
selectedPage() {
|
|
100
|
+
let selected;
|
|
101
|
+
for (const entry of this.connections) if (entry[0].readyState === WebSocket.OPEN && (!selected || entry[1].focus > selected[1].focus)) selected = entry;
|
|
102
|
+
if (!selected) throw new Error('BROWSER_NOT_CONNECTED');
|
|
103
|
+
return selected;
|
|
104
|
+
}
|
|
105
|
+
async newWorkflow() {
|
|
106
|
+
const [socket, connection] = this.selectedPage();
|
|
107
|
+
return this.send(socket, connection, undefined, 'new');
|
|
108
|
+
}
|
|
109
|
+
/** @param {string} path */
|
|
110
|
+
async openWorkflow(path) {
|
|
111
|
+
const [socket, connection] = this.selectedPage();
|
|
112
|
+
return this.send(socket, connection, undefined, 'open', { path });
|
|
113
|
+
}
|
|
114
|
+
/** @param {string} workflowId @param {WorkflowMethod} method @param {unknown} [workflow] @param {string} [name] */
|
|
115
|
+
request(workflowId, method, workflow, name) {
|
|
116
|
+
const found = [...this.connections].find(([socket, c]) => socket.readyState === WebSocket.OPEN && c.tabs.some(t => t.id === workflowId));
|
|
117
|
+
if (!found) return Promise.reject(new Error('WORKFLOW_NOT_FOUND'));
|
|
118
|
+
const [socket, connection] = found;
|
|
119
|
+
const tab = connection.tabs.find(t => t.id === workflowId).workflow_tab_id;
|
|
120
|
+
return this.send(socket, connection, tab, method, { workflow, name });
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* @private
|
|
124
|
+
* @param {WebSocket} socket
|
|
125
|
+
* @param {Connection} connection
|
|
126
|
+
* @param {string | undefined} tab
|
|
127
|
+
* @param {WorkflowMethod | 'new' | 'open'} method
|
|
128
|
+
* @param {{workflow?: unknown, name?: string, path?: string}} [params]
|
|
129
|
+
* @returns {Promise<unknown>}
|
|
130
|
+
*/
|
|
131
|
+
send(socket, connection, tab, method, params = {}) {
|
|
132
|
+
const id = randomUUID();
|
|
133
|
+
this.log('workflow.request', { request_id: id, method });
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
connection.pending.delete(id); this.log('workflow.timeout', { request_id: id, method });
|
|
137
|
+
reject(new Error('BROWSER_TIMEOUT_OUTCOME_UNKNOWN'));
|
|
138
|
+
}, this.timeout);
|
|
139
|
+
connection.pending.set(id, { tab, timer, allowNewTab: method === 'new' || method === 'save' || method === 'open', resolve: value => {
|
|
140
|
+
const { workflow_tab_id: internal, ...result } = value;
|
|
141
|
+
const workflowId = connection.tabs.find(t => t.workflow_tab_id === internal)?.id;
|
|
142
|
+
if (!workflowId) { reject(new Error('WORKFLOW_NOT_FOUND')); return; }
|
|
143
|
+
this.log(result.accepted === false || result.error ? 'workflow.rejected' : 'workflow.completed', { request_id: id, method }); resolve({ ...result, id: workflowId }); },
|
|
144
|
+
reject: error => { this.log('workflow.failed', { request_id: id, method, code: error.message }); reject(error); } });
|
|
145
|
+
socket.send(JSON.stringify({ type: 'request', request_id: id, workflow_tab_id: tab, method, ...params }));
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
close() {
|
|
149
|
+
clearInterval(this.heartbeat);
|
|
150
|
+
for (const [socket, connection] of this.connections) {
|
|
151
|
+
for (const pending of connection.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('BROWSER_DISCONNECTED')); }
|
|
152
|
+
connection.pending.clear(); socket.terminate();
|
|
153
|
+
}
|
|
154
|
+
this.connections.clear(); this.server.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import pMemoize, { pMemoizeClear } from 'p-memoize';
|
|
2
|
+
|
|
3
|
+
/** @typedef {(action: () => Promise<unknown>) => Promise<unknown>} Reader */
|
|
4
|
+
|
|
5
|
+
// One owner per backend session. No TTL, timers or process-wide session registry.
|
|
6
|
+
export class PromiseCache {
|
|
7
|
+
/** @private @type {Map<string, Map<string, Reader>>} */
|
|
8
|
+
groups = new Map();
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @template T
|
|
12
|
+
* @param {{group: string, key: string}} address
|
|
13
|
+
* @param {() => Promise<T>} action
|
|
14
|
+
* @returns {Promise<T>}
|
|
15
|
+
*/
|
|
16
|
+
cachePromise({ group, key }, action) {
|
|
17
|
+
let entries = this.groups.get(group);
|
|
18
|
+
if (!entries) { entries = new Map(); this.groups.set(group, entries); }
|
|
19
|
+
let read = entries.get(key);
|
|
20
|
+
if (!read) {
|
|
21
|
+
read = pMemoize(async (work) => work(), { cacheKey: () => key });
|
|
22
|
+
entries.set(key, read);
|
|
23
|
+
}
|
|
24
|
+
const current = read, currentEntries = entries;
|
|
25
|
+
return (read(action)).catch(error => {
|
|
26
|
+
if (currentEntries.get(key) === current) {
|
|
27
|
+
currentEntries.delete(key);
|
|
28
|
+
if (!currentEntries.size && this.groups.get(group) === currentEntries) this.groups.delete(group);
|
|
29
|
+
}
|
|
30
|
+
throw error;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {string} [group] @param {string} [key] */
|
|
35
|
+
clear(group, key) {
|
|
36
|
+
for (const [name, entries] of this.groups) {
|
|
37
|
+
if (group !== undefined && name !== group) continue;
|
|
38
|
+
for (const [entryKey, read] of entries) {
|
|
39
|
+
if (key !== undefined && entryKey !== key) continue;
|
|
40
|
+
// The library also prevents an older in-flight call from refilling the cache.
|
|
41
|
+
pMemoizeClear(read); entries.delete(entryKey);
|
|
42
|
+
}
|
|
43
|
+
if (!entries.size) this.groups.delete(name);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import spawn from 'cross-spawn';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { packageInfo } from './settings.js';
|
|
4
|
+
|
|
5
|
+
/** @param {{local?: boolean}} [options] */
|
|
6
|
+
export function createCliRunner({ local = false } = {}) {
|
|
7
|
+
const command = local ? process.execPath : 'npx';
|
|
8
|
+
const prefix = local ? [fileURLToPath(new URL('./cli.js', import.meta.url))]
|
|
9
|
+
: ['-y', '--prefer-online', `${packageInfo.name}@latest`];
|
|
10
|
+
/** @param {string[]} args @param {unknown} [input] @param {AbortSignal} [signal] */
|
|
11
|
+
return (args, input, signal) => new Promise((resolve, reject) => {
|
|
12
|
+
const child = spawn(command, [...prefix, ...args], { windowsHide: true, signal, timeout: 180_000, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
13
|
+
let stdout = '', stderr = '', bytes = 0;
|
|
14
|
+
const collect = (chunk, diagnostic) => {
|
|
15
|
+
bytes += Buffer.byteLength(chunk);
|
|
16
|
+
if (bytes > 8 * 1024 * 1024) { child.kill(); reject(new Error('CLI_RESPONSE_TOO_LARGE')); return; }
|
|
17
|
+
if (diagnostic) stderr += chunk; else stdout += chunk;
|
|
18
|
+
};
|
|
19
|
+
child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8');
|
|
20
|
+
child.stdout.on('data', chunk => collect(chunk, false));
|
|
21
|
+
child.stderr.on('data', chunk => collect(chunk, true));
|
|
22
|
+
child.once('error', reject);
|
|
23
|
+
child.once('close', (code, exitSignal) => {
|
|
24
|
+
if (code !== 0) { reject(new Error(`CLI_FAILED (${exitSignal ?? code}): ${stderr.trim().slice(-2000)}`)); return; }
|
|
25
|
+
try { resolve(JSON.parse(stdout)); }
|
|
26
|
+
catch { reject(new Error('CLI_INVALID_RESPONSE')); }
|
|
27
|
+
});
|
|
28
|
+
child.stdin.on('error', () => {});
|
|
29
|
+
child.stdin.end(input === undefined ? '' : JSON.stringify(input));
|
|
30
|
+
});
|
|
31
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { configuredPort, serverInfo } from './settings.js';
|
|
3
|
+
|
|
4
|
+
// Use the real SDK for both manifest generation and argument validation, offline.
|
|
5
|
+
/** @template T @param {(client: import('@modelcontextprotocol/client').Client) => Promise<T>} action @returns {Promise<T>} */
|
|
6
|
+
async function withTools(action) {
|
|
7
|
+
const [{ Client, InMemoryTransport }, { createToolServer }, { HttpBackend }] = await Promise.all([
|
|
8
|
+
import('@modelcontextprotocol/client'), import('./tools.js'), import('./daemon.js'),
|
|
9
|
+
]);
|
|
10
|
+
let backend;
|
|
11
|
+
const mcp = createToolServer(async (name, args, signal) => {
|
|
12
|
+
backend ??= new HttpBackend(configuredPort());
|
|
13
|
+
const client = await backend.getClient();
|
|
14
|
+
return client.callTool({ name, arguments: args }, { signal, timeout: 180_000 });
|
|
15
|
+
});
|
|
16
|
+
const client = new Client(serverInfo);
|
|
17
|
+
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
|
|
18
|
+
try {
|
|
19
|
+
await Promise.all([mcp.connect(serverTransport), client.connect(clientTransport)]);
|
|
20
|
+
return await action(client);
|
|
21
|
+
} finally {
|
|
22
|
+
await Promise.allSettled([client.close(), mcp.close(), backend?.close()]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const args = process.argv.slice(2);
|
|
27
|
+
const usage = 'Usage: comfyui-mcp [mcp [--local] | --tool-manifest | --execute-tool NAME | --version | --help]';
|
|
28
|
+
try {
|
|
29
|
+
if (!args.length || args[0] === 'mcp' || args[0] === '--local') {
|
|
30
|
+
await import('./stdio.js');
|
|
31
|
+
} else if (args[0] === '--tool-manifest' && args.length === 1) {
|
|
32
|
+
console.log(JSON.stringify(await withTools(client => client.listTools())));
|
|
33
|
+
} else if (args[0] === '--execute-tool' && args.length === 2) {
|
|
34
|
+
let result;
|
|
35
|
+
try {
|
|
36
|
+
let input = '';
|
|
37
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
38
|
+
let parameters;
|
|
39
|
+
try { parameters = JSON.parse(input); }
|
|
40
|
+
catch { throw new Error('CLI_INVALID_ARGUMENTS_JSON'); }
|
|
41
|
+
result = await withTools(client => client.callTool({ name: args[1], arguments: parameters }, { timeout: 180_000 }));
|
|
42
|
+
} catch (error) {
|
|
43
|
+
// The operation may have reached HTTP. Report it once; never retry it here.
|
|
44
|
+
result = { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : 'CLI_REQUEST_FAILED' }] };
|
|
45
|
+
}
|
|
46
|
+
console.log(JSON.stringify(result));
|
|
47
|
+
} else if (args[0] === '--version' && args.length === 1) {
|
|
48
|
+
console.log(serverInfo.version);
|
|
49
|
+
} else if (['--help', '-h'].includes(args[0]) && args.length === 1) {
|
|
50
|
+
console.log(usage);
|
|
51
|
+
} else {
|
|
52
|
+
throw new Error(usage);
|
|
53
|
+
}
|
|
54
|
+
} catch (error) {
|
|
55
|
+
console.error(error instanceof Error ? error.message : 'CLI_FAILED');
|
|
56
|
+
process.exitCode = 1;
|
|
57
|
+
}
|
package/src/daemon.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { open, mkdir } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
8
|
+
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
|
|
9
|
+
import { serverInfo, protocolVersion } from './settings.js';
|
|
10
|
+
|
|
11
|
+
/** @param {number} port */
|
|
12
|
+
export const daemonLogPath = (port) => join(tmpdir(), 'comfyui-mcp-runtime', `http-${port}.log`);
|
|
13
|
+
|
|
14
|
+
/** @param {number} port @returns {Promise<number | undefined>} */
|
|
15
|
+
async function health(port) {
|
|
16
|
+
let response;
|
|
17
|
+
try { response = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1000) }); }
|
|
18
|
+
catch (error) {
|
|
19
|
+
if ((error).cause?.code === 'ECONNREFUSED') return undefined;
|
|
20
|
+
throw new Error('HTTP_SERVER_UNRESPONSIVE');
|
|
21
|
+
}
|
|
22
|
+
const data = await response.json().catch(() => null);
|
|
23
|
+
if (!response.ok || data?.name !== serverInfo.name || data.protocol_version !== protocolVersion || !Number.isInteger(data.pid)) {
|
|
24
|
+
throw new Error('HTTP_SERVER_INCOMPATIBLE');
|
|
25
|
+
}
|
|
26
|
+
return data.pid;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {number} port */
|
|
30
|
+
async function ensureHttp(port) {
|
|
31
|
+
const running = await health(port);
|
|
32
|
+
if (running !== undefined) return running;
|
|
33
|
+
const logPath = daemonLogPath(port);
|
|
34
|
+
await mkdir(dirname(logPath), { recursive: true });
|
|
35
|
+
const log = await open(logPath, 'a');
|
|
36
|
+
const entry = fileURLToPath(new URL('./index.js', import.meta.url));
|
|
37
|
+
try {
|
|
38
|
+
const child = spawn(process.execPath, [entry], {
|
|
39
|
+
cwd: dirname(entry), env: { ...process.env, COMFY_MCP_PORT: String(port) },
|
|
40
|
+
detached: true, windowsHide: true, stdio: ['ignore', log.fd, log.fd],
|
|
41
|
+
});
|
|
42
|
+
await once(child, 'spawn');
|
|
43
|
+
child.unref();
|
|
44
|
+
} finally { await log.close(); }
|
|
45
|
+
// Concurrent launchers may race. The listening socket selects one HTTP process.
|
|
46
|
+
const deadline = Date.now() + 15_000;
|
|
47
|
+
while (Date.now() < deadline) {
|
|
48
|
+
const ready = await health(port);
|
|
49
|
+
if (ready !== undefined) return ready;
|
|
50
|
+
await delay(100);
|
|
51
|
+
}
|
|
52
|
+
throw new Error(`HTTP_START_FAILED: ${logPath}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class HttpBackend {
|
|
56
|
+
/** @private @type {{pid: number, client: Promise<Client>} | undefined} */
|
|
57
|
+
connection;
|
|
58
|
+
/** @private @type {Promise<Client> | undefined} */
|
|
59
|
+
starting;
|
|
60
|
+
port;
|
|
61
|
+
/** @param {number} port */
|
|
62
|
+
constructor(port) { this.port = port; }
|
|
63
|
+
async connect() {
|
|
64
|
+
const pid = await ensureHttp(this.port);
|
|
65
|
+
if (this.connection?.pid === pid) return this.connection.client;
|
|
66
|
+
await this.closeConnection();
|
|
67
|
+
const client = new Client(serverInfo);
|
|
68
|
+
const promise = client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${this.port}/mcp`)), { timeout: 10_000 })
|
|
69
|
+
.then(() => client).catch(async error => { await client.close(); if (this.connection === connection) this.connection = undefined; throw error; });
|
|
70
|
+
const connection = { pid, client: promise };
|
|
71
|
+
this.connection = connection;
|
|
72
|
+
client.onclose = () => { if (this.connection === connection) this.connection = undefined; };
|
|
73
|
+
return promise;
|
|
74
|
+
}
|
|
75
|
+
async getClient() {
|
|
76
|
+
if (!this.starting) this.starting = this.connect().finally(() => { this.starting = undefined; });
|
|
77
|
+
return this.starting;
|
|
78
|
+
}
|
|
79
|
+
async closeConnection() {
|
|
80
|
+
const connection = this.connection;
|
|
81
|
+
this.connection = undefined;
|
|
82
|
+
if (connection) await connection.client.then(client => client.close(), () => {});
|
|
83
|
+
}
|
|
84
|
+
async close() { await this.starting?.catch(() => {}); await this.closeConnection(); }
|
|
85
|
+
}
|