AI エージェントに Twitter リーダーを持たせる: Claude、ChatGPT、Codex 向けの MCP とツール定義

AI エージェントに Twitter リーダーを持たせる: Claude、ChatGPT、Codex 向けの MCP とツール定義
Unif Agents team
Unif Agents team

更新日

UnifAPI MCP サーバーを接続するか、有料 X API 用のツール定義を貼れば、Claude・ChatGPT・Codex が公開 X のプロフィール、投稿、返信、検索を読めます。

要点: エージェントが X を読むには 4 つのものが要ります。ハンドルや投稿リンクで呼び出せるオペレーション、読める JSON の本文、分岐できるエラー、そして見えるコストです。この 4 つをいちばん簡単にそろえる方法が UnifAPI MCP サーバーです。Claude、ChatGPT、Codex に https://mcp.unifapi.com を追加し、クライアントに求められたら OAuth でサインインすれば(貼り付けるキーはありません)、エージェントは call_api で X を読みます。料金は従量課金で、返されたレコード 1 件につき 1 クレジット($0.001)です。エージェントのループを自分で動かす場合のために、以下に Anthropic のツール使用と OpenAI の関数呼び出し用のコピペできる定義(有料 X API を呼ぶハンドラー付き)、Claude Code と Codex 向けの SKILL.md、そしてモデルに必要な 3 つのルールを載せます。ページングの前にクレジットを数える、Retry-After の分だけ待つ、コンテキストウィンドウに入れるものを絞る、です。

モデルはすでに X の読み方を知っています。Claude や ChatGPT に @NASA が今週何を投稿したか尋ねれば、試みはします。Web 検索、x.com のフェッチ、ことによると学習データにあった Nitter の URL。検索が返すのは要約、フェッチが返すのは JavaScript のシェル、Nitter のインスタンスはもうありません。モデルはそこで推測するか、謝ります。

解決策は賢いモデルではなく、モデルが呼び出せるオペレーションと、パースできる本文を持つツールです。この記事はそのツールを、実際に人が使っている形式で示します。まず MCP サーバー、次に自分で組み込むツールです。

まず MCP サーバーを接続する

エージェントが Claude、ChatGPT、Codex で動いているなら、ツールを書く必要はまったくありません。UnifAPI MCP サーバーを追加すれば、エージェントは 3 つのツールを手にします。カタログを検索する list_operations、オペレーション 1 つのパラメータを読む get_operation、それを実行する call_api です。Cursor などを含むクライアントごとの手順は unifapi.com/mcp にあります。要約すると次のとおりです。

  • Claude: Settings → Connectors → Add custom connector。名前を UnifAPI にして https://mcp.unifapi.com を貼り付け、Authentication は OAuth のままにして、Add して Connect します。
  • ChatGPT: Plus、Pro、Team、Enterprise のいずれかのプランで Developer Mode を有効にし(Settings → Connectors → Advanced)、Create app をクリックして、同じ URL を MCP Server URL に貼り付け、Authentication は OAuth のままにします。
  • Codex: codex mcp add unifapi --url https://mcp.unifapi.com を実行し、サインインが自動で開かなかった場合は codex mcp login unifapi を実行します(詳しくは Codex の MCP 設定)。
  • Claude Code: claude mcp add --transport http unifapi https://mcp.unifapi.com を実行します。

クライアントが UnifAPI ワークスペース用のブラウザのサインインを開きます。貼り付けるキーはありません。呼び出しはワークスペースクレジットを消費する従量課金です。あとは普通の言葉で尋ねれば(「@NASA が最近投稿した写真や動画付きの投稿は?」)、エージェントは次のような呼び出しを行います。

{
  "path": "/x/tweets/search/recent",
  "method": "GET",
  "query": { "query": "from:nasa filter:media", "max_results": 20 }
}

この呼び出しは最大 20 件の投稿を返し、コストは最大 20 クレジット($0.02)です。サーバーの詳細は MCP ドキュメントにあります。

X のオペレーション

