Skip to content

00Integration guide

Claude: Agent SDK and API tool use

Record every tool call a Claude agent makes: hooks for the Claude Agent SDK, one call per tool_use block for the Messages API.

Walkthrough · recorded against a local Ovelin

Two ways to build a Claude agent, two places to record it:

  • Claude Agent SDK (@anthropic-ai/claude-agent-sdk): register PostToolUse and PostToolUseFailure hooks. They run in your process, outside the model's control, for every tool call, including built-in tools like Read and Bash.
  • Messages API with your own tools (anthropic): you run each tool_use block yourself, so record it right where you run it.

Either way only metadata is sent: tool name, input and duration. Tool output stays on your machine.

Prerequisites

  • An Anthropic API key in ANTHROPIC_API_KEY.
  • Node.js 22.6+ for the Agent SDK example; Python 3.10+ for the API example.
  • The Node or Python Ovelin client from the Node or Python guide.

1. Get an API key

  1. In Ovelin, open Settings → API keys.
  2. Under Ingest key, create a key and copy it. It is shown once; Ovelin keeps only a hash.
  3. Copy the Organization ID from the same page.

Put all three values in your environment, not in code:

sh
export OVELIN_URL="https://your-ovelin-host"   # http://localhost:3000 for a local instance
export OVELIN_ORG_ID="your-organization-id"
export OVELIN_API_KEY="agl_live_…"

An organization key can report for any agent. For production, give each agent its own key under Settings → API keys → Agent keys: a leaked agent key can then only write as that one agent, and you can revoke it alone.

2. Install

sh
npm install @anthropic-ai/claude-agent-sdk     # Agent SDK
pip install anthropic requests                  # Messages API

3a. Minimal working example: Claude Agent SDK

