ComfyUI图像生成服务器

ImageMCP是一个MCP协议服务器,为LM Studio等客户端提供通过ComfyUI的Stable Diffusion工作流生成图像的功能。

  • by AvidGameFan
  • C#
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 AvidGameFan/ImageMCP

使用说明

# ImageMCP-ComfyUI图像生成MCP服务器

MCP(模型上下文协议)服务器,使LM Studio和其他MCP兼容客户端能够使用ComfyUI的稳定扩散工作流生成图像。

🎯 概述

ImageMCP通过为ComfyUI提供干净的MCP接口,弥合了AI语言模型和图像生成之间的差距。这允许语言模型在对话期间按需生成图像。

💡 注: 以下文档包括开发细节。如果你想跳进去使用,请参阅 快速入门指南.

🏗️ 建筑

LM Studio ↔ MCP Protocol (HTTP) ↔ ImageMCP Server ↔ WebSocket ↔ ComfyUI API

关键部件:

  • MCP 服务器:通过HTTP(EDMCP风格)处理JSON-RPC 2.0协议
  • 工作流模板管理器:解析和修改ComfyUI JSON工作流
  • ComfyUI客户端:与ComfyUI的WebSocket/HTTP通信
  • 自动格式检测:处理UI和API格式工作流

✨ 特性

  • ✅ HTTP MCP支持:用于LM Studio集成的基于HTTP的JSON-RPC 2.0
  • ✅ ComfyUI工作流集成:解析、修改和执行ComfyUI工作流
  • ✅ 智能快速注射:自动查找和替换CLIP文本编码节点
  • ✅ 自动格式检测:同时使用UI和API格式工作流
  • ✅ 可配置模板:支持自定义工作流JSON文件
  • ✅ WebSocket监控:通过ComfyUI WebSocket实时跟踪进度
  • ✅ Base64图像返回:MCP格式的直接图像数据
  • ✅ 综合录井:与Microsoft进行详细的执行跟踪。扩展。日志记录
  • ✅ 重试逻辑:历史检索的自动重试
  • ✅ 错误处理:优雅的超时和错误管理

📋 先决条件

  1. .NET 10 SDK - 下载
  2. Comfy用户界面 -正在运行启用WebSocket API的实例
    • 下载地址:https://github.com/comfyanonymous/ComfyUI
    • 默认URL: ws://127.0.0.1:8188
  3. LM工作室 -用于MCP客户端支持
    • 下载地址:https://lmstudio.ai/
  4. 稳定扩散模型 -ComfyUI中至少有一个检查点模型

🚀 入门指南

步骤1:安装ComfyUI

# Clone ComfyUI
git clone https://github.com/comfyanonymous/ComfyUI.git
cd ComfyUI

# Install dependencies (Python 3.10+)
pip install -r requirements.txt

# Desktop version (optional)
Installing the ComfyUI desktop app is optional but recommended for ease of use.

# Download a model (e.g., Stable Diffusion XL)
# Place models in: ComfyUI/models/checkpoints/
# Example: sd_xl_base_1.0_0.9vae.safetensors

(或者,安装ComfyUI桌面应用程序)

步骤2:启动ComfyUI

# From ComfyUI directory
python main.py

# ComfyUI will start on: http://127.0.0.1:8188
# WebSocket available at: ws://127.0.0.1:8188/ws

(或者,如果已安装,只需运行ComfyUI桌面应用程序)

步骤3:构建ImageMCP

# Clone this repository
git clone <your-repo-url>
cd ImageMCP

# Restore dependencies
dotnet restore

# Build the project
dotnet build

# Run tests (optional)
dotnet test

(或下载并安装构建包)

步骤4:配置ImageMCP

编辑 appsettings.json:

{
  "ComfyUI": {
    "ApiEndpoint": "ws://127.0.0.1:8188",
    "DefaultTemplate": "workflows/default_workflow.json",
    "TimeoutSeconds": 300,
    "PollIntervalSeconds": 1
  },
  "MCP": {
    "ServerName": "ImageMCP",
    "ServerVersion": "1.0.0-dev",
    "HttpPort": 5243,
    "HttpUrl": "http://localhost:5243"
  }
}

步骤5:创建工作流模板

