---
docId: doc_698c3774dbc14b3caf5623cc2f264fc8
title: Write a custom function
description: "Calculate a quote with your business rules and connect the function to your agent."
---

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

# Write a custom function

<span id="what-youll-build"></span>

Give your agent a function with your business rules. This example calculates a quote: products plus shipping, with free shipping from 1,000 MXN.

You can also use functions to check availability across systems or create a request. They are written in TypeScript and return a JSON object.

## Before you start

You need your Platica API key in `PLATIC_API_KEY`. For the SDK, use Node.js 20.3 or newer and `platic-sdk`; the REST examples use `jq` to read the file.

To connect it to an agent, keep its id in `AGENT_ID` ([create one](/guides/create-an-agent)). In the platform, use [Custom functions](/help/integrations/functions/custom-functions).

<Steps>
<Steps.Step>

**Create the function**

Save this code as `quote.ts`. It takes quantity and unit price. Shipping costs 100 MXN and is free when the subtotal reaches 1,000 MXN.

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

export default defineFunction({
  input: z.object({
    quantity: z.number().int().min(1).describe("Number of products"),
    unitPrice: z.number().nonnegative().describe("Unit price in MXN"),
  }),
  async run(input) {
    const subtotal = input.quantity * input.unitPrice;
    const shipping = subtotal >= 1000 ? 0 : 100;
    return { currency: "MXN", subtotal, shipping, total: subtotal + shipping };
  },
});
```

`input` defines the data the agent sends. Descriptions explain each field. `run` calculates and returns the result.

[Create the draft](/api-reference/custom-functions/create) with the file:

<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 quote.ts '{
    name: "quote_total",
    description: "Calculates the product and shipping total in MXN from quantity and unit price.",
    source: $source
  }')"
```

</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 fn = await platic.tools.functions.create({
  name: "quote_total",
  description: "Calculates the product and shipping total in MXN from quantity and unit price.",
  source: await readFile("quote.ts", "utf8"),
});
console.log(fn.id);
```

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

Create quote_total from quote.ts. It calculates the product and shipping total from quantity and unit price.

</Ways.Say>

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

</Ways.Way>
</Ways>

Save the function's `id` in `FUNCTION_ID`. You can't change its name later. The function starts in `draft` and is not yet available to agents. When connected, the agent will see it as `fn_quote_total`.

</Steps.Step>
<Steps.Step>

**Test the calculation**

[Test the draft](/api-reference/custom-functions/test) with two products at 250 MXN each:

<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": { "quantity": 2, "unitPrice": 250 } }'
```

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

```ts
const test = await platic.tools.functions.test(fn.id, {
  input: { quantity: 2, unitPrice: 250 },
});
console.log(test.ok, test.output);
```

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

Test quote_total with quantity 2 and unit price 250. Show the subtotal, shipping and total.

</Ways.Say>

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

</Ways.Way>
</Ways>

The test verifies the code, deploys the draft separately and runs it once. It leaves the published version unchanged. Check `ok: true` and this `output`:

```json
{ "currency": "MXN", "subtotal": 500, "shipping": 100, "total": 600 }
```

If you receive `ok: false`, check `error` and `logs`, fix the code and retry. A code failure can still return HTTP `200`. Testing and publishing count toward the workspace's limit of 50 daily deployments.

</Steps.Step>
<Steps.Step>

**Publish the function**

[Publish](/api-reference/custom-functions/publish) the draft when its result is correct:

<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": "Quote with shipping" }'
```

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

```ts
const published = await platic.tools.functions.publish(fn.id, {
  notes: "Quote with shipping",
});
console.log(published.toolId);
```

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

Publish quote_total with the note "Quote with shipping".

</Ways.Say>

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

</Ways.Way>
</Ways>

The function becomes `enabled` and the response includes `toolId`. Save it in `TOOL_ID`. Each publication creates a fixed version; later edits change the draft until you publish it again.

</Steps.Step>
<Steps.Step>

**Connect it to the agent**

[Connect the tool](/api-reference/agents/tools/connect) so the agent can use it. The connection applies immediately and doesn't require publishing the agent.

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

```bash
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
await platic.agents.tools.connect(process.env.AGENT_ID!, published.toolId!);
```

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

Connect quote_total to the Sales agent.

</Ways.Say>

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

</Ways.Way>
</Ways>

To use the function from your backend, you can also [run the published version through the API](/api-reference/custom-functions/run).

</Steps.Step>
</Steps>

## Check it worked

Ask the agent for a quote for two products at 250 MXN each. Check that it uses the function and gives a total of 600 MXN. Read [executions](/api-reference/custom-functions/executions) to review the input and output.

## If you need to call other systems

Declare allowed domains and bind their credentials as secrets. Use `http.fetch` for HTTP calls. Tests call the real system and may change it if your code does.

The [authenticated service example](/sdk/examples/custom-function#query-a-service-with-authentication) includes verification, domains, secrets, logs and errors. SOAP and XML are possible cases within this kind of integration.

<span id="limits"></span>

See [the environment and packages](/api-reference/custom-functions/environment) and [limits and usage](/api-reference/custom-functions/usage). For a single HTTP call, you can use a [custom API](/guides/connect-an-api).

## Next steps

- [Test the agent with evals](/guides/evals).
- [Custom functions](/api-reference/custom-functions): parameters, versions, pausing and restoring.
- [Complete SDK example](/sdk/examples/custom-function): creation, testing, publishing and cleanup.
