comfy-native-apps 0.0.0-stage → 1.0.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.
@@ -0,0 +1,179 @@
1
+ // assert_media.mjs — offline regression checks for the native-app converter.
2
+ // No ComfyUI needed: pure loadNativeApp → buildOverrides → graphToPrompt checks.
3
+ // Run: node assert_media.mjs
4
+ //
5
+ // Everything here is SYNTHETIC: a minimal .app.json fixture is generated in a temp
6
+ // dir, so the suite is self-contained and names no real workflow. A final generic
7
+ // pass scans whatever apps are actually installed and asserts shared invariants.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { loadNativeApp, buildOverrides, graphToPrompt, listApps } from './native_lib.mjs';
12
+
13
+ const SG_ID = 'sg-synthetic';
14
+
15
+ // A minimal native app: one subgraph input IMAGE fed by a top-level LoadImage,
16
+ // plus STRING and INT ports, an internal CLIPTextEncode/KSampler, a top-level
17
+ // SaveImage, and a frontend-only Note that must never be emitted.
18
+ function syntheticApp() {
19
+ return {
20
+ nodes: [
21
+ {
22
+ id: 1, type: SG_ID, pos: [0, 0], size: [200, 100], flags: {}, order: 0, mode: 0,
23
+ inputs: [
24
+ { name: 'image', type: 'IMAGE', link: 201, localized_name: 'Source Image' },
25
+ { name: 'prompt', type: 'STRING', link: null, widget: { name: 'prompt' }, label: 'Prompt Text' },
26
+ { name: 'seed', type: 'INT', link: null, widget: { name: 'seed' } },
27
+ ],
28
+ outputs: [{ name: 'IMAGE', type: 'IMAGE', links: [202] }],
29
+ widgets_values: ['', 0],
30
+ widgets_values_named: { prompt: '', seed: 0 },
31
+ },
32
+ {
33
+ id: 2, type: 'LoadImage', pos: [0, 0], size: [100, 100], flags: {}, order: 1, mode: 0,
34
+ inputs: [{ name: 'image', type: 'IMAGE', localized_name: 'Source Image', widget: { name: 'image' } }],
35
+ outputs: [{ name: 'IMAGE', type: 'IMAGE', links: [201] }],
36
+ widgets_values: ['default.png'],
37
+ widgets_values_named: { image: 'default.png' },
38
+ },
39
+ {
40
+ id: 3, type: 'SaveImage', pos: [0, 0], size: [100, 100], flags: {}, order: 2, mode: 0,
41
+ inputs: [{ name: 'images', type: 'IMAGE', link: 202 }],
42
+ outputs: [],
43
+ widgets_values: ['synthetic'],
44
+ widgets_values_named: { filename_prefix: 'synthetic' },
45
+ },
46
+ ],
47
+ links: [
48
+ [201, 2, 0, 1, 0, 'IMAGE'],
49
+ [202, 1, 0, 3, 0, 'IMAGE'],
50
+ ],
51
+ definitions: {
52
+ subgraphs: [{
53
+ id: SG_ID,
54
+ name: 'Synthetic App',
55
+ inputNode: { id: -10 },
56
+ outputNode: { id: -20 },
57
+ inputs: [
58
+ { id: 'p-image', name: 'image', type: 'IMAGE', linkIds: [101] },
59
+ { id: 'p-prompt', name: 'prompt', type: 'STRING', label: 'Prompt Text', linkIds: [102] },
60
+ { id: 'p-seed', name: 'seed', type: 'INT', linkIds: [104] },
61
+ ],
62
+ outputs: [{ id: 'o-image', name: 'IMAGE', type: 'IMAGE', linkIds: [103] }],
63
+ nodes: [
64
+ { id: 10, type: 'CLIPTextEncode', mode: 0,
65
+ inputs: [{ name: 'text', type: 'STRING', widget: { name: 'text' }, link: 102 }],
66
+ outputs: [{ name: 'CONDITIONING', type: 'CONDITIONING', links: [105] }],
67
+ widgets_values_named: { text: '' } },
68
+ { id: 11, type: 'ImageScale', mode: 0,
69
+ inputs: [{ name: 'image', type: 'IMAGE', link: 101 }],
70
+ outputs: [{ name: 'IMAGE', type: 'IMAGE', links: [103] }],
71
+ widgets_values_named: {} },
72
+ { id: 12, type: 'KSampler', mode: 0,
73
+ inputs: [
74
+ { name: 'model', type: 'MODEL', link: null },
75
+ { name: 'positive', type: 'CONDITIONING', link: 105 },
76
+ { name: 'negative', type: 'CONDITIONING', link: null },
77
+ { name: 'latent_image', type: 'LATENT', link: null },
78
+ { name: 'seed', type: 'INT', widget: { name: 'seed' }, link: 104 },
79
+ ],
80
+ outputs: [{ name: 'LATENT', type: 'LATENT', links: [] }],
81
+ widgets_values_named: { seed: 0 } },
82
+ { id: 150, type: 'Note', mode: 0, inputs: [], outputs: [], widgets_values_named: {} },
83
+ ],
84
+ links: [
85
+ { id: 101, origin_id: -10, origin_slot: 0, target_id: 11, target_slot: 0, type: 'IMAGE' },
86
+ { id: 102, origin_id: -10, origin_slot: 1, target_id: 10, target_slot: 0, type: 'STRING' },
87
+ { id: 103, origin_id: 11, origin_slot: 0, target_id: -20, target_slot: 0, type: 'IMAGE' },
88
+ { id: 104, origin_id: -10, origin_slot: 2, target_id: 12, target_slot: 4, type: 'INT' },
89
+ { id: 105, origin_id: 10, origin_slot: 0, target_id: 12, target_slot: 1, type: 'CONDITIONING' },
90
+ ],
91
+ }],
92
+ },
93
+ extra: {
94
+ linearData: {
95
+ inputs: [
96
+ [`${SG_ID}:2:image`, 'image'],
97
+ [`${SG_ID}:1:prompt`, 'prompt'],
98
+ [`${SG_ID}:1:seed`, 'seed'],
99
+ ],
100
+ },
101
+ },
102
+ };
103
+ }
104
+
105
+ let failed = 0;
106
+ const check = (label, ok, got) => {
107
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${label}${ok ? '' : ' -> ' + JSON.stringify(got)}`);
108
+ if (!ok) failed++;
109
+ };
110
+
111
+ // --------------------------------------------------------------------------- #
112
+ // Synthetic fixture: linearMode labels, aliases, media routing, top widgets.
113
+ // --------------------------------------------------------------------------- #
114
+ {
115
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'native-app-fixture-'));
116
+ const file = path.join(dir, 'synthetic.app.json');
117
+ fs.writeFileSync(file, JSON.stringify(syntheticApp()));
118
+ const app = loadNativeApp(file);
119
+
120
+ const labels = app.inputs.map((i) => i.label);
121
+ check('linearMode labels use the target socket name chain',
122
+ JSON.stringify(labels) === JSON.stringify(['Source Image', 'Prompt Text', 'seed']), labels);
123
+
124
+ const img = app.inputs.find((i) => i.label === 'Source Image');
125
+ check('image port keeps the linearData key as an alias', img?.aliases?.includes('image'), img);
126
+ check('image port routes to its top-level loader', img?.media && img.feed?.nodeId === 2 && img.loader?.nodeId === 2, img);
127
+
128
+ const prompt = app.inputs.find((i) => i.label === 'Prompt Text');
129
+ check('ref-adopted port keeps the old key as an alias', prompt?.aliases?.includes('prompt'), prompt);
130
+
131
+ // Media value lands on the loader widget; the internal consumer links to it.
132
+ const media = graphToPrompt(app, buildOverrides(app, { 'Source Image': 'x.png' }));
133
+ check('internal consumer links to the top-level loader', JSON.stringify(media['11'].inputs.image) === '["t2",0]', media['11']);
134
+ check('loader widget gets the supplied filename', media.t2?.inputs?.image === 'x.png', media.t2);
135
+ check('top-level saver is kept (no synthetic saver added)', media.t3?.class_type === 'SaveImage', Object.keys(media));
136
+
137
+ // Scalar overrides: alias key and localized label both resolve.
138
+ const scalar = graphToPrompt(app, buildOverrides(app, { prompt: 'hello' }));
139
+ check('alias key overrides the internal text widget', scalar['10'].inputs.text === 'hello', scalar['10']);
140
+ const seed = graphToPrompt(app, buildOverrides(app, { seed: 3 }));
141
+ check('ref-adopted scalar overrides its internal target', seed['12'].inputs.seed === 3, seed['12']);
142
+ const rolled = graphToPrompt(app, buildOverrides(app, { seed: -1 }));
143
+ check('seed -1 rolls a real seed', Number.isInteger(rolled['12'].inputs.seed) && rolled['12'].inputs.seed >= 0, rolled['12']);
144
+
145
+ // Frontend-only node must never reach the API prompt.
146
+ check('frontend-only Note is not emitted', !('150' in media) && !Object.values(media).some((n) => n.class_type === 'Note'), Object.keys(media));
147
+
148
+ fs.rmSync(dir, { recursive: true, force: true });
149
+ }
150
+
151
+ // --------------------------------------------------------------------------- #
152
+ // Generic invariants over EVERY installed app (no fixture names/ids).
153
+ // --------------------------------------------------------------------------- #
154
+ {
155
+ const apps = listApps().apps.filter((a) => !a.error);
156
+ const FE = /^(Note|MarkdownNote|Reroute|PrimitiveNode)$/;
157
+ const problems = [];
158
+ for (const a of apps) {
159
+ const app = loadNativeApp(a.file);
160
+ const prompt = graphToPrompt(app, buildOverrides(app, {}));
161
+
162
+ const labels = app.inputs.map((i) => i.label);
163
+ if (labels.some((l) => !l)) problems.push(`${a.number}: empty input label`);
164
+ if (new Set(labels).size !== labels.length) problems.push(`${a.number}: duplicate input labels`);
165
+
166
+ for (const [id, n] of Object.entries(prompt)) {
167
+ if (FE.test(String(n.class_type))) problems.push(`${a.number}#${id}: frontend-only ${n.class_type}`);
168
+ if (!n.class_type || typeof n.inputs !== 'object') problems.push(`${a.number}#${id}: malformed node`);
169
+ }
170
+
171
+ for (const p of app.inputs) {
172
+ if (p.media && !p.loader && !p.feed) problems.push(`${a.number}: media port "${p.label}" has no loader/feed`);
173
+ }
174
+ }
175
+ check(`all installed apps convert cleanly (${apps.length} checked)`, problems.length === 0, problems);
176
+ }
177
+
178
+ console.log(failed ? `\n${failed} check(s) failed` : '\nall checks passed');
179
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,375 @@
1
+ #!/usr/bin/env node
2
+ // comfy-native-apps — an MCP server for small (9B-class) local models.
3
+ // Runs ComfyUI's NATIVE workflow apps (.app.json) and manages the render queue.
4
+ //
5
+ // It drives ONLY ComfyUI's NATIVE ".app.json" apps (the built-in "构建应用" feature)
6
+ // and does the UI→API conversion itself — so it works against a headless OR a
7
+ // frontend ComfyUI, with ZERO dependency on the artokun comfyui-mcp / panel plugin.
8
+ //
9
+ // Tools (no list_tools / describe_tool / call_tool indirection — the model sees
10
+ // exactly these, each single-purpose):
11
+ //
12
+ // list_apps() -> catalog: number, name, description, output
13
+ // types for every native .app.json app
14
+ // get_app_params(app) -> the parameter contract of ONE app
15
+ // (input name + type + default, outputs)
16
+ // COMBO inputs also carry their full options list
17
+ // run_app(app, inputs, wait_s?) -> fill only the params you want to change,
18
+ // convert UI→API, enqueue, wait, return the
19
+ // image (or the video URL); wait_s: 0 = submit only
20
+ // upload_file(path, subfolder) -> upload a LOCAL file (image/video/audio/mask)
21
+ // into ComfyUI's input dir; returns the
22
+ // ComfyUI-side relative path for a file param
23
+ // download_output(prompt_id, index?, dest?) -> download one finished output to a
24
+ // local file (file or dir dest); works remote too
25
+ // queue_status(recent?) -> what is running + pending, plus recent finished jobs
26
+ // job_status(prompt_id, wait_s?, preview?, index?) -> state + output files of one
27
+ // job; wait_s blocks, and a completed job returns
28
+ // its view URL plus the image inline (no download)
29
+ // clear_queue() -> clear the pending queue
30
+ // interrupt() -> stop the current generation
31
+ //
32
+ // Config (env vars): COMFYUI_URL (http://127.0.0.1:8188),
33
+ // COMFYUI_PUBLIC_URL (URL clients use for download links; defaults to
34
+ // COMFYUI_URL), WORKFLOWS_ROOT (optional local override of app discovery —
35
+ // by default apps are read from the server's /userdata API), RUN_TIMEOUT_S
36
+ // (300), DOWNLOAD_DIR (default <cwd>/downloads).
37
+ // Legacy COMFYUI_HOST + COMFYUI_PORT still work as a fallback.
38
+ //
39
+ // Client config (Claude Code / any MCP client):
40
+ // { "command": "node",
41
+ // "args": ["<path-to>/comfy-native-apps/comfy_native_apps.mjs"],
42
+ // "env": { "COMFYUI_URL": "http://127.0.0.1:8188" } }
43
+ import {
44
+ BASE, RUN_TIMEOUT_S, appCatalog, appParams, resolveAppRef, loadNativeApp,
45
+ graphToPrompt, buildOverrides, postPrompt, waitForJob, collectOutputs,
46
+ getQueue, jobStatus, jobPreview, postJson, uploadFile, downloadOutput, refreshApps,
47
+ resolveWorkflowsRoot,
48
+ } from './native_lib.mjs';
49
+
50
+ const PROTOCOL_VERSION = '2024-11-05';
51
+ const SERVER_INFO = { name: 'comfy-native-apps', version: '1.0.0' };
52
+
53
+ const TOOLS = [
54
+ {
55
+ name: 'list_apps',
56
+ description: 'List the ComfyUI apps (.app.json) available on the server: number, name, short description and ' +
57
+ 'output types. Call this first to pick an app, then get_app_params(app) for the params you can fill.',
58
+ inputSchema: { type: 'object', properties: {}, required: [] },
59
+ },
60
+ {
61
+ name: 'get_app_params',
62
+ description: 'Show the parameter contract of ONE app: every input param (name, type, default) and its outputs. ' +
63
+ 'COMBO inputs also carry their full "options" list so you can pick a value instead of guessing a filename. ' +
64
+ 'Call this after list_apps and before run_app to see which params exist.',
65
+ inputSchema: {
66
+ type: 'object',
67
+ properties: {
68
+ app: { type: 'string', description: 'Which app: its number from list_apps (e.g. "1"), its name, or its id.' },
69
+ },
70
+ required: ['app'],
71
+ },
72
+ },
73
+ {
74
+ name: 'run_app',
75
+ description: 'Run one app: fill its input params and generate. Waits for the job and returns a downscaled preview ' +
76
+ 'image of every output it wrote (or the video URL), plus the full-resolution URL of each file. ' +
77
+ 'Pass app as its number from list_apps, its name, or its id. ' +
78
+ 'Call get_app_params first, then pass the params you want to change in the "inputs" object ' +
79
+ '(NOT at the top level — a stray field is an error, not a silently-ignored default). ' +
80
+ 'Omitted ones keep their defaults. A seed of -1 rolls a random seed. ' +
81
+ 'Set wait_s to 0 to enqueue and return the prompt_id immediately.',
82
+ inputSchema: {
83
+ type: 'object',
84
+ properties: {
85
+ app: { type: 'string', description: 'Which app to run: its number from list_apps (e.g. "1"), its name, or its id (relative workflows path).' },
86
+ inputs: {
87
+ type: 'object',
88
+ description: 'Params to fill, keyed by the names get_app_params returns (e.g. "prompt", "seed"). Omit any you want to leave at its default.',
89
+ additionalProperties: true,
90
+ },
91
+ wait_s: {
92
+ type: 'integer', minimum: 0, maximum: 3600,
93
+ description: 'Seconds to block waiting for the result. Defaults to the server RUN_TIMEOUT_S. 0 = submit and return prompt_id at once.',
94
+ },
95
+ },
96
+ required: ['app'],
97
+ },
98
+ },
99
+ {
100
+ name: 'upload_file',
101
+ description: 'Upload a local file (image / video / audio / mask — anything a ComfyUI input can load) into ' +
102
+ 'the ComfyUI input folder, so it can be referenced by run_app. Give the LOCAL path to the file on this ' +
103
+ 'machine; optionally a subfolder name. Returns the ComfyUI-side relative path to pass as the value of ' +
104
+ 'an image/video/audio/mask input param.',
105
+ inputSchema: {
106
+ type: 'object',
107
+ properties: {
108
+ path: { type: 'string', description: 'Absolute (or relative) path to the LOCAL file to upload, e.g. "C:/pics/my photo.png" or "D:/vids/clip.mp4".' },
109
+ subfolder: { type: 'string', description: 'Optional destination subfolder inside the ComfyUI input dir (no leading/trailing slash).'},
110
+ },
111
+ required: ['path'],
112
+ },
113
+ },
114
+ {
115
+ name: 'queue_status',
116
+ description: 'Show the ComfyUI queue: what is running and pending now, plus the last few finished jobs (recent, newest first).',
117
+ inputSchema: {
118
+ type: 'object',
119
+ properties: {
120
+ recent: { type: 'integer', description: 'How many finished jobs to list in "recent". Defaults to 5, use 0 to skip history.', minimum: 0, maximum: 50 },
121
+ },
122
+ required: [],
123
+ },
124
+ },
125
+ {
126
+ name: 'job_status',
127
+ description: 'Report the state (running / pending / completed / error) and output files of one job. ' +
128
+ 'Pass the UUID prompt_id returned by run_app. While a job is still queued, its queue number also works. ' +
129
+ 'Set wait_s to block until the job finishes (or the budget runs out) instead of polling. ' +
130
+ 'When the job is completed, "outputs" lists every file it wrote with a viewable "url" and a stable "index" ' +
131
+ '(saved files first, temp previews last), and (preview=true, the default) the image at "index" is returned ' +
132
+ 'inline as a downscaled preview, so a submit-only run_app can be previewed without download_output.',
133
+ inputSchema: {
134
+ type: 'object',
135
+ properties: {
136
+ prompt_id: { type: 'string', description: 'The prompt_id returned by run_app or seen in queue_status.' },
137
+ wait_s: { type: 'integer', minimum: 0, maximum: 3600, description: 'Block until the job finishes, up to this many seconds. Defaults to 0 (return at once).' },
138
+ preview: { type: 'boolean', description: 'When the job is completed, return the image inline (base64) for immediate viewing. Defaults to true; set false to get only the JSON status/URLs.' },
139
+ index: { type: 'integer', description: 'Which output to preview when the job wrote several (index into job_status "outputs"). Defaults to 0.' },
140
+ },
141
+ required: ['prompt_id'],
142
+ },
143
+ },
144
+ {
145
+ name: 'clear_queue',
146
+ description: 'Clear all pending (not yet started) jobs from the queue. Running jobs are untouched.',
147
+ inputSchema: { type: 'object', properties: {}, required: [] },
148
+ },
149
+ {
150
+ name: 'interrupt',
151
+ description: 'Interrupt the currently running generation, if any.',
152
+ inputSchema: { type: 'object', properties: {}, required: [] },
153
+ },
154
+ {
155
+ name: 'download_output',
156
+ description: 'Download one finished output to a local file. Only needs the prompt_id returned by run_app or job_status; ' +
157
+ 'filename comes from ComfyUI history, so it works for local and remote ComfyUI alike. ' +
158
+ 'dest is a file path or a directory (relative paths resolve against the MCP server working dir); ' +
159
+ 'omit it to use $DOWNLOAD_DIR, else <cwd>/downloads.',
160
+ inputSchema: {
161
+ type: 'object',
162
+ properties: {
163
+ prompt_id: { type: 'string', description: 'The prompt_id returned by run_app or job_status.' },
164
+ index: { type: 'integer', description: 'Which output to take when the job wrote several (index into job_status "outputs"). Defaults to 0.', minimum: 0 },
165
+ dest: { type: 'string', description: 'Local destination: a file ("E:/out/clip.mp4"), a directory ("E:/out" or "out/"), or a relative path. Omit for the default downloads folder.' },
166
+ },
167
+ required: ['prompt_id'],
168
+ },
169
+ },
170
+ ];
171
+
172
+ // --------------------------------------------------------------------------- #
173
+ // Tool handlers. Each app-facing handler refreshes the catalog from the server
174
+ // first (cheap: one /userdata listing, files re-downloaded only when they change),
175
+ // so apps added or edited in ComfyUI show up without restarting the MCP.
176
+ // --------------------------------------------------------------------------- #
177
+ async function listAppsHandler() {
178
+ await refreshApps();
179
+ return JSON.stringify(appCatalog(), null, 2);
180
+ }
181
+
182
+ async function appParamsHandler({ app }) {
183
+ await refreshApps();
184
+ return JSON.stringify(await appParams(app), null, 2);
185
+ }
186
+
187
+ async function uploadFileHandler({ path: localPath, subfolder }) {
188
+ const r = await uploadFile(localPath, subfolder);
189
+ return [{ type: 'text', text: JSON.stringify(r, null, 2) }];
190
+ }
191
+
192
+ async function downloadOutputHandler(args) {
193
+ const r = await downloadOutput(args);
194
+ return [{ type: 'text', text: JSON.stringify(r, null, 2) }];
195
+ }
196
+
197
+ // Params travel in ONE field, "inputs" (the same word get_app_params returns).
198
+ // Anything else at the top level is a misplaced param — a model that meant "inputs"
199
+ // but wrote "input" / "values" / "params", or flat name → value pairs. Failing loudly
200
+ // here is the whole point: silently dropping them would run the app with its saved
201
+ // defaults and return a plausible image the model takes for its own request.
202
+ async function runAppHandler({ app, wait_s, inputs, ...stray }) {
203
+ await refreshApps();
204
+ const ref = resolveAppRef(app);
205
+ const a = loadNativeApp(ref.file);
206
+ const labels = new Set(a.inputs.map((i) => String(i.label)));
207
+ const strayNames = Object.keys(stray);
208
+ if (strayNames.length) {
209
+ // Name the strays that are clearly this app's params so the model sees its own
210
+ // mistake, not a generic "unknown key".
211
+ const asParams = strayNames.filter((k) => labels.has(k) || /^loras?\./i.test(k) || /seed|prompt|width|height/i.test(k));
212
+ const where = asParams.length
213
+ ? `"${asParams.join('", "')}" ${asParams.length === 1 ? 'is' : 'are'} ${a.name}'s params`
214
+ : `top-level "${strayNames.join('", "')}" ${strayNames.length === 1 ? 'is' : 'are'} not a run_app field`;
215
+ throw new Error(
216
+ `run_app takes "app", "inputs", "wait_s" only — ${where}. ` +
217
+ `Move every param inside the "inputs" object (see get_app_params); left at the top level it would be ignored and the app would run with its saved defaults.`,
218
+ );
219
+ }
220
+ if (inputs !== undefined && (typeof inputs !== 'object' || inputs === null || Array.isArray(inputs))) {
221
+ throw new Error('"inputs" must be an object of param name → value (see get_app_params)');
222
+ }
223
+ const values = inputs ?? {};
224
+ const overrides = buildOverrides(a, values);
225
+ const prompt = graphToPrompt(a, overrides);
226
+ const resp = await postPrompt(prompt);
227
+ const promptId = resp.prompt_id;
228
+
229
+ const waitS = wait_s === undefined || wait_s === null || wait_s === ''
230
+ ? RUN_TIMEOUT_S
231
+ : Math.max(0, Number(wait_s) || 0);
232
+
233
+ // wait_s: 0 → submit only; the client decides later with job_status(wait_s).
234
+ if (waitS === 0) {
235
+ const st = await jobStatus(promptId);
236
+ return [{
237
+ type: 'text',
238
+ text: JSON.stringify({
239
+ ...st,
240
+ hint: 'Job submitted. Call job_status with this prompt_id and wait_s to block; once completed it returns the image inline plus a view URL, so no download is needed.',
241
+ }, null, 2),
242
+ }];
243
+ }
244
+
245
+ let entry;
246
+ try {
247
+ entry = await waitForJob(promptId, waitS);
248
+ } catch (e) {
249
+ if (e.code !== 'TIMEOUT') throw e;
250
+ const st = await jobStatus(promptId);
251
+ return [{
252
+ type: 'text',
253
+ text: JSON.stringify({
254
+ ...st,
255
+ timed_out: true,
256
+ waited_s: waitS,
257
+ hint: 'Still not finished. Call job_status with this prompt_id and wait_s to keep waiting; it returns the image inline once completed (download_output only if you need a local file).',
258
+ }, null, 2),
259
+ }];
260
+ }
261
+
262
+ const out = await collectOutputs(entry, { previews: true });
263
+ // A job can write several files (two save nodes, or one save node with a
264
+ // batch of images), so list every output and attach every image inline — as
265
+ // downscaled previews, keeping a 10 MB PNG out of the client's context.
266
+ const previews = out.previews ?? [];
267
+ const many = (out.files?.length ?? 0) > 1;
268
+ const listing = many
269
+ ? ['', `${out.files.length} outputs (attached previews are in this order):`,
270
+ ...out.files.map((f, i) => `${i}. ${f.url}`)]
271
+ : [];
272
+ const previewNote = (previews.some((p) => p.shrunk) || out.shrunk)
273
+ ? ['', 'Preview images are downscaled/re-encoded; open the URLs for full resolution.']
274
+ : [];
275
+
276
+ if (out.kind === 'image') {
277
+ const lines = many
278
+ ? [`App "${a.name}" finished (prompt_id ${promptId}).`, ...listing, ...previewNote]
279
+ : [`Generated ${out.filename} with app "${a.name}".`, `URL: ${out.url}`, `(prompt_id ${promptId})`, ...previewNote];
280
+ if (out.extra?.length) lines.push('', 'Other outputs:', ...out.extra);
281
+ return [
282
+ { type: 'text', text: lines.join('\n') },
283
+ ...previews.map((p) => ({ type: 'image', data: p.b64, mimeType: p.mime })),
284
+ ];
285
+ }
286
+ if (out.kind === 'video') {
287
+ const lines = [`App "${a.name}" finished (prompt_id ${promptId}).`, `Video: ${out.url}`, ...listing];
288
+ if (out.extra?.length) lines.push('', 'Other outputs:', ...out.extra);
289
+ return [{ type: 'text', text: lines.join('\n') }];
290
+ }
291
+ const lines = [`App "${a.name}" finished (prompt_id ${promptId}).`, out.text, ...listing];
292
+ if (out.extra?.length) lines.push('', 'Other outputs:', ...out.extra);
293
+ return [{ type: 'text', text: lines.join('\n') }];
294
+ }
295
+
296
+ // --------------------------------------------------------------------------- #
297
+ // MCP over stdio: newline-delimited JSON-RPC 2.0.
298
+ // --------------------------------------------------------------------------- #
299
+ function send(obj) { process.stdout.write(JSON.stringify(obj) + '\n'); }
300
+
301
+ function handle(msg) {
302
+ const { method, id, params = {} } = msg;
303
+
304
+ if (method === 'initialize') {
305
+ send({ jsonrpc: '2.0', id, result: {
306
+ protocolVersion: params.protocolVersion ?? PROTOCOL_VERSION,
307
+ capabilities: { tools: {} }, serverInfo: SERVER_INFO,
308
+ } });
309
+ } else if (method === 'tools/list') {
310
+ send({ jsonrpc: '2.0', id, result: { tools: TOOLS } });
311
+ } else if (method === 'tools/call') {
312
+ const { name, arguments: args = {} } = params;
313
+ const run = async () => {
314
+ switch (name) {
315
+ case 'list_apps': return [{ type: 'text', text: await listAppsHandler() }];
316
+ case 'get_app_params': return [{ type: 'text', text: await appParamsHandler(args) }];
317
+ case 'run_app': return runAppHandler(args);
318
+ case 'upload_file': return uploadFileHandler(args);
319
+ case 'download_output': return downloadOutputHandler(args);
320
+ case 'queue_status': {
321
+ const recent = Math.min(Math.max(Number(args.recent ?? 5) || 0, 0), 50);
322
+ return [{ type: 'text', text: JSON.stringify(await getQueue({ recent }), null, 2) }];
323
+ }
324
+ case 'job_status': {
325
+ const waitS = Math.min(Math.max(Number(args.wait_s ?? 0) || 0, 0), 3600);
326
+ const st = await jobStatus(args.prompt_id, { waitS });
327
+ const content = [{ type: 'text', text: JSON.stringify(st, null, 2) }];
328
+ // Completed + preview (default on): attach the image inline so a
329
+ // submit-only run_app can be viewed without download_output.
330
+ if (st.state === 'completed' && args.preview !== false) {
331
+ const index = Math.max(0, Number(args.index ?? 0) || 0);
332
+ const out = await jobPreview(st.prompt_id, { index }).catch(() => null);
333
+ if (out?.kind === 'image') content.push({ type: 'image', data: out.b64, mimeType: out.mime });
334
+ }
335
+ return content;
336
+ }
337
+ case 'clear_queue': { const r = await postJson('/queue', { clear: true }); return [{ type: 'text', text: JSON.stringify(r) }]; }
338
+ case 'interrupt': { const r = await postJson('/interrupt', {}); return [{ type: 'text', text: JSON.stringify(r) }]; }
339
+ default: throw new Error(`Unknown tool: ${name}`);
340
+ }
341
+ };
342
+ run().then((content) => send({ jsonrpc: '2.0', id, result: { content, isError: false } }))
343
+ .catch((e) => send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: `Error: ${e.message}` }], isError: true } }));
344
+ } else if (method === 'ping') {
345
+ send({ jsonrpc: '2.0', id, result: {} });
346
+ } else if (method && method.startsWith('notifications/')) {
347
+ return;
348
+ } else if (id !== undefined) {
349
+ send({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } });
350
+ }
351
+ }
352
+
353
+ function main() {
354
+ process.stderr.write(`comfy-native-apps targeting ${BASE} (timeout ${RUN_TIMEOUT_S}s)\n`);
355
+ refreshApps({ maxAgeMs: 0 }).then((count) => {
356
+ process.stderr.write(count == null
357
+ ? `apps: /userdata unavailable, reading local files under ${resolveWorkflowsRoot()}\n`
358
+ : `apps: ${count} from ${BASE}/userdata\n`);
359
+ });
360
+ let buf = '';
361
+ process.stdin.setEncoding('utf8');
362
+ process.stdin.on('data', (chunk) => {
363
+ buf += chunk;
364
+ let i;
365
+ while ((i = buf.indexOf('\n')) >= 0) {
366
+ const line = buf.slice(0, i).trim();
367
+ buf = buf.slice(i + 1);
368
+ if (!line) continue;
369
+ try { handle(JSON.parse(line)); } catch (e) { process.stderr.write(`bad json: ${e.message}\n`); }
370
+ }
371
+ });
372
+ process.stdin.on('end', () => process.exit(0));
373
+ }
374
+
375
+ main();
package/drive_safe.mjs ADDED
@@ -0,0 +1,68 @@
1
+ // drive_safe.mjs — NON-destructive end-to-end test: list_apps + run_app + job_status.
2
+ // No /interrupt, no /queue clear (those are left for the user / a deliberate run).
3
+ import { spawn } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ const srv = spawn(process.execPath, ['comfy_native_apps.mjs'], { cwd: process.cwd() });
9
+ // Swallow pipe EPIPE after srv.kill() so the test exits on its own logic, not a crash.
10
+ for (const s of [srv.stdin, srv.stdout, srv.stderr]) s.on('error', () => {});
11
+ srv.stderr.on('data', (d) => process.stderr.write('[srv] ' + d));
12
+ let buf = '';
13
+ const pending = new Map();
14
+ srv.stdout.setEncoding('utf8');
15
+ srv.stdout.on('data', (c) => {
16
+ buf += c;
17
+ let i;
18
+ while ((i = buf.indexOf('\n')) >= 0) {
19
+ const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
20
+ if (!line) continue;
21
+ const m = JSON.parse(line);
22
+ if (m.id !== undefined && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); }
23
+ }
24
+ });
25
+ let n = 0;
26
+ const call = (method, params = {}) => new Promise((res) => { const id = ++n; pending.set(id, res); srv.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n'); });
27
+ const text = (r) => (r.result?.content ?? []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
28
+
29
+ await call('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '0' } });
30
+ srv.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
31
+
32
+ const la = await call('tools/call', { name: 'list_apps', arguments: {} });
33
+ const catalog = JSON.parse(text(la));
34
+ const apps = catalog.apps;
35
+ console.log('### list_apps:', apps.length, 'apps ->',
36
+ apps.map((a) => a.number + ':' + (a.name ?? 'unreadable')).join(' | '));
37
+
38
+ const sc = await call('tools/call', { name: 'get_app_params', arguments: { app: 'Text to Image (Z-Image-Turbo)' } });
39
+ const schema = JSON.parse(text(sc));
40
+ console.log('\n### get_app_params:', schema.name, '->',
41
+ schema.inputs.length, 'params:', schema.inputs.map((i) => i.name + ':' + i.type).join(', '));
42
+
43
+ const ra = await call('tools/call', { name: 'run_app', arguments: { app: 'Text to Image (Z-Image-Turbo)', inputs: { width: 512, height: 512, seed: -1 } } });
44
+ const content = ra.result?.content ?? [];
45
+ const txt = content.filter((c) => c.type === 'text').map((c) => c.text).join('\n');
46
+ const img = content.find((c) => c.type === 'image');
47
+ console.log('\n### run_app:'); console.log(txt);
48
+ if (img) {
49
+ const out = path.join(os.tmpdir(), 'comfy_native_mcp_test.png');
50
+ fs.writeFileSync(out, Buffer.from(img.data, 'base64'));
51
+ console.log(' -> IMAGE OK, saved to', out, '(' + img.data.length + ' b64 chars, ' + img.mimeType + ')');
52
+ } else {
53
+ console.log(' -> NO IMAGE RETURNED');
54
+ }
55
+
56
+ // A param placed at the top level (not in "inputs") must error, not run with defaults.
57
+ const bad = await call('tools/call', { name: 'run_app', arguments: { app: 'Text to Image (Z-Image-Turbo)', width: 512 } });
58
+ const badOk = bad.result?.isError === true && /takes "app", "inputs", "wait_s" only/.test(text(bad));
59
+ console.log('\n### stray top-level field -> isError:', bad.result?.isError, '(expected true)');
60
+
61
+ const pidMatch = txt.match(/prompt_id ([0-9a-f-]{36})/);
62
+ if (pidMatch) {
63
+ const js = await call('tools/call', { name: 'job_status', arguments: { prompt_id: pidMatch[1] } });
64
+ console.log('\n### job_status(' + pidMatch[1] + '):'); console.log(text(js));
65
+ }
66
+
67
+ srv.kill();
68
+ setTimeout(() => process.exit(img && badOk ? 0 : 1), 200);