---
docId: doc_0309bb5cdb58402ca5428e89d20f3572
title: 'Custom functions'
description: "Write TypeScript functions that agents can use as tools."
---

<script>
  import { Ways, Note, Collapsible } from '$lib/components';
</script>

# Custom functions

Write a **custom function** in TypeScript so your agent can use your business logic and services. For example:

- Calculate a quote using your prices and rules.
- Check availability in your systems and combine their responses.
- Create a request in your system through its API.

You define these actions in the code. Platica reviews and runs it in an isolated environment. The agent calls the function as `fn_<name>`.

For one HTTP call with JSON, you can configure a [custom API](/api-reference/custom-apis) without writing code.

## Quick example

<Ways tabs="api,sdk">
<Ways.Way name="api">

```bash
# Cycle: create (draft) -> verify -> bind secrets -> test -> publish (enabled) -> connect to the agent
curl -X POST https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/test \
  -H "Authorization: Bearer $PLATIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"input": {"taxId": "XAXX010101000"}}'

curl -X POST https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/publish \
  -H "Authorization: Bearer $PLATIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"notes": "First version"}'
```

</Ways.Way>
<Ways.Way name="sdk">

```ts
import { readFile } from "node:fs/promises";

// 1. Create the function as a draft with the code from your repository
const fn = await platic.tools.functions.create({
  name: "tax_id_lookup",
  description: "Looks up a customer's company name by tax ID. Use it when the customer gives their tax ID.",
  source: await readFile("tax_id_lookup.ts", "utf8"),
  allowedDomains: ["api.example.com"],
  secretSlots: [{ slot: "API_KEY", origin: "https://api.example.com" }],
});

// 2. Verify, bind the secret, test, publish and connect to the agent
const check = await platic.tools.functions.verify(fn.id);
if (!check.ok) for (const issue of check.issues) console.log(issue.stage, issue.line, issue.message);
await platic.tools.functions.bindSecret(fn.id, { slot: "API_KEY", secretId });
const test = await platic.tools.functions.test(fn.id, { input: { taxId: "XAXX010101000" } });
if (test.ok) {
  const { toolId } = await platic.tools.functions.publish(fn.id, { notes: "First version" });
  if (toolId) await platic.agents.tools.connect(agentId, toolId);
}
```

</Ways.Way>
</Ways>

## Code format

```ts
import { z } from "zod";
import { defineFunction } from "@platica/functions";

export default defineFunction({
  input: z.object({
    taxId: z.string().describe("Customer tax ID, 12 or 13 characters")
  }),
  async run(input, { http, secrets, log }) {
    const res = await http.fetch("https://api.example.com/v1/tax-id", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${secrets.API_KEY}` },
      body: JSON.stringify({ taxId: input.taxId })
    });
    if (res.status !== 200) return { found: false };
    log.info("response", { status: res.status });
    return { found: true, name: res.json().company_name };
  }
});
```

- **`input`** is a `zod` schema. Platica turns it into the schema the agent sees, and the descriptions in `.describe(...)` tell it what to send.
- **`run(input, { http, secrets, log })`** returns a JSON object. That is what the agent receives.
- **`http.fetch(url, { method, headers, body })`** is the only way out to the internet. It answers `{ status, headers, text, json() }`.
- **`secrets.API_KEY`** is not the key: it is a placeholder. Platica swaps it for the value only when the call goes to the origin declared for that slot.
- **`log.info`, `log.warn` and `log.error`** end up in the [executions](/api-reference/custom-functions/executions).

<Collapsible summary="Packages and code restrictions">

**Allowed packages:** `zod`, `@platica/functions`, `date-fns`, `decimal.js`, `papaparse`, `lodash-es` and `fast-xml-parser`. [Get the environment](/api-reference/custom-functions/environment) gives their versions, the template and the exact types.

**Not allowed:** `fs`, `net`, `http`, `https`, `child_process`, `process`, `require`, `import()`, `eval`, `Function`, the global `fetch`, `WebAssembly`, `globalThis`, `XMLHttpRequest` and `WebSocket`. [Verify](/api-reference/custom-functions/verify) rejects code that uses them.

</Collapsible>

## Security

- **Each function has an isolated environment.** It cannot access other functions, other workspaces, or Platica's data.
- **Internet access is limited.** Only HTTPS calls to domains in `allowedDomains` are allowed: up to 10 exact names, such as `api.example.com`. Any other call fails with `EGRESS_DENIED`.
- **Protected secrets.** The code receives a placeholder. Platica sends the real value only to the slot's authorized origin. Other destinations receive the placeholder. Logs and executions exclude the value.
- **It is reviewed before running.** Verify compiles the code and rejects packages and APIs that are not allowed before anything is deployed.
- **What is published does not change.** Each publication is a fixed version. Editing changes the draft; agents keep using the published version until the next publication, and you can [go back to an earlier one](/api-reference/custom-functions/restore-version).

## Secrets

To bind a credential:

1. Declare each credential in `secretSlots` with an uppercase name (`API_KEY`) and the only origin it can be sent to (`https://api.example.com`). The origin's host has to be in `allowedDomains`.
2. Store the value as a [workspace secret](/api-reference/secrets/create) or reuse one from [List secrets](/api-reference/secrets/list).
3. [Bind the secret](/api-reference/custom-functions/bind-secret) to the slot. It is authorized only for that origin.

