Functions
A Function in an Andera Worker is a unit of business logic that can be called through REST /task or the optional MCP endpoint. Functions are defined in the src/functions/ directory and are auto-discovered at startup.
Structure of a Function
A function is defined using defineFunction from @andera-top/worker-core. Each function specifies:
params: The input parameters and their types. Omit it (or use{}) for a function without parameters. Parameters not declared inparamsare rejected.description: Optional explanation for agents discovering the function through MCP (defaults toExecute <name>)config: Optional configuration (timeout, retries, streaming, etc.)handler: The async function that implements the logic
Parameter Schema Options
Each parameter in params can have the following options:
| Option | Type | Description | Default |
|---|---|---|---|
type | string | Parameter type: string, number, boolean, object, array | Required |
description | string | Optional parameter explanation for MCP clients | None |
required | boolean | Whether the parameter is required | false |
default | any | Default value if not provided | None |
enum | any[] | Allowed values (for enums) | None |
pattern | string | Regex pattern (for strings) | None |
min | number | Minimum value/length (number, string, array) | None |
max | number | Maximum value/length (number, string, array) | None |
Use enum, pattern, min, and max to validate and restrict input values.
Function Config Options
The config object can have the following options:
| Option | Type | Description | Default |
|---|---|---|---|
timeout | number | Timeout in ms for each attempt; an integer between 1 and 2147483647 | DEFAULT_TIMEOUT (30000) |
maxRetries | number | Retries after ordinary failures (non-negative integer); never after a timeout | 0 |
supportsStreaming | boolean | Whether the function supports streaming mode | false |
logResult | boolean | Whether to log the function result. Set to false for heavy or sensitive data. | true |
String lengths count Unicode code points, consistently with MCP JSON Schema. Object and array enum values are compared structurally.
An invalid timeout or maxRetries value stops the Worker at startup, with an error naming the function.
Timeouts and cooperative cancellation
Each handler attempt receives context.signal, an AbortSignal. At the function's timeout, Core aborts that signal and returns an error to the caller. Pass the signal to asynchronous APIs that support cancellation:
import { defineFunction } from '@andera-top/worker-core'
import { setTimeout as delay } from 'node:timers/promises'
export const delayedHello = defineFunction({
params: { name: { type: 'string', default: 'World' } },
config: { timeout: 5000, maxRetries: 0 },
handler: async (params, context) => {
await delay(1000, undefined, { signal: context?.signal })
context?.signal.throwIfAborted()
return { message: `Hello ${params.name}!` }
},
})
For HTTP requests, pass signal: context?.signal to fetch. Check context?.signal.throwIfAborted() between processing steps. Use finally to release resources, and await cleanup before the handler settles.
- The Worker retains the slot until the handler actually settles, including cleanup after cancellation. The caller receives the timeout error without waiting for cleanup.
- Timeout failures are never retried, even with
maxRetries > 0. Ordinary failures still retry sequentially with a fresh signal per attempt. - Direct REST calls return HTTP 504 with
code: "FUNCTION_TIMEOUT"; MCP returns a tool error. If streaming has already begun, the response simply ends because its HTTP status can no longer be changed: the client cannot distinguish a stream cut off by a timeout from a complete one. Late stream writes from the handler are discarded. - Authenticated Worker
/healthlists still-running timed-out handlers inexecutions.timedOutRunning. Each entry containsfunction,startedAt,timedOutAtandtimeoutMs; inputs and secrets are omitted. Entries disappear when handlers settle. Public health and MCP-only credentials do not expose this list. - Existing handlers remain compatible. A handler that ignores cancellation can hold its slot indefinitely. Synchronous blocking code prevents the timer from firing until the event loop is free; hard interruption requires isolated execution.
- Await all child operations: detached background work is outside the handler's lifetime and slot accounting. Cancellation does not undo an external write that has already happened; keep side-effecting functions idempotent.
The function timeout starts when execution begins, excluding time waiting in the Worker queue. An LB/client deadline or disconnection does not send cancellation to the Worker; configure the LB deadline to allow for queueing and the Worker's execution deadline.
Example
import { defineFunction } from "@andera-top/worker-core";
import { log } from "@andera-top/worker-core/dist/utils/logger";
export const hello = defineFunction({
description: "Return a greeting for the given name.",
params: {
name: { type: "string", description: "The person to greet.", required: false, default: "World" },
},
config: {
timeout: 5000,
maxRetries: 0,
supportsStreaming: true,
},
handler: async (params, context) => {
log("[HELLO]", `Hello function called for ${params.name}`);
if (context?.stream) {
context.stream(`Hello ${params.name}!`);
return { streaming: true };
}
return { message: `Hello ${params.name}!` };
},
});
Logging in Functions
You can use the logging utilities to trace function calls, warnings, or errors (see Logging):
import { log, warn, error } from "@andera-top/worker-core/dist/utils/logger";
log("[MYFUNC]", "Function called");
warn("[MYFUNC]", "Something might be wrong");
error("[MYFUNC]", "Something went wrong");
Creating a New Function
- Create a new file in
src/functions/, e.g.myFunction.ts. - Export your function using
defineFunctionas shown above, either as a named export matching the file name (export const myFunction = ...) or as the default export. - The function will be auto-registered at startup under the file name (
myFunction). Files whose name starts with.or_are ignored.
Testing a Function
You can test your function by sending a POST request to the /task endpoint of your Worker:
curl -X POST http://localhost:3000/task \
-H 'Authorization: <AUTH_KEY>' \
-H 'Content-Type: application/json' \
-d '{
"function": "myFunction",
"input": { "name": "Function" },
"contract": 1,
"mode": "sync"
}'
The response will contain the result of your function.