# Mobilerun > This file is very large and may be truncated. For an index of this content, please refer to https://docs.mobilerun.ai/llms.txt instead. # Use these docs with AI agents Source: https://docs.mobilerun.ai/agents-docs Read Mobilerun documentation as Markdown or connect it directly to your AI tools. ## Copy or open any page Use the page menu at the top of any page to copy it as Markdown or view its Markdown source. You can also open the page in ChatGPT, Claude, or Perplexity, connect the docs MCP server to Cursor or VS Code, or copy its URL. ## Markdown for every page Append `.md` to a docs page URL to read its Markdown directly: ```bash theme={null} curl -s https://docs.mobilerun.ai/devices.md ``` The response has the `text/markdown` content type, so an agent can read the page without parsing the website layout. ## llms.txt * [llms.txt](https://docs.mobilerun.ai/llms.txt) is the documentation index: use it to discover pages and choose which ones to read. * [llms-full.txt](https://docs.mobilerun.ai/llms-full.txt) contains all pages in one file: use it when you need the complete documentation as context. ## Docs MCP server Connect to `https://docs.mobilerun.ai/mcp` to search and read the documentation from your AI tool. The server also offers a tool for submitting documentation feedback. Run the Claude Code command in your terminal, add the Codex entry to `~/.codex/config.toml`, or merge the Cursor entry into `~/.cursor/mcp.json`: ```bash Claude Code theme={null} claude mcp add --transport http mobilerun-docs https://docs.mobilerun.ai/mcp ``` ```toml Codex theme={null} [mcp_servers.mobilerun-docs] url = "https://docs.mobilerun.ai/mcp" ``` ```json Cursor theme={null} { "mcpServers": { "mobilerun-docs": { "url": "https://docs.mobilerun.ai/mcp" } } } ``` > [!NOTE] > > The docs MCP server provides documentation access; it cannot control phones. To control phones, connect the [Mobilerun MCP server](/mcp-server) and see [Agent skills](/skills/overview). # Devices Source: https://docs.mobilerun.ai/agents/devices Ask your agent to activate, create, and manage phones, apps, accounts, proxies, numbers, and mailboxes. Your agent works on the phones already in your account (Cloud Android, Cloud iOS, and Personal Phones, Android and iPhone), or creates a Cloud Android phone when you ask. It can only create Cloud Android phones. It also handles the things a phone needs to be useful: apps, logins, a proxy, and verification codes. ## Cloud Android Tell your agent what you want to do and it activates a ready phone from your account. If you have several ready phones, it asks which one before touching any of them. Say "switch to my other phone" to change targets mid-conversation. Ask for a subscription Cloud Android phone when you need a persistent setup, or explicitly ask for a pay-as-you-go phone for temporary work. Your agent checks the available templates and capacity. A subscription phone uses a slot and an eligible dedicated proxy; pay-as-you-go phones use device minutes while running and residential traffic for their country proxy. See [Cloud devices](/cloud-devices) for billing modes, templates, stopping, resuming, and deletion, and [Credits & usage](/credits) for the meters. Your agent presents purchase options when capacity is missing; you complete purchases yourself. ### Stop, resume, and delete Ask explicitly to stop, resume, reset, or delete a named phone. Stop preserves a pay-as-you-go phone’s data; delete erases it. A reset wipes apps, accounts, and storage. In **Manual** mode, these sensitive actions use approval cards. **Auto** can approve eligible actions automatically; some requests still need a confirmation card. Read [Human in the loop](/agents/human-in-the-loop). Subscription and Personal Phones do not use the pay-as-you-go stop/resume flow. > Stop my test phone and keep its apps and logins. > Resume my test phone for another check. > [!WARNING] > > Deletion and reset destroy data. Ask for a stop if you only want to pause a pay-as-you-go phone. ## Installing apps Your agent tries the Mobilerun App Store first, since it needs no Google account. If an app isn't in the Store, it shows you one card with the options: install from Google Play (needs a Google account signed into the phone), use the website instead, or cancel. There is no Play Store on iOS. | Source | Needs | Notes | | - | - | - | | Mobilerun App Store | Nothing | Curated catalog, the default install path | | Google Play Store | A Google account signed into the phone | Offered on the card when the app isn't in the Mobilerun Store | | An app you uploaded | Uploading the file under [Apps](/apps) | Ask your agent to install that app on a phone; it picks it from your Apps library | > Install TikTok on my Cloud Android phone. > I uploaded my own build in the Apps tab, put it on my second phone. If an app needs a Google account and none is set up, your agent asks before starting that setup. ## Accounts and credentials For any login, signup, or verification, your agent prefers a Cloud Android subscription phone. On a pay-as-you-go phone it warns you first: stopping the phone keeps your logins, but deleting it erases them. Saved logins live in your credential store, referenced by name only. Credential tools expose metadata and references instead of saved secret values. Do not paste passwords, tokens, or verification codes into chat. To save a new login, it opens an in-chat card and you type the values there directly, never into the conversation. Your agent can't attach a credential to a task itself. A saved login is filled in when you attach it in the [Task runner](/tasks#run-a-task) credential picker, or when a routine injects it. If neither applies, the app's login screen asks for the password on the phone, and your agent tells you so and waits for you to type it there. For 2FA, codes from your Mobilerun mailboxes, numbers you rented through your agent, and saved authenticator (TOTP) secrets are filled in automatically. For any other code, you type it on the phone yourself. Your agent never asks you to relay a code in chat. | You can ask | It needs from you | Needs approval | | - | - | - | | Log into an app with a saved credential | The credential attached in the Task runner or a routine | No, beyond the normal login screen | | Save a new login | Filling in the in-chat credential card | Card is the only path in, no separate approval | | Handle a 2FA or OTP prompt | Nothing for mailbox, rented number, or saved authenticator codes; otherwise typing the code on the phone | No | See [Credentials](/credentials) for how the credential store works. ## Proxies Apps see a Cloud Android phone's network location through its IP address. Many apps restrict or challenge traffic from datacenter IPs, so Mobilerun recommends a proxy for any phone that signs into real accounts. Ask your agent which proxies you have and it lists them, with which device each one is connected to. Ask it to connect a Mobilerun proxy to a phone and it confirms the change before making it. WireGuard proxies are connected in the dashboard. Cancelling a managed proxy or deleting one you brought yourself needs your approval. Buying a new proxy happens through a purchase card your agent shows you; it never invents a price. > Set up a dedicated proxy for my Instagram phone. > Which proxy is my second Cloud Android phone using right now? See [Proxies](/proxies) for proxy types and setup. ## Phone numbers and SMS verification Ask your agent which numbers you already have and which can receive the verification code you need. It can use available capacity, and shows purchase options when more capacity is required. See [Phone numbers](/identity/numbers) for capabilities and availability. > Verify this signup with an available US phone number. ## Mailboxes for email verification Ask for a mailbox to receive an email code or confirmation link. Your agent can create one from available capacity and read its messages during a signup. A mailbox is separate from a connected personal inbox. See [Mailboxes](/identity/mailboxes) for receiving mail and capacity. > Create an email inbox for testing this new app. ## Websites and app shortcuts Apps come first. If there is no app for what you need, or you ask for the web version, your agent opens the site in Chrome on the phone and works there, including logins, search, and pages that load as you scroll. It can switch a site to its desktop layout when the mobile page hides what you need. For well-known apps such as TikTok, Instagram, X, Reddit, LinkedIn, WhatsApp, Uber, and Gmail, your agent can jump straight to a profile, post, search, or settings screen instead of tapping through menus. That is faster and less likely to break when an app changes its layout. Android only. > Open the LinkedIn profile for this URL and tell me their current title. ## Connected services Your agent can also work with services you connect, such as Gmail, Google Calendar and Drive, GitHub, Slack, Microsoft Teams, and OneDrive, and pair that with device work. See [Integrations](/agents/integrations). ## Related > [card] [Results](/agents/results) > > How your agent scrapes lists, diffs runs, and delivers files. > [card] [Human in the loop](/agents/human-in-the-loop) > > How approvals and questions work in chat. > [card] [Limits and costs](/agents/limits-and-costs) > > Credits, step budgets, and what your agent hands off. > [card] [Credentials](/credentials) > > The credential store behind saved logins. # Serverless Functions Source: https://docs.mobilerun.ai/agents/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](/routines/functions). 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](/agents/workflows). > [!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](/routines/functions#upload-through-the-api) to check a function without saving it. ## Run with your own device For interactive device work, see [Sandboxes](/sandboxes). 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](/routines/functions#upload-through-the-api) for the request format, inspection status, and SDK examples. Use your [API key](/api-keys). ## 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](/routines/functions) for version management. Open Serverless Functions ## Run a function directly A Serverless Function can run without a routine or a device. See [Run it](/routines/functions#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](/routines/functions#use-it-in-a-routine) and [Working with routines](/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](/routines/runs) and [Steps and Functions](/routines/functions). # Getting started Source: https://docs.mobilerun.ai/agents/getting-started Go from your first conversation with your agent to your first result on a device. This page walks you from signing in to reading your first result. It takes a few minutes. **1. Sign in** Open Mobilerun and sign in or create an account. You do not need a device for file, public-API, or connected-service work. Open Mobilerun **2. Say hello** Open Matty and say what you want to do. Name the app or service, the result you want, and any file it should use. If device work is needed, your agent checks the available phones. **3. Get a phone** For work inside a phone app, use an existing Cloud Android, Cloud iOS, or Personal Phone, or ask your agent to help you get one. Ask explicitly for a pay-as-you-go Cloud Android phone if that is what you want; it uses device minutes while running. See [Phones, apps & accounts](/agents/devices), [Cloud devices](/cloud-devices), and [connecting your own phone](/devices) for setup and lifecycle details. **4. Give it a real task** Describe a concrete goal instead of a vague one. "Automate my phone" is too broad; "open Settings and tell me the Android version" is something it can just do. See the example prompts below. **5. Read the result** Your agent leads with the outcome, not a play by play. It states what succeeded or failed, gives you the file, link, or count you asked for, and offers a next step only when a decision is actually needed. **6. Answer if it asks** Mid-task, your agent sometimes pauses to ask a clarifying question or to get your approval before a sensitive action, like resetting a device. Answer it and the task continues. See [Human in the loop](/agents/human-in-the-loop) for how these work and what happens if you walk away. ## Prompts to try Copy any of these into your first chat, adjusted to your own app or site. > Open Settings and tell me the Android version. > Log into this app with my account and tell me my current balance. > Scrape all attendees of this Luma event and give me a CSV. > Check my inbox app and summarize anything unread from the last 24 hours. > Take a screenshot of the home screen so I can see what's installed. > Check this page every morning and tell me if the price drops. > [!TIP] > > Be specific about the app, the data you want, and the format. A precise goal takes fewer steps > to complete, and fewer steps means a cheaper run. See [Limits and costs](/agents/limits-and-costs). ## Related > [card] [Overview](/agents/overview) > > What your agent is and what it can do. > [card] [Devices](/agents/devices) > > Cloud Android phones, pay as you go, apps, and accounts in more depth. > [card] [Human in the loop](/agents/human-in-the-loop) > > Questions, approvals, and coming back to a paused run. > [card] [Cloud Quickstart](/cloud/quickstart) > > Run a task from the API instead of chat. # Human in the loop Source: https://docs.mobilerun.ai/agents/human-in-the-loop When your agent asks you a question or waits for your approval before doing something sensitive, and what happens while you decide. Your agent does not guess on things that matter, and it does not act on sensitive requests without checking with you first. Both show up as a card in the chat. ## When your agent asks a question Your agent asks when it needs information only you can give, or when a step is genuinely ambiguous, such as which of two matching accounts you meant. A question can arrive as option cards you tap to answer, free text you type yourself, or both together. Answer directly in the chat. There is nothing else to configure. > Which of these two events did you mean: "Design Meetup" on the 12th, or "Design Meetup Berlin" on the 19th? Your agent does not ask for confirmation on everything, only where the answer actually changes what it does next. ## What needs your explicit approval In **Manual** mode, sensitive actions use approval cards, including: * Creating a Cloud Android subscription phone * Resetting a device to a clean state * Stopping or resuming a pay-as-you-go phone * Permanently removing a temporary, pay-as-you-go phone * Cancelling a managed proxy or deleting one you brought yourself * Deleting a recording * Deploying a routine, and aborting, unblocking, enabling, or archiving one * Turning off a routine's health monitoring or its notifications * Creating or archiving an agent, or changing an agent's instructions * Writes to connected services, such as posting a Slack message or editing a file Creating a pay-as-you-go phone is different: when you explicitly ask for one, that request counts as your consent and your agent creates it. It asks you to confirm per-minute billing in the conversation only when your request doesn't clearly accept it. ### Auto mode The chat composer offers **Manual** and **Auto**. Auto approves eligible actions without a new card. Some actions always ask: creating or archiving an agent, changing its instructions, deploying a routine with a real verification run, archiving or enabling a routine, and turning its health monitoring off. Delegating routine creation to another agent also needs approval. Use Manual to keep approval prompts for eligible sensitive actions. > [!WARNING] > > These are one-way or billable actions. Your agent tells you what it is about to do in one short sentence before the approval card appears, so it never shows up out of nowhere. You can approve or decline. A one-time approval applies to that request. Supported integration-write cards can also offer **Always allow**, which saves a grant for the organization; custom MCP writes do not support this. Auto mode changes which eligible actions ask again. Declining stops the action; nothing happens. Everyday, reversible steps, like installing an app or filling out a form, do not need this card. It is reserved for actions you cannot casually undo. ## Saving a login If a task needs you to log into an app for the first time, your agent does not ask you to type your password into the chat. It shows a secure card where you enter your credentials directly. Afterward your agent only knows a reference to them, never the actual value. > Save my login for this app so future runs don't need to ask me again. If a session on the device is already active, your agent skips the login step entirely rather than asking you to save anything. ## If you do not answer Questions and approvals can pause work, and pending requests can expire. If a card has expired, send a new message so your agent can check the current state before requesting the action again. Do not assume a closed tab means unlimited running time; turns have a time limit. ## Leaving the tab and coming back If the job is running on a phone, closing the chat does not stop it. Work already in progress on the device continues. When you reopen the conversation, it catches you up automatically, including any question or approval that is still waiting for you. You do not need to scroll back through everything that happened while you were away. If you would rather not check back manually, set up notifications so you hear the moment your agent finishes, fails, or needs your answer to a question. See [Notifications](/agents/notifications). ## Stopping a running job Ask your agent to stop, or use the stop control in the chat. This stops the current chat turn. It does not undo completed actions or cancel scheduled routines. Check [Tasks](/tasks) and [routine runs](/routines/runs) for work already submitted. ## Blockers on the phone While working on a device, your agent sometimes runs into something covering the screen that it did not ask for: | What it looks like | What your agent does | | - | - | | An "app isn't responding" box, a rating nag, or an update prompt | Dismissed automatically, then it continues. | | A permission prompt clearly tied to what you asked for (like camera access for a scan) | Granted automatically. | | A permission prompt that is not obviously needed | Surfaced to you as a question before granting it. | | A request for contacts, SMS, call log, or location access | Always surfaced to you as a question, regardless of the task. Your agent never grants these on its own. | | An unrecognized popup with no clear close button | Your agent stops and tells you, rather than guessing or backing out blindly. | Your agent never scrolls past or blindly dismisses something it does not recognize. If a login screen appears unexpectedly mid-task, it stops rather than retrying, since the next tap could go somewhere wrong. ## Related > [card] [Notifications](/agents/notifications) > > Get notified when your agent finishes, fails, or has a question for you. > [card] [Devices](/agents/devices) > > Phones, accounts, and credentials your agent works with. > [card] [Routines](/agents/workflows) > > How approvals and questions fit into recurring automation. > [card] [Limits and costs](/agents/limits-and-costs) > > What your agent will refuse or hand off entirely. # Integrations Source: https://docs.mobilerun.ai/agents/integrations Connect Gmail, Google Workspace, GitHub, Slack, Microsoft Teams, and OneDrive so your agent can read your data and act in those tools with your approval. Your agent can look things up in services you have connected to your Mobilerun account and combine that with what it does on a phone. Ask about an email, a calendar conflict, a file in Drive, or a pull request, and it answers with a short summary and links to the source items. To connect an external agent or SDK to Mobilerun instead, see the [integrations overview](/integrations/overview). ## Supported services Connected services include Gmail, Google Calendar, Drive, Sheets, Docs, Slides, GitHub, Slack, Microsoft Teams, and OneDrive. The tools available to your agent depend on the service, your connection, and the current tool catalog. Ask what it can do before relying on a particular action; connecting an app does not make every action available in a routine. You can also connect a custom MCP server. Its available tools follow the same distinction between reading data and approving writes. See [Integrations and delivery](/routines/integrations) for routine actions and artifact destinations. ## Connecting a service On the overview, open **Connections → Apps** and connect the service with its normal sign-in. You can also use the Integrations page. You can also ask your agent directly; if the service is not connected yet it shows a **Connect** card in the chat, and you finish the sign-in there. Open Integrations > Connect my Gmail so you can check for verification emails. A connection belongs to your account. Your agent only reaches a service through that connection and only while you ask it something that needs it. ## What your agent does with a connection It narrows first, then reads. For "did anyone email me about the invoice" it searches for matching messages, reads the few that fit, and answers with the relevant lines and a link to each message. It does not dump your inbox into the chat, and very large results are summarized rather than pasted in full. Typical requests: > Check my calendar for conflicts tomorrow afternoon. > Find the latest spreadsheet in Drive with "Q3 pipeline" in the name and tell me the total in column F. > Summarize open pull requests in the mobile app repo that touch the login screen. > Post a summary of today's scrape results to the #growth channel in Slack. > Upload this CSV to my OneDrive under Reports/September. > Upload the screen recording from this run to my Google Drive. Writes happen only when you ask for them, and every write shows an approval card first. Eligible writes can run without a new card in **Auto** mode, under a saved organization-wide grant, or in a deployed routine. Custom MCP writes cannot use remembered grants. Your agent does not send a Slack message or move a OneDrive file as a side effect of another task. See [Human in the loop](/agents/human-in-the-loop). ## Combining a service with a phone The useful cases pair a connected service with device work: * Read a verification email in Gmail while signing up for an app on a Cloud Android phone. * Take a list of leads from a Google Sheet and look each one up in an app. * Scrape a list on a phone and post the result to Slack or Teams when done. For "tell me when you are finished" without a chat message, use [Notifications](/agents/notifications) instead of a Slack write; that path works even when the chat is closed. ## Related > [card] [Devices](/agents/devices) > > Phones, apps, accounts, and verification codes from managed numbers and mailboxes. > [card] [Results](/agents/results) > > How scraped data and files come back to you. > [card] [Notifications](/agents/notifications) > > Get notified when your agent finishes, fails, or has a question for you. > [card] [Human in the loop](/agents/human-in-the-loop) > > What your agent asks before acting. # Limits and costs Source: https://docs.mobilerun.ai/agents/limits-and-costs How credits are spent, how to estimate a job before running it, and what stops a run from getting out of hand. ## How credits are spent Agent conversations and device tasks consume credits for model usage. Cloud execution, device minutes, storage, and residential traffic have their own meters. A plain conversation can also use credits; do not assume a chat without phone work is free. See [Credits & usage](/credits) for units, allowances, and top-ups, and the [website pricing](https://mobilerun.ai/pricing) for current prices. Check actual usage in Billing → Usage. Use your provider account for model usage on any plan: [Bring your own model key](/byok). ## Getting a cost estimate You can ask your agent how much a task will cost before you run it. It gives you a rough estimate based on how many steps the task is likely to take, not a hard quote. The only exact number is what a run actually spends, which you can see on the task afterward or in your account balance. > Roughly how many credits would it cost to scrape this page every day? > [!TIP] > > You can also ask your agent to explain how credits are counted, or to show you a breakdown of > your recent usage, straight in the chat. ## What makes a job expensive * **More steps.** A task that decides what to do screen by screen, using vision to figure out where to tap, takes more steps than one with a clear, repeatable path. * **Loosely described goals.** "Check my accounts" takes more exploration than "open Instagram and check my DMs." * **Extra devices.** One Cloud Android phone can usually run several accounts. Add a device only when you genuinely need separate isolation, such as a dedicated proxy per account. * **Repeated retries.** If the same approach keeps failing, your agent treats that as a signal to change tactics or stop, rather than a reason to try the exact same thing again. ## Budgets that stop runaway jobs Tasks have configured step and time limits; chat turns also have a maximum age. These limits bound work, but are not a fixed credit quote. While it works, your agent also checks whether it's actually making progress toward your goal. If a run stops advancing, it stops itself, reports what it achieved, and tells you what's left, instead of looping. A Pay as you go phone also stops billing on its own: when your device minutes run out, it is stopped and keeps its data. A country proxy on that phone is billed as residential traffic (GB). ## Agent and routine capacity Additional agents and routines require available capacity. Ask Matty what is available before creating another one. Disabled agents cannot accept requests; enabling or creating resources must fit the current plan. Routine capacity includes enabled and disabled routines; archiving frees its slot. See [Routines](/routines) and [Credits & usage](/credits). ## What it refuses or hands to the dashboard Your agent never buys, subscribes, upgrades, or adds credits on your behalf. Anything involving money shows up as a card in the chat, and you complete it in the dashboard yourself. It does not quote plan prices from memory; it shows you the current pricing card. For your balance, check the Billing section of the dashboard. ## Plans, upgrades, and top-ups Ask your agent what plans are available or how to add credits, and it shows you the relevant card. See [Credits](/credits) for how device subscriptions, credit allowances, and top-ups work. ## Related > [card] [Credits](/credits) > > Credit units, allowances, and links to current pricing. > [card] [Overview](/agents/overview) > > What your agent is and what it can do. > [card] [Human in the loop](/agents/human-in-the-loop) > > How approvals and questions pause a run mid-task. > [card] [Getting started](/agents/getting-started) > > Your first conversation and first result. # Memory and skills Source: https://docs.mobilerun.ai/agents/memory-and-skills What your agent remembers between conversations, how to ask it for a recap, and how to teach it your own playbooks and apps. Your agent gets better at working with your devices and apps over time, and lets you teach it directly. Memory is what it noticed and verified on its own, while a skill is a playbook you hand it directly. Both carry forward into future conversations. ## What your agent remembers Across conversations, your agent keeps its own notes: device quirks, app-specific traps, your stated preferences, and workarounds that turned out to be necessary before. > This device needs a couple of extra seconds after launch before the screen responds. > This account always shows a login screen on a fresh session, even though it worked yesterday. It writes these down as plain facts, not guesses. Memory belongs to each agent, not to your whole account and not to a single conversation, so a new chat with the same agent benefits from what an earlier one learned. Archiving an agent removes its memory. | Remembers | Never remembers | | - | - | | Device quirks and app-specific traps | Passwords, one-time codes, or any credential value | | Your stated preferences | Personal information you did not explicitly ask it to keep | | Workarounds that turned out to be necessary | Guesses or unverified assumptions | ## Asking what it did Ask "what did you do" or "give me a recap" and your agent answers from its own record of past actions in this account, not by re-inspecting your devices from scratch. For a specific past session, ask about it by what you were doing at the time. > What did you do on the Pixel 8 yesterday? Narrow the question to a device or an app and your agent filters its answer instead of giving you everything. ## Uploading your own skills Open **Skills** in the agent’s menu. Choose **Upload skill** or drop a Markdown (`.md`) file containing your playbook, checklist, domain knowledge, or app instructions. A normal chat attachment is a file for that conversation; use the Skills pane for reusable instructions. Use **Skill library** to browse and install ready-made app skills. You can preview a skill, enable or disable it, and use **Rename**, **Replace**, or **Delete** from its options. Skills are scoped to the agent; check which agent you are editing. > Follow this checklist whenever I ask you to close a listing. ## Teaching it an app or a path once Ask your agent to learn a specific path through an app, for example how you post a listing or export a report, and it walks through that path once, on a real device. It notes the stable steps, the screens involved, and anything that tends to go wrong, then saves that as reusable knowledge. > Learn how to export a CSV of orders from this app, so you don't have to rediscover it every time. Ask it to verify the path and report where it stopped. A saved procedure is guidance; changes to the app or login state can still require another check. ## App cards it consults before acting Before your agent takes its first action inside an app during a conversation, it checks whether it already has notes on that app: known screens, a login flow, and traps to avoid. If notes exist, it uses them and tends to work more reliably and faster. If not, it falls back to figuring the app out as it goes, and may write new notes afterward. This happens automatically. You do not need to ask for it, and it applies both to apps your agent already knows well and to ones you taught it yourself with a learn request. ## Limits Memory belongs to the agent that wrote it, and nothing is shared with other Mobilerun accounts. Use agent instructions for its ongoing focus and skills for reusable procedures. Ask Matty to create another agent or change its instructions; those changes need your approval, even in Auto mode. If you are unsure whether your agent already knows something about a device or app, just ask it. ## Related > [card] [Human in the loop](/agents/human-in-the-loop) > > How your agent asks questions and gets approval. > [card] [Devices](/agents/devices) > > The devices, apps, and accounts your agent works with. > [card] [Getting started](/agents/getting-started) > > Your first conversation, device, and result. > [card] [Mobilerun Agents chat skill](/skills/assistant) > > Talk to your agent from your own code over the chat API. # Get notified by your agent Source: https://docs.mobilerun.ai/agents/notifications Get notified in Slack, Teams, your browser, or by webhook when your agent finishes, fails, or has a question for you, so you can start a long job and walk away. Your agent often runs for many minutes: scraping a list, working through a multi-step job, or waiting for you to answer a question. You should not have to keep the chat open to find out when it is done. For notifications across all platform events, including tasks, routines, messages, and cards, see [Notifications](/notifications). ## Slack, Teams, and browser notifications Open **Connections → Alerts** on the overview to choose what you hear about and where: * **Notifications in Mobilerun** lists the moments you can be notified about. Use the quick presets to switch whole groups on or off. * **Browser notifications** show a system notification even when Mobilerun is in the background. Your browser asks for permission the first time; on a phone, Mobilerun has to be added to your home screen and opened from there. * **Notifications in Slack or Teams** sends the same moments to a channel. Pick the channel and what you want to hear about; you can change it later on the Notifications page. Questions your agent asks can also be answered from Slack. Everything below is the webhook route, for sending these events to your own systems. ## Webhook events Three webhook events cover the whole lifecycle of an agent turn. They cover interactive conversations whether the tab is open, in the background, or closed. | Event | When it fires | | - | - | | `chat.turn.completed` | Your agent finished the current turn successfully. | | `chat.turn.failed` | The turn ended with an error. | | `chat.input.required` | Your agent asked you a question and is waiting for an answer. Approval cards do not fire this event. | ## Ask your agent to set it up > Notify me at [https://hooks.example.com/mobilerun](https://hooks.example.com/mobilerun) when you finish, fail, or need an answer. Send a test. Your agent can discover available events, create an outbound webhook, send a test, and inspect its deliveries. A signing secret is shown once on creation or rotation; store it securely. See [Webhooks](/webhooks) for endpoint setup, signatures, retries, and delivery troubleshooting. ## Set it up in Cloud Use **Connections → Alerts** on the overview, or open Notifications directly. Pick the moments and destinations you need. These alerts are distinct from asking your agent to write a custom Slack or Teams message through a [connected service](/agents/integrations). Open Notifications Add a notification channel For routine-specific outcome notifications and artifact delivery, see [Integrations and delivery](/routines/integrations). ## What the payload contains Agent-turn events identify the conversation and turn without including the prompt, answer, or question text. Open the conversation to read it. Use the [event catalog](/webhooks#event-catalog) for event details and [SDK webhook helpers](/sdk/helpers) for verification examples. A stopped turn does not produce a successful completion event. See [Notifications](/notifications) for the platform event feed, browser delivery, and channel configuration. ## Turning it into a message Prefer the built-in Slack or Teams destination for standard alerts. For custom routing, send webhook events to your receiver or an automation tool. Verify signatures and deduplicate by event ID before acting; follow [Webhooks](/webhooks#verifying-the-signature). # Overview Source: https://docs.mobilerun.ai/agents/overview What Mobilerun Agents is, what it can do, and how a conversation with your agent works. Mobilerun Agents are hosted agents you chat with in the dashboard. Your default agent is Matty. Tell it what you want done: it can work with files, connected services, and public APIs in the cloud, or use a phone when the job needs an app. It reports back with the result. Open Mobilerun Think of it as an operator for your Mobilerun account. It can set up and manage devices, run apps, handle accounts and logins, scrape data, and build recurring automations, all from a chat window. You don't write scripts or call an API. You describe a goal, and it figures out the steps. ## What it can do > [card] Devices > > Create a Cloud Android phone (subscription or Pay as you go), work on your Cloud iOS and Personal Phones, or point you to connecting your own. > [card] Apps and accounts > > Install apps, log in, and manage credentials on a device. > [card] Scraping and results > > Collect data from an app or page and hand it back as a file or a table. > [card] Routines > > Build a routine from a trigger and steps. Run manually or on a schedule; event triggers are Soon. > [card] Notifications > > Tell you in Slack, Teams, your browser, or by webhook when it finishes, fails, or has a question. > [card] Files > > Produce downloads, screenshots, and other artifacts from a run. > [card] Integrations > > Read Gmail, Calendar, GitHub, Slack, and Teams, and work in Google Drive, Sheets, Docs, Slides, Slack, Teams, and OneDrive. > [card] Recordings > > Record the phone screen while it works and play it back in the chat. It also answers questions about Mobilerun itself: plans and credits, what a job might cost, and where to start if you want to build with the SDK or API instead. For developer questions it points you to the right docs page and example rather than teaching code in the chat. ## Agents you can personalize Ask Matty to create an agent with a name and instructions for a recurring area of work. Creation needs your approval and available agent capacity. Each agent has its own conversations, memory, and files; agents can share files and request work from one another. Archiving an agent removes its conversations, workspace, and memory, so read the confirmation before approving. See [Memory and skills](/agents/memory-and-skills) for reusable instructions and the skill library. ## What it is not Mobilerun Agents is a chat interface, not the raw automation layer underneath it. It is not the task agent that developers call directly to drive a device step by step. For that, see [Agent configuration](/tasks#configure-the-agent). It is also not a developer SDK. If you want to build your own integration that talks to the agent over an API, or teach another AI agent to hold this conversation for you, see [Mobilerun Agents · chat](/skills/assistant) and the [MCP Server](/mcp-server) page. ## How a conversation works **1. You ask** Describe what you want in plain language. No commands, no tool names. **2. It plans** Your agent figures out which device, app, or account the task needs. **3. It may ask back** If something is ambiguous or sensitive, it pauses and asks you a question or asks for approval before continuing. **4. It works on your goal** It uses the cloud for file and connected-service work, or a phone for device work, within the run’s limits. **5. It presents results** It leads with the outcome: what succeeded, what failed, and any file or link you need. > [!NOTE] > > Your agent never completes a purchase for you. When money is involved, it shows you a card > in the dashboard and you click it. See [Limits and costs](/agents/limits-and-costs). Your agent can use your provider account on any plan: [Bring your own model key](/byok). ## Where to go next > [card] [Getting started](/agents/getting-started) > > Your first conversation, first device, and first result. > [card] [Devices](/agents/devices) > > Phones, pay as you go, apps, accounts, proxies, numbers, and mailboxes. > [card] [Results](/agents/results) > > How scraped data, diffs, and files are collected and presented. > [card] [Routines](/agents/workflows) > > Manual and scheduled routines built in chat, with event triggers marked Soon. > [card] [Notifications](/agents/notifications) > > Get notified when a run finishes, fails, or has a question for you. > [card] [Integrations](/agents/integrations) > > Connected services: what your agent can read and where it can write. > [card] [Tasks and recordings](/agents/tasks-and-recordings) > > Where device work shows up, and how to record the screen. > [card] [Human in the loop](/agents/human-in-the-loop) > > How questions and approvals work, and how to walk away and come back. > [card] [Memory and skills](/agents/memory-and-skills) > > What your agent remembers and how to teach it a new app. > [card] [Limits and costs](/agents/limits-and-costs) > > How credits work and what stops a run from getting out of hand. # Results Source: https://docs.mobilerun.ai/agents/results How your agent scrapes lists, compares runs, and hands you files and answers. Ask your agent to pull data out of an app or website and it collects the data, then hands it back as a clear answer, a file, or both. ## Scraping lists from apps and websites For a list such as followers, listings, or orders, specify whether you want everything or a sample. A phone scrape reads what the app exposes; a connected service or public API may provide a more direct path. App access, permissions, and run limits can prevent a complete collection. Check the reported scope and completeness. For a full collection, "complete" means the list stopped moving because you reached the actual end, not because your agent gave up early. If you ask for a specific number of rows instead, it returns that many, then asks you one question: continue to the end of the list, or keep the sample. If the run gets interrupted, blocked by a popup, or the app changes screens mid-scrape, your agent tries to recover once and continue from where it left off. Ask for deduplication by a stable identifier, such as a listing ID or profile URL, and check the exported result. When it reports back, it states plainly which of these happened: | Outcome | What you hear | | - | - | | You asked for everything and the list ended | "All rows collected, list end reached." | | You asked for the first N and got them | "Requested scope complete," followed by a question about continuing | | The run stopped before the list ended | "N collected; list end not reached," with a way to resume | > [!NOTE] > > A row count alone never proves a list is complete. Your agent states explicitly whether it reached the end. > Scrape every attendee of this event and give me a CSV. > Get me the first 50 listings sorted by price. ## Diffs against a previous run If you already have a list and want only what changed, send it as an attachment and ask for the difference. Your agent matches your file's rows against a fresh scrape using a shared key, such as an id or a name plus company combination, and returns only the rows that are new, changed, or gone. This always requires a complete, unbounded scrape. Reporting removed rows from a partial run would falsely mark everything past the stopping point as gone, so your agent skips the removed-rows answer entirely rather than guess, and tells you why. If your file has no column your agent can reliably match against the app, it asks you which column to use instead of picking one for you. > Here's last month's export. Scrape the app again and tell me what's new or changed. ## Collection status Scrape files can report completeness, coverage, whether the source end was verified, and whether the collection is resumable. **Unknown** means there is no verified completeness claim. A row count or a successful file download does not prove the source was exhausted. For recurring collections, inspect [routine runs](/routines/runs) as well as the exported file. ## Files and downloads You can attach a file, such as a CSV or spreadsheet, to give your agent a starting point, a baseline to diff against, or data to look something up in. It reads the file directly and never asks you to paste rows into chat. When a task produces a list, a report, or extracted data, your agent creates a downloadable file rather than pasting hundreds of rows into the conversation. Common formats are CSV for tabular data and JSONL for anything with nested fields. The file appears as a link in the chat reply; open it to download. Screenshots taken during a task, such as proof of a completed step or a visual result, are attached to the task the same way. ## How results are presented Your agent leads with the outcome, not a replay of every step it took. A typical reply states what succeeded or failed, points at the file or number that answers your question, and only asks a follow-up question when a real decision is needed. It discloses limits rather than rounding up. A partial result is reported as partial, with what's missing and how to continue. If it could not find something on screen after checking the obvious places, it says so and asks you what to do next instead of guessing or clicking blindly. > [!TIP] > > If a result looks off, ask your agent to explain what it checked. It can tell you what it verified and where it stopped, rather than just asserting success. ## Example prompts > Scrape all products in this category and export them as CSV. > Compare this spreadsheet against the app and show me what changed. > Get me a screenshot proving the order went through. ## Related > [card] [Devices](/agents/devices) > > The phones, apps, and accounts a scrape runs on. > [card] [Human in the loop](/agents/human-in-the-loop) > > What happens when your agent needs your input mid-task. > [card] [Routines](/agents/workflows) > > Turn a recurring scrape or diff into an automation. > [card] [Limits and costs](/agents/limits-and-costs) > > Credits and step budgets behind a long-running scrape. # Tasks and recordings Source: https://docs.mobilerun.ai/agents/tasks-and-recordings Where your agent’s device work shows up in the dashboard, how to look it up later, and how to record a phone screen while it works. Your agent can run device tasks and use device controls directly. Cloud-only work does not require a device task. Tasks are visible outside the chat, so you can check what happened without scrolling back through a conversation. ## Tasks in the dashboard When your agent starts a device task, each task appears on the [Tasks](/tasks) page with its status, the device it ran on, screenshots taken along the way, and the result. You can also ask your agent about its own tasks: > What did the last task on my Instagram phone do? > List the tasks that failed today. Your agent reads task status and results; it does not cancel or edit tasks from that view. To stop work that is running right now, stop the current turn in the chat. See [Human in the loop](/agents/human-in-the-loop). ## Screen recordings Ask your agent to record the phone while it works. It starts a video recording on the device, shows a recording card in the chat, does the job, and stops the recording when done. The card becomes an inline video player once the recording is ready. > Record the screen while you go through the signup, I want to see every step. | You can ask | What happens | | - | - | | Start a recording | A named video recording begins on the chosen phone. | | Show a recording | The card with the player appears in the chat. | | List recordings | The recordings on that phone, newest first. | | Stop a recording | The active recording ends and finishes processing. | | Delete a recording | Permanent. Your agent shows an approval card first. | Recording support depends on the device’s capabilities. Recordings belong to the device where they were made and use storage. Your agent shows the inline recording card instead of pasting a raw video URL. See [Devices](/devices) for device controls and [Credits & usage](/credits) for storage usage. > [!NOTE] > > A recording captures the whole screen, including anything your agent types or reads while it is on. Do not record while credentials or codes are visible if the recording will be shared. ## Screenshots For a quick look rather than a video, ask for a screenshot. It is attached to the task and shown in the chat. > Take a screenshot of the home screen so I can see what's installed. ## Related > [card] [Tasks page](/tasks) > > The dashboard view of every task, with screenshots and results. > [card] [Results](/agents/results) > > Files, lists, and how results are presented. > [card] [Devices](/agents/devices) > > The phones your agent records and works on. > [card] [Routines](/agents/workflows) > > Recurring runs, which can also be recorded. # Routines Source: https://docs.mobilerun.ai/agents/workflows Turn a job you would otherwise ask for by hand into recurring or triggered automation your agent builds and runs for you. For the dashboard and API workflow, see [Working with routines](/routines), [Triggers](/routines/triggers), and [Runs and troubleshooting](/routines/runs). A routine is a job your agent sets up once and then runs again on its own, manually or on a schedule. You do not need to open the chat and ask each time. ## When to use a routine instead of a one-off job Ask for a one-off job when you want an answer right now and will not need it again. Ask for a routine when you want the same job to repeat, or to run it on demand with the same inputs and steps. Event triggers are **Soon**. > Check this product's price every morning at 9am and tell me if it drops. > Every Monday morning, collect the new sign-ups from this app and send me the list. If you are not sure yet whether something should recur, say so. Your agent can build it as a one-off first and turn it into a routine later. Your agent writes the same [routine document](/routines/documents) you can view and edit as YAML or JSON. ## How your agent builds a routine Your agent chooses the route the job needs: a cloud routine for APIs, files, and connected services, or a device routine for phone apps. It checks the routine before submitting it for a real verification run. **1. Learning** For phone work, your agent explores the relevant app screens. Cloud work does not require a phone. **2. Building** It prepares a trigger and ordered steps, including Serverless Functions where repeatable code helps. **3. Testing** Checks validate the routine’s structure. A check does not perform its actions or prove a live result. See [Check and Test run](/routines/runs). **4. Deploy** Your agent shows an approval card for a real verification run. That run performs the actual actions and can use credits. The routine activates only after verification succeeds; a failure rolls back activation. Cloud routines run without a device. Read the card before approving. Along the way your agent asks you a small set of questions up front, like cadence, which device, and how results should be checked, so it does not have to interrupt you again later. ## Triggers A routine needs exactly one trigger, chosen when you set it up. | Trigger | Fires when | | - | - | | **On a schedule** | A recurring time you set, for example daily at 9am. You can give it an end date ("run this every Monday until October 15") instead of asking for it to run forever. | | **On an event** | **Soon.** App, device, and platform event triggers are not offered as generally available in this guide. | | **Manually** | You or your agent fire it on demand, with no recurring schedule. | Specify a timezone for schedules. See [Triggers](/routines/triggers) for schedule rules, stored inputs, and authenticated custom firing. ## Steps and Serverless Functions A routine combines a trigger with ordered steps. Steps can use tasks, supported integration actions, Serverless Functions, file processing, or delivery. A function can also run independently of a routine. See [Steps and Functions](/routines/functions) and [Integrations and delivery](/routines/integrations) for supported actions and connection requirements. ## What a run produces You choose how each routine delivers its result: a result card (the default), a summary written by your agent (which costs an agent turn), or nothing. A routine posts at most one result card per hour. A run can also produce a downloadable file, depending on what you asked for. For result checking, you choose how thorough your agent should be: it can trust the automation's own checks, review the result itself, or do both, flagging only what looks off. Ask for one of these when you set the routine up, or leave it to your agent's judgment for a simple job. A routine can also send its result straight to a webhook endpoint you own, as one of its steps. That is different from the **Notify on success** and **Notify on failure** controls in the routine's Notifications dialog, where you pick a webhook to receive a notification for each outcome. Turning a routine's notifications off asks for your approval; set up the webhook itself in the dashboard. See [Notifications](/agents/notifications) and [Webhooks](/webhooks) for both mechanisms. ## Running the same job across many phones Ask your agent to run a routine, or a one-off job, across several devices at once. > Run this same check on all five of my Cloud Android phones. Name the target phones and ask for a result per device. Available capacity and device readiness determine what can run. See [Runs and troubleshooting](/routines/runs) for execution history and failures. ## When a run fails or repairs itself Agent-managed routines can have health monitoring and self-healing. Availability depends on the routine’s configuration; do not assume every routine repairs itself. Turning health monitoring off requires your approval. See [Runs and troubleshooting](/routines/runs) for health states and repair eligibility. A failure that is not fixable this way, such as a login your agent cannot get past, is not silently retried forever. Your agent reports it and asks what you want to do next. A routine is a trigger plus steps, and a step can be a Serverless Function: a Python file you write. See [Serverless Functions](/agents/functions). ## Inspecting past runs Every run is recorded. Ask your agent to show you the history of a routine, what happened in a specific run, or why the last one failed, and it reads that back to you. ## Pausing, archiving, or deleting a routine Your agent can pause a routine (it stops firing until you enable it again) and archive one, which frees its slot. Archiving shows an approval card, and enabling a paused routine again shows one too. Archiving keeps its history. Use the dashboard for other lifecycle controls; see [Routines](/routines). ## Cost Building a routine (the Learning phase) uses credits the same way a normal job does. Testing and deployed runs use device minutes, plus credits for steps that run the AI agent and for repairs. See [Limits and costs](/agents/limits-and-costs) and [Credits & usage](/credits) for how usage is measured. ## Related > [card] [Notifications](/agents/notifications) > > Get notified when a run finishes, fails, or needs you. > [card] [Webhooks](/webhooks) > > Configure the endpoints a routine can send results to. > [card] [Results](/agents/results) > > How files and structured results are presented back to you. > [card] [Limits and costs](/agents/limits-and-costs) > > Credits, step budgets, and what your agent will refuse. # API Keys & Stream Tokens Source: https://docs.mobilerun.ai/api-keys Choose API keys for backend API access and stream tokens for showing and controlling a device in your app. > [!NOTE] > > TypeScript and Python examples require SDK 6.3.1 or later. Use an **API key** (`dr_sk_…`) in your backend for server access to the Mobilerun API. Give a browser or app a **stream token** (`dr_st_…`) when it needs to show and control one device, without exposing your API key. | Credential | Prefix | Lifetime | Scope | Where it lives | | - | - | - | - | - | | API key | `dr_sk_…` | Until its configured expiry or revocation; Never is available | The key's granted API permissions, limited by its creator's role | Backend or server only | | Stream token | `dr_st_…` | Short-lived and single use; see [limits](#lifetime-and-limits) | One stream connection to one device, with viewing and control | Browser or app | ## API keys The API Keys tab allows you to generate and manage authentication keys for accessing the Mobilerun API. Use API keys to integrate Mobilerun into your applications, CI/CD pipelines, and automation workflows. ### Overview API keys provide: * Authentication for API requests * Programmatic access limited by the key's permissions and your role * Integration with external tools and services ### Creating an API Key Issue keys in the dashboard's **API Keys** tab: Create an API key 1. Click **New key** to open the **New API key** dialog 2. Enter a descriptive key label (e.g., "Production CI runner") 3. Choose an expiration: Never, 24 hours, 1 week, 1 month, 3 months, 6 months, or 1 year. Restricted keys also offer **Default** (90 days) 4. Under **Access**, select **Restricted** to choose permissions, then start from a preset or select individual actions. Select at least one permission. Choose **Full access** only when the integration needs everything your role allows 5. Click **Issue key** 6. Copy the generated key immediately > [!WARNING] > > API keys are only displayed once at creation. Store your key securely as you will not be able to view it again. > [!NOTE] > > Mobilerun API keys always start with the prefix **`dr_sk_`**. Pass the full key, including the prefix, as a bearer token in the form `Authorization: Bearer dr_sk_...`. This is a different credential from your LLM provider keys such as `GOOGLE_API_KEY` or `OPENAI_API_KEY`, which are only used by the local [Framework](/framework/quickstart). See [the two kinds of API keys](/quickstart#two-kinds-of-api-keys) for guidance on when to use each one. ### Permissions #### Presets Presets are starting points for restricted keys. You can change the selected actions before issuing the key. Only permissions your role can grant are included; full access permissions are excluded from presets. | Preset | Permissions | | - | - | | **Read only** | Available Read actions, except Mailboxes, Phone numbers, 1Password items, Webhooks, and Sandbox | | **Devices** | Devices: Read, Control, Stream; Apps: Read, Create; App store: Read | | **Automation** | Routines: Read, Control; Tasks: Read, Control; Devices: Read | #### Custom permissions Choose actions for each resource in the **Permissions** panel. The picker groups resources under **Devices & apps**, **App store**, **Agents & automation**, **Files**, **Credentials**, **Numbers, mail & network**, **Developer**, **Serverless Functions**, **Sandbox**, **Wallet**, and **Organization**, when permissions are available for that group. Actions depend on the resource: for example, Devices offer Read, Control, and Stream; Apps offer Read and Create; Tasks and Routines offer Read and Control; Credentials have their own actions for accessing and managing stored credentials. Select only the actions your integration needs. Actions your role cannot grant are disabled, and sensitive actions are marked **Sensitive**. Permissions apply across your organization, including all its devices; they do not restrict a key to one device. The **End customer** field is a display label, not an access restriction. Keep these keys in your backend rather than handing them to end customers. #### Full access **Full access** means everything your role allows. Issuing a key requires permission to create API keys; choosing Full access does not give you or the key permissions beyond your role. > [!WARNING] > > Some permissions inside the restricted picker also confer full authority. The **Routines (full access)** section warns that a routine runs with your full access, not with the key's selected permissions. Enabling **Allow creating and changing routines** lets the key do anything you can through routines. Other such permissions appear under **Full access permissions**. You can grant them only when your role allows them. #### When a request is outside the key's permissions A request denied because the key lacks the required scope returns HTTP **403** with code **`api_key_scope_denied`**. For example, an endpoint that refuses scoped keys returns: ```json theme={null} { "code": "api_key_scope_denied", "message": "Scoped API key is not permitted here" } ``` Check the key's granted permissions against the operation you are calling. Issue a replacement key with the required permission, update your integration, and revoke the old key. The dashboard currently does not offer editing an existing key's permissions. Your role must also allow the operation; granting a key more permissions cannot expand your own access. ### Managing API Keys Your API key list displays: | Field | Description | | - | - | | **Key ID** | The key's identifier | | **Name** | The descriptive name you assigned | | **Status** | Active, expired, or revoked | | **Access** | **Full access** or a **Restricted** badge; hover over or focus the badge to see **Granted permissions** | | **Expiration** | When the key stops working, or Never | | **Usage** | How much the key has been used | | **Last used** | Most recent API request using this key | | **Created** | When the key was generated | | **Created by** | Who issued the key | The Access details also warn about **Full access via routines** or other **Full access permissions**, when applicable. The row menu's **Edit end customer** action changes only the display label, not permissions. To change access, issue a replacement key. #### Revoke Keys Delete API keys that are no longer needed or may have been compromised. Revoked keys immediately stop working for all API requests. > [!NOTE] > > Revoking a key cannot be undone. You will need to create a new key and update any integrations that used the old key. ### Using API Keys Include your API key in the request headers when calling the Mobilerun API: ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const task = await mobilerun.tasks.run({ task: 'Open Settings app', deviceId: '', llmModel: 'mobilerun/mobile-agent-fast', }); console.log(task.id); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() task = mobilerun.tasks.run( task="Open Settings app", device_id="", llm_model="mobilerun/mobile-agent-fast", ) print(task.id) ``` ```bash cURL theme={null} curl -X POST https://api.mobilerun.ai/v1/tasks \ -H "Authorization: Bearer dr_sk_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task": "Open Settings app", "deviceId": "", "llmModel": "mobilerun/mobile-agent-fast"}' ``` > [!TIP] > > If you are new to the API, the [Cloud Quickstart](/cloud/quickstart) walks through the full flow in TypeScript, Python, and cURL. It covers finding a device, running a task, and reading the result. #### Authentication Header All API requests require the `Authorization` header: ``` Authorization: Bearer dr_sk_YOUR_API_KEY ``` ### API Documentation The complete API reference is available via OpenAPI specification. Access the full documentation to explore all available endpoints: * **Tasks** - Create, monitor, and manage agent tasks * **Devices** - List and manage your devices * **Apps** - Upload and install applications * **Credentials** - Manage stored credentials * **Hooks** - Configure webhooks for task events > [card] [API Reference](/api-reference/tasks/run-task) > > View the complete API documentation with request/response schemas and examples. ### Best Practices | Practice | Description | | - | - | | **Grant only what the key needs** | Start with a restricted preset and remove unnecessary actions; avoid full access permissions unless required | | **Use descriptive names** | Name keys by their purpose (e.g., "GitHub Actions", "Monitoring Service") | | **Separate environments** | Create distinct keys for development, staging, and production | | **Rotate periodically** | Generate new keys and revoke old ones on a regular schedule | | **Limit exposure** | Store keys in environment variables or secret managers, never in code | | **Monitor usage** | Check the "Last used" timestamp to identify inactive keys | ### Environment Variables Store your API key as an environment variable rather than hardcoding it: ```bash theme={null} export MOBILERUN_API_KEY="your_api_key_here" ``` > [!NOTE] > > For `mobilerun` CLI commands that use Cloud devices, sign in with `mobilerun login` or set `MOBILERUN_API_KEY`. Then reference it in your code or scripts: ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; // Reads MOBILERUN_API_KEY from the environment const mobilerun = new MobilerunSDK(); const task = await mobilerun.tasks.run({ task: 'Open Settings app', deviceId: '', llmModel: 'mobilerun/mobile-agent-fast', }); console.log(task.id); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK # Reads MOBILERUN_API_KEY from the environment mobilerun = MobilerunSDK() task = mobilerun.tasks.run( task="Open Settings app", device_id="", llm_model="mobilerun/mobile-agent-fast", ) print(task.id) ``` ```bash cURL theme={null} curl -X POST https://api.mobilerun.ai/v1/tasks \ -H "Authorization: Bearer $MOBILERUN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task": "Open Settings app", "deviceId": "", "llmModel": "mobilerun/mobile-agent-fast"}' ``` ## Stream tokens A stream token lets a browser or app view and control one device for a single stream connection. It also allows publishing microphone and camera input when the device supports call media and media injection is enabled for your organization. It cannot mint credentials or call other API routes. Your backend must authenticate the user and authorize access to the requested device before minting a token; never send the API key to the frontend. `viewOnly` is not supported: including it in a mint request, even as `false`, returns HTTP 422. A client-side control setting does not reduce the token's authority. ### Create a token in the dashboard Open API keys 1. Select **New key**. 2. Switch to **Stream token**, pick the device and a validity, and select **Create token**. 3. Select **Test in viewer** to check the stream, or use the token in your app. The token is shown once. Keep it out of logs, analytics, traces, error reports, and local storage. ### Required permissions Your backend's API key needs these permissions in **Devices & apps**: * **Stream keys: Create** (`stream_key.create`) * **Devices: Stream** (`device.stream`) * **Devices: Control** (`device.control`) Add **Stream keys: Delete** (`stream_key.delete`) if the key should revoke tokens. The picker calls the resource **Stream keys**, while the issued `dr_st_…` credential is a stream token. The key and its creator's role must allow the operation. ### Mint via the API `POST /v1/identity/stream-keys` accepts a device UUID, optional `ttlSeconds`, and optional `allowedOrigins`. It returns HTTP 201 with `key` (the stream token), `keyId` (for revocation), and `expiresAt`. Use `@mobilerun/sdk` or `mobilerun-sdk` 6.3.1 or later. The SDK reads `MOBILERUN_API_KEY` from the environment. Run this only in your backend, after checking the user may access the device: ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const { key, keyId, expiresAt } = await mobilerun.streamTokens.create({ deviceId: 'DEVICE_ID', ttlSeconds: 120, allowedOrigins: ['https://app.example.com'], }); // Return key only to the authorized viewer; never log it. ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() token = mobilerun.stream_tokens.create( device_id="DEVICE_ID", ttl_seconds=120, allowed_origins=["https://app.example.com"], ) # Return token.key only to the authorized viewer; never log it. ``` ```bash Without the SDK (cURL) theme={null} curl --request POST 'https://api.mobilerun.ai/v1/identity/stream-keys' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" \ --header 'Content-Type: application/json' \ --data '{"deviceId":"DEVICE_ID","ttlSeconds":120,"allowedOrigins":["https://app.example.com"]}' ``` ### Revoke via the API `DELETE /v1/identity/stream-keys/{keyId}` revokes an owned stream token and returns HTTP 204. Use `keyId` from the mint response; repeating a revoke for that owned token is safe. ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); await mobilerun.streamTokens.delete('KEY_ID'); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() mobilerun.stream_tokens.delete("KEY_ID") ``` ```bash Without the SDK (cURL) theme={null} curl --request DELETE 'https://api.mobilerun.ai/v1/identity/stream-keys/KEY_ID' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" ``` ### Lifetime and limits * `ttlSeconds` is an integer from **60 to 86400 seconds (24 hours)**, default **120 seconds**. A deployment may enforce a lower maximum. * A token is bound to one device and is consumed by its first admitted stream connection. Each reconnect needs a fresh token; an unused token expires at `expiresAt`. * `allowedOrigins` optionally binds the token to **1–10 exact origins**: HTTPS origins or `http://localhost[:port]`. Paths, wildcards, queries, and fragments are not accepted. Without this field, no browser-origin restriction is applied. * Origin binding limits browser embedding. A non-browser client can set its own Origin header, so this does not replace your application's authorization checks. * The default organization limit is **500 live unused tokens**. * Revoking or disabling the API key that minted a token invalidates its unused tokens. > [!NOTE] > > Stream tokens minted before the prefix change may still begin with `dr_sk_` until they expire, for up to 24 hours. Treat any `dr_sk_` value as a backend secret; do not use the prefix alone to decide whether a credential can be exposed. ### Stream-token errors | Status | Meaning | | - | - | | `401` | Invalid authentication; at stream connection, also a used, expired, revoked, wrong-device, or origin-refused token | | `403` | A required permission is missing, the creator's role refuses it, or token management is denied | | `404` | Revoke: token ID is invalid, unknown, or outside your account | | `409` | Live unused token limit reached | | `415` | A session caller did not send JSON content | | `422` | Invalid device UUID, TTL, or allowed origins, or a request containing `viewOnly` | | `503` | Temporarily unavailable | See [Embed a device stream](/guides/embed-device-stream) for the authenticated backend route, React component, and reconnect flow. # Connect a 1Password service account Source: https://docs.mobilerun.ai/api-reference/1password/connect-a-1password-service-account /api-reference/credentials-ref/1password.yaml put /credentials/onepassword # Disconnect 1Password Source: https://docs.mobilerun.ai/api-reference/1password/disconnect-1password /api-reference/credentials-ref/1password.yaml delete /credentials/onepassword # Get 1Password connection Source: https://docs.mobilerun.ai/api-reference/1password/get-1password-connection /api-reference/credentials-ref/1password.yaml get /credentials/onepassword # List 1Password field metadata Source: https://docs.mobilerun.ai/api-reference/1password/list-1password-field-metadata /api-reference/credentials-ref/1password.yaml get /credentials/onepassword/vaults/{vaultId}/items/{itemId}/fields # List 1Password item metadata Source: https://docs.mobilerun.ai/api-reference/1password/list-1password-item-metadata /api-reference/credentials-ref/1password.yaml get /credentials/onepassword/vaults/{vaultId}/items # Get a catalog entry Source: https://docs.mobilerun.ai/api-reference/action-catalog/get-a-catalog-entry /api-reference/workflows/action-catalog.yaml get /action-catalog/{catalogEntryId} Fetch a single action catalog entry by its ID, including its service, method, and parameter schema. Returns 404 if no entry matches. # List action catalog entries Source: https://docs.mobilerun.ai/api-reference/action-catalog/list-action-catalog-entries /api-reference/workflows/action-catalog.yaml get /action-catalog Return a paginated list of catalog entries — the service/method templates that actions are created from, each carrying its parameter schema. Supports filtering by `service`. # Check if overlay is visible Source: https://docs.mobilerun.ai/api-reference/actions/check-if-overlay-is-visible /api-reference/phones/actions.yaml get /devices/{deviceId}/overlay Returns whether the accessibility overlay is currently visible on the device. Reports the state of the visual overlay that the device's automation service can draw over the screen. > [!NOTE] > > Not every device draws an overlay. Devices without one always report `visible: false`. # Create an action Source: https://docs.mobilerun.ai/api-reference/actions/create-an-action /api-reference/workflows/actions.yaml post /actions Create a reusable action from a catalog entry (`catalogEntryId`), with an optional `params` object supplying the values for that entry's service method. Returns 400 if the params are invalid for the chosen catalog entry. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters). Replays with the same key and an identical body return the original 201; a changed body under the same key returns 422 `idempotency_key_reused`. # Delete an action Source: https://docs.mobilerun.ai/api-reference/actions/delete-an-action /api-reference/workflows/actions.yaml delete /actions/{actionId} Delete an action by its ID. Returns 404 if no action matches. # Get an action Source: https://docs.mobilerun.ai/api-reference/actions/get-an-action /api-reference/workflows/actions.yaml get /actions/{actionId} Fetch a single action by its ID, including its configured service, method, and params. Returns 404 if no action matches. # List actions Source: https://docs.mobilerun.ai/api-reference/actions/list-actions /api-reference/workflows/actions.yaml get /actions Return a paginated list of actions. Supports filtering by `service`, free-text `search`, and ordering by name, createdAt, or updatedAt. # List allowed methods for a service Source: https://docs.mobilerun.ai/api-reference/actions/list-allowed-methods-for-a-service /api-reference/workflows/actions.yaml get /actions/services/{service}/methods Return the methods allowed for the given service, each with its parameter definitions (name, type, whether required, description, and optional default/example). Returns 404 if the service is unknown. # List available services Source: https://docs.mobilerun.ai/api-reference/actions/list-available-services /api-reference/workflows/actions.yaml get /actions/services Return the names of the services that actions can be built against. Use these values to look up each service's allowed methods. # Perform a global action Source: https://docs.mobilerun.ai/api-reference/actions/perform-a-global-action /api-reference/phones/actions.yaml post /devices/{deviceId}/global Performs a global system action on the device, such as navigating back or going to the home screen, identified by an action code. Action codes follow Android's accessibility global actions: * `1` — back * `2` — home * `3` — recents (app switcher) These three work on every Android device. Higher codes — `4` (notifications), `5` (quick settings), `6` (power dialog), `8` (lock screen) — are device-dependent and rejected with an error where unsupported. # Set overlay visibility Source: https://docs.mobilerun.ai/api-reference/actions/set-overlay-visibility /api-reference/phones/actions.yaml post /devices/{deviceId}/overlay Shows or hides the accessibility overlay on the device based on the visibility flag in the request body. While visible, the overlay is part of the screen output: screenshots include it unless you pass `hideOverlay=true` to the screenshot endpoint. > [!NOTE] > > Devices that don't draw an overlay fail this call and always report `visible: false` on the read side. # Swipe Source: https://docs.mobilerun.ai/api-reference/actions/swipe /api-reference/phones/actions.yaml post /devices/{deviceId}/swipe Swipes from a start coordinate to an end coordinate over the given duration in milliseconds. An optional humanize flag applies human-like jitter and curved paths on devices that support it. With holdMs > 0 the request returns 422 when combined with humanize, when duration + holdMs exceeds 9000 ms, or on devices that do not support it. With `humanize: true`, the gesture is humanized: start and end points shift randomly (up to ±5 and ±15 pixels), the duration gets ±10% jitter, and supported devices trace a curved path with micro-jitter instead of a straight line. Devices with human-like input support inject the whole gesture with human motor timing instead. A humanized swipe covering less than \~5 pixels is treated as a long press with slight drift. `holdMs` cannot be combined with `humanize`; that combination is rejected with 422 `SWIPE_HOLD_HUMANIZE_CONFLICT`. # Tap by coordinates Source: https://docs.mobilerun.ai/api-reference/actions/tap-by-coordinates /api-reference/phones/actions.yaml post /devices/{deviceId}/tap Taps the device screen at the given x/y coordinates. An optional humanize flag routes the tap through human-like input on devices that support it. Coordinates are absolute screen pixels — the same space as `boundsInScreen` in the UI state response, so you can read an element's bounds and tap the center of its box. With `humanize: true`, devices that support human-like input inject the tap with human motor timing rather than a plain synthetic event. # Update an action Source: https://docs.mobilerun.ai/api-reference/actions/update-an-action /api-reference/workflows/actions.yaml patch /actions/{actionId} Partially update an action's name, description, or params; all fields are optional. Returns 404 if the action does not exist. # List credentials Source: https://docs.mobilerun.ai/api-reference/app-credentials/list-credentials /api-reference/credentials-ref.yaml get /credentials Returns a paginated list of all credentials belonging to the authenticated user across every package. Accepts standard pagination query parameters and responds with the credential items plus pagination metadata. # Confirm successful app upload Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/confirm-successful-app-upload /api-reference/apps-ref.yaml post /apps/{id}/confirm-upload Verifies the uploaded files and sets the app version status to available. Idempotent: replaying confirmation for an already-available version returns the same successful response without re-verifying the files. # Create a signed upload URL for an app Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/create-a-signed-upload-url-for-an-app /api-reference/apps-ref.yaml post /apps/create-signed-upload-url Creates or updates an app and returns pre-signed upload URLs for each file. Honours an optional `Idempotency-Key` header: a retry with the same key and body returns the same app and version with freshly signed URLs and `Idempotent-Replayed: true`, and never creates a second version. An Idempotency-Key is honoured for 7 days; after that it behaves like a fresh request. A replay whose version was deleted is a 404; a replay whose version already left the queued state is a 409 `idempotency_key_consumed`; a replay that cannot get the version lock within 5 s is a 409 `idempotency_request_in_progress`. Every response produced by a replay, including those 404/409 errors, carries `Idempotent-Replayed: true`. A same-key request still in flight after a 5 s wait is a 409 `idempotency_request_in_progress` (retry after `Retry-After`). If signing fails, nothing is persisted (with or without a key) and the same request, key included, can be retried. # Delete uploaded app Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/delete-uploaded-app /api-reference/apps-ref.yaml delete /apps/{id} Deletes an uploaded app by ID. Removes its files and metadata. # Get app by ID Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/get-app-by-id /api-reference/apps-ref.yaml get /apps/{id} Retrieves an app by its ID # Get the user’s storage usage Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/get-the-user’s-storage-usage /api-reference/apps-ref.yaml get /apps/storage-usage Returns the user’s storage allowance in bytes: bytes used, bytes included in the plan, the hard maximum (included + max purchasable overage; null = unlimited) and whether usage above the included amount is billed as overage. With storage billing off there is no limit: only usedBytes is set. # List apps Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/list-apps /api-reference/apps-ref.yaml get /apps Retrieves a paginated list of apps with filtering and search capabilities # List versions for an app Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/list-versions-for-an-app /api-reference/apps-ref.yaml get /apps/{id}/versions Retrieves all versions of an app visible to the user (own uploads + system versions) # Mark app upload as failed Source: https://docs.mobilerun.ai/api-reference/apps-cloud-storage/mark-app-upload-as-failed /api-reference/apps-ref.yaml post /apps/{id}/mark-failed Sets the app status to failed. # Delete app Source: https://docs.mobilerun.ai/api-reference/apps/delete-app /api-reference/phones/apps.yaml delete /devices/{deviceId}/apps/{packageName} Uninstalls the app identified by the path package name from the device. Protected packages cannot be deleted. On Android, the path parameter is the package name (e.g. `com.example.app`); on iOS, pass the app's bundle identifier instead. Deleting an app does not touch your app library — an uploaded APK stays there, so you can reinstall the app later with `install-app`. Requests targeting a protected package fail with `403 Forbidden`. # Grant app permission Source: https://docs.mobilerun.ai/api-reference/apps/grant-app-permission /api-reference/phones/apps.yaml put /devices/{deviceId}/apps/{packageName}/permissions/{permission} Grants an Android runtime permission to the package named in the path. The permission is given by its short name (e.g. POST_NOTIFICATIONS). Grants the permission directly — the app will not prompt the user for it on the device. The short name expands to the full Android permission string: `POST_NOTIFICATIONS` becomes `android.permission.POST_NOTIFICATIONS`. The target app must already be installed. Not supported on iOS devices — the request fails with an unsupported-feature error. Use `revoke-permission` to take the permission back. # Install app Source: https://docs.mobilerun.ai/api-reference/apps/install-app /api-reference/phones/apps.yaml post /devices/{deviceId}/apps Requests an app install on the device. The request body must supply exactly one of an Android packageName or an iOS bundleId. For packageName installs, optional country and versionCode select an exact regional uploaded Android version, and protected packages are rejected. background (default false) selects the response contract: false installs inline and returns the outcome directly (200 on success, an error status on failure); true accepts the request and runs the download + install in the background, returning 202 immediately — poll list-app-installs for the backend's view of that attempt's status. Refuses with 409 once 2 other installs are already running on the device, in either mode; a repeat request for an app that already has an install running is also refused with 409 rather than superseding it — retry once that attempt reaches a terminal state. Synchronous failures report APP_DOWNLOAD_FAILED (502) when the app file cannot be downloaded or APP_INSTALL_TIMEOUT (504) when the install times out. Requests an app install on the device. `background` (default `false`) selects the response contract: * `background: false` (default) — installs inline; the response is the actual outcome: `200` on success, an error status on failure. * `background: true` — accepts the request and runs the download + install in the background; a `202` response means the request was accepted, not that the app is installed yet — poll `list-apps` until the app appears, or poll `list-app-installs` for the backend's view of the install attempt itself (useful while the device is offline or crashed, when `list-apps` can't be called at all). Both modes are subject to the same concurrency cap: a request is refused with `409 Conflict` once 2 other installs are already running on the device. A repeat request for an app that already has an install running is also refused with `409 Conflict` rather than superseding it — retry once that attempt reaches a terminal state. Provide **exactly one** of: * `packageName` — Android package name. Resolved against the device owner's app library, so upload the APK first. * `bundleId` — iOS bundle identifier (e.g. `com.example.app`) or a numeric App Store ID. The app is installed from the App Store. Uploaded Android app versions may additionally be selected with: * `country` — ISO 3166-1 alpha-2 country stored on the uploaded version (for example, `MY` or `SG`). * `versionCode` — exact uploaded app version code. Pass both fields when the app library contains multiple regional versions for the same package name. Omitting them keeps the default lookup, which uses the country `US`. ### Updating an installed app Call `install-app` again with `packageName` to update an installed Android app; for regional versions, also pass `country` and `versionCode` from `availableUpdate`, read via `list-apps?includeUpdates=true`. Installation uses `-r`, keeping app data. Android rejects downgrades, and an update with a different signing key fails with `adb_install_failed`. > [!WARNING] > > Protected system packages cannot be installed over. Requests targeting a protected package fail with `403 Forbidden`. # List app installs Source: https://docs.mobilerun.ai/api-reference/apps/list-app-installs /api-reference/phones/apps.yaml get /devices/{deviceId}/apps/installs Reports the backend's durable view of background app-install attempts on this device — status reflects the install ATTEMPT, not device ground truth; list-apps remains authoritative for what is actually installed. Terminal and projected timeout records are kept ~15 minutes. Not gated on device readiness, so it also answers while the device is offline or crashed. Reports the backend's view of background app-install attempts on this device — one entry per `(platform, appId)` pair that has an `install-app` attempt in progress or recently finished. > [!WARNING] > > `status` reflects the install **attempt**, not device ground truth. It is `running` from the moment `install-app` returns `202`, then flips to `succeeded` or `failed` once the background download + install finishes. If a `running` attempt passes its background deadline without a terminal update, this endpoint reports it as `failed` with `errorClass: "timeout"`. `list-apps` remains authoritative for what is actually installed — a `succeeded` entry here is a strong signal, not a guarantee. On some iOS devices, `succeeded` means the device accepted the install command — the install may still be running on the device, or may yet fail there — so `list-apps` remains the authoritative check there too. Unlike most `Tools/Apps` endpoints, this one is **not gated on device readiness** — it answers from durable install records, not from the device, so it also works while the device is offline, crashed, or otherwise unreachable. That's the situation this endpoint exists to surface: an install that fails because the device dropped mid-download has no other way to be observed by a caller. On failure, `errorClass` narrows down what went wrong from a small closed set: * `download_failed` — fetching the app asset failed * `adb_install_failed` — the download succeeded, but Android refused to install the app (for example a downgrade or a different signing key) * `timeout` — the attempt exceeded its background time budget * `panic` — an unexpected internal error stopped the install * `failed` — anything else > [!NOTE] > > Terminal (`succeeded`/`failed`) records are returned for roughly 15 minutes after their last update. A `running` record that passes its background deadline is projected as `failed` with `errorClass: "timeout"` and remains visible for roughly 15 minutes after that deadline. Older records are omitted from this endpoint's response. Records are scoped to the tenant that owned the device when the install attempt started: after an ownership transfer (e.g. reassignment or a BYOD re-pair), the new owner cannot see the previous tenant's install attempts, even while those records are still within their retention window above. # List apps Source: https://docs.mobilerun.ai/api-reference/apps/list-apps /api-reference/phones/apps.yaml get /devices/{deviceId}/apps Returns detailed information about apps installed on the device, including package name and label. System and protected apps are excluded unless the corresponding query parameters are set. The detailed counterpart to `list-packages`: each entry carries the package name plus a label, version info, and an `isSystemApp` flag. > [!NOTE] > > Only `packageName` is guaranteed — depending on the device type, label and version fields can be empty. On iOS devices, entries are keyed by bundle identifier, Apple's built-in apps never appear, and `versionCode` is always `0`. Only when `includeUpdates=true`: `availableUpdate` is present when a newer version exists for an Android non-system app in the device owner's library. It is returned as `{versionCode, versionName, country}` using the same resolution as `install-app` with only `packageName`. This lookup is best effort with a shared 1.5-second budget; Absent means up to date or unknown (including lookup failures, system apps, protected apps, and iOS). By default, no app library lookups are made and `availableUpdate` is omitted. # Revoke app permission Source: https://docs.mobilerun.ai/api-reference/apps/revoke-app-permission /api-reference/phones/apps.yaml delete /devices/{deviceId}/apps/{packageName}/permissions/{permission} Revokes an Android runtime permission from the package named in the path. The permission is given by its short name (e.g. POST_NOTIFICATIONS). Revokes the permission directly, without any user interaction on the device. Counterpart to `grant-permission`. The short name expands to the full Android permission string: `POST_NOTIFICATIONS` becomes `android.permission.POST_NOTIFICATIONS`. Not supported on iOS devices — the request fails with an unsupported-feature error. # Start app Source: https://docs.mobilerun.ai/api-reference/apps/start-app /api-reference/phones/apps.yaml put /devices/{deviceId}/apps/{packageName} Launches the app identified by the path package name, optionally starting a specific activity given in the request body. Protected packages cannot be started. Starting an app that is already running brings it to the foreground. Omit `activity` to launch the app's default (launcher) activity. To open a specific screen, pass the fully qualified activity class name, e.g. `com.example.app.MainActivity`. Requests targeting a protected package fail with `403 Forbidden`. Not supported on iOS devices — the request fails with an unsupported-feature error. # Stop app Source: https://docs.mobilerun.ai/api-reference/apps/stop-app /api-reference/phones/apps.yaml patch /devices/{deviceId}/apps/{packageName} Force-stops the app identified by the path package name. When clearData is set in the request body, the app's data is also cleared. Protected packages cannot be stopped. Stopping kills every process and service of the app immediately — the same as **Force stop** in Android settings. > [!WARNING] > > `clearData: true` additionally wipes the app's local storage (databases, preferences, cache) — the same as **Clear data** in Android settings. This is irreversible and typically signs you out of the app. Requests targeting a protected package fail with `403 Forbidden`. Not supported on iOS devices. # Execute JavaScript in the device's Chrome browser (CDP) Source: https://docs.mobilerun.ai/api-reference/browser/execute-javascript-in-the-devices-chrome-browser-cdp /api-reference/phones/browser.yaml post /devices/{deviceId}/browser/execute-script Evaluates a JavaScript expression exactly once in the device's single, confirmed foreground Chrome tab via the Chrome DevTools Protocol and returns its JSON-serialized result. A responsive browser state without exactly one visible page returns DEVICE_NO_BROWSER_TARGET (400). Transient discovery, page-dial, or visibility-probe transport failures return CDP_TRANSPORT_UNAVAILABLE (503) with Retry-After and an executionOutcome; the service may start Chrome once and retry selection before Runtime.evaluate, but dial or probe recovery is skipped for a backgrounded Chrome, and a user script is never retried after its write or read. Devices without browser support return an unsupported-feature error. The script is a single JavaScript expression, not a function body — skip the top-level `return` and wrap multi-statement logic in an IIFE: ```js (() => { const links = [...document.querySelectorAll('a')]; return links.map(a => a.href); })() ``` The result must be JSON-serializable: `undefined` comes back as `null`, and `NaN`, `Infinity`, and `-0` are returned as strings. Scripts run in Chrome itself — in-app WebViews are not reachable. iOS devices don't support browser control and fail with `400`. If CDP discovery, page connection, or the foreground visibility probe fails before `Runtime.evaluate` is sent, the service may start Chrome once and retry target selection. Dial and probe recovery only starts Chrome when it is already the foreground app (or the Chrome CDP socket itself is unavailable), so a backgrounded browser still fails closed. The response keeps the `CDP_TRANSPORT_UNAVAILABLE` `503` contract and reports the phase and recovery result in its details when recovery was attempted. A selection deadline shortfall, or failures while writing or reading `Runtime.evaluate`, is never replayed. > [!TIP] > > For a persistent session or full DevTools protocol access, connect a Playwright- or Puppeteer-style CDP client to the raw websocket at `/devices/{deviceId}/browser/cdp` instead of issuing one-shot calls. # Abort the named session's in-flight chat turn Source: https://docs.mobilerun.ai/api-reference/chat/abort-the-named-sessions-in-flight-chat-turn /api-reference/mobilerun-agents/chat.yaml post /assistant/chat/abort Abort the in-flight chat turn owned by `sessionId`. Idempotent. A turn owned by a different session is left untouched (204). # Create a named chat session Source: https://docs.mobilerun.ai/api-reference/chat/create-a-named-chat-session /api-reference/mobilerun-agents/chat.yaml post /assistant/chat/sessions Creates a titled agent session. Setup may occur on the first prompt. Idempotent via the `Idempotency-Key` header — a duplicate submit by the same authenticated caller within the 24-hour idempotency window returns the already-created session instead of a second one. Reusing the same key with a different request body is a 422 `idempotency_key_reused`. # Deliver a HITL approval/rejection to the user's active chat session Source: https://docs.mobilerun.ai/api-reference/chat/deliver-a-hitl-approvalrejection-to-the-users-active-chat-session /api-reference/mobilerun-agents/chat.yaml post /assistant/chat/permission Deliver a HITL approval/rejection for an in-flight turn. Interactive HITL clients must start the turn with `Accept: text/event-stream`, wait for a `tool-hitl-approval` event, and send its `permissionId` here at `/assistant/chat/permission`. Do not submit approval as free-form user text or as `confirmed: true`. For `devices.reset`, only `once` and `reject` are allowed; the generic `always` response is rejected with HTTP 400. # Deliver a question answer to the user's active chat session Source: https://docs.mobilerun.ai/api-reference/chat/deliver-a-question-answer-to-the-users-active-chat-session /api-reference/mobilerun-agents/chat.yaml post /assistant/chat/question Deliver the user's answers to the agent's pending question for an in-flight turn. Idempotent via the `idempotency-key` header. # Dismiss an outstanding question without answering Source: https://docs.mobilerun.ai/api-reference/chat/dismiss-an-outstanding-question-without-answering /api-reference/mobilerun-agents/chat.yaml post /assistant/chat/question/reject Dismiss the agent's pending question. Already-resolved questions return 200 (no-op) so multi-tab dismiss stays idempotent. # List messages for a chat session Source: https://docs.mobilerun.ai/api-reference/chat/list-messages-for-a-chat-session /api-reference/mobilerun-agents/chat.yaml get /assistant/chat/messages Return the user's chat history for the given session. History remains readable after the session is no longer active. # List the user's named chat or agent-workflow sessions Source: https://docs.mobilerun.ai/api-reference/chat/list-the-users-named-chat-or-agent-workflow-sessions /api-reference/mobilerun-agents/chat.yaml get /assistant/chat/sessions Default (`kind` absent or `chat`): active named chat sessions, pinned first then most recent activity — `workflowId` must be absent, or the request 400s. `mine=true` (only valid with `kind=chat`) narrows to sessions the caller created. `kind=agent_workflow`: workflow-linked sessions for one workflow (`workflowId` required, or the request 400s), no status filter, newest episode first. # Re-attach to the active turn stream Source: https://docs.mobilerun.ai/api-reference/chat/re-attach-to-the-active-turn-stream /api-reference/mobilerun-agents/chat.yaml get /assistant/chat/stream Reconnect to the in-flight turn stream. Replays buffered events from the start of the active turn, then continues live until the turn finishes. Responds 204 when no active turn exists for the requested session. Upstream streaming failures return a retryable 503 with `Retry-After`. Resume is best-effort. Does not start an inactive session. # Rename, archive, or pin a named chat session Source: https://docs.mobilerun.ai/api-reference/chat/rename-archive-or-pin-a-named-chat-session /api-reference/mobilerun-agents/chat.yaml patch /assistant/chat/sessions/{id} Rename, change status, and/or pin. Title updates apply best-effort. Archiving always clears the pinned flag. `title` is rejected with 409 `code: "session_title_managed_by_workflow"` when this chat is bound to a workflow — a bound chat's title is managed by the workflow. Other fields (description, status, pinned) remain updateable; archiving a bound chat stays allowed. # Send a single user message Source: https://docs.mobilerun.ai/api-reference/chat/send-a-single-user-message /api-reference/mobilerun-agents/chat.yaml post /assistant/chat/message Send a single user message. The response format follows the Accept header: `text/event-stream` for SSE, `application/json` for a buffered assistant reply. Interactive HITL requires `Accept: text/event-stream`: the stream can emit a `tool-hitl-approval` event, whose decision must be delivered to `/assistant/chat/permission`. Buffered JSON responses do not provide an interactive HITL continuation contract. `sessionId` targets a concrete active chat. The resolved chat session ID is returned as `chatSessionId` in the JSON body and as the `X-Chat-Session-Id` response header on the SSE response. # Get device clipboard Source: https://docs.mobilerun.ai/api-reference/clipboard/get-device-clipboard /api-reference/phones/clipboard.yaml get /devices/{deviceId}/clipboard Returns the current text content of the device's clipboard. Devices without clipboard support return an unsupported-feature error. Reads the device's primary clipboard as plain text — whatever was last copied on the device or written through the set-clipboard endpoint. `text` is an empty string when the clipboard is empty or its current content is not text. On phones, Android only grants clipboard access to the selected input method: the read requires the Mobilerun keyboard to be selected on the device, and answers `409 DEVICE_CLIPBOARD_KEYBOARD_REQUIRED` until it is. # Set device clipboard Source: https://docs.mobilerun.ai/api-reference/clipboard/set-device-clipboard /api-reference/phones/clipboard.yaml post /devices/{deviceId}/clipboard Replaces the device's clipboard content with the text in the request body; an empty text clears the clipboard. Devices without clipboard support return an unsupported-feature error. Replaces the device's primary clipboard with the given plain text, exactly as if it had been copied on the device — a paste in any app inserts it. Sending an empty `text` clears the clipboard. # Connect a Gmail inbox Source: https://docs.mobilerun.ai/api-reference/connections/connect-a-gmail-inbox /api-reference/mobilerun-mailbox/connections.yaml post /mailboxes/connections Links the caller’s Gmail account. Replaying the same Idempotency-Key returns the same mailbox. When Gmail is already active, redirectUrl is null and the mailbox is usable immediately. # Poll a Gmail inbox connection Source: https://docs.mobilerun.ai/api-reference/connections/poll-a-gmail-inbox-connection /api-reference/mobilerun-mailbox/connections.yaml get /mailboxes/connections/{connectionId} Reports pending, active (with the Gmail address), expired, or removed. connectionId is the mailbox id. # List the caller's own SMS conversations, one row per thread Source: https://docs.mobilerun.ai/api-reference/conversations/list-the-callers-own-sms-conversations-one-row-per-thread /api-reference/mobilerun-numbers/messages/conversations.yaml get /numbers/messages/conversations Lists SMS conversations by recent activity. Use both cursor fields from `nextCursor` to fetch the next page. # Mark a conversation's inbound messages read up to a cursor Source: https://docs.mobilerun.ai/api-reference/conversations/mark-a-conversations-inbound-messages-read-up-to-a-cursor /api-reference/mobilerun-numbers/messages/conversations.yaml post /numbers/messages/conversations/read Marks inbound messages in a conversation as read through the supplied cursor. Repeating the request is safe. # List available countries Source: https://docs.mobilerun.ai/api-reference/countries/list-available-countries /api-reference/mobilerun-proxy/countries.yaml get /connect/countries Lookup of countries that can be selected when creating a proxy. Each country lists the proxy types available there; without a ?type filter, every covered country is returned. # Add a credential field Source: https://docs.mobilerun.ai/api-reference/credential-packages/add-a-credential-field /api-reference/credentials-ref/credential-packages.yaml post /credentials/packages/{packageName}/credentials/{credentialName}/fields Adds a single field to an existing credential. The body specifies a `fieldType` (one of the supported field types) and its value. Returns a conflict if a field of that type already exists on the credential. # Create a credential Source: https://docs.mobilerun.ai/api-reference/credential-packages/create-a-credential /api-reference/credentials-ref/credential-packages.yaml post /credentials/packages/{packageName} Creates a credential under the given package with a `credentialName` and at least one field. Each field has a `fieldType` (email, username, password, api_token, phone_number, two_factor_secret, or backup_codes) and a value. # Delete a credential and all its fields Source: https://docs.mobilerun.ai/api-reference/credential-packages/delete-a-credential-and-all-its-fields /api-reference/credentials-ref/credential-packages.yaml delete /credentials/packages/{packageName}/credentials/{credentialName} Permanently deletes the credential identified by `packageName` and `credentialName`, removing all of its fields. Returns the deleted credential. # Delete a field from a credential Source: https://docs.mobilerun.ai/api-reference/credential-packages/delete-a-field-from-a-credential /api-reference/credentials-ref/credential-packages.yaml delete /credentials/packages/{packageName}/credentials/{credentialName}/fields/{fieldType} Removes a single field of the given `fieldType` from the specified credential while leaving the credential itself intact. Returns the updated credential. # Initialize a new package/app Source: https://docs.mobilerun.ai/api-reference/credential-packages/initialize-a-new-packageapp /api-reference/credentials-ref/credential-packages.yaml post /credentials/packages Creates a new package (identified by `packageName`) under which credentials can be grouped. Returns a conflict if a package with the same name already exists for the user. # Link a 1Password item to a credential Source: https://docs.mobilerun.ai/api-reference/credential-packages/link-a-1password-item-to-a-credential /api-reference/credentials-ref/credential-packages.yaml post /credentials/packages/{packageName}/links # List credentials for a specific package Source: https://docs.mobilerun.ai/api-reference/credential-packages/list-credentials-for-a-specific-package /api-reference/credentials-ref/credential-packages.yaml get /credentials/packages/{packageName} Returns all credentials stored under the given `packageName`. Each credential includes its name, secret path, and the list of fields it holds. # List packages Source: https://docs.mobilerun.ai/api-reference/credential-packages/list-packages /api-reference/credentials-ref/credential-packages.yaml get /credentials/packages Returns the names of all packages (apps) the authenticated owner has credentials grouped under. Use this to discover which `packageName` values are valid for the per-package credential routes. # Update the value of a credential field Source: https://docs.mobilerun.ai/api-reference/credential-packages/update-the-value-of-a-credential-field /api-reference/credentials-ref/credential-packages.yaml patch /credentials/packages/{packageName}/credentials/{credentialName}/fields/{fieldType} Updates the value of an existing field on a credential, identified by `packageName`, `credentialName`, and `fieldType` in the path. The body carries the new value and returns the updated credential. # Create a proxy config Source: https://docs.mobilerun.ai/api-reference/custom-proxies/create-a-proxy-config /api-reference/mobilerun-proxy/custom-proxies.yaml post /proxies Creates a proxy config. The body is a discriminated union on `protocol`: `socks5` requires name, host, port, user, and password, while `wireguard` requires name and a config string. Returns the created config with its generated `proxyId`. # Delete a proxy config Source: https://docs.mobilerun.ai/api-reference/custom-proxies/delete-a-proxy-config /api-reference/mobilerun-proxy/custom-proxies.yaml delete /proxies/{proxyId} Permanently deletes the proxy config identified by `proxyId` and returns the deleted config. Returns not found if no matching config exists. # Get a proxy config Source: https://docs.mobilerun.ai/api-reference/custom-proxies/get-a-proxy-config /api-reference/mobilerun-proxy/custom-proxies.yaml get /proxies/{proxyId} Fetches a single proxy config by its `proxyId`. The response shape depends on the proxy's `protocol` (socks5 or wireguard). Returns not found if no matching config exists. # List proxy configs Source: https://docs.mobilerun.ai/api-reference/custom-proxies/list-proxy-configs /api-reference/mobilerun-proxy/custom-proxies.yaml get /proxies Returns all proxy configs for the authenticated user. An optional `protocol` query parameter (`socks5` or `wireguard`) filters the results by proxy type. # Update a proxy config Source: https://docs.mobilerun.ai/api-reference/custom-proxies/update-a-proxy-config /api-reference/mobilerun-proxy/custom-proxies.yaml put /proxies/{proxyId} Replaces the proxy config identified by `proxyId` with the provided body. As with creation, the body is a `protocol`-discriminated union of socks5 or wireguard fields. Returns the updated config. # Open a deep link Source: https://docs.mobilerun.ai/api-reference/deep-link/open-a-deep-link /api-reference/phones/deep-link.yaml post /devices/{deviceId}/apps/open-deep-link Opens a deep link on the device. On Android the link is dispatched as an intent — packageName optionally pins it to a specific app and action overrides the default android.intent.action.VIEW. On iOS the URL is opened directly and the optional fields must be omitted. Protected packages are rejected. Opens a deep link on the device, e.g. `myapp://profile/42` or an HTTPS app link such as `https://example.com/item/7`. On Android the link is dispatched as an intent. By default any app that handles the link can receive it (`android.intent.action.VIEW`); pass `packageName` to pin the intent to a specific app, or `action` to dispatch a different intent action. Requests targeting a protected package fail with `403 Forbidden`. On iOS the URL is opened directly by the system. `packageName` and `action` are Android-only and fail with an unsupported-feature error when set; `bundleId` is reserved for targeting a specific iOS app and is not yet supported. # Count claimed devices Source: https://docs.mobilerun.ai/api-reference/devices/count-claimed-devices /api-reference/phones.yaml get /devices/count Deprecated: use GET /devices/summary instead. Returns the number of active claimed devices for the user, broken down by device type, in the legacy response shape. # Device fingerprint snapshot Source: https://docs.mobilerun.ai/api-reference/devices/device-fingerprint-snapshot /api-reference/phones.yaml get /devices/{deviceId}/fingerprint Returns a live snapshot of the device's spoofed identity, including model, display, identifiers, and carrier. Devices without fingerprint support return an unsupported-feature error. The snapshot reflects what apps running on the device observe. Sections are collected independently and best-effort: values the device cannot report come back empty instead of failing the request — treat empty fields as "unknown", not as an error. # Get capabilities for a specific device Source: https://docs.mobilerun.ai/api-reference/devices/get-capabilities-for-a-specific-device /api-reference/phones.yaml get /devices/{deviceId}/capabilities Returns the set of capabilities supported by this device. Used to determine which tools and features are available for the device. # Get device info Source: https://docs.mobilerun.ai/api-reference/devices/get-device-info /api-reference/phones.yaml get /devices/{deviceId} Returns the current state and metadata for a single device, including its lifecycle state, type, stream URL, billing strategy, and timestamps. A stream token is included while the device is active. # List devices Source: https://docs.mobilerun.ai/api-reference/devices/list-devices /api-reference/phones.yaml get /devices Returns a paginated list of the user's devices along with pagination metadata. By default every device except terminated and unknown-state ones is listed, including stopped and maintenance devices; narrow with e.g. `state=ready` or `state=stopped,maintenance`, and pass `state=terminated` or `state=unknown` to see those. Returns a paginated list of your devices with pagination metadata. ## Default state filter Without a `state` parameter the list contains devices in these states: `creating`, `assigned`, `ready`, `rebooting`, `migrating`, `resetting`, `maintenance` and `stopped`. A stopped device or a device in maintenance still exists and is listed. ```http GET /v1/devices ``` Devices in the `terminated` or `unknown` state are hidden unless you request them: ```http GET /v1/devices?state=terminated ``` ## Filter by state Pass one or more states to narrow the list. Separate states with commas: ```http GET /v1/devices?state=stopped,maintenance ``` Repeating the parameter (`?state=stopped&state=maintenance`) returns the same result. To list only devices that can run a task right now, request `state=ready`. A stopped device keeps its data and is not billed. Start it again with `POST /v1/devices/{deviceId}/resume`. ## Filter by creation start `createdAfter` includes devices created at or after the RFC3339 timestamp. ```http GET /v1/devices?createdAfter=2026-10-01T00:00:00Z ``` ## Filter by creation end `createdBefore` includes devices created before the RFC3339 timestamp. The end is exclusive. When both bounds are set, `createdAfter` must be earlier than `createdBefore`; an equal or inverted range returns 400. ```http GET /v1/devices?createdAfter=2026-10-01T00:00:00Z&createdBefore=2026-10-02T00:00:00Z ``` Both date filters combine with state, type, name, createdBy and other existing filters in the same paginated query. Pagination totals reflect every filter. # Provision a new device Source: https://docs.mobilerun.ai/api-reference/devices/provision-a-new-device /api-reference/phones.yaml post /devices Requests a new device from the specification in the request body. Optional query parameters select the canonical device type, country, billing mode, and base profile. Returns the device, its resolved billing strategy, and its stream token. Requests a new device from the specification in the request body. The response includes the device, its resolved `billingStrategy`, and its stream token. ## Choose a device type Use **`android_cloud_phone`** for the cloud Android phone offering. For example: ```http POST /v1/devices?deviceType=android_cloud_phone&billing=minute Content-Type: application/json {} ``` Send your normal API authentication with this request. Explicit minute billing still requires sufficient minute balance and an available concurrency allowance. The accepted device types are **`android_cloud_phone`**, **`ios_phone`** and **`device_slot`**. Any other value is rejected with HTTP 422. A listed type that is not available for creation in your deployment returns **`DEVICE_TYPE_UNAVAILABLE` (HTTP 422)**. This is different from temporarily having no free devices. ## Choose a billing mode | Mode | Admission behavior | | - | - | | `auto` (default) | Tries subscription billing first. If the customer has **no subscription entitlement**, or **all subscription slots are in use**, tries minute billing when enabled for this type. If subscription billing is disabled, uses minute billing directly when enabled. | | `subscription` | Requires subscription billing to be enabled, an active entitlement, and a free subscription slot. Never falls back to minutes. | | `minute` | Uses minute billing only. Requires that mode to be enabled, sufficient minute balance, and an available minute concurrency allowance where configured. | A missing subscription and exhausted subscription slots are distinct denials, but both allow `auto` to try minutes. **Billing-service failures and indeterminate responses never trigger fallback.** When neither mode is enabled, creation is denied. Fallback is another admission attempt, not a guarantee that creation will succeed. An explicit subscription request without entitlement returns `SUBSCRIPTION_REQUIRED` (HTTP 402). When minute billing is enabled, the message suggests explicitly selecting `billing=minute`, subject to its own checks. A minute-billed request whose cloud-phone minute balance is exhausted (the plan's minute feature is spent, not a generic credits shortfall) returns `MINUTE_BALANCE_EXHAUSTED` (HTTP 402). The remedy is a plan upgrade, a one-off minute top-up, or the next billing period, not a credits top-up. Minute-billed concurrency limits keep the generic `PAYMENT_REQUIRED` (HTTP 402) shape. ## Idempotency Send an optional `Idempotency-Key` header (1-255 printable ASCII characters, no spaces) to make a retry safe. Retrying with the same key and the same request returns the same device, with the original status, its current state and `Idempotent-Replayed: true`; no second device is created or billed. * The same key with a different request (device type, country, billing, profile or spec) returns `422 idempotency_key_reused`. * While the first request is still running, a retry returns `409 idempotency_request_in_progress` with `Retry-After: 1`; retry shortly. * If the device has since been terminated, deleted or transferred to another owner, the retry returns `404` (still marked `Idempotent-Replayed: true`) and never a stream token. * A create that is **denied before any device exists** (for example a billing or capacity denial) frees the key, so a retry re-evaluates the request. * A create that fails **after the device was announced** (for example a provider error) binds the key to that device instead, so a retry can never create a second one: the retry is a replay (`404` if that device is already terminated). This is a deliberate deviation from "a failed create always frees the key"; use a new key to start over. * A create that is cancelled because it ran too long follows the same rule: the key stays bound only if a device was created, and is otherwise freed. * A malformed key returns `400 invalid_idempotency_key`. Without the header the endpoint behaves exactly as before. Keys are scoped to your account and kept for at least 24 hours. # Reboot a device Source: https://docs.mobilerun.ai/api-reference/devices/reboot-a-device /api-reference/phones.yaml post /devices/{deviceId}/reboot Triggers a reboot of the device. The device transitions through its reboot lifecycle and becomes ready again once the restart completes. Only devices whose capabilities report `reboot=true` can be rebooted. Personal (BYOD) devices cannot be rebooted remotely: the request is refused with 400 `DEVICE_TOOL_UNSUPPORTED` and nothing happens on the device. # Reset a device to a fresh state Source: https://docs.mobilerun.ai/api-reference/devices/reset-a-device-to-a-fresh-state /api-reference/phones.yaml post /devices/{deviceId}/reset Resets the device. `mode` selects what is erased: `full` (factory reset: apps, accounts, storage, new identity) or `identity` (new fingerprint, apps and data kept). Without `mode` the reset is `full`, or `identity` on devices with `factoryReset=false`. A mode or `preserve` value the device does not support is refused with 400 `DEVICE_TOOL_UNSUPPORTED`. `preserve` restores the latest proxy, location, locale or timezone set through the API after the reset; omitted or empty preserves nothing. The device becomes ready again after the reset. # Resume (unpark) a stopped device Source: https://docs.mobilerun.ai/api-reference/devices/resume-unpark-a-stopped-device /api-reference/phones.yaml post /devices/{deviceId}/resume Wakes a parked device: it first checks that the device can run again, then the same device starts and per-minute billing resumes. On a device that is not parked, the request does nothing. # Stop (park) a device Source: https://docs.mobilerun.ai/api-reference/devices/stop-park-a-device /api-reference/phones.yaml post /devices/{deviceId}/stop Parks the device: its data, apps and identity are kept, but nothing runs and nothing is billed until it is resumed. Only devices whose capabilities report stop=true support this; others return 404. # Summarize claimed devices Source: https://docs.mobilerun.ai/api-reference/devices/summarize-claimed-devices /api-reference/phones.yaml get /devices/summary Returns the total number of the user's devices and counts grouped by current state and device type. # Terminate a device Source: https://docs.mobilerun.ai/api-reference/devices/terminate-a-device /api-reference/phones.yaml delete /devices/{deviceId} Terminates the device and releases its resources. For a personal (BYOD) device the owner (API key or user) can instead remove the phone from the account so anyone can pair it again; the phone must be disconnected first, otherwise the request is rejected with 409 BYOD_DEVICE_CONNECTED. Other subscription-billed devices cannot be terminated with this request; it is rejected with 401. The `terminateAt` and `previousDeviceId` body fields are reserved for internal use; requests that set them are rejected with 401. Terminates the device and releases its resources. ## Personal (BYOD) devices A personal device is your own phone, connected through the Mobilerun app. It cannot be terminated: it reconnects on its own. Instead, `DELETE` removes the phone from your account. Afterwards anyone can pair it again, including you. The phone must be disconnected first. If it is still connected, the request fails with `409 BYOD_DEVICE_CONNECTED`: ```json { "code": "BYOD_DEVICE_CONNECTED", "message": "BYOD device is connected; disconnect the phone before removing it" } ``` Close the app or log out on the phone, wait until the device shows as offline, then send the request again. # Update device name Source: https://docs.mobilerun.ai/api-reference/devices/update-device-name /api-reference/phones.yaml put /devices/{deviceId}/name Sets the display name for a device from the name in the request body and returns the updated device. # Wait for device to be ready Source: https://docs.mobilerun.ai/api-reference/devices/wait-for-device-to-be-ready /api-reference/phones.yaml get /devices/{deviceId}/wait Blocks until the device reaches the ready state, then returns the same payload as Get device info. The call returns early with an error if the wait is cancelled or times out. # Ingest an event Source: https://docs.mobilerun.ai/api-reference/events/ingest-an-event /api-reference/workflows/events.yaml post /events/ingest Ingest an event for trigger evaluation. Returns immediately with 202 Accepted. # Simulate event matching (dry run) Source: https://docs.mobilerun.ai/api-reference/events/simulate-event-matching-dry-run /api-reference/workflows/events.yaml post /events/dry-run Simulate an event against all configured flows. Returns which flows would match and what actions would run, without storing the event or enqueuing jobs. # Abort a running or pending execution Source: https://docs.mobilerun.ai/api-reference/executions/abort-a-running-or-pending-execution /api-reference/workflows/executions.yaml post /executions/{executionId}/abort Stops the execution between steps and marks it cancelled. Idempotent-ish: already-terminal executions return 409. # Get execution details Source: https://docs.mobilerun.ai/api-reference/executions/get-execution-details /api-reference/workflows/executions.yaml get /executions/{executionId} Fetch a single flow execution by its ID, including its status, kind, result or error, and start/finish timestamps. Returns 404 if no execution matches. # Get execution metrics Source: https://docs.mobilerun.ai/api-reference/executions/get-execution-metrics /api-reference/workflows/executions.yaml get /executions/metrics Return aggregate execution metrics — total count, counts by status, average duration, and the last execution time. Can be scoped by `flowId`, `triggerId`, and a `from`/`to` time range. # List flow executions Source: https://docs.mobilerun.ai/api-reference/executions/list-flow-executions /api-reference/workflows/executions.yaml get /executions Return a paginated history of flow executions. Supports filtering by `flowId`, `triggerId`, `invocationId` (the client/verify key), `status`, and a `from`/`to` time range, plus free-text `search` and ordering by startedAt, finishedAt, or status. # Redirect to a freshly signed screenshot URL Source: https://docs.mobilerun.ai/api-reference/executions/redirect-to-a-freshly-signed-screenshot-url /api-reference/workflows/executions.yaml get /executions/{executionId}/screenshots/{screenshotId} Redirects (302) to a freshly signed, time-limited image URL for a screenshot captured during this execution. Owner-gated: 404 if the execution or the screenshot does not belong to the caller. # Cancel a pending upload (transitions to expired, deletes the underlying object) Source: https://docs.mobilerun.ai/api-reference/files/cancel-a-pending-upload-transitions-to-expired-deletes-the-underlying-object /api-reference/mobilerun-agents/files.yaml delete /agents/files/{fileId}/pending Soft-cancels an in-flight upload before confirm. Only acts on `pending` uploads — refuses to touch `ready` files, so confirmed files are never removed. Idempotent: `{ cancelled: false }` if the file exists but is no longer pending. # Confirm a file upload by server-side HEAD validation Source: https://docs.mobilerun.ai/api-reference/files/confirm-a-file-upload-by-server-side-head-validation /api-reference/mobilerun-agents/files.yaml post /agents/files/{fileId}/confirm # Delete file Source: https://docs.mobilerun.ai/api-reference/files/delete-file /api-reference/phones/files.yaml delete /devices/{deviceId}/files Deletes the file at the path given in the path query parameter from the device. Removes the file at `path`, rooted at the device's shared storage, e.g. `/Download/report.pdf`. Deletion is immediate and permanent — there is no trash to recover from. The endpoint targets individual files; to clear out a directory, list it and delete its files one by one. # Download an owned file Source: https://docs.mobilerun.ai/api-reference/files/download-an-owned-file /api-reference/mobilerun-agents/files.yaml get /agents/files/{fileId}/download Redirects to a short-lived presigned download URL. Missing, non-ready, and files owned by another tenant all return the same 404 response. # Download file Source: https://docs.mobilerun.ai/api-reference/files/download-file /api-reference/phones/files.yaml get /devices/{deviceId}/files/download Pulls the file at the given path query parameter from the device and returns its raw bytes as an octet-stream. Returns the file's raw bytes in the response body. The `Content-Type` is always `application/octet-stream` regardless of the file's actual type, and no filename header is set — derive the name from the `path` you requested. The whole file arrives in a single response; range requests are not supported. Errors: a missing file returns `404 DEVICE_PATH_NOT_FOUND`; a directory returns `422 DEVICE_PATH_NOT_FILE`. # Hard-delete a file Source: https://docs.mobilerun.ai/api-reference/files/hard-delete-a-file /api-reference/mobilerun-agents/files.yaml delete /agents/files/{fileId} # List files Source: https://docs.mobilerun.ai/api-reference/files/list-files /api-reference/phones/files.yaml get /devices/{deviceId}/files Lists the files at the directory path given in the path query parameter, returning each entry's metadata along with the path and total count. `path` is a directory path rooted at the device's shared storage — `/` is the storage root (primary external storage on Android devices), e.g. `/Download`. The response contains the directory's direct entries only — it does not recurse into subdirectories. File access is available on Android devices only; file requests against an iOS device fail with `400`. > [!NOTE] > > Depending on the device type, some entry metadata (`owner`, `group`, `permissions`, `hardLinks`) may be zeroed rather than reflect real values. # Invalid directories On hosted Android Phones, nonexistent directories return `404 DEVICE_PATH_NOT_FOUND`, files used as directories return `422 DEVICE_PATH_NOT_DIRECTORY`, and unreadable directories return `403 DEVICE_PATH_FORBIDDEN`. A readable empty directory remains a successful listing with zero entries. Paths retain the external-storage scope: `/` means primary shared storage, and `/data/...` does not grant app-private filesystem access. # List the user's ready files, optionally filtered by zone Source: https://docs.mobilerun.ai/api-reference/files/list-the-users-ready-files-optionally-filtered-by-zone /api-reference/mobilerun-agents/files.yaml get /agents/files # Mint a presigned PUT URL for a user file upload Source: https://docs.mobilerun.ai/api-reference/files/mint-a-presigned-put-url-for-a-user-file-upload /api-reference/mobilerun-agents/files.yaml post /agents/files/upload-url # Update file metadata (skills zone only) Source: https://docs.mobilerun.ai/api-reference/files/update-file-metadata-skills-zone-only /api-reference/mobilerun-agents/files.yaml patch /agents/files/{fileId} Partial update of `displayName` and/or `enabled`. Only files with `zone=skills` are mutable; other zones return 422 `unsupported_zone`. # Upload file Source: https://docs.mobilerun.ai/api-reference/files/upload-file /api-reference/phones/files.yaml post /devices/{deviceId}/files Uploads a file to the device via multipart form data, writing it into the directory given by the path query parameter using the uploaded file's name. `path` is the destination **directory**, not the full file path — the file is written there under its original uploaded filename. Paths are rooted at the device's shared storage (`/` is the storage root): uploading `report.pdf` with `path=/Download` creates `/Download/report.pdf`. > [!TIP] > > File access runs without root and stays within the device's shared storage tree; protected system paths are not reachable. # Activate a verified flow Source: https://docs.mobilerun.ai/api-reference/flows/activate-a-verified-flow /api-reference/workflows/flows.yaml post /flows/{flowId}/activate Activate a disabled flow only when the supplied verification execution succeeded and the flow graph has not changed since verification. Repeating activation is idempotent for an already-enabled flow. # Add an action to a flow Source: https://docs.mobilerun.ai/api-reference/flows/add-an-action-to-a-flow /api-reference/workflows/flows.yaml post /flows/{flowId}/actions Append a single action to a flow at the given `position`, optionally nesting it under a `parentFlowActionId` or supplying its own `children`. Supports a `nameOverride`, param `overrides`, and `continueOnError`. Returns 404 if the flow does not exist. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters). Replays with the same key and an identical body return the original 201; a changed body under the same key returns 422 `idempotency_key_reused`. # Archive a flow Source: https://docs.mobilerun.ai/api-reference/flows/archive-a-flow /api-reference/workflows/flows.yaml delete /flows/{flowId} Terminally archive a flow by its ID. Archived flows cannot be restored and are hidden from customer reads. Repeating the request is idempotent for the owner. # Clone a flow Source: https://docs.mobilerun.ai/api-reference/flows/clone-a-flow /api-reference/workflows/flows.yaml post /flows/{flowId}/clone Create a copy of an existing flow, including its actions and settings. The optional body can override the new flow's `name` and target `deviceIds`. Returns 404 if the source flow does not exist. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters). Replays with the same key and an identical body return the original 201; a changed body under the same key returns 422 `idempotency_key_reused`. # Create a flow Source: https://docs.mobilerun.ai/api-reference/flows/create-a-flow /api-reference/workflows/flows.yaml post /flows Create a flow that binds a trigger (`triggerId`) to an ordered list of actions, with at least one action required. Optional settings include target `deviceIds`, a cooldown (`cooldownSeconds`/`cooldownScope`), and webhook notifications on success or failure. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters). Replays with the same key and an identical body return the original 201; a changed body under the same key returns 422 `idempotency_key_reused`. # Dry-run a flow Source: https://docs.mobilerun.ai/api-reference/flows/dry-run-a-flow /api-reference/workflows/flows.yaml post /flows/{flowId}/dry-run Simulate this flow firing without storing events, enqueuing jobs, or consuming cooldown/rate-limit slots. Works for every trigger activation type: - `event`: validates the payload against the event catalog schema and evaluates the trigger conditions. - `custom`: validates the payload against the custom payload schema (conditions do not apply). - `schedule`: ignores the payload and reports the next fire time. The response reports `wouldFire` — whether the flow would actually run right now — alongside the gates that decide it (enabled, device attached, blocked, cooldown). `rateLimited` is informational and is not folded into `wouldFire`. # Get a flow Source: https://docs.mobilerun.ai/api-reference/flows/get-a-flow /api-reference/workflows/flows.yaml get /flows/{flowId} Fetch a single flow by its ID, including its trigger binding, configuration, and current status. Returns 404 if no flow matches. # Get flow delivery options Source: https://docs.mobilerun.ai/api-reference/flows/get-flow-delivery-options /api-reference/workflows/flows.yaml get /flows/{flowId}/delivery-options Return the recording/delivery readiness for a flow (recording mode, whether delivery can include the recording, whether a files.upload action exists, the first direct OneDrive/Google Drive upload step if any) plus, per destination, whether the flow owner has an active connection. Returns 404 if the flow does not exist. # Get flow template context Source: https://docs.mobilerun.ai/api-reference/flows/get-flow-template-context /api-reference/workflows/flows.yaml get /flows/template-context # Get routine capacity Source: https://docs.mobilerun.ai/api-reference/flows/get-routine-capacity /api-reference/workflows/flows.yaml get /flows/capacity Returns the environment routine limit and remaining capacity for this owner and agent bucket, counting enabled and disabled non-deleted flows. Omit agentId (or use unassigned) for the unassigned bucket. This is advisory; create and clone enforce admission under a bucket lock. # List actions for a flow Source: https://docs.mobilerun.ai/api-reference/flows/list-actions-for-a-flow /api-reference/workflows/flows.yaml get /flows/{flowId}/actions Return the ordered list of actions attached to a flow, including any nested child actions. Returns 404 if the flow does not exist. # List flows Source: https://docs.mobilerun.ai/api-reference/flows/list-flows /api-reference/workflows/flows.yaml get /flows Return a paginated list of flows. Supports filtering by `agentId` (UUID or `unassigned`; omit for all buckets), `triggerId`, `enabled`, one or more health `status` values (healthy, failing, blocked), `mine` (flows created by the calling actor), `createdBy` (flows created by a given actor id — mutually exclusive with `mine`), plus free-text `search` and ordering. # List self-healing repair episodes Source: https://docs.mobilerun.ai/api-reference/flows/list-self-healing-repair-episodes /api-reference/workflows/flows.yaml get /flows/{flowId}/repairs # Remove an action from a flow Source: https://docs.mobilerun.ai/api-reference/flows/remove-an-action-from-a-flow /api-reference/workflows/flows.yaml delete /flows/{flowId}/actions/{flowActionId} Remove a single action from a flow by its `flowActionId`. Returns 404 if the flow or flow action does not exist. # Replace all actions for a flow Source: https://docs.mobilerun.ai/api-reference/flows/replace-all-actions-for-a-flow /api-reference/workflows/flows.yaml put /flows/{flowId}/actions Replace a flow's entire action list with the supplied set (at least one required). Each action references an `actionId` and a unique `position`, and may include nested `children`, a `nameOverride`, param `overrides`, and a `continueOnError` flag. Returns 404 if the flow does not exist. # Run a flow now Source: https://docs.mobilerun.ai/api-reference/flows/run-a-flow-now /api-reference/workflows/flows.yaml post /flows/{flowId}/run Immediately enqueue one live execution on every device bound to the flow, regardless of whether its trigger is event-based, custom, or scheduled. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters). The run identity is derived from the key, so a retry never starts a second run. Replays with the same key and an identical body return the original status and the original `executionIds`; a changed body under the same key returns 422 `idempotency_key_reused`. # Unblock a flow Source: https://docs.mobilerun.ai/api-reference/flows/unblock-a-flow /api-reference/workflows/flows.yaml post /flows/{flowId}/unblock Clear a flow's blocked status after fixing the underlying issue. Idempotent — safe to call on already-healthy flows. # Update a flow Source: https://docs.mobilerun.ai/api-reference/flows/update-a-flow /api-reference/workflows/flows.yaml patch /flows/{flowId} Partially update a flow's settings — name, trigger binding, enabled state, target devices, cooldown, or notifications; all fields are optional. Actions are managed through the flow-actions endpoints, not here. Returns 404 if the flow does not exist. # Validate a flow Source: https://docs.mobilerun.ai/api-reference/flows/validate-a-flow /api-reference/workflows/flows.yaml post /flows/validate # Verify a flow Source: https://docs.mobilerun.ai/api-reference/flows/verify-a-flow /api-reference/workflows/flows.yaml post /flows/{flowId}/verify Run a bound, deduplicated **verification** of this flow on exactly one device as a real run. Unlike a normal trigger firing, verification: - runs a flow that is `enabled` OR `disabled` (an archived flow returns 404); - targets one device (`deviceId`, or the single bound device); - is idempotent per `invocationId`: a repeat returns the existing run (`deduplicated: true`, HTTP 200) instead of enqueuing another (HTTP 202); - never mutates flow health, `lastTriggeredAt`, or the repair loop. Per-activation payload gate: - `custom`: validates the payload against the custom payload schema (422 on failure). - `event`: validates the payload against the event catalog schema and evaluates the trigger conditions; a failing gate returns 409 `conditions_not_met` with the dry-run report. - `schedule`: the payload is ignored. # Delete a function Source: https://docs.mobilerun.ai/api-reference/functions/delete-a-function /api-reference/serverless-functions.yaml delete /compute/functions/{functionId} # Get function metadata Source: https://docs.mobilerun.ai/api-reference/functions/get-function-metadata /api-reference/serverless-functions.yaml get /compute/functions/{functionId} # List functions owned by this organisation Source: https://docs.mobilerun.ai/api-reference/functions/list-functions-owned-by-this-organisation /api-reference/serverless-functions.yaml get /compute/functions # Read verified function source Source: https://docs.mobilerun.ai/api-reference/functions/read-verified-function-source /api-reference/serverless-functions.yaml get /compute/functions/{functionId}/source # Upload an immutable Python function as the next version of its name Source: https://docs.mobilerun.ai/api-reference/functions/upload-an-immutable-python-function-as-the-next-version-of-its-name /api-reference/serverless-functions.yaml post /compute/functions # List integration targets Source: https://docs.mobilerun.ai/api-reference/integrations/list-integration-targets /api-reference/webhooks/integrations.yaml get /webhooks/integrations/{capabilityId}/targets Returns the live list of targets (e.g. Slack channels the connected account is a member of) for an integration. Pass a target's `args` together with the integration `capability` to `POST /webhooks` with `kind: "integration"`. # List message integrations Source: https://docs.mobilerun.ai/api-reference/integrations/list-message-integrations /api-reference/webhooks/integrations.yaml get /webhooks/integrations Returns the integrations that can receive webhook events as channel messages (e.g. Slack), with your org's connection state for each. Connect an integration in the Cloud app before creating a webhook for it. # Clear input Source: https://docs.mobilerun.ai/api-reference/keyboard/clear-input /api-reference/phones/keyboard.yaml delete /devices/{deviceId}/keyboard Clears the contents of the currently focused text input field. Clears whatever text the currently focused input field contains. Make sure an editable field has focus first — check `phone_state.isEditable` and `focusedElement` in the UI state response. When you're replacing a field's contents, the input text endpoint's `clear` flag does the same thing in one call. # Input key Source: https://docs.mobilerun.ai/api-reference/keyboard/input-key /api-reference/phones/keyboard.yaml put /devices/{deviceId}/keyboard Sends a single Android key event to the device, identified by its key code. Key codes are standard Android `KeyEvent` codes — for example `66` (Enter) or `4` (Back). A common pattern: type into a field with the input text endpoint, then send `66` to submit it. # Input text Source: https://docs.mobilerun.ai/api-reference/keyboard/input-text /api-reference/phones/keyboard.yaml post /devices/{deviceId}/keyboard Types text into the focused input field. The optional completionMode defaults to accepted for backwards-compatible low latency; committed additionally waits for the complete text or a quiescent UI state. Text goes to the currently focused input field — tap a field first, and confirm focus via the UI state response (`phone_state.focusedElement` and `keyboardVisible`). `wpm` and `errorRate` are humanize tuning knobs, and each applies to a different class of device: devices with human-like input support honor `errorRate` and ignore `wpm`; all other devices honor `wpm` and ignore `errorRate`. `completionMode` is optional and defaults to `accepted`, which preserves the existing behavior and returns after the device input provider accepts the operation. Use `committed` when the next action depends on the complete value being visible: the request then waits until the focused field contains the full expected text or the focused UI state remains unchanged for a bounded stability window. Devices without accessibility read-back reject `committed` before typing. Set `humanize: true` for human-like typing where the device supports it. # Disable kiosk (lock-task) mode Source: https://docs.mobilerun.ai/api-reference/kiosk/disable-kiosk-lock-task-mode /api-reference/phones/kiosk.yaml delete /devices/{deviceId}/kiosk Disables Android lock-task (kiosk) mode on the device, releasing it from the locked app. The previously locked app keeps running — the device is unpinned, but the app is not stopped. Android only: iOS devices return an unsupported-feature error. # Enable kiosk (lock-task) mode Source: https://docs.mobilerun.ai/api-reference/kiosk/enable-kiosk-lock-task-mode /api-reference/phones/kiosk.yaml put /devices/{deviceId}/kiosk Locks the device to the package named in the request body using Android lock-task (kiosk) mode, preventing the user from leaving the app. The app must already be running in the foreground — kiosk mode locks the device to the app's existing task, and the call fails if the package has no task. Launch it first, e.g. with the start-app endpoint. Locking is applied once and is not restored automatically; re-enable it after a reboot or reset. > [!NOTE] > > Android only. iOS devices return an unsupported-feature error. # Get device language/locale Source: https://docs.mobilerun.ai/api-reference/language/get-device-languagelocale /api-reference/phones/language.yaml get /devices/{deviceId}/language Returns the device's current language/locale as a BCP-47 locale string. Most devices report a BCP-47 tag like `de-DE`, but some use an underscore separator (`zh_CN` instead of `zh-CN`) — normalize before comparing. # Set device language/locale Source: https://docs.mobilerun.ai/api-reference/language/set-device-languagelocale /api-reference/phones/language.yaml post /devices/{deviceId}/language Sets the device language/locale to the BCP-47 locale in the request body. An optional restart flag applies the change immediately by restarting the Android system framework (open apps are closed) instead of waiting for the next reboot; some devices ignore it. Include a region subtag — use `de-DE` rather than `de` — since some devices reject language-only locales. Script subtags may be dropped: `zh-Hans-CN` is applied as `zh-CN`. If the device cannot apply the requested locale, the call fails with a verification error instead of silently keeping the old language. # Get device location Source: https://docs.mobilerun.ai/api-reference/location/get-device-location /api-reference/phones/location.yaml get /devices/{deviceId}/location Returns the device's current simulated GPS location as latitude and longitude. Devices without geo support return an unsupported-feature error. If the device cannot report a position yet, the call still succeeds and returns latitude and longitude `0` — treat `0,0` as "not available", not as a real coordinate. # Reset the device location to default Source: https://docs.mobilerun.ai/api-reference/location/reset-the-device-location-to-default /api-reference/phones/location.yaml delete /devices/{deviceId}/location Clears any simulated GPS location and restores the device's default location behavior. Devices without geo support return an unsupported-feature error. On cloud devices this re-points the simulated position at the platform default — New York City (`40.7128, -74.0060`) — it does not disable location simulation. # Set device location Source: https://docs.mobilerun.ai/api-reference/location/set-device-location /api-reference/phones/location.yaml post /devices/{deviceId}/location Sets the device's simulated GPS location to the latitude and longitude in the request body. Devices without geo support return an unsupported-feature error. Coordinates are decimal degrees; negative latitude is south, negative longitude is west. The new position applies to the running device immediately. This changes the simulated GPS position only — the device's IP-based geolocation is determined by its proxy. > [!NOTE] > > Connecting a proxy with `smartIp: true` overwrites the position to match the proxy's exit IP. # Get a mailbox message Source: https://docs.mobilerun.ai/api-reference/mailbox-messages/get-a-mailbox-message /api-reference/mobilerun-mailbox/mailbox-messages.yaml get /mailboxes/{mailboxId}/messages/{messageId} # List mailbox messages Source: https://docs.mobilerun.ai/api-reference/mailbox-messages/list-mailbox-messages /api-reference/mobilerun-mailbox/mailbox-messages.yaml get /mailboxes/{mailboxId}/messages Lists mailbox messages with cursor pagination and optional time, sender, and OTP filters. # Cancel or archive a mailbox Source: https://docs.mobilerun.ai/api-reference/mailboxes/cancel-or-archive-a-mailbox /api-reference/mobilerun-mailbox.yaml delete /mailboxes/{mailboxId} Cancels a pending mailbox or schedules an active paid mailbox for cancellation. Existing addresses and messages are retained. Repeating the request is safe. An external inbox (Gmail) cannot be cancelled here; disconnect the link instead. # Claim or rent a mailbox Source: https://docs.mobilerun.ai/api-reference/mailboxes/claim-or-rent-a-mailbox /api-reference/mobilerun-mailbox.yaml post /mailboxes Creates a mailbox on the default domain or a connected custom domain. An optional `localPart` selects the address. Replaying the same Idempotency-Key and payload returns the original mailbox. Fresh requests and replays return 202 with the current mailbox state. Poll the mailbox when the response does not yet include a checkout URL. # Get a mailbox Source: https://docs.mobilerun.ai/api-reference/mailboxes/get-a-mailbox /api-reference/mobilerun-mailbox.yaml get /mailboxes/{mailboxId} # Get included mailbox capacity Source: https://docs.mobilerun.ai/api-reference/mailboxes/get-included-mailbox-capacity /api-reference/mobilerun-mailbox.yaml get /mailboxes/capacity Returns the number of mailboxes currently available through included capacity. # Get the best OTP candidate Source: https://docs.mobilerun.ai/api-reference/mailboxes/get-the-best-otp-candidate /api-reference/mobilerun-mailbox.yaml get /mailboxes/{mailboxId}/otp Returns the most likely recent OTP for the mailbox. Returns 204 when no matching code is available. # List mailboxes Source: https://docs.mobilerun.ai/api-reference/mailboxes/list-mailboxes /api-reference/mobilerun-mailbox.yaml get /mailboxes Lists the caller-owned mailboxes with page-based pagination. # Restart rent on an archived mailbox Source: https://docs.mobilerun.ai/api-reference/mailboxes/restart-rent-on-an-archived-mailbox /api-reference/mobilerun-mailbox.yaml post /mailboxes/{mailboxId}/restart Restarts an archived mailbox with the same address. Uses included capacity when available unless paid service is requested. # Undo a scheduled cancellation Source: https://docs.mobilerun.ai/api-reference/mailboxes/undo-a-scheduled-cancellation /api-reference/mobilerun-mailbox.yaml post /mailboxes/{mailboxId}/uncancel Withdraws a scheduled cancellation. Only available while cancellation is pending. # Unlink a Gmail inbox Source: https://docs.mobilerun.ai/api-reference/mailboxes/unlink-a-gmail-inbox /api-reference/mobilerun-mailbox.yaml post /mailboxes/{mailboxId}/disconnect Removes only this mailbox link. The Gmail connection used by your agents stays in place. # Update a mailbox label Source: https://docs.mobilerun.ai/api-reference/mailboxes/update-a-mailbox-label /api-reference/mobilerun-mailbox.yaml patch /mailboxes/{mailboxId} Updates the label of a mailbox. # Get one of the caller's SMS messages Source: https://docs.mobilerun.ai/api-reference/messages/get-one-of-the-callers-sms-messages /api-reference/mobilerun-numbers/messages.yaml get /numbers/messages/{id} Returns one message. For an outbound message that is not yet final, the status may be refreshed once (at most every 30 s) before it is returned; a failed refresh returns the stored message. # List messages (inbox + outbox) on a number Source: https://docs.mobilerun.ai/api-reference/messages/list-messages-inbox-+-outbox-on-a-number /api-reference/mobilerun-numbers/numbers/messages.yaml get /numbers/phones/{id}/messages Returns SMS messages on the number, inbound and outbound, scoped to the authenticated user. Newest first. Messages stay with the number across device switches. # List the caller's own SMS inbox/outbox messages Source: https://docs.mobilerun.ai/api-reference/messages/list-the-callers-own-sms-inboxoutbox-messages /api-reference/mobilerun-numbers/messages.yaml get /numbers/messages Lists SMS messages newest first, with filters for direction, eSIM, phone number, status, and conversation. # Send an SMS from a number Source: https://docs.mobilerun.ai/api-reference/messages/send-an-sms-from-a-number /api-reference/mobilerun-numbers/numbers/messages.yaml post /numbers/phones/{id}/messages Queues an SMS from one of the caller's numbers that can send. Replaying an Idempotency-Key with the same payload returns the original message, reusing it with a different payload returns 422. 409 capability_unavailable: this number cannot send right now. 422 invalid_recipient / unsupported_destination / body_too_long: the recipient or text does not fit the number. 429 daily_limit_reached: the rolling 24 h limit for the account is used up; 429 rate_limited: too many sends by the owner in a short window; 429 number_rate_limited: too many outbound sends from this number in the configured window (all sends from this number count, including those made on your behalf). 403 send_disabled: self-service SMS send is switched off. # Cancel a phone-number purchase or an active rental Source: https://docs.mobilerun.ai/api-reference/numbers/cancel-a-phone-number-purchase-or-an-active-rental /api-reference/mobilerun-numbers/numbers.yaml delete /numbers/phones/{id} Cancels a pending purchase or schedules cancellation of an active paid phone number. Repeating a scheduled cancellation is safe. Returns 409 when cancellation is not available. # Get included phone-number capacity for a country Source: https://docs.mobilerun.ai/api-reference/numbers/get-included-phone-number-capacity-for-a-country /api-reference/mobilerun-numbers/numbers.yaml get /numbers/phones/capacity Returns included phone capacity for a country. Creating a phone is authoritative. # Get phone number by id Source: https://docs.mobilerun.ai/api-reference/numbers/get-phone-number-by-id /api-reference/mobilerun-numbers/numbers.yaml get /numbers/phones/{id} Retrieves a single phone number. # List dedicated-number countries Source: https://docs.mobilerun.ai/api-reference/numbers/list-dedicated-number-countries /api-reference/mobilerun-numbers/numbers.yaml get /numbers/phones/countries Lists available countries and current phone-number availability. # List phone numbers Source: https://docs.mobilerun.ai/api-reference/numbers/list-phone-numbers /api-reference/mobilerun-numbers/numbers.yaml get /numbers/phones Lists the caller's phone numbers. # Purchase a phone number Source: https://docs.mobilerun.ai/api-reference/numbers/purchase-a-phone-number /api-reference/mobilerun-numbers/numbers.yaml post /numbers/phones Starts a phone-number purchase. Poll the returned phone number for status updates. # Update a phone number's display label Source: https://docs.mobilerun.ai/api-reference/numbers/update-a-phone-numbers-display-label /api-reference/mobilerun-numbers/numbers.yaml patch /numbers/phones/{id} Updates the display label. Omitting `label` leaves it unchanged; null or an empty string clears it. # List packages Source: https://docs.mobilerun.ai/api-reference/packages/list-packages /api-reference/phones/packages.yaml get /devices/{deviceId}/packages Returns the package names of apps installed on the device. System and protected packages are excluded unless the corresponding query parameters are set. Returns bare package names. Use `list-apps` when you also need labels and version info. Protected packages are the platform's own device-management apps: they stay hidden unless you set `includeProtectedPackages=true`, and other app endpoints reject them with `403 Forbidden` anyway. On iOS devices, entries are bundle identifiers and `includeSystemPackages` has no effect — Apple's built-in apps are never listed. # Apply a profile to a device Source: https://docs.mobilerun.ai/api-reference/profile/apply-a-profile-to-a-device /api-reference/phones/profile.yaml put /devices/{deviceId}/profile # Create a proxy Source: https://docs.mobilerun.ai/api-reference/proxies/create-a-proxy /api-reference/mobilerun-proxy/proxies.yaml post /connect/proxies Provisions a proxy of the requested type for the caller in the selected country. # Delete a proxy Source: https://docs.mobilerun.ai/api-reference/proxies/delete-a-proxy /api-reference/mobilerun-proxy/proxies.yaml delete /connect/proxies/{id} Deletes the proxy identified by the path ID and releases its provisioning. Returns 404 if no such proxy exists for the caller. # Ensure the proxy's upstream session works Source: https://docs.mobilerun.ai/api-reference/proxies/ensure-the-proxys-upstream-session-works /api-reference/mobilerun-proxy/proxies.yaml post /connect/proxies/{id}/ensure-healthy Checks right now that the proxy's upstream accepts a connection through its current session. If the upstream refuses the session and the proxy is a rotating (sticky-session) proxy, the proxy is moved onto a fresh session that has been checked to work; its credentials and country stay the same, its exit IP changes. Intended for callers that are about to depend on the proxy (e.g. while provisioning a phone). After `rotated`, the gateway uses the new session within about 30 seconds. A `refused` or `unreachable` result is not an error: the response describes the proxy's state. # Get a payable checkout for a pending proxy Source: https://docs.mobilerun.ai/api-reference/proxies/get-a-payable-checkout-for-a-pending-proxy /api-reference/mobilerun-proxy/proxies.yaml post /connect/proxies/{id}/checkout Refreshes a pending dedicated proxy's checkout on explicit payment intent. Already-paid proxies (provisioning, active, or cancelling) return their current status without a payment URL. An expired checkout requires a new purchase. # Get proxy by ID Source: https://docs.mobilerun.ai/api-reference/proxies/get-proxy-by-id /api-reference/mobilerun-proxy/proxies.yaml get /connect/proxies/{id} Returns the proxy identified by the path ID. The response includes the proxy's password. # Latency check Source: https://docs.mobilerun.ai/api-reference/proxies/latency-check /api-reference/mobilerun-proxy/proxies.yaml get /connect/proxies/{id}/ping Returns the most recent cached network-latency measurement for the proxy, sampled periodically by connecting through the proxy to a fixed target. `latency` is null when no measurement is available yet (e.g. the proxy is not active, or it has not been sampled since coming online). # List proxies Source: https://docs.mobilerun.ai/api-reference/proxies/list-proxies /api-reference/mobilerun-proxy/proxies.yaml get /connect/proxies Returns proxies owned by the caller. Credentials are omitted from the list. # List Proxy Connections Source: https://docs.mobilerun.ai/api-reference/proxies/list-proxy-connections /api-reference/mobilerun-proxy/proxies.yaml get /connect/proxies/{id}/connections Returns the connection history recorded for this proxy, one item per connection (aggregated across the connection's lifetime). Supports filtering on every property plus ordering and pagination. Returns 503 when connection history is temporarily unavailable. # Update a proxy Source: https://docs.mobilerun.ai/api-reference/proxies/update-a-proxy /api-reference/mobilerun-proxy/proxies.yaml patch /connect/proxies/{id} Renames the proxy identified by the path ID. # Connect proxy Source: https://docs.mobilerun.ai/api-reference/proxy/connect-proxy /api-reference/phones/proxy.yaml post /devices/{deviceId}/proxy Routes the device's traffic through a SOCKS5 proxy supplied in the request body, replacing any existing connection. A smartIp option can be used to select an IP automatically; the legacy flat host/port/user/password fields remain supported. Provide **exactly one** proxy definition: the `socks5` object, the deprecated flat `host`/`port`/`user`/`password` fields (all four required together), or a Mobilerun Connect `connect` reference (see below). Sending more than one fails validation. ## Mobilerun Connect proxies Instead of passing credentials, reference a Mobilerun Connect proxy: ```json { "connect": { "id": "0d5a…" } } ``` fetches the credentials of an existing Connect proxy owned by the device's owner (it must be `active` or `cancelling`), while ```json { "connect": { "country": "us" } } ``` provisions a rotating **residential** proxy in that country — or reuses the one previously provisioned for this device when it is still active and in the same country. Provisioning waits up to 60 s for the proxy to become active. If payment is required first, the request fails with `402 PAYMENT_REQUIRED` and a `paymentUrl` detail pointing to checkout. With `smartIp: true`, the exit-IP precheck probes the proxy for up to \~45 s, so a freshly provisioned proxy that is still being routed passes without caller-side retries. If the precheck still fails, the error tells you why: * `409 CONNECT_PROXY_NOT_ACTIVE` — the proxy is not (or no longer) serving traffic, e.g. still provisioning. Transient while provisioning: retry in a few seconds. * A denial that keeps failing while the proxy is `active` usually means the organization is out of prepaid proxy data. The same error can occur briefly during transient failures, so it surfaces as a generic error rather than a billing one: retry, and check your proxy data balance if retries keep failing. Pass exactly one of `id` or `country`, and don't combine `connect` with `socks5` or the legacy flat fields. `smartIp` works with all variants. A proxy provisioned via `country` stays with the device and is cancelled automatically when the device is terminated. Proxies referenced by `id` are never cancelled by this API. With `smartIp: true`, the API geolocates the proxy's exit IP through the proxy itself and aligns the device to match — GPS location, time zone, locale, and (unless an eSIM is active) mobile carrier and network type. > [!WARNING] > > A smart IP failure leaves your existing proxy untouched, but a failure while connecting the new proxy can leave the device with no proxy at all. Check the proxy state before retrying. > [!NOTE] > > On some device types, an upstream switch on an already-proxied device applies live with no interruption, but the first time a device gets a proxy the device restarts to pick it up. # Disconnect proxy Source: https://docs.mobilerun.ai/api-reference/proxy/disconnect-proxy /api-reference/phones/proxy.yaml delete /devices/{deviceId}/proxy Disconnects the device's active proxy connection and clears its stored proxy state. Returns successfully if no proxy is connected. After disconnecting, the device's traffic uses its direct network connection again. > [!NOTE] > > Disconnecting does not revert `smartIp` changes — the device keeps the location, time zone, locale, and carrier settings that were aligned to the previous proxy's exit IP. > [!NOTE] > > On some device types, disconnecting always restarts the device to remove the proxy. # Get proxy connection state Source: https://docs.mobilerun.ai/api-reference/proxy/get-proxy-connection-state /api-reference/phones/proxy.yaml get /devices/{deviceId}/proxy Returns the device's current proxy connection state, including whether a proxy is connected and its protocol and name. The `connected` flag is a live check against the device, not just stored state — it can be `false` while `protocol` and `name` still describe a configured proxy whose link has dropped. Proxy host and credentials are never returned; you only get back the protocol and the `name` you supplied when connecting. # Delete a device recording Source: https://docs.mobilerun.ai/api-reference/recordings/delete-a-device-recording /api-reference/phones/recordings.yaml delete /devices/{deviceId}/recordings/{recordingId} # Get a device recording Source: https://docs.mobilerun.ai/api-reference/recordings/get-a-device-recording /api-reference/phones/recordings.yaml get /devices/{deviceId}/recordings/{recordingId} # Get a device recording trajectory Source: https://docs.mobilerun.ai/api-reference/recordings/get-a-device-recording-trajectory /api-reference/phones/recordings.yaml get /devices/{deviceId}/recordings/{recordingId}/trajectory # Get a device recording video Source: https://docs.mobilerun.ai/api-reference/recordings/get-a-device-recording-video /api-reference/phones/recordings.yaml get /devices/{deviceId}/recordings/{recordingId}/video # List a device recording's saved screenshots Source: https://docs.mobilerun.ai/api-reference/recordings/list-a-device-recordings-saved-screenshots /api-reference/phones/recordings.yaml get /devices/{deviceId}/recordings/{recordingId}/screenshots Screenshots saved into the recording with `GET /devices/{deviceId}/screenshot?save=true`, oldest first, each with a presigned download URL. # List device recordings Source: https://docs.mobilerun.ai/api-reference/recordings/list-device-recordings /api-reference/phones/recordings.yaml get /devices/{deviceId}/recordings # Start a device recording Source: https://docs.mobilerun.ai/api-reference/recordings/start-a-device-recording /api-reference/phones/recordings.yaml post /devices/{deviceId}/recordings # Stop a device recording Source: https://docs.mobilerun.ai/api-reference/recordings/stop-a-device-recording /api-reference/phones/recordings.yaml post /devices/{deviceId}/recordings/{recordingId} # Capture a device screenshot Source: https://docs.mobilerun.ai/api-reference/screenshots/capture-a-device-screenshot /api-reference/phones/screenshots.yaml post /devices/{deviceId}/screenshots Captures the device screen and returns it as a PNG image. Pass save=true to store it as device media. The response body is the PNG image itself (`Content-Type: image/png`), not a JSON wrapper. The accessibility overlay is the on-screen element-highlight layer controlled by the set overlay visibility endpoint. If you've enabled it, pass `hideOverlay=true` to capture a clean frame; on devices whose capture path sits below the overlay, the flag has no effect either way. Pass `save=true` to also store the captured PNG as device media. If the device has an active recording owned by the device owner, the screenshot is saved into that recording and inherits its retention. Otherwise it is saved standalone for seven days. Without `save=true`, no screenshot is stored. `X-Screenshot-Id` contains the saved screenshot ID only when persistence succeeds. The PNG response is unchanged; `X-Screenshot-Saved` is `true` when both the object and its metadata were stored, and `false` if storage limits or a save failure prevented persistence. A failed save does not fail screenshot capture. The device screenshots endpoints list saved screenshots, open their images, and delete individual screenshots. Recording screenshots remain available through the existing list recording screenshots endpoint and are also deleted with the recording. # Delete a device screenshot Source: https://docs.mobilerun.ai/api-reference/screenshots/delete-a-device-screenshot /api-reference/phones/screenshots.yaml delete /devices/{deviceId}/screenshots/{screenshotId} # Get a device screenshot image Source: https://docs.mobilerun.ai/api-reference/screenshots/get-a-device-screenshot-image /api-reference/phones/screenshots.yaml get /devices/{deviceId}/screenshots/{screenshotId}/image Redirects to a presigned PNG URL valid for 15 minutes. # Get Task Screenshot Source: https://docs.mobilerun.ai/api-reference/screenshots/get-task-screenshot /api-reference/tasks/screenshots.yaml get /tasks/{task_id}/screenshots/{index} Get a specific screenshot by index. # Get Task Screenshots Source: https://docs.mobilerun.ai/api-reference/screenshots/get-task-screenshots /api-reference/tasks/screenshots.yaml get /tasks/{task_id}/screenshots List all screenshot URLs for a task. # List device screenshots Source: https://docs.mobilerun.ai/api-reference/screenshots/list-device-screenshots /api-reference/phones/screenshots.yaml get /devices/{deviceId}/screenshots Saved screenshots, newest first. Pass nextCursor as cursor to retrieve the next page. # Configure eSIM Source: https://docs.mobilerun.ai/api-reference/sim/configure-esim /api-reference/phones/sim.yaml post /devices/{deviceId}/esim Download profile and/or enable subscription. Returns the newly installed subscription — keep its `subId` for later enable, delete, and APN calls. With `enable: true` the profile is activated in the same call; otherwise enable it later with enable-esim. `smDpAddr` is the bare SM-DP+ address, not a full activation code. Given `LPA:1$smdp.example.com$MATCH-123`, pass `smdp.example.com` as `smDpAddr` and `MATCH-123` as `matchingId`; a fourth segment would be `confirmationCode`. eSIM operations run one at a time per device — a concurrent call fails instead of queueing. # Create and set an APN for an eSIM subscription Source: https://docs.mobilerun.ai/api-reference/sim/create-and-set-an-apn-for-an-esim-subscription /api-reference/phones/sim.yaml post /devices/{deviceId}/esim/apn Creates an access point name (APN) from the request body and applies it to the given eSIM subscription. Type, protocol, and roaming protocol default to common values when omitted. `subId` comes from list-esim. Defaults when omitted: `name` takes the `apn` value; `type` is `default,supl`; `protocol` and `roamingProtocol` are `IPV4V6`. On iOS the new APN becomes active immediately, replacing the previous one. On Android it is only created — and the response doesn't return its id — so call list-esim-apns to find it, then select-esim-apn to make it preferred. # Delete eSIM subscription Source: https://docs.mobilerun.ai/api-reference/sim/delete-esim-subscription /api-reference/phones/sim.yaml delete /devices/{deviceId}/esim Deletes the eSIM subscription identified by the subId query parameter from the device. Get the `subId` from list-esim. > [!WARNING] > > Deletion is permanent. To use the plan on this device again, the profile must be downloaded again with configure-esim. # Enable an eSIM subscription Source: https://docs.mobilerun.ai/api-reference/sim/enable-an-esim-subscription /api-reference/phones/sim.yaml put /devices/{deviceId}/esim Enables the eSIM subscription identified by the subId in the request body so it becomes the active subscription. Use the `subId` from list-esim or from the configure-esim response. If you passed `enable: true` to configure-esim, the new profile is already active and this call is unnecessary. > [!NOTE] > > On iOS this re-requests the plan from the carrier rather than switching profiles — iOS provides no way to deactivate an active eSIM. # Get eSIM connectivity status Source: https://docs.mobilerun.ai/api-reference/sim/get-esim-connectivity-status /api-reference/phones/sim.yaml get /devices/{deviceId}/esim/status Returns the connectivity status of the device's eSIM subscriptions. Where list-esim shows what is provisioned, this shows how each active subscription is connecting. Poll it after enable-esim, set-esim-roaming, or an APN change to confirm mobile data actually came up (`dataState`, `networkType`) and that roaming flags took effect. # List APNs for active subscriptions Source: https://docs.mobilerun.ai/api-reference/sim/list-apns-for-active-subscriptions /api-reference/phones/sim.yaml get /devices/{deviceId}/esim/apn Returns the access point names (APNs) configured for the device's active eSIM subscriptions. Use an entry's `id` as `apnId` in select-esim-apn; `isPreferred` marks the APN currently in use. On Android the list covers all APNs of the active subscriptions, including carrier-provisioned ones; on iOS it shows only APNs created through this API. # List eSIM subscriptions Source: https://docs.mobilerun.ai/api-reference/sim/list-esim-subscriptions /api-reference/phones/sim.yaml get /devices/{deviceId}/esim Returns the eSIM subscriptions currently provisioned on the device. Start here: the `subId` of each entry is what the other SIM endpoints take (enable, delete, and APN calls). The list may also include physical SIM slots — entries with `isEmbedded: false` are not eSIM profiles. # Select an existing APN as preferred Source: https://docs.mobilerun.ai/api-reference/sim/select-an-existing-apn-as-preferred /api-reference/phones/sim.yaml put /devices/{deviceId}/esim/apn Marks an existing APN, identified by apnId, as the preferred APN for the given eSIM subscription in the request body. Get `apnId` from the `id` field of list-esim-apns and `subId` from list-esim. Use it after set-esim-apn on Android, where new APNs are not preferred automatically. > [!NOTE] > > iOS APNs apply device-wide, so `subId` is ignored there. # Toggle eSIM data roaming Source: https://docs.mobilerun.ai/api-reference/sim/toggle-esim-data-roaming /api-reference/phones/sim.yaml put /devices/{deviceId}/esim/roaming Enables or disables data roaming for the device's eSIM based on the enabled flag in the request body. Roaming is a device-wide setting — it is not scoped to a `subId`. Check the effect with get-esim-status, which reports `dataRoamingEnabled` per subscription. On iOS this toggles voice roaming along with data roaming. # Device time Source: https://docs.mobilerun.ai/api-reference/state/device-time /api-reference/phones/state.yaml get /devices/{deviceId}/time Returns the device's current wall-clock time as an RFC 3339 timestamp. The timestamp is read live from the device's own clock, not from the API server. > [!TIP] > > Don't infer the device's timezone from the timestamp's UTC offset — it isn't guaranteed to match the device's setting. Use the get-timezone endpoint for that. # Take screenshot Source: https://docs.mobilerun.ai/api-reference/state/take-screenshot /api-reference/phones/state.yaml get /devices/{deviceId}/screenshot Deprecated: use POST /devices/{deviceId}/screenshots. Captures the device screen and returns it as a PNG image. An optional hideOverlay query parameter excludes the accessibility overlay from the capture. Deprecated: use `POST /devices/{deviceId}/screenshots` to capture a screenshot. Existing callers can continue using this endpoint and migrate in a follow-up. The response body is the PNG image itself (`Content-Type: image/png`), not a JSON wrapper. The accessibility overlay is the on-screen element-highlight layer controlled by the set overlay visibility endpoint. If you've enabled it, pass `hideOverlay=true` to capture a clean frame; on devices whose capture path sits below the overlay, the flag has no effect either way. Pass `save=true` to also store the captured PNG as device media. If the device has an active recording owned by the device owner, the screenshot is saved into that recording and inherits its retention. Otherwise it is saved standalone for seven days. Without `save=true`, no screenshot is stored. The PNG response is unchanged; `X-Screenshot-Saved` is `true` when both the object and its metadata were stored, and `false` if storage limits or a save failure prevented persistence. A failed save does not fail screenshot capture. The device screenshots endpoints list saved screenshots, open their images, and delete individual screenshots. Recording screenshots remain available through the existing list recording screenshots endpoint and are also deleted with the recording. # UI state Source: https://docs.mobilerun.ai/api-reference/state/ui-state /api-reference/phones/state.yaml get /devices/{deviceId}/ui-state Returns the current accessibility UI state of the device as a structured tree of on-screen elements. An optional filter query reduces the result to interactive elements. Alongside the main `a11y_tree`, the response carries a separate `ime_tree` for the on-screen keyboard window, `phone_state` (foreground app, focused element, keyboard visibility), and `device_context` (screen bounds, display density). > [!TIP] > > Element `boundsInScreen` values are in the same pixel space the tap and swipe endpoints use — read an element's bounds and tap the center of its box for element-driven automation. ## iOS phones iOS phones (`ios_phone`, virtual and physical) return the same response: the same top-level keys (`a11y_tree`, `ime_tree`, `phone_state`, `device_context`), the same node fields and the same `filter` semantics. The device's capabilities report `accessibility: true` when it serves the UI state; otherwise this endpoint answers 400 `DEVICE_TOOL_UNSUPPORTED`. * Coordinates are iOS logical points, the space the tap and swipe endpoints use on iOS, so the tap-the-center rule above holds unchanged. `device_context.screen_bounds` is in points, and `display_metrics` gives the scale (`density` 3 means `widthPixels` is three times the width in points). * `className` uses iOS element types (`Application`, `Button`, `TextField`, `SearchField`, `SecureTextField`, `Switch`, `StaticText`, `Key`, ...), and `resourceId` is the accessibility identifier. * `ime_tree` is the software keyboard when it is up, otherwise empty. On phones that cannot read the keyboard separately it stays empty and `keyboardVisible` still reports it. * `phone_state.packageName` is the bundle ID and `currentApp` the app's name. `activityName` is absent: iOS has no activities. * `isVisibleToUser` is absent and `isLongClickable` is always `false`: iOS exposes no such signal. # Attach Task Source: https://docs.mobilerun.ai/api-reference/tasks/attach-task /api-reference/tasks.yaml get /tasks/{task_id}/attach Attach to a running task and receive its events as an SSE stream. # Get Task Source: https://docs.mobilerun.ai/api-reference/tasks/get-task /api-reference/tasks.yaml get /tasks/{task_id} Get full details of a task by ID. # Get Task Status Source: https://docs.mobilerun.ai/api-reference/tasks/get-task-status /api-reference/tasks.yaml get /tasks/{task_id}/status Get the status of a task. # Get Task Trajectory Source: https://docs.mobilerun.ai/api-reference/tasks/get-task-trajectory /api-reference/tasks.yaml get /tasks/{task_id}/trajectory Get the trajectory of a task. # List Tasks Source: https://docs.mobilerun.ai/api-reference/tasks/list-tasks /api-reference/tasks.yaml get /tasks List tasks with optional filtering, sorting, and pagination. # List tasks for a device Source: https://docs.mobilerun.ai/api-reference/tasks/list-tasks-for-a-device /api-reference/phones/tasks.yaml get /devices/{deviceId}/tasks Returns a paginated list of tasks that have run on the device, along with pagination metadata. # Run Streamed Task Source: https://docs.mobilerun.ai/api-reference/tasks/run-streamed-task /api-reference/tasks.yaml post /tasks/stream Create and dispatch a new agent task, returning an SSE stream of task events. Cancels the task if the client disconnects. # Run Task Source: https://docs.mobilerun.ai/api-reference/tasks/run-task /api-reference/tasks.yaml post /tasks Create and dispatch a new agent task. Returns the task ID and device stream details. # Send Message Source: https://docs.mobilerun.ai/api-reference/tasks/send-message /api-reference/tasks.yaml post /tasks/{task_id}/message Send a message to a running agent task. The message ID is delivered via SSE (UserMessageEvent with action=queued). # Stop Task Source: https://docs.mobilerun.ai/api-reference/tasks/stop-task /api-reference/tasks.yaml post /tasks/{task_id}/cancel Cancel a running task. Returns an error if the task is already in a terminal state. # Get device timezone Source: https://docs.mobilerun.ai/api-reference/timezone/get-device-timezone /api-reference/phones/timezone.yaml get /devices/{deviceId}/timezone Returns the device's current timezone identifier. Devices that do not support timezone control return an unsupported-feature error. The identifier is an IANA timezone name, e.g. `Europe/Berlin`. `timezone` is `null` when the device doesn't report one — for example when no timezone has been set yet. # Set device timezone Source: https://docs.mobilerun.ai/api-reference/timezone/set-device-timezone /api-reference/phones/timezone.yaml post /devices/{deviceId}/timezone Sets the device timezone to the identifier in the request body. Devices that do not support timezone control return an unsupported-feature error. Provide an IANA timezone identifier, e.g. `Europe/Berlin` or `America/New_York`. The change applies immediately; no reboot is needed. # List supported IANA timezones Source: https://docs.mobilerun.ai/api-reference/timezones/list-supported-iana-timezones /api-reference/workflows/timezones.yaml get /timezones # Get a device traffic session Source: https://docs.mobilerun.ai/api-reference/traffic-sessions/get-a-device-traffic-session /api-reference/phones/traffic-sessions.yaml get /devices/{deviceId}/traffic/sessions/{sessionId} Returns status and the device stream credential for a live session. # List device traffic sessions Source: https://docs.mobilerun.ai/api-reference/traffic-sessions/list-device-traffic-sessions /api-reference/phones/traffic-sessions.yaml get /devices/{deviceId}/traffic/sessions # Start device traffic inspection Source: https://docs.mobilerun.ai/api-reference/traffic-sessions/start-device-traffic-inspection /api-reference/phones/traffic-sessions.yaml post /devices/{deviceId}/traffic/sessions Starts one live-only decoded HTTP/1.1, HTTP/2, HTTP/3 and WebSocket traffic session. # Stop device traffic inspection Source: https://docs.mobilerun.ai/api-reference/traffic-sessions/stop-device-traffic-inspection /api-reference/phones/traffic-sessions.yaml delete /devices/{deviceId}/traffic/sessions/{sessionId} # Create a trigger Source: https://docs.mobilerun.ai/api-reference/triggers/create-a-trigger /api-reference/workflows/triggers.yaml post /triggers Create a trigger with an activation type of `event`, `schedule`, or `custom`. Each type requires its own fields (e.g. `eventType` and optional `conditions` for events, `scheduleRule` and `timezone` for schedules, `customPayloadSchema` for custom triggers); mismatched fields are rejected. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters). Replays with the same key and an identical body return the original 201; a changed body under the same key returns 422 `idempotency_key_reused`. # Delete a trigger Source: https://docs.mobilerun.ai/api-reference/triggers/delete-a-trigger /api-reference/workflows/triggers.yaml delete /triggers/{triggerId} Delete a trigger by its ID. Returns 404 if no trigger matches. # Fire a custom trigger with payload Source: https://docs.mobilerun.ai/api-reference/triggers/fire-a-custom-trigger-with-payload /api-reference/workflows/triggers.yaml post /triggers/{triggerId}/fire Invoke a custom trigger directly with an arbitrary JSON payload. Fan-out: a trigger may be referenced by multiple flows (workflows). Firing it enqueues one execution per enabled, non-deleted flow attached to this trigger, each receiving the same payload. The `enqueuedCount` in the response reports how many were enqueued (0 if no flows are attached, or if all matching flows are gated by a cooldown). Payload validation: - If the trigger has a `customPayloadSchema`, the payload is validated against it (JSON Schema). - If no schema is configured, the payload only needs to be a JSON object — any keys and values are accepted. Only triggers with `activation = "custom"` can be fired through this endpoint; event and schedule triggers return 409. Supports an optional `Idempotency-Key` header (1-255 printable ASCII characters), which maps to the derived `invocationId` used for fan-out deduplication. The payload is bound to the key on the first accepted fire, before fan-out. A repeat with the same key and an identical payload returns 202 with `Idempotent-Replayed: true` (`deduplicated: true` when flows were skipped; `enqueuedCount` counts only executions enqueued by that call); a changed payload under the same key returns 422 `idempotency_key_reused`. # Get a trigger Source: https://docs.mobilerun.ai/api-reference/triggers/get-a-trigger /api-reference/workflows/triggers.yaml get /triggers/{triggerId} Fetch a single trigger by its ID, including its activation type and type-specific configuration. Returns 404 if no trigger matches. # List triggers Source: https://docs.mobilerun.ai/api-reference/triggers/list-triggers /api-reference/workflows/triggers.yaml get /triggers Return a paginated list of triggers. Supports filtering by `activation` and `eventType`, free-text `search`, and ordering by name, createdAt, or updatedAt. # Update a trigger Source: https://docs.mobilerun.ai/api-reference/triggers/update-a-trigger /api-reference/workflows/triggers.yaml patch /triggers/{triggerId} Partially update a trigger; all fields are optional. When `activation` is changed, the type-specific field rules are re-validated. Returns 404 if the trigger does not exist. # Get Task Ui State Source: https://docs.mobilerun.ai/api-reference/ui-states/get-task-ui-state /api-reference/tasks/ui-states.yaml get /tasks/{task_id}/ui_states/{index} Get a specific UI state by index. # Get Task Ui States Source: https://docs.mobilerun.ai/api-reference/ui-states/get-task-ui-states /api-reference/tasks/ui-states.yaml get /tasks/{task_id}/ui_states List all UI state URLs for a task. # Create a SOCKS5 user Source: https://docs.mobilerun.ai/api-reference/users/create-a-socks5-user /api-reference/mobilerun-proxy/users.yaml post /connect/users Creates a SOCKS5 credential, optionally bound to a proxy for dedicated routing. Username and password are generated when omitted. # Delete a SOCKS5 user Source: https://docs.mobilerun.ai/api-reference/users/delete-a-socks5-user /api-reference/mobilerun-proxy/users.yaml delete /connect/users/{id} Deletes the SOCKS5 user identified by the path ID, revoking its credentials and any proxy binding. Returns 404 if no such user exists for the caller. # Get a SOCKS5 user by ID Source: https://docs.mobilerun.ai/api-reference/users/get-a-socks5-user-by-id /api-reference/mobilerun-proxy/users.yaml get /connect/users/{id} Returns the SOCKS5 user identified by the path ID. The response includes the user's password. # List connections by SOCKS5 user Source: https://docs.mobilerun.ai/api-reference/users/list-connections-by-socks5-user /api-reference/mobilerun-proxy/users.yaml get /connect/users/{id}/connections Returns the connection history recorded for this user, one item per connection (aggregated across the connection's lifetime). Supports filtering on every property plus ordering and pagination. Returns 503 when connection history is temporarily unavailable. # List SOCKS5 users Source: https://docs.mobilerun.ai/api-reference/users/list-socks5-users /api-reference/mobilerun-proxy/users.yaml get /connect/users Returns SOCKS5 users owned by the caller. Passwords are omitted from the list. # Update a SOCKS5 user Source: https://docs.mobilerun.ai/api-reference/users/update-a-socks5-user /api-reference/mobilerun-proxy/users.yaml patch /connect/users/{id} Rebind the user to a different proxy (or detach it by passing null). # Retrieve a function validation owned by this organisation Source: https://docs.mobilerun.ai/api-reference/validations/retrieve-a-function-validation-owned-by-this-organisation /api-reference/serverless-functions/validations.yaml get /compute/functions/validations/{validationId} # Validate Python function source without uploading it Source: https://docs.mobilerun.ai/api-reference/validations/validate-python-function-source-without-uploading-it /api-reference/serverless-functions/validations.yaml post /compute/functions/validations # Get a delivery with its attempts Source: https://docs.mobilerun.ai/api-reference/webhook-deliveries/get-a-delivery-with-its-attempts /api-reference/webhooks/webhook-deliveries.yaml get /webhooks/{id}/deliveries/{deliveryId} Returns a single delivery for a webhook subscription along with the full list of captured attempt records. Each attempt includes the request URL, method, headers and body, whether it was signed, and the response status, headers, and snippet. # Get delivery statistics Source: https://docs.mobilerun.ai/api-reference/webhook-deliveries/get-delivery-statistics /api-reference/webhooks/webhook-deliveries.yaml get /webhooks/deliveries/stats Returns aggregate delivery statistics across all of your webhooks, including the total count, a breakdown by status (pending, success, skipped, dead), and the overall success rate. Optional `since` and endpoint delivery `kind` filters narrow the reporting window. # List deliveries across all your webhooks Source: https://docs.mobilerun.ai/api-reference/webhook-deliveries/list-deliveries-across-all-your-webhooks /api-reference/webhooks/webhook-deliveries.yaml get /webhooks/deliveries Returns a paginated feed of webhook deliveries across all of your subscriptions, with the originating endpoint URL included on each record. Results can be filtered by delivery status (pending, success, skipped, or dead), by a `since` timestamp, by `eventId` (exact match against the originating event id), and/or by endpoint delivery `kind`. # List deliveries for a webhook Source: https://docs.mobilerun.ai/api-reference/webhook-deliveries/list-deliveries-for-a-webhook /api-reference/webhooks/webhook-deliveries.yaml get /webhooks/{id}/deliveries Returns a paginated list of deliveries for a single webhook subscription, identified by its id. Each record reports the event, delivery status, attempt count, and the last response code or error. Results can be filtered by `eventId` (exact match against the originating event id). # Delete a webhook subscription Source: https://docs.mobilerun.ai/api-reference/webhooks/delete-a-webhook-subscription /api-reference/webhooks.yaml delete /webhooks/{id} Deletes a webhook subscription so it stops receiving deliveries. Returns 204 No Content on success. # Get a webhook subscription Source: https://docs.mobilerun.ai/api-reference/webhooks/get-a-webhook-subscription /api-reference/webhooks.yaml get /webhooks/{id} Returns a single webhook subscription by id, including its URL (or integration target), subscribed event types, state, and system-observed delivery health. The signing secret is never included. # List your webhook subscriptions Source: https://docs.mobilerun.ai/api-reference/webhooks/list-your-webhook-subscriptions /api-reference/webhooks.yaml get /webhooks Returns a paginated list of your webhook subscriptions, optionally filtered by status (active, failing, blocked, or disabled), by `search` (a case-insensitive substring match against the URL or description), and/or by delivery `kind`. The response also includes per-status counts across all of your subscriptions (of the requested `kind`, if given; the other filters do not apply to the counts). # Register a webhook subscription Source: https://docs.mobilerun.ai/api-reference/webhooks/register-a-webhook-subscription /api-reference/webhooks.yaml post /webhooks Creates a webhook subscription and an optional list of event types to subscribe to (defaults to all when omitted). `kind: "http"` (the default) delivers signed JSON to a URL; the response includes the generated signing secret, which is returned only once at creation time and cannot be retrieved later. `kind: "integration"` posts each event as a message into a connected integration target (e.g. a Slack channel): pick the `capability` from `GET /webhooks/integrations` and the `args` from `GET /webhooks/integrations/{capabilityId}/targets`. Integration webhooks have no signing secret. Send an `Idempotency-Key` header to make the create safe to retry: the same key with the same body returns the existing webhook (status 201, `Idempotent-Replayed: true`) instead of creating a second one, and the same key with a different body is a 422. A replayed create does not return the signing secret again; use rotate-secret if the original response was lost. If that webhook was deleted in the meantime, the retry is a 404. # Rotate signing secret Source: https://docs.mobilerun.ai/api-reference/webhooks/rotate-signing-secret /api-reference/webhooks.yaml post /webhooks/{id}/rotate-secret Generates a new signing secret for the webhook subscription and returns it once in the response. The previous secret is replaced immediately, so any signature verification on your endpoint must be updated to use the new value. Only `http` webhooks have a signing secret; for `integration` webhooks this returns 400. # Send a one-shot test delivery Source: https://docs.mobilerun.ai/api-reference/webhooks/send-a-one-shot-test-delivery /api-reference/webhooks.yaml post /webhooks/{id}/test Sends a single test payload to the webhook subscription URL (or a test message to its integration target) to verify connectivity. The response reports whether the attempt succeeded along with the returned HTTP status code or error, if any. # Update a webhook subscription Source: https://docs.mobilerun.ai/api-reference/webhooks/update-a-webhook-subscription /api-reference/webhooks.yaml patch /webhooks/{id} Updates a webhook subscription. Any combination of the subscribed event types, state (ACTIVE or DISABLED), and description may be changed, and at least one field must be supplied. Setting state to ACTIVE re-enables a subscription that was auto-blocked after sustained delivery failures. The URL or integration target cannot be changed; delete and recreate the webhook instead. # Apps Source: https://docs.mobilerun.ai/apps Manage your app library: upload your own app files or add apps from the Mobilerun App Store, then deploy them to your devices. The Apps tab is your central hub for managing apps. Upload your own Android or iOS app files, or browse the Mobilerun App Store and add apps to your library, then deploy them to your devices. ## Overview The Apps tab allows you to: * View all apps available in your user space * Upload your own app files (APK, XAPK, APKM, ZIP, or IPA) * Browse the hosted App Store and add apps to your library * Deploy apps to your devices ## App Library Your app library displays all applications you have access to. Each app entry shows: | Field | Description | | - | - | | **App Name** | The application display name | | **Package Name** | App package identifier (e.g., `com.example.app`) | | **Version** | Installed app version | ## Uploading your own apps To upload your own app, open the upload dialog: Upload an app 1. Click the **Upload app** button 2. Select an APK, XAPK, APKM, ZIP, or IPA file from your local machine 3. Review the app details 4. The app appears in your library once ready > [!NOTE] > > Uploaded apps are stored securely in your user space and are only accessible to your account. Uploads count toward your storage and are blocked when your storage is full. ## Mobilerun App Store Choose **Browse the App Store** to search the hosted App Store and add apps to your library without uploading a file. Browse the App Store ## Deploying Apps to Devices Once an app is in your library, you can install it on any of your devices: | Device Type | Deployment | | - | - | | **Cloud Android** | Apps persist across sessions on your dedicated virtual devices | | **Cloud iOS** | IPA files you uploaded or added from the App Store | | **Personal Phone** | Apps install to your connected hardware via the [Mobilerun Portal App](/guides/connect-android) (Android) | ### Installation Methods **From the Apps tab** Select an app and choose which device to install it on. **From the Task runner** Reference apps by package name in your agent prompts. The agent can install and interact with any app in your library. **Via API** Specify apps in your task configuration when running tasks programmatically. ### Upload with the SDK `apps.upload` uploads the files and returns an `App`. A string is a local file path, and the file streams from disk. Uploads count toward your storage and may incur storage charges. ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const app = await mobilerun.apps.upload({ bundleId: 'com.example.app', displayName: 'Example', versionCode: 1, versionName: '1.0', files: ['app.apk'], }); console.log(app.id); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() app = mobilerun.apps.upload( bundle_id="com.example.app", display_name="Example", version_code=1, version_name="1.0", files=["app.apk"], ) print(app.id) ``` See [SDK helpers](/sdk/helpers#uploads) for file uploads. ## Managing Apps ### Remove Apps Delete apps from your library when no longer needed. This removes the app from your user space but does not uninstall it from devices where it was previously deployed. ### Update Apps Upload a new version of an app file to replace the existing one in your library. Installing the new version on a device replaces the installed app in place and preserves its app data. You don't need to uninstall the old version first. To check for newer Android app versions in your library, use `includeUpdates=true` on [List apps](/api-reference/apps/list-apps). Checks are off by default. An `availableUpdate` object includes `versionCode`, `versionName`, and `country`; pass `versionCode` and `country` to [Install app](/api-reference/apps/install-app) to select that update. Checks are best effort: an absent `availableUpdate` can mean up to date or unknown, and iOS and system apps do not receive update information. ### View App Details Click on any app to see: * Full package information * Installation history * Devices where the app is currently installed # Browser Automation Source: https://docs.mobilerun.ai/browser-automation Drive Chrome on a Mobilerun device with Puppeteer or Playwright over the Chrome DevTools Protocol. Mobilerun exposes a per-device WebSocket that reverse-proxies Chrome-for-Android's DevTools (CDP) endpoint. Off-the-shelf browser automation libraries — [Puppeteer](https://pptr.dev) and [Playwright](https://playwright.dev) — connect to it with a single URL, just like they would to a local Chrome instance. Use this when you want to script Chrome on a device directly (navigate, evaluate JavaScript, intercept network requests, scrape content) instead of going through the agent. ## Endpoint ``` wss://api.mobilerun.ai/v1/devices/{deviceId}/browser/cdp ``` The endpoint is a **browser-level** CDP socket. Pages are multiplexed over the CDP `Target` domain — you do not need a separate URL per tab. ### Authentication Pass your Mobilerun API key as a request header during the WebSocket handshake: ``` Authorization: Bearer dr_sk_YOUR_API_KEY ``` > [!WARNING] > > Always send the key as a header. Never put credentials in the URL — query-string tokens leak into logs, traces, and proxy access records. ### Requirements * The device must be in the `ready` state. See [Devices](/devices) for state details. * Chrome must be installed and have remote debugging available on the device. If Chrome's CDP socket is not reachable, the connection fails at handshake with a clear error. * You need a Mobilerun [API key](/api-keys). ## Connect with Puppeteer The Python tab uses Playwright for the same CDP connection. ```typescript TypeScript theme={null} import puppeteer from 'puppeteer-core'; const deviceId = process.env.DEVICE_ID!; const browser = await puppeteer.connect({ browserWSEndpoint: `wss://api.mobilerun.ai/v1/devices/${deviceId}/browser/cdp`, headers: { Authorization: `Bearer ${process.env.MOBILERUN_API_KEY}`, }, }); const page = await browser.newPage(); await page.goto('https://example.com'); const title = await page.title(); console.log(title); await browser.disconnect(); ``` ```python Python theme={null} import os from playwright.sync_api import sync_playwright with sync_playwright() as playwright: browser = playwright.chromium.connect_over_cdp( f"wss://api.mobilerun.ai/v1/devices/{os.environ['DEVICE_ID']}/browser/cdp", headers={"Authorization": f"Bearer {os.environ['MOBILERUN_API_KEY']}"}, ) context = browser.contexts[0] if browser.contexts else browser.new_context() page = context.new_page() page.goto("https://example.com") print(page.title()) browser.close() ``` ## Connect with Playwright ```typescript TypeScript theme={null} import { chromium } from 'playwright'; const deviceId = process.env.DEVICE_ID!; const browser = await chromium.connectOverCDP( `wss://api.mobilerun.ai/v1/devices/${deviceId}/browser/cdp`, { headers: { Authorization: `Bearer ${process.env.MOBILERUN_API_KEY}`, }, } ); const context = browser.contexts()[0] ?? await browser.newContext(); const page = await context.newPage(); await page.goto('https://example.com'); console.log(await page.title()); await browser.close(); ``` ```python Python theme={null} import os from playwright.sync_api import sync_playwright with sync_playwright() as playwright: browser = playwright.chromium.connect_over_cdp( f"wss://api.mobilerun.ai/v1/devices/{os.environ['DEVICE_ID']}/browser/cdp", headers={"Authorization": f"Bearer {os.environ['MOBILERUN_API_KEY']}"}, ) context = browser.contexts[0] if browser.contexts else browser.new_context() page = context.new_page() page.goto("https://example.com") print(page.title()) browser.close() ``` ## How it works The endpoint transparently bridges the WebSocket to Chrome's `chrome_devtools_remote` socket on the device. There is no local port forwarding to set up and no separate ADB tunnel to manage — once the device is connected to Mobilerun, the CDP endpoint is available automatically on every adb-backed device type such as a [Cloud Android](/device-types#cloud-android). Standard CDP semantics apply: connect once at the browser level, then attach to individual tabs through `Target.getTargets` / `Target.attachToTarget` (Puppeteer and Playwright handle this for you). ## Limitations * **Chrome only.** WebView debugging (`webview_devtools_remote_`) is not exposed. * **Browser-level only.** There is no per-page `/json/list` proxy — use the CDP `Target` domain to enumerate and attach to pages. * **Chrome must be debuggable.** A device without an active Chrome CDP socket fails at connect time. # Bring your own model key Source: https://docs.mobilerun.ai/byok Use your OpenAI, Anthropic, or Google key for models in Mobilerun Cloud. Bring your own key (BYOK) connects Mobilerun to your model-provider account. You keep using Mobilerun's tasks, agent, and routines while your provider bills you directly for model usage routed through that key. BYOK is available on all plans, including Free. Keys belong to the selected workspace, not just the person who adds them. Organization owners and admins can manage them; members have read-only access. You can also use Mobilerun without adding a model key. ## Supported providers | Provider | Where to create a key | | - | - | | OpenAI | [OpenAI Platform → API keys](https://platform.openai.com/api-keys) | | Anthropic | [Anthropic Console → API Keys](https://console.anthropic.com/settings/keys) | | Google | [Google AI Studio → Get API key](https://aistudio.google.com/apikey) | Adding a provider key makes its supported model set available in Mobilerun. It does not add every model the provider offers. Use the model list shown in Cloud. ## Add a key in Cloud Open LLM keys **1. Open LLM keys** Select the workspace that should use the key. In **Billing & plans**, open **LLM keys**. **2. Add a credential** Choose **New credential**. Select **Provider**, optionally enter a **Label**, and paste the provider's **API key**. Choose **Save**. Cloud checks the key's format and sets up its models. Saving is not a live connection test. **3. Test the key** In **Test a credential**, select the saved **Credential** and choose **Test connection**. This sends a short message through that key. **Connection succeeded** confirms a response from the provider. The test uses the provider and normal usage billing applies. **4. Check routing** The **Routing** card lists **Available models**. Your key is used for the models it covers; other models use Mobilerun's model service. ## Use it for tasks, the agent, and routines Choose a model as usual. Tasks use `llmModel` in the API/SDK or the model picker in Cloud; see [Model selection](/tasks#model-selection). The agent and routine task steps use their model pickers too. You do not pass the provider key in task prompts, routine inputs, or each API call. For a model covered by an active workspace key, Mobilerun routes the request through it automatically. You still use your [Mobilerun API key](/api-keys) to authenticate Cloud API requests; it serves a different purpose from your model-provider key. ## What you pay | Usage | How it is paid | | - | - | | Model requests routed through your key | Your provider bills the model usage directly; Mobilerun's BYOK platform fee uses AI credits. | | Models using Mobilerun's service | Normal model usage uses AI credits. | | Agent compute | Still uses AI credits, even with your own model key. | | Phone time, functions, proxy traffic, and storage | Keep their own units; BYOK does not replace those balances. | Check LLM keys for routing, provider spend, and the monthly LLM limit. This limit applies to requests through the workspace's own keys. See [Credits and units](/credits) for metering and [Pricing](https://mobilerun.ai/pricing/) for rates. If an authentication failure or certain connection failures cause a request to retry through Mobilerun's service, that retry uses normal AI-credit billing. Provider rate limits do not trigger this fallback. ## Keep your key safe Cloud stores keys encrypted and does not show the saved key again. Keep provider keys out of client-side code, prompts, screenshots, and logs. Use the key's action menu to manage it: * **Rotate key** replaces it with a new provider key. A rejected key may show **Replace key** instead. * **Pause key** temporarily routes matching requests through Mobilerun; **Resume key** uses your key again. * **Revoke key** stops routing through it and cannot be undone. To cancel the credential at its source, also revoke it in the provider's dashboard. ## Troubleshooting | Problem | What to check | | - | - | | Key rejected while saving | Choose the matching provider and paste the key without a `Bearer` prefix or extra spaces. | | Connection test rejects the key | Check that the provider key is valid and has access to the model. Use **Rotate key** or **Replace key**, then test again. | | Google key fails | Enable the Generative Language API and allow it in the key's API restrictions. If an `AQ.` key gets a 401, try an `AIza` key from Google Cloud Console. | | Provider rate limit | Wait and retry, or check your provider account's quota. A provider 429 does not switch the request to Mobilerun's key. | | Monthly LLM limit reached | Check and adjust the limit in **LLM keys**; it is separate from the other usage meters. | | No models after saving | Use **Retry provisioning** in the credential's action menu, then check **Routing**. | # Working with cloud devices Source: https://docs.mobilerun.ai/cloud-devices Explore the device grid, stream toolbar, and device settings in the Cloud dashboard. Open **Devices** in the Cloud dashboard; see [Manage devices](/devices) for states, API operations, and billing modes.## The device gridSearch, filter, and arrange your devices, or open a tile's controls to manage it. !\[Cloud dashboard device grid with search, filters, and device controls.]\(https\://mintcdn.com/mobilerun/5fhpAhiM6yJPIu5h/images/cloud-devices/grid-light.png?fit=max\&auto=format\&n=5fhpAhiM6yJPIu5h\&q=85\&s=2ed9e413b50188eb783b371c938136e6) !\[Cloud dashboard device grid with search, filters, and device controls.]\(/images/cloud-devices/grid-dark.png) \
\All points\ \
    \
