Nuke AI桥接工具

Nuke-MCP是一个连接The Foundry's Nuke与AI系统的桥梁,通过Model Context Protocol (MCP)实现AI助手与Nuke的交互,包括脚本信息获取、节点创建与修改、渲染控制等功能。

  • by dughogan
  • Python
  • 本地部署
  • 39 星标
  • 更新于
在 GitHub 查看 dughogan/nuke_mcp

使用说明

核MCP

使用模型上下文协议(MCP)在The Foundry的Nuke和AI系统之间架起桥梁。

概述

Nuke MCP允许AI助手通过套接字连接与Nuke交互,使他们能够:

  • 获取有关Nuke脚本的信息
  • 创建、修改和删除节点
  • 在节点图中定位节点
  • 将节点连接在一起
  • 控制播放和渲染
  • 在Nuke中执行任意Python代码

组件

  1. 核插件 (nuke_mcp_addon.py):在Nuke中创建套接字服务器的Nuke脚本
  2. MCP服务器 (nuke_mcp_server.py):一个连接到Nuke插件并将工具暴露给AI系统的Python服务器
  3. 入口点 (main.py):启动MCP服务器的简单脚本

安装

先决条件

  • Foundry的Nuke(任何最新版本都应该有效)
  • Python 3.7+
  • FastMCP封装
  • 克劳德桌面

安装FastMCP软件包

pip install fastmcp

安装Nuke MCP

  1. 克隆或下载此存储库
  2. 复制 nuke_mcp_addon.py 到Nuke脚本文件夹或Nuke Python路径中的某个位置

用法

安装Nuke插件

  1. 复制插件文件:

    • 拿着 nuke_mcp_addon.py 文件并将其放置在Nuke可以找到的位置:
      • 将其复制到Nuke脚本文件夹(通常位于 ~/.nuke/python 在Linux/Mac上或在Windows上的主目录中)
      • 或者将其放置在Nuke Python路径中的文件夹中
  2. 创建启动脚本 (推荐):

    • 创建或编辑现有 init.py 文件在您的 .nuke 目录
    • 添加以下行以在Nuke启动时自动加载插件,并确保您指向MCP工具所在的python子文件夹:
      nuke.pluginAddPath("./python")
      
      import nuke_mcp_addon
      
  3. 手动加载 (备选方案):

    • 如果你不想自动加载它,每次都可以通过以下方式手动加载:
      • 打开核武器
      • 确保在MCP工具所在的init.py中设置了python子文件夹
      • 转到“脚本编辑器”面板
      • 跑步 import nuke_mcp_addon

对接NukeMCP面板

默认情况下,NukeMCP面板以浮动窗口的形式打开。如果您希望将其停靠在Nuke的界面中,可以修改 NukeMCPPanel 类在 nuke_mcp_addon.py:

# Find the NukeMCPPanel class definition (around line 380)
class NukeMCPPanel(nukescripts.PythonPanel):
    def __init__(self):
        nukescripts.PythonPanel.__init__(self, 'Nuke MCP', 'com.example.NukeMCP')
        # ... existing code ...

# Add this method to enable docking
    def addToPane(self):
        pane = nuke.getPaneFor('Properties.1')
        if not pane:
            pane = nuke.getPaneFor('Viewer.1')
        self.setMinimumSize(300, 200)  # Set a reasonable minimum size
        return pane.addPermanentAsQWidget(self)

# Modify the show_panel function to use docking
def show_panel():
    """Show the NukeMCP panel"""
    global _panel
    if _panel is None:
        _panel = NukeMCPPanel()
    
    # Show as docked panel instead of floating window
    pane = _panel.addToPane()
    if pane:
        _panel.setParent(pane)

您还可以修改面板在菜单中的显示方式。根据您的menu.py文件,您有:

# MCP Tools
nuke.toolbar("Nodes").addCommand('NukeMCP/NukeMCP Panel', 'nuke_mcp_addon.show_panel()')

为了确保它与现有的工具栏结构正确集成,请确保此行在menu.py文件中没有注释。

故障排除

