agentface

On this page

  1. 1. Before you start
  2. 2. The file
  3. 3. The fields
  4. 4. What execute gets and returns
  5. 5. What it can reach
  6. 6. Errors an agent can act on
  7. 7. A complete example
  8. 8. Submitting, and what happens next
  9. 9. Try it before you submit
  10. 10. Not yet
  11. 11. Checklist for a coding agent

Docs · Tools

How to write a tool

A tool lets AI agents do one job on your site, such as listing a signed-in visitor's orders. This page is everything you, or a coding agent you hand it to, need to write one that is accepted first time.

Updated Nov 23, 2026 · This page as Markdown

1. Before you start

A tool is one job an AI agent can do on your site, such as listing a signed-in visitor's orders. agentface offers it on every page of your site through WebMCP, the way a page hands tools to agents, beside the general tools agentface gives every site.

  • Who: an owner or an admin of the organisation. A member can't submit a tool.
  • When: once the website is live in agentface.
  • Where: on your website's Tools page in agentface, under New tool. It needs you to be signed in.
  • How many: a site has at most 25 tools of its own, the ones agentface built and yours together.

Handing the job to a coding agent, such as Claude Code? Press Copy for AI at the top of this page and paste it in: you get the whole page, with a line that asks the agent to help you write your tool. Or give it this page's address, or this page as Markdown. The checklist at the end is for it.

2. The file

A tool is one JavaScript file, .js or .mjs, that runs by itself in your visitors' pages.

  • It imports nothing. A line that starts with import followed by a name, a brace, a star or a quote is refused. Don't load other code with import() either: the file has to work alone.
  • It has exactly one export: export default, at the start of a line, followed by the tool. No other line starts with export.
  • Both are checked line by line, so they hold inside text that spans lines too.
  • It is at most 200 KB, counted in UTF-8 bytes.
  • There is no await at the top level of the file. Use await inside execute.

The file's top-level code runs once, in strict mode, the first time an agent calls the tool, not when the page loads. Keep it to constants and helper functions, and don't touch window or document there: do that inside execute.

The smallest file that is accepted:

store_hours.js
export default {
  name: "store_hours",
  description:
    "Returns the shop's opening hours for each day of the week, as JSON. Use it when someone asks when the shop is open.",
  inputSchema: { type: "object", properties: {} },
  annotations: { readOnlyHint: true },
  async execute() {
    const response = await fetch(new URL("/api/hours", location.origin), { credentials: "include" });
    if (!response.ok) {
      const error = new Error(`The site answered ${response.status}. Another call may work.`);
      error.code = "site_error";
      throw error;
    }
    return { text: JSON.stringify(await response.json()) };
  },
};

3. The fields

What follows export default is an object written out in the file, or the name of a top-level const that holds one, with these fields.

name
Required. snake_case: a lowercase letter, then lowercase letters, digits or underscores, at most 64 characters (^[a-z][a-z0-9_]{0,63}$). Unique on your site, and not help or a name agentface built a tool under. Avoid the names below.
description
Required, at most 10 KB. Say in words what the tool returns, when to use it, and what each input means: agents choose a tool by its description.
inputSchema
Required. A JSON Schema whose type is "object", at most 20 KB as JSON. One that takes nothing is { type: "object", properties: {} }. Give each property a description, and list in required what the tool can't do without.
annotations
Optional. An object of at most 2 KB as JSON. Set readOnlyHint: true when the tool changes nothing: without it, agents and agentface treat the tool as one that can change things. The other hints you may set are destructiveHint, idempotentHint and openWorldHint.
execute
Required. A function, usually async execute(input), that does the work. It is the only field that runs.

Names to avoid

agentface gives every page these general tools: read_page, list_forms, fill_form, dismiss_popups, help, and ask_site, leave_message, search_site where available. A published search index always supplies search_site. help is refused. A tool of yours with any other general tool's name takes its place on your pages. Give yours a name of its own. If your pages register a WebMCP tool of their own with the same name, theirs stays and yours is not added.

Plain values only

name, description, inputSchema and annotations are read from the file's text without running it, so each is written out as a plain value. You may use:

  • text, numbers, true, false and null
  • arrays and objects of those, with plain keys
  • the name of a top-level const that holds one of those
  • text joined with +, and template strings whose ${} parts are text or numbers
  • an array of text joined with .join()
  • Object.freeze() around any of these
  • a minus or plus sign before a number

