> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rasen.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rasen.ai/_mcp/server.

# Add a before-call tool

> Add a webhook that the platform calls while an inbound call rings, so the agent starts the call with its answer in the prompt.

## Summary

A before-call tool is a webhook that the platform sends while an inbound call rings, and its
response goes into the agent's system prompt. This guide
adds a before-call tool to an agent's draft and publishes the agent. It does not cover tools that
the model calls during the call; see [Tools and MCP servers](/guides/tools).

## Facts

| Item                                   | Value                                                                                                                                 |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Operations                             | `getAgentDraft`, `createAgentTool`, `publishAgent`                                                                                    |
| Paths                                  | `GET /agents/{agent_id}/draft`, `POST /agents/{agent_id}/tools`, `POST /agents/{agent_id}/publish`                                    |
| Related operations                     | `listAgentTools`, `validateAgentTool`, `replaceAgentTool`, `deleteAgentTool`                                                          |
| Capability                             | `config.read` for reads; `tools.write` for tool writes, and `secrets.read` for a secret header reference; `agents.publish` to publish |
| Required headers                       | `Authorization` on every request; `Idempotency-Key` and `If-Match` with the draft ETag on `createAgentTool` and `publishAgent`        |
| Field that makes it a before-call tool | `"timing": "pre_call"` in the tool body. An omitted `timing` on create is `during_call`                                               |
| When it runs                           | Inbound calls only, one time while the phone rings. It does not run on outbound calls or browser test calls                           |
| Tools for each agent                   | At most one before-call tool                                                                                                          |
| Kind                                   | `webhook` only                                                                                                                        |
| Parameter `source`                     | `constant` or `dynamic_variable`. A `model` parameter is refused, because no model runs before the call                               |
| `side_effect`, `retry_posture`         | Both `none`: a lookup with no automatic retry                                                                                         |
| `deadline_ms`                          | 500 to 10000; 3000 when omitted                                                                                                       |
| `max_response_bytes`                   | At most 4096; 4096 when omitted                                                                                                       |
| Omitted limits                         | Take the before-call defaults, not the during-call ones                                                                               |
| `wait_for_response`                    | `true`                                                                                                                                |
| Name                                   | Not an agent variable, `agent_name` or `language`, and not starting with `system__`                                                   |
| Caller number                          | The dynamic variable `system__caller_id`, as a `dynamic_variable` parameter value                                                     |
| Prompt placement                       | At the `{{<tool name>}}` placeholder in the system prompt, or at the end of the prompt without one                                    |
| First message                          | One field with a fallback: `{{<tool name>.<path>\|<fallback>}}`                                                                       |
| Environment                            | `RASEN_API_BASE` (the base URL, ending in `/v1`), `RASEN_API_KEY`, `AGENT_ID`, `SECRET_ID`, `ETAG`                                    |
| Python                                 | 3.10 or later, with the `httpx` package                                                                                               |
| TypeScript                             | Node.js 22 or later (built-in `fetch`)                                                                                                |

## Steps

Set `AGENT_ID` to the `id` of the agent that answers your inbound number. `listAgents` lists the
agents of the workspace, and [Route phone calls](/guides/phone-numbers) assigns an agent to a
number. Set `SECRET_ID` to the `id` of a secret with `purpose` `webhook_tool` that holds the API key
of your lookup service ([Secrets and rotation](/guides/secrets)).

### 1. Read the draft ETag

**`curl`**

```bash curl
curl --fail-with-body -sS -i "$RASEN_API_BASE/agents/$AGENT_ID/draft" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]

response = httpx.get(f"{BASE}/agents/{AGENT_ID}/draft", headers={"Authorization": f"Bearer {KEY}"})
response.raise_for_status()
print(response.headers["ETag"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/draft`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.headers.get("ETag"));
```

Set `ETAG` to the `ETag` of the answer, including its quotes. It is the draft revision that the
next write needs in `If-Match`.

### 2. Add the before-call tool

This tool sends the caller's number to your lookup service as the `phone` query parameter, from
the dynamic variable `system__caller_id`. It sends the API key of the service from the secret in
the `X-Api-Key` header. It omits `deadline_ms` and `max_response_bytes`, so it takes the
before-call defaults: 3000 ms and 4096 bytes.

**`curl`**

```bash curl
curl --fail-with-body -sS -i -X POST "$RASEN_API_BASE/agents/$AGENT_ID/tools" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "lookup_caller",
    "description": "Look up the caller by phone number.",
    "kind": "webhook",
    "timing": "pre_call",
    "side_effect": "none",
    "retry_posture": "none",
    "definition": {
      "url": "https://api.example.com/callers",
      "method": "GET",
      "parameters": [
        {"name": "phone", "location": "query", "source": "dynamic_variable",
         "value": "system__caller_id", "schema": {"type": "string"}}
      ],
      "headers": [
        {"name": "X-Api-Key", "value_type": "secret",
         "credential": {"secret_id": "'"$SECRET_ID"'", "version": 1}}
      ]
    }
  }'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
