# Automated Bug Hunting with Claude: Integrating LLM Security Scans into Your CI/CD

> Learn how to deploy Claude’s BugHunter skill to automatically find and triage security bugs in production code, boosting safety without slowing delivery.

I’ve been tinkering with LLM‑driven security tools for a few years now, and the moment I got my hands on Claude’s **BugHunter** skill I realized it could finally bridge the gap between “nice‑to‑have” AI suggestions and a production‑grade, automated bug‑hunting pipeline. In this post I’ll walk through how I wired BugHunter into a typical CI/CD flow, the practical gotchas I hit, and why I still keep a human in the loop. If you’re looking for a polished marketing brochure, you’re in the wrong place – this is a raw, senior‑engineer‑level playbook that assumes you already have a CI system, a codebase you care about, and the willingness to treat AI output as a first‑class artifact.

## Why LLMs belong in bug hunting now

Static analysis, SAST, and dependency scanners have been around forever, but they all suffer from the same fundamental limitation: they are rule‑based. An LLM, on the other hand, can reason about code context, infer intent, and surface issues that never made it into a rule set. In practice I’ve seen three concrete benefits:

1. **Cross‑language insight** – BugHunter can read a TypeScript file, a Dockerfile, and a Bash script in the same pass and point out mismatched environment variables that a language‑specific linter would miss.
2. **Rapid triage of new CVEs** – When a new vulnerability is disclosed, the model can instantly scan for patterns that match the advisory, even if the advisory’s PoC is in a different language.
3. **Developer‑centric explanations** – The output includes a short natural‑language description and a suggested fix, which cuts down the time spent Googling “why is this line unsafe?”.

That said, LLMs are not a silver bullet. They hallucinate, they can miss low‑level memory bugs, and they are only as good as the prompt you give them. The rest of this article is about turning those “only as good as the prompt” moments into a repeatable, auditable process.

## Understanding Claude's BugHunter skill

