Event-Triggered AI Agent with MCP Tools / 事件驱动 AI Agent(MCP 工具)¶
假设你请助理每小时检查一次备份。到了整点,定时器发出一条消息。这时你知道检查该开始了;要知道备份有没有成功,还得看助理查了什么、拿到了什么结果。本实验先在本地观察定时器如何唤醒处理器,再用 HTTP 接口追踪一项请求怎样得到答复。
理解问题与方法¶
离线演示里,定时器和文件监听器负责发现变化,把事件放进同一个队列。事件循环每次取出一条,交给处理器。这样,发现文件被修改的代码只管报告“哪个文件变了”;如何读文件、要不要通知用户,可以交给同一个处理器决定。
HTTP 服务提供另一种入口。调用者把 Web 消息、邮件、GitHub 更新或定时提醒提交给 FastAPI,服务在本次请求里等待 Agent 处理完再返回。两种入口使用同一套事件类型,但 POST /event 的调用者收到的已经是处理结果。要观察生产者先投递、消费者稍后取出的过程,请看下面的本地队列演示。
服务还可以加载三个 MCP 服务器提供的协作、执行和感知工具。时间戳、工具计数和待办事项帮助读者对照执行过程;后台另有进程监控和系统提醒。运行时打开 /docs 可查看 HTTP 接口,访问 /mcp/status 可查看这次成功加载的工具及其分组。下面按实验配置列出 42 个工具的分工。
MCP 工具分类¶
协作工具(18 个): - 浏览器自动化(导航、截图、执行任务) - 通知(邮件、Telegram、Slack、Discord) - 人机协同(管理员审批、输入请求) - 定时器管理(一次性、循环)
执行工具(6 个): - 文件操作(写入、带校验的编辑) - 代码执行(Python 解释器、shell 命令) - 外部集成(Google Calendar、GitHub PR)
感知工具(18 个): - 网络搜索与内容抽取 - 文档阅读(PDF、DOCX、PPTX) - 多模态解析(图像、视频、网页) - 公开数据(天气、股票、Wikipedia、ArXiv) - 私有数据(Google Calendar、Notion)
架构¶
本地演示的路径是“定时器或文件监听器 → 事件队列 → 处理器”。HTTP 入口的路径是“调用端 → FastAPI → Agent → 工具或最终答复”。要追踪其中一步,可以分别打开事件循环、HTTP 处理函数和模型与工具的交互循环。
事件类型¶
class EventType(Enum):
# External input events
WEB_MESSAGE = "web_message" # Web interface
IM_MESSAGE = "im_message" # Instant messaging
EMAIL_REPLY = "email_reply" # Email responses
GITHUB_PR_UPDATE = "github_pr_update" # PR notifications
TIMER_TRIGGER = "timer_trigger" # Scheduled tasks (one-shot / recurring)
FILE_CHANGE = "file_change" # File watch trigger (created / modified)
# System reminder events
USER_TIMEOUT = "user_timeout" # No user activity
PROCESS_TIMEOUT = "process_timeout" # Long-running process
SYSTEM_ALERT = "system_alert" # System warnings
事件格式¶
{
"event_type": "web_message",
"content": "Your task description",
"metadata": {
"user_id": "user123",
"session_id": "session456"
}
}
安全考虑¶
生产部署建议:
- HTTPS:使用反向代理(nginx、Caddy)
- 认证:增加 API Key 校验
- 限流:防止滥用
- 输入校验:清洗全部输入
- CORS:配置允许的源
- 环境:使用密钥管理
从旧版迁移¶
若从 Flask 版本升级:
- 端口变更:4242 → 8000
- 无弃用警告:使用现代 lifespan 事件
- 默认启用 MCP:
ENABLE_MCP_TOOLS=false可关闭 - API 契约不变:端点用法相同
- 性能更好:MCP 调用原生异步
准备环境与输入¶
本机先用 event_loop_demo.py --mock 检查事件如何到达处理循环;要区分一次性与重复触发,再分别选择 timer 和 recurring。这一步观察调度过程,无需调用模型。
事件驱动演示(离线可运行,无需 API Key)¶
在启动 HTTP 服务器之前,推荐先运行 event_loop_demo.py,它在单个进程里
直观演示本章的核心概念——外部世界主动唤醒 Agent。脚本注册三类"事件触发器",
由后台线程在事件真正发生时把结构化事件推入统一的事件队列,事件循环逐个取出
并唤醒 Agent 处理,形成"注册 → 触发 → 唤醒 → 处理"的完整闭环:
| 触发器 | 类 | 对应书中概念 |
|---|---|---|
| 一次性定时器 | OneShotTimer |
set_timer 一次性定时器(如"下周一 10:00 致电 DMV") |
| 循环定时器 | RecurringTimer |
set_timer 循环定时器 / Heartbeat(如"每小时检查服务器") |
| 文件监听 | FileWatchTrigger |
n8n 等平台的文件变更触发器 |
--mock 离线模式不调用大模型,用"模拟动作"打印 Agent 被唤醒后的处理过程,
因此无需任何 API Key 即可跑通:
# 离线演示全部触发器(一次性定时器 + 循环定时器 + 文件监听)
python event_loop_demo.py --mock
# 只演示一次性定时器;2 秒后触发,共运行 6 秒
python event_loop_demo.py --mock --trigger timer --delay 2 --duration 6
# 每 3 秒触发一次循环定时器
python event_loop_demo.py --mock --trigger recurring --interval 3 --duration 12
# 监听目录,向其中写入文件即可触发事件(另开终端 echo hello > watched_dir/a.txt)
python event_loop_demo.py --mock --trigger file --watch-dir watched_dir
离线运行的输出示例(节选):
⏱️ [OneShotTimer(daily_backup_check)] 已注册:2 秒后触发
🔁 [RecurringTimer(health_check)] 已注册:每 3 秒触发一次
🟢 事件循环启动,将运行 8 秒,等待事件唤醒 Agent...
⚡ [OneShotTimer(daily_backup_check)] 触发事件 -> timer_trigger: 一次性定时器到期:请检查每日备份是否已经完成。
📥 事件循环取出第 1 个事件 -> 唤醒 Agent
🤖 Agent 被唤醒,收到消息: [Timer daily_backup_check triggered] 一次性定时器到期:请检查每日备份是否已经完成。
🛠️ [模拟动作] 读取定时任务上下文 -> 执行例行检查 -> 汇报结果
✅ Agent 处理完成: 已响应 timer_trigger 事件
去掉 --mock 即接入真实的大模型(默认仅用内置工具,不加载 MCP),
需要设置对应 provider 的 API Key:
export KIMI_API_KEY='your-api-key-here'
python event_loop_demo.py --trigger timer --provider kimi
export DASHSCOPE_API_KEY='your-dashscope-api-key-here'
python event_loop_demo.py --trigger timer --provider dashscope
OpenRouter 通用兜底:若所选 provider(默认
kimi)的 Key 缺失,但设置了OPENROUTER_API_KEY,event_loop_demo.py/server.py/quickstart.py会自动 改用openrouterprovider 继续运行(可用LLM_MODEL=openai/gpt-5.6-luna指定模型)。例如:OPENROUTER_API_KEY=your-openrouter-api-key LLM_MODEL=openai/gpt-5.6-luna python event_loop_demo.py --trigger timer
完整参数见 python event_loop_demo.py --help。
配置¶
环境变量¶
# Required
export KIMI_API_KEY="your-key"
# Optional
export LLM_PROVIDER="kimi" # dashscope/qwen/bailian, kimi, siliconflow, doubao, openrouter
export LLM_MODEL="kimi-k3" # Override default model
export AGENT_PORT="8000" # Server port (default: 8000)
export ENABLE_MCP_TOOLS="true" # Enable MCP (default: true)
禁用 MCP 工具¶
若只要内置工具:
自定义端口¶
按照步骤完成实验¶
先运行一次短定时器演示,观察计时结束、事件进入队列和处理结果三个环节。再按下文尝试周期事件或文件观察。理解本地路径后,才接入真实模型和外部来源。
快速开始¶
安装¶
本实验位于第 6 章,但复用第 4 章的 MCP 工具服务器。当前 ch6 extra 不包含 FastAPI、Uvicorn 和 MCP 依赖,因此安装时同时启用 ch6 和 ch4。
# 在仓库根目录安装第 6 章与共享 MCP 工具依赖
uv sync --locked --python 3.12 --extra ch6 --extra ch4
# 切换目录前先激活环境:
# macOS/Linux:
source .venv/bin/activate
# Windows PowerShell:.venv\Scripts\Activate.ps1
# Windows cmd:.venv\Scripts\activate.bat
# 未安装 uv 时可用 pip 兜底:
# python -m pip install -e ".[ch6,ch4]"
cd chapter6/agent-with-event-trigger
# 迁移期间仍支持单项目兼容路径:
# python -m pip install -r requirements.txt
# Set up environment
cp env.example .env
# Edit .env and add your API key
export KIMI_API_KEY='your-api-key-here'
测试与手动演示¶
自动化测试位于 tests/,均为离线回归测试,不需要 API Key。
# 在仓库根目录安装 pytest 所需的 dev extra:
uv sync --locked --python 3.12 --extra ch6 --extra ch4 --extra dev
# pip 测试兜底路径:
# python -m pip install -e ".[ch6,ch4,dev]"
cd chapter6/agent-with-event-trigger
python -m pytest tests
独立的联网演示已移动到 tests/manual/demo.py;它仍需要模型提供商 API Key,且不会被 pytest 默认收集:
启动服务器¶
服务器支持命令行参数(优先级高于环境变量),完整列表见 python server.py --help:
python server.py --port 9000 # 自定义端口
python server.py --provider doubao # 指定大模型提供商
python server.py --no-mcp # 只用内置工具,不加载 MCP 工具
输出:
🤖 EVENT-TRIGGERED AGENT SERVER (FastAPI)
✅ Starting server on port 8000
📡 API Documentation: http://localhost:8000/docs
📊 ReDoc: http://localhost:8000/redoc
🚀 Starting Event-Triggered Agent Server (FastAPI)
✅ Agent initialized with kimi provider
🔄 MCP tools enabled (default) - loading asynchronously...
✅ Discovered tools from 'collaboration': 18 tools
✅ Discovered tools from 'execution': 6 tools
✅ Discovered tools from 'perception': 18 tools
✅ MCP tools loaded: 42 tools available
✅ Server ready to receive events
INFO: Uvicorn running on http://0.0.0.0:8000
交互式 API 文档¶
访问 http://localhost:8000/docs 可以: - 📖 浏览全部端点 - 🧪 交互式测试 API - 📝 查看请求/响应 schema - ⚡ 一键发送事件
使用示例¶
运行独立示例¶
无需服务器、完整演示 MCP 集成:
该独立脚本: - 启用 MCP 工具并初始化 Agent - 从 3 个 MCP 服务器加载全部 42 个工具 - 处理样例事件(网络搜索任务) - 展示从工具发现到执行的完整流程 - 正确清理 MCP 连接
适用于: - 不启服务器测试 MCP 集成 - 理解异步工具加载流程 - 调试 MCP 连接问题 - 学习如何以编程方式使用 Agent
示例 1:网络搜索任务¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Search for the latest FastAPI features and summarize them",
"metadata": {"user": "demo"}
}'
Agent 将:
1. 用 perception_web_search 搜索
2. 用 perception_webpage_reader 解析内容
3. 在响应中总结结果
示例 2:浏览器自动化¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Navigate to example.com and take a screenshot",
"metadata": {}
}'
使用:
- collaboration_mcp_browser_navigate
- collaboration_mcp_browser_screenshot
示例 3:文档处理¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Download and summarize the PDF from https://example.com/doc.pdf",
"metadata": {}
}'
使用:
- perception_download
- perception_document_reader
示例 4:邮件通知¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "timer_trigger",
"content": "Send daily report to admin@example.com",
"metadata": {"scheduled": true}
}'
使用:
- collaboration_mcp_send_email
使用客户端¶
内置客户端便于测试:
# Interactive mode
python client.py --mode interactive
# Test scenarios
python client.py --mode test
# Send a single event (defaults to web_message)
python client.py --message "Create a Python hello world script"
# Send a single event of a specific type
python client.py --event-type timer_trigger --message "检查每日备份"
扩展(选做):多来源接入与故障注入¶
正文实验 6-1 的选做扩展在 multisource/ 中实现,离线运行,不需要 API Key:
cd chapter6/agent-with-event-trigger
python multisource_demo.py # 临时目录,脚本化回复
python multisource_demo.py --workdir runs/demo # 保留 SQLite、邮箱和渠道文件,便于事后查看
python multisource_demo.py --live --provider kimi # 可选:用真实模型起草回复,需按上文在仓库根目录安装
三个来源各有一个适配器,都先验证来源、生成信封、写入接入日志,再确认来源:
| 来源 | 验证 | dedupe_key |
thread |
确认 |
|---|---|---|---|---|
Webhook(标准库 http.server,127.0.0.1) |
HMAC-SHA256 签名,覆盖投递 ID 和正文 | 投递 ID | 退款单号 | 返回 HTTP 200 |
SQS(fake_sqs.py 本地模拟 FIFO 队列) |
队列记录的 SenderId(发布者不能自填)在白名单内 |
MessageId |
MessageGroupId |
删除消息 |
测试邮箱(本地目录 INBOX/、Sent/) |
DKIM 通过,且签名域与发件人域名一致 | Message-ID |
首个 References |
记录读取位置 |
验证不通过、缺少必要字段或事件类型不受支持的输入不写入接入日志,而是在审计表里记一条 source_rejected,同时照常确认来源,免得来源反复重投一条永远处理不了的消息。原始载荷按内容的 SHA-256 存放,重投不会覆盖已有事件引用的字节。
接入日志是一个 SQLite 文件里的 events 表:触发器禁止更新和删除,dedupe_key 有唯一约束,(thread, thread_seq) 记录线程内顺序。来源进度(source_progress)、分派进度(dispatch)、任务状态(task_state)和发件箱(outbox)分表保存,与正文的三种进度一一对应;三类故障的证据写在只增不改的 audit 表里。
模拟 SQS 不是 AWS 服务。它保留了实验依赖的语义:接收后在可见性超时内隐藏消息,每次接收换一个接收句柄,过期句柄不能删除消息,未删除的消息超时后重新可见,同一消息组在前一条处理完之前不投递下一条。它存放在单独的文件里,代表外部服务,适配器进程被杀不会影响它。测试邮箱同样是本地模拟,与需要 Unipile 凭据的真实邮箱实验无关,不改变实验 6-1 的验收状态。
故障由 faults.py 注入:每个角色(Webhook 服务、SQS 轮询、邮箱轮询、运行时)都是独立进程,MULTISOURCE_FAULT 指定故障点;子进程到达故障点后打印标记并等待,父进程随即发送 SIGKILL,没有 finally 或缓冲写入能够执行。
| 故障 | 注入方式 | 日志中的证据 |
|---|---|---|
| 1. 重复投递 | 用同一 X-Delivery-Id 签名 POST 两次;另 POST 一次错误签名 |
appended → deduplicated;伪造请求 source_rejected,返回 401 |
| 2. 确认前崩溃 | sqs_after_log:写入日志后、删除消息前杀掉 SQS 适配器 |
appended → redelivered(receive_count: 2)→ deduplicated → acked;日志仍只有一条事件 |
| 3. 回执前崩溃 | runtime_after_send:每次发出回复后、记录回执前杀掉运行时,共四次 |
邮件 reply_verified_not_resent(查已发送记录);App 对话 reply_confirmed_by_idempotency_key(服务端按幂等键返回原消息);短信 reply_needs_manual_confirmation(不重发) |
运行时每次启动都从日志重放:先核对发件箱中有发送意图、没有回执的回复,再分派新事件,最后按线程逐条处理。发送前先在 outbox 记下发送意图和幂等键(reply-<event_id>),再调用渠道。核对时把“有意图、无回执”当作崩溃留下的发送,这只有在没有另一个运行时正在发送时才成立,所以同一工作目录只允许一个运行时(runtime.lock 上的 flock,进程被杀后由操作系统释放)。
离线测试覆盖三类故障、线程内顺序、发件箱核对和模拟 SQS 的语义:
规范运行记录见 validation/experiment_6_1_multisource/,其中 summary.json 保存每项检查和对应的审计记录,manifest.json 记录其 SHA-256。
分析结果与形成判断¶
先跑上面的一次性定时器示例。在终端里依次找到定时器触发、事件循环取出事件和模拟处理器打印动作这三处。如果最后一行说“共处理 1 个事件”,它统计的是循环取出并尝试分发的次数。--mock 打印的备份检查步骤只是演示文字,备份系统究竟返回了什么,仍然未知。
换到 HTTP 入口,可以沿一次响应检查更多内容:
| 要回答的问题 | 看哪里 |
|---|---|
| 这份响应对应哪个事件? | 读响应的 event_id。处理函数在 Agent 返回后才把它交给调用方。 |
| Agent 有没有给出最终答复? | 对照 result.success 和 result.final_answer。外层 success 表示接口正常返回,内层才是 Agent 报告的处理结果。 |
| 工具实际返回了什么? | 启用轨迹保存后,打开服务端 result.trajectory_file 指向的 JSON,对照 tool_calls 中的工具名、参数、结果和错误,再读最终答复。 |
如果连续提交了两次请求,第二次看到的 tool_calls_count 可能包含第一次的调用。这个 Agent 会保留会话历史,默认轨迹文件也会在后续迭代中更新。要只分析第二次请求,可以在两次返回后分别保存轨迹,再比较新增的调用编号。一个事件 ID 能帮助辨认请求,却不能单独证明某项外部操作已经成功。
再看一封会议邀请。 假设对方约了 10:00 到 11:00,日历上已有一场从 09:30 开始的会。若这场会恰好在 10:00 结束,两场会首尾相接;若在 10:01 结束,它们就重叠了一分钟。可以在实验目录运行下面的例子,直接调用邮箱处理器使用的函数。两个时间段都用 UTC。
from datetime import datetime, timezone
from unipile_mailbox_experiment import event_overlaps
def at(hour, minute):
return datetime(2026, 7, 30, hour, minute, tzinfo=timezone.utc)
for minute, cancelled in [(0, False), (1, False), (1, True)]:
event = {"start": at(9, 30).isoformat(), "end": at(10, minute).isoformat(),
"is_cancelled": cancelled}
print(event_overlaps(event, at(10, 0), at(11, 0)))
结果依次为 False、True、False。最后一次保留了重叠的一分钟,但原会议已经取消。沿着邮箱处理器里的 _meeting 往下读:它在所选日历里数出冲突,有冲突就拟婉拒信,没有冲突就拟接受信,并把草稿写入 meeting_reply_draft.txt。要判断邀请者是否已经收到答复,还得查发送记录。
这段练习可以离线验证时间判断。要核实真实邮箱里那场会议,还需要读到日历服务返回的事件。邮箱运行摘要显示,当次试跑停在凭据检查,尚无会议邀请的处理回执。
检查自己的解释¶
如果一个周期任务的执行时间超过触发间隔,应排队、合并,还是跳过本轮?
阅读实现与继续探索¶
项目说明¶
Companion code for AI Agents in Depth, Chapter 6 — Experiment 6-1 ★★★. FastAPI event-driven Agent with async MCP tool loading from collaboration / execution / perception servers. 配套《深入理解 AI Agent》第 6 章 实验 6-1 ★★★。FastAPI 事件驱动 Agent,异步加载协作/执行/感知 MCP 工具。
API 端点¶
核心端点¶
# Health check
curl http://localhost:8000/health
# Check MCP tools status
curl http://localhost:8000/mcp/status
# Send an event
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Search the web for Python async best practices",
"metadata": {"user": "demo"}
}'
# Get agent status
curl http://localhost:8000/agent/status
# Reset agent state
curl -X POST http://localhost:8000/agent/reset
# Reload MCP tools
curl -X POST http://localhost:8000/mcp/reload
使用交互式文档¶
- 打开 http://localhost:8000/docs
- 点击任意端点(如
POST /event) - 点击 "Try it out"
- 填写请求体
- 点击 "Execute"
- 即时查看响应
项目结构¶
agent-with-event-trigger/
├── agent.py # Event-triggered agent with system hints
├── event_types.py # Event type definitions
├── event_loop_demo.py # Offline event-loop demo (timer / recurring / file-watch triggers)
├── multisource/ # Optional extension: Webhook/SQS/mailbox adapters, ingress log, faults
├── multisource_demo.py # Runs the three fault-injection scenarios offline
├── server.py # FastAPI server (main entry point)
├── tests/ # Automated regressions and manual live demos
│ └── manual/
├── requirements.txt # Dependencies (FastAPI, uvicorn, MCP)
├── env.example # Environment template
├── README.md # This file
└── example_with_mcp.py # Standalone MCP example
对比:Flask vs FastAPI¶
| 特性 | 旧版(Flask) | 新版(FastAPI) |
|---|---|---|
| Framework | Flask (WSGI) | FastAPI (ASGI) |
| Async Support | ❌ Threads | ✅ Native async/await |
| MCP Integration | ⚠️ Complex | ✅ Clean |
| API Docs | ❌ Manual | ✅ Auto-generated |
| Performance | Good | Better (2-3x) |
| Port | 4242 | 8000 |
| Deprecation Warnings | N/A | ✅ Fixed (lifespan) |
排查问题与查阅资料¶
MCP 工具参考¶
查看可用工具¶
响应包含:
- tools:全部 42 个工具名
- tools_by_server:按服务器分组
- tools_count:总数
- loaded:MCP 是否已加载
工具命名约定¶
MCP 工具使用前缀:
- collaboration_* — 协作工具
- execution_* — 执行工具
- perception_* — 感知工具
内置工具(无前缀):
- read_file
- write_file
- code_interpreter
- execute_command
- rewrite_todo_list
- update_todo_status
故障排除¶
端口占用¶
MCP 工具未加载¶
# Check status
curl http://localhost:8000/mcp/status
# Look for error in response
# Common issue: Missing API keys for MCP servers
# Reload tools
curl -X POST http://localhost:8000/mcp/reload
导入错误¶
# 从仓库根目录重新安装第 6 章与共享 MCP 工具依赖
uv sync --locked --python 3.12 --extra ch6 --extra ch4
# 单项目兼容路径:
# python -m pip install -r requirements.txt
# Verify FastAPI installed
python -c "import fastapi; print(fastapi.__version__)"
Agent 无响应¶
# Check health
curl http://localhost:8000/health
# View logs in server terminal
# Check trajectory file: event_agent_trajectory.json
许可证¶
MIT License - 详见 LICENSE 文件
致谢¶
- 基于 FastAPI 构建
- MCP 协议:Model Context Protocol
- 工具服务器:collaboration-tools、execution-tools、perception-tools
Notes / 说明¶
- Start with
python event_loop_demo.py --mock(no API key). - 建议先跑
python event_loop_demo.py --mock(无需 API Key)。 - Chapter 4 MCP servers expected: collaboration-tools, execution-tools, perception-tools.
- MCP 服务器见第 4 章的三个工具项目。
English¶
A modern AI agent with native async support that responds to events from various sources. Built with FastAPI and integrated with 42 MCP tools for enhanced capabilities including browser automation, web search, document processing, and more.
Features¶
Core Capabilities¶
- ✅ Native Async - FastAPI with clean async/await support
- ✅ 42 MCP Tools - Automatically loaded from 3 MCP servers
- ✅ Event-Driven - Responds to web messages, emails, GitHub updates, timers
- ✅ System Hints - Timestamps, tool counters, TODO management
- ✅ Auto API Docs - Interactive Swagger UI at
/docs - ✅ Background Tasks - Process monitoring and system alerts
MCP Tool Categories¶
Collaboration Tools (18 tools): - Browser automation (navigate, screenshot, execute tasks) - Notifications (email, Telegram, Slack, Discord) - Human-in-the-loop (admin approval, input requests) - Timer management (one-time, recurring)
Execution Tools (6 tools): - File operations (write, edit with verification) - Code execution (Python interpreter, shell commands) - External integrations (Google Calendar, GitHub PRs)
Perception Tools (18 tools): - Web search and content extraction - Document reading (PDF, DOCX, PPTX) - Multimodal parsing (images, videos, webpages) - Public data (weather, stocks, Wikipedia, ArXiv) - Private data (Google Calendar, Notion)
Event-driven demo (offline runnable, no API key)¶
Before starting the HTTP server, run event_loop_demo.py. In one process it demonstrates the chapter core idea—the external world wakes the Agent. The script registers three trigger types; background threads push structured events into a shared queue when events occur; the event loop dequeues and wakes the Agent—“register → trigger → wake → handle”:
| Trigger | Class | Book concept |
|---|---|---|
| One-shot timer | OneShotTimer |
set_timer one-shot (e.g. “call DMV next Monday 10:00”) |
| Recurring timer | RecurringTimer |
set_timer recurring / Heartbeat (e.g. “check server hourly”) |
| File watch | FileWatchTrigger |
File-change triggers like n8n |
--mock offline mode does not call an LLM; it prints simulated actions when the Agent is woken—no API key required:
# Offline: all triggers (one-shot + recurring + file watch)
python event_loop_demo.py --mock
# One-shot only; fire after 2s; run 6s total
python event_loop_demo.py --mock --trigger timer --delay 2 --duration 6
# Recurring every 3s
python event_loop_demo.py --mock --trigger recurring --interval 3 --duration 12
# Watch a directory; write a file to trigger (other terminal: echo hello > watched_dir/a.txt)
python event_loop_demo.py --mock --trigger file --watch-dir watched_dir
Sample offline output (excerpt):
⏱️ [OneShotTimer(daily_backup_check)] 已注册:2 秒后触发
🔁 [RecurringTimer(health_check)] 已注册:每 3 秒触发一次
🟢 事件循环启动,将运行 8 秒,等待事件唤醒 Agent...
⚡ [OneShotTimer(daily_backup_check)] 触发事件 -> timer_trigger: 一次性定时器到期:请检查每日备份是否已经完成。
📥 事件循环取出第 1 个事件 -> 唤醒 Agent
🤖 Agent 被唤醒,收到消息: [Timer daily_backup_check triggered] 一次性定时器到期:请检查每日备份是否已经完成。
🛠️ [模拟动作] 读取定时任务上下文 -> 执行例行检查 -> 汇报结果
✅ Agent 处理完成: 已响应 timer_trigger 事件
Drop --mock to use a real LLM (built-in tools only by default, no MCP); set the provider API key:
export KIMI_API_KEY='your-api-key-here'
python event_loop_demo.py --trigger timer --provider kimi
# Alibaba Cloud Model Studio / Bailian (Qwen)
export DASHSCOPE_API_KEY='your-dashscope-api-key-here'
python event_loop_demo.py --trigger timer --provider dashscope
# `qwen` and `bailian` are accepted aliases; international keys may use
# DASHSCOPE_BASE_URL=https://dashscope-intl.aliyuncs.com/compatible-mode/v1
Universal OpenRouter fallback: if the chosen provider’s key is missing (default
kimi) butOPENROUTER_API_KEYis set,event_loop_demo.py/server.py/quickstart.pyswitch toopenrouter(set model withLLM_MODEL=openai/gpt-5.6-luna). Example:
OPENROUTER_API_KEY=your-openrouter-api-key LLM_MODEL=openai/gpt-5.6-luna python event_loop_demo.py --trigger timer
Full flags: python event_loop_demo.py --help.
Exact Experiment 6-1: real mailbox listener¶
unipile_mailbox_experiment.py implements the manuscript's complete
three-email acceptance scenario against Unipile's real Email and Calendar
APIs. It uses documented mailbox polling (GET /api/v1/emails) as the event
source, converts provider email objects into a FIFO queue, and then performs:
- meeting invitation → live calendar/event query → hashed accept/decline draft;
- customer complaint → order extraction → durable high-priority notification;
- marketing email → provider
PUTarchive operation → providerGETverification.
The runner sends three uniquely tagged messages through Unipile before waiting for their inbound mailbox objects. A local file or synthetic event can never satisfy its acceptance gates. Configure a real project first:
export UNIPILE_DSN='apiN.unipile.com:PORT'
export UNIPILE_ACCESS_TOKEN='...'
# Read-only authentication/account check
python unipile_mailbox_experiment.py --preflight-only
# Full unattended workflow; the listener address is normally inferred
python unipile_mailbox_experiment.py
# If account metadata does not expose the mailbox address
python unipile_mailbox_experiment.py --recipient 'test-mailbox@example.com'
Every run writes a redacted, hash-manifested bundle under
validation/experiment_6_1/. Invalid credentials produce status: blocked
with the observed HTTP receipt; they are never treated as experiment evidence.
The official endpoint versions used by the implementation are pinned in
experiment_protocol.json.
Optional extension: multi-source ingress and fault injection¶
The chapter's optional extension lives in multisource/ and runs offline with no API key:
python multisource_demo.py # temp workdir, scripted replies
python multisource_demo.py --workdir runs/demo # keep the SQLite files, mailbox and channel files
python multisource_demo.py --live --provider kimi # optional: real model; needs the repo-root install
python -m pytest tests/test_multisource.py
A signed Webhook endpoint (stdlib http.server, HMAC-SHA256 over delivery ID and body), a local FIFO
queue simulation with SQS semantics (multisource/fake_sqs.py: visibility
timeout, receipt handles, redelivery, message-group order) and a local test
mailbox each verify the source, build an envelope, append it to an
append-only SQLite ingress log with a unique dedupe_key, and only then
acknowledge the source; inputs that fail verification or validation are
acked and recorded as source_rejected instead of logged. Source progress, dispatch progress, task state and the
outbox are separate tables. Every role is its own OS process; faults are a
SIGKILL from the parent at a named point (MULTISOURCE_FAULT):
- Duplicate delivery -- the same
X-Delivery-Idposted twice gives one event and adeduplicatedaudit record. - Crash before ack (
sqs_after_log) -- the message becomes visible again, is re-read (redelivered, receive count 2), deduplicated, then deleted. - Crash before receipt (
runtime_after_send) -- on restart the runtime reconciles the outbox: mail is checked in the Sent folder (reply_verified_not_resent), app chat is re-sent with the same idempotency key and the server returns the original message, SMS has neither and is markedreply_needs_manual_confirmation.
The simulated mailbox is separate from the real Unipile mailbox experiment and
does not change its blocked status. The canonical run is under
validation/experiment_6_1_multisource/.
Quick Start¶
Installation¶
This Chapter 6 experiment reuses the Chapter 4 MCP tool servers. The current ch6 extra does not include FastAPI, Uvicorn or MCP, so enable both ch6 and ch4 when installing.
# From the repository root: install Chapter 6 and shared MCP tool dependencies
uv sync --locked --python 3.12 --extra ch6 --extra ch4
# Activate it before changing directories:
# macOS/Linux:
source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
# Windows cmd: .venv\Scripts\activate.bat
# pip fallback when uv is not installed:
# python -m pip install -e ".[ch6,ch4]"
cd chapter6/agent-with-event-trigger
# Single-project compatibility path, still supported during migration:
# python -m pip install -r requirements.txt
# Set up environment
cp env.example .env
# Edit .env and add your API key
export KIMI_API_KEY='your-api-key-here'
export DASHSCOPE_API_KEY='your-dashscope-api-key-here' # for dashscope/qwen/bailian
Tests and Manual Demo¶
Automated tests are offline regressions under tests/ and do not require an API key.
# From the repository root, include the dev extra for pytest:
uv sync --locked --python 3.12 --extra ch6 --extra ch4 --extra dev
# pip testing fallback:
# python -m pip install -e ".[ch6,ch4,dev]"
cd chapter6/agent-with-event-trigger
python -m pytest tests
The standalone live demo was moved to tests/manual/demo.py; it still requires a provider API key and is not collected by pytest:
Start the Server¶
CLI flags override env vars; see python server.py --help:
python server.py --port 9000 # custom port
python server.py --provider doubao # LLM provider
python server.py --no-mcp # built-in tools only, no MCP
Output:
🤖 EVENT-TRIGGERED AGENT SERVER (FastAPI)
✅ Starting server on port 8000
📡 API Documentation: http://localhost:8000/docs
📊 ReDoc: http://localhost:8000/redoc
🚀 Starting Event-Triggered Agent Server (FastAPI)
✅ Agent initialized with kimi provider
🔄 MCP tools enabled (default) - loading asynchronously...
✅ Discovered tools from 'collaboration': 18 tools
✅ Discovered tools from 'execution': 6 tools
✅ Discovered tools from 'perception': 18 tools
✅ MCP tools loaded: 42 tools available
✅ Server ready to receive events
INFO: Uvicorn running on http://0.0.0.0:8000
Interactive API Documentation¶
Visit http://localhost:8000/docs to: - 📖 Browse all available endpoints - 🧪 Test API calls interactively - 📝 See request/response schemas - ⚡ Send events with one click
API Endpoints¶
Core Endpoints¶
# Health check
curl http://localhost:8000/health
# Check MCP tools status
curl http://localhost:8000/mcp/status
# Send an event
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Search the web for Python async best practices",
"metadata": {"user": "demo"}
}'
# Get agent status
curl http://localhost:8000/agent/status
# Reset agent state
curl -X POST http://localhost:8000/agent/reset
# Reload MCP tools
curl -X POST http://localhost:8000/mcp/reload
Using the Interactive Docs¶
- Open http://localhost:8000/docs
- Click on any endpoint (e.g.,
POST /event) - Click "Try it out"
- Fill in the request body
- Click "Execute"
- See the response instantly!
Usage Examples¶
Running the Standalone Example¶
For a complete demonstration of MCP integration without the server, run:
This standalone script: - Initializes the agent with MCP tools enabled - Loads all 42 tools from the 3 MCP servers - Processes a sample event (web search task) - Shows the complete flow from tool discovery to execution - Properly cleans up MCP connections
Useful for: - Testing MCP integration without running a server - Understanding the async tool loading flow - Debugging MCP connection issues - Learning how to use the agent programmatically
Example 1: Web Search Task¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Search for the latest FastAPI features and summarize them",
"metadata": {"user": "demo"}
}'
The agent will:
1. Use perception_web_search to find results
2. Parse the content with perception_webpage_reader
3. Summarize findings in the response
Example 2: Browser Automation¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Navigate to example.com and take a screenshot",
"metadata": {}
}'
Uses:
- collaboration_mcp_browser_navigate
- collaboration_mcp_browser_screenshot
Example 3: Document Processing¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "web_message",
"content": "Download and summarize the PDF from https://example.com/doc.pdf",
"metadata": {}
}'
Uses:
- perception_download
- perception_document_reader
Example 4: Email Notification¶
curl -X POST http://localhost:8000/event \
-H "Content-Type: application/json" \
-d '{
"event_type": "timer_trigger",
"content": "Send daily report to admin@example.com",
"metadata": {"scheduled": true}
}'
Uses:
- collaboration_mcp_send_email
Configuration¶
Environment Variables¶
# Required
export KIMI_API_KEY="your-key"
# Optional
export LLM_PROVIDER="kimi" # dashscope/qwen/bailian, kimi, siliconflow, doubao, openrouter
export LLM_MODEL="kimi-k3" # Override default model
export AGENT_PORT="8000" # Server port (default: 8000)
export ENABLE_MCP_TOOLS="true" # Enable MCP (default: true)
Disable MCP Tools¶
If you only want built-in tools:
Custom Port¶
Architecture¶
┌─────────────────────────────────────────────────────────┐
│ FastAPI Server │
│ (Native Async) │
└───────────┬─────────────────────────────────────────────┘
│
├─► Lifespan Events (Startup/Shutdown)
│ └─► Load MCP Tools Asynchronously
│
├─► Event Handler (Process incoming events)
│ └─► EventTriggeredAgent
│ ├─► System Hints (timestamps, TODOs)
│ ├─► Tool Execution (MCP + built-in)
│ └─► Trajectory Saving
│
└─► MCP Server Manager
├─► Collaboration Tools (18 tools)
├─► Execution Tools (6 tools)
└─► Perception Tools (18 tools)
Project Structure¶
agent-with-event-trigger/
├── agent.py # Event-triggered agent with system hints
├── event_types.py # Event type definitions
├── event_loop_demo.py # Offline event-loop demo (timer / recurring / file-watch triggers)
├── multisource/ # Optional extension: Webhook/SQS/mailbox adapters, ingress log, faults
├── multisource_demo.py # Runs the three fault-injection scenarios offline
├── server.py # FastAPI server (main entry point)
├── tests/ # Automated regressions and manual live demos
│ └── manual/
├── requirements.txt # Dependencies (FastAPI, uvicorn, MCP)
├── env.example # Environment template
├── README.md # This file
└── example_with_mcp.py # Standalone MCP example
MCP Tools Reference¶
Check Available Tools¶
Response shows:
- tools: List of all 42 tool names
- tools_by_server: Tools grouped by server
- tools_count: Total count
- loaded: Whether MCP tools are active
Tool Naming Convention¶
MCP tools use underscore prefixes:
- collaboration_* - Collaboration tools
- execution_* - Execution tools
- perception_* - Perception tools
Built-in tools (no prefix):
- read_file
- write_file
- code_interpreter
- execute_command
- rewrite_todo_list
- update_todo_status
Event Types¶
class EventType(Enum):
# External input events
WEB_MESSAGE = "web_message" # Web interface
IM_MESSAGE = "im_message" # Instant messaging
EMAIL_REPLY = "email_reply" # Email responses
GITHUB_PR_UPDATE = "github_pr_update" # PR notifications
TIMER_TRIGGER = "timer_trigger" # Scheduled tasks (one-shot / recurring)
FILE_CHANGE = "file_change" # File watch trigger (created / modified)
# System reminder events
USER_TIMEOUT = "user_timeout" # No user activity
PROCESS_TIMEOUT = "process_timeout" # Long-running process
SYSTEM_ALERT = "system_alert" # System warnings
Event Format¶
{
"event_type": "web_message",
"content": "Your task description",
"metadata": {
"user_id": "user123",
"session_id": "session456"
}
}
Using the Client¶
The included client provides easy testing:
# Interactive mode
python client.py --mode interactive
# Test scenarios
python client.py --mode test
# Send a single event (defaults to web_message)
python client.py --message "Create a Python hello world script"
# Send a single event of a specific type
python client.py --event-type timer_trigger --message "检查每日备份"
Security Considerations¶
For production deployment:
- HTTPS: Use a reverse proxy (nginx, Caddy)
- Authentication: Add API key validation
- Rate Limiting: Prevent abuse
- Input Validation: Sanitize all inputs
- CORS: Configure allowed origins
- Environment: Use secrets management
Comparison: Flask vs FastAPI¶
| Feature | Old (Flask) | New (FastAPI) |
|---|---|---|
| Framework | Flask (WSGI) | FastAPI (ASGI) |
| Async Support | ❌ Threads | ✅ Native async/await |
| MCP Integration | ⚠️ Complex | ✅ Clean |
| API Docs | ❌ Manual | ✅ Auto-generated |
| Performance | Good | Better (2-3x) |
| Port | 4242 | 8000 |
| Deprecation Warnings | N/A | ✅ Fixed (lifespan) |
Troubleshooting¶
Port Already in Use¶
MCP Tools Not Loading¶
# Check status
curl http://localhost:8000/mcp/status
# Look for error in response
# Common issue: Missing API keys for MCP servers
# Reload tools
curl -X POST http://localhost:8000/mcp/reload
Import Errors¶
# Reinstall Chapter 6 and shared MCP tool dependencies from the repository root
uv sync --locked --python 3.12 --extra ch6 --extra ch4
# Single-project compatibility path:
# python -m pip install -r requirements.txt
# Verify FastAPI installed
python -c "import fastapi; print(fastapi.__version__)"
Agent Not Responding¶
# Check health
curl http://localhost:8000/health
# View logs in server terminal
# Check trajectory file: event_agent_trajectory.json
Migration from Old Version¶
If upgrading from Flask version:
- Port changed: 4242 → 8000
- No deprecation warnings: Using modern lifespan events
- MCP enabled by default: Set
ENABLE_MCP_TOOLS=falseto disable - Same API contracts: Endpoints work the same way
- Better performance: Native async for MCP calls
License¶
MIT License - See LICENSE file for details
Acknowledgments¶
- Built with FastAPI
- MCP protocol by Model Context Protocol
- Tool servers: collaboration-tools, execution-tools, perception-tools