---
title: "Mastra"
description: "通过 TwexAPI MCP 构建 TypeScript Mastra AI Agent，实现推文搜索、资料查询、趋势读取与经审核的 X 写操作。"
---

通过 TwexAPI 的 MCP 服务器构建 Mastra Twitter API AI Agent。搜索推文、查看资料、读取趋势并审核写操作。将 tweet ID、游标与路由名保留为类型化 JSON，而非仅聊天摘要。

## 为何将 Mastra 与 TwexAPI 搭配使用？

Mastra 是 TypeScript AI Agent框架。TwexAPI 通过 `explore` 与 `twexapi_request` 提供端点发现与认证调用。

| AI Agent任务 | TwexAPI 路由 | 为下一步保留 |
| --- | --- | --- |
| 搜索推文 | `POST /twitter/advanced_search/page` | 查询、tweet ID、作者、`created_at`、游标 |
| 查看资料 | `GET /twitter/{screen_name}/about` | 用户 ID、用户名、简介、粉丝数 |
| 读取趋势 | `GET /twitter/global-trending/tweets` | 国家、主题、推文行 |
| 发帖或回复 | `POST /twitter/tweets/create` | Tweet ID、路由、人工审批、cookie 确认 |

已使用 Vercel AI SDK 模型的 TypeScript 应用用 Mastra。无需模型的定时作业请用 [TypeScript SDK](/sdks/typescript) 或 [CLI](/sdks/cli)。

## 前置条件

- Node.js 20 或更高版本
- [TwexAPI API 密钥](https://twexapi.io/dashboard)
- Mastra 支持的模型提供商密钥
- 写操作所需的 Twitter cookie 或 `auth_token` — 见

公开 X 读取无需 X Developer 凭证，使用 TwexAPI 认证即可。

## 安装

```bash
npm install @mastra/core @mastra/mcp @ai-sdk/openai dotenv
```

```txt .env
TWEXAPI_API_KEY=YOUR_API_KEY
OPENAI_API_KEY=sk-...
```

## 连接 TwexAPI MCP

```ts
import "dotenv/config";
import { MCPClient } from "@mastra/mcp";

export const twexapiMcp = new MCPClient({
  servers: {
    twexapi: {
      url: new URL("https://api.twexapi.io/mcp"),
      requestInit: {
        headers: {
          "x-api-key": process.env.TWEXAPI_API_KEY!,
        },
      },
    },
  },
});
```

服务器暴露 `explore` 用于发现、`twexapi_request` 用于认证调用。未认证 MCP 请求返回 `401`。

## 完整示例

```ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { writeFile } from "node:fs/promises";
import { twexapiMcp } from "./mcp";

type TweetRow = {
  tweet_id: string;
  text: string;
  author_username?: string;
  created_at?: string;
};

type TweetSearchHandoff = {
  query: string;
  route_used: string;
  tweets: TweetRow[];
  has_more: boolean;
  next_cursor: string | null;
  stop_reason: "complete" | "requested_limit" | "cursor_stalled" | "page_cap";
};

const tools = await twexapiMcp.listTools();

export const twexapiAgent = new Agent({
  name: "twexapi-agent",
  instructions: `
    Use TwexAPI MCP for Twitter API requests.
    Call explore before twexapi_request.
    Preserve exact IDs and cursors. Never invent missing tweet fields.
    Ask for confirmation before read_only: false actions.
    Return only valid JSON matching the handoff contract.
  `,
  model: openai("gpt-4o-mini"),
  tools,
});

const result = await twexapiAgent.generate(
  `Search 25 recent tweets about Mastra MCP.
Return JSON with query, route_used, tweets[{tweet_id,text,author_username,created_at}],
has_more, next_cursor, and stop_reason.`
);

const handoff = JSON.parse(result.text) as TweetSearchHandoff;
await writeFile(
  "twexapi-mastra-handoff.json",
  JSON.stringify(handoff, null, 2),
  "utf8"
);
```

另一工作流消费前校验 JSON。对话历史不是作业数据库。

## 保留 MCP 响应契约

仅将 `explore` 中文档化的 `query` 与 `body` 字段传入 `twexapi_request`。

满足以下任一条件时停止分页：

- AI Agent已收集请求总量。
- `has_more` 或 `has_next_page` 为 false。
- `next_cursor` 缺失或重复。
- 达到配置的页面上限。

按 `tweet_id` 或 `user_id` 对推文与用户去重。

## 保持可恢复的AI Agent handoff

<CardGroup cols={2}>
  <Card title="推文分页数据" icon="message-square">
    存储 `tweet_id`、`text`、`author_username`、`created_at`、`has_more`、`next_cursor` 与原始查询。
  </Card>
  <Card title="用户资料数据" icon="user-round">
    存储 `user_id`、`username`、`name`、`description`、粉丝数与查找输入。
  </Card>
  <Card title="趋势话题榜单" icon="radio">
    存储国家、主题、tweet ID 与互动指标。
  </Card>
  <Card title="写入操作 (发推/点赞/关注)" icon="send">
    存储路由、预览文本与人工审批。cookie 勿写入 handoff 文件。见。
  </Card>
</CardGroup>

完整清单见 [Agent MCP Handoff](/mcp/agent-handoff)。

## 构建错误处理

| 状态 | 含义 | AI Agent决策 |
| --- | --- | --- |
| `400` | 无效路由或参数 | 重试前修正请求 |
| `401` | API 密钥缺失或无效 | 停止并更换凭证 |
| `403` | 访问被拒或额度不足 | 暂停写操作；查 [Get Balance](/api-reference/balance-endpoints/get-balance-api-balance-get) |
| `429` | 达到速率限制 | 退避后从同一游标继续 |
| `5xx` | 临时服务故障 | 对安全读取应用有界退避 |

超时后重试写操作前须 read-back 检查。见 [Error Handling](/guides/error-handling) 与 [Rate Limits](/guides/rate-limits)。

## X 操作前要求审批

```txt
Call explore with include_writes true only when the user asked to post, like, follow, or DM.
Stop before any read_only: false call.
Show method, path, tweet text or target username, and media URLs.
Do not send cookie values in the model output.
```

用 [CLI](/sdks/cli) `--dry-run` 预览，审批后通过 REST 或 TypeScript SDK 执行。

## 连接多个 MCP 服务器

```ts
export const mcp = new MCPClient({
  servers: {
    twexapi: {
      url: new URL("https://api.twexapi.io/mcp"),
      requestInit: {
        headers: { "x-api-key": process.env.TWEXAPI_API_KEY! },
      },
    },
    twexapiDocs: {
      url: new URL("https://docs.twexapi.io/mcp"),
    },
  },
});
```

保持 TwexAPI 服务器名稳定。仅向AI Agent提供当前任务所需工具。

## 包版本

| 包 | 支持范围 |
| --- | --- |
| Node.js | `>=20` |
| `@mastra/core` | `>=0.10` |
| `@mastra/mcp` | `>=0.10` |

## 下一步

- [MCP Tools](/mcp/tools)
- [Agent MCP Handoff](/mcp/agent-handoff)
-
- [TypeScript SDK](/sdks/typescript)
- [Advanced Twitter Search](/api-reference/search-endpoints/get-data-page-twitter-advanced-search-page-post)
