Spaces:
Running on Zero
Running on Zero
layout.py: Support High-Level MCP
Browse filesFiles changed (14)
- README.md+6-4
- mcp_tools/__init__.py+47-47
- mcp_tools/error_schema.py+85-85
- mcp_tools/get_feature_list.py+127-127
- mcp_tools/get_model_architecture_list.py+36-36
- mcp_tools/get_model_features.py+102-102
- mcp_tools/get_model_list.py+64-64
- mcp_tools/get_task_list.py+11-11
- mcp_tools/get_task_status.py+21-21
- mcp_tools/mcp_gradio_integration.py+130-130
- mcp_tools/run.py+76-76
- mcp_tools/tool_handlers.py+28-28
- ui/layout.py+1-1
- yaml/chain_features.yaml+652-652
149 unmodified lines150151152153154155156157158159160161156157158159162163164149 unmodified lines - krea/Krea-2-Turbo
- lodestones/Chroma1-HD
- lodestones/Chroma1-Radiance
- mage-flow-community/Mage-Flow
- mage-flow-community/Mage-Flow-Base
- mage-flow-community/Mage-Flow-Edit
- mage-flow-community/Mage-Flow-Edit-Base
- mage-flow-community/Mage-Flow-Edit-Turbo
- mage-flow-community/Mage-Flow-Turbo
- meituan-longcat/LongCat-Image
- microsoft/Lens
- microsoft/Lens-Turbo
- microsoft/Mage-Flow
- microsoft/Mage-Flow-Edit
- microsoft/Mage-Flow-Edit-Turbo
- microsoft/Mage-Flow-Turbo
- NewBie-AI/NewBie-image-Exp0.1
- nvidia/PiD
- nvidia/PixelDiT-1300M-1024px12345678910111213141516171819202122232425262728293031323334353637383940414243444546471234567891011121314151617181920212223242526272829303132333435363738394041424344454647def __getattr__(name): if name in ("types", "server", "client", "shared"): raise ImportError(f"No module named 'mcp.{name}' in local mcp package") raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
from .get_task_list import handle_get_task_listfrom .get_model_architecture_list import handle_get_model_architecture_listfrom .get_model_list import handle_get_model_listfrom .get_feature_list import handle_get_feature_listfrom .get_model_features import handle_get_model_featuresfrom .run import handle_runfrom .get_task_status import handle_get_task_statusfrom .error_schema import make_error, make_validation_error, make_not_found_errorfrom .mcp_gradio_integration import ( register_high_level_mcp_apis, cleanup_dependencies_api_names, patch_gradio_api_suppression, HIGH_LEVEL_MCP_API_NAMES,)
MCP_FUNCTIONS = [ handle_get_task_list, handle_get_model_architecture_list, handle_get_model_list, handle_get_feature_list, handle_get_model_features, handle_run, handle_get_task_status,]
__all__ = [ "handle_get_task_list", "handle_get_model_architecture_list", "handle_get_model_list", "handle_get_feature_list", "handle_get_model_features", "handle_run", "handle_get_task_status", "make_error", "make_validation_error", "make_not_found_error", "register_high_level_mcp_apis", "cleanup_dependencies_api_names", "patch_gradio_api_suppression", "HIGH_LEVEL_MCP_API_NAMES", "MCP_FUNCTIONS",]def __getattr__(name):
if name in ("types", "server", "client", "shared"):
raise ImportError(f"No module named 'mcp.{name}' in local mcp package")
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
from .get_task_list import handle_get_task_list
from .get_model_architecture_list import handle_get_model_architecture_list
from .get_model_list import handle_get_model_list
from .get_feature_list import handle_get_feature_list
from .get_model_features import handle_get_model_features
from .run import handle_run
from .get_task_status import handle_get_task_status
from .error_schema import make_error, make_validation_error, make_not_found_error
from .mcp_gradio_integration import (
register_high_level_mcp_apis,
cleanup_dependencies_api_names,
patch_gradio_api_suppression,
HIGH_LEVEL_MCP_API_NAMES,
)
MCP_FUNCTIONS = [
handle_get_task_list,
handle_get_model_architecture_list,
handle_get_model_list,
handle_get_feature_list,
handle_get_model_features,
handle_run,
handle_get_task_status,
]
__all__ = [
"handle_get_task_list",
"handle_get_model_architecture_list",
"handle_get_model_list",
"handle_get_feature_list",
"handle_get_model_features",
"handle_run",
"handle_get_task_status",
"make_error",
"make_validation_error",
"make_not_found_error",
"register_high_level_mcp_apis",
"cleanup_dependencies_api_names",
"patch_gradio_api_suppression",
"HIGH_LEVEL_MCP_API_NAMES",
"MCP_FUNCTIONS",
]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Unified MCP tool error response format.
Error code enumeration: - INVALID_PARAMS: Parameter validation failed (missing required fields, type errors, value out of range) - MODEL_NOT_FOUND: The specified model name does not exist - ARCHITECTURE_NOT_FOUND: The specified architecture name does not exist - CHAIN_TYPE_NOT_FOUND: The specified chain/injector type is invalid - FEATURE_NOT_SUPPORTED: The current model does not support the requested feature - TASK_NOT_FOUND: The async task ID does not exist - MODEL_OOM: GPU out of memory - INTERNAL_ERROR: Internal server error"""
def make_error(code: str, message: str, details: dict = None) -> dict: """ Construct a unified MCP tool error response.
Args: code: Error code (UPPER_SNAKE_CASE format) message: Human-readable error description details: Optional details dictionary
Returns: Standardized error response dictionary """ error = { "error": { "code": code, "message": message, } } if details: error["error"]["details"] = details return error
def make_validation_error( message: str = "Request validation failed.", missing_fields: list = None, invalid_fields: dict = None,) -> dict: """ Construct a parameter validation failure error response.
Args: message: Error description missing_fields: List of missing required field names invalid_fields: Key-value pairs of invalid fields, key=field name, value=reason description
Returns: Standardized INVALID_PARAMS error response """ details = {} if missing_fields: details["missing_fields"] = missing_fields if invalid_fields: details["invalid_fields"] = invalid_fields return make_error("INVALID_PARAMS", message, details if details else None)
def make_not_found_error(resource_type: str, resource_id: str) -> dict: """ Construct a resource-not-found error response.
Args: resource_type: Resource type (e.g., "model", "architecture", "chain_type", "task") resource_id: Resource identifier
Returns: Standardized *_NOT_FOUND error response """ code_map = { "model": "MODEL_NOT_FOUND", "architecture": "ARCHITECTURE_NOT_FOUND", "chain_type": "CHAIN_TYPE_NOT_FOUND", "task": "TASK_NOT_FOUND", } code = code_map.get(resource_type, f"{resource_type.upper()}_NOT_FOUND") return make_error( code, f"The specified {resource_type} '{resource_id}' was not found.", {"resource_type": resource_type, "resource_id": resource_id}, )"""
Unified MCP tool error response format.
Error code enumeration:
- INVALID_PARAMS: Parameter validation failed (missing required fields, type errors, value out of range)
- MODEL_NOT_FOUND: The specified model name does not exist
- ARCHITECTURE_NOT_FOUND: The specified architecture name does not exist
- CHAIN_TYPE_NOT_FOUND: The specified chain/injector type is invalid
- FEATURE_NOT_SUPPORTED: The current model does not support the requested feature
- TASK_NOT_FOUND: The async task ID does not exist
- MODEL_OOM: GPU out of memory
- INTERNAL_ERROR: Internal server error
"""
def make_error(code: str, message: str, details: dict = None) -> dict:
"""
Construct a unified MCP tool error response.
Args:
code: Error code (UPPER_SNAKE_CASE format)
message: Human-readable error description
details: Optional details dictionary
Returns:
Standardized error response dictionary
"""
error = {
"error": {
"code": code,
"message": message,
}
}
if details:
error["error"]["details"] = details
return error
def make_validation_error(
message: str = "Request validation failed.",
missing_fields: list = None,
invalid_fields: dict = None,
) -> dict:
"""
Construct a parameter validation failure error response.
Args:
message: Error description
missing_fields: List of missing required field names
invalid_fields: Key-value pairs of invalid fields, key=field name, value=reason description
Returns:
Standardized INVALID_PARAMS error response
"""
details = {}
if missing_fields:
details["missing_fields"] = missing_fields
if invalid_fields:
details["invalid_fields"] = invalid_fields
return make_error("INVALID_PARAMS", message, details if details else None)
def make_not_found_error(resource_type: str, resource_id: str) -> dict:
"""
Construct a resource-not-found error response.
Args:
resource_type: Resource type (e.g., "model", "architecture", "chain_type", "task")
resource_id: Resource identifier
Returns:
Standardized *_NOT_FOUND error response
"""
code_map = {
"model": "MODEL_NOT_FOUND",
"architecture": "ARCHITECTURE_NOT_FOUND",
"chain_type": "CHAIN_TYPE_NOT_FOUND",
"task": "TASK_NOT_FOUND",
}
code = code_map.get(resource_type, f"{resource_type.upper()}_NOT_FOUND")
return make_error(
code,
f"The specified {resource_type} '{resource_id}' was not found.",
{"resource_type": resource_type, "resource_id": resource_id},
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127import osfrom copy import deepcopyfrom .common import _load_yaml, _CHAIN_FEATURES_PATH, _YAML_DIRfrom .error_schema import make_not_found_error
def _build_feature_entry(chain_name: str, chain_data: dict, include_schema: bool = False) -> dict: entry = { "feature_name": chain_name, "chains": chain_data.get("chains", chain_name), "display_name": chain_data.get("display_name", chain_name), "description": chain_data.get("description", ""), "supported_tasks": chain_data.get("supported_tasks", []), "max_count": chain_data.get("max_count", 1), "usage_guideline": chain_data.get("usage_guideline", ""), } if include_schema: schema = deepcopy(chain_data.get("parameters_schema", {})) if chain_name in ("krea2_controlnet", "diffsynth_controlnet", "controlnet", "anima_controlnet_lllite"): config_key = ( "Krea2_ControlNet" if chain_name == "krea2_controlnet" else "DiffSynth_ControlNet" if chain_name == "diffsynth_controlnet" else "Anima_ControlNet_Lllite" if chain_name == "anima_controlnet_lllite" else "ControlNet" ) yaml_filename = f"{chain_name}_models.yaml" model_path = os.path.join(_YAML_DIR, yaml_filename) raw_models = _load_yaml(model_path).get(config_key, []) models_list = [] if isinstance(raw_models, dict): for val in raw_models.values(): if isinstance(val, list): models_list.extend(val) elif isinstance(val, dict): models_list.append(val) elif isinstance(raw_models, list): models_list = raw_models
types_set = set() for m in models_list: t_val = m.get("Type", []) if isinstance(t_val, list): types_set.update(t_val) elif isinstance(t_val, str): types_set.add(t_val) types = sorted(list(types_set)) series = sorted(list(set(m.get("Series") for m in models_list if m.get("Series")))) if "properties" in schema: if "type" in schema["properties"] and types: schema["properties"]["type"]["enum"] = types if "series" in schema["properties"] and series: schema["properties"]["series"]["enum"] = series if chain_name == "controlnet" and isinstance(raw_models, dict): schema["architectures"] = raw_models elif chain_name == "ipadapter": from .common import _get_ipadapter_presets_by_arch presets_by_arch = _get_ipadapter_presets_by_arch() schema["presets_by_architecture"] = presets_by_arch all_presets = sorted(list(set(presets_by_arch.get("SD1.5", []) + presets_by_arch.get("SDXL", [])))) if "properties" in schema and "preset" in schema["properties"]: schema["properties"]["preset"]["enum"] = all_presets entry["parameters_schema"] = schema return entry
def handle_get_feature_list(feature_name: str | list[str] = "") -> list | dict: """ Dynamically load supported advanced features from chain_features.yaml.
- If feature_name is empty: returns a summary list of ALL features (excluding parameters_schema) to optimize response size and token usage. - If feature_name is specified (single feature name, comma-separated string, or list of strings): returns complete feature details INCLUDING parameters_schema for the requested feature(s). """ chain_features = _load_yaml(_CHAIN_FEATURES_PATH)
targets = [] is_single_string_query = False
if isinstance(feature_name, list): targets = [str(x).strip() for x in feature_name if str(x).strip()] elif isinstance(feature_name, str) and feature_name.strip(): raw_str = feature_name.strip() parts = [x.strip() for x in raw_str.split(",") if x.strip()] targets = parts if len(parts) == 1 and "," not in raw_str: is_single_string_query = True
# Case 1: Empty input -> return summary list of all features (without parameters_schema) if not targets: return [ _build_feature_entry(name, data, include_schema=False) for name, data in chain_features.items() ]
# Helper function to resolve feature target by key or chains alias def _resolve_target(target_name: str) -> str | None: if target_name in chain_features: return target_name for feat_key, feat_data in chain_features.items(): feat_chains = feat_data.get("chains") if isinstance(feat_chains, str) and feat_chains == target_name: return feat_key elif isinstance(feat_chains, list) and target_name in feat_chains: return feat_key return None
resolved_targets = [] # Case 2: Specific feature(s) requested -> validate existence for target in targets: resolved = _resolve_target(target) if not resolved: return make_not_found_error("feature_name", target) resolved_targets.append(resolved)
# Case 3: Return full info including parameters_schema results = [ _build_feature_entry(target, chain_features[target], include_schema=True) for target in resolved_targets ]
if is_single_string_query and len(results) == 1: return results[0]
return results
import os
from copy import deepcopy
from .common import _load_yaml, _CHAIN_FEATURES_PATH, _YAML_DIR
from .error_schema import make_not_found_error
def _build_feature_entry(chain_name: str, chain_data: dict, include_schema: bool = False) -> dict:
entry = {
"feature_name": chain_name,
"chains": chain_data.get("chains", chain_name),
"display_name": chain_data.get("display_name", chain_name),
"description": chain_data.get("description", ""),
"supported_tasks": chain_data.get("supported_tasks", []),
"max_count": chain_data.get("max_count", 1),
"usage_guideline": chain_data.get("usage_guideline", ""),
}
if include_schema:
schema = deepcopy(chain_data.get("parameters_schema", {}))
if chain_name in ("krea2_controlnet", "diffsynth_controlnet", "controlnet", "anima_controlnet_lllite"):
config_key = (
"Krea2_ControlNet" if chain_name == "krea2_controlnet"
else "DiffSynth_ControlNet" if chain_name == "diffsynth_controlnet"
else "Anima_ControlNet_Lllite" if chain_name == "anima_controlnet_lllite"
else "ControlNet"
)
yaml_filename = f"{chain_name}_models.yaml"
model_path = os.path.join(_YAML_DIR, yaml_filename)
raw_models = _load_yaml(model_path).get(config_key, [])
models_list = []
if isinstance(raw_models, dict):
for val in raw_models.values():
if isinstance(val, list):
models_list.extend(val)
elif isinstance(val, dict):
models_list.append(val)
elif isinstance(raw_models, list):
models_list = raw_models
types_set = set()
for m in models_list:
t_val = m.get("Type", [])
if isinstance(t_val, list):
types_set.update(t_val)
elif isinstance(t_val, str):
types_set.add(t_val)
types = sorted(list(types_set))
series = sorted(list(set(m.get("Series") for m in models_list if m.get("Series"))))
if "properties" in schema:
if "type" in schema["properties"] and types:
schema["properties"]["type"]["enum"] = types
if "series" in schema["properties"] and series:
schema["properties"]["series"]["enum"] = series
if chain_name == "controlnet" and isinstance(raw_models, dict):
schema["architectures"] = raw_models
elif chain_name == "ipadapter":
from .common import _get_ipadapter_presets_by_arch
presets_by_arch = _get_ipadapter_presets_by_arch()
schema["presets_by_architecture"] = presets_by_arch
all_presets = sorted(list(set(presets_by_arch.get("SD1.5", []) + presets_by_arch.get("SDXL", []))))
if "properties" in schema and "preset" in schema["properties"]:
schema["properties"]["preset"]["enum"] = all_presets
entry["parameters_schema"] = schema
return entry
def handle_get_feature_list(feature_name: str | list[str] = "") -> list | dict:
"""
Dynamically load supported advanced features from chain_features.yaml.
- If feature_name is empty: returns a summary list of ALL features (excluding parameters_schema)
to optimize response size and token usage.
- If feature_name is specified (single feature name, comma-separated string, or list of strings):
returns complete feature details INCLUDING parameters_schema for the requested feature(s).
"""
chain_features = _load_yaml(_CHAIN_FEATURES_PATH)
targets = []
is_single_string_query = False
if isinstance(feature_name, list):
targets = [str(x).strip() for x in feature_name if str(x).strip()]
elif isinstance(feature_name, str) and feature_name.strip():
raw_str = feature_name.strip()
parts = [x.strip() for x in raw_str.split(",") if x.strip()]
targets = parts
if len(parts) == 1 and "," not in raw_str:
is_single_string_query = True
# Case 1: Empty input -> return summary list of all features (without parameters_schema)
if not targets:
return [
_build_feature_entry(name, data, include_schema=False)
for name, data in chain_features.items()
]
# Helper function to resolve feature target by key or chains alias
def _resolve_target(target_name: str) -> str | None:
if target_name in chain_features:
return target_name
for feat_key, feat_data in chain_features.items():
feat_chains = feat_data.get("chains")
if isinstance(feat_chains, str) and feat_chains == target_name:
return feat_key
elif isinstance(feat_chains, list) and target_name in feat_chains:
return feat_key
return None
resolved_targets = []
# Case 2: Specific feature(s) requested -> validate existence
for target in targets:
resolved = _resolve_target(target)
if not resolved:
return make_not_found_error("feature_name", target)
resolved_targets.append(resolved)
# Case 3: Return full info including parameters_schema
results = [
_build_feature_entry(target, chain_features[target], include_schema=True)
for target in resolved_targets
]
if is_single_string_query and len(results) == 1:
return results[0]
return results
123456789101112131415161718192021222324252627282930313233343536123456789101112131415161718192021222324252627282930313233343536"""MCP Tool: get_model_architecture_listGet all supported model architectures and their corresponding default resolutions."""
from .common import _load_yaml, _MODEL_ARCHITECTURES_PATH, _CONSTANTS_PATH
def handle_get_model_architecture_list() -> list: """Dynamically load all supported model architectures from model_architectures.yaml.""" arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH) constants = _load_yaml(_CONSTANTS_PATH) resolution_map = constants.get("RESOLUTION_MAP", {}) architectures = arch_config.get("architectures", {}) architecture_order = arch_config.get("architecture_order", list(architectures.keys()))
result = [] for arch_name in architecture_order: if arch_name not in architectures: continue arch_data = architectures[arch_name] model_type = arch_data.get("model_type", arch_name.lower())
default_res = [1024, 1024] if model_type in resolution_map: resolutions = resolution_map[model_type] if resolutions: first_key = next(iter(resolutions)) default_res = resolutions[first_key]
result.append({ "model_architecture": arch_name, "default_resolution": default_res, })
return result"""
MCP Tool: get_model_architecture_list
Get all supported model architectures and their corresponding default resolutions.
"""
from .common import _load_yaml, _MODEL_ARCHITECTURES_PATH, _CONSTANTS_PATH
def handle_get_model_architecture_list() -> list:
"""Dynamically load all supported model architectures from model_architectures.yaml."""
arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH)
constants = _load_yaml(_CONSTANTS_PATH)
resolution_map = constants.get("RESOLUTION_MAP", {})
architectures = arch_config.get("architectures", {})
architecture_order = arch_config.get("architecture_order", list(architectures.keys()))
result = []
for arch_name in architecture_order:
if arch_name not in architectures:
continue
arch_data = architectures[arch_name]
model_type = arch_data.get("model_type", arch_name.lower())
default_res = [1024, 1024]
if model_type in resolution_map:
resolutions = resolution_map[model_type]
if resolutions:
first_key = next(iter(resolutions))
default_res = resolutions[first_key]
result.append({
"model_architecture": arch_name,
"default_resolution": default_res,
})
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""MCP Tool: get_model_featuresQuery metadata for a specified model, including supported task types, extended features, and default inference parameters."""
from .common import ( _load_yaml, _MODEL_LIST_PATH, _MODEL_DEFAULTS_PATH, _IMAGE_GEN_FEATURES_PATH, _MODEL_ARCHITECTURES_PATH, _CHAIN_FEATURES_PATH, _TASK_DEFINITIONS,)from .error_schema import make_validation_error, make_not_found_error
def handle_get_model_features(model: str) -> dict: """Query metadata for a specified model: supported task types, extended features, and default inference parameters.""" if not model: return make_validation_error( "Parameter 'model' is required.", missing_fields=["model"], )
model_list = _load_yaml(_MODEL_LIST_PATH) model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH) features_config = _load_yaml(_IMAGE_GEN_FEATURES_PATH) arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH) chain_features = _load_yaml(_CHAIN_FEATURES_PATH)
found_arch = None checkpoints = model_list.get("Checkpoint", {}) for arch_name, arch_data in checkpoints.items(): if not isinstance(arch_data, dict): continue for m in arch_data.get("models", []): if m.get("display_name") == model: found_arch = arch_name break if found_arch: break
if not found_arch: return make_not_found_error("model", model)
architectures = arch_config.get("architectures", {}) arch_info = architectures.get(found_arch, {}) model_type = arch_info.get("model_type", found_arch.lower())
arch_features = features_config.get(model_type, features_config.get("default", {})) enabled_chains = arch_features.get("enabled_chains", [])
supported_features = [] for feat_name, feat_data in chain_features.items(): feat_chains = feat_data.get("chains") if feat_chains is None: feat_chains = [feat_name] elif isinstance(feat_chains, str): feat_chains = [feat_chains]
if any(c in enabled_chains for c in feat_chains): supported_features.append(feat_name)
arch_defaults_section = model_defaults.get(found_arch, {}) arch_level_defaults = arch_defaults_section.get("_defaults", {}) model_specific_defaults = arch_defaults_section.get(model, {}) global_defaults = model_defaults.get("Default", {})
merged_defaults = {**global_defaults, **arch_level_defaults, **model_specific_defaults}
default_parameter = { "sampler": merged_defaults.get("sampler_name", "euler"), "scheduler": merged_defaults.get("scheduler", "simple"), "steps": merged_defaults.get("steps", 20), "cfg": merged_defaults.get("cfg", 1.0), }
supported_tasks = [t["task_type"] for t in _TASK_DEFINITIONS]
result = { "name": model, "model_architecture": found_arch, "supported_tasks": supported_tasks, "supported_features": supported_features, "default_parameter": default_parameter, }
default_pos = model_specific_defaults.get( "positive_prompt", arch_level_defaults.get("positive_prompt", ""), ) default_neg = model_specific_defaults.get( "negative_prompt", arch_level_defaults.get("negative_prompt", ""), ) if default_pos: result["default_positive_prompt"] = default_pos if default_neg: result["default_negative_prompt"] = default_neg
return result"""
MCP Tool: get_model_features
Query metadata for a specified model, including supported task types, extended features, and default inference parameters.
"""
from .common import (
_load_yaml,
_MODEL_LIST_PATH,
_MODEL_DEFAULTS_PATH,
_IMAGE_GEN_FEATURES_PATH,
_MODEL_ARCHITECTURES_PATH,
_CHAIN_FEATURES_PATH,
_TASK_DEFINITIONS,
)
from .error_schema import make_validation_error, make_not_found_error
def handle_get_model_features(model: str) -> dict:
"""Query metadata for a specified model: supported task types, extended features, and default inference parameters."""
if not model:
return make_validation_error(
"Parameter 'model' is required.",
missing_fields=["model"],
)
model_list = _load_yaml(_MODEL_LIST_PATH)
model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH)
features_config = _load_yaml(_IMAGE_GEN_FEATURES_PATH)
arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH)
chain_features = _load_yaml(_CHAIN_FEATURES_PATH)
found_arch = None
checkpoints = model_list.get("Checkpoint", {})
for arch_name, arch_data in checkpoints.items():
if not isinstance(arch_data, dict):
continue
for m in arch_data.get("models", []):
if m.get("display_name") == model:
found_arch = arch_name
break
if found_arch:
break
if not found_arch:
return make_not_found_error("model", model)
architectures = arch_config.get("architectures", {})
arch_info = architectures.get(found_arch, {})
model_type = arch_info.get("model_type", found_arch.lower())
arch_features = features_config.get(model_type, features_config.get("default", {}))
enabled_chains = arch_features.get("enabled_chains", [])
supported_features = []
for feat_name, feat_data in chain_features.items():
feat_chains = feat_data.get("chains")
if feat_chains is None:
feat_chains = [feat_name]
elif isinstance(feat_chains, str):
feat_chains = [feat_chains]
if any(c in enabled_chains for c in feat_chains):
supported_features.append(feat_name)
arch_defaults_section = model_defaults.get(found_arch, {})
arch_level_defaults = arch_defaults_section.get("_defaults", {})
model_specific_defaults = arch_defaults_section.get(model, {})
global_defaults = model_defaults.get("Default", {})
merged_defaults = {**global_defaults, **arch_level_defaults, **model_specific_defaults}
default_parameter = {
"sampler": merged_defaults.get("sampler_name", "euler"),
"scheduler": merged_defaults.get("scheduler", "simple"),
"steps": merged_defaults.get("steps", 20),
"cfg": merged_defaults.get("cfg", 1.0),
}
supported_tasks = [t["task_type"] for t in _TASK_DEFINITIONS]
result = {
"name": model,
"model_architecture": found_arch,
"supported_tasks": supported_tasks,
"supported_features": supported_features,
"default_parameter": default_parameter,
}
default_pos = model_specific_defaults.get(
"positive_prompt",
arch_level_defaults.get("positive_prompt", ""),
)
default_neg = model_specific_defaults.get(
"negative_prompt",
arch_level_defaults.get("negative_prompt", ""),
)
if default_pos:
result["default_positive_prompt"] = default_pos
if default_neg:
result["default_negative_prompt"] = default_neg
return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636412345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""MCP Tool: get_model_listQuery the list of available image generation models, with optional filtering by model architecture."""
from .common import _load_yaml, _MODEL_LIST_PATH, _MODEL_DEFAULTS_PATH, _MODEL_ARCHITECTURES_PATHfrom .error_schema import make_not_found_error
def handle_get_model_list(model_architecture: str = None) -> list | dict: """Dynamically load the list of available image generation models from model_list.yaml.""" model_list = _load_yaml(_MODEL_LIST_PATH) model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH) arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH) valid_architectures = set(arch_config.get("architectures", {}).keys())
if model_architecture and model_architecture not in valid_architectures: return make_not_found_error("architecture", model_architecture)
result = [] checkpoints = model_list.get("Checkpoint", {})
for arch_name, arch_data in checkpoints.items(): if model_architecture and arch_name != model_architecture: continue if not isinstance(arch_data, dict): continue
models = arch_data.get("models", []) if not isinstance(models, list): continue
arch_defaults = model_defaults.get(arch_name, {}) arch_level_defaults = arch_defaults.get("_defaults", {})
for model in models: display_name = model.get("display_name", "") category = model.get("category", None)
model_specific_defaults = arch_defaults.get(display_name, {})
default_pos = model_specific_defaults.get( "positive_prompt", arch_level_defaults.get("positive_prompt", ""), ) default_neg = model_specific_defaults.get( "negative_prompt", arch_level_defaults.get("negative_prompt", ""), )
entry = { "name": display_name, "model_architecture": arch_name, } if category: entry["category"] = category if default_pos: entry["default_positive_prompt"] = default_pos if default_neg: entry["default_negative_prompt"] = default_neg
result.append(entry)
return result"""
MCP Tool: get_model_list
Query the list of available image generation models, with optional filtering by model architecture.
"""
from .common import _load_yaml, _MODEL_LIST_PATH, _MODEL_DEFAULTS_PATH, _MODEL_ARCHITECTURES_PATH
from .error_schema import make_not_found_error
def handle_get_model_list(model_architecture: str = None) -> list | dict:
"""Dynamically load the list of available image generation models from model_list.yaml."""
model_list = _load_yaml(_MODEL_LIST_PATH)
model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH)
arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH)
valid_architectures = set(arch_config.get("architectures", {}).keys())
if model_architecture and model_architecture not in valid_architectures:
return make_not_found_error("architecture", model_architecture)
result = []
checkpoints = model_list.get("Checkpoint", {})
for arch_name, arch_data in checkpoints.items():
if model_architecture and arch_name != model_architecture:
continue
if not isinstance(arch_data, dict):
continue
models = arch_data.get("models", [])
if not isinstance(models, list):
continue
arch_defaults = model_defaults.get(arch_name, {})
arch_level_defaults = arch_defaults.get("_defaults", {})
for model in models:
display_name = model.get("display_name", "")
category = model.get("category", None)
model_specific_defaults = arch_defaults.get(display_name, {})
default_pos = model_specific_defaults.get(
"positive_prompt",
arch_level_defaults.get("positive_prompt", ""),
)
default_neg = model_specific_defaults.get(
"negative_prompt",
arch_level_defaults.get("negative_prompt", ""),
)
entry = {
"name": display_name,
"model_architecture": arch_name,
}
if category:
entry["category"] = category
if default_pos:
entry["default_positive_prompt"] = default_pos
if default_neg:
entry["default_negative_prompt"] = default_neg
result.append(entry)
return result12345678910111234567891011"""MCP Tool: get_task_listGet a list of all supported image generation task types along with their required/optional parameter lists."""
from .common import _TASK_DEFINITIONS
def handle_get_task_list() -> list: """Get a list of all supported image generation task types along with their required/optional parameter lists.""" return _TASK_DEFINITIONS"""
MCP Tool: get_task_list
Get a list of all supported image generation task types along with their required/optional parameter lists.
"""
from .common import _TASK_DEFINITIONS
def handle_get_task_list() -> list:
"""Get a list of all supported image generation task types along with their required/optional parameter lists."""
return _TASK_DEFINITIONS123456789101112131415161718192021123456789101112131415161718192021"""MCP Tool: get_task_statusQuery the processing progress and final results of an async image generation task."""
from .common import _TASKS_DBfrom .error_schema import make_validation_error, make_not_found_error
def handle_get_task_status(task_id: str) -> dict: """Query the processing progress and final results of an async image generation task.""" if not task_id: return make_validation_error( "Parameter 'task_id' is required.", missing_fields=["task_id"], )
if task_id not in _TASKS_DB: return make_not_found_error("task", task_id)
return _TASKS_DB[task_id]"""
MCP Tool: get_task_status
Query the processing progress and final results of an async image generation task.
"""
from .common import _TASKS_DB
from .error_schema import make_validation_error, make_not_found_error
def handle_get_task_status(task_id: str) -> dict:
"""Query the processing progress and final results of an async image generation task."""
if not task_id:
return make_validation_error(
"Parameter 'task_id' is required.",
missing_fields=["task_id"],
)
if task_id not in _TASKS_DB:
return make_not_found_error("task", task_id)
return _TASKS_DB[task_id]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""MCP & Gradio Integration Module
Provides:1. register_high_level_mcp_apis: Expose only 7 high-level abstract API/MCP endpoints (using gr.api without polluting the visual UI structure)2. cleanup_dependencies_api_names: Force cleanup of show_api attribute for non-high-level APIs in dependencies3. patch_gradio_api_suppression: No-op implementation retained for backward compatibility"""
import jsonimport gradio as gr
from .get_task_list import handle_get_task_listfrom .get_model_architecture_list import handle_get_model_architecture_listfrom .get_model_list import handle_get_model_listfrom .get_feature_list import handle_get_feature_listfrom .get_model_features import handle_get_model_featuresfrom .run import handle_runfrom .get_task_status import handle_get_task_status
HIGH_LEVEL_MCP_API_NAMES = { "get_task_list", "get_model_architecture_list", "get_model_list", "get_feature_list", "get_model_features", "run", "get_task_status",}
def sanitize_keys(obj): """Recursively ensure all dictionary keys are converted to str type to avoid Gradio 5 orjson TypeError: Dict key must be str.""" if isinstance(obj, dict): return {str(k): sanitize_keys(v) for k, v in obj.items()} elif isinstance(obj, list): return [sanitize_keys(x) for x in obj] elif isinstance(obj, tuple): return tuple(sanitize_keys(x) for x in obj) return obj
def patch_gradio_api_suppression(): """Retained for backward compatibility (no-op).""" pass
def cleanup_dependencies_api_names(demo): """ Clean up residual auto-generated API names in demo.fns and demo.dependencies. Force only the 7 high-level abstract MCP APIs to be exposed as public endpoints. """ for fn in demo.fns.values(): api_name = getattr(fn, "api_name", None) if api_name not in HIGH_LEVEL_MCP_API_NAMES: fn.show_api = False
deps = getattr(demo, "dependencies", None) if deps is None and hasattr(demo, "config") and isinstance(demo.config, dict): deps = demo.config.get("dependencies", [])
if deps: for dep in deps: if isinstance(dep, dict): api_name = dep.get("api_name") if api_name not in HIGH_LEVEL_MCP_API_NAMES: dep["show_api"] = False
print("[MCP Protection] Cleaned up demo dependencies. Suppressed atomic API endpoints.")
def register_high_level_mcp_apis(demo): """ Explicitly register 7 high-level abstract MCP API endpoints on the Gradio demo using gr.api. Using gr.api() never adds any visual UI components (such as Row, Textbox, Button, etc.), avoiding duplicate interface rendering. """ def get_task_list() -> list: """[Recommended Discovery Flow Step 1] Get a list of all supported image generation task types (txt2img, img2img, inpaint, outpaint, hires_fix) along with their required and optional parameter lists. Recommended flow: get_task_list -> get_model_architecture_list -> get_model_list -> [Path 1: Call run directly (pass only required params) | Path 2: Call get_model_features to get official default hyperparams -> run].""" return sanitize_keys(handle_get_task_list())
def get_model_architecture_list() -> list: """[Recommended Discovery Flow Step 2] Get a list of all supported model architectures (e.g., SD1.5, SDXL, FLUX, etc.) along with their default resolutions. It is recommended to call this tool before get_model_list to obtain valid model_architecture parameters for precise model filtering.""" return sanitize_keys(handle_get_model_architecture_list())
def get_model_list(model_architecture: str = "") -> list | dict: """[Recommended Discovery Flow Step 3] Query the list of available image generation models. After obtaining models, choose one of two paths: 1. [Path 1 (Recommended - Minimal Mode)] Call run directly with only required parameters. Do NOT guess steps/cfg/sampler/scheduler from experience; the server will automatically apply the model's optimal default hyperparameters. 2. [Path 2 (Explicit Alignment Mode)] First call get_model_features to query the model's officially recommended hyperparameters, then pass them to run.""" arch = model_architecture.strip() if model_architecture else None return sanitize_keys(handle_get_model_list(arch))
def get_feature_list(feature_name: str = "") -> list | dict: """Get supported advanced features. If feature_name is empty, returns a summary list of ALL features (excluding parameters_schema to save tokens). Pass a specific feature_name (single name like 'lora', or comma-separated like 'lora, ipadapter') to retrieve complete details INCLUDING parameters_schema for requested feature(s).""" return sanitize_keys(handle_get_feature_list(feature_name.strip() if isinstance(feature_name, str) else feature_name))
def get_model_features(model: str = "") -> dict: """Query metadata for the specified model, including supported task types, extended features, and official default inference parameters (steps, cfg, sampler, scheduler). This tool MUST be called when explicitly obtaining a model's optimal default hyperparameters (Path 2). Guessing or fabricating hyperparameters without querying is strictly prohibited.""" return sanitize_keys(handle_get_model_features(model.strip()))
def run(json_params: str = "{}") -> dict: """[Recommended Discovery Flow Step 4] Unified image generation task execution interface. Supports txt2img, img2img, and other tasks with chainable extended features. [IMPORTANT PARAMETER RULES] Do NOT guess or fabricate inference hyperparameters such as steps, cfg, sampler, scheduler! Path 1 (Recommended): Pass only required parameters (task_type, model, prompt, width, height), leave optional hyperparams empty (server uses optimal defaults). Path 2: If explicit hyperparams are needed, you MUST first call get_model_features to obtain official defaults before passing them.""" try: if isinstance(json_params, dict): params = json_params else: params = json.loads(json_params or "{}") except Exception as e: return {"error": {"code": "INVALID_JSON", "message": f"Failed to parse JSON params: {e}"}} return sanitize_keys(handle_run(params))
def get_task_status(task_id: str = "") -> dict: """Query the progress, status, and final generated results of an async image generation task.""" return sanitize_keys(handle_get_task_status(task_id.strip()))
funcs = [ get_task_list, get_model_architecture_list, get_model_list, get_feature_list, get_model_features, run, get_task_status, ]
for func in funcs: gr.api(func)
for fn in demo.fns.values(): if getattr(fn, "api_name", None) in HIGH_LEVEL_MCP_API_NAMES: fn.show_api = True
print("[MCP Integration] Successfully registered 7 High-Level Abstract MCP APIs via gr.api().")"""
MCP & Gradio Integration Module
Provides:
1. register_high_level_mcp_apis: Expose only 7 high-level abstract API/MCP endpoints (using gr.api without polluting the visual UI structure)
2. cleanup_dependencies_api_names: Force cleanup of show_api attribute for non-high-level APIs in dependencies
3. patch_gradio_api_suppression: No-op implementation retained for backward compatibility
"""
import json
import gradio as gr
from .get_task_list import handle_get_task_list
from .get_model_architecture_list import handle_get_model_architecture_list
from .get_model_list import handle_get_model_list
from .get_feature_list import handle_get_feature_list
from .get_model_features import handle_get_model_features
from .run import handle_run
from .get_task_status import handle_get_task_status
HIGH_LEVEL_MCP_API_NAMES = {
"get_task_list",
"get_model_architecture_list",
"get_model_list",
"get_feature_list",
"get_model_features",
"run",
"get_task_status",
}
def sanitize_keys(obj):
"""Recursively ensure all dictionary keys are converted to str type to avoid Gradio 5 orjson TypeError: Dict key must be str."""
if isinstance(obj, dict):
return {str(k): sanitize_keys(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [sanitize_keys(x) for x in obj]
elif isinstance(obj, tuple):
return tuple(sanitize_keys(x) for x in obj)
return obj
def patch_gradio_api_suppression():
"""Retained for backward compatibility (no-op)."""
pass
def cleanup_dependencies_api_names(demo):
"""
Clean up residual auto-generated API names in demo.fns and demo.dependencies.
Force only the 7 high-level abstract MCP APIs to be exposed as public endpoints.
"""
for fn in demo.fns.values():
api_name = getattr(fn, "api_name", None)
if api_name not in HIGH_LEVEL_MCP_API_NAMES:
fn.show_api = False
deps = getattr(demo, "dependencies", None)
if deps is None and hasattr(demo, "config") and isinstance(demo.config, dict):
deps = demo.config.get("dependencies", [])
if deps:
for dep in deps:
if isinstance(dep, dict):
api_name = dep.get("api_name")
if api_name not in HIGH_LEVEL_MCP_API_NAMES:
dep["show_api"] = False
print("[MCP Protection] Cleaned up demo dependencies. Suppressed atomic API endpoints.")
def register_high_level_mcp_apis(demo):
"""
Explicitly register 7 high-level abstract MCP API endpoints on the Gradio demo using gr.api.
Using gr.api() never adds any visual UI components (such as Row, Textbox, Button, etc.), avoiding duplicate interface rendering.
"""
def get_task_list() -> list:
"""[Recommended Discovery Flow Step 1] Get a list of all supported image generation task types (txt2img, img2img, inpaint, outpaint, hires_fix) along with their required and optional parameter lists. Recommended flow: get_task_list -> get_model_architecture_list -> get_model_list -> [Path 1: Call run directly (pass only required params) | Path 2: Call get_model_features to get official default hyperparams -> run]."""
return sanitize_keys(handle_get_task_list())
def get_model_architecture_list() -> list:
"""[Recommended Discovery Flow Step 2] Get a list of all supported model architectures (e.g., SD1.5, SDXL, FLUX, etc.) along with their default resolutions. It is recommended to call this tool before get_model_list to obtain valid model_architecture parameters for precise model filtering."""
return sanitize_keys(handle_get_model_architecture_list())
def get_model_list(model_architecture: str = "") -> list | dict:
"""[Recommended Discovery Flow Step 3] Query the list of available image generation models. After obtaining models, choose one of two paths: 1. [Path 1 (Recommended - Minimal Mode)] Call run directly with only required parameters. Do NOT guess steps/cfg/sampler/scheduler from experience; the server will automatically apply the model's optimal default hyperparameters. 2. [Path 2 (Explicit Alignment Mode)] First call get_model_features to query the model's officially recommended hyperparameters, then pass them to run."""
arch = model_architecture.strip() if model_architecture else None
return sanitize_keys(handle_get_model_list(arch))
def get_feature_list(feature_name: str = "") -> list | dict:
"""Get supported advanced features. If feature_name is empty, returns a summary list of ALL features (excluding parameters_schema to save tokens). Pass a specific feature_name (single name like 'lora', or comma-separated like 'lora, ipadapter') to retrieve complete details INCLUDING parameters_schema for requested feature(s)."""
return sanitize_keys(handle_get_feature_list(feature_name.strip() if isinstance(feature_name, str) else feature_name))
def get_model_features(model: str = "") -> dict:
"""Query metadata for the specified model, including supported task types, extended features, and official default inference parameters (steps, cfg, sampler, scheduler). This tool MUST be called when explicitly obtaining a model's optimal default hyperparameters (Path 2). Guessing or fabricating hyperparameters without querying is strictly prohibited."""
return sanitize_keys(handle_get_model_features(model.strip()))
def run(json_params: str = "{}") -> dict:
"""[Recommended Discovery Flow Step 4] Unified image generation task execution interface. Supports txt2img, img2img, and other tasks with chainable extended features. [IMPORTANT PARAMETER RULES] Do NOT guess or fabricate inference hyperparameters such as steps, cfg, sampler, scheduler! Path 1 (Recommended): Pass only required parameters (task_type, model, prompt, width, height), leave optional hyperparams empty (server uses optimal defaults). Path 2: If explicit hyperparams are needed, you MUST first call get_model_features to obtain official defaults before passing them."""
try:
if isinstance(json_params, dict):
params = json_params
else:
params = json.loads(json_params or "{}")
except Exception as e:
return {"error": {"code": "INVALID_JSON", "message": f"Failed to parse JSON params: {e}"}}
return sanitize_keys(handle_run(params))
def get_task_status(task_id: str = "") -> dict:
"""Query the progress, status, and final generated results of an async image generation task."""
return sanitize_keys(handle_get_task_status(task_id.strip()))
funcs = [
get_task_list,
get_model_architecture_list,
get_model_list,
get_feature_list,
get_model_features,
run,
get_task_status,
]
for func in funcs:
gr.api(func)
for fn in demo.fns.values():
if getattr(fn, "api_name", None) in HIGH_LEVEL_MCP_API_NAMES:
fn.show_api = True
print("[MCP Integration] Successfully registered 7 High-Level Abstract MCP APIs via gr.api().")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""MCP Tool: runUnified image generation task submission and execution interface."""
import timeimport uuidimport threadingfrom .common import ( _load_yaml, _MODEL_LIST_PATH, _TASK_DEFINITIONS, _TASKS_DB, _execute_imagegen_pipeline,)from .error_schema import make_validation_error, make_not_found_error
def handle_run(params: dict) -> dict: """Unified image generation task execution interface.""" if not isinstance(params, dict): return make_validation_error("Request params must be an object.")
missing = [] for req_field in ["task_type", "model", "prompt"]: if req_field not in params or not params[req_field]: missing.append(req_field) if missing: return make_validation_error( f"Missing required parameter(s): {', '.join(missing)}", missing_fields=missing, )
task_type = params["task_type"] valid_tasks = [t["task_type"] for t in _TASK_DEFINITIONS] if task_type not in valid_tasks: return make_validation_error( f"Invalid task_type '{task_type}'. Must be one of {valid_tasks}.", invalid_fields={"task_type": f"Must be in {valid_tasks}"}, )
model_list = _load_yaml(_MODEL_LIST_PATH) checkpoints = model_list.get("Checkpoint", {}) all_models = set() for arch_name, arch_data in checkpoints.items(): if isinstance(arch_data, dict): for m in arch_data.get("models", []): all_models.add(m.get("display_name"))
if params["model"] not in all_models: return make_not_found_error("model", params["model"])
task_id = f"img_task_{uuid.uuid4().hex[:10]}" created_at = int(time.time())
_TASKS_DB[task_id] = { "task_id": task_id, "status": "queued", "progress": 0, "created_at": created_at, }
async_exec = params.get("async_execution", False)
if async_exec: t = threading.Thread(target=_execute_imagegen_pipeline, args=(task_id, params), daemon=True) t.start() return { "status": "queued", "task_id": task_id, "poll_interval_ms": 2000, "message": "Task queued successfully. Poll get_task_status for results.", } else: _execute_imagegen_pipeline(task_id, params) return _TASKS_DB[task_id]"""
MCP Tool: run
Unified image generation task submission and execution interface.
"""
import time
import uuid
import threading
from .common import (
_load_yaml,
_MODEL_LIST_PATH,
_TASK_DEFINITIONS,
_TASKS_DB,
_execute_imagegen_pipeline,
)
from .error_schema import make_validation_error, make_not_found_error
def handle_run(params: dict) -> dict:
"""Unified image generation task execution interface."""
if not isinstance(params, dict):
return make_validation_error("Request params must be an object.")
missing = []
for req_field in ["task_type", "model", "prompt"]:
if req_field not in params or not params[req_field]:
missing.append(req_field)
if missing:
return make_validation_error(
f"Missing required parameter(s): {', '.join(missing)}",
missing_fields=missing,
)
task_type = params["task_type"]
valid_tasks = [t["task_type"] for t in _TASK_DEFINITIONS]
if task_type not in valid_tasks:
return make_validation_error(
f"Invalid task_type '{task_type}'. Must be one of {valid_tasks}.",
invalid_fields={"task_type": f"Must be in {valid_tasks}"},
)
model_list = _load_yaml(_MODEL_LIST_PATH)
checkpoints = model_list.get("Checkpoint", {})
all_models = set()
for arch_name, arch_data in checkpoints.items():
if isinstance(arch_data, dict):
for m in arch_data.get("models", []):
all_models.add(m.get("display_name"))
if params["model"] not in all_models:
return make_not_found_error("model", params["model"])
task_id = f"img_task_{uuid.uuid4().hex[:10]}"
created_at = int(time.time())
_TASKS_DB[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 0,
"created_at": created_at,
}
async_exec = params.get("async_execution", False)
if async_exec:
t = threading.Thread(target=_execute_imagegen_pipeline, args=(task_id, params), daemon=True)
t.start()
return {
"status": "queued",
"task_id": task_id,
"poll_interval_ms": 2000,
"message": "Task queued successfully. Poll get_task_status for results.",
}
else:
_execute_imagegen_pipeline(task_id, params)
return _TASKS_DB[task_id]1234567891011121314151617181920212223242526272812345678910111213141516171819202122232425262728"""MCP Tool Handlers — Backward-compatible aggregation entry point.Core logic has been split into individual files (get_*.py and run.py)."""
from .get_task_list import handle_get_task_listfrom .get_model_architecture_list import handle_get_model_architecture_listfrom .get_model_list import handle_get_model_listfrom .get_feature_list import handle_get_feature_listfrom .get_model_features import handle_get_model_featuresfrom .run import handle_runfrom .get_task_status import handle_get_task_statusfrom .common import ( _TASK_DEFINITIONS, _TASKS_DB, _load_yaml, _execute_imagegen_pipeline,)
__all__ = [ "handle_get_task_list", "handle_get_model_architecture_list", "handle_get_model_list", "handle_get_feature_list", "handle_get_model_features", "handle_run", "handle_get_task_status",]"""
MCP Tool Handlers — Backward-compatible aggregation entry point.
Core logic has been split into individual files (get_*.py and run.py).
"""
from .get_task_list import handle_get_task_list
from .get_model_architecture_list import handle_get_model_architecture_list
from .get_model_list import handle_get_model_list
from .get_feature_list import handle_get_feature_list
from .get_model_features import handle_get_model_features
from .run import handle_run
from .get_task_status import handle_get_task_status
from .common import (
_TASK_DEFINITIONS,
_TASKS_DB,
_load_yaml,
_execute_imagegen_pipeline,
)
__all__ = [
"handle_get_task_list",
"handle_get_model_architecture_list",
"handle_get_model_list",
"handle_get_feature_list",
"handle_get_model_features",
"handle_run",
"handle_get_task_status",
]11 unmodified lines121314151516171811 unmodified lines with gr.Blocks() as demo:
gr.Markdown("# ImageGen")
gr.Markdown(
"This demo is a streamlined version of the [Comfy web UI](https://github.com/RioShiina47/comfy-webui)'s [ImageGen](https://huggingface.co/spaces/RioShiina/ImageGen) functionality."
"This demo is a streamlined version of the [Comfy web UI](https://github.com/RioShiina47/comfy-webui)'s [ImageGen](https://huggingface.co/spaces/RioShiina/ImageGen) functionality. Support [High-Level MCP](https://rioshiina-imagegen.hf.space/gradio_api/mcp/) 🤖"
)
with gr.Tabs(elem_id="tabs_container") as tabs:
with gr.TabItem("Txt2Img", id=0):123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652# Complete Feature & Chain Definitions Configuration for MCP Tools# Every chain injector in chain_injectors/ corresponds 1-to-1 with an entry here (21 injectors total).
lora: chains: lora display_name: "LoRA Fine-tuning Injector" description: "Injects LoRA weights into UNet/DiT model and CLIP text encoder for custom style, character, or domain adaptation." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), then provide the lora_value (Civitai Version ID or HF repo path), and a single scale value (0.0~2.0) that controls both model and clip strength simultaneously." parameters_schema: type: object properties: source: type: string enum: ["Civitai", "Hugging Face"] description: "Download source for the LoRA model. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo path." lora_value: type: string description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456). For Hugging Face: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., 'lightx2v/Qwen-Image-Lightning/Qwen-Image-Lightning-4steps-V2.0-bf16.safetensors')." scale: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Unified strength applied to both the UNet/DiT model and CLIP text encoder (0.0 to 2.0)." required: - source - lora_value
ipadapter: chains: ipadapter display_name: "IP-Adapter Image Prompt" description: "Uses reference images to guide generation style, composition, structure, or face appearance without prompt text restrictions (SD1.5 & SDXL)." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply global settings (preset, embeds_scaling, combine_method, final_weight) and up to 5 reference images with individual weights. Preset must match the target model architecture (SD1.5 or SDXL)." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI (e.g., data:image/png;base64,...) or HTTP/HTTPS URL." weight: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Influence weight of the individual image prompt (0.0 to 2.0)." preset: type: string default: "STANDARD (medium strength)" description: "IPAdapter preset model variant loaded from ipadapter.yaml. Must match model architecture (SD1.5 vs SDXL)." embeds_scaling: type: string default: "V only" enum: - "V only" - "K+V" - "K+V w/ C penalty" - "K+mean(V) w/ C penalty" description: "Embedding scaling method for IPAdapter." combine_method: type: string default: "concat" enum: - "concat" - "add" - "subtract" - "average" - "norm average" - "max" - "min" description: "Combination method for multiple reference images." final_weight: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Global weight multiplier for IPAdapter conditioning (0.0 to 2.0)." lora_strength: type: number default: 0.6 description: "LoRA weight strength for FaceID adapter variants." required: - image
controlnet: chains: controlnet display_name: "ControlNet Spatial Guidance" description: "Applies structural and spatial conditioning (depth, pose, lineart, tile, scribble, canny) to guide output composition." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Specify ControlNet type and series (must match requested model architecture e.g., SD1.5, SDXL, SD3.5, FLUX.1, Qwen-Image), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and guidance strength." parameters_schema: type: object properties: type: type: string description: "ControlNet conditioning type (must match model architecture)." series: type: string description: "ControlNet model series (must match model architecture)." image: type: string description: "Pre-processed control image (e.g., Depth, Canny, Pose, Lineart map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." strength: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Control influence strength (0.0 to 2.0)." required: - type - series - image
conditioning: chains: conditioning display_name: "Regional Conditioning / Area Prompt" description: "Defines rectangular areas (X, Y, Width, Height) and assigns specific text prompts and conditioning strengths to them." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 10 usage_guideline: "Define rectangular spatial areas (X, Y, width, height) and assign specific prompts and strengths to them. Supports up to 10 area prompts." parameters_schema: type: object properties: prompt: type: string description: "Text prompt for this specific rectangular area." x: type: integer default: 0 description: "Top-left X coordinate of the rectangular area." y: type: integer default: 0 description: "Top-left Y coordinate of the rectangular area." width: type: integer default: 512 description: "Width of the rectangular area." height: type: integer default: 512 description: "Height of the rectangular area." strength: type: number default: 1.0 minimum: 0.1 maximum: 2.0 description: "Conditioning strength for this area (0.1 to 2.0)." required: - prompt
vae: chains: vae display_name: "Custom VAE Loader" description: "Overrides default VAE model used for latent space encoding and final image decoding." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 1 usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), then provide the vae_value (Civitai Version ID or HF file path)." parameters_schema: type: object properties: source: type: string enum: ["Civitai", "Hugging Face"] description: "Download source for the VAE model. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo path." vae_value: type: string description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456). For Hugging Face: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., 'madebyollin/sdxl-vae-fp16-fix/sdxl_vae.safetensors')." required: - source - vae_value
pid: chains: pid display_name: "PiD High-Resolution Refinement" description: "Progressive Detail (PiD) upscale injector for fine detail enhancement and resolution upscaling." supported_tasks: - txt2img max_count: 1 usage_guideline: "Enables PiD detail refinement pipeline using a boolean switch ('enabled': true/false)." parameters_schema: type: object properties: enabled: type: boolean default: true description: "Enable or disable PiD High-Resolution Refinement." required: - enabled
flux1_style: chains: style display_name: "FLUX.1 Style Reference" description: "Applies artistic style conditioning from reference images onto FLUX.1 model generated outputs." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply style reference image(s) (up to 5) encoded as Base64 Data URI or HTTP/HTTPS URL and optional strength." parameters_schema: type: object properties: image: type: string description: "Style reference image encoded as Base64 Data URI or HTTP/HTTPS URL." strength: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Style influence strength (0.0 to 2.0)." required: - image
reference_edit: chains: reference_latent display_name: "Reference Edit" description: "For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 10 usage_guideline: "Supply reference image(s) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images (up to 10) performs an Image Combine." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
mage_flow_reference_edit: chains: reference_image display_name: "Mage-Flow Reference Edit" description: " (Mage-Flow-Edit-Turbo/Mage-Flow-Edit recommended) For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 10 usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
krea2_identity_edit: chains: krea2_identity_edit display_name: "KREA2 Identity Edit" description: "Processed using the lbouaraba/comfyui-krea2edit node. (Krea-2-Turbo recommended, Krea-2-Raw need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 2 usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
krea2_style_reference: chains: krea2_style_reference display_name: "KREA2 Style Reference" description: "(Krea-2-Turbo recommended) Add style reference images to perform style reference editing." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 3 usage_guideline: "Supply style reference image as Base64 Data URI or HTTP/HTTPS URL." parameters_schema: type: object properties: image: type: string description: "Style reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
diffsynth_controlnet: chains: diffsynth_controlnet display_name: "DiffSynth ControlNet" description: "DiffSynth optimized ControlNet injector for Z-Image models." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply ControlNet type (e.g., 'Canny'), series (e.g., 'alibaba-pai Controlnet Union 2.1 8steps'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength." parameters_schema: type: object properties: type: type: string description: "ControlNet conditioning type." series: type: string description: "ControlNet model series name." image: type: string description: "Pre-processed control image (e.g., Depth map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." strength: type: number default: 1.0 description: "Control influence strength." required: - type - series - image
boogu_image_edit: chains: boogu_image_edit display_name: "Boogu-Image Edit" description: " (Boogu-Image-Edit-Turbo/Boogu-Image-Edit recommended, Boogu-Image-Edit need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 2 usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
joyai_reference_edit: chains: joyai_image display_name: "JoyAI Reference Edit" description: " (JoyAI-Image-Edit recommended) For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit (JoyAI-Image-Edit recommended), while adding multiple images performs an Image Combine (JoyAI-Image-Edit-Plus recommended with ZeroGPU Duration (s) set to 120)." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 2 usage_guideline: "Supply JoyAI reference image as Base64 Data URI or HTTP/HTTPS URL." parameters_schema: type: object properties: image: type: string description: "Input reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
qwen_image_edit: chains: qwen_image_edit display_name: "Qwen-Image Edit" description: " (lightx2v/Qwen-Image-Edit-2511-Lightning recommended) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 3 usage_guideline: "Supply reference image(s) (up to 3) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images performs an Image Combine." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
hidream_o1_smoothing: chains: hidream_o1_smoothing display_name: "HiDream O1 Smoothing Injector" description: "HiDream O1 detail smoothing and artifact reduction injector." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 1 usage_guideline: "Configures smoothing factor for HiDream models." parameters_schema: type: object properties: factor: type: number default: 0.5 description: "Smoothing intensity (0.0 to 1.0)." required: []
krea2_controlnet: chains: krea2_controlnet display_name: "KREA2 ControlNet" description: "Processed using the facok/comfyui-krea2-controlnet node." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply ControlNet type (e.g., 'Depth'), series (e.g., 'Patil'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength." parameters_schema: type: object properties: type: type: string enum: - "Depth" description: "ControlNet conditioning type." series: type: string enum: - "Patil" default: "Patil" description: "ControlNet model series." image: type: string description: "Pre-processed control image (e.g., Depth map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." strength: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Control influence strength (0.0 to 2.0)." required: - type - series - image
anima_controlnet_lllite: chains: anima_controlnet_lllite display_name: "Anima ControlNet LLLite" description: "Anima model-specific lightweight ControlNet." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply Anima ControlNet LLLite type (e.g., 'Depth'), series (e.g., 'kohya-ss'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength." parameters_schema: type: object properties: type: type: string description: "Anima ControlNet LLLite conditioning type." series: type: string description: "Anima ControlNet LLLite model series." image: type: string description: "Pre-processed control image (e.g., Depth, Lineart map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." strength: type: number default: 1.0 minimum: 0.0 maximum: 2.0 description: "Control influence strength (0.0 to 2.0)." required: - type - series - image
hidream_o1_reference: chains: hidream_o1_reference display_name: "HiDream-O1 Reference Edit" description: " (HiDream-O1-Image-Dev recommended with resolution set to 4.0MP, e.g., 2048x2048) For HiDream-O1 models, this feature enables reference image editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 9 usage_guideline: "Supply reference image(s) (up to 9) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images performs an Image Combine." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." required: - image
flux1_ipadapter: chains: flux1_ipadapter display_name: "Flux1 IP-Adapter" description: "FLUX.1 model-specific IP-Adapter implementation." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply reference image (Base64 Data URI or HTTP/HTTPS URL), optional weight (default 1.0), start_at (default 0.0), and end_at (default 1.0). Up to 5 images supported." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." weight: type: number default: 1.0 description: "Influence weight of the image prompt (0.0 to 2.0)." start_at: type: number default: 0.0 description: "Start step percentage for IP-Adapter application (0.0 to 1.0)." end_at: type: number default: 1.0 description: "End step percentage for IP-Adapter application (0.0 to 1.0)." start_percent: type: number default: 0.0 description: "Alias for start_at." end_percent: type: number default: 1.0 description: "Alias for end_at." required: - image
sd3_ipadapter: chains: sd3_ipadapter display_name: "SD3 IP-Adapter" description: "SD3/SD3.5 model-specific IP-Adapter implementation." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Supply reference image (Base64 Data URI or HTTP/HTTPS URL), optional weight (default 1.0), start_at (default 0.0), and end_at (default 1.0). Up to 5 images supported." parameters_schema: type: object properties: image: type: string description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." weight: type: number default: 1.0 description: "Influence weight of the image prompt (0.0 to 2.0)." start_at: type: number default: 0.0 description: "Start step percentage for IP-Adapter application (0.0 to 1.0)." end_at: type: number default: 1.0 description: "End step percentage for IP-Adapter application (0.0 to 1.0)." start_percent: type: number default: 0.0 description: "Alias for start_at." end_percent: type: number default: 1.0 description: "Alias for end_at." required: - image
embedding: chains: embedding display_name: "Textual Inversion Embedding Injector" description: "Downloads Textual Inversion embedding files from Civitai or Hugging Face to the server. Note: This feature ONLY handles file downloading/preparation. To activate the embedding, manually add 'embedding:<filename>' (e.g. 'embedding:civitai_456' for Civitai ID 456, or 'embedding:filename' for Hugging Face) into your prompt or negative_prompt." supported_tasks: - txt2img - img2img - inpaint - outpaint - hires_fix max_count: 5 usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), and embedding_value (Civitai Version ID or HF repo file path). The file is downloaded to server; manually enter 'embedding:<filename>' in prompt or negative_prompt to activate." parameters_schema: type: object properties: source: type: string enum: - "Civitai" - "Hugging Face" description: "Download source for the Textual Inversion embedding file. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo file path." embedding_value: type: string description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456, saved as 'civitai_456.safetensors'). For Hugging Face: repo_id/filename.extension (e.g., 'ilikebigturtles/lazypos/lazypos.safetensors', saved as 'lazypos.safetensors'). Manually reference embedding:<filename> in prompt or negative_prompt." required: - source - embedding_value# Complete Feature & Chain Definitions Configuration for MCP Tools
# Every chain injector in chain_injectors/ corresponds 1-to-1 with an entry here (21 injectors total).
lora:
chains: lora
display_name: "LoRA Fine-tuning Injector"
description: "Injects LoRA weights into UNet/DiT model and CLIP text encoder for custom style, character, or domain adaptation."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), then provide the lora_value (Civitai Version ID or HF repo path), and a single scale value (0.0~2.0) that controls both model and clip strength simultaneously."
parameters_schema:
type: object
properties:
source:
type: string
enum: ["Civitai", "Hugging Face"]
description: "Download source for the LoRA model. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo path."
lora_value:
type: string
description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456). For Hugging Face: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., 'lightx2v/Qwen-Image-Lightning/Qwen-Image-Lightning-4steps-V2.0-bf16.safetensors')."
scale:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Unified strength applied to both the UNet/DiT model and CLIP text encoder (0.0 to 2.0)."
required:
- source
- lora_value
ipadapter:
chains: ipadapter
display_name: "IP-Adapter Image Prompt"
description: "Uses reference images to guide generation style, composition, structure, or face appearance without prompt text restrictions (SD1.5 & SDXL)."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply global settings (preset, embeds_scaling, combine_method, final_weight) and up to 5 reference images with individual weights. Preset must match the target model architecture (SD1.5 or SDXL)."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI (e.g., data:image/png;base64,...) or HTTP/HTTPS URL."
weight:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Influence weight of the individual image prompt (0.0 to 2.0)."
preset:
type: string
default: "STANDARD (medium strength)"
description: "IPAdapter preset model variant loaded from ipadapter.yaml. Must match model architecture (SD1.5 vs SDXL)."
embeds_scaling:
type: string
default: "V only"
enum:
- "V only"
- "K+V"
- "K+V w/ C penalty"
- "K+mean(V) w/ C penalty"
description: "Embedding scaling method for IPAdapter."
combine_method:
type: string
default: "concat"
enum:
- "concat"
- "add"
- "subtract"
- "average"
- "norm average"
- "max"
- "min"
description: "Combination method for multiple reference images."
final_weight:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Global weight multiplier for IPAdapter conditioning (0.0 to 2.0)."
lora_strength:
type: number
default: 0.6
description: "LoRA weight strength for FaceID adapter variants."
required:
- image
controlnet:
chains: controlnet
display_name: "ControlNet Spatial Guidance"
description: "Applies structural and spatial conditioning (depth, pose, lineart, tile, scribble, canny) to guide output composition."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Specify ControlNet type and series (must match requested model architecture e.g., SD1.5, SDXL, SD3.5, FLUX.1, Qwen-Image), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and guidance strength."
parameters_schema:
type: object
properties:
type:
type: string
description: "ControlNet conditioning type (must match model architecture)."
series:
type: string
description: "ControlNet model series (must match model architecture)."
image:
type: string
description: "Pre-processed control image (e.g., Depth, Canny, Pose, Lineart map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images."
strength:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Control influence strength (0.0 to 2.0)."
required:
- type
- series
- image
conditioning:
chains: conditioning
display_name: "Regional Conditioning / Area Prompt"
description: "Defines rectangular areas (X, Y, Width, Height) and assigns specific text prompts and conditioning strengths to them."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 10
usage_guideline: "Define rectangular spatial areas (X, Y, width, height) and assign specific prompts and strengths to them. Supports up to 10 area prompts."
parameters_schema:
type: object
properties:
prompt:
type: string
description: "Text prompt for this specific rectangular area."
x:
type: integer
default: 0
description: "Top-left X coordinate of the rectangular area."
y:
type: integer
default: 0
description: "Top-left Y coordinate of the rectangular area."
width:
type: integer
default: 512
description: "Width of the rectangular area."
height:
type: integer
default: 512
description: "Height of the rectangular area."
strength:
type: number
default: 1.0
minimum: 0.1
maximum: 2.0
description: "Conditioning strength for this area (0.1 to 2.0)."
required:
- prompt
vae:
chains: vae
display_name: "Custom VAE Loader"
description: "Overrides default VAE model used for latent space encoding and final image decoding."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 1
usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), then provide the vae_value (Civitai Version ID or HF file path)."
parameters_schema:
type: object
properties:
source:
type: string
enum: ["Civitai", "Hugging Face"]
description: "Download source for the VAE model. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo path."
vae_value:
type: string
description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456). For Hugging Face: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., 'madebyollin/sdxl-vae-fp16-fix/sdxl_vae.safetensors')."
required:
- source
- vae_value
pid:
chains: pid
display_name: "PiD High-Resolution Refinement"
description: "Progressive Detail (PiD) upscale injector for fine detail enhancement and resolution upscaling."
supported_tasks:
- txt2img
max_count: 1
usage_guideline: "Enables PiD detail refinement pipeline using a boolean switch ('enabled': true/false)."
parameters_schema:
type: object
properties:
enabled:
type: boolean
default: true
description: "Enable or disable PiD High-Resolution Refinement."
required:
- enabled
flux1_style:
chains: style
display_name: "FLUX.1 Style Reference"
description: "Applies artistic style conditioning from reference images onto FLUX.1 model generated outputs."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply style reference image(s) (up to 5) encoded as Base64 Data URI or HTTP/HTTPS URL and optional strength."
parameters_schema:
type: object
properties:
image:
type: string
description: "Style reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
strength:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Style influence strength (0.0 to 2.0)."
required:
- image
reference_edit:
chains: reference_latent
display_name: "Reference Edit"
description: "For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 10
usage_guideline: "Supply reference image(s) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images (up to 10) performs an Image Combine."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
mage_flow_reference_edit:
chains: reference_image
display_name: "Mage-Flow Reference Edit"
description: " (Mage-Flow-Edit-Turbo/Mage-Flow-Edit recommended) For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 10
usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
krea2_identity_edit:
chains: krea2_identity_edit
display_name: "KREA2 Identity Edit"
description: "Processed using the lbouaraba/comfyui-krea2edit node. (Krea-2-Turbo recommended, Krea-2-Raw need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 2
usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
krea2_style_reference:
chains: krea2_style_reference
display_name: "KREA2 Style Reference"
description: "(Krea-2-Turbo recommended) Add style reference images to perform style reference editing."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 3
usage_guideline: "Supply style reference image as Base64 Data URI or HTTP/HTTPS URL."
parameters_schema:
type: object
properties:
image:
type: string
description: "Style reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
diffsynth_controlnet:
chains: diffsynth_controlnet
display_name: "DiffSynth ControlNet"
description: "DiffSynth optimized ControlNet injector for Z-Image models."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply ControlNet type (e.g., 'Canny'), series (e.g., 'alibaba-pai Controlnet Union 2.1 8steps'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength."
parameters_schema:
type: object
properties:
type:
type: string
description: "ControlNet conditioning type."
series:
type: string
description: "ControlNet model series name."
image:
type: string
description: "Pre-processed control image (e.g., Depth map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images."
strength:
type: number
default: 1.0
description: "Control influence strength."
required:
- type
- series
- image
boogu_image_edit:
chains: boogu_image_edit
display_name: "Boogu-Image Edit"
description: " (Boogu-Image-Edit-Turbo/Boogu-Image-Edit recommended, Boogu-Image-Edit need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 2
usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
joyai_reference_edit:
chains: joyai_image
display_name: "JoyAI Reference Edit"
description: " (JoyAI-Image-Edit recommended) For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit (JoyAI-Image-Edit recommended), while adding multiple images performs an Image Combine (JoyAI-Image-Edit-Plus recommended with ZeroGPU Duration (s) set to 120)."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 2
usage_guideline: "Supply JoyAI reference image as Base64 Data URI or HTTP/HTTPS URL."
parameters_schema:
type: object
properties:
image:
type: string
description: "Input reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
qwen_image_edit:
chains: qwen_image_edit
display_name: "Qwen-Image Edit"
description: " (lightx2v/Qwen-Image-Edit-2511-Lightning recommended) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 3
usage_guideline: "Supply reference image(s) (up to 3) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images performs an Image Combine."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
hidream_o1_smoothing:
chains: hidream_o1_smoothing
display_name: "HiDream O1 Smoothing Injector"
description: "HiDream O1 detail smoothing and artifact reduction injector."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 1
usage_guideline: "Configures smoothing factor for HiDream models."
parameters_schema:
type: object
properties:
factor:
type: number
default: 0.5
description: "Smoothing intensity (0.0 to 1.0)."
required: []
krea2_controlnet:
chains: krea2_controlnet
display_name: "KREA2 ControlNet"
description: "Processed using the facok/comfyui-krea2-controlnet node."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply ControlNet type (e.g., 'Depth'), series (e.g., 'Patil'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength."
parameters_schema:
type: object
properties:
type:
type: string
enum:
- "Depth"
description: "ControlNet conditioning type."
series:
type: string
enum:
- "Patil"
default: "Patil"
description: "ControlNet model series."
image:
type: string
description: "Pre-processed control image (e.g., Depth map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images."
strength:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Control influence strength (0.0 to 2.0)."
required:
- type
- series
- image
anima_controlnet_lllite:
chains: anima_controlnet_lllite
display_name: "Anima ControlNet LLLite"
description: "Anima model-specific lightweight ControlNet."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply Anima ControlNet LLLite type (e.g., 'Depth'), series (e.g., 'kohya-ss'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength."
parameters_schema:
type: object
properties:
type:
type: string
description: "Anima ControlNet LLLite conditioning type."
series:
type: string
description: "Anima ControlNet LLLite model series."
image:
type: string
description: "Pre-processed control image (e.g., Depth, Lineart map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images."
strength:
type: number
default: 1.0
minimum: 0.0
maximum: 2.0
description: "Control influence strength (0.0 to 2.0)."
required:
- type
- series
- image
hidream_o1_reference:
chains: hidream_o1_reference
display_name: "HiDream-O1 Reference Edit"
description: " (HiDream-O1-Image-Dev recommended with resolution set to 4.0MP, e.g., 2048x2048) For HiDream-O1 models, this feature enables reference image editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 9
usage_guideline: "Supply reference image(s) (up to 9) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images performs an Image Combine."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
required:
- image
flux1_ipadapter:
chains: flux1_ipadapter
display_name: "Flux1 IP-Adapter"
description: "FLUX.1 model-specific IP-Adapter implementation."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply reference image (Base64 Data URI or HTTP/HTTPS URL), optional weight (default 1.0), start_at (default 0.0), and end_at (default 1.0). Up to 5 images supported."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
weight:
type: number
default: 1.0
description: "Influence weight of the image prompt (0.0 to 2.0)."
start_at:
type: number
default: 0.0
description: "Start step percentage for IP-Adapter application (0.0 to 1.0)."
end_at:
type: number
default: 1.0
description: "End step percentage for IP-Adapter application (0.0 to 1.0)."
start_percent:
type: number
default: 0.0
description: "Alias for start_at."
end_percent:
type: number
default: 1.0
description: "Alias for end_at."
required:
- image
sd3_ipadapter:
chains: sd3_ipadapter
display_name: "SD3 IP-Adapter"
description: "SD3/SD3.5 model-specific IP-Adapter implementation."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Supply reference image (Base64 Data URI or HTTP/HTTPS URL), optional weight (default 1.0), start_at (default 0.0), and end_at (default 1.0). Up to 5 images supported."
parameters_schema:
type: object
properties:
image:
type: string
description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL."
weight:
type: number
default: 1.0
description: "Influence weight of the image prompt (0.0 to 2.0)."
start_at:
type: number
default: 0.0
description: "Start step percentage for IP-Adapter application (0.0 to 1.0)."
end_at:
type: number
default: 1.0
description: "End step percentage for IP-Adapter application (0.0 to 1.0)."
start_percent:
type: number
default: 0.0
description: "Alias for start_at."
end_percent:
type: number
default: 1.0
description: "Alias for end_at."
required:
- image
embedding:
chains: embedding
display_name: "Textual Inversion Embedding Injector"
description: "Downloads Textual Inversion embedding files from Civitai or Hugging Face to the server. Note: This feature ONLY handles file downloading/preparation. To activate the embedding, manually add 'embedding:<filename>' (e.g. 'embedding:civitai_456' for Civitai ID 456, or 'embedding:filename' for Hugging Face) into your prompt or negative_prompt."
supported_tasks:
- txt2img
- img2img
- inpaint
- outpaint
- hires_fix
max_count: 5
usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), and embedding_value (Civitai Version ID or HF repo file path). The file is downloaded to server; manually enter 'embedding:<filename>' in prompt or negative_prompt to activate."
parameters_schema:
type: object
properties:
source:
type: string
enum:
- "Civitai"
- "Hugging Face"
description: "Download source for the Textual Inversion embedding file. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo file path."
embedding_value:
type: string
description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456, saved as 'civitai_456.safetensors'). For Hugging Face: repo_id/filename.extension (e.g., 'ilikebigturtles/lazypos/lazypos.safetensors', saved as 'lazypos.safetensors'). Manually reference embedding:<filename> in prompt or negative_prompt."
required:
- source
- embedding_valueREADME.md+6-4
mcp_tools/__init__.py+47-47
mcp_tools/error_schema.py+85-85
mcp_tools/get_feature_list.py+127-127
mcp_tools/get_model_architecture_list.py+36-36
mcp_tools/get_model_features.py+102-102
mcp_tools/get_model_list.py+64-64
mcp_tools/get_task_list.py+11-11
mcp_tools/get_task_status.py+21-21
mcp_tools/mcp_gradio_integration.py+130-130
mcp_tools/run.py+76-76
mcp_tools/tool_handlers.py+28-28
ui/layout.py+1-1
yaml/chain_features.yaml+652-652