Back to Continue

Automated Security Scanning with Snyk MCP and Continue

docs/guides/snyk-mcp-continue-cookbook.mdx

1.5.4525.9 KB
Original Source

import { OSAutoDetect } from '/snippets/OSAutoDetect.jsx' import CLIInstall from '/snippets/cli-install.mdx'

<OSAutoDetect /> <Note>

🚀 New: Snyk Mission Control Integration with Continuous AI

The new Snyk Mission Control Integration enables Continuous AI - where AI agents autonomously detect, analyze, and fix vulnerabilities. When Snyk detects an issue, your agent automatically generates a fix, creates a PR, and validates the solution without manual intervention.

Mission Control Benefits:

  • One-click OAuth - No tokens, no configuration files, just connect and go
  • Centralized workflows - Manage all security Tasks and automations from one dashboard
  • Webhook triggers - Automatically respond to new vulnerabilities as they're discovered
  • Metrics & intervention rates - Track how often agents successfully fix issues without human help

This represents Level 2 Continuous AI: AI handles routine security work autonomously while developers focus on complex problems. As outlined in our Continuous AI guide, this reduces intervention rates and accelerates secure development.

Get Started: Use this cookbook to understand the fundamentals, then enable Mission Control to deploy autonomous security agents across your organization.

</Note> <Card title="What You'll Build" icon="shield-halved"> An automated security scanning system that uses Continue's AI agent with Snyk MCP to identify vulnerabilities in code, dependencies, infrastructure, and containers - all through simple natural language prompts </Card>

Demo Video

<iframe width="100%" height="400" src="https://www.youtube.com/embed/cwVnKOf3tVg" title="Snyk MCP Continue Cookbook Demo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen ></iframe>

Prerequisites

Before starting, ensure you have:

For all options, first: <Steps> <Step title="Install Continue CLI"> <CLIInstall /> </Step>

<Step title="Add Your Project to Snyk">
  1. Sign up for a Snyk account at snyk.io
  2. Create a new project in Snyk by importing your code repository (Git provider or manual upload)
  3. Install and authenticate the Snyk CLI locally:
    bash
    npm install -g snyk
    snyk auth
    
    This will open your browser to authenticate with your Snyk account. </Step>
