Optimize API/MCP Tools.
Browse filesFiles changed (11)
- core/pipelines/pipeline_input_processor.py+32-27
- mcp_tools/__init__.py+3-6
- mcp_tools/common.py+422-30
- mcp_tools/get_chain_schema.pyDeleted-32
- mcp_tools/get_feature_list.py+123-25
- mcp_tools/get_model_features.py+9-18
- mcp_tools/mcp_gradio_integration.py+14-21
- mcp_tools/run_imagegen.py → mcp_tools/run.pyRenamed+2-2
- mcp_tools/tool_handlers.py+3-5
- requirements.txt+3-3
- yaml/chain_features.yamlAdded+652
30 unmodified lines313233343536373849 unmodified lines88899091929394959697989910010110210310410510610710810911011111211311435 unmodified lines15015115215315415515615715815916016116230 unmodified linesif input_image_pil:img_w, img_h = input_image_pil.width, input_image_pil.heightelif task_type == 'inpaint':inpaint_dict = ui_inputs.get('inpaint_image_dict')if inpaint_dict and inpaint_dict.get('background'):img_w, img_h = inpaint_dict['background'].width, inpaint_dict['background'].heightelif task_type == 'outpaint':input_image_pil = ui_inputs.get('outpaint_image')49 unmodified linesui_inputs['height'] = input_image_pil.heightelif task_type == 'inpaint':inpaint_dict = ui_inputs.get('inpaint_image_dict')if not inpaint_dict or not inpaint_dict.get('background') or not inpaint_dict.get('layers'):raise gr.Error("Inpainting requires an input image and a drawn mask.")background_img = inpaint_dict['background'].convert("RGBA")composite_mask_pil = Image.new('L', background_img.size, 0)for layer in inpaint_dict['layers']:if layer:layer_alpha = layer.split()[-1]composite_mask_pil = ImageChops.lighter(composite_mask_pil, layer_alpha)inverted_mask_alpha = Image.fromarray(255 - np.array(composite_mask_pil), mode='L')r, g, b, _ = background_img.split()composite_image_with_mask = Image.merge('RGBA', [r, g, b, inverted_mask_alpha])temp_file_path = os.path.join(INPUT_DIR, f"temp_inpaint_composite_{random.randint(1000, 9999)}.png")composite_image_with_mask.save(temp_file_path, "PNG")ui_inputs['input_image'] = os.path.basename(temp_file_path)temp_files_to_clean.append(temp_file_path)ui_inputs.pop('inpaint_mask', None)elif task_type == 'outpaint':input_image_pil = ui_inputs.get('outpaint_image')35 unmodified linesif emb_filename:embedding_filenames.append(emb_filename)if embedding_filenames:embedding_prompt_text = " ".join([f"embedding:{f}" for f in embedding_filenames])if ui_inputs['positive_prompt']:ui_inputs['positive_prompt'] = f"{ui_inputs['positive_prompt']}, {embedding_prompt_text}"else:ui_inputs['positive_prompt'] = embedding_prompt_textcontrolnet_data = ui_inputs.get('controlnet_data', [])active_controlnets = []30 unmodified lines313233343536373839404149 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512635 unmodified lines16216316416516616730 unmodified linesif input_image_pil:img_w, img_h = input_image_pil.width, input_image_pil.heightelif task_type == 'inpaint':inpaint_img = ui_inputs.get('inpaint_image')inpaint_dict = ui_inputs.get('inpaint_image_dict')if inpaint_img:img_w, img_h = inpaint_img.width, inpaint_img.heightelif inpaint_dict and inpaint_dict.get('background'):img_w, img_h = inpaint_dict['background'].width, inpaint_dict['background'].heightelif task_type == 'outpaint':input_image_pil = ui_inputs.get('outpaint_image')49 unmodified linesui_inputs['height'] = input_image_pil.heightelif task_type == 'inpaint':inpaint_img = ui_inputs.get('inpaint_image')inpaint_dict = ui_inputs.get('inpaint_image_dict')if inpaint_img:temp_file_path = os.path.join(INPUT_DIR, f"temp_inpaint_{random.randint(1000, 9999)}.png")inpaint_img.save(temp_file_path, "PNG")ui_inputs['input_image'] = os.path.basename(temp_file_path)temp_files_to_clean.append(temp_file_path)ui_inputs['width'] = inpaint_img.widthui_inputs['height'] = inpaint_img.heightelif inpaint_dict and inpaint_dict.get('background') and inpaint_dict.get('layers'):background_img = inpaint_dict['background'].convert("RGBA")composite_mask_pil = Image.new('L', background_img.size, 0)for layer in inpaint_dict['layers']:if layer:layer_alpha = layer.split()[-1]composite_mask_pil = ImageChops.lighter(composite_mask_pil, layer_alpha)inverted_mask_alpha = Image.fromarray(255 - np.array(composite_mask_pil), mode='L')r, g, b, _ = background_img.split()composite_image_with_mask = Image.merge('RGBA', [r, g, b, inverted_mask_alpha])temp_file_path = os.path.join(INPUT_DIR, f"temp_inpaint_composite_{random.randint(1000, 9999)}.png")composite_image_with_mask.save(temp_file_path, "PNG")ui_inputs['input_image'] = os.path.basename(temp_file_path)temp_files_to_clean.append(temp_file_path)ui_inputs.pop('inpaint_mask', None)else:raise gr.Error("Inpainting requires an input image with a mask.")elif task_type == 'outpaint':input_image_pil = ui_inputs.get('outpaint_image')35 unmodified linesif emb_filename:embedding_filenames.append(emb_filename)controlnet_data = ui_inputs.get('controlnet_data', [])active_controlnets = []
7 unmodified lines891011121314159 unmodified lines2526272829303132332 unmodified lines36373839404142437 unmodified linesfrom .get_model_list import handle_get_model_listfrom .get_feature_list import handle_get_feature_listfrom .get_model_features import handle_get_model_featuresfrom .get_chain_schema import handle_get_chain_schemafrom .run_imagegen import handle_run_imagegenfrom .get_task_status import handle_get_task_statusfrom .error_schema import make_error, make_validation_error, make_not_found_errorfrom .mcp_gradio_integration import (9 unmodified lineshandle_get_model_list,handle_get_feature_list,handle_get_model_features,handle_run_imagegen,handle_get_task_status,handle_get_chain_schema,]__all__ = [2 unmodified lines"handle_get_model_list","handle_get_feature_list","handle_get_model_features","handle_get_chain_schema","handle_run_imagegen","handle_get_task_status","make_error","make_validation_error",7 unmodified lines8910111213149 unmodified lines24252627282930312 unmodified lines343536373839407 unmodified linesfrom .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 (9 unmodified lineshandle_get_model_list,handle_get_feature_list,handle_get_model_features,handle_run,handle_get_task_status,]__all__ = [2 unmodified lines"handle_get_model_list","handle_get_feature_list","handle_get_model_features","handle_run","handle_get_task_status","make_error","make_validation_error",
6 unmodified lines78910111211 unmodified lines24252627282930312 unmodified lines34353637383940414243442 unmodified lines4748495051525354555657585960616263646566676842 unmodified lines111112113114115116117108 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722736 unmodified linesimport timeimport urllib.parseimport urllib.requestimport base64import ioimport yaml11 unmodified lines_CONSTANTS_PATH = os.path.join(_YAML_DIR, "constants.yaml")def _parse_image_param(image_param: Any) -> Any:"""Parse a Base64 Data URI, local file path, or PIL.Image into a PIL Image object. HTTP URLs are not supported."""if isinstance(image_param, Image.Image):return image_param2 unmodified linesimage_param = image_param.strip()# Reject HTTP / HTTPS URLif image_param.startswith("http://") or image_param.startswith("https://"):raise ValueError("Image URLs are not supported. Please supply the image directly as a Base64 Data URI (e.g., 'data:image/png;base64,...').")# Base64 Data URI (e.g. data:image/png;base64,...)if image_param.startswith("data:image/"):2 unmodified linesreturn Image.open(io.BytesIO(data))# Base64 string without headerif len(image_param) > 100 and not os.path.exists(image_param):try:data = base64.b64decode(image_param)return Image.open(io.BytesIO(data))except Exception:pass# Local file pathif os.path.exists(image_param):return Image.open(image_param)raise ValueError("Invalid image parameter format. Expected a Base64 Data URI (e.g., 'data:image/png;base64,...') or local file path.")def _load_yaml(filepath: str) -> dict:"""Safely load a YAML file, returning an empty dict if the file does not exist."""if not os.path.exists(filepath):42 unmodified lines"display_name": "Hi-Res Fix / Upscale","description": "Enhance details and upscale an existing low-resolution image.","required_inputs": ["prompt", "image", "upscale_by"],"optional_inputs": _COMMON_OPTIONAL_INPUTS,},]108 unmodified linesui_inputs["feathering"] = params.get("feathering", 10)elif task_type == "hires_fix":ui_inputs["hires_image"] = pil_imgui_inputs["hires_upscaler"] = params.get("upscaler", "latent")ui_inputs["hires_scale_by"] = params.get("upscale_by", 2.0)ui_inputs["hires_denoise"] = params.get("denoise", 0.55)chain = params.get("chain", [])if chain:lora_data = []controlnet_data = []ipadapter_data = []style_data = []for item in chain:itype = item.get("injector_type")if itype == "lora":lora_data.extend([item.get("lora_source", "Civitai"),item.get("lora_value", ""),item.get("scale", 1.0),None])elif itype in ("controlnet", "krea2_controlnet", "anima_controlnet_lllite"):controlnet_data.extend([item.get("control_net_name", ""),_parse_image_param(item.get("image")),item.get("strength", 1.0)])elif itype in ("ipadapter", "flux1_ipadapter", "sd3_ipadapter"):ipadapter_data.extend([item.get("preset", "STANDARD (medium strength)"),_parse_image_param(item.get("image")),item.get("weight", 1.0)])elif itype == "style":style_data.extend([_parse_image_param(item.get("image")),item.get("strength", 1.0)])if lora_data: ui_inputs["lora_data"] = lora_dataif controlnet_data: ui_inputs["controlnet_data"] = controlnet_dataif ipadapter_data: ui_inputs["ipadapter_data"] = ipadapter_dataif style_data: ui_inputs["style_data"] = style_data_TASKS_DB[task_id]["progress"] = 506 unmodified lines7891011121311 unmodified lines252627282930313233343536373839404142434445464748495051522 unmodified lines5556575859606162632 unmodified lines6667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813942 unmodified lines182183184185186187188108 unmodified lines2972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656 unmodified linesimport timeimport urllib.parseimport urllib.requestimport urllib.errorimport base64import ioimport yaml11 unmodified lines_CONSTANTS_PATH = os.path.join(_YAML_DIR, "constants.yaml")_MAX_IMAGE_DOWNLOAD_BYTES = 50 * 1024 * 1024 # 50 MB_IMAGE_DOWNLOAD_TIMEOUT = 30 # seconds_ALLOWED_IMAGE_CONTENT_TYPES = frozenset(["image/png", "image/jpeg", "image/jpg", "image/gif","image/webp", "image/bmp", "image/tiff",])def _get_ipadapter_presets_by_arch() -> Dict[str, list]:"""Load IPAdapter presets from yaml/ipadapter.yaml for SD1.5 and SDXL."""ipadapter_yaml_path = os.path.join(_YAML_DIR, "ipadapter.yaml")data = _load_yaml(ipadapter_yaml_path)res = {}for arch in ("SD1.5", "SDXL"):std = data.get("IPAdapter_presets", {}).get(arch, [])face = data.get("IPAdapter_FaceID_presets", {}).get(arch, [])res[arch] = list(std) + list(face)return resdef _parse_image_param(image_param: Any) -> Any:"""Parse a Base64 Data URI, HTTP/HTTPS URL, or PIL.Image into a PIL Image object."""if isinstance(image_param, Image.Image):return image_param2 unmodified linesimage_param = image_param.strip()# HTTP / HTTPS URL — download the imageif image_param.startswith("http://") or image_param.startswith("https://"):return _download_image_from_url(image_param)# Base64 Data URI (e.g. data:image/png;base64,...)if image_param.startswith("data:image/"):2 unmodified linesreturn Image.open(io.BytesIO(data))# Base64 string without headerif len(image_param) > 100:try:data = base64.b64decode(image_param)return Image.open(io.BytesIO(data))except Exception:passraise ValueError("Invalid image parameter format. Expected a Base64 Data URI (e.g., 'data:image/png;base64,...') ""or an HTTP/HTTPS URL.")def _download_image_from_url(url: str) -> Image.Image:"""Download an image from an HTTP/HTTPS URL and return it as a PIL Image.Security measures:- Timeout to prevent hanging on slow/malicious servers.- Response size cap to prevent memory exhaustion.- Content-Type validation to reject non-image responses."""req = urllib.request.Request(url, headers={"User-Agent": "ImageGen-MCP/1.0"})try:with urllib.request.urlopen(req, timeout=_IMAGE_DOWNLOAD_TIMEOUT) as resp:# Validate content typecontent_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()if content_type and content_type not in _ALLOWED_IMAGE_CONTENT_TYPES:raise ValueError(f"URL returned non-image Content-Type '{content_type}'. "f"Expected one of: {', '.join(sorted(_ALLOWED_IMAGE_CONTENT_TYPES))}.")# Enforce size limitcontent_length = resp.headers.get("Content-Length")if content_length and int(content_length) > _MAX_IMAGE_DOWNLOAD_BYTES:raise ValueError(f"Image at URL is too large ({int(content_length)} bytes). "f"Maximum allowed size is {_MAX_IMAGE_DOWNLOAD_BYTES} bytes.")# Stream-read with size capchunks = []total = 0while True:chunk = resp.read(8192)if not chunk:breaktotal += len(chunk)if total > _MAX_IMAGE_DOWNLOAD_BYTES:raise ValueError(f"Image download exceeded maximum allowed size of "f"{_MAX_IMAGE_DOWNLOAD_BYTES} bytes.")chunks.append(chunk)data = b"".join(chunks)except urllib.error.URLError as e:raise ValueError(f"Failed to download image from URL: {e}") from eexcept urllib.error.HTTPError as e:raise ValueError(f"HTTP error {e.code} when downloading image from URL: {e.reason}") from eif not data:raise ValueError("Downloaded image data is empty.")return Image.open(io.BytesIO(data))def _load_yaml(filepath: str) -> dict:"""Safely load a YAML file, returning an empty dict if the file does not exist."""if not os.path.exists(filepath):42 unmodified lines"display_name": "Hi-Res Fix / Upscale","description": "Enhance details and upscale an existing low-resolution image.","required_inputs": ["prompt", "image", "upscale_by"],"optional_inputs": ["upscaler", "denoise"] + _COMMON_OPTIONAL_INPUTS,},]108 unmodified linesui_inputs["feathering"] = params.get("feathering", 10)elif task_type == "hires_fix":ui_inputs["hires_image"] = pil_imgupscaler = params.get("upscaler", "nearest-exact")if upscaler == "latent" or upscaler not in ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]:upscaler = "nearest-exact"ui_inputs["hires_upscaler"] = upscalerui_inputs["hires_scale_by"] = params.get("upscale_by", 2.0)ui_inputs["hires_denoise"] = params.get("denoise", 0.55)chain = params.get("chain", [])if chain:lora_data = []embedding_data = []controlnet_data = []diffsynth_controlnet_data = []ipadapter_data = []ipadapter_images = []ipadapter_weights = []ipadapter_lora_strengths = []ipadapter_global_preset = params.get("ipadapter_preset") or params.get("preset")ipadapter_global_embeds_scaling = params.get("ipadapter_embeds_scaling") or params.get("embeds_scaling")ipadapter_global_combine_method = params.get("ipadapter_combine_method") or params.get("combine_method")ipadapter_global_final_weight = params.get("ipadapter_final_weight") or params.get("final_weight")flux1_ipadapter_images = []flux1_ipadapter_weights = []flux1_ipadapter_starts = []flux1_ipadapter_ends = []sd3_ipadapter_images = []sd3_ipadapter_weights = []sd3_ipadapter_starts = []sd3_ipadapter_ends = []style_images = []style_strengths = []krea2_identity_edit_data = []krea2_reference_edit_data = []krea2_controlnet_data = []anima_controlnet_lllite_data = []reference_latent_data = []reference_image_data = []joyai_reference_data = []boogu_edit_data = []qwen_image_edit_data = []hidream_o1_reference_data = []cond_prompts = []cond_widths = []cond_heights = []cond_xs = []cond_ys = []cond_strengths = []for item in chain:itype = item.get("injector_type")if itype == "lora":lora_data.extend([item.get("source", item.get("lora_source", "Civitai")),item.get("lora_value", ""),item.get("scale", 1.0),None])elif itype == "embedding":e_source = item.get("source", item.get("embedding_source", "Civitai"))e_val = item.get("embedding_value", item.get("value", item.get("embedding_id", "")))if e_source and e_val:embedding_data.extend([e_source,str(e_val),None])elif itype == "conditioning":p = item.get("prompt", "")if p:cond_prompts.append(p)cond_widths.append(int(item.get("width", 512)))cond_heights.append(int(item.get("height", 512)))cond_xs.append(int(item.get("x", 0)))cond_ys.append(int(item.get("y", 0)))cond_strengths.append(float(item.get("strength", 1.0)))elif itype == "controlnet":cn_type = item.get("type", item.get("Type", ""))cn_series = item.get("series", item.get("Series", ""))cn_strength = float(item.get("strength", 1.0))cn_img = _parse_image_param(item.get("image"))cn_filepath = item.get("control_net_name", "None")cn_raw = _load_yaml(os.path.join(_YAML_DIR, "controlnet_models.yaml")).get("ControlNet", {})cn_arch_key = Noneif found_arch:arch_cfg = _load_yaml(os.path.join(_YAML_DIR, "model_architectures.yaml")).get("architectures", {})cn_arch_key = arch_cfg.get(found_arch, {}).get("controlnet_key", found_arch)arch_entries = []if cn_arch_key and cn_arch_key in cn_raw:arch_entries = cn_raw[cn_arch_key]elif found_arch and found_arch in cn_raw:arch_entries = cn_raw[found_arch]else:for val in cn_raw.values():if isinstance(val, list):arch_entries.extend(val)elif isinstance(val, dict):arch_entries.append(val)if arch_entries:for entry in arch_entries:entry_types = entry.get("Type", [])if isinstance(entry_types, str):entry_types = [entry_types]if not cn_type or cn_type in entry_types:if not cn_series or entry.get("Series") == cn_series:cn_filepath = entry.get("Filepath", cn_filepath)if not cn_series:cn_series = entry.get("Series", "")if not cn_type and entry_types:cn_type = entry_types[0]breakcontrolnet_data.extend([cn_img,cn_type,cn_series,cn_strength,cn_filepath])elif itype == "anima_controlnet_lllite":cn_type = item.get("type", item.get("Type", ""))cn_series = item.get("series", item.get("Series", ""))cn_strength = float(item.get("strength", 1.0))cn_start = float(item.get("start_percent", 0.0))cn_end = float(item.get("end_percent", 1.0))cn_img = _parse_image_param(item.get("image"))cn_filepath = item.get("control_net_name", "None")anima_cfg = _load_yaml(os.path.join(_YAML_DIR, "anima_controlnet_lllite_models.yaml")).get("Anima_ControlNet_Lllite", [])if anima_cfg:for entry in anima_cfg:entry_types = entry.get("Type", [])if isinstance(entry_types, str):entry_types = [entry_types]if not cn_type or cn_type in entry_types:if not cn_series or entry.get("Series") == cn_series:cn_filepath = entry.get("Filepath", cn_filepath)if not cn_series:cn_series = entry.get("Series", "")if not cn_type and entry_types:cn_type = entry_types[0]breakanima_controlnet_lllite_data.extend([cn_img,cn_type,cn_series,cn_strength,cn_filepath,cn_start,cn_end])elif itype == "diffsynth_controlnet":cn_type = item.get("type", "")cn_series = item.get("series", "")cn_strength = float(item.get("strength", 1.0))cn_img = _parse_image_param(item.get("image"))cn_filepath = "None"diffsynth_raw = _load_yaml(os.path.join(_YAML_DIR, "diffsynth_controlnet_models.yaml")).get("DiffSynth_ControlNet", {})diffsynth_entries = []if isinstance(diffsynth_raw, dict):for val in diffsynth_raw.values():if isinstance(val, list):diffsynth_entries.extend(val)elif isinstance(val, dict):diffsynth_entries.append(val)elif isinstance(diffsynth_raw, list):diffsynth_entries = diffsynth_rawif diffsynth_entries:for entry in diffsynth_entries:if not cn_type or cn_type in entry.get("Type", []):if not cn_series or entry.get("Series") == cn_series:cn_filepath = entry.get("Filepath", cn_filepath)if not cn_series:cn_series = entry.get("Series", cn_series)if not cn_type and entry.get("Type"):cn_type = entry.get("Type")[0]breakdiffsynth_controlnet_data.extend([cn_img,cn_type,cn_series,cn_strength,cn_filepath])elif itype == "krea2_controlnet":cn_type = item.get("type", "Depth")cn_series = item.get("series", "Patil")cn_strength = float(item.get("strength", 1.0))cn_img = _parse_image_param(item.get("image"))cn_filepath = "depth-control-lora.safetensors"krea2_cfg = _load_yaml(os.path.join(_YAML_DIR, "krea2_controlnet_models.yaml")).get("Krea2_ControlNet", [])if krea2_cfg:for entry in krea2_cfg:if cn_type in entry.get("Type", []):if not cn_series or entry.get("Series") == cn_series:cn_filepath = entry.get("Filepath", cn_filepath)cn_series = entry.get("Series", cn_series)breakkrea2_controlnet_data.extend([cn_img,cn_type,cn_series,cn_strength,cn_filepath])elif itype == "flux1_ipadapter":if len(flux1_ipadapter_images) < 5:img = _parse_image_param(item.get("image"))weight = float(item.get("weight", 1.0))start_at = float(item.get("start_at", item.get("start_percent", item.get("start", 0.0))))end_at = float(item.get("end_at", item.get("end_percent", item.get("end", 1.0))))flux1_ipadapter_images.append(img)flux1_ipadapter_weights.append(weight)flux1_ipadapter_starts.append(start_at)flux1_ipadapter_ends.append(end_at)elif itype == "sd3_ipadapter":if len(sd3_ipadapter_images) < 5:img = _parse_image_param(item.get("image"))weight = float(item.get("weight", 1.0))start_at = float(item.get("start_at", item.get("start_percent", item.get("start", 0.0))))end_at = float(item.get("end_at", item.get("end_percent", item.get("end", 1.0))))sd3_ipadapter_images.append(img)sd3_ipadapter_weights.append(weight)sd3_ipadapter_starts.append(start_at)sd3_ipadapter_ends.append(end_at)elif itype == "ipadapter":if len(ipadapter_images) < 5:img = _parse_image_param(item.get("image"))weight = float(item.get("weight", 1.0))lora_str = float(item.get("lora_strength", 0.6))ipadapter_images.append(img)ipadapter_weights.append(weight)ipadapter_lora_strengths.append(lora_str)if "preset" in item and not ipadapter_global_preset:ipadapter_global_preset = item["preset"]if "embeds_scaling" in item and not ipadapter_global_embeds_scaling:ipadapter_global_embeds_scaling = item["embeds_scaling"]if "combine_method" in item and not ipadapter_global_combine_method:ipadapter_global_combine_method = item["combine_method"]if "final_weight" in item and ipadapter_global_final_weight is None:ipadapter_global_final_weight = float(item["final_weight"])elif itype in ("style", "flux1_style"):img = _parse_image_param(item.get("image"))if img:style_images.append(img)style_strengths.append(float(item.get("strength", item.get("weight", 1.0))))elif itype == "pid":is_enabled = item.get("enabled", True)if isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["pid_settings"] = "ON" if is_enabled else "OFF"elif itype == "krea2_identity_edit":img = _parse_image_param(item.get("image"))if img:krea2_identity_edit_data.append(img)elif itype == "krea2_style_reference":img = _parse_image_param(item.get("image"))if img:krea2_reference_edit_data.append(img)elif itype in ("reference_latent", "reference_edit"):img = _parse_image_param(item.get("image"))if img:reference_latent_data.append(img)elif itype in ("reference_image", "mage_flow_reference_edit"):img = _parse_image_param(item.get("image"))if img:reference_image_data.append(img)elif itype in ("joyai_image", "joyai_reference_edit"):img = _parse_image_param(item.get("image"))if img:joyai_reference_data.append(img)elif itype in ("boogu_image_edit", "boogu_edit"):img = _parse_image_param(item.get("image"))if img:boogu_edit_data.append(img)elif itype == "qwen_image_edit":img = _parse_image_param(item.get("image"))if img:qwen_image_edit_data.append(img)elif itype == "hidream_o1_reference":img = _parse_image_param(item.get("image"))if img:hidream_o1_reference_data.append(img)elif itype == "vae":v_source = item.get("source", item.get("vae_source", "Civitai"))v_val = item.get("vae_value", item.get("value", item.get("vae_id", item.get("vae_name", ""))))if v_source and v_val:ui_inputs["vae_source"] = v_sourceui_inputs["vae_id"] = str(v_val)if lora_data: ui_inputs["lora_data"] = lora_dataif embedding_data: ui_inputs["embedding_data"] = embedding_dataif controlnet_data: ui_inputs["controlnet_data"] = controlnet_dataif anima_controlnet_lllite_data: ui_inputs["anima_controlnet_lllite_data"] = anima_controlnet_lllite_dataif diffsynth_controlnet_data: ui_inputs["diffsynth_controlnet_data"] = diffsynth_controlnet_dataif krea2_controlnet_data: ui_inputs["krea2_controlnet_data"] = krea2_controlnet_dataif ipadapter_images:preset = ipadapter_global_preset or "STANDARD (medium strength)"embeds_scaling = ipadapter_global_embeds_scaling or "V only"combine_method = ipadapter_global_combine_method or "concat"final_weight = float(ipadapter_global_final_weight) if ipadapter_global_final_weight is not None else 1.0final_lora_strength = 0.6presets_by_arch = _get_ipadapter_presets_by_arch()target_arch = "SD1.5" if found_arch in ("sd15", "SD1.5") else "SDXL"allowed_presets = presets_by_arch.get(target_arch, [])if preset not in allowed_presets:raise ValueError(f"Invalid IPAdapter preset '{preset}' for model architecture '{target_arch}'. "f"Preset must match the target model architecture. Allowed presets for {target_arch}: {allowed_presets}")ui_inputs["ipadapter_data"] = (ipadapter_images + ipadapter_weights + ipadapter_lora_strengths +[preset, final_weight, final_lora_strength, embeds_scaling, combine_method])elif ipadapter_data:ui_inputs["ipadapter_data"] = ipadapter_dataif flux1_ipadapter_images:ui_inputs["flux1_ipadapter_data"] = (flux1_ipadapter_images + flux1_ipadapter_weights + flux1_ipadapter_starts + flux1_ipadapter_ends)if sd3_ipadapter_images:ui_inputs["sd3_ipadapter_chain"] = (sd3_ipadapter_images + sd3_ipadapter_weights + sd3_ipadapter_starts + sd3_ipadapter_ends)if style_images: ui_inputs["style_data"] = style_images + style_strengthsif krea2_identity_edit_data: ui_inputs["krea2_identity_edit_data"] = krea2_identity_edit_dataif krea2_reference_edit_data: ui_inputs["krea2_reference_edit_data"] = krea2_reference_edit_dataif reference_latent_data: ui_inputs["reference_latent_data"] = reference_latent_dataif reference_image_data: ui_inputs["reference_image_data"] = reference_image_dataif joyai_reference_data: ui_inputs["joyai_reference_data"] = joyai_reference_dataif boogu_edit_data: ui_inputs["boogu_edit_data"] = boogu_edit_dataif qwen_image_edit_data: ui_inputs["qwen_image_edit_data"] = qwen_image_edit_dataif hidream_o1_reference_data: ui_inputs["hidream_o1_reference_data"] = hidream_o1_reference_dataif cond_prompts:ui_inputs["conditioning_data"] = (cond_prompts + cond_widths + cond_heights + cond_xs + cond_ys + cond_strengths)if "vae_source" in params and "vae_id" in params:ui_inputs["vae_source"] = params["vae_source"]ui_inputs["vae_id"] = str(params["vae_id"])pid_val = params.get("pid") if params.get("pid") is not None else params.get("pid_settings")if pid_val is not None:if isinstance(pid_val, bool):ui_inputs["pid_settings"] = "ON" if pid_val else "OFF"elif str(pid_val).upper() in ("ON", "TRUE", "1"):ui_inputs["pid_settings"] = "ON"else:ui_inputs["pid_settings"] = "OFF"_TASKS_DB[task_id]["progress"] = 50
1234567891011121314151617181920212223242526272829303132"""MCP Tool: get_chain_schemaGet the complete parameter schema and usage guide for a specified chain/injector type."""
from .common import _load_yaml, _CHAIN_FEATURES_PATHfrom .error_schema import make_validation_error, make_not_found_error
def handle_get_chain_schema(chain_type: str) -> dict: """Get the complete parameter schema and usage guide for a specified chain/injector type.""" if not chain_type: return make_validation_error( "Parameter 'chain_type' is required.", missing_fields=["chain_type"], )
chain_features = _load_yaml(_CHAIN_FEATURES_PATH)
if chain_type not in chain_features: return make_not_found_error("chain_type", chain_type)
chain_data = chain_features[chain_type] return { "feature_name": chain_type, "display_name": chain_data.get("display_name", chain_type), "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", ""), "parameters_schema": chain_data.get("parameters_schema", {}), }1234567891011121314151617181920212223242526272829"""MCP Tool: get_feature_listGet the list of supported advanced features along with their usage constraints and parameter schemas."""from .common import _load_yaml, _CHAIN_FEATURES_PATHdef handle_get_feature_list() -> list:"""Dynamically load the list of supported advanced features from chain_features.yaml."""chain_features = _load_yaml(_CHAIN_FEATURES_PATH)result = []for chain_name, chain_data in chain_features.items():if chain_data.get("visibility", "public") != "public":continueentry = {"feature_name": 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", ""),"parameters_schema": chain_data.get("parameters_schema", {}),}result.append(entry)return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127import osfrom copy import deepcopyfrom .common import _load_yaml, _CHAIN_FEATURES_PATH, _YAML_DIRfrom .error_schema import make_not_found_errordef _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_modelstypes_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"] = typesif "series" in schema["properties"] and series:schema["properties"]["series"]["enum"] = seriesif chain_name == "controlnet" and isinstance(raw_models, dict):schema["architectures"] = raw_modelselif chain_name == "ipadapter":from .common import _get_ipadapter_presets_by_archpresets_by_arch = _get_ipadapter_presets_by_arch()schema["presets_by_architecture"] = presets_by_archall_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_presetsentry["parameters_schema"] = schemareturn entrydef 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 = Falseif 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 = partsif 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 aliasdef _resolve_target(target_name: str) -> str | None:if target_name in chain_features:return target_namefor 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_keyelif isinstance(feat_chains, list) and target_name in feat_chains:return feat_keyreturn Noneresolved_targets = []# Case 2: Specific feature(s) requested -> validate existencefor 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_schemaresults = [_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
51 unmodified lines52535455565758596061626364656667686970717273747551 unmodified linesenabled_chains = arch_features.get("enabled_chains", [])supported_features = []for chain_name in enabled_chains:if chain_name in chain_features:chain_data = chain_features[chain_name]visibility = chain_data.get("visibility", "public")if visibility == "public":supported_features.append(chain_name)else:generic_mapping = {"krea2_controlnet": "controlnet","anima_controlnet_lllite": "controlnet","controlnet_model_patch": "controlnet","flux1_ipadapter": "ipadapter","sd3_ipadapter": "ipadapter","hidream_o1_reference": "reference_latent",}generic_name = generic_mapping.get(chain_name)if generic_name and generic_name not in supported_features:supported_features.append(generic_name)arch_defaults_section = model_defaults.get(found_arch, {})arch_level_defaults = arch_defaults_section.get("_defaults", {})51 unmodified lines52535455565758596061626364656651 unmodified linesenabled_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", {})
1 unmodified line23456786 unmodified lines15161718192021222 unmodified lines25262728293031323316 unmodified lines5051525354555616 unmodified lines73747576777879808182831 unmodified line8586878889909192939495969798991001011021032 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291303 unmodified lines1341351361371 unmodified lineMCP & Gradio Integration ModuleProvides:1. register_high_level_mcp_apis: Expose only 8 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"""6 unmodified linesfrom .get_model_list import handle_get_model_listfrom .get_feature_list import handle_get_feature_listfrom .get_model_features import handle_get_model_featuresfrom .get_chain_schema import handle_get_chain_schemafrom .run_imagegen import handle_run_imagegenfrom .get_task_status import handle_get_task_statusHIGH_LEVEL_MCP_API_NAMES = {2 unmodified lines"get_model_list","get_feature_list","get_model_features","run_imagegen","get_task_status","get_chain_schema",}16 unmodified linesdef cleanup_dependencies_api_names(demo):"""Clean up residual auto-generated API names in demo.fns and demo.dependencies.Force only the 8 high-level abstract MCP APIs to be exposed as public endpoints."""for fn in demo.fns.values():api_name = getattr(fn, "api_name", None)16 unmodified linesdef register_high_level_mcp_apis(demo):"""Explicitly register 8 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_imagegen directly (pass only required params) | Path 2: Call get_model_features to get official default hyperparams -> run_imagegen]."""return sanitize_keys(handle_get_task_list())def get_model_architecture_list() -> list:1 unmodified linereturn 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_imagegen 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_imagegen."""arch = model_architecture.strip() if model_architecture else Nonereturn sanitize_keys(handle_get_model_list(arch))def get_feature_list() -> list:"""Get the list of supported advanced features along with their usage constraints and parameter schemas."""return sanitize_keys(handle_get_feature_list())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_imagegen(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):2 unmodified linesparams = 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_imagegen(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()))def get_chain_schema(chain_type: str = "") -> dict:"""Get the complete parameter schema and usage examples for a specified chain/injector type."""return sanitize_keys(handle_get_chain_schema(chain_type.strip()))funcs = [get_task_list,get_model_architecture_list,get_model_list,get_feature_list,get_model_features,run_imagegen,get_task_status,get_chain_schema,]for func in funcs:3 unmodified linesif getattr(fn, "api_name", None) in HIGH_LEVEL_MCP_API_NAMES:fn.show_api = Trueprint("[MCP Integration] Successfully registered 8 High-Level Abstract MCP APIs via gr.api().")1 unmodified line23456786 unmodified lines151617181920212 unmodified lines242526272829303116 unmodified lines4849505152535416 unmodified lines71727374757677787980811 unmodified line83848586878889909192939495969798991001012 unmodified lines1041051061071081091101111121131141151161171181191201211221233 unmodified lines1271281291301 unmodified lineMCP & Gradio Integration ModuleProvides: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"""6 unmodified linesfrom .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_statusHIGH_LEVEL_MCP_API_NAMES = {2 unmodified lines"get_model_list","get_feature_list","get_model_features","run","get_task_status",}16 unmodified linesdef 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)16 unmodified linesdef 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:1 unmodified linereturn 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 Nonereturn 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):2 unmodified linesparams = 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:3 unmodified linesif getattr(fn, "api_name", None) in HIGH_LEVEL_MCP_API_NAMES:fn.show_api = Trueprint("[MCP Integration] Successfully registered 7 High-Level Abstract MCP APIs via gr.api().")
1234510 unmodified lines16171819202122"""MCP Tool: run_imagegenUnified image generation task submission and execution interface."""10 unmodified linesfrom .error_schema import make_validation_error, make_not_found_errordef handle_run_imagegen(params: dict) -> dict:"""Unified image generation task execution interface."""if not isinstance(params, dict):return make_validation_error("Request params must be an object.")1234510 unmodified lines16171819202122"""MCP Tool: runUnified image generation task submission and execution interface."""10 unmodified linesfrom .error_schema import make_validation_error, make_not_found_errordef 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.")
1234561 unmodified line891011121314158 unmodified lines24252627282930"""MCP Tool Handlers — Backward-compatible aggregation entry point.Core logic has been split into individual files (get_*.py and run_imagegen.py)."""from .get_task_list import handle_get_task_list1 unmodified linefrom .get_model_list import handle_get_model_listfrom .get_feature_list import handle_get_feature_listfrom .get_model_features import handle_get_model_featuresfrom .get_chain_schema import handle_get_chain_schemafrom .run_imagegen import handle_run_imagegenfrom .get_task_status import handle_get_task_statusfrom .common import (_TASK_DEFINITIONS,8 unmodified lines"handle_get_model_list","handle_get_feature_list","handle_get_model_features","handle_get_chain_schema","handle_run_imagegen","handle_get_task_status",]1234561 unmodified line8910111213148 unmodified lines232425262728"""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_list1 unmodified linefrom .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,8 unmodified lines"handle_get_model_list","handle_get_feature_list","handle_get_model_features","handle_run","handle_get_task_status",]
1234517 unmodified lines23242526272829comfyui-frontend-package==1.47.12comfyui-workflow-templates==0.11.27comfyui-embedded-docs==0.5.9torchtorchsde17 unmodified linesfilelockav>=16.0.0comfy-kitchen==0.2.26comfy-aimdo==0.4.11requestssimpleeval>=1.0.0blake31234517 unmodified lines23242526272829comfyui-frontend-package==1.48.6comfyui-workflow-templates==0.11.31comfyui-embedded-docs==0.5.9torchtorchsde17 unmodified linesfilelockav>=16.0.0comfy-kitchen==0.2.26comfy-aimdo==0.4.13requestssimpleeval>=1.0.0blake3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652# 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_valuecore/pipelines/pipeline_input_processor.py+32-27
mcp_tools/__init__.py+3-6
mcp_tools/common.py+422-30
mcp_tools/get_chain_schema.pyDeleted-32
mcp_tools/get_feature_list.py+123-25
mcp_tools/get_model_features.py+9-18
mcp_tools/mcp_gradio_integration.py+14-21
mcp_tools/run_imagegen.py → mcp_tools/run.pyRenamed+2-2
mcp_tools/tool_handlers.py+3-5
requirements.txt+3-3
yaml/chain_features.yamlAdded+652