loopable / api /tool_groups /__init__.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame
13.9 kB
"""Discover MCP groups and adapt the previous tool names."""
import copy
import importlib
import json
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."
GUIDE_TOOL = "loopable_guide"
# One intent schema for the base specs and the served tools/list, so the two cannot drift.
INTENT_SCHEMA = {"type": "string", "minLength": 1, "maxLength": 500,
"description": "State why you are making this call. Required for every write, including confirmation."}
def canonical_name(name):
"""Resolve the previous Table group key without advertising a second group."""
return "table" if name == "data" else name
def _prefixed_action(name, arguments):
"""Strip a repeated group prefix from an action, as in sheet_write_cells, when the rest is exact."""
group = groups().get(canonical_name(name))
action = arguments.get("action") if isinstance(arguments, dict) else None
if group is None or not isinstance(action, str) or action in group["actions"]:
return arguments
inner = arguments.get("arguments")
if action == group["name"] and isinstance(inner, dict) and inner.get("action") in group["actions"]:
# The group name sent as the action, with the real action inside arguments, unwraps one level.
rest = {key: value for key, value in inner.items() if key != "action"}
return {**arguments, "action": inner["action"], "arguments": rest}
for prefix in {name, canonical_name(name)}:
for joint in ("_", "."):
if action.startswith(prefix + joint) and action[len(prefix) + 1:] in group["actions"]:
return {**arguments, "action": action[len(prefix) + 1:]}
return arguments
def canonical_call(name, arguments):
"""Adapt Table group aliases and dotted actions before normal admission."""
if name == GUIDE_TOOL + ".read":
return GUIDE_TOOL, arguments
if name == "data":
return "table", _prefixed_action("data", arguments)
if not isinstance(name, str):
return name, arguments
prefix, separator, action = name.partition(".")
if not separator:
return name, _prefixed_action(name, arguments)
if 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 _kind(rule):
"""Name the JSON type a schema rule accepts, in plain words."""
if not isinstance(rule, dict):
return "value"
if isinstance(rule.get("enum"), list) and rule["enum"]:
return "one of " + ", ".join(str(choice) for choice in rule["enum"])
kind = rule.get("type")
if isinstance(kind, list):
return " or ".join(str(item) for item in kind)
if isinstance(kind, str):
return kind
branches = rule.get("oneOf") or rule.get("anyOf") or []
kinds = list(dict.fromkeys(_kind(branch) for branch in branches))
return " or ".join(kinds) or "value"
def _example(key, rule):
"""Return a placeholder value of the type a schema rule accepts."""
if not isinstance(rule, dict):
return "<" + key + ">"
if isinstance(rule.get("enum"), list) and len(rule["enum"]) == 1:
return rule["enum"][0]
kind = rule.get("type")
if kind == "array":
return [_example(key, rule.get("items"))]
if kind == "object":
return {}
if kind in ("integer", "number"):
return max(1, rule.get("minimum", 1))
if kind == "boolean":
return True
return "<" + key + ">"
def call_shape(group, action, schema, sent=None, example=None):
"""Name the current address, the argument shape and any key the caller got wrong."""
schema = schema if isinstance(schema, dict) else {}
properties = schema.get("properties", {})
required = [key for key in schema.get("required", ()) if key in properties]
shown = example if isinstance(example, dict) else {key: _example(key, properties[key]) for key in required}
sentences = []
if isinstance(sent, dict):
stray = sorted(str(key) for key in sent if key not in properties)
missing = [key for key in required if key not in sent]
if stray and schema.get("additionalProperties") is False:
sentences.append(", ".join(stray) + (" is not an argument of " if len(stray) == 1
else " are not arguments of ") + action + ".")
if missing:
sentences.append(", ".join(missing) + (" is required." if len(missing) == 1 else " are required."))
sentences.append("Call " + group + " with " + json.dumps(
{"action": action, "arguments": shown}, separators=(", ", ": ")) + ".")
optional = [key for key in properties if key not in required and key not in shown
and key not in {"action", "arguments"}]
if optional:
sentences.append("Optional arguments: " + ", ".join(
key + " (" + _kind(properties[key]) + ")" for key in optional) + ".")
elif not properties or set(properties) <= {"action", "arguments"}:
sentences.append(action + " takes no arguments.")
return " ".join(sentences)
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
action = arguments.get("action") if isinstance(arguments, dict) else None
if isinstance(arguments, dict) and (not isinstance(action, str) or action not in group["actions"]):
# A bare group name as the action gets one clause naming the mix-up before the action list.
named = group["name"] + " is the tool name, not an action. " if action == group["name"] else ""
raise sheets.SheetRefusal("tool_arguments_invalid", (
named + "Tool arguments must match the published input schema. Set action to one of the "
+ group["name"] + " actions: " + ", ".join(group["actions"]) + ". Put that action's inputs inside "
"arguments, and intent, about and purpose beside action and arguments."))
entry = group["actions"][arguments["action"]] if isinstance(arguments, dict) else None
try:
external_tools.validate_arguments(arguments, {
"type": "object", "properties": {
"action": {"type": "string", "enum": list(group["actions"])},
"arguments": {"type": "object"},
}, "required": ["action"], "additionalProperties": False,
})
args = arguments.get("arguments", {})
if entry.get("legacy_name") in {"query_database", "list_databases"}:
args = external_tools.table_read_arguments(entry["legacy_name"], args, entry["schema"])
else:
external_tools.validate_arguments(args, entry["schema"])
except sheets.SheetRefusal as exc:
if exc.code != "tool_arguments_invalid" or entry is None:
raise
# S79-T11: a schema refusal names the current tool, action and argument shape.
stray = sorted(str(key) for key in arguments if key not in {"action", "arguments"})
beside = (", ".join(stray) + (" goes" if len(stray) == 1 else " go")
+ " inside arguments, not beside action. ") if stray else ""
inner = arguments.get("arguments")
raise sheets.SheetRefusal(exc.code, exc.message + " " + beside + call_shape(
group["name"], arguments["action"], entry["schema"],
inner if isinstance(inner, dict) else {}, entry.get("example"))) from exc
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 writes(group):
"""Tell whether any action in a group writes."""
return any(not entry["read"] for entry in group["actions"].values())
def tool_specs():
"""Publish compact group summaries with call metadata and conservative effect hints."""
import wiki_log
return [{
"name": name, "description": group["guide"],
"inputSchema": {"type": "object", "properties": {
"action": {"type": "string"}, "arguments": {"type": "object"},
"intent": copy.deepcopy(INTENT_SCHEMA), "about": copy.deepcopy(external_tools.ABOUT_SCHEMA),
"purpose": copy.deepcopy(wiki_log.PURPOSE_SCHEMA),
}, "required": ["action", "intent"] if writes(group) else ["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()]