Custom Node Development

Expert 2 min read 8 sections
GitHub
On this page

Every node in ComfyUI is a Python class. ComfyUI's modern V3 Custom Node API (comfy_api.latest) replaces scattered class attributes and dict schemas with typed io.Schema definitions, structured io.NodeOutput returns, and async extension entrypoints.

#Folder structure

Create a subfolder inside ComfyUI/custom_nodes/ (for example ComfyUI/custom_nodes/my_custom_nodes/):

text
ComfyUI/custom_nodes/my_custom_nodes/
|-- __init__.py          # Exports comfy_entrypoint() returning a ComfyExtension
|-- nodes.py             # V3 io.ComfyNode subclasses
|-- requirements.txt     # Extra pip packages (only if needed beyond ComfyUI deps)
\-- pyproject.toml       # Metadata for Comfy Registry publishing

In __init__.py, register your node classes through a ComfyExtension and comfy_entrypoint():

python
from typing_extensions import override
from comfy_api.latest import ComfyExtension, io
from .nodes import ConditionalImageBlend, ImageBlur, SimpleTextProcessor


class MyNodesExtension(ComfyExtension):
    @override
    async def get_node_list(self) -> list[type[io.ComfyNode]]:
        return [
            SimpleTextProcessor,
            ImageBlur,
            ConditionalImageBlend,
        ]


async def comfy_entrypoint() -> MyNodesExtension:
    return MyNodesExtension()

#V3 node anatomy (comfy_api.latest)

Every V3 node inherits from io.ComfyNode and implements two @classmethod methods:

  • define_schema(cls) -> io.Schema: declares node_id, display_name, category, optional description and search_aliases, typed inputs=[...] and outputs=[...], and optional flags like is_output_node=True or is_experimental=True.
  • execute(cls, ...) -> io.NodeOutput: receives socket values and widget arguments by name and returns io.NodeOutput(...) matching the declared outputs order.

#Example 1: Basic text processor (V3)

python
from comfy_api.latest import io


class SimpleTextProcessor(io.ComfyNode):
    @classmethod
    def define_schema(cls) -> io.Schema:
        return io.Schema(
            node_id="MyPack_SimpleTextProcessor",
            display_name="Simple Text Processor",
            category="text/processing",
            description="Uppercases and repeats text lines.",
            inputs=[
                io.String.Input("text", multiline=True, default="Hello ComfyUI"),
                io.Boolean.Input("uppercase", default=False),
                io.Int.Input("repeat_count", default=1, min=1, max=10),
            ],
            outputs=[
                io.String.Output(display_name="processed_text"),
            ],
        )

    @classmethod
    def execute(cls, text: str, uppercase: bool, repeat_count: int) -> io.NodeOutput:
        processed = text.upper() if uppercase else text
        result = "\n".join([processed] * repeat_count)
        return io.NodeOutput(result)

#Example 2: Working with PyTorch image tensors (V3)

In ComfyUI, IMAGE sockets pass PyTorch float32 tensors with shape [B, H, W, C] (Batch, Height, Width, Channels) and pixel values normalized to 0.0 .. 1.0 in RGB order. MASK tensors use shape [B, H, W] (or [H, W]) in 0.0 .. 1.0.

python
import numpy as np
import torch
from PIL import Image, ImageFilter
from comfy_api.latest import io


class ImageBlur(io.ComfyNode):
    @classmethod
    def define_schema(cls) -> io.Schema:
        return io.Schema(
            node_id="MyPack_ImageBlur",
            display_name="Simple Image Blur",
            category="image/filters",
            search_aliases=["gaussian blur", "soften"],
            inputs=[
                io.Image.Input("image"),
                io.Float.Input("blur_radius", default=2.0, min=0.0, max=25.0, step=0.5),
            ],
            outputs=[
                io.Image.Output(display_name="image"),
            ],
        )

    @classmethod
    def execute(cls, image: torch.Tensor, blur_radius: float) -> io.NodeOutput:
        results = []
        for i in range(image.shape[0]):
            # Convert [H, W, C] float32 (0..1) -> uint8 PIL Image
            img_np = np.clip(image[i].cpu().numpy() * 255.0, 0, 255).astype(np.uint8)
            pil_img = Image.fromarray(img_np)

            blurred = pil_img.filter(ImageFilter.GaussianBlur(radius=blur_radius))

            # Convert back to [H, W, C] float32 (0..1)
            out_np = np.array(blurred).astype(np.float32) / 255.0
            results.append(torch.from_numpy(out_np))

        return io.NodeOutput(torch.stack(results, dim=0))

