Skip to content
Twexapi
English
Esc
↑↓navigate↵open⌘Jpreview
On this page

Mastra

Build TypeScript Mastra agents for tweet search, profiles, trends, and reviewed X writes through TwexAPI MCP.

Build a Mastra Twitter API agent through TwexAPI’s MCP server. Search tweets, inspect profiles, read trends,. Preserve tweet IDs, cursors, and route names as typed JSON instead of chat-only summaries.

Why use Mastra with TwexAPI?

Mastra is a TypeScript agent framework. TwexAPI supplies endpoint discovery and authenticated calls through explore and twexapi_request.

Agent task TwexAPI route Preserve for the next step
Search tweets POST /twitter/advanced_search/page Query, tweet IDs, authors, created_at, cursor
Inspect a profile GET /twitter/{screen_name}/about User ID, username, biography, follower count
Read trends GET /twitter/global-trending/tweets Country, topic, tweet rows
Post or reply POST /twitter/tweets/create Tweet ID, route, human approval

Use Mastra for TypeScript apps that already use Vercel AI SDK models. Use the TypeScript SDK or CLI for scheduled jobs that need no model.

Prerequisites

  • Node.js 20 or later
  • A TwexAPI API key
  • A Mastra-supported model provider key

Public X reads need no X Developer credentials. Authenticate with TwexAPI.

Install

npm install @mastra/core @mastra/mcp @ai-sdk/openai dotenv
TWEXAPI_API_KEY=YOUR_API_KEY
OPENAI_API_KEY=sk-...

Connect TwexAPI MCP

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!,
        },
      },
    },
  },
});

The server exposes explore for discovery and twexapi_request for authenticated calls. Unauthenticated MCP requests return 401.

Full example

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"
);

Validate the JSON before another workflow consumes it. Conversation history is not a job database.

Preserve the MCP response contract

Pass only documented query and body fields from explore into twexapi_request.

Stop pagination when one condition becomes true:

  • The agent collects the requested total.
  • has_more or has_next_page becomes false.
  • next_cursor is missing or repeats.
  • The configured page cap is reached.

Deduplicate tweets and users by tweet_id or user_id.

Keep a resumable agent handoff

Tweet pages

Store tweet_id, text, author_username, created_at, has_more, next_cursor, and the original query.

Profile rows

Store user_id, username, name, description, follower counts, and the lookup input.

Trend rows

Store country, topic, tweet IDs, and engagement metrics.

Write actions

Store route, preview text, and human approval. Keep API keys out of the handoff file.

See Agent MCP Handoff for the full checklist.

Build error handling

Status Meaning Agent decision
400 Invalid route or parameters Fix the request before retrying
401 Missing or invalid API key Stop and replace the credential
403 Access denied or credits Pause writes; check Get Balance
429 Rate limit reached Back off, then resume the same cursor
5xx Temporary server failure Apply bounded backoff to safe reads

Never retry a write after a timeout without a read-back check. See Error Handling and Rate Limits.

Require approval before X actions

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.

Preview with the CLI --dry-run, then execute through REST or the TypeScript SDK after approval.

Connect multiple MCP servers

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"),
    },
  },
});

Keep the TwexAPI server name stable. Give the agent only the tools required for the current job.

Package versions

Package Supported range
Node.js >=20
@mastra/core >=0.10
@mastra/mcp >=0.10

Next steps

Was this page helpful?