> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gourmand.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Automated Security Scanning with Snyk MCP and Gobi

> Set up an AI-powered security workflow that automatically scans your code, dependencies, infrastructure, and containers using natural language commands.

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

## Prerequisites

Before starting, ensure you have:

* Gobi account with **Hub access**
* Read: [Understanding Configs — How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs)
* Node.js 18+ installed locally
* [Snyk account](https://snyk.io/) (free tier works)
* A local project to scan for vulnerabilities

For all options, first:

<Steps>
  <Step title="Install Gobi CLI">
    ```bash theme={null}
    npm i -g @gourmanddev/cli
    ```
  </Step>

  <Step title="Add Your Project to Snyk">
    1. Sign up for a Snyk account at [snyk.io](https://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 theme={null}
       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 Gobi agent with Snyk MCP.
</Note>

<Warning>
  To use agents in headless mode, you need a [Gobi API key](https://hub.gourmand.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 theme={null}
        cn --config gourmand/snyk-continuous-ai
        ```

        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 theme={null}
         # 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 Gobi Hub">
        Go to the [Gobi Hub](https://hub.gourmand.dev) and [create a new agent](https://hub.gourmand.dev/new?type=agent).
      </Step>

      <Step title="Connect Snyk MCP via Gobi Hub">
        Visit the [Snyk MCP on Gobi Hub](https://hub.gourmand.dev/snyk/snyk-mcp) 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 Hub listing automatically configures the MCP command:

        ```bash theme={null}
        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 `~/.gobi/config.json` under the `mcpServers` section

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

        <Info>
          The MCP will request authentication and folder trust permissions when first used.
          This is handled automatically by the Gobi agent.
        </Info>
      </Step>

      <Step title="Add Secure-at-Inception Rules">
        Install the [Snyk Secure-at-Inception rules](https://hub.gourmand.dev/snyk/secure-at-inception) from the Hub 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 Gobi 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 theme={null}
        # 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:

  * **Gobi CLI Pro Plan** with the models add-on, OR
  * **Your own API keys** added to Gobi Hub 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 Gobi 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 [Gobi Hub](https://hub.gourmand.dev), click **Edit**, and add prompts under the **Prompts** section.
</Info>

<Info>
  **Where to run these workflows:**

  * **IDE Extensions**: Use Gobi 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](/guides/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](https://snyk.io/learn/application-security/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 theme={null}
  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](https://snyk.io/learn/software-composition-analysis-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 theme={null}
  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](https://snyk.io/learn/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 theme={null}
  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 theme={null}
  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 theme={null}
  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 theme={null}
  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:

* `GOBI_API_KEY`: Your Gobi API key from [hub.gourmand.dev/settings/api-keys](https://hub.gourmand.dev/settings/api-keys)
* `SNYK_TOKEN`: Your Snyk authentication token from [app.snyk.io/account](https://app.snyk.io/account)

### Create Workflow File

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

```yaml theme={null}
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 Gobi CLI
        run: |
          npm install -g @gourmanddev/cli
          echo "✅ Gobi 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.GOBI_API_KEY }}" ]; then
            echo "⚠️ Warning: GOBI_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:
          GOBI_API_KEY: ${{ secrets.GOBI_API_KEY }}
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        run: |
          echo "🤖 Generating AI-powered mitigation suggestions..."

          # Create a summary of findings for Gobi 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 Gobi 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 --config gourmand/snyk-continuous-ai -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 Gobi 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. **Gobi CLI access** - Available as an environment variable when Gobi 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 Gobi 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 Gobi's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.

<Note>
  **Coming Soon**: These security guardrail prompts will be available as pre-configured rules on the Gobi Hub for easy installation.
</Note>

<Card title="Pre-commit Scanning" icon="lock">
  ```bash theme={null}
  "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 theme={null}
  "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 theme={null}
  "Before building containers, scan base images and recommend
  security-hardened alternatives."
  ```
</Card>

<Card title="IaC Compliance" icon="clipboard-list">
  ```bash theme={null}
  "Scan all Terraform changes for compliance
  violations before applying infrastructure."
  ```
</Card>

<Tip>
  Enable the **Secure-at-Inception** rules from the Hub to automatically apply
  these guardrails to all code generation and modifications.
</Tip>

## Troubleshooting

### Authentication Issues

```bash theme={null}
"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 theme={null}
"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 [Gobi
  Hub](https://hub.gourmand.dev/snyk/snyk-mcp) - Secure-at-Inception rules are
  [enabled](https://hub.gourmand.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.gourmand.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](https://snyk.io/learn/application-security/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](https://snyk.io/learn/security-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="Gobi Hub" icon="plug" href="https://hub.gourmand.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>
