К основному содержанию
скилл CX Codex

gh-code-scanning — скилл для Claude Code: что делает и как установить

Скилл gh-code-scanning для Claude Code собирает открытые алерты GitHub Code Scanning и группирует их по правилам для разбора проблем безопасности в репозитории.

MIT ★ 1 627 обновлён 2026-10-25

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add microsoft/hve-core --skill gh-code-scanning -a claude-code
Открыть на GitHub

Что делает gh-code-scanning

Скилл запускает скрипт, который получает открытые алерты Code Scanning и сортирует группы по числу срабатываний. В отчёте есть правило, инструмент анализа, серьёзность, число алертов и затронутые пути. Можно выбрать ветку или включить алерты, которые закрыты, но всё ещё обнаруживаются.

Для работы нужны PowerShell 7+ и установленный gh, авторизованный с областью security_events; для публичных репозиториев подходит public_repo, а repo тоже покрывает security_events. Bash-скрипту дополнительно нужен jq. Без авторизации gh с нужной областью скрипт PowerShell остановится при проверке требований.

Для программного разбора запускайте PowerShell-скрипт с -OutputFormat Json. Скилл предназначен только для чтения алертов: список и группировку через gh api использовать как запасной способ нельзя.

Какие задачи решает

  • сгруппировать открытые алерты по правилам
  • отсортировать группы по числу срабатываний
  • ограничить отчёт конкретной веткой
  • найти закрытые алерты, которые всё ещё обнаруживаются

Примеры запросов агенту

  • Собери открытые алерты Code Scanning для {owner}/{repo} и выведи их в JSON.
  • Покажи алерты Code Scanning для {branch} в {owner}/{repo}.
  • Добавь в отчёт закрытые алерты, которые всё ещё обнаруживаются в {owner}/{repo}.

Как установить gh-code-scanning

1Через Skills CLI (Vercel)

npx skills add microsoft/hve-core --skill gh-code-scanning -a claude-code

2Вручную: положить файлы

~/.claude/skills/gh-code-scanning/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/gh-code-scanning/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о gh-code-scanning

Как установить gh-code-scanning в Claude Code?

Выполните npx skills add microsoft/hve-core --skill gh-code-scanning -a claude-code, затем используйте файл ~/.claude/skills/gh-code-scanning/SKILL.md.

Что делает gh-code-scanning?

Скилл получает открытые алерты GitHub Code Scanning и группирует их по правилам, сортируя группы по числу срабатываний. Можно указать ветку и включить закрытые, но всё ещё обнаруживаемые алерты.

Что нужно для запуска gh-code-scanning?

Нужны PowerShell 7+ и авторизованный gh CLI с областью security_events; для публичных репозиториев подходит public_repo. Bash-скрипту также требуется jq.

Исходный текст

SKILL.md · MIT
---
name: gh-code-scanning
description: 'Retrieves and groups GitHub code scanning alerts by rule and severity using the gh CLI'
license: MIT
compatibility: 'Requires pwsh 7+ and gh CLI authenticated with the security_events scope. Bash script requires jq.'
metadata:
  authors: "microsoft/hve-core"
  spec_version: "1.0"
  last_updated: "2026-10-02"
---

# 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

| Requirement | Details                                                                 |
|-------------|-------------------------------------------------------------------------|
| `pwsh`      | PowerShell 7+; install from <https://learn.microsoft.com/powershell>    |
| `gh` CLI    | Installed and on `PATH`; install from <https://cli.github.com>          |
| Auth        | Run `gh auth login` or set `GH_TOKEN`; requires `security_events` scope |
| Scope       | `security_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.

```bash
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

| Parameter                        | Type   | Required | Default | Description                                                                                                                 |
|----------------------------------|--------|----------|---------|-----------------------------------------------------------------------------------------------------------------------------|
| `-Owner`                         | String | Yes      |         | GitHub organization or user that owns the repository                                                                        |
| `-Repo`                          | String | Yes      |         | Repository name                                                                                                             |
| `-OutputFormat`                  | String | No       | Table   | Output format: agents must always use `Json` for programmatic consumption; `GroupedJson` is accepted as an alias for `Json` |
| `-Branch`                        | String | No       | `main`  | Branch to scope alert results                                                                                               |
| `-IncludeDismissedStillDetected` | Switch | No       |         | Also 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.

```bash
# 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`.

```bash
# 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.

```bash
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:

```json
[
  {
    "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.

```bash
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.

```bash
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.

```bash
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

