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/sessions.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { get as httpGet } from 'node:http';
|
|
3
|
+
import { get as httpsGet } from 'node:https';
|
|
4
|
+
import open from 'open';
|
|
5
|
+
import { createSessionProxy } from './proxy.js';
|
|
6
|
+
import { createSessionLog, describeUrl } from './log.js';
|
|
7
|
+
import { PortPreferences, portPreferencesFile } from './ports.js';
|
|
8
|
+
import { backendHistory, backendInputsList, backendWorkflowList } from './backend.js';
|
|
9
|
+
import { backendUpload, backendDownload } from './files.js';
|
|
10
|
+
import { workflowPath } from './workflow.js';
|
|
11
|
+
import { backendNodeInfo } from './nodes.js';
|
|
12
|
+
|
|
13
|
+
/** @param {string} input */
|
|
14
|
+
export function normalizeUrl(input) {
|
|
15
|
+
const url = new URL(input);
|
|
16
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('INVALID_BACKEND_URL');
|
|
17
|
+
url.hash = '';
|
|
18
|
+
if (!url.pathname.endsWith('/')) url.pathname += '/';
|
|
19
|
+
return url;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @typedef {{target: string, created: string, probeStatus: number, proxy: Awaited<ReturnType<typeof createSessionProxy>>, log: Awaited<ReturnType<typeof createSessionLog>>}} Session */
|
|
23
|
+
|
|
24
|
+
export class Sessions {
|
|
25
|
+
/** @private @type {Map<string, Session>} */
|
|
26
|
+
sessions = new Map();
|
|
27
|
+
queue = Promise.resolve();
|
|
28
|
+
ports;
|
|
29
|
+
onActivity = () => {};
|
|
30
|
+
opener;
|
|
31
|
+
timeout;
|
|
32
|
+
/** @param {(url: string) => Promise<unknown>} [opener] @param {number} [timeout] @param {string | null} [preferencesFile] */
|
|
33
|
+
constructor(opener = open, timeout = 10_000, preferencesFile = portPreferencesFile) {
|
|
34
|
+
this.opener = opener; this.timeout = timeout;
|
|
35
|
+
this.ports = new PortPreferences(preferencesFile);
|
|
36
|
+
}
|
|
37
|
+
/** @private @template T @param {() => Promise<T>} action @returns {Promise<T>} */
|
|
38
|
+
serial(action) {
|
|
39
|
+
const result = this.queue.then(action);
|
|
40
|
+
this.queue = result.then(() => undefined, () => undefined);
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
/** @param {string} input */
|
|
44
|
+
connect(input) {
|
|
45
|
+
return this.serial(async () => {
|
|
46
|
+
const target = normalizeUrl(input);
|
|
47
|
+
let response;
|
|
48
|
+
try {
|
|
49
|
+
response = await new Promise((resolve, reject) => {
|
|
50
|
+
const get = target.protocol === 'https:' ? httpsGet : httpGet;
|
|
51
|
+
const request = get(target, { rejectUnauthorized: false, agent: false, signal: AbortSignal.timeout(this.timeout) }, incoming => {
|
|
52
|
+
resolve({ status: incoming.statusCode, cookies: incoming.headers['set-cookie'] ?? [] });
|
|
53
|
+
incoming.destroy();
|
|
54
|
+
});
|
|
55
|
+
request.once('error', reject);
|
|
56
|
+
});
|
|
57
|
+
} catch { throw new Error('BACKEND_UNREACHABLE'); }
|
|
58
|
+
let id;
|
|
59
|
+
let log;
|
|
60
|
+
while (true) {
|
|
61
|
+
id = randomBytes(4).toString('hex');
|
|
62
|
+
try { log = await createSessionLog(id); break; }
|
|
63
|
+
catch (error) { if ((error).code !== 'EEXIST') throw error; }
|
|
64
|
+
}
|
|
65
|
+
log.write('session.probed', { backend_origin: target.origin, ...describeUrl(target.href), status: response.status });
|
|
66
|
+
let preferredPort;
|
|
67
|
+
try { preferredPort = await this.ports.get(target); }
|
|
68
|
+
catch { log.write('proxy.port_preference_error', { operation: 'read' }); }
|
|
69
|
+
let proxy;
|
|
70
|
+
try { proxy = await createSessionProxy(target, response.cookies, log.write, preferredPort,
|
|
71
|
+
{ sessionId: id, activity: () => this.onActivity() }); }
|
|
72
|
+
catch (error) { log.write('session.failed', { reason: 'PROXY_START_FAILED' }); await log.close(); throw error; }
|
|
73
|
+
log.write('session.created', { proxy_url: proxy.url });
|
|
74
|
+
try { await this.opener(proxy.url); log.write('browser.opened'); }
|
|
75
|
+
catch { await proxy.close(); log.write('session.closed', { reason: 'BROWSER_OPEN_FAILED' }); await log.close(); throw new Error('BROWSER_OPEN_FAILED'); }
|
|
76
|
+
try { await this.ports.remember(target, Number(new URL(proxy.url).port)); }
|
|
77
|
+
catch { log.write('proxy.port_preference_error', { operation: 'write' }); }
|
|
78
|
+
for (const [id, previous] of this.sessions) {
|
|
79
|
+
if (previous.target === target.href) {
|
|
80
|
+
this.sessions.delete(id);
|
|
81
|
+
await previous.proxy.close();
|
|
82
|
+
previous.log.write('session.closed', { reason: 'replaced' });
|
|
83
|
+
await previous.log.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
this.sessions.set(id, { target: target.href, created: new Date().toISOString(), probeStatus: response.status, proxy, log });
|
|
87
|
+
return this.status(id);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/** @param {string} [id] @returns {Promise<unknown>} */
|
|
91
|
+
async status(id) {
|
|
92
|
+
if (id) {
|
|
93
|
+
const session = this.sessions.get(id);
|
|
94
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
95
|
+
await session.log.flush();
|
|
96
|
+
return { session_id: id, backend_url: session.target, proxy_url: session.proxy.url,
|
|
97
|
+
created_at: session.created, probe_status: session.probeStatus, reverse_proxy_log_path: session.log.path, ...session.proxy.status() };
|
|
98
|
+
}
|
|
99
|
+
return { sessions: await Promise.all([...this.sessions.keys()].map(key => this.status(key))) };
|
|
100
|
+
}
|
|
101
|
+
/** @param {string} id */
|
|
102
|
+
disconnect(id) {
|
|
103
|
+
return this.serial(async () => {
|
|
104
|
+
const session = this.sessions.get(id);
|
|
105
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
106
|
+
this.sessions.delete(id);
|
|
107
|
+
await session.proxy.close();
|
|
108
|
+
session.log.write('session.closed', { reason: 'disconnect' });
|
|
109
|
+
await session.log.close();
|
|
110
|
+
return { disconnected: id };
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** @param {string} sessionId */
|
|
114
|
+
workflowNew(sessionId) {
|
|
115
|
+
const session = this.sessions.get(sessionId);
|
|
116
|
+
if (!session) return Promise.reject(new Error('SESSION_NOT_FOUND'));
|
|
117
|
+
return session.proxy.browser.newWorkflow();
|
|
118
|
+
}
|
|
119
|
+
/** @param {string} sessionId @param {string} path */
|
|
120
|
+
workflowOpen(sessionId, path) {
|
|
121
|
+
return this.serial(async () => {
|
|
122
|
+
const session = this.sessions.get(sessionId);
|
|
123
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
124
|
+
path = workflowPath(path);
|
|
125
|
+
const id = session.proxy.browser.openedWorkflow(path);
|
|
126
|
+
if (id) return { error: 'WORKFLOW_ALREADY_OPEN', session_id: sessionId, id };
|
|
127
|
+
const data = await session.proxy.browser.openWorkflow(path);
|
|
128
|
+
return { session_id: sessionId, ...data };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/** @param {string} sessionId */
|
|
132
|
+
async backendWorkflowList(sessionId) {
|
|
133
|
+
const session = this.sessions.get(sessionId);
|
|
134
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
135
|
+
const data = await backendWorkflowList(session.proxy.url);
|
|
136
|
+
session.log.write('backend.workflow_list', { count: data.workflows.length });
|
|
137
|
+
return { session_id: sessionId, ...data };
|
|
138
|
+
}
|
|
139
|
+
/** @param {string} sessionId @param {import('./nodes.js').NodeInfoArgs} args */
|
|
140
|
+
async backendNodeInfo(sessionId, args) {
|
|
141
|
+
const session = this.sessions.get(sessionId);
|
|
142
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
143
|
+
const data = await backendNodeInfo(session.proxy.url, args, session.proxy.promiseCache);
|
|
144
|
+
session.log.write('backend.node_info', { mode: args.node_type ? 'definition' : 'search',
|
|
145
|
+
...(data.nodes ? { count: data.nodes.length, total: data.total } : {}), ...('error' in data ? { error: data.error } : {}) });
|
|
146
|
+
return { session_id: sessionId, ...data };
|
|
147
|
+
}
|
|
148
|
+
/** @param {string} workflowId @param {import('./browser.js').WorkflowMethod} method @param {unknown} [workflow] @param {string} [name] */
|
|
149
|
+
workflowRequest(workflowId, method, workflow, name) {
|
|
150
|
+
const session = [...this.sessions.values()].find(s => s.proxy.browser.hasWorkflow(workflowId));
|
|
151
|
+
if (!session) return Promise.reject(new Error('WORKFLOW_NOT_FOUND'));
|
|
152
|
+
return session.proxy.browser.request(workflowId, method, workflow, name);
|
|
153
|
+
}
|
|
154
|
+
/** @param {string} sessionId */
|
|
155
|
+
async backendInputsList(sessionId) {
|
|
156
|
+
const session = this.sessions.get(sessionId);
|
|
157
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
158
|
+
const data = await backendInputsList(session.proxy.url);
|
|
159
|
+
session.log.write('backend.inputs_list', { count: data.files.length });
|
|
160
|
+
return { session_id: sessionId, proxy_url: session.proxy.url, ...data };
|
|
161
|
+
}
|
|
162
|
+
/** @param {string} sessionId @param {string} file @param {string} [name] */
|
|
163
|
+
async backendUpload(sessionId, file, name) {
|
|
164
|
+
const session = this.sessions.get(sessionId);
|
|
165
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
166
|
+
const data = await backendUpload(session.proxy.url, file, name);
|
|
167
|
+
session.log.write('backend.upload', { path: data.path, bytes: data.bytes });
|
|
168
|
+
return { session_id: sessionId, ...data };
|
|
169
|
+
}
|
|
170
|
+
/** @param {string} sessionId @param {string} remotePath @param {string} file @param {import('./files.js').BackendFileType} [type] */
|
|
171
|
+
async backendDownload(sessionId, remotePath, file, type = 'input') {
|
|
172
|
+
const session = this.sessions.get(sessionId);
|
|
173
|
+
if (!session) throw new Error('SESSION_NOT_FOUND');
|
|
174
|
+
const data = await backendDownload(session.proxy.url, remotePath, file, type);
|
|
175
|
+
session.log.write('backend.download', { path: data.path, type, bytes: data.bytes });
|
|
176
|
+
return { session_id: sessionId, ...data };
|
|
177
|
+
}
|
|
178
|
+
/** @param {string} [sessionId] */
|
|
179
|
+
backendStatus(sessionId) { return this.jobStatus(sessionId, false); }
|
|
180
|
+
/** @param {string} [sessionId] */
|
|
181
|
+
backendHistory(sessionId) { return this.jobStatus(sessionId, true); }
|
|
182
|
+
/** @private @param {string | undefined} sessionId @param {boolean} history */
|
|
183
|
+
async jobStatus(sessionId, history) {
|
|
184
|
+
if (sessionId && !this.sessions.has(sessionId)) throw new Error('SESSION_NOT_FOUND');
|
|
185
|
+
return { backends: await Promise.all([...this.sessions].filter(([id]) => !sessionId || id === sessionId).map(async ([id, session]) => {
|
|
186
|
+
const base = { session_id: id, backend_url: session.target };
|
|
187
|
+
try {
|
|
188
|
+
const data = await (history ? backendHistory(session.proxy.url) : session.proxy.jobs.status(session.proxy.url));
|
|
189
|
+
session.log.write(history ? 'backend.history' : 'backend.status', { active: data.active.length, recent: data.recent.length });
|
|
190
|
+
return { ...base, ok: true, ...data };
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const code = error instanceof Error ? error.message : 'BACKEND_STATUS_FAILED';
|
|
193
|
+
session.log.write('backend.status_error', { code });
|
|
194
|
+
return { ...base, ok: false, error: code };
|
|
195
|
+
}
|
|
196
|
+
})) };
|
|
197
|
+
}
|
|
198
|
+
async close() {
|
|
199
|
+
await this.serial(async () => {
|
|
200
|
+
const sessions = [...this.sessions.values()];
|
|
201
|
+
this.sessions.clear();
|
|
202
|
+
await Promise.all(sessions.map(async session => {
|
|
203
|
+
await session.proxy.close();
|
|
204
|
+
session.log.write('session.closed', { reason: 'shutdown' });
|
|
205
|
+
await session.log.close();
|
|
206
|
+
}));
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
package/src/settings.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
export const packageInfo = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
4
|
+
export const serverInfo = { name: 'comfyui-proxy', version: packageInfo.version };
|
|
5
|
+
// Compatibility of the CLI/HTTP contract, independent of npm release versions.
|
|
6
|
+
export const protocolVersion = 1;
|
|
7
|
+
|
|
8
|
+
export function configuredPort() {
|
|
9
|
+
const port = Number(process.env.COMFY_MCP_PORT ?? 37861);
|
|
10
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('INVALID_MCP_PORT');
|
|
11
|
+
return port;
|
|
12
|
+
}
|
package/src/stdio.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
|
3
|
+
import { createAdapter } from './adapter.js';
|
|
4
|
+
import { createCliRunner } from './cli-runner.js';
|
|
5
|
+
|
|
6
|
+
const mcp = await createAdapter(createCliRunner({ local: process.argv.includes('--local') }));
|
|
7
|
+
await mcp.connect(new StdioServerTransport());
|
|
8
|
+
let closing = false;
|
|
9
|
+
function close() {
|
|
10
|
+
if (closing) return;
|
|
11
|
+
closing = true;
|
|
12
|
+
void mcp.close().finally(() => process.exit(0));
|
|
13
|
+
}
|
|
14
|
+
process.stdin.once('end', close);
|
|
15
|
+
process.once('SIGINT', close);
|
|
16
|
+
process.once('SIGTERM', close);
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/server';
|
|
2
|
+
import * as z from 'zod/v4';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { serverInfo } from './settings.js';
|
|
5
|
+
import { nodeInfoArgs } from './nodes.js';
|
|
6
|
+
|
|
7
|
+
const sessionId = z.string().min(1).describe('Backend connection ID returned by connect. Selects the backend and its stored authentication (cookies/Authorization). Not a workflow ID.');
|
|
8
|
+
const file = z.string().refine(value => path.isAbsolute(value), 'Use an absolute local file path');
|
|
9
|
+
const target = { id: z.string().min(1).describe('Session-prefixed ID (e.g. 7fa2c8d1-w3) from status.workflows_opened. Use the returned ID; expired IDs return WORKFLOW_NOT_FOUND. After a server restart connect again. Session routing is automatic.') };
|
|
10
|
+
|
|
11
|
+
export const definitions = {
|
|
12
|
+
connect: { description: 'Probe an HTTP(S) backend, create an isolated local proxy and open the default browser. Replaces an existing session for the same URL.', inputSchema: z.object({ url: z.string().url() }) },
|
|
13
|
+
status: { description: 'List sessions or inspect one session, including workflows_opened (open editor tabs, also unsaved) and reverse_proxy_log_path for diagnostics. For saved backend files use backend_workflow_list. Never returns credentials.', inputSchema: z.object({ session_id: sessionId.optional() }) },
|
|
14
|
+
backend_status: { description: 'Read only jobs accepted through the current proxy session, including Run clicked in its browser UI. Active jobs and jobs finished in the last 12 hours, with native states, workflow UUIDs, short errors and output path/type for backend_download. Finished results are cached. unavailable reports accepted IDs no longer found by the backend. No editor activation. Omit session_id for all connected sessions. Use backend_history for jobs outside these sessions.', inputSchema: z.strictObject({ session_id: sessionId.optional() }) },
|
|
15
|
+
backend_history: { description: 'Read all backend jobs, including runs outside our proxy sessions and closed workflows. Every active job plus jobs finished in the last 12 hours; native states, workflow UUIDs, short errors and output path/type for backend_download. No full graphs, URLs or file contents. Does not activate editor tabs. Omit session_id for all connected backends.', inputSchema: z.strictObject({ session_id: sessionId.optional() }) },
|
|
16
|
+
backend_node_info: { description: 'Discover node types or read one exact native definition through the backend session and its stored authentication, without CLI or an open browser. Successful validated responses are cached by URL for the session, without TTL. Concurrent calls share a fetch. A successful upload via the proxy or a changed Authorization clears the cache; a new connect starts fresh. External changes require reconnecting. query returns compact paged summaries, never the full catalog. node_type returns its full native definition: inputs, input_order, outputs, parameter settings and choice lists including models. These are type definitions, not workflow instance values or guaranteed render compatibility. Transient GET failures may be retried twice; authentication, JSON/schema errors and missing node types are not retried or cached. No installation or generation.', inputSchema: nodeInfoArgs.safeExtend({ session_id: sessionId }) },
|
|
17
|
+
backend_inputs_list: { description: 'List input files exposed by one backend through its authenticated proxy. Returns proxy_url and the original backend strings in their original order, including any [input] annotation. root_only is false if any returned path contains a forward slash or backslash, otherwise true. No recursive requests, saved-workflow scan or extra metadata requests. For backend_download, use the returned path without its trailing [input] annotation; type defaults to input. Does not require an open browser tab.', inputSchema: z.strictObject({ session_id: sessionId }) },
|
|
18
|
+
backend_workflow_list: { description: 'List saved workflow JSON files recursively through the backend session proxy. One userdata metadata request; no graph downloads and no browser page required. Returns session_id and workflows with path (including workflows/ prefix), size in bytes, modified and optional created timestamps in Unix milliseconds. Pass path directly to workflow_open. Does not include unsaved editor tabs; see status.workflows_opened for those.', inputSchema: z.strictObject({ session_id: sessionId }) },
|
|
19
|
+
backend_upload: { description: 'Upload a local file to the backend input root using this session authentication. Optional name defaults to the local filename and must not contain a folder. Subfolders are not supported. Uses native backend collision handling without overwrite or custom hashes. Returns actual path and type for the graph or backend_download, plus bytes; no URL or file contents. Does not modify a workflow, save or run it. No automatic retries.', inputSchema: z.strictObject({ session_id: sessionId, file, name: z.string().min(1).optional() }) },
|
|
20
|
+
backend_download: { description: 'Download a backend file to an absolute local file using this session authentication. path is relative to the input/output/temp directory; use actual path from backend_upload or outputs in backend_status, or an input list entry without its trailing [input] annotation. type defaults to input. Streams file bytes to disk; returns a compact summary, no contents or URL. Refuses to overwrite an existing local file and removes temporary data after failure. Does not activate editor tabs.', inputSchema: z.strictObject({ session_id: sessionId, path: z.string().min(1), type: z.enum(['input', 'output', 'temp']).default('input'), file }) },
|
|
21
|
+
disconnect: { description: 'Close a local proxy and forget its session, without stopping the backend.', inputSchema: z.object({ session_id: sessionId }) },
|
|
22
|
+
workflow_open: { description: 'Open and activate a saved workflow in the last focused connected page of the backend session (same selection as workflow_new). path is the exact path from backend_workflow_list, including workflows/ prefix. If already open anywhere in this session, returns tool error WORKFLOW_ALREADY_OPEN with session_id and existing id, without changing tabs or unsaved edits. Otherwise returns the new id, session_id, name, path, modified and temporary. Updates status.workflows_opened automatically; no graph contents. No automatic retries after timeout: check status first.', inputSchema: z.strictObject({ session_id: sessionId, path: z.string().min(1) }) },
|
|
23
|
+
workflow_new: { description: 'Create and activate a new blank unsaved workflow in the last focused connected browser page of this backend session. Focus order comes only from window focus events; if none were received, uses the first connected page. Returns the new short id, name, path (null), modified and temporary, without graph contents. Updates status automatically. No automatic retries after timeout: inspect status first.', inputSchema: z.strictObject({ session_id: sessionId }) },
|
|
24
|
+
workflow_save: { description: 'Activate the exact workflow tab and save its current graph to backend storage. Without name, saves at its existing path; a temporary workflow returns NAME_REQUIRED without a dialog. Optional name is a new path relative to workflows/, e.g. project/scene.json (.json is added if missing). New-name conflicts return NAME_EXISTS without overwriting. Saving an existing workflow under a different name may create a new tab; always use the returned id. Returns id/name/path/modified/temporary/saved, no graph contents. Does not run. After timeout inspect status before retrying.', inputSchema: z.strictObject({ ...target, name: z.string().min(1).optional() }) },
|
|
25
|
+
run: { description: 'Activate the exact workflow tab and submit its current graph once through the frontend API. Does not save or wait for rendering. Returns accepted and prompt_id, or validation errors. Check backend_status for execution and outputs. After a timeout or disconnect the outcome may be unknown; check backend_status before retrying.', inputSchema: z.strictObject(target) },
|
|
26
|
+
workflow_download: { description: 'Activate the exact tab and write its current standard ComfyUI Workflow JSON, including unsaved edits, to an absolute local file. Returns a compact summary. Does not save to backend or generate.', inputSchema: z.strictObject({ ...target, file, overwrite: z.boolean().default(false) }) },
|
|
27
|
+
workflow_upload: { description: 'Parse standard Workflow JSON from an absolute local file, then refresh the target page node catalog and validate the candidate in a detached frontend graph (schema, links, missing nodes/models/media). Validation errors return a compact issue list without activating or replacing the target tab. Only after validation succeeds, activate the exact tab and replace its graph. Frontend checks are preliminary; run still performs backend validation. Does not save or generate. No snapshot token; overwrites current edits.', inputSchema: z.strictObject({ ...target, file }) },
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** @typedef {keyof typeof definitions} ToolName */
|
|
31
|
+
/**
|
|
32
|
+
* @template {ToolName} K
|
|
33
|
+
* @typedef {z.output<(typeof definitions)[K]['inputSchema']>} ToolArgs
|
|
34
|
+
*/
|
|
35
|
+
/** @typedef {{[K in ToolName]: (args: ToolArgs<K>) => Promise<import('@modelcontextprotocol/server').CallToolResult>}} ToolHandlers */
|
|
36
|
+
/** @typedef {<K extends ToolName>(name: K, args: ToolArgs<K>, signal: AbortSignal) => Promise<import('@modelcontextprotocol/server').CallToolResult>} ToolExecutor */
|
|
37
|
+
|
|
38
|
+
/** @param {ToolExecutor} execute */
|
|
39
|
+
export function createToolServer(execute) {
|
|
40
|
+
const mcp = new McpServer(serverInfo);
|
|
41
|
+
function register(name) {
|
|
42
|
+
const definition = definitions[name];
|
|
43
|
+
mcp.registerTool(name, { ...definition, inputSchema: definition.inputSchema },
|
|
44
|
+
(args, context) => execute(name, args, context.mcpReq.signal));
|
|
45
|
+
}
|
|
46
|
+
(Object.keys(definitions)).forEach(register);
|
|
47
|
+
return mcp;
|
|
48
|
+
}
|
package/src/workflow.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import * as z from 'zod/v4';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { copyFile, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
|
|
6
|
+
export const workflowSchema = z.object({ nodes: z.array(z.object({ id: z.union([z.string(), z.number()]), type: z.string() }).loose()), links: z.array(z.unknown()) }).loose();
|
|
7
|
+
export const workflowResultSchema = z.object({ id: z.string(), modified: z.boolean(), temporary: z.boolean(), workflow: workflowSchema }).loose();
|
|
8
|
+
const issueSchema = z.object({ type: z.string(), message: z.string(), details: z.string().optional() });
|
|
9
|
+
export const runResultSchema = z.discriminatedUnion('accepted', [
|
|
10
|
+
z.object({ id: z.string(), accepted: z.literal(true), prompt_id: z.string().min(1) }),
|
|
11
|
+
z.object({ id: z.string(), accepted: z.literal(false), http_status: z.number().nullable(), error: issueSchema,
|
|
12
|
+
node_errors: z.record(z.string(), z.object({ class_type: z.string().optional(), errors: z.array(issueSchema) })) }),
|
|
13
|
+
]);
|
|
14
|
+
/** @param {z.infer<typeof workflowResultSchema>} result */
|
|
15
|
+
export function summary(result) {
|
|
16
|
+
const { workflow, ...rest } = result;
|
|
17
|
+
return { ...rest, format: 'comfyui-workflow', nodes: workflow.nodes.length, links: workflow.links.length };
|
|
18
|
+
}
|
|
19
|
+
/** @param {string} file */
|
|
20
|
+
export async function readWorkflow(file) {
|
|
21
|
+
const text = await readFile(file, 'utf8');
|
|
22
|
+
let graph;
|
|
23
|
+
try { graph = JSON.parse(text); }
|
|
24
|
+
catch { throw new Error('WORKFLOW_INVALID_JSON'); }
|
|
25
|
+
const result = workflowSchema.safeParse(graph);
|
|
26
|
+
if (!result.success) throw new Error('INVALID_WORKFLOW');
|
|
27
|
+
return result.data;
|
|
28
|
+
}
|
|
29
|
+
/** @param {string} value */
|
|
30
|
+
export function workflowPath(value) {
|
|
31
|
+
const normalized = value.replace(/\\/g, '/');
|
|
32
|
+
if (!normalized.startsWith('workflows/') || !/\.json$/i.test(normalized) || /[\0:]/.test(normalized)
|
|
33
|
+
|| normalized.split('/').some(part => !part || part === '.' || part === '..')) throw new Error('INVALID_WORKFLOW_PATH');
|
|
34
|
+
return normalized;
|
|
35
|
+
}
|
|
36
|
+
/** @param {string} file @param {unknown} workflow @param {boolean} overwrite */
|
|
37
|
+
export async function writeWorkflow(file, workflow, overwrite) {
|
|
38
|
+
const temp = `${file}.mcp-${randomUUID()}.tmp`;
|
|
39
|
+
try {
|
|
40
|
+
await writeFile(temp, JSON.stringify(workflow, null, 2) + '\n', { flag: 'wx' });
|
|
41
|
+
if (overwrite) await rename(temp, file);
|
|
42
|
+
else await copyFile(temp, file, constants.COPYFILE_EXCL);
|
|
43
|
+
} finally { await unlink(temp).catch(() => {}); }
|
|
44
|
+
}
|