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

# 项目工具

> 添加用于测试 API、数据准备和设备操作的工具。

项目工具是智能体在完成目标时可以调用的 AI SDK 工具，例如请求你的测试 API 或执行数据准备步骤。

## 添加工具

使用 `defineTool` 包装工具，并将其放入智能体的 `tools` 中：

```ts title="e2e.config.ts"

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;
```

现在，智能体可以在结账前填充购物车数据：

```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>
如果工具与语法动词（`tap`、`screenshot`）或测试执行框架添加的工具同名，配置加载会失败并报 `INVALID_CONFIG`。这些工具包括 `complete_step`、`locate`、`run_code`、`test_lines`、`start_recording`、`stop_recording` 和 `report_finding`。如果值不是由 `defineTool` 创建的，或在使用自定义 `executor` 的条目上设置了 `tools`，也会失败。
</Note>

## 声明工具的行为

`defineTool` 接收 AI SDK 工具和以下注解：

| 注解 | 含义 |
| --- | --- |
| `mutates: true` | 更改状态。调用会在执行前占用步骤操作预算中的一个名额，无论成功与否，并与其他操作按顺序运行。[回放缓存](https://e2e.com/docs/zh/cache)无法回放它，因此智能体会实时执行步骤的这一部分。 |
| `mutates: false` | 只读。运行时不占用操作名额，可以观察屏幕或读取节点属性。 |
| `platforms: ['ios', 'android']` | 仅在这些平台上提供工具。省略后会在所有测试目标上提供工具。 |

## 从工具中观察

只读工具可以通过 `getToolContext` 观察脱敏后的屏幕。此示例在像素可用时保存一张经过遮罩处理的截图，作为报告证据：

```ts

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()` 返回脱敏后的文本快照。`tree: true` 添加节点树，`pixels: true` 添加经过遮罩处理的截图，遵循内置智能体的规则。
- 在 `mutates: true` 的工具中，`observe()` 会失败并报 `POLICY_DENIED`。请在单独的只读工具中观察。
- `attachScreenshot(pixels, label)` 将图像添加到步骤的产物中，并返回其产物 ID。重复使用同一标签会覆盖之前的图像。

## 读取节点的计算样式

在只读工具中，使用 `context.read` 测量网页端引擎中已列出节点的渲染样式：

```ts
const context = getToolContext(executionOptions);
await context.observe();
const result = await context.read({ id: nodeId }, {
  style: ['color', 'font-weight', 'visibility', 'opacity'],
});
return result.style;
```

传入最新观察结果中的节点 ID。结果只包含请求的属性，机密值会像节点树中一样脱敏。属性值采用浏览器的计算 CSS 格式，例如红色为 `rgb(255, 0, 0)`。

请求[计算样式允许列表](https://e2e.com/docs/zh/reference/engine#rendered-node-properties)中的属性。自定义属性、生成内容、选择器和页面代码都会被拒绝。

读取使用步骤的截止时间，与观察和操作按顺序执行，不占用操作名额。它们测量原始元素的当前值，不会刷新观察结果，也不会等待值发生变化。计算后的 `visibility` 和 `opacity` 描述的是元素的 CSS，而非它是否被其他元素遮挡，或是否因祖先元素而不可见。

| 错误 | 触发条件 |
| --- | --- |
| `POLICY_DENIED` | `mutates: true` 的工具调用 `read`，或引擎没有 `readStyle` 方法，例如移动端引擎。 |
| `INVALID_ARGUMENT` | 选项或属性名无效。 |
| `LOCATOR_NOT_FOUND` | 没有语义观察结果、最新观察结果未列出该 ID，或元素已脱离页面。读取前请重新观察。 |
| `STEP_TIMEOUT` | 读取耗尽步骤的剩余时间，包括在截止时间发生的引擎超时。捕获读取错误也不能让步骤通过。 |

在测试上使用 `requires: ['computed-style']`，跳过不支持样式读取的测试目标。

## 设备工具包

`@e2e-dev/mobile` 提供现成的工具包 `mobileTools`，包含 `open_app`、`swipe` 和 `alert`。使用展开语法，在其旁边添加你自己的工具：

```ts
tools: { ...mobileTools(iphone, pixel), seedCart },
```

配置方式请参阅[智能体工具](https://e2e.com/docs/zh/mobile#agent-tools)。如果自定义工具需要原始驱动会话，可以通过 [`unstable_deviceSession`](https://e2e.com/docs/zh/reference/mobile#unstable_devicesession) 获取正在运行的设备客户端。

## 下一步

<CardGroup cols={2}>
  <Card title="自定义执行器" icon="gears" href="/executors">
    替换提示词或决策循环。
  </Card>
  <Card title="智能体步骤的工作原理" icon="stairs" href="/agent-steps">
    模型能看到什么，以及能做什么。
  </Card>
</CardGroup>