[Test](/api-reference/custom-functions/test) and [run](/api-reference/custom-functions/run) use the bound secrets, which are resolved on Platica's side. If the code reads a secret that is not bound, the execution answers `SECRET_MISSING`. Sending `secrets` in the body of a test or a run answers `400`.

## States

| `status` | What it means |
|----------|---------------|
| `draft` | Draft. It has never been published and no agent sees it |
| `enabled` | Published and on. The tool is in the catalog and connected agents use it |
| `paused` | Paused. No agent sees it; the code, the versions and the connections to agents are kept |

An `enabled` function still has a draft: editing does not change what agents use until you [publish](/api-reference/custom-functions/publish) again.

## Limits

| What | Limit |
|------|-------|
| Functions per workspace | 20 |
| Time per execution | 1 to 60 s; 20 s by default |
| Memory | 256 MB |
| HTTP calls per execution | 20, each up to 15 s and 2 MB |
| Input and output | 256 KB each. The agent reads up to 16,000 characters of the output |
| Code | 100 KB (1 MB bundled) |
| Allowed domains | 10 per function |
| Secret slots | 10 per function |
| Calls | 60 per minute per function; 5,000 per day and 50,000 per month per workspace |
| Deployments (publish and test) | 50 per day per workspace |

[Get usage](/api-reference/custom-functions/usage) says how much you have used. When a limit is exceeded, the response is `LIMIT_REACHED` with `details.limit` and, on calls, `details.resetAt`.

## Errors

<Collapsible summary="Show error codes and fixes">

Errors follow the format in [Errors](/api-reference/errors): `{ code, error, details: { code, message, ... } }`.

| Status | `details.code` | When |
|--------|----------------|------|
| `400` | `INVALID_REQUEST` | The body or parameters fail validation. `details.issues` has the list of problems |
| `401` | `UNAUTHENTICATED` | The credential is missing, or revoked or expired |
| `403` | `FORBIDDEN` | The person behind the token does not have access to Integrations |
| `403` | `INSUFFICIENT_SCOPE` | The OAuth token does not have write permission |
| `404` | `NOT_FOUND` | The function or the version does not exist in this workspace |
| `409` | `NAME_TAKEN` | A function with that `name` already exists |
| `409` | `NOT_PUBLISHED` | The function does not have a published version yet |
| `409` | `PAUSED` | The function is paused |
| `409` | `LIMIT_REACHED` | The workspace already has 20 functions |
| `422` | `VALIDATION_FAILED` | The code does not pass verification when publishing or testing. `details.issues` has each problem |
| `429` | `LIMIT_REACHED` | A call or deployment limit was exceeded. `details.limit` says which and `details.resetAt` when it frees up |
| `501` | `FUNCTION_SECRETS_UNAVAILABLE` | Binding secrets is not available at the moment |
| `502` | `SERVICE_MISCONFIGURED` or `CUSTOM_FUNCTIONS_SERVICE_ERROR` | Internal Platica failure. Try later |
| `503` | `CUSTOM_FUNCTIONS_SERVICE_UNAVAILABLE` or `PROVIDER_UNAVAILABLE` | Functions are not available at this moment |

