Skip to content

Tools, Safety, and Human Approval

Tools give a MemAgent authority outside the model. Treat their Python callable, schema, credentials, and approval policy as host code—not prompt content.

The examples use environment-backed model credentials. Later snippets assume the provider and tool functions created by your application are still in scope.

Register a typed tool

Type annotations and defaults become a strict JSON Schema. Keep the function small, return JSON-serializable data, and describe the contract in its docstring.

from typing import Literal

from memorizz import MemAgentBuilder, governed_tool


@governed_tool(deterministic=True, domains=("inventory",))
def inventory_lookup(
    sku: str,
    warehouse: Literal["london", "new-york"] = "london",
) -> dict:
    """Return current inventory for one SKU and warehouse."""
    return {"sku": sku, "warehouse": warehouse, "available": 12}


agent = (
    MemAgentBuilder()
    .with_llm_config({"provider": "openai", "model": "gpt-4o-mini"})
    .with_tools([inventory_lookup])
    .build()
)

MemoRizz rejects undeclared arguments and binds the Python signature before dispatch. Never accept arbitrary shell, SQL, path, URL, or Python text unless a separate policy validates and confines it.

Classify side effects explicitly

from memorizz import governed_tool


@governed_tool(
    deterministic=False,
    side_effects=True,
    requires_approval=True,
    approval_reason="Creates a customer in the production CRM",
    domains=("crm",),
)
def create_customer(name: str, email: str) -> dict:
    """Create one CRM customer after host approval."""
    return application_crm.create_customer(name=name, email=email)

Replace application_crm with a least-privileged client supplied by your host application; never let the model construct that client or its credentials.

Side-effecting tools bypass semantic-cache admission. The model never receives an approved or confirm argument.

Reuse results of repeated calls

A slow or rate-limited read can opt in to the MemAgent tool cache, so a repeated call with the same arguments reuses a fresh result instead of running again:

@governed_tool(cacheable=True, cache_ttl_seconds=600, domains=("orders",))
def lookup_order(order_id: str) -> dict:
    """Look up an order's status, carrier and dates."""
    return orders_api.get(order_id)

Enable the cache on the agent with tool_cache=True or .with_tool_cache(). Only a deterministic tool without side effects or approval can be cacheable. See Tool call cache.

Durable approval lifecycle

When a governed tool requires approval, agent.run() pauses with an exact, serializable proposal. A trusted host decides it and resumes the stored checkpoint:

pending = agent.list_approval_proposals(status="pending")
proposal_id = pending[0]["proposal_id"]

agent.approve(
    proposal_id,
    approver_id="operator@example.com",
    reason="Customer and destination reviewed",
)
result = agent.resume_approval(proposal_id, continue_model=False)

print(result.proposal)
print(result.tool_result)
print(result.consumed)  # True; the proposal cannot be reused

The host may instead call reject() or cancel_approval(). Proposals bind the tool name, exact arguments, argument hash, policy reason, owner, thread and checkpoint, expiry, approver identity, and audit time.

A rejection by itself leaves the run paused. To let the model react in the same run, hand the rejection back as the result of the call it asked for:

agent.reject(proposal_id, approver_id="owner", reason="I will go after all.")
result = agent.resume_rejection(proposal_id)

print(result.tool_result)         # {"status": "rejected", "reason": "I will go after all.", ...}
print(result.assistant_response)  # the model's reply to the refusal
print(result.consumed)            # False; nothing was executed

The model receives the approver's reason and is told not to make the call again unless asked. A rejection is handed back once.

What the conversation keeps. A turn that pauses stores a one-line waiting note as its reply ("[Waiting for approval] ... (proposal ...)"), not the proposal. When the proposal is approved and resumed, or rejected, the note is replaced by what happened: the model's reply, or a line saying the call ran, failed or was rejected. Later turns, in this thread or another, therefore never read a decided proposal as still waiting.

Several guarded calls in one turn. The first one pauses and the others are held back. After the resume the model is told the held calls did not run and may be made now; each then pauses for its own approval.

Progressive disclosure

Large toolboxes should not send every schema on every turn. Attach a deterministic Toolbox and let the semantic router select a scoped top-k set:

from memorizz import ContextPolicy, MemAgentBuilder, Toolbox

toolbox = Toolbox.from_functions(
    [inventory_lookup, create_customer],
    memory_provider=provider,
    agent_id="operations-agent",
    augment=False,
)

agent = (
    MemAgentBuilder()
    .with_name("Operations")
    .with_memory_provider(provider)
    .with_tools([inventory_lookup, create_customer])
    .with_toolbox(toolbox)
    .with_context_policy(ContextPolicy(tool_top_k=4))
    .build_and_save()
)

The model receives stable discovery/invocation handles plus the selected strict schemas. Scope and allowlists are applied before top-k retrieval. Trusted callables are rebound from an explicit registry or reviewed import reference; MemoRizz never unpickles executable code.

Offer no tool to an unrelated request

Routing offers the tool_top_k closest tools however far they are, so a request unrelated to every tool is still offered some. Set tool_min_similarity to the least cosine similarity a tool needs:

ContextPolicy(tool_top_k=2, tool_min_similarity=0.25)

