본문으로 건너뛰기
Twexapi
한국어
Esc
이동열기⌘J미리보기
이 페이지에서

Mastra

TwexAPI MCP를 통해 트윗 검색, 프로필, 트렌드 및 검토된 X 쓰기 작업을 위한 TypeScript Mastra 에이전트를 구축합니다.

TwexAPI MCP 서버를 통해 Mastra Twitter API 에이전트를 구축합니다. 트윗을 검색하고, 프로필을 조회하며, 트렌드를 읽고, 쓰기 작업을 검토합니다. 채팅 전용 요약 대신 트윗 ID, 커서 및 경로 이름을 타입 JSON으로 보존합니다.

TwexAPI와 함께 Mastra를 사용하는 이유

Mastra는 TypeScript 에이전트 프레임워크입니다. TwexAPI는 exploretwexapi_request를 통해 엔드포인트 발견 및 인증된 호출을 제공합니다.

에이전트 작업 TwexAPI 경로 다음 단계를 위해 보존
트윗 검색 POST /twitter/advanced_search/page 쿼리, 트윗 ID, 작성자, created_at, 커서
프로필 조회 GET /twitter/{screen_name}/about 사용자 ID, 사용자명, 약력, 팔로워 수
트렌드 읽기 GET /twitter/global-trending/tweets 국가, 주제, 트윗 행
게시 또는 답글 POST /twitter/tweets/create 트윗 ID, 경로, 사람 승인, 쿠키 확인

이미 Vercel AI SDK 모델을 사용하는 TypeScript 앱에는 Mastra를 사용하세요. 모델이 필요 없는 예약 작업에는 TypeScript SDK 또는 CLI를 사용하세요.

전제조건

  • Node.js 20 이상
  • TwexAPI API 키
  • Mastra 지원 모델 제공자 키 Public docs focus on API-key reads.

공개 X 읽기에는 X Developer 자격 증명이 필요하지 않습니다. TwexAPI로 인증하세요.

설치

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

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

서버는 발견을 위한 explore와 인증된 호출을 위한 twexapi_request를 노출합니다. 인증되지 않은 MCP 요청은 401을 반환합니다.

전체 예제

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의 문서화된 querybody 필드만 twexapi_request에 전달하세요.

다음 조건 중 하나가 참이 되면 페이지네이션을 중지합니다.

  • 에이전트가 요청한 총량을 수집합니다.
  • has_more 또는 has_next_page가 false가 됩니다.
  • next_cursor가 누락되거나 반복됩니다.
  • 구성된 페이지 상한에 도달합니다.

tweet_id 또는 user_id로 트윗과 사용자를 중복 제거합니다.

재개 가능한 에이전트 핸드오프 유지

트윗 페이지

tweet_id, text, author_username, created_at, has_more, next_cursor, 원본 쿼리를 저장합니다.

프로필 행

user_id, username, name, description, 팔로워 수, 조회 입력을 저장합니다.

트렌드 행

국가, 주제, 트윗 ID, 참여 지표를 저장합니다.

쓰기 작업

경로, 미리보기 텍스트, 사람 승인을 저장합니다. 쿠키는 핸드오프 파일 밖에 보관하세요. 참조.

전체 체크리스트는 Agent MCP Handoff를 참조하세요.

오류 처리 구축

상태 의미 에이전트 결정
400 잘못된 경로 또는 매개변수 재시도 전에 요청을 수정합니다
401 API 키 누락 또는 유효하지 않음 중지하고 자격 증명을 교체합니다
403 액세스 거부 또는 크레딧 쓰기 일시 중지; Get Balance 확인
429 속도 제한 도달 백오프 후 동일 커서로 재개합니다
5xx 일시적 서버 오류 안전한 읽기에 제한된 백오프를 적용합니다

타임아웃 후 읽기 확인 없이 쓰기를 재시도하지 마세요. Error HandlingRate Limits를 참조하세요.

X 작업 전 승인 요구

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 --dry-run으로 미리보기한 다음 승인 후 REST 또는 TypeScript SDK를 통해 실행하세요.

여러 MCP 서버 연결

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 서버 이름을 안정적으로 유지하세요. 에이전트에는 현재 작업에 필요한 도구만 부여하세요.

패키지 버전

패키지 지원 범위
Node.js >=20
@mastra/core >=0.10
@mastra/mcp >=0.10

다음 단계

이 페이지가 도움이 되었나요?