Automation & CI · As of 2026-11-25

Claude Code in GitHub Actions: PR Reviews with claude -p and a Custom Base URL

As of 2026-11-25, the most controllable way to run Claude Code in GitHub Actions is to call headless mode, claude -p, from a plain run step. You point it at your API service with the ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN environment variables, then lock down permissions and spend with --permission-mode dontAsk, --tools, --max-turns and --max-budget-usd. This guide gives you a copy-paste PR-review workflow and explains key storage, permission settings, model choice and one sub-key per pipeline for teams. QCode is an independent third-party API service and is not affiliated with Anthropic.

Updated 2026-11-26

Key facts

  • claude -p "prompt" (long form --print) runs non-interactively. It exits 0 on success and non-zero on failure. --output-format takes text, json or stream-json; the json payload includes result, session_id and total_cost_usd (Anthropic docs, read 2026-11-25).
  • Under claude -p, permissions.allow rules in the repository's .claude/settings.json are not applied, because the folder was never trusted. deny and ask rules, hooks and the env block do apply. Put CI allow rules on the command line.
  • The official action, anthropics/claude-code-action@v1, documents four ways to authenticate: an API key, a subscription OAuth token, OIDC workload identity federation, and Bedrock / Agent Platform / Foundry. It documents no custom base URL. For a third-party endpoint, calling the CLI directly is the safer route.
  • Three cost brakes: --max-turns (agent turns), --max-budget-usd (a cap based on the client-side estimate), and the workflow's timeout-minutes plus concurrency.
  • Give every pipeline its own QCode team sub-key. If one leaks you revoke only that key, and usage splits cleanly by pipeline.

Why not just use the official action?

The official claude-code-action is great for interactive "@claude in a comment" flows. It handles GitHub App auth, comment write-back and checks on who triggered the run. But none of its inputs (anthropic_api_key, claude_code_oauth_token, use_bedrock, use_vertex, use_foundry, settings, claude_args and others) is a base URL. The old claude_env input is marked deprecated in favor of "environment in the settings JSON", and the docs do not promise that ANTHROPIC_BASE_URL set that way is supported. So this guide does not recommend that path; if you want to try it anyway, test it with a small request first.

Calling the CLI yourself has three advantages:

  1. You control every environment variable, so the base URL, key and model are explicit.
  2. You don't need to install the Claude GitHub App, so you don't grant its full repository permission set.
  3. The same command moves unchanged to GitLab CI, Jenkins, self-hosted runners or Docker.

Step 1: Store the key as a secret

In the repository, open Settings → Secrets and variables → Actions and add a secret such as QCODE_CI_KEY whose value is your key starting with cr_. You can use an organization-level secret across repositories, but one sub-key per pipeline (below) is the better pattern.

Ground rules:

  • Never put the key in .claude/settings.json, .env or any committed file.
  • Never echo the key. GitHub masks secrets in logs, but don't rely on it.
  • In public repositories, runs triggered by fork pull requests do not receive secrets. That is a safeguard, not a bug. Don't switch to pull_request_target and check out untrusted code just to make forks work.

Step 2: Set the base URL and token in the workflow

QCode's Anthropic-protocol endpoint is https://api.qcode.cc/api. Authenticate with ANTHROPIC_AUTH_TOKEN, which Claude Code sends as an Authorization: Bearer header. Don't also set ANTHROPIC_API_KEY: per Anthropic's docs, in -p mode that variable is always used when present.

Alternate hosts: asia.qcode.cc (Asia) and us.qcode.cc (North America / Europe). Measure latency from the region your runners live in before you choose.

Step 3: A copy-paste PR-review workflow

This workflow runs when a pull request is opened or updated. It feeds the diff to Claude on stdin, exposes only the Read tool, and posts the review as a PR comment.

# .github/workflows/claude-pr-review.yml
name: claude-pr-review

on:
  pull_request:
    types: [opened, synchronize, ready_for_review]

permissions:
  contents: read
  pull-requests: write

concurrency:
  group: claude-review-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  review:
    if: github.event.pull_request.draft == false
    runs-on: ubuntu-latest
    timeout-minutes: 15
    env:
      ANTHROPIC_BASE_URL: https://api.qcode.cc/api
      ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_CI_KEY }}
      CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
      PR_NUMBER: ${{ github.event.pull_request.number }}
      GH_TOKEN: ${{ github.token }}
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 1

      - name: Install Claude Code
        run: |
          curl -fsSL https://claude.ai/install.sh | bash -s stable
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"

      - name: Run review
        run: |
          gh pr diff "$PR_NUMBER" > pr.diff
          claude -p "You are reviewing a pull request. The diff is on stdin. \
          Report bugs, security issues and missing tests. Cite file:line. \
          Be concise." \
            --model claude-sonnet-5-5 \
            --setting-sources user \
            --settings '{"permissions":{"deny":["Read(./.env)","Read(./.env.*)"]}}' \
            --permission-mode dontAsk \
            --tools "Read" \
            --max-turns 8 \
            --max-budget-usd 1.50 \
            --output-format json < pr.diff > review.json

      - name: Post comment
        run: |
          jq -r '.result' review.json > review.md
          echo "Estimated cost (USD): $(jq -r '.total_cost_usd' review.json)" >> "$GITHUB_STEP_SUMMARY"
          gh pr comment "$PR_NUMBER" --body-file review.md

What each setting does:

Flag / setting Purpose
--setting-sources user Loads user settings only. The repo's .claude/settings.json and .mcp.json are not read, so a PR that changes hooks or env can't run them in CI
--settings '{...}' Extra settings for this run; here it denies reading .env files
--permission-mode dontAsk Denies every call that would need approval; actions that need none, such as reading files in the working directory, still run
--tools "Read" Actually restricts the built-in tools. --allowedTools only skips approval and does not block other tools
--max-turns 8 Caps agent turns; the run exits with an error at the limit
--max-budget-usd 1.50 Stops at a client-side cost estimate, which can differ from your bill, so leave headroom
timeout-minutes / concurrency Stops stuck jobs; a new push to the same PR cancels the older review
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC Turns off auto-updates, telemetry and other nonessential traffic in a throwaway CI container

A note on injection: don't splice user-controlled text such as PR titles or branch names into the shell command. If you need them, pass them as environment variables and tell Claude to treat them as data.

Going further: a JSON Schema quality gate

--json-schema makes the final answer match a schema, returned in the structured_output field. This step fails the job when blocking issues are found:

claude -p "Review the diff on stdin. Count only blocking issues." \
  --model claude-sonnet-5-5 \
  --permission-mode dontAsk --tools "Read" --max-turns 6 \
  --output-format json \
  --json-schema '{"type":"object","properties":{"blocking":{"type":"integer"},"summary":{"type":"string"}},"required":["blocking","summary"]}' \
  < pr.diff > gate.json

jq -e '.structured_output.blocking == 0' gate.json

If the model declines or the run fails, the payload has no structured_output field, jq -e returns non-zero, and the gate fails. That is the safe default.

Permissions and safety: the CI pitfalls

  1. Project allow rules are skipped. claude -p never shows the workspace trust dialog, so permissions.allow in the repo's .claude/settings.json is skipped and a "this workspace has not been trusted" warning goes to stderr. Use --allowedTools, for example --allowedTools "Bash(npm test)".
  2. Repo hooks and env do run. Without limits, -p runs hooks from project settings and connects servers in .mcp.json. When you review someone else's code, keep them out with --setting-sources user.
  3. Always set the permission mode explicitly. Versions and docs describe the -p default differently, so write --permission-mode in every CI command.
  4. Keep --dangerously-skip-permissions for isolated containers. It equals bypassPermissions and skips almost every prompt.
  5. Minimize the GitHub token. Grant contents: read and pull-requests: write only. Put "auto-fix and push" jobs in a separate workflow.

Cost control: model, turns and concurrency

Official price ×1.0, per QCode's /models page (read 2026-11-26; live prices on /models win):

Model ID Input / output per 1M tokens Good CI fit
claude-haiku-5-5 $0.10 / $0.50 (prompt ≤100K); $0.50 / $2.50 above 100K change summaries, labels, commit messages
claude-sonnet-5-5 $2 / $10 everyday PR review, writing tests
claude-opus-5-5 $4 / $20 security review, risky refactors

Illustrative arithmetic only: a review that reads 60K tokens and writes 4K on Sonnet 5.5 costs about $0.12 + $0.04 = $0.16. Multi-turn runs resend context, and prompt-cache reads cost 5% of the input price for Opus 5.5 and Sonnet 5.5 (2.5% for Fable 5.2), per Anthropic's price list as of 2026-11-26, which cuts the repeated part.

More tips: for huge diffs, review changed files only or split by directory. Keep a short CLAUDE.md with your review rules, since Claude reads it on every run. Use concurrency to avoid overlapping runs; the team edition gives 35 concurrent requests per unit.

Team pattern: one sub-key per pipeline

QCode's team edition is sold in units. Each unit includes a $4,000 pooled monthly quota (monthly reset, no daily cap) and 35 concurrent requests, and is sized for 3-5 people; each member gets a sub-key. For CI we suggest:

  • a review-bot sub-key for PR review only, with a low quota;
  • a nightly-tests sub-key for scheduled jobs;
  • a release-notes sub-key for release scripts.

If one key leaks you revoke just that key and the other pipelines keep running. Keeping a separate sub-key per pipeline also keeps spend easy to attribute. More on shared keys: /en/claude-code-team-shared-keys.

GitLab CI version

claude-review:
  image: node:22
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  variables:
    ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
  script:
    - npm install -g @anthropic-ai/claude-code
    - git fetch origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - git diff "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD" > mr.diff
    - claude -p "Review the diff on stdin." --model claude-sonnet-5-5 --setting-sources user --permission-mode dontAsk --tools "Read" --max-turns 6 --output-format json < mr.diff > review.json
  artifacts:
    paths: [review.json]

Store ANTHROPIC_AUTH_TOKEN under GitLab CI/CD Variables with Masked and Protected checked. The npm package needs Node.js 22 or later.

Before you ship: run the same command locally

Most CI problems reproduce on a laptop. Export the same two variables in your terminal and run the exact flags first:

export ANTHROPIC_BASE_URL=https://api.qcode.cc/api
export ANTHROPIC_AUTH_TOKEN=cr_your_test_key
git diff main...HEAD | claude -p "Review the diff on stdin." \
  --model claude-sonnet-5-5 --permission-mode dontAsk --tools "Read" \
  --max-turns 4 --output-format json | jq '{cost: .total_cost_usd, text: .result}'

If you get a result and a total_cost_usd locally, the key, endpoint and flags are fine, so move the command into the workflow. If it works locally but fails in CI, check that the secret was injected, that the runner can reach the endpoint host, and whether the PR came from a fork.

When several repositories share the same review logic, turn the job into a GitHub reusable workflow. Each repository passes only its own sub-key secret, while the prompt, model and limits live in one place.

Common errors

  • 401 / authentication failed: check the secret name, make sure ANTHROPIC_API_KEY isn't also set, and confirm the base URL ends in /api. See /en/claude-code-401-custom-base-url.
  • "this workspace has not been trusted": project allow rules were skipped; use --allowedTools.
  • Exit at max turns: raise the limit or split the task.
  • claude: command not found: the native installer puts the binary in ~/.local/bin; add it to $GITHUB_PATH.

Sources: Anthropic Claude Code docs (headless, CLI reference, permissions and GitHub Actions pages) and QCode's headless docs, all read 2026-11-25.

FAQ

Can the official claude-code-action use a custom base URL?

As of 2026-11-25, the official docs list only API key, subscription OAuth token, OIDC federation and the three cloud providers as ways to authenticate, with no base URL option. For a third-party endpoint, call claude -p directly in a run step and set the variables yourself.

Should CI use ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY?

With QCode, use ANTHROPIC_AUTH_TOKEN set to your cr_ key, together with ANTHROPIC_BASE_URL=https://api.qcode.cc/api. Don't also set ANTHROPIC_API_KEY, because -p mode always uses it when it is present.

Why are the allow rules in my .claude/settings.json ignored in CI?

claude -p never shows the workspace trust dialog, and project permissions.allow rules apply only after the folder is trusted. Pass allow rules with --allowedTools or --settings instead.

What is the difference between --allowedTools and --tools?

--allowedTools lets the listed tools run without approval but does not remove other tools. --tools restricts which built-in tools exist at all. For CI review jobs, use --tools "Read" with --permission-mode dontAsk.

How do I stop one CI run from burning the budget?

Combine --max-turns, --max-budget-usd, timeout-minutes and concurrency, and give CI its own low-quota sub-key. --max-budget-usd uses a client-side estimate and spend can pass the cap slightly, so leave headroom.

Why didn't the review run on a fork's pull request?

In public repositories GitHub doesn't pass secrets to runs triggered by fork pull requests, so there is no key to use. That is by design. Don't work around it with pull_request_target plus a checkout of untrusted code.

Which model is the best value for CI?

Use claude-sonnet-5-5 for everyday reviews, claude-haiku-5-5 for summaries and labels, and claude-opus-5-5 for security reviews. Check /models for live prices.

Next step: give CI its own team keys

If several pipelines and repositories run Claude Code, QCode's team edition is sold in units: each unit includes a $4,000 pooled monthly quota and 35 concurrent requests, for 3-5 people, and each member gets a sub-key. See /enterprise for current terms, or start with a personal plan on /pricing.

Next step: give CI its own team keys

One key for both the Anthropic Messages API and OpenAI-compatible APIs. Claude and GPT are billed at the official price ×1.0; live rates are on /models.

Not sure where to start?

Try it for a week

Small Pack: $4 for $30 of quota, valid 7 days

Use it every day

Starter: $9.00/month with $5 of quota every day — just $0.060 per $1 of quota, vs about $0.113 for the Medium Pack