Advertisement
Verified Partner
Enterprise Cloud Infrastructure, GPU Clusters & AI APIs
Deploy high-throughput inference and quant trading pipelines with ultra-low latency.
Explore Platform →

Claude Code CLI Mastery: Terminal Agentics, Headless Refactoring & PR Automation

By Marcus Sterling • Advanced • 19 min read • Updated 2026-09-12

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.

BASH
# 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
Note: Tip: Set cost protection limits in your terminal profile with export CLAUDE_COST_LIMIT=10.0 to prevent runaway API expenditures.
Advertisement
Verified Partner
Quantitative Trading Systems & 30 AI Business Blueprints
Build predictable monthly recurring revenue with retainers & automated bots.
View Blueprints →

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.

BASH
# 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."
Note: Productivity Boost: Chaining Claude Code with shell pipelines allows automating tedious legacy framework migrations overnight.

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.

JSON
# 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"]
    }
  }
}
Note: Key Insight: Giving Claude Code direct schema access eliminates 95% of SQL column name and relation errors.

Knowledge Check: Test Your Understanding

1. What is the primary advantage of Claude Code over web-based chat interfaces?

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.

BASH
# 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:

MARKDOWN
# 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:

BASH
# 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:

BASH
#!/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:

YAML
# .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

Get 1 AI agent blueprint every week

Join the free PVT newsletter: one practical AI agent or automation you can build and sell, every week. No spam.