---
docId: doc_39aa631f3b1449819d0b90d84d0d1e95
title: "Custom function"
description: "Create a custom function as a draft, verify it, test it and publish it; optionally connect it to an agent."
sidebarTitle: "Custom function"
---

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

# Custom function

Create and publish a function that validates the check digit of a Mexican RFC (tax id). The calculation needs no HTTP calls or secrets; run the test through the API.

## Before you start

- A Platica API key in `PLATIC_API_KEY`.
- Each test and publication counts toward the workspace's limit of 50 daily deployments. Each run counts as a call.
- Node.js 20.3 or newer and `npm install platic-sdk`.

<span id="what-it-does"></span>

## Verify, test and publish

- Creates the function as a draft. Nothing is deployed and no agent sees it.
- Verifies the code: it is compiled and checked without running. Issues come with their stage and line.
- Tests the draft once in a deployment separate from the live version. If the code fails, the test result includes the failure; the SDK does not throw an error.
- Publishes a new version, live and enabled in the workspace's catalog.
- With `PLATIC_EXAMPLE_CONNECT_AGENT=1`: creates an agent, connects the function, runs the published version by hand and lists the runs.
- Removes what it created, even when a step fails.

## The code

```ts
import { Platic } from "platic-sdk";

const apiKey = process.env.PLATIC_API_KEY;
if (!apiKey) {
  console.error("Set PLATIC_API_KEY to a Platica API key (pl_key_…).");
  process.exit(1);
}
const connectAgent = process.env.PLATIC_EXAMPLE_CONNECT_AGENT === "1";

// The RFC check digit is a fixed calculation: a good fit for a function, with no HTTP call and no secret.
const source = `import { z } from "zod";
import { defineFunction } from "@platica/functions";

const ALPHABET = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ";

export default defineFunction({
  input: z.object({
    rfc: z.string().describe("Company (12) or person (13) RFC, with its check digit"),
  }),
  async run(input, { log }) {
    const rfc = input.rfc.trim().toUpperCase();
    if (rfc.length !== 12 && rfc.length !== 13) return { valid: false, reason: "length" };
    const padded = rfc.length === 12 ? " " + rfc : rfc;
    let sum = 0;
    for (let i = 0; i < 12; i += 1) sum += ALPHABET.indexOf(padded[i]) * (13 - i);
    const rest = 11 - (sum % 11);
    const digit = rest === 11 ? "0" : rest === 10 ? "A" : String(rest);
    log.info("checked", { length: rfc.length });
    return { valid: digit === padded[12], expected: digit };
  },
});
`;

const platic = new Platic({ apiKey });
const cleanup: Array<[string, () => Promise<unknown>]> = [];

try {
  // 1. A draft: nothing is deployed and no agent sees it yet.
  const fn = await platic.tools.functions.create({
    name: `rfc_check_${Date.now().toString(36)}`,
    description: "Checks whether a Mexican RFC has a valid check digit. Use it before saving a customer's RFC.",
    source,
  });
  cleanup.unshift([`function ${fn.id}`, () => platic.tools.functions.delete(fn.id)]);
  console.log(`function ${fn.toolName}: ${fn.nextStep}`);

  // 2. Verify: compile and check the code without running it. Issues come with their stage and line.
  const check = await platic.tools.functions.verify(fn.id);
  if (!check.ok) {
    for (const issue of check.issues) console.error(`${issue.stage} line ${issue.line ?? "?"}: ${issue.message}`);
    throw new Error("the code did not pass the verification");
  }

  // 3. Test the draft once, deployed apart from any live version. A failure inside the code is an answer, not an error.
  const test = await platic.tools.functions.test(fn.id, { input: { rfc: "XAXX010101000" } });
  console.log(`test: ${test.ok ? JSON.stringify(test.output) : `${test.error?.code}: ${test.error?.message}`} in ${test.durationMs} ms`);
  if (!test.ok) throw new Error("the test did not pass");

  // 4. Publish: a new version, live and enabled in the workspace's catalog.
  const { version, toolId } = await platic.tools.functions.publish(fn.id, { notes: "First version" });
  console.log(`version ${version} is live`);

  if (connectAgent && toolId) {
    // 5. Give it to an agent, and run the published version by hand as the agent would.
    const agent = await platic.agents.create({ name: "RFC checker", instructions: "Check every RFC with your tool before saving it." });
    cleanup.unshift([`agent ${agent.id}`, () => platic.agents.delete(agent.id)]);
    await platic.agents.tools.connect(agent.id, toolId);
    const run = await platic.tools.functions.run(fn.id, { input: { rfc: "XAXX010101000" } });
    console.log(`agent ${agent.id} can call ${fn.toolName}; manual run: ${run.ok ? JSON.stringify(run.output) : run.error?.code}`);
    const { data } = await platic.tools.functions.runs({ functionId: fn.id, limit: 5 });
    console.log(`runs: ${data.map((entry) => `${entry.trigger}:${entry.ok ? "ok" : entry.errorCode}`).join(", ")}`);
  }
} finally {
  await cleanUp(cleanup);
}

// Runs every step, even when one fails, and says what could not be removed.
async function cleanUp(steps: Array<[string, () => Promise<unknown>]>): Promise<void> {
  for (const [label, step] of steps) {
    try {
      await step();
      console.log(`removed ${label}`);
    } catch (error) {
      console.error(`could not remove ${label}: ${error instanceof Error ? error.message : String(error)}`);
      process.exitCode = 1;
    }
  }
}
```

