gh-code-scanning

Récupère et regroupe les alertes de scan de code GitHub par règle et sévérité en utilisant l'interface en ligne de commande gh - Proposé par microsoft/hve-core

npx skills add https://github.com/microsoft/hve-core --skill gh-code-scanning

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

These parameters apply to Get-CodeScanningAlerts.ps1. For bash script flags including -s {severity}, 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

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

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.

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

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/

Plus de skills de microsoft

oss-growth
microsoft
Persona de growth hacker OSS
agent-framework-azure-ai-py
microsoft
Créez des agents Azure AI Foundry à l’aide du SDK Python Microsoft Agent Framework (agent-framework-azure-ai). À utiliser lors de la création d’agents persistants avec AzureAIAgentsProvider, de l’utilisation d’outils hébergés (interpréteur de code, recherche de fichiers, recherche web), de l’intégration de serveurs MCP, de la gestion de fils de conversation ou de l’implémentation de réponses en streaming. Couvre les outils de fonction, les sorties structurées et les agents multi-outils.
development
airunway-aks-setup
microsoft
Configurez AI Runway sur AKS — du cluster nu au modèle en cours d'exécution. Couvre la vérification du cluster, l'installation du contrôleur, l'évaluation GPU, la configuration du fournisseur et le premier déploiement. QUAND : « configurer AI Runway », « intégrer un cluster AKS », « installer AI Runway », « configuration airunway », « déployer un modèle sur AKS », « inférence GPU sur AKS », « configuration KAITO sur AKS », « exécuter LLM sur AKS », « vLLM sur AKS », « configurer le service de modèles sur AKS », « contrôleur AI Runway ».
devops
appinsights-instrumentation
microsoft
Conseils pour instrumenter les applications web avec Azure Application Insights. Fournit des modèles de télémétrie, la configuration du SDK et des références de configuration. QUAND : comment instrumenter une application, SDK App Insights, modèles de télémétrie, qu'est-ce qu'App Insights, conseils sur Application Insights, exemples d'instrumentation, bonnes pratiques APM.
devops
applicationinsights-web-ts
microsoft
Instrumentez les applications navigateur/web avec le SDK JavaScript Application Insights (@microsoft/applicationinsights-web). Utilisez-le pour la surveillance des utilisateurs réels (RUM) — vues de page, clics, dépendances AJAX/fetch, exceptions, événements personnalisés et traces d’agents GenAI côté navigateur corrélées aux traces OpenTelemetry backend. Couvre le script de chargement du SDK et la configuration npm, les extensions de framework (React, React Native, Angular), Click Analytics, les initialiseurs de télémétrie et les conventions sémantiques OTel GenAI pour les spans d’agents/outils/modèles émises depuis le navigateur.
devops
azure-ai-anomalydetector-java
microsoft
Créez des applications de détection d'anomalies avec le SDK Azure AI Anomaly Detector pour Java. Utilisez-le lors de l'implémentation de la détection d'anomalies univariées/multivariées, de l'analyse de séries temporelles ou de la surveillance basée sur l'IA.
development
azure-ai-language-conversations-py
microsoft
Implémentez la compréhension du langage conversationnel (CLU) à l’aide du SDK Python azure-ai-language-conversations. Utilisez-le lorsque vous travaillez avec ConversationAnalysisClient pour analyser l’intention et les entités d’une conversation, créer des fonctionnalités de NLP ou intégrer la compréhension du langage dans des applications.
development
azure-ai-ml-py
microsoft
SDK v2 d’Azure Machine Learning pour Python. Utiliser pour les espaces de travail ML, les tâches, les modèles, les jeux de données, le calcul et les pipelines. Déclencheurs : « azure-ai-ml », « MLClient », « espace de travail », « registre de modèles », « tâches d’entraînement », « jeux de données ».
development