Skip to main content

Usage

tip

To learn how to create and use business logic in your Worker, see the Functions and Services pages.

The Base Worker exposes several endpoints and features for task execution and monitoring.

Endpoints​

EndpointMethodDescription
/mcpPOSTOptional tool discovery and calls using a dedicated MCP_AUTH_KEY.
/taskPOSTSubmit a task to the worker.
/healthGETGet the status of the worker (public info, more details with authentication).
/logsGETRetrieve recent log lines, bounded by MAX_LOGS (authentication required).
/onPOSTEnable the worker to accept new tasks (authentication required).
/offPOSTSet the worker to maintenance mode (no new tasks accepted; authentication required).
/docs, /openapiGETSwagger UI and OpenAPI specification, only when OPENAPI_ENABLED=true (unauthenticated).

Slot Management​

  • Each worker manages a number of parallel slots (e.g., 10).
  • If all slots are busy, new tasks are queued and prioritized (by the priority field, an integer from 1 to 2097152 with 1 = highest priority and the default; equal priorities are FIFO).
  • Slot availability is updated in real time and can be pushed to the Load Balancer via WebSocket.

Task Handling​

  • Direct Worker tasks specify function, contract, and optional priority. Requests through the LB also specify group. REST calls require AUTH_KEY; see the authenticated example.
  • input is an object holding the parameters accepted by the called function. It may be omitted when the function needs none; undeclared parameters are rejected.
  • contract must equal the Worker's CONTRACT.
  • The worker validates the request and executes the corresponding function.
  • If the worker is saturated, tasks are queued and processed as slots become available.
  • Function timeouts abort context.signal and return an error, while retaining the slot until the handler settles. See timeouts and cancellation.

Example contacting a Worker directly:

{
"function": "hello",
"input": { "name": "Andera" },
"contract": 1,
"priority": 1,
"mode": "sync"
}

Responses and Errors​

StatusBodyMeaning
200{ "success": true, "result": ... }sync mode: the function succeeded.
200{ "success": true, "message": "Sent to webhook" }webhook mode: the function succeeded and the result was delivered.
400{ "success": false, "error": "..." }Invalid request: priority, function name, contract mismatch, input, mode, webhook, or parameter validation. Malformed JSON returns { "error": "Invalid request" }.
401{ "error": "Unauthorized" }Missing or invalid Authorization (or x-lb-auth) header.
404{ "success": false, "error": "Function not found" }No function with this name.
413{ "error": "Invalid request" }Body larger than REQUEST_BODY_LIMIT.
500{ "success": false, "error": "Function execution failed" }The function threw (after its retries).
502{ "success": false, "error": "Failed to send webhook", "code": "WEBHOOK_FAILED" }webhook mode: the function succeeded but the result could not be delivered.
503{ "success": false, "error": "Worker is in maintenance mode" }Maintenance mode is enabled.
504{ "success": false, "error": "Function execution timed out", "code": "FUNCTION_TIMEOUT" }The function reached its timeout.

The Authorization header accepts the key as is or with a Bearer prefix.

Response Modes​

The mode field in the /task payload controls how the Worker returns the result of your function. There are three supported modes:

1. sync (default)​

  • Behavior: The Worker executes the function and returns the result in the HTTP response.
  • Usage:
    {
    "function": "hello",
    "input": { "name": "Andera" },
    "contract": 1,
    "priority": 1,
    "mode": "sync"
    }
  • When to use: For most standard function calls where you want the result immediately.

2. stream​

  • Behavior: The Worker streams the result back to the client as it is produced (useful for long-running or incremental output).
  • Prerequisite: The function must have supportsStreaming: true in its config.
  • Usage:
    {
    "function": "hello",
    "input": { "name": "Andera" },
    "contract": 1,
    "priority": 1,
    "mode": "stream"
    }
  • The response is plain text (Content-Type: text/plain) made of the chunks passed to context.stream; the function's return value is not sent.
  • Errors that occur before the first chunk return the usual JSON error. Once streaming has begun, an error or timeout simply ends the response: a stream cut off by a timeout cannot be distinguished from a complete one, so include your own end marker if the client needs to know.
  • When to use: For functions that can produce output incrementally (e.g., chat, logs, progress updates).