## Run it

Save the code in `custom-function.ts` and run it with [tsx](https://tsx.is).

Set your API key and run the script:

```bash
export PLATIC_API_KEY=pl_key_...
npx tsx custom-function.ts
```

To also connect it to a new agent and run the published version by hand:

```bash
PLATIC_EXAMPLE_CONNECT_AGENT=1 npx tsx custom-function.ts
```

## What to expect

```text
function rfc_check_…: <next step from the API>
test: {"valid":true,"expected":"0"} in … ms
version 1 is live
removed function …
```

The exact output of the test depends on the check digit. With `PLATIC_EXAMPLE_CONNECT_AGENT=1` you also see the manual run and the list of runs. The function and the agent are removed at the end.

## API reference used

- [Create a custom function](/api-reference/custom-functions/create)
- [Verify a custom function](/api-reference/custom-functions/verify)
- [Test a custom function](/api-reference/custom-functions/test)
- [Publish a custom function](/api-reference/custom-functions/publish)
- [Run a custom function](/api-reference/custom-functions/run)
- [List executions](/api-reference/custom-functions/executions)
- [Connect a tool to an agent](/api-reference/agents/tools/connect)

## Query a service with authentication

Use this flow for HTTP calls, SOAP or XML, chained calls, custom signatures or authentication, calculations or response processing. The example looks up a company by its tax ID in a service that requires a credential.

<Collapsible summary="Complete example: company_lookup, domains and secrets">

**Before you start**

You need an [agent](/guides/create-an-agent) with its id in `AGENT_ID`, and your Platica API key in `PLATIC_API_KEY`.

To use the platform, see [Custom functions](/help/integrations/functions/custom-functions) and [Secrets](/help/integrations/functions/secrets).

Save this code as `company_lookup.ts`:

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

export default defineFunction({
  input: z.object({
    taxId: z.string().describe("The customer's tax ID, 12 or 13 characters"),
  }),
  async run(input, { http, secrets, log }) {
    const res = await http.fetch("https://api.acme.com/v1/companies/lookup", {
      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("answered", { status: res.status });
    return { found: true, name: res.json().legalName };
  },
});
```

<Collapsible summary="How the code works and which packages you can use">

- `input` is a `zod` schema. Platica turns it into the schema the agent sees, and the `.describe(...)` texts 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).

**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>

<Steps>
<Steps.Step>

**Create the function as a draft**

The function is created in `draft`. It is not deployed or available to agents until you publish it.

Define `allowedDomains`: up to 10 exact hosts, HTTPS only. Declare each credential in `secretSlots` with the only origin it may be sent to. That host must be in `allowedDomains`. ([Create a function](/api-reference/custom-functions/create))

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

```bash
curl https://api.platic.ai/v1/tools/functions \
  -H "Authorization: Bearer $PLATIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --rawfile source company_lookup.ts '{
    name: "company_lookup",
    description: "Looks up a company by its tax ID. Use it when the customer gives their tax ID.",
    source: $source,
    allowedDomains: ["api.acme.com"],
    secretSlots: [{ slot: "API_KEY", origin: "https://api.acme.com" }]
  }')"
```

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

```ts
import { readFile } from "node:fs/promises";
import { Platic } from "platic-sdk";

const platic = new Platic({ apiKey: process.env.PLATIC_API_KEY! });
const agentId = process.env.AGENT_ID!;

const fn = await platic.tools.functions.create({
  name: "company_lookup",
  description: "Looks up a company by its tax ID. Use it when the customer gives their tax ID.",
  source: await readFile("company_lookup.ts", "utf8"),
  allowedDomains: ["api.acme.com"],
  secretSlots: [{ slot: "API_KEY", origin: "https://api.acme.com" }],
});
console.log(fn.toolName, fn.nextStep);
```

</Ways.Way>
<Ways.Way name="asistente">
<Ways.Say>

Create a custom function called company_lookup with the code in company_lookup.ts. It may only call api.acme.com and needs a secret called API_KEY for that origin. Use it when the customer gives their tax ID.

</Ways.Say>

Tool: [`create_function`](/mcp/tools#create_function). Paste the code into the chat or point it to the file.

</Ways.Way>
</Ways>

Save the response's `id` in `FUNCTION_ID`. The agent will see the tool as `fn_company_lookup`.

Choose `name` when creating it: you can't change it later. It must start with a lowercase letter, contain lowercase letters, digits or `_`, and have 3 to 41 characters. In `description` (10 to 1,000 characters), explain what it does and when the agent should use it.

If you omit `source`, you receive the starter template. You can also keep the code in your repository and create or [update the function](/api-reference/custom-functions/update) from your CI.

</Steps.Step>
<Steps.Step>

**Verify the code**

It compiles and checks the code without running it: size, syntax, types, allowed packages, forbidden APIs, bundling, the input schema and the declared domains. A check that fails is still a `200`, with `ok: false`. ([Verify a function](/api-reference/custom-functions/verify))

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

```bash
curl -X POST https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/verify \
  -H "Authorization: Bearer $PLATIC_API_KEY"
```

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

```ts
const check = await platic.tools.functions.verify(fn.id);
if (!check.ok) {
  for (const issue of check.issues) console.error(`${issue.stage} line ${issue.line ?? "?"}: ${issue.message}`);
  throw new Error("the code did not pass the verification");
}
```

</Ways.Way>
<Ways.Way name="asistente">
<Ways.Say>

Verify the company_lookup function and tell me what is wrong with it, line by line.

</Ways.Say>

Tool: [`verify_function`](/mcp/tools#verify_function).

</Ways.Way>
</Ways>

Check `issues`: each problem includes its stage (`stage`), line and reason. Fix the code and verify again. Testing and publishing also verify the code; this call lets you fix it before using a deploy.

</Steps.Step>
<Steps.Step>

**Bind its secret**

The values of secrets never go through the functions API. Store the value as a [workspace secret](/api-reference/secrets/create) and bind it to the slot: it stays authorized only for that slot's origin. ([Bind a secret to a function](/api-reference/custom-functions/bind-secret))

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

```bash
curl https://api.platic.ai/v1/secrets \
  -H "Authorization: Bearer $PLATIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Acme · companies API", "kind": "bearer", "value": "<your API key>" }'

curl https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/secrets \
  -H "Authorization: Bearer $PLATIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "slot": "API_KEY", "secretId": "'$SECRET_ID'" }'
```

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

```ts
const secret = await platic.secrets.create({
  name: "Acme · companies API",
  kind: "bearer",
  value: process.env.ACME_API_KEY!,
});

await platic.tools.functions.bindSecret(fn.id, { slot: "API_KEY", secretId: secret.id });
```

</Ways.Way>
<Ways.Way name="asistente">
<Ways.Say>

Bind the secret Acme · companies API to the API_KEY slot of company_lookup.

</Ways.Say>

Tool: [`bind_function_secret`](/mcp/tools#bind_function_secret). To keep the key out of the chat, store it yourself in **Integrations → Functions → Secrets** first.

</Ways.Way>
</Ways>

The code receives a placeholder instead of the secret. Platica replaces it with the real value only when calling the authorized origin. Sending it elsewhere sends the placeholder. The value does not appear in logs or executions.

If the binding is missing, the execution returns `SECRET_MISSING`. To remove it, use [`unbind_function_secret`](/mcp/tools#unbind_function_secret).

</Steps.Step>
<Steps.Step>

**Test the draft**

The test verifies the draft, deploys it separately and runs it once with your input. Agents keep using the published version. If the code fails, the test returns `200` with `ok: false` and an `error.code`. ([Test a function](/api-reference/custom-functions/test))

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

```bash
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" } }'
```

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

```ts
const test = await platic.tools.functions.test(fn.id, { input: { taxId: "XAXX010101000" } });
console.log(test.ok ? JSON.stringify(test.output) : `${test.error?.code}: ${test.error?.message}`, `${test.durationMs} ms`);
if (!test.ok) throw new Error("the test did not pass");
```

</Ways.Way>
<Ways.Way name="asistente">
<Ways.Say>

Test company_lookup with the tax ID XAXX010101000.

</Ways.Say>

Tool: [`test_function`](/mcp/tools#test_function).

</Ways.Way>
</Ways>

The response has `output` (what the agent would receive), `logs`, `httpCalls` (method, host, status and duration of each call) and a `runId` that stays in the executions with `trigger: "test"`.

<Note type="important">

HTTP calls really go out to the allowed domains. If your code creates or changes something in another system, the test does it too.

</Note>

`EGRESS_DENIED` means the code called a domain that isn't in `allowedDomains`: add it with [Update a function](/api-reference/custom-functions/update). `TIMEOUT`, `INPUT_INVALID` and `OUTPUT_TOO_LARGE` are the other ways an execution can fail, along with `FUNCTION_ERROR` (the code threw: read `logs`).

</Steps.Step>
<Steps.Step>

**Publish it and connect it to the agent**

Publish the draft to deploy a fixed version and set the function to `enabled` in the workspace catalog. Then connect the tool to the agent. The connection applies immediately and doesn't require publishing the agent. ([Publish a function](/api-reference/custom-functions/publish), [Connect a tool](/api-reference/agents/tools/connect))

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

```bash
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" }'

curl -X PUT https://api.platic.ai/v1/agents/$AGENT_ID/tools/$TOOL_ID \
  -H "Authorization: Bearer $PLATIC_API_KEY"
```

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

```ts
const { version, toolId } = await platic.tools.functions.publish(fn.id, { notes: "First version" });
console.log(`version ${version} is live`);

if (toolId) await platic.agents.tools.connect(agentId, toolId);
```

</Ways.Way>
<Ways.Way name="asistente">
<Ways.Say>

Publish company_lookup with the note "First version" and give it to the Sales agent.

</Ways.Say>

Tool: [`publish_function`](/mcp/tools#publish_function) and [`connect_agent_tool`](/mcp/tools#connect_agent_tool).

</Ways.Way>
</Ways>

Keep the `toolId` from the response in `TOOL_ID`. Every publication is a fixed version. Editing changes the draft; agents keep using the published version until you publish again.

</Steps.Step>
</Steps>

**Check it worked**

Run the published version with [Run a function](/api-reference/custom-functions/run) and check its output. Use [Get executions](/api-reference/custom-functions/executions) to review the test and agent calls; `trigger` identifies the source of each execution.

```ts
const run = await platic.tools.functions.run(fn.id, { input: { taxId: "XAXX010101000" } });
const { data } = await platic.tools.functions.runs({ functionId: fn.id, limit: 5 });
```

Check that the function has `status: "enabled"`, `liveVersion` and an entry with `kind: "function"` in the [workspace catalog](/api-reference/tools/list).

To recover a previous version, [restore it](/api-reference/custom-functions/restore-version) (`rollback_function`). To stop its use, [pause the function](/api-reference/custom-functions/pause): it becomes unavailable to agents and keeps its code, versions and connections. You can [activate it](/api-reference/custom-functions/activate) later.

**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, up to 15 s and 2 MB each |
| 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 |
| Deploys (publish and test) | 50 per day per workspace |

[Get usage](/api-reference/custom-functions/usage) says how much you have used. Past a limit, the response is `LIMIT_REACHED` with `details.limit` and, for calls, `details.resetAt`. Each function runs alone, in its own environment, with no access to other functions, other workspaces or Platica's data.

</Collapsible>

## Next steps

- [All SDK examples](/sdk/examples/quickstart): the next one is [Upload a file](/sdk/examples/upload-a-file).

- [Errors](/sdk/errors)