要将Nuke MCP与Claude Desktop一起使用,请执行以下步骤:

  1. 下载并安装Claude Desktop:

    • 从Anthropic网站下载Claude Desktop
    • 安装并设置您的帐户
  2. 启用开发人员模式:

    • 打开克劳德桌面
    • 前往设置
    • 启用开发人员模式(这可能需要特定权限)
  3. 编辑配置文件:

    • 在Claude Desktop设置中,单击“编辑配置”(或直接编辑 claude_desktop_config.json 文件)
    • 添加Nuke MCP服务器配置:
{
  "mcpServers": {
    "nuke": {
      "command": "python",
      "args": [
        "/path/to/your/nuke-mcp/main.py"
      ],
      "trusted": true
    }
  }
}
  1. 替换路径:

    • 用保存路径的实际路径更新路径 main.py 文件
    • 确保使用完整的绝对路径
    • 对于Windows,使用正斜杠或转义反斜杠:
      "args": ["Z:/path/to/nuke_mcp/main.py"]
      
      或
      "args": ["Z:\\path\\to\\nuke_mcp\\main.py"]
      
    • 注: "trusted": true 完整功能需要标志
  2. 重新启动克劳德桌面:

    • 保存配置文件
    • 重新启动Claude Desktop以应用更改

现在,当您使用Claude Desktop时,您可以指示它通过MCP连接与Nuke交互。

系统架构

该系统由三个协同工作的主要组件组成:

  1. 核插件:在Nuke内部运行并创建一个监听命令的套接字服务器
  2. MCP服务器:充当AI系统和Nuke之间的中间件
  3. AI客户端:连接到MCP服务器以控制Nuke(例如Claude Desktop)
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│             │     │             │     │             │
│  AI Client  │◄───►│  MCP Server │◄───►│  Nuke Addon │
│ (Claude)    │     │             │     │ (in Nuke)   │
│             │     │             │     │             │
└─────────────┘     └─────────────┘     └─────────────┘

可用工具

MCP服务器公开了以下工具:

  • get_script_info():获取有关当前Nuke脚本的信息
  • get_node_info(node_name):获取特定节点的详细信息
  • create_node(node_type, name, position, inputs, parameters):创建新节点
  • modify_node(name, parameters, position, inputs):更改现有节点
  • delete_node(name):删除节点
  • position_node(name, x, y):在节点图中定位节点
  • connect_nodes(output_node, input_node, input_index):连接节点
  • render(frame_range, write_node, proxy_mode):渲染帧
  • viewer_playback(action, start_frame, end_frame):控制查看器播放
  • execute_nuke_code(code):在Nuke中运行Python代码
  • auto_layout_nodes(selected_only):自动排列节点
  • set_frames(first_frame, last_frame, current_frame):设置帧范围
  • create_viewer(input_node):创建查看器节点

例子

创建一个简单的模糊节点

create_node(node_type="Blur", parameters={"size": 10})

构建等级节点链

create_node(node_type="Read", name="input", parameters={"file": "/path/to/image.exr"})
create_node(node_type="Grade", name="grade1", position=[200, 0])
create_node(node_type="Grade", name="grade2", position=[400, 0])
create_node(node_type="Write", name="output", position=[600, 0], parameters={"file": "/path/to/output.exr"})
connect_nodes(output_node="input", input_node="grade1")
connect_nodes(output_node="grade1", input_node="grade2")
connect_nodes(output_node="grade2", input_node="output")

渲染输出

render(frame_range="1-10", write_node="output")

Claude的命令示例

使用Claude Desktop时,您可以给它自然语言指令来控制Nuke。以下是一些示例命令:

基本脚本分析

"Can you tell me what's in my current Nuke script?"

创建完整的合成设置

"Create a compositing setup in Nuke with a Read node, Color Correct, Grade, and Write node, all properly connected."

构建绿屏按键设置

"Create a professional green screen keying setup in Nuke with Keyer, Despill, Edge Blur, and compositing over a background."

添加特殊效果

"Build a particle system in Nuke using Noise, ParticleEmitter, and Merge nodes to create a fire effect."