3. webhook​

  • Behavior: The Worker executes the function and sends the result to a specified webhook URL. The HTTP request stays open until delivery succeeds or fails; this is not an immediate background-job acknowledgment.
  • Prerequisite: You must provide a webhook object with a mandatory HTTP(S) url (without credentials in the URL). The optional headers object must contain string values. Use the final destination URL: webhook delivery does not follow redirects.
  • The Worker sends the function result as a JSON POST body, retrying up to WEBHOOK_MAX_RETRIES times with WEBHOOK_RETRY_DELAY between attempts.
  • If the function succeeded but delivery still fails, the Worker answers HTTP 502 with code: "WEBHOOK_FAILED". The function has already run: do not re-run it just to retry the delivery.
  • Webhook destinations are controlled by authenticated REST callers. The runtime does not block private-network addresses; restrict outbound network access when callers are not fully trusted.
  • Usage:
    {
    "function": "hello",
    "input": { "name": "Andera" },
    "contract": 1,
    "priority": 1,
    "mode": "webhook",
    "webhook": {
    "url": "https://your-callback.url",
    "headers": {
    "Authorization": "Bearer my-token",
    "X-Custom-Header": "value"
    }
    }
    }
  • Important: The webhook object must contain a url property when using mode: "webhook". The headers property is optional and only used to override or add to the default headers defined in the configuration (WEBHOOK_HEADERS). WEBHOOK_HEADERS are sent to whatever URL the caller supplies: do not put secrets there that API callers must not learn.
  • When to use: For asynchronous workflows or when you want the Worker to notify another service upon completion.

If mode is omitted, sync is used by default.

Maintenance Mode​

Workers support a maintenance mode that allows you to temporarily stop accepting new tasks while letting current tasks finish. This is useful for safe updates, scaling, or graceful shutdowns.

  • POST /off: Enable maintenance mode. The Worker will refuse new tasks, but ongoing tasks will continue until completion.
  • POST /on: Disable maintenance mode. The Worker will accept new tasks again.

When to use:

  • For direct usage, use maintenance mode before stopping or updating a Worker to avoid losing or interrupting tasks.
  • When using the Load Balancer and before removing a Worker from the cluster (or from workers.json), set it to maintenance mode to ensure no new tasks are sent and current tasks finish cleanly.

Example:

curl -X POST http://localhost:3000/off -H 'Authorization: <AUTH_KEY>'
curl -X POST http://localhost:3000/on -H 'Authorization: <AUTH_KEY>'

Logs and Tags​

  • /logs endpoint provides recent log lines, bounded by MAX_LOGS for monitoring and debugging. See the Logging page for details and best practices.
  • Tags are dynamic metadata exposed by the worker (e.g., Chrome version, AI model used), accessible via /health with authentication or from the dashboard of the Load Balancer. See the Tags page for usage and examples.

OpenAPI & Swagger Documentation​

The Base Worker exposes interactive API documentation endpoints when OPENAPI_ENABLED is explicitly set to true. It is false by default and in the example .env.

  • Swagger UI:

    • Accessible at: /docs
    • Provides an interactive web interface to explore and test all available endpoints and their schemas.
  • OpenAPI JSON:

    • Accessible at: /openapi
    • Returns the OpenAPI (Swagger) specification in JSON format, which can be used for client generation, integration, or further documentation.

These endpoints are useful for:

  • Discovering all available API endpoints and their parameters
  • Testing API calls directly from the browser
  • Generating client SDKs or integrating with other tools that support OpenAPI

Note: These endpoints require no authentication. Keep them disabled in production, or restrict access to them (e.g., at the reverse proxy or via IP allowlists).

MCP tools for agents​

Optional POST /mcp exposes selected local functions with one dedicated MCP_AUTH_KEY bearer token. Calls use the existing Worker queue and function runner. Authenticated /health includes sanitized MCP status and the exposed tools. See MCP setup.