Not allowed, because they have a value only when the file runs: spreads (...), getters, computed keys, other function calls, and names declared with let, var or function. In the tool's own object a spread, a getter or a computed key refuses the whole file.

Accepted:

orders_by_status.js
const STATUSES = ["open", "shipped", "delivered", "cancelled"];

const INPUT = Object.freeze({
  type: "object",
  properties: {
    status: {
      type: "string",
      enum: STATUSES,
      description: `Only orders with this status: ${STATUSES.join(", ")}.`,
    },
  },
  required: ["status"],
});

export default {
  name: "orders_by_status",
  description: [
    "Lists the signed-in visitor's orders with one status, newest first.",
    "Returns JSON: { total, orders: [{ id, url }] }.",
  ].join(" "),
  inputSchema: INPUT,
  annotations: { readOnlyHint: true },
  async execute({ status }) {
    const url = new URL("/api/orders", location.origin);
    url.searchParams.set("status", status);
    const response = await fetch(url, { credentials: "include" });
    if (!response.ok) throw Object.assign(new Error(`The site answered ${response.status}.`), { code: "site_error" });
    return { text: JSON.stringify(await response.json()) };
  },
};

Refused, because of the spread in inputSchema:

refused.js
const BASE = { type: "object", properties: {} };

export default {
  name: "orders_by_status",
  description: "Lists the signed-in visitor's orders with one status, newest first.",
  inputSchema: { ...BASE, required: [] },
  async execute() {
    return { text: "[]" };
  },
};

The reason it is refused with: “Write the tool’s inputSchema out in the file as a plain value. It is read without running the file, so it can’t be worked out by code.”

4. What execute gets and returns

  • It gets the input as an object: what the agent sent. With no input at all, it gets {}.
  • Before your code runs, agentface checks the input against inputSchema: each value's type, and that every required input is there. A call that fails the check never reaches your code. Nothing else is checked, so check allowed values, lengths, formats and ranges yourself, and throw bad_input when one is wrong.
  • It returns { text }, where text is a string the agent reads: usually compact JSON. Anything else fails the call as bad_result.
  • text longer than 200,000 characters is cut, with a note saying so.
  • It may add meta: a small, flat object of counts, booleans and codes for your analytics. The agent never sees it. Never put in it what the visitor or the agent typed.
  • meta: { ok: false } counts the call as failed, while the agent still gets your text.
  • A call has 15 seconds. With no answer by then, the agent is told the site was slow and that another call may work. For a tool without readOnlyHint: true, it is told instead that the call may still go through, so another call could make the change twice. Your code isn't stopped, but what it returns after that goes nowhere.
  • It must not leave the page: no change to location, no form submit that loads another page, no click on a link that does. That ends the call. Fetch the other page instead and read it with DOMParser, or return its address for the agent to open.

5. What it can reach

The tool runs in the visitor's browser tab, on whichever page of your site they are on, as that visitor. It can reach:

  • the page itself: what the visitor sees, and the data the page holds, such as JSON-LD or the state your app starts with
  • your site's own addresses, with fetch and the visitor's cookies and signed-in session: pass credentials: "include"
  • API hosts that your site's own pages already call

Nothing else. Send nothing to a server your pages don't already trust. The file is served to every visitor of your site, so it holds no keys, tokens or secrets.

Any page, any moment

An agent may call the tool on any page of your site, seconds after it loads, in a new session with no history. Build addresses from location.origin, so the tool works on each of your site's hostnames. If it needs something your app sets up as it starts, wait for it with a short poll, every 100 to 250 ms for up to about 5 seconds, not a fixed sleep, then fail with timeout.

Requests and CSRF tokens

Read a CSRF token, or any header your site expects, from the page or a cookie at the moment of the call. Never write one into the file. Give each request an AbortController, so one that stalls can't use up the 15 seconds, and clear its timer only once the answer's body is read: a site can send its headers and then stall. Inside execute:

Inside execute
const token = document.querySelector('meta[name="csrf-token"]')?.content;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
try {
  const response = await fetch(new URL("/api/cart", location.origin), {
    method: "POST",
    credentials: "include",
    headers: { "content-type": "application/json", ...(token ? { "x-csrf-token": token } : {}) },
    body: JSON.stringify({ sku: input.sku, quantity: 1 }),
    signal: controller.signal,
  });
  // …
} finally {
  clearTimeout(timer);
}