增强现有脚本

"Analyze my current Nuke script, then enhance it by creating a color grading chain with separate adjustments for shadows, midtones, and highlights. Add a subtle film grain effect and a gentle vignette."

3D场景设置

"Set up a 3D scene in Nuke with a Camera, 3D objects, and proper lighting."

扩展MCP工具

您可以通过向中添加新工具来扩展系统 nuke_mcp_server.py 文件。MCP工具使用 @mcp.tool() 装饰图案。

刀具结构

每个工具都遵循以下基本结构:

@mcp.tool()
def tool_name(ctx: Context, param1: type, param2: type = default_value) -> str:
    """
    Tool description for documentation.
    
    Parameters:
    - param1: Description of param1
    - param2: Description of param2 with default value
    """
    try:
        logger.info(f"Tool called: tool_name with params")
        nuke = get_nuke_connection()
        result = nuke.send_command("command_name", {
            "param1": param1,
            "param2": param2
        })
        
        # Process result and format response
        return "Human-readable response"
    except Exception as e:
        logger.error(f"Error in tool_name: {str(e)}")
        return f"Error message: {str(e)}"

添加新工具

要添加新工具,请执行以下操作:

  1. 识别功能 您想添加

  2. 在Nuke插件中添加新方法 (in nuke_mcp_addon.py):

    • 将该方法添加到 NukeMCPServer 类
    • 向添加条目 handlers 字典在 execute_command 方法
  3. 创建相应的工具 在 nuke_mcp_server.py:

    • 使用 @mcp.tool() 装饰器
    • 使用类型提示定义参数
    • 添加描述性文档字符串
    • 实现调用相应Nuke命令的逻辑
  4. 测试新工具 彻底地

示例:添加变换节点工具

以下是一个示例,说明如何添加一个专门的工具来创建Transform节点:

@mcp.tool()
def create_transform(
    ctx: Context,
    name: str = None,
    position: List[int] = None,
    rotation: float = 0.0,
    scale: float = 1.0,
    center: List[float] = None
) -> str:
    """
    Create a Transform node with specified parameters.
    
    Parameters:
    - name: Optional name for the Transform node
    - position: Optional [x, y] position coordinates for the node
    - rotation: Rotation in degrees
    - scale: Uniform scale factor
    - center: Optional [x, y] center of transformation
    """
    try:
        logger.info(f"Tool called: create_transform")
        nuke = get_nuke_connection()
        
        # Prepare parameters for the Transform node
        parameters = {
            "rotate": rotation,
            "scale": scale
        }
        
        if center:
            parameters["center"] = center
        
        # Call the generic create_node command
        result = nuke.send_command("create_node", {
            "node_type": "Transform",
            "name": name,
            "position": position,
            "parameters": parameters
        })
        
        actual_name = result.get("name", "unknown")
        return f"Created Transform node named '{actual_name}' with rotation={rotation}° and scale={scale}"
    except Exception as e:
        logger.error(f"Error in create_transform: {str(e)}")
        return f"Error creating Transform node: {str(e)}"

此模式允许您构建提供更高级别功能的专用工具,同时利用现有的命令基础架构。

故障排除

连接问题

如果Claude无法连接到Nuke,请检查以下内容:

  1. Nuke正在运行:确保Nuke已打开并正在运行
  2. 插件处于活动状态:验证NukeMCP面板是否显示“在端口9876上运行”
  3. 端口配置:确保Nuke和MCP服务器中的端口匹配
  4. 防火墙设置:检查防火墙是否阻止了连接

常见错误

  • “无法连接到Nuke”:确保Nuke插件正在运行并使用正确的端口
  • “等待响应时套接字超时”:Nuke的操作可能需要太长时间
  • “创建节点失败”:检查节点类型名称是否正确

发展

这是一个初步实施。未来的改进可能包括:

  • 支持更专业的核功能(旋转、跟踪等)
  • 更好的错误处理和超时管理
  • 支持基于模板的工作流
  • 与其他资产管理系统集成

许可证

MIT许可证