# Function calling

Default on, user curated: a registered tool works with no configuration, and every layer's default is not to restrict. Tool-call results live only in run history and never enter later prompt context, so broad exposure costs no context. Loop mechanics: [tool calling](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/tool-calling.html).

## One registry

| Authoring | API wire |
| --- | --- |
| `@function` | `Tool`, `ToolCall`, `ToolResultMessage` |
| Agent method with `method_options[name]["tool"] = True` | `tools=[...]` |
| `agent_tools()`, `get_agent_tool()` | `tool_calls=[...]` |

The act is "function calling"; the API object stays `tool`. Our `AgentTool` and `AgentToolResult` add what the wire lacks: sidecar gating, sync to async, char cap. Providers serialize each one; returned `tool_calls` match by name and `AgentTool.execute(...)` runs. Managed Program packages list public entries in `PROGRAM_ENTRIES`. Automatic scope capture exposes nothing. Class authoring and lifetime: [Agent and Context contract](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/nooa.html#contract).

## Six gating layers

| Layer | Configured by | Default | When rejected |
| --- | --- | --- | --- |
| 1 Import | `available_if` | Registers | Never enters `_registry` |
| 2 Exposure | `expose=False`, internal helpers only | Exposed, plugins and MCP included. Bare `runtime.exec` gets the full set | Python-callable, never in a tools array |
| 2b Preset | `toolset=[...]`, `TOOLSETS`, `DEFAULT_TOOLS`, a named profile; `toolset="none"` for no tools | None forced | A named subset, not a visibility gate |
| 3 Session and channel | `agent_profile.toolset`, `unsafe_in` | No restriction. `source=None` filters nothing | Narrower set; a channel (telegram, wechat, plan) hides the tool |
| 4 List build | `check_fn`, `requires_env`, `can_use`; `agent_tools(only_available=True)` | Assumed runnable; checked only on the dispatcher path | Dropped, so the LLM never sees a tool that would error |
| 5 User and policy | `agent_tools(deny=, allow=)`, `agent_profile.disabled`, `tools.disabled`, attended mode | Vetoes nothing | Subtracted by name; attended mode withholds `ask_user_question` |
| 6 Prompt | `defer=True`, MCP wiring | Schema ships | Name and one line in a catalog; `tool_search` loads the schema |

Layers 2, 2b and 6 select; 3, 4 and 5 only veto. Layers 1 to 5 mean the LLM cannot use the tool. Layer 6 lets the LLM choose what to load.

**Why 2b and 5 stay separate**

2b chooses a set to use; 5 removes what must not be used. A veto must hold whatever is selected: attended mode withholds `ask_user_question` in every folder. So the Programs page leads with 2b (pick folders) and offers 5 as a per-tool off switch. System vetoes (attended, subagent and role caps through allow and deny) are code-only and invisible.

## Plugins and MCP servers

Registering is enough; there is no central allowlist. Plugin tools use `_build_and_register_tool` like built-ins. MCP tools register as `AgentTool` on connect, `defer=True` by default.

## Tool settings

| Setting | Controls |
| --- | --- |
| `name`, `description`, `parameters`, `label` | What the LLM sees. `@function` derives them from signature and docstring; Agent methods reuse `_build_agentic_tool_spec` |
| `max_result_weight`, `stream_capacity_chars` | A smaller result bound than the model's, recorded as `details["cap"]` and applied once by the agent loop, which keeps the whole text in the conversation's `tool_results/<sha256>.txt` ([Tool output](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/overview.html#cross-turn-tool-context)); bounded tail for streamed `on_update` |
| `timeout`, `timeout_min`, `timeout_max` | Static or LLM-controlled timeout |
| `cache`, `cache_ttl` | Memoize on name and arguments |
| `describe` | Current description and parameters, applied at each list resolve (`current_tool`), so a tool names only what is available |
| `requires_approval` | Dispatcher consults before invoking |
| `register_globally=False` | Builds the tool and sidecars, skips the global register (test isolation) |

**Four knobs the references lack**

Claude Code, Hermes and OpenClaw ship none of these.

| Knob | Behaviour |
| --- | --- |
| Result share of a small window | The agent loop stores a result bounded to the model's `tool_output_weight` (default 10,000), at most `0.3 × context window`, in weight: a CJK character 1, anything else 0.25. A local model added by hand without a window (4,096 tokens) gets 1,228, a 32,768-token model 9,830. `spill.result_cap`, set around each tool dispatch from the model, including the weekly report's source reads |
| A read page in that share | `read` pages within the same cap, its header and continue note counted, a line cut to what one page holds. The AGENTS.md a read reaches goes beside the result, bounded on its own, so it takes nothing from the page |
| LLM-controllable timeout | If the function declares `timeout` and the decorator sets the range, the value is clamped and used as both `wait_for` budget and parameter |
| Bounded streaming tail | `_TailAccumulator`; capacity defaults to 40,000 characters, head evicted on overflow |
| `can_use()` | Session-level "is this user or role allowed", beside `check_fn` (process) and `unsafe_in` (channel) |

## Agent method registration

```
from openprogram import Agent

class ResearchAgent(Agent):
    method_options = {
        "research": {"tool": True, "name": "research", "toolset": ["research"], "expose": "io"},
    }

    def research(self, topic: str) -> str:
        """Research a topic."""
        return self(topic)

researcher = ResearchAgent()
PROGRAM_ENTRIES = [researcher.research]
```

- Method handling runs cancellation hooks, runtime injection, Context derivation, DAG entry and terminal updates, and error restoration. Options retain schema, caching, timeout, availability, approval and explicit-step recovery.
- Construction registers only methods asking for tool exposure, in the same registry and sidecars. `available_if` gates registration, not the method scope.
- The managed loader records package ownership. It adds no public decorator and no authority.

## Tool profiles

- **Catalog**: All registered, exposed tools, read-only on `/programs`
- **Profile**: A named tool set. A new one starts as a copy of all tools; remove what a scenario does not need
- **`FULL`, `BUILT-IN`**: Always exist, cannot be changed or deleted. `FULL` is the active default
- **Use**: Agents → Capabilities → Programs picks all tools, a selected scope, a named profile (Access preset) or none. The composer has no tool picker. A profile name resolves wherever `toolset=` is accepted, and in `tools.toolset` of `agent.json`
- **Global disable**: `tools.disabled` applies after the profile, removing the tool everywhere

```
// functions_meta.json, beside programs_meta.json
{
  "profiles": {
    "FULL": ["bash", "read", "write", ...],
    "BUILT-IN": [...],
    "research": ["web_search", "web_fetch", "read", "write", "bash"]
  },
  "active": "FULL"
}
```

| Entry point | Controls | Layer | Stored in |
| --- | --- | --- | --- |
| Programs page, `/api/tool-profiles` | Create, edit, delete profiles | 2b | `functions_meta.json` |
| Composer "+" menu | Web Search on or off, on top of the Agent's set | 2b, 5 | Branch configuration in session metadata |
| Agent profile `tools` | All, selected, Access preset, none; disabled names | 2b, 5 | `~/.openprogram/agents/<id>.json` |
| Attended switch (CLI, TUI, Web) | Withholds `ask_user_question` with no human watching | 5 | Session state |
| Global tool disable | One tool everywhere; overrides any profile; rare | 5 | `config.json`: `tools.disabled` |
| Decorator kwargs | `expose`, `available_if`, `defer`, `toolset`, `unsafe_in`, `check_fn` | 1, 2, 3, 6 | Code |

## Resolution path

1. `resolve_tools` calls `agent_tools(toolset=…, source=req.source, only_available=True)`, walking layers 2 to 5, not 6.
2. The deferred catalog goes beside the user message as the `turn_context` section `deferred_catalog`: every deferred tool in scope, loaded or not, in full the first time and then only what was added or removed, so neither loading a tool nor a server connecting changes the prompt ([Deferred tools](https://fzkuji.github.io/OpenProgram/docs/reference/design/function/deferred-tools.html#catalog)). `agent_loop` still receives the full list.
3. Before each provider call, `split_tools_for_dispatch` keeps non-deferred tools and the ones the request's own messages loaded (`loaded_tools(messages)`: load records on tool results, names a compaction summary carries) for `tools=[]`.
4. On a `ToolCall`, `agent_loop` finds the tool in `context.tools` or `_registry`, validates arguments, and awaits `execute(call_id, args, cancel, on_update)`.
5. `tool_search(select="cron")` loads `cron`: the next request carries its schema, because the search's result records each loaded tool's definition (`details.loads`, `record_loads`), so the history keeps what the model was first sent. A Responses provider that sends the loader natively carries it in the search's result rather than in `tools=[]` ([Codex transport](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/requests/codex-transport.html#deferred-tools)).

**Where each piece lives**

| File | Holds |
| --- | --- |
| `openprogram/programs/_host/runtime.py` | `_registry` (layer 2 source), `_toolset_membership`, `_unsafe_in_channel`, `filter_for`, `_build_and_register_tool`, `function`, `_parse_docstring`, `_build_parameters_schema`, `_evaluate_approval`, `tool_requires_approval`, `_TailAccumulator`, `loaded_tools`, `record_loads`, `split_tools_for_dispatch`, `deferred_catalog_text`, `tool_search` |
| `openprogram/programs/_host/execution.py` | `_normalize_result` (never cuts), `with_cap`, `_persist_full_result` |
| `openprogram/programs/_authoring/helpers.py` | `is_available_agent_tool`: layer 4 |
| `openprogram/programs/__init__.py` | `DEFAULT_TOOLS`, `TOOLSETS`, `agent_tools`, `apply_tool_policy`, `get_agent_tool`, `list_registered_agent_tools`, `list_available`; imports every subpackage so tools register |
| `openprogram/programs/tools/<group>/<name>/` | One `@function` per leaf tool |
| `openprogram/programs/applications/*/__init__.py` | Agent method modules |
| `openprogram/runtime/agent/agent_class.py` | `Agent`, method scopes, `method_options`, registration |
| `openprogram/runtime/agent/agent_method.py` | `MethodOptions`, execution, schema, registration |
| `openprogram/runtime/agent/call_state.py` | Task-local call identity, runtime injection, cancellation hooks |
| `openprogram/runtime/agent/call_scope.py` | Scope entry and exit, Context and DAG state |
| `openprogram/runtime/conversation/turn_runtime/` | `turn_context.py` installs deferred state; `loop_runner.py` resolves tools; layers 2 to 5, catalog block |
| `openprogram/runtime/agent/loop/streaming.py` | Per-provider-call `split_tools_for_dispatch`: layer 6 enforcement |

**Test invariants**

`tests/unit/programs/runtime/test_tools_runtime.py`, `tests/component/agent/turns/test_dispatcher_tools.py`:

- Docstring and signature to parameter schema; sync and async dispatch; exception to `AgentToolResult(is_error=True)`
- The declared cap recorded, and the loop bounding once with the whole text kept; `on_update` delivery and tail accumulator; cancel propagation; `asyncio.wait_for` timeout; `requires_approval`
- Registry filter by toolset, source, names; all shipped tools register on import; `@function` overrides
- Layer 1 skips registration on False or exception
- Layer 6 sidecar, `tool_search` promotion, unknown names, catalog text
- Agent method registers only with explicit `tool=True` or `as_tool=True`; `tool=False` skips the registry; `register_globally=False` skips it but attaches `_agent_tool`; `available_if` False skips registration, keeps scope handling

## Stable boundary

| Leaves the boundary alone | Would touch it; defer unless necessary |
| --- | --- |
| New `@function` tools; Agent methods with `tool=True`; `expose=False`; a named subset in `TOOLSETS` or a Functions-page folder; `defer` and `available_if`; wiring MCP servers and plugins | A new gating layer; a changed `AgentTool.execute` signature; splitting or merging the registry; replacing deferred loading |

## Implementation status

Built: registry, six layers, `@function` and Agent method registration, four knobs, Agent profile choice (Access preset), profile storage and the `/api/tool-profiles` endpoints. Not built: the Programs-page profile manager UI.

[Tool guides](https://fzkuji.github.io/OpenProgram/docs/reference/design/function/tool-guides.html)
