Skip to content
Back to skills

Using Iii

ASecurity

}) ``` </Tab> <Tab title="Rust"> ```rust use iii_sdk::CallAction; use iii_sdk::protocol::CallRequest; use serde_json::json; let result = worker .call(CallRequest { function_id: "math::add".into(), payload: json!({ "a": 2, "b": 3 }), action: None, // action: Some(CallAction::Void), // fire-and-forget // action: Some(CallAction::Enqueue { queue: "math".to_string() }), // route through queue timeout_ms: None, } // .namespace("default"), // target a specific names...

  • 18,978 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added September 3, 2026
developmenttypescriptpythonrustgobashreactnodeexpressdebuggingdatabase

Works with

  • terminal
  • cli

Security analysis

A100/100

Pro scans all 21 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add iii-hq/iii --skill using-iii --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Using Iii?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Using Iii
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/iii-hq-using-iii-2813c864/badge)](https://www.skillsdirectory.com/skills/iii-hq-using-iii-2813c864)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
<!-- generated by iii-skill-render. DO NOT EDIT (changes here are overwritten on the next render). Edit docs/next/using-iii/functions.mdx. -->


{/* TODO: Re-link worker references to https://workers.iii.dev/workers/<name> once the Worker Docs migration ships. */}

## Register a function

Inside a worker, `worker.registerFunction(id, handler)` makes a function callable from anywhere in
the iii system. The `id` follows the `service::name` form; the handler receives the call's payload
and returns the result.

<Tabs>
  <Tab title="Node / TypeScript">
    ```typescript
    import { registerWorker } from "iii-sdk";

    const url = process.env.III_URL;
    if (!url) throw new Error("III_URL must be set");
    const worker = registerWorker(url, { namespace: "orders" });

    worker.registerFunction("math::add", async (payload: { a: number; b: number }) => {
      return { c: payload.a + payload.b };
    });
    ```

  </Tab>
  <Tab title="Python">
    ```python
    import os
    from iii import register_worker, InitOptions

    worker = register_worker(
        os.environ.get("III_URL"),
        InitOptions(
            worker_name="math-worker",
            namespace="orders",
        ),
    )

    def add_handler(payload: dict) -> dict:
        return {"c": payload["a"] + payload["b"]}

    worker.register_function("math::add", add_handler)
    ```

  </Tab>
  <Tab title="Rust">
    ```rust
    use iii_sdk::{InitOptions, RegisterFunction, register_worker};

    let url = std::env::var("III_URL").expect("III_URL must be set");
    let worker = register_worker(
        &url,
        InitOptions {
            namespace: Some("orders".into()),
            ..Default::default()
        },
    );

    worker.register_function("math::add", RegisterFunction::new(|input: AddInput| {
        Ok(serde_json::json!({ "c": input.a + input.b }))
    }));
    ```

  </Tab>
  <Tab title="Go">
    ```go
    client := iii.RegisterWorker(os.Getenv("III_URL"), iii.WithNamespace("orders"))

    client.RegisterFunction("math::add", func(ctx context.Context, data json.RawMessage) (any, error) {
        var payload struct {
            A float64 `json:"a"`
            B float64 `json:"b"`
        }
        if err := json.Unmarshal(data, &payload); err != nil {
            return nil, err
        }
        return map[string]float64{"c": payload.A + payload.B}, nil
    })
    ```

  </Tab>
</Tabs>

## Call a function

`call` runs a function and resolves to its result. The engine routes the call to the worker that
registered the function, wherever it runs. Call a function from the terminal with `iii call`, or
from worker code with `worker.call`. The `action` field sets how the call is delivered: by default
the call waits for the function to return its result, or for the configured timeout to fire.

<Tabs>
  <Tab title="CLI">
    ```bash
    iii call math::add a=2 b=3
    ```
  </Tab>
  <Tab title="Node / TypeScript">
    ```typescript
    import { CallAction } from "iii-sdk";

    const result = await worker.call({
      function_id: "math::add",
      payload: { a: 2, b: 3 },
      // namespace: "default", // target a specific namespace
      // action: CallAction.Void(), // fire-and-forget
      // action: CallAction.Enqueue({ queue: "math" }), // route through queue
    });
    ```

  </Tab>
  <Tab title="Python">
    ```python
    from iii import CallAction

    result = worker.call({
        "function_id": "math::add",
        "payload": {"a": 2, "b": 3},
        # "namespace": "default", # target a specific namespace
        # "action": CallAction.Void(), # fire-and-forget
        # "action": CallAction.Enqueue(queue="math"), # route through queue
    })
    # result = await worker.call_async({...}) # awaitable form for asyncio callers
    ```

  </Tab>
  <Tab title="Rust">
    ```rust
    use iii_sdk::CallAction;
    use iii_sdk::protocol::CallRequest;
    use serde_json::json;

    let result = worker
        .call(CallRequest {
            function_id: "math::add".into(),
            payload: json!({ "a": 2, "b": 3 }),
            action: None,
            // action: Some(CallAction::Void),                                  // fire-and-forget
            // action: Some(CallAction::Enqueue { queue: "math".to_string() }), // route through queue
            timeout_ms: None,
        }
        // .namespace("default"), // target a specific namespace
        )
        .await?;
    ```

  </Tab>
  <Tab title="Go">
    ```go
    result, err := client.Call(ctx, iii.CallRequest{
        FunctionID: "math::add",
        Payload:    json.RawMessage(`{"a":2,"b":3}`),
        // Namespace:  "default", // target a specific namespace
        // Action: iii.VoidAction(),          // fire-and-forget
        // Action: iii.EnqueueAction("math"), // route through queue
    })
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("math::add returned %s", result)
    ```

  </Tab>
</Tabs>

The actions are:

- **Default (synchronous)**. No `action` set. The call waits for the function to return its result
  or for the configured timeout to fire.
- **`CallAction.Void()`**. Fire-and-forget. The call returns at once; the function still runs, and
  the caller does not see the result.
- **`CallAction.Enqueue({ queue })`**. Provided by [queue](https://workers.iii.dev/workers/queue).
  Routes the call through a named queue with retries; the call returns once the message is enqueued.

Workers can provide their own `CallAction`s. Check each
[worker's documentation](https://workers.iii.dev) for the actions it offers.

<Info>
  Refer to [Using iii / Namespaces](./namespaces#call-a-function-in-a-namespace) for more
  information on namespaces and calling functions in a specific namespace.
</Info>

<Note>
  A call to a function that the calling worker registered itself runs in-process once the engine
  confirmed the registration (local dispatch), with the same result, errors, and timeout as a call
  through the engine. Pass `dispatch: "remote"` (Python `"dispatch": "remote"`, Rust
  `.dispatch(Dispatch::Remote)`, Go `Dispatch: iii.DispatchRemote`) to send one call through the
  engine. See [Local dispatch](./observers#local-dispatch).
</Note>

<Note>
  In Python, every blocking method has an awaitable twin (`call_async`, `shutdown_async`,
  `pipe_async`) for use inside `asyncio`. See the [Python SDK reference](../reference/sdk-python).
</Note>

### Routing to a namespace

Workers and their associated functions can be namespaced. A function id is unique per namespace, not
globally: `state::get` can be registered once in `default`, once in `orders`, and once in
`analytics`. Set `namespace` on the call to pick one.

Resolution is strict. A call that names `orders` resolves there and nowhere else, and a call that
names none resolves in the namespace of the calling worker. A miss returns `function_not_found`
naming the namespaces where the id does exist.

<Note>
  `iii call` reaches `default` unless you pass `--namespace <NS>`, also from a process whose
  `III_NAMESPACE` names another namespace, such as a script Compose starts. For calling across
  namespaces from worker code, see [Use namespaces](./namespaces#call-a-function-in-a-namespace).
</Note>

## Run a function when something happens

A call runs a function once, when you make it. To run a function each time something happens
(another function runs, an HTTP request arrives, a row changes), observe the function that
represents it:

<Tabs>
  <Tab title="Node / TypeScript">
    ```typescript
    // When math::add runs, run audit::record.
    worker.observe("math::add", "audit::record");

    // Every day at 09:00, run reports::daily-summary.
    worker.observe(
      { function_id: "cron::on-tick", args: { expression: "0 0 9 * * * *" } },
      "reports::daily-summary",
    );
    ```

  </Tab>
  <Tab title="Python">
    ```python
    # When math::add runs, run audit::record.
    worker.observe("math::add", "audit::record")

    # Every day at 09:00, run reports::daily-summary.
    worker.observe(
        {"function_id": "cron::on-tick", "args": {"expression": "0 0 9 * * * *"}},
        "reports::daily-summary",
    )
    ```

  </Tab>
  <Tab title="Rust">
    ```rust
    use iii_sdk::Source;
    use serde_json::json;

    // When math::add runs, run audit::record.
    worker.observe("math::add", "audit::record");

    // Every day at 09:00, run reports::daily-summary.
    worker.observe(
        Source::function("cron::on-tick").args(json!({ "expression": "0 0 9 * * * *" })),
        "reports::daily-summary",
    );
    ```

  </Tab>
  <Tab title="Go">
    ```go
    // When math::add runs, run audit::record.
    client.ObserveFunction("math::add", "audit::record")

    // Every day at 09:00, run reports::daily-summary.
    client.Observe(iii.Source{
        FunctionID: "cron::on-tick",
        Args:       iii.Args{"expression": "0 0 9 * * * *"},
    }, "reports::daily-summary")
    ```

  </Tab>
</Tabs>

See [Observers](./observers).

### Every function is observable

Any worker can observe any function, private ones included, unless the function is registered with
`observable: false` or RBAC restricts it.

The worker that registers a function can make it private or unobservable, and can override what iii
does by default when it is observed; see
[Observable functions](../creating-workers/observable-functions).

## Call functions from the CLI

iii call is useful for running functions during development without needing to write temporary code

`iii call` is a useful development tool. Pass `--help` to any function to see its arguments and a
description of what it does:

```bash
iii call function::id --help
```

Because `iii call` runs through the exact same code paths as the rest of the system, you can do real
work straight from the terminal: figure out what a function does, apply database modifications, make
state changes, or try any other manipulation or new code interactively. That makes it a useful tool
for development and debugging.

<Note>
  Request and response formats are what make `iii call <function> --help` work. Functions can carry
  JSON Schemas for their request payload and response shape. For how to create these schemas when
  registering a function, see
  [Creating Workers / Functions](../creating-workers/functions#attach-request-and-response-schemas).
</Note>

### Streams from the CLI

When a function's request schema has a `stdout` or `stderr` stream that it writes, or a `stdin`
stream that it reads, `iii call` connects it to its own standard output, standard error, or
standard input. When the result carries a `stdout` or `stderr` stream, `iii call` prints it as
well. The call ends once the function answered and its streams ended.

```bash
# The function writes into `stdout`: its lines appear as they come.
iii call reports::export report_id=r-42

# Save the output to a file. It is written as it arrives, not at the end.
iii call reports::export report_id=r-42 > report.csv

# Run the call without its streams and print the result JSON.
iii call reports::export report_id=r-42 --no-follow
```

- Only fields named `stdout`, `stderr`, and `stdin` are bound. A function meant for the command
  line names its streams that way.
- A call to a function that takes a stream has no timeout unless you pass `--timeout-ms`, also
  with `--no-follow`.
- While a stream runs, the result JSON is printed only with `--print-result`, after the streams
  end.
- The first `Ctrl+C` or `SIGTERM` closes the streams. The function sees its next write fail, stops,
  and answers, and `iii call` exits with that answer. A second one exits at once.
- `--no-follow` connects no stream and leaves the streams of the result unread. The call only
  runs, and the result JSON is printed with each stream shown as a ref. A function that needs its
  stream answers with an error.

| Exit code | When                                                                   |
| --------- | ---------------------------------------------------------------------- |
| `0`       | The call succeeded and every stream ended.                             |
| `1`       | The function failed, or a stream it wrote was aborted.                 |
| `2`       | The arguments, engine address, or `III_CALL_DEFAULTS` are unusable.    |
| `130`     | A second `Ctrl+C`, or one after the answer while a stream still runs.  |
| `143`     | The same for `SIGTERM`.                                                |

When the function fails, `iii call` prints `Error: {code, message, stacktrace}` on standard error,
on one line when standard error is not a terminal, so a script can read `code` and `message`. Other
failures, such as arguments that cannot make a call (exit code `2`) or an engine that cannot be
reached, print a plain-text `Error:` line instead.

### Defaults from the environment

`III_CALL_DEFAULTS` holds a JSON object keyed by namespace, each holding entries keyed by function
id. When you call a function that has an entry in the namespace the call resolves in, `default`
without `--namespace`, the entry is the base payload, and `--json` and `key=value` override its
keys. A parent process uses it to hand a call values that must not appear on the command line,
where `ps` shows them, such as a token:

```bash
export III_CALL_DEFAULTS='{"default": {"reports::export": {"report_id": "r-42"}}}'
iii call reports::export              # report_id is r-42
iii call reports::export report_id=r-7
iii call reports::export -n orders    # no entry in orders: no report_id
```

Only the function the entry names, in the namespace it is written under, receives it. The same
function id in another namespace is another handler and receives nothing. A value that is not a JSON object fails the call
with exit code `2`, and the message quotes nothing of the value.

## Common functions

A handful of functions ship with the iii engine and the standard workers. You'll likely call them
from almost every iii project. They look like any function you'd register yourself and are called
the same way (with [`iii call`](./cli) or [`worker.call`](#call-a-function)). The only thing special
about them is that you didn't have to register them.

### Engine functions (`engine::*`)

The engine itself registers a small set of introspection and lifecycle functions. Full request and
response schemas are in the
[engine protocol reference](../reference/engine-protocol#engine-discovery-functions).

| Function                     | What it does                                                                                                                                                       |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `engine::functions::list`    | List every registered function with its `args_format`, `private`, `observable`, and observer count. Pass `{ include_internal: true }` to include engine internals. |
| `engine::workers::list`      | List every connected worker with its metrics. Pass `{ worker_id: "<uuid>" }` to look one up.                                                                       |
| `engine::channels::create`   | Allocate a pipe and return its writer and reader refs. The SDK calls it for each [stream](../creating-workers/streaming) in a call, and for `iii.pipe()`.          |
| `engine::workers::register`  | Publish the calling worker's metadata (runtime, version, OS, PID, optional `namespace`, optional `description`). The SDK calls this automatically on connect.      |
| `engine::observers::list`    | List observers. Pass `{ function_id, namespace, worker }` to narrow the list. See [Inspect observers](./observers#inspect-observers).                              |
| `engine::observers::get`     | Read one observer by `{ id }`.                                                                                                                                     |
| `engine::observers::dispose` | Remove an observer by `{ id }`. Only its observing worker, or a caller without RBAC restrictions, may do it.                                                       |

The engine also hosts event sources for its registry. Observe them to react when it changes:

| Function                       | Runs when                                                |
| ------------------------------ | -------------------------------------------------------- |
| `engine::on-functions-changed` | A function is registered or unregistered.                |
| `engine::on-workers-changed`   | A worker connects, disconnects, or updates its metadata. |
| `engine::on-observers-changed` | An observer changes state.                               |

See [Engine-hosted event sources](./observers#engine-hosted-event-sources) for their events.

### Common workers

Each of these is published by a separate worker. Function ids, payload shapes, and per-function
behaviour are in the worker's own docs at [workers.iii.dev](https://workers.iii.dev):

<Warning title="Deprecated">
  `iii-stream` is deprecated (iii-stream) and will be removed in an upcoming release. `pubsub` is
  deprecated (pubsub) and will be removed in an upcoming release. Behavior is unchanged for now. See
  [Migrate from iii-stream and pubsub](../upgrading/migrate-from-streams).
</Warning>

- **HTTP**: Serves HTTP routes. Observe `http::on-request` with a method and a path to add a route.
  See [http](https://workers.iii.dev/workers/http).
- **Cron**: Runs functions on a schedule. Observe `cron::on-tick` with an expression. See
  [cron](https://workers.iii.dev/workers/cron).
- **State**: KV-style state with scoped key namespaces (distinct from
  [routing namespaces](../understanding-iii/namespaces)). Each create, update, and delete runs
  `state::on-changed`, which you observe. See [state](https://workers.iii.dev/workers/state).
- **Stream** (deprecated): Real-time push to connected clients over WebSocket. See
  [iii-stream](https://workers.iii.dev/workers/iii-stream). Use
  [observable functions](../creating-workers/observable-functions) or
  [streams](../using-iii/streaming) for new work.
- **Queue**: Durable, ordered job processing with retries, concurrency limits, and a dead-letter
  queue. Observe `queue::on-message` to consume a topic. See
  [queue](https://workers.iii.dev/workers/queue).
- **Pub/Sub** (deprecated): Lightweight in-engine topic subscription for fan-out without durability
  guarantees. See [pubsub](https://workers.iii.dev/workers/pubsub). Use observable functions or
  durable queue topics for new work.
- **Observability**: Traces, logs, metrics, alerts, sampling rules, and rollups. See
  [iii-observability](https://workers.iii.dev/workers/iii-observability).

Files in this skill

  • cli.mdx1.8 KB
  • cli.mdx.skill.md1.8 KB
  • compose.mdx39.1 KB
  • compose.mdx.skill.md39.1 KB
  • configuration.mdx7.6 KB
  • configuration.mdx.skill.md7.5 KB
  • console.mdx7.5 KB
  • console.mdx.skill.md7.5 KB
  • deployment.mdx3.2 KB
  • deployment.mdx.skill.md3.2 KB
  • engine.mdx3.1 KB
  • engine.mdx.skill.md2.8 KB
  • functions.mdx10.9 KB
  • functions.mdx.skill.md10.9 KB
  • namespaces.mdx7.6 KB
  • namespaces.mdx.skill.md7.6 KB
  • triggers.mdx11.4 KB
  • triggers.mdx.skill.md11.4 KB
  • workers-registry.mdx1.6 KB
  • workers-registry.mdx.skill.md1.6 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.