Download api/tool_groups/__init__.py from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 7.42 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/623acbc433f972703d46dcda190a3d39c4064fa7/api/tool_groups/__init__.py
- Command line
-
hf download hf://spaces/fsanyoto/loopable@623acbc433f972703d46dcda190a3d39c4064fa7/api/tool_groups/__init__.py
-
curl -L -o __init__.py https://huggingface.co/spaces/fsanyoto/loopable/resolve/623acbc433f972703d46dcda190a3d39c4064fa7/api/tool_groups/__init__.py
7.42 kB
| """Discover MCP groups and adapt the previous tool names.""" | |
| import copy | |
| import importlib | |
| import pkgutil | |
| from core import external_tools, sheets | |
| _GROUP_MODULE_NAMES = {"data": "table"} | |
| TABLE_ALIAS_NOTE = "The data tool is deprecated for one release. Use table for the Table module." | |
| def canonical_name(name): | |
| """Resolve the previous Table group key without advertising a second group.""" | |
| return "table" if name == "data" else name | |
| def canonical_call(name, arguments): | |
| """Adapt Table group aliases and dotted actions before normal admission.""" | |
| if name == "data": | |
| return "table", arguments | |
| if not isinstance(name, str): | |
| return name, arguments | |
| prefix, separator, action = name.partition(".") | |
| if not separator or prefix not in {"table", "data"}: | |
| return name, arguments | |
| entry = groups().get("table", {}).get("actions", {}).get(action) | |
| if entry is None: | |
| return name, arguments | |
| if not isinstance(arguments, dict): | |
| return "table", arguments | |
| metadata = {key: value for key, value in arguments.items() if key in {"intent", "purpose", "about"}} | |
| args = {key: value for key, value in arguments.items() if key not in metadata} | |
| if entry.get("legacy_action") is not None: | |
| args.setdefault("action", entry["legacy_action"]) | |
| return "table", {"action": action, "arguments": args, **metadata} | |
| def legacy_action(name, *, action=None, read=None, destructive=False): | |
| """Bind one legacy operation to a fixed read or write class.""" | |
| tool = external_tools.TOOLS[name] | |
| schema = copy.deepcopy(tool["inputSchema"]) | |
| if action is not None: | |
| schema["properties"]["action"] = {"enum": [action]} | |
| if read is None: | |
| read = not tool["write"] | |
| return { | |
| "read": read, "destructive": destructive, "confirm": True, | |
| "schema": schema, | |
| "handler": lambda ctx, args: external_tools.dispatch(ctx, name, args), | |
| "legacy_name": name, "legacy_action": action, | |
| } | |
| def groups(): | |
| """Find group modules without requiring optional groups to be installed.""" | |
| found = {} | |
| importlib.invalidate_caches() | |
| for module in sorted(pkgutil.iter_modules(__path__), key=lambda item: item.name): | |
| if module.name.startswith("_") or module.ispkg: | |
| continue | |
| group = importlib.import_module(f"{__name__}.{module.name}").GROUP | |
| name = group["name"] | |
| if (name != _GROUP_MODULE_NAMES.get(module.name, module.name) or name in found | |
| or name in external_tools.TOOLS or name == "loopable_guide"): | |
| raise ValueError("Invalid tool group name") | |
| if not all(isinstance(group[key], str) and group[key] for key in ("name", "title", "guide")): | |
| raise ValueError("Invalid tool group description") | |
| if not isinstance(group["actions"], dict) or not group["actions"]: | |
| raise ValueError("A tool group needs actions") | |
| for key, entry in group["actions"].items(): | |
| if not isinstance(key, str) or not key: | |
| raise ValueError("Invalid tool action name") | |
| if any(type(entry[field]) is not bool for field in ("read", "destructive", "confirm")): | |
| raise ValueError("Tool action effects must be explicit") | |
| if not isinstance(entry["schema"], dict) or not callable(entry["handler"]): | |
| raise ValueError("A tool action needs a schema and handler") | |
| # Receipt checks are read-only and return True only with current object access. | |
| if "receipt_access" in entry and not callable(entry["receipt_access"]): | |
| raise ValueError("A receipt access check must be callable") | |
| if entry["read"] and entry["destructive"]: | |
| raise ValueError("A read action cannot be destructive") | |
| if not entry["read"] and not entry["confirm"] and (name, key) not in { | |
| ("requests", "send"), ("requests", "send_message"), ("intelligence", "create_wiki")}: | |
| raise ValueError("Only requests.send, requests.send_message and intelligence.create_wiki may write without confirmation") | |
| found[name] = group | |
| return found | |
| def resolve(name, arguments): | |
| """Validate the selected action before a preview or handler can run.""" | |
| group = groups().get(canonical_name(name)) if isinstance(name, str) else None | |
| if group is None: | |
| return None | |
| external_tools.validate_arguments(arguments, { | |
| "type": "object", "properties": { | |
| "action": {"type": "string", "enum": list(group["actions"])}, | |
| "arguments": {"type": "object"}, | |
| }, "required": ["action"], "additionalProperties": False, | |
| }) | |
| entry = group["actions"][arguments["action"]] | |
| args = arguments.get("arguments", {}) | |
| external_tools.validate_arguments(args, entry["schema"]) | |
| legacy = entry.get("legacy_name") | |
| if legacy and external_tools.is_write(legacy, args) == entry["read"]: | |
| raise sheets.SheetRefusal( | |
| "tool_arguments_invalid", "Choose the action that matches this change.") | |
| return entry, args | |
| def legacy_target(name, arguments): | |
| """Return the grouped address for each supported legacy operation.""" | |
| for group_name, group in groups().items(): | |
| for action, entry in group["actions"].items(): | |
| if entry.get("legacy_name") != name: | |
| continue | |
| fixed = entry.get("legacy_action") | |
| if fixed is not None and arguments.get("action") != fixed: | |
| continue | |
| if external_tools.is_write(name, arguments) == entry["read"]: | |
| continue | |
| return group_name, {"action": action, "arguments": copy.deepcopy(arguments)} | |
| if name.endswith("_object") and isinstance(arguments.get("action"), str): | |
| # A native handler that replaced a legacy object action keeps the grouped address. | |
| operation = name.removesuffix("_object") + "." + arguments["action"] | |
| for group_name, group in groups().items(): | |
| entry = group["actions"].get(operation) | |
| if entry is not None and not entry.get("legacy_name"): | |
| return group_name, {"action": operation, "arguments": copy.deepcopy(arguments)} | |
| if name == "confirm_change": | |
| return name, copy.deepcopy(arguments) | |
| raise KeyError(name) | |
| def action_grants(entry, group=""): | |
| """Use the handler's declared grants for caller capability reporting.""" | |
| legacy = entry.get("legacy_name") | |
| if legacy: | |
| return external_tools.TOOLS[legacy]["grants"] | |
| grants = ("ai_apps", "intelligence") if group == "intelligence" else ("ai_apps",) | |
| return tuple(dict.fromkeys((*grants, *entry.get("grants", ())))) | |
| def tool_specs(): | |
| """Publish compact group summaries with conservative effect hints.""" | |
| return [{ | |
| "name": name, "description": group["guide"], | |
| "inputSchema": {"type": "object", "properties": { | |
| "action": {"type": "string"}, "arguments": {"type": "object"}, | |
| }, "required": ["action"], "additionalProperties": False}, | |
| "annotations": { | |
| "title": group["title"], | |
| "readOnlyHint": all(entry["read"] for entry in group["actions"].values()), | |
| "destructiveHint": any(entry["destructive"] for entry in group["actions"].values()), | |
| "openWorldHint": True, | |
| }, | |
| } for name, group in groups().items()] | |