Claude Code CLI Mastery: Terminal Agentics, Headless Refactoring & PR Automation
What You Will Master in This Tutorial
- Install and configure @anthropic-ai/claude-code with proper environment and budget settings.
- Execute headless repository refactors with one-shot terminal commands.
- Automate GitHub pull requests with comprehensive commit diffs and test verification.
- Connect Claude Code CLI to external databases and APIs using FastMCP.
1. Installing and Configuring Claude Code CLI
Claude Code is Anthropic's official terminal-native autonomous coding tool. Designed to operate directly in your shell, it navigates complex repositories, edits files, executes unit tests, and commits changes autonomously.
# Install Claude Code globally via npm
npm install -g @anthropic-ai/claude-code
# Authenticate with Anthropic API key
export ANTHROPIC_API_KEY="sk-ant-api03-..."
# Launch interactive agent session in any git directory
claude
2. Headless Refactoring & Non-Interactive Invocations
Claude Code can run headlessly in CI/CD pipelines or automated developer scripts using the --print or -p flag, enabling autonomous lint fixes, migrations, and test additions.
# Run headless refactor across all repository controllers
claude -p "Migrate all Express controllers in src/controllers/*.js to TypeScript strict types. Run npm test after each file. Commit when passing."
# Generate automated pull request description from git diff
claude -p "Review git diff origin/main...HEAD and generate a Markdown PR description with Summary, Breaking Changes, and Testing Evidence."
3. Connecting Custom MCP Servers in CLI
Claude Code supports Anthropic's Model Context Protocol (MCP). You can connect your local PostgreSQL database or Redis cluster directly to the CLI agent so it can query real schemas during code generation.
# claude.config.json
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost:5432/production"]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/dev/projects"]
}
}
}
Knowledge Check: Test Your Understanding
4. Step by step: run a headless refactor sweep
Section 2 introduced non-interactive invocations; here is the full working pattern for the job headless mode exists for — a repository-wide refactor you can supervise by results instead of by keystrokes. Three passes: recon with read-only tools, the edit with a bounded tool set and turn budget, and a machine-readable summary for your records.
# Pass 1 - recon: plan the change, touch nothing
claude -p "List every file that imports the legacy logger and describe the
change each one needs. Do not edit anything." \
--allowedTools "Read,Grep,Glob"
# Pass 2 - execute: bounded tools, bounded turns
claude -p "Replace all imports of src/legacy/logger with src/lib/log.
Update the call sites, run the test suite, and stop immediately
if any test fails." \
--allowedTools "Read,Edit,Bash" --max-turns 20
# Pass 3 - report: JSON summary for CI or your changelog
claude -p "Summarize the changes from this refactor as a changelog entry." \
--output-format json > refactor-summary.json
Before pass 2 ever runs in anger, give the agent the project’s standing orders in a CLAUDE.md at the repository root — Claude Code reads it at the start of every session, interactive or headless:
# Project rules
- Run `npm test` before committing; never commit on a red suite.
- Never edit generated files under src/gen/.
- Log through src/lib/log.ts. The legacy logger in src/legacy/ is
deprecated and is being removed.
- Prefer small, focused diffs over sweeping rewrites.
Verify with git, not with confidence
Headless output is a claim; the diff is the evidence. Build the review into the workflow: after any sweep, inspect what actually changed before the next pass builds on it — and when two refactors are independent, run them in parallel git worktrees so neither tree’s edits can contaminate the other:
# What did the sweep actually touch?
git diff --stat
git status --porcelain
# A second, independent sweep in its own worktree, in parallel
git worktree add ../repo-docs-sweep HEAD
cd ../repo-docs-sweep
claude -p "Update the README examples to the new logger API from
src/lib/log. Do not change any source files." \
--allowedTools "Read,Edit" --max-turns 10
The worktree gives the second agent a full checkout of the same commit with its own working directory and branch, so both sweeps proceed at once and merge — or don’t — as ordinary git history. Autonomy scales when verification is mechanical.
5. A complete worked example
Put the sweep on rails: a short shell script that refactors one module at a time and commits each module separately. Small commits are the supervision strategy — every step is reviewable with git show and reversible with git revert, which is what makes an unsupervised run acceptable:
#!/usr/bin/env bash
# refactor-sweep.sh - rename a deprecated helper, one module at a time
set -euo pipefail
for module in auth billing reports; do
echo "== Refactoring $module =="
claude -p "In src/$module, rename the deprecated getUserData() helper
to fetchUserProfile() and update every caller in that module.
Run the module's tests when you are done." \
--allowedTools "Read,Edit,Bash" --max-turns 15
git add -A
git commit -m "refactor($module): rename getUserData to fetchUserProfile"
done
echo "Sweep complete. Review with: git log --oneline -3"
Run it in the evening and review three tidy commits in the morning. If the billing refactor went sideways, revert that one commit and re-run just that module with a tighter prompt; the other two modules are untouched. Combined with the MCP connections from section 3 — schema access while the agent works — this is the workflow that turns headless mode from a demo into infrastructure.
Later: promote the sweep to a nightly CI job
Once the sweep has earned trust locally, the same script runs unchanged in CI — the only additions are installing the CLI and providing the API key as a secret, which is exactly the headless-auth pattern from the troubleshooting list below. A nightly run against the day’s merges keeps small refactors small:
# .github/workflows/nightly-refactor.yml (excerpt)
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run the refactor sweep
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: ./refactor-sweep.sh
Keep the workflow’s output as a pull request rather than a direct push: the per-module commits arrive review-ready, and a human still merges — automation proposes, people dispose.
6. Troubleshooting
- "claude: command not found" right after a successful global install. The npm global bin directory is not on your PATH. Run npm config get prefix, add its bin subdirectory to your shell profile, and open a fresh terminal — or bypass the issue entirely with npx @anthropic-ai/claude-code, which runs the same package without the global install.
- Authentication fails in CI but works on your machine. Your laptop has a saved login; the CI runner has only the environment. The ANTHROPIC_API_KEY export from section 1 must exist in the CI job’s environment (store it as a masked secret), and no interactive login flow will save you there — headless environments can only use the key.
- The headless run never exits. Something in the session is waiting for input: a prompt that asks a clarifying question, or a tool approval with no one to approve it. Always pair -p with --max-turns, restrict --allowedTools to what the job needs, and phrase the prompt as an instruction with a completion condition ("stop immediately if any test fails"), not as a conversation opener.
- The agent edited files far outside the intended scope. Scope is your job, not the model’s. Name the directory in the prompt (the worked example scopes every run to one module), keep Edit out of --allowedTools for recon passes, forbid generated paths in CLAUDE.md, and review git diff before each commit lands — the per-module commit rhythm exists so an overreach is a revert, not a rescue.