ETAG = os.environ["ETAG"]
SECRET_ID = os.environ["SECRET_ID"]

tool = {
    "name": "lookup_caller",
    "description": "Look up the caller by phone number.",
    "kind": "webhook",
    "timing": "pre_call",
    "side_effect": "none",
    "retry_posture": "none",
    "definition": {
        "url": "https://api.example.com/callers",
        "method": "GET",
        "parameters": [
            {
                "name": "phone",
                "location": "query",
                "source": "dynamic_variable",
                "value": "system__caller_id",
                "schema": {"type": "string"},
            }
        ],
        "headers": [
            {
                "name": "X-Api-Key",
                "value_type": "secret",
                "credential": {"secret_id": SECRET_ID, "version": 1},
            }
        ],
    },
}

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/tools",
    headers={
        "Authorization": f"Bearer {KEY}",
        "Idempotency-Key": str(uuid.uuid4()),
        "If-Match": ETAG,
    },
    json=tool,
)
response.raise_for_status()
print(response.headers["ETag"])
created = response.json()
print(created["id"], created["configuration"].get("timing"))
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, ETAG, SECRET_ID } = process.env;

const tool = {
  name: "lookup_caller",
  description: "Look up the caller by phone number.",
  kind: "webhook",
  timing: "pre_call",
  side_effect: "none",
  retry_posture: "none",
  definition: {
    url: "https://api.example.com/callers",
    method: "GET",
    parameters: [
      { name: "phone", location: "query", source: "dynamic_variable", value: "system__caller_id", schema: { type: "string" } },
    ],
    headers: [
      { name: "X-Api-Key", value_type: "secret", credential: { secret_id: SECRET_ID, version: 1 } },
    ],
  },
};

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/tools`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": ETAG!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify(tool),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.headers.get("ETag"));
const created = await response.json();
console.log(created.id, created.configuration.timing);
```

The `201` answer is the tool. Its `configuration` has `"timing": "pre_call"`, `"deadline_ms": 3000`
and `"max_response_bytes": 4096`. Set `ETAG` to the `ETag` of the answer: adding the tool changed
the draft revision.