重要:使用 API格式 工作流程以获得最佳效果!

  1. 在ComfyUI的web界面中设计工作流
  2. 点击 “保存(API格式)” 或通过API导出
  3. 保存到 workflows/default_workflow.json

工作流必须包含:

  • 至少一个 CLIPTextEncode 积极提示的节点
  • 可选第二个 CLIPTextEncode 负提示节点
  • A. SaveImage 输出节点

备注:ImageMCP自动检测工作流格式并处理UI和API格式,但建议使用API格式以提高可靠性。

步骤6:运行ImageMCP

dotnet run --project ImageMCP

或者从项目目录中:

dotnet run

或者,从Windows:

start_server.bat

或者,从Linux:

./start_server.sh

输出:

info: Startup[0]
      ComfyUI settings loaded: ApiEndpoint=ws://127.0.0.1:8188, DefaultTemplate=workflows/default_workflow.json
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5243
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.

步骤7:配置LM Studio

ImageMCP使用HTTP模式(EDMCP风格) 对于LM Studio集成:

  1. 打开LM工作室
  2. 首选 开发者 tab → MCP服务器
  3. 点击 “配置” 或编辑 mcp.json
  4. 添加ImageMCP服务器配置:
{
  "mcpServers": {
    "imagemcp": {
      "url": "http://localhost:5243/mcp"
    }
  }
}
  1. 点击 “保存” 或保存文件
  2. 重新启动LM Studio或重新加载MCP配置

服务器应连接并显示为LM Studio中可用。

步骤8:测试图像生成

在LM Studio聊天中,询问模特:

“用鲜艳的色彩生成日落时宁静的山景图像”

该模型将:

  1. 识别图像生成请求
  2. 打电话给 generate_image 工具与您的提示
  3. ImageMCP将把提示注入工作流
  4. ComfyUI将生成图像(这可能需要1-2分钟)
  5. 图像将返回并显示在LM Studio中

输出示例:

info: ImageGen[0]
      Template is already in API format, injecting prompts directly
info: ImageGen[0]
      Submitting workflow with prompt: serene mountain landscape at sunset with vibrant colors
info: ImageMCP.Services.ComfyUIClient[0]
      Workflow submitted successfully. Prompt ID: 628d6005-8bee-4236-b15b-eefdd39efeb6
info: ImageMCP.Services.ComfyUIClient[0]
      Workflow execution completed: 628d6005-8bee-4236-b15b-eefdd39efeb6
info: ImageMCP.Services.ComfyUIClient[0]
      Retrieved 1 images for prompt: 628d6005-8bee-4236-b15b-eefdd39efeb6

🔧 配置选项

ComfyUI设置

设置 说明 默认值
ApiEndpoint 舒适的websocket URL ws://127.0.0.1:8188
DefaultTemplate 默认工作流JSON路径 workflows/default_workflow.json
TimeoutSeconds 最大执行时间 300 (5分钟)
PollIntervalSeconds WebSocket轮询间隔 1

MCP设置

设置 说明 默认值
ServerName MCP的显示名称 ImageMCP
ServerVersion 服务器版本 1.0.0-dev
HttpPort HTTP服务器端口 5243
HttpUrl HTTP服务器URL http://localhost:5243

📝 刀具参数

generate_image

参数 类型 必填 说明
prompt string ✅ 是 要生成的图像的文本描述
negative_prompt string ❌ 否 图像中应避免的内容(默认:“文本、水印、低质量、模糊、失真”)
template string ❌ 否 自定义工作流模板路径(默认:来自配置)

📁 项目结构

ImageMCP/
├── Models/
│   ├── ComfyUISettings.cs          # Configuration model
│   ├── ComfyWorkflow.cs            # Workflow JSON structure
│   ├── ComfyPromptRequest.cs       # API request/response models
│   ├── McpMessage.cs               # MCP protocol messages
│   └── McpSettings.cs              # MCP configuration
├── Services/
│   ├── ComfyUIClient.cs            # WebSocket/HTTP client for ComfyUI
│   └── WorkflowTemplateManager.cs  # Template loading and prompt injection
├── workflows/
│   └── default_workflow.json       # Default SDXL workflow (API format)
├── ImageMCP.Tests/
│   ├── Services/                   # Service layer tests
│   └── Integration/                # End-to-end tests
├── Program.cs                      # Application entry point (HTTP server)
├── appsettings.json                # Configuration file
└── README.md                       # This file

