---
title: "Mastra"
description: "TwexAPI MCP 経由で TypeScript Mastra エージェントを構築し、ツイート検索、プロフィール、トレンド、レビュー済み X 書き込みを実現する。"
---

TwexAPI の MCP サーバー経由で Mastra Twitter API エージェントを構築します。ツイート検索、プロフィール確認、トレンド読み取り、書き込みアクションのレビューが可能です。ツイート ID、カーソル、ルート名をチャット要約ではなく型付き JSON として保持してください。

## TwexAPI と Mastra を組み合わせる理由

Mastra は TypeScript エージェントフレームワークです。TwexAPI は `explore` と `twexapi_request` 経由でエンドポイント発見と認証済み呼び出しを提供します。

| Agent task | TwexAPI route | Preserve for the next step |
| --- | --- | --- |
| ツイート検索 | `POST /twitter/advanced_search/page` | クエリ、ツイート ID、著者、`created_at`、カーソル |
| プロフィール確認 | `GET /twitter/{screen_name}/about` | ユーザー ID、ユーザー名、略歴、フォロワー数 |
| トレンド読み取り | `GET /twitter/global-trending/tweets` | 国、トピック、ツイート行 |
| 投稿または返信 | `POST /twitter/tweets/create` | ツイート ID、ルート、人間の承認、cookie 確認 |

Vercel AI SDK モデルをすでに使用する TypeScript アプリには Mastra を使用してください。モデルが不要なスケジュールジョブには [TypeScript SDK](/sdks/typescript) または [CLI](/sdks/cli) を使用してください。

## 前提条件

- Node.js 20 以降
- [TwexAPI API キー](https://twexapi.io/dashboard)
- Mastra 対応モデルプロバイダーの API キー
Public docs focus on API-key reads.

公開 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` に渡してください。

次のいずれかが真になったらページネーションを停止します。

- エージェントが要求総数を収集した。
- `has_more` または `has_next_page` が false になった。
- `next_cursor` が欠落または繰り返された。
- 設定されたページ上限に達した。

`tweet_id` または `user_id` でツイートとユーザーを重複排除します。

## 再開可能なエージェントハンドオフを保持

<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">
    国、トピック、ツイート ID、エンゲージメントメトリクスを保存。
  </Card>
  <Card title="書き込みアクション" icon="send">
    ルート、プレビューテキスト、人間の承認を保存。cookie はハンドオフファイル外に保持。 を参照。
  </Card>
</CardGroup>

完全なチェックリストは [Agent MCP Handoff](/mcp/agent-handoff) を参照してください。

## エラー処理を構築

| ステータス | 意味 | エージェントの判断 |
| --- | --- | --- |
| `400` | 無効なルートまたはパラメータ | リトライ前にリクエストを修正 |
| `401` | API キー欠落または無効 | 停止し、認証情報を差し替え |
| `403` | アクセス拒否またはクレジット | 書き込みを一時停止。[Get Balance](/api-reference/balance-endpoints/get-balance-api-balance-get) を確認 |
| `429` | レート制限到達 | バックオフ後、同じカーソルから再開 |
| `5xx` | 一時的なサーバー障害 | 安全な読み取りに上限付きバックオフを適用 |

タイムアウト後の書き込みを読み戻しチェックなしでリトライしないでください。[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 サーバー名は安定させてください。エージェントには現在のジョブに必要なツールのみを付与してください。

## パッケージバージョン

| Package | Supported range |
| --- | --- |
| 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)
