---
title: "MCP 服务器"
description: "通过 Model Context Protocol 将 AI Agent 连接到 TwexAPI。"
---

# 通过 MCP 连接 AI Agent

TwexAPI 提供了官方的 [Model Context Protocol (MCP)](https://modelcontextprotocol.io) 服务器，使各类 AI Agent 与开发工具能够以自然语言或代码方式自主与你的 TwexAPI 账号进行交互。

本页介绍位于 `https://api.twexapi.io/mcp` 的 **API MCP 服务器**，专用于执行已鉴权的 Twitter/X 业务调用。若只需以只读方式检索接口文档，请参阅 [Docs MCP 文档服务器](/mcp/docs-mcp)（地址：`https://docs.twexapi.io/mcp`）。

## 服务连接规范

### 通信协议

面向 MCP 客户端采用标准 HTTP 及可流式传输的 Streamable HTTP (SSE) 传输协议。

### 服务端点 (Endpoint)

客户端连接地址：

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

API 服务器同时兼容 `https://api.twexapi.io/mcp` 与带尾部斜杠的 `https://api.twexapi.io/mcp/`。除非客户端具备自动 URL 规范化功能，否则在客户端配置中推荐使用不带尾部斜杠的标准地址。

### 服务发现元数据 (Discovery Metadata)

在 `x-api-key` 请求头中传入 TwexAPI API 密钥；若你的工作区已启用 OAuth，也可使用 OAuth 2.1 Bearer Token。

MCP 服务发现元数据可通过以下地址获取：

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

`GET /.well-known/mcp.json` 将直接返回 MCP Registry 标准的服务卡片 (Server Card) JSON。`GET /.well-known/mcp/server-card.json` 为读取嵌套路径的客户端返回完全相同的内容。

通过 Registry Card 接入的客户端会自动识别指向 `https://api.twexapi.io/mcp` 的 `streamable-http` 远程连接及 API Key 鉴权方式。在下文的直连客户端示例中，只要客户端支持自定义 Header，均可直接通过 `x-api-key` 传入该密钥。

:::note
  使用 API Key 的客户端必须在首次握手请求中携带 `x-api-key`。任何未经身份验证访问 `https://api.twexapi.io/mcp` 的请求都将直接返回 `401 Unauthorized`。
:::

## 鉴权方式说明

MCP 服务器支持以下两种鉴权方式：

- **API Key（`x-api-key` 请求头）**：Claude Code、Cursor、VS Code、Windsurf、Codex CLI、OpenCode 以及通过远程桥接使用的 Claude Desktop 均推荐此方式。在与 MCP 服务端建立握手时直接传入 API Key。
- **Bearer Token（`Authorization: Bearer <token>` 请求头）**：适用于偏好标准 Authorization 请求头的客户端。传入值可以是 TwexAPI 的 API Key，或者是工作区启用 OAuth 时的 Access Token。

前往 [TwexAPI 控制台](https://twexapi.io/dashboard) 即可创建并获取 API 密钥。

## 核心工作原理

MCP 服务器向 AI Agent 暴露了两个核心工具：

### 1. `explore`（接口发现与探查）

用于检索 TwexAPI 的全量接口目录。这是一个探查工具：返回接口名称、HTTP 方法、接口路径、分类、请求参数 Schema、调用示例载荷以及只读/写入安全属性标记。

### 2. `twexapi_request`（接口调用执行）

用于真正发起已鉴权的 TwexAPI 接口调用。接口产生的费用将按照底层调用的具体端点正常计费。

典型的 Agent 工作流是：Agent 先调用 `explore` 检索需要的接口，获取到返回的 HTTP 方法与相对路径后，再调用 `twexapi_request` 执行请求。鉴权凭据会自动从当前的 MCP 连接中透传注入。

### `explore` 工具详解

在内存中实时搜索 API 端点目录。调用该工具本身仍须先通过 API Key 或 Bearer Token 完成 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 Agent、IDE 集成与自然语言工作流。使用 `x-api-key` 或 Bearer 认证连接 `https://api.twexapi.io/mcp`。Agent 用 `explore` 搜索端点，用 `twexapi_request` 执行已认证的 API 调用。

### REST API

最适合后端服务、自动化脚本与直接编程访问。使用 `Authorization: Bearer <token>` 调用 `https://api.twexapi.io/*`。需要细粒度控制端点、分页、响应处理或直接 SDK 代码时，请查阅 API 参考。

希望 Agent 以自然语言与 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

工作区启用 MCP connectors 时，Claude.ai 可连接远程 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 有三种方式：

**方式一：Custom GPT**

创建 Custom GPT，并使用 API 部署中的 OpenAPI schema 将 Twexapi 添加为 Action。根据你的配置，将认证设为 API 密钥请求头或 Bearer token。

**方式二：Agents SDK**

从 Agent 运行时使用 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
```

**方式三：Developer Mode**

当 ChatGPT 环境支持 MCP connectors 时，以 `https://api.twexapi.io/mcp` 为端点添加 Twexapi。启用 OAuth 的工作区可在浏览器中完成认证。

## 示例 Prompt

连接后，你可以向 AI Agent 提出如下请求：

### 搜索与查询

- 搜索过去 24 小时关于 `AI agents` 的近期 X 帖子。返回前 20 条推文，包含 tweet ID、作者、创建时间、点赞、转推与一行摘要。
- 查找 `@elonmusk` 提及 `Grok` 或 `AI` 的近期推文。按主题分组，并附上直接 X 链接。
- 阅读推文：`https://x.com/elonmusk/status/1803006263529541838`。摘要帖子内容，再拉取最相关的回复并显示回复 ID。
- 获取 tweet ID `1803006263529541838` 的相似推文，并说明每条结果为何相关。

### 用户资料与关注

- 读取 `@openai` 资料简介，返回用户名、显示名、user ID、位置、粉丝数与资料 URL。
- 搜索 X 用户 `AI infrastructure`。返回 25 个账号，包含用户名、简介、粉丝数与匹配理由。
- 获取 `@elonmusk` 最新粉丝，找出简介中提及 AI、创业或 crypto 的账号。
- 拉取 `@sama` 的一页游标分页粉丝，返回前 20 个用户，并保留 `next_cursor` 供下次运行。
- 检查账号 `44196397`、`elonmusk`、`openai` 是否已认证或属于组织账号。

### 趋势

- 显示所有支持的全球趋势国家，再获取 `united-states` 的热门主题。
- 获取 `united-states`、主题 `technology`、内容标签 `AI` 的热门推文。返回 tweet ID、作者与互动指标。
- 检查 `AI`、`Bitcoin` 或 `Grok` 今日是否在美国 trending，并用返回的推文说明依据。
- 比较 `united-states`、`japan`、`united-kingdom` 的热门主题，并总结各区域差异。

### 提取

- 拉取 `https://x.com/elonmusk/status/1803006263529541838` 的回复，按相关性排序，返回回复 ID、作者、文本与点赞数。
- 列出转推 tweet ID `1803006263529541838` 的 50 个用户。返回 user ID、用户名、显示名，以及可用的粉丝数。
- 获取 tweet ID `1803006263529541838` 的引用推文，并将引用分类为支持、批评或中性。
- 提取 tweet ID `1803006263529541838` 的完整推文串，并转为 Markdown 大纲。
- 获取 `@elonmusk` 的推文与回复共 `20` 条，并区分原创与回复。

### 文章

- 将 X 文章 `1803006263529541838` 取为 Markdown，并转为 5 条要点摘要。
- 批量获取 X 文章 ID `1803006263529541838` 与 `1803006263529541839`；返回标题、作者、发布时间与摘要。
- 将此 X 文章读为 Markdown，提取所有链接，并生成简洁的简报式摘要。

### 社区与列表

- 搜索 X 社区 `AI builders`。返回 community ID、名称、成员数与描述。
- 获取 community ID `1234567890123456789` 的最新推文，tweet 类型 `Latest`，目标数量 `20`。
- 搜索列表 `AI founders`。返回前 10 个列表，包含 list ID、名称、描述与成员数。
- 从 list ID `987654321098765432` 获取成员，包含 next cursor，并格式化为潜在客户表格。

### X 写操作

- 发帖：`Just shipped v2.0 of our Twexapi integration. MCP setup now takes less than 2 minutes.`
- 回复 tweet ID `1803006263529541838`：`This is a useful example. I tested it through Twexapi MCP.`
- 创建含图片 URL `https://example.com/launch.png` 与文本 `New launch: Twexapi MCP now supports agent workflows.` 的推文。
- 起草但不发送对 `https://x.com/elonmusk/status/1803006263529541838` 的简洁技术风回复。

:::warning
  写操作标记为 `read_only: false`。发帖、回复、关注、屏蔽或执行任何其他有副作用的操作前，必须获得用户明确确认。
:::

### 账号与用量

- 说明我对 `/twitter/global-trending/tweets` 的 MCP 请求为何返回 `401`，并列出应检查的请求头。
- 说明 MCP 请求为何返回 `403 No available credits!`，以及重试前应采取的措施。
- 说明大批量粉丝提取为何返回 `429`，并提出重试与分页方案。
- 判断此任务应使用 MCP 还是直接 REST：`每天早上拉取 @openai 的 10,000 粉丝并存入数据库`。

## 框架指南

在首选框架中使用 Twexapi MCP 工具构建 Agent：

<CardGroup cols={2}>
  <Card title="LangChain" icon="link" href="/guides/langchain">
    将 Twexapi MCP 工具连接到 LangChain 与 LangGraph Agent。
  </Card>
  <Card title="CrewAI" icon="users" href="/guides/crewai">
    构建共享一条 Twexapi MCP 连接的研究团队。
  </Card>
  <Card title="Pydantic AI" icon="brackets-curly" href="/guides/pydantic-ai">
    使用带 Streamable HTTP MCP 工具的类型安全 Agent。
  </Card>
  <Card title="Google ADK" icon="sparkles" href="/guides/google-adk">
    为 Gemini 驱动的 ADK Agent 添加 Twexapi 工具。
  </Card>
  <Card title="Mastra" icon="workflow" href="/guides/mastra">
    将 TypeScript Agent 连接到远程 Twexapi MCP 工具。
  </Card>
  <Card title="无代码工作流" icon="blocks" href="/guides/no-code-workflow-handoff">
    将 Agent 输出交接至 n8n、Zapier、Make 与 Pipedream。
  </Card>
</CardGroup>

## AI Agent Skill

Twexapi skill 让 AI 编程 Agent 深入理解 Twexapi API，无需 MCP 连接。安装后，Agent 可编写 API 集成、配置 MCP 连接，并遵循 Twexapi 最佳实践。

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