エージェントが call_api で呼んでも、自前のハンドラーが HTTP で呼んでも、X の読み取りは有料 X API の同じ GET オペレーションです(リファレンスは unifapi.com/apis/twitter、完全な仕様は https://api.unifapi.com/openapi.json)。

照会オペレーションパラメータ返すもの
プロフィール/x/users/by/username/{username}username(@ なし)数値の id と指標を含むプロフィール 1 件
タイムライン/x/users/{id}/tweetsmax_results(1–100)、pagination_token、excludeアカウントの投稿、新しい順
投稿/x/tweets/{id}id著者、メディア、指標を含む投稿 1 件
メディア/x/tweets/search/recentquery=from:<handle> filter:mediaアカウントの最近の写真・動画投稿
返信/x/tweets/search/recentquery=conversation_id:<post id>投稿への公開返信
検索/x/tweets/search/recentquery、max_results(1–100)、pagination_token最近の投稿。X の検索演算子が使える
トレンド/x/trends/by/woeid/{woeid}woeid(1 は全世界)、max_trends(1–50)今トレンドのもの
コミュニティ/x/communities/searchqueryトピックに関する X コミュニティ
フォロワー/x/users/{id}/followers、/x/users/{id}/followingmax_results(1–100)、pagination_tokenアカウントのフォロワー、またはフォロー中の相手

レスポンスはすべて同じエンベロープです。

{
  "request_id": "…",
  "data": [ … ],
  "pagination": { "has_more": true, "next_cursor": "…" },
  "billing": { "credits_charged": 20, "records_charged": 20, "balance_remaining": 1980, "truncated_due_to_balance": false }
}

data は単一の項目ならオブジェクト、リストなら配列で、pagination はリストに付きます。次のページは next_cursor を pagination_token として渡して取得します。フィールド名は X API v2 に従います。投稿には text、created_at、conversation_id、public_metrics、author があり、ユーザーには username、description、public_metrics.followers_count があります。エラーはすべて { error: { type, message } } で、型は閉じた集合です(unauthorized、insufficient_credits、not_found、rate_limited、upstream_error ほか数種)。すべての HTTP レスポンスに RateLimit-* と X-RateLimit-* ヘッダーが付き、429 には Retry-After が加わります。

コストは返されたレコード 1 件につき 1 クレジット($0.001)、1 回の呼び出しにつき最低 1 クレジットです。プロフィール 1 件や投稿 1 件は 1 クレジット、プロフィールと投稿 10 件で 11、20 件の検索ページで 20($0.02)。サブスクリプションはありません。

以前 /tools/x/ 以下の旧無料エンドポイントを使っていた場合、これらの URL は 2026 年 10 月 17 日から、スクリプトやエージェントに HTTP 402 を返し、本文には MCP サーバーと、各照会を置き換える有料のオペレーションが示されます。X プロフィールビューアなどのビューアページは、ブラウザでは引き続き無料です。MCP サーバー(https://mcp.unifapi.com)または X API 経由では、返されたレコード 1 件につき 1 クレジット($0.001)、1 回の呼び出しにつき最低 1 クレジットが課金されるので、プロフィールと最新の投稿 10 件で 11 クレジット($0.011)です。

Anthropic のツール使用

自分で動かすエージェントのループでは、同じ読み取りがツール 1 つと、環境変数から読んだワークスペース API キーで https://api.unifapi.com を呼ぶハンドラーになります。キーは api.unifapi.com/sign-in でサインインし、/dashboard/billing でチャージして、/dashboard/api-keys で作成します。X のどのビューアページにもある Connect ボタンを使えば、この 3 つを 1 つの流れで済ませられます。

lookup の enum を持つツール 1 つのほうが、4 つのツールよりモデルには単純です。しかも各照会は決まったオペレーションに対応するので、モデルが自分でパスを組み立てることはありません。profile は /x/users/by/username/{username} を呼び(posts を指定すると /x/users/{id}/tweets も)、post は /x/tweets/{id} を呼び、replies は /x/tweets/search/recent で conversation_id:<post id> を検索し、search は同じ検索に q を渡します。

{
  "name": "read_x",
  "description": "Read public X (Twitter) data through the UnifAPI X API: a profile (optionally with its recent posts), one post, the replies under a post, or a search over recent posts (X operators like from:, since:, min_faves:, filter:media work). Each returned record costs 1 credit ($0.001), minimum 1 per call, so ask for the fewest results that answer the question. Returns JSON with data, pagination and billing. Pass cursor from a previous result to page, only when the answer needs more.",
  "input_schema": {
    "type": "object",
    "properties": {
      "lookup": { "type": "string", "enum": ["profile", "post", "replies", "search"] },
      "handle": { "type": "string", "description": "X handle without the @ (profile)" },
      "posts": {
        "type": "integer",
        "minimum": 0,
        "maximum": 100,
        "description": "Recent posts to include with a profile; 0 for the profile only"
      },
      "id": { "type": "string", "description": "Post ID or x.com status URL (post, replies)" },
      "q": { "type": "string", "description": "Search query; X operators work (search)" },
      "max_results": {
        "type": "integer",
        "minimum": 1,
        "maximum": 100,
        "description": "Page size for replies and search; default 10"
      },
      "cursor": { "type": "string", "description": "next_cursor from a previous result" }
    },
    "required": ["lookup"]
  }
}

ハンドラーは、認証付きの fetch 1 つを包む小さな switch です。

const API = "https://api.unifapi.com";

type ReadXInput = {
  lookup: "profile" | "post" | "replies" | "search";
  handle?: string;
  posts?: number;
  id?: string;
  q?: string;
  max_results?: number;
  cursor?: string;
};

// A post ID from an ID or an x.com status URL.
const postId = (value = "") => value.match(/status\/(\d+)/)?.[1] ?? value.trim();

async function gateway(path: string, query: Record<string, string | number | undefined> = {}) {
  const qs = new URLSearchParams();
  for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== "") qs.set(k, String(v));
  const res = await fetch(`${API}${path}?${qs}`, {
    headers: { Authorization: `Bearer ${process.env.UNIFAPI_API_KEY}` },
  });
  const body = await res.json();
  if (res.status === 429)
    return { error: body.error, retryAfterSeconds: Number(res.headers.get("Retry-After")) };
  return body; // { data, pagination?, billing } on success, { error: { type, message } } otherwise
}

async function readX(input: ReadXInput) {
  const page = { max_results: input.max_results ?? 10, pagination_token: input.cursor };
  switch (input.lookup) {
    case "profile": {
      const handle = (input.handle ?? "").replace(/^@/, "");
      const profile = await gateway(`/x/users/by/username/${encodeURIComponent(handle)}`);
      if (!input.posts || profile.error) return profile;
      const posts = await gateway(`/x/users/${profile.data.id}/tweets`, {
        max_results: input.posts,
        pagination_token: input.cursor,
      });
      return { profile, posts }; // 1 credit for the profile, 1 per post
    }
    case "post":
      return gateway(`/x/tweets/${encodeURIComponent(postId(input.id))}`);
    case "replies":
      return gateway("/x/tweets/search/recent", {
        query: `conversation_id:${postId(input.id)}`,
        ...page,
      });
    case "search":
      return gateway("/x/tweets/search/recent", { query: input.q, ...page });
  }
}

ゲートウェイの billing ブロックをそのままモデルに返すのは意図的です。呼び出しのたびに credits_charged と balance_remaining が見えるモデルは、ページングをやめて手元にあるもので答えるのに必要な情報を持っています。

OpenAI の関数呼び出し

同じ形を、OpenAI のラッパーで。

{
  "type": "function",
  "function": {
    "name": "read_x",
    "description": "Read public X (Twitter) data through the UnifAPI X API. lookup=profile|post|replies|search. Costs 1 credit ($0.001) per returned record, minimum 1 per call: keep max_results small and pass cursor only when the answer needs more. Returns JSON with data, pagination { has_more, next_cursor } and billing { credits_charged, balance_remaining }.",
    "parameters": {
      "type": "object",
      "properties": {
        "lookup": { "type": "string", "enum": ["profile", "post", "replies", "search"] },
        "handle": { "type": "string" },
        "posts": { "type": "integer", "minimum": 0, "maximum": 100 },
        "id": { "type": "string" },
        "q": { "type": "string" },
        "max_results": { "type": "integer", "minimum": 1, "maximum": 100 },
        "cursor": { "type": "string" }
      },
      "required": ["lookup"]
    }
  }
}

上の readX ハンドラーはそのまま使えます。呼び出しの arguments 文字列をパースして、オブジェクトを渡すだけです。

Claude Code と Codex 向けの SKILL.md

MCP サーバーに接続したコーディングエージェントは、すでにツールを持っています。足りないのは、X のためにどのオペレーションを呼ぶか、それぞれいくらかかるかという知識です。プロジェクト内のスキルファイルがそれを教えます。

---
name: read-x
description: Read public X (Twitter) profiles, posts, replies, search, trends, communities and followers through the UnifAPI MCP tools (list_operations, get_operation, call_api). Use when a task needs what an account or post says on X.
---

# Reading X

Use the UnifAPI MCP server (https://mcp.unifapi.com, OAuth sign-in, setup at
https://unifapi.com/mcp). Run call_api with method GET and one of these paths; get_operation
on a path lists every parameter.

- /x/users/by/username/{username} one profile; its id feeds the paths below
- /x/users/{id}/tweets max_results, pagination_token, exclude=replies: recent posts
- /x/tweets/{id} one post
- /x/tweets/search/recent query=conversation_id:<post id> replies under a post
- /x/tweets/search/recent query=from:nasa filter:media, max_results: search; X operators work
- /x/trends/by/woeid/{woeid} max_trends: trending now (woeid 1 = worldwide)
- /x/communities/search query: X Communities for a topic
- /x/users/{id}/followers, /x/users/{id}/following

Every returned record costs 1 credit ($0.001), minimum 1 per call. Start with max_results
10-20 and pass pagination.next_cursor as pagination_token only when the answer needs more.
Results are { data, pagination { has_more, next_cursor }, billing { credits_charged,
balance_remaining } }. Errors are { error: { type, message } }. A 402 means the workspace is
out of credits: tell the user to top up at payment.top_up_url from the result, then retry.
Without MCP, the same paths work on https://api.unifapi.com with
Authorization: Bearer $UNIFAPI_API_KEY. Reference: https://unifapi.com/apis/twitter

このファイルがあれば、「@NASA が今週投稿したものを確認して、一番人気の投稿への返信を要約して」は、エージェントが自分で書く call_api 呼び出し 2 回になります。from:nasa の検索と、いいねが最も多い投稿に対する conversation_id: の検索です。max_results を 10 と 20 にすれば、最大 30 クレジット、3 セントです。

モデルのための 3 つのルール

  1. ページングの前にクレジットを数える。 返されたレコードは 1 件ごとに 1 クレジット($0.001)、1 回の呼び出しにつき最低 1 クレジットで、すべてのレスポンスがそれを示します。その呼び出しの分は billing.credits_charged、残りは billing.balance_remaining です。プロフィールと投稿 10 件で 11 クレジット、20 件の検索ページで 20、100 件のページを 1 つ追加するごとにさらに 100 です。質問に答えられる最小の max_results を指定し、答えにもっと必要なときだけ next_cursor をたどってください。残高が足りなくなると、リストの呼び出しは返すレコードを減らして truncated_due_to_balance を立てます。残高がマイナスになることはありません。
  2. Retry-After の分だけ待つ。ループで再試行しない。 キーごとの既定の上限は 1 分あたり 60 リクエストで、RateLimit-* と X-RateLimit-* ヘッダーで数えられます。429 の rate_limited には Retry-After が加わります。402 の insufficient_credits も再試行するものではありません。api.unifapi.com/dashboard/billing でチャージしてから(MCP 経由なら結果に payment.top_up_url が入っています)、同じ呼び出しを繰り返す、という合図です。
  3. コンテキストウィンドウに入れるものを絞る。 投稿には public_metrics、attachments、edit_history_tweet_ids、author オブジェクト、media のバリアントが付いてきます。読むための結果なら、text、author.username、created_at、public_metrics と billing ブロックだけ残します。モデルがデータをフィルタ、ソート、または別のツールへ渡すときは、JSON をまるごと残します。

MCP か、自前のツールか

エージェントがすでに MCP を話せるなら、サーバーを接続するほうが上のどのツールより手間がかからず、カバー範囲も広くなります。これらの X オペレーションを提供するのと同じカタログに、X API の残り(リスト、引用投稿、いいねしたユーザー、翻訳)と UnifAPI のほかの公開データプラットフォームもあり、すべて 1 回の OAuth サインインの背後で、同じワークスペースクレジットから課金されます。自前の read_x を組むのは、Anthropic や OpenAI の API の上でエージェントのループを自分で動かし、環境変数のキーで動く狭く固定されたツールが欲しいときです。どちらの道も同じオペレーションを呼び、同じエンベロープを受け取るので、一方のために書いた SKILL.md やプロンプトはもう一方にもそのまま使えます。手作業で数件調べるだけなら、X ビューアページはブラウザで引き続き無料で、ログイン不要、訪問者ごとのレート制限付きです。

FAQ

Claude は Twitter を読めますか?

ツールがあれば読めます。Claude 自身は x.com を読み込めません(ページは JavaScript のシェルです)が、UnifAPI MCP サーバーを接続すれば(Settings → Connectors)、call_api でプロフィール、投稿、返信、検索結果を読み、それをもとに推論します。Anthropic API で作ったアプリなら、上の read_x ツールが同じことをします。

ChatGPT はツイートを読めますか?

答えは同じです。ChatGPT の Developer Mode で MCP サーバーを接続するか(手順は unifapi.com/mcp)、OpenAI API で作った自分のアプリで上の関数定義を使います。ChatGPT 組み込みのブラウジングは x.com を描画できません。

API キーは必要ですか?

MCP なら不要です。クライアントに求められたときにサーバーが OAuth でサインインさせるので、貼り付けるキーはありません。自前のツールには、UNIFAPI_API_KEY などの環境変数から読むワークスペース API キーが必要です。どちらの道も X の開発者アカウントは不要で、どちらもワークスペースクレジットによる従量課金です。返されたレコード 1 件につき 1 クレジット($0.001)で、サブスクリプションはありません。

エージェントがデータでできることに制限はありますか?

オペレーションは公開データだけを読み、投稿、いいね、フォローは一切しません。キーごとの既定の上限は 1 分あたり 60 リクエストで、各呼び出しは返したレコード数で課金されます。公開コンテンツについて X の規約が許す範囲でデータを使ってください。