|
| 1 | +""" |
| 2 | +request_tools — lazy tool loading meta-tool. |
| 3 | +
|
| 4 | +Agents start with a small set of core tools to keep token usage low. |
| 5 | +When they need additional capabilities (web search, browser, image gen, |
| 6 | +etc.), they call request_tools(categories) to inject those tool schemas |
| 7 | +into the next API call. |
| 8 | +
|
| 9 | +This follows the same pattern as request_mcp_access — the agent asks |
| 10 | +for what it needs, the gateway provides it. |
| 11 | +
|
| 12 | +Core tools (~2-3K tokens, always loaded): |
| 13 | + terminal, read_file, write_file, patch, search_files, |
| 14 | + memory, todo, clarify, request_tools |
| 15 | +
|
| 16 | +Extended tools (~6-7K tokens, loaded on demand): |
| 17 | + web, browser, image, vision, tts, delegation, code, |
| 18 | + workflows, cron, messaging, logs, skills, process, bugs |
| 19 | +
|
| 20 | +The split point is: can the agent have a useful conversation with just |
| 21 | +the core tools? Yes — it can read/write files, run commands, search |
| 22 | +code, and remember things. The extended tools are for specific tasks. |
| 23 | +""" |
| 24 | + |
| 25 | +import json |
| 26 | +import logging |
| 27 | + |
| 28 | +logger = logging.getLogger(__name__) |
| 29 | + |
| 30 | +# --------------------------------------------------------------------------- |
| 31 | +# Tool categories → toolset names (maps user-friendly names to registry IDs) |
| 32 | +# --------------------------------------------------------------------------- |
| 33 | + |
| 34 | +TOOL_CATEGORIES = { |
| 35 | + "web": {"tools": ["web_search", "web_extract"], "description": "Web search and content extraction (Firecrawl)"}, |
| 36 | + "browser": {"tools": ["browser_navigate", "browser_click", "browser_type", "browser_snapshot", "browser_scroll", "browser_press", "browser_back", "browser_close", "browser_get_images", "browser_vision", "browser_console"], "description": "Browser automation"}, |
| 37 | + "image": {"tools": ["image_generate"], "description": "Image generation (fal.ai)"}, |
| 38 | + "vision": {"tools": ["vision_analyze"], "description": "Image analysis using AI vision"}, |
| 39 | + "tts": {"tools": ["text_to_speech"], "description": "Text-to-speech audio generation"}, |
| 40 | + "delegation": {"tools": ["delegate_task", "execute_code", "mixture_of_agents"], "description": "Subagent spawning and programmatic tool calling"}, |
| 41 | + "workflows": {"tools": ["workflow"], "description": "Multi-step DAG task workflows"}, |
| 42 | + "cron": {"tools": ["schedule_cronjob", "list_cronjobs", "remove_cronjob"], "description": "Scheduled task management"}, |
| 43 | + "messaging": {"tools": ["send_message"], "description": "Cross-platform message delivery"}, |
| 44 | + "logs": {"tools": ["log_inspector"], "description": "Runtime log analysis"}, |
| 45 | + "skills": {"tools": ["skill_manage", "skill_view", "skills_list"], "description": "Skill management and browsing"}, |
| 46 | + "process": {"tools": ["process"], "description": "Background process management"}, |
| 47 | + "bugs": {"tools": ["bug_notes"], "description": "Self-reported bug tracking"}, |
| 48 | + "session": {"tools": ["session_search"], "description": "Long-term conversation memory search"}, |
| 49 | +} |
| 50 | + |
| 51 | +# Core tools — always loaded regardless of lazy mode |
| 52 | +CORE_TOOLS = frozenset({ |
| 53 | + "terminal", |
| 54 | + "read_file", |
| 55 | + "write_file", |
| 56 | + "patch", |
| 57 | + "search_files", |
| 58 | + "memory", |
| 59 | + "todo", |
| 60 | + "clarify", |
| 61 | +}) |
| 62 | + |
| 63 | +# --------------------------------------------------------------------------- |
| 64 | +# Session-level tool grants (same pattern as mcp_access) |
| 65 | +# --------------------------------------------------------------------------- |
| 66 | + |
| 67 | +import threading |
| 68 | + |
| 69 | +_lock = threading.Lock() |
| 70 | +_session_tools: dict[str, set[str]] = {} # session_id → set of granted tool names |
| 71 | + |
| 72 | + |
| 73 | +def grant_tools(session_id: str, tool_names: list[str]) -> None: |
| 74 | + """Grant additional tools to a session.""" |
| 75 | + with _lock: |
| 76 | + if session_id not in _session_tools: |
| 77 | + _session_tools[session_id] = set() |
| 78 | + _session_tools[session_id].update(tool_names) |
| 79 | + |
| 80 | + |
| 81 | +def get_granted_tools(session_id: str) -> frozenset[str]: |
| 82 | + """Return the set of tools granted to this session beyond core.""" |
| 83 | + with _lock: |
| 84 | + return frozenset(_session_tools.get(session_id, set())) |
| 85 | + |
| 86 | + |
| 87 | +def clear_session(session_id: str) -> None: |
| 88 | + """Clean up when session ends.""" |
| 89 | + with _lock: |
| 90 | + _session_tools.pop(session_id, None) |
| 91 | + |
| 92 | + |
| 93 | +# --------------------------------------------------------------------------- |
| 94 | +# Handler |
| 95 | +# --------------------------------------------------------------------------- |
| 96 | + |
| 97 | +_TOOL_NAME = "request_tools" |
| 98 | + |
| 99 | + |
| 100 | +def _handler(args: dict, **kwargs) -> str: |
| 101 | + categories = args.get("categories") or [] |
| 102 | + session_id = kwargs.get("session_id") |
| 103 | + |
| 104 | + if not categories: |
| 105 | + # List available categories |
| 106 | + cat_list = [] |
| 107 | + for cat, info in TOOL_CATEGORIES.items(): |
| 108 | + cat_list.append(f" {cat}: {info['description']} ({len(info['tools'])} tools)") |
| 109 | + return json.dumps({ |
| 110 | + "available_categories": list(TOOL_CATEGORIES.keys()), |
| 111 | + "details": "\n".join(cat_list), |
| 112 | + "message": "Call request_tools with the categories you need.", |
| 113 | + }) |
| 114 | + |
| 115 | + granted = [] |
| 116 | + not_found = [] |
| 117 | + for cat in categories: |
| 118 | + cat = cat.strip().lower() |
| 119 | + if cat in TOOL_CATEGORIES: |
| 120 | + tools = TOOL_CATEGORIES[cat]["tools"] |
| 121 | + if session_id: |
| 122 | + grant_tools(session_id, tools) |
| 123 | + granted.extend(tools) |
| 124 | + logger.info("request_tools: granted %s tools to session %s: %s", cat, session_id, tools) |
| 125 | + else: |
| 126 | + not_found.append(cat) |
| 127 | + |
| 128 | + result = { |
| 129 | + "status": "granted", |
| 130 | + "tools_added": granted, |
| 131 | + "message": f"Added {len(granted)} tools. They will be available from your next message.", |
| 132 | + } |
| 133 | + if not_found: |
| 134 | + result["not_found"] = not_found |
| 135 | + result["available_categories"] = list(TOOL_CATEGORIES.keys()) |
| 136 | + |
| 137 | + return json.dumps(result) |
| 138 | + |
| 139 | + |
| 140 | +# --------------------------------------------------------------------------- |
| 141 | +# Self-registration |
| 142 | +# --------------------------------------------------------------------------- |
| 143 | + |
| 144 | +def _register(): |
| 145 | + try: |
| 146 | + from tools.registry import registry |
| 147 | + |
| 148 | + cat_names = ", ".join(TOOL_CATEGORIES.keys()) |
| 149 | + schema = { |
| 150 | + "name": _TOOL_NAME, |
| 151 | + "description": ( |
| 152 | + "Request additional tool capabilities beyond the core set. " |
| 153 | + f"Available categories: {cat_names}. " |
| 154 | + "Call with no arguments to see descriptions. " |
| 155 | + "Tools are added to your session and available from the next message." |
| 156 | + ), |
| 157 | + "parameters": { |
| 158 | + "type": "object", |
| 159 | + "properties": { |
| 160 | + "categories": { |
| 161 | + "type": "array", |
| 162 | + "items": {"type": "string"}, |
| 163 | + "description": f"Tool categories to load. Available: {cat_names}", |
| 164 | + }, |
| 165 | + }, |
| 166 | + "required": [], |
| 167 | + }, |
| 168 | + } |
| 169 | + |
| 170 | + registry.register( |
| 171 | + name=_TOOL_NAME, |
| 172 | + toolset="core", |
| 173 | + schema=schema, |
| 174 | + handler=_handler, |
| 175 | + is_async=False, |
| 176 | + description=schema["description"], |
| 177 | + ) |
| 178 | + logger.debug("request_tools: registered") |
| 179 | + except Exception as exc: |
| 180 | + logger.debug("request_tools: registration failed: %s", exc) |
| 181 | + |
| 182 | + |
| 183 | +_register() |
0 commit comments