AG2
AG2 マルチエージェントを TwexAPI に接続 — ツイート検索、プロフィール、タイムライン、委譲リサーチ。
AG2 はマルチエージェント向けオープンソース Python フレームワークです。TwexAPI はネイティブ AG2 検索ツールキットをまだ提供していません。MCPToolkit で TwexAPI MCP サーバー に接続し、explore と twexapi_request を呼び出しながら API 認証情報をインフラ内に保持できます。API が返す tweet ID、user ID、カーソルを保持してください。
Preserve every tweet ID, user ID, and cursor the API returns.
AG2 と TwexAPI を組み合わせる理由
AG2 はツール公開、委譲、ミドルウェアを明示制御。すべての REST ルートをハードコードせずマルチエージェントリサーチしたいとき TwexAPI MCP と組み合わせ。
| 境界 | AG2 制御 | メリット |
|---|---|---|
| ツール構築 | MCPToolkit(...) |
explore と twexapi_request に制限、またはさらにフィルタ |
| モデル入力 | MCP tool schemas | モデルは発見エンドポイントからのみルート選択 |
| ランタイムスコープ | Variable |
実行時にユーザー/テナントごとヘッダー解決 |
| 委譲 | Agent.as_tool() |
検索者の tool 履歴をコーディネーターコンテキスト外に |
| トランスポート | MCPServerConfig |
x-api-key で https://api.twexapi.io/mcp を指定 |
リサーチ、監視、レポートエージェント向け。モデル判断不要の決定的ジョブは Python SDK または Prefect collection。
前提条件
- Python 3.10 or later
- A TwexAPI API key
- An LLM provider key supported by AG2
公開 X 読み取りに X Developer 認証情報は不要。TwexAPI で認証します。
インストール AG2
python -m pip install "ag2>=1.0.0" python-dotenv
モデルプロバイダー extra もインストール。
python -m pip install "ag2[anthropic]>=1.0.0"
秘密情報はソース管理外に保存してください。
export TWEXAPI_API_KEY="YOUR_API_KEY"
export ANTHROPIC_API_KEY="YOUR_ANTHROPIC_KEY"
TwexAPI MCP に接続 with MCPToolkit
認証情報をインフラ内に置く必要があるときクライアント側 MCPToolkit。TwexAPI MCP は explore と twexapi_request を公開。
import asyncio
import os
from ag2 import Agent
from ag2.config import AnthropicConfig
from ag2.tools import MCPToolkit, MCPServerConfig
from dotenv import load_dotenv
load_dotenv()
config = AnthropicConfig(model="claude-sonnet-4-20250514")
twexapi_mcp = MCPToolkit(
MCPServerConfig(
server_url="https://api.twexapi.io/mcp",
server_label="twexapi",
headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
allowed_tools=["explore", "twexapi_request"],
)
)
agent = Agent(
"x-researcher",
prompt=(
"Search X for evidence before answering. "
"Always call explore before twexapi_request. "
"Quote tweet text verbatim and keep every tweet ID you receive. "
"Ask for confirmation before read_only: false actions."
),
config=config,
tools=[twexapi_mcp],
)
async def main() -> None:
reply = await agent.ask(
"What are developers saying about AI agents on X this week? "
"Return tweet IDs, authors, and a 5-bullet summary."
)
print(reply.body)
asyncio.run(main())
x-api-key 付き headers が必要。https://api.twexapi.io/mcp への未認証リクエストは 401。
Restrict tools by agent role
探索専用エージェントには explore のみ。実行エージェントには両ツール。
catalog_agent_tools = [
MCPToolkit(
MCPServerConfig(
server_url="https://api.twexapi.io/mcp",
headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
allowed_tools=["explore"],
server_label="twexapi-catalog",
)
)
]
execution_agent_tools = [
MCPToolkit(
MCPServerConfig(
server_url="https://api.twexapi.io/mcp",
headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
allowed_tools=["explore", "twexapi_request"],
server_label="twexapi-execute",
)
)
]
マルチエージェントチームで検索を委譲
Agent.as_tool() はエージェントを別エージェントのツールとして公開。コーディネーターは委譲先の最終回答のみ受け取り、内部ツール履歴は受け取らない。
searcher = Agent(
"searcher",
prompt=(
"Use TwexAPI MCP to search public X posts. "
"Call explore first. Return tweet text with IDs. Do not summarise away IDs."
),
config=config,
tools=[twexapi_mcp],
)
analyst = Agent(
"analyst",
prompt="Turn tweet records into a factual brief. Keep every tweet ID.",
config=config,
)
coordinator = Agent(
"coordinator",
prompt="Delegate the search, then pass the tweets to the analyst.",
config=config,
tools=[
searcher.as_tool(description="Search public X posts and return raw tweet records."),
analyst.as_tool(description="Analyse tweet records. Pass them in the context parameter."),
],
)
reply = await coordinator.ask("Brief me on this week's discussion of AI agents on X.")
print(reply.body)
ハンドオフチェックリスト
後続ワークフローがチャット履歴に依存しないよう MCP レスポンスから耐久フィールドを保存。
| Data type | Store |
|---|---|
| Tweets | tweet_id, text, author_username, created_at, has_more, next_cursor, original query |
| Profiles | user_id, username, name, description, followers_count, source lookup |
| Trends | country, topic, content tag, tweet rows, requested filters |
| Writes | tweet_id, route name, status, confirmation record |
完全チェックリストは Agent MCP Handoff。
ページネーション
explore がページネーションルートを返したら、文書化カーソルフィールドを twexapi_request 経由で変更せず渡す。カーソルは不透明文字列。tweet_id または user_id で行を重複排除。
checkpoint = {
"route_used": "/twitter/advanced_search/page",
"query": "AI agents",
"has_more": True,
"next_cursor": "cursor_123",
}
Docs MCP と組み合わせ
ルート選択前に TwexAPI ドキュメントを検索すべきエージェントには Docs MCP server を追加。
tools=[
MCPToolkit(
MCPServerConfig(
server_url="https://docs.twexapi.io/mcp",
server_label="twexapi-docs",
)
),
twexapi_mcp,
]
失敗の処理
MCP と REST エラーはツールキット経由で HTTP 失敗として表面化。リトライ前にステータスで分岐。
| ステータス | 対応 |
|---|---|
400 |
修正 the request. Do not retry unchanged. |
401 |
Check the x-api-key header or Bearer token. |
403 |
Check account access, credits, and write permissions. |
429 |
Back off and preserve the cursor. |
5xx |
Retry with bounded backoff. |
Wrap MCPToolkit with AG2 tool middleware when you need retries, approval gates, or audit logging around every call.
Provider-side MCP (Anthropic only)
Anthropic 向けでプロバイダーへ認証情報転送を許容するなら MCPToolkit の代わりに MCPServerTool。プロバイダー非依存デプロイや API キーをインフラ内に置く場合は MCPToolkit を優先。