<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Agent Hooks on Bruce AI 工程笔记</title><link>https://www.heyuan110.com/zh/tags/agent-hooks/</link><description>Recent content in Agent Hooks on Bruce AI 工程笔记</description><generator>Hugo</generator><language>zh</language><lastBuildDate>Mon, 14 Sep 2026 03:00:00 +0000</lastBuildDate><atom:link href="https://www.heyuan110.com/zh/tags/agent-hooks/index.xml" rel="self" type="application/rss+xml"/><item><title>深度驾驭 Anthropic Agent SDK 钩子：通过 pretooluse 与 posttooluse 构建安全闭环</title><link>https://www.heyuan110.com/zh/posts/ai/2026-09-14-mastering-anthropic-agent-hooks/</link><pubDate>Mon, 14 Sep 2026 03:00:00 +0000</pubDate><guid>https://www.heyuan110.com/zh/posts/ai/2026-09-14-mastering-anthropic-agent-hooks/</guid><description>&lt;p&gt;&lt;img src="https://www.heyuan110.com/posts/ai/2026-09-14-mastering-anthropic-agent-hooks/cover.webp"
 alt="ALT"
 
 loading="lazy"
 decoding="async"
 fetchpriority="low"
 width="1200"
 height="630"
/&gt;
&lt;/p&gt;
&lt;p&gt;前几周，我在测试一个处于私有代码库环境的自主 Agent 时，差点遭遇灭顶之灾：该 Agent 试图删掉整个 PostgreSQL 数据库的表结构。起因是由于一个恶意用户在 GitHub Issue 的 Mock Bug 报告里埋了&lt;strong&gt;提示词注入（Prompt Injection）攻击&lt;/strong&gt;。Agent 在解析该 Issue 时被大模型脑补诱导，认为必须“通过清理 Schema 冲突来解决 Bug”，进而尝试执行一条删除表结构的裸 SQL 语句。&lt;/p&gt;
&lt;p&gt;这笔惊出冷汗的教训再次证明了一个血淋淋的现实：&lt;strong&gt;给 AI Agent 毫无约束地开放外部工具权限，等同于让一个未经授权的用户在你的服务器上执行任意命令&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;依靠系统提示词（System Prompt）无法彻底解决这个问题。在开发提示词里叮嘱 Claude“请不要运行具有破坏性的命令”，就像是用纸箱给银行做防盗门。一旦黑客使用高阶注入技巧，提示词防线会在瞬间溃散。如果想在生产环境中安稳地运行 AI Agent，必须建立&lt;strong&gt;代码级的强控制底座&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;在 Anthropic 的开发者生态中，这道牢不可破的底层代码边界是通过官方 Agent SDK 的生命周期钩子（Lifecycle Hooks）来构建的：&lt;code&gt;pretooluse&lt;/code&gt;、&lt;code&gt;posttooluse&lt;/code&gt;、&lt;code&gt;onstart&lt;/code&gt; 和 &lt;code&gt;onfini&lt;/code&gt;。深度掌控这套拦截钩子，是将“脆弱的玩具级 Agent”蜕变为“生产级受控 Agent”的唯一分水岭。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="剖析-anthropic-agent-调用的完整生命周期"&gt;剖析 Anthropic Agent 调用的完整生命周期&lt;a href="#%e5%89%96%e6%9e%90-anthropic-agent-%e8%b0%83%e7%94%a8%e7%9a%84%e5%ae%8c%e6%95%b4%e7%94%9f%e5%91%bd%e5%91%a8%e6%9c%9f" class="anchor" aria-hidden="true"&gt;&lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
 stroke-linecap="round" stroke-linejoin="round"&gt;
 &lt;path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"&gt;&lt;/path&gt;
 &lt;line x1="8" y1="12" x2="16" y2="12"&gt;&lt;/line&gt;
 &lt;/svg&gt;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;在动笔写钩子代码之前，必须先厘清 SDK 是在哪个阶段进行拦截的。一个合格的 Agent 运行并不是简单的单次 API 请求与响应，而是一个迭代的、回合制（Turn-based）的控制环。Claude 决定调用某个工具，SDK 去运行该工具，然后将结果反馈给 Claude。&lt;/p&gt;</description></item></channel></rss>