@metabrain-labs/comfyui-mcp-server 1.0.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.
Files changed (88) hide show
  1. package/.env +179 -0
  2. package/.github/workflows/ci.yml +63 -0
  3. package/.husky/pre-commit +11 -0
  4. package/LICENSE +21 -0
  5. package/README-en.md +635 -0
  6. package/README.md +656 -0
  7. package/__tests__/services/task/execution.test.ts +272 -0
  8. package/__tests__/services/task/wait.test.ts +220 -0
  9. package/__tests__/types/result.test.ts +227 -0
  10. package/__tests__/utils/mcp-helpers.test.ts +137 -0
  11. package/__tests__/utils/special-node-handler.test.ts +186 -0
  12. package/comfyui-mcp-server-skill/SKILL.md +43 -0
  13. package/comfyui-mcp-server-skill/references/api-json.md +323 -0
  14. package/comfyui-mcp-server-skill/references/catalog.md +251 -0
  15. package/comfyui-mcp-server-skill/rules/api-json.md +94 -0
  16. package/comfyui-mcp-server-skill/rules/catalog.md +93 -0
  17. package/comfyui-mcp-server-skill/rules/comfyui.md +158 -0
  18. package/configs/inspector/dev.json +11 -0
  19. package/configs/inspector/prod.json +9 -0
  20. package/docs/en/content/public/inspector-example.png +0 -0
  21. package/docs/en/content/public/workflow_name_example.png +0 -0
  22. package/docs/en/content/public/workflow_parameter_example.png +0 -0
  23. package/docs/en/md/Project-Advantages.md +75 -0
  24. package/docs/zh-CN/content/public/inspector-example.png +0 -0
  25. package/docs/zh-CN/content/public/workflow_name_example.png +0 -0
  26. package/docs/zh-CN/content/public/workflow_parameter_example.png +0 -0
  27. package/docs/zh-CN/md/why-us.md +51 -0
  28. package/example.json +26 -0
  29. package/jest.config.js +45 -0
  30. package/locales/en.json +150 -0
  31. package/locales/zh.json +150 -0
  32. package/package.json +68 -0
  33. package/src/api/api.ts +123 -0
  34. package/src/api/http.ts +70 -0
  35. package/src/constants/common.ts +38 -0
  36. package/src/constants/index.ts +1 -0
  37. package/src/hooks/websocket.ts +93 -0
  38. package/src/i18n.ts +40 -0
  39. package/src/index.ts +268 -0
  40. package/src/scripts/comfy-ui/list-history.ts +31 -0
  41. package/src/scripts/comfy-ui/run-ws.ts +23 -0
  42. package/src/scripts/ws/send-feature-flags.ts +23 -0
  43. package/src/server-stdio.ts +23 -0
  44. package/src/services/business.ts +194 -0
  45. package/src/services/dynamic-tool.ts +303 -0
  46. package/src/services/index.ts +19 -0
  47. package/src/services/storage/asset-storage.ts +48 -0
  48. package/src/services/storage/index.ts +2 -0
  49. package/src/services/storage/workflow-storage.ts +192 -0
  50. package/src/services/task/execution.ts +69 -0
  51. package/src/services/task/fetch.ts +131 -0
  52. package/src/services/task/index.ts +3 -0
  53. package/src/services/task/wait.ts +294 -0
  54. package/src/services/workflow/executor.ts +134 -0
  55. package/src/services/workflow/index.ts +1 -0
  56. package/src/tools/handlers/core-manual.ts +28 -0
  57. package/src/tools/handlers/index.ts +22 -0
  58. package/src/tools/handlers/interrupt-prompt.ts +35 -0
  59. package/src/tools/handlers/list-models.ts +51 -0
  60. package/src/tools/handlers/mount-workflow.ts +88 -0
  61. package/src/tools/handlers/prompt-result.ts +35 -0
  62. package/src/tools/handlers/prompts.ts +61 -0
  63. package/src/tools/handlers/queue-custom-prompt.ts +164 -0
  64. package/src/tools/handlers/queue-prompt.ts +170 -0
  65. package/src/tools/handlers/save-custom-workflow.ts +67 -0
  66. package/src/tools/handlers/save-task-assets.ts +82 -0
  67. package/src/tools/handlers/system-status.ts +30 -0
  68. package/src/tools/handlers/task-detail.ts +35 -0
  69. package/src/tools/handlers/tool-status-map.ts +33 -0
  70. package/src/tools/handlers/upload-assets.ts +82 -0
  71. package/src/tools/handlers/workflow-api.ts +46 -0
  72. package/src/tools/handlers/workflows-catalog.ts +79 -0
  73. package/src/tools/index.ts +101 -0
  74. package/src/types/common.ts +74 -0
  75. package/src/types/dynamic-tool.ts +85 -0
  76. package/src/types/enums/result.ts +29 -0
  77. package/src/types/execute.ts +24 -0
  78. package/src/types/object-info.ts +43 -0
  79. package/src/types/result.ts +126 -0
  80. package/src/types/task.ts +118 -0
  81. package/src/types/workflow.ts +111 -0
  82. package/src/types/ws.ts +80 -0
  83. package/src/utils/format.ts +134 -0
  84. package/src/utils/mcp-helpers.ts +110 -0
  85. package/src/utils/special-node-handler.ts +36 -0
  86. package/src/utils/workflow-converter.ts +140 -0
  87. package/src/utils/ws.ts +219 -0
  88. package/tsconfig.json +18 -0