| Symptom                                                    | Likely cause                                   | Fix                                                                                                                 |
|------------------------------------------------------------|------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| `gh CLI not found. Install it from https://cli.github.com` | `gh` CLI not on `PATH`                         | Install from <https://cli.github.com>, then re-open your terminal                                                   |
| `gh CLI is not authenticated. Run 'gh auth login'`         | `gh` auth not completed                        | Run `gh auth login`; ensure `security_events` scope is granted                                                      |
| `HTTP 403 Resource not accessible by integration`          | Missing `security_events` scope on token       | Re-authenticate: `gh auth refresh -s security_events` or set `GH_TOKEN` with appropriate scope                      |
| Empty results `[]`                                         | Wrong `ref` format or no alerts on that branch | Omit `-f ref=` to search all branches, or use `refs/heads/main` format (not just `main`)                            |
| `bash: jq: command not found`                              | `jq` not installed                             | Install via `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or from <https://jqlang.github.io/jq/> |

© microsoft · MIT · microsoft/hve-core

Похожие скиллы

Все скиллы по теме «Безопасность» →
secret-scanning официальный github Скилл secret-scanning помогает настроить поиск утёкших секретов, защиту push и работу с алертами GitHub. Пригодится перед коммитом и при разборе заблокированных отправок. CX Codex +1 4 600установок infisical-secret-scanning Infisical Скилл infisical-secret-scanning помогает найти утёкшие ключи в репозитории и поставить проверку до пуша: облачные источники, infisical scan, pre-commit хук. CX Codex +1 254установок diff-scanning-with-aws-security-agent aws Скилл diff-scanning-with-aws-security-agent для Claude Code и других ИИ-редакторов, запускает AWS Security Agent только на изменённом коде с указанного git-рефа. Срабатывает перед коммитом или PR. CX Codex +1 1 600установок implementing-secret-scanning-with-gitleaks mahipal Скилл implementing-secret-scanning-with-gitleaks для Claude Code, Codex, Cursor, GitHub Copilot и Gemini CLI учит агента настраивать Gitleaks для поиска захардкоженных секретов в git-репозитории. CX Codex +1 577установок scanning-with-aws-security-agent aws Скилл scanning-with-aws-security-agent запускает аудит репозитория через AWS Security Agent, загружая архив в S3. Возвращает проверенный список уязвимостей с рекомендациями по исправлению. CX Codex +1 1 600установок vulnerability-scanning aj-geddes Скилл vulnerability-scanning для поиска уязвимостей в зависимостях, коде, контейнерах и секретах. Пригодится перед деплоем и при аудитах безопасности. CX Codex +1 621установок

Из того же набора148

Весь набор →
PowerPoint Builder Субагент PowerPoint Builder для Claude Code создаёт, обновляет и проверяет презентации PowerPoint через YAML и python-pptx. Собирает слайды с нуля и точечно правит готовые колоды. CX Codex +1 ★ 1 627звёзд репо rpi-review Скилл rpi-review для Claude Code сверяет план задачи с записью изменений и результатами реализации. Выполняет приёмочную проверку и направляет найденные пробелы на доработку. CX Codex +1 ★ 1 627звёзд репо rpi-implement Скилл rpi-implement выполняет утверждённый план разработки, держит его актуальным, отмечает сделанное и ведёт лог изменений. Запускается, когда готовы начать реализацию или продолжить её. CX Codex +1 ★ 1 627звёзд репо Codebase Profiler Субагент Codebase Profiler сканирует репозиторий, определяет стек и отдаёт родительскому агенту профиль с перечнем применимых security- и accessibility-скиллов. CX Codex +1 ★ 1 627звёзд репо privacy-by-design Проверяет проект по 7 принципам Privacy by Design: находит уязвимости в защите данных, даёт вердикт по каждому принципу и предлагает исправления. CX Codex +1 ★ 1 627звёзд репо pull-request Скилл pull-request готовит, открывает и обновляет пулл-реквесты на GitHub с локальной проверкой diff, точечными тестами и раздельным подтверждением пуша. CX Codex +1 ★ 1 627звёзд репо gitlab Управляет merge request, заметками, пайплайнами и логами заданий GitLab через Python CLI. Работает с GitLab.com и собственными инстансами GitLab. CX Codex +1 ★ 1 627звёзд репо Finding Deep Verifier Субагент Finding Deep Verifier для Claude Code перепроверяет находки FAIL и PARTIAL в ревью безопасности: ищет в коде доводы за и против каждой и выносит вердикт. CX Codex +1 ★ 1 627звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой