# `ToolCall`

Derive LLM tool-call schemas from `@spec` and `@doc`.

    defmodule MyApp.Tools.Weather do
      use ToolCall

      @doc """
      Get the forecast for a city.

      ## Parameters
        * `city` - city name
        * `days` - how many days ahead
      """
      @spec get_weather(city :: String.t(), days :: pos_integer() | nil) ::
              {:ok, %{temp: float()}} | {:error, String.t()}
      def get_weather(city, days \\ 3)
    end

    ToolCall.emit(MyApp.Tools.Weather, :openai)
    ToolCall.run(MyApp.Tools.Weather, :get_weather, %{"city" => "Shanghai"})

Everything is generated at compile time from module attributes. No runtime
path reads the `Docs` or `Dbgi` chunks, because release builds strip them.
Visible local `@typedoc` text is recovered in a second compile phase
(`@after_compile`) and embedded in a generated companion module; runtime code
never calls `Code.fetch_docs/1`. The companion is ordinary compiled code,
loaded on first use like any other module.

## Type source

The current type source is the internal typespec provider. It may be replaced
by a future compiler-signature source. The wire schema and IR do not depend on
the typespec AST shape; the current provider still requires `@spec` to declare
a tool.

## Supported typespec subset

See `docs/design.md`. `@type`, `@typep` and `@opaque` declarations in the same
module are resolved before mapping, including parameterised ones. Unknown
types degrade to `{}` (any value) rather than failing compilation unless a
`ToolCall.TypeProvider` registered with `use ToolCall, types: [...]` resolves
them; types that JSON cannot express at all (functions, pids, refs) are
flagged with a compile-time warning.

# `describe`

```elixir
@spec describe(module(), keyword()) :: [
  %{
    module: module(),
    name: String.t(),
    description: String.t(),
    parameters: map()
  }
]
```

Returns a provider-neutral description of every tool in `module`.

Each entry has `:module`, `:name`, `:description` and `:parameters`, where
`:parameters` is the JSON Schema object for the arguments with no provider
envelope around it. Use this when your client owns the request format; use
`emit/3` when you want the OpenAI or Anthropic envelope.

## Options

  * `:strict` - render the strict JSON Schema subset (see `emit/3`).

# `emit`

```elixir
@spec emit(
  module() | [ToolCall.IR.Tool.t()] | ToolCall.IR.Tool.t(),
  :openai | :anthropic | :mcp | :gemini,
  keyword()
) :: map() | [map()]
```

Emits schemas for `target` (`:openai`, `:anthropic`, `:mcp` or `:gemini`).

For a module the OpenAI and Anthropic variants are rendered at **compile time**
and embedded as a literal, so this is a direct or guarded map lookup and
`strict` may be a runtime boolean. MCP and Gemini are rendered on demand. MCP
because its `inputSchema` is the parameters object the other targets already
embed; Gemini because its OpenAPI subset differs (uppercase types, no
`additionalProperties`). A module returns a list with one schema per tool; a
single `ToolCall.IR.Tool` returns one schema map and a list of them a list,
rendered on demand, which is what dynamically built tools need. Runtime IR is
validated before rendering; invalid types raise `ArgumentError`.

Gemini's `parameters` cannot express `$ref`/`$defs`, `additionalProperties`
or non-string enums, and it has no positional tuples; a recursive parameter
raises, and the other losses are documented in `ToolCall.Emit.Gemini`.

## Options

  * `:strict` - OpenAI strict mode: `true`, or `:fine_tuned` for the subset
    fine-tuned models accept. Both make every property required, optional
    values nullable and every object closed. `:fine_tuned` also drops
    `pattern`, `format`, numeric bounds and array bounds, which fine-tuned
    models reject. For `:mcp` it renders the same closed subset without a flag
    (MCP has none); `:fine_tuned` is OpenAI-only and raises for MCP. Ignored for
    `:anthropic` and `:gemini`.

# `run`

```elixir
@spec run(module(), atom() | String.t(), term(), keyword()) ::
  {:ok, term()} | {:pending, ToolCall.Approval.Request.t()} | {:error, term()}
```

Runs a tool by name. `args` uses string keys, as decoded from JSON.

## Options

  * `:validate_result` - when true, the function's raw return value is
    validated against the declared `@spec` return type before
    `{:ok, value}` / `{:error, reason}` is unwrapped. A mismatch returns
    `{:error, {:invalid_result, reason}}`. Defaults to false, which is the
    generated fast path. Validation uses the generic runner path.
  * `:timeout` - a per-invocation timeout in milliseconds or `:infinity`;
    defaults to the module's `use ToolCall, timeout: ...` policy. A finite
    timeout answers `{:error, {:timeout, ms}}` and runs the function in a
    task; `:infinity` runs in the caller unless `:task_supervisor` is given,
    which starts a task.
  * `:task_supervisor` - a `Task.Supervisor` name or pid for a timed
    invocation, including one supplied by the module timeout. With
    `:infinity` a supervisor still starts a task; without a supervisor a
    finite timeout uses a task linked to the caller and `:infinity` runs in
    the caller. An unreachable or invalid supervisor answers
    `{:error, {:task_supervisor, reason}}`.
  * `:context` - passed to the timeout, approval and audit policies. It is
    also stored on the call by `Runner.resolve/4` for `execute/2`.
  * `:approval` - `:granted`, `:denied`, or a `ToolCall.Approval` policy module;
    `nil` disables the module policy for one call. A policy may answer
    `{:required, reason}`, which returns
    `{:pending, %ToolCall.Approval.Request{}}`; the call is not invoked.
  * `:audit` - a `ToolCall.Audit` policy module; `nil` disables the module
    policy for one call. The hook receives one `%ToolCall.Audit.Entry{}` per
    dispatch attempt, including a resolve/execute exception. An approval or
    other dispatch exception is recorded as `:error` with
    `error: {:exception, message}`; a timeout policy failure is recorded as
    `:error` with `error: {:invalid_timeout, reason}`.

# `tool_names`

```elixir
@spec tool_names(module()) :: [String.t()]
```

Returns the tool names derived from a module, in declaration order.

# `tools`

```elixir
@spec tools(module()) :: [ToolCall.IR.Tool.t()]
```

Returns the tools derived from a module.

The embedded IR keeps the atom `Type.source` values (string sub-kinds drive
dispatch and result validation) and drops non-atom sources, the spec and the
parameter ASTs, which are compile-time provenance only.

# `validate_policies!`

```elixir
@spec validate_policies!(module()) :: :ok
```

Validates the module-level timeout, approval and audit policies.

Call this at application startup to reject a bad `use ToolCall` policy before
the first dispatch instead of waiting for `resolve` or `execute`. One-off
`run/4` options are validated when the call is made. Raises `ArgumentError`
for an unknown callback or an invalid mode.

    :ok = ToolCall.validate_policies!(MyApp.Tools)

Or add `{ToolCall.PolicyValidation, [MyApp.Tools]}` to the supervision tree
as a one-shot startup child.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
