How custom code tools work
A custom code tool is a JavaScript function you add to a thunk so the AI agent can run deterministic logic during a workflow — calculations, status checks, lookups, and calls to other tools. The agent calls the tool by name, passes structured inputs, and uses whatever the function returns.
When a workflow step or a custom AI tool would copy a large value into this tool, or copy a large result back, map those fields on that caller with Map I/O. See Map a tool's inputs and outputs to the work item. The mapping is on the caller, not inside this tool: the script still reads the filled-in inputs with getTypedInput(), and still passes exact values on any tools.* calls.
Use a code tool when the same inputs should always produce the same output: comparisons, date arithmetic, filtering a list, or chaining a few integration calls in a fixed order. When the agent has to pick one item by comparing it with others ("the cheapest", "the most recent"), have the code tool make the comparison and return the chosen item, not just the list to choose from; see "Answer 'which one' with a query tool" in Custom Tools. If the work needs language understanding or judgment, use a custom AI tool instead.
This article is the JavaScript contract: how to write the function, which globals exist, how to return a result, and how to keep the script readable. Naming, input descriptions, and the shared tool-builder sections are covered in Custom Tools.
What belongs in a code tool
A code tool is the right place for logic that is fixed: the same typed inputs always give the same answer, and a person could check the answer without reading the case. Keep two things out of it.
Data does not go in the code. A table of records — products and what their labels list, a reference list of codes, a rate card, countries and the authority for each — belongs in a Spreadsheets content folder on the thunk, one tab per kind of record. The code reads it through the folder's list and lookup tools (see Calling other tools: tools). In the folder, the business owner can see the data and change it without editing code, and every tool and step reads the same copy. If the data already lives in another system the thunk reaches through a connection, call that connection's tools instead of keeping a second copy. Thresholds and short lists of allowed values are not data in this sense: they are part of the rule, and they go in named constants at the top of the script.
Judgment does not go in the code. Deciding what a piece of free text means — which product a reporter meant by a misspelled name, which country "the clinic in Lyon" is in, whether a description names a more specific condition than the one coded — is the AI agent's job. Substring checks, regular expressions and spelling-distance matches on free text guess at meaning and fail on the first wording they were not written for. Instead:
Give the agent a lookup tool that returns the candidates (the products, the reference terms, the countries).
Let the agent choose one, and record it in a property with a fixed list of allowed values.
Have the code tool take that chosen value as an input and apply the fixed rule to it.
Two more rules keep a code tool easy to trust:
One source for each rule. When a policy document states a rule and a code tool applies it, say in the tool's description which document it implements, and keep the document as the written source. Don't also give the step's agent the document to apply the same rule again: two copies of a rule drift apart.
Comments explain the business rule, not how the tool came to be written. Leave out change history, test results and ticket numbers; the thunk's work log is the place for those.
Create the tool
Open Custom-built tools in the left navigation.
Click Add New Tool and choose Custom Code Tool.
In Logic/Intent, describe what the tool does: its inputs, the steps it takes, what it returns, and any side effects. This is the one required field, and the cursor starts in it.
Optionally fill in the Tool name and Description (the AI agent uses both to decide when to call it). Leave them blank and the tool builder names and describes the tool.
Click Create tool. The tool builder writes the JavaScript, the Inputs (each field the caller must pass) and any Outputs from your intent.
Review the Inputs, Outputs and the code in the Code editor, and change them if you need to.
Under Tools, enable any libraries this script may call (for example Microsoft Excel or another application library). Those tools appear on the tools object inside the script. More libraries can be turned on at the thunk level.
The Try It tab runs the tool with sample arguments before you rely on it in a workflow. Add lasting cases on the Tests tab — see Automated tests for custom tools.
JavaScript format
The code is plain JavaScript. You cannot import or require packages. Standard language features work, including async/await, optional chaining (?.), destructuring, and template literals.
There are two valid shapes.
Function body (preferred)
Write statements directly. Thunk.AI runs them inside an async function, so top-level await and return are allowed. Do not add an extra async function run() { ... }; run(); wrapper, and do not end with (async () => { ... })(); — those extra wrappers discard the return value, so the tool appears to return nothing.
const input = getTypedInput();
const status = (input.CurrentStatus || "").trim();
if (["Completed", "Cancelled", "Closed"].includes(status)) {
return "NO";
}
return "YES";
Full async function
The entire editor contents can be one async function. Thunk.AI calls that function and passes the raw input object.
async function run(input) {
const status = (input.CurrentStatus || "").trim();
if (["Completed", "Cancelled", "Closed"].includes(status)) {
return "NO";
}
return "YES";
}
The script is treated as a full function only when it starts with async (after leading whitespace). A comment or helper before async function changes how the code is run. Prefer the function-body form unless you intentionally want a single callable async function.
Inside a full function, the input argument is the raw object from getInput(). You can still call getTypedInput() from the body if you want schema-typed fields.
Reading inputs
Helper | What it returns |
| The same arguments, with each field coerced to its declared input type ( |
| The raw arguments object after schema validation, with no extra coercion. |
Field names match the Inputs section and are case-sensitive. Guard against empty strings and unused optional fields:
const input = getTypedInput();
const name = (input.CustomerName || "").trim();
if (!name) {
throw new Error("CustomerName is required");
}
If the tool needs "today", declare it as an input (for example CurrentDate) instead of reading the clock. A tool that reads the current time cannot be tested from a fixed test case.
Leave language to AI
A code tool checks structured values: ids, numbers, dates, booleans, and choices from a fixed list. Do not use it to work out what free text means. Lists of words to look for, keyword checks, and regular expressions that try to tell whether a comment is a complaint, a reply is a yes, or a form answer is complete all break on wording you did not foresee. They miss synonyms, negation ("not approved"), typos, and other languages. They also fail quietly: the tool returns a confident wrong answer instead of an error.
Watch for these in particular:
Branching on words in a person's answer. Have the AI record the answer as one of a fixed list of values, and branch on that value.
Finding a record by its name in one language. Look it up by its id, or let the agent pick from a lookup tool's candidates and record the id.
Working out what kind of field or question something is (a file upload, an email address, a phone number) from its wording. Read the type from the source's own data, or have an AI tool decide and return a value from a fixed list.
Searching an AI tool's written explanation for words to accept or overrule its verdict. Give the AI tool an output field for each decision (yes or no, or a fixed list) and read that field.
Keeping lists of words that mean yes, no or "don't know", or of ways to name a numbered option, usually in only one or two languages. Have the AI turn the answer into a typed value: yes or no, a number, one of the allowed options, or no answer.
Put the reading in an AI step or a custom AI tool instead, and have it record the result as a structured value, such as a Text property with a fixed list of allowed values (see Structure Types and the Type Library). The code tool then checks that value:
// Route the request by the category the AI step recorded.
// Returns the queue name.
const QUEUE_BY_CATEGORY = {
Billing: "finance",
Technical: "support",
};
const input = getTypedInput();
return QUEUE_BY_CATEGORY[input.Category] || "triage";
When a code tool needs one such judgment partway through its work, it can call a custom AI tool on the same thunk and use the value it returns. Enable the AI tool under the code tool's Tools first (see Calling other tools: tools). Each call adds AI time and cost.
Matching exact codes and identifiers is fine: a status from a fixed list, an order number, or the format of an email address. The rule is about meaning, not about strings.
What to return
return a JSON value: an object, array, string, number, boolean, or null. Do not return functions or other non-JSON values.
A string or number is a scalar result (for example
"YES"or a count). That matches an Outputs contract that declares a single value.An object with named fields matches an Outputs property list. The AI agent reads those fields by name in later steps.
Always return something. If the script ends without a return, the tool succeeds and returns the text undefined.
Globals always available
These exist in every custom code tool:
Global | Purpose |
| Read the tool's arguments (see above). |
| Write trace lines. They show up in a Console block with the tool result on the Try It tab and on the Call history tab, separate from any Tools called. |
| Pause for the given milliseconds ( |
| UTC date helpers. Use these instead of |
| Call the tools this code tool can use (see below). |
| Call the tools of one connection by its name (see below). |
| Open a File input. Returns the file-bound tools for it, plus |
Ordinary JavaScript built-ins are available too (JSON, Math, Array, Object, String, Number, Boolean, Promise, Map, Set, Date). There is no Node.js process, no file system, no package manager, and no global fetch (or other raw HTTP client). The tool cannot eval a string or use new Function(...) to run extra JavaScript — only the script in the tool's Code field runs. Call other tools with tools.* or connections[...]. To read a File input, use openFile — do not fetch the file's URL.
Dates: thunk.dates
Every code tool has thunk.dates. It is all UTC. Pass anything date-like ("YYYY-MM-DD", a longer ISO string, a Calendar Date field, or a Date) and get a Date back — or null if the value cannot be parsed (impossible dates such as 2026-02-31 are rejected rather than rolled over).
Helper | Result |
|
|
|
|
| Shift by |
| Shift by |
| Signed whole days; |
| Signed weekdays; |
| Boolean, or |
|
|
| Null-tolerant |
thunk.dates has no "today" helper. Pass the current date in as an input.
const input = getTypedInput();
const start = thunk.dates.parse(input.StartDate);
const today = thunk.dates.parse(input.CurrentDate);
if (!start || !today) {
throw new Error("StartDate and CurrentDate must be YYYY-MM-DD");
}
return {
continueTracking: false,
DaysOpen: thunk.dates.calendarDaysBetween(start, today),
};
Calling other tools: tools
When you enable libraries under the tool's Tools section, they appear as async methods on tools. For example, after you enable an integration that can list and update customers:
const customers = await tools.list_customers({});
const match = customers.find((c) =>
(c.name || "").toLowerCase().includes(input.nameSubstring.toLowerCase()),
);
if (!match) {
throw new Error("No customer matched that name");
}
await tools.update_customer({ id: match.id, company: input.newCompany });
return { updatedCustomerId: match.id, updatedCompany: input.newCompany };
Those tools.* calls run only when this tool itself runs. If Reuse identical lookups is on and a later call reuses a stored result, none of them happen — so do not turn reuse on when this function writes, sends, or otherwise changes something. See Cache results of a custom AI or code tool.
Names are turned into valid JavaScript identifiers: lowercased, and characters other than letters, digits, _, and $ become underscores. So a tool advertised as list-customers is called as await tools.list_customers({ ... }) (or tools["list_customers"]). Do not write tools.list-customers — that is invalid JavaScript.
If a tool call fails, await throws an Error whose message is the tool's error. When the tool you call is another code tool, the message is what that tool threw. When it is a tool on an MCP connection and the server answers that the call failed, the message is the server's error text. Catch the error when the script should carry on; otherwise let it fail the tool:
let customer;
try {
customer = await tools.get_customer({ id: input.customerId });
} catch (e) {
return { found: false, reason: e.message };
}
Decide which failures are results. When the tool looks up a value that comes from outside the system, such as an address on a lead or a name a customer typed, "not found" is an answer the work has to handle, not a fault. Catch that one answer, return it as a value the tool's output allows (for example an Unresolved status), and say in the step's directions what to do with it. Let every other failure fail the tool. If the expected "not found" fails the tool instead, the agent tends to retry with guessed variations of the value, and the step can stop after repeated failed calls.
Try each code tool that calls another system once with a call you know will fail, such as an unknown id or a write the system refuses. Check that the tool fails with the system's error message. If it fails later with a message from one of your own checks instead, the failed call's result was treated as data.
Pass only the business arguments the tool's schema lists. Do not copy extra reasoning fields you might see when the AI agent calls tools in a chat.
Calling a tool the script cannot reach fails with Tool … not found, followed by the names it can call. That happens when nothing is enabled under Tools, or when the library is enabled but its connection is not in the thunk Owner's account. In the second case the message also names the connection, so you know which one to reconnect. Enable the library first, or the script cannot call it.
Calling a connection's tools: connections
A tool that comes from a connection can also be called through that connection by name. A connection here is anything the thunk's Connections list shows: an MCP server, a REST API, a built-in integration, another thunk whose tools you use, or a plug-in connection. Use the name exactly as the list shows it:
const matches = await connections["Acme CRM"].tools.search({ query: input.company });
Use this form when two connections have a tool with the same name. For example, if two MCP servers both have search, tools.search fails because it cannot tell which one you mean, and connections["Acme CRM"].tools.search calls the one on Acme CRM. Tool names follow the same rules as on tools.
If no connection has that name, the call fails with Connection … not found and lists the connections the tool can use. A name that differs only in upper and lower case still works when only one connection matches. Object.keys(connections) lists the connection names, and Object.keys(connections["Acme CRM"].tools) lists that connection's tools.
Renaming a connection breaks calls that use its old name. After a rename, run the thunk's Workflow Review: its design review reports each call to a connection the tool no longer has. This thunk's own custom tools are not a connection: call them on tools.
Working with files: openFile
File tools (Excel, Google Sheets, Google Docs, Word) bind to an open file rather than standing alone. When a caller passes a File input, open it and call those tools on the handle — not on tools. The same handle can also read the file's bytes or mint a short-lived download link for an attachment.
const currentFile = await openFile(getTypedInput().workbook);
const rows = await currentFile.tools.lookup_excel({
where: [{ columnName: "sku", filter: "A-1" }],
select: null,
firstMatchOnly: true,
});
await currentFile.tools.append_to_excel_workbook({
rows: [{ update: [{ name: "sku", value: "B-2" }] }],
});
return { url: currentFile.url, rowCount: rows.length };
openFile(url, options?) returns { url, mimeType, tools, getBytes, getDownloadLink }:
urlis where the file actually resolved (it can differ from the string you passed).toolsholds only the tools bound to that file, with the same name rules astools.*. InspectObject.keys(currentFile.tools)rather than assuming names — for example the Excel append tool isappend_to_excel_workbook. A file type with no matching library still opens:toolsis empty and you can still read the file.getBytes()returns the current file as bytes (Uint8Array). Use this when your script needs the file itself. Do notreturnthose bytes as the tool result — only JSON-serializable values survive. Files larger than 10 MiB cannot be read this way.getDownloadLink()returns a short-lived signed download URL (expires after 1 hour). Use this when you want to attach the file to an email or pass it to another tool that fetches a file from a URL — includinggeneric_api_post_binaryon a REST API connection. Same kind of link as Convert URLs to signed download URLs on a connected tool.options.refresh(openFile(url, { refresh: true })) re-binds after your code changes the file's shape, such as adding a column.
Enable at least one library in this tool's Tools section or openFile explains that it is unavailable. Enable the matching library (for example Microsoft Excel) when you need that file's tools. A File input whose access is Read only gets the read tools only — in-place updates are withheld.
tools.* stays the file-independent set. File tools live on the handle from openFile, not on tools.
To upload a File input to a REST API as raw bytes, enable the REST API library and generic_api_post_binary under this tool's Tools section, then pass getDownloadLink(). See Connecting to External Systems and Tools.
const file = await openFile(getTypedInput().attachment);
await tools.generic_api_post_binary({
path: "/files/upload?name=report.pdf",
mimeType: file.mimeType,
publicContentUrl: await file.getDownloadLink(),
});
Messaging a conversation
A custom code tool can also send on a work-item conversation. Add a Conversation input (or a Reference that points at a Conversation property). When the tool runs on a work item, tools includes add_message_to_<property> for that conversation, and getConversationTranscript("EndUserConvo") returns what has been said so far. Set waitMode to waitForReply when the next line of script needs the person's answer. To hand the same conversation to another custom tool, pass getInput().EndUserConvo (or getTypedInput()) — that is the conversation, not the transcript.
The Try It tab has no work item, so those send tools are not there. Test cases on the Tests tab can run them on a copy of a conversation. How to declare the input, the send-tool arguments, and full examples for both custom code and custom AI tools are in How to build a tool that uses a conversation.
To attach the file to an email, enable Communications and send_email for this tool, then pass the signed URL:
const currentFile = await openFile(getTypedInput().invoice);
const link = await currentFile.getDownloadLink();
await tools.send_email({
recipientEmails: [getTypedInput().recipient],
subject: "Invoice",
body: "See attached.",
fileAttachments: [{ name: "invoice.pdf", url: link, inlineAsHtml: false }],
});
return { sent: true };
When a code tool waits
A code tool can wait for a reply on a conversation (see How to build a tool that uses a conversation). It does not pause in the middle of the script. When the reply arrives, the script runs again from the first line:
Tool calls that already finished are not made again. Each returns the result it returned before, in the same order, so the script reaches the waiting call with the same values. A call that failed throws the same error again.
Everything else runs again.
sleeppauses again, andopenFile,getBytes, andgetDownloadLinkopen, read, and create links again. Console lines come from the last run only.The clock stops after the first wait. On the first run
Date.now()is the current time. On every run after a wait it returns the time the tool first started, however long the wait lasted. Do not measure elapsed time across a wait.The conversation transcript is read again, so code after the wait can see the reply.
Write the script with that in mind:
Make the same tool calls in the same order on every run. Decide what to call from inputs and tool results, not from
Math.random().Put anything that must happen exactly once, such as sending or creating something, inside a tool call.
Wait for one reply at a time. Start a waiting call with
await, not insidePromise.all; overlapping waits fail with "Await long-running tools one at a time. Overlapping tool calls cannot wait."Do not change the tool's code while work items are waiting in it. When the reply arrives, the tool fails with "This code tool changed while it was waiting. It cannot resume safely." If the tool was renamed or deleted, the wait ends with an error and the step continues from that error.
The run-time limit applies to each run of the script. Time spent waiting for a reply does not count.
Write code people can read
The thunk's owners and admins read a code tool's script in the Code editor to review it, change it, and work out what went wrong when a run gives an unexpected answer. Write it the way you would want to find it, whether you write it yourself or have an AI assistant write it for you:
One statement per line, indented two spaces inside each block. Never put the whole script on one line or minify it.
Start with a short comment that says what the tool does and what it returns. In the full async function form, put the comment on the first line inside the function: the script must start with
async.Name fixed values at the top. Thresholds and short lists of allowed statuses go in named constants (
const MAX_DAYS_OPEN = 30;), not as bare numbers and strings in the middle of the logic. A table of records is data, not a fixed value: read it from a Spreadsheets folder (see What belongs in a code tool).Use descriptive names for variables and helpers (
daysOpen,isOverdue), not single letters, except for a short callback such as(c) => c.id.Split long logic into small helper functions, each with a name that says what it works out, instead of one long expression or deeply nested conditions.
Comment the business rules, not the JavaScript: say why a value is compared or a case is skipped ("contracts under 10,000 do not need legal review"), not what
ifdoes.Name what you return. When the tool returns more than one value, return an object whose fields match the tool's Outputs, so the caller and a reviewer can both see what each value means.
// Decide whether an invoice needs a manual check.
// Returns { needsReview, reasons }.
const REVIEW_THRESHOLD = 10000;
const TRUSTED_VENDORS = ["Acme Supplies", "Globex"];
function reviewReasons(invoice) {
const reasons = [];
if (invoice.Amount > REVIEW_THRESHOLD) {
reasons.push("Amount is over the review threshold");
}
// Invoices from vendors we have not vetted are always checked.
if (!TRUSTED_VENDORS.includes(invoice.Vendor)) {
reasons.push("Vendor is not on the trusted list");
}
return reasons;
}
const input = getTypedInput();
const reasons = reviewReasons(input);
return { needsReview: reasons.length > 0, reasons };
When the tool builder or an AI assistant connected through the FDA MCP writes a script, Thunk.AI checks it. A script with a line longer than 160 characters, or with more than three lines and no comments, is still saved, but the assistant is told the code is hard to read and asked to send it again formatted and commented. When an assistant connected through the FDA MCP sends a script that is not valid JavaScript, for example one cut off part way, nothing is saved and the assistant is told the line where the code breaks. An assistant can also change part of a script without sending all of it again: it names the exact text to find and the text to put in its place, and the change is refused unless that text appears exactly once.
Limits to keep in mind
No
import/require, no npm packages, no access to the machine's file system, and no globalfetch.Return JSON-serializable values only.
getBytes()returns aUint8Arrayyou can use inside the script; do not return it as the tool result.The run is time-bounded (about 15 minutes), including any
sleepcalls.Each run of the script can use about 4 minutes of CPU time. Waiting on tools or in
sleepuses almost none of it. A script that goes over stops with an error that it exceeded the CPU time limit.One run can make at most 50 tool calls, counting
tools.*and the tools on files opened withopenFiletogether. The next call throws an error and does not run the tool. To work through more items, have the tool handle fewer items per call and call it more than once.Clicking Stop on a step also stops a code tool script that is still running for it.
Empty code fails with an error that the tool has not been implemented yet.
consolelines are captured for debugging; they are not the tool's return value — alwaysreturnthe result.
Once the script behaves on the Try It tab, capture that invocation as a test case so later edits cannot silently change the result.
