mcp-comfyui-proxy 0.0.0-stage → 0.3.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 +169 -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/src/files.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { constants, createWriteStream, openAsBlob } from 'node:fs';
|
|
4
|
+
import { copyFile, stat, unlink } from 'node:fs/promises';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import * as z from 'zod/v4';
|
|
8
|
+
import { readJson } from './backend.js';
|
|
9
|
+
|
|
10
|
+
/** @typedef {'input' | 'output' | 'temp'} BackendFileType */
|
|
11
|
+
|
|
12
|
+
/** @param {string} value */
|
|
13
|
+
function relativePath(value) {
|
|
14
|
+
const normalized = value.replace(/\\/g, '/');
|
|
15
|
+
if (!normalized || normalized.startsWith('/') || /^[a-z]:/i.test(normalized)
|
|
16
|
+
|| normalized.includes('\0') || normalized.split('/').some(part => part === '..' || part === '.')) {
|
|
17
|
+
throw new Error('INVALID_BACKEND_PATH');
|
|
18
|
+
}
|
|
19
|
+
return normalized.replace(/\/+$/g, '');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {string} value */
|
|
23
|
+
function filename(value) {
|
|
24
|
+
const name = relativePath(value);
|
|
25
|
+
if (name.includes('/')) throw new Error('INVALID_BACKEND_FILENAME');
|
|
26
|
+
return name;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {string} proxyUrl @param {string} file @param {string} [name] */
|
|
30
|
+
export async function backendUpload(proxyUrl, file, name) {
|
|
31
|
+
if (!path.isAbsolute(file)) throw new Error('ABSOLUTE_LOCAL_FILE_REQUIRED');
|
|
32
|
+
const requestedName = filename(name ?? path.basename(file));
|
|
33
|
+
const info = await stat(file);
|
|
34
|
+
if (!info.isFile()) throw new Error('LOCAL_FILE_REQUIRED');
|
|
35
|
+
const body = new FormData();
|
|
36
|
+
body.append('image', await openAsBlob(file), requestedName);
|
|
37
|
+
body.append('type', 'input');
|
|
38
|
+
// Omit overwrite: the backend resolves collisions and reuses identical files.
|
|
39
|
+
const uploaded = z.object({ name: z.string().min(1), subfolder: z.literal(''), type: z.literal('input') }).safeParse(
|
|
40
|
+
await readJson(new URL('upload/image', proxyUrl), 'BACKEND_INVALID_UPLOAD_RESPONSE', {
|
|
41
|
+
method: 'POST', body, signal: AbortSignal.timeout(120_000),
|
|
42
|
+
}));
|
|
43
|
+
if (!uploaded.success) throw new Error('BACKEND_INVALID_UPLOAD_RESPONSE');
|
|
44
|
+
const actualName = filename(uploaded.data.name);
|
|
45
|
+
return { file, path: actualName, type: uploaded.data.type, bytes: info.size };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @param {string} proxyUrl @param {string} remotePath @param {string} file @param {BackendFileType} [type] */
|
|
49
|
+
export async function backendDownload(proxyUrl, remotePath, file, type = 'input') {
|
|
50
|
+
if (!path.isAbsolute(file)) throw new Error('ABSOLUTE_LOCAL_FILE_REQUIRED');
|
|
51
|
+
const normalized = relativePath(remotePath);
|
|
52
|
+
const split = normalized.lastIndexOf('/');
|
|
53
|
+
const url = new URL('view', proxyUrl);
|
|
54
|
+
url.search = new URLSearchParams({ type, filename: normalized.slice(split + 1), subfolder: split < 0 ? '' : normalized.slice(0, split) }).toString();
|
|
55
|
+
let response;
|
|
56
|
+
try { response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(120_000) }); }
|
|
57
|
+
catch { throw new Error('BACKEND_UNREACHABLE'); }
|
|
58
|
+
if (!response.ok) { await response.body?.cancel(); throw new Error(`BACKEND_HTTP_${response.status}`); }
|
|
59
|
+
if (!response.body) throw new Error('BACKEND_EMPTY_RESPONSE');
|
|
60
|
+
const temp = `${file}.mcp-${randomUUID()}.tmp`;
|
|
61
|
+
try {
|
|
62
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(temp, { flags: 'wx' }));
|
|
63
|
+
await copyFile(temp, file, constants.COPYFILE_EXCL);
|
|
64
|
+
return { file, path: normalized, type, bytes: (await stat(temp)).size };
|
|
65
|
+
} finally { await unlink(temp).catch(() => {}); }
|
|
66
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { startMcp } from './mcp.js';
|
|
2
|
+
import { configuredPort } from './settings.js';
|
|
3
|
+
|
|
4
|
+
const app = await startMcp(configuredPort());
|
|
5
|
+
console.log(`ComfyUI MCP: ${app.url}`);
|
|
6
|
+
void app.closed.then(() => process.exit(0));
|
|
7
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
8
|
+
process.once(signal, () => { void app.close().then(() => process.exit(0)); });
|
|
9
|
+
}
|
package/src/inject.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { responseInterceptor } from 'http-proxy-middleware';
|
|
3
|
+
import { describeUrl } from './log.js';
|
|
4
|
+
|
|
5
|
+
export const scriptPath = '/_comfy_mcp/bridge.js';
|
|
6
|
+
export const validationPath = '/_comfy_mcp/validation.js';
|
|
7
|
+
|
|
8
|
+
/** @param {import('node:http').IncomingMessage} req @param {import('node:http').ServerResponse} res @param {import('./log.js').LogEvent} log */
|
|
9
|
+
export async function serveScript(req, res, log) {
|
|
10
|
+
if (!['GET', 'HEAD'].includes(req.method ?? '')) { res.writeHead(405, { Allow: 'GET, HEAD' }).end(); return; }
|
|
11
|
+
try {
|
|
12
|
+
const filename = new URL(req.url ?? '/', 'http://local').pathname === validationPath ? 'validation.js' : 'bridge.js';
|
|
13
|
+
const source = await readFile(new URL(`../extension/${filename}`, import.meta.url));
|
|
14
|
+
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Length': source.length });
|
|
15
|
+
res.end(req.method === 'HEAD' ? undefined : source);
|
|
16
|
+
log('inject.script_served');
|
|
17
|
+
} catch {
|
|
18
|
+
log('inject.script_error');
|
|
19
|
+
res.writeHead(500).end('Script unavailable');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @param {ReturnType<import('httpxy').createProxyServer>} proxy @param {import('./log.js').LogEvent} log @param {(id: string) => void} [onPrompt] */
|
|
24
|
+
export function attachInjection(proxy, log, onPrompt = () => {}) {
|
|
25
|
+
const intercepted = new WeakMap();
|
|
26
|
+
// proxyReq exposes this request's options. Select interception after seeing headers,
|
|
27
|
+
// before httpxy's response handler runs; non-HTML responses keep normal streaming.
|
|
28
|
+
proxy.on('proxyReq', (outgoing, req, _res, options) => {
|
|
29
|
+
if (req.headers.accept?.includes('text/html')) {
|
|
30
|
+
outgoing.removeHeader('if-none-match');
|
|
31
|
+
outgoing.removeHeader('if-modified-since');
|
|
32
|
+
}
|
|
33
|
+
outgoing.prependOnceListener('response', response => {
|
|
34
|
+
const type = response.headers['content-type'] ?? '';
|
|
35
|
+
const pathname = new URL(req.url ?? '/', 'http://local').pathname;
|
|
36
|
+
if (req.method === 'POST' && /^\/(api\/)?prompt\/?$/.test(pathname) && response.statusCode === 200 && /^application\/json\b/i.test(type)) {
|
|
37
|
+
options.selfHandleResponse = true;
|
|
38
|
+
intercepted.set(response, 'prompt');
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (req.method !== 'GET' || response.statusCode !== 200 || !/^text\/html\b/i.test(type)) return;
|
|
42
|
+
if (/charset\s*=\s*['"]?(?!utf-?8\b|us-ascii\b)[\w-]+/i.test(type)) {
|
|
43
|
+
log('inject.skipped', { ...describeUrl(req.url ?? '/'), reason: 'UNSUPPORTED_CHARSET' });
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
options.selfHandleResponse = true;
|
|
47
|
+
intercepted.set(response, 'html');
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
const intercept = responseInterceptor(async (buffer, response, req, res) => {
|
|
51
|
+
if (intercepted.get(response) === 'prompt') {
|
|
52
|
+
try {
|
|
53
|
+
const result = JSON.parse(buffer.toString('utf8'));
|
|
54
|
+
if (typeof result.prompt_id === 'string' && result.prompt_id.length > 0) onPrompt(result.prompt_id);
|
|
55
|
+
} catch { log('prompt.capture_error'); }
|
|
56
|
+
return buffer;
|
|
57
|
+
}
|
|
58
|
+
const html = buffer.toString('utf8');
|
|
59
|
+
const tag = `<script type="module" src="${scriptPath}"></script>`;
|
|
60
|
+
const end = html.toLowerCase().lastIndexOf('</body>');
|
|
61
|
+
const result = end < 0 ? html + tag : html.slice(0, end) + tag + html.slice(end);
|
|
62
|
+
for (const header of ['etag', 'last-modified', 'accept-ranges', 'content-md5', 'digest', 'content-digest', 'repr-digest']) res.removeHeader(header);
|
|
63
|
+
res.setHeader('cache-control', 'no-store');
|
|
64
|
+
log('html.injected', { ...describeUrl(req.url ?? '/'), csp_present: Boolean(response.headers['content-security-policy'] || /http-equiv\s*=\s*["']content-security-policy["']/i.test(html)) });
|
|
65
|
+
return result;
|
|
66
|
+
});
|
|
67
|
+
proxy.on('proxyRes', (response, req, res) => {
|
|
68
|
+
if (intercepted.has(response)) void intercept(response, req, res).catch(() => {
|
|
69
|
+
log('response.interception_error', describeUrl(req.url ?? '/'));
|
|
70
|
+
if (!res.headersSent) res.writeHead(502);
|
|
71
|
+
res.end('Response interception failed');
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
}
|
package/src/log.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { mkdir, open } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { finished } from 'node:stream/promises';
|
|
5
|
+
|
|
6
|
+
/** @typedef {(event: string, data?: Record<string, unknown>) => void} LogEvent */
|
|
7
|
+
|
|
8
|
+
/** @param {string} id */
|
|
9
|
+
export function sessionLogPath(id) {
|
|
10
|
+
if (!/^[a-f0-9]{8}$/.test(id)) throw new Error('INVALID_SESSION_ID');
|
|
11
|
+
return join(tmpdir(), 'comfyui-mcp', `${id}.jsonl`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param {string} id */
|
|
15
|
+
export async function createSessionLog(id) {
|
|
16
|
+
const path = sessionLogPath(id);
|
|
17
|
+
await mkdir(join(tmpdir(), 'comfyui-mcp'), { recursive: true });
|
|
18
|
+
const file = await open(path, 'wx');
|
|
19
|
+
const stream = file.createWriteStream();
|
|
20
|
+
let failed = false;
|
|
21
|
+
stream.on('error', () => { failed = true; });
|
|
22
|
+
/** @type {LogEvent} */
|
|
23
|
+
const write = (event, data = {}) => {
|
|
24
|
+
if (!failed && !stream.writableEnded) stream.write(JSON.stringify({ time: new Date().toISOString(), event, ...data }) + '\n');
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
path, write,
|
|
28
|
+
flush: async () => {
|
|
29
|
+
if (failed) throw new Error('LOG_WRITE_FAILED');
|
|
30
|
+
await new Promise((resolve, reject) => stream.write('', error => error ? reject(new Error('LOG_WRITE_FAILED')) : resolve()));
|
|
31
|
+
},
|
|
32
|
+
close: async () => { stream.end(); await finished(stream).catch(() => {}); },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Values of query parameters may contain credentials; only their names are useful here.
|
|
37
|
+
/** @param {string} input */
|
|
38
|
+
export function describeUrl(input) {
|
|
39
|
+
const url = new URL(input, 'http://local');
|
|
40
|
+
return { path: url.pathname, query_keys: [...new Set(url.searchParams.keys())] };
|
|
41
|
+
}
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { NodeStreamableHTTPServerTransport, localhostHostValidation, localhostOriginValidation } from '@modelcontextprotocol/node';
|
|
3
|
+
import { Sessions } from './sessions.js';
|
|
4
|
+
import { workflowResultSchema, runResultSchema, summary, readWorkflow, writeWorkflow } from './workflow.js';
|
|
5
|
+
import { createToolServer } from './tools.js';
|
|
6
|
+
import { serverInfo, protocolVersion } from './settings.js';
|
|
7
|
+
|
|
8
|
+
/** @param {Sessions} sessions @param {() => void} [activity] */
|
|
9
|
+
export function createMcp(sessions, activity = () => {}) {
|
|
10
|
+
const result = async (action) => {
|
|
11
|
+
try {
|
|
12
|
+
const data = await action();
|
|
13
|
+
return { ...(data && typeof data === 'object' && ('error' in data || 'accepted' in data && data.accepted === false) ? { isError: true } : {}),
|
|
14
|
+
content: [{ type: 'text', text: JSON.stringify(data) }] };
|
|
15
|
+
}
|
|
16
|
+
catch (error) { return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : 'REQUEST_FAILED' }] }; }
|
|
17
|
+
};
|
|
18
|
+
/** @type {import('./tools.js').ToolHandlers} */
|
|
19
|
+
const handlers = {
|
|
20
|
+
connect: ({ url }) => result(() => sessions.connect(url)),
|
|
21
|
+
status: ({ session_id }) => result(() => sessions.status(session_id)),
|
|
22
|
+
backend_status: ({ session_id }) => result(() => sessions.backendStatus(session_id)),
|
|
23
|
+
backend_history: ({ session_id }) => result(() => sessions.backendHistory(session_id)),
|
|
24
|
+
backend_node_info: ({ session_id, ...args }) => result(() => sessions.backendNodeInfo(session_id, args)),
|
|
25
|
+
backend_inputs_list: ({ session_id }) => result(() => sessions.backendInputsList(session_id)),
|
|
26
|
+
backend_workflow_list: args => result(() => sessions.backendWorkflowList(args.session_id)),
|
|
27
|
+
backend_upload: args => result(() => sessions.backendUpload(args.session_id, args.file, args.name)),
|
|
28
|
+
backend_download: args => result(() => sessions.backendDownload(args.session_id, args.path, args.file, args.type)),
|
|
29
|
+
disconnect: ({ session_id }) => result(() => sessions.disconnect(session_id)),
|
|
30
|
+
workflow_open: args => result(() => sessions.workflowOpen(args.session_id, args.path)),
|
|
31
|
+
workflow_new: args => result(() => sessions.workflowNew(args.session_id)),
|
|
32
|
+
workflow_save: args => result(() => sessions.workflowRequest(args.id, 'save', undefined, args.name)),
|
|
33
|
+
run: args => result(async () =>
|
|
34
|
+
runResultSchema.parse(await sessions.workflowRequest(args.id, 'run'))),
|
|
35
|
+
workflow_download: args => result(async () => {
|
|
36
|
+
const data = workflowResultSchema.parse(await sessions.workflowRequest(args.id, 'read'));
|
|
37
|
+
await writeWorkflow(args.file, data.workflow, args.overwrite);
|
|
38
|
+
return { ...summary(data), file: args.file };
|
|
39
|
+
}),
|
|
40
|
+
workflow_upload: args => result(async () => {
|
|
41
|
+
const workflow = await readWorkflow(args.file);
|
|
42
|
+
const data = await sessions.workflowRequest(args.id, 'replace', workflow);
|
|
43
|
+
if (data && typeof data === 'object' && 'error' in data) return data;
|
|
44
|
+
return summary(workflowResultSchema.parse(data));
|
|
45
|
+
}),
|
|
46
|
+
};
|
|
47
|
+
return createToolServer(async (name, args) => {
|
|
48
|
+
activity();
|
|
49
|
+
try { return await handlers[name](args); }
|
|
50
|
+
finally { activity(); }
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param {number} [port] @param {Sessions} [sessions] @param {number} [idleMs] */
|
|
55
|
+
export async function startMcp(port = 37861, sessions = new Sessions(), idleMs = 30 * 60 * 1000) {
|
|
56
|
+
let timer;
|
|
57
|
+
let closing;
|
|
58
|
+
let finish;
|
|
59
|
+
const closed = new Promise(resolve => { finish = resolve; });
|
|
60
|
+
const activity = () => {
|
|
61
|
+
if (closing) return;
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
timer = setTimeout(() => { void close().catch(error => console.error('Idle shutdown failed:', error)); }, idleMs);
|
|
64
|
+
timer.unref();
|
|
65
|
+
};
|
|
66
|
+
sessions.onActivity = activity;
|
|
67
|
+
const validateHost = localhostHostValidation();
|
|
68
|
+
const validateOrigin = localhostOriginValidation();
|
|
69
|
+
const server = createServer(async (req, res) => {
|
|
70
|
+
if (!validateHost(req, res) || !validateOrigin(req, res)) return;
|
|
71
|
+
if (req.url === '/health' && req.method === 'GET') {
|
|
72
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
73
|
+
res.end(JSON.stringify({ ...serverInfo, protocol_version: protocolVersion, pid: process.pid }));
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (req.url !== '/mcp') { res.writeHead(404).end(); return; }
|
|
77
|
+
const mcp = createMcp(sessions, activity);
|
|
78
|
+
const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
79
|
+
res.once('close', () => { void mcp.close(); });
|
|
80
|
+
try { await mcp.connect(transport); await transport.handleRequest(req, res); }
|
|
81
|
+
catch { if (!res.headersSent) res.writeHead(500); res.end(); }
|
|
82
|
+
});
|
|
83
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
|
|
84
|
+
const address = server.address();
|
|
85
|
+
if (!address || typeof address === 'string') throw new Error('MCP_LISTEN_FAILED');
|
|
86
|
+
function close() {
|
|
87
|
+
return closing ??= (async () => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
await sessions.close();
|
|
90
|
+
server.closeAllConnections();
|
|
91
|
+
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
92
|
+
finish();
|
|
93
|
+
})();
|
|
94
|
+
}
|
|
95
|
+
activity();
|
|
96
|
+
return { url: `http://127.0.0.1:${address.port}/mcp`, close, closed };
|
|
97
|
+
}
|
package/src/nodes.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import * as z from 'zod/v4';
|
|
2
|
+
import { readJson, retryableBackendRead } from './backend.js';
|
|
3
|
+
import { retryPromise } from './retry-promise.js';
|
|
4
|
+
|
|
5
|
+
const nodeSchema = z.object({
|
|
6
|
+
input: z.record(z.string(), z.unknown()), output: z.array(z.unknown()),
|
|
7
|
+
display_name: z.string().nullish(), category: z.string().nullish(), description: z.string().nullish(),
|
|
8
|
+
search_aliases: z.array(z.string()).nullish(),
|
|
9
|
+
}).passthrough();
|
|
10
|
+
const catalogSchema = z.record(z.string(), nodeSchema);
|
|
11
|
+
|
|
12
|
+
export const nodeInfoArgs = z.strictObject({
|
|
13
|
+
node_type: z.string().trim().min(1).max(300).refine(name => name !== '.' && name !== '..', 'Use a node type from search results').optional()
|
|
14
|
+
.describe('Exact backend class name from a workflow node.type or a search result. Returns its native definition, including input_order and input choice lists such as available models. Reads the dedicated object_info endpoint on the first lookup; later lookups use this session cache.'),
|
|
15
|
+
query: z.string().trim().max(200).optional()
|
|
16
|
+
.describe('Search words in class name, display name, category, description and aliases. Case-insensitive; all words must match. Omit to browse node types. Cannot be combined with node_type.'),
|
|
17
|
+
offset: z.number().int().nonnegative().default(0).describe('Search offset; use next_offset from the previous search result.'),
|
|
18
|
+
limit: z.number().int().min(1).max(100).default(30).describe('Maximum search results, default 30. Exact node definitions are returned in full.'),
|
|
19
|
+
}).refine(args => !args.node_type || args.query === undefined && args.offset === 0 && args.limit === 30,
|
|
20
|
+
'node_type cannot be combined with query or search pagination');
|
|
21
|
+
|
|
22
|
+
/** @typedef {z.output<typeof nodeInfoArgs>} NodeInfoArgs */
|
|
23
|
+
|
|
24
|
+
/** @param {string} proxyUrl @param {NodeInfoArgs} args @param {import('./cache-promise.js').PromiseCache} cache */
|
|
25
|
+
export async function backendNodeInfo(proxyUrl, args, cache) {
|
|
26
|
+
const path = args.node_type ? `object_info/${encodeURIComponent(args.node_type)}` : 'object_info';
|
|
27
|
+
const url = new URL(path, proxyUrl);
|
|
28
|
+
let catalog;
|
|
29
|
+
try {
|
|
30
|
+
catalog = await cache.cachePromise({ group: 'nodes', key: url.href }, async () => {
|
|
31
|
+
const raw = await retryPromise({ retries: 2, minTimeout: 250, maxTimeout: 1000,
|
|
32
|
+
shouldRetry: ({ error }) => retryableBackendRead(error) }, () => readJson(url, 'BACKEND_INVALID_NODE_INFO'));
|
|
33
|
+
const result = catalogSchema.safeParse(raw);
|
|
34
|
+
if (!result.success) throw new Error('BACKEND_INVALID_NODE_INFO');
|
|
35
|
+
if (args.node_type && !Object.hasOwn(result.data, args.node_type)) throw new Error('NODE_TYPE_NOT_FOUND');
|
|
36
|
+
return result.data;
|
|
37
|
+
});
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (error instanceof Error && error.message === 'NODE_TYPE_NOT_FOUND') return { error: error.message, node_type: args.node_type };
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
if (args.node_type) {
|
|
43
|
+
return { node_type: args.node_type, definition: catalog[args.node_type] };
|
|
44
|
+
}
|
|
45
|
+
const words = (args.query ?? '').toLowerCase().split(/\s+/).filter(Boolean);
|
|
46
|
+
const matches = Object.entries(catalog).filter(([type, node]) => {
|
|
47
|
+
const text = [type, node.display_name, node.category, node.description, ...(node.search_aliases ?? [])].join(' ').toLowerCase();
|
|
48
|
+
return words.every(word => text.includes(word));
|
|
49
|
+
}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
50
|
+
const end = args.offset + args.limit;
|
|
51
|
+
return { query: args.query ?? '', total: matches.length, offset: args.offset, next_offset: end < matches.length ? end : null,
|
|
52
|
+
nodes: matches.slice(args.offset, end).map(([node_type, node]) => ({ node_type,
|
|
53
|
+
display_name: node.display_name ?? node_type, category: node.category ?? '', description: (node.description ?? '').slice(0, 300),
|
|
54
|
+
})) };
|
|
55
|
+
}
|
package/src/ports.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const portPreferencesFile = join(tmpdir(), 'comfyui-mcp', 'proxy-ports.json');
|
|
6
|
+
/** @param {URL} url */
|
|
7
|
+
const key = (url) => `${url.hostname}:${url.port || (url.protocol === 'https:' ? 443 : 80)}`;
|
|
8
|
+
|
|
9
|
+
export class PortPreferences {
|
|
10
|
+
/** @private @type {Record<string, number> | undefined} */
|
|
11
|
+
ports;
|
|
12
|
+
file;
|
|
13
|
+
/** @param {string | null} [file] */
|
|
14
|
+
constructor(file = portPreferencesFile) { this.file = file; }
|
|
15
|
+
async load() {
|
|
16
|
+
if (this.ports) return this.ports;
|
|
17
|
+
let ports;
|
|
18
|
+
try { ports = this.file ? JSON.parse(await readFile(this.file, 'utf8')) : {}; }
|
|
19
|
+
catch (error) { if ((error).code !== 'ENOENT') throw error; ports = {}; }
|
|
20
|
+
if (!ports || typeof ports !== 'object' || Array.isArray(ports)) throw new Error('INVALID_PORT_PREFERENCES');
|
|
21
|
+
this.ports = ports;
|
|
22
|
+
return this.ports;
|
|
23
|
+
}
|
|
24
|
+
/** @param {URL} url */
|
|
25
|
+
async get(url) {
|
|
26
|
+
const port = (await this.load())[key(url)];
|
|
27
|
+
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined;
|
|
28
|
+
}
|
|
29
|
+
/** @param {URL} url @param {number} port */
|
|
30
|
+
async remember(url, port) {
|
|
31
|
+
if (await this.get(url)) return;
|
|
32
|
+
const ports = await this.load();
|
|
33
|
+
ports[key(url)] = port;
|
|
34
|
+
if (this.file) {
|
|
35
|
+
await mkdir(dirname(this.file), { recursive: true });
|
|
36
|
+
await writeFile(this.file, JSON.stringify(ports, null, 2) + '\n');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/proxy.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { createServer, ServerResponse } from 'node:http';
|
|
2
|
+
import { createProxyServer } from 'httpxy';
|
|
3
|
+
import { Cookie, CookieJar } from 'tough-cookie';
|
|
4
|
+
import { describeUrl } from './log.js';
|
|
5
|
+
import { attachInjection, scriptPath, validationPath, serveScript } from './inject.js';
|
|
6
|
+
import { BrowserBridge, bridgePath } from './browser.js';
|
|
7
|
+
import { SessionJobs } from './backend.js';
|
|
8
|
+
import { PromiseCache } from './cache-promise.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {URL} target
|
|
12
|
+
* @param {string[]} [initialCookies]
|
|
13
|
+
* @param {import('./log.js').LogEvent} [log]
|
|
14
|
+
* @param {number} [preferredPort]
|
|
15
|
+
* @param {{sessionId?: string, activity?: () => void}} [options]
|
|
16
|
+
*/
|
|
17
|
+
export async function createSessionProxy(target, initialCookies = [], log = () => {}, preferredPort,
|
|
18
|
+
options = {}) {
|
|
19
|
+
const jar = new CookieJar();
|
|
20
|
+
const promiseCache = new PromiseCache();
|
|
21
|
+
const browser = new BrowserBridge(log, 30_000, target.origin + target.pathname, options.sessionId);
|
|
22
|
+
const jobs = new SessionJobs();
|
|
23
|
+
const sockets = new Set();
|
|
24
|
+
const upstreamSockets = new Set();
|
|
25
|
+
let requests = 0;
|
|
26
|
+
let lastActivity = null;
|
|
27
|
+
let lastError = null;
|
|
28
|
+
let localUrl = '';
|
|
29
|
+
let authorization;
|
|
30
|
+
const contexts = new WeakMap();
|
|
31
|
+
const details = (req) => ({
|
|
32
|
+
request_id: contexts.get(req)?.id,
|
|
33
|
+
method: req.method, ...describeUrl(req.url ?? '/'),
|
|
34
|
+
authorization_present: Boolean(req.headers.authorization),
|
|
35
|
+
cookie_present: Boolean(req.headers.cookie),
|
|
36
|
+
csrf_header_present: Boolean(req.headers['x-csrf-token'] || req.headers['x-xsrf-token']),
|
|
37
|
+
});
|
|
38
|
+
const capture = (cookies, url) => {
|
|
39
|
+
for (const cookie of cookies) jar.setCookieSync(cookie, url, { ignoreError: true });
|
|
40
|
+
};
|
|
41
|
+
capture(initialCookies, target.href);
|
|
42
|
+
const upstreamUrl = (req) => {
|
|
43
|
+
const incoming = new URL(req.url ?? '/', 'http://local');
|
|
44
|
+
const url = new URL(target);
|
|
45
|
+
url.pathname = target.pathname.replace(/\/$/, '') + incoming.pathname;
|
|
46
|
+
url.search = incoming.search;
|
|
47
|
+
return url.href;
|
|
48
|
+
};
|
|
49
|
+
// Cookies remain in Node, independently of cookies shared by localhost ports.
|
|
50
|
+
const requestHeaders = (url = target.href) => {
|
|
51
|
+
if (new URL(url).origin !== target.origin) throw new Error('CROSS_ORIGIN_REQUEST');
|
|
52
|
+
const headers = {};
|
|
53
|
+
const cookie = jar.getCookieStringSync(url);
|
|
54
|
+
if (cookie) headers.cookie = cookie;
|
|
55
|
+
if (authorization) headers.authorization = authorization;
|
|
56
|
+
return headers;
|
|
57
|
+
};
|
|
58
|
+
const prepare = (req) => {
|
|
59
|
+
requests++;
|
|
60
|
+
contexts.set(req, { id: requests, started: Date.now(), important: !['GET', 'HEAD'].includes(req.method ?? '') || Boolean(req.headers.accept?.includes('text/html')), setCookies: 0 });
|
|
61
|
+
lastActivity = new Date().toISOString();
|
|
62
|
+
if (req.headers.authorization && req.headers.authorization !== authorization) {
|
|
63
|
+
authorization = req.headers.authorization;
|
|
64
|
+
promiseCache.clear();
|
|
65
|
+
log('authorization.updated', { request_id: requests });
|
|
66
|
+
}
|
|
67
|
+
delete req.headers.cookie;
|
|
68
|
+
Object.assign(req.headers, requestHeaders(upstreamUrl(req)));
|
|
69
|
+
for (const name of ['origin', 'referer']) {
|
|
70
|
+
const value = req.headers[name];
|
|
71
|
+
if (value && (value === localUrl || value.startsWith(localUrl + '/'))) {
|
|
72
|
+
req.headers[name] = name === 'origin' ? target.origin : new URL(value.slice(localUrl.length).replace(/^\//, ''), target).href;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const proxy = createProxyServer({ target, changeOrigin: true, secure: false, proxyTimeout: 30_000, upgradeTimeout: 10_000 });
|
|
77
|
+
proxy.on('proxyReq', (outgoing) => {
|
|
78
|
+
outgoing.on('socket', (socket) => {
|
|
79
|
+
upstreamSockets.add(socket);
|
|
80
|
+
socket.once('close', () => upstreamSockets.delete(socket));
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
proxy.on('proxyReqWs', (outgoing, req) => {
|
|
84
|
+
outgoing.on('socket', (socket) => {
|
|
85
|
+
upstreamSockets.add(socket);
|
|
86
|
+
socket.once('close', () => upstreamSockets.delete(socket));
|
|
87
|
+
});
|
|
88
|
+
const captureResponse = (response) => {
|
|
89
|
+
log(response.statusCode === 101 ? 'ws.open' : 'ws.rejected', { ...details(req), status: response.statusCode });
|
|
90
|
+
capture(response.headers['set-cookie'] ?? [], upstreamUrl(req));
|
|
91
|
+
delete response.headers['set-cookie'];
|
|
92
|
+
};
|
|
93
|
+
outgoing.on('upgrade', captureResponse);
|
|
94
|
+
outgoing.on('upgrade', (_response, socket) => {
|
|
95
|
+
socket.once('close', hadError => log('ws.closed', { ...details(req), had_error: hadError }));
|
|
96
|
+
});
|
|
97
|
+
outgoing.on('response', captureResponse);
|
|
98
|
+
});
|
|
99
|
+
proxy.on('proxyRes', (response, req) => {
|
|
100
|
+
if (req.method === 'POST' && response.statusCode === 200 &&
|
|
101
|
+
/^\/(api\/)?upload\/(image|mask)\/?$/.test(new URL(req.url ?? '/', localUrl).pathname)) promiseCache.clear('nodes');
|
|
102
|
+
const context = contexts.get(req);
|
|
103
|
+
if (context) context.setCookies = response.headers['set-cookie']?.length ?? 0;
|
|
104
|
+
capture(response.headers['set-cookie'] ?? [], upstreamUrl(req));
|
|
105
|
+
delete response.headers['set-cookie'];
|
|
106
|
+
const location = response.headers.location;
|
|
107
|
+
if (location) {
|
|
108
|
+
try {
|
|
109
|
+
const destination = new URL(location, upstreamUrl(req));
|
|
110
|
+
const base = target.pathname.replace(/\/$/, '');
|
|
111
|
+
if (destination.origin === target.origin && (destination.pathname === base || destination.pathname.startsWith(base + '/'))) {
|
|
112
|
+
response.headers.location = localUrl + (destination.pathname.slice(base.length) || '/') + destination.search + destination.hash;
|
|
113
|
+
}
|
|
114
|
+
} catch { /* Forward malformed upstream Location unchanged. */ }
|
|
115
|
+
}
|
|
116
|
+
lastError = null;
|
|
117
|
+
});
|
|
118
|
+
attachInjection(proxy, log, id => { jobs.track(id); log('prompt.accepted', { prompt_id: id }); });
|
|
119
|
+
proxy.on('error', (error, req, response) => {
|
|
120
|
+
lastError = 'UPSTREAM_REQUEST_FAILED';
|
|
121
|
+
const code = (error).code;
|
|
122
|
+
log('upstream.error', { ...(req ? details(req) : {}), code: code && /^[A-Z0-9_]+$/.test(code) ? code : 'UPSTREAM_REQUEST_FAILED' });
|
|
123
|
+
if (response instanceof ServerResponse) {
|
|
124
|
+
if (!response.headersSent) response.writeHead(502);
|
|
125
|
+
response.end('Upstream request failed');
|
|
126
|
+
} else response?.destroy();
|
|
127
|
+
});
|
|
128
|
+
const server = createServer((req, res) => {
|
|
129
|
+
if (!allowed(req)) { log('http.blocked', { ...details(req), status: 403 }); res.writeHead(403).end(); return; }
|
|
130
|
+
prepare(req);
|
|
131
|
+
const context = contexts.get(req);
|
|
132
|
+
if (context.important) log('http.start', details(req));
|
|
133
|
+
res.once('finish', () => {
|
|
134
|
+
if (context.important || res.statusCode >= 300 || context.setCookies) {
|
|
135
|
+
log('http.end', { ...details(req), status: res.statusCode, duration_ms: Date.now() - context.started, set_cookie_count: context.setCookies });
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
res.once('close', () => {
|
|
139
|
+
if (!res.writableFinished) log('http.aborted', { ...details(req), duration_ms: Date.now() - context.started });
|
|
140
|
+
});
|
|
141
|
+
if ([scriptPath, validationPath].includes(new URL(req.url ?? '/', localUrl).pathname)) {
|
|
142
|
+
void serveScript(req, res, log);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
// Background GET polling and static assets must not keep an idle server alive.
|
|
146
|
+
if (context.important || new URL(req.url ?? '/', localUrl).pathname === '/view') options.activity?.();
|
|
147
|
+
void proxy.web(req, res).catch(() => {
|
|
148
|
+
if (!res.headersSent) res.writeHead(502);
|
|
149
|
+
res.end('Upstream request failed');
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
server.on('connection', (socket) => {
|
|
153
|
+
sockets.add(socket);
|
|
154
|
+
socket.once('close', () => sockets.delete(socket));
|
|
155
|
+
});
|
|
156
|
+
server.on('upgrade', (req, socket, head) => {
|
|
157
|
+
if (!allowed(req)) { log('ws.blocked', details(req)); socket.destroy(); return; }
|
|
158
|
+
if (new URL(req.url ?? '/', localUrl).pathname === bridgePath) {
|
|
159
|
+
browser.upgrade(req, socket, head, localUrl);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
prepare(req);
|
|
163
|
+
log('ws.connect', details(req));
|
|
164
|
+
void proxy.ws(req, socket, {}, head).catch(() => { socket.destroy(); });
|
|
165
|
+
});
|
|
166
|
+
const listen = (port) => new Promise((resolve, reject) => {
|
|
167
|
+
server.once('error', reject);
|
|
168
|
+
server.listen(port, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); });
|
|
169
|
+
});
|
|
170
|
+
try {
|
|
171
|
+
try { await listen(preferredPort ?? 0); }
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (!preferredPort || !['EADDRINUSE', 'EACCES'].includes((error).code ?? '')) throw error;
|
|
174
|
+
log('proxy.preferred_port_unavailable', { port: preferredPort });
|
|
175
|
+
await listen(0);
|
|
176
|
+
}
|
|
177
|
+
} catch (error) { browser.close(); throw error; }
|
|
178
|
+
const address = server.address();
|
|
179
|
+
if (!address || typeof address === 'string') throw new Error('PROXY_LISTEN_FAILED');
|
|
180
|
+
localUrl = `http://127.0.0.1:${address.port}`;
|
|
181
|
+
function allowed(req) {
|
|
182
|
+
return req.headers.host === new URL(localUrl).host && (!req.headers.origin || req.headers.origin === localUrl);
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
url: localUrl + '/', requestHeaders, browser, jobs, promiseCache,
|
|
186
|
+
status: () => ({ ...browser.status(), requests, last_activity: lastActivity, last_error: lastError, authorization_present: Boolean(authorization),
|
|
187
|
+
cookie_count: (jar.serializeSync()?.cookies ?? []).filter(c => (Cookie.fromJSON(c)?.expiryTime() ?? 0) > Date.now()).length }),
|
|
188
|
+
close: async () => {
|
|
189
|
+
promiseCache.clear();
|
|
190
|
+
browser.close();
|
|
191
|
+
for (const socket of [...sockets, ...upstreamSockets]) socket.destroy();
|
|
192
|
+
if (server.listening) await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
193
|
+
jar.removeAllCookiesSync();
|
|
194
|
+
authorization = undefined;
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import pRetry, {} from 'p-retry';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @template T
|
|
5
|
+
* @param {import('p-retry').Options & {retries: number}} options
|
|
6
|
+
* @param {() => Promise<T>} action
|
|
7
|
+
* @returns {Promise<T>}
|
|
8
|
+
*/
|
|
9
|
+
export function retryPromise(options, action) {
|
|
10
|
+
return pRetry(action, options);
|
|
11
|
+
}
|