Files
e2e/docs/tools.mdx
T
Mikolaj AdamowiczandOskar Kwaśniewski 984f139d7c feat(mobile): let custom tools call agent-device through deviceSession (#1584)
* feat(mobile): export agent-device from @e2e-dev/mobile/agent-device

Custom tools that extend the mobile engine with agent-device calls have
to import `agent-device` directly. pnpm does not resolve that import
from a transitive dependency, so the project installs agent-device
itself and has to keep it at the exact version @e2e-dev/mobile pins,
because two versions do not share one daemon.

The new subpath re-exports what a tool commonly needs from the engine's
copy: `createAgentDeviceClient`, the error helpers (`AppError`,
`isAgentDeviceError`, `normalizeAgentDeviceError`), `centerOfRect`, and
the types for the client, snapshots, screenshots, targets, gestures,
text entry, alerts, and waits. `ensureDaemon` and `startAgentDevice`
stay out because the engine owns the daemon.

The install smoke imports the subpath from a fresh pnpm project with no
agent-device dependency and checks there is one agent-device install.
The e2e skill tells agents to use this import instead of adding
agent-device.

* docs(mobile): mark @e2e-dev/mobile/agent-device unstable, point tests to unstable_raw

A client built with `createAgentDeviceClient` does not get the engine's
daemon, lease, or per-worker session name, so the docs no longer say it
drives the engine's session. Tests use `device.unstable_raw.client`.
The subpath is agent-device's API at the pinned version, so it is
labeled unstable like `unstable_raw`.

* chore(mobile): shorten the agent-device subpath comments

* feat(mobile): give custom tools the running device session

A custom tool had no way to reach the engine's agent-device client, and
a client built from `createAgentDeviceClient` misses the engine's
daemon, lease, and per-worker session. `deviceSession(...engines)` on
`@e2e-dev/mobile/tools` returns the running attempt's `DeviceSession`,
the object a test reads from `device.unstable_raw`, using the lookup
`mobileTools` already had.

From review: `@e2e-dev/mobile/agent-device` drops the client factory and
keeps the types and error helpers. The skill line is scoped to these
imports, and the stale Limrun peer line is fixed. The export-map test
checks every entry's paths, the install smoke stops reading the `.pnpm`
layout, and the docs keep one full description in the reference.

* fix(mobile): spread the device selection in the deviceSession example

The docs example called `settings.update` without the session's
`selection`, unlike every engine call, so it could miss the worker's
device before an app is open. Also restores `createDeviceFixture`'s
JSDoc and tests the several-attempts refusal of `deviceSession`.

* refactor(mobile): keep raw sessions behind a neutral unstable API

* fix(mobile): type the unstable raw session client

---------

Co-authored-by: Oskar Kwaśniewski <oskar@okwasniewski.com>
2026-11-11 17:52:58 +00:00

133 lines
4.6 KiB
Plaintext

---
title: Project tools
description: Add tools for test APIs, data setup, and device operations.
"og:image": "https://e2e.com/docs/images/og/tools.png?v=8747047102"
"twitter:image": "https://e2e.com/docs/images/og/tools.png?v=8747047102"
---
A project tool is an AI SDK tool that the agent can call during a goal, such
as a request to your test API or a data setup step.
## Add a tool
Wrap the tool with `defineTool` and put it in the agent's `tools`:
```ts title="e2e.config.ts"
import type { E2EConfig } from 'e2e';
import { defineTool } from 'e2e/agent';
import { web } from '@e2e-dev/web';
import { gateway, tool } from 'ai';
import { z } from 'zod';
const APP_URL = process.env.APP_URL ?? 'http://localhost:3000';
const seedCart = defineTool(
tool({
description: 'Seed the cart with a SKU via the store test API',
inputSchema: z.object({ sku: z.string() }),
execute: async ({ sku }) => {
const response = await fetch(`${APP_URL}/api/test/cart?sku=${encodeURIComponent(sku)}`);
if (!response.ok) throw new Error(`Cart seeding failed: HTTP ${response.status}`);
return response.text();
},
}),
{ mutates: true },
);
export default {
targets: [{ engine: web(), app: { url: APP_URL } }],
agents: { default: { model: gateway('openai/gpt-6-luna-fast'), tools: { seedCart } } },
} satisfies E2EConfig;
```
The agent can now seed a cart before it checks out:
```ts
await agent.act('seed the cart with SKU {sku}, then check out', {
params: { sku: 'SHIRT-BLUE-M' },
});
await expect(screen.getByText('Order confirmed')).toBeVisible();
```
<Note>
The config load fails with `INVALID_CONFIG` for a tool named like a
grammar verb (`tap`, `screenshot`) or a tool the harness adds:
`complete_step`, `locate`, `run_code`, `test_lines`, `start_recording`,
`stop_recording`, or `report_finding`. It also fails for a value
`defineTool` didn't build, and for `tools` on an entry with a custom
`executor`.
</Note>
## Declare what a tool does
`defineTool` takes the AI SDK tool and these annotations:
| Annotation | Meaning |
| --- | --- |
| `mutates: true` | Changes state. The call takes a slot of the step's action budget before it runs, failed or not, and runs in order with the other actions. The [replay cache](/cache) can't replay it, so the agent runs that part of the step live. |
| `mutates: false` | Read-only. Runs without an action slot and may observe the screen. |
| `platforms: ['ios', 'android']` | Offers the tool only on those platforms. Omit it to offer the tool on every target. |
## Observe from a tool
A read-only tool can observe the redacted screen through `getToolContext`.
This example saves a masked screenshot as report evidence when pixels are
available:
```ts
import { randomUUID } from 'node:crypto';
import { defineTool, getToolContext } from 'e2e/agent';
import { tool } from 'ai';
import { z } from 'zod';
const captureEvidence = defineTool(
tool({
description: 'Save a screenshot as evidence in the report',
inputSchema: z.object({}),
execute: async (_input, executionOptions) => {
const context = getToolContext(executionOptions);
const observation = await context.observe({ pixels: true });
const pixels = observation.pixels;
if (pixels === undefined) {
return { withheld: observation.pixelsWithheld ?? 'UNSUPPORTED_CAPABILITY' };
}
const id = await context.attachScreenshot(pixels, `evidence-${randomUUID()}`);
return { evidence: id };
},
}),
{ mutates: false },
);
```
- `observe()` returns a redacted text snapshot. `tree: true` adds the node
tree and `pixels: true` a masked screenshot, under the built-in agent's
rules.
- In a `mutates: true` tool, `observe()` fails with `POLICY_DENIED`.
Observe in a separate read-only tool.
- `attachScreenshot(pixels, label)` adds the image to the step's artifacts
and returns its artifact id. A reused label overwrites the earlier image.
## Device toolkits
`@e2e-dev/mobile` has a ready tool pack, `mobileTools`, with `open_app`,
`swipe`, and `alert`. Spread it to add your own tools beside it:
```ts
tools: { ...mobileTools(iphone, pixel), seedCart },
```
See [Agent tools](/mobile#agent-tools) for the setup. A tool of your own
that needs a raw driver session gets the running device's client from
[`unstable_deviceSession`](/reference/mobile#unstable_devicesession).
## Next
<CardGroup cols={2}>
<Card title="Custom executors" icon="gears" href="/executors">
Replace the prompt or decision loop.
</Card>
<Card title="How agent steps work" icon="stairs" href="/agent-steps">
What the model sees and what it may do.
</Card>
</CardGroup>