A tool below it is not offered, and keyword matching doesn't bring it back. Good values depend on the embedding model and how tools are described, so measure a few requests with agent.semantic_tool_router.preview(request) and the scores from toolbox.get_most_similar_tools(request). With all-MiniLM-L6-v2 and five travel tools, relevant requests scored 0.28 to 0.55 against the right tool, and "Find me a direct flight to Lisbon" scored 0.24 against the closest one, so 0.25 left it with no tools. The cut-off applies when routing picks tools, not when every tool is sent (see stable_tool_list_tokens).

Let a decision model pick the tool

Ranking by meaning puts the closest topic first: for "Send the Q3 report to Sarah" the report tool outranks the email tool. With ContextPolicy(tool_selection=True), a decision model picks from the five closest tools, or none, and only that tool is offered (the runner-up too when it is within tool_selection_margin, 0.15).

Large tool results

from memorizz import ToolResultPolicy

agent = (
    MemAgentBuilder()
    .with_tool_result_policy(
        ToolResultPolicy(offload_above_chars=8_000)
    )
    .build()
)

Small results stay inline. Large results are stored once and replaced by an auditable pointer containing a digest and identifiers. Expansion tools are never re-offloaded, preventing pointer-to-pointer loops.

Report structured tool outcomes

A tool can complete without producing a clean primary-provider success. Use a ToolResult when the host knows that execution was empty, degraded, or served by a fallback:

from memorizz import ToolOutcome, ToolOutcomeStatus, ToolResult


def inventory_lookup(sku: str) -> ToolResult:
    try:
        return ToolResult(
            primary_inventory.lookup(sku),
            ToolOutcome(
                status=ToolOutcomeStatus.SUCCESS,
                provider="primary_inventory",
                result_count=1,
            ),
        )
    except TimeoutError:
        rows = inventory_replica.lookup(sku)
        return ToolResult(
            rows,
            ToolOutcome(
                status=ToolOutcomeStatus.FALLBACK,
                reason_code="primary_timeout",
                primary_provider="primary_inventory",
                fallback_provider="inventory_replica",
                retryable=True,
                result_count=len(rows),
            ),
        )

MemoRizz unwraps the value before sending it to the model. The tool's existing result schema therefore stays unchanged, while the SDK, CLI, MCP server, UI, trace analyzer, and learning control plane receive content-free outcome evidence. Non-clean outcomes bypass semantic-cache admission for that turn, so an empty, degraded, fallback, or failed provider response is not replayed later as though it were a clean primary-provider success.

Outcome Meaning Counts as usable
success Primary path completed normally Yes
empty A read completed but returned no records Yes
degraded The result is usable with reduced capability Yes
fallback A usable alternate path completed the operation Yes
provider_error No provider path produced a usable result No
error A non-provider execution or validation failure No

Fallback and degradation can coexist. status="fallback" remains the primary display state while degraded=True preserves the quality signal. Do not label an unavailable-provider placeholder as a successful fallback: if the user's operation was not satisfied, return provider_error.

Legacy tools do not have to change immediately. MemoRizz safely recognizes ok: false, success: false, structured error codes, empty results/items/ matches collections, and existing fallback_used/degraded retrieval diagnostics. It does not infer outcomes from arbitrary prose.

After a turn, trusted SDK hosts can inspect the same evidence:

for outcome in agent.last_tool_outcomes:
    print(outcome["tool_name"], outcome["status"], outcome.get("reason_code"))

The per-turn tool-call limit

A turn runs at most ContextPolicy.max_tool_invocations_per_turn tool calls (20 by default). Calls past the limit do not run. A message with 25 facts to save, for example, saves 20 and leaves 5.

The turn reports this in three places:

  • agent.last_turn_limits after the turn:

    agent.run("remember these 25 facts")
    limits = agent.last_turn_limits
    # {"tool_budget_exhausted": True, "refused_tool_calls": 5,
    #  "refused_tools": {"save_fact": 5}, "tool_call_limit": 20}
    
  • each refused call in agent.last_tool_outcomes, with reason_code="tool_budget_exhausted";

  • the turn's turn_result trace event, with tool_budget_exhausted=true, refused_tool_calls and tool_call_limit. The Dashboard's Needs attention list names the cause for the tool whose calls were refused.

The model is told too. The results of a turn's last three allowed calls carry a short note with the calls left, so the model can combine the remaining work into fewer calls. A refused call tells the model it did not run, so the model can say what is still to do. The note is added to the newest tool result only, so the cached prompt prefix does not change.

To allow more calls, raise the limit:

agent = MemAgent(..., context_policy=ContextPolicy(max_tool_invocations_per_turn=40))

Choose the right execution boundary

Need Capability Boundary
Call a typed application function Python tool Your application process
Call Notion, Calendar, or another MCP service MCP client Remote/local MCP server plus durable mutation gate
Navigate websites Browser control Isolated Browser Use process plus approval
Operate the apps on a Mac Desktop control macOS Accessibility permission plus approval for every action
Execute code Sandbox Provider-specific; read each security contract

Approval limits when authority is exercised. It does not make untrusted code, web content, or credentials safe. Apply least privilege and input validation at the underlying boundary.