Agent-Friendly CLI 综合 4 个权威来源
把 几百个 API endpoint
重构为
Agent 真正会用的工具
Agent 不需要 GUI,也不需要 1:1 包装的 API。它需要的是按业务 workflow 组合的、可自省的、对 hallucination 有防御的 CLI 。几百个 API 应该被合并成 30–50 个 agent-facing 命令 ——这才是合理的合并比。
来源 Anthropic 官方 · Justin Poehnelt (Google) · AXI benchmark · CWC 2026 #14
实证 425 runs / 17 tasks / Sonnet 4.6
~/internal-cli
✗ 1:1 包装:Agent 自己拼装 workflow
internal-cli users list → 找 Jane 的 ID
internal-cli users get --id 73a9f...
internal-cli events query --user 73a9f...
internal-cli events create --user 73a9f... --time ...
# 4 步、4 次 round-trip、每一步都可能 hallucinate ID
▼ 合并为 workflow 命令
✓ Workflow-merged:一步到位
internal-cli schedule-meeting \
--with "Jane" \
--topic "Q1 review" \
--duration 30m
# 内部串联 lookup → 查双方空闲 → 创建 → 邀请
§1 · 为什么是 CLI
CLI 不只是"另一个接口"——它是 token 效率的代名词
Anthropic 在 Claude Code 的官方文档里给出明确判断:CLI 工具是 agent 与外部世界交互最 context-efficient 的方式。这不是品味,而是约束驱动的设计——schema 定义本身就消耗 context,调用越多 round-trip 损耗越大。AXI 的 425 次实证给出了硬数据。
"CLI tools are the most context-efficient way to interact with external services."
— code.claude.com/docs/en/best-practices
Claude Code 自身只给 agent 4 个 primitive tool(bash / read / write / edit),让它通过 shell 与世界交互。这不是简陋——bash 是最通用、最可组合的接口。Agent SDK 进一步阐述这个设计哲学:
"The key design principle behind the Claude Agent SDK is to give your agents a computer, allowing them to work like humans do."
— Anthropic, "Building agents with the Claude Agent SDK" (2025-09-29)
AXI Benchmark:5 种条件的实证赛跑
AXI 项目(github.com/kunchenguid/axi)跑了 425 次 benchmark:17 tasks × 5 conditions × 5 repeats,Claude Sonnet 4.6。用 GitHub 操作作为代表性 workflow。
成功率赛跑(Success Rate, %)
425 runs · Claude Sonnet 4.6 · 2026-03
平均成本
$0.050
←
$0.148
省 66%(vs MCP)
平均时长
15.7s
←
34.2s
省 54% 延迟
结论:Agent-optimized CLI 在成功率、成本、延迟三个维度全面碾压 MCP。 原因清晰——MCP tool schema 每个定义就吃掉 ~200–500 tokens,发现/调用流程多一层 round-trip;CLI 天然支持 pipe 组合,一次 bash 调用可以串联多个操作。
§2 · 决策矩阵
CLI 还是 MCP?六个维度判定
DEV Community 给出的这张矩阵是工程化角度的实操指南。但更重要的判断在 Justin Poehnelt 那里——这不是二选一,而是一套架构里的两个 surface。
选 CLI
选 MCP
操作数量
< 15 个命令
50+ 个工具且 agent 无 shell
状态管理
无状态调用
需要有状态 session
Agent 是否有 shell 权限
有
没有(纯 API-only 环境)
Token 预算
紧张(CLI 更省)
不太紧张
已有工具基础
已有 CLI,包装或改造
从零搭 server
可靠性要求
高(CLI 无需额外进程)
可接受 server 依赖
实际建议 :Justin Poehnelt 的架构是 one binary → CLI + MCP 双 surface 。CLI 做执行层(性价比最高),MCP 做 discovery 层(当工具数量超过 agent 一次能记住的上限时)。两套逻辑共用同一份 schema source。
§3 · 设计原则体系
10 条原则,按实施 ROI 排序
这套原则整合自三方权威来源:Anthropic 官方 方法论、Google DevRel Justin Poehnelt 的 Workspace CLI 实战、AXI 的 benchmark 实证。每条都标注来源。前 3 条是最低门槛——做完 Phase 1 就能让现有 agent 立刻能用起来。
来源缩写
A Anthropic 官方(最高)
G Justin Poehnelt / Google
AXI AXI benchmark 实证
CWC Code with Claude 2026 #14
# 01
按 Workflow 合并,不做 1:1 包装
A
每个 CLI 命令应对应"Agent 会自然采取的行动步骤 ",而非一个底层 API endpoint。
Anthropic 在《Writing effective tools for agents》里直接点名这个常见错误:
"A common error we've observed is tools that merely wrap existing software functionality or API endpoints—whether or not the tools are appropriate for agents."
internal-cli users list
internal-cli events list
internal-cli events create \
--user-id X --title Y --time Z
internal-cli schedule-meeting \
--with "Jane" \
--topic "Q1 review" \
--duration 30m
# 内部自动:查用户 → 查双方空闲
# → 创建事件 → 发邀请
操作规则: 先列出 agent 要解决的 Top 20 高频任务,为每个任务设计"一步到位"的命令。几百个 API → 30–50 个 agent-facing 命令是正常合并比。
每个命令必须支持 --output json(或 --json),没有例外 。
# 人类模式(默认)
internal-cli orders recent
# → 漂亮的表格输出
# Agent 模式
internal-cli orders recent --output json
# → 纯 JSON,stdout 只有数据,stderr 放日志
进阶特性 做什么 为什么
--fieldsfield masks 限定返回字段 保护 context window
--streamNDJSON 每行一个 object 流式处理不爆内存
auto-detect TTY 非 TTY 时自动切 JSON agent 场景无需手动加 flag
TOON 格式 token-efficient 替代 AXI 实测省 40% token
AXI 的额外建议: 默认输出只含 3–4 个核心字段(如 id, name, status)。大文本字段自动截断,提供 --full escape hatch。包含 pre-computed aggregates(count: 47 of 1203)避免 agent 自己数。
# 03
Runtime Schema 自省,替代静态文档
G
让 CLI 自己描述自己——schema 子命令返回机器可读的方法签名。
问题不复杂:Agent 不能 Google 文档 ——查文档消耗 token 且文档会过期。
internal-cli schema orders.create
# 返回:参数类型、必填/可选、枚举值、示例、所需权限
internal-cli schema --all
# 返回所有命令的 schema 索引(agent 做 tool discovery)
"Each gws schema call dumps the full method signature—params, request body, response types, required OAuth scopes—as machine-readable JSON. The agent self-serves without pre-stuffed documentation."
— Justin Poehnelt
Help 文本 agent-friendly 要求: 前 2–3 行必须是真实使用示例 (agent 从示例学得比从 flag 描述快);清晰标注 required vs optional;约束 flag 显示枚举(--format json|table|csv);单个命令 help < 50 行 (过长稀释信号)。
# 04
Input Hardening — 防 Hallucination
G
Agent 不是可信操作员。 人类会 typo,Agent 会 hallucinate——失败模式完全不同。
错误类型 人类 Agent 防御
路径穿越 ../../.ssh 几乎不会 会(混淆路径段) canonicalize + sandbox to CWD
控制字符 copy-paste 生成不可见字符 reject ASCII < 0x20
资源 ID 内嵌 query 不会 会(fileId?fields=name) reject ? 和 #
双 URL 编码 几乎不会 常见(%2e%2e) reject % in resource names
超长输入 少见 context 长文本直接当参数 输入长度上限
def validate_input (value: str, field_type: str) -> str:
"""所有 agent 输入必须经过的校验"""
reject_control_chars(value)
reject_path_traversal(value)
reject_embedded_query_params(value)
reject_percent_encoding(value)
enforce_length_limit(value, field_type)
return value
Anthropic 在 AGENTS.md 里给出了强化版的指导:"This CLI is frequently invoked by AI/LLM agents. Always assume inputs can be adversarial."
# 05
--dry-run 是写操作必备
G AXI
所有 mutating 操作(create/update/delete)必须支持 --dry-run。
internal-cli orders cancel --order-id 12345 --dry-run
# 输出:Would cancel order 12345 (status: processing, amount: $847.00)
# 不实际执行
为什么必备: Agent 会先用 --dry-run 验证自己的理解;错误成本不对称——hallucinated 参数做 dry-run 只浪费一次调用,实际执行可能丢数据;人机协作时 agent 可以拿 dry-run 输出向人确认。
扩展: 不能有 "Are you sure? (y/n)" 交互式提示——agent 无法处理 stdin 提示。destructive 操作用 --confirm flag 显式确认。
永远不要要求浏览器 OAuth redirect 或交互式登录。
✓ 可接受
环境变量 INTERNAL_API_TOKEN
Credential 文件 ~/.config/.../credentials.json
Service account 注入容器环境
系统 Keychain(人类便利模式)
✗ 不可接受
"Press Enter to continue"
打开浏览器做 OAuth consent
交互式密码输入(stdin)
错误消息必须是 specific & actionable ,不是 opaque error code 或 stack trace。
{
"error": "ERR_4012",
"trace": "at OrderService.java:847..."
}
{
"error" : "order_not_found" ,
"message" : "Order ID 12345 does not exist" ,
"suggestion" : "Use 'internal-cli
orders search --customer X' to find
valid order IDs" ,
"exit_code" : 1
}
"If a tool call raises an error, you can prompt-engineer your error responses to clearly communicate specific and actionable improvements, rather than opaque error codes or tracebacks."
— Anthropic, Writing effective tools for agents
Exit Code 体系(agent-cli-framework)
Code 含义 Agent 该怎么做
0 成功 继续下一步
1 瞬态错误(可重试) 读 stderr 诊断,等待后重试
2 配置/认证错误 停止,报告缺失凭证
3 输入验证失败 修正输入后重试
4 速率限制 等待后重试
124 超时 重试或拆分请求
# 08
Ship CONTEXT.md / SKILL.md
G CWC
--help 告诉 agent 参数格式,但无法传达隐含的不变量和最佳实践 。在 CLI 旁边 ship 一个 SKILL.md,agent 拿到这个工具时一并获取。
---
name : internal-orders-cli
version : 2.1.0
---
# Internal Orders CLI — Agent Guide
## 不变量(每次操作前必须满足)
- ALWAYS use --output json when calling this CLI
- ALWAYS use --fields to limit response size
- ALWAYS use --dry-run before any delete/cancel
- NEVER pass customer PII directly — use ID lookup first
## 常见 Workflow
### 退款处理
1. orders search --customer-id CID --status disputed
2. orders refund --order-id OID --reason "..." --dry-run
3. 确认 dry-run 输出正确后:去掉 --dry-run 执行
Will Steuk 在 CWC 2026 Session #14 展示:把 400 行 system prompt 中的业务逻辑全部迁移到 Skills 做 progressive disclosure——只在 agent 需要时才 pull 进 context。结果:system prompt 从 400 行压到 15 行,eval pass rate 从 62% 跳到 92%。
# 09
Response Token 纪律
A AXI
Anthropic 的硬规则:"For Claude Code, we restrict tool responses to 25,000 tokens by default."
策略 实现 效果
Pagination --limit 20 + --page-token防止一次 dump 全表
Field masks --fields "id,name,status"减少 50–80% 返回量
Truncation + hint 大字段截断 + [truncated, 4.2KB total, use --full] Agent 按需展开
Pre-computed aggregates 输出含 total: 1203, shown: 20, filtered: 47 减少往返调用
Token-efficient format TOON / 压缩 JSON AXI 实测省 40%
AXI 的独特贡献:Contextual Disclosure
每个输出末尾附带"下一步建议"——让 agent 不需要事先知道所有可能的下一步,工具本身在引导:
count : 3 of 47
orders[3] {id,status,amount}:
ORD-001, processing, $847.00
ORD-002, shipped, $124.50
ORD-003, disputed, $2100.00
help[1] :
Run `internal-cli orders detail ORD-003` to see dispute details
# 10
Raw JSON Payload 路径
G
当 CLI 背后是 REST API 时,提供 "透传"路径 ——bespoke flags 给人类,--json 给 agent。
# 人类友好模式(bespoke flags)
internal-cli users create --name "Jane" --role admin --team engineering
# Agent 透传模式(raw API payload)
internal-cli users create --json '{
"name": "Jane",
"role": "admin",
"team": "engineering",
"permissions": ["read", "write", "admin"],
"metadata": {"source": "agent-created", "ticket": "JIRA-4521"}
}'
为什么 Agent 偏爱 JSON: 直接映射 API schema 零翻译损失;支持嵌套结构(bespoke flags 表达不了);LLM 天然擅长生成 JSON;消除了 flag 顺序、引号转义等 shell 歧义。
"Make the raw-payload path a first-class citizen alongside any convenience flags you ship for humans. Most teams can't afford to maintain two separate tools."
— Justin Poehnelt
§4 · 实施路径
3 阶段、10 步:从最低门槛到 agent-native
按 ROI 排序——Phase 1 的三步两周内可完成,立刻让现有 agent 能用起来 。优先改高频 workflow 的 CLI,不要一次性改所有。
PHASE 1
1–2 周
最低可行改造
让现有 agent 立刻能用,立竿见影效果。
1. 所有命令加 --output json → Agent 能 parse 输出
2. Input validation + hardening → 防 hallucination 越权
3. 错误改为结构化 + 可操作建议 → Agent 能自我修正
PHASE 2
2–4 周
Agent-Optimized
让 agent 自服务、写操作有安全网。
4. 加 schema / --describe → runtime 自省
5. 加 --fields 和 --limit → 保护 context
6. 加 --dry-run → 写操作安全网
PHASE 3
4–8 周
Agent-Native
从 1:1 包装升级为 workflow-merged。
7. Ship SKILL.md / CONTEXT.md → 隐含知识
8. 按 workflow 合并命令 → 减少 tool 数量
9. 考虑 MCP surface(如需) → 无 shell 环境覆盖
10. Eval-driven 优化 → 让 Claude 自己优化 description
§5 · CWC 2026 #14 实证
"工具越多 agent 越强"是错的
Will Steuk(Anthropic)在 Code with Claude 2026 Session #14 展示了一个 agent 退化-修复的真实案例。三个数字讲完核心 insight:
System Prompt
400
15
业务逻辑迁移到 Skills (progressive disclosure)
Custom Tools
12
3
砍到 bash / read / write 三个 primitive (agent 用 code execution 自组合)
Eval Pass Rate
62%
92%
+30 个百分点 (同模型、同任务、不同工具设计)
核心 insight: 12 个 custom tool 的 schema 定义消耗大量 context token,挤占了 agent 的"思考空间"。砍到 3 个 primitive + 按需加载 skill,反而让 agent 更聪明。
Will 给出的工具设计优先级
先给 human-like primitives (bash / read / write)——通用能力
按需加 custom tool ——只在 primitive 无法高效完成时
MCP 最后才考虑 ——只在无 shell 环境或需要 discovery 时
§6 · 架构参考
Single Binary, Multi-Surface
Justin Poehnelt 在 Google Workspace CLI 的架构选择:一套核心逻辑,多个对外 surface 。CLI 和 MCP 从同一个 schema source 生成——避免维护两套工具的成本。
API / Backend
existing services
Core Binary
internal-cli
single source of schema + logic
CLI
human / agent shell
$ internal-cli ...
MCP
stdio server
discovery surface
Skill
SKILL.md
progressive context
SDK
env / library
embedded use
同一份 schema source · 自动生成 4 种 surface
"Most teams can't afford to maintain two separate tools." — 让 schema 自动生成多个 surface 的代码 / 配置,是规避双重维护成本的核心。
Agent-Readiness Score(agent-cli-builder)
该项目提供 11 维度评分 rubric,用来评估现有 CLI 的 agent 友好程度:
01 Structured output(JSON/TOON)
02 Semantic exit codes
03 Input validation depth
04 Schema introspection
05 Help text quality
06 Dry-run support
07 Non-interactive auth
08 Field mask / pagination
09 Error actionability
10 Skill file presence
11 Multi-surface exposure
§7 · 反模式
常见错误,逐条对应解法
这 7 条都是 Anthropic / Justin Poehnelt / AXI 反复点名的典型错误。如果你的 CLI 命中其中 3 条以上,agent 调用基本都会卡住——但每条都有清晰的解法。
1:1 包装每个 API endpoint Tool 数量泛滥,agent 选择困难,schema 吃掉大量 context
→
按 workflow 合并 — 几百 API 收敛到 30–50 个 agent-facing 命令
返回完整 API response 动辄几千 token,单次调用就把 context 吃光
→
默认精简(3–4 字段)+ --fields + --full escape hatch
用 UUID 做唯一标识 Agent 极易 hallucinate UUID(生成形似但错位的字符串)
→
支持 name / email / slug 等语义标识,UUID 只在内部使用
交互式确认 prompt "Are you sure? (y/n)" — Agent 无法处理 stdin 提示
→
用 --confirm 或 --dry-run + --apply 两步式 flag
文档只在网页上 Agent 查文档每次消耗 context;文档过期 agent 不知道
→
--describe / schema runtime 自省,文档随代码走
错误返回 stack trace "java.lang.NullPointerException at OrderService.java:847" — Agent 无法解析
→
结构化 error JSON + suggestion 字段告诉 agent 下一步
所有 tool schema 预加载 Schema 占用 ~200–500 tokens 每个,几十个就吃掉 context budget
→
Progressive disclosure / Tool search — 按需加载
§8 · Eval-Driven 优化
让 Claude 自己优化 tool description
Anthropic 推荐的核心方法论:写完 prototype 之后,不要靠人手动调措辞 。让 Claude 跑 eval、分析失败 transcript、自己提出优化——结果在 held-out test set 上超越人工编写的版本。
STEP 1
Prototype
在 Claude Code 手动测试
STEP 2
生成 Eval
基于真实 workflow 的 prompt-response 对
STEP 3
跑 Eval
程序化 API 调用,记录成败 / token
STEP 4
分析 Transcript
把失败 session 喂给 Claude Code
STEP 5
Claude 自动改进
优化 description / schema / 错误信息
STEP 6
Held-out 验证
防止过拟合,确认真实提升
Anthropic 内部结果: 在 Slack 和 Asana tool 的 held-out test set 评估中,Claude 优化后的工具超越了人工编写的版本 。提升主要来自 subtle refinements——更好的 namespacing、更清晰的 description、更有针对性的 tool implementation。大部分性能提升来自 tool description 的微调(措辞、示例、边界说明),而非底层实现变更。
§9 · 给客户的摘要
从"几百个 API"到"agent 真能用"的最短路径
现状
几百个内部 API,agent 无法高效调用
想通过 CLI 化提升 agent 交互效率
当前 1:1 包装思路会把问题搬到 CLI 层
建议
不做 1:1 转换 — 按业务 workflow 合并,目标 30–50 个 agent-facing 命令
渐进改造 — Phase 1 两周内可完成,立刻让现有 agent 能用
优先级 — 先改高频 workflow,不一次性改所有
双 surface — CLI 做执行层 + MCP 做 discovery 层
Eval-driven — 上线后让 Claude 自己优化 tool description
ROI 预期(基于 AXI benchmark)
−66%
Token 成本($0.148 → $0.050)
§10 · Reference Implementation
说到不如做到——把这 10 条原则做成了一个 Skill
讲完原则、benchmark、反模式、audit rubric,光说不练显然不够。我们把整套 5-phase 工作流直接做成了一个 Claude Code Skill,包含强制的 workflow merge gate、Python+Typer 模板、配套 SKILL.md 模板和 11 维 audit rubric——以及一个真能跑的完整 reference 实现。开源在 aws-samples,MIT-0。
API → Agent-Friendly CLI
5-phase prescriptive wizard ,强制把 workflow merge 放在生成代码之前——这是这个领域 #1 决定成败的环节,但也是用户最容易跳过的步骤。OpenAPI spec 在那里诱惑太大,所以 Skill 把"merge ratio < 3:1"设成 hard gate,不达标不让继续。
api-to-agent-cli/
├── SKILL.md # 5-phase wizard 主入口
├── references/
│ ├── principles-checklist.md # 10 原则 quick check
│ ├── workflow-merge-examples.md ⭐ 5 个真实合并案例
│ ├── antipatterns-quickref.md # 7 反模式 + 解法
│ ├── cli-template-python.md # Typer 写法指南
│ ├── error-schema.md # 结构化 error JSON schema
│ └── audit-rubric.md # 11 维评分(可独立调用)
└── assets/
├── inventory.template.md # Phase 1 产出
├── commands.spec.template.md # Phase 2 产出
├── SKILL.template.md # Phase 4 产出
├── audit-report.template.md # Phase 5 产出
└── example-hello-cli/ # 完整 Typer 实现
├── SKILL.md
├── pyproject.toml
└── src/hello_cli/ # 10 原则全部体现
§11 · 来源索引
12 条原始材料
所有论点都可追溯到下面的来源——每条标注[官方]/[第三方],并附原文链接和发布时间。
[05]
2026-03-04
Google DevRel
[06]
2026-03-21
benchmark