---
title: "MCP サーバー"
description: "Model Context Protocol 経由で AI エージェントを Twexapi に接続します。"
---

# MCP で AI エージェントを接続する

Twexapi は [Model Context Protocol](https://modelcontextprotocol.io) サーバーを提供しており、AI エージェントや開発ツールから Twexapi アカウントをプログラムで操作できます。

このページでは、認証済み API アクション向けの API MCP サーバー `https://api.twexapi.io/mcp` について説明します。読み取り専用のドキュメント検索には、[Docs MCP サーバー](/mcp/docs-mcp) `https://docs.twexapi.io/mcp` を使用してください。

## 接続

### プロトコル

MCP クライアント向けに Streamable HTTP トランスポートを使った HTTP です。

### エンドポイント

クライアントは次の URL に接続します：

```txt
https://api.twexapi.io/mcp
```

API サーバーは `https://api.twexapi.io/mcp` と `https://api.twexapi.io/mcp/` の両方を受け付けます。クライアントが明示的に正規化しない限り、末尾スラッシュなしの URL を設定に使ってください。

### 認証

`x-api-key` に Twexapi API キーを指定するか、ワークスペースで OAuth が有効な場合は OAuth 2.1 Bearer トークンを使用します。

MCP サーバーのディスカバリーメタデータは次で取得できます：

```txt
https://api.twexapi.io/.well-known/mcp.json
```

`GET /.well-known/mcp.json` は MCP レジストリのサーバーカード JSON を直接返します。`GET /.well-known/mcp/server-card.json` は、ネストされた server-card パスを読むクライアント向けに同じカードを返します。

レジストリカードのクライアントには、`https://api.twexapi.io/mcp` 向けの API キー認証付き `streamable-http` リモートが提供されます。下記の直接接続例では、カスタムヘッダーに対応しているクライアントは同じキーを `x-api-key` で送れます。

:::note
  API キー利用のクライアントは最初のリクエストで `x-api-key` を送ってください。`https://api.twexapi.io/mcp` への未認証リクエストは `401` を返します。
:::

## 認証

MCP サーバーは次の認証方式をサポートしています：

- API キー（`x-api-key` ヘッダー）：Claude Code、Cursor、VS Code、Windsurf、Codex CLI、OpenCode、Claude Desktop（リモートブリッジ経由）で使用します。MCP ハンドシェイク時にキーを渡してください。
- Bearer トークン（`Authorization: Bearer <token>`）：Authorization ヘッダーを好むクライアント向け。Twexapi API キー、または OAuth 有効時の OAuth トークンが使えます。

API キーは [Twexapi dashboard](https://twexapi.io/dashboard) から作成できます。

## 仕組み

MCP サーバーは 2 つのツールを公開しています：

### `explore`

Twexapi API カタログを検索します。ディスカバリーツールで、エンドポイント名、メソッド、パス、カテゴリ、パラメータスキーマ、例、安全フラグを返します。

### `twexapi_request`

認証済みの Twexapi API 呼び出しを実行します。コストは基になるエンドポイントに従います。

エージェントはまず `explore` で検索し、返されたメソッドと相対パスで `twexapi_request` を呼び出します。認証は MCP リクエストから自動注入されます。

### `explore` ツール

メモリ上の API エンドポイントカタログを検索します。呼び出しには API キーまたは Bearer トークンによる MCP 認証が必要です。

```ts
interface EndpointInfo {
  name: string;
  method: string;
  path: string;
  category: string; // trending, search, users, tweets, followers, engagement, communities, lists, dm, articles, timeline, accounts, write
  description: string;
  read_only: boolean;
  parameters_schema?: Record<string, unknown>;
  example?: Record<string, unknown>;
}
```

### `twexapi_request` ツール

許可リストに載った Twexapi REST エンドポイントに対して API 呼び出しを実行します。

```ts
declare const twexapi_request: {
  method: string;
  path: string;
  query?: Record<string, unknown>;
  body?: unknown;
};
```

呼び出し例：

```json
{
  "method": "GET",
  "path": "/twitter/global-trending/countries"
}
```

## MCP と REST API

### MCP サーバー

AI エージェント、IDE 連携、自然言語ワークフロー向けです。`x-api-key` または Bearer 認証で `https://api.twexapi.io/mcp` に接続します。エージェントは `explore` でエンドポイント検索、`twexapi_request` で認証済み API 呼び出しを行います。

### REST API

バックエンドサービス、自動化スクリプト、直接的なプログラムアクセス向けです。`Authorization: Bearer <token>` で `https://api.twexapi.io/*` を呼び出します。エンドポイント、ページネーション、レスポンス処理、SDK コードを細かく制御したい場合は API リファレンスを参照してください。

自然言語で X/Twitter データを操作させたいときは MCP、本番バックエンド、定期ジョブ、直接統合を組むときは REST を選びましょう。

## セットアップ

### Web・ターミナルクライアント

- [Claude.ai](#claude-ai)
- [Claude Desktop](#claude-desktop)
- [Claude Code](#claude-code)
- [Codex CLI](#codex-cli)

<a id="claude-ai"></a>

#### Claude.ai

Claude.ai は、ワークスペースで MCP コネクタが有効な場合、リモート MCP サーバーに接続できます。サーバー URL に `https://api.twexapi.io/mcp` を指定します。OAuth 有効のワークスペースではブラウザで認証を完了できます。API キークライアントは `x-api-key` を使ってください。

<a id="claude-desktop"></a>

#### Claude Desktop

Claude Desktop は stdio トランスポートのみサポートします。`mcp-remote` npm パッケージをブリッジとして使います：

```json
{
  "mcpServers": {
    "twexapi": {
      "command": "npx",
      "args": [
        "mcp-remote@latest",
        "https://api.twexapi.io/mcp",
        "--header",
        "x-api-key:twexapi_YOUR_KEY_HERE"
      ]
    }
  }
}
```

<a id="claude-code"></a>

#### Claude Code

`.mcp.json` に追加します：

```json
{
  "mcpServers": {
    "twexapi": {
      "type": "http",
      "url": "https://api.twexapi.io/mcp",
      "headers": {
        "x-api-key": "twexapi_YOUR_KEY_HERE"
      }
    }
  }
}
```

<a id="codex-cli"></a>

#### Codex CLI

`~/.codex/config.toml` に追加します：

```toml
[mcp_servers.twexapi]
url = "https://api.twexapi.io/mcp"
http_headers = { "x-api-key" = "twexapi_YOUR_KEY_HERE" }
```

### エディタークライアント

- [Cursor](#cursor)
- [VS Code](#vs-code)
- [Windsurf](#windsurf)
- [OpenCode](#opencode)

<a id="cursor"></a>

#### Cursor

`~/.cursor/mcp.json`（グローバル）または `.cursor/mcp.json`（プロジェクト）に追加します：

```json
{
  "mcpServers": {
    "twexapi": {
      "url": "https://api.twexapi.io/mcp",
      "headers": {
        "x-api-key": "twexapi_YOUR_KEY_HERE"
      }
    }
  }
}
```

<a id="vs-code"></a>

#### VS Code

`.vscode/mcp.json`（プロジェクト）に追加するか、**MCP: Open User Configuration**（グローバル）を使います：

```json
{
  "servers": {
    "twexapi": {
      "type": "http",
      "url": "https://api.twexapi.io/mcp",
      "headers": {
        "x-api-key": "twexapi_YOUR_KEY_HERE"
      }
    }
  }
}
```

<a id="windsurf"></a>

#### Windsurf

`~/.codeium/windsurf/mcp_config.json` に追加します：

```json
{
  "mcpServers": {
    "twexapi": {
      "serverUrl": "https://api.twexapi.io/mcp",
      "headers": {
        "x-api-key": "twexapi_YOUR_KEY_HERE"
      }
    }
  }
}
```

<a id="opencode"></a>

#### OpenCode

`opencode.json` に追加します：

```json
{
  "mcp": {
    "twexapi": {
      "type": "remote",
      "url": "https://api.twexapi.io/mcp",
      "headers": {
        "x-api-key": "twexapi_YOUR_KEY_HERE"
      }
    }
  }
}
```

### ChatGPT

ChatGPT を Twexapi に接続する方法は 3 つあります：

**Option 1: Custom GPT**

Custom GPT を作成し、API デプロイの OpenAPI スキーマから Twexapi を Action として追加します。セットアップに応じて API キーヘッダーまたは Bearer トークンで認証を設定します。

**Option 2: Agents SDK**

エージェントランタイムから Streamable HTTP MCP を使います：

```python
from agents.mcp import MCPServerStreamableHttp

async with MCPServerStreamableHttp(
    url="https://api.twexapi.io/mcp",
    headers={"x-api-key": "twexapi_YOUR_KEY_HERE"},
    params={},
) as twexapi:
    # use Twexapi as a tool provider
    pass
```

**Option 3: Developer Mode**

ChatGPT 環境が MCP コネクタをサポートしている場合、エンドポイント `https://api.twexapi.io/mcp` で Twexapi を追加します。OAuth 有効のワークスペースではブラウザで認証を完了できます。

## プロンプト例

接続後、AI エージェントには次のような依頼ができます：

### 検索・参照

- Search recent X posts about `AI agents` from the last 24 hours. Return the top 20 tweets with tweet ID, author, created time, likes, reposts, and a one-line summary.
- Find recent tweets from `@elonmusk` that mention `Grok` or `AI`. Group the results by topic and include direct X links.
- Read this tweet: `https://x.com/elonmusk/status/1803006263529541838`. Summarize the post, then pull the most relevant replies and show reply IDs.
- Get similar tweets for tweet ID `1803006263529541838` and explain why each result is related.

### ユーザープロフィールとフォロー

- Read `@openai` profile bio and return username, display name, user ID, location, follower count, and profile URL.
- Search X users for `AI infrastructure`. Return 25 accounts with username, bio, follower count, and why they match.
- Get the latest followers for `@elonmusk`, then identify which accounts mention AI, startups, or crypto in their bios.
- Pull one cursor-paginated followers page for `@sama`, return the first 20 users, and preserve the `next_cursor` for the next run.
- Check whether accounts `44196397`, `elonmusk`, and `openai` are verified or organization-affiliated.

### トレンド

- Show all supported global trend countries, then fetch top trend topics for `united-states`.
- Fetch trending tweets for `united-states` with topic `technology` and content tag `AI`. Return tweet IDs, authors, and engagement metrics.
- Check whether `AI`, `Bitcoin`, or `Grok` is trending today in the United States. Explain the evidence from returned tweets.
- Compare trending topics for `united-states`, `japan`, and `united-kingdom` and summarize what differs by region.

### 抽出

- Pull replies to `https://x.com/elonmusk/status/1803006263529541838`, sort them by relevance, and return reply ID, author, text, and like count.
- List 50 users who retweeted tweet ID `1803006263529541838`. Return user ID, username, display name, and follower count if available.
- Get quote tweets for tweet ID `1803006263529541838`, then classify quotes as supportive, critical, or neutral.
- Extract the full thread for tweet ID `1803006263529541838` and turn it into a Markdown outline.
- Get all tweets and replies for `@elonmusk` with a count of `20`, then separate original posts from replies.

### 記事

- Fetch X article `1803006263529541838` as Markdown and convert it into a 5-bullet executive brief.
- Batch fetch X articles with IDs `1803006263529541838` and `1803006263529541839`; return title, author, publish time, and summary.
- Read this X article as Markdown, extract all links, and produce a clean newsletter-style summary.

### コミュニティとリスト

- Search X communities for `AI builders`. Return community ID, name, member count, and description.
- Get the latest tweets from community ID `1234567890123456789` with tweet type `Latest` and target count `20`.
- Search lists for `AI founders`. Return the top 10 lists with list ID, name, description, and member count.
- Fetch members from list ID `987654321098765432`, include the next cursor, and format the result as a prospecting table.

### X 書き込みアクション

- Post a tweet saying: `Just shipped v2.0 of our Twexapi integration. MCP setup now takes less than 2 minutes.`
- Reply to tweet ID `1803006263529541838` with: `This is a useful example. I tested it through Twexapi MCP.`
- Create a tweet with image URL `https://example.com/launch.png` and text: `New launch: Twexapi MCP now supports agent workflows.`
- Draft, but do not send, a reply to `https://x.com/elonmusk/status/1803006263529541838` in a concise technical style.

:::warning
  書き込みアクションは `read_only: false` です。投稿、返信、フォロー、ブロック、その他副作用のある操作の前に、必ずユーザーの明示的な確認を求めてください。
:::

### アカウントと利用状況

- Explain why my MCP request to `/twitter/global-trending/tweets` returned `401`, and list the headers I should check.
- Explain why my MCP request returned `403 No available credits!` and what I should do before retrying.
- Explain why a high-volume followers extraction returned `429`, then propose a retry and pagination plan.
- Decide whether this task should use MCP or direct REST: `pull 10,000 followers for @openai every morning and store them in my database`.

## フレームワークガイド

好みのフレームワークで Twexapi MCP ツールを使ったエージェントを構築できます：

<CardGroup cols={2}>
  <Card title="LangChain" icon="link" href="/guides/langchain">
    Twexapi MCP ツールを LangChain と LangGraph エージェントに接続します。
  </Card>
  <Card title="CrewAI" icon="users" href="/guides/crewai">
    1 つの Twexapi MCP 接続を共有するリサーチクルーを構築します。
  </Card>
  <Card title="Pydantic AI" icon="brackets-curly" href="/guides/pydantic-ai">
    Streamable HTTP MCP ツールで型安全なエージェントを使います。
  </Card>
  <Card title="Google ADK" icon="sparkles" href="/guides/google-adk">
    Gemini ベースの ADK エージェントに Twexapi ツールを追加します。
  </Card>
  <Card title="Mastra" icon="workflow" href="/guides/mastra">
    TypeScript エージェントをリモート Twexapi MCP ツールに接続します。
  </Card>
  <Card title="ノーコードワークフロー" icon="blocks" href="/guides/no-code-workflow-handoff">
    エージェント出力を n8n、Zapier、Make、Pipedream に引き渡します。
  </Card>
</CardGroup>

## AI エージェントスキル

Twexapi スキルは、MCP 接続なしでも AI コーディングエージェントに Twexapi API の深い知識を与えます。インストールすると、API 統合の記述、MCP 接続の設定、Twexapi のベストプラクティスをエージェントが使えるようになります。

```bash
npx skills add twexapi-dev/x-api-scraper-cli
```
