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.

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

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.

Set your API key and run the script:

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:

PLATIC_EXAMPLE_CONNECT_AGENT=1 npx tsx custom-function.ts

What to expect

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

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.

Before you start

You need an agent with its id in AGENT_ID, and your Platica API key in PLATIC_API_KEY.

To use the platform, see Custom functions and Secrets.

Save this code as company_lookup.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 };
  },
});
  • 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.

Allowed packages: zod, @platica/functions, date-fns, decimal.js, papaparse, lodash-es and fast-xml-parser. Get the 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 rejects code that uses them.

  1. 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)

    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);

    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 from your CI.

  2. 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)

    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");
    }

    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.

  3. Bind its secret

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

    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 });

    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.

  4. 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)

    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");

    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".

    EGRESS_DENIED means the code called a domain that isn't in allowedDomains: add it with Update a function. TIMEOUT, INPUT_INVALID and OUTPUT_TOO_LARGE are the other ways an execution can fail, along with FUNCTION_ERROR (the code threw: read logs).

  5. 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, Connect a tool)

    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);

    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.

Check it worked

Run the published version with Run a function and check its output. Use Get executions to review the test and agent calls; trigger identifies the source of each execution.

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.

To recover a previous version, restore it (rollback_function). To stop its use, pause the function: it becomes unavailable to agents and keeps its code, versions and connections. You can activate it later.

Limits

WhatLimit
Functions per workspace20
Time per execution1 to 60 s; 20 s by default
Memory256 MB
HTTP calls per execution20, up to 15 s and 2 MB each
Input and output256 KB each. The agent reads up to 16,000 characters of the output
Code100 KB (1 MB bundled)
Allowed domains10 per function
Secret slots10 per function
Calls60 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 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.

Next steps