examples/node/claude-agent-sdk.ts
// A Claude Agent SDK agent whose every tool call is recorded in Ovelin.
//
// PostToolUse and PostToolUseFailure hooks run in the host process, outside
// the model's control: the agent cannot skip them. Only metadata is sent
// (tool name, input, duration); tool output never leaves your machine.
import { query, type HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { logEvent, RUN_ID } from "./ovelin.ts";

const AGENT = "docs-agent";

const recordSuccess: HookCallback = async (input) => {
  if (input.hook_event_name !== "PostToolUse") return {};
  await logEvent(AGENT, input.tool_name, {
    dataAccessed: ["internal_documents"],
    metadata: { tool_input: input.tool_input, duration_ms: input.duration_ms, claude_session: input.session_id },
  });
  return {};
};

const recordFailure: HookCallback = async (input) => {
  if (input.hook_event_name !== "PostToolUseFailure") return {};
  await logEvent(AGENT, input.tool_name, {
    outcome: "failure",
    metadata: { tool_input: input.tool_input, error: input.error, claude_session: input.session_id },
  });
  return {};
};

for await (const message of query({
  prompt: "Read README.md and summarize it in one sentence.",
  options: {
    model: "claude-opus-5-5",
    allowedTools: ["Read", "Glob"],
    settingSources: [], // ignore local settings files: this run is self-contained
    hooks: {
      PostToolUse: [{ hooks: [recordSuccess] }],
      PostToolUseFailure: [{ hooks: [recordFailure] }],
    },
  },
})) {
  if (message.type === "result") {
    console.log(message.subtype === "success" ? message.result : `Agent stopped: ${message.subtype}`);
  }
}
console.log(`Recorded in Ovelin under run ${RUN_ID}`);

claude_session in the metadata groups each Agent SDK session into one execution under Sessions.

3b. Minimal working example: Messages API tool use

examples/python/anthropic_tool_use.py
"""A Claude tool-use agent that records every tool call in Ovelin.

The agent loop is the Anthropic SDK's manual loop. Each tool call is logged
after it runs, with its arguments, its outcome and how long it took, so a
failed call is on the record too.
"""

import time

import anthropic

from ovelin import RUN_ID, log_event

AGENT = "billing-assistant"
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

tools = [
    {
        "name": "lookup_invoice",
        "description": "Look up an invoice by id. Returns status, amount and the customer's email.",
        "input_schema": {
            "type": "object",
            "properties": {"invoice_id": {"type": "string"}},
            "required": ["invoice_id"],
        },
    },
    {
        "name": "send_reminder",
        "description": "Email a payment reminder for an invoice.",
        "input_schema": {
            "type": "object",
            "properties": {"invoice_id": {"type": "string"}, "email": {"type": "string"}},
            "required": ["invoice_id", "email"],
        },
    },
]


def run_tool(name: str, args: dict) -> str:
    if name == "lookup_invoice":
        return f"{args['invoice_id']}: overdue, EUR 4,200, billing@example.com"
    if name == "send_reminder":
        return f"Reminder for {args['invoice_id']} sent to {args['email']}"
    raise ValueError(f"unknown tool {name}")


def run_and_record(block) -> dict:
    """Run one tool_use block, record it in Ovelin, return the tool_result."""
    started = time.monotonic()
    try:
        result, outcome = run_tool(block.name, block.input), "success"
    except Exception as exc:  # the failure is evidence too
        result, outcome = f"Error: {exc}", "failure"
    log_event(
        AGENT,
        block.name,
        outcome=outcome,
        actor="ops@example.com",
        data_accessed=["financial_data"],
        metadata={"tool_input": block.input, "duration_ms": round((time.monotonic() - started) * 1000)},
    )
    return {
        "type": "tool_result",
        "tool_use_id": block.id,
        "content": result,
        "is_error": outcome == "failure",
    }


messages = [{"role": "user", "content": "Invoice INV-1042 is overdue. Look it up and send a reminder."}]
while True:
    response = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
    if response.stop_reason == "end_turn":
        break
    messages.append({"role": "assistant", "content": response.content})
    tool_uses = [b for b in response.content if b.type == "tool_use"]
    messages.append({"role": "user", "content": [run_and_record(b) for b in tool_uses]})

print(next(b.text for b in response.content if b.type == "text"))
print(f"Recorded in Ovelin under run {RUN_ID}")

Recording happens after the tool runs and before the result goes back to Claude, so a tool that raises is still recorded, as failure.

4. Run it

sh
cd examples/node && node claude-agent-sdk.ts
cd examples/python && python anthropic_tool_use.py

5. Check it in Ovelin

  1. Open Activity. The newest rows are the events you just sent, each with a sequence number and a seal.
  2. Click one. The detail panel shows the payload as received; Recompute seal checks its seal again.
  3. One event per tool call: Read from the Agent SDK, lookup_invoice and send_reminder from the API example. Open Agents: an agent name Ovelin had not seen before is registered automatically, without an owner. Give it one so someone is accountable for it.

To confirm nothing was altered later, open Integrity. It recomputes every seal and every link between records, and reports Trail intact.

Common errors

ResponseCauseFix
401 Invalid API keyThe key is wrong, revoked, or belongs to another organization.Create a key in Settings → API keys and check OVELIN_ORG_ID is the same organization's.
401 Missing API key (use Authorization: Bearer <key>)The Authorization header was not sent.Send Authorization: Bearer $OVELIN_API_KEY. The key never goes in the body.
422 Payload must include a 'source' fieldThe JSON has no source.Add "source": "custom" (or n8n, make_com, openai_api, zapier).
422 Invalid option: expected one of "success"|"failure"|"unknown"outcome has another value, such as warning.Use success, failure or unknown.
400 Invalid organization idOVELIN_ORG_ID is not the organization's UUID.Copy the Organization ID from Settings → API keys.
429 Rate limit exceededMore than 600 events a minute for one organization.Retry after the Retry-After header. To send many events, use the batch endpoint (up to 100 per request).
No events, agent ran fineHooks registered under the wrong key, or the tool was denied before running.Keys are PostToolUse / PostToolUseFailure. Denied calls never run, so they never reach PostToolUse; add a PermissionDenied hook to record those.
Agent slower than beforeEach hook awaits one HTTP round trip.Hooks run inline. For high-volume agents, queue events and send them from a background task.

How this guide is tested

Every code block above is copied from examples/node/claude-agent-sdk.ts and examples/python/anthropic_tool_use.py by node scripts/sync-guide-snippets.mjs, and pnpm examples:test runs both against a local Ovelin and checks the events were sealed. The model is replaced by a local scripted stand-in (examples/_testing/scripted-model.mjs) that calls the tools in a fixed order, so the test needs no provider key; with a real key, unset ANTHROPIC_BASE_URL/OPENAI_BASE_URL and the same code talks to the provider.