Skip to content

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:

FileResponsibility
packages/core/src/tools/tool-registry.tsBuilt-in, discovered, and MCP tool registration.
packages/core/src/tools/definitions/base-declarations.tsBuilt-in tool names and declarations.
packages/core/src/scheduler/scheduler.tsValidation, approval, scheduling, execution orchestration.
packages/core/src/scheduler/policy.tsPolicy lookup and confirmation outcome handling.
packages/core/src/scheduler/tool-executor.tsInvocation execution and result shaping.
packages/core/src/core/coreToolHookTriggers.tsBeforeTool 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.ts and mcp-tool.ts.
  • Discovered tools come from a tools.discoveryCommand and are invoked via tools.callCommand; their names are prefixed with discovered_tool_.
  • Skills are not tools themselves; activate_skill is the built-in tool that loads a skill body on demand.

Restrictions are applied at discovery time or policy time:

SettingEffect
tools.coreRestricts the built-in tool set.
tools.excludeHides tools from discovery.
mcp.allowed, mcp.excludedFilters MCP servers.
--allowed-mcp-server-namesPer-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.

text
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 request

Ordering matters:

  1. BeforeTool runs before policy. evaluateBeforeToolHook() in packages/core/src/scheduler/hook-utils.ts can block the call, force ask_user, or modify parameters. A hook can stop the whole agent run with continue: false.
  2. 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.
  3. Confirmation is interactive-only. If the decision is ask_user in a non-interactive run, checkPolicy() throws instead of prompting.
  4. Taint risks downgrade allow. Shell invocations that detect tainted or build-file risk are forced to ask_user when interactive and to deny otherwise.
  5. AfterTool runs after execution through executeToolWithHooks() in packages/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():

  • ProceedOnce changes nothing durable.
  • ProceedAlways adds an in-memory allow rule scoped to the current approval mode and more permissive modes; for edit tools it can also transition the session to auto_edit.
  • ProceedAlwaysAndSave persists 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 under policies/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 via M31A_SANDBOX.
  • Per-tool isolation: security.toolSandboxing.
  • Legacy process-level controls: tools.sandbox, tools.sandboxAllowedPaths, and tools.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 (default 40000 characters) caps shown output.
  • ToolOutputDistillationService spills oversized output to disk and replaces it with a placeholder.
  • ToolOutputMaskingService masks 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.disableLLMCorrection defaults to true, which uses a local string correction path; setting it to false enables an LLM-based fixer for some file types (not .json or .ipynb).

general.maxAttempts caps main-model attempts at 10. tools.useRipgrep (always on by default) selects ripgrep for content search.

8. Observing a call ​

bash
m31a --approval-mode plan          # analysis only; writes are denied by policy
# inside the TUI:
# /tools list
# /tools desc
# /mcp schema
# /policies list

For scripted runs, --output-format stream-json emits tool events as they complete; see Headless CI.

Next steps ​

Built with VitePress. Powered by NVIDIA NIM.