Claude’s BugHunter is exposed as a **skill** in the Anthropic API. From a developer’s perspective it behaves like a CLI tool that accepts a list of file paths (or a git diff) and returns a JSON payload of findings. It is worth knowing what a skill actually is before wiring one into CI: [Anthropic's engineering write-up on writing tools for agents](https://www.anthropic.com/engineering/writing-tools-for-agents) sets out why a narrow, well-described tool is more reliable than a broad one, which is the same reason a single-purpose skill beats one prompt asked to do everything. The payload schema looks like this (simplified):

```json
{
  "findings": [
    {
      "file": "src/api/user.ts",
      "line": 42,
      "severity": "high",
      "type": "sql-injection",
      "description": "User‑controlled input is interpolated directly into a SQL query.",
      "suggested_fix": "Use parameterized queries via the database client."
    }
  ],
  "metadata": {
    "model": "claude-3-5-sonnet-20241022",
    "prompt_tokens": 1234,
    "completion_tokens": 567
  }
}
```

The skill is invoked via the `anthropic` CLI (installed from `@anthropic-ai/sdk`), or directly over HTTP. The key thing is that the skill **does not** modify your repository; it only reports. This makes it safe to drop into a CI step that can fail the build if any finding exceeds a configurable severity threshold.

> **Verification note**
> The exact JSON schema and model name are taken from the Anthropic API documentation at the time of writing. If Anthropic renames the skill or changes the payload, the parsing logic below needs to follow.

## Setting up the environment

Before you can call BugHunter you need two things:

1. **Anthropic API key** – Create one in the Anthropic console under *API Keys*. Store it as a secret in your CI provider (e.g., `ANTHROPIC_API_KEY` in GitHub Actions).
2. **CLI wrapper** – I prefer the official `anthropic` npm package because it ships a thin wrapper around the HTTP endpoint and handles retries.

```bash
# Install the CLI globally (or add to your repo’s devDependencies)
npm i -g @anthropic-ai/sdk
# Verify installation
anthropic --version
```

If you’re using a Docker‑based CI runner, add the install step to your Dockerfile:

```dockerfile
FROM node:20-alpine AS builder
RUN npm i -g @anthropic-ai/sdk@latest
# ...rest of your build steps
```

Make sure the runner’s network can reach `api.anthropic.com`. In restricted corporate environments you may need to whitelist the domain.

## Adding BugHunter to a typical CI workflow

Below is a minimal GitHub Actions workflow that runs BugHunter on every push to `main`. It assumes you already have a `test` job that runs your unit and integration suites.

```yaml
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npm test

  bughunt:
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: read
      checks: write
    steps:
      - uses: actions/checkout@v4
      - name: Install Anthropic CLI
        run: npm i -g @anthropic-ai/sdk
      - name: Run Claude BugHunter
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          # Collect changed files (or all files for a full scan)
          git diff --name-only ${{ github.event.before }} ${{ github.sha }} > changed.txt
          # Fallback to full repo if PR is from a fork without a base SHA
          if [ ! -s changed.txt ]; then
            git ls-files > changed.txt
          fi
          # Invoke the skill
          anthropic bughunter \
            --files @changed.txt \
            --output bughunter-report.json \
            --max-tokens 4096
      - name: Fail on high‑severity findings
        id: evaluate
        run: |
          jq -e '.findings[] | select(.severity=="high")' bughunter-report.json > /dev/null && exit 1 || exit 0
      - name: Upload report as artifact
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: bughunter-report
          path: bughunter-report.json
```

### Configuring the BugHunter step

The CLI accepts a handful of flags that are worth tweaking:

| Flag | Description | Typical value |
|------|-------------|---------------|
| `--files` | Path to a newline‑separated list of files to scan. Use `@` prefix to read from a file. | `@changed.txt` |
| `--output` | Destination JSON file. | `bughunter-report.json` |
| `--max-tokens` | Upper bound on tokens for the model’s response. Larger codebases need more. | `4096` |
| `--severity-threshold` | Optional filter; only returns findings at or above this level. | `medium` |
| `--timeout` | HTTP timeout in seconds. | `120` |

I usually set `--max-tokens` to 4096 for monorepos; anything higher triggers a “prompt too large” error from the API. If you hit that, split the scan into batches (e.g., per package) and merge the JSON outputs later.

### Handling findings and fail‑fast logic

The `jq` step above is deliberately simple: any `high` severity finding fails the job. In practice you’ll want a more nuanced policy:

```bash
# Fail on high, warn on medium
HIGH=$(jq '[.findings[] | select(.severity=="high")] | length' bughunter-report.json)
MEDIUM=$(jq '[.findings[] | select(.severity=="medium")] | length' bughunter-report.json)

if [ "$HIGH" -gt 0 ]; then
  echo "::error ::BugHunter found $HIGH high‑severity issues"
  exit 1
elif [ "$MEDIUM" -gt 5 ]; then
  echo "::warning ::BugHunter found $MEDIUM medium‑severity issues (threshold 5)"
fi
```

You can also post a GitHub Check Run with a markdown summary, which surfaces directly in the PR UI. The `actions/github-script` action makes that painless:

```yaml
- uses: actions/github-script@v7
  if: always()
  with:
    script: |
      const fs = require('fs');
      const report = JSON.parse(fs.readFileSync('bughunter-report.json', 'utf8'));
      const markdown = report.findings.map(f => `- **${f.severity.toUpperCase()}** ${f.file}:${f.line} – ${f.type}\n  ${f.description}\n  Suggested fix: ${f.suggested_fix}`).join('\n');
      await github.checks.create({
        owner: context.repo.owner,
        repo: context.repo.repo,
        name: 'Claude BugHunter',
        head_sha: context.sha,
        status: 'completed',
        conclusion: report.findings.some(f => f.severity === 'high') ? 'failure' : 'success',
        output: {
          title: 'BugHunter Findings',
          summary: `${report.findings.length} issues detected`,
          text: markdown
        }
      });
```

## Integrating with existing security tools

You probably already have a SAST scanner (e.g., CodeQL, SonarQube) or a dependency checker (Snyk, Dependabot). Rather than replace them, treat BugHunter as a **supplementary** layer:

1. **Run BugHunter after SAST** – This ensures any low‑level static rule violations are caught first, and you can set a higher severity threshold for the LLM to avoid duplicate noise.
2. **Merge reports** – Both tools emit JSON; a small Node script can concatenate them into a unified SARIF file for consumption by GitHub’s code scanning UI.

```ts
// merge-reports.ts
import * as fs from 'fs';
import * as path from 'path';

const bugHunter = JSON.parse(fs.readFileSync('bughunter-report.json', 'utf8'));
const codeQL = JSON.parse(fs.readFileSync('codeql-results.sarif', 'utf8'));

const merged = {
  version: '2.1.0',
  runs: [
    ...codeQL.runs,
    {
      tool: { name: 'Claude BugHunter' },
      results: bugHunter.findings.map((f: any) => ({
        ruleId: f.type,
        level: f.severity,
        message: { text: f.description },
        locations: [{ physicalLocation: { artifactLocation: { uri: f.file }, region: { startLine: f.line } } }],
        partialFingerprints: { suggestedFix: f.suggested_fix }
      }))
    }
  ]
};

fs.writeFileSync('merged.sarif', JSON.stringify(merged, null, 2));
```

You can then upload `merged.sarif` with the `github/codeql-action/upload-sarif` action. This approach gives you a single view in the *Security* tab while preserving the provenance of each finding.

## Managing false positives and feedback loops

No LLM is perfect. In my experience, about **15‑20 %** of BugHunter findings are either false positives or low‑impact suggestions. The key to keeping the pipeline usable is a feedback loop:

1. **Label** – Add a `bughunter-fp` label to PRs where you manually dismiss a finding.
2. **Store** – Write the dismissed finding IDs to a JSON file (`bughunter-ignore.json`) that lives in the repo.
3. **Filter** – Pass `--ignore @bughunter-ignore.json` to the CLI on subsequent runs.

A minimal ignore file looks like this:

```json
{
  "ignore": [
    {
      "file": "src/utils/logger.ts",
      "line": 12,
      "type": "hardcoded-secret"
    }
  ]
}
```

You can automate the update with a small GitHub Action that runs after a PR merge:

```yaml
- name: Update BugHunter ignore list
  if: github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged == true
  run: |
    node scripts/update-ignore.js
    git config user.name "github-actions[bot]"
    git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
    git add bughunter-ignore.json
    git commit -m "chore: add BugHunter false positives from #${{ github.event.pull_request.number }}"
    git push
```

The `update-ignore.js` script parses the SARIF report for findings that were marked as `dismissed` in the UI and appends them to the ignore file.

## Scaling the pipeline for monorepos

Monorepos introduce two challenges:

* **File‑count explosion** – Scanning every file on every commit is wasteful.
* **Package‑specific context** – A vulnerability in a Node package may be irrelevant to a Rust crate.

My strategy is to **scope** BugHunter per package using the `--files` flag combined with a `paths-filter` action:

```yaml
- uses: dorny/paths-filter@v3
  id: filter
  with:
    filters: |
      api:
        - 'packages/api/**'
      ui:
        - 'packages/ui/**'
      infra:
        - 'infra/**'
```

Then spin up a matrix job:

```yaml
bughunt:
  needs: test
  runs-on: ubuntu-latest
  strategy:
    matrix:
      package: ${{ fromJSON(steps.filter.outputs.matches) }}
  steps:
    - uses: actions/checkout@v4
    - name: Install Anthropic CLI
      run: npm i -g @anthropic-ai/sdk
    - name: Run BugHunter for ${{ matrix.package }}
      env:
        ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
      run: |
        # Gather files belonging to the current package
        git ls-files packages/${{ matrix.package }}/** > files.txt
        anthropic bughunter --files @files.txt --output report-${{ matrix.package }}.json
    - name: Upload per‑package report
      uses: actions/upload-artifact@v4
      with:
        name: bughunter-${{ matrix.package }}
        path: report-${{ matrix.package }}.json
```

This keeps each run under the 4096‑token limit and isolates findings to the relevant component, which is crucial for downstream owners.

## Observability and audit trails

Because LLM output is non‑deterministic, you need a solid audit trail:

* **Persist raw JSON** – Store the report as an artifact and also push it to an S3 bucket or internal artifact store.
* **Log request metadata** – The CLI prints `model`, `prompt_tokens`, and `completion_tokens`. Capture those logs in your CI system for cost tracking.
* **Version pin the model** – In the request payload you can specify `model: "claude-3-5-sonnet-20241022"`; this guarantees you’re always hitting the same snapshot unless you deliberately upgrade.

If you need a longer‑term view, consider feeding the JSON into a lightweight ElasticSearch index and building a dashboard that shows trends (e.g., “high‑severity findings per week”). This also helps you spot regressions when a new code change introduces a spike.

## Limitations and uncertainty

I’m honest about the blind spots:

* **No guarantee of zero‑day detection** – BugHunter can only reason about patterns it has seen during training. A brand‑new exploit that manipulates a language feature in an unexpected way will slip through.
* **Hallucinated line numbers** – Occasionally the model will reference a line that doesn’t exist in the submitted file. The CLI currently flags such entries with `"line": null`, but you must still verify manually.
* **Cost volatility** – Token pricing for Claude can change quarterly. I recommend budgeting a fixed monthly cap and using the `--max-tokens` flag conservatively.

> **Verification note**  
> The statements above about hallucinated line numbers and token pricing are based on observed behavior and public pricing pages from Anthropic. Exact percentages of false positives and cost figures are not officially published and may vary per organization.

## Conclusion
1. **Start small** – Add BugHunter as a separate job that runs after your existing tests. Treat the first few weeks as a data‑collection phase.
2. **Tune severity thresholds** – Use `--severity-threshold=medium` for early adopters; tighten to `high` once you’ve built confidence.
3. **Close the feedback loop** – Persist dismissed findings and feed them back into the ignore list. Over time the noise drops dramatically.
4. **Combine with traditional SAST** – Don’t replace CodeQL or SonarQube; let BugHunter surface the “soft” issues that rule‑based tools miss.
5. **Monitor cost and latency** – The CLI call adds ~5‑10 seconds per 100 files; for large monorepos batch the scans or run them on a schedule instead of every PR.

If you’re already using an LLM‑based code reviewer, you can reuse the same Anthropic API key and even the same prompt engineering patterns. For a deeper dive into scaling AI‑driven code reviews, see my post on [AI Agent Code Review: Patterns That Scale in Production](/blog/ai-agent-code-review-patterns/). And if you want a concrete example of mixing an LLM security scanner with OpenAI’s Codex Security CLI, check out the guide on [AI‑Powered Security Scanning for TypeScript](/blog/ai-powered-codex-security-typescript-ci/).

Integrating Claude’s BugHunter into CI/CD isn’t a plug‑and‑play affair, but the payoff is tangible: fewer security regressions slipping into production, faster developer onboarding (the model explains why a pattern is unsafe), and a single source of truth for “AI‑found” bugs. As LLMs keep improving, the line between “assistant” and “autonomous security auditor” will blur—today’s manual triage will become tomorrow’s automated gate. Until then, keep the human in the loop, log everything, and let the model do the heavy lifting where it excels.

The findings only pay off if the review process can act on them, and [AI agent code review](/blog/ai-agent-code-review-patterns/) covers that side. I wire these pipelines up as part of [AI engineering](/services/ai-engineering/) and [cloud and DevOps](/services/cloud-devops/) work. [OWASP's Top 10 for LLM Applications](https://genai.owasp.org/llmrisk/llm01-prompt-injection/) is the reference I check a scanner's coverage against. If you have a scanner producing more noise than signal, [send me a week of output](/contact/).

## Frequently asked questions

### Will an LLM find bugs a linter misses?

Sometimes. It is better at intent and data flow across files, and worse at being predictable. Run both, and expect the model to contribute a smaller number of findings that need more judgement.

### How do you keep false positives from killing adoption?

Report first, block later, and track which finding types were actually real. Turn off the categories that keep being wrong rather than asking reviewers to skip them by hand.

### What should never be sent to the model?

Secrets and anything you have not cleared for that provider. Decide the allowlist before the first run, and check that the tool respects it, because a scan that uploads a `.env` is worse than the bug it found.

### How much does this cost per pull request?

It scales with the diff you send, so scan the change rather than the repository. Measure a representative week before turning it on for every pull request.

---

HTML version: https://fullstackweb.dev/blog/automated-bug-hunting-with-claude-llm/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
