| name | tool-security |
| description | Design secure tool systems for AI agents using the dual-defense pattern (prompt guidance + code enforcement). Use when (1) designing tool prompts with preference chains and safety constraints, (2) implementing code-layer security checks for agent tool calls, (3) building tool permission and sandbox systems, (4) auditing existing tool security architectures. Triggers on phrases like tool security, agent tool design, preference chain, sandbox, tool permission, dual defense. |
Tool Security
Prompt引导行为,Code确保安全。两层缺一不可。
Core Philosophy
LLM 是概率性的,无法通过 prompt 达到 100% 行为一致性。
单靠 Prompt = 赌博
单靠 Code = 失去 LLM 灵活性
Prompt + Code = 引导 + 兜底
Step 1: Design the Prompt Layer (第一道防线)
Prompt 层负责"让模型倾向于做对的事"。三个关键 pattern:
Preference Chain — 引导模型选最优工具/路径:
Do NOT use [general] when [specific] is available:
- [scenario]: use [specific] instead of [general]
Because [reason].
If [edge case], fallback to [general].
Risk Declaration — 用 NEVER 做硬约束,用 prefer 做软引导:
NEVER [destructive action] unless user explicitly requests.
Prefer [safe alternative] over [risky approach].
Sandbox Instructions — 动态注入环境限制,而非静态描述。
详见 references/prompt-layer.md
Step 2: Implement the Code Layer (第二道防线)
Code 层独立于 Prompt,用确定性逻辑兜底。典型的安全检查管线:
命令输入
├─ 控制字符检查 → block
├─ 注入模式检测 → block
├─ 管线式分层检查
│ ├─ 早期验证器(安全操作快速放行)
│ └─ 主验证链(危险操作层层递进)
└─ 结果: passthrough / ask / deny
关键设计:
- 管线式执行,常见安全操作尽早放行
- 检测到风险时 ask(用户确认)而非 deny(直接拒绝)
- 独立于 prompt,安全团队可独立审查
详见 references/code-layer.md
Step 3: Connect the Two Layers
5 个设计原则:
- Prompt 做软约束,Code 做硬约束 — "prefer" vs if-else
- Code 层独立于 Prompt 层 — 删除 prompt 不影响安全
- 管线式检查有优先级 — 常见安全操作不浪费计算
- Code 层给用户选择权 — ask > deny
- 两层用不同的"语言" — Prompt 对 LLM,Code 对执行环境
详见 references/dual-defense.md
Key Rules
- 永远不要只靠 Prompt 做安全 — 概率性 LLM 不适合做确定性安全决策
- 永远不要只靠 Code 做安全 — 没有 prompt 引导,code 兜底的请求会暴增
- Code 层用 ask 而非 deny — 除非是明确恶意,保留用户控制权
- 管线式 > 全量检查 — 常见安全操作尽早放行
- 两层失效场景必须分析 — 知道边界在哪才能补漏洞