## Working in the streamFocus a running device's screen to tap, drag, and type; the Manage device image below also shows its stream toolbar.### Paste from your computerFocus a device text field, keep the stream focused, and press **Cmd+V** on macOS or **Ctrl+V** on Windows or Linux, allowing clipboard access when asked. Copying text from the device to your computer is not supported yet.**Call media:** use **Webcam** on supported devices to send browser microphone and camera input; check `GET /devices/{deviceId}/capabilities` for `microphoneInjection`, `cameraInjection`, and `mediaInjectionTransport: "direct"`. A [stream token](/api-keys#stream-tokens) can also publish call media when enabled for your organization.## Manage deviceChoose **Manage device** from a device's controls or table-row menu to open its stream and settings.In **Overview**, use **Auto-stop** on eligible devices to choose how long they can go without activity before stopping. Choose **Off** to disable the timer, or **Default (N minutes)** when available to use the platform default. See [Idle timeout](/devices#idle-timeout) for activity rules and API settings. !\[Manage device dialog with settings sections and the stream toolbar.]\(https\://mintcdn.com/mobilerun/5fhpAhiM6yJPIu5h/images/cloud-devices/manage-light.png?fit=max\&auto=format\&n=5fhpAhiM6yJPIu5h\&q=85\&s=3d0f1a8f8b15f4e6f346751a708bbe09) !\[Manage device dialog with settings sections and the stream toolbar.]\(/images/cloud-devices/manage-dark.png) \
\All points\ \
    \