6. Errors an agent can act on

When the tool can't do its job, throw an Error with a code and a message that tells the agent what to do next.

  • code: snake_case, a lowercase letter then lowercase letters, digits or underscores, at most 40 characters (^[a-z][a-z0-9_]{0,39}$). An error without one, or with another kind, is recorded as unexpected.
  • message: what went wrong and the next step, in a sentence or two. The agent reads it.

When the visitor isn't signed in

A tool that reads a visitor's own data needs them signed in. Tell it from your site's own answer: a 401 (or the 403 your site may send instead), or a redirect to your sign-in page. Then say where to sign in:

Inside execute
const signIn = new URL("/login", location.origin);
const response = await fetch(new URL("/api/orders", location.origin), { credentials: "include" });
if (response.status === 401 || (response.redirected && new URL(response.url).pathname === signIn.pathname)) {
  const error = new Error(
    `The visitor isn't signed in. Ask them to sign in at ${signIn.href}, then call list_orders again.`,
  );
  error.code = "not_signed_in";
  throw error;
}

Codes to use

bad_input
The agent's input is missing or invalid, or your site refused a value it gave. Say which input, and what it may be.
not_found
The input is fine, and nothing matches it.
not_signed_in
The tool needs a signed-in visitor, and there isn't one. Say where to sign in.
blocked
Your site refuses automated access: a 429, a bot check or a CAPTCHA page instead of the data. Say not to call the tool again, and don't say retry.
timeout
Something the tool waits for, such as a request or the page's app starting, didn't come in time. Say the site was slow. Say another call may work only if calling again is safe: the tool changes nothing, or the change can't happen twice.
site_changed
Your site no longer works the way the tool expects, and the tool couldn't find the new way.
site_error
Your site failed for another reason, such as a 5xx answer or an error in its JSON. Include its own message.
unexpected_answer
Your site answered, but not in the form the tool expects. Say what came instead: the status, the content type and the address it ended on.

What the agent sees, and what you see

  • The agent gets your message first. Then, for most codes, how long the call took and whether another call may end differently, and then your input schema with an example input, so it can call again correctly.
  • On the tool's page under Tools in agentface, each failed call shows its code.
  • agentface keeps each failed call's message, up to 1,000 characters, beside its input for 30 days, to help you fix the tool.

Codes agentface adds

bad_input
The input didn't fit your inputSchema, by a value's type or a required input left out, so your code didn't run.
timeout
No answer within 15 seconds.
broken_tool
The file's top-level code threw, or what it exports has no execute function.
bad_result
execute returned something without a text string.
unexpected
Your code threw without a code, or with one that isn't short snake_case.

7. A complete example

list_orders lists the signed-in visitor's orders. It checks its input, waits for nothing it doesn't need, ends a request that stalls, even partway through the answer, tells a signed-out visitor where to sign in, reports an answer it can't read as unexpected_answer, caps the list at 20 with the total, gives absolute addresses and throws coded errors. It changes nothing, so it says readOnlyHint: true.

list_orders.js
// Lists the signed-in visitor's orders through the site's own GET /api/orders.
const STATUSES = ["open", "shipped", "delivered", "cancelled"];
const MAX = 20;

function fail(code, message) {
  const error = new Error(message);
  error.code = code;
  return error;
}

