Generated banner for Gh Code Scanning
Generated logo for Gh Code Scanning

Gh Code Scanning

MicrosoftOfficialPublished by Microsoft

  • Skill
  • Tool integration
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

Retrieves and groups GitHub code scanning alerts by rule and severity using the gh CLI
— the description by Microsoft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The gh-code-scanning skill provides a structured way to interact with GitHub code scanning alerts, which are otherwise difficult to access via standard toolsets. By utilizing the gh CLI, this skill allows users to fetch, group, and analyze security alerts from static analysis tools like CodeQL and Scorecard. It provides scripts for both PowerShell and Bash environments, ensuring that security data can be consumed programmatically in a consistent JSON format for triage and reporting.

What it does

  • Retrieves open code scanning alerts from GitHub repositories.
  • Groups alerts by rule ID and severity for easier analysis.
  • Supports filtering by branch and severity levels.
  • Identifies dismissed alerts that are still detected in the codebase.
  • Provides detailed JSON output including affected file paths and alert URLs.
  • Includes guidance on creating deduplicated security issues based on scan results.

When to use it

  • When you need to perform security triage on a GitHub repository.
  • When you need to programmatically aggregate code scanning findings.
  • When you want to identify which files are most affected by specific security rules.
  • When you need to track dismissed alerts that have not been fully resolved.

Advantages

  • Standardizes security alert data into a machine-readable JSON format.
  • Simplifies the triage process by grouping alerts by rule and severity.
  • Provides cross-platform support via PowerShell and Bash scripts.
  • Enables automated reporting and issue creation workflows.

Usage examples

“Get a summary of all open code scanning alerts for the repository microsoft/hve-core.”
The agent executes the PowerShell script to return a JSON array of grouped alerts, sorted by occurrence count, which the agent then presents to the user.
“List all critical severity code scanning alerts for the main branch of my-org/my-repo.”
The agent uses the bash script with the -s critical flag to filter and return the relevant alerts in JSON format.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/microsoft/gh-code-scanning/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip gh-code-scanning.zip -d .agents/skills

Documentation by Microsoft

GitHub Code Scanning Skill

Overview

GitHub code scanning alerts are produced by static analysis tools such as CodeQL and Scorecard and surfaced in the GitHub Security tab. The GitHub Security tab is not accessible through the default MCP toolset, so this skill provides scripts for all read operations.

Prerequisites

RequirementDetails
pwshPowerShell 7+; install from https://learn.microsoft.com/powershell
gh CLIInstalled and on PATH; install from https://cli.github.com
AuthRun gh auth login or set GH_TOKEN; requires security_events scope
Scopesecurity_events for private repos; public_repo for public-only

The repo scope also satisfies security_events. The gh CLI handles authentication automatically; no explicit token passing is needed in commands.

Get-CodeScanningAlerts.ps1 validates both prerequisites at startup and aborts with a targeted error message if either check fails.

Quick Start

Run this command to get a grouped summary of open code scanning alerts, sorted by frequency. This is the recommended first command when triaging a repository's code scanning posture.

pwsh scripts/Get-CodeScanningAlerts.ps1 -Owner "{owner}" -Repo "{repo}" -OutputFormat Json

This returns a JSON array of alert groups sorted by occurrence count, descending. Always use -OutputFormat Json when consuming results programmatically.

Parameters Reference

ParameterTypeRequiredDefaultDescription
-OwnerStringYesGitHub organization or user that owns the repository
-RepoStringYesRepository name
-OutputFormatStringNoTableOutput format: agents must always use Json for programmatic consumption; GroupedJson is accepted as an alias for Json
-BranchStringNomainBranch to scope alert results
-IncludeDismissedStillDetectedSwitchNoAlso report dismissed alerts that are still detected on the branch, as groups with Kind set to dismissed-still-detected

These parameters apply to Get-CodeScanningAlerts.ps1. For bash script flags including -s {severity} and -d, see the Script Reference section below.