> [!NOTE] > > Sections depend on device capabilities and current state; check `GET /devices/{deviceId}/capabilities` > for fields such as `apps`, `files`, `geo`, `proxy`, `esim`, `recording`, and `stop`.## Stop, reset or delete| Action | What stays | Billing | When to use | | - | - | - | - | | [Stop](/devices#stop-and-resume-a-device) | Apps, accounts, files, and device identity | No phone credits while stopped | Pause an eligible minute-billed device and continue later | | [Reset](/devices#reset-a-device) | `full` clears apps, accounts, and storage and changes identity; `identity` keeps apps and data and changes the fingerprint | Reset does not cancel a subscription or end minute billing | Start clean, or request a new fingerprint using the supported reset mode | | [Delete](/devices#terminate-a-device) | Device data is erased | Ends that minute-billed device session; subscription slots are managed separately | Permanently remove a device you no longer need |### Stop and resumePark an eligible minute-billed device without losing its apps, accounts, files, or identity, then resume the same device later.```typescript TypeScript theme=\{null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); await device.stop(); // waits until stopped // Later, resume the same device await device.resume(); // waits until ready ``````python Python theme=\{null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") device.stop() # waits until stopped # Later, resume the same device device.resume() # waits until ready ``````bash cURL theme=\{null} curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/stop' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" # Later, resume the same device curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/resume' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" ```### ResetChoose what to erase with `mode`, and which API-managed configuration to restore with `preserve`.| Option | What it does | When to use | | - | - | - | | `mode: "full"` | Factory reset: erases apps, accounts, and storage, and gives the device a new identity | Start with a clean device | | `mode: "identity"` | Changes the device fingerprint; apps and data are kept | Request a new identity without wiping app state | | `preserve: ["proxy"]` | Restores the latest proxy configuration set through the API | Reuse the device's network configuration | | `preserve: ["location"]` | Restores the latest GPS location set through the API | Keep the configured location | | `preserve: ["locale"]` | Restores the latest locale (language and region) set through the API | Keep the configured locale | | `preserve: ["timezone"]` | Restores the latest timezone set through the API | Keep the configured timezone || Device type | `resetPreserve` support | | - | - | | Cloud Android | `proxy`, `location`, `locale`, `timezone` | | Cloud iOS | `[]`: omit `preserve` | | Personal Phone | Device-dependent subset of `proxy`, `location`, `timezone`; use its reported list. Without reset support, the list is `[]` |Combine preserve values in one array. Omitting `mode` selects `full`, or `identity` on devices whose capabilities report `factoryReset: false`. Omitting `preserve`, passing `null`, or passing an empty array preserves no configuration.> [!NOTE] > > Check `GET /v1/devices/{deviceId}/capabilities` before resetting: `reset` indicates reset support, `factoryReset` and `identityReset` indicate the supported modes, and `resetPreserve` is an array of supported preserve values. An unsupported mode or preserve value returns HTTP 400 `DEVICE_TOOL_UNSUPPORTED`. The device reports `resetting` until it becomes `ready` again.The examples below show two alternatives: an identity reset preserving proxy and location, or a full reset preserving no configuration.```typescript TypeScript theme=\{null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); await device.reset({ mode: 'identity', preserve: ['proxy', 'location'] }); // Factory reset, preserving no configuration await device.reset({ mode: 'full' }); ``````python Python theme=\{null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") device.reset(mode="identity", preserve=["proxy", "location"]) # Factory reset, preserving no configuration device.reset(mode="full") ``````bash cURL theme=\{null} curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/reset' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" \ --header 'Content-Type: application/json' \ --data '{"mode":"identity","preserve":["proxy","location"]}' # Factory reset, preserving no configuration curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/reset' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" \ --header 'Content-Type: application/json' \ --data '{"mode":"full"}' ```In the dashboard, **Reset & recreate** offers **Factory reset** and **New identity** where supported; the `preserve` options described above are currently available through the API and SDKs only.### DeleteDeleting erases the device and its data; the API can delete eligible minute-billed devices, while subscription devices must be released from the dashboard.```typescript TypeScript theme=\{null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); await device.terminate(); ``````python Python theme=\{null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") device.terminate() ``````bash cURL theme=\{null} curl --request DELETE 'https://api.mobilerun.ai/v1/devices/DEVICE_ID' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" ``` # Cloud Quickstart Source: https://docs.mobilerun.ai/cloud/quickstart Create a cloud device, run your first agent task, and read the result with TypeScript, Python or cURL. Create a hosted device, give the managed agent a goal, and read the answer. These examples use the Cloud API; for your own device and local agent, see the [Framework Quickstart](/framework/quickstart). [AI credits pay for the agent; phone credits pay while the device runs](/credits). **1. Get an API key** Create an API key Sign in or create an account, then create a cloud API key (`dr_sk_…`). You do not need your own model key, but you can [bring your own](/byok). Export it for the examples: ```bash theme={null} export MOBILERUN_API_KEY=dr_sk_your_key_here ``` **2. Install** ```bash TypeScript theme={null} npm install @mobilerun/sdk ``` ```bash Python theme={null} pip install mobilerun-sdk ``` Use SDK 6.2.0 or later. Both SDKs read `MOBILERUN_API_KEY` automatically. **3. Run your first task** Create a device, run the task, print the answer, then stop the device. ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; // Reads MOBILERUN_API_KEY from the environment const mobilerun = new MobilerunSDK(); // 1. Create a pay-as-you-go device. It uses phone credits only while it runs. // create() returns once the device is ready. const device = await mobilerun.devices.create({ deviceType: 'android_cloud_phone', billing: 'minute', }); // 2. Run an autonomous task on the device const task = await device.run({ task: 'Open Settings and tell me the Android version', llmModel: 'mobilerun/mobile-agent-fast', maxSteps: 50, }); // 3. Wait for the task to finish const status = await task.wait(); // 4. Read the result console.log('Result:', status.message); // 5. Stop the device so it no longer uses phone credits await device.stop(); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK # Reads MOBILERUN_API_KEY from the environment mobilerun = MobilerunSDK() # 1. Create a pay-as-you-go device. It uses phone credits only while it runs. # create() returns once the device is ready. device = mobilerun.devices.create(device_type="android_cloud_phone", billing="minute") # 2. Run an autonomous task on the device task = device.run( task="Open Settings and tell me the Android version", llm_model="mobilerun/mobile-agent-fast", max_steps=50, ) # 3. Wait for the task to finish status = task.wait() # 4. Read the result print("Result:", status.message) # 5. Stop the device so it no longer uses phone credits device.stop() ``` ```bash cURL theme={null} # 1. Create a pay-as-you-go device. It uses phone credits only while it runs. # Use the "id" in the response as . curl -s -X POST "https://api.mobilerun.ai/v1/devices?deviceType=android_cloud_phone&billing=minute" \ -H "Authorization: Bearer $MOBILERUN_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' # 2. Wait until the device is ready curl -s https://api.mobilerun.ai/v1/devices//wait \ -H "Authorization: Bearer $MOBILERUN_API_KEY" # 3. Run a task. Use the "id" in the response as . curl -s -X POST https://api.mobilerun.ai/v1/tasks \ -H "Authorization: Bearer $MOBILERUN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "deviceId": "", "task": "Open Settings and tell me the Android version", "llmModel": "mobilerun/mobile-agent-fast", "maxSteps": 50 }' # 4. Check the status until it is "completed". The answer is in "message". curl -s https://api.mobilerun.ai/v1/tasks//status \ -H "Authorization: Bearer $MOBILERUN_API_KEY" # 5. Stop the device so it no longer uses phone credits curl -s -X POST https://api.mobilerun.ai/v1/devices//stop \ -H "Authorization: Bearer $MOBILERUN_API_KEY" ``` **4. Read the result** `task.wait()` returns the same response as `GET /tasks/{id}/status`: ```json theme={null} { "status": "completed", "succeeded": true, "message": "The Android version on your device is 15.", "output": null, "steps": 5 } ``` The `message` field holds the agent's natural-language answer. The `output` field holds your structured data when you submitted an `outputSchema`, and it is `null` otherwise. See [Agent configuration](/tasks#structured-output) for more. See the [task trajectory](/tasks#task-details-and-recordings) for the full record of screenshots and actions (`GET /tasks/{id}/trajectory`). ## Details > [accordion] Run TypeScript as an ES module > > The TypeScript example uses top-level `await`, so run it as an ES module. Set `"type": "module"` in > your `package.json`, or save it as `quickstart.mts`, and run it with `npx tsx quickstart.ts` (or > `npx tsx quickstart.mts`). > [accordion] Stop or terminate a device > > This example uses **pay as you go** (`billing: 'minute'`). Step 5 stops the device: it keeps its apps and data and uses no phone credits until you resume it, but still occupies a device slot. Call `device.terminate()` when you no longer need it. See [Cloud Android](/device-types#cloud-android) to compare pay as you go with a monthly subscription. > > Cloud iOS devices cannot be stopped yet; call `device.terminate()` instead. > [accordion] Use an existing device > > Replace device creation with `await mobilerun.devices.get('DEVICE_ID')` in TypeScript or > `mobilerun.devices.get("DEVICE_ID")` in Python. Remove the stop call if it should keep running. > See [Mobilerun SDK](/guides/sdk-objects) for resuming devices and [SDK helpers](/sdk/helpers) for all helpers. > [accordion] Handle a failed task > > `task.wait()` returns the final status on completion. If the task fails or is cancelled, it throws > `WaitFailureError` in TypeScript or raises it in Python. > [accordion] Choose a model > > Pass `llmModel` to pick the model that drives the agent. Use one of the identifiers from the > [cloud model catalog](/tasks#model-selection). For example, `mobilerun/mobile-agent-fast` is tuned > for speed and cost, while `mobilerun/mobile-agent-thinking` gives stronger reasoning for complex > flows. Omit the field to use the default, `mobilerun/mobile-agent-fast`. ## SDK and API reference * [Mobilerun SDK](/guides/sdk-objects): devices, tasks, cleanup, and streaming. * [API reference](/api-reference/tasks/run-task): request and response schemas. * [Embed a device stream](/guides/embed-device-stream): add a live device to your app. ## Automate it > [card] [Working with tasks](/tasks) > > Configure the agent and read task results. > [card] [Routines](/routines) > > Turn repeatable work into routines. > [card] [Serverless Functions](/routines/functions) > > Run code without managing a server. > [card] [Sandboxes](/sandboxes) > > Run your automation in a sandbox. Examples: [TypeScript task runner](https://github.com/droidrun/mobilerun-examples/tree/main/examples/typescript/task-runner) · [Python signed webhook receiver](https://github.com/droidrun/mobilerun-examples/tree/main/examples/python/webhook-file-receiver). # Credentials Source: https://docs.mobilerun.ai/credentials Securely store and manage authentication credentials for automated app interactions. The Credentials tab allows you to create and manage secure credentials that your agent can use when automating apps. Store login information, API tokens, and other secrets without exposing them in your prompts. ## Overview The Credentials tab provides: * Secure storage for app credentials * Per-app credential organization * Encrypted secret management * Credential attachment for agent tasks ## Security Model > [!WARNING] > > Credentials are always encrypted at rest and in transit. The agent never has access to raw passwords or secrets. When the agent needs to authenticate: 1. The agent identifies a login field in the app 2. It requests the credential from the secure vault 3. The credential is injected directly into the field 4. The raw value is never exposed to the agent's context This architecture ensures your secrets remain protected even during automated interactions. ## Credential Structure Credentials are organized by app package name. Each credential can contain multiple fields: | Field Type | Description | | - | - | | **Username** | Account username or identifier | | **Email** | Email address for login | | **Password** | Account password (encrypted) | | **API Token** | API keys or access tokens | | **Phone Number** | Phone number for SMS verification | | **Two-Factor Secret** | TOTP setup key used to generate authenticator codes | | **Backup Codes** | Recovery codes for account access | ## Creating Credentials To add credentials for an app, open the credential dialog: Add a credential 1. Click **Add Credential** 2. Select the app package name from your [app library](/apps) 3. Enter a credential name: 3 to 50 lowercase letters, digits, `_`, or `-` (e.g., `prod_account`, `test-user`) 4. Add the required fields (username, password, etc.) 5. Save the credential > [!NOTE] > > You can create multiple credentials per app. This is useful for testing different account types or environments. ## Managing Credentials ### View Credentials Your credential list shows: * App package name * Credential name * Field types configured (without revealing values) ### Edit Credentials Update credential fields when passwords change or tokens expire. Click on any credential to modify its fields. ### Delete Credentials Remove credentials that are no longer needed. This action is permanent and cannot be undone. ## 1Password and payment cards If you use 1Password, connect it and grant its service account Read access to a vault to link logins and payment cards from there instead of saving a copy in Mobilerun. Linked credentials show as **Linked from 1Password** and stay managed in 1Password; each selected item is read from 1Password once when a task uses it. Payment cards can be linked from 1Password the same way, for use in tasks. ## Using Credentials in Tasks Attach credentials to your agent tasks to enable authenticated automation: ### In the Task runner Select the credentials to use in the credential picker before running your task. Mobilerun fills them in when the task reaches a login screen. ### Via API Specify credentials in your task configuration: ```json theme={null} { "task": "Log into the app and check notifications", "credentials": [ { "packageName": "com.example.app", "credentialNames": ["prod_account"] } ] } ``` ### Fields available to the agent During a task, the agent can enter only these field types: * **Username** * **Email** * **Password** * **Two-Factor Secret**, as the current 2FA code The agent can't enter **API Token**, **Phone Number**, or **Backup Codes** fields during a task. You can still store them in a credential. ### Two-factor codes If an app asks for a code from an authenticator app, the agent can enter it for you. Add a **Two-Factor Secret** field to the credential and attach the credential to your task. 1. In the app's 2FA settings, choose to set up an authenticator app. 2. Copy the setup key (the TOTP secret) that the app shows, instead of scanning the QR code. 3. Add the setup key as a **Two-Factor Secret** field on the app's credential. 4. Attach the credential to your task, as shown above. When the agent reaches the 2FA screen, Mobilerun generates the current code and types it into the field. The agent never sees the secret or the code. > [!NOTE] > > The agent can enter a two-factor code at most 3 times per task. If the code is rejected more often than that, the task can't complete 2FA. Check that the stored secret matches the app's current authenticator setup. ### Multiple Credentials You can attach credentials for multiple apps in a single task. The agent will use the appropriate credential based on which app it is interacting with. ### Validation errors Task creation validates attached credential references before the task runs. A credential missing from your account returns `422` with `Credential missing or changed; choose it again`; reselect it and retry. If the credentials service is unavailable, the request returns `503` with `Credentials could not be validated; retry the task`. No task is created with unresolved references. ## Best Practices | Practice | Description | | - | - | | **Use descriptive names** | Name credentials clearly (e.g., `qa_test_account`) | | **Separate environments** | Create distinct credentials for dev, staging, and production | | **Rotate regularly** | Update credentials when passwords change | | **Minimal access** | Only attach credentials the task actually needs | # Credits and units Source: https://docs.mobilerun.ai/credits How phone credits, AI credits, function minutes, proxy traffic and storage are metered on Mobilerun. Mobilerun meters phone time, AI usage, function execution, proxy traffic, and storage in separate units. Prices, plan allowances, and pack sizes are listed on the website; Cloud shows your account's balances and limits. > [card] [See pricing](https://mobilerun.ai/pricing/) > > Current prices, plan allowances, and top-up packs. View usage in Cloud | Meter | What it covers | Unit / rate | | - | - | - | | [Phone credits](#phone-credits) | Running time of pay-as-you-go cloud phones | Cloud Android: 1 per minute; Cloud iOS: 3 per minute | | [AI credits](#ai-credits) | Model usage and the agent's compute | AI credits | | [Function minutes](#function-minutes) | Function execution time in sandboxes | Minutes | | [Proxy traffic](#residential-traffic-proxy-traffic) | Data routed through Mobilerun residential IPs | GB | | [Storage](#storage) | Apps, files, recordings and screenshots | GB | Allowances depend on your plan. Plans shows the comparison; Usage shows the amounts available to your account. Function minutes and Storage appear when available for your account. See [Pricing](https://mobilerun.ai/pricing/) for current prices, allowances, and bundles. ## How paying works ### Pay as you go (PAYG) A pay-as-you-go phone uses phone credits for each running minute. In the API, select `billing: 'minute'` when creating it. A [monthly device subscription](/device-types#cloud-android) is a separate way to pay for a phone; it does not draw from the phone-credit balance. See [stop and resume](/devices#stop-and-resume-a-device) and [terminate](/devices#terminate-a-device) for what each action means for your data and billing. Your plan allowance covers usage first. Prepaid units cover further usage before any permitted PAYG overage. Overage means usage billed after those balances run out, up to your account's limit. Check Usage for the balance and status of each meter. ### Top up with prepaid packs Open Add-ons → Top up to buy **Phone credits**, **AI credits**, **Function minutes**, or **Proxy traffic**. Pick the pack for the unit you need; a phone-credit pack does not refill your AI-credit balance. Packs are drawn after the plan allowance. Choose a pack or **Or choose a custom amount**, then complete the purchase. Billing changes require permission to manage billing. See [Pricing](https://mobilerun.ai/pricing/) for pack sizes and prices. Open top-ups in Cloud ### Auto top-up Soon Auto top-up will buy more of a unit when its balance falls below the threshold you choose. ### Request a limit increase In Usage → Monthly overage limits, check the caps for **Cloud phone overage**, **Residential traffic overage**, and **AI credit overage**. These monthly caps limit extra usage beyond your included and prepaid balances, rather than limiting pack purchases. Paid plans can continue with PAYG up to their cap; Free plans do not have paid overage. When no balance or permitted overage remains, that usage stops. A pay-as-you-go Cloud Android phone is stopped and keeps its data. For an eligible paid account, choose **Request increase** to ask for a higher limit. Cloud confirms **Limit increase requested — we'll follow up**. This sends a request; it does not immediately change the cap. Near a PAYG cap, usage panels can also show **Raise PAYG limits**, which sends the same request. For rates and plan allowances, see [Pricing](https://mobilerun.ai/pricing/). ### Which balance is used first? | Order | What covers usage | | - | - | | 1. Included allowance | The units your plan provides. | | 2. Top-up balance | Prepaid units for that meter. | | 3. PAYG overage | Extra usage, only where your account permits it and up to the monthly cap. | | 4. Limit reached | Further usage stops until capacity is available again. | This is the order for meters with PAYG overage. Function minutes can instead show **Covered by AI credits** after their own balance runs out; see [Function minutes](#function-minutes). Storage has no top-up pack; see [Storage](#storage). ## Phone credits Phone credits cover the time your pay-as-you-go cloud phones are powered on. They share a balance across your phones, with a monthly allowance from your plan. | Cloud phone | Phone credits per running minute | | - | - | | Cloud Android | 1 | | Cloud iOS | 3 | Stopped Cloud Android phones keep their apps and data and use no phone credits. When the available phone balance and permitted overage are exhausted, the phone is stopped and keeps its data. Stopping and resuming a Cloud iOS phone is not available yet. The [idle timeout](/devices#idle-timeout) automatically stops idle pay-as-you-go phones that support stopping so they stop using phone credits. * **Included:** check **Plans** for your monthly phone credit allowance and **Usage** for the remaining balance. * **Overage:** paid plans can continue up to their monthly overage limit; Free plans stop at the limit. See [Pricing](https://mobilerun.ai/pricing/) for rates. * **Prepaid packs:** available under Add-ons → Top up → Phone credits. Prepaid phone credits are drawn after the plan allowance. See [Pricing](https://mobilerun.ai/pricing/) for pack sizes and prices. > [!NOTE] > > Subscription phones (Cloud Android, dedicated Cloud iOS and Connect your phone) are billed by their subscription rather than by phone credits. Their AI usage is separate. See [Device Types](/device-types). ## AI credits AI credits cover the model usage behind agent tasks and chat, plus the agent's compute. Non-LLM API calls do not consume AI credits; running a pay-as-you-go phone still uses phone credits. Model usage is deducted in real time based on the token cost of each request. The model, context size, vision, reasoning and number of steps affect the cost. * **Included:** your plan and eligible phone bundles provide monthly AI credits. See **Plans** and **Usage** for your allowance and balance. * **Overage:** paid plans can use extra AI credits up to their monthly overage limit; Free plans stop at the limit. See [Pricing](https://mobilerun.ai/pricing/) for rates. * **Top-up:** buy prepaid AI credits under Add-ons → Top up → AI credits. See [Pricing](https://mobilerun.ai/pricing/) for pack sizes and prices. See [Pricing](https://mobilerun.ai/pricing/) for the AI credits included with each phone bundle. ### Your own model keys (BYOK) You can [bring your own model key](/byok) on any plan. Your provider bills model usage directly; Mobilerun's platform fee and agent compute still use AI credits. ## Function minutes Function minutes cover execution time in sandboxes, separately from phone time and model usage. Your monthly allowance and remaining balance appear in **Usage** when available. Buy extra function minutes under Add-ons → Top up → Function minutes; see [Pricing](https://mobilerun.ai/pricing/) for packs and rates. These are drawn after the plan allowance. Check the meter's status when the allowance is exhausted: **Using top-up**, **Covered by AI credits** or **Limit reached** shows how your account handles further usage. ## Residential traffic (proxy traffic) The **Proxy traffic** meter tracks data routed through Mobilerun residential IPs, pooled across your phones in GB. Check **Plans** for the monthly allowance and **Usage** for consumption and limits. Paid plans can use extra traffic up to their monthly overage limit; Free plans stop at the limit. Prepaid traffic packs are available under Add-ons → Top up → Proxy traffic. See [Pricing](https://mobilerun.ai/pricing/) for rates and pack sizes. A dedicated residential proxy is a separate subscription with unlimited bandwidth; it is not a prepaid traffic pack. ## Storage The **Storage** meter covers apps, files, recordings and screenshots. When available, **Usage** shows your included capacity, consumption and any permitted overage. Paid plans can have storage overage up to their plan's cap; accounts without overage stop at their storage limit. Storage has no prepaid top-up pack in Add-ons. Check Cloud for your account's allowance and [Pricing](https://mobilerun.ai/pricing/) for rates. ## Monitoring usage In Billing & plans: * **Plans** compares monthly allowances and phone credit rates. * **Add-ons** contains phone bundles, subscriptions and **Top up** prepaid packs. * **Usage** shows meter balances, included and prepaid usage, and the **AI credits breakdown**. **Monthly overage limits** shows the caps for cloud phones, residential traffic and AI usage. Use **Request increase** to ask for a higher limit. * **LLM keys**, when available, manages your provider credentials and shows routing, spend and the monthly LLM limit. ## Cost optimization | Strategy | Description | | - | - | | **Stop phones you don't use** | Stopped Cloud Android phones keep their apps and data and use no phone credits | | **Pick a cheaper model** | Use faster, cheaper models for simple tasks | | **Describe tasks tightly** | Well-written prompts reduce the number of agent steps needed | | **Watch each meter** | Phone credits, AI credits, function minutes and traffic packs cover different usage; top up the meter you need | # Device Types Source: https://docs.mobilerun.ai/device-types Learn about the different device types available on Mobilerun and choose the one that best fits your automation needs. Mobilerun offers three device types, each designed for different use cases and requirements. Understanding these options will help you select the right infrastructure for your mobile automation workflows. ## Personal Phone Connect your own physical smartphone to the cloud. Follow the [Connect an iPhone](/guides/connect-iphone) or [Connect an Android](/guides/connect-android) guide depending on your device. Connect your phone | Feature | Description | | - | - | | **Provisioning** | BYO — bring your own device | | **Persistence** | Persistent — your device keeps its state | | **Cost** | Monthly subscription, see [Pricing](https://mobilerun.ai/pricing/) | | **Hardware** | Remote physical (your own device) | | **Best For** | Quick testing on your own hardware | Eligible accounts can claim one free Personal Phone slot, free for life, with no credit card required. Look for **Claim free slot** in the dashboard. Personal phones are ideal when you want to: * Use your existing hardware for automation * Maintain persistent device state across sessions * Test on specific device models you own *** ## Cloud Android A high-performance virtual Android device with dedicated resources and advanced automation capabilities. It comes in two forms: a monthly **subscription** (dedicated, always on) and **pay as you go** (billed per minute, with stop and resume). Create a Cloud Android | Feature | Subscription | Pay as you go | | - | - | - | | **Provisioning** | Dedicated — always-on, reserved for your account | Created on request, with a name and a country | | **Persistence** | Persistent — full state persistence across sessions | Stopped phones keep apps, logins, files, and identity; deleting erases them | | **Cost** | Monthly subscription, see [Pricing](https://mobilerun.ai/pricing/) | Phone credits while running (1 minute = 1 phone credit), see [Credits and units](/credits). A stopped phone uses no phone credits | | **Hardware** | Virtual device | Virtual device | | **Location** | EU | EU | | **Best For** | Mobile RPA and scalable automation | Short tasks, or work you want to pause and resume | Cloud Android subscription phones are ideal when you need: * Persistent app installations and configurations * Scalable automation with multiple devices * Profile support for running separate profiles * Predictable performance without cold-start delays (subscription phones are always on) > [!NOTE] > > Cloud Android phones support **profiles**, allowing you to run separate profiles from a single subscription. > [!NOTE] > > See the [Cloud Android Setup](/guides/cloud-device-setup) guide for setup best practices, including proxy and Google account configuration. *** ## Cloud iOS A hosted iOS phone in the Mobilerun cloud, created from the dashboard or the API. You automate iOS apps without owning any hardware. Create a Cloud iOS It comes in two forms: | Feature | Dedicated | On demand (per minute) | | - | - | - | | **Hardware** | A real, physical iPhone in a Mobilerun data center | A virtual iOS device | | **Provisioning** | Monthly subscription, with its own residential IP | Created from the dashboard or the API | | **Persistence** | Persistent and always on | Created when needed | | **Location** | EU or US | — | | **eSIM** | Support available | No | | **Cost** | Monthly subscription, see [Pricing](https://mobilerun.ai/pricing/) | Phone credits while running (1 minute = 3 phone credits), see [Credits and units](/credits) | | **Best For** | Long-lived iOS accounts and apps | Automating iOS apps without your own hardware | Stopping and resuming a Cloud iOS phone is not available yet. *** ## Comparison | Aspect | Personal Phone | Cloud Android | Cloud iOS | | - | - | - | - | | **Hardware** | Your own device | Virtual | Dedicated: real iPhone. On demand: virtual | | **State** | Persistent | Subscription: persistent. Pay as you go: stopped phones keep apps and data | Dedicated: persistent, always on | | **Deployment** | BYO | Subscription: dedicated, always on. Pay as you go: on request | Hosted in the Mobilerun cloud | | **Location** | Yours | EU | Dedicated: EU or US | | **Scalable** | No | Yes | Not auto-scalable | | **eSIM** | No | No | Dedicated: support available | | **Profiles** | No | Yes | No | | **App Support** | Yes | Yes | Yes | | **Cost** | Subscription | Subscription or phone credits (1 per minute) | Subscription or phone credits (3 per minute) | See [Pricing](https://mobilerun.ai/pricing/) for plan prices and [Credits and units](/credits) for how phone credits are metered. ## Choosing the Right Device Type > [card] Personal Phone > > Choose this to connect your own physical smartphone for testing on your own hardware. > [card] Cloud Android > > Choose this for scalable, persistent virtual devices with profile support and dedicated resources. > [card] Cloud iOS > > Choose this to automate iOS apps on a hosted iPhone without your own hardware. # Devices Source: https://docs.mobilerun.ai/devices View and manage all your devices and monitor active device streams. The Devices tab provides a centralized overview of all devices associated with your account. Use it to monitor device status, manage your device inventory, and access active streams. > [!TIP] > > To use devices in the dashboard (grid, stream, device settings), see [Working with cloud devices](/cloud-devices). ## Overview The Devices tab displays: * All devices allocated to your account * Currently running devices and their streams * Device status and availability ## Device Inventory Your device inventory shows every device you have access to, organized by type: | Device Type | Description | | - | - | | **Personal Phone** | Your own physical smartphone. Android connects through the [Mobilerun Portal App](/guides/connect-android); iPhone connects over USB in the browser or with the [`mobilerun-ios` CLI](/guides/connect-iphone) | | **Cloud Android** | Dedicated, persistent virtual devices with profile support | | **Cloud iOS** | Hosted iOS devices in the Mobilerun cloud, billed in phone credits (3 per minute) or as a dedicated monthly subscription | > [!TIP] > > For detailed information about each device type, including pricing and capabilities, see the [Device Types](/device-types) documentation. ## Device Status Each device in your inventory displays its current status: | Status | Description | | - | - | | **Ready** | Device is ready to accept new tasks | | **Assigned** | Device is reserved for you and still being set up | | **Creating** | Device is being created | | **Maintenance** | Device is on hold for a person to look at it | | **Rebooting** | Device is restarting | | **Migrating** | Device is moving to another host | | **Resetting** | Device is being wiped and set up again | | **Stopped** | Device is paused: apps, data, and identity are kept and no minutes are billed | | **Terminated** | Device has been removed | | **Disconnected** | Device is not currently connected (physical devices only) | | **Unknown** | Mobilerun cannot determine the device's state | > [!NOTE] > > These are the human readable labels shown in the dashboard. The API and SDK use lowercase state > values instead. The most important one is **`ready`**, which you filter for with `?state=ready` in > REST or with `mobilerun.devices.list({ state: ['ready'] })` in the SDK. Other API states include > `creating`, `assigned`, `rebooting`, `resetting`, `stopped`, `terminated`, and `maintenance`. > A `stopped` device is parked between sessions: it is switched off and not billed, but its data, installed apps, and identity are preserved so the next session resumes on the same device. ### Listing devices Without a `state` filter, `GET /v1/devices` returns all devices except `terminated` and `unknown`. Use `state=ready` for devices ready to run tasks, or request `state=terminated` explicitly. Multiple states can be comma-separated or repeated, such as `state=stopped,maintenance` or `state=stopped&state=maintenance`; unknown values return `422`. The `platform` filter accepts `android` or `ios` and combines with the other filters, such as `state`. To filter by device type instead, see [Billing modes](#billing-modes). ### Device details `GET /v1/devices/{deviceId}` can return the device successfully without `streamToken` when reading that token remains unavailable after retries. Treat the field as optional; retry the read before opening a stream if no token was returned. ## Managing Devices From the Devices tab, you can: ### Connect Your Own Device With a Personal Phone subscription, connect your own physical phone. Android uses the [Mobilerun Portal App](/guides/connect-android) (the Portal app is Android only); an iPhone connects over USB in the browser or with the `mobilerun-ios` CLI, see [Connect an iPhone](/guides/connect-iphone). Connected devices appear in your inventory alongside cloud-hosted devices. When a Personal Phone disconnects cleanly, Mobilerun stops its session and frees its device slot while keeping its ID, owner, and history. If the connection drops unexpectedly, it allows about 30 seconds for a reconnect before stopping the session. Reconnect the phone to resume it; normal device-slot checks apply. Personal Phones use their connection to control their state, rather than the stop and resume API calls. ### Reset a Device Reset with `mode: "full"` to erase apps, accounts, and storage and obtain a new identity, or `mode: "identity"` to change the fingerprint while keeping apps and data. Use `preserve` to restore selected configuration last set through the API. Cloud Android supports all four preserve values; Cloud iOS reports `resetPreserve: []` (omit `preserve`), while Personal Phone support follows the handset's reported list; see [preserve support by device type](/cloud-devices#reset). The examples show an identity reset preserving proxy and location, or a full reset preserving no configuration: ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); await device.reset({ mode: 'identity', preserve: ['proxy', 'location'] }); // Factory reset, preserving no configuration await device.reset({ mode: 'full' }); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") device.reset(mode="identity", preserve=["proxy", "location"]) # Factory reset, preserving no configuration device.reset(mode="full") ``` ```bash cURL theme={null} curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/reset' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" \ --header 'Content-Type: application/json' \ --data '{"mode":"identity","preserve":["proxy","location"]}' # Factory reset, preserving no configuration curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/reset' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" \ --header 'Content-Type: application/json' \ --data '{"mode":"full"}' ``` The device reports the `resetting` state for the entire reset, including the reconnection and setup steps that follow the wipe. It returns to `ready` once the reset completes. Resetting a Personal Phone factory-resets the handset. The phone goes offline for several minutes while it wipes and reboots. Mobilerun keeps the device in `resetting` for up to 5 minutes while it waits for the phone to reconnect. When the phone comes back online, the device returns to `ready` within seconds. If the phone does not reconnect within that window, Mobilerun terminates the device. ### Stop and Resume a Device Stopping parks a device instead of terminating it. A stopped device keeps its apps, data, and identity, but nothing runs and usage is not billed until you resume it. Use this to pause a device you are not actively using without losing its state. Stopping a device does not cancel a recurring subscription; manage that separately in Billing. ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); await device.stop(); // returns once the device is stopped // Later, wake the same device back up await device.resume(); // returns once the device is ready ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") device.stop() # returns once the device is stopped # Later, wake the same device back up device.resume() # returns once the device is ready ``` ```bash cURL theme={null} curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/stop' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" # Later, resume the same device curl --request POST 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/resume' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" ``` Both calls wait for the new state. Options and errors are on the [SDK helpers](/sdk/helpers#stop-and-resume) page. A stopped device reports the `stopped` state. Filter for parked devices with `?state=stopped` in REST or `mobilerun.devices.list({ state: ['stopped'] })` in the SDK. Resuming wakes the same device: Mobilerun checks that capacity is available, starts the device again, and returns it to `ready`. Resuming a device that is not stopped is a no-op. While it wakes, the device reports `assigned` with a progress message. Repeating resume reuses the same in-flight request. If no capacity is available before resume starts, the API returns `409 DEVICE_CAPACITY_UNAVAILABLE` and leaves the device `stopped`. Retry shortly. If capacity disappears after acceptance, the device waits without using phone credits. You can stop a device that is still waking to cancel its pending resume. A failed start parks it again with a retry message, preserving its identity and data. If billing denies resume, the device stays `stopped` and its `stateMessage` explains the problem. Resolve the phone credit balance, allowance, or concurrency limit and resume again. Minute-billed devices that run out of phone credits are parked automatically and keep their data. Their `stateMessage` explains that the phone credit balance is exhausted. Resume them after adding phone credits. Stop and resume are available for pay-as-you-go Cloud Android devices; Cloud iOS stop and resume is not available yet. Free-plan accounts may have exhausted Cloud Android devices terminated instead of parked. Upgrade before exhausting your phone credits if you need to keep the device across sessions. > [!NOTE] > > Not every device supports stopping. Check the device's capabilities with `device.retrieveCapabilities()`: stopping is available when the response reports `stop: true`. Unsupported stop or resume requests return HTTP `400` with code `DEVICE_TOOL_UNSUPPORTED`. ### Idle timeout The idle timeout automatically stops a pay-as-you-go device that supports stopping after the configured number of minutes without client activity. The device reports `state: 'stopped'` and `stopReason: 'IDLE_TIMEOUT'`, keeps its apps, data, and identity, and stops using phone credits. [Resume it](#stop-and-resume-a-device) when needed; the timer stays enabled and starts afresh. API tool calls, open stream, ADB, browser, Frida, or port connections, and a held device lease count as activity. Reading device state does **not** reset the timer, so polling a device does not keep it running. Automatic stopping is not exact to the second. A routine run holds a device lease, which counts as activity and updates `lastActivityAt` while the timer is on, so a phone left running starts a fresh idle countdown after the run. Without its own setting, an eligible pay-as-you-go device uses the platform default, if one applies. Read the device's reported default rather than assuming a fixed duration. A device's own setting overrides the default, including explicitly turning the timer off. #### Change the timeout Send `PUT /v1/devices/{deviceId}/idle-timeout` with one of these values: | `minutes` | Effect | | - | - | | Integer from `5` to `240` | Set this device's own timeout in minutes; requires capabilities `stop: true` | | `0` | Turn off the idle timer for this device | | `null` | Clear this device's own setting and use the platform default again, if one applies | The SDK examples require SDK 6.3.2 or later and set a 30-minute timeout. The helper returns a new `Device` with fresh `info`. To update the original handle's snapshot after the call, call `refresh()` on it. ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); const updatedDevice = await device.setIdleTimeout(30); // 0 for off; null for the default console.log(updatedDevice.info?.idleTimeoutMinutes); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") updated_device = device.set_idle_timeout(30) # 0 for off; None for the default if updated_device.info is not None: print(updated_device.info.idle_timeout_minutes) ``` ```bash cURL theme={null} curl --fail-with-body --request PUT 'https://api.mobilerun.ai/v1/devices/DEVICE_ID/idle-timeout' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" \ --header 'Content-Type: application/json' \ --data '{"minutes":30}' ``` With the raw client, use `client.devices.updateIdleTimeout('DEVICE_ID', { minutes: 30 })` (Python `client.devices.update_idle_timeout("DEVICE_ID", minutes=30)`). The same Python methods are available with `await` on the async client and `AsyncMobilerunSDK` device objects. | Status | Meaning | | - | - | | `200` | Setting saved; the response is the updated device with its effective timeout | | `409` | A custom timeout was requested for a device that cannot be stopped; `0` and `null` do not require stop support | | `422` | Invalid `minutes`: use an integer from 5–240, `0`, or `null`; values 1–4, negative values, and values above 240 are rejected | In Cloud, open **Manage device → Overview → Auto-stop** to choose a timeout, **Off**, or **Default (N minutes)** when a default is available. See [Working with cloud devices](/cloud-devices#manage-device). #### Read the effective timeout Device details and list results expose the following fields. SDK 6.3.1 includes these fields on `device.info` after `devices.get`: | API / TypeScript field | Python field | Meaning | | - | - | - | | `idleTimeoutMinutes` | `idle_timeout_minutes` | Effective timeout in minutes; omitted when the timer is off or no timer applies | | `idleTimeoutSource` | `idle_timeout_source` | `device` for the device's own setting, including explicit off; `default` for the platform default; omitted when no timer can apply | | `idleTimeoutDefaultMinutes` | `idle_timeout_default_minutes` | Default this device would use after `minutes: null`; omitted when no default applies | | `lastActivityAt` | `last_activity_at` | Last client activity in RFC 3339 format, tracked only while the timer is on, to about one minute of precision; omitted otherwise | ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = await mobilerun.devices.get('DEVICE_ID'); console.log(device.info?.idleTimeoutMinutes); console.log(device.info?.idleTimeoutSource); console.log(device.info?.idleTimeoutDefaultMinutes); console.log(device.info?.lastActivityAt); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.get("DEVICE_ID") if device.info is not None: print(device.info.idle_timeout_minutes) print(device.info.idle_timeout_source) print(device.info.idle_timeout_default_minutes) print(device.info.last_activity_at) ``` ```bash cURL theme={null} curl --fail-with-body 'https://api.mobilerun.ai/v1/devices/DEVICE_ID' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" ``` ### Terminate a Device `DELETE /v1/devices/{deviceId}` removes a device and erases everything on it. Through the API you can terminate minute-billed devices that are `ready` or `stopped`. Subscription devices cannot be terminated with this request; release them from the dashboard. A Personal Phone can be removed from your account once it is disconnected. This releases ownership so anyone can pair it again. If it is still connected, the API returns `409 BYOD_DEVICE_CONNECTED`; disconnect and wait until it is offline before retrying. Sign out on the phone before handing it to someone else, or its next connection can pair it to your account again. ```typescript TypeScript theme={null} import { MobilerunSDK } from '@mobilerun/sdk'; const mobilerun = new MobilerunSDK(); const device = mobilerun.devices.fromId('DEVICE_ID'); await device.terminate(); ``` ```python Python theme={null} from mobilerun_sdk import MobilerunSDK mobilerun = MobilerunSDK() device = mobilerun.devices.from_id("DEVICE_ID") device.terminate() ``` ```bash cURL theme={null} curl --request DELETE 'https://api.mobilerun.ai/v1/devices/DEVICE_ID' \ --header "Authorization: Bearer $MOBILERUN_API_KEY" ``` ## Billing modes When you create a device, the `billing` query parameter on `POST /v1/devices` selects how the session is admitted and paid for. Availability of each mode depends on the device type's billing configuration. | Mode | Behavior | | - | - | | `auto` (default) | Tries subscription billing first. If your account has no subscription entitlement for the type, or every subscription slot is in use, falls back to minute billing when it is enabled for the type. When subscription billing is disabled, uses minute billing directly. | | `subscription` | Requires an active subscription entitlement and a free subscription slot. Never falls back to minutes. | | `minute` | Uses minute billing only. Requires a sufficient phone credit balance and an available minute concurrency allowance. When the balance is spent, creation fails with `MINUTE_BALANCE_EXHAUSTED`. | Minute billing is metered only while the device is ready. Setup, reboot, reset, maintenance, and resume do not use phone credits. Metering has whole-minute granularity, so the minute in which the device becomes ready may be charged in full. Billing-service errors and indeterminate responses never trigger fallback: the request fails closed so a paid session is never opened on an unverified entitlement. Request minute billing explicitly by appending the query parameter: ```http theme={null} POST /v1/devices?deviceType=android_cloud_phone&billing=minute Content-Type: application/json {} ``` > [!NOTE] > > The `deviceType` parameter accepts `android_cloud_phone`, `ios_phone`, or `device_slot`. Any other value, including the retired `dedicated_*` aliases, is rejected with HTTP 422. The same values apply to the `type` filter on `GET /v1/devices`. Older iOS devices are reported as `ios_phone`. ## Device operation errors | Status | Code | Meaning | What to do | | - | - | - | - | | `503` | `DEVICE_SERVING_UNAVAILABLE` | The Cloud Android device exists, but its connection is temporarily unavailable. | Respect `Retry-After: 1` and retry. Do not create a replacement device for this error. | ## Device creation errors When you create a device or connect your own phone, Mobilerun checks type availability and the entitlement, phone credits, or capacity required by the selected billing mode. If a check fails, the API returns one of these errors: | Status | Code | Meaning | What to do | | - | - | - | - | | `422` | `DEVICE_TYPE_UNAVAILABLE` | The device type is recognized but not available for creation in this deployment. | Use a different device type. This is not fleet exhaustion, so retrying will not help. | | `402` | `SUBSCRIPTION_REQUIRED` | Your account has no active subscription for this device type. | Subscribe or upgrade your plan, then try again. If minute billing is enabled for the type, retry with `billing=minute`. | | `402` | `MINUTE_BALANCE_EXHAUSTED` | Minute billing: your plan's phone credit balance is spent. | Upgrade your plan, top up phone credits, or wait for the next period. An AI credits top-up does not help. | | `429` | `RESOURCE_EXHAUSTED` | All device slots in your plan are in use, or the platform has no free capacity right now (`details.reason` is `capacity_unavailable`). | For slots: terminate a minute-billed device or upgrade your plan. For capacity: try again shortly. | | `402` | `PAYMENT_REQUIRED` | The billing check could not be completed and access was denied, including when your minute concurrency allowance is used up. | Try again shortly, or contact support if the error persists. | Example error body from a device creation request: ```json theme={null} { "code": "SUBSCRIPTION_REQUIRED", "message": "You need an active subscription to create this device. Subscribe or upgrade your plan, then try again." } ``` > [!NOTE] > > `SUBSCRIPTION_REQUIRED`, `MINUTE_BALANCE_EXHAUSTED`, and `PAYMENT_REQUIRED` all return HTTP 402. Match on the `code` field to tell them apart. If your own phone cannot connect through the Portal app, verify that your [Personal Phone](/device-types#personal-phone) subscription is active. `SUBSCRIPTION_REQUIRED` and `RESOURCE_EXHAUSTED` with `details.reason: "plan_device_slots_exhausted"` only surface for explicit `billing=subscription` requests, or for `auto` requests when minute billing is not enabled for the device type. With `auto`, either denial silently falls back to minute billing when it is enabled. For `429 RESOURCE_EXHAUSTED`, read `details.reason` instead of matching message text: `plan_device_slots_exhausted` means your plan has no free slot; `capacity_unavailable` means the platform has no capacity for the device type. Retry later for platform capacity; upgrading does not help. Handle missing or unrecognized reasons without assuming either cause. ### Retry device creation safely Send an `Idempotency-Key` header on `POST /v1/devices` and reuse it with the same request after a timeout or connection error. Mobilerun returns the original device with its current state and `Idempotent-Replayed: true`, rather than creating and billing another device. Keys are scoped to your account, retained for at least 24 hours, and must contain 1–255 printable ASCII characters without spaces. | Status | Code | What to do | | - | - | - | | `400` | `invalid_idempotency_key` | Fix the key format. | | `409` | `idempotency_request_in_progress` | Wait for `Retry-After: 1`, then retry the same request. | | `422` | `idempotency_key_reused` | Use a new key for a different device type, country, billing mode, profile, or spec. | | `404` | — | The original device was terminated, deleted, or transferred; use a new key to create another. | A denial before a device exists frees the key, so a retry checks billing and capacity again. If creation fails after a device exists, the key stays bound to it; use a fresh key to start over. # Drive the device step by step Source: https://docs.mobilerun.ai/examples/drive-the-phone Inspect the screen and choose each device action in your own code. Read the screen and control a device from your own code. The screen needs a moment after opening an app or tapping; these examples retry UI reads because the SDK has no element-wait helper yet. > [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 > ``` ## Read the screen Read the filtered UI tree and capture a screenshot. **Needs:** Cloud Android · API key and `DEVICE_ID` · no app or device account · device minutes, no task credits or add-ons · one-shot, under 1 min. > Use `get_device_ui_state` to read the filtered UI state and `get_device_screenshot` to capture the screen. List the foreground app and each clickable element with its text and bounds. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > from mobilerun_sdk import MobilerunSDK > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > state = device.ui(filter=True) > print("Foreground:", state.phone_state.current_app or state.phone_state.package_name) > > > def show(node): > if node.is_clickable: > print(node.text or node.content_description, node.bounds_in_screen) > for child in node.children or []: > show(child) > > > show(state.a11y_tree) > device.screenshot().save("screen.png") > print("Screenshot: screen.png") > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > import type { A11YNode } from '@mobilerun/sdk/resources/devices/state'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > const state = await device.ui({ filter: true }); > console.log('Foreground:', state.phone_state.currentApp || state.phone_state.packageName); > > function show(node: A11YNode): void { > if (node.isClickable) console.log(node.text || node.contentDescription, node.boundsInScreen); > for (const child of node.children || []) show(child); > } > show(state.a11y_tree); > await (await device.screenshot()).save('screen.png'); > console.log('Screenshot: screen.png'); > ``` ![Android launcher](/images/examples/drive-the-phone/launcher.png) Result ```text theme={null} Foreground: com.android.mxLauncher3 Settings { left: 36, top: 2076, right: 288, bottom: 2312 } Screenshot: screen.png ``` ## Tap and type an alarm Start Clock, create and verify a 07:00 alarm, then delete it. **Needs:** Cloud Android · standard Clock app · no device account · API key and `DEVICE_ID` · device minutes, no task credits or add-ons · one-shot, \~1 min · dedicated test device without 07:00 or earlier alarms; remove the test alarm if interrupted. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > import time > from mobilerun_sdk import MobilerunSDK > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > > > def nodes(node): > yield node > for child in node.children or []: > yield from nodes(child) > > > def state(): > return device.ui(filter=True).a11y_tree > > > def find(needle): > deadline = time.monotonic() + 10 > while True: > for node in nodes(state()): > b = node.bounds_in_screen > if needle in (node.text, node.content_description, node.resource_id) and b.right > b.left and b.bottom > b.top: > return node > if time.monotonic() >= deadline: > raise RuntimeError(f"Not found: {needle}") > time.sleep(0.5) > > > def tap(needle): > b = find(needle).bounds_in_screen > device.tap((b.left + b.right) // 2, (b.top + b.bottom) // 2) > > > device.open_app("com.android.deskclock") > tap("Alarm") > b = state().bounds_in_screen > device.swipe((b.left + b.right) // 2, b.top + (b.bottom - b.top) // 2, (b.left + b.right) // 2, b.top + (b.bottom - b.top) * 3 // 4, 400) > if any(n.content_description in ("07:00 Alarm", "7:00 Alarm") for n in nodes(state())): > raise RuntimeError("Remove the existing 07:00 alarm before running") > tap("Add alarm") > tap("android:id/toggle_mode") > tap("android:id/input_hour") > device.type("07", clear=True, completion_mode="committed") > tap("android:id/input_minute") > device.type("00", clear=True, completion_mode="committed") > tap("OK") > # A fresh phone asks for notification permission shortly after the alarm is saved. > deadline = time.monotonic() + 10 > while time.monotonic() < deadline: > if any(n.resource_id.endswith(":id/permission_allow_button") for n in nodes(state())): > tap("com.android.permissioncontroller:id/permission_allow_button") > break > time.sleep(0.5) > root = state() > alarm = next((n for n in nodes(root) if n.content_description in ("07:00 Alarm", "7:00 Alarm")), None) > if not alarm or not any(n.resource_id.endswith(":id/onoff") and n.is_checked for n in nodes(alarm)): > raise RuntimeError("07:00 alarm is missing or off") > print("07:00 alarm is on") > device.screenshot().save("alarm.png") > tap("Expand alarm") > tap("Delete") > print("Alarm deleted") > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > import type { A11YNode } from '@mobilerun/sdk/resources/devices/state'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > > function* nodes(node: A11YNode): Generator { > yield node; > for (const child of node.children || []) yield* nodes(child); > } > async function state() { return (await device.ui({ filter: true })).a11y_tree; } > async function find(needle: string) { > const deadline = performance.now() + 10_000; > while (true) { > for (const node of nodes(await state())) { > const b = node.boundsInScreen; > if ([node.text, node.contentDescription, node.resourceId].includes(needle) && b.right > b.left && b.bottom > b.top) return node; > } > if (performance.now() >= deadline) throw new Error(`Not found: ${needle}`); > await new Promise(resolve => setTimeout(resolve, 500)); > } > } > async function tap(needle: string) { > const b = (await find(needle)).boundsInScreen; > await device.tap(Math.floor((b.left + b.right) / 2), Math.floor((b.top + b.bottom) / 2)); > } > > await device.openApp('com.android.deskclock'); > await tap('Alarm'); > const b = (await state()).boundsInScreen; > await device.swipe(Math.floor((b.left + b.right) / 2), b.top + Math.floor((b.bottom - b.top) / 2), Math.floor((b.left + b.right) / 2), b.top + Math.floor((b.bottom - b.top) * 3 / 4), 400); > if ([...nodes(await state())].some(n => ['07:00 Alarm', '7:00 Alarm'].includes(n.contentDescription))) throw new Error('Remove the existing 07:00 alarm before running'); > await tap('Add alarm'); > await tap('android:id/toggle_mode'); > await tap('android:id/input_hour'); > await device.type('07', { clear: true, completionMode: 'committed' }); > await tap('android:id/input_minute'); > await device.type('00', { clear: true, completionMode: 'committed' }); > await tap('OK'); > // A fresh phone asks for notification permission shortly after the alarm is saved. > const deadline = performance.now() + 10_000; > while (performance.now() < deadline) { > if ([...nodes(await state())].some(n => n.resourceId.endsWith(':id/permission_allow_button'))) { > await tap('com.android.permissioncontroller:id/permission_allow_button'); > break; > } > await new Promise(resolve => setTimeout(resolve, 500)); > } > const root = await state(); > const alarm = [...nodes(root)].find(n => ['07:00 Alarm', '7:00 Alarm'].includes(n.contentDescription)); > if (!alarm || ![...nodes(alarm)].some(n => n.resourceId.endsWith(':id/onoff') && n.isChecked)) throw new Error('07:00 alarm is missing or off'); > console.log('07:00 alarm is on'); > await (await device.screenshot()).save('alarm.png'); > await tap('Expand alarm'); > await tap('Delete'); > console.log('Alarm deleted'); > ``` ![Clock with the 07:00 alarm switched on](/images/examples/drive-the-phone/alarm.png) Result ```text theme={null} 07:00 alarm is on Alarm deleted ``` ## Run your own loop Run an observe–decide–act loop to enable Dark theme, verify it survives [stop and resume](/sdk/helpers#stop-and-resume), and turn it off. **Needs:** Cloud Android · Settings · no device account · API key and `DEVICE_ID` · device minutes, no task credits or add-ons · one-shot, up to 20 steps. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > import time > from mobilerun_sdk import MobilerunSDK > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > > > def nodes(node): > yield node > for child in node.children or []: > yield from nodes(child) > > > def observe(): > deadline = time.monotonic() + 10 > while True: > tree = device.ui(filter=True).a11y_tree > if any((n.content_description == "Dark theme" and n.is_checkable) > or (n.text == "Display" and n.resource_id == "android:id/title") > or n.text == "Settings" for n in nodes(tree)): > return tree > if time.monotonic() >= deadline: > raise RuntimeError("Display or Dark theme not visible") > time.sleep(0.5) > > > # To replace the rules with your own model (pseudocode, not executed): > # def decide_with_model(tree, phase): > # prompt = {"goal": phase, "ui": tree} > # reply = your_llm.generate(prompt) > # return validate_action(reply) # Allow only supported actions and bounds. > > def decide(tree, phase): > items = list(nodes(tree)) > toggle = next((n for n in items if n.content_description == "Dark theme" and n.is_checkable), None) > if toggle: > if phase == "enable" and toggle.is_checked: > return "restart", None > if phase == "verify" and toggle.is_checked: > return "persisted", None > if phase == "verify": > raise RuntimeError("Dark theme did not persist") > if phase == "disable" and not toggle.is_checked: > return "done", None > return "tap", toggle > display = next((n for n in items if n.text == "Display" and n.resource_id == "android:id/title"), None) > if display: > return "tap", display > if any(n.text == "Settings" for n in items): > return "open settings", None > raise RuntimeError("Display or Dark theme not visible") > > > device.open_app("com.android.settings") > phase = "enable" > for step in range(1, 21): > tree = observe() > action, target = decide(tree, phase) > print(f"Step {step}: {phase} → {action}", flush=True) > if action == "done": > print("Dark theme is off") > break > if action == "restart": > device.screenshot().save("dark-theme.png") > device.stop() # waits until stopped > device.resume() # waits until ready > device.open_app("com.android.settings") > phase = "verify" > elif action == "persisted": > print("Dark theme persisted after resume") > phase = "disable" > elif action == "open settings": > device.open_app("com.android.settings") > elif action == "tap" and target: > b = target.bounds_in_screen > device.tap((b.left + b.right) // 2, (b.top + b.bottom) // 2) > elif action == "type": > device.type("example", completion_mode="committed") > elif action == "swipe": > b = tree.bounds_in_screen > device.swipe((b.left + b.right) // 2, b.bottom * 3 // 4, (b.left + b.right) // 2, b.bottom // 4, 400) > elif action == "back": > device.back() > else: > raise RuntimeError("Step limit reached") > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > import type { A11YNode } from '@mobilerun/sdk/resources/devices/state'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > > function* nodes(node: A11YNode): Generator { > yield node; > for (const child of node.children || []) yield* nodes(child); > } > async function observe() { > const deadline = performance.now() + 10_000; > while (true) { > const tree = (await device.ui({ filter: true })).a11y_tree; > if ([...nodes(tree)].some(n => (n.contentDescription === 'Dark theme' && n.isCheckable) > || (n.text === 'Display' && n.resourceId === 'android:id/title') > || n.text === 'Settings')) return tree; > if (performance.now() >= deadline) throw new Error('Display or Dark theme not visible'); > await new Promise(resolve => setTimeout(resolve, 500)); > } > } > // To replace the rules with your own model (pseudocode, not executed): > // async function decideWithModel(tree, phase) { > // const prompt = { goal: phase, ui: tree }; > // const reply = await yourLlm.generate(prompt); > // return validateAction(reply); // Allow only supported actions and bounds. > // } > function decide(tree: A11YNode, phase: string): [string, A11YNode | undefined] { > const items = [...nodes(tree)]; > const toggle = items.find(n => n.contentDescription === 'Dark theme' && n.isCheckable); > if (toggle) { > if (phase === 'enable' && toggle.isChecked) return ['restart', undefined]; > if (phase === 'verify' && toggle.isChecked) return ['persisted', undefined]; > if (phase === 'verify') throw new Error('Dark theme did not persist'); > if (phase === 'disable' && !toggle.isChecked) return ['done', undefined]; > return ['tap', toggle]; > } > const display = items.find(n => n.text === 'Display' && n.resourceId === 'android:id/title'); > if (display) return ['tap', display]; > if (items.some(n => n.text === 'Settings')) return ['open settings', undefined]; > throw new Error('Display or Dark theme not visible'); > } > > await device.openApp('com.android.settings'); > let phase = 'enable'; > for (let step = 1; step <= 20; step++) { > const tree = await observe(); > const [action, target] = decide(tree, phase); > console.log(`Step ${step}: ${phase} → ${action}`); > if (action === 'done') { console.log('Dark theme is off'); process.exit(0); } > if (action === 'restart') { > await (await device.screenshot()).save('dark-theme.png'); > await device.stop(); // waits until stopped > await device.resume(); // waits until ready > await device.openApp('com.android.settings'); > phase = 'verify'; > } else if (action === 'persisted') { > console.log('Dark theme persisted after resume'); > phase = 'disable'; > } else if (action === 'open settings') { > await device.openApp('com.android.settings'); > } else if (action === 'tap' && target) { > const b = target.boundsInScreen; > await device.tap(Math.floor((b.left + b.right) / 2), Math.floor((b.top + b.bottom) / 2)); > } else if (action === 'type') { > await device.type('example', { completionMode: 'committed' }); > } else if (action === 'swipe') { > const b = tree.boundsInScreen; > await device.swipe(Math.floor((b.left + b.right) / 2), Math.floor(b.bottom * 3 / 4), Math.floor((b.left + b.right) / 2), Math.floor(b.bottom / 4), 400); > } else if (action === 'back') { > await device.back(); > } > } > throw new Error('Step limit reached'); > ``` ![Display settings showing Dark theme enabled](/images/examples/drive-the-phone/dark-theme.png) Result ```text theme={null} Dark theme persisted after resume Dark theme is off ``` ## Run it on many devices > [!TIP] > > This runs on as many devices as you need: each device is read in parallel. Read each device's filtered UI tree and save its screenshot in parallel. **Needs:** 2+ ready devices · `DEVICE_IDS` or all ready devices · one-shot > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import asyncio > import os > from pathlib import Path > from mobilerun_sdk import AsyncMobilerunSDK, AsyncDevice > > mobilerun = AsyncMobilerunSDK() > > > def show(node, lines): > if node.is_clickable: > lines.append(f"{node.text or node.content_description} {node.bounds_in_screen}") > for child in node.children or []: > show(child, lines) > > > async def read_screen(device: AsyncDevice) -> tuple[str, str, bool]: > name = device.name or device.id > try: > if device.state != "ready": > raise RuntimeError("Device is not ready") > state = await device.ui(filter=True) > lines = [f"Foreground: {state.phone_state.current_app or state.phone_state.package_name}"] > show(state.a11y_tree, lines) > Path(f"{device.id}.txt").write_text("\n".join(lines) + "\n") > (await device.screenshot()).save(f"{device.id}.png") > return name, f"{len(lines) - 1} clickable elements; screenshot saved", False > except Exception as error: > return name, f"ERROR: {error}", True > > > async def main() -> None: > ids = [i.strip() for i in os.getenv("DEVICE_IDS", "").split(",") if i.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"], platform="android")] > if not devices: > raise SystemExit("No ready devices found") > rows = await asyncio.gather(*(read_screen(d) for d in devices)) > print("Device | Result") > for name, result, _ in rows: > print(f"{name} | {result}") > if any(failed for _, _, failed in rows): > raise SystemExit(1) > > > asyncio.run(main()) > ``` > > ```typescript TypeScript theme={null} > import { writeFile } from 'node:fs/promises'; > import { MobilerunSDK, type Device } from '@mobilerun/sdk'; > import type { A11YNode } from '@mobilerun/sdk/resources/devices/state'; > > const mobilerun = new MobilerunSDK(); > const ids = (process.env.DEVICE_IDS ?? '').split(',').map(id => id.trim()).filter(Boolean); > const devices: Device[] = []; > 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'], platform: 'android' })) devices.push(device); > } > if (!devices.length) throw new Error('No ready devices found'); > > function show(node: A11YNode, lines: string[]): void { > if (node.isClickable) lines.push(`${node.text || node.contentDescription} ${JSON.stringify(node.boundsInScreen)}`); > for (const child of node.children || []) show(child, lines); > } > > const rows = await Promise.all(devices.map(async (device) => { > const name = device.name ?? device.id; > try { > if (device.state !== 'ready') throw new Error('Device is not ready'); > const state = await device.ui({ filter: true }); > const lines = [`Foreground: ${state.phone_state.currentApp || state.phone_state.packageName}`]; > show(state.a11y_tree, lines); > await writeFile(`${device.id}.txt`, lines.join('\n') + '\n'); > await (await device.screenshot()).save(`${device.id}.png`); > return { name, result: `${lines.length - 1} clickable elements; screenshot saved`, failed: false }; > } catch (error) { > return { name, result: `ERROR: ${error instanceof Error ? error.message : String(error)}`, failed: true }; > } > })); > console.log('Device | Result'); > for (const row of rows) console.log(`${row.name} | ${row.result}`); > if (rows.some(row => row.failed)) process.exitCode = 1; > ``` ![Android launcher from Docs scale J](/images/examples/drive-the-phone/many-phones.png) Result ```text theme={null} Device | Result Docs scale J | 6 clickable elements; screenshot saved Docs test A | 13 clickable elements; screenshot saved ``` ## Next steps Explore [device controls](/devices) to build your own actions. > [accordion] For AI agents > > Start with the first example on a ready device the user names. Uses device UI state, screenshots, app launch, tap, swipe, and keyboard calls. Ask before changing device settings or creating an alarm; never purchase anything or use real accounts. Report the result and any failed step. # Read app data as JSON Source: https://docs.mobilerun.ai/examples/extract-data Extract structured data from apps and serve it through an API. Read Android settings as JSON, compare listings across apps, and expose a book lookup as an HTTP service. > [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 > ``` ## Read Settings as JSON Read model, Android version and free storage from Settings as JSON with [typed output](/sdk/helpers#typed-output). **Needs:** [Cloud API key](/api-keys) and credits · ready Cloud Android · Settings · no app account · `MOBILERUN_API_KEY` and `DEVICE_ID` · one-shot, a few minutes · device time and task credits; no residential traffic or add-ons. > On my ready Android device, open Settings and read the device model, Android version and available free storage. Return the three values as JSON. Do not change settings or guess values. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > from pydantic import BaseModel > from mobilerun_sdk import MobilerunSDK > > > class Settings(BaseModel): > model: str > android_version: str > free_storage: str > > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > task = device.run( > task="Open Android Settings. Read the device model, Android version, and available free storage. " > "Copy each value as displayed; do not guess. Do not change any settings.", > output_schema=Settings, > ) > print(f"Task: {task.id}", flush=True) > print(task.wait_output().output.model_dump_json(indent=2)) > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > import { output } from '@mobilerun/sdk/zod'; > import { z } from 'zod/v4'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > const task = await device.run({ > task: 'Open Android Settings. Read the device model, Android version, and available free storage. ' + > 'Copy each value as displayed; do not guess. Do not change any settings.', > outputSchema: output(z.object({ model: z.string(), android_version: z.string(), free_storage: z.string() })), > }); > console.log(`Task: ${task.id}`); > console.log(JSON.stringify((await task.waitOutput()).output, null, 2)); > ``` ![Settings showing Pixel 8 and 6.03 GB free](/images/examples/extract-data/settings.png) Result ```json theme={null} {"model":"Pixel 8","android_version":"15","free_storage":"6.03 GB free"} ``` ## Compare several apps Compare Kindle Paperwhite listings from Amazon and eBay, or adapt the same pattern to LinkedIn and Indeed jobs. **Needs:** cloud API key and credits · ready Cloud Android · Amazon and eBay · guest access, no third-party account · `MOBILERUN_API_KEY`, optional `DEVICE_ID`, `QUERY`, `MAX_RESULTS` · one-shot, several minutes · device time and task credits; no residential traffic or add-ons. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import json > import os > import sys > from typing import Literal, Optional > from pydantic import BaseModel > from mobilerun_sdk import MobilerunSDK, WaitTimeoutError > > Condition = Literal["new", "used", "refurbished", "open_box", "unknown"] > > > class Listing(BaseModel): > title: str > price_text: str > price: float > currency: str > condition_label: str > seller_or_shipping: Optional[str] > sponsored: bool > > > class Listings(BaseModel): > offers: list[Listing] > > > def normalize_condition(label: str) -> Condition: > mapping: dict[str, Condition] = { > "new": "new", "brand new": "new", "used": "used", "pre-owned": "used", > "like-new": "used", "open box": "open_box", "refurbished": "refurbished", > "good - refurbished": "refurbished", "excellent - refurbished": "refurbished", > "very good - refurbished": "refurbished", "certified - refurbished": "refurbished", > } > return mapping.get(label.strip().lower(), "unknown") > > > # Add another store as a (name, Android package) pair. > STORES = [("Amazon", "com.amazon.mShop.android.shopping"), ("eBay", "com.ebay.mobile")] > query = os.environ.get("QUERY", "Kindle Paperwhite") > max_results = int(os.environ.get("MAX_RESULTS", "3")) > if max_results < 1: > raise ValueError("MAX_RESULTS must be positive") > mobilerun = MobilerunSDK() > device_id = os.getenv("DEVICE_ID") > device = mobilerun.devices.from_id(device_id) if device_id else next(iter(mobilerun.devices.list(state=["ready"], platform="android")), None) > if not device: > raise RuntimeError("No matching ready Android device found") > > offers = [] > failures = [] > for name, package in STORES: > try: > goal = (f"Open the {name} app ({package}). Continue as guest; dismiss sign-in prompts without signing in. " > f"Search for {json.dumps(query)}. Collect up to {max_results} matching listings, scrolling as needed. " > "Only include the searched product itself in the same model line, not other models, accessories, cases, or bundles with a different main item. Skip nonmatching listings, including sponsored listings. " > "Copy price_text exactly as displayed and use its numeric amount as price, and ISO currency code. " > "Copy condition_label exactly as displayed, such as Open Box or Pre-Owned; use an empty string if no explicit condition is displayed. Copy an explicit condition phrase even if it appears in the title; never infer a condition. Use null for unknown seller_or_shipping. " > "Set sponsored true only when the listing is labeled sponsored. Omit listings with unclear title or price; never estimate. " > "Never sign in, buy, or add to cart. Stop on the search results screen.") > task = device.run(task=goal, output_schema=Listings, max_steps=60, execution_timeout=300) > print(f"{name} task: {task.id}", file=sys.stderr, flush=True) > found = task.wait_output(timeout=360).output.offers[:max_results] > if not found: > raise ValueError("No offers returned") > offers.extend({"store": name, "condition": normalize_condition(o.condition_label), **o.model_dump()} for o in found) > except Exception as exc: > failures.append(name) > print(f"{name}: {exc}", file=sys.stderr) > if isinstance(exc, WaitTimeoutError): > print("Task may still be running; skipping remaining stores to avoid device conflicts.", file=sys.stderr) > break > > offers.sort(key=lambda offer: (offer["currency"], offer["price"])) > with open("offers.json", "w", encoding="utf-8") as f: > json.dump(offers, f, indent=2, ensure_ascii=False) > print(f"{'Store':<10} {'Price':<16} {'Condition':<12} {'Sponsored':<10} Title") > for offer in offers: > print(f"{offer['store']:<10} {offer['price_text']:<16} {offer['condition']:<12} {str(offer['sponsored']):<10} {offer['title']}") > for currency in sorted({offer["currency"] for offer in offers}): > cheapest = next(offer for offer in offers if offer["currency"] == currency) > print(f"Cheapest in {currency}: {cheapest['store']} {cheapest['title']} ({cheapest['price_text']})") > if failures: > print(f"Incomplete comparison; failed stores: {', '.join(failures)}", file=sys.stderr) > if not offers: > sys.exit(1) > ``` > > ```typescript TypeScript theme={null} > import { writeFile } from 'node:fs/promises'; > import { MobilerunSDK, WaitTimeoutError } from '@mobilerun/sdk'; > import { output } from '@mobilerun/sdk/zod'; > import { z } from 'zod/v4'; > > type Condition = 'new' | 'used' | 'refurbished' | 'open_box' | 'unknown'; > function normalizeCondition(label: string): Condition { > const mapping: Record = { > 'new': 'new', 'brand new': 'new', 'used': 'used', 'pre-owned': 'used', > 'like-new': 'used', 'open box': 'open_box', 'refurbished': 'refurbished', > 'good - refurbished': 'refurbished', 'excellent - refurbished': 'refurbished', > 'very good - refurbished': 'refurbished', 'certified - refurbished': 'refurbished', > }; > return mapping[label.trim().toLowerCase()] ?? 'unknown'; > } > const listings = z.object({ > offers: z.array(z.object({ > title: z.string(), price_text: z.string(), price: z.number(), currency: z.string(), > condition_label: z.string(), seller_or_shipping: z.string().nullable(), sponsored: z.boolean(), > })), > }); > // Add another store with its Android package. > const stores = [ > { name: 'Amazon', packageName: 'com.amazon.mShop.android.shopping' }, > { name: 'eBay', packageName: 'com.ebay.mobile' }, > ]; > const query = process.env.QUERY ?? 'Kindle Paperwhite'; > const maxResults = Number(process.env.MAX_RESULTS ?? '3'); > if (!Number.isInteger(maxResults) || maxResults < 1) throw new Error('MAX_RESULTS must be a positive integer'); > const mobilerun = new MobilerunSDK(); > let device; > if (process.env.DEVICE_ID) device = mobilerun.devices.fromId(process.env.DEVICE_ID); > else for await (const ready of mobilerun.devices.list({ state: ['ready'], platform: 'android' })) { device = ready; break; } > if (!device) throw new Error('No matching ready Android device found'); > const offers: (z.infer['offers'][number] & { store: string; condition: Condition })[] = []; > const failures: string[] = []; > for (const store of stores) { > try { > const goal = `Open the ${store.name} app (${store.packageName}). Continue as guest; dismiss sign-in prompts without signing in. ` + > `Search for ${JSON.stringify(query)}. Collect up to ${maxResults} matching listings, scrolling as needed. ` + > 'Only include the searched product itself in the same model line, not other models, accessories, cases, or bundles with a different main item. Skip nonmatching listings, including sponsored listings. ' + > 'Copy price_text exactly as displayed and use its numeric amount as price, and ISO currency code. ' + > 'Copy condition_label exactly as displayed, such as Open Box or Pre-Owned; use an empty string if no explicit condition is displayed. Copy an explicit condition phrase even if it appears in the title; never infer a condition. Use null for unknown seller_or_shipping. ' + > 'Set sponsored true only when the listing is labeled sponsored. Omit listings with unclear title or price; never estimate. ' + > 'Never sign in, buy, or add to cart. Stop on the search results screen.'; > const task = await device.run({ task: goal, outputSchema: output(listings), maxSteps: 60, executionTimeout: 300 }); > console.error(`${store.name} task: ${task.id}`); > const found = (await task.waitOutput({ timeoutMs: 360_000 })).output.offers.slice(0, maxResults); > if (!found.length) throw new Error('No offers returned'); > offers.push(...found.map((o) => ({ store: store.name, condition: normalizeCondition(o.condition_label), ...o }))); > } catch (error) { > failures.push(store.name); > console.error(`${store.name}: ${error}`); > if (error instanceof WaitTimeoutError) { console.error('Task may still be running; skipping remaining stores to avoid device conflicts.'); break; } > } > } > offers.sort((a, b) => a.currency.localeCompare(b.currency) || a.price - b.price); > await writeFile('offers.json', JSON.stringify(offers, null, 2) + '\n'); > console.log(`${'Store'.padEnd(10)} ${'Price'.padEnd(16)} ${'Condition'.padEnd(12)} ${'Sponsored'.padEnd(10)} Title`); > for (const offer of offers) console.log(`${offer.store.padEnd(10)} ${offer.price_text.padEnd(16)} ${offer.condition.padEnd(12)} ${String(offer.sponsored).padEnd(10)} ${offer.title}`); > for (const currency of [...new Set(offers.map(o => o.currency))]) { > const cheapest = offers.find(o => o.currency === currency)!; > console.log(`Cheapest in ${currency}: ${cheapest.store} ${cheapest.title} (${cheapest.price_text})`); > } > if (failures.length) console.error(`Incomplete comparison; failed stores: ${failures.join(', ')}`); > if (!offers.length) process.exitCode = 1; > ``` ![eBay listing for Kindle Paperwhite at \$54.99](/images/examples/extract-data/ebay-live.png) Result ```text theme={null} Cheapest in USD: eBay Kindle Paperwhite 10th Generation 6" 8gb (Black) ($54.99) ``` ## Serve it as an API Start a local book-lookup server, then request `http://127.0.0.1:8000/books/a-light-in-the-attic_1000` until the result is ready. **Needs:** cloud API key and credits · ready Cloud Android · Chrome and internet · no site account · `MOBILERUN_API_KEY` and `DEVICE_ID` · keeps running until Ctrl+C · device time and task credits per uncached lookup; no residential traffic or add-ons. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import json > import logging > import os > import re > import threading > import time > from datetime import datetime, timezone > from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer > from typing import Optional > from urllib.parse import urlparse > from pydantic import BaseModel > from mobilerun_sdk import MobilerunSDK, Task > > TTL, DEADLINE = 300, 600 > mobilerun = MobilerunSDK(max_retries=0) > device = mobilerun.devices.from_id(os.environ.get("DEVICE_ID", "")) > lock = threading.Lock() > cache = {} > job = None > failure = None > > > class Lookup(BaseModel): > found: bool > title: Optional[str] = None > price: Optional[str] = None > in_stock: Optional[bool] = None > stock_count: Optional[int] = None > > > def to_book(out: Lookup, slug: str): > if not out.found: > return None > if (not out.title or not out.title.strip() or not out.price or not re.fullmatch(r"£[0-9]+\.[0-9]{2}", out.price) > or out.in_stock is None or out.stock_count is None or out.stock_count < 0 > or out.in_stock != (out.stock_count > 0)): > raise ValueError("Invalid product fields") > return {"title": out.title, "price": out.price, "in_stock": out.in_stock, "stock_count": out.stock_count, > "url": f"https://books.toscrape.com/catalogue/{slug}/index.html"} > > > def finish(slug: str, task: "Task[Lookup]"): > global job, failure > try: > book = to_book(task.wait_output(timeout=DEADLINE).output, slug) # waits for the task to complete > if book is None: > with lock: > failure = {"slug": slug, "task_id": task.id, "status": "not_found"} > return > fetched_at = datetime.now(timezone.utc).isoformat() > with lock: > cache[slug] = (time.monotonic() + TTL, book, fetched_at) > except Exception as exc: > logging.exception("Task failed") > with lock: > failure = {"slug": slug, "task_id": task.id, "status": str(exc)} > finally: > with lock: > job = None > > > class Handler(BaseHTTPRequestHandler): > def send_json(self, code, data, retry=False): > body = json.dumps(data).encode("utf-8") > self.send_response(code) > self.send_header("Content-Type", "application/json; charset=utf-8") > self.send_header("Content-Length", str(len(body))) > if retry: > self.send_header("Retry-After", "15") > self.end_headers() > self.wfile.write(body) > > def do_GET(self): > global job, failure > url = urlparse(self.path) > match = re.fullmatch(r"/books/([a-z0-9-]+_[0-9]+)", url.path) > if not match or url.query or url.fragment: > return self.send_json(400, {"error": "Use /books/, for example a-light-in-the-attic_1000"}) > slug = match.group(1) > with lock: > entry = cache.get(slug) > if entry and entry[0] > time.monotonic(): > return self.send_json(200, {"book": entry[1], "cached": True, "fetched_at": entry[2]}) > if job: > if job["slug"] == slug: > return self.send_json(202, {"status": "pending", "task_id": job["task_id"]}, True) > return self.send_json(409, {"error": "device_busy", "running_slug": job["slug"]}, True) > if failure and failure["slug"] == slug: > result, failure = failure, None > return self.send_json(404 if result["status"] == "not_found" else 502, {"error": result["status"] if result["status"] == "not_found" else "task_failed", "task_id": result["task_id"], "status": result["status"]}) > try: > product_url = f"https://books.toscrape.com/catalogue/{slug}/index.html" > task = device.run( > task=(f"Open Chrome and go to {product_url}. If the page clearly says not found, report found false. " > "Otherwise read this product page and report found true. Copy its complete title and displayed price " > "exactly, including the £ symbol. Read availability and the exact stock count from the product information. " > "Never infer or guess. If any value is unreadable, fail the task rather than inventing it."), > max_steps=40, output_schema=Lookup, timeout=30) > except Exception: > logging.exception("Task submission failed; inspect device before retrying") > return self.send_json(502, {"error": "submission_failed", "status": "unknown"}) > job = {"slug": slug, "task_id": task.id} > threading.Thread(target=finish, args=(slug, task), daemon=True).start() > return self.send_json(202, {"status": "pending", "task_id": task.id}, True) > > def do_POST(self): > self.send_json(405, {"error": "Only GET is supported"}) > > def send_error(self, code, message=None, explain=None): > self.send_json(code, {"error": message or "Request error"}) > > > if __name__ == "__main__": > if not os.environ.get("MOBILERUN_API_KEY") or not os.environ.get("DEVICE_ID"): > raise SystemExit("Set MOBILERUN_API_KEY and DEVICE_ID") > ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever() > ``` > > ```typescript TypeScript theme={null} > import { createServer, type ServerResponse } from 'node:http'; > import { MobilerunSDK, type Task } from '@mobilerun/sdk'; > import { output } from '@mobilerun/sdk/zod'; > import { z } from 'zod/v4'; > > type Book = { title: string; price: string; in_stock: boolean; stock_count: number; url: string }; > type Job = { slug: string; task_id: string }; > const ttl = 300_000, deadlineMs = 600_000; > if (!process.env.MOBILERUN_API_KEY || !process.env.DEVICE_ID) throw new Error('Set MOBILERUN_API_KEY and DEVICE_ID'); > const mobilerun = new MobilerunSDK({ maxRetries: 0 }); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID); > const cache = new Map(); > let job: Job | null = null; > let failure: (Job & { status: string }) | null = null; > let submitting: string | null = null; > const lookup = z.object({ > found: z.boolean(), title: z.string().optional(), price: z.string().optional(), > in_stock: z.boolean().optional(), stock_count: z.int().optional(), > }); > > function toBook(b: z.infer, slug: string): Book | null { > if (!b.found) return null; > if (!b.title?.trim() || !b.price || !/^£[0-9]+\.[0-9]{2}$/.test(b.price) || b.in_stock === undefined || > b.stock_count === undefined || b.stock_count < 0 || b.in_stock !== (b.stock_count > 0)) throw new Error('Invalid product fields'); > return { title: b.title, price: b.price, in_stock: b.in_stock, stock_count: b.stock_count, > url: `https://books.toscrape.com/catalogue/${slug}/index.html` }; > } > const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); > async function finish(slug: string, task: Task>): Promise { > try { > const book = toBook((await task.waitOutput({ timeoutMs: deadlineMs })).output, slug); // waits for the task to complete > if (!book) { failure = { slug, task_id: task.id, status: 'not_found' }; return; } > cache.set(slug, { expires: performance.now() + ttl, book, fetched_at: new Date().toISOString() }); > } catch (err) { > console.error('Task failed', err); > failure = { slug, task_id: task.id, status: err instanceof Error ? err.message : String(err) }; > } finally { > job = null; > } > } > function send(res: ServerResponse, code: number, data: unknown, retry = false) { > res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', ...(retry ? { 'Retry-After': '15' } : {}) }); > res.end(JSON.stringify(data)); > } > createServer(async (req, res) => { > if (req.method !== 'GET') return send(res, 405, { error: 'Only GET is supported' }); > const url = new URL(req.url ?? '/', 'http://localhost'); > const match = /^\/books\/([a-z0-9-]+_[0-9]+)$/.exec(url.pathname); > if (!match || url.search || url.hash) return send(res, 400, { error: 'Use /books/, for example a-light-in-the-attic_1000' }); > const slug = match[1]; > const entry = cache.get(slug); > if (entry && entry.expires > performance.now()) return send(res, 200, { book: entry.book, cached: true, fetched_at: entry.fetched_at }); > if (job) return job.slug === slug > ? send(res, 202, { status: 'pending', task_id: job.task_id }, true) > : send(res, 409, { error: 'device_busy', running_slug: job.slug }, true); > // During submission there is no task ID yet; avoid starting another device task. > if (submitting) { > if (submitting !== slug) return send(res, 409, { error: 'device_busy', running_slug: submitting }, true); > while (submitting === slug) await sleep(100); > if (job && (job as Job).slug === slug) return send(res, 202, { status: 'pending', task_id: (job as Job).task_id }, true); > return send(res, 502, { error: 'submission_failed', status: 'unknown' }); > } > if (failure?.slug === slug) { > const result = failure; failure = null; > return send(res, result.status === 'not_found' ? 404 : 502, { error: result.status === 'not_found' ? 'not_found' : 'task_failed', task_id: result.task_id, status: result.status }); > } > submitting = slug; > try { > const productUrl = `https://books.toscrape.com/catalogue/${slug}/index.html`; > const task = await device.run({ task: `Open Chrome and go to ${productUrl}. If the page clearly says not found, report found false. Otherwise read this product page and report found true. Copy its complete title and displayed price exactly, including the £ symbol. Read availability and the exact stock count from the product information. Never infer or guess. If any value is unreadable, fail the task rather than inventing it.`, maxSteps: 40, outputSchema: output(lookup) }, { timeout: 30_000, maxRetries: 0 }); > job = { slug, task_id: task.id }; > void finish(slug, task); > return send(res, 202, { status: 'pending', task_id: task.id }, true); > } catch (err) { > console.error('Task submission failed; inspect device before retrying', err); > return send(res, 502, { error: 'submission_failed', status: 'unknown' }); > } finally { > submitting = null; > } > }).listen(8000, '127.0.0.1', () => console.log('Listening on http://127.0.0.1:8000')); > ``` ![Book product page showing £51.77 and 22 in stock](/images/examples/extract-data/product-lookup.png) Result ```json theme={null} {"title":"A Light in the Attic","price":"£51.77","in_stock":true,"stock_count":22} ``` > [!NOTE] > > Verify extracted values before relying on them. The local API has no authentication; add access controls before exposing it. ## Run it on many devices > [!TIP] > > This runs on as many devices as you need: each device gets the same task in parallel. Read the same Settings values from each device and print one result per device. **Needs:** 2+ ready Cloud Android devices · `DEVICE_IDS` or all ready devices · `MOBILERUN_API_KEY` · one-shot · device time and task credits > [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 Settings(BaseModel): > model: str > android_version: str > free_storage: str > > > mobilerun = AsyncMobilerunSDK() > goal = ("Open Android Settings. Read the device model, Android version, and available free storage. " > "Copy each value as displayed; do not guess. Do not change any settings.") > > > async def run(device: AsyncDevice) -> tuple[str, str, bool]: > name = device.name or device.id > try: > if device.state != "ready" or (device.info and device.info.platform) != "android": > raise RuntimeError("Device must be ready and Android") > task = await device.run(task=goal, output_schema=Settings) > print(f"{name} task: {task.id}", file=sys.stderr, flush=True) > return name, (await task.wait_output()).output.model_dump_json(), False > except Exception as exc: > return name, f"ERROR: {exc}", True > > > async def main() -> None: > ids = list(dict.fromkeys(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"], platform="android")] > if len(devices) < 2: > raise SystemExit("Select at least two ready Android devices") > results = await asyncio.gather(*(run(d) for d in devices)) > print("Device | Result") > for name, result, _ in results: > print(f"{name} | {result}") > if any(failed for _, _, failed in results): > sys.exit(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 = [...new Set((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'], platform: 'android' })) devices.push(device); > } > if (devices.length < 2) throw new Error('Select at least two ready Android devices'); > const settings = z.object({ model: z.string(), android_version: z.string(), free_storage: z.string() }); > const goal = 'Open Android Settings. Read the device model, Android version, and available free storage. ' + > 'Copy each value as displayed; do not guess. Do not change any settings.'; > const results = await Promise.allSettled(devices.map(async device => { > if (device.state !== 'ready' || device.info?.platform !== 'android') throw new Error('Device must be ready and Android'); > const task = await device.run({ task: goal, outputSchema: output(settings) }); > console.error(`${device.name || device.id} task: ${task.id}`); > return JSON.stringify((await task.waitOutput()).output); > })); > console.log('Device | Result'); > results.forEach((result, index) => console.log(`${devices[index].name || devices[index].id} | ${result.status === 'fulfilled' > ? result.value : `ERROR: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`}`)); > if (results.some(result => result.status === 'rejected')) process.exitCode = 1; > ``` ![Settings showing Pixel 8 and 7.53 GB free](/images/examples/extract-data/settings-parallel.png) Result ```text theme={null} Phone | Result Docs test E (personal) | {"model":"Pixel 8","android_version":"15","free_storage":"7.53 GB free"} Docs test F (codes) | {"model":"Pixel 9","android_version":"15","free_storage":"7.54 GB"} ``` ## Next steps * Learn about [structured output](/tasks#structured-output) and [task monitoring](/tasks). * Explore [cloud devices](/devices) and [webhooks](/webhooks). > [accordion] For AI agents > > Start with the first example on a ready device the user names. Uses `device.run`, `task.waitOutput()`, device UI state, and a local HTTP API. Ask before starting a server or exposing it; never buy anything or use real accounts. Report the result and any failed step. # Same app, different markets Source: https://docs.mobilerun.ai/examples/markets Verify network countries, compare markets, and align language and timezone. Switch one Cloud Android device between markets and verify what a fresh browser request sees. > [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 > ``` > [!NOTE] > > Use device Connect proxies, not task `vpnCountry`, to switch markets on Cloud Android; attaching or disconnecting can restart the device. Each sample starts Chrome on a unique trace URL and has a task read the country (`loc=`) from the page as [typed output](/sdk/helpers#typed-output). `device.waitReady()` returns once the device is ready again after a proxy change. ## Check one country Attach a German residential proxy, check a fresh page for `DE`, then disconnect. **Needs:** Ready Cloud Android · Chrome with first-run prompts cleared · Connect access and proxy data · `MOBILERUN_API_KEY`, `DEVICE_ID` · Python 3.9+ or Node.js · no site account · one-shot, \~1–3 min · device minutes + residential traffic. > **MCP prompt:** On my test Cloud Android device with no proxy attached, connect a rotating residential Connect proxy in Germany. Force-stop Chrome without clearing its data, open a new network trace URL with a unique query, and read the country. Verify DE, then disconnect the proxy and wait for the device to be ready. Do not sign in. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > import time > from pydantic import BaseModel > from mobilerun_sdk import MobilerunSDK > > > class Trace(BaseModel): > country: str > > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > if device.proxy.status().connected: > raise RuntimeError("Use a test device with no attached proxy") > try: > device.proxy.connect(connect={"country": "de"}, smart_ip=False) > device.wait_ready() > device.stop_app("com.android.chrome") > url = f"https://one.one.one.one/cdn-cgi/trace?x={time.time_ns()}" > device.deep_link.execute_deep_link(deep_link=url, package_name="com.android.chrome") > task = device.run( > task="Read the two-letter loc= value on the page shown in Chrome", > output_schema=Trace, > ) > country = task.wait_output().output.country > if country != "DE": > raise ValueError(f"Expected DE; page reported {country}") > print(f"Network country: {country}") > finally: > device.proxy.disconnect() > device.wait_ready() > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > import { output } from '@mobilerun/sdk/zod'; > import { z } from 'zod/v4'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > if ((await device.proxy.status()).connected) throw new Error('Use a test device with no attached proxy'); > try { > await device.proxy.connect({ connect: { country: 'de' }, smartIp: false }); > await device.waitReady(); > await device.stopApp('com.android.chrome'); > const url = `https://one.one.one.one/cdn-cgi/trace?x=${Date.now()}`; > await device.deepLink.executeDeepLink({ deepLink: url, packageName: 'com.android.chrome' }); > const task = await device.run({ > task: 'Read the two-letter loc= value on the page shown in Chrome', > outputSchema: output(z.object({ country: z.string() })), > }); > const { country } = (await task.waitOutput()).output; > if (country !== 'DE') throw new Error(`Expected DE; page reported ${country}`); > console.log(`Network country: ${country}`); > } finally { > await device.proxy.disconnect(); > await device.waitReady(); > } > ``` ![Network trace showing Germany, with the IP address removed](/images/examples/markets/l1-de.png) Result ```text theme={null} Network country: DE ``` ## Compare several markets Compare DE, JP and BR in `markets.json`, adding GPS coordinates for location-aware apps—GPS alone does not change the network country. **Needs:** Same setup · location-control capability · test device with no attached proxy · no site account · one-shot, \~2–5 min · device minutes + residential traffic. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import json > import os > import time > from pydantic import BaseModel > from mobilerun_sdk import MobilerunSDK, Device > > > class Trace(BaseModel): > country: str > > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > markets = [("DE", 52.52, 13.405), ("JP", 35.6762, 139.6503), ("BR", -23.5505, -46.6333)] > if device.proxy.status().connected: > raise RuntimeError("Use a test device with no attached proxy") > > > def read_country(device: Device) -> str: > device.stop_app("com.android.chrome") > url = f"https://one.one.one.one/cdn-cgi/trace?x={time.time_ns()}" > device.deep_link.execute_deep_link(deep_link=url, package_name="com.android.chrome") > task = device.run( > task="Read the two-letter loc= value on the page shown in Chrome", > output_schema=Trace, > ) > return task.wait_output().output.country > > > rows = [] > try: > for country, latitude, longitude in markets: > device.proxy.connect(connect={"country": country.lower()}, smart_ip=False) > device.wait_ready() > device.location.set(latitude=latitude, longitude=longitude) > observed = read_country(device) > if observed != country: > raise ValueError(f"Expected {country}; page reported {observed}") > rows.append({"market": country, "network_country": observed}) > finally: > try: > device.proxy.disconnect() > device.wait_ready() > finally: > device.location.reset() > with open("markets.json", "w", encoding="utf-8") as report: > json.dump(rows, report, indent=2) > print("Market Network country") > for row in rows: > print(f"{row['market']:<8}{row['network_country']}") > ``` > > ```typescript TypeScript theme={null} > import { writeFile } from 'node:fs/promises'; > import { MobilerunSDK, type Device } from '@mobilerun/sdk'; > import { output } from '@mobilerun/sdk/zod'; > import { z } from 'zod/v4'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > const markets = [ > { country: 'DE', latitude: 52.52, longitude: 13.405 }, > { country: 'JP', latitude: 35.6762, longitude: 139.6503 }, > { country: 'BR', latitude: -23.5505, longitude: -46.6333 }, > ]; > if ((await device.proxy.status()).connected) throw new Error('Use a test device with no attached proxy'); > > async function readCountry(device: Device): Promise { > await device.stopApp('com.android.chrome'); > const url = `https://one.one.one.one/cdn-cgi/trace?x=${Date.now()}`; > await device.deepLink.executeDeepLink({ deepLink: url, packageName: 'com.android.chrome' }); > const task = await device.run({ > task: 'Read the two-letter loc= value on the page shown in Chrome', > outputSchema: output(z.object({ country: z.string() })), > }); > return (await task.waitOutput()).output.country; > } > > const rows: { market: string; network_country: string }[] = []; > try { > for (const { country, latitude, longitude } of markets) { > await device.proxy.connect({ connect: { country: country.toLowerCase() }, smartIp: false }); > await device.waitReady(); > await device.location.set({ latitude, longitude }); > const observed = await readCountry(device); > if (observed !== country) throw new Error(`Expected ${country}; page reported ${observed}`); > rows.push({ market: country, network_country: observed }); > } > } finally { > try { > await device.proxy.disconnect(); > await device.waitReady(); > } finally { > await device.location.reset(); > } > } > await writeFile('markets.json', JSON.stringify(rows, null, 2) + '\n'); > console.log('Market Network country'); > for (const row of rows) console.log(`${row.market.padEnd(8)}${row.network_country}`); > ``` ![Network trace showing Japan, with the IP address removed](/images/examples/markets/l2-jp.png) Result ```text theme={null} Market Network country DE DE JP JP BR BR ``` ## Use any country with a proxy Choose an available Connect country with `COUNTRY`, `LOCALE` and `TIMEZONE`, use Smart IP for GPS alignment, and restore language/timezone afterward. **Needs:** Same setup · language, timezone and location controls · dedicated test device · defaults: CA, en-CA, America/Toronto · no site account · one-shot, \~1–3 min · device minutes + residential traffic. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import json > import os > import time > from pydantic import BaseModel > from mobilerun_sdk import MobilerunSDK, Device > > > class Trace(BaseModel): > country: str > > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > country = os.environ.get("COUNTRY", "CA").upper() > locale = os.environ.get("LOCALE", "en-CA") > timezone = os.environ.get("TIMEZONE", "America/Toronto") > if device.proxy.status().connected: > raise RuntimeError("Use a test device with no attached proxy") > original_locale = device.language.get().locale > original_timezone = device.timezone.get().timezone > if not original_locale or not original_timezone: > raise RuntimeError("Could not read original locale and timezone") > > > def settle(device: Device) -> None: > device.wait_ready() > device.ui() # a restarting device answers once its services are back > > > try: > device.proxy.connect(connect={"country": country.lower()}, smart_ip=True) > settle(device) > device.language.set(locale=locale, restart=True) > settle(device) > device.timezone.set(timezone=timezone) > device.stop_app("com.android.chrome") > url = f"https://one.one.one.one/cdn-cgi/trace?x={time.time_ns()}" > device.deep_link.execute_deep_link(deep_link=url, package_name="com.android.chrome") > task = device.run( > task="Read the two-letter loc= value on the page shown in Chrome", > output_schema=Trace, > ) > observed = task.wait_output().output.country > if observed != country: > raise ValueError(f"Expected {country}; page reported {observed}") > current_locale = device.language.get().locale > current_timezone = device.timezone.get().timezone > if current_locale != locale or current_timezone != timezone: > raise ValueError("Device locale or timezone did not match") > print(json.dumps({"country": observed, "locale": current_locale, "timezone": current_timezone})) > finally: > try: > device.proxy.disconnect() > settle(device) > finally: > try: > device.language.set(locale=original_locale, restart=True) > settle(device) > finally: > try: > device.timezone.set(timezone=original_timezone) > finally: > device.location.reset() > ``` > > ```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 device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > const country = (process.env.COUNTRY ?? 'CA').toUpperCase(); > const locale = process.env.LOCALE ?? 'en-CA'; > const timezone = process.env.TIMEZONE ?? 'America/Toronto'; > if ((await device.proxy.status()).connected) throw new Error('Use a test device with no attached proxy'); > const originalLocale = (await device.language.get()).locale; > const originalTimezone = (await device.timezone.get()).timezone; > if (!originalLocale || !originalTimezone) throw new Error('Could not read original locale and timezone'); > > async function settle(device: Device) { > await device.waitReady(); > await device.ui(); // a restarting device answers once its services are back > } > > try { > await device.proxy.connect({ connect: { country: country.toLowerCase() }, smartIp: true }); > await settle(device); > await device.language.set({ locale, restart: true }); > await settle(device); > await device.timezone.set({ timezone }); > await device.stopApp('com.android.chrome'); > const url = `https://one.one.one.one/cdn-cgi/trace?x=${Date.now()}`; > await device.deepLink.executeDeepLink({ deepLink: url, packageName: 'com.android.chrome' }); > const task = await device.run({ > task: 'Read the two-letter loc= value on the page shown in Chrome', > outputSchema: output(z.object({ country: z.string() })), > }); > const observed = (await task.waitOutput()).output.country; > if (observed !== country) throw new Error(`Expected ${country}; page reported ${observed}`); > const currentLocale = (await device.language.get()).locale; > const currentTimezone = (await device.timezone.get()).timezone; > if (currentLocale !== locale || currentTimezone !== timezone) throw new Error('Device locale or timezone did not match'); > console.log(JSON.stringify({ country: observed, locale: currentLocale, timezone: currentTimezone })); > } finally { > try { > await device.proxy.disconnect(); > await settle(device); > } finally { > try { > await device.language.set({ locale: originalLocale, restart: true }); > await settle(device); > } finally { > try { > await device.timezone.set({ timezone: originalTimezone }); > } finally { > await device.location.reset(); > } > } > } > } > ``` ![Network trace showing Canada, with the IP address removed](/images/examples/markets/l3-ca.png) Result ```json theme={null} {"country":"CA","locale":"en-CA","timezone":"America/Toronto"} ``` ## One device per market > [!TIP] > > Add as many markets as you need: one device per market, all in parallel. Map countries to distinct device IDs and run the same country check on every device in parallel. **Needs:** Same setup on each device · `DEVICE_IDS` JSON, e.g. `{"DE":"device-id","JP":"another-device-id"}` · one-shot, \~1–3 min · device minutes + residential traffic per device. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import asyncio > import json > import os > import time > from pydantic import BaseModel > from mobilerun_sdk import AsyncMobilerunSDK > > > class Trace(BaseModel): > country: str > > > mobilerun = AsyncMobilerunSDK() > markets = json.loads(os.environ["DEVICE_IDS"]) # {"DE":"device-id","JP":"another-device-id"} > if not isinstance(markets, dict) or not markets: > raise ValueError("DEVICE_IDS must be a nonempty country-to-device JSON object") > if not all(isinstance(c, str) and len(c) == 2 and isinstance(d, str) and d for c, d in markets.items()): > raise ValueError("Use two-letter country keys and device ID strings") > if len(set(markets.values())) != len(markets): > raise ValueError("Each market needs a different device") > > > async def check_market(market: str, device_id: str) -> dict[str, str]: > country = market.upper() > device = mobilerun.devices.from_id(device_id) > await device.refresh() > if device.state != "ready" or (await device.proxy.status()).connected: > raise RuntimeError("Each test device must be ready with no attached proxy") > try: > await device.proxy.connect(connect={"country": country.lower()}, smart_ip=False) > await device.wait_ready() > await device.stop_app("com.android.chrome") > url = f"https://one.one.one.one/cdn-cgi/trace?x={time.time_ns()}" > await device.deep_link.execute_deep_link(deep_link=url, package_name="com.android.chrome") > task = await device.run( > task="Read the two-letter loc= value on the page shown in Chrome", > output_schema=Trace, > ) > observed = (await task.wait_output()).output.country > if observed != country: > raise ValueError(f"Expected {country}; page reported {observed}") > return {"market": country, "network_country": observed} > finally: > await device.proxy.disconnect() > await device.wait_ready() > > > async def main() -> None: > results = await asyncio.gather( > *(check_market(m, d) for m, d in markets.items()), return_exceptions=True > ) > if any(isinstance(r, BaseException) for r in results): > raise RuntimeError("A market failed; all workers have finished cleanup") > print("Market Network country") > for row in results: > if isinstance(row, dict): > print(f"{row['market']:<8}{row['network_country']}") > > > asyncio.run(main()) > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > import { output } from '@mobilerun/sdk/zod'; > import { z } from 'zod/v4'; > > const mobilerun = new MobilerunSDK(); > const markets: unknown = JSON.parse(process.env.DEVICE_IDS ?? 'null'); // {"DE":"device-id","JP":"another-device-id"} > if (!markets || typeof markets !== 'object' || Array.isArray(markets)) throw new Error('DEVICE_IDS must be a country-to-device JSON object'); > const entries = Object.entries(markets); > if (!entries.length || entries.some(([c, d]) => c.length !== 2 || typeof d !== 'string' || !d)) throw new Error('Use country keys and device ID strings'); > if (new Set(entries.map(([, d]) => d)).size !== entries.length) throw new Error('Each market needs a different device'); > > async function checkMarket([market, id]: [string, unknown]) { > const country = market.toUpperCase(); > const device = mobilerun.devices.fromId(id as string); > await device.refresh(); > if (device.state !== 'ready' || (await device.proxy.status()).connected) > throw new Error('Each test device must be ready with no attached proxy'); > try { > await device.proxy.connect({ connect: { country: country.toLowerCase() }, smartIp: false }); > await device.waitReady(); > await device.stopApp('com.android.chrome'); > const url = `https://one.one.one.one/cdn-cgi/trace?x=${Date.now()}`; > await device.deepLink.executeDeepLink({ deepLink: url, packageName: 'com.android.chrome' }); > const task = await device.run({ > task: 'Read the two-letter loc= value on the page shown in Chrome', > outputSchema: output(z.object({ country: z.string() })), > }); > const observed = (await task.waitOutput()).output.country; > if (observed !== country) throw new Error(`Expected ${country}; page reported ${observed}`); > return { market: country, network_country: observed }; > } finally { > await device.proxy.disconnect(); > await device.waitReady(); > } > } > > const results = await Promise.allSettled(entries.map(checkMarket)); > if (results.some((result) => result.status === 'rejected')) throw new Error('A market failed; all workers have finished cleanup'); > console.log('Market Network country'); > for (const result of results) { > if (result.status === 'fulfilled') console.log(`${result.value.market.padEnd(8)}${result.value.network_country}`); > } > ``` ![Network trace showing Brazil, with the IP address removed](/images/examples/markets/l4-br.png) Parallel market checks ```text theme={null} Market Network country DE DE JP JP BR BR ``` ## Next steps * Replace the trace page with your app's regional content or pricing screen. * Find supported countries in the [Connect country catalog](/api-reference/countries/list-available-countries). * Explore [proxies and Smart IP](/proxies) or [read app data as JSON](/examples/extract-data). > [accordion] For AI agents > > * Start with Check one country on a ready test device with no attached proxy. > * Use device proxy, deep-link and typed task output; map `DEVICE_IDS` to distinct devices for parallel checks. > * Ask before attaching a proxy: it can restart the device and uses residential traffic. > * Report requested versus observed countries and cleanup status. # Examples Source: https://docs.mobilerun.ai/examples/overview Pick a use case. Each one starts small and builds up from there. [Example projects on GitHub](https://github.com/droidrun/mobilerun-examples) > [card] [Read app data as JSON](/examples/extract-data) > > Turn what a phone shows into structured data. > [card] [Same app, different markets](/examples/markets) > > See what an app shows in another country. > [card] [Test a flow and keep proof](/examples/test-and-prove) > > Run a test and keep video and screenshots. > [card] [Drive the phone step by step](/examples/drive-the-phone) > > Read the screen and tap from your own code. > [card] [Watch an app and get alerts](/examples/watch-and-alert) > > Get notified when something changes. > [card] [Automate your own phone](/examples/personal-phone) > > Briefings and approved actions on your phone. > [card] [Finish a sign-up that sends a code](/examples/sign-up-codes) > > Read email and SMS codes during a sign-up. > [card] [Your work phone in the browser](/examples/stream-phone) > > Watch and control a phone from your browser. ## Before you start 1. Create a key on the [API Keys](/api-keys) page and `export MOBILERUN_API_KEY=...`. 2. Install `pip install mobilerun-sdk` or `npm install @mobilerun/sdk`, or connect the [MCP server](/mcp-server). 3. Have a ready phone. Start a Cloud Android phone in the [dashboard](https://cloud.mobilerun.ai), or connect [your own phone](/device-types#personal-phone). Stop cloud phones when you're done. > [!TIP] > > Each example includes a multi-phone version, whether that's running tasks in parallel, comparing markets, or streaming a grid of phones. ## Phones and add-ons Run the examples on our phones or yours, and add what a use case needs. > [card] [Cloud Android](/device-types) > > Pay per minute or a dedicated phone. Stop and resume keeps apps and logins. > [card] [Cloud iOS](/device-types) > > A dedicated real iPhone, or a virtual iPhone billed per minute. > [card] [Your own phone](/guides/connect-android) > > Connect your own Android phone to Mobilerun. > [card] [Proxies and countries](/proxies) > > Residential IPs and GPS for other countries. > [card] [Mailboxes and numbers](/examples/sign-up-codes) > > Receive email and SMS codes during a flow. > [card] [Live stream in your app](/guides/embed-device-stream) > > Show a phone to your users and let them take over. > [accordion] Advanced > > * **Many phones at once:** examples include multi-phone variants. See [Devices](/devices). > * **Logins:** store app logins in [Credentials](/credentials) and attach them to tasks. Never put passwords in prompts. > * **Your own apps:** upload your APK to the [app library](/apps) and install it on any Cloud Android phone. > * **Events instead of polling:** [Webhooks](/webhooks) send `task.run.completed` and `task.run.failed` to your backend. > * **Browser control:** drive Chrome on the phone with Puppeteer or Playwright, see [Browser automation](/browser-automation). > * **Traffic inspection:** see an app's HTTP and WebSocket traffic while you walk its screens, see [Network inspection](/integrations/network-inspection). > [accordion] For AI assistants > > 1. Ask what the user wants to build and match it to an example above. Start at Level 1. > 2. Use MCP if it's connected; otherwise write SDK code. > 3. List phones and capabilities first. Ask before creating phones, proxies, mailboxes, numbers or webhooks, and never approve a purchase. > 4. Report the result, the steps, and anything that failed. > > Never put passwords in prompts. Use [Credentials](/credentials). # Automate your own device Source: https://docs.mobilerun.ai/examples/personal-phone 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](/guides/connect-android) 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): 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](/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](/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](/tasks) and [Personal Phones](/device-types#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. # Finish a sign-up that sends a code Source: https://docs.mobilerun.ai/examples/sign-up-codes Read email and SMS verification codes for your own test sign-up flow. Use a Mobilerun mailbox and an optional phone number to test verification in your own application. > [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 > ``` > [!NOTE] > > These examples require an active mailbox or number. This walkthrough was not verified end to end: the test account required payment checkout before either resource could be activated. Never log verification codes or use this flow on accounts without permission. ## Read an email code Request a fresh code from a test app you control, then wait for it with `mailbox.waitForOtp()` (Python `wait_for_otp`). The API returns the most likely code, not proof that a sign-up succeeded. **Needs:** A Mobilerun API key and an active mailbox; included mailbox entitlement or paid rental after checkout. Check the displayed checkout price before confirming. No device or third-party account is needed. Set `MOBILERUN_API_KEY` and `MAILBOX_ID`. This is a one-shot wait for up to two minutes; message allowance and mailbox rental may apply. Create a mailbox with `mobilerun.mailboxes.create()` and check that `mailbox.status` is `active` (`mailbox.refresh()` updates it). If it is `awaiting_payment`, complete checkout from its `checkoutUrl` before continuing. Reuse the active mailbox ID; do not create a mailbox on every run. Configure your test app to send a code to that mailbox, and trigger it after the script starts. The test app must be able to send real email; this example does not send email itself. > **MCP prompt:** Find my active test mailbox, wait for a new verification code from my test app, and report only whether a code arrived. Do not disclose the code. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > from datetime import datetime, timezone > from mobilerun_sdk import MobilerunSDK > > mobilerun = MobilerunSDK() > mailbox = mobilerun.mailboxes.from_id(os.environ['MAILBOX_ID']) > after = datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') > print('Request a code from your test app now; waiting up to 2 minutes.') > otp = mailbox.wait_for_otp(after=after, timeout=120) # raises WaitTimeoutError if no code arrives > print('Code received; message ID:', otp.message_id) > # Use otp.code in your test; never print it in CI logs. > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > > const mobilerun = new MobilerunSDK(); > const mailbox = mobilerun.mailboxes.fromId(process.env.MAILBOX_ID!); > const after = new Date().toISOString(); > console.log('Request a code from your test app now; waiting up to 2 minutes.'); > const otp = await mailbox.waitForOtp({ after }, { timeoutMs: 120_000 }); // throws WaitTimeoutError if no code arrives > console.log('Code received; message ID:', otp.messageId); > // Use otp.code in your test; never print it in CI logs. > ``` Result Expected: a code is received; do not print it. This example was not verified end to end. ## Complete test sign-up verification The first task requests a code; the script fetches it and starts a second task to enter it. Point the URL at your own test build. The second task assumes the verification form is still open on the same device. **Needs:** the mailbox from above, plus a ready Cloud Android device with Chrome, device minutes and agent credits; set `DEVICE_ID` and `TEST_SIGNUP_URL` to an HTTPS test form reachable by the device. No consumer-service account. One-shot; each task can take up to six minutes, then up to two minutes waiting for the email. Agent task instructions contain the mailbox address and verification code: use only test data and restrict access to task history. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > from datetime import datetime, timezone > from mobilerun_sdk import MobilerunSDK > > mobilerun = MobilerunSDK() > device = mobilerun.devices.from_id(os.environ['DEVICE_ID']) > mailbox = mobilerun.mailboxes.get(os.environ['MAILBOX_ID']) > if mailbox.status != 'active' or not mailbox.address: > raise RuntimeError('Mailbox must be active') > > after = datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') > device.run( > task=f"Open Chrome at {os.environ['TEST_SIGNUP_URL']}. Enter {mailbox.address} " > 'in the test sign-up form, request a verification code, and stop at the code field.', > max_steps=30, > ).wait(timeout=360) > otp = mailbox.wait_for_otp(after=after, timeout=120) > device.run( > task=f'Enter the verification code {otp.code} in the current form and finish the test sign-up.', > max_steps=30, > ).wait(timeout=360) > print('Verification task completed') > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > const mailbox = await mobilerun.mailboxes.get(process.env.MAILBOX_ID!); > if (mailbox.status !== 'active' || !mailbox.address) throw new Error('Mailbox must be active'); > > const after = new Date().toISOString(); > const signup = await device.run({ > task: `Open Chrome at ${process.env.TEST_SIGNUP_URL}. Enter ${mailbox.address} in the test sign-up form, request a verification code, and stop at the code field.`, > maxSteps: 30, > }); > await signup.wait({ timeoutMs: 360_000 }); > const otp = await mailbox.waitForOtp({ after }, { timeoutMs: 120_000 }); > const verify = await device.run({ > task: `Enter the verification code ${otp.code} in the current form and finish the test sign-up.`, > maxSteps: 30, > }); > await verify.wait({ timeoutMs: 360_000 }); > console.log('Verification task completed'); > ``` Result Expected: the test verification completes. This example was not verified end to end. ## Read an SMS code Use a number that has already been provisioned. Poll inbound messages after the script starts, looking for a six-digit code. Adapt the expression and filter sender or message content for your own app; an unrelated message may otherwise match. **Needs:** A Mobilerun API key, an active SMS-capable number, and a test service you control that can send SMS to it. Set `MOBILERUN_API_KEY` and `NUMBER_ID`. No device is needed. Number entitlement or rental, checkout, and sender SMS charges may apply; confirm the displayed price. The script polls for up to two minutes; stop early with Ctrl+C. Use `mobilerun.numbers.countries()` to find available countries, then `mobilerun.numbers.create(country=...)` (Python) or `mobilerun.numbers.create({ country: ... })` (TypeScript). `number.waitUntilActive()` (Python `wait_until_active`) returns once the number is `active`; a paid rental can require checkout. Reuse the number rather than purchasing one on each run. Start the script before triggering your test SMS. SMS delivery and code extraction were not live-tested here. > [accordion] Show the code (Python and TypeScript) > > ```python Python theme={null} > import os > import re > import time > from datetime import datetime, timezone > from mobilerun_sdk import MobilerunSDK > > mobilerun = MobilerunSDK() > number = mobilerun.numbers.get(os.environ['NUMBER_ID']) > if number.state != 'active': > raise RuntimeError('Number must be active') > since = datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') > print('Request an SMS code from your test app; waiting up to 2 minutes.') > # The SDK has no helper that waits for an incoming SMS, so poll the number. > for _ in range(24): > for message in number.messages.list(direction='inbound', since=since): > match = re.search(r'\b\d{6}\b', getattr(message.info, 'body', None) or '') > if match: > print('SMS code received; message ID:', message.id) > # Use match.group(0) in your test without logging it. > raise SystemExit(0) > time.sleep(5) > raise TimeoutError('No matching SMS arrived') > ``` > > ```typescript TypeScript theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > > const mobilerun = new MobilerunSDK(); > const number = await mobilerun.numbers.get(process.env.NUMBER_ID!); > if (number.state !== 'active') throw new Error('Number must be active'); > const since = new Date().toISOString(); > console.log('Request an SMS code from your test app; waiting up to 2 minutes.'); > // The SDK has no helper that waits for an incoming SMS, so poll the number. > for (let i = 0; i < 24; i++) { > for await (const message of number.messages.list({ direction: 'inbound', since })) { > const info = message.info; > const match = (info && 'body' in info ? info.body : undefined)?.match(/\b\d{6}\b/); > if (match) { > console.log('SMS code received; message ID:', message.id); > // Use match[0] in your test without logging it. > process.exit(0); > } > } > await new Promise(resolve => setTimeout(resolve, 5000)); > } > throw new Error('No matching SMS arrived'); > ``` Result Expected: a code is received; do not print it. This example was not verified end to end. ## Run it on many devices > [!TIP] > > Use a separate test mailbox and device for each parallel sign-up. These examples run one verification at a time; coordinate separate runs for parallel tests. **Needs:** A separate ready device and active test mailbox per sign-up · device minutes and task credits per run. Result Expected: each test sign-up is verified independently. Parallel runs were not verified here. ## Next steps * Review the [API key guide](/api-keys) for mailbox and number endpoints. * Use a dedicated test mailbox and number. Release rentals when you no longer need them. > [accordion] For AI agents > > Start with the first example on a ready device the user names. Uses `mailbox.waitForOtp`, number messages, and optionally `device.run`. Ask before creating or renting mailboxes/numbers or completing a test sign-up; never purchase resources or use real accounts. Report the result and any failed step. # Your work device in the browser Source: https://docs.mobilerun.ai/examples/stream-phone Stream a cloud device into a web app and use it from any browser. > [!NOTE] > > TypeScript and Python examples require SDK 6.3.1 or later. Use a cloud device from your browser while an agent works alongside you. The backend mints a single-use stream token for the device; the API key never reaches the browser. See the [embed guide](/guides/embed-device-stream) for the authenticated production flow. > [accordion] Set up the web app > > Install Node 20.19+ or 22.12+, then create a folder for the app: > > ```bash TypeScript theme={null} > npm init -y > npm pkg set type=module > npm install @mobilerun/react @mobilerun/sdk react react-dom vite tsx > export MOBILERUN_API_KEY="your-api-key" > export DEVICE_ID="your-device-id" > npx tsx server.ts > ``` > > ```bash Python theme={null} > npm init -y > npm pkg set type=module > npm install @mobilerun/react react react-dom vite > pip install mobilerun-sdk fastapi uvicorn httpx > export MOBILERUN_API_KEY="your-api-key" > export DEVICE_ID="your-device-id" > uvicorn server:app --host 127.0.0.1 --port 8000 > # In a second terminal in the same folder: > npx vite --host 127.0.0.1 --port 5173 --strictPort > ``` > > Save the server tab you choose and `App.tsx` from one example below before running its commands. For Python, also save these two Vite files so browser API requests reach FastAPI on port 8000: > > ```typescript vite.config.ts theme={null} > import { defineConfig } from 'vite'; > > export default defineConfig({ > server: { proxy: { '/api': 'http://127.0.0.1:8000' } }, > }); > ``` > > ```html index.html theme={null} > >
> > ``` > > Open `http://localhost:5173`; press Ctrl+C to stop the server. The demo binds to localhost only: before exposing it, authenticate users and authorize access to each device in your backend. Never log or persist stream credentials. > > Save this backend helper beside the server file. It mints fresh credentials instead of reading the deprecated token from `device.info`; the [embed guide](/guides/embed-device-stream) covers authorization, token permissions, and errors. These local demos must not be exposed until you authenticate the caller and authorize the device before calling the helper. > > ```typescript stream-token.ts theme={null} > import { MobilerunSDK } from '@mobilerun/sdk'; > > const mobilerun = new MobilerunSDK(); > > export async function mintStream(deviceId: string) { > const { key } = await mobilerun.streamTokens.create({ > deviceId, > ttlSeconds: 120, > allowedOrigins: ['http://localhost:5173'], > }); > return { streamUrl: `wss://api.mobilerun.ai/v1/devices/${deviceId}/stream`, streamToken: key }; > } > ``` > > ```python stream_token.py theme={null} > import httpx > from mobilerun_sdk import MobilerunSDK, AsyncMobilerunSDK > > > def mint_stream(device_id: str) -> dict[str, str]: > with httpx.Client(timeout=10) as http: > mobilerun = MobilerunSDK(http_client=http) > token = mobilerun.stream_tokens.create( > device_id=device_id, > ttl_seconds=120, > allowed_origins=["http://localhost:5173"], > ) > return {"streamUrl": f"wss://api.mobilerun.ai/v1/devices/{device_id}/stream", > "streamToken": token.key} > > > async def mint_stream_async(device_id: str) -> dict[str, str]: > async with httpx.AsyncClient(timeout=10) as http: > mobilerun = AsyncMobilerunSDK(http_client=http) > token = await mobilerun.stream_tokens.create( > device_id=device_id, > ttl_seconds=120, > allowed_origins=["http://localhost:5173"], > ) > return {"streamUrl": f"wss://api.mobilerun.ai/v1/devices/{device_id}/stream", > "streamToken": token.key} > ``` > > For a deployed frontend, replace `http://localhost:5173` in `allowedOrigins` / `allowed_origins` with its exact HTTPS origin. Keep `MOBILERUN_API_KEY` server-side only. > > Every reconnect needs a fresh token. The examples use the published React package's `onStreamHealed` callback to ask the backend again. ## Show a device in your web app Stream a device into a React page and tap or type directly on its screen. **Needs:** Node 20.19+ or 22.12+ · a ready Cloud Android device · server-side API key and `DEVICE_ID` · device minutes · dev server keeps running. > [accordion] Show the code > > ```typescript server.ts theme={null} > import { mintStream } from './stream-token.js'; > import { MobilerunSDK } from '@mobilerun/sdk'; > import { createServer } from 'node:http'; > import { createServer as createViteServer } from 'vite'; > > const mobilerun = new MobilerunSDK(); > const vite = await createViteServer({ server: { middlewareMode: true } }); > createServer(async (req, res) => { > if (req.url === '/api/stream') { > try { > const credentials = await mintStream(process.env.DEVICE_ID!); > res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); > res.end(JSON.stringify(credentials)); > } catch { > res.writeHead(502).end('Unable to load the device'); > } > return; > } > if (req.url === '/') { > res.writeHead(200, { 'Content-Type': 'text/html' }); > res.end(await vite.transformIndexHtml('/', '
')); > return; > } > vite.middlewares(req, res, () => res.writeHead(404).end()); > }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173')); > ``` > > ```python server.py theme={null} > from stream_token import mint_stream, mint_stream_async > import os > from fastapi import FastAPI > from fastapi.responses import JSONResponse, PlainTextResponse > from mobilerun_sdk import MobilerunSDK > > app = FastAPI() > mobilerun = MobilerunSDK() > > @app.get("/api/stream", response_model=None) > def stream() -> JSONResponse | PlainTextResponse: > try: > return JSONResponse(mint_stream(os.environ["DEVICE_ID"]), headers={"Cache-Control": "no-store"}) > except Exception: > return PlainTextResponse("Unable to load the device", status_code=502) > ``` > > The React component runs in the browser with either server: > > ```tsx App.tsx theme={null} > import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react'; > import '@mobilerun/react/styles.css'; > import { useCallback, useEffect, useRef, useState } from 'react'; > import { createRoot } from 'react-dom/client'; > > function App() { > const controls = useRef(null); > const [stream, setStream] = useState<{ streamUrl?: string; streamToken?: string }>({}); > const loadStream = useCallback(async () => { > const response = await fetch('/api/stream', { cache: 'no-store' }); > if (response.ok) setStream(await response.json()); > }, []); > useEffect(() => { void loadStream(); }, [loadStream]); > return
>

