Excellent for agents when --json, scoped auth, and explicit approval gates are used.
Many repo, issue, PR, release, and API commands support --json fields that agents can parse.
Most read operations run without prompts after auth, but first-time login remains interactive.
Safe read commands are clear, while merge/delete/edit actions need explicit approval and scoped tokens.
The command surface is discoverable through help output and can be documented cleanly in AGENTS.md.
安装方式
$ brew install gh $ winget install --id GitHub.cli $ sudo apt install gh 常用命令
$ gh repo view owner/repo --json name,description,stargazerCount,defaultBranchRef Read-only repository context for agents.
$ gh pr list --state open --json number,title,author,url,reviewDecision,mergeStateStatus,updatedAt Useful for triage, release checks, and review summaries.
$ gh pr view 123 --json number,title,files,commits,reviews,statusCheckRollup,url Reads review and CI context before the agent summarizes risk.
$ gh pr merge 123 --squash Changes repository state and must require human approval.
Agent 使用示例
Use gh only for read-only GitHub inspection unless I approve a state-changing command. Prefer --json and summarize PR blockers before suggesting next steps. Paste this into AGENTS.md for repositories where the agent can inspect GitHub state.
安全说明
- Treat repo view, issue list, pr list, and pr view as the default safe command set.
- Require approval before merge, close, delete, edit, release, or workflow-run commands.
- Prefer scoped or read-only tokens for agent sessions and always request JSON output where supported.
TL;DR
GitHub CLI 是最适合给编码 Agent 配置的默认工具之一,因为它可以直接读取仓库、Issue、PR、Release 和 Workflow 状态,不需要抓取 GitHub 页面。
- 最适合:PR 分拣、Issue 查询、发布上下文、Workflow 状态、仓库元数据。
- 不适合自动执行:合并 PR、关闭 Issue、删除 Release、修改仓库设置、触发 Workflow。
- Agent 规则:先用只读命令,优先使用 `--json`,任何会改变仓库状态的命令都必须先询问用户。
Agent 可以安全执行的命令
gh repo view owner/repo --json name,description,stargazerCount,defaultBranchRef
gh pr list --state open --json number,title,author,url,reviewDecision,mergeStateStatus,updatedAt
gh pr view 123 --json number,title,body,files,commits,reviews,statusCheckRollup,url
gh issue list --state open --json number,title,labels,updatedAt,url必须人工确认的命令
gh pr merge
gh issue close
gh release delete
gh repo edit
gh workflow run标准 Agent 指令
除非用户明确批准,否则只能用 GitHub CLI 做只读检查。必须优先使用 `--json`。在运行 merge、close、delete、edit 或 workflow run 之前,Agent 必须说明要执行的命令、预期影响、回滚方式,以及为什么需要批准。
示例流程:总结 PR 风险
1. 用 `gh pr list --json ...` 读取开放 PR。 2. 用 `gh pr view --json ...` 检查风险 PR。 3. 总结 review blocker、合并冲突、CI 状态和更新时间。 4. 不直接合并。下一步如果会改变状态,必须等待用户确认。
常见失败
- 没有认证:先运行 `gh auth status`,必要时手动 `gh auth login`。
- Token 权限过大:Agent 会话优先使用只读权限。
- 仓库上下文错误:显式传入 `owner/repo`。
- JSON 字段不存在:检查 `gh help pr list`,或减少字段列表。