> This is a page from the ElevenLabs documentation. For an index of the documentation, fetch https://elevenlabs.io/docs/llms.txt.

# Tools as code

## Overview

A [tool](/docs/eleven-agents/customization/tools) is stored as a config with nested JSON schemas for its parameters. Writing that config by hand means you have to keep path parameters in step with the URL, `required` lists in step with their properties, and give every parameter exactly one value source. The tool builder in the Python and JavaScript SDKs lets you describe the same tool with chained method calls. It then produces the request that `tools.create()` and `tools.update()` already accept.

Use it to:

* Define webhook, client and system tools in code and review them like any other code change.
* Load a tool, change one parameter, and push it back without disturbing the rest of its config.
* Store tools as JSON in version control and validate them in CI.

> **Note**
>
> The builder runs entirely in the SDK. It calls no new API endpoints, and anything it builds can be
> opened and edited in the dashboard.

## Requirements

* Python: the `elevenlabs` package. The builder is imported from `elevenlabs.agent_tools`.
* JavaScript: the `@elevenlabs/elevenlabs-js` package. The builder is exported from the package root.

## Build a webhook tool

`Tool.webhook(name, description)` starts a [webhook tool](/docs/eleven-agents/customization/tools/webhook-tools). The name and description are what the LLM sees when it decides whether to call the tool. This example looks up an order by the number the caller gives, sends an API key from the workspace's secrets, and stores the order's status in a dynamic variable:

```python
from elevenlabs import ElevenLabs
from elevenlabs.agent_tools import Header, Schema, Tool

elevenlabs = ElevenLabs()

get_order = (
    Tool.webhook("get_order", "Look up an order by the number the caller gives")
    .get("https://api.example.com/orders/{order_id}")
    .path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
    .query_param("include", Schema.string().constant("items"))
    .header("Authorization", Header.secret("sec_orders_api"))
    .assign("order_status", "order.status")
    .options(response_timeout_secs=10)
)

tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())
```

```typescript
import { ElevenLabsClient, Header, Schema, Tool } from "@elevenlabs/elevenlabs-js";

const elevenlabs = new ElevenLabsClient();

const getOrder = Tool.webhook("get_order", "Look up an order by the number the caller gives")
  .get("https://api.example.com/orders/{order_id}")
  .pathParam("order_id", Schema.string().describe("The order number, e.g. A-1042"))
  .queryParam("include", Schema.string().constant("items"))
  .header("Authorization", Header.secret("sec_orders_api"))
  .assign("order_status", "order.status")
  .options({ responseTimeoutSecs: 10 });

const tool = await elevenlabs.conversationalAi.tools.create(getOrder.build());
```

The request methods set the HTTP method and URL. `{name}` placeholders in the URL are filled from path parameters:

