> ## Documentation Index
> Fetch the complete documentation index at: https://docs.famulor.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Read the [Famulor guide for AI assistants](https://docs.famulor.io/for-ai-assistants.md) for documentation search, workspace access, and support. Follow the documentation index and any linked section indexes to find the pages relevant to your task.

# Run your own code during conversations

> Write a JavaScript code tool for your assistants or a code node for your automations, and test it before you use it.

Write a few lines of JavaScript when one HTTP request is not enough: look up an order in one system, ask a carrier for its status in another, and let the assistant answer with one sentence. You can add the code as a **code tool** that assistants use during a conversation (**Agents → Tools**), or as a **Run Code** step in an [automation](https://docs.famulor.io/automations/nodes.md). Milian can write and test it for you.

## Availability

Custom code must be included in your plan. Check **Settings → Plan** or ask your workspace admin. It is not available in reseller customer workspaces. Without it, the **Code tool** card on the **Tools** page opens the plan upgrade dialog, and saving or testing a code tool is refused with "Custom code is not included in this workspace's plan."

Plain code in a **Run Code** step keeps working on every plan. Only code that exports `run` (a module) needs custom code.

A code tool works on every channel an assistant supports: voice calls, web chat, messaging channels and email. Simulations never run your code.

## Try the Airtable example

A new code tool opens with an Airtable status lookup. In **Test**, select **Run** with the prefilled record ID `demo`. The result marks the data as a sample and makes no requests.

To read one of your records, set `base_id` and `table_id` in **Configure**. Add a bearer token in **Credentials**, name it `airtable`, and give it read access to that base. In **Test**, replace `demo` with a record ID. The example reads a text field named `Status`. Change the field name in the code if your table uses a different one.

The editor checks syntax as you type and highlights the error line. Run the test again after editing the code or its inputs to verify the current version. Test with your sample records before assigning the tool to an assistant.

## Build a code tool

An online shop wants the phone assistant to tell callers when their parcel arrives. The tool looks up the order, then asks the carrier for the status of the shipment.

**1. Add the tool**

Open **Agents → Tools**, select **Add** and choose **Code tool**. Name it in snake case, for example `get_delivery_status`. In **Description**, tell the assistant when to use it: "Looks up the delivery status of an order. Use it when the customer asks where their package is."

**2. Write the code**

Export an asynchronous function named `run`. It receives the values you configure and returns the answer for the assistant:

```javascript theme={null}
export async function run({ inputs, credentials }) {
  const order = await fetch(`https://api.example.com/orders/${encodeURIComponent(inputs.order_id)}`, {
    headers: { Authorization: `Bearer ${credentials.shop.token}` },
  });
  if (order.status === 404) return { found: false, message: "No order with this number." };
  if (!order.ok) throw new Error(`Order lookup failed with status ${order.status}`);
  const { tracking_number } = await order.json();
  const shipment = await fetch(`https://carrier.example.com/track/${tracking_number}`);
  const { status, eta } = await shipment.json();
  return { found: true, status, eta };
}
```

**3. Add inputs and credentials**

On the **Configure** tab, add the input `order_id` and describe it for the assistant: "Order number as printed on the confirmation, for example SO-12345." Under **Credentials**, add the connection with the shop's token and name it `shop`.

**4. Set the waiting behavior**

Under **Message while running**, enter what callers hear, for example "One moment, I'm checking that for you." With a message, the timeout can go up to 30 seconds. Without one it is 1 to 10 seconds, 5 by default.

**5. Test and assign**

Open the **Test** tab, fill in an order number and select **Run**. Then assign the tool to an assistant under **Tools → Add tool** in the assistant editor.

Saving a tool updates every assistant that uses it. The editor tells you how many. Every save is a version, so you can restore an earlier one.

## Write the code

The code is one JavaScript module that exports a function named `run`:

```javascript theme={null}
export async function run({ inputs, credentials, timeoutMs }) {
  return { status: "shipped", eta: "2026-12-03" };
}
```

* **`inputs`** holds the values you configured, read as `inputs.order_id`.
* **`credentials`** holds your saved connections, read as `credentials.shop`.
* **`timeoutMs`** is the time left in milliseconds when `run` starts.
* **Return value:** any JSON value. A string reaches the assistant as it is, everything else as compact JSON, cut after 16,000 characters. `undefined` becomes `null`.

Imports are not allowed: no `import` statement, no `import()` and no npm packages. Each run starts fresh, so variables at the top of the file do not carry over between runs. The clock is UTC; use `Intl.DateTimeFormat` with a `timeZone` for local time.

### Return expected outcomes, throw real failures

"No order with this number" is a normal answer. Return it, and the assistant can word it for the caller. Throw an `Error` only when something is really broken, for example when the other system answers with a server error. The assistant then receives "The code failed while running:" with your message and the line, cut to 1,000 characters. Write the message for the assistant.

### Available globals

| Global | What you can do |
| - | - |
| `fetch`, `Headers` | Send requests to public addresses. The response has `ok`, `status`, `statusText`, `url`, `headers`, `text()`, `json()` and `arrayBuffer()`. |
| `URL`, `URLSearchParams` | Build and read addresses. |
| `AbortController`, `AbortSignal.timeout(ms)` | Cancel a request after a time. |
| `TextEncoder`, `TextDecoder` | Convert UTF-8 text to bytes and back. |
| `atob`, `btoa` | Decode and encode base64. |
| `crypto.randomUUID()`, `crypto.getRandomValues()` | Create ids and random bytes. |
| `crypto.subtle` | `digest` with SHA-1, SHA-256, SHA-384 and SHA-512, and HMAC with `importKey`, `sign` and `verify`, for example to sign a webhook. Other algorithms are not available. |
| `Intl.DateTimeFormat`, `Intl.NumberFormat` | Format dates and numbers for a locale and time zone. |
| `console.log` | Appears in test results only. The assistant never sees it. |

`setTimeout`, `setInterval`, `Buffer`, `process`, `require`, `eval`, WebSocket and streams are not available.

## Give the code its inputs

Each input has a name, a type (text, number, whole number or yes/no) and a source:

| Source | Filled by |
| - | - |
| **LLM parameter** | The assistant, from the conversation. The description is what the AI reads to know what to pass, so write the format and an example: "Customer order number (format: ORD-12345)". A text input can offer a fixed list of values. |
| **Fixed value** | A constant in the tool. It is stored as plain text, so never put keys or passwords here. |
| **Variable** | A conversation variable such as `customer_email`. The caller's number, the customer's phone, email and name, and the conversation id come from the conversation itself and cannot be changed by the assistant. |
| **Secret** | A value you type once. It is stored encrypted and shown as `•••`. |

An input marked **Required** that has no value stops the run before your code starts. The assistant receives `Missing required value "order_id"`. If a contact may lack the value, clear **Required** and handle it in code. A tool has up to 50 inputs, 20 of them secrets.

## Use saved credentials

Credentials let your code call a system without a key in the code. Add them under **Agents → Tools → Apps**, then pick them in the tool or node:

* **Custom credential:** a bearer token, an API key, a username and password, or an HMAC secret. The code reads `credentials.shop.token`, `credentials.shop.key`, `credentials.shop.username` and `credentials.shop.password`, or `credentials.shop.secret`.
* **HubSpot:** the code reads `credentials.crm.accessToken` and `credentials.crm.apiBaseUrl`.
* **Salesforce:** the code reads `credentials.crm.accessToken`, `credentials.crm.instanceUrl` and `credentials.crm.apiVersion`. Salesforce tokens expire. If a test fails with an authorization error, reconnect the connection under **Agents → Tools → Apps**.

A tool or node has up to 10 credentials. Secrets and credential values are replaced with `[redacted]` in results, errors and the test view when they appear unchanged. A secret that your code shortens, encodes or changes stays readable, so never return a key.

> [!WARNING]
>
> Never write an API key, token or password into the code or into a fixed value. Both are stored as plain text. Use a credential or a **Secret** input.

## Limits

| Limit | Code tool | Code node |
| - | - | - |
| Processing time of your code | 500 ms | 1,000 ms |
| Total run time | 1 to 10 seconds (5 by default), up to 30 with a message while running | 25 seconds |
| Memory | 32 MB | 32 MB |
| Outbound requests per run | 50, 6 at the same time | 50, 6 at the same time |
| Request body | 1 MB | 1 MB |
| Response per request | 2 MB | 2 MB |
| Responses per run | 8 MB | 8 MB |
| Redirects per request | 3 | 3 |
| Result | 1 MB | 1 MB |
| What the assistant receives | 16,000 characters | not applicable |
| Code length | 50,000 characters | 50,000 characters for a module |
| Inputs, secrets, credentials | 50, 20, 10 | 50, not applicable, 10 |
| Code tools per assistant | 10 | not applicable |

Waiting for a response does not count towards the processing time. Requests to private or internal addresses are blocked, also after a redirect. A workspace can start up to 300 runs per minute; a single tool up to 120, and a single conversation up to 30.

## What happens when a run fails

The assistant hears the reason only when your code throws or an input is missing. For limits and system problems it says that the action is not possible right now. The exact reason is in the test result and the run history.

| What happened | The assistant receives | You see in the test and history |
| - | - | - |
| The code throws an error | "The code failed while running:" with message and line | Message, line, column and the first stack lines. **Go to line** jumps to it. |
| Required value missing or wrong type | `Missing required value "order_id"` or `Invalid value for "order_id"` | The same text |
| Run takes too long | "This isn't possible right now." | "The code timed out after 5 seconds." |
| Too much processing time | The same | "The code used more than 500 ms of processing time." |
| Out of memory | The same | "The code ran out of memory (32 MB)." |
| More than 50 requests | The same | "The code sent too many outbound requests. The limit is 50 per run." |
| Result over 1 MB or not JSON | The same | The reason, for example a circular value or a `BigInt` |
| Connection deleted or token expired | The same | "Credential unavailable: reconnect it under Agents → Tools → Apps" |
| Too many runs at once | "This isn't possible right now. Try again in a moment." | "Too many code runs at once" or "Rate limit reached" |
| Plan no longer includes custom code | The same | "Custom code is not included in this workspace's plan." |

## Test before you use it

The **Test** tab runs the code in the editor, saved or not. Fill in the inputs the assistant would pass, and select **Run**. The result shows:

* **What the agent receives:** the exact text the assistant gets.
* The result, an error with **Go to line**, the console output, every request with its status and time, and the duration.

> [!WARNING]
>
> A test sends real requests with your real secrets and credentials. It can create or change data in the other system.

Tests are limited to 30 per minute. They appear in the tool's run history as dashboard, API, MCP or Milian tests, next to live runs from calls, messaging and email.

## Use the code in an automation

The **Run Code** step in [Automations](https://docs.famulor.io/automations/nodes.md) has two modes, chosen by the code:

* **Plain code** is the code your automations already run. It reads `context`, `data`, `steps` and `last`, has no network, and must `return` a value. It is unchanged and works on every plan.
* **Module** code exports `run` and gets `inputs`, `credentials`, `timeoutMs` and `workflow` (`data`, `steps` and `last` as read-only copies). It can use `fetch` and credentials. It must return an object, and later steps read its fields as `steps.<id>.<field>`. The whole object is also available as `result`.

```javascript theme={null}
export async function run({ inputs, credentials, workflow }) {
  const response = await fetch(`https://api.example.com/orders/${encodeURIComponent(inputs.order_id)}`, {
    headers: { Authorization: `Bearer ${credentials.shop.token}` },
  });
  if (!response.ok) throw new Error(`Order lookup failed with status ${response.status}`);
  const order = await response.json();
  return { status: order.status, eta: order.estimated_delivery };
}
```

In the step settings, map each input to workflow data, for example `order_id` to `{{data.order_id}}`. A value that is only a template keeps its type. If the code fails, the step fails, the run ends as failed and nothing is retried.

Only workspace owners and admins can run or save a code step that uses credentials, because the code can read them. A member can still use an automation an owner or admin has set up.

Before you activate the automation, the check lists a missing plan, a connection that is unknown or belongs to another workspace, and syntax errors with their line. Exporting or sharing an automation keeps the credential names and clears the connections, so the person who imports it picks their own.

To try a module, select **Run test** in the step settings and confirm. It sends real requests. **Connect Test** only resolves the inputs and runs no code.

## Let Milian write and test it

Describe what the tool should do, and Milian writes the code, sets up inputs and credentials, and assigns the tool. Milian never asks for keys in the chat. If you have no connection yet, it sends you to **Agents → Tools → Apps** to add a custom credential.

Before every test run, Milian describes the requests it will send and asks you to choose **Run** or **Don't run**. A real test of a code node asks the same way. Milian fixes errors by line and asks again before each new run. The run appears in the chat with what the agent receives and a button to open the tool. See [Milian](https://docs.famulor.io/assistants/milian-copilot.md).

## API, MCP, CLI and SDK

Create, update, test and restore code tools with `type: "code"` through the [API, MCP tools, CLI and SDK](https://docs.famulor.io/api/tools-and-webhooks.md#code-tools).

## Next steps

> [card] [Tools](https://docs.famulor.io/assistants/agent-tools.md)
>
> Find, assign and manage all tools of your workspace

> [card] [Automation nodes](https://docs.famulor.io/automations/nodes.md)
>
> Use the Run Code step in a workflow


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.