<Note type="important">

A `503` on a write means the change could not be confirmed. [Get the function](/api-reference/custom-functions/get) before retrying.

</Note>

### Errors inside an execution

Check `ok` in the response: a failed execution returns HTTP `200`, with `ok: false` and the reason in `error.code`.

| `error.code` | What happened |
|--------------|---------------|
| `FUNCTION_ERROR` | The code threw an error. Check `logs` |
| `TIMEOUT` | It took longer than `timeoutSeconds` and was stopped |
| `EGRESS_DENIED` | It tried to call a domain that is not in `allowedDomains` |
| `INPUT_INVALID` | The input does not meet the `input` schema |
| `OUTPUT_TOO_LARGE` | It returned more than 256 KB |
| `SECRET_MISSING` | It reads a secret that is not bound. Bind it with [Bind a secret](/api-reference/custom-functions/bind-secret) |

</Collapsible>

## Endpoints

| Method | Endpoint | What it does |
|--------|----------|--------------|
| `GET` / `POST` | [`/v1/tools/functions`](/api-reference/custom-functions/list) | List functions or [create one](/api-reference/custom-functions/create) as `draft` |
| `GET` / `PATCH` / `DELETE` | [`/v1/tools/functions/{functionId}`](/api-reference/custom-functions/get) | Get, [edit the draft](/api-reference/custom-functions/update) or [delete](/api-reference/custom-functions/delete) |
| `POST` | [`/v1/tools/functions/{functionId}/verify`](/api-reference/custom-functions/verify) | Review the code without running it |
| `POST` | [`/v1/tools/functions/{functionId}/secrets`](/api-reference/custom-functions/bind-secret) | Bind a secret to a slot |
| `POST` | [`/v1/tools/functions/{functionId}/test`](/api-reference/custom-functions/test) | Test the draft with an input |
| `POST` | [`/v1/tools/functions/{functionId}/publish`](/api-reference/custom-functions/publish) | Publish a new version and turn it on |
| `POST` | [`/v1/tools/functions/{functionId}/rollback`](/api-reference/custom-functions/restore-version) | Put an earlier version live |
| `POST` | [`/v1/tools/functions/{functionId}/enable`](/api-reference/custom-functions/activate) | Turn on a paused function |
| `POST` | [`/v1/tools/functions/{functionId}/pause`](/api-reference/custom-functions/pause) | Pause without losing anything |
| `POST` | [`/v1/tools/functions/{functionId}/run`](/api-reference/custom-functions/run) | Run the published version by hand |
| `GET` | [`/v1/tools/functions/{functionId}/versions`](/api-reference/custom-functions/versions) | Published versions, and one with its code |
| `GET` | [`/v1/tools/functions/runs`](/api-reference/custom-functions/executions) | Executions of all functions or of one |
| `GET` | [`/v1/tools/functions/usage`](/api-reference/custom-functions/usage) | The workspace's usage against its limits |
| `GET` | [`/v1/tools/functions/runtime`](/api-reference/custom-functions/environment) | Packages, limits, template and types |

**Permissions:** reading requires read access to **Integrations**; creating, changing, testing, publishing and running, write access (a workspace API key, or an OAuth token with the `integrations` permission and `platica:write`); deleting, delete access. If the credential covers several workspaces, send `?workspace=<id>`.

Once published, the function appears in the [workspace catalog](/api-reference/tools/list) with `kind: "function"` and is connected to an agent with [Connect a tool](/api-reference/agents/tools/connect). AI tools are in the [Custom functions MCP tools](/mcp/tools#tools) and the dashboard guide is in [Custom functions](/help/integrations/functions/custom-functions).
