tools/registry.pymodel_tools.pytoolsets.pytools/terminal_tool.pytools/environments/*
Tool registration model
Each tool module callsregistry.register(...) at import time.
model_tools.py is responsible for importing/discovering tool modules and building the schema list used by the model.
How registry.register() works
Every tool file in tools/ calls registry.register() at module level to declare itself. The function signature is:
ToolEntry stored in the singleton ToolRegistry._tools dict keyed by tool name. A registration that would shadow an existing tool from a different toolset is rejected (with an error log) unless the caller passes override=True; plugin overrides of built-in tools additionally require the operator opt-in plugins.entries.<plugin_id>.allow_tool_override: true in config.yaml.
schema["description"] is the authoritative model-facing description. The separate description= argument populates ToolEntry.description; when it is omitted, the registry metadata falls back to the schema description. get_definitions() builds the OpenAI function definition from entry.schema and does not copy entry.description into a schema that lacks description. Therefore, description= alone does not describe the tool to the model, and when both values differ the model sees the schema value. Prefer defining the description once in the schema unless a registry consumer intentionally needs different metadata.
Discovery: discover_builtin_tools()
When model_tools.py is imported, it calls discover_builtin_tools() from tools/registry.py. This function scans every tools/*.py file using AST parsing to find modules that contain top-level registry.register() calls, then imports them:
registry.register() calls (not calls inside functions), so helper modules in tools/ are not imported.
Each import triggers the module’s registry.register() calls. Errors in optional tools (e.g., missing fal_client for image generation) are caught and logged — they don’t prevent other tools from loading.
After core tool discovery, MCP tools and plugin tools are also discovered:
- MCP tools —
tools.mcp_tool_discovery.discover_mcp_tools()(re-exported by thetools.mcp_toolfacade) reads MCP server config and registers tools from external servers. - Plugin tools —
mibyan_cli.plugins.discover_plugins()loads user/project/pip plugins that may register additional tools.
Tool availability checking (check_fn)
Each tool can optionally provide a check_fn — a callable that returns True when the tool is available and False otherwise. Typical checks include:
- API key present — e.g.,
lambda: bool(os.environ.get("SERP_API_KEY"))for web search - Service running — e.g., checking if the Honcho server is configured
- Binary installed — e.g., verifying
playwrightis available for browser tools
registry.get_definitions() builds the schema list for the model, it runs each tool’s check_fn():
- Check results are cached per-call — if multiple tools share the same
check_fn, it only runs once. - Exceptions in
check_fn()are treated as “unavailable” (fail-safe). - The
is_toolset_available()method checks whether a toolset’scheck_fnpasses, used for UI display and toolset resolution.
Toolset resolution
Toolsets are named bundles of tools. Mibyan resolves them through:- explicit enabled/disabled toolset lists
- platform presets (
mibyan-cli,mibyan-telegram, etc.) - dynamic MCP toolsets
- curated special-purpose sets like
mibyan-acp
How get_tool_definitions() filters tools
The main entry point is model_tools.get_tool_definitions(enabled_toolsets, disabled_toolsets, quiet_mode):
-
If
enabled_toolsetsis provided — only tools from those toolsets are included. Each toolset name is resolved viaresolve_toolset()which expands composite toolsets into individual tool names. -
If
disabled_toolsetsis provided — start with ALL toolsets, then subtract the disabled ones. - If neither — include all known toolsets.
-
Registry filtering — the resolved tool name set is passed to
registry.get_definitions(), which appliescheck_fnfiltering and returns OpenAI-format schemas. -
Dynamic schema patching — after filtering,
execute_codeandbrowser_navigateschemas are dynamically adjusted to only reference tools that actually passed filtering (prevents model hallucination of unavailable tools).
Legacy toolset names
Old toolset names with_tools suffixes (e.g., web_tools, terminal_tools) are mapped to their modern tool names via _LEGACY_TOOLSET_MAP for backward compatibility.
Dispatch
At runtime, tools are dispatched through the central registry, with agent-loop exceptions for some agent-level tools such as memory/todo/session-search handling.Dispatch flow: model tool_call → handler execution
When the model returns atool_call, the flow is:
Error wrapping
All tool execution is wrapped in error handling at two levels:-
registry.dispatch()— catches any exception from the handler and returns{"error": "Tool execution failed: ExceptionType: message"}as JSON. -
handle_function_call()— wraps the entire dispatch in a secondary try/except that returns{"error": "Error executing tool_name: message"}.
Agent-loop tools
Four tools are intercepted before registry dispatch because they need agent-level state (TodoStore, MemoryStore, etc.):todo_list— planning/task trackingmemory— persistent memory writessession_search— cross-session recalldelegate_task— spawns subagent sessions
get_tool_definitions), but their handlers return a stub error if dispatch somehow reaches them directly.
Async bridging
When a tool handler is async,_run_async() bridges it to the sync dispatch path:
- CLI path (no running loop) — uses a persistent event loop to keep cached async clients alive
- Gateway path (running loop) — spins up a disposable thread with
asyncio.run() - Worker threads (parallel tools) — uses per-thread persistent loops stored in thread-local storage
The DANGEROUS_PATTERNS approval flow
The terminal tool integrates a dangerous-command approval system defined intools/approval.py:
-
Pattern detection —
DANGEROUS_PATTERNSis a list of(regex, description)tuples covering destructive operations:- Recursive deletes (
rm -rf) - Filesystem formatting (
mkfs,dd) - SQL destructive operations (
DROP TABLE,DELETE FROMwithoutWHERE) - System config overwrites (
> /etc/) - Service manipulation (
systemctl stop) - Remote code execution (
curl | sh) - Fork bombs, process kills, etc.
- Recursive deletes (
-
Detection — before executing any terminal command,
detect_dangerous_command(command)checks against all patterns. -
Approval prompt — if a match is found:
- CLI mode — an interactive prompt asks the user to approve, deny, or allow permanently
- Gateway mode — an async approval callback sends the request to the messaging platform
- Smart approval — optionally, an auxiliary LLM can auto-approve low-risk commands that match patterns (e.g.,
rm -rf node_modules/is safe but matches “recursive delete”)
-
Session state — approvals are tracked per-session. Once you approve “recursive delete” for a session, subsequent
rm -rfcommands don’t re-prompt. -
Permanent allowlist — the “allow permanently” option writes the pattern to
config.yaml’scommand_allowlist, persisting across sessions.
Terminal/runtime environments
The terminal system supports multiple backends:- local
- docker
- ssh
- singularity
- modal
- daytona
- vercel_sandbox
- per-task cwd overrides
- background process management
- PTY mode
- approval callbacks for dangerous commands
tools/process_registry_checkpoint.py owns running-process checkpoints and
PID-safe adoption. Completed output is separate: tools/process_registry_results.py
writes one atomic, redacted receipt per process under the profile’s
logs/process-results/. Producers cannot overwrite another parent’s results by
rewriting the shared PID checkpoint. The registry persists the receipt before
releasing its completion event; one-shot linger waits on that event. The existing
process query methods load retained snapshots without adopting PIDs or enqueuing
notifications. Reads require the commissioning durable session or its compression
continuation; knowing a handle alone does not authorize a retained result read.
The registry captures that owner before starting any output reader, including on
CLI and non-notifying processes, and preserves the producer’s profile context in
reader threads. Receipt redaction is forced independently of live-output opt-out;
retention is bounded by age and count.

