> ## 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.

# Automate your own device

> Read your device, send a morning briefing, and approve a personal assistant action.

Review notification titles, send a morning briefing, and approve a contact before it is saved.

> [accordion] Setup (once)
>
> ```bash Python theme={null}
> pip install mobilerun-sdk
> export MOBILERUN_API_KEY=dr_sk_...   # API Keys page
> export DEVICE_ID=...                 # a ready device from the dashboard
> python example.py
> ```
>
> ```bash TypeScript theme={null}
> npm init -y && npm pkg set type=module
> npm install @mobilerun/sdk && npm install -D tsx
> export MOBILERUN_API_KEY=dr_sk_...   # API Keys page
> export DEVICE_ID=...                 # a ready device from the dashboard
> npx tsx example.ts
> ```

## Review notifications

Collect notification app names and titles as structured output without opening messages.

**Needs:** Your own Android device connected through [Portal](https://docs.mobilerun.ai/guides/connect-android.md) or a ready Cloud Android device · API key and `DEVICE_ID` · task credits and Cloud Android device usage · one-shot, \~1 min.

> List the app names and titles visible in my notification shade without opening or dismissing notifications.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import os
> from pydantic import BaseModel, field_validator
> from mobilerun_sdk import MobilerunSDK
>
>
> class Notification(BaseModel):
>     app: str
>     title: str
>
>     @field_validator("app", "title")
>     @classmethod
>     def not_blank(cls, value: str) -> str:
>         if not value.strip():
>             raise ValueError("blank value")
>         return value
>
>
> class Notifications(BaseModel):
>     notifications: list[Notification]
>
>
> mobilerun = MobilerunSDK()
> device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
> task = device.run(
>     task="Inspect the notification shade and list visible notification app names and titles only. Do not open, expand, dismiss, or reply to notifications, or change settings. Return an empty list if there are none; fail if unreadable, never guess.",
>     output_schema=Notifications,
>     max_steps=20,
> )
> print(f"Task: {task.id}", flush=True)
> rows = task.wait_output().output.notifications
> for row in rows:
>     print(f"{row.app}: {row.title}")
> if not rows:
>     print("No notifications")
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const text = z.string().trim().min(1);
> const notifications = z.object({ notifications: z.array(z.object({ app: text, title: text })) });
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const task = await device.run({
>   task: 'Inspect the notification shade and list visible notification app names and titles only. Do not open, expand, dismiss, or reply to notifications, or change settings. Return an empty list if there are none; fail if unreadable, never guess.',
>   outputSchema: output(notifications),
>   maxSteps: 20,
> });
> console.log(`Task: ${task.id}`);
> const rows = (await task.waitOutput()).output.notifications;
> for (const row of rows) console.log(`${row.app}: ${row.title}`);
> if (!rows.length) console.log('No notifications');
> ```

Illustrative result

```text theme={null}
Messages: New message
```

## Build a morning briefing

Read today's calendar and notification titles, then print the briefing or send it to a webhook.

**Needs:** Connected Android device or ready Cloud Android · API key and `DEVICE_ID` · Calendar app and accessible schedule · optional `WEBHOOK_URL` · task credits and Cloud Android device usage · one-shot, a few minutes.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import json
> import os
> from urllib.request import Request, urlopen
> from pydantic import BaseModel, field_validator
> from mobilerun_sdk import MobilerunSDK
>
>
> class Event(BaseModel):
>     time: str
>     title: str
>
>
> class Notification(BaseModel):
>     app: str
>     title: str
>
>
> class Briefing(BaseModel):
>     date: str
>     events: list[Event]
>     notifications: list[Notification]
>
>     @field_validator("date")
>     @classmethod
>     def date_present(cls, value: str) -> str:
>         if not value.strip():
>             raise ValueError("Missing date")
>         return value
>
>
> def format_briefing(data: Briefing) -> str:
>     events = [f"- {e.time}: {e.title}" for e in data.events]
>     notifications = [f"- {n.app}: {n.title}" for n in data.notifications]
>     return "\n".join([
>         f"Morning briefing — {data.date}",
>         "Calendar:", *(events or ["- No events today"]),
>         "Notifications:", *(notifications or ["- No notifications"]),
>     ])
>
>
> def main() -> None:
>     mobilerun = MobilerunSDK()
>     device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
>     task = device.run(
>         task=("Read-only morning briefing on my device: use the Calendar app to list today's "
>               "event times and titles, inspect the notification shade for unread notification app "
>               "names and titles only. Return the device's date "
>               "as YYYY-MM-DD; use empty arrays when there are no events or notifications. "
>               "Never open, dismiss, expand, or reply to notifications; do not open message "
>               "contents. Do not change settings or modify any data. If a required value cannot "
>               "be read, fail rather than guess."),
>         output_schema=Briefing,
>         max_steps=40,
>     )
>     print(f"Task: {task.id}")
>     text = format_briefing(task.wait_output().output)
>     webhook = os.environ.get("WEBHOOK_URL")
>     if webhook:
>         # Slack reads text; Discord reads content.
>         payload = json.dumps({"text": text, "content": text}).encode("utf-8")
>         request = Request(webhook, data=payload, headers={"Content-Type": "application/json"})
>         with urlopen(request, timeout=15) as response:
>             if not 200 <= response.status < 300:
>                 raise RuntimeError(f"Webhook returned HTTP {response.status}")
>     else:
>         print(text)
>
>
> if __name__ == "__main__":
>     main()
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const text = z.string().trim().min(1);
> const briefing = z.object({
>   date: text,
>   events: z.array(z.object({ time: text, title: text })),
>   notifications: z.array(z.object({ app: text, title: text })),
> });
>
> function formatBriefing(data: z.infer<typeof briefing>): string {
>   const events = data.events.map((event) => `- ${event.time}: ${event.title}`);
>   const notifications = data.notifications.map((item) => `- ${item.app}: ${item.title}`);
>   return [
>     `Morning briefing — ${data.date}`,
>     'Calendar:', ...(events.length ? events : ['- No events today']),
>     'Notifications:', ...(notifications.length ? notifications : ['- No notifications']),
>   ].join('\n');
> }
>
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const task = await device.run({
>   task: "Read-only morning briefing on my device: use the Calendar app to list today's " +
>     'event times and titles, inspect the notification shade for unread notification app ' +
>     "names and titles only. Return the device's date " +
>     'as YYYY-MM-DD; use empty arrays when there are no events or notifications. ' +
>     'Never open, dismiss, expand, or reply to notifications; do not open message ' +
>     'contents. Do not change settings or modify any data. If a required value cannot ' +
>     'be read, fail rather than guess.',
>   outputSchema: output(briefing),
>   maxSteps: 40,
> });
> console.log(`Task: ${task.id}`);
> const message = formatBriefing((await task.waitOutput()).output);
> if (process.env.WEBHOOK_URL) {
>   const response = await fetch(process.env.WEBHOOK_URL, {
>     method: 'POST', headers: { 'Content-Type': 'application/json' },
>     body: JSON.stringify({ text: message, content: message }), signal: AbortSignal.timeout(15_000),
>   });
>   if (!response.ok) throw new Error(`Webhook returned HTTP ${response.status}`);
> } else {
>   console.log(message);
> }
> ```

![Calendar on the test device](https://docs.mobilerun.ai/images/examples/personal-phone/l2-calendar.png)

Illustrative result

```text theme={null}
Morning briefing — 2026-11-12
Calendar:
- No events today
Notifications:
- No notifications
```

## Save a contact with approval

Prepare a local contact, then let a human approve whether the agent saves it.

**Needs:** Connected Android device or ready Cloud Android · API key and `DEVICE_ID` · Contacts app with writable Device storage · task credits and Cloud Android device usage · runs daily until stopped with Ctrl+C.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import os
> import sys
> import time
> from mobilerun_sdk import MobilerunSDK
>
> mobilerun = MobilerunSDK()
> device = mobilerun.devices.from_id(os.environ['DEVICE_ID'])
> interval = int(os.getenv('INTERVAL_SECONDS', '86400'))
> cycles = int(os.getenv('CYCLES', '0'))  # 0 means run until interrupted
> approval = os.getenv('APPROVE')
> if approval is not None and approval not in ('yes', 'no'):
>     raise ValueError('APPROVE must be yes or no')
> if approval is None and not sys.stdin.isatty():
>     raise ValueError('Set APPROVE=yes or APPROVE=no for non-interactive runs')
>
>
> def run(goal):
>     task = device.run(task=goal, max_steps=40)
>     print(f'Task: {task.id}', flush=True)
>     task.wait()  # raises if the task fails
>
>
> count = 0
> while True:
>     run('Open Contacts and inspect whether a local Device contact named Docs Test with phone +1 555 0100 can be added. Do not create, save, or change any contact.')
>     approved = approval == 'yes' if approval is not None else input('Save contact Docs Test, +1 555 0100? [y/N] ').strip().lower() == 'y'
>     if approved:
>         run('In Contacts, save one local Device contact named Docs Test with phone +1 555 0100. If that exact contact already exists, leave it unchanged and do not create a duplicate. Do not modify other contacts.')
>         print('Approved task completed.')
>     else:
>         print('Rejected; no save task submitted.')
>     count += 1
>     if cycles and count >= cycles:
>         break
>     time.sleep(interval)
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { createInterface } from 'node:readline/promises';
> import { stdin, stdout } from 'node:process';
>
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const interval = Number(process.env.INTERVAL_SECONDS ?? '86400');
> const cycles = Number(process.env.CYCLES ?? '0'); // 0 means run until interrupted
> const approval = process.env.APPROVE;
> if (approval !== undefined && !['yes', 'no'].includes(approval)) throw new Error('APPROVE must be yes or no');
> if (approval === undefined && !stdin.isTTY) throw new Error('Set APPROVE=yes or APPROVE=no for non-interactive runs');
>
> async function run(goal: string) {
>   const task = await device.run({ task: goal, maxSteps: 40 });
>   console.log(`Task: ${task.id}`);
>   await task.wait(); // throws if the task fails
> }
>
> for (let count = 0; !cycles || count < cycles; count++) {
>   await run('Open Contacts and inspect whether a local Device contact named Docs Test with phone +1 555 0100 can be added. Do not create, save, or change any contact.');
>   let approved = approval === 'yes';
>   if (approval === undefined) {
>     const input = createInterface({ input: stdin, output: stdout });
>     try { approved = (await input.question('Save contact Docs Test, +1 555 0100? [y/N] ')).trim().toLowerCase() === 'y'; }
>     finally { input.close(); }
>   }
>   if (approved) {
>     await run('In Contacts, save one local Device contact named Docs Test with phone +1 555 0100. If that exact contact already exists, leave it unchanged and do not create a duplicate. Do not modify other contacts.');
>     console.log('Approved task completed.');
>   } else {
>     console.log('Rejected; no save task submitted.');
>   }
>   if (!cycles || count + 1 < cycles) await new Promise((resolve) => setTimeout(resolve, interval * 1000));
> }
> ```

![Approved Docs Test contact on the device](https://docs.mobilerun.ai/images/examples/personal-phone/l3-contact.png)

Result

```text theme={null}
Approved task completed.
```

The interactive prompt accepts `y`; anything else rejects. For unattended runs, `APPROVE=yes` pre-approves every cycle and `APPROVE=no` rejects every cycle. Set `CYCLES=1` for one run or `INTERVAL_SECONDS` to change the default daily interval.

To use cron instead of the loop, set `CYCLES=1` and `APPROVE=yes` in a private environment file, then schedule a single run at 7:00 a.m. in the host's local time:

```cron theme={null}
0 7 * * * . /path/to/private.env; /path/to/venv/bin/python /path/to/example.py >> /path/to/personal-phone.log 2>&1
```

## Run it on many devices

> [!TIP]
>
> This runs on as many devices as you need: each device is checked in parallel.

Check whether Google Maps is installed on each consenting household or team device, in parallel. This reads the installed-app list without installing or updating anything.

**Needs:** API key · 2+ ready devices whose owners consent · `DEVICE_IDS` or all ready devices · task credits and Cloud Android device usage · one-shot

Set `DEVICE_IDS` to a comma-separated list of consented device IDs. If it is omitted, the example checks every ready device on the account; use that fallback only when every owner has consented.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import asyncio
> import os
> import sys
> from pydantic import BaseModel
> from mobilerun_sdk import AsyncMobilerunSDK, AsyncDevice
>
>
> class Maps(BaseModel):
>     installed: bool
>
>
> mobilerun = AsyncMobilerunSDK()
>
>
> async def check(device: AsyncDevice) -> tuple[str, str, bool]:
>     name = device.name or device.id
>     try:
>         if device.state != "ready":
>             raise ValueError("Device is not ready")
>         task = await device.run(
>             task="Check the installed apps list in Settings for Google Maps. Return whether it is installed. Do not launch, install, update, or remove apps, or change settings. If the list cannot be read, fail rather than guess.",
>             output_schema=Maps,
>             max_steps=20,
>         )
>         print(f"{name}: task {task.id}", file=sys.stderr, flush=True)
>         installed = (await task.wait_output()).output.installed
>         return name, "Installed" if installed else "Not installed", True
>     except Exception as error:
>         return name, f"Error: {error}", False
>
>
> async def main() -> None:
>     ids = [x.strip() for x in os.getenv("DEVICE_IDS", "").split(",") if x.strip()]
>     if ids:
>         devices = [await mobilerun.devices.get(i) for i in ids]
>     else:
>         devices = [d async for d in mobilerun.devices.list(state=["ready"])]
>     if not devices or len({d.id for d in devices}) != len(devices):
>         raise SystemExit("Provide distinct device IDs or make devices ready")
>     rows = await asyncio.gather(*(check(d) for d in devices))
>     print("Device | Google Maps")
>     for name, result, _ in rows:
>         print(f"{name} | {result}")
>     sys.exit(0 if all(ok for _, _, ok in rows) else 1)
>
>
> asyncio.run(main())
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK, type Device } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const mobilerun = new MobilerunSDK();
> const devices: Device[] = [];
> const ids = (process.env.DEVICE_IDS ?? '').split(',').map(x => x.trim()).filter(Boolean);
> if (ids.length) {
>   for (const id of ids) devices.push(await mobilerun.devices.get(id));
> } else {
>   for await (const device of mobilerun.devices.list({ state: ['ready'] })) devices.push(device);
> }
> if (!devices.length || new Set(devices.map(d => d.id)).size !== devices.length) throw new Error('Provide distinct device IDs or make devices ready');
>
> async function check(device: Device) {
>   const name = device.name || device.id;
>   try {
>     if (device.state !== 'ready') throw new Error('Device is not ready');
>     const task = await device.run({
>       task: 'Check the installed apps list in Settings for Google Maps. Return whether it is installed. Do not launch, install, update, or remove apps, or change settings. If the list cannot be read, fail rather than guess.',
>       outputSchema: output(z.object({ installed: z.boolean() })),
>       maxSteps: 20,
>     });
>     console.error(`${name}: task ${task.id}`);
>     const { installed } = (await task.waitOutput()).output;
>     return { name, result: installed ? 'Installed' : 'Not installed' };
>   } catch (error) {
>     throw { name, error: error instanceof Error ? error.message : String(error) };
>   }
> }
>
> const results = await Promise.allSettled(devices.map(check));
> console.log('Device | Google Maps');
> for (const row of results) {
>   if (row.status === 'fulfilled') console.log(`${row.value.name} | ${row.value.result}`);
>   else console.log(`${row.reason.name} | Error: ${row.reason.error}`);
> }
> if (results.some(row => row.status === 'rejected')) process.exitCode = 1;
> ```

Illustrative result

```text theme={null}
Phone | Google Maps
Phone A | Installed
Phone B | Not installed
```

## Next steps

* Explore [tasks](https://docs.mobilerun.ai/tasks.md) and [Personal Phones](https://docs.mobilerun.ai/device-types.md#personal-phone).

> [accordion] For AI agents
>
> Start with the first example on a ready device the user names. Notification titles and calendar details may be sensitive; use only devices whose owners consent. For the multi-phone check, select only consented devices. Uses `device.run`, `task.waitOutput()` and device state; the contact example saves a contact after approval. Ask before saving a contact or sending a briefing; never purchase anything or use real accounts. Report the result and any failed step.


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