🧪 测试

运行所有测试

dotnet test

运行特定测试类别

# Unit tests only
dotnet test --filter Category=Unit

# Integration tests (requires ComfyUI running)
dotnet test --filter Category=Integration

测试覆盖率

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=opencover

🔍 故障排除

ComfyUI连接失败

错误: Could not connect to ComfyUI at ws://127.0.0.1:8188

解决方案:

  1. 验证ComfyUI是否正在运行:打开 http://127.0.0.1:8188 浏览器中
  2. 检查防火墙设置
  3. 验证中的WebSocket端点 appsettings.json
  4. 确保ComfyUI可访问(不绑定到其他接口)

生成后未找到历史记录

错误: No history found for prompt after 10 attempts

解决方案:

  1. ComfyUI可能负载过重-重试逻辑最多等待11秒
  2. 在执行过程中检查ComfyUI控制台是否有错误
  3. 在ComfyUI的UI中验证工作流是否成功完成
  4. 检查ComfyUI output 生成图像的目录

配置未加载

错误: Workflow template not found: path/to/template.json

解决方案:

  1. 确保 appsettings.json 正在复制到输出目录
  2. 检查项目文件是否包括 <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  3. 验证中的路径 ComfyUI:DefaultTemplate 与可执行文件相关
  4. 检查一下 workflows 输出目录中存在文件夹

工作流格式问题

错误: Workflow does not contain nodes 或 Required input is missing

解决方案:

  1. 使用 API格式 工作流(保存→ ComfyUI中的API格式)
  2. 确保工作流具有所有必需的节点(CLIPTextEncode、SaveImage)
  3. 在用作模板之前,先在ComfyUI中测试工作流
  4. 检查ImageMCP日志,查看检测到的格式

未生成图像

错误: Image generation completed but no images were produced

解决方案:

  1. 检查ComfyUI控制台是否有错误
  2. 验证工作流是否具有 SaveImage 节点
  3. 检查ComfyUI中是否加载了模型
  4. 确保有足够的磁盘空间用于输出
  5. 验证SaveImage节点是否已连接到生成管道

工作流执行超时

错误: Workflow execution timed out after 300 seconds

解决方案:

  1. 增加 TimeoutSeconds 在 appsettings.json
  2. 使用更快的采样器(euler、deis、dpm++)
  3. 减少 num_inference_steps (尝试SDXL 20-30)
  4. 检查GPU/CPU利用率
  5. 确保ComfyUI没有排队处理多个请求

LM Studio连接问题

错误:LM Studio显示“服务器没有响应”或超时