Script Reference

Get-CodeScanningAlerts.ps1

Groups and sorts open code scanning alerts by occurrence count, descending.

# JSON output for programmatic consumption
pwsh scripts/Get-CodeScanningAlerts.ps1 -Owner "{owner}" -Repo "{repo}" -OutputFormat Json

# Scope to a specific branch
pwsh scripts/Get-CodeScanningAlerts.ps1 -Owner "{owner}" -Repo "{repo}" -Branch "{branch}" -OutputFormat Json

# Also report dismissed alerts that are still detected
pwsh scripts/Get-CodeScanningAlerts.ps1 -Owner "{owner}" -Repo "{repo}" -OutputFormat Json -IncludeDismissedStillDetected
get-code-scanning-alerts.sh

Groups and sorts open code scanning alerts by occurrence count, descending. Requires jq.

# JSON output for programmatic consumption
bash scripts/get-code-scanning-alerts.sh -o "{owner}" -r "{repo}"

# Scope to a specific branch
bash scripts/get-code-scanning-alerts.sh -o "{owner}" -r "{repo}" -b "{branch}"

# Filter by severity
bash scripts/get-code-scanning-alerts.sh -o "{owner}" -r "{repo}" -s critical

# Also report dismissed alerts that are still detected
bash scripts/get-code-scanning-alerts.sh -o "{owner}" -r "{repo}" -d

When to Use This Skill

Use this skill when the task involves reading code scanning alerts only. Get-CodeScanningAlerts.ps1 is the only supported method for listing and grouping code scanning alerts. gh api must not be used as a fallback for listing or grouping.

When the GitHub MCP server is configured with the code_security toolset, read-only access to code scanning alerts is available without gh api. Enable via toolsets: all or explicit toolset configuration.

Code Scanning Alerts

List and group open alerts

Always run with -OutputFormat Json. Parse the JSON output and present it to the user.

pwsh scripts/Get-CodeScanningAlerts.ps1 -Owner "{owner}" -Repo "{repo}" -OutputFormat Json

Use -Branch {branch} to scope to a branch other than main.

JSON output shape

-OutputFormat Json returns an array of group objects:

[
  {
    "RuleDescription": "Empty except",
    "RuleId": "py/empty-except",
    "Tool": "CodeQL",
    "SecuritySeverity": null,
    "Severity": "warning",
    "Count": 23,
    "AffectedPaths": [
      "scripts/plugins/Sync-PluginManifest.ps1",
      "scripts/linting/Validate-MarkdownFrontmatter.py"
    ],
    "HasFilePaths": true,
    "AlertUrl": "https://github.com/microsoft/hve-core/security/code-scanning/42",
    "FindingDescription": "'except' clause does nothing but pass and there is no explanatory comment."
  },
  {
    "RuleDescription": "Code injection",
    "RuleId": "actions/code-injection/medium",
    "Tool": "CodeQL",
    "SecuritySeverity": "medium",
    "Severity": "error",
    "Count": 2,
    "AffectedPaths": [
      ".github/workflows/validate.yml"
    ],
    "HasFilePaths": true,
    "AlertUrl": "https://github.com/microsoft/hve-core/security/code-scanning/17",
    "FindingDescription": "Potential code injection in ${{ inputs.version }}, which may be controlled by an external user."
  },
  {
    "RuleDescription": "Branch-Protection",
    "RuleId": "BranchProtectionID",
    "Tool": "Scorecard",
    "SecuritySeverity": "high",
    "Severity": "error",
    "Count": 1,
    "AffectedPaths": [],
    "HasFilePaths": false,
    "AlertUrl": "https://github.com/microsoft/hve-core/security/code-scanning/1",
    "FindingDescription": "score is 9: branch protection is not maximal on development and all release branches"
  }
]

