> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mobilerun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Serverless Functions

> Write typed Python automation for your agent, with links to uploads, versions, standalone runs, and routine steps.

For cloud execution through the API, see [Working with Serverless Functions](https://docs.mobilerun.ai/routines/functions.md).

A Serverless Function is versioned Python code that can run on its own or as a routine step. Use it for repeatable logic such as calling an API, transforming data, or controlling a device.

A routine is a trigger plus steps. A step can be a Serverless Function. A routine without one still works: your agent can run it with no code at all. See [Routines](https://docs.mobilerun.ai/agents/workflows.md).

> [!NOTE]
>
> You can run a function on its own, without a routine. See [Run a function directly](#run-a-function-directly).

## Install and create a function

Install the stable helper package with Python 3.11–3.13:

```bash theme={null}
pip install mobilerun-functions==0.1.0
python -m mobilerun_functions new hello.py
```

The starter creates a complete function file. For this walkthrough, replace its contents with:

```python theme={null}
from pydantic import BaseModel
from mobilerun_functions import Context, script


class Input(BaseModel):
    name: str = "world"


class Output(BaseModel):
    message: str


@script
def main(input: Input, ctx: Context) -> Output:
    ctx.log.info("greeting")
    return Output(message=f"Hello, {input.name}!")
```

A function file must have exactly one entry point marked with the bare `@script` decorator. It can use `def` or `async def`. The first parameter is a Pydantic input model; `ctx: Context` is optional. Fields with defaults are optional inputs.

The return annotation must be a Pydantic output model, `Output | None`, `None`, or `Dataset[Item]`. Use `Output | None` if returning no value is intentional; returning `None` from a required `Output` fails validation. A dataset can also use `Dataset[Item] | None` to publish items pushed through `ctx.dataset.push(...)`.

Keep the function in one file. Helper modules next to it are not importable. Model schemas support common scalar types, lists, and nested models, plus date, datetime, UUID, URL, and email formats. Regex patterns and recursive models are not supported.

`ctx.log.info(...)`, `ctx.log.warning(...)`, `ctx.log.error(...)`, and `print(...)` write log output. The platform sets the time limit. Do not print secrets.

## Return data, keep state, control a device

These parts of the `Context` are optional. Use only what your function needs.

### Return a list

Return a `Dataset` when the result is a list. Mark the field that identifies each item with `key_field()`. It must serialize to a string or an integer.

Call `ctx.dataset.push(item)` to add each item as you find it. If the run stops early, the items you already pushed are kept.

```python theme={null}
from pydantic import BaseModel
from mobilerun_functions import Context, Dataset, key_field, script


class Input(BaseModel):
    query: str


class Product(BaseModel):
    sku: str = key_field()
    name: str


@script
def main(input: Input, ctx: Context) -> Dataset[Product] | None:
    for row in find_products(input.query):  # your code
        ctx.dataset.push(Product(sku=row["sku"], name=row["name"]))
```

### Fail on purpose or return a partial result

Raise `ScriptError(code, message)` for a failure you expect. Call `ctx.partial("reason")` when the result is incomplete but still useful; the run ends as partial and shows your reason.

```python theme={null}
from mobilerun_functions import ScriptError

if input.max_pages < 1:
    raise ScriptError("bad_pages", "max_pages must be at least 1")

try:
    rows = fetch_page(page)  # your code
except TimeoutError:
    ctx.partial(f"page {page} timed out")
```

### Keep data between runs

`ctx.state.previous` holds the data saved by the last successful run of the same step, or `None` on the first run. Save new data with `ctx.state.save(...)`. Only a successful run saves state. If you change the shape of the saved data, pass a version with `ctx.state.save(data, schema=2)` and read the old one from `ctx.state.previous_schema`. Nothing on disk survives a run.

```python theme={null}
@script
def main(input: Input, ctx: Context) -> Output:
    previous = ctx.state.previous or {"count": 0}
    count = previous["count"] + 1
    ctx.state.save({"count": count})
    return Output(run_count=count)
```

### Control the device

When the routine step has a device, call `ctx.device()`. The device is connected once and reused for every call in the run. A run without a device raises an error that says so.

```python theme={null}
@script
def main(input: Input, ctx: Context) -> None:
    device = ctx.device()
    device.start_app("com.android.settings")
    screen = device.ui()  # the screen's elements are in screen.nodes
    device.tap(540, 1200)
    device.type("hello")
    image_path = device.screenshot()  # path of a temporary image file
```

Install the extra for device control: `pip install "mobilerun-functions[device]==0.1.0"`.

### Limits

| Limit | Value |
| - | - |
| Input | 1 MB |
| Result, saved state, dataset | 512 KB each |
| Timeout per step | 1 to 3600 seconds. Default 600 |

Do not print secrets. Log output is stored as you write it.

## Validate before uploading

Inspect the file locally:

```bash theme={null}
python -m mobilerun_functions inspect hello.py
```

A valid function exits with code `0` and prints JSON with `ok: true`, its entry point, and its input and output schemas. An invalid file exits with code `3` and prints the issues, including line numbers and repair hints where available.

> [!NOTE]
>
> Inspection imports your file, so top-level code runs during the check. Keep work inside the entry point. Inspection checks the function contract; it does not prove that its business logic succeeds.

You can also run this greeting locally:

```bash theme={null}
printf '{"name":"Ada"}\n' > input.json
python -m mobilerun_functions run hello.py \
  --input-file input.json --result-file result.json
cat result.json
```

The result includes `ok: true`, `outcome: "succeeded"`, `result: {"message": "Hello, Ada!"}`, and the validated input.

## Validate through the API

Use [source validation](https://docs.mobilerun.ai/routines/functions.md#upload-through-the-api) to check a function without saving it.

## Run with your own device

For interactive device work, see [Sandboxes](https://docs.mobilerun.ai/sandboxes.md). The local function runner is separate
from a hosted sandbox; a successful local run does not prove that hosted execution will succeed.

## Upload through the API

Follow [uploading and versioning](https://docs.mobilerun.ai/routines/functions.md#upload-through-the-api) for the request format,
inspection status, and SDK examples. Use your [API key](https://docs.mobilerun.ai/api-keys.md).

## Manage functions and versions

Use the **Serverless Functions** tab in **Routines**. Open a function to inspect **Code**,
**Inputs & returns**, and **Runs**. Only a ready version can run. See
[Steps and Functions](https://docs.mobilerun.ai/routines/functions.md) for version management.

Open Serverless Functions

## Run a function directly

A Serverless Function can run without a routine or a device. See
[Run it](https://docs.mobilerun.ai/routines/functions.md#run-it) for inputs, versions, results, and logs.

## Run as a routine step through the API

A routine is a trigger plus ordered steps. Choose the function action from the action catalog,
then bind its inputs. Follow [Use in a routine](https://docs.mobilerun.ai/routines/functions.md#use-it-in-a-routine) and
[Working with routines](https://docs.mobilerun.ai/routines) for the API workflow.

## Run results and errors

Inspect the result and logs for the version that actually ran. A local format check, an accepted
upload, and a successful live run prove different things. See [Runs and troubleshooting](https://docs.mobilerun.ai/routines/runs.md)
and [Steps and Functions](https://docs.mobilerun.ai/routines/functions.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.