推特MCP代理实验
Twitter自动化代理的简洁架构实现,可通过两者访问 MCP(模型上下文协议) 和 REST API.
特性
- 阅读推文 从任何用户的个人资料
- 回复推文 按ID
- 转发 (转发)推文
- 发布新推文
- 双重接口:MCP服务器+REST API
- 干净的建筑 适当分离关注点
- 结构化日志记录 可观察性
- 浏览器自动化 通过剧作家
快速开始
1.安装依赖项
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install packages
pip install -r requirements.txt
# Install Playwright browser
playwright install chromium2.使用推特进行身份验证
python login_and_save_auth.py这将打开Chromium浏览器。登录推特/X,看到时间线后按Enter键。这创造了 auth.json 与您的会话。
3.运行REST API
python run_rest_api.pyAPI将于 http://localhost:8000.
交互式文档:参观 http://localhost:8000/docs
4.或运行MCP服务器
python run_mcp_server.py使用示例
REST API
阅读推文:
curl -X POST http://localhost:8000/api/v1/read_tweets \
-H "Content-Type: application/json" \
-d '{"username": "elonmusk", "count": 5}'发布推文:
curl -X POST http://localhost:8000/api/v1/post_tweet \
-H "Content-Type: application/json" \
-d '{"text": "Hello from Twitter MCP Agent!"}'回复推特:
curl -X POST http://localhost:8000/api/v1/reply \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890", "text": "Great point!"}'转发:
curl -X POST http://localhost:8000/api/v1/retweet \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890"}'主控程序
MCP服务器公开了以下工具:
read_last_tweets(username, count)reply_to_tweet(tweet_id, text)retweet(tweet_id)post_tweet(text)
配置
编辑 .env 要自定义设置,请执行以下操作:
TWITTER_BASE_URL=https://x.com
AUTH_STATE_PATH=auth.json
BROWSER_HEADLESS=false
BROWSER_TIMEOUT=60000
HTTP_HOST=0.0.0.0
HTTP_PORT=8000
LOG_LEVEL=INFO建筑
该项目如下 清洁建筑 原则有四个主要层次:
- 域层 -纯业务逻辑(用例、模型、接口)
- 基础设施层 -外部集成(剧作家、浏览器管理)
- API层 -使用FastAPI的REST API
- MCP层 -使用FastMCP的MCP服务器
看 建筑.md 详细文档。
项目结构
twitter-mcp-agent/
├── src/
│ ├── domain/ # Business logic
│ ├── infrastructure/ # Playwright, browser, logging
│ ├── api/ # FastAPI routes and schemas
│ └── mcp/ # MCP server and tools
├── login_and_save_auth.py
├── run_rest_api.py
├── run_mcp_server.py
└── requirements.txt安全
auth.json包含您的推特会话 -保守秘密!- 已添加到
.gitignore - 不要将其提交给版本控制
故障排除
快速修复
浏览器无法启动?
playwright install chromium会话已过期?
python login_and_save_auth.py启用调试模式:
LOG_LEVEL=DEBUG
BROWSER_HEADLESS=falseread_tweets返回空数组?
如果你得到 {"success":true,"tweets":[],"count":0}:
快速测试:
# Run the debugging script
python test_tweet_extraction.py elonmusk 5这将:
- 明显打开浏览器
- 显示详细日志
- 如果找不到推文,请保存截图
- 帮助识别问题
常见原因:
- 身份验证已过期 -快跑
python login_and_save_auth.py再次 - Twitter DOM已更改 -检查日志中有关选择器的警告
- 页面未加载 -增加
BROWSER_TIMEOUT在.env
详细故障排除,请参阅 故障排除.md
发展
运行测试
# Manual test
python test_agent.py添加新功能
- 在中添加域模型
src/domain/models.py - 在中添加接口方法
src/domain/interfaces.py - 实施中
src/infrastructure/twitter_repository.py - 在中创建用例
src/domain/use_cases.py - 在中添加API终结点
src/api/routes.py - 在中添加MCP工具
src/mcp/server.py
许可证
MIT许可证-请参阅 许可证 详细信息文件
贡献
欢迎投稿!请保持干净的架构原则:
- 域层不应依赖于框架
- 使用依赖关系反转
- 添加适当的日志记录和错误处理