#Example 3: Optional inputs, combos, and multiple outputs (V3)

Pass optional=True for sockets users do not need to wire up, use io.Combo.Input for dropdowns, and return multiple outputs inside io.NodeOutput(...). For dynamic graphs, V3 also provides io.DynamicCombo.Input (conditional sub-inputs per choice) and io.Autogrow.Input (expandable socket lists).

python
import torch
from comfy_api.latest import io


class ConditionalImageBlend(io.ComfyNode):
    @classmethod
    def define_schema(cls) -> io.Schema:
        return io.Schema(
            node_id="MyPack_ConditionalImageBlend",
            display_name="Conditional Image Blend",
            category="image/adjustments",
            inputs=[
                io.Image.Input("image"),
                io.Combo.Input(
                    "operation",
                    options=["darken", "lighten", "invert"],
                    default="darken",
                ),
                io.Float.Input("strength", default=0.5, min=0.0, max=1.0, step=0.05),
                io.Mask.Input("mask", optional=True),
            ],
            outputs=[
                io.Image.Output(display_name="image"),
                io.String.Output(display_name="summary"),
            ],
        )

    @classmethod
    def execute(cls, image: torch.Tensor, operation: str, strength: float, mask=None) -> io.NodeOutput:
        if operation == "invert":
            modified = 1.0 - image
        elif operation == "lighten":
            modified = torch.clamp(image + strength * 0.25, 0.0, 1.0)
        else:
            modified = torch.clamp(image * (1.0 - strength * 0.25), 0.0, 1.0)

        if mask is not None:
            m = mask if mask.ndim == 3 else mask.unsqueeze(0)
            m = m.unsqueeze(-1).to(image.device)
            output = image * (1.0 - m) + modified * m
        else:
            output = image * (1.0 - strength) + modified * strength

        return io.NodeOutput(output, f"Applied {operation} at strength {strength:.2f}")

#Caching, validation, and lazy evaluation

V3 io.ComfyNode subclasses support optional @classmethod lifecycle hooks:

  • Cache fingerprinting (fingerprint_inputs(cls, **kwargs)): replaces V1 IS_CHANGED. Return a changing token (such as a file mtime hash) only when reading external mutable state. Never return float("nan") unless you genuinely want to bypass downstream workflow caching every run.
  • Pre-flight validation (validate_inputs(cls, **kwargs) -> bool | str): replaces V1 VALIDATE_INPUTS. Return True if valid or a clear error string to fail cleanly before GPU execution begins.
  • Lazy evaluation (check_lazy_status(cls, **kwargs) -> list[str]): with lazy=True on optional inputs, return only the input names that still need upstream evaluation so unused branches stay skipped.
  • Terminal output nodes: set is_output_node=True inside io.Schema(...) on saver or preview nodes with no downstream outputs.

#Legacy V1 API reference

Older community packs still use the V1 dictionary format, which ComfyUI continues to load for backwards compatibility:

V1 convention V3 replacement (comfy_api.latest)
NODE_CLASS_MAPPINGS / NODE_DISPLAY_NAME_MAPPINGS ComfyExtension.get_node_list() + comfy_entrypoint()
INPUT_TYPES, RETURN_TYPES, RETURN_NAMES, CATEGORY @classmethod def define_schema(cls) -> io.Schema
FUNCTION = "method_name" @classmethod def execute(cls, ...) -> io.NodeOutput
OUTPUT_NODE = True is_output_node=True on io.Schema
IS_CHANGED / VALIDATE_INPUTS fingerprint_inputs / validate_inputs classmethods

#Testing and publishing

  1. Test your pack in isolation with python main.py --disable-all-custom-nodes --whitelist-custom-nodes my_custom_nodes.
  2. Verify batch_size = 1, batch_size > 1, non-square dimensions, optional None sockets, and edge bounds (0.0, max values).
  3. Avoid mutating sys.path or pinning conflicting torch / numpy versions inside requirements.txt.
  4. Add a pyproject.toml and publish to the Comfy Registry so users can install and update your pack safely through ComfyUI-Manager.