SecuritySeverity is null for code quality rules that have no security classification; Severity (the non-security rule severity: error, warning, note, none) provides a fallback. AffectedPaths is always a JSON array of unique, sorted file paths with sentinel strings filtered out. HasFilePaths is false and AffectedPaths is [] when an alert has no associated source file (for example, BranchProtectionID). AlertUrl links directly to the alert in the GitHub Security tab. FindingDescription is the most recent alert message text.

With -IncludeDismissedStillDetected (or -d in bash), dismissed alerts whose most recent instance on the branch is not fixed are appended as separate groups after the open-alert groups. Those groups add Kind (dismissed-still-detected) and DismissedReason; open-alert groups are unchanged. A dismissal does not resolve an alert, so present these as alerts to reopen and fix.

Get single alert detail

This call returns one record; it is not a listing or grouping operation and does not conflict with the gh api restriction above.

gh api repos/{owner}/{repo}/code-scanning/alerts/{alert_number}
List affected file paths

Use -OutputFormat Json and read the AffectedPaths field from each rule group. The JSON output includes RuleDescription, RuleId, Tool, SecuritySeverity, Severity, Count, AffectedPaths (unique, sorted file paths), HasFilePaths (boolean: false for repo-level rules that have no associated source file), AlertUrl (string: direct link to the alert in the GitHub Security tab), and FindingDescription (string: most recent alert message text from the analysis tool) per group.

Key fields

These are GitHub API response field paths, not output object properties. The grouped output object field names are listed in the JSON output shape section above.

  • rule.security_severity_level: security severity tier: critical, high, medium, or low; null for code quality rules

  • rule.severity: non-security rule severity: error, warning, note, or none; always populated

  • rule.id: rule identifier used for deduplication and cross-referencing

  • tool.name: analysis tool that produced the alert (for example, CodeQL)

  • most_recent_instance.location.path: source file path of the most recent alert occurrence

Resolution policy

Resolve alerts in code or configuration. Never dismiss an alert, and never suggest dismissing one, including for false positives or test code. When a finding cannot be fixed yet, a maintainer can add a reviewed, expiring tracked exception; the alert stays open. Repositories that adopt this policy document it in their code-scanning alert lifecycle; for hve-core, see https://github.com/microsoft/hve-core/blob/main/docs/security/code-scanning-alert-lifecycle.md.

Code Scanning Analyses

These calls retrieve analysis metadata, not alert listings, and do not conflict with the gh api restriction above.

List recent analyses

Returns the last 10 CodeQL runs on the main branch.

gh api repos/{owner}/{repo}/code-scanning/analyses \
  -f tool_name=CodeQL \
  -f ref=refs/heads/main \
  -f per_page=10
Key fields
  • created_at: timestamp of the analysis run

  • results_count: number of alerts produced

  • rules_count: number of rules evaluated

  • tool.version: version of the analysis tool

  • warning / error: any issues reported during analysis

Backlog Issue Creation

Dedup check before creation

Search for an existing issue using the title and an embedded automation marker before creating a new one.

existing=$(gh issue list --repo "{owner}/{repo}" \
  --search "\"[Security] {rule_description}\" in:title" \
  --state open --json number --jq '.[0].number // empty')
if [[ -z "$existing" ]]; then
  gh issue create --repo "{owner}/{repo}" \
    --title "[Security] {rule_description}" \
    --label "security" \
    --body "<!-- automation:security-scan:{rule_id} -->
## Code Scanning Alert: {rule_description}