解决方案:

  1. 验证ImageMCP是否正在运行(http://localhost:5243/health 应返回 {"status":"ok"})
  2. 检查端口是否尚未使用
  3. 确保 appsettings.json 有正确 HttpUrl 和 HttpPort
  4. 检查LM Studio的开发人员控制台以获取错误消息
  5. 重新启动ImageMCP和LM Studio

📖 运作原理

1.HTTP MCP服务器

ImageMCP运行一个简单的HTTP服务器(EDMCP风格),它公开了两个端点:

  • 获取 /mcp:返回服务器信息(名称、版本、协议)
  • 发布 /mcp:处理JSON-RPC 2.0请求(初始化、工具/列表、工具/调用)

2.工作流模板加载和自动检测

var workflowJson = await File.ReadAllTextAsync(templatePath);
var template = JsonDocument.Parse(workflowJson);

// Auto-detect format
bool isApiFormat = !template.RootElement.TryGetProperty("nodes", out _);

ImageMCP自动检测:

  • API格式:节点ID作为顶级密钥(例如。, {"3": {...}, "6": {...}})
  • UI格式:有 nodes 和 links 数组(从ComfyUI UI导出)

3.即时注入(API格式)

// For API format workflows
var workflow = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(workflowJson);

foreach (var (nodeId, node) in workflow)
{
    if (node.class_type == "CLIPTextEncode")
    {
        node.inputs.text = positivePrompt; // or negativePrompt
    }
}

经理使用启发式方法来识别积极和消极的提示:

  • 负面的:包含“质量最差”、“糟糕”、“水印”、“文本”等关键字
  • 积极的:其他一切(第一 CLIPTextEncode 节点已找到)

4.工作流提交

var requestJson = $$"""
{
    "prompt": {{workflowJson}},
    "client_id": "{{_clientId}}"
}
""";

await httpClient.PostAsync($"{comfyUIEndpoint}/prompt", content);
// Returns prompt_id for tracking

5.通过WebSocket进行进度监控

await webSocket.ConnectAsync($"ws://127.0.0.1:8188/ws?clientId={clientId}");

while (true)
{
    var message = await ReceiveWebSocketMessage();
    
    if (message.type == "executed" && message.data.prompt_id == promptId)
    {
        return true; // Execution complete
    }
}

监听WebSocket消息:

  • progress:生成过程中的步骤更新
  • executed:完工信号
  • execution_error:失败
  • execution_cached:缓存结果

6.使用重试逻辑的图像检索

// Wait 1 second for history to finalize
await Task.Delay(1000);

// Retry up to 10 times
for (int attempt = 0; attempt < 10; attempt++)
{
    var history = await httpClient.GetAsync($"/history/{promptId}");
    
    if (history.ContainsKey(promptId))
    {
        var images = ExtractImages(history[promptId].outputs);
        return images; // Success!
    }
    
    await Task.Delay(1000); // Wait and retry
}

这解释了ComfyUI信令完成和写入历史之间的轻微延迟。

🔐 安全考虑

  • 仅限本地:默认配置绑定到localhost
  • 无需认证:ComfyUI API默认情况下未经身份验证
  • 文件访问:模板可以访问本地文件系统
  • 资源限制:设置适当的超时以防止滥用

🛣️ 路线图

  • []支持多代并发
  • []队列管理和优先级
  • []向MCP客户报告进度
  • []ControlNet和LoRA支持
  • []批量生成
  • []图像到图像工作流
  • []升级工作流程
  • []通过参数选择型号
  • []工作流缓存
  • []远程ComfyUI支持身份验证

📄 许可证

[您的许可证在这里]

🤝 贡献

欢迎投稿!请提交拉取请求或未决问题。

📞 支持

🙏 致谢


建于❤️ 对于AI社区 “ServerName”:“ComfyUI图像生成器”, “服务器版本”:“1.0.0” } }


### Command Line Arguments

```bash
dotnet run --template ./workflows/sdxl_basic.json --comfyui-endpoint ws://127.0.0.1:8188

用法

启动服务器

cd ImageMCP
dotnet run

使用自定义配置

dotnet run --template ./custom_workflow.json --comfyui-endpoint ws://192.168.1.100:8188

与LM Studio集成

通过添加到MCP配置中,配置LM Studio以使用此MCP服务器:

{
  "mcpServers": {
    "comfyui": {
      "command": "dotnet",
      "args": ["run", "--project", "C:/path/to/ImageMCP"],
      "env": {}
    }
  }
}

开发状态

?第1阶段:基础(当前)

  • [x] MCP协议实现
  • [x] 标准传输层
  • [x] 工具登记系统
  • [x] 配置管理
  • [x] 基本单元测试

??第2阶段:ComfyUI集成(进行中)

  • []ComfyUI API的WebSocket客户端
  • []JSON工作流模板解析器
  • []CLIP节点检测和修改
  • []图像生成编排

??第3阶段:高级功能(计划中)

  • []多模板支持
  • []高级工作流定制
  • []图像结果缓存
  • []进度跟踪

测试

运行所有测试:

cd ImageMCP.Tests
dotnet test

跑步覆盖:

dotnet test /p:CollectCoverage=true

需求

  • .NET 10.0 SDK
  • ComfyUI在本地或网络上运行
  • LM Studio支持MCP

工具定义

服务器向LM Studio公开以下工具:

generate_image

  • 描述:根据文本提示使用ComfyUI生成图像
  • 参数:
    • prompt (必填):图像的文字描述
    • negative_prompt (可选):图像中应避免的内容
    • template (可选):自定义工作流模板路径

许可证

[在此处添加您的许可证]

贡献

[在此处添加贡献指南]