Your work device

>
>
> controls.current?.sendSystemKey(action)} /> >
>
; > } > createRoot(document.getElementById('root')!).render(); > ``` ![Browser app streaming Android Settings](/images/examples/stream-phone/show-phone.png) Result ```text theme={null} Tapped Settings → com.android.settings ``` ## Stream your Personal Phone full-screen Keep your Personal Phone connected through Portal and control it in a browser-sized stream. **Needs:** Node 20.19+ or 22.12+ · a connected Personal Phone · server-side API key and its `DEVICE_ID` · Portal and the dev server keep running. Connect your [Android device](/guides/connect-android) or [iPhone](/guides/connect-iphone), then use its Personal Phone ID from the dashboard. On Android, approve screen sharing when prompted. The stream fills the viewport without stretching the device image; black space may appear around it. > [!NOTE] > > Online availability depends on the device, its network, and Portal remaining connected; it is not guaranteed. iPhone setup may require a connected computer. The navigation bar provides Android system keys; iPhone control and screen sharing depend on its connection mode and permissions. > [accordion] Show the code > > ```typescript server.ts theme={null} > import { mintStream } from './stream-token.js'; > import { MobilerunSDK } from '@mobilerun/sdk'; > import { createServer } from 'node:http'; > import { createServer as createViteServer } from 'vite'; > > const mobilerun = new MobilerunSDK(); > const deviceId = process.env.DEVICE_ID; > if (!deviceId) throw new Error('Set DEVICE_ID to your Personal Phone ID'); > const vite = await createViteServer({ server: { middlewareMode: true } }); > createServer(async (req, res) => { > if (req.url?.split('?')[0] === '/api/phone' && req.method === 'GET') { > res.setHeader('Content-Type', 'application/json'); > res.setHeader('Cache-Control', 'no-store'); > try { > const device = await mobilerun.devices.get(deviceId); > const info = device.info; > if (info?.type !== 'device_slot') { > res.writeHead(400).end(JSON.stringify({ error: 'DEVICE_ID must be a Personal Phone' })); > } else if (device.state !== 'ready') { > res.end(JSON.stringify({ state: device.state })); > } else { > const credentials = new URL(req.url!, 'http://localhost').searchParams.has('connect') > ? await mintStream(deviceId) : {}; > res.end(JSON.stringify({ state: device.state, platform: info.platform, ...credentials })); > } > } catch { > res.writeHead(502).end(JSON.stringify({ error: 'Unable to look up the device' })); > } > return; > } > if (req.url === '/') { > res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-store' }); > res.end(await vite.transformIndexHtml('/', '
')); > return; > } > vite.middlewares(req, res, () => res.writeHead(404).end()); > }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173')); > ``` > > ```python server.py theme={null} > from stream_token import mint_stream, mint_stream_async > import os > from fastapi import FastAPI > from fastapi.responses import JSONResponse > from mobilerun_sdk import MobilerunSDK > > app = FastAPI() > mobilerun = MobilerunSDK() > device_id = os.environ["DEVICE_ID"] > > @app.get("/api/phone") > def stream(connect: bool = False) -> JSONResponse: > headers = {"Cache-Control": "no-store"} > try: > device = mobilerun.devices.get(device_id) > info = device.info > if not info or info.type != "device_slot": > return JSONResponse({"error": "DEVICE_ID must be a Personal Phone"}, status_code=400, headers=headers) > if device.state != "ready": > return JSONResponse({"state": device.state}, headers=headers) > credentials = mint_stream(device_id) if connect else {} > return JSONResponse({"state": device.state, "platform": info.platform, **credentials}, headers=headers) > except Exception: > return JSONResponse({"error": "Unable to look up the device"}, status_code=502, headers=headers) > ``` > > The React component runs in the browser with either server: > > ```tsx App.tsx theme={null} > import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react'; > import '@mobilerun/react/styles.css'; > import { useCallback, useEffect, useRef, useState } from 'react'; > import { createRoot } from 'react-dom/client'; > > type Phone = { state: string; platform?: string; streamUrl?: string; streamToken?: string }; > function App() { > const controls = useRef(null); > const [phone, setPhone] = useState(); > const [error, setError] = useState(''); > const [connected, setConnected] = useState(false); > const loadCredentials = useCallback(async () => { > const response = await fetch('/api/phone?connect=1', { cache: 'no-store' }); > if (response.ok) setPhone(await response.json()); > }, []); > useEffect(() => { > let cancelled = false; > let timer: ReturnType; > async function poll() { > try { > const response = await fetch('/api/phone', { cache: 'no-store' }); > const data = await response.json(); > if (!response.ok) throw new Error(data.error || 'Unable to look up the device'); > if (!cancelled) { > if (data.state !== 'ready') setConnected(false); > setPhone(previous => data.state === 'ready' ? { ...previous, ...data } : data); setError(''); > } > } catch (e) { > if (!cancelled) { setPhone(undefined); setConnected(false); setError(e instanceof Error ? e.message : 'Unable to look up the device'); } > } > if (!cancelled) timer = setTimeout(poll, 3000); > } > void poll(); > return () => { cancelled = true; clearTimeout(timer); }; > }, []); > useEffect(() => { > if (phone?.state === 'ready' && !phone.streamToken) void loadCredentials(); > }, [phone?.state, phone?.streamToken, loadCredentials]); > const ready = phone?.state === 'ready' && phone.streamUrl && phone.streamToken; > const status = error || (!phone ? 'Checking device…' : phone.state !== 'ready' > ? 'Device offline — open Portal on the device' : !ready ? 'Waiting for stream credentials…' > : connected ? 'Device online' : 'Device online — connecting stream…'); > return
>
{status}
>
> {ready && } >
> {ready && phone.platform === 'android' && controls.current?.sendSystemKey(action)} />} >
; > } > createRoot(document.getElementById('root')!).render(); > ``` The browser polls only the device's state every three seconds. It mints credentials when the device first becomes ready and on reconnect, rather than minting unused tokens on each status poll. When it is not ready, the stream is removed. The example never starts or stops the personal device. Before exposing this beyond localhost, authenticate users and authorize access to the device. Result ```text theme={null} Device offline — open Portal on the device Device online — connecting stream… Device online ``` ## Let an agent work while you watch Run a task on the same device, watch the agent, and stop it when you want to take over. **Needs:** Node 20.19+ or 22.12+ · a ready Cloud Android device · server-side API key and `DEVICE_ID` · device minutes and task credits · dev server keeps running. > [accordion] Show the code > > ```typescript server.ts theme={null} > import { mintStream } from './stream-token.js'; > import { MobilerunSDK, WaitError, type Task } from '@mobilerun/sdk'; > import { createServer } from 'node:http'; > import { createServer as createViteServer } from 'vite'; > > const mobilerun = new MobilerunSDK(); > const device = mobilerun.devices.fromId(process.env.DEVICE_ID!); > const vite = await createViteServer({ server: { middlewareMode: true } }); > let current: Task | undefined; > createServer(async (req, res) => { > if (req.url?.startsWith('/api/')) { > res.setHeader('Cache-Control', 'no-store'); > res.setHeader('Content-Type', 'application/json'); > try { > if (req.url === '/api/stream' && req.method === 'GET') { > res.end(JSON.stringify(await mintStream(process.env.DEVICE_ID!))); > } else if (req.url === '/api/task' && req.method === 'POST') { > let body = ''; > for await (const chunk of req) body += chunk; > const { task } = JSON.parse(body) as { task: string }; > if (typeof task !== 'string' || !task.trim()) throw new Error('Task required'); > const run = await device.run({ task, maxSteps: 30 }); > current = run; > // Answer when the task ends. A stopped or failed task is reported, not thrown. > const s = await run.wait().catch(async (error) => { > if (error instanceof WaitError) return run.getStatus(); > throw error; > }); > res.end(JSON.stringify({ status: s.status, message: s.message, succeeded: s.succeeded })); > } else if (req.url === '/api/stop' && req.method === 'POST' && current) { > await current.stop(); > res.end('{}'); > } else res.writeHead(404).end('{}'); > } catch { > res.writeHead(502).end(JSON.stringify({ error: 'Request failed' })); > } > return; > } > if (req.url === '/') { > res.writeHead(200, { 'Content-Type': 'text/html' }); > res.end(await vite.transformIndexHtml('/', '
')); > return; > } > vite.middlewares(req, res, () => res.writeHead(404).end()); > }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173')); > ``` > > ```python server.py theme={null} > from stream_token import mint_stream, mint_stream_async > import os > from fastapi import FastAPI, Request > from fastapi.responses import JSONResponse > from mobilerun_sdk import AsyncMobilerunSDK, AsyncTask, WaitError > > app = FastAPI() > mobilerun = AsyncMobilerunSDK() > device = mobilerun.devices.from_id(os.environ["DEVICE_ID"]) > current: AsyncTask | None = None > > @app.api_route("/api/{path:path}", methods=["GET", "POST"]) > async def api(path: str, request: Request) -> JSONResponse: > global current > headers = {"Cache-Control": "no-store"} > try: > if path == "stream" and request.method == "GET": > data = await mint_stream_async(os.environ["DEVICE_ID"]) > return JSONResponse(data, headers=headers) > if path == "task" and request.method == "POST": > body = await request.json() > task = body.get("task") > if not isinstance(task, str) or not task.strip(): > raise ValueError("Task required") > run = await device.run(task=task, max_steps=30) > current = run > try: > result = await run.wait() > except WaitError: > result = await run.get_status() > return JSONResponse({"status": result.status, "message": result.message, > "succeeded": result.succeeded}, headers=headers) > if path == "stop" and request.method == "POST" and current: > await current.stop() > return JSONResponse({}, headers=headers) > return JSONResponse({}, status_code=404, headers=headers) > except Exception: > return JSONResponse({"error": "Request failed"}, status_code=502, headers=headers) > ``` > > The React component runs in the browser with either server: > > ```tsx App.tsx theme={null} > import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react'; > import '@mobilerun/react/styles.css'; > import { useCallback, useEffect, useRef, useState } from 'react'; > import { createRoot } from 'react-dom/client'; > > function App() { > const controls = useRef(null); > const [stream, setStream] = useState<{ streamUrl?: string; streamToken?: string }>({}); > const [task, setTask] = useState('Open Settings and tell me the Android version.'); > const [result, setResult] = useState(''); > const [running, setRunning] = useState(false); > const loadStream = useCallback(async () => { > const response = await fetch('/api/stream', { cache: 'no-store' }); > if (response.ok) setStream(await response.json()); > }, []); > useEffect(() => { void loadStream(); }, [loadStream]); > async function run() { > setRunning(true); > setResult('Running…'); > try { > // The server answers when the task has ended. > const response = await fetch('/api/task', { method: 'POST', body: JSON.stringify({ task }) }); > if (!response.ok) throw new Error('Could not run task'); > setResult(JSON.stringify(await response.json(), null, 2)); > } catch (error) { setResult(String(error)); } > finally { setRunning(false); } > } > return
>

Your work device

>
>
>
> controls.current?.sendSystemKey(action)} /> >
>

Run task

>