AG2
Connect AG2 multi-agent systems to TwexAPI for tweet search, profiles, timelines, and delegated research workflows.
AG2 is an open-source Python framework for multi-agent systems. TwexAPI does not ship a native AG2 search toolkit yet. Connect AG2 agents to the TwexAPI MCP server with MCPToolkit so agents can call explore and twexapi_request while keeping API credentials inside your infrastructure.
Preserve every tweet ID, user ID, and cursor the API returns.
Why use AG2 with TwexAPI?
AG2 gives you explicit control over tool exposure, delegation, and middleware. Pair that with TwexAPI MCP when you want multi-agent research without hardcoding every REST route.
| Boundary | AG2 control | Benefit |
|---|---|---|
| Tool construction | MCPToolkit(...) |
Restrict to explore and twexapi_request, or filter further |
| Model input | MCP tool schemas | The model chooses routes only from discovered endpoints |
| Runtime scope | Variable |
Resolve per-user or per-tenant headers at execution time |
| Delegation | Agent.as_tool() |
Keep the searcher’s tool-call history out of the coordinator’s context |
| Transport | MCPServerConfig |
Point at https://api.twexapi.io/mcp with x-api-key |
This suits research, monitoring, and reporting agents. Use the Python SDK or Prefect collection for deterministic jobs that need no model decisions.
Prerequisites
- Python 3.10 or later
- A TwexAPI API key
- An LLM provider key supported by AG2
Public X reads need no X Developer credentials. Authenticate with TwexAPI.
Install AG2
python -m pip install "ag2>=1.0.0" python-dotenv
Install your model provider extra as well.
python -m pip install "ag2[anthropic]>=1.0.0"
Store secrets outside source control.
export TWEXAPI_API_KEY="YOUR_API_KEY"
export ANTHROPIC_API_KEY="YOUR_ANTHROPIC_KEY"
Connect TwexAPI MCP with MCPToolkit
Use client-side MCPToolkit when credentials must stay in your infrastructure. TwexAPI MCP exposes explore and 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())
headers with x-api-key is required. Unauthenticated requests to https://api.twexapi.io/mcp return 401.
Restrict tools by agent role
Give discovery-only agents access to explore. Give execution agents both tools.
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",
)
)
]
Delegate search in a multi-agent team
Agent.as_tool() exposes an agent as a tool for another agent. The coordinator receives the delegate’s final answer, not its internal tool-call history.
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)
Handoff checklist
Store durable fields from MCP responses so later workflow steps do not depend on chat history.
| 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 |
See Agent MCP Handoff for the full checklist.
Pagination
When explore returns a paginated route, pass the documented cursor fields back through twexapi_request unchanged. Treat cursors as opaque strings. Deduplicate rows on tweet_id or user_id.
checkpoint = {
"route_used": "/twitter/advanced_search/page",
"query": "AI agents",
"has_more": True,
"next_cursor": "cursor_123",
}
Combine with Docs MCP
Add the Docs MCP server when agents should search TwexAPI documentation before choosing routes.
tools=[
MCPToolkit(
MCPServerConfig(
server_url="https://docs.twexapi.io/mcp",
server_label="twexapi-docs",
)
),
twexapi_mcp,
]
Handle failures
MCP and REST errors surface through the toolkit as HTTP failures. Branch on status before retrying.
| Status | Action |
|---|---|
400 |
Fix 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)
If you target Anthropic and accept forwarding credentials to the provider, use MCPServerTool instead of MCPToolkit. Prefer MCPToolkit for provider-agnostic deployments and when API keys must stay in your infrastructure.