</Steps> <Note> **Important**: The Snyk MCP requires the Snyk CLI to be authenticated locally. Run `snyk auth` to authenticate before using the Continue agent with Snyk MCP. </Note> <Warning> To use agents in headless mode, you need a [Continue API key](https://continue.dev/settings/api-keys). </Warning>

Snyk Continuous AI Workflow Options

<Card title="🚀 Fastest Path to Success" icon="zap"> Skip the manual setup and use our pre-built Snyk Continuous AI agent that includes the Snyk MCP and optimized security scanning workflows for more consistent results. </Card>

After ensuring you meet the Prerequisites above, you have two paths to get started:

<Tabs> <Tab title="⚡ Quick Start (Recommended)"> <Steps> <Step title="Load the Pre-Built Agent"> Navigate to your project directory and run: ```bash cn --agent continuedev/snyk-continuous-ai-agent ```
    This agent includes:
    - **Snyk MCP** pre-configured and ready to use
    - **Security-focused rules** for best practices
  </Step>

  <Step title="Run Your First Security Scan">
    From your project directory, start with a comprehensive security scan:
    ```bash
     # Headless mode
    cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." --auto
    ```

    That's it! The agent handles everything automatically.
  </Step>
</Steps>

<Info>
  **Why Use the Agent?** The pre-built agent provides consistent security scanning workflows and handles MCP configuration automatically, making it easier to get started with AI-powered security scanning.
</Info>
</Tab> <Tab title="🛠️ Manual Setup"> <Steps> <Step title="Create a New Agent via the Continue Mission Control"> Go to the [Continue Mission Control](https://continue.dev) and [create a new agent](https://continue.dev/agents/new). </Step> <Step title="Connect Snyk MCP via Continue Mission Control"> Visit the [Snyk Continuous AI Agent](https://continue.dev/continuedev/snyk-continuous-ai-agent) and click **Install** to add it to the agent you created in the step above.
This will add Snyk MCP to your agent's available tools. The Mission Control listing automatically configures the MCP command:
```bash
npx -y snyk@latest mcp -t stdio
```

<Tip>
  **Alternative installation methods:**
  1. **Quick CLI install**: `cn --mcp snyk/snyk-mcp`
  2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section

  Once installed, Snyk MCP tools become available to your Continue agent for all prompts.
</Tip>

<Info>
  The MCP will request authentication and folder trust permissions when first used.
  This is handled automatically by the Continue agent.
</Info>
</Step> <Step title="Add Secure-at-Inception Rules"> Install the [Snyk Secure-at-Inception rules](https://continue.dev/snyk/secure-at-inception) from Mission Control to enable automatic security scanning.
**How to add rules to your agent:**
1. Visit the rules link above and click **Install**
2. The rules will be added to your agent configuration automatically
3. Rules apply globally to all your Continue sessions

These rules configure your agent to:
- **Run [SAST](https://snyk.io/learn/application-security/sast/) scans** on newly generated or modified code
- **Check dependencies** when adding or updating packages
- **Auto-fix issues** using Snyk's recommendations, then rescan
</Step> <Step title="Run Your First Security Scan"> Start with a comprehensive security scan: ```bash # TUI mode cn "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." ``` </Step> </Steps> </Tab> </Tabs> <Accordion title="Agent Requirements"> To use the pre-built agent, you need either: - **Continue CLI Pro Plan** with the models add-on, OR - **Your own API keys** added to Continue Mission Control secrets (same as manual setup)
The agent will automatically detect and use your configuration along with the pre-configured Snyk MCP for security scanning operations.
</Accordion>

Security Scanning Recipes

Now you can use natural language prompts to run comprehensive security scans. The Continue agent automatically calls the appropriate Snyk MCP tools.

<Info> You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Mission Control](https://continue.dev), click **Edit**, and add prompts under the **Prompts** section. </Info> <Info> **Where to run these workflows:** - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for headless commands

Test in Plan Mode First: Before running security scans that might make changes, test your prompts in plan mode (see the Plan Mode Guide; press Shift+Tab to switch modes in TUI/IDE). This shows you what the agent will do without executing it. For example: "Run a Snyk Code scan and fix the top 3 issues" </Info>

Code Vulnerability Scanning (SAST)

<Card title="Static Application Security Testing" icon="code"> Scan your source code for security vulnerabilities and code quality issues.

TUI Mode Prompt:

Run a Snyk Code scan on this repo with severity threshold medium.
Summarize issues with file:line. Propose minimal diffs for the top 3
and rerun to verify.

Headless Mode Prompt:

bash
cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify." --auto
</Card>

Dependency Scanning (SCA)

<Card title="Software Composition Analysis" icon="cube"> Check open source dependencies for known vulnerabilities.

TUI Mode Prompt:

Run Snyk Open Source on this repo (include dev deps).
Summarize vulnerable paths and propose a minimal-risk upgrade plan.
Re-test after the plan (dry run).

Headless Mode Prompt:

bash
cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)." --auto
</Card>

Infrastructure as Code (IaC)

<Card title="IaC Security" icon="cloud"> Scan Terraform, CloudFormation, and Kubernetes configs for misconfigurations.

TUI Mode Prompt:

Scan ./infra with Snyk IaC. Report high/critical misconfigs
with exact files/lines. Provide code changes and re-scan to confirm.

Headless Mode Prompt:

bash
cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm." --auto
</Card>

Container Scanning

<Card title="Container Security" icon="docker"> Analyze Docker images for vulnerabilities in base images and packages.

TUI Mode Prompt:

Scan image my-api:latest. Exclude base image vulns.
Print dependency tree. Recommend a safer base image or upgrades.
Re-test after the change (dry run).

Headless Mode Prompt:

bash
cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)." --auto
</Card>

Pull Request Scanning

<Card title="Changed Files Only" icon="code-branch"> Focus scanning on modified files to catch issues before merging.

TUI Mode Prompt:

Scan only files changed since origin/main with Snyk Code.
Block if new high issues would be introduced. Show deltas.

Headless Mode Prompt:

bash
cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas." --auto
</Card>

Security Learning

<Card title="Snyk Learn Integration" icon="graduation-cap"> Access security education resources based on identified vulnerabilities ([CWE](https://cwe.mitre.org/)).

TUI Mode Prompt:

Open Snyk Learn lessons related to the top CWE(s) from this scan.

Headless Mode Prompt:

bash
cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." --auto
</Card>

Continuous Security with GitHub Actions

This example demonstrates a Continuous AI workflow where security scanning runs automatically on pull requests, generates AI-powered mitigation suggestions, and posts them as PR comments.

<Info>

About the --auto flag: The --auto flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like security scanning, vulnerability analysis, and fix validation.

</Info>

Add GitHub Secrets

Navigate to Repository Settings → Secrets and variables → Actions and add:

Create Workflow File

Create .github/workflows/snyk-security.yml in your repository:

yaml
name: Snyk Security Scanning

on:
  pull_request:
    branches: [main]

jobs:
  security-scan:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Fetch all history for git diff

      - name: Get Changed Files
        id: changed-files
        run: |
          echo "📝 Getting changed files since main branch..."
          CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ')
          echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT
          echo "Changed files: $CHANGED_FILES"

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install Snyk CLI
        run: |
          npm install -g snyk
          echo "✅ Snyk CLI installed"

      - name: Install Continue CLI
        run: |
          npm install -g @continuedev/cli
          echo "✅ Continue CLI installed"

      - name: Validate Secrets
        run: |
          if [ -z "${{ secrets.SNYK_TOKEN }}" ]; then
            echo "❌ Error: SNYK_TOKEN secret is not set"
            exit 1
          fi
          if [ -z "${{ secrets.CONTINUE_API_KEY }}" ]; then
            echo "⚠️ Warning: CONTINUE_API_KEY not set - AI mitigation suggestions will be skipped"
          fi
          echo "✅ Required secrets validated"

      - name: Authenticate Snyk
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        run: |
          snyk auth "$SNYK_TOKEN"
          echo "✅ Snyk authenticated"

      - name: Run Security Scans
        id: security-scan
        continue-on-error: true
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
          CHANGED_FILES: ${{ steps.changed-files.outputs.changed_files }}
        run: |
          SCAN_FAILED=0

          if [ -n "$CHANGED_FILES" ]; then
            echo "🔍 Running targeted scan on changed files..."
            echo "Changed files: $CHANGED_FILES"
            FILE_ARGS=""
            for file in $CHANGED_FILES; do
              if [[ "$file" =~ \.(js|jsx|ts|tsx|py|java|go|rb)$ ]]; then
                FILE_ARGS="$FILE_ARGS --file=$file"
              fi
            done

            if [ -n "$FILE_ARGS" ]; then
              echo "🔍 Running Snyk Code scan on changed files..."
              snyk code test $FILE_ARGS --severity-threshold=high --json > snyk-code-results.json || {
                echo "❌ Snyk Code found high severity issues in changed files"
                SCAN_FAILED=1
              }
            else
              echo "⚠️ No scannable code files changed, skipping Snyk Code scan"
              echo '{"runs": [{"results": []}]}' > snyk-code-results.json
            fi
          else
            echo "⚠️ No changed files detected, creating empty results"
            echo '{"runs": [{"results": []}]}' > snyk-code-results.json
          fi

          echo "📦 Checking dependencies..."
          snyk test --severity-threshold=high --json > snyk-oss-results.json || {
            echo "❌ Snyk Open Source found high severity issues"
            SCAN_FAILED=1
          }

          if [ $SCAN_FAILED -eq 1 ]; then
            echo "scan_status=failed" >> $GITHUB_OUTPUT
            echo "⚠️ Scans completed with issues - continuing to generate mitigation suggestions"
          else
            echo "scan_status=passed" >> $GITHUB_OUTPUT
            echo "✅ All security scans passed"
          fi

      - name: Generate AI Mitigation Suggestions
        if: always() && steps.security-scan.outputs.scan_status == 'failed'
        continue-on-error: true
        env:
          CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        run: |
          echo "🤖 Generating AI-powered mitigation suggestions..."

          # Create a summary of findings for Continue CLI
          FINDINGS_SUMMARY=$(cat snyk-code-results.json snyk-oss-results.json | jq -r '
            if .runs then
              .runs[0].results[] | "Code Issue: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri) (Severity: \(.level))"
            elif .vulnerabilities then
              .vulnerabilities[] | "Dependency Issue: \(.title) in \(.packageName)@\(.version) (Severity: \(.severity))"
            else
              empty
            end
          ' | head -20)

          if [ -n "$FINDINGS_SUMMARY" ]; then
            echo "📋 Security findings to analyze:"
            echo "$FINDINGS_SUMMARY"
            echo ""

            # Use Continue CLI to generate mitigation suggestions
            PROMPT="Analyze these Snyk security findings and provide specific, actionable mitigation steps for each issue. Focus on: 1) Root cause, 2) Immediate fix, 3) Long-term prevention. Findings: $FINDINGS_SUMMARY. Provide clear, prioritized recommendations."

            cn --agent continuedev/snyk-continuous-ai-agent -p "$PROMPT" --auto > mitigation-suggestions.md || {
              echo "⚠️ Warning: Could not generate AI suggestions"
              exit 0
            }

            if [ -f mitigation-suggestions.md ]; then
              echo "✅ AI mitigation suggestions generated"
              echo ""
              echo "--- Mitigation Suggestions ---"
              cat mitigation-suggestions.md
            fi
          else
            echo "⚠️ No findings to analyze"
          fi

      - name: Post Mitigation Summary to PR
        if: steps.security-scan.outputs.scan_status == 'failed' && hashFiles('mitigation-suggestions.md') != ''
        continue-on-error: true
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          if [ -f mitigation-suggestions.md ]; then
            echo "💬 Posting mitigation summary to PR..."

            # Create PR comment with mitigation suggestions
            cat > pr-comment.md <<'EOF'
          ## 🛡️ Snyk Mitigation Summary

          Snyk has identified security issues in this PR. Here are AI-generated mitigation recommendations:

          EOF

            cat mitigation-suggestions.md >> pr-comment.md

            cat >> pr-comment.md <<EOF

          ---
          **Scan Details:**
          - 📊 Full report available in workflow artifacts
          - 🔍 Review the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for complete details
          - 🤖 Generated with Continue CLI + Snyk

          _This is an automated security analysis. Please review and address the findings before merging._
          EOF

            gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md

            echo "✅ Mitigation summary posted to PR"
          else
            echo "⚠️ No mitigation suggestions file found"
          fi

      - name: Generate Security Report
        if: always()
        continue-on-error: true
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        run: |
          echo "📊 Generating security report..."
          {
            echo "# Security Scan Report"
            echo ""
            echo "**Date:** $(date -u +"%Y-%m-%d %H:%M:%S UTC")"
            echo "**Branch:** ${{ github.ref_name }}"
            echo "**Commit:** ${{ github.sha }}"
            echo "**Status:** ${{ steps.security-scan.outputs.scan_status }}"
            echo ""

            echo "## Snyk Code Scan Results"
            if [ -f snyk-code-results.json ]; then
              jq -r '.runs[0].results[] | "- **\(.level | ascii_upcase)**: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri)"' snyk-code-results.json || echo "No code issues found"
            else
              echo "No scan results available"
            fi
            echo ""

            echo "## Snyk Open Source Scan Results"
            if [ -f snyk-oss-results.json ]; then
              jq -r '.vulnerabilities[] | "- **\(.severity | ascii_upcase)**: \(.title) (\(.packageName)@\(.version))"' snyk-oss-results.json || echo "No dependency issues found"
            else
              echo "No scan results available"
            fi
            echo ""

            if [ -f mitigation-suggestions.md ]; then
              echo "## AI-Powered Mitigation Suggestions"
              echo ""
              cat mitigation-suggestions.md
            fi
          } > scan-results.md

          if [ -f scan-results.md ]; then
            echo "✅ Security report generated successfully"
            cat scan-results.md
          else
            echo "⚠️ Warning: scan-results.md was not created"
          fi

      - name: Upload Security Report
        if: always()
        continue-on-error: true
        uses: actions/upload-artifact@v4
        with:
          name: security-scan-results
          path: |
            scan-results.md
            snyk-code-results.json
            snyk-oss-results.json
            mitigation-suggestions.md
          if-no-files-found: warn

      - name: Fail if Security Issues Found
        if: steps.security-scan.outputs.scan_status == 'failed'
        run: |
          echo "❌ Security scan failed - high severity issues found"
          echo "📋 Review the security report artifact for details and mitigation suggestions"
          exit 1
<Info> **About SNYK_TOKEN**: The workflow uses the SNYK_TOKEN in two ways: 1. **Direct Snyk CLI authentication** - Authenticates the Snyk CLI for running scans 2. **Continue CLI access** - Available as an environment variable when Continue generates AI mitigation suggestions

The cn agent automatically uses the SNYK_TOKEN when needed for Snyk MCP operations. </Info>

<Info> This workflow demonstrates several advanced features: - **Changed Files Detection**: Only scans files modified in the PR - **AI Mitigation**: Uses Continue CLI to generate actionable mitigation steps - **PR Comments**: Automatically posts mitigation suggestions as PR comments - **Comprehensive Reporting**: Generates detailed security reports with artifacts </Info>

Security Guardrails

Implement automated security policies using Continue's rule system. See the Rules deep dive for authoring tips.

<Note> **Coming Soon**: These security guardrail prompts will be available as pre-configured rules on the Continue Mission Control for easy installation. </Note> <Card title="Pre-commit Scanning" icon="lock"> ```bash "Always run Snyk Code before committing newly generated code; refuse to proceed if high issues remain." ``` </Card> <Card title="Dependency Safety" icon="shield-check"> ```bash "When adding/updating a dependency, run Snyk Open Source, choose the lowest-risk upgrade, and re-test." ``` </Card> <Card title="Container Hardening" icon="box"> ```bash "Before building containers, scan base images and recommend security-hardened alternatives." ``` </Card> <Card title="IaC Compliance" icon="clipboard-list"> ```bash "Scan all Terraform changes for compliance violations before applying infrastructure." ``` </Card> <Tip> Enable the **Secure-at-Inception** rules from Mission Control to automatically apply these guardrails to all code generation and modifications. </Tip>

Troubleshooting

Authentication Issues

bash
"Check Snyk auth status and current org. If not authenticated,
help me authenticate. Then run a quick Code scan on ./
with severity medium and print one example issue."

Fix Validation

bash
"Propose minimal diffs only in affected files,
then rerun the same Snyk scan to confirm resolution."

Connection Problems

<Check> **Verification Steps:** - Snyk MCP is installed via [Continue Hub](https://continue.dev/snyk/snyk-mcp) - Secure-at-Inception rules are [enabled](https://continue.dev/snyk/secure-at-inception) - Authentication completed successfully - Project folder has been trusted </Check>

What You've Built

After completing this guide, you have a complete AI-powered security system that:

  • ✅ Uses natural language — Simple prompts instead of complex CLI commands
  • ✅ Fixes automatically — AI suggests and validates security fixes
  • ✅ Runs continuously — Automated scanning in CI/CD pipelines
  • ✅ Enforces guardrails — Security rules prevent vulnerable code from shipping
<Card title="Continuous AI" icon="rocket"> Your security workflow now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine security scanning and remediation with human oversight through review and approval of fixes. </Card>

Next Steps

  1. Run your first scan - Try the SAST prompt on your current project
  2. Review findings - Analyze the security report and implement fixes
  3. Set up CI pipeline - Add the GitHub Actions workflow to your repo
  4. Customize rules - Add project-specific security policies
  5. Monitor trends - Track vulnerability reduction over time

Additional Resources

<CardGroup cols={2}> <Card title="Snyk Documentation" icon="book" href="https://docs.snyk.io"> Complete Snyk platform documentation </Card> <Card title="Continue Mission Control" icon="plug" href="https://continue.dev"> Explore more MCP integrations and agents </Card> <Card title="Security Best Practices" icon="shield" href="https://snyk.io/learn" > Learn about secure coding practices </Card> <Card title="MCP Concepts" icon="puzzle-piece" href="https://docs.snyk.io/integrations/developer-guardrails-for-agentic-workflows" > Understanding MCP architecture </Card> </CardGroup>