package/README-en.md ADDED
@@ -0,0 +1,635 @@
1
+ # ComfyUI-MCP-Server - ComfyUI Model Context Protocol Integration
2
+
3
+ <p align="center">
4
+ [<a href="./README.md">简体中文</a>]
5
+ [<a href="./README-en.md">ENGLISH</a>]
6
+ </p>
7
+
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
9
+ [![Node.js](https://img.shields.io/badge/Node.js-18+-success)](https://nodejs.org/)
10
+ [![MCP Protocol](https://img.shields.io/badge/Protocol-MCP-purple)](https://modelcontextprotocol.io/)
11
+ [![Static Badge](https://img.shields.io/badge/MetaBrainLabs-Org?logo=github&label=GitHub)](https://github.com/orgs/MetaBrain-Labs)
12
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript)
13
+ [![GitHub stars](https://img.shields.io/github/stars/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript?style=social)](https://github.com/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript/stargazers)
14
+ [![GitHub forks](https://img.shields.io/github/forks/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript?style=social)](https://github.com/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript/network)
15
+
16
+ > [!NOTE]
17
+ > **⭐ If you like this project or find it helpful, please give it a Star. Your support is our motivation for continuous improvement!**
18
+
19
+ **ComfyUI-MCP-Server is an MCP (Model Context Protocol) based server implementation that transforms user-defined workflows in ComfyUI into parameter-configurable MCP tools, allowing AI Agents to use them directly.**
20
+
21
+ > This project provides two independent language versions, **Python** and **TypeScript**, with functionally equivalent capabilities. You can choose based on your needs:
22
+ >
23
+ > [![Python Version](https://img.shields.io/badge/ComfyUIMCPServer-Server?logo=python&label=Python)](https://github.com/MetaBrain-Labs/ComfyUI-MCP-Server-Python)
24
+ > [![Typescript Version](https://img.shields.io/badge/ComfyUIMCPServer-Server?logo=typescript&label=TypeScript)](https://github.com/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript)
25
+ >
26
+ > Note: The Python version contains more experimental features, while the TypeScript version is more stable.
27
+
28
+ ## 📋 Project Features
29
+
30
+ Through this project, you can empower AI assistants (such as `Claude Desktop`, `Trae`, `Dify`, etc.) with powerful multimedia generation capabilities by connecting to ComfyUI:
31
+
32
+ | Feature | Description |
33
+ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34
+ | **Image/Video Generation** | Drives AI assistants to generate multimedia files like images and videos using custom user workflows; allows AI to modify user-exposed node parameters to fine-tune results. |
35
+ | **Custom Workflow Import** | Supports manually importing ComfyUI API format JSON files into the server's workflow directory. Automatically validated and mounted for immediate use. |
36
+ | **Asset Management** | Automatically downloads and saves generated multimedia files to a specified local directory after completion. |
37
+ | **Advanced Custom Execution** | Allows AI to directly provide the complete API JSON to schedule ComfyUI (Advanced Mode). |
38
+ | **Asset Uploading** | Supports uploading image/video assets from local paths or HTTP URLs to ComfyUI's input directory for direct workflow usage. |
39
+
40
+ ## ✨ Project Highlights
41
+
42
+ - 🔌 **Workflow as a Tool**: Abstracts ComfyUI node graphs into tools usable by Agents.
43
+ - 🎛️ **Custom Parameter Exposure**: Precisely defines which parameters are visible externally in the workflow, limiting AI operations within the exposed scope to prevent model hallucinations and misoperations.
44
+ - 🔧 **Zero-Intrusion Integration**: Plugs and plays immediately without modifying the ComfyUI core or installing any mandatory plugins.
45
+ - 📥 **Custom Workflow Import**: Manually import API-format workflow JSON files, available to the Agent immediately after passing validation without restarting the service.
46
+ - 📂 **Asset Management**: Supports automatic uploading of resources to ComfyUI from local paths or web URLs.
47
+ - ⚡ **Stream and Progress Support**: Supports generating progress reports (requires Client/Host support).
48
+ - 🌍 **Internationalization Support**: Built-in bilingual support (zh-CN/en).
49
+ - 🧩 **Standard MCP Adaptation**: Fully supports STDIO and Streamable HTTP communication protocols.
50
+ - 🔬 **Skills Support**: Includes project skills manual SKILL.md, deeply optimized for AI assistants supporting Skills.
51
+
52
+ For more details, please check [Why Choose Us](./docs/en/md/why-us.md)
53
+
54
+ ## 🧰 Available Tools
55
+
56
+ AI agents can call the following built-in tools via the MCP protocol:
57
+
58
+ | Tool | Tool Name | Description |
59
+ | ----------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
60
+ | `get_core_manual` | Get Core Manual | [System Guide] Core protocol and operation dictionary. Must be read before initializing or calling other tools to get the latest parameter filling strategies and error recovery mechanisms. |
61
+ | `get_workflows_catalog` | Get Workflow Catalog | [Directory Search] Retrieve a list of all workflows supported by the current server. Commands involving image generation must exactly match this list. Forging or guessing workflow names is strictly prohibited. |
62
+ | `get_workflow_API` | Get Workflow Details | [Workflow API] Read the full underlying topology JSON of the target workflow. Large volume, only invoked when troubleshooting abnormal execution of underlying logic. Strictly prohibited in routine business context to prevent context pollution. |
63
+ | `mount_workflow` | Mount Workflow | [Parameter Mounting] Extract the supported interaction parameter Schema for the target generation task (hiding connection details). Before submitting a workflow task, this interface must be called to obtain a valid parameter key name table. |
64
+ | `queue_prompt` | Execute Workflow Task | [Task Submission] Submit a task Prompt to the queue. Deeply automatically schedules computing nodes and synchronizes progress in real-time with the Host. Must ensure all key names have passed mount validation; forging key names is strictly prohibited. |
65
+ | `queue_custom_prompt` | Execute Custom Workflow | [Advanced Mode] Submit the complete native ComfyUI API Prompt JSON directly to the queue. Only open for debugging underlying solutions or responding to clear expert instructions. Strictly prohibited for regular tasks. |
66
+ | `save_custom_workflow` | Save Custom Workflow | [Save Workflow] Save a custom parameterized workflow to the server's workflow directory, subsequently automatically performing syntax validation and mounting. The submitted JSON must conform to the specification (contains at least one valid ==name== node for mounting), otherwise the save will be rejected. |
67
+ | `save_task_assets` | Save Task Assets | [Save Generated Assets] Get the execution history for a specified task (prompt_id), and download/save all generated multimedia artifacts (images, videos, GIFs, etc.) to a specified local directory. |
68
+ | `interrupt_prompt` | Cancel Task | [Task Cancellation] Cancel the computation process of a specific `prompt_id` and forcefully remove the waiting item in the queue. |
69
+ | `get_prompt_result` | Get Task Result | [Output Snapshot & Assets] Get a snapshot of the nodes after a specific Prompt execution finishes, extract generated target media files (image/video links), or backtrack Traceback for error diagnosis. |
70
+ | `get_system_status` | Get System Status | [System Monitoring] Collect memory, VRAM, and Python runtime metrics to troubleshoot underlying abnormalities such as OOM or service deadlocks. |
71
+ | `list_models` | Retrieve Model Files | [Model Directory] Poll the local disk model storage area. When parameters involve specific model files, this interface must be called first to enumerate calibration. Fabricating model filenames out of thin air is strictly prohibited. |
72
+ | `upload_assets` | Upload Assets to ComfyUI | [Upload Files] Upload a local file or network URL to the ComfyUI server's input directory so it can be directly applied in the workflow. |
73
+
74
+ ## 🏆 Why Choose Us?
75
+
76
+ | Feature | ComfyUI MCP Server | Other Similar Projects |
77
+ | --------------- | ------------------ | --------------------- |
78
+ | Custom Parameter Exposure | ✅ Supported | ❌ Limited or not supported |
79
+ | No ComfyUI Modification Required | ✅ Fully supported | ❌ Usually requires modification or plugin |
80
+ | Natural Language Interaction | ✅ Supported | ❌ Usually requires API calls |
81
+ | Real-Time Progress Notification | ✅ Supported | ❌ Limited support |
82
+ | Multiple Transport Modes | ✅ STDIO + HTTP | ❌ Usually only one mode |
83
+ | Internationalization Support | ✅ Built-in | ❌ Usually English only |
84
+ | Session Management | ✅ Robust | ❌ Basic or none |
85
+
86
+ For more details, please check [Why Choose Us](./docs/en/md/Project-Advantages.md)
87
+
88
+ ## 🎬 Demo Videos
89
+
90
+ ### Default Mode
91
+
92
+ Click the image below to watch the demo video.
93
+
94
+ <p align="center">
95
+ <a href="https://www.youtube.com/watch?v=Aqi7yK7pPag">
96
+ <img src="https://img.youtube.com/vi/Aqi7yK7pPag/0.jpg" width="700">
97
+ </a>
98
+ </p>
99
+
100
+ ### API JSON Mode
101
+
102
+ Click the image below to watch the demo video.
103
+
104
+ <p align="center">
105
+ <a href="https://www.youtube.com/watch?v=fGEUCbfrqK8">
106
+ <img src="https://img.youtube.com/vi/fGEUCbfrqK8/0.jpg" width="700">
107
+ </a>
108
+ </p>
109
+
110
+ ## 🚀 Quick Start
111
+
112
+ Start the project quickly in just two steps.
113
+
114
+ > Reminder: After installing and running the project, you need to read the [[Usage Tutorial](#usage)], otherwise you will not be able to use workflow-related functions.
115
+
116
+ ### Prerequisites (Mandatory)
117
+
118
+ Before starting this project, ensure that the following software is installed on your system:
119
+
120
+ - Node.js 18+ [[Official Link](https://nodejs.org/)]
121
+ - ComfyUI 0.9.1+ [[Official Link](https://github.com/comfyanonymous/ComfyUI)]
122
+ - MCP Client/AI Agent, such as Claude Desktop, Cursor, etc.
123
+
124
+ ---
125
+
126
+ ### Step 1: Install Project and Dependencies
127
+
128
+ **1. Clone this project**
129
+ Execute the following command in your terminal:
130
+
131
+ ```bash
132
+ git clone https://github.com/MetaBrain-Labs/ComfyUI-MCP-Server-TypeScript.git
133
+ ```
134
+
135
+ **2. Navigate to the project directory**
136
+
137
+ ```bash
138
+ cd ComfyUI-MCP-Server-TypeScript
139
+ ```
140
+
141
+ **3. Install dependencies**
142
+
143
+ ```bash
144
+ npm install
145
+ ```
146
+
147
+ ---
148
+
149
+ ### Step 2: Configure Environment and Start the Project
150
+
151
+ #### 1. Project Environment Configuration
152
+
153
+ Go to the project root directory and modify the configurations in the `.env` file according to your actual setup.
154
+ For detailed configuration instructions, please refer to: [[Environment Variables](#config)]
155
+
156
+ #### 2. Connect and Run the Project
157
+
158
+ Choose a transport method according to your requirements to start the project:
159
+
160
+ > [!TIP]
161
+ > **MCP Transport Mechanisms**
162
+ >
163
+ > The MCP protocol currently defines two standard transport mechanisms for client-server communication:
164
+ >
165
+ > - STDIO
166
+ > - Streamable HTTP
167
+ >
168
+ > This project supports both. Choose based on your MCP client's capabilities.
169
+ >
170
+ > You are responsible for ensuring that the use of these servers complies with relevant terms, as well as any laws, rules, regulations, policies, or standards applicable to you.
171
+
172
+ **Mode 1: STDIO Connection (Recommended for local clients like Claude Desktop)**
173
+
174
+ - **MCP Client Startup:**
175
+ Copy the following JSON and paste/modify it in your MCP client's configuration.
176
+
177
+ > [!NOTE]
178
+ >
179
+ > For methods to configure the MCP Server in some MCP clients, see: [[Examples](#examples)]
180
+ >
181
+ > For other project settings, please modify them in the environment variables. For parameter details, check: [[Environment Variables](#config)]
182
+ >
183
+ > If ComfyUI is running in the cloud, please set "SYNC_MODE" to "manual".
184
+
185
+ ```json
186
+ {
187
+ "mcpServers": {
188
+ "comfy-ui-advanced": {
189
+ "command": "npx",
190
+ "args": [
191
+ "tsx",
192
+ "<Absolute path to the project root directory, e.g., D:/ComfyUI-MCP-Server-TypeScript>"
193
+ ],
194
+ "env": {
195
+ "LOCALE": "en",
196
+ "MCP_SERVER_URL": "http://127.0.0.1:8189/mcp",
197
+ "MCP_SERVER_IP": "127.0.0.1",
198
+ "MCP_SERVER_PORT": "8189",
199
+ "COMFY_UI_SERVER_IP": "http://127.0.0.1:8188",
200
+ "COMFY_UI_SERVER_HOST": "127.0.0.1",
201
+ "COMFY_UI_SERVER_PORT": "8188",
202
+ "SYNC_MODE": "timed",
203
+ "SYNC_POLL_INTERVAL_SECONDS": "3",
204
+ "SYNC_EVENT_FALLBACK_INTERVAL_SECONDS": "300",
205
+ "ONDEMAND_REFRESH_COOLDOWN_SECONDS": "3",
206
+ "COMFY_UI_INSTALL_PATH": "",
207
+ "WORKFLOW_NAME_REGEX": "^==(.+?)==$",
208
+ "WORKFLOW_PARAM_REGEX": "^=>(.+)$",
209
+ "LOG_LEVEL": "INFO"
210
+ }
211
+ }
212
+ }
213
+ }
214
+ ```
215
+
216
+ - **Terminal Startup:**
217
+ ```bash
218
+ # For starting via terminal connection, no JSON config is required. Directly execute in the root directory:
219
+ npm run dev
220
+ ```
221
+
222
+ **Mode 2: StreamHTTP Connection (Recommended for networked/distributed deployment)**
223
+
224
+ - **MCP Client Startup:**
225
+ StreamHTTP project settings are specified in [[.env](./.env)], no need to configure them in the JSON below.
226
+
227
+ > [!NOTE]
228
+ >
229
+ > For methods to configure the MCP Server in some MCP clients, see: [[Examples](#examples)]
230
+ >
231
+ > Currently, few MCP Client/Hosts support StreamHTTP, use it based on your needs.
232
+ >
233
+ > If ComfyUI is running in the cloud, please set "SYNC_MODE" to "manual" in [[.env](./.env)].
234
+
235
+ ```json
236
+ {
237
+ "mcpServers": {
238
+ "comfy-ui-advanced-http": {
239
+ "url": "http://127.0.0.1:8189/mcp"
240
+ }
241
+ }
242
+ }
243
+ ```
244
+
245
+ - **Terminal Startup:**
246
+ ```bash
247
+ # Start Streamable HTTP
248
+ npm run dev
249
+ ```
250
+
251
+ At this point, project deployment and startup are complete. If you need to debug tools, please continue reading below; otherwise, skip directly to the [[Usage Tutorial](#usage)].
252
+
253
+ ### Debugging Tools (MCP Inspector)
254
+
255
+ Inspector is the official MCP debugging tool provided by MCP. It is recommended to use StreamHTTP for the Inspector connection.
256
+
257
+ - Clone the project
258
+ - Install dependencies
259
+ ```bash
260
+ npm install
261
+ ```
262
+ - Start the Server using the StreamHTTP connection method:
263
+ ```bash
264
+ # 1. Start HTTP service in Terminal A
265
+ npm run dev
266
+ ```
267
+ - Start Inspector:
268
+ ```bash
269
+ # 2. Start Inspector in Terminal B
270
+ npm run inspector
271
+ ```
272
+
273
+ Once started, a similar address below will appear in the console. Copy the URL to your browser to begin debugging the tools:
274
+
275
+ ```bash
276
+ # MCP_PROXY_AUTH_TOKEN changes every time you start, so you must update the link each time
277
+ http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=d66fcf6cbbb3723c...
278
+ ```
279
+
280
+ After Inspector starts successfully, refer to the browser page configuration:
281
+
282
+ ![Inspector Configuration Example](./docs/en/content/public/inspector-example.png)
283
+
284
+ <a id="usage"></a>
285
+
286
+ ## 📖 Usage Tutorial
287
+
288
+ This project requires simple specific markup on ComfyUI workflows so the AI Agent can accurately identify and call them. Available workflows can be added in two ways:
289
+
290
+ ### Markup Rules (Must Understand)
291
+
292
+ Regardless of the method used to add available workflows, the following marker nodes must be added to the workflow:
293
+
294
+ #### 1. Define Tool Name and Description (Mandatory)
295
+
296
+ - Create a new `PrimitiveNode` or `PrimitiveStringMultiline` node, **do not connect it to any other nodes**.
297
+ - Double-click to modify the node title to `==Your Workflow Name==` (e.g., `==TextToImage-Basic==`). **Note: This is the tool name the AI Agent will see and must be unique.**
298
+ - In this node's text input box, write the **functional description** of this workflow (e.g., "This is a basic text-to-image process, suitable for generating anime-style images"). **The clearer the description, the better the AI can judge when to call it.**
299
+
300
+ > [!TIP]
301
+ > **Automatic Filtering:** This project will automatically ignore workflows missing a `==Workflow Name==` format to ensure the AI only operates within safe predefined bounds, preventing model hallucinations.
302
+
303
+ ![Workflow Example](./docs/en/content/public/workflow_name_example.png)
304
+
305
+ #### 2. Expose Modifiable Parameters (Optional)
306
+
307
+ - If you want the AI to dynamically modify certain node properties (e.g., positive prompt, dimensions, random seed), you must expose their parameters.
308
+ - Locate the target node (e.g., `CLIP Text Encode (Prompt)` node).
309
+ - Double-click to change its title to `=>Parameter Description` (e.g., `=>Positive Prompt` or `=>Generated Image Width`).
310
+ - Once saved, this server will automatically parse it into a variable parameter for the MCP tool, allowing the AI to fill in values as needed.
311
+
312
+ > [!TIP]
313
+ > **Automatic Filtering:** This project automatically ignores all other regular node parameters and node-connection parameters without the `=>` title prefix to ensure the AI only operates within the defined safe scope.
314
+
315
+ ![Parameter Example](./docs/en/content/public/workflow_parameter_example.png)
316
+
317
+ ---
318
+
319
+ ### Method 1: Set up in the ComfyUI Canvas (Recommended)
320
+
321
+ Suitable for users actively running ComfyUI supporting the new workflow saving mechanism:
322
+
323
+ 1. Organize nodes in ComfyUI according to the **Markup Rules** above.
324
+ 2. Click the **Save** button in the ComfyUI panel.
325
+ > It is recommended to run a **Queue Prompt** test once yourself after saving to ensure the workflow runs properly.
326
+ 3. The workflow will be saved in ComfyUI's user data directory (usually `userdata/workflows/`).
327
+ 4. **The workflow effective time depends on the `SYNC_MODE` config**:
328
+ - `timed` mode (default): The MCP server quietly polls in the background, automatically catches the newly saved workflow, and immediately mounts it as an available AI Agent tool upon passing the auto-verification.
329
+ - `manual` mode: Triggers an on-demand scan only when the AI Agent tries to invoke the tool catalog.
330
+ - `push` mode (experimental): Requires a ComfyUI plugin, actively pushing the workflow to the server in real-time upon saving.
331
+
332
+ ### Method 2: Manually Import API Format JSON files
333
+
334
+ Suitable for externally importing workflows or writing pure API format workflow files directly:
335
+
336
+ 1. Prepare your ComfyUI API format JSON file.
337
+ 2. Open the JSON file in a text editor and add the following to comply with the **Core Markup Rules**:
338
+ - **Tool Name:** Add the following anywhere (as a node representation):
339
+
340
+ ```json
341
+ "99": {
342
+ "inputs": {
343
+ "value": "**Functional Description**"
344
+ },
345
+ "class_type": "PrimitiveStringMultiline",
346
+ "_meta": {
347
+ "title": "==Workflow Name=="
348
+ }
349
+ }
350
+ ```
351
+
352
+ > "99" is just an example, please use an unoccupied node ID in actual use.<br>
353
+ > After adding, ensure the JSON formatting is correct. Commas must be attached to the end of each node as necessary, otherwise the workflow will be unusable.
354
+ - **Exposed Parameters:** Locate the node where the AI should alter parameters. Add or modify `"title": "=>Parameter Description"` in the `_meta` object.
355
+
356
+ 3. Directly place the modified JSON file into the `workflow/` directory of this project (if the directory doesn't exist, create it manually).
357
+ 4. **The mechanism for the workflow to become effective is the same as above**, based on the `SYNC_MODE`:
358
+ - `timed` mode (default): The MCP server regularly scans this directory, automatically parses parameters, and completes mounting.
359
+ - `manual` / `push` mode: Workflows load on demand the next time the AI Agent requests workflows or executes tools.
360
+
361
+ > [!NOTE]
362
+ >
363
+ > **Notice Regarding Errors/Failed Tasks in the Queue**
364
+ >
365
+ > While using this project, red boxes indicating errors or failed tasks may occasionally appear in your ComfyUI Queue. This happens because the MCP server needs to silently verify your workflow topology and node legality via the ComfyUI engine in the background to confirm if it's fit for AI invocation. **This is normal and will absolutely not affect other image generations or the AI's standard operations. You may safely ignore it.**
366
+
367
+ <a id="config"></a>
368
+
369
+ ## ⚙️ Environment Configuration
370
+
371
+ > [!TIP]
372
+ > **Notice**
373
+ >
374
+ > Below are all the environment variables for this server and their introductions. Please read this first.
375
+ >
376
+ > Some of the environment configuration parameters below are not fully enabled yet; any disabled ones are intended for future use.
377
+
378
+ <details open>
379
+ <summary>Click to view full configuration file instructions</summary>
380
+
381
+ ```
382
+ # =============================================================================
383
+ # ComfyUI MCP Server - Configuration
384
+ # Configuration instructions:
385
+ # [User Config] Modify this section based on your deployment environment.
386
+ # [System Config] Keep the defaults, do not modify.
387
+ # =============================================================================
388
+
389
+ # =============================================================================
390
+ # [User Config]
391
+ # Modify this section based on your deployment environment.
392
+ # =============================================================================
393
+
394
+ # Language for MCP tool descriptions. Optional values: en | zh
395
+ LOCALE=en
396
+
397
+ # -----------------------------------------------------------------------------
398
+ # ComfyUI Server Connection
399
+ # -----------------------------------------------------------------------------
400
+
401
+ # Full URL of your ComfyUI server. No trailing slash.
402
+ COMFY_UI_SERVER_IP="http://192.168.0.171:8188"
403
+
404
+ # Host (without protocol) and port. Used separately for WebSocket connections.
405
+ COMFY_UI_SERVER_HOST="192.168.0.171"
406
+ COMFY_UI_SERVER_PORT="8188"
407
+
408
+ # -----------------------------------------------------------------------------
409
+ # Sync Mode
410
+ # -----------------------------------------------------------------------------
411
+
412
+ # Controls how the server detects workflow updates from ComfyUI.
413
+ #
414
+ # timed — Background loop polls ComfyUI at a fixed interval. (default)
415
+ #
416
+ # push — [Experiments] ComfyUI plugin sends real-time save events; long fallback poll as safety net.
417
+ # Requires COMFY_UI_INSTALL_PATH (must be on same machine as ComfyUI).
418
+ #
419
+ # manual — No background loop. Refresh only when tools are called
420
+ # (get_workflows_catalog / mount_workflow / queue_prompt).
421
+ #
422
+ SYNC_MODE=timed
423
+
424
+ # Polling interval in seconds for timed mode.
425
+ SYNC_POLL_INTERVAL_SECONDS=3
426
+
427
+ # Fallback polling interval in seconds for push mode (safety net for missed events).
428
+ SYNC_EVENT_FALLBACK_INTERVAL_SECONDS=300
429
+
430
+ # Cooldown in seconds between manual mode refreshes.
431
+ # Prevents excessive ComfyUI API calls when tools are called in quick succession.
432
+ ONDEMAND_REFRESH_COOLDOWN_SECONDS=30
433
+
434
+ # -----------------------------------------------------------------------------
435
+ # Push Mode Plugin (Required only if SYNC_MODE=push)
436
+ # -----------------------------------------------------------------------------
437
+
438
+ # Absolute path to your LOCAL ComfyUI installation root directory.
439
+ # Required when SYNC_MODE=push: MCP Server will automatically deploy a lightweight
440
+ # backend plugin that pushes workflow save events in real-time.
441
+ # Leave blank if ComfyUI runs on a remote machine or if using timed/manual mode.
442
+ #
443
+ # Windows Example: COMFY_UI_INSTALL_PATH=C:/ComfyUI
444
+ # Linux Example: COMFY_UI_INSTALL_PATH=/home/user/ComfyUI
445
+ COMFY_UI_INSTALL_PATH=
446
+
447
+ # -----------------------------------------------------------------------------
448
+ # Workflow Marker Patterns
449
+ # -----------------------------------------------------------------------------
450
+
451
+ # Regex identifying the workflow name node (title of a PrimitiveStringMultiline node).
452
+ # Must contain ONE capture group that extracts the MCP tool name.
453
+ # Default matches titles like "==my_workflow=="
454
+ WORKFLOW_NAME_REGEX=^==(.+?)==$
455
+
456
+ # Regex identifying configurable parameter nodes.
457
+ # Must contain ONE capture group that extracts the parameter description.
458
+ # Default matches titles like "=>prompt text"
459
+ WORKFLOW_PARAM_REGEX=^=>(.+)$
460
+
461
+ # =============================================================================
462
+ # [System Config]
463
+ # Internal settings — change only if you know what you are doing.
464
+ # =============================================================================
465
+
466
+ # -----------------------------------------------------------------------------
467
+ # MCP Server Location
468
+ # -----------------------------------------------------------------------------
469
+
470
+ # MCP server bind address and listening port. (The MCP Client connects here)
471
+ MCP_SERVER_URL="http://192.168.0.192:8189/mcp"
472
+ MCP_SERVER_IP="192.168.0.192"
473
+ MCP_SERVER_PORT="8189"
474
+
475
+ # -----------------------------------------------------------------------------
476
+ # Logging configuration
477
+ # -----------------------------------------------------------------------------
478
+
479
+ # Minimum log level written to stderr.
480
+ # DEBUG | INFO | WARNING | ERROR (default: INFO)
481
+ LOG_LEVEL=INFO
482
+
483
+ # Optional absolute path for a log file.
484
+ # When set, logs are written to BOTH stderr and this file.
485
+ # Leave blank to disable file logging.
486
+ # LOG_FILE=
487
+
488
+ # Log file rotation size. Default: 10 MB
489
+ # LOG_ROTATE=10 MB
490
+
491
+ # Number of rotated log files to retain. Default: 7
492
+ # LOG_RETAIN=7
493
+ ```
494
+
495
+ </details>
496
+
497
+ <a id="examples"></a>
498
+
499
+ ## Examples
500
+
501
+ ### Claude Desktop
502
+
503
+ Click the image below to watch the demo video.
504
+
505
+ <p align="center">
506
+ <a href="https://www.youtube.com/watch?v=gC78RJ8wTRU">
507
+ <img src="https://img.youtube.com/vi/gC78RJ8wTRU/0.jpg" width="700">
508
+ </a>
509
+ </p>
510
+
511
+ ### Trae
512
+
513
+ Click the image below to watch the demo video.
514
+
515
+ <p align="center">
516
+ <a href="https://www.youtube.com/watch?v=V-c_FrojPt0">
517
+ <img src="https://img.youtube.com/vi/V-c_FrojPt0/0.jpg" width="700">
518
+ </a>
519
+ </p>
520
+
521
+ ## 🛠️ Troubleshooting
522
+
523
+ ### Frequently Asked Questions
524
+
525
+ 1. **WebSocket connection failed**
526
+ - Ensure ComfyUI is running.
527
+ - Check ComfyUI's WebSocket port configuration.
528
+ - Confirm `COMFY_UI_SERVER_HOST` and `PORT` are properly configured in `.env`.
529
+ 2. **Workflow execution failed**
530
+ - Verify that submitted parameter types match target node requirements (Schema).
531
+ - Check the ComfyUI console for missing Custom Nodes errors.
532
+ - Inspect the MCP Client/Host log corresponding to the MCP Server for detailed error messages.
533
+ 3. **Session timeout**
534
+ - Default HTTP session timeout is 30 minutes. For extremely long video rendering, adjust the `SESSION_TIMEOUT` constant in the code to extend it.
535
+
536
+ ## 🔬 Technical Details
537
+
538
+ ### Core Protocols
539
+
540
+ 1. **MCP (Model Context Protocol)**
541
+
542
+ [What is the Model Context Protocol (MCP)? - Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro)
543
+
544
+ 2. **JSON-RPC 2.0**
545
+
546
+ [JSON-RPC 2.0 Specification](https://www.jsonrpc.org/specification)
547
+
548
+ 3. **WebSocket**
549
+
550
+ [The WebSocket API (WebSockets) - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)
551
+
552
+ 4. **REST API**
553
+
554
+ [About the REST API - GitHub Docs](https://docs.github.com/en/rest/about-the-rest-api/about-the-rest-api?apiVersion=2022-11-28)
555
+
556
+ ### Technical Limitations and Security Considerations
557
+
558
+ - **Dependencies**: Strongly relies on ComfyUI's native API and WebSocket. Graph imports lacking a standard ComfyUI format are not supported.
559
+ - **Security Validation**: The current version doesn't implement strong authentication (Token/Auth). Please **DO NOT** run this exposed to public networks. It is advised to configure HTTPS and supplementary gateway access controls for production environments.
560
+ - **Resource Consumption**: High concurrency may cause the ComfyUI host machine's VRAM to run out (OOM). Please limit the concurrent request frequency inside your AI system prompts.
561
+
562
+ ### **Workflow Validation Accuracy**
563
+
564
+ This project divides workflow validation accuracy into three modes:
565
+
566
+ - Validated via Historical Tasks: Verified against **historical tasks that completed with a SUCCESS status**.
567
+ - This ensures a high workflow success rate as long as core models and dependencies are uncompromised.
568
+ - Validated via Initial Workflow only: Evaluated on workflows **without historical tasks or if the newest task execution time predates the workflow's latest modification**.
569
+ - Only preliminary verification runs here—guaranteeing node-to-node connectivity, but lacking assurance for successful end-to-end execution.
570
+ - To secure a high image-generation success rate, you may manually run workflows first. A logged task track gets created upon an end-to-end success, establishing it as historically verified for the AI tools.
571
+ - External Import: **API JSON files provided directly by the AI/user**. Unverified before workflow execution with no guarantee of successful end-to-end processing.
572
+ - No verification executes here; everything relies off the ComfyUI backend. For example, if API JSON formats, nodes, or parameter ranges have issues, the ComfyUI backend intercepts them, outputting matching error prompts.
573
+ - Seen as a fallback image-generation resort when the historical task or initial workflow methods hit dead ends.
574
+
575
+ ## 🗺️ Roadmap
576
+
577
+ > [!TIP]
578
+ > **Notice**
579
+ >
580
+ > We are actively expanding project functionality. If you have good suggestions, feel free to open an Issue!
581
+
582
+ - [ ] **Enhanced Workflow Parsing**: Support for more complex nested nodes and dynamic parameter extraction.
583
+ - [ ] **Cloud Service Integration**: Adapt for mainstream ComfyUI cloud hosting platforms (Authentication and API mapping).
584
+ - [ ] **Connection Optimization**: Improve reconnection mechanisms and state maintenance for StreamHTTP disconnects.
585
+ - [ ] **Performance Dashboard**: Add visible tracking for resource consumption and queued tasks.
586
+ - [ ] **ComfyUI Plugin**: Develop a ComfyUI plugin to seamlessly integrate with the MCP Service.
587
+
588
+ ## 🤝 Contribution
589
+
590
+ Contributions are welcome! Please feel free to open a Pull Request.
591
+
592
+ ### Contribution Guidelines
593
+
594
+ 1. Fork the project
595
+ 2. Create a Feature branch
596
+ 3. Commit your changes
597
+ 4. Push to the branch
598
+ 5. Open a Pull Request
599
+
600
+ ## 📄 License
601
+
602
+ This project is generously open-sourced under the **MIT** License - see the [LICENSE](./LICENSE) file for details.
603
+
604
+ _This project is driven by a third-party community open-source effort and is not an official ComfyUI product; incubated and contributed by [MetaBrain-Labs](https://github.com/MetaBrain-Labs)._
605
+
606
+ ## 📬 Contact Information
607
+
608
+ _(Note: Due to work schedules, emails may not receive immediate replies. Please prioritize submitting GitHub Issues.)_
609
+
610
+ ### Issue/Request Submission
611
+
612
+ [MetaBrain-Labs(metabrain0302@163.com)](mailto:metabrain0302@163.com)
613
+
614
+ ### Contributors
615
+
616
+ `TypeScript` version author:
617
+
618
+ [LaiFQZzr(lfq2376939781@gmail.com)](mailto:lfq2376939781@gmail.com)
619
+
620
+ [![Static Badge](https://img.shields.io/badge/LaiFQZzr-User?logo=github&label=GitHub)](https://github.com/LaiFQzzr)
621
+
622
+ `Python` version author:
623
+
624
+ [OldDeer(q1498823915@outlook.com)](mailto:q1498823915@outlook.com)
625
+
626
+ [![Static Badge](https://img.shields.io/badge/OldDeer-User?logo=github&label=GitHub)](https://github.com/OldDeer00)
627
+
628
+ ## Disclaimer
629
+
630
+ > [!WARNING]
631
+ > **Disclaimer**
632
+ >
633
+ > We currently **DO NOT** have an official website. Any related websites you see online are entirely unofficial and unaffiliated with this open-source project. Please screen risks cautiously yourselves.
634
+ >
635
+ > **Also, we provide absolutely no paid services. Users please stay alert regarding Token expenses. Losses accrued are purely unaffiliated with our organization.**