**Rule:** \`{rule_id}\`
$([ -n "{severity}" ] && echo "**Severity:** {severity}")
**Tool:** {tool}
**Affected files:** {count} occurrences

### Affected paths
{affected_paths}
"
fi

The automation marker <!-- automation:security-scan:{rule_id} --> is embedded in the issue body and serves as the deduplication anchor. Replace all {placeholders} with actual values from the alert-grouping JSON output.

Troubleshooting

SymptomLikely causeFix
gh CLI not found. Install it from https://cli.github.comgh CLI not on PATHInstall from https://cli.github.com, then re-open your terminal
gh CLI is not authenticated. Run 'gh auth login'gh auth not completedRun gh auth login; ensure security_events scope is granted
HTTP 403 Resource not accessible by integrationMissing security_events scope on tokenRe-authenticate: gh auth refresh -s security_events or set GH_TOKEN with appropriate scope
Empty results []Wrong ref format or no alerts on that branchOmit -f ref= to search all branches, or use refs/heads/main format (not just main)
bash: jq: command not foundjq not installedInstall via brew install jq (macOS), apt-get install jq (Debian/Ubuntu), or from https://jqlang.github.io/jq/

Files

SECURITY.md


title: GH Code Scanning Skill Security Model description: STRIDE threat model for the gh-code-scanning skill organized by assets, adversaries, and trust buckets (CLI to gh/GitHub API subprocess, untrusted alert-data rendering, CLI caller process and credentials) with in-code mitigations and acknowledged enterprise readiness gaps author: microsoft/hve-core ms.date: 2026-10-02 ms.topic: reference estimated_reading_time: 8 keywords:

  • security

  • STRIDE

  • gh-code-scanning

  • github

  • threat model


<!-- markdownlint-disable-file -->

GH Code Scanning Skill Security Model

This document records the STRIDE threat model for the gh-code-scanning skill (scripts/Get-CodeScanningAlerts.ps1 and scripts/get-code-scanning-alerts.sh, the PowerShell and POSIX twins). The model is organized by trust bucket: CLI → gh/GitHub API subprocess (B1), Untrusted alert-data rendering (B2), and CLI caller process and credentials (B3). Each bucket enumerates all six STRIDE categories with the in-code mitigations that address them. Assets and adversaries are enumerated first. Acknowledged enterprise readiness gaps are listed at the end.

The skill reads open GitHub code-scanning alerts for a repository and branch through the gh CLI, groups them by rule, and prints a table or JSON. With the opt-in -IncludeDismissedStillDetected (-d in bash) option it makes one more read-only GET on the same endpoint with state=dismissed, keeps alerts whose branch instance is not fixed, and adds their dismissed_reason enum value to the output; the dismissal comment is not read or rendered. It handles no credential directly (gh owns the token), opens no local listener, and writes no files: output goes to stdout only.

See also: repo-wide STRIDE model. This skill participates in the repository-wide threat model at docs/security/security-model.md and is registered in its Skill Security Models section.

Executive Summary

The gh-code-scanning skill is a read-only reporting wrapper over gh api. Its highest-risk behavior is rendering untrusted alert data returned by the GitHub API to the operator's terminal or a JSON consumer. Every caller-supplied argument (Owner, Repo, Branch, output format, severity) is validated against a strict allow-list before it is interpolated into the gh api endpoint, closing argument- and query-injection vectors; alert fields are emitted as data (Format-Table, ConvertTo-Json, jq), never executed. Credentials are delegated entirely to gh and never touched by the script. Residual risk concentrates in the unpinned gh/jq PATH dependencies and TLS trust delegated to gh.

Security Posture Overview
DimensionValue
Runtime surfaceLocal CLI (PowerShell + bash); gh CLI subprocess; stdout only; no listener, no writes
Trust bucketsB1 CLI→gh/GitHub API, B2 untrusted alert-data rendering, B3 caller process/credentials
CredentialsNone handled in-script; gh owns the token (keyring or GH_TOKEN), security_events scope
Network egressHTTPS to the GitHub REST API via gh (read-only GET)
Open residual gaps3 (SupplyChain-Med: unpinned gh/jq PATH dependencies)

Contents

  • System Description

  • Trust Boundaries

  • Assets

  • Adversaries

  • Bucket B1: CLI → gh/GitHub API subprocess

  • Bucket B2: Untrusted alert-data rendering

  • Bucket B3: CLI caller process and credentials

  • Enterprise Readiness Gaps

  • References

System Description

Components
  1. scripts/Get-CodeScanningAlerts.ps1 — PowerShell twin: validates parameters via [ValidatePattern]/[ValidateSet], calls gh api, groups alerts by rule, and prints a table or JSON.

  2. scripts/get-code-scanning-alerts.sh — POSIX/bash twin with the same behavior, validating arguments with regex guards and grouping via jq.

Data Flow
flowchart TD
    subgraph HOST["Operator Workstation / Runner (trust zone)"]
        CLI["Get-CodeScanningAlerts.ps1 / .sh"]
        GHAUTH["gh auth token store<br/>(keyring / GH_TOKEN)"]
        OUT["Grouped alert output<br/>(table / JSON)"]
    end
    subgraph GH["GitHub REST API (network boundary)"]
        API["code-scanning/alerts endpoint"]
    end
    CLI -->|"validated args"| GHSUB["gh CLI subprocess"]
    GHSUB -->|"reads token"| GHAUTH
    GHSUB -->|"GET (HTTPS/TLS)"| API
    API -->|"alert JSON (untrusted data)"| GHSUB
    GHSUB -->|"stdout"| CLI
    CLI -->|"renders as data"| OUT

Trust Boundaries

Boundary Diagram
┌───────────────────────────────────────────────────────────┐
│ TRUST BOUNDARY: Operator Workstation / Runner             │
│  ┌─────────────┐   ┌──────────────┐   ┌────────────────┐  │
│  │ CodeScanning│   │ gh token     │   │ stdout report  │  │
│  │ CLI twins   │   │ (keyring/env)│   │ (table/JSON)   │  │
│  └─────────────┘   └──────────────┘   └────────────────┘  │
└───────────────────────────┬───────────────────────────────┘
                            │ TLS (via gh)
        ┌────────────────────▼────────────────────┐
        │ TRUST BOUNDARY: GitHub REST API          │
        │  ┌────────────────────────────────────┐  │
        │  │ code-scanning/alerts (read-only)   │  │
        │  └────────────────────────────────────┘  │
        └──────────────────────────────────────────┘
Boundary Descriptions
BoundaryAssets ProtectedControls Enforced
Workstation / Runnergh token, output integrityStrict argument allow-lists; no in-script token handling; stdout-only
GitHub REST APIRequest integrity, tokenTLS + auth delegated to gh; read-only GET; endpoint built from validated inputs

Assets

IdAssetLifetimeNotes
A1GitHub auth tokenManaged by ghNever read by the script; gh sources it from its keyring or GH_TOKEN; security_events scope
A2Owner / Repo / Branch argumentsCommand lifetimeCaller-supplied; strictly validated before interpolation into the endpoint
A3Alert data (descriptions, paths, URLs)Command lifetimeReturned by the GitHub API; rendered as data, never executed
A4gh / jq binariesExternal, PATH-resolvedUnpinned host dependencies (see G-SUP-1)

Adversaries

IdAdversaryIn-scope mitigations
ADV-aCaller supplying adversarial Owner/Repo/Branch/severityAllow-list validation (^[a-zA-Z0-9._-]+$ / ^[a-zA-Z0-9._/-]+$, [ValidateSet], severity enum) blocks argument and query injection into gh api
ADV-bMalicious content in alert fields (crafted rule text, path, URL)Alert fields are emitted as data (Format-Table, ConvertTo-Json, jq); never evaluated or executed
ADV-cNetwork attacker on the CLI ↔ GitHub channelTLS and certificate validation delegated to gh; no plaintext fallback

Bucket B1: CLI → gh/GitHub API subprocess

Spoofing
  • Authentication and endpoint identity are delegated to gh, which validates the GitHub API's TLS certificate. The script constructs the endpoint from a fixed template with validated path segments.

Tampering
  • All caller inputs are validated before use: Owner and Repo against ^[a-zA-Z0-9._-]+$, Branch against ^[a-zA-Z0-9._/-]+$, OutputFormat against a [ValidateSet], and severity against a fixed enum. Because &, ?, and whitespace are excluded, a caller cannot inject additional query parameters or alter the REST path.

  • The Branch value is confined to the ref=refs/heads/... query-string segment; its allow-list still permits . and / (including ..), recorded as G-TAM-1.

Repudiation
  • Not applicable. This is a read-only reporting tool with no state change to attribute.

Information Disclosure
  • No secret is handled in-script; the token lives only inside gh. GH_PAGER is cleared to keep output non-interactive.

Denial of Service
  • The query caps page size (per_page=100) and uses gh --paginate; runtime is bounded by the number of open alerts. No unbounded local loops.

Elevation of Privilege
  • The subprocess runs with the caller's privileges; access is limited to whatever the gh token already grants. The script requests no additional scope.

Risk Rating
ThreatLikelihoodImpactResidual RiskStatus
Argument/query injection into gh apiLowMedLowMitigated (allow-list validation)
Branch allow-list permits ./..//LowLowLowAccepted (confined to query value; G-TAM-1)

Bucket B2: Untrusted alert-data rendering

Spoofing
  • Not applicable. Alert content carries no identity claim; it is treated as data.

Tampering
  • The script does not modify alert data; it groups and sorts it for display.

Repudiation
  • Not applicable.

Information Disclosure
  • Alert descriptions, affected paths, and URLs originate from the operator's own repository scanning and are printed to the operator's terminal or a JSON consumer. They are rendered as data; downstream consumers are responsible for their own safe handling.

Denial of Service
  • Grouping is proportional to the number of alerts returned; there is no amplification.

Elevation of Privilege
  • Rendered fields are never interpreted as code or commands, so hostile alert content cannot drive execution.

Risk Rating
ThreatLikelihoodImpactResidual RiskStatus
Hostile alert field rendered downstreamLowLowLowMitigated (emitted as data only)

Bucket B3: CLI caller process and credentials

Spoofing
  • Not applicable. No local identity surface.

Tampering
  • The script writes no files; output is stdout only, so there is no on-disk artifact to tamper with.

Repudiation
  • Not applicable. Local read-only tool.

Information Disclosure
  • The token is never read, logged, or echoed by the script; it stays inside gh. Only grouped alert data reaches stdout.

Denial of Service
  • No local resource is consumed beyond the bounded gh call and in-memory grouping.

Elevation of Privilege
  • Runs entirely with the caller's privileges; no elevation and no setuid behavior.

Risk Rating
ThreatLikelihoodImpactResidual RiskStatus
Token leakage via script handlingLowHighLowMitigated (token owned by gh, never touched)

Enterprise Readiness Gaps

The following are known limitations recorded so operators can make informed deployment decisions. Severity ratings are the project's own assessment and are not equivalent to a CVSS score.

IdGapSeverityStatus
G-SUP-1gh and jq are external, unpinned dependencies resolved from PATH; the skill inherits their integrity and CVE posture.SupplyChain-MedAccepted (operator keeps gh/jq patched)
G-TLS-1No certificate pinning for the GitHub API; TLS validation is delegated to gh and the system trust store.InfoDisc-LowAccepted (operator-acceptable for a managed GitHub endpoint)
G-TAM-1The Branch allow-list permits ., .., and /; the value is confined to the ref= query segment (so it cannot inject query parameters or traverse the REST path) but is not canonicalized.Tampering-LowAccepted (defence-in-depth)

For an active issue tracker entry covering these gaps, see the hve-core issues list.

References

🤖 Crafted with precision by ✨Copilot following brilliant human instruction, then carefully refined by our team of discerning human reviewers.

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs a command-line tool

The author says: Requires pwsh 7+ and gh CLI authenticated with the security_events scope. Bash script requires jq.

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Microsoft
Publisher
Microsoft (Official)
Source
microsoft/hve-core · .github/skills/security/gh-code-scanning · commit f425e94
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Microsoft.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download gh-code-scanning.zip