Files
claude-code-action/base-action/README.md
km-anthropic 0630ef383a feat: implement Claude Code GitHub Action v1.0 with auto-detection and slash commands (#421)
* feat: implement Claude Code GitHub Action v1.0 with auto-detection and slash commands

Major features:
- Mode auto-detection based on GitHub event type
- Unified prompt field replacing override_prompt and direct_prompt
- Slash command system with pre-built commands
- Full backward compatibility with v0.x

Key changes:
- Add mode detector for automatic mode selection
- Implement slash command loader with YAML frontmatter support
- Update action.yml with new prompt input
- Create pre-built slash commands for common tasks
- Update all tests for v1.0 compatibility

Breaking changes (with compatibility):
- Mode input now optional (auto-detected)
- override_prompt deprecated (use prompt)
- direct_prompt deprecated (use prompt)

* test + formatting fixes

* feat: simplify to two modes (tag and agent) for v1.0

BREAKING CHANGES:
- Remove review mode entirely - now handled via slash commands in agent mode
- Remove all deprecated backward compatibility fields (mode, anthropic_model, override_prompt, direct_prompt)
- Simplify mode detection: prompt overrides everything, then @claude mentions trigger tag mode, default is agent mode
- Remove slash command resolution from GitHub Action - Claude Code handles natively
- Remove variable substitution - prompts passed through as-is

Architecture changes:
- Only two modes now: tag (for @claude mentions) and agent (everything else)
- Agent mode is the default for all events including PRs
- Users configure behavior via prompts/slash commands (e.g. /review)
- GitHub Action is now a thin wrapper that passes prompts to Claude Code
- Mode names changed: 'experimental-review' → removed entirely

This aligns with the philosophy that the GitHub Action should do minimal work and delegate to Claude Code for all intelligent behavior.

* fix: address PR review comments for v1.0 simplification

- Remove duplicate prompt field spread (line 160)
- Remove async from generatePrompt since slash commands are handled by Claude Code
- Add detailed comment explaining why prompt → agent mode logic
- Remove entire slash-commands loader and directories as Claude Code handles natively
- Simplify prompt generation to just pass through to Claude Code

These changes align with v1.0 philosophy: GitHub Action is a thin wrapper
that delegates everything to Claude Code for native handling.

* chore: remove unused js-yaml dependencies

These were added for slash-command YAML parsing but are no longer
needed since we removed slash-command preprocessing entirely

* fix: remove experimental-review mode reference from MCP config

The inline comment server configuration was checking for deprecated
'mode' field. Since review mode is removed in v1.0, this conditional
block is no longer needed.

* prettify

* feat: add claudeArgs input for direct CLI argument passing

- Add claude_args input to both action.yml files
- Implement shell-style argument parsing with quote handling
- Pass arguments directly to Claude CLI for maximum flexibility
- Add comprehensive tests for argument parsing
- Log custom arguments for debugging

Users can now pass any Claude CLI arguments directly:
  claude_args: '--max-turns 3 --mcp-config /path/to/config.json'

This provides power users full control over Claude's behavior without
waiting for specific inputs to be added to the action.

* refactor: use industry-standard shell-quote for argument parsing

- Replace custom parseShellArgs with battle-tested shell-quote package
- Simplify code by removing unnecessary -p filtering (Claude handles it)
- Update tests to use shell-quote directly
- Add example workflow showing claude_args usage

This provides more robust argument parsing while reducing code complexity.

* bun format

* feat: add claudeArgs input for direct CLI argument passing

- Add claude_args input to action.yml for flexible CLI control
- Parse arguments with industry-standard shell-quote library
- Maintain proper argument order: -p [claudeArgs] [legacy] [BASE_ARGS]
- Keep tag mode defaults (needed for functionality)
- Agent mode has no defaults (full user control)
- Add comprehensive tests for new functionality
- Add example workflow showing usage

* format

* refactor: complete v1.0 simplification by removing all legacy inputs

- Remove all backward compatibility for v1.0 simplification
- Remove 10 legacy inputs from base-action/action.yml
- Remove 9 legacy inputs from main action.yml
- Simplify ClaudeOptions type to just timeoutMinutes and claudeArgs
- Remove all legacy option handling from prepareRunConfig
- Update tests to remove references to deleted fields
- Remove obsolete test file github/context.test.ts
- Clean up types to remove customInstructions, allowedTools, disallowedTools

Users now use claudeArgs exclusively for CLI control.

* fix: update MCP server tests after removing additionalPermissions

- Change github_ci server logic to check for workflow token presence
- Update test names to reflect new behavior
- Fix test that was incorrectly setting workflow token

* model version update

* Update package json

* remove deprecated workflow file (tests features we no longer support)

* Simplify agent mode and re-add additional_permissions input

- Agent mode now only triggers when explicit prompt is provided
- Removed automatic triggering for workflow_dispatch/schedule without prompt
- Re-added additional_permissions input for requesting GitHub permissions
- Fixed TypeScript types for mock context helpers to properly handle partial inputs
- Updated documentation to reflect simplified mode behavior

* Fix MCP config not being passed to Claude CLI

The MCP servers (including github_comment server) were configured but not passed to Claude. This caused the "update_claude_comment" tool to be unavailable.

Changes:
- Write MCP config to a file at $RUNNER_TEMP/claude-mcp-config.json
- Add mcp_config_file output from prepare.ts
- Pass MCP config file via --mcp-config flag in claude_args
- Use fs/promises writeFile to match codebase conventions

* Fix MCP tool availability and shell escaping in tag mode

Pass MCP config and allowed tools through claude_args to ensure tools like
mcp__github_comment__update_claude_comment are properly available to Claude CLI.

Key changes:
- Tag mode outputs claude_args with MCP config (as JSON string) and allowed tools
- Fixed shell escaping vulnerability when JSON contains single quotes
- Agent mode passes through user-provided claude_args unchanged
- Re-added mcp_config input for users to provide custom MCP servers
- Cleaned up misleading comments and unused file operations
- Clarified test workflow is for fork testing

Security fix: Properly escape single quotes in MCP config JSON to prevent
shell injection vulnerabilities.

Co-Authored-By: Claude <noreply@anthropic.com>

* bun format

* tests, typecheck, format

* registry test update

* Update agent mode to have github server as a default

* Fix agent mode to include GitHub MCP server with proper token

* Simplify review workflow - prevent multiple submissions

- Rename workflow to avoid conflicts
- Remove review submission tools
- Keep only essential tools for reading and analyzing PR

* Add GitHub MCP server and context prefix to agent mode

- Include main GitHub MCP server (Docker-based) by default
- Fetch and prefix GitHub context to prompts when in PR/issue context
- Users no longer need to manually configure GitHub tools

* Delete .github/workflows/claude-auto-review-test.yml

* Remove github_comment and inline_comment servers from agent mode defaults

- Agent mode now only includes the main GitHub MCP server by default
- Users can add additional servers via mcp_config if needed
- Reduces unnecessary MCP server overhead

* Remove all default MCP servers from agent mode

Agent mode now starts with no default servers - users must explicitly configure any MCP servers they need via mcp_config input

* Remove GitHub context prefixing and clean up agent mode

- Remove automatic GitHub context fetching and prefixing
- Remove unused imports (fetcher, formatter, context checks)
- Clean up comments
- Agent mode now simply passes through the user's prompt as-is

* Add GitHub MCP support to agent mode

- Parse --allowedTools from claude_args to detect when user wants GitHub MCPs
- Wire up github_inline_comment server in prepareMcpConfig for PR contexts
- Update agent mode to use prepareMcpConfig instead of manual config
- Add comprehensive tests for parseAllowedTools edge cases
- Fix TypeScript types to support both entity and automation contexts

* Format code with prettier

* Fix agent mode test to expect branch values

* Fix agent test to handle dynamic branch names from environment

* Better fix: Control environment variables in agent test for predictable behavior

* minor formatting

* Simplify MCP configuration to use multiple --mcp-config flags

- Remove MCP config merging logic from prepareMcpConfig
- Update agent and tag modes to pass multiple --mcp-config flags
- Let Claude handle config merging natively through multiple flags
- Fix TypeScript errors in test file

This approach is cleaner and relies on Claude's built-in support for multiple --mcp-config flags instead of manual JSON merging.

* feat: Copy project subagents to Claude runtime environment

Enables custom subagents defined in .claude/agents/ to work in GitHub Actions by:
- Checking for project agents in GITHUB_WORKSPACE/.claude/agents/
- Creating ~/.claude/agents/ directory if needed
- Copying all .md agent files to Claude's runtime location
- Following same pattern as slash commands for consistency

Includes comprehensive test coverage for the new functionality.

* formatting

* Add auto-fix CI workflows with slash command and inline approaches

- Add /fix-ci slash command for programmatic CI failure fixing
- Create auto-fix-ci.yml workflow using slash command approach
- Create auto-fix-ci-inline.yml workflow with full inline prompt
- Both workflows automatically analyze CI failures and create fix branches

* Add workflow_run event support and auto-fix CI workflows

- Add support for workflow_run event type in GitHub context
- Create /fix-ci slash command for programmatic CI failure fixing
- Add auto-fix-ci.yml workflow using slash command approach
- Add auto-fix-ci-inline.yml workflow with full inline prompt
- Both workflows automatically analyze CI failures and create fix branches
- Fix workflow syntax issues with optional chaining operator

* Use proper WorkflowRunEvent type instead of any

* bun formatting

* Remove auto-fix workflows and commands from v1-dev

These files should only exist in km-anthropic fork:
- .github/workflows/auto-fix-ci.yml
- .github/workflows/auto-fix-ci-inline.yml
- slash-commands/fix-ci.md
- .claude/commands/fix-ci.md

The workflow_run event support remains as it's useful for general automation.

* feat: Expose GitHub token as action output for external use

This allows workflows to use the Claude App token obtained by the action
for posting comments as claude[bot] instead of github-actions[bot].

Changes:
- Add github_token output to action.yml
- Export token from prepare.ts after authentication
- Allows workflows to use the same token Claude uses internally

* Debug: Add logging and always output github_token in prepare step

* Fix: Add git authentication to agent mode

Agent mode now fetches the authenticated user (claude[bot] when using Claude App token)
and configures git identity properly, matching the behavior of tag mode.

This fixes the issue where commits in agent mode were failing due to missing git identity.

* minor bun format

* remove unnecessary file

* fix: Add branch environment variable support to agent mode for signed commits

- Read CLAUDE_BRANCH and BASE_BRANCH env vars in agent mode
- Pass correct branch info to MCP file ops server
- Enables signed auto-fix workflows to create branches via API

* feat: Add auto-fix CI workflow examples

- Add auto-fix-ci example with inline git commits
- Add auto-fix-ci-signed example with signed commits via MCP
- Include corresponding slash commands for both workflows
- Examples demonstrate automated CI failure detection and fixing

* fix: Fix TypeScript error in agent mode git config

- Remove dependency on configureGitAuth which expects ParsedGitHubContext
- Implement git configuration directly for automation contexts
- Properly handle git authentication for agent mode

* fix: Align agent mode git config with existing patterns

- Use GITHUB_SERVER_URL from config module consistently
- Remove existing headers before setting new ones
- Use remote URL with embedded token like git-config.ts does
- Match the existing git authentication pattern in the codebase

* refactor: Use shared configureGitAuth function in agent mode

- Update configureGitAuth to accept GitHubContext instead of ParsedGitHubContext
- This allows both tag mode and agent mode to use the same function
- Removes code duplication and ensures consistent git configuration

* feat: Improve error message for 403 permission errors when committing

When the github_file_ops MCP server gets a 403 error, it now shows a cleaner
message suggesting to rebase from main/master branch to fix the issue.

* docs: Update documentation for v1.0 release (#476)

* docs: Update documentation for v1.0 release

- Integrate breaking changes naturally without alarming users
- Replace deprecated inputs (direct_prompt, custom_instructions, mode) with new unified approach
- Update all examples to use prompt and claude_args instead of deprecated inputs
- Add migration guides to help users transition from v0.x to v1.0
- Emphasize automatic mode detection as a key feature
- Update all workflow examples to @v1 from @beta
- Document how claude_args provides direct CLI control
- Update FAQ with automatic mode detection explanation
- Convert all tool configuration to use claude_args format

* fix: Apply prettier formatting to documentation files

* fix: Update all Claude model versions to latest and improve documentation accuracy

- Update all model references to claude-4-0-sonnet-20250805 (latest Sonnet 4)
- Update Bedrock models to anthropic.claude-4-0-sonnet-20250805-v1:0
- Update Vertex models to claude-4-0-sonnet@20250805
- Fix cloud-providers.md to use claude_args instead of deprecated model input
- Ensure all examples use @v1 instead of @beta
- Keep claude-opus-4-1-20250805 in examples where Opus is demonstrated
- Align all documentation with v1.0 patterns consistently

* feat: Add dedicated migration guide as requested in PR feedback

- Create comprehensive migration-guide.md with step-by-step instructions
- Add prominent links to migration guide in README.md
- Update usage.md to reference the separate migration guide
- Include before/after examples for all common scenarios
- Add checklist for systematic migration
- Address Ashwin's feedback about having a separate, clearly linked migration guide

* feat: Add comprehensive examples for hero use cases

- Add dedicated issue deduplication workflow example
- Add issue triage example (moved from .github/workflows)
- Update all examples to use v1-dev branch consistently
- Enable MCP tools in claude-auto-review.yml
- Consolidate PR review examples into single comprehensive example

Hero use cases now covered:
1. Code reviews (claude-auto-review.yml)
2. Issue triaging (issue-triage.yml)
3. Issue deduplication (issue-deduplication.yml)
4. Auto-fix CI failures (auto-fix-ci/auto-fix-ci.yml)

All examples updated to follow v1-dev paradigm with proper prompt and claude_args configuration.

* refactor: Remove timeout_minutes parameter from action (#482)

This change removes the custom timeout_minutes parameter from the action in favor of using GitHub Actions' native timeout-minutes feature.

Changes:
- Removed timeout_minutes input from action.yml and base-action/action.yml
- Removed all timeout handling logic from base-action/src/run-claude.ts
- Updated base-action/src/index.ts to remove timeoutMinutes parameter
- Removed timeout-related tests from base-action/test/run-claude.test.ts
- Removed timeout_minutes from all example workflow files (19 files)

Rationale:
- Simplifies the codebase by removing custom timeout logic
- Users can use GitHub Actions' native timeout-minutes at the job/step level
- Reduces complexity and maintenance burden
- Follows GitHub Actions best practices

BREAKING CHANGE: The timeout_minutes parameter is no longer supported. Users should use GitHub Actions' native timeout-minutes instead.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>

* refactor: Remove unused slash commands and agents copying logic

Removes experimental file copying features that had no default content:
- Removed experimental_slash_commands_dir parameter and related logic
- Removed automatic project agents copying from .claude/agents/
- Eliminated flaky error-prone cp operations with stderr suppression
- Removed 175 lines of unused code and associated tests

These features were infrastructure without default content that used
problematic error handling patterns (2>/dev/null || true) which could
hide real filesystem errors.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: Remove references to timeout_minutes parameter

The timeout_minutes parameter was removed in commit 986e40a but
documentation still referenced it. This updates:
- docs/usage.md: Removed timeout_minutes from inputs table
- base-action/README.md: Removed from inputs table and example

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: km-anthropic <km-anthropic@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Kashyap Murali <13315300+katchu11@users.noreply.github.com>
2025-08-25 12:51:37 -07:00

19 KiB

Claude Code Base Action

This GitHub Action allows you to run Claude Code within your GitHub Actions workflows. You can use this to build any custom workflow on top of Claude Code.

For simply tagging @claude in issues and PRs out of the box, check out the Claude Code action and GitHub app.

Usage

Add the following to your workflow file:

# Using a direct prompt
- name: Run Claude Code with direct prompt
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Or using a prompt from a file
- name: Run Claude Code with prompt file
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt_file: "/path/to/prompt.txt"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Or limiting the conversation turns
- name: Run Claude Code with limited turns
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    max_turns: "5" # Limit conversation to 5 turns
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Using custom system prompts
- name: Run Claude Code with custom system prompt
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Build a REST API"
    system_prompt: "You are a senior backend engineer. Focus on security, performance, and maintainability."
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Or appending to the default system prompt
- name: Run Claude Code with appended system prompt
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Create a database schema"
    append_system_prompt: "After writing code, be sure to code review yourself."
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Using custom environment variables
- name: Run Claude Code with custom environment variables
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Deploy to staging environment"
    claude_env: |
      ENVIRONMENT: staging
      API_URL: https://api-staging.example.com
      DEBUG: true
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Using fallback model for handling API errors
- name: Run Claude Code with fallback model
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Review and fix TypeScript errors"
    model: "claude-opus-4-1-20250805"
    fallback_model: "claude-sonnet-4-20250514"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# Using OAuth token instead of API key
- name: Run Claude Code with OAuth token
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Update dependencies"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}

Inputs

Input Description Required Default
prompt The prompt to send to Claude Code No* ''
prompt_file Path to a file containing the prompt to send to Claude Code No* ''
allowed_tools Comma-separated list of allowed tools for Claude Code to use No ''
disallowed_tools Comma-separated list of disallowed tools that Claude Code cannot use No ''
max_turns Maximum number of conversation turns (default: no limit) No ''
mcp_config Path to the MCP configuration JSON file, or MCP configuration JSON string No ''
settings Path to Claude Code settings JSON file, or settings JSON string No ''
system_prompt Override system prompt No ''
append_system_prompt Append to system prompt No ''
claude_env Custom environment variables to pass to Claude Code execution (YAML multiline format) No ''
model Model to use (provider-specific format required for Bedrock/Vertex) No 'claude-4-0-sonnet-20250219'
anthropic_model DEPRECATED: Use 'model' instead No 'claude-4-0-sonnet-20250219'
fallback_model Enable automatic fallback to specified model when default model is overloaded No ''
anthropic_api_key Anthropic API key (required for direct Anthropic API) No ''
claude_code_oauth_token Claude Code OAuth token (alternative to anthropic_api_key) No ''
use_bedrock Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API No 'false'
use_vertex Use Google Vertex AI with OIDC authentication instead of direct Anthropic API No 'false'
use_node_cache Whether to use Node.js dependency caching (set to true only for Node.js projects with lock files) No 'false'

*Either prompt or prompt_file must be provided, but not both.

Outputs

Output Description
conclusion Execution status of Claude Code ('success' or 'failure')
execution_file Path to the JSON file containing Claude Code execution log

Environment Variables

The following environment variables can be used to configure the action:

Variable Description Default
NODE_VERSION Node.js version to use (e.g., '18.x', '20.x', '22.x') '18.x'

Example usage:

- name: Run Claude Code with Node.js 20
  uses: anthropics/claude-code-base-action@beta
  env:
    NODE_VERSION: "20.x"
  with:
    prompt: "Your prompt here"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Custom Environment Variables

You can pass custom environment variables to Claude Code execution using the claude_env input. This allows Claude to access environment-specific configuration during its execution.

The claude_env input accepts YAML multiline format with key-value pairs:

- name: Deploy with custom environment
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Deploy the application to the staging environment"
    claude_env: |
      ENVIRONMENT: staging
      API_BASE_URL: https://api-staging.example.com
      DATABASE_URL: ${{ secrets.STAGING_DB_URL }}
      DEBUG: true
      LOG_LEVEL: debug
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Features:

  • YAML Format: Use standard YAML key-value syntax (KEY: value)
  • Multiline Support: Define multiple environment variables in a single input
  • Comments: Lines starting with # are ignored
  • GitHub Secrets: Can reference GitHub secrets using ${{ secrets.SECRET_NAME }}
  • Runtime Access: Environment variables are available to Claude during execution

Example Use Cases:

# Development configuration
claude_env: |
  NODE_ENV: development
  API_URL: http://localhost:3000
  DEBUG: true

# Production deployment
claude_env: |
  NODE_ENV: production
  API_URL: https://api.example.com
  DATABASE_URL: ${{ secrets.PROD_DB_URL }}
  REDIS_URL: ${{ secrets.REDIS_URL }}

# Feature flags and configuration
claude_env: |
  FEATURE_NEW_UI: enabled
  MAX_RETRIES: 3
  TIMEOUT_MS: 5000

Using Settings Configuration

You can provide Claude Code settings configuration in two ways:

Option 1: Settings Configuration File

Provide a path to a JSON file containing Claude Code settings:

- name: Run Claude Code with settings file
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    settings: "path/to/settings.json"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Option 2: Inline Settings Configuration

Provide the settings configuration directly as a JSON string:

- name: Run Claude Code with inline settings
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    settings: |
      {
        "model": "claude-opus-4-1-20250805",
        "env": {
          "DEBUG": "true",
          "API_URL": "https://api.example.com"
        },
        "permissions": {
          "allow": ["Bash", "Read"],
          "deny": ["WebFetch"]
        },
        "hooks": {
          "PreToolUse": [{
            "matcher": "Bash",
            "hooks": [{
              "type": "command",
              "command": "echo Running bash command..."
            }]
          }]
        }
      }
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

The settings file supports all Claude Code settings options including:

  • model: Override the default model
  • env: Environment variables for the session
  • permissions: Tool usage permissions
  • hooks: Pre/post tool execution hooks
  • includeCoAuthoredBy: Include co-authored-by in git commits
  • And more...

Note: The enableAllProjectMcpServers setting is always set to true by this action to ensure MCP servers work correctly.

Using MCP Config

You can provide MCP configuration in two ways:

Option 1: MCP Configuration File

Provide a path to a JSON file containing MCP configuration:

- name: Run Claude Code with MCP config file
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    mcp_config: "path/to/mcp-config.json"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Option 2: Inline MCP Configuration

Provide the MCP configuration directly as a JSON string:

- name: Run Claude Code with inline MCP config
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    mcp_config: |
      {
        "mcpServers": {
          "server-name": {
            "command": "node",
            "args": ["./server.js"],
            "env": {
              "API_KEY": "your-api-key"
            }
          }
        }
      }
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

The MCP config file should follow this format:

{
  "mcpServers": {
    "server-name": {
      "command": "node",
      "args": ["./server.js"],
      "env": {
        "API_KEY": "your-api-key"
      }
    }
  }
}

You can combine MCP config with other inputs like allowed tools:

# Using multiple inputs together
- name: Run Claude Code with MCP and custom tools
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Access the custom MCP server and use its tools"
    mcp_config: "mcp-config.json"
    allowed_tools: "Bash(git:*),View,mcp__server-name__custom_tool"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Example: PR Code Review

name: Claude Code Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  code-review:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Run Code Review with Claude
        id: code-review
        uses: anthropics/claude-code-base-action@beta
        with:
          prompt: "Review the PR changes. Focus on code quality, potential bugs, and performance issues. Suggest improvements where appropriate. Write your review as markdown text."
          allowed_tools: "Bash(git diff --name-only HEAD~1),Bash(git diff HEAD~1),View,GlobTool,GrepTool,Write"
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

      - name: Extract and Comment PR Review
        if: steps.code-review.outputs.conclusion == 'success'
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const fs = require('fs');
            const executionFile = '${{ steps.code-review.outputs.execution_file }}';
            const executionLog = JSON.parse(fs.readFileSync(executionFile, 'utf8'));

            // Extract the review content from the execution log
            // The execution log contains the full conversation including Claude's responses
            let review = '';

            // Find the last assistant message which should contain the review
            for (let i = executionLog.length - 1; i >= 0; i--) {
              if (executionLog[i].role === 'assistant') {
                review = executionLog[i].content;
                break;
              }
            }

            if (review) {
              github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body: "## Claude Code Review\n\n" + review + "\n\n*Generated by Claude Code*"
              });
            }

Check out additional examples in ./examples.

Using Cloud Providers

You can authenticate with Claude using any of these methods:

  1. Direct Anthropic API (default) - requires API key or OAuth token
  2. Amazon Bedrock - requires OIDC authentication and automatically uses cross-region inference profiles
  3. Google Vertex AI - requires OIDC authentication

Note:

  • Bedrock and Vertex use OIDC authentication exclusively
  • AWS Bedrock automatically uses cross-region inference profiles for certain models
  • For cross-region inference profile models, you need to request and be granted access to the Claude models in all regions that the inference profile uses
  • The Bedrock API endpoint URL is automatically constructed using the AWS_REGION environment variable (e.g., https://bedrock-runtime.us-west-2.amazonaws.com)
  • You can override the Bedrock API endpoint URL by setting the ANTHROPIC_BEDROCK_BASE_URL environment variable

Model Configuration

Use provider-specific model names based on your chosen provider:

# For direct Anthropic API (default)
- name: Run Claude Code with Anthropic API
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    model: "claude-3-7-sonnet-20250219"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# For Amazon Bedrock (requires OIDC authentication)
- name: Configure AWS Credentials (OIDC)
  uses: aws-actions/configure-aws-credentials@v4
  with:
    role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
    aws-region: us-west-2

- name: Run Claude Code with Bedrock
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    model: "anthropic.claude-3-7-sonnet-20250219-v1:0"
    use_bedrock: "true"

# For Google Vertex AI (requires OIDC authentication)
- name: Authenticate to Google Cloud
  uses: google-github-actions/auth@v2
  with:
    workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
    service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}

- name: Run Claude Code with Vertex AI
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    model: "claude-3-7-sonnet@20250219"
    use_vertex: "true"

Example: Using OIDC Authentication for AWS Bedrock

This example shows how to use OIDC authentication with AWS Bedrock:

- name: Configure AWS Credentials (OIDC)
  uses: aws-actions/configure-aws-credentials@v4
  with:
    role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
    aws-region: us-west-2

- name: Run Claude Code with AWS OIDC
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    use_bedrock: "true"
    model: "anthropic.claude-3-7-sonnet-20250219-v1:0"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"

Example: Using OIDC Authentication for GCP Vertex AI

This example shows how to use OIDC authentication with GCP Vertex AI:

- name: Authenticate to Google Cloud
  uses: google-github-actions/auth@v2
  with:
    workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
    service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}

- name: Run Claude Code with GCP OIDC
  uses: anthropics/claude-code-base-action@beta
  with:
    prompt: "Your prompt here"
    use_vertex: "true"
    model: "claude-3-7-sonnet@20250219"
    allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"

Security Best Practices

⚠️ IMPORTANT: Never commit API keys directly to your repository! Always use GitHub Actions secrets.

To securely use your Anthropic API key:

  1. Add your API key as a repository secret:

    • Go to your repository's Settings
    • Navigate to "Secrets and variables" → "Actions"
    • Click "New repository secret"
    • Name it ANTHROPIC_API_KEY
    • Paste your API key as the value
  2. Reference the secret in your workflow:

    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    

Never do this:

# ❌ WRONG - Exposes your API key
anthropic_api_key: "sk-ant-..."

Always do this:

# ✅ CORRECT - Uses GitHub secrets
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

This applies to all sensitive values including API keys, access tokens, and credentials. We also recommend that you always use short-lived tokens when possible

License

This project is licensed under the MIT License—see the LICENSE file for details.