| Python                                                           | JavaScript                 | Sets                                                                                                                  |
| ---------------------------------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `get(url)`, `post(url)`, `put(url)`, `patch(url)`, `delete(url)` | same                       | The method and URL. `POST`, `PUT` and `PATCH` need a body; `GET` can't have one.                                      |
| `path_param(name, schema)`                                       | `pathParam(name, schema)`  | A path parameter, for the `{name}` placeholder in the URL.                                                            |
| `query_param(name, schema)`                                      | `queryParam(name, schema)` | A query parameter.                                                                                                    |
| `body(schema)`                                                   | `body(schema)`             | The request body. Must be an object schema.                                                                           |
| `response(schema)`                                               | `response(schema)`         | The response body schema. Must be an object schema.                                                                   |
| `header(name, value)`                                            | `header(name, value)`      | A request header. See [Headers and authentication](#headers-and-authentication).                                      |
| `auth(connection)`                                               | `auth(connection)`         | The [auth connection](/docs/eleven-agents/customization/tools/webhook-tools#supported-authentication-methods) to use. |
| `assign(variable, path)`                                         | `assign(variable, path)`   | Stores the value at `path` in the response (dot notation) in a dynamic variable.                                      |

Setting a parameter or header whose name already exists replaces it and keeps its position. `remove_path_param()`, `remove_query_param()`, `remove_header()` and `remove_assignment()` (`removePathParam()` and so on in JavaScript) take one out. Parameter names must be unique across the path, query and body.

A body is an object schema built property by property:

```python
refund = (
    Tool.webhook("issue_refund", "Refund an order the caller asked to return")
    .post("https://api.example.com/refunds")
    .body(
        Schema.object()
        .property("order_id", Schema.string().from_variable("order_id"))
        .property(
            "reason",
            Schema.string().describe("Why the caller wants a refund").choices(["damaged", "late", "other"]),
        )
        .property("note", Schema.string().describe("Anything else the caller said").optional())
    )
)
```

```typescript
const refund = Tool.webhook("issue_refund", "Refund an order the caller asked to return")
  .post("https://api.example.com/refunds")
  .body(
    Schema.object()
      .property("order_id", Schema.string().fromVariable("order_id"))
      .property(
        "reason",
        Schema.string()
          .describe("Why the caller wants a refund")
          .choices(["damaged", "late", "other"])
      )
      .property("note", Schema.string().describe("Anything else the caller said").optional())
  );
```

## Parameter schemas

`Schema` builds the parameter schemas that webhook and client tools use. Every method returns a new schema and leaves the one it was called on unchanged, so you can define a schema once and use it in several tools.

| Constructor                                                               | Builds                                           |
| ------------------------------------------------------------------------- | ------------------------------------------------ |
| `Schema.string()`, `Schema.integer()`, `Schema.number()`, `Schema.bool()` | A literal value                                  |
| `Schema.object()`                                                         | An object. Add properties with `property()`.     |
| `Schema.array(items)`                                                     | An array whose elements match the `items` schema |

### Where a value comes from

Every literal needs exactly one value source, wherever it appears: in a parameter, in a body, in a response schema, or inside an object or array. An object or array can have one too, which then supplies the whole value.

| Python                | JavaScript           | The value                                                                                                                  |
| --------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `describe(text)`      | `describe(text)`     | Is provided by the LLM, guided by `text`.                                                                                  |
| `from_variable(name)` | `fromVariable(name)` | Is read from a [dynamic variable](/docs/eleven-agents/customization/personalization/dynamic-variables) when the tool runs. |
| `constant(value)`     | `constant(value)`    | Is always `value`.                                                                                                         |
| `system_provided()`   | `systemProvided()`   | Is filled in by the system when the tool runs. Literals only.                                                              |
| `omit()`              | `omit()`             | Is left out of the request. Only for an optional property.                                                                 |

On an object or array, `describe()` documents the container for the LLM, and each property or element still has its own source.

### Other schema methods

| Python                                            | JavaScript                                    | Does                                                                                        |
| ------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `optional()`                                      | `optional()`                                  | Makes a property optional. Properties are required unless marked optional.                  |
| `choices(values)`                                 | `choices(values)`                             | Limits a string to a fixed set of values, which the LLM picks from.                         |
| `allowed_from(variable)`                          | `allowedFrom(variable)`                       | Rejects an LLM value that isn't in the list held by a dynamic variable. Needs `describe()`. |
| `property(name, schema)` / `without(name)`        | `property(name, schema)` / `without(name)`    | Adds, replaces or removes an object property. A replaced property keeps its position.       |
| `require_any_of(names)` / `require_all_of(names)` | `requireAnyOf(names)` / `requireAllOf(names)` | Requires at least one, or all, of a group of optional properties.                           |

## Headers and authentication

A header value comes from one of four places. Use a secret or an environment variable for anything sensitive, so the value never appears in the tool config:

| Constructor                                      | The header value is                                                                                                            |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `Header.value(text)`                             | Fixed text.                                                                                                                    |
| `Header.secret(id)`                              | A secret from the workspace's secret store.                                                                                    |
| `Header.variable(name)`                          | A dynamic variable, read when the tool runs.                                                                                   |
| `Header.env_var(label)` / `Header.envVar(label)` | A workspace [environment variable](/docs/eleven-agents/integrate/environment-variables), resolved for the current environment. |

`AuthConnection.id(id)` uses an auth connection from the workspace by ID. `AuthConnection.env_var(label)` / `AuthConnection.envVar(label)` picks it from an environment variable, so the same tool config can use a different connection in each environment.

```python
from elevenlabs.agent_tools import AuthConnection, Header

update_profile = (
    Tool.webhook("update_profile", "Update the caller's email address")
    .put("https://api.example.com/profiles/{profile_id}")
    .path_param("profile_id", Schema.string().from_variable("profile_id"))
    .body(Schema.object().property("email", Schema.string().describe("The new email address")))
    .header("X-Api-Key", Header.env_var("profiles_api_key"))
    .auth(AuthConnection.env_var("profiles_oauth"))
)
```

```typescript
import { AuthConnection, Header } from "@elevenlabs/elevenlabs-js";

const updateProfile = Tool.webhook("update_profile", "Update the caller's email address")
  .put("https://api.example.com/profiles/{profile_id}")
  .pathParam("profile_id", Schema.string().fromVariable("profile_id"))
  .body(Schema.object().property("email", Schema.string().describe("The new email address")))
  .header("X-Api-Key", Header.envVar("profiles_api_key"))
  .auth(AuthConnection.envVar("profiles_oauth"));
```

## Build a client tool

`Tool.client(name, description)` starts a [client tool](/docs/eleven-agents/customization/tools/client-tools), which runs in your application instead of on a server. Add its parameters with `param(name, schema)`. Set `expects_response` / `expectsResponse` when the agent should wait for your application's result:

```python
show_map = (
    Tool.client("show_store_map", "Show the caller a map of the nearest store")
    .param("store_id", Schema.string().describe("The store to show"))
    .options(expects_response=False)
)
```

```typescript
const showMap = Tool.client("show_store_map", "Show the caller a map of the nearest store")
  .param("store_id", Schema.string().describe("The store to show"))
  .options({ expectsResponse: false });
```

## Build a system tool

[System tools](/docs/eleven-agents/customization/tools/system-tools) are built into the platform. Each has its own constructor on `SystemTool`, which takes that tool's settings:

| Python                                                  | JavaScript                                            |
| ------------------------------------------------------- | ----------------------------------------------------- |
| `SystemTool.end_call()`                                 | `SystemTool.endCall()`                                |
| `SystemTool.skip_turn(wait_timeout_secs=...)`           | `SystemTool.skipTurn({ waitTimeoutSecs })`            |
| `SystemTool.language_detection(...)`                    | `SystemTool.languageDetection(options?)`              |
| `SystemTool.play_keypad_touch_tone(...)`                | `SystemTool.playKeypadTouchTone(options?)`            |
| `SystemTool.voicemail_detection(voicemail_message=...)` | `SystemTool.voicemailDetection({ voicemailMessage })` |
| `SystemTool.knowledge_base(enabled_strategies=...)`     | `SystemTool.knowledgeBase({ enabledStrategies })`     |
| `SystemTool.transfer_to_number(...)`                    | `SystemTool.transferToNumber(options?)`               |
| `SystemTool.transfer_to_agent()`                        | `SystemTool.transferToAgent()`                        |

The two transfer tools take their destinations from `transfer(condition, destination, options)`. The condition tells the LLM when to transfer there, and the destination uses the same `Destination` as [workflows as code](/docs/eleven-agents/customization/agents-as-code/workflows#transfer-destinations). A transfer to a SIP URI needs a SIP REFER transfer:

```python
from elevenlabs.agent_tools import SystemTool
from elevenlabs.agent_workflows import Destination

transfer = (
    SystemTool.transfer_to_number()
    .transfer("Caller asks for billing", Destination.phone("+15551234567"))
    .transfer("Caller is a reseller partner", Destination.sip("sip:partners@pbx.example.com"), transfer_type="sip_refer")
)

to_sales = SystemTool.transfer_to_agent().transfer(
    "Caller wants to buy something", Destination.agent("agent_sales"), transfer_message="Connecting you to sales"
)
```

```typescript
import { Destination, SystemTool } from "@elevenlabs/elevenlabs-js";

const transfer = SystemTool.transferToNumber()
  .transfer("Caller asks for billing", Destination.phone("+15551234567"))
  .transfer("Caller is a reseller partner", Destination.sip("sip:partners@pbx.example.com"), {
    transferType: "sip_refer",
  });

const toSales = SystemTool.transferToAgent().transfer(
  "Caller wants to buy something",
  Destination.agent("agent_sales"),
  { transferMessage: "Connecting you to sales" }
);
```

## Tool options

Settings shared by every kind of tool go in `options()`, as keyword arguments in Python and an object in JavaScript. Their names match the tool config's fields in the API:

| Applies to    | Python                                                                                                                                       | JavaScript                                                                                                                          |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| All tools     | `name`, `description`, `response_timeout_secs`, `interruption_mode`, `pre_tool_speech`, `tool_call_sound`, `tool_error_handling_mode`, ...   | `name`, `description`, `responseTimeoutSecs`, `interruptionMode`, `preToolSpeech`, `toolCallSound`, `toolErrorHandlingMode`, ...    |
| Webhook tools | `execution_mode`, `content_type`, `response_filter`, `follow_redirects`, `follow_redirects_allowed_domains`, `dynamic_variable_placeholders` | `executionMode`, `contentType`, `responseFilter`, `followRedirects`, `followRedirectsAllowedDomains`, `dynamicVariablePlaceholders` |
| Client tools  | `execution_mode`, `expects_response`, `dynamic_variable_placeholders`                                                                        | `executionMode`, `expectsResponse`, `dynamicVariablePlaceholders`                                                                   |

A webhook tool's response timeout is 5 to 300 seconds. A client tool's is 1 to 120 seconds, or -1 to wait as long as it takes, which needs `expects_response` / `expectsResponse`. `follow_redirects` / `followRedirects` needs a list of allowed domains.

## Attach tools to an agent

Webhook and client tools are created on their own with `tools.create()` and attached to agents by ID, so one tool can be shared by several agents. System tools are part of the agent's config: `build_config()` / `buildConfig()` returns the entry for the agent's built-in tools.

```python
from elevenlabs import AgentConfig, BuiltInToolsOutput, ConversationalConfig, PromptAgentApiModelOutput

order_tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())

agent = elevenlabs.conversational_ai.agents.create(
    name="Support line",
    conversation_config=ConversationalConfig(
        agent=AgentConfig(
            prompt=PromptAgentApiModelOutput(
                prompt="You are a support agent for Acme.",
                tool_ids=[order_tool.id],
                built_in_tools=BuiltInToolsOutput(
                    end_call=SystemTool.end_call().build_config(),
                    transfer_to_number=transfer.build_config(),
                ),
            )
        )
    ),
)
```

```typescript
const orderTool = await elevenlabs.conversationalAi.tools.create(getOrder.build());

const agent = await elevenlabs.conversationalAi.agents.create({
  name: "Support line",
  conversationConfig: {
    agent: {
      prompt: {
        prompt: "You are a support agent for Acme.",
        toolIds: [orderTool.id],
        builtInTools: {
          endCall: SystemTool.endCall().buildConfig(),
          transferToNumber: transfer.buildConfig(),
        },
      },
    },
  },
});
```

> **Warning**
>
> The agent's `prompt.tools` field, which holds tool configs inline, is deprecated. It can't be
> combined with `tool_ids`, and when a request includes it, the agent's built-in tools are replaced
> by the system tools it contains. Create tools with `tools.create()` and attach them by ID instead.

## Edit an existing tool

`Tool.from_response()` / `Tool.fromResponse()` loads a tool returned by `tools.get()`. Fields the builder doesn't model, and the defaults the API fills in, are kept, so pushing it back only changes what you changed. `as_webhook()`, `as_client()` and `as_system()` (`asWebhook()` and so on in JavaScript) give you the typed tool to edit, or `None` / `undefined` if it's another kind.

To change a body property, read the body schema, set the property again, and set the body:

```python
from elevenlabs.agent_tools import ObjectSchema

loaded = Tool.from_response(elevenlabs.conversational_ai.tools.get("tool_id")).as_webhook()
if loaded is None:
    raise ValueError("Not a webhook tool")

body = loaded.body_schema
assert isinstance(body, ObjectSchema)
loaded.body(body.property("reason", Schema.string().describe("Why the caller wants a refund")))
loaded.query_param("locale", Schema.string().describe("The caller's language").optional())

elevenlabs.conversational_ai.tools.update("tool_id", request=loaded.build())
```

```typescript
import { type ObjectSchema, Schema, Tool } from "@elevenlabs/elevenlabs-js";

const loaded = Tool.fromResponse(
  await elevenlabs.conversationalAi.tools.get("tool_id")
).asWebhook();
if (!loaded) throw new Error("Not a webhook tool");

const body = loaded.bodySchema as ObjectSchema;
loaded.body(body.property("reason", Schema.string().describe("Why the caller wants a refund")));
loaded.queryParam("locale", Schema.string().describe("The caller's language").optional());

await elevenlabs.conversationalAi.tools.update("tool_id", loaded.build());
```

## Store tools in version control

`to_json_string()` / `toJSONString()` writes the tool in the API's wire format: snake_case keys, sorted at every level, with 2-space indentation. It's the same shape the [CLI](/docs/eleven-agents/operate/cli) keeps in its `tool_configs/` directory, and both SDKs write byte-for-byte identical files for the same tool, so diffs stay small. `Tool.from_json()` / `Tool.fromJSON()` reads it back.

```python
from pathlib import Path

from elevenlabs.agent_tools import Tool

Path("tool_configs/get_order.json").write_text(get_order.to_json_string())

stored = Tool.from_json(Path("tool_configs/get_order.json").read_text())
elevenlabs.conversational_ai.tools.update("tool_id", request=stored.build())
```

```typescript
import { Tool } from "@elevenlabs/elevenlabs-js";
import { readFile, writeFile } from "node:fs/promises";

await writeFile("tool_configs/get_order.json", getOrder.toJSONString());

const stored = Tool.fromJSON(await readFile("tool_configs/get_order.json", "utf8"));
await elevenlabs.conversationalAi.tools.update("tool_id", stored.build());
```

A typical setup is the same as for [workflows](/docs/eleven-agents/customization/agents-as-code/workflows#store-workflows-in-version-control): seed the files with `elevenlabs tools pull`, edit them directly or with the builder, run `Tool.from_json(file).build()` / `Tool.fromJSON(file).build()` in CI on every pull request, and push them with `tools.update()` or `elevenlabs tools push` on merge.

## Validation

Chained calls never fail on their own. `build()`, `build_config()` / `buildConfig()`, `to_json()` / `toJSON()` and `to_json_string()` / `toJSONString()` check the whole tool and raise or throw a single `ToolValidationError` whose `issues` list every problem, each with a `code`, a `message` and the `path` of the part it concerns, such as `body.reason`.

```python
from elevenlabs.agent_tools import ToolValidationError

try:
    request = refund.build()
except ToolValidationError as err:
    for issue in err.issues:
        print(issue.code, issue.path, issue.message)
```

```typescript
import { ToolValidationError } from "@elevenlabs/elevenlabs-js";

try {
  const request = refund.build();
} catch (err) {
  if (err instanceof ToolValidationError) {
    for (const issue of err.issues) console.error(issue.code, issue.path, issue.message);
  } else {
    throw err;
  }
}
```

Errors include:

* A URL placeholder with no path parameter, or a path parameter with no placeholder. Environment variable templates such as `{{system__env_api_host}}` aren't placeholders.
* A literal with no value source, or with more than one.
* A body on a `GET`, or no body on a `POST`, `PUT` or `PATCH`.
* The same parameter name in more than one of the path, query and body.
* `omit()` on a required property, `choices()` on a schema that isn't a string, or a constant that doesn't match the schema's type.
* A transfer tool with no destinations, a destination of the wrong kind, or a SIP URI destination without a SIP REFER transfer.
* An option that doesn't apply to the kind of tool, or a timeout outside its range.

## Tool types newer than your SDK

A tool loaded from the API or from a file can be of a type that the builder can't edit, such as an MCP tool. It loads with the kind `"other"` and round-trips through `from_json()` / `fromJSON()` and `to_json_string()` / `toJSONString()` unchanged, and `build()` reports it as a warning through `on_warning` / `onWarning`.