The response body of your service goes into the system prompt as data, so the agent knows the
caller from its first sentence. Put the placeholder `{{lookup_caller}}` in the prompt where the data
belongs; without it, the data goes at the end of the prompt. The first message can name one field
of the response with a fallback, for example `Hi {{lookup_caller.name|there}}`. Edit the prompt and the first message as in
[Build and publish an agent](/guides/agents#4-edit-the-draft).

### 3. Publish the agent

**`curl`**

```bash curl
curl --fail-with-body -sS -X POST "$RASEN_API_BASE/agents/$AGENT_ID/publish" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
ETAG = os.environ["ETAG"]

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/publish",
    headers={
        "Authorization": f"Bearer {KEY}",
        "Idempotency-Key": str(uuid.uuid4()),
        "If-Match": ETAG,
    },
)
response.raise_for_status()
publication = response.json()
print(publication["version"]["id"], publication["live_version_id"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, ETAG } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/publish`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": ETAG!,
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const publication = await response.json();
console.log(publication.version.id, publication.live_version_id);
```

The tool runs on inbound calls that start after the publish. Calls already admitted keep their
version. The version's `tools` list holds the before-call tool with `"timing": "pre_call"`.

## Rules

* MUST send `"timing": "pre_call"` to make a before-call tool. An omitted `timing` on create makes a
  during-call tool; an omitted `timing` on replace keeps the stored timing.
* A replace that sends `timing` moves the tool between `during_call` and `pre_call`. The tool MUST
  then meet the rules of its new timing.
* MUST NOT send `timing` on an MCP tool write: only a webhook tool runs before the call. The API
  refuses it with `400 invalid_request`.
* MUST NOT give a before-call tool a parameter with `source` `model`.
* MUST send `side_effect` `none` and `retry_posture` `none`. The platform sends the request one
  time and never retries it.
* MUST keep `deadline_ms` from 500 to 10000 and `max_response_bytes` at most 4096. A value outside
  100 to 30000 ms or 256 to 65536 bytes is `400 invalid_request` for every tool, before the
  before-call bounds apply.
* MUST NOT name the tool after an agent variable, `agent_name` or `language`, or start its name
  with `system__`.
* MUST NOT send a body from a `GET` or `DELETE` tool. Put its values in the query or the path.
* MUST send `"timing": "pre_call"` to `validateAgentTool` to check a before-call tool. An omitted
  `timing` is checked as a during-call tool.
* A slow or failed request does not stop the call: the agent answers without the data.

## Verify

```bash
curl --fail-with-body -sS "$RASEN_API_BASE/agents/$AGENT_ID/tools" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

Expected output: the tool from step 2, with `"timing": "pre_call"` in its `configuration`.

```json
{"items": [{"id": "tool_01j00000000000000000000000", "agent_id": "agent_01j00000000000000000000000", "configuration": {"name": "lookup_caller", "kind": "webhook", "timing": "pre_call", "side_effect": "none", "retry_posture": "none", "deadline_ms": 3000, "max_response_bytes": 4096}}], "next_cursor": null}
```

After an inbound call, [Read tool call logs](/guides/tool-call-logs) shows the run of the tool with
`"timing": "pre_call"` and no model arguments.

## Errors

| Code                           | Cause                                                                                                                                                                 | Fix                                                                                                                    |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `tool_pre_call_exists`         | The agent already has a before-call tool.                                                                                                                             | Replace or delete that tool, or send `"timing": "during_call"`.                                                        |
| `tool_pre_call_llm_parameter`  | A parameter has `source` `model`. `details.index` names the parameter.                                                                                                | Use `constant` or `dynamic_variable`.                                                                                  |
| `tool_pre_call_side_effect`    | `side_effect` or `retry_posture` is not `none`. `details.field` names the field.                                                                                      | Send `none` for both.                                                                                                  |
| `tool_pre_call_bounds`         | `deadline_ms`, `max_response_bytes` or `wait_for_response` is outside the before-call bounds. `details.field` names it, with `details.minimum` and `details.maximum`. | Send a `deadline_ms` from 500 to 10000, a `max_response_bytes` of at most 4096 and `wait_for_response` `true`.         |
| `tool_pre_call_name`           | The name is an agent variable, `agent_name` or `language`, or starts with `system__`. On `publishAgent`, a variable of the draft has the tool's name.                 | Rename the tool or the variable.                                                                                       |
| `tool_body_on_get_or_delete`   | A `GET` or `DELETE` tool has body parameters or puts its effect ID in the body. On `publishAgent`, `details.name` names the tool.                                     | Move the body values to the query or the path, and the effect ID to a header.                                          |
| `tool_name_conflict`           | Another tool of the draft has this name.                                                                                                                              | Use another name.                                                                                                      |
| `draft_conflict`               | The draft changed after you read its ETag.                                                                                                                            | Read the draft again (step 1), then send the request with the new ETag.                                                |
| `outbound_destination_refused` | The URL names a private address.                                                                                                                                      | Use a public HTTPS URL.                                                                                                |
| `invalid_request`              | An MCP tool write sent `timing`, or a limit is outside the bounds of every tool.                                                                                      | Send `timing` only on a webhook tool. Keep `deadline_ms` from 100 to 30000 and `max_response_bytes` from 256 to 65536. |
| `credential_unavailable`       | The secret version is revoked or destroyed, belongs to another workspace, or has another `purpose`.                                                                   | Use a releasable version of a `webhook_tool` secret.                                                                   |
| `forbidden`                    | The key lacks `tools.write`, `secrets.read` or `agents.publish`. `details.required_capabilities` lists them.                                                          | Use a key with those capabilities.                                                                                     |

## Related

* [Tools and MCP servers](/guides/tools)
* [Build and publish an agent](/guides/agents)
* [Secrets and rotation](/guides/secrets)
* [Read tool call logs](/guides/tool-call-logs)
* [Route phone calls](/guides/phone-numbers)
* [Error codes](/concepts/error-codes)