// The request and its answer, start to end. The signal can end it at any point, reading the body included.
async function readOrders(url, limit, signal) {
  const response = await fetch(url, {
    credentials: "include",
    headers: { accept: "application/json" },
    signal,
  });

  const signIn = new URL("/login", location.origin);
  if (response.status === 401 || (response.redirected && new URL(response.url).pathname === signIn.pathname)) {
    throw fail(
      "not_signed_in",
      `The visitor isn't signed in. Ask them to sign in at ${signIn.href}, then call list_orders again.`,
    );
  }
  if (response.status === 429) {
    throw fail(
      "blocked",
      "The site is refusing automated requests. Don't call list_orders again: send the visitor to their orders page.",
    );
  }
  if (!response.ok) throw fail("site_error", `The site answered ${response.status} ${response.statusText}.`);
  const type = response.headers.get("content-type") ?? "";
  if (!type.includes("application/json")) {
    throw fail("unexpected_answer", `Expected JSON, got ${type || "no content type"} from ${response.url}.`);
  }

  let body;
  try {
    body = await response.json();
  } catch (error) {
    if (signal.aborted) throw error;
    throw fail("unexpected_answer", `The site said it sent JSON from ${response.url}, but it couldn't be read: ${error.message}.`);
  }
  if (!Array.isArray(body?.orders)) throw fail("unexpected_answer", "The answer had no list of orders.");
  const orders = body.orders.slice(0, limit).map((order) => ({
    id: order.id,
    placed: order.created_at,
    status: order.status,
    total: order.total,
    url: new URL(`/account/orders/${encodeURIComponent(order.id)}`, location.origin).href,
  }));
  return {
    text: JSON.stringify({ total: Number.isInteger(body.total) ? body.total : orders.length, orders }),
    meta: { count: orders.length },
  };
}

export default {
  name: "list_orders",
  description: [
    "Lists the signed-in visitor's orders on this site, newest first, at most 20.",
    "Returns JSON: { total, orders: [{ id, placed, status, total, url }] },",
    "where total counts every matching order and url is the order's own page.",
    "Use it when the visitor asks about an order they placed. The visitor has to be signed in.",
  ].join(" "),
  inputSchema: {
    type: "object",
    properties: {
      status: {
        type: "string",
        enum: STATUSES,
        description: "Only orders with this status. Leave it out for every order.",
      },
      limit: {
        type: "integer",
        minimum: 1,
        maximum: MAX,
        default: 10,
        description: "How many orders to return, from 1 to 20. Defaults to 10.",
      },
    },
    additionalProperties: false,
  },
  annotations: { readOnlyHint: true },
  async execute(input) {
    const limit = input.limit ?? 10;
    if (!Number.isInteger(limit) || limit < 1 || limit > MAX) {
      throw fail("bad_input", `limit must be a whole number from 1 to ${MAX}.`);
    }
    if (input.status != null && !STATUSES.includes(input.status)) {
      throw fail("bad_input", `status must be one of ${STATUSES.join(", ")}, or left out.`);
    }

    const url = new URL("/api/orders", location.origin);
    url.searchParams.set("limit", String(limit));
    if (input.status != null) url.searchParams.set("status", input.status);

    // Ends a request that stalls, even partway through the answer, well before the call's 15 seconds are up.
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 10_000);
    try {
      return await readOrders(url, limit, controller.signal);
    } catch (error) {
      if (controller.signal.aborted) {
        throw fail("timeout", "The site was slow to answer. list_orders changes nothing, so another call may work.");
      }
      if (typeof error.code === "string") throw error;
      throw fail("site_error", `The request didn't reach the site (${error.message}). Another call may work.`);
    } finally {
      clearTimeout(timer);
    }
  },
};

8. Submitting, and what happens next

  1. On your website's Tools page in agentface, press New tool. Its editor opens on a template, with agentface beside it: say what the tool should do, and it writes the file.
  2. Or paste your own file over the template, or drop or choose the .js or .mjs file. The checks under it say what is missing. Then press Save for review.
  3. If the file can't be taken, the reason shows under the box, with your text as you sent it, to fix in place.
  4. Once it is taken, it waits to go live: Review on the Tools page lists it, marked your own, beside any tool marked built by agentface. Agents don't have it yet.
  5. An owner or an admin presses Put live. That puts live everything that is waiting, including any tool agentface built since. Once live, agents get it within about five minutes.
  • To change your tool, submit the file again under the same name: it replaces the one you sent before.
  • Take back removes your tool while it has never been live. Once it has been live, it stays until a newer version of it is put live.

Nothing runs your tool before it goes live: the file is only read. Try it yourself first.

Why a file is refused

no_tool
Paste the tool’s file, or choose it.
tool_too_large
A tool’s file is at most 200 KB.
tool_imports
A tool’s file can’t import anything. It is one file that runs by itself in the page.
tool_exports
A tool’s file exports one thing, the tool, with export default.
tool_exports
A tool’s file needs exactly one export default, at the start of a line: the tool.
tool_syntax
The file isn’t JavaScript a browser can run: …
tool_shape
The file has to export the tool written out as an object: export default { name, description, inputSchema, execute }.
tool_name
The tool needs a name in snake_case, such as list_orders: lowercase letters, digits and underscores, starting with a letter.
tool_description
The tool needs a description, in words, of what it returns: at most 10 KB.
tool_schema
The tool needs an inputSchema: a JSON Schema whose type is "object", at most 20 KB. One that takes nothing is { type: "object", properties: {} }.
tool_annotations
The tool’s annotations are an object, at most 2 KB.
tool_execute
The tool needs an execute(input) function, which returns { text }.
tool_taken
agentface already built a tool named … for this site. Give yours another name.
submit_not_live
A tool can be submitted once the site is live.
org_role
Only an owner or an admin of the organisation can do that.
tool_refused
The tool wasn’t taken: …

When name, description, inputSchema or annotations isn't a plain value, the code is that field's and the reason is “Write the tool’s … out in the file as a plain value. It is read without running the file, so it can’t be worked out by code.”, with the field's name.

tool_refused comes from the last check, as the tool joins your site's tools, followed by why: the name help, more than 25 tools on the site, more than 1,000 KB of tools' files together, or a file that doesn't parse as the body of a function, which is what an await at the top level does.

9. Try it before you submit

You can run the file on your own site from the browser's console, the way it will run there. Open a page of your site, signed in as a test visitor if the tool needs one, open the browser's developer console, and paste this, with your file in place of the comment and its export default changed to return:

Console
var tool = (function () {
  "use strict";
  // Your whole file here, with its "export default" changed to "return".
})();

Then call it with a sample input, and look at what comes back:

Console
var result = await tool.execute({ limit: 3 });
console.log(typeof result?.text === "string" ? result.text : "No text: agents would get bad_result.");

Try it signed in and signed out, with a wrong input, on another page of your site, and in a private window, where nothing from your session is there yet. A throw shows its code and message in the console.

10. Not yet

These aren't possible yet:

  • submitting a tool from a terminal, or straight from your own AI tool
  • agentface trying your tool in a browser before it goes live
  • a link to try a waiting tool on your site before it goes live
  • editing, switching off or removing a tool once it is live; submitting a newer version under the same name replaces it
  • an email when your tool goes live
  • more than 15 seconds for a call of your own tool

11. Checklist for a coding agent

Check the file against each of these before you hand it back:

  1. One .js or .mjs file of at most 200 KB.
  2. No line starts with import, and the file loads no other code.
  3. Exactly one line starts with export: export default, then the tool's object or the name of a top-level const that holds it.
  4. No await at the top level. Top-level code only defines constants and functions, and doesn't touch window or document.
  5. name matches ^[a-z][a-z0-9_]{0,63}$, isn't help, and isn't the name of another tool on the site or of agentface's general tools.
  6. description is at most 10 KB and says what the tool returns, when to use it and what each input means.
  7. inputSchema has type: "object", a description for each property and required for what the tool can't do without, and is at most 20 KB as JSON.
  8. name, description, inputSchema and annotations are plain values: no spreads, getters, computed keys or calls other than .join() and Object.freeze().
  9. annotations, if there, is an object of at most 2 KB, with readOnlyHint: true only if the tool changes nothing.
  10. execute(input) checks the input the schema can't, and returns { text } with text a string: compact JSON, absolute addresses, lists capped at about 20 with the total. meta, if any, is small and flat and holds nothing anyone typed.
  11. Every request goes to the site's own origin, or an API host its pages already call, with credentials: "include" and an AbortController whose timer runs until the body is read, and the call ends well within 15 seconds.
  12. CSRF tokens and headers are read from the page or a cookie when the tool runs. None is written in the file.
  13. execute never leaves the page.
  14. Every failure throws an Error with a snake_case code of at most 40 characters and a message that says what to do next, not_signed_in for a visitor who isn't signed in.
  15. It ran on the site from the console, as in Try it before you submit: signed in and signed out, with a wrong input, and on another page.
agentface

Your customers are starting to send AI agents. Make it easy for them to do business with you.

Talk to us

This page

  • Join the waiting list
  • Try the demo
  • Contact

For AI agents

  • index.md
  • sitemap.xml
  • robots.txt

© 2026 agentface

Privacy

Written for people, and for the agents they send.

agentface
Log inFor businesses