mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-01-23 15:04:13 +08:00
Compare commits
59 Commits
ashwin-ant
...
v0.0.27
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00f9595fb4 | ||
|
|
79f2086fce | ||
|
|
bcb072b63f | ||
|
|
e3b3e531a7 | ||
|
|
a7665d3698 | ||
|
|
91c510a769 | ||
|
|
1e006bf2d0 | ||
|
|
ece712ea81 | ||
|
|
032008d3b6 | ||
|
|
b0d9b8c4cd | ||
|
|
c831be8f54 | ||
|
|
38254908ae | ||
|
|
882586e496 | ||
|
|
28aaa5404d | ||
|
|
ebbd9e9be4 | ||
|
|
237de9d329 | ||
|
|
91f620f8c2 | ||
|
|
3486c33ebf | ||
|
|
13ccdab2f8 | ||
|
|
bcf2fe94f8 | ||
|
|
2dab3f2afe | ||
|
|
1b94b9e5a8 | ||
|
|
e0d3fec39f | ||
|
|
3c748dc927 | ||
|
|
ffb2927088 | ||
|
|
def1b3a94e | ||
|
|
67d7753c80 | ||
|
|
a8d323af27 | ||
|
|
41dd0aa695 | ||
|
|
55966a1dc0 | ||
|
|
b10f287695 | ||
|
|
56d8eac7ce | ||
|
|
25f9b8ef9e | ||
|
|
3bcfbe7385 | ||
|
|
bdd0c925cb | ||
|
|
37ec8e4781 | ||
|
|
e5b1633249 | ||
|
|
37483ba112 | ||
|
|
9b50f473cb | ||
|
|
47ea5c2a69 | ||
|
|
4bd9c2053a | ||
|
|
f862b5a16a | ||
|
|
424d1b8f87 | ||
|
|
1d5e695d0c | ||
|
|
8e8be41f15 | ||
|
|
c7957fda5d | ||
|
|
1990b0bdb3 | ||
|
|
699aa26b41 | ||
|
|
94c0c31c1b | ||
|
|
be799cbe7b | ||
|
|
bd71ac0e8f | ||
|
|
65b9bcde80 | ||
|
|
70245e56e3 | ||
|
|
1d4d6c4b93 | ||
|
|
e409c57d90 | ||
|
|
f6e5597633 | ||
|
|
0cd44e50dd | ||
|
|
a8a36ced96 | ||
|
|
180a1b6680 |
2
.github/workflows/claude-review.yml
vendored
2
.github/workflows/claude-review.yml
vendored
@@ -29,4 +29,4 @@ jobs:
|
||||
|
||||
Be constructive and specific in your feedback. Give inline comments where applicable.
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
allowed_tools: "mcp__github__add_pull_request_review_comment"
|
||||
allowed_tools: "mcp__github__create_pending_pull_request_review,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff"
|
||||
|
||||
26
.github/workflows/issue-triage.yml
vendored
26
.github/workflows/issue-triage.yml
vendored
@@ -23,18 +23,20 @@ jobs:
|
||||
mkdir -p /tmp/mcp-config
|
||||
cat > /tmp/mcp-config/mcp-servers.json << 'EOF'
|
||||
{
|
||||
"github": {
|
||||
"command": "docker",
|
||||
"args": [
|
||||
"run",
|
||||
"-i",
|
||||
"--rm",
|
||||
"-e",
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
||||
"ghcr.io/github/github-mcp-server:sha-7aced2b"
|
||||
],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}"
|
||||
"mcpServers": {
|
||||
"github": {
|
||||
"command": "docker",
|
||||
"args": [
|
||||
"run",
|
||||
"-i",
|
||||
"--rm",
|
||||
"-e",
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
||||
"ghcr.io/github/github-mcp-server:sha-6d69797"
|
||||
],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
138
.github/workflows/release.yml
vendored
Normal file
138
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,138 @@
|
||||
name: Create Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: "Dry run (only show what would be created)"
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
create-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
next_version: ${{ steps.next_version.outputs.next_version }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
run: |
|
||||
# Get only version tags (v + number pattern)
|
||||
latest_tag=$(git tag -l 'v[0-9]*' | sort -V | tail -1 || echo "v0.0.0")
|
||||
if [ -z "$latest_tag" ]; then
|
||||
latest_tag="v0.0.0"
|
||||
fi
|
||||
echo "latest_tag=$latest_tag" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: $latest_tag"
|
||||
|
||||
- name: Calculate next version
|
||||
id: next_version
|
||||
run: |
|
||||
latest_tag="${{ steps.get_latest_tag.outputs.latest_tag }}"
|
||||
# Remove 'v' prefix and split by dots
|
||||
version=${latest_tag#v}
|
||||
IFS='.' read -ra VERSION_PARTS <<< "$version"
|
||||
|
||||
# Increment patch version
|
||||
major=${VERSION_PARTS[0]:-0}
|
||||
minor=${VERSION_PARTS[1]:-0}
|
||||
patch=${VERSION_PARTS[2]:-0}
|
||||
patch=$((patch + 1))
|
||||
|
||||
next_version="v${major}.${minor}.${patch}"
|
||||
echo "next_version=$next_version" >> $GITHUB_OUTPUT
|
||||
echo "Next version: $next_version"
|
||||
|
||||
- name: Display dry run info
|
||||
if: ${{ inputs.dry_run }}
|
||||
run: |
|
||||
echo "🔍 DRY RUN MODE"
|
||||
echo "Would create tag: ${{ steps.next_version.outputs.next_version }}"
|
||||
echo "From commit: ${{ github.sha }}"
|
||||
echo "Previous tag: ${{ steps.get_latest_tag.outputs.latest_tag }}"
|
||||
|
||||
- name: Create and push tag
|
||||
if: ${{ !inputs.dry_run }}
|
||||
run: |
|
||||
next_version="${{ steps.next_version.outputs.next_version }}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git tag -a "$next_version" -m "Release $next_version"
|
||||
git push origin "$next_version"
|
||||
|
||||
- name: Create Release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
next_version="${{ steps.next_version.outputs.next_version }}"
|
||||
|
||||
gh release create "$next_version" \
|
||||
--title "$next_version" \
|
||||
--generate-notes \
|
||||
--latest=false # We want to keep beta as the latest
|
||||
|
||||
update-beta-tag:
|
||||
needs: create-release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Update beta tag
|
||||
run: |
|
||||
# Get the latest version tag
|
||||
VERSION=$(git tag -l 'v[0-9]*' | sort -V | tail -1)
|
||||
|
||||
# Update the beta tag to point to this release
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -fa beta -m "Update beta tag to ${VERSION}"
|
||||
git push origin beta --force
|
||||
|
||||
- name: Update beta release to be latest
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Update beta release to be marked as latest
|
||||
gh release edit beta --latest
|
||||
|
||||
update-major-tag:
|
||||
needs: create-release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Update major version tag
|
||||
run: |
|
||||
next_version="${{ needs.create-release.outputs.next_version }}"
|
||||
# Extract major version (e.g., v0 from v0.0.20)
|
||||
major_version=$(echo "$next_version" | cut -d. -f1)
|
||||
|
||||
# Update the major version tag to point to this release
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -fa "$major_version" -m "Update $major_version tag to $next_version"
|
||||
git push origin "$major_version" --force
|
||||
|
||||
echo "Updated $major_version tag to point to $next_version"
|
||||
@@ -50,20 +50,6 @@ Thank you for your interest in contributing to Claude Code Action! This document
|
||||
bun test
|
||||
```
|
||||
|
||||
2. **Integration Tests** (using GitHub Actions locally):
|
||||
|
||||
```bash
|
||||
./test-local.sh
|
||||
```
|
||||
|
||||
This script:
|
||||
|
||||
- Installs `act` if not present (requires Homebrew on macOS)
|
||||
- Runs the GitHub Action workflow locally using Docker
|
||||
- Requires your `ANTHROPIC_API_KEY` to be set
|
||||
|
||||
On Apple Silicon Macs, the script automatically adds the `--container-architecture linux/amd64` flag to avoid compatibility issues.
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
1. Create a new branch from `main`:
|
||||
@@ -103,13 +89,7 @@ Thank you for your interest in contributing to Claude Code Action! This document
|
||||
|
||||
When modifying the action:
|
||||
|
||||
1. Test locally with the test script:
|
||||
|
||||
```bash
|
||||
./test-local.sh
|
||||
```
|
||||
|
||||
2. Test in a real GitHub Actions workflow by:
|
||||
1. Test in a real GitHub Actions workflow by:
|
||||
- Creating a test repository
|
||||
- Using your branch as the action source:
|
||||
```yaml
|
||||
|
||||
6
FAQ.md
6
FAQ.md
@@ -6,12 +6,16 @@ This FAQ addresses common questions and gotchas when using the Claude Code GitHu
|
||||
|
||||
### Why doesn't tagging @claude from my automated workflow work?
|
||||
|
||||
The `github-actions` user (and other GitHub Apps/bots) cannot trigger subsequent GitHub Actions workflows. This is a GitHub security feature to prevent infinite loops. To make this work, you need to use a Personal Access Token (PAT) instead, which will act as a regular user. When posting a comment on an issue or PR from your workflow, use your PAT instead of the `GITHUB_TOKEN` generated in your workflow.
|
||||
The `github-actions` user cannot trigger subsequent GitHub Actions workflows. This is a GitHub security feature to prevent infinite loops. To make this work, you need to use a Personal Access Token (PAT) instead, which will act as a regular user, or use a separate app token of your own. When posting a comment on an issue or PR from your workflow, use your PAT instead of the `GITHUB_TOKEN` generated in your workflow.
|
||||
|
||||
### Why does Claude say I don't have permission to trigger it?
|
||||
|
||||
Only users with **write permissions** to the repository can trigger Claude. This is a security feature to prevent unauthorized use. Make sure the user commenting has at least write access to the repository.
|
||||
|
||||
### Why can't I assign @claude to an issue on my repository?
|
||||
|
||||
If you're in a public repository, you should be able to assign to Claude without issue. If it's a private organization repository, you can only assign to users in your own organization, which Claude isn't. In this case, you'll need to make a custom user in that case.
|
||||
|
||||
### Why am I getting OIDC authentication errors?
|
||||
|
||||
If you're using the default GitHub App authentication, you must add the `id-token: write` permission to your workflow:
|
||||
|
||||
152
README.md
152
README.md
@@ -49,7 +49,7 @@ on:
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
types: [opened, assigned, labeled]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
@@ -65,6 +65,15 @@ jobs:
|
||||
# trigger_phrase: "/claude"
|
||||
# Optional: add assignee trigger for issues
|
||||
# assignee_trigger: "claude"
|
||||
# Optional: add label trigger for issues
|
||||
# label_trigger: "claude"
|
||||
# Optional: add custom environment variables (YAML format)
|
||||
# claude_env: |
|
||||
# NODE_ENV: test
|
||||
# DEBUG: true
|
||||
# API_URL: https://api.example.com
|
||||
# Optional: limit the number of conversation turns
|
||||
# max_turns: "5"
|
||||
```
|
||||
|
||||
## Inputs
|
||||
@@ -73,7 +82,10 @@ jobs:
|
||||
| --------------------- | -------------------------------------------------------------------------------------------------------------------- | -------- | --------- |
|
||||
| `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - |
|
||||
| `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - |
|
||||
| `base_branch` | The base branch to use for creating new branches (e.g., 'main', 'develop') | No | - |
|
||||
| `max_turns` | Maximum number of conversation turns Claude can take (limits back-and-forth exchanges) | No | - |
|
||||
| `timeout_minutes` | Timeout in minutes for execution | No | `30` |
|
||||
| `use_sticky_comment` | Use just one comment to deliver PR comments (only applies for pull_request event workflows) | No | `false` |
|
||||
| `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - |
|
||||
| `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - |
|
||||
| `anthropic_model` | **DEPRECATED**: Use `model` instead. Kept for backward compatibility. | No | - |
|
||||
@@ -82,13 +94,106 @@ jobs:
|
||||
| `allowed_tools` | Additional tools for Claude to use (the base GitHub tools will always be included) | No | "" |
|
||||
| `disallowed_tools` | Tools that Claude should never use | No | "" |
|
||||
| `custom_instructions` | Additional custom instructions to include in the prompt for Claude | No | "" |
|
||||
| `mcp_config` | Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers | No | "" |
|
||||
| `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - |
|
||||
| `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude") | No | - |
|
||||
| `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` |
|
||||
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
|
||||
| `claude_env` | Custom environment variables to pass to Claude Code execution (YAML format) | No | "" |
|
||||
|
||||
\*Required when using direct Anthropic API (default and when not using Bedrock or Vertex)
|
||||
|
||||
> **Note**: This action is currently in beta. Features and APIs may change as we continue to improve the integration.
|
||||
|
||||
### Using Custom MCP Configuration
|
||||
|
||||
The `mcp_config` input allows you to add custom MCP (Model Context Protocol) servers to extend Claude's capabilities. These servers merge with the built-in GitHub MCP servers.
|
||||
|
||||
#### Basic Example: Adding a Sequential Thinking Server
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
mcp_config: |
|
||||
{
|
||||
"mcpServers": {
|
||||
"sequential-thinking": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"@modelcontextprotocol/server-sequential-thinking"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
allowed_tools: "mcp__sequential-thinking__sequentialthinking" # Important: Each MCP tool from your server must be listed here, comma-separated
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
#### Passing Secrets to MCP Servers
|
||||
|
||||
For MCP servers that require sensitive information like API keys or tokens, use GitHub Secrets in the environment variables:
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
mcp_config: |
|
||||
{
|
||||
"mcpServers": {
|
||||
"custom-api-server": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@example/api-server"],
|
||||
"env": {
|
||||
"API_KEY": "${{ secrets.CUSTOM_API_KEY }}",
|
||||
"BASE_URL": "https://api.example.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
#### Using Python MCP Servers with uv
|
||||
|
||||
For Python-based MCP servers managed with `uv`, you need to specify the directory containing your server:
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
mcp_config: |
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-python-server": {
|
||||
"type": "stdio",
|
||||
"command": "uv",
|
||||
"args": [
|
||||
"--directory",
|
||||
"${{ github.workspace }}/path/to/server/",
|
||||
"run",
|
||||
"server_file.py"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
allowed_tools: "my-python-server__<tool_name>" # Replace <tool_name> with your server's tool names
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
For example, if your Python MCP server is at `mcp_servers/weather.py`, you would use:
|
||||
|
||||
```yaml
|
||||
"args":
|
||||
["--directory", "${{ github.workspace }}/mcp_servers/", "run", "weather.py"]
|
||||
```
|
||||
|
||||
**Important**:
|
||||
|
||||
- Always use GitHub Secrets (`${{ secrets.SECRET_NAME }}`) for sensitive values like API keys, tokens, or passwords. Never hardcode secrets directly in the workflow file.
|
||||
- Your custom servers will override any built-in servers with the same name.
|
||||
|
||||
## Examples
|
||||
|
||||
### Ways to Tag @claude
|
||||
@@ -233,6 +338,40 @@ This action is built on top of [`anthropics/claude-code-base-action`](https://gi
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Custom Environment Variables
|
||||
|
||||
You can pass custom environment variables to Claude Code execution using the `claude_env` input. This is useful for CI/test setups that require specific environment variables:
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
claude_env: |
|
||||
NODE_ENV: test
|
||||
CI: true
|
||||
DATABASE_URL: postgres://test:test@localhost:5432/test_db
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
The `claude_env` input accepts YAML format where each line defines a key-value pair. These environment variables will be available to Claude Code during execution, allowing it to run tests, build processes, or other commands that depend on specific environment configurations.
|
||||
|
||||
### Limiting Conversation Turns
|
||||
|
||||
You can use the `max_turns` parameter to limit the number of back-and-forth exchanges Claude can have during task execution. This is useful for:
|
||||
|
||||
- Controlling costs by preventing runaway conversations
|
||||
- Setting time boundaries for automated workflows
|
||||
- Ensuring predictable behavior in CI/CD pipelines
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
max_turns: "5" # Limit to 5 conversation turns
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
When the turn limit is reached, Claude will stop execution gracefully. Choose a value that gives Claude enough turns to complete typical tasks while preventing excessive usage.
|
||||
|
||||
### Custom Tools
|
||||
|
||||
By default, Claude only has access to:
|
||||
@@ -248,8 +387,15 @@ Claude does **not** have access to execute arbitrary Bash commands by default. I
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
allowed_tools: "Bash(npm install),Bash(npm run test),Edit,Replace,NotebookEditCell"
|
||||
disallowed_tools: "TaskOutput,KillTask"
|
||||
allowed_tools: |
|
||||
Bash(npm install)
|
||||
Bash(npm run test)
|
||||
Edit
|
||||
Replace
|
||||
NotebookEditCell
|
||||
disallowed_tools: |
|
||||
TaskOutput
|
||||
KillTask
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
|
||||
20
ROADMAP.md
Normal file
20
ROADMAP.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Claude Code GitHub Action Roadmap
|
||||
|
||||
Thank you for trying out the beta of our GitHub Action! This document outlines our path to `v1.0`. Items are not necessarily in priority order.
|
||||
|
||||
## Path to 1.0
|
||||
|
||||
- **Ability to see GitHub Action CI results** - This will enable Claude to look at CI failures and make updates to PRs to fix test failures, lint errors, and the like.
|
||||
- **Cross-repo support** - Enable Claude to work across multiple repositories in a single session
|
||||
- **Ability to modify workflow files** - Let Claude update GitHub Actions workflows and other CI configuration files
|
||||
- **Support for workflow_dispatch and repository_dispatch events** - Dispatch Claude on events triggered via API from other workflows or from other services
|
||||
- **Ability to disable commit signing** - Option to turn off GPG signing for environments where it's not required. This will enable Claude to use normal `git` bash commands for committing. This will likely become the default behavior once added.
|
||||
- **Better code review behavior** - Support inline comments on specific lines, provide higher quality reviews with more actionable feedback
|
||||
- **Support triggering @claude from bot users** - Allow automation and bot accounts to invoke Claude
|
||||
- **Customizable base prompts** - Full control over Claude's initial context with template variables like `$PR_COMMENTS`, `$PR_FILES`, etc. Users can replace our default prompt entirely while still accessing key contextual data
|
||||
|
||||
---
|
||||
|
||||
**Note:** This roadmap represents our current vision for reaching `v1.0` and is subject to change based on user feedback and development priorities.
|
||||
|
||||
We welcome feedback on these planned features! If you're interested in contributing to any of these features, please open an issue to discuss implementation details with us. We're also open to suggestions for new features not listed here.
|
||||
40
action.yml
40
action.yml
@@ -12,9 +12,17 @@ inputs:
|
||||
assignee_trigger:
|
||||
description: "The assignee username that triggers the action (e.g. @claude)"
|
||||
required: false
|
||||
label_trigger:
|
||||
description: "The label that triggers the action (e.g. claude)"
|
||||
required: false
|
||||
default: "claude"
|
||||
base_branch:
|
||||
description: "The branch to use as the base/source when creating new branches (defaults to repository default branch)"
|
||||
required: false
|
||||
branch_prefix:
|
||||
description: "The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format)"
|
||||
required: false
|
||||
default: "claude/"
|
||||
|
||||
# Claude Code configuration
|
||||
model:
|
||||
@@ -39,6 +47,12 @@ inputs:
|
||||
description: "Direct instruction for Claude (bypasses normal trigger detection)"
|
||||
required: false
|
||||
default: ""
|
||||
mcp_config:
|
||||
description: "Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers"
|
||||
claude_env:
|
||||
description: "Custom environment variables to pass to Claude Code execution (YAML format)"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
# Auth configuration
|
||||
anthropic_api_key:
|
||||
@@ -56,10 +70,18 @@ inputs:
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
max_turns:
|
||||
description: "Maximum number of conversation turns"
|
||||
required: false
|
||||
default: ""
|
||||
timeout_minutes:
|
||||
description: "Timeout in minutes for execution"
|
||||
required: false
|
||||
default: "30"
|
||||
use_sticky_comment:
|
||||
description: "Use just one comment to deliver issue/PR comments"
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
outputs:
|
||||
execution_file:
|
||||
@@ -77,38 +99,45 @@ runs:
|
||||
- name: Install Dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
cd ${{ github.action_path }}
|
||||
cd ${GITHUB_ACTION_PATH}
|
||||
bun install
|
||||
|
||||
- name: Prepare action
|
||||
id: prepare
|
||||
shell: bash
|
||||
run: |
|
||||
bun run ${{ github.action_path }}/src/entrypoints/prepare.ts
|
||||
bun run ${GITHUB_ACTION_PATH}/src/entrypoints/prepare.ts
|
||||
env:
|
||||
TRIGGER_PHRASE: ${{ inputs.trigger_phrase }}
|
||||
ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }}
|
||||
LABEL_TRIGGER: ${{ inputs.label_trigger }}
|
||||
BASE_BRANCH: ${{ inputs.base_branch }}
|
||||
BRANCH_PREFIX: ${{ inputs.branch_prefix }}
|
||||
ALLOWED_TOOLS: ${{ inputs.allowed_tools }}
|
||||
DISALLOWED_TOOLS: ${{ inputs.disallowed_tools }}
|
||||
CUSTOM_INSTRUCTIONS: ${{ inputs.custom_instructions }}
|
||||
DIRECT_PROMPT: ${{ inputs.direct_prompt }}
|
||||
MCP_CONFIG: ${{ inputs.mcp_config }}
|
||||
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
|
||||
GITHUB_RUN_ID: ${{ github.run_id }}
|
||||
USE_STICKY_COMMENT: ${{ inputs.use_sticky_comment }}
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude-code
|
||||
if: steps.prepare.outputs.contains_trigger == 'true'
|
||||
uses: anthropics/claude-code-base-action@c8e31bd52d9a149b3f8309d7978c6edaa282688d # v0.0.8
|
||||
uses: anthropics/claude-code-base-action@bdaad5f64e7ad7a8c0be290a3c49d0fa7e1bb442 # v0.0.29
|
||||
with:
|
||||
prompt_file: /tmp/claude-prompts/claude-prompt.txt
|
||||
prompt_file: ${{ runner.temp }}/claude-prompts/claude-prompt.txt
|
||||
allowed_tools: ${{ env.ALLOWED_TOOLS }}
|
||||
disallowed_tools: ${{ env.DISALLOWED_TOOLS }}
|
||||
timeout_minutes: ${{ inputs.timeout_minutes }}
|
||||
max_turns: ${{ inputs.max_turns }}
|
||||
model: ${{ inputs.model || inputs.anthropic_model }}
|
||||
mcp_config: ${{ steps.prepare.outputs.mcp_config }}
|
||||
use_bedrock: ${{ inputs.use_bedrock }}
|
||||
use_vertex: ${{ inputs.use_vertex }}
|
||||
anthropic_api_key: ${{ inputs.anthropic_api_key }}
|
||||
claude_env: ${{ inputs.claude_env }}
|
||||
env:
|
||||
# Model configuration
|
||||
ANTHROPIC_MODEL: ${{ inputs.model || inputs.anthropic_model }}
|
||||
@@ -139,7 +168,7 @@ runs:
|
||||
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
|
||||
shell: bash
|
||||
run: |
|
||||
bun run ${{ github.action_path }}/src/entrypoints/update-comment-link.ts
|
||||
bun run ${GITHUB_ACTION_PATH}/src/entrypoints/update-comment-link.ts
|
||||
env:
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
PR_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }}
|
||||
@@ -156,6 +185,7 @@ runs:
|
||||
TRIGGER_USERNAME: ${{ github.event.comment.user.login || github.event.issue.user.login || github.event.pull_request.user.login || github.event.sender.login || github.triggering_actor || github.actor || '' }}
|
||||
PREPARE_SUCCESS: ${{ steps.prepare.outcome == 'success' }}
|
||||
PREPARE_ERROR: ${{ steps.prepare.outputs.prepare_error || '' }}
|
||||
USE_STICKY_COMMENT: ${{ inputs.use_sticky_comment }}
|
||||
|
||||
- name: Display Claude Code Report
|
||||
if: steps.prepare.outputs.contains_trigger == 'true' && steps.claude-code.outputs.execution_file != ''
|
||||
|
||||
2
bun.lock
2
bun.lock
@@ -2,7 +2,7 @@
|
||||
"lockfileVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "claude-pr-action",
|
||||
"name": "@anthropic-ai/claude-code-action",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
|
||||
@@ -35,4 +35,4 @@ jobs:
|
||||
|
||||
Provide constructive feedback with specific suggestions for improvement.
|
||||
Use inline comments to highlight specific areas of concern.
|
||||
# allowed_tools: "mcp__github__add_pull_request_review_comment"
|
||||
# allowed_tools: "mcp__github__create_pending_pull_request_review,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "claude-pr-action",
|
||||
"name": "@anthropic-ai/claude-code-action",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
|
||||
@@ -24,6 +24,7 @@ export type { CommonFields, PreparedContext } from "./types";
|
||||
|
||||
const BASE_ALLOWED_TOOLS = [
|
||||
"Edit",
|
||||
"MultiEdit",
|
||||
"Glob",
|
||||
"Grep",
|
||||
"LS",
|
||||
@@ -31,53 +32,39 @@ const BASE_ALLOWED_TOOLS = [
|
||||
"Write",
|
||||
"mcp__github_file_ops__commit_files",
|
||||
"mcp__github_file_ops__delete_files",
|
||||
"mcp__github_file_ops__update_claude_comment",
|
||||
];
|
||||
const DISALLOWED_TOOLS = ["WebSearch", "WebFetch"];
|
||||
|
||||
export function buildAllowedToolsString(
|
||||
eventData: EventData,
|
||||
customAllowedTools?: string,
|
||||
): string {
|
||||
export function buildAllowedToolsString(customAllowedTools?: string[]): string {
|
||||
let baseTools = [...BASE_ALLOWED_TOOLS];
|
||||
|
||||
// Add the appropriate comment tool based on event type
|
||||
if (eventData.eventName === "pull_request_review_comment") {
|
||||
// For inline PR review comments, only use PR comment tool
|
||||
baseTools.push("mcp__github__update_pull_request_comment");
|
||||
} else {
|
||||
// For all other events (issue comments, PR reviews, issues), use issue comment tool
|
||||
baseTools.push("mcp__github__update_issue_comment");
|
||||
}
|
||||
|
||||
let allAllowedTools = baseTools.join(",");
|
||||
if (customAllowedTools) {
|
||||
allAllowedTools = `${allAllowedTools},${customAllowedTools}`;
|
||||
if (customAllowedTools && customAllowedTools.length > 0) {
|
||||
allAllowedTools = `${allAllowedTools},${customAllowedTools.join(",")}`;
|
||||
}
|
||||
return allAllowedTools;
|
||||
}
|
||||
|
||||
export function buildDisallowedToolsString(
|
||||
customDisallowedTools?: string,
|
||||
allowedTools?: string,
|
||||
customDisallowedTools?: string[],
|
||||
allowedTools?: string[],
|
||||
): string {
|
||||
let disallowedTools = [...DISALLOWED_TOOLS];
|
||||
|
||||
// If user has explicitly allowed some hardcoded disallowed tools, remove them from disallowed list
|
||||
if (allowedTools) {
|
||||
const allowedToolsArray = allowedTools
|
||||
.split(",")
|
||||
.map((tool) => tool.trim());
|
||||
if (allowedTools && allowedTools.length > 0) {
|
||||
disallowedTools = disallowedTools.filter(
|
||||
(tool) => !allowedToolsArray.includes(tool),
|
||||
(tool) => !allowedTools.includes(tool),
|
||||
);
|
||||
}
|
||||
|
||||
let allDisallowedTools = disallowedTools.join(",");
|
||||
if (customDisallowedTools) {
|
||||
if (customDisallowedTools && customDisallowedTools.length > 0) {
|
||||
if (allDisallowedTools) {
|
||||
allDisallowedTools = `${allDisallowedTools},${customDisallowedTools}`;
|
||||
allDisallowedTools = `${allDisallowedTools},${customDisallowedTools.join(",")}`;
|
||||
} else {
|
||||
allDisallowedTools = customDisallowedTools;
|
||||
allDisallowedTools = customDisallowedTools.join(",");
|
||||
}
|
||||
}
|
||||
return allDisallowedTools;
|
||||
@@ -94,6 +81,7 @@ export function prepareContext(
|
||||
const eventAction = context.eventAction;
|
||||
const triggerPhrase = context.inputs.triggerPhrase || "@claude";
|
||||
const assigneeTrigger = context.inputs.assigneeTrigger;
|
||||
const labelTrigger = context.inputs.labelTrigger;
|
||||
const customInstructions = context.inputs.customInstructions;
|
||||
const allowedTools = context.inputs.allowedTools;
|
||||
const disallowedTools = context.inputs.disallowedTools;
|
||||
@@ -131,8 +119,10 @@ export function prepareContext(
|
||||
triggerPhrase,
|
||||
...(triggerUsername && { triggerUsername }),
|
||||
...(customInstructions && { customInstructions }),
|
||||
...(allowedTools && { allowedTools }),
|
||||
...(disallowedTools && { disallowedTools }),
|
||||
...(allowedTools.length > 0 && { allowedTools: allowedTools.join(",") }),
|
||||
...(disallowedTools.length > 0 && {
|
||||
disallowedTools: disallowedTools.join(","),
|
||||
}),
|
||||
...(directPrompt && { directPrompt }),
|
||||
...(claudeBranch && { claudeBranch }),
|
||||
};
|
||||
@@ -253,7 +243,7 @@ export function prepareContext(
|
||||
}
|
||||
|
||||
if (eventAction === "assigned") {
|
||||
if (!assigneeTrigger) {
|
||||
if (!assigneeTrigger && !directPrompt) {
|
||||
throw new Error(
|
||||
"ASSIGNEE_TRIGGER is required for issue assigned event",
|
||||
);
|
||||
@@ -265,7 +255,20 @@ export function prepareContext(
|
||||
issueNumber,
|
||||
baseBranch,
|
||||
claudeBranch,
|
||||
assigneeTrigger,
|
||||
...(assigneeTrigger && { assigneeTrigger }),
|
||||
};
|
||||
} else if (eventAction === "labeled") {
|
||||
if (!labelTrigger) {
|
||||
throw new Error("LABEL_TRIGGER is required for issue labeled event");
|
||||
}
|
||||
eventData = {
|
||||
eventName: "issues",
|
||||
eventAction: "labeled",
|
||||
isPR: false,
|
||||
issueNumber,
|
||||
baseBranch,
|
||||
claudeBranch,
|
||||
labelTrigger,
|
||||
};
|
||||
} else if (eventAction === "opened") {
|
||||
eventData = {
|
||||
@@ -339,10 +342,17 @@ export function getEventTypeAndContext(envVars: PreparedContext): {
|
||||
eventType: "ISSUE_CREATED",
|
||||
triggerContext: `new issue with '${envVars.triggerPhrase}' in body`,
|
||||
};
|
||||
} else if (eventData.eventAction === "labeled") {
|
||||
return {
|
||||
eventType: "ISSUE_LABELED",
|
||||
triggerContext: `issue labeled with '${eventData.labelTrigger}'`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
eventType: "ISSUE_ASSIGNED",
|
||||
triggerContext: `issue assigned to '${eventData.assigneeTrigger}'`,
|
||||
triggerContext: eventData.assigneeTrigger
|
||||
? `issue assigned to '${eventData.assigneeTrigger}'`
|
||||
: `issue assigned event`,
|
||||
};
|
||||
|
||||
case "pull_request":
|
||||
@@ -429,6 +439,7 @@ ${
|
||||
}
|
||||
<claude_comment_id>${context.claudeCommentId}</claude_comment_id>
|
||||
<trigger_username>${context.triggerUsername ?? "Unknown"}</trigger_username>
|
||||
<trigger_display_name>${githubData.triggerDisplayName ?? context.triggerUsername ?? "Unknown"}</trigger_display_name>
|
||||
<trigger_phrase>${context.triggerPhrase}</trigger_phrase>
|
||||
${
|
||||
(eventData.eventName === "issue_comment" ||
|
||||
@@ -447,33 +458,15 @@ ${sanitizeContent(context.directPrompt)}
|
||||
</direct_prompt>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
eventData.eventName === "pull_request_review_comment"
|
||||
? `<comment_tool_info>
|
||||
IMPORTANT: For this inline PR review comment, you have been provided with ONLY the mcp__github__update_pull_request_comment tool to update this specific review comment.
|
||||
${`<comment_tool_info>
|
||||
IMPORTANT: You have been provided with the mcp__github_file_ops__update_claude_comment tool to update your comment. This tool automatically handles both issue and PR comments.
|
||||
|
||||
Tool usage example for mcp__github__update_pull_request_comment:
|
||||
Tool usage example for mcp__github_file_ops__update_claude_comment:
|
||||
{
|
||||
"owner": "${context.repository.split("/")[0]}",
|
||||
"repo": "${context.repository.split("/")[1]}",
|
||||
"commentId": ${eventData.commentId || context.claudeCommentId},
|
||||
"body": "Your comment text here"
|
||||
}
|
||||
All four parameters (owner, repo, commentId, body) are required.
|
||||
</comment_tool_info>`
|
||||
: `<comment_tool_info>
|
||||
IMPORTANT: For this event type, you have been provided with ONLY the mcp__github__update_issue_comment tool to update comments.
|
||||
|
||||
Tool usage example for mcp__github__update_issue_comment:
|
||||
{
|
||||
"owner": "${context.repository.split("/")[0]}",
|
||||
"repo": "${context.repository.split("/")[1]}",
|
||||
"commentId": ${context.claudeCommentId},
|
||||
"body": "Your comment text here"
|
||||
}
|
||||
All four parameters (owner, repo, commentId, body) are required.
|
||||
</comment_tool_info>`
|
||||
}
|
||||
Only the body parameter is required - the tool automatically knows which comment to update.
|
||||
</comment_tool_info>`}
|
||||
|
||||
Your task is to analyze the context, understand the request, and provide helpful responses and/or implement code changes as needed.
|
||||
|
||||
@@ -487,12 +480,13 @@ Follow these steps:
|
||||
1. Create a Todo List:
|
||||
- Use your GitHub comment to maintain a detailed task list based on the request.
|
||||
- Format todos as a checklist (- [ ] for incomplete, - [x] for complete).
|
||||
- Update the comment using ${eventData.eventName === "pull_request_review_comment" ? "mcp__github__update_pull_request_comment" : "mcp__github__update_issue_comment"} with each task completion.
|
||||
- Update the comment using mcp__github_file_ops__update_claude_comment with each task completion.
|
||||
|
||||
2. Gather Context:
|
||||
- Analyze the pre-fetched data provided above.
|
||||
- For ISSUE_CREATED: Read the issue body to find the request after the trigger phrase.
|
||||
- For ISSUE_ASSIGNED: Read the entire issue body to understand the task.
|
||||
- For ISSUE_LABELED: Read the entire issue body to understand the task.
|
||||
${eventData.eventName === "issue_comment" || eventData.eventName === "pull_request_review_comment" || eventData.eventName === "pull_request_review" ? ` - For comment/review events: Your instructions are in the <trigger_comment> tag above.` : ""}
|
||||
${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was provided and is shown in the <direct_prompt> tag above. This is not from any GitHub comment but a direct instruction to execute.` : ""}
|
||||
- IMPORTANT: Only the comment/issue containing '${context.triggerPhrase}' has your instructions.
|
||||
@@ -517,11 +511,11 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
|
||||
- Look for bugs, security issues, performance problems, and other issues
|
||||
- Suggest improvements for readability and maintainability
|
||||
- Check for best practices and coding standards
|
||||
- Reference specific code sections with file paths and line numbers${eventData.isPR ? "\n - AFTER reading files and analyzing code, you MUST call mcp__github__update_issue_comment to post your review" : ""}
|
||||
- Reference specific code sections with file paths and line numbers${eventData.isPR ? "\n - AFTER reading files and analyzing code, you MUST call mcp__github_file_ops__update_claude_comment to post your review" : ""}
|
||||
- Formulate a concise, technical, and helpful response based on the context.
|
||||
- Reference specific code with inline formatting or code blocks.
|
||||
- Include relevant file paths and line numbers when applicable.
|
||||
- ${eventData.isPR ? "IMPORTANT: Submit your review feedback by updating the Claude comment. This will be displayed as your PR review." : "Remember that this feedback must be posted to the GitHub comment."}
|
||||
- ${eventData.isPR ? "IMPORTANT: Submit your review feedback by updating the Claude comment using mcp__github_file_ops__update_claude_comment. This will be displayed as your PR review." : "Remember that this feedback must be posted to the GitHub comment using mcp__github_file_ops__update_claude_comment."}
|
||||
|
||||
B. For Straightforward Changes:
|
||||
- Use file system tools to make the change locally.
|
||||
@@ -532,12 +526,14 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
|
||||
? `
|
||||
- Push directly using mcp__github_file_ops__commit_files to the existing branch (works for both new and existing files).
|
||||
- Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files).
|
||||
- When pushing changes with this tool and TRIGGER_USERNAME is not "Unknown", include a "Co-authored-by: ${context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>" line in the commit message.`
|
||||
- When pushing changes with this tool and the trigger user is not "Unknown", include a Co-authored-by trailer in the commit message.
|
||||
- Use: "Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>"`
|
||||
: `
|
||||
- You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch.
|
||||
- Push changes directly to the current branch using mcp__github_file_ops__commit_files (works for both new and existing files)
|
||||
- Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files).
|
||||
- When pushing changes and TRIGGER_USERNAME is not "Unknown", include a "Co-authored-by: ${context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>" line in the commit message.
|
||||
- When pushing changes and the trigger user is not "Unknown", include a Co-authored-by trailer in the commit message.
|
||||
- Use: "Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>"
|
||||
${
|
||||
eventData.claudeBranch
|
||||
? `- Provide a URL to create a PR manually in this format:
|
||||
@@ -576,8 +572,8 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
|
||||
|
||||
Important Notes:
|
||||
- All communication must happen through GitHub PR comments.
|
||||
- Never create new comments. Only update the existing comment using ${eventData.eventName === "pull_request_review_comment" ? "mcp__github__update_pull_request_comment" : "mcp__github__update_issue_comment"} with comment_id: ${context.claudeCommentId}.
|
||||
- This includes ALL responses: code reviews, answers to questions, progress updates, and final results.${eventData.isPR ? "\n- PR CRITICAL: After reading files and forming your response, you MUST post it by calling mcp__github__update_issue_comment. Do NOT just respond with a normal response, the user will not see it." : ""}
|
||||
- Never create new comments. Only update the existing comment using mcp__github_file_ops__update_claude_comment.
|
||||
- This includes ALL responses: code reviews, answers to questions, progress updates, and final results.${eventData.isPR ? "\n- PR CRITICAL: After reading files and forming your response, you MUST post it by calling mcp__github_file_ops__update_claude_comment. Do NOT just respond with a normal response, the user will not see it." : ""}
|
||||
- You communicate exclusively by editing your single comment - not through any other means.
|
||||
- Use this spinner HTML when work is in progress: <img src="https://github.com/user-attachments/assets/5ac382c7-e004-429b-8e35-7feb3e8f9c6f" width="14px" height="14px" style="vertical-align: middle; margin-left: 4px;" />
|
||||
${eventData.isPR && !eventData.claudeBranch ? `- Always push to the existing branch when triggered on a PR.` : `- IMPORTANT: You are already on the correct branch (${eventData.claudeBranch || "the created branch"}). Never create new branches when triggered on issues or closed/merged PRs.`}
|
||||
@@ -650,7 +646,9 @@ export async function createPrompt(
|
||||
claudeBranch,
|
||||
);
|
||||
|
||||
await mkdir("/tmp/claude-prompts", { recursive: true });
|
||||
await mkdir(`${process.env.RUNNER_TEMP}/claude-prompts`, {
|
||||
recursive: true,
|
||||
});
|
||||
|
||||
// Generate the prompt
|
||||
const promptContent = generatePrompt(preparedContext, githubData);
|
||||
@@ -661,16 +659,18 @@ export async function createPrompt(
|
||||
console.log("=======================");
|
||||
|
||||
// Write the prompt file
|
||||
await writeFile("/tmp/claude-prompts/claude-prompt.txt", promptContent);
|
||||
await writeFile(
|
||||
`${process.env.RUNNER_TEMP}/claude-prompts/claude-prompt.txt`,
|
||||
promptContent,
|
||||
);
|
||||
|
||||
// Set allowed tools
|
||||
const allAllowedTools = buildAllowedToolsString(
|
||||
preparedContext.eventData,
|
||||
preparedContext.allowedTools,
|
||||
context.inputs.allowedTools,
|
||||
);
|
||||
const allDisallowedTools = buildDisallowedToolsString(
|
||||
preparedContext.disallowedTools,
|
||||
preparedContext.allowedTools,
|
||||
context.inputs.disallowedTools,
|
||||
context.inputs.allowedTools,
|
||||
);
|
||||
|
||||
core.exportVariable("ALLOWED_TOOLS", allAllowedTools);
|
||||
|
||||
@@ -65,7 +65,17 @@ type IssueAssignedEvent = {
|
||||
issueNumber: string;
|
||||
baseBranch: string;
|
||||
claudeBranch: string;
|
||||
assigneeTrigger: string;
|
||||
assigneeTrigger?: string;
|
||||
};
|
||||
|
||||
type IssueLabeledEvent = {
|
||||
eventName: "issues";
|
||||
eventAction: "labeled";
|
||||
isPR: false;
|
||||
issueNumber: string;
|
||||
baseBranch: string;
|
||||
claudeBranch: string;
|
||||
labelTrigger: string;
|
||||
};
|
||||
|
||||
type PullRequestEvent = {
|
||||
@@ -85,6 +95,7 @@ export type EventData =
|
||||
| IssueCommentEvent
|
||||
| IssueOpenedEvent
|
||||
| IssueAssignedEvent
|
||||
| IssueLabeledEvent
|
||||
| PullRequestEvent;
|
||||
|
||||
// Combined type with separate eventData field
|
||||
|
||||
@@ -59,6 +59,7 @@ async function run() {
|
||||
repository: `${context.repository.owner}/${context.repository.repo}`,
|
||||
prNumber: context.entityNumber.toString(),
|
||||
isPR: context.isPR,
|
||||
triggerUsername: context.actor,
|
||||
});
|
||||
|
||||
// Step 8: Setup branch
|
||||
@@ -84,12 +85,16 @@ async function run() {
|
||||
);
|
||||
|
||||
// Step 11: Get MCP configuration
|
||||
const mcpConfig = await prepareMcpConfig(
|
||||
const additionalMcpConfig = process.env.MCP_CONFIG || "";
|
||||
const mcpConfig = await prepareMcpConfig({
|
||||
githubToken,
|
||||
context.repository.owner,
|
||||
context.repository.repo,
|
||||
branchInfo.currentBranch,
|
||||
);
|
||||
owner: context.repository.owner,
|
||||
repo: context.repository.repo,
|
||||
branch: branchInfo.currentBranch,
|
||||
additionalMcpConfig,
|
||||
claudeCommentId: commentId.toString(),
|
||||
allowedTools: context.inputs.allowedTools,
|
||||
});
|
||||
core.setOutput("mcp_config", mcpConfig);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "../github/context";
|
||||
import { GITHUB_SERVER_URL } from "../github/api/config";
|
||||
import { checkAndDeleteEmptyBranch } from "../github/operations/branch-cleanup";
|
||||
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
@@ -166,7 +167,7 @@ async function run() {
|
||||
if (Array.isArray(outputData) && outputData.length > 0) {
|
||||
const lastElement = outputData[outputData.length - 1];
|
||||
if (
|
||||
lastElement.role === "system" &&
|
||||
lastElement.type === "result" &&
|
||||
"cost_usd" in lastElement &&
|
||||
"duration_ms" in lastElement
|
||||
) {
|
||||
@@ -204,23 +205,14 @@ async function run() {
|
||||
|
||||
const updatedBody = updateCommentBody(commentInput);
|
||||
|
||||
// Update the comment using the appropriate API
|
||||
try {
|
||||
if (isPRReviewComment) {
|
||||
await octokit.rest.pulls.updateReviewComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body: updatedBody,
|
||||
});
|
||||
} else {
|
||||
await octokit.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body: updatedBody,
|
||||
});
|
||||
}
|
||||
await updateClaudeComment(octokit.rest, {
|
||||
owner,
|
||||
repo,
|
||||
commentId,
|
||||
body: updatedBody,
|
||||
isPullRequestReviewComment: isPRReviewComment,
|
||||
});
|
||||
console.log(
|
||||
`✅ Updated ${isPRReviewComment ? "PR review" : "issue"} comment ${commentId} with job link`,
|
||||
);
|
||||
|
||||
@@ -9,7 +9,10 @@ export type Octokits = {
|
||||
|
||||
export function createOctokit(token: string): Octokits {
|
||||
return {
|
||||
rest: new Octokit({ auth: token }),
|
||||
rest: new Octokit({
|
||||
auth: token,
|
||||
baseUrl: GITHUB_API_URL,
|
||||
}),
|
||||
graphql: graphql.defaults({
|
||||
baseUrl: GITHUB_API_URL,
|
||||
headers: {
|
||||
|
||||
@@ -104,3 +104,11 @@ export const ISSUE_QUERY = `
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const USER_QUERY = `
|
||||
query($login: String!) {
|
||||
user(login: $login) {
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as github from "@actions/github";
|
||||
import type {
|
||||
IssuesEvent,
|
||||
IssuesAssignedEvent,
|
||||
IssueCommentEvent,
|
||||
PullRequestEvent,
|
||||
PullRequestReviewEvent,
|
||||
@@ -28,11 +29,14 @@ export type ParsedGitHubContext = {
|
||||
inputs: {
|
||||
triggerPhrase: string;
|
||||
assigneeTrigger: string;
|
||||
allowedTools: string;
|
||||
disallowedTools: string;
|
||||
labelTrigger: string;
|
||||
allowedTools: string[];
|
||||
disallowedTools: string[];
|
||||
customInstructions: string;
|
||||
directPrompt: string;
|
||||
baseBranch?: string;
|
||||
branchPrefix: string;
|
||||
useStickyComment: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -52,11 +56,14 @@ export function parseGitHubContext(): ParsedGitHubContext {
|
||||
inputs: {
|
||||
triggerPhrase: process.env.TRIGGER_PHRASE ?? "@claude",
|
||||
assigneeTrigger: process.env.ASSIGNEE_TRIGGER ?? "",
|
||||
allowedTools: process.env.ALLOWED_TOOLS ?? "",
|
||||
disallowedTools: process.env.DISALLOWED_TOOLS ?? "",
|
||||
labelTrigger: process.env.LABEL_TRIGGER ?? "",
|
||||
allowedTools: parseMultilineInput(process.env.ALLOWED_TOOLS ?? ""),
|
||||
disallowedTools: parseMultilineInput(process.env.DISALLOWED_TOOLS ?? ""),
|
||||
customInstructions: process.env.CUSTOM_INSTRUCTIONS ?? "",
|
||||
directPrompt: process.env.DIRECT_PROMPT ?? "",
|
||||
baseBranch: process.env.BASE_BRANCH,
|
||||
branchPrefix: process.env.BRANCH_PREFIX ?? "claude/",
|
||||
useStickyComment: process.env.STICKY_COMMENT === "true",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -110,6 +117,14 @@ export function parseGitHubContext(): ParsedGitHubContext {
|
||||
}
|
||||
}
|
||||
|
||||
export function parseMultilineInput(s: string): string[] {
|
||||
return s
|
||||
.split(/,|[\n\r]+/)
|
||||
.map((tool) => tool.replace(/#.+$/, ""))
|
||||
.map((tool) => tool.trim())
|
||||
.filter((tool) => tool.length > 0);
|
||||
}
|
||||
|
||||
export function isIssuesEvent(
|
||||
context: ParsedGitHubContext,
|
||||
): context is ParsedGitHubContext & { payload: IssuesEvent } {
|
||||
@@ -139,3 +154,9 @@ export function isPullRequestReviewCommentEvent(
|
||||
): context is ParsedGitHubContext & { payload: PullRequestReviewCommentEvent } {
|
||||
return context.eventName === "pull_request_review_comment";
|
||||
}
|
||||
|
||||
export function isIssuesAssignedEvent(
|
||||
context: ParsedGitHubContext,
|
||||
): context is ParsedGitHubContext & { payload: IssuesAssignedEvent } {
|
||||
return isIssuesEvent(context) && context.eventAction === "assigned";
|
||||
}
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import { execSync } from "child_process";
|
||||
import type { Octokits } from "../api/client";
|
||||
import { ISSUE_QUERY, PR_QUERY, USER_QUERY } from "../api/queries/github";
|
||||
import type {
|
||||
GitHubPullRequest,
|
||||
GitHubIssue,
|
||||
GitHubComment,
|
||||
GitHubFile,
|
||||
GitHubIssue,
|
||||
GitHubPullRequest,
|
||||
GitHubReview,
|
||||
PullRequestQueryResponse,
|
||||
IssueQueryResponse,
|
||||
PullRequestQueryResponse,
|
||||
} from "../types";
|
||||
import { PR_QUERY, ISSUE_QUERY } from "../api/queries/github";
|
||||
import type { Octokits } from "../api/client";
|
||||
import { downloadCommentImages } from "../utils/image-downloader";
|
||||
import type { CommentWithImages } from "../utils/image-downloader";
|
||||
import { downloadCommentImages } from "../utils/image-downloader";
|
||||
|
||||
type FetchDataParams = {
|
||||
octokits: Octokits;
|
||||
repository: string;
|
||||
prNumber: string;
|
||||
isPR: boolean;
|
||||
triggerUsername?: string;
|
||||
};
|
||||
|
||||
export type GitHubFileWithSHA = GitHubFile & {
|
||||
@@ -31,6 +32,7 @@ export type FetchDataResult = {
|
||||
changedFilesWithSHA: GitHubFileWithSHA[];
|
||||
reviewData: { nodes: GitHubReview[] } | null;
|
||||
imageUrlMap: Map<string, string>;
|
||||
triggerDisplayName?: string | null;
|
||||
};
|
||||
|
||||
export async function fetchGitHubData({
|
||||
@@ -38,6 +40,7 @@ export async function fetchGitHubData({
|
||||
repository,
|
||||
prNumber,
|
||||
isPR,
|
||||
triggerUsername,
|
||||
}: FetchDataParams): Promise<FetchDataResult> {
|
||||
const [owner, repo] = repository.split("/");
|
||||
if (!owner || !repo) {
|
||||
@@ -101,6 +104,14 @@ export async function fetchGitHubData({
|
||||
let changedFilesWithSHA: GitHubFileWithSHA[] = [];
|
||||
if (isPR && changedFiles.length > 0) {
|
||||
changedFilesWithSHA = changedFiles.map((file) => {
|
||||
// Don't compute SHA for deleted files
|
||||
if (file.changeType === "DELETED") {
|
||||
return {
|
||||
...file,
|
||||
sha: "deleted",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Use git hash-object to compute the SHA for the current file content
|
||||
const sha = execSync(`git hash-object "${file.path}"`, {
|
||||
@@ -183,6 +194,12 @@ export async function fetchGitHubData({
|
||||
allComments,
|
||||
);
|
||||
|
||||
// Fetch trigger user display name if username is provided
|
||||
let triggerDisplayName: string | null | undefined;
|
||||
if (triggerUsername) {
|
||||
triggerDisplayName = await fetchUserDisplayName(octokits, triggerUsername);
|
||||
}
|
||||
|
||||
return {
|
||||
contextData,
|
||||
comments,
|
||||
@@ -190,5 +207,27 @@ export async function fetchGitHubData({
|
||||
changedFilesWithSHA,
|
||||
reviewData,
|
||||
imageUrlMap,
|
||||
triggerDisplayName,
|
||||
};
|
||||
}
|
||||
|
||||
export type UserQueryResponse = {
|
||||
user: {
|
||||
name: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export async function fetchUserDisplayName(
|
||||
octokits: Octokits,
|
||||
login: string,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const result = await octokits.graphql<UserQueryResponse>(USER_QUERY, {
|
||||
login,
|
||||
});
|
||||
return result.user.name;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to fetch user display name for ${login}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ export async function setupBranch(
|
||||
): Promise<BranchInfo> {
|
||||
const { owner, repo } = context.repository;
|
||||
const entityNumber = context.entityNumber;
|
||||
const { baseBranch } = context.inputs;
|
||||
const { baseBranch, branchPrefix } = context.inputs;
|
||||
const isPR = context.isPR;
|
||||
|
||||
if (isPR) {
|
||||
@@ -45,9 +45,16 @@ export async function setupBranch(
|
||||
|
||||
const branchName = prData.headRefName;
|
||||
|
||||
// Execute git commands to checkout PR branch (shallow fetch for performance)
|
||||
// Fetch the branch with a depth of 20 to avoid fetching too much history, while still allowing for some context
|
||||
await $`git fetch origin --depth=20 ${branchName}`;
|
||||
// Determine optimal fetch depth based on PR commit count, with a minimum of 20
|
||||
const commitCount = prData.commits.totalCount;
|
||||
const fetchDepth = Math.max(commitCount, 20);
|
||||
|
||||
console.log(
|
||||
`PR #${entityNumber}: ${commitCount} commits, using fetch depth ${fetchDepth}`,
|
||||
);
|
||||
|
||||
// Execute git commands to checkout PR branch (dynamic depth based on PR size)
|
||||
await $`git fetch origin --depth=${fetchDepth} ${branchName}`;
|
||||
await $`git checkout ${branchName}`;
|
||||
|
||||
console.log(`Successfully checked out PR branch for PR #${entityNumber}`);
|
||||
@@ -90,7 +97,7 @@ export async function setupBranch(
|
||||
.split("T")
|
||||
.join("_");
|
||||
|
||||
const newBranch = `claude/${entityType}-${entityNumber}-${timestamp}`;
|
||||
const newBranch = `${branchPrefix}${entityType}-${entityNumber}-${timestamp}`;
|
||||
|
||||
try {
|
||||
// Get the SHA of the source branch
|
||||
|
||||
@@ -9,6 +9,7 @@ import { appendFileSync } from "fs";
|
||||
import { createJobRunLink, createCommentBody } from "./common";
|
||||
import {
|
||||
isPullRequestReviewCommentEvent,
|
||||
isPullRequestEvent,
|
||||
type ParsedGitHubContext,
|
||||
} from "../../context";
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
@@ -25,8 +26,39 @@ export async function createInitialComment(
|
||||
try {
|
||||
let response;
|
||||
|
||||
// Only use createReplyForReviewComment if it's a PR review comment AND we have a comment_id
|
||||
if (isPullRequestReviewCommentEvent(context)) {
|
||||
if (
|
||||
context.inputs.useStickyComment &&
|
||||
context.isPR &&
|
||||
!isPullRequestEvent(context)
|
||||
) {
|
||||
const comments = await octokit.rest.issues.listComments({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: context.entityNumber,
|
||||
});
|
||||
const existingComment = comments.data.find(
|
||||
(comment) =>
|
||||
comment.user?.login.indexOf("claude[bot]") !== -1 ||
|
||||
comment.body === initialBody,
|
||||
);
|
||||
if (existingComment) {
|
||||
response = await octokit.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: existingComment.id,
|
||||
body: initialBody,
|
||||
});
|
||||
} else {
|
||||
// Create new comment if no existing one found
|
||||
response = await octokit.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: context.entityNumber,
|
||||
body: initialBody,
|
||||
});
|
||||
}
|
||||
} else if (isPullRequestReviewCommentEvent(context)) {
|
||||
// Only use createReplyForReviewComment if it's a PR review comment AND we have a comment_id
|
||||
response = await octokit.rest.pulls.createReplyForReviewComment({
|
||||
owner,
|
||||
repo,
|
||||
|
||||
70
src/github/operations/comments/update-claude-comment.ts
Normal file
70
src/github/operations/comments/update-claude-comment.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
export type UpdateClaudeCommentParams = {
|
||||
owner: string;
|
||||
repo: string;
|
||||
commentId: number;
|
||||
body: string;
|
||||
isPullRequestReviewComment: boolean;
|
||||
};
|
||||
|
||||
export type UpdateClaudeCommentResult = {
|
||||
id: number;
|
||||
html_url: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a Claude comment on GitHub (either an issue/PR comment or a PR review comment)
|
||||
*
|
||||
* @param octokit - Authenticated Octokit instance
|
||||
* @param params - Parameters for updating the comment
|
||||
* @returns The updated comment details
|
||||
* @throws Error if the update fails
|
||||
*/
|
||||
export async function updateClaudeComment(
|
||||
octokit: Octokit,
|
||||
params: UpdateClaudeCommentParams,
|
||||
): Promise<UpdateClaudeCommentResult> {
|
||||
const { owner, repo, commentId, body, isPullRequestReviewComment } = params;
|
||||
|
||||
let response;
|
||||
|
||||
try {
|
||||
if (isPullRequestReviewComment) {
|
||||
// Try PR review comment API first
|
||||
response = await octokit.rest.pulls.updateReviewComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
// Use issue comment API (works for both issues and PR general comments)
|
||||
response = await octokit.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body,
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
// If PR review comment update fails with 404, fall back to issue comment API
|
||||
if (isPullRequestReviewComment && error.status === 404) {
|
||||
response = await octokit.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: response.data.id,
|
||||
html_url: response.data.html_url,
|
||||
updated_at: response.data.updated_at,
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
isPullRequestReviewCommentEvent,
|
||||
type ParsedGitHubContext,
|
||||
} from "../../context";
|
||||
import { updateClaudeComment } from "./update-claude-comment";
|
||||
|
||||
export async function updateTrackingComment(
|
||||
octokit: Octokits,
|
||||
@@ -36,25 +37,19 @@ export async function updateTrackingComment(
|
||||
|
||||
// Update the existing comment with the branch link
|
||||
try {
|
||||
if (isPullRequestReviewCommentEvent(context)) {
|
||||
// For PR review comments (inline comments), use the pulls API
|
||||
await octokit.rest.pulls.updateReviewComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body: updatedBody,
|
||||
});
|
||||
console.log(`✅ Updated PR review comment ${commentId} with branch link`);
|
||||
} else {
|
||||
// For all other comments, use the issues API
|
||||
await octokit.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: commentId,
|
||||
body: updatedBody,
|
||||
});
|
||||
console.log(`✅ Updated issue comment ${commentId} with branch link`);
|
||||
}
|
||||
const isPRReviewComment = isPullRequestReviewCommentEvent(context);
|
||||
|
||||
await updateClaudeComment(octokit.rest, {
|
||||
owner,
|
||||
repo,
|
||||
commentId,
|
||||
body: updatedBody,
|
||||
isPullRequestReviewComment: isPRReviewComment,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`✅ Updated ${isPRReviewComment ? "PR review" : "issue"} comment ${commentId} with branch link`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error updating comment with branch link:", error);
|
||||
throw error;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Types for GitHub GraphQL query responses
|
||||
export type GitHubAuthor = {
|
||||
login: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type GitHubComment = {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import * as core from "@actions/core";
|
||||
import {
|
||||
isIssuesEvent,
|
||||
isIssuesAssignedEvent,
|
||||
isIssueCommentEvent,
|
||||
isPullRequestEvent,
|
||||
isPullRequestReviewEvent,
|
||||
@@ -12,7 +13,7 @@ import type { ParsedGitHubContext } from "../context";
|
||||
|
||||
export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
|
||||
const {
|
||||
inputs: { assigneeTrigger, triggerPhrase, directPrompt },
|
||||
inputs: { assigneeTrigger, labelTrigger, triggerPhrase, directPrompt },
|
||||
} = context;
|
||||
|
||||
// If direct prompt is provided, always trigger
|
||||
@@ -22,10 +23,10 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
|
||||
}
|
||||
|
||||
// Check for assignee trigger
|
||||
if (isIssuesEvent(context) && context.eventAction === "assigned") {
|
||||
if (isIssuesAssignedEvent(context)) {
|
||||
// Remove @ symbol from assignee_trigger if present
|
||||
let triggerUser = assigneeTrigger.replace(/^@/, "");
|
||||
const assigneeUsername = context.payload.issue.assignee?.login || "";
|
||||
const assigneeUsername = context.payload.assignee?.login || "";
|
||||
|
||||
if (triggerUser && assigneeUsername === triggerUser) {
|
||||
console.log(`Issue assigned to trigger user '${triggerUser}'`);
|
||||
@@ -33,6 +34,16 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
// Check for label trigger
|
||||
if (isIssuesEvent(context) && context.eventAction === "labeled") {
|
||||
const labelName = (context.payload as any).label?.name || "";
|
||||
|
||||
if (labelTrigger && labelName === labelTrigger) {
|
||||
console.log(`Issue labeled with trigger label '${labelTrigger}'`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for issue body and title trigger on issue creation
|
||||
if (isIssuesEvent(context) && context.eventAction === "opened") {
|
||||
const issueBody = context.payload.issue.body || "";
|
||||
|
||||
@@ -7,6 +7,8 @@ import { readFile } from "fs/promises";
|
||||
import { join } from "path";
|
||||
import fetch from "node-fetch";
|
||||
import { GITHUB_API_URL } from "../github/api/config";
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
|
||||
|
||||
type GitHubRef = {
|
||||
object: {
|
||||
@@ -123,13 +125,58 @@ server.tool(
|
||||
? filePath
|
||||
: join(REPO_DIR, filePath);
|
||||
|
||||
const content = await readFile(fullPath, "utf-8");
|
||||
return {
|
||||
path: filePath,
|
||||
mode: "100644",
|
||||
type: "blob",
|
||||
content: content,
|
||||
};
|
||||
// Check if file is binary (images, etc.)
|
||||
const isBinaryFile =
|
||||
/\.(png|jpg|jpeg|gif|webp|ico|pdf|zip|tar|gz|exe|bin|woff|woff2|ttf|eot)$/i.test(
|
||||
filePath,
|
||||
);
|
||||
|
||||
if (isBinaryFile) {
|
||||
// For binary files, create a blob first using the Blobs API
|
||||
const binaryContent = await readFile(fullPath);
|
||||
|
||||
// Create blob using Blobs API (supports encoding parameter)
|
||||
const blobUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/blobs`;
|
||||
const blobResponse = await fetch(blobUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
Authorization: `Bearer ${githubToken}`,
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content: binaryContent.toString("base64"),
|
||||
encoding: "base64",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!blobResponse.ok) {
|
||||
const errorText = await blobResponse.text();
|
||||
throw new Error(
|
||||
`Failed to create blob for ${filePath}: ${blobResponse.status} - ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const blobData = (await blobResponse.json()) as { sha: string };
|
||||
|
||||
// Return tree entry with blob SHA
|
||||
return {
|
||||
path: filePath,
|
||||
mode: "100644",
|
||||
type: "blob",
|
||||
sha: blobData.sha,
|
||||
};
|
||||
} else {
|
||||
// For text files, include content directly in tree
|
||||
const content = await readFile(fullPath, "utf-8");
|
||||
return {
|
||||
path: filePath,
|
||||
mode: "100644",
|
||||
type: "blob",
|
||||
content: content,
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -439,6 +486,70 @@ server.tool(
|
||||
},
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"update_claude_comment",
|
||||
"Update the Claude comment with progress and results (automatically handles both issue and PR comments)",
|
||||
{
|
||||
body: z.string().describe("The updated comment content"),
|
||||
},
|
||||
async ({ body }) => {
|
||||
try {
|
||||
const githubToken = process.env.GITHUB_TOKEN;
|
||||
const claudeCommentId = process.env.CLAUDE_COMMENT_ID;
|
||||
const eventName = process.env.GITHUB_EVENT_NAME;
|
||||
|
||||
if (!githubToken) {
|
||||
throw new Error("GITHUB_TOKEN environment variable is required");
|
||||
}
|
||||
if (!claudeCommentId) {
|
||||
throw new Error("CLAUDE_COMMENT_ID environment variable is required");
|
||||
}
|
||||
|
||||
const owner = REPO_OWNER;
|
||||
const repo = REPO_NAME;
|
||||
const commentId = parseInt(claudeCommentId, 10);
|
||||
|
||||
const octokit = new Octokit({
|
||||
auth: githubToken,
|
||||
baseUrl: GITHUB_API_URL,
|
||||
});
|
||||
|
||||
const isPullRequestReviewComment =
|
||||
eventName === "pull_request_review_comment";
|
||||
|
||||
const result = await updateClaudeComment(octokit, {
|
||||
owner,
|
||||
repo,
|
||||
commentId,
|
||||
body,
|
||||
isPullRequestReviewComment,
|
||||
});
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Error: ${errorMessage}`,
|
||||
},
|
||||
],
|
||||
error: errorMessage,
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
async function runServer() {
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
|
||||
@@ -1,28 +1,37 @@
|
||||
import * as core from "@actions/core";
|
||||
import { GITHUB_API_URL } from "../github/api/config";
|
||||
|
||||
type PrepareConfigParams = {
|
||||
githubToken: string;
|
||||
owner: string;
|
||||
repo: string;
|
||||
branch: string;
|
||||
additionalMcpConfig?: string;
|
||||
claudeCommentId?: string;
|
||||
allowedTools: string[];
|
||||
};
|
||||
|
||||
export async function prepareMcpConfig(
|
||||
githubToken: string,
|
||||
owner: string,
|
||||
repo: string,
|
||||
branch: string,
|
||||
params: PrepareConfigParams,
|
||||
): Promise<string> {
|
||||
const {
|
||||
githubToken,
|
||||
owner,
|
||||
repo,
|
||||
branch,
|
||||
additionalMcpConfig,
|
||||
claudeCommentId,
|
||||
allowedTools,
|
||||
} = params;
|
||||
try {
|
||||
const mcpConfig = {
|
||||
const allowedToolsList = allowedTools || [];
|
||||
|
||||
const hasGitHubMcpTools = allowedToolsList.some((tool) =>
|
||||
tool.startsWith("mcp__github__"),
|
||||
);
|
||||
|
||||
const baseMcpConfig: { mcpServers: Record<string, unknown> } = {
|
||||
mcpServers: {
|
||||
github: {
|
||||
command: "docker",
|
||||
args: [
|
||||
"run",
|
||||
"-i",
|
||||
"--rm",
|
||||
"-e",
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
||||
"ghcr.io/anthropics/github-mcp-server:sha-7382253",
|
||||
],
|
||||
env: {
|
||||
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
|
||||
},
|
||||
},
|
||||
github_file_ops: {
|
||||
command: "bun",
|
||||
args: [
|
||||
@@ -35,12 +44,65 @@ export async function prepareMcpConfig(
|
||||
REPO_NAME: repo,
|
||||
BRANCH_NAME: branch,
|
||||
REPO_DIR: process.env.GITHUB_WORKSPACE || process.cwd(),
|
||||
...(claudeCommentId && { CLAUDE_COMMENT_ID: claudeCommentId }),
|
||||
GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "",
|
||||
IS_PR: process.env.IS_PR || "false",
|
||||
GITHUB_API_URL: GITHUB_API_URL,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return JSON.stringify(mcpConfig, null, 2);
|
||||
if (hasGitHubMcpTools) {
|
||||
baseMcpConfig.mcpServers.github = {
|
||||
command: "docker",
|
||||
args: [
|
||||
"run",
|
||||
"-i",
|
||||
"--rm",
|
||||
"-e",
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
||||
"ghcr.io/github/github-mcp-server:sha-6d69797", // https://github.com/github/github-mcp-server/releases/tag/v0.5.0
|
||||
],
|
||||
env: {
|
||||
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Merge with additional MCP config if provided
|
||||
if (additionalMcpConfig && additionalMcpConfig.trim()) {
|
||||
try {
|
||||
const additionalConfig = JSON.parse(additionalMcpConfig);
|
||||
|
||||
// Validate that parsed JSON is an object
|
||||
if (typeof additionalConfig !== "object" || additionalConfig === null) {
|
||||
throw new Error("MCP config must be a valid JSON object");
|
||||
}
|
||||
|
||||
core.info(
|
||||
"Merging additional MCP server configuration with built-in servers",
|
||||
);
|
||||
|
||||
// Merge configurations with user config overriding built-in servers
|
||||
const mergedConfig = {
|
||||
...baseMcpConfig,
|
||||
...additionalConfig,
|
||||
mcpServers: {
|
||||
...baseMcpConfig.mcpServers,
|
||||
...additionalConfig.mcpServers,
|
||||
},
|
||||
};
|
||||
|
||||
return JSON.stringify(mergedConfig, null, 2);
|
||||
} catch (parseError) {
|
||||
core.warning(
|
||||
`Failed to parse additional MCP config: ${parseError}. Using base config only.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(baseMcpConfig, null, 2);
|
||||
} catch (error) {
|
||||
core.setFailed(`Install MCP server failed with error: ${error}`);
|
||||
process.exit(1);
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
buildDisallowedToolsString,
|
||||
} from "../src/create-prompt";
|
||||
import type { PreparedContext } from "../src/create-prompt";
|
||||
import type { EventData } from "../src/create-prompt/types";
|
||||
|
||||
describe("generatePrompt", () => {
|
||||
const mockGitHubData = {
|
||||
@@ -227,6 +226,33 @@ describe("generatePrompt", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should generate prompt for issue labeled event", () => {
|
||||
const envVars: PreparedContext = {
|
||||
repository: "owner/repo",
|
||||
claudeCommentId: "12345",
|
||||
triggerPhrase: "@claude",
|
||||
eventData: {
|
||||
eventName: "issues",
|
||||
eventAction: "labeled",
|
||||
isPR: false,
|
||||
issueNumber: "888",
|
||||
baseBranch: "main",
|
||||
claudeBranch: "claude/issue-888-20240101_120000",
|
||||
labelTrigger: "claude-task",
|
||||
},
|
||||
};
|
||||
|
||||
const prompt = generatePrompt(envVars, mockGitHubData);
|
||||
|
||||
expect(prompt).toContain("<event_type>ISSUE_LABELED</event_type>");
|
||||
expect(prompt).toContain(
|
||||
"<trigger_context>issue labeled with 'claude-task'</trigger_context>",
|
||||
);
|
||||
expect(prompt).toContain(
|
||||
"[Create a PR](https://github.com/owner/repo/compare/main",
|
||||
);
|
||||
});
|
||||
|
||||
test("should include direct prompt when provided", () => {
|
||||
const envVars: PreparedContext = {
|
||||
repository: "owner/repo",
|
||||
@@ -317,7 +343,7 @@ describe("generatePrompt", () => {
|
||||
|
||||
expect(prompt).toContain("<trigger_username>johndoe</trigger_username>");
|
||||
expect(prompt).toContain(
|
||||
"Co-authored-by: johndoe <johndoe@users.noreply.github.com>",
|
||||
'Use: "Co-authored-by: johndoe <johndoe@users.noreply.github.com>"',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -615,19 +641,56 @@ describe("getEventTypeAndContext", () => {
|
||||
expect(result.eventType).toBe("ISSUE_ASSIGNED");
|
||||
expect(result.triggerContext).toBe("issue assigned to 'claude-bot'");
|
||||
});
|
||||
|
||||
test("should return correct type and context for issue labeled", () => {
|
||||
const envVars: PreparedContext = {
|
||||
repository: "owner/repo",
|
||||
claudeCommentId: "12345",
|
||||
triggerPhrase: "@claude",
|
||||
eventData: {
|
||||
eventName: "issues",
|
||||
eventAction: "labeled",
|
||||
isPR: false,
|
||||
issueNumber: "888",
|
||||
baseBranch: "main",
|
||||
claudeBranch: "claude/issue-888-20240101_120000",
|
||||
labelTrigger: "claude-task",
|
||||
},
|
||||
};
|
||||
|
||||
const result = getEventTypeAndContext(envVars);
|
||||
|
||||
expect(result.eventType).toBe("ISSUE_LABELED");
|
||||
expect(result.triggerContext).toBe("issue labeled with 'claude-task'");
|
||||
});
|
||||
|
||||
test("should return correct type and context for issue assigned without assigneeTrigger", () => {
|
||||
const envVars: PreparedContext = {
|
||||
repository: "owner/repo",
|
||||
claudeCommentId: "12345",
|
||||
triggerPhrase: "@claude",
|
||||
directPrompt: "Please assess this issue",
|
||||
eventData: {
|
||||
eventName: "issues",
|
||||
eventAction: "assigned",
|
||||
isPR: false,
|
||||
issueNumber: "999",
|
||||
baseBranch: "main",
|
||||
claudeBranch: "claude/issue-999-20240101_120000",
|
||||
// No assigneeTrigger when using directPrompt
|
||||
},
|
||||
};
|
||||
|
||||
const result = getEventTypeAndContext(envVars);
|
||||
|
||||
expect(result.eventType).toBe("ISSUE_ASSIGNED");
|
||||
expect(result.triggerContext).toBe("issue assigned event");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAllowedToolsString", () => {
|
||||
test("should return issue comment tool for regular events", () => {
|
||||
const mockEventData: EventData = {
|
||||
eventName: "issue_comment",
|
||||
commentId: "123",
|
||||
isPR: true,
|
||||
prNumber: "456",
|
||||
commentBody: "Test comment",
|
||||
};
|
||||
|
||||
const result = buildAllowedToolsString(mockEventData);
|
||||
const result = buildAllowedToolsString();
|
||||
|
||||
// The base tools should be in the result
|
||||
expect(result).toContain("Edit");
|
||||
@@ -636,22 +699,15 @@ describe("buildAllowedToolsString", () => {
|
||||
expect(result).toContain("LS");
|
||||
expect(result).toContain("Read");
|
||||
expect(result).toContain("Write");
|
||||
expect(result).toContain("mcp__github__update_issue_comment");
|
||||
expect(result).toContain("mcp__github_file_ops__update_claude_comment");
|
||||
expect(result).not.toContain("mcp__github__update_issue_comment");
|
||||
expect(result).not.toContain("mcp__github__update_pull_request_comment");
|
||||
expect(result).toContain("mcp__github_file_ops__commit_files");
|
||||
expect(result).toContain("mcp__github_file_ops__delete_files");
|
||||
});
|
||||
|
||||
test("should return PR comment tool for inline review comments", () => {
|
||||
const mockEventData: EventData = {
|
||||
eventName: "pull_request_review_comment",
|
||||
isPR: true,
|
||||
prNumber: "456",
|
||||
commentBody: "Test review comment",
|
||||
commentId: "789",
|
||||
};
|
||||
|
||||
const result = buildAllowedToolsString(mockEventData);
|
||||
const result = buildAllowedToolsString();
|
||||
|
||||
// The base tools should be in the result
|
||||
expect(result).toContain("Edit");
|
||||
@@ -660,23 +716,16 @@ describe("buildAllowedToolsString", () => {
|
||||
expect(result).toContain("LS");
|
||||
expect(result).toContain("Read");
|
||||
expect(result).toContain("Write");
|
||||
expect(result).toContain("mcp__github_file_ops__update_claude_comment");
|
||||
expect(result).not.toContain("mcp__github__update_issue_comment");
|
||||
expect(result).toContain("mcp__github__update_pull_request_comment");
|
||||
expect(result).not.toContain("mcp__github__update_pull_request_comment");
|
||||
expect(result).toContain("mcp__github_file_ops__commit_files");
|
||||
expect(result).toContain("mcp__github_file_ops__delete_files");
|
||||
});
|
||||
|
||||
test("should append custom tools when provided", () => {
|
||||
const mockEventData: EventData = {
|
||||
eventName: "issue_comment",
|
||||
commentId: "123",
|
||||
isPR: true,
|
||||
prNumber: "456",
|
||||
commentBody: "Test comment",
|
||||
};
|
||||
|
||||
const customTools = "Tool1,Tool2,Tool3";
|
||||
const result = buildAllowedToolsString(mockEventData, customTools);
|
||||
const customTools = ["Tool1", "Tool2", "Tool3"];
|
||||
const result = buildAllowedToolsString(customTools);
|
||||
|
||||
// Base tools should be present
|
||||
expect(result).toContain("Edit");
|
||||
@@ -706,7 +755,7 @@ describe("buildDisallowedToolsString", () => {
|
||||
});
|
||||
|
||||
test("should append custom disallowed tools when provided", () => {
|
||||
const customDisallowedTools = "BadTool1,BadTool2";
|
||||
const customDisallowedTools = ["BadTool1", "BadTool2"];
|
||||
const result = buildDisallowedToolsString(customDisallowedTools);
|
||||
|
||||
// Base disallowed tools should be present
|
||||
@@ -724,8 +773,8 @@ describe("buildDisallowedToolsString", () => {
|
||||
});
|
||||
|
||||
test("should remove hardcoded disallowed tools if they are in allowed tools", () => {
|
||||
const customDisallowedTools = "BadTool1,BadTool2";
|
||||
const allowedTools = "WebSearch,SomeOtherTool";
|
||||
const customDisallowedTools = ["BadTool1", "BadTool2"];
|
||||
const allowedTools = ["WebSearch", "SomeOtherTool"];
|
||||
const result = buildDisallowedToolsString(
|
||||
customDisallowedTools,
|
||||
allowedTools,
|
||||
@@ -743,7 +792,7 @@ describe("buildDisallowedToolsString", () => {
|
||||
});
|
||||
|
||||
test("should remove all hardcoded disallowed tools if they are all in allowed tools", () => {
|
||||
const allowedTools = "WebSearch,WebFetch,SomeOtherTool";
|
||||
const allowedTools = ["WebSearch", "WebFetch", "SomeOtherTool"];
|
||||
const result = buildDisallowedToolsString(undefined, allowedTools);
|
||||
|
||||
// Both hardcoded disallowed tools should be removed
|
||||
@@ -755,8 +804,8 @@ describe("buildDisallowedToolsString", () => {
|
||||
});
|
||||
|
||||
test("should handle custom disallowed tools when all hardcoded tools are overridden", () => {
|
||||
const customDisallowedTools = "BadTool1,BadTool2";
|
||||
const allowedTools = "WebSearch,WebFetch";
|
||||
const customDisallowedTools = ["BadTool1", "BadTool2"];
|
||||
const allowedTools = ["WebSearch", "WebFetch"];
|
||||
const result = buildDisallowedToolsString(
|
||||
customDisallowedTools,
|
||||
allowedTools,
|
||||
|
||||
57
test/github/context.test.ts
Normal file
57
test/github/context.test.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { parseMultilineInput } from "../../src/github/context";
|
||||
|
||||
describe("parseMultilineInput", () => {
|
||||
it("should parse a comma-separated string", () => {
|
||||
const input = `Bash(bun install),Bash(bun test:*),Bash(bun typecheck)`;
|
||||
const result = parseMultilineInput(input);
|
||||
expect(result).toEqual([
|
||||
"Bash(bun install)",
|
||||
"Bash(bun test:*)",
|
||||
"Bash(bun typecheck)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should parse multiline string", () => {
|
||||
const input = `Bash(bun install)
|
||||
Bash(bun test:*)
|
||||
Bash(bun typecheck)`;
|
||||
const result = parseMultilineInput(input);
|
||||
expect(result).toEqual([
|
||||
"Bash(bun install)",
|
||||
"Bash(bun test:*)",
|
||||
"Bash(bun typecheck)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should parse comma-separated multiline line", () => {
|
||||
const input = `Bash(bun install),Bash(bun test:*)
|
||||
Bash(bun typecheck)`;
|
||||
const result = parseMultilineInput(input);
|
||||
expect(result).toEqual([
|
||||
"Bash(bun install)",
|
||||
"Bash(bun test:*)",
|
||||
"Bash(bun typecheck)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should ignore comments", () => {
|
||||
const input = `Bash(bun install),
|
||||
Bash(bun test:*) # For testing
|
||||
# For type checking
|
||||
Bash(bun typecheck)
|
||||
`;
|
||||
const result = parseMultilineInput(input);
|
||||
expect(result).toEqual([
|
||||
"Bash(bun install)",
|
||||
"Bash(bun test:*)",
|
||||
"Bash(bun typecheck)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should parse an empty string", () => {
|
||||
const input = "";
|
||||
const result = parseMultilineInput(input);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
414
test/install-mcp-server.test.ts
Normal file
414
test/install-mcp-server.test.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
|
||||
import { prepareMcpConfig } from "../src/mcp/install-mcp-server";
|
||||
import * as core from "@actions/core";
|
||||
|
||||
describe("prepareMcpConfig", () => {
|
||||
let consoleInfoSpy: any;
|
||||
let consoleWarningSpy: any;
|
||||
let setFailedSpy: any;
|
||||
let processExitSpy: any;
|
||||
|
||||
beforeEach(() => {
|
||||
consoleInfoSpy = spyOn(core, "info").mockImplementation(() => {});
|
||||
consoleWarningSpy = spyOn(core, "warning").mockImplementation(() => {});
|
||||
setFailedSpy = spyOn(core, "setFailed").mockImplementation(() => {});
|
||||
processExitSpy = spyOn(process, "exit").mockImplementation(() => {
|
||||
throw new Error("Process exit");
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleInfoSpy.mockRestore();
|
||||
consoleWarningSpy.mockRestore();
|
||||
setFailedSpy.mockRestore();
|
||||
processExitSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("should return base config when no additional config is provided and no allowed_tools", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers).toBeDefined();
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops.env.GITHUB_TOKEN).toBe(
|
||||
"test-token",
|
||||
);
|
||||
expect(parsed.mcpServers.github_file_ops.env.REPO_OWNER).toBe("test-owner");
|
||||
expect(parsed.mcpServers.github_file_ops.env.REPO_NAME).toBe("test-repo");
|
||||
expect(parsed.mcpServers.github_file_ops.env.BRANCH_NAME).toBe(
|
||||
"test-branch",
|
||||
);
|
||||
});
|
||||
|
||||
test("should include github MCP server when mcp__github__ tools are allowed", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
allowedTools: [
|
||||
"mcp__github__create_issue",
|
||||
"mcp__github_file_ops__commit_files",
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers).toBeDefined();
|
||||
expect(parsed.mcpServers.github).toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe(
|
||||
"test-token",
|
||||
);
|
||||
});
|
||||
|
||||
test("should not include github MCP server when only file_ops tools are allowed", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
allowedTools: [
|
||||
"mcp__github_file_ops__commit_files",
|
||||
"mcp__github_file_ops__update_claude_comment",
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers).toBeDefined();
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
});
|
||||
|
||||
test("should include file_ops server even when no GitHub tools are allowed", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
allowedTools: ["Edit", "Read", "Write"],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers).toBeDefined();
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
});
|
||||
|
||||
test("should return base config when additional config is empty string", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: "",
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers).toBeDefined();
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
expect(consoleWarningSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should return base config when additional config is whitespace only", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: " \n\t ",
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers).toBeDefined();
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
expect(consoleWarningSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should merge valid additional config with base config", async () => {
|
||||
const additionalConfig = JSON.stringify({
|
||||
mcpServers: {
|
||||
custom_server: {
|
||||
command: "custom-command",
|
||||
args: ["arg1", "arg2"],
|
||||
env: {
|
||||
CUSTOM_ENV: "custom-value",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: additionalConfig,
|
||||
allowedTools: [
|
||||
"mcp__github__create_issue",
|
||||
"mcp__github_file_ops__commit_files",
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
"Merging additional MCP server configuration with built-in servers",
|
||||
);
|
||||
expect(parsed.mcpServers.github).toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
expect(parsed.mcpServers.custom_server).toBeDefined();
|
||||
expect(parsed.mcpServers.custom_server.command).toBe("custom-command");
|
||||
expect(parsed.mcpServers.custom_server.args).toEqual(["arg1", "arg2"]);
|
||||
expect(parsed.mcpServers.custom_server.env.CUSTOM_ENV).toBe("custom-value");
|
||||
});
|
||||
|
||||
test("should override built-in servers when additional config has same server names", async () => {
|
||||
const additionalConfig = JSON.stringify({
|
||||
mcpServers: {
|
||||
github: {
|
||||
command: "overridden-command",
|
||||
args: ["overridden-arg"],
|
||||
env: {
|
||||
OVERRIDDEN_ENV: "overridden-value",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: additionalConfig,
|
||||
allowedTools: [
|
||||
"mcp__github__create_issue",
|
||||
"mcp__github_file_ops__commit_files",
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
"Merging additional MCP server configuration with built-in servers",
|
||||
);
|
||||
expect(parsed.mcpServers.github.command).toBe("overridden-command");
|
||||
expect(parsed.mcpServers.github.args).toEqual(["overridden-arg"]);
|
||||
expect(parsed.mcpServers.github.env.OVERRIDDEN_ENV).toBe(
|
||||
"overridden-value",
|
||||
);
|
||||
expect(
|
||||
parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN,
|
||||
).toBeUndefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
});
|
||||
|
||||
test("should merge additional root-level properties", async () => {
|
||||
const additionalConfig = JSON.stringify({
|
||||
customProperty: "custom-value",
|
||||
anotherProperty: {
|
||||
nested: "value",
|
||||
},
|
||||
mcpServers: {
|
||||
custom_server: {
|
||||
command: "custom",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: additionalConfig,
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.customProperty).toBe("custom-value");
|
||||
expect(parsed.anotherProperty).toEqual({ nested: "value" });
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.custom_server).toBeDefined();
|
||||
});
|
||||
|
||||
test("should handle invalid JSON gracefully", async () => {
|
||||
const invalidJson = "{ invalid json }";
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: invalidJson,
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(consoleWarningSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to parse additional MCP config:"),
|
||||
);
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
});
|
||||
|
||||
test("should handle non-object JSON values", async () => {
|
||||
const nonObjectJson = JSON.stringify("string value");
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: nonObjectJson,
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(consoleWarningSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to parse additional MCP config:"),
|
||||
);
|
||||
expect(consoleWarningSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("MCP config must be a valid JSON object"),
|
||||
);
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
});
|
||||
|
||||
test("should handle null JSON value", async () => {
|
||||
const nullJson = JSON.stringify(null);
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: nullJson,
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(consoleWarningSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to parse additional MCP config:"),
|
||||
);
|
||||
expect(consoleWarningSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("MCP config must be a valid JSON object"),
|
||||
);
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
});
|
||||
|
||||
test("should handle array JSON value", async () => {
|
||||
const arrayJson = JSON.stringify([1, 2, 3]);
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: arrayJson,
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
// Arrays are objects in JavaScript, so they pass the object check
|
||||
// But they'll fail when trying to spread or access mcpServers property
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
"Merging additional MCP server configuration with built-in servers",
|
||||
);
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops).toBeDefined();
|
||||
// The array will be spread into the config (0: 1, 1: 2, 2: 3)
|
||||
expect(parsed[0]).toBe(1);
|
||||
expect(parsed[1]).toBe(2);
|
||||
expect(parsed[2]).toBe(3);
|
||||
});
|
||||
|
||||
test("should merge complex nested configurations", async () => {
|
||||
const additionalConfig = JSON.stringify({
|
||||
mcpServers: {
|
||||
server1: {
|
||||
command: "cmd1",
|
||||
env: { KEY1: "value1" },
|
||||
},
|
||||
server2: {
|
||||
command: "cmd2",
|
||||
env: { KEY2: "value2" },
|
||||
},
|
||||
github_file_ops: {
|
||||
command: "overridden",
|
||||
env: { CUSTOM: "value" },
|
||||
},
|
||||
},
|
||||
otherConfig: {
|
||||
nested: {
|
||||
deeply: "value",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
additionalMcpConfig: additionalConfig,
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.server1).toBeDefined();
|
||||
expect(parsed.mcpServers.server2).toBeDefined();
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_file_ops.command).toBe("overridden");
|
||||
expect(parsed.mcpServers.github_file_ops.env.CUSTOM).toBe("value");
|
||||
expect(parsed.otherConfig.nested.deeply).toBe("value");
|
||||
});
|
||||
|
||||
test("should preserve GITHUB_ACTION_PATH in file_ops server args", async () => {
|
||||
const oldEnv = process.env.GITHUB_ACTION_PATH;
|
||||
process.env.GITHUB_ACTION_PATH = "/test/action/path";
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github_file_ops.args[1]).toBe(
|
||||
"/test/action/path/src/mcp/github-file-ops-server.ts",
|
||||
);
|
||||
|
||||
process.env.GITHUB_ACTION_PATH = oldEnv;
|
||||
});
|
||||
|
||||
test("should use process.cwd() when GITHUB_WORKSPACE is not set", async () => {
|
||||
const oldEnv = process.env.GITHUB_WORKSPACE;
|
||||
delete process.env.GITHUB_WORKSPACE;
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
allowedTools: [],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github_file_ops.env.REPO_DIR).toBe(process.cwd());
|
||||
|
||||
process.env.GITHUB_WORKSPACE = oldEnv;
|
||||
});
|
||||
});
|
||||
@@ -10,14 +10,17 @@ import type {
|
||||
const defaultInputs = {
|
||||
triggerPhrase: "/claude",
|
||||
assigneeTrigger: "",
|
||||
labelTrigger: "",
|
||||
anthropicModel: "claude-3-7-sonnet-20250219",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
allowedTools: [] as string[],
|
||||
disallowedTools: [] as string[],
|
||||
customInstructions: "",
|
||||
directPrompt: "",
|
||||
useBedrock: false,
|
||||
useVertex: false,
|
||||
timeoutMinutes: 30,
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
};
|
||||
|
||||
const defaultRepository = {
|
||||
@@ -91,6 +94,12 @@ export const mockIssueAssignedContext: ParsedGitHubContext = {
|
||||
actor: "admin-user",
|
||||
payload: {
|
||||
action: "assigned",
|
||||
assignee: {
|
||||
login: "claude-bot",
|
||||
id: 11111,
|
||||
avatar_url: "https://avatars.githubusercontent.com/u/11111",
|
||||
html_url: "https://github.com/claude-bot",
|
||||
},
|
||||
issue: {
|
||||
number: 123,
|
||||
title: "Feature: Add dark mode support",
|
||||
@@ -122,6 +131,46 @@ export const mockIssueAssignedContext: ParsedGitHubContext = {
|
||||
inputs: { ...defaultInputs, assigneeTrigger: "@claude-bot" },
|
||||
};
|
||||
|
||||
export const mockIssueLabeledContext: ParsedGitHubContext = {
|
||||
runId: "1234567890",
|
||||
eventName: "issues",
|
||||
eventAction: "labeled",
|
||||
repository: defaultRepository,
|
||||
actor: "admin-user",
|
||||
payload: {
|
||||
action: "labeled",
|
||||
issue: {
|
||||
number: 1234,
|
||||
title: "Enhancement: Improve search functionality",
|
||||
body: "The current search is too slow and needs optimization",
|
||||
user: {
|
||||
login: "alice-wonder",
|
||||
id: 54321,
|
||||
avatar_url: "https://avatars.githubusercontent.com/u/54321",
|
||||
html_url: "https://github.com/alice-wonder",
|
||||
},
|
||||
assignee: null,
|
||||
},
|
||||
label: {
|
||||
id: 987654321,
|
||||
name: "claude-task",
|
||||
color: "f29513",
|
||||
description: "Label for Claude AI interactions",
|
||||
},
|
||||
repository: {
|
||||
name: "test-repo",
|
||||
full_name: "test-owner/test-repo",
|
||||
private: false,
|
||||
owner: {
|
||||
login: "test-owner",
|
||||
},
|
||||
},
|
||||
} as IssuesEvent,
|
||||
entityNumber: 1234,
|
||||
isPR: false,
|
||||
inputs: { ...defaultInputs, labelTrigger: "claude-task" },
|
||||
};
|
||||
|
||||
// Issue comment on issue event
|
||||
export const mockIssueCommentContext: ParsedGitHubContext = {
|
||||
runId: "1234567890",
|
||||
|
||||
@@ -62,10 +62,13 @@ describe("checkWritePermissions", () => {
|
||||
inputs: {
|
||||
triggerPhrase: "@claude",
|
||||
assigneeTrigger: "",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
labelTrigger: "",
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
customInstructions: "",
|
||||
directPrompt: "",
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -219,6 +219,55 @@ describe("parseEnvVarsWithContext", () => {
|
||||
),
|
||||
).toThrow("BASE_BRANCH is required for issues event");
|
||||
});
|
||||
|
||||
test("should allow issue assigned event with direct_prompt and no assigneeTrigger", () => {
|
||||
const contextWithDirectPrompt = createMockContext({
|
||||
...mockIssueAssignedContext,
|
||||
inputs: {
|
||||
...mockIssueAssignedContext.inputs,
|
||||
assigneeTrigger: "", // No assignee trigger
|
||||
directPrompt: "Please assess this issue", // But direct prompt is provided
|
||||
},
|
||||
});
|
||||
|
||||
const result = prepareContext(
|
||||
contextWithDirectPrompt,
|
||||
"12345",
|
||||
"main",
|
||||
"claude/issue-123-20240101_120000",
|
||||
);
|
||||
|
||||
expect(result.eventData.eventName).toBe("issues");
|
||||
expect(result.eventData.isPR).toBe(false);
|
||||
expect(result.directPrompt).toBe("Please assess this issue");
|
||||
if (
|
||||
result.eventData.eventName === "issues" &&
|
||||
result.eventData.eventAction === "assigned"
|
||||
) {
|
||||
expect(result.eventData.issueNumber).toBe("123");
|
||||
expect(result.eventData.assigneeTrigger).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
test("should throw error when neither assigneeTrigger nor directPrompt provided for issue assigned event", () => {
|
||||
const contextWithoutTriggers = createMockContext({
|
||||
...mockIssueAssignedContext,
|
||||
inputs: {
|
||||
...mockIssueAssignedContext.inputs,
|
||||
assigneeTrigger: "", // No assignee trigger
|
||||
directPrompt: "", // No direct prompt
|
||||
},
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
prepareContext(
|
||||
contextWithoutTriggers,
|
||||
"12345",
|
||||
"main",
|
||||
"claude/issue-123-20240101_120000",
|
||||
),
|
||||
).toThrow("ASSIGNEE_TRIGGER is required for issue assigned event");
|
||||
});
|
||||
});
|
||||
|
||||
describe("optional fields", () => {
|
||||
@@ -242,7 +291,7 @@ describe("parseEnvVarsWithContext", () => {
|
||||
...mockPullRequestCommentContext,
|
||||
inputs: {
|
||||
...mockPullRequestCommentContext.inputs,
|
||||
allowedTools: "Tool1,Tool2",
|
||||
allowedTools: ["Tool1", "Tool2"],
|
||||
},
|
||||
});
|
||||
const result = prepareContext(contextWithAllowedTools, "12345");
|
||||
|
||||
@@ -6,6 +6,7 @@ import { describe, it, expect } from "bun:test";
|
||||
import {
|
||||
createMockContext,
|
||||
mockIssueAssignedContext,
|
||||
mockIssueLabeledContext,
|
||||
mockIssueCommentContext,
|
||||
mockIssueOpenedContext,
|
||||
mockPullRequestReviewContext,
|
||||
@@ -29,10 +30,13 @@ describe("checkContainsTrigger", () => {
|
||||
inputs: {
|
||||
triggerPhrase: "/claude",
|
||||
assigneeTrigger: "",
|
||||
labelTrigger: "",
|
||||
directPrompt: "Fix the bug in the login form",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
customInstructions: "",
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
},
|
||||
});
|
||||
expect(checkContainsTrigger(context)).toBe(true);
|
||||
@@ -55,10 +59,13 @@ describe("checkContainsTrigger", () => {
|
||||
inputs: {
|
||||
triggerPhrase: "/claude",
|
||||
assigneeTrigger: "",
|
||||
labelTrigger: "",
|
||||
directPrompt: "",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
customInstructions: "",
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
},
|
||||
});
|
||||
expect(checkContainsTrigger(context)).toBe(false);
|
||||
@@ -87,6 +94,11 @@ describe("checkContainsTrigger", () => {
|
||||
...mockIssueAssignedContext,
|
||||
payload: {
|
||||
...mockIssueAssignedContext.payload,
|
||||
assignee: {
|
||||
...(mockIssueAssignedContext.payload as IssuesAssignedEvent)
|
||||
.assignee,
|
||||
login: "otherUser",
|
||||
},
|
||||
issue: {
|
||||
...(mockIssueAssignedContext.payload as IssuesAssignedEvent).issue,
|
||||
assignee: {
|
||||
@@ -102,6 +114,39 @@ describe("checkContainsTrigger", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("label trigger", () => {
|
||||
it("should return true when issue is labeled with the trigger label", () => {
|
||||
const context = mockIssueLabeledContext;
|
||||
expect(checkContainsTrigger(context)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when issue is labeled with a different label", () => {
|
||||
const context = {
|
||||
...mockIssueLabeledContext,
|
||||
payload: {
|
||||
...mockIssueLabeledContext.payload,
|
||||
label: {
|
||||
...(mockIssueLabeledContext.payload as any).label,
|
||||
name: "bug",
|
||||
},
|
||||
},
|
||||
} as ParsedGitHubContext;
|
||||
expect(checkContainsTrigger(context)).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for non-labeled events", () => {
|
||||
const context = {
|
||||
...mockIssueLabeledContext,
|
||||
eventAction: "opened",
|
||||
payload: {
|
||||
...mockIssueLabeledContext.payload,
|
||||
action: "opened",
|
||||
},
|
||||
} as ParsedGitHubContext;
|
||||
expect(checkContainsTrigger(context)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("issue body and title trigger", () => {
|
||||
it("should return true when issue body contains trigger phrase", () => {
|
||||
const context = mockIssueOpenedContext;
|
||||
@@ -227,10 +272,13 @@ describe("checkContainsTrigger", () => {
|
||||
inputs: {
|
||||
triggerPhrase: "@claude",
|
||||
assigneeTrigger: "",
|
||||
labelTrigger: "",
|
||||
directPrompt: "",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
customInstructions: "",
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
},
|
||||
});
|
||||
expect(checkContainsTrigger(context)).toBe(true);
|
||||
@@ -254,10 +302,13 @@ describe("checkContainsTrigger", () => {
|
||||
inputs: {
|
||||
triggerPhrase: "@claude",
|
||||
assigneeTrigger: "",
|
||||
labelTrigger: "",
|
||||
directPrompt: "",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
customInstructions: "",
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
},
|
||||
});
|
||||
expect(checkContainsTrigger(context)).toBe(true);
|
||||
@@ -281,10 +332,13 @@ describe("checkContainsTrigger", () => {
|
||||
inputs: {
|
||||
triggerPhrase: "@claude",
|
||||
assigneeTrigger: "",
|
||||
labelTrigger: "",
|
||||
directPrompt: "",
|
||||
allowedTools: "",
|
||||
disallowedTools: "",
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
customInstructions: "",
|
||||
branchPrefix: "claude/",
|
||||
useStickyComment: false,
|
||||
},
|
||||
});
|
||||
expect(checkContainsTrigger(context)).toBe(false);
|
||||
|
||||
413
test/update-claude-comment.test.ts
Normal file
413
test/update-claude-comment.test.ts
Normal file
@@ -0,0 +1,413 @@
|
||||
import { describe, test, expect, jest, beforeEach } from "bun:test";
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import {
|
||||
updateClaudeComment,
|
||||
type UpdateClaudeCommentParams,
|
||||
} from "../src/github/operations/comments/update-claude-comment";
|
||||
|
||||
describe("updateClaudeComment", () => {
|
||||
let mockOctokit: Octokit;
|
||||
|
||||
beforeEach(() => {
|
||||
mockOctokit = {
|
||||
rest: {
|
||||
issues: {
|
||||
updateComment: jest.fn(),
|
||||
},
|
||||
pulls: {
|
||||
updateReviewComment: jest.fn(),
|
||||
},
|
||||
},
|
||||
} as any as Octokit;
|
||||
});
|
||||
|
||||
test("should update issue comment successfully", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 123456,
|
||||
html_url: "https://github.com/owner/repo/issues/1#issuecomment-123456",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
body: "Updated comment",
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 123456,
|
||||
body: "Updated comment",
|
||||
isPullRequestReviewComment: false,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(mockOctokit.rest.issues.updateComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 123456,
|
||||
body: "Updated comment",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 123456,
|
||||
html_url: "https://github.com/owner/repo/issues/1#issuecomment-123456",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should update PR comment successfully", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 789012,
|
||||
html_url: "https://github.com/owner/repo/pull/2#issuecomment-789012",
|
||||
updated_at: "2024-01-02T00:00:00Z",
|
||||
body: "Updated PR comment",
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 789012,
|
||||
body: "Updated PR comment",
|
||||
isPullRequestReviewComment: false,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(mockOctokit.rest.issues.updateComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 789012,
|
||||
body: "Updated PR comment",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 789012,
|
||||
html_url: "https://github.com/owner/repo/pull/2#issuecomment-789012",
|
||||
updated_at: "2024-01-02T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should update PR review comment successfully", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 345678,
|
||||
html_url: "https://github.com/owner/repo/pull/3#discussion_r345678",
|
||||
updated_at: "2024-01-03T00:00:00Z",
|
||||
body: "Updated review comment",
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.pulls.updateReviewComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 345678,
|
||||
body: "Updated review comment",
|
||||
isPullRequestReviewComment: true,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(mockOctokit.rest.pulls.updateReviewComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 345678,
|
||||
body: "Updated review comment",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 345678,
|
||||
html_url: "https://github.com/owner/repo/pull/3#discussion_r345678",
|
||||
updated_at: "2024-01-03T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should fallback to issue comment API when PR review comment update fails with 404", async () => {
|
||||
const mockError = new Error("Not Found") as any;
|
||||
mockError.status = 404;
|
||||
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 456789,
|
||||
html_url: "https://github.com/owner/repo/pull/4#issuecomment-456789",
|
||||
updated_at: "2024-01-04T00:00:00Z",
|
||||
body: "Updated via fallback",
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.pulls.updateReviewComment = jest
|
||||
.fn()
|
||||
.mockRejectedValue(mockError);
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 456789,
|
||||
body: "Updated via fallback",
|
||||
isPullRequestReviewComment: true,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(mockOctokit.rest.pulls.updateReviewComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 456789,
|
||||
body: "Updated via fallback",
|
||||
});
|
||||
|
||||
expect(mockOctokit.rest.issues.updateComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 456789,
|
||||
body: "Updated via fallback",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 456789,
|
||||
html_url: "https://github.com/owner/repo/pull/4#issuecomment-456789",
|
||||
updated_at: "2024-01-04T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should propagate error when PR review comment update fails with non-404 error", async () => {
|
||||
const mockError = new Error("Internal Server Error") as any;
|
||||
mockError.status = 500;
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.pulls.updateReviewComment = jest
|
||||
.fn()
|
||||
.mockRejectedValue(mockError);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 567890,
|
||||
body: "This will fail",
|
||||
isPullRequestReviewComment: true,
|
||||
};
|
||||
|
||||
await expect(updateClaudeComment(mockOctokit, params)).rejects.toEqual(
|
||||
mockError,
|
||||
);
|
||||
|
||||
expect(mockOctokit.rest.pulls.updateReviewComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 567890,
|
||||
body: "This will fail",
|
||||
});
|
||||
|
||||
// Ensure fallback wasn't attempted
|
||||
expect(mockOctokit.rest.issues.updateComment).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should propagate error when issue comment update fails", async () => {
|
||||
const mockError = new Error("Forbidden");
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockRejectedValue(mockError);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 678901,
|
||||
body: "This will also fail",
|
||||
isPullRequestReviewComment: false,
|
||||
};
|
||||
|
||||
await expect(updateClaudeComment(mockOctokit, params)).rejects.toEqual(
|
||||
mockError,
|
||||
);
|
||||
|
||||
expect(mockOctokit.rest.issues.updateComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 678901,
|
||||
body: "This will also fail",
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle empty body", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 111222,
|
||||
html_url: "https://github.com/owner/repo/issues/5#issuecomment-111222",
|
||||
updated_at: "2024-01-05T00:00:00Z",
|
||||
body: "",
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 111222,
|
||||
body: "",
|
||||
isPullRequestReviewComment: false,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 111222,
|
||||
html_url: "https://github.com/owner/repo/issues/5#issuecomment-111222",
|
||||
updated_at: "2024-01-05T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle very long body", async () => {
|
||||
const longBody = "x".repeat(10000);
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 333444,
|
||||
html_url: "https://github.com/owner/repo/issues/6#issuecomment-333444",
|
||||
updated_at: "2024-01-06T00:00:00Z",
|
||||
body: longBody,
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 333444,
|
||||
body: longBody,
|
||||
isPullRequestReviewComment: false,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(mockOctokit.rest.issues.updateComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 333444,
|
||||
body: longBody,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 333444,
|
||||
html_url: "https://github.com/owner/repo/issues/6#issuecomment-333444",
|
||||
updated_at: "2024-01-06T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle markdown formatting in body", async () => {
|
||||
const markdownBody = `
|
||||
# Header
|
||||
- List item 1
|
||||
- List item 2
|
||||
|
||||
\`\`\`typescript
|
||||
const code = "example";
|
||||
\`\`\`
|
||||
|
||||
[Link](https://example.com)
|
||||
`.trim();
|
||||
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 555666,
|
||||
html_url: "https://github.com/owner/repo/issues/7#issuecomment-555666",
|
||||
updated_at: "2024-01-07T00:00:00Z",
|
||||
body: markdownBody,
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.updateComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 555666,
|
||||
body: markdownBody,
|
||||
isPullRequestReviewComment: false,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
expect(mockOctokit.rest.issues.updateComment).toHaveBeenCalledWith({
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
comment_id: 555666,
|
||||
body: markdownBody,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 555666,
|
||||
html_url: "https://github.com/owner/repo/issues/7#issuecomment-555666",
|
||||
updated_at: "2024-01-07T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle different response data fields", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: 777888,
|
||||
html_url: "https://github.com/owner/repo/pull/8#discussion_r777888",
|
||||
updated_at: "2024-01-08T12:30:45Z",
|
||||
body: "Updated",
|
||||
// Additional fields that might be in the response
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
user: { login: "bot" },
|
||||
node_id: "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDc3Nzg4OA==",
|
||||
},
|
||||
};
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.pulls.updateReviewComment = jest
|
||||
.fn()
|
||||
.mockResolvedValue(mockResponse);
|
||||
|
||||
const params: UpdateClaudeCommentParams = {
|
||||
owner: "testowner",
|
||||
repo: "testrepo",
|
||||
commentId: 777888,
|
||||
body: "Updated",
|
||||
isPullRequestReviewComment: true,
|
||||
};
|
||||
|
||||
const result = await updateClaudeComment(mockOctokit, params);
|
||||
|
||||
// Should only return the specific fields we care about
|
||||
expect(result).toEqual({
|
||||
id: 777888,
|
||||
html_url: "https://github.com/owner/repo/pull/8#discussion_r777888",
|
||||
updated_at: "2024-01-08T12:30:45Z",
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user