Microsoft Agent Framework
通过 TwexAPI MCP 构建 Python 或 .NET Microsoft Agent Framework 工作流,实现推文搜索、资料查询与经审核的 X 写操作。
通过 TwexAPI 的 MCP 服务器构建 Microsoft Agent Framework Twitter API AI Agent。搜索推文、查看资料、读取趋势并审核写操作。在聊天记录外持久化 tweet ID、游标与路由名。
为何将 Microsoft Agent Framework 与 TwexAPI 搭配使用?
该框架在 Python 或 .NET 中托管工具调用AI Agent。TwexAPI 通过 Streamable HTTP 提供 explore 与 twexapi_request。
| AI Agent任务 | TwexAPI 路由 | 为下一步保留 |
|---|---|---|
| 搜索推文 | POST /twitter/advanced_search/page |
查询、tweet ID、作者、created_at、游标 |
| 查看资料 | GET /twitter/{screen_name}/about |
用户 ID、用户名、简介、粉丝数 |
| 列出粉丝 | POST /v3/twitter/users/followers |
用户名、粉丝行、next_cursor |
| 发帖或回复 | POST /twitter/tweets/create |
Tweet ID、路由、人工审批、cookie 确认 |
已运行 Microsoft AI Agent宿主时用该框架。无需模型的确定性作业请用 Python SDK 或 C# SDK。
前置条件
- Python 3.10 或更高版本,或带 MCP Streamable HTTP 支持的 .NET 8+ 宿主
- TwexAPI API 密钥
- 为Agent 运行时配置的模型
- 写操作所需的 Twitter cookie 或
auth_token— 见
公开 X 读取无需 X Developer 凭证,使用 TwexAPI 认证即可。
安装
Python:
python -m pip install "agent-framework>=0.2" mcp python-dotenv pydantic
TWEXAPI_API_KEY=YOUR_API_KEY
OPENAI_API_KEY=sk-...
连接 TwexAPI MCP
import os
from agent_framework import MCPStreamableHTTPTool
mcp_tool = MCPStreamableHTTPTool(
name="twexapi",
url="https://api.twexapi.io/mcp",
headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
description="TwexAPI X/Twitter tools through MCP",
)
等效宿主 JSON:
{
"name": "twexapi",
"transport": "streamable-http",
"url": "https://api.twexapi.io/mcp",
"headers": {
"x-api-key": "YOUR_API_KEY"
}
}
未认证 MCP 请求返回 401。
完整示例(Python)
import asyncio
import os
from pathlib import Path
from typing import Literal
from agent_framework import ChatAgent, MCPStreamableHTTPTool
from agent_framework.openai import OpenAIChatClient
from dotenv import load_dotenv
from pydantic import BaseModel
class TweetRow(BaseModel):
tweet_id: str
text: str
author_username: str | None = None
created_at: str | None = None
class TweetSearchHandoff(BaseModel):
query: str
route_used: str
tweets: list[TweetRow]
has_more: bool
next_cursor: str | None = None
stop_reason: Literal[
"complete",
"requested_limit",
"cursor_stalled",
"page_cap",
]
async def main() -> None:
load_dotenv()
mcp_tool = MCPStreamableHTTPTool(
name="twexapi",
url="https://api.twexapi.io/mcp",
headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
description="TwexAPI X/Twitter tools through MCP",
)
async with mcp_tool:
agent = ChatAgent(
chat_client=OpenAIChatClient(model_id="gpt-4o"),
name="twexapi_agent",
instructions=(
"Use TwexAPI MCP. Call explore before twexapi_request. "
"Preserve exact IDs and cursors. Never invent missing fields. "
"Ask for confirmation before read_only: false actions. "
"Return only JSON for TweetSearchHandoff."
),
tools=[mcp_tool],
)
response = await agent.run(
"Search 25 recent tweets about Microsoft Agent Framework MCP. "
"Return query, route_used, tweets, has_more, next_cursor, and stop_reason as JSON."
)
handoff = TweetSearchHandoff.model_validate_json(response.text)
Path("twexapi-agent-framework-handoff.json").write_text(
handoff.model_dump_json(indent=2),
encoding="utf-8",
)
asyncio.run(main())
若模型用 Markdown 围栏包裹 JSON 则剥离。在会话状态外持久化文件。
.NET 宿主草图
var mcp = new McpStreamableHttpTool
{
Name = "twexapi",
Url = new Uri("https://api.twexapi.io/mcp"),
Headers = { ["x-api-key"] = Environment.GetEnvironmentVariable("TWEXAPI_API_KEY")! },
};
相同指令:先 explore、保留游标、read_only: false 前停止。类型化 REST 调用见 C# SDK。
保留 MCP 响应契约
每页复用相同查询与筛选。游标视为 opaque。
满足请求总量、has_more 为 false、next_cursor 重复或达到页面上限时停止分页。
保持可恢复的AI Agent handoff
推文分页数据
存储 tweet_id、text、author_username、created_at、has_more、next_cursor 与原始查询。
用户资料数据
存储 user_id、username、name、description 与粉丝数。
粉丝列表分页
存储源用户名、粉丝行、next_cursor 与页索引。
写入操作 (发推/点赞/关注)
存储路由、预览文本与审批。cookie 勿写入 handoff 文件。见。
构建错误处理
| 状态 | 含义 | AI Agent决策 |
|---|---|---|
400 |
无效路由或参数 | 重试前修正请求 |
401 |
API 密钥缺失或无效 | 停止并更换凭证 |
403 |
访问被拒或额度不足 | 暂停写操作;查 Get Balance |
429 |
达到速率限制 | 退避后从同一游标继续 |
5xx |
临时服务故障 | 对安全读取应用有界退避 |
超时后重试写操作前须 read-back 检查。见 Error Handling 与 Rate Limits。
X 操作前要求审批
You have access to TwexAPI MCP tools.
Call explore before twexapi_request.
Use only relative paths returned by explore.
Return tweet_id, user_id, author_username, route_used, has_more, and next_cursor.
Ask for confirmation before read_only: false actions.
Never print cookie or auth_token values.
用 CLI --dry-run 预览。经批准的写操作通过 REST 或 SDK 执行,而非无人监督的AI Agent循环。
生产指南
- 每环境使用独立 API 密钥。勿将密钥嵌入 prompt。
- 记录 MCP 工具名与返回的
path,勿记录 cookie header。 - 在存储中持久化游标与 tweet ID,而非仅
ChatAgent内存。 - 将读研究与写执行拆成独立AI Agent或作业。
包版本
| 包 | 支持范围 |
|---|---|
| Python | >=3.10 |
agent-framework |
>=0.2 |
mcp |
>=1.9 |
pydantic |
>=2.7 |