A tool call is the bridge between a model response and a change in the workspace. M31A runs every call through a predictable pipeline; understanding it makes policy and hook behavior much easier to reason about.
Key source files:
| File | Responsibility |
|---|---|
packages/core/src/tools/tool-registry.ts | Built-in, discovered, and MCP tool registration. |
packages/core/src/tools/definitions/base-declarations.ts | Built-in tool names and declarations. |
packages/core/src/scheduler/scheduler.ts | Validation, approval, scheduling, execution orchestration. |
packages/core/src/scheduler/policy.ts | Policy lookup and confirmation outcome handling. |
packages/core/src/scheduler/tool-executor.ts | Invocation execution and result shaping. |
packages/core/src/core/coreToolHookTriggers.ts | BeforeTool and AfterTool invocation plumbing. |
1. Discovery
At startup the tool registry is populated with built-in tools such as read_file, glob, grep_search, apply_patch, run_shell_command, and activate_skill. The full list is in Tools, with names declared in packages/core/src/tools/tool-names.ts.
Additional sources are added in layers:
- MCP servers contribute prefixed tools through
packages/core/src/tools/mcp-client-manager.tsandmcp-tool.ts. - Discovered tools come from a
tools.discoveryCommandand are invoked viatools.callCommand; their names are prefixed withdiscovered_tool_. - Skills are not tools themselves;
activate_skillis the built-in tool that loads a skill body on demand.
Restrictions are applied at discovery time or policy time:
| Setting | Effect |
|---|---|
tools.core | Restricts the built-in tool set. |
tools.exclude | Hides tools from discovery. |
mcp.allowed, mcp.excluded | Filters MCP servers. |
--allowed-mcp-server-names | Per-invocation MCP restriction. |
2. Schema exposure
Each registered tool exposes a name, description, and parameter schema. The NIM generator converts those schemas into OpenAI function definitions and sends them with tool_choice: "auto"; see The agent loop. When tool history exists but no tools are currently applicable, an empty tools array is still sent so the provider accepts the assistant's prior tool calls.
Use /tools list to see what the current session exposes and /tools desc for descriptions. /mcp schema shows MCP tool schemas specifically.
3. The call lifecycle
Scheduler.schedule() accepts one or more ToolCallRequestInfo values from a Turn. Each call moves through statuses such as validating, awaiting approval, scheduled, executing, success, error, and cancelled.
model emits function call
-> Turn creates ToolCallRequest (normalized callId)
-> BeforeTool hook evaluation
-> policy check (allow / deny / ask_user)
-> confirmation (if needed), policy update on "always allow"
-> scheduled -> executing -> success / error
-> AfterTool hook -> response parts -> next model requestOrdering matters:
BeforeToolruns before policy.evaluateBeforeToolHook()inpackages/core/src/scheduler/hook-utils.tscan block the call, forceask_user, or modify parameters. A hook can stop the whole agent run withcontinue: false.- Policy runs with shell-parse caching.
checkPolicy()queries the policy engine with the tool name, arguments, MCP server name, tool annotations, and optional subagent name. - Confirmation is interactive-only. If the decision is
ask_userin a non-interactive run,checkPolicy()throws instead of prompting. - Taint risks downgrade allow. Shell invocations that detect tainted or build-file risk are forced to
ask_userwhen interactive and todenyotherwise. AfterToolruns after execution throughexecuteToolWithHooks()inpackages/core/src/core/coreToolHookTriggers.ts. It can block the result, append context, or request a tail tool call whose result replaces the original response.
The executor deliberately skips a second BeforeTool fire, so a hook is not evaluated twice for one call.
4. Confirmation and policy updates
When ask_user is reached, resolveConfirmation() presents the appropriate dialog: a generic confirmation, an edit diff, a shell command, an MCP tool, or a sandbox expansion request.
The chosen outcome feeds updatePolicy():
ProceedOncechanges nothing durable.ProceedAlwaysadds an in-memory allow rule scoped to the current approval mode and more permissive modes; for edit tools it can also transition the session toauto_edit.ProceedAlwaysAndSavepersists a rule to workspace policies when the folder is trusted and a workspace policy directory exists, otherwise to user policies. Rules are written as TOML underpolicies/auto-saved.toml.
Sensitive tools require a narrowed command prefix or argument pattern; a broad "always allow" for them is skipped. See Policy evaluation for tier and priority rules.
5. Sandboxing
Authorization and isolation are separate concerns. Policy decides whether a call may run; the sandbox decides what it can touch while running.
- Whole-process isolation: macOS Seatbelt profiles via
SEATBELT_PROFILE, or Docker/Podman viaM31A_SANDBOX. - Per-tool isolation:
security.toolSandboxing. - Legacy process-level controls:
tools.sandbox,tools.sandboxAllowedPaths, andtools.sandboxNetworkAccess.
If a sandboxed shell needs more rights, the tool returns sandbox_expansion_required. The scheduler turns that into an approval dialog; on acceptance it re-executes the call with additional_permissions. See Sandboxing.
6. Result handling
A successful tool call produces a ToolResult with llmContent for the model and returnDisplay for the UI. Errors carry a ToolErrorType such as POLICY_VIOLATION, INVALID_TOOL_PARAMS, STOP_EXECUTION, or TOOL_EXECUTION_ERROR. Error text is returned to the model as a function response so it can try a different approach.
Output management happens before the next request:
tools.truncateToolOutputThreshold(default40000characters) caps shown output.ToolOutputDistillationServicespills oversized output to disk and replaces it with a placeholder.ToolOutputMaskingServicemasks older outputs once enough prunable tokens have accumulated.
See Context lifecycle for those mechanisms.
M31aChat.recordToolCalls() stores the call ID, name, arguments, result, status, timestamp, and optional agent ID. Recording scheduled calls before execution keeps an interrupted run auditable.
7. Retries and correction
Two different retry layers exist:
- Model-level retries handle invalid streams, transient fetch errors, and context-window pressure. One-shot nudge messages can steer the model after a thinking-only or empty response.
- Edit correction rewrites malformed edit arguments.
tools.disableLLMCorrectiondefaults totrue, which uses a local string correction path; setting it tofalseenables an LLM-based fixer for some file types (not.jsonor.ipynb).
general.maxAttempts caps main-model attempts at 10. tools.useRipgrep (always on by default) selects ripgrep for content search.
8. Observing a call
m31a --approval-mode plan # analysis only; writes are denied by policy
# inside the TUI:
# /tools list
# /tools desc
# /mcp schema
# /policies listFor scripted runs, --output-format stream-json emits tool events as they complete; see Headless CI.
Next steps
- Read Policy evaluation for rule precedence.
- Read Hooks for hook event payloads.
- Write a custom hook that logs or validates a call.