PluginWorks in Claude CodeCurrent
Pagerduty
Enhance code quality and security through PagerDuty risk scoring and incident correlation. Score pre-commit diffs against historical incident data and surface deployment risk before you ship.
0
Try it
See what this would do for you. No sign-up needed.
Install in Claude Code
Run these in Claude Code, in order. The first adds the marketplace, the second installs the plugin.
Step 1
/plugin marketplace add anthropics/claude-plugins-official
Step 2
/plugin install pagerduty@claude-plugins-official
Review commands before running them. Promptu never runs code on your machine or pushes changes to your repo.
What's inside
2 commands
- create-pagerduty-skill
- pre-commit-risk-scoring
1 MCP server
Security scan
Passed
Promptu's text scan of the files it could read didn't match any known risky patterns. It doesn't run the plugin, and a clean scan doesn't mean the plugin is safe.
Automated pattern check of 6 file(s) found nothing risky. Not a full audit.
Details
# PagerDuty Claude Code Plugins
[](https://opensource.org/licenses/Apache-2.0)
PagerDuty's open source [Claude Code plugins](https://code.claude.com/docs/en/plugins) that bring operational intelligence into your development workflow.
## Available plugins
| Plugin | Description |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| pre-commit-risk-scoring | Pre-commit risk assessment using PagerDuty incident history, change event correlation, and git diff analysis |
| create-pagerduty-skill | Create and manage PagerDuty skills for AI agents through guided interview (Early Access) |
## Getting started
### Prerequisites
- [Claude Code](https://code.claude.com) v1.0.33 or later
### 1. Add the marketplace
Run this once in any Claude Code session:
```bash
/plugin marketplace add pagerduty/claude-code-plugins
```
### 2. Browse and install plugins
Open the plugin manager and go to the **Discover** tab to browse available plugins:
```bash
/plugin
```
Or install a plugin directly:
```bash
/plugin install pagerduty@pagerduty-claude-code-plugins
```
### 3. Configure API key
The plugins bundle a PagerDuty MCP server that needs an API token. Git commit history is read directly from the local repository.
**Option A: Per-repo via `.claude/settings.local.json`** (recommended)
This file is gitignored by default, so secrets stay local:
```json
{
"env": {
"PAGERDUTY_API_KEY": "your-pagerduty-token"
}
}
```
If the file already exists, merge the `env` key into it.
**Option B: Global via `~/.claude/settings.json`**
This applies the key to all projects:
```json
{
"env": {
"PAGERDUTY_API_KEY": "your-pagerduty-token"
}
}
```
If the file already exists, merge the `env` key into it.
> **Note:** You may need to restart VS Code for environment variable changes to take effect.
#### Where to get the token
PagerDuty > User Profile > User Settings > API Access > Create API User Token.
Restart Claude Code after setting the key so the MCP server picks it up.
## Set up for your team
You can configure a repository so team members are automatically prompted to add this marketplace when they trust the project folder. Add the following to your project's `.claude/settings.json`:
```json
{
"extraKnownMarketplaces": {
"pagerduty-claude-code-plugins": {
"source": {
"source": "github",
"repo": "pagerduty/claude-code-plugins"
}
}
}
}
```
To also auto-enable specific plugins for the project:
```json
{
"extraKnownMarketplaces": {
"pagerduty-claude-code-plugins": {
"source": {
"source": "github",
"repo": "pagerduty/claude-code-plugins"
}
}
},
"enabledPlugins": {
"pagerduty@pagerduty-claude-code-plugins": true
}
}
```
## Managing plugins
Update the marketplace to get the latest plugins:
```bash
/plugin marketplace update pagerduty-claude-code-plugins
```
Disable a plugin without uninstalling:
```bash
/plugin disable pagerduty@pagerduty-claude-code-plugins
```
Uninstall a plugin:
```bash
/plugin uninstall pagerduty@pagerduty-claude-code-plugins
```
## Plugin: Pre-Commit Risk Scoring
A plugin that assesses pre-commit risk by correlating PagerDuty incident history with current code changes.
The `/pagerduty:pre-commit-risk-scoring` command gathers PagerDuty incident data for your service, analyzes your current git diff, and looks for correlations between the areas you are changing and areas that have historically caused incidents. It surfaces active incidents, recent incident patterns, structural risk signals in the diff, and actionable recommendations.
### Usage
With uncommitted changes in your working tree:
```bash
/pagerduty:pre-commit-risk-scoring
```
On first run, the plugin resolves your repository to a PagerDuty service through a fallback chain:
1. Explicit argument passed at invocation (one-time override, not cached)
2. Cached config in `.claude/risk-config.json`
3. Backstage `catalog-info.yaml` annotation (`pagerduty.com/service-id`)
4. Auto-detection by matching the repository name against PagerDuty services
5. Manual input via interactive prompt
The resolved mapping is saved to `.claude/risk-config.json` for subsequent runs.
You can pass a service name as a one-time override. This takes highest priority, skipping cache and auto-detection, and will not update `.claude/risk-config.json`:
```bash
/pagerduty:pre-commit-risk-scoring my-service-name
```
### Output
The command produces a structured risk assessment containing:
- **Active incidents** for the mapped service (highest-priority signal)
- **Incident history** summary over the last 90 days
- **Change analysis** with file-level and structural risk signals
- **Correlation findings** between current changes and past incidents
- **Risk score** from 0 (no risk) to 5 (critical), based on incident correlation and change analysis
- **Recommendations** based on identified risk factors
### Changing the mapped service
Delete `.claude/risk-config.json` and re-run `/pagerduty:pre-commit-risk-scoring` to pick a different service.
### Plugin structure
```text
.claude-plugin/
marketplace.json # Marketplace registry
plugin.json # Plugin metadata
commands/
pre-commit-risk-scoring.md # Slash command definition
.mcp.json # PagerDuty MCP server declaration
```
### MCP servers
| Server | Declared in | Tools used |
| --------- | -------------------------- | -------------------------------------------------------------------------------------- |
| PagerDuty | `.mcp.json` (plugin-local) | `get_service`, `list_services`, `list_incidents`, `list_incident_notes`, `list_service_change_events` |
## Plugin: Create PagerDuty Skill
**Early Access**: This feature requires enrollment in two Early Access programs:
- [PagerDuty Skills EA](https://www.pagerduty.com/early-access/)
- [PagerDuty Advance MCP/API EA](https://support.pagerduty.com/main/changelog/pagerduty-advance-mcpapi-support-is-now-in-early-access-for-advance-customers)
A plugin that provides an interactive workflow for creating and updating PagerDuty skills for AI agents. Skills allow you to encode your team's domain knowledge and operational procedures into structured instructions that the SRE Agent can follow during incident response.
### Usage
Launch the interactive skill builder:
```bash
/pagerduty:create-pagerduty-skill
```
The command guides you through:
1. **Mode selection**: Create new or update existing skill
2. **Scope selection**: Personal (user) or shared (account-level)
3. **Workflow definition**: What should the agent do?
4. **Skill configuration**: Name, description, instructions, examples, and metadata
5. **API deployment**: Immediate deployment to PagerDuty platform
### Features
- **Interactive interview**: Short, natural conversation extracts your domain knowledge
- **Two scope types**:
- **Personal (user)**: Private skills visible only to you (max 25 per agent)
- **Shared (account)**: Team-level skills visible to everyone (max 50 per agent)
- **Update mode**: Fetch existing skills and modify them (full replacement)
- **Validation**: Name format (kebab-case), length limits, token estimation
- **Integration references**: Automatically includes available SRE Agent integrations (Confluence, GitHub, Grafana, Datadog, etc.)
- **Immediate deployment**: Skills are available in the PagerDuty platform right after creation
### Skill structure
Skills consist of:
- **Name**: kebab-case identifier (max 60 chars, unique per agent/scope)
- **Description**: What the skill does (max 1024 chars)
- **Instructions**: Step-by-step execution guide (max 5000 tokens)
- **Examples**: Trigger conditions for automatic invocation
- **Metadata**: Version, author, team, type (experimental/production)
### MCP servers
| Server | Declared in | Tools used |
| --------- | -------------------------- | -------------------------------------------------------------------------------------- |
| PagerDuty Advance MCP | `.mcp.json` (plugin-local) | `create_skill_tool`, `get_skill_tool`, `list_skills_tool`, `update_skill_tool` |
## Contributing
We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
## License
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
## commands/create-pagerduty-skill.md
---
description: "Create or update PagerDuty skills for AI agents through guided interview"
allowed-tools: [
"ToolSearch",
"Read",
"Write",
"Bash",
"AskUserQuestion",
"Glob",
"mcp__pagerduty-advance-mcp-__create_skill_tool",
"mcp__pagerduty-advance-mcp-__get_skill_tool",
"mcp__pagerduty-advance-mcp-__list_skills_tool",
"mcp__pagerduty-advance-mcp-__update_skill_tool"
]
---
You are creating or updating a PagerDuty Skill for AI agents. Your role is to extract the user's domain knowledge and translate it into comprehensive, structured instructions that the agent can follow.
## Pre-flight Checks
**CRITICAL: Before proceeding, verify PagerDuty Advance MCP is available.**
1. Use ToolSearch to check for `mcp__pagerduty-advance-mcp-__create_skill_tool`
2. If not found, display error and EXIT (do not proceed):
```
❌ PagerDuty Advance MCP is not available.
This command requires the PagerDuty Advance MCP server to create and manage skills via API.
Note: PagerDuty Skills is currently in Early Access (EA).
To get access:
1. Request PagerDuty Skills EA access: https://www.pagerduty.com/early-access/
2. Request PagerDuty Advance MCP/API EA access: https://support.pagerduty.com/main/changelog/pagerduty-advance-mcpapi-support-is-now-in-early-access-for-advance-customers
3. Once approved, configure PagerDuty Advance MCP in .mcp.json
4. Set your PAGERDUTY_API_KEY in the environment (.claude/settings.local.json or ~/.claude/settings.json)
5. Restart Claude Code
6. Re-run /pagerduty:create-pagerduty-skill
```
3. Do NOT proceed without MCP access - no silent degradation
## API Constraints
Skills are managed via the PagerDuty Advance MCP API with these constraints:
- **agent_type**: Always `"sre"` (only SRE Agent supports skills currently)
- **scope**: REQUIRED - `"account"` (shared, team-level) or `"user"` (personal, individual)
- **name**: kebab-case, max 60 chars, unique per (agent, scope) - same name can exist in both scopes
- **description**: max 1024 chars
- **instructions**: max 5000 tokens total (entire skill document)
- **limits**:
- Account scope: Max 50 skills per agent
- User scope: Max 25 skills per agent
- **immutable fields**: scope and name cannot be changed after creation (must delete and recreate)
**Validation rules:**
- Name format: `^[a-z0-9]+(-[a-z0-9]+)*$` (kebab-case only)
- Token estimation: `chars / 4 ≈ tokens`
- Warn at 90% of 5000 token limit (4500 tokens)
## Skill Quality Standards
A good PagerDuty Skill should be:
- **Specific**: Clear about when and how to use it
- **Actionable**: Step-by-step instructions the agent can follow
- **Contextual**: Includes prerequisites, tools, and resources needed
- **Robust**: Handles edge cases and errors gracefully
## Interview Process
Keep the interview SHORT and NATURAL. Don't over-question. Ask 2-3 clarifying questions maximum, then draft comprehensive instructions yourself.
**Your role**: You are the translator between the user's natural language and agent-optimized skill definitions. The user describes what they want; YOU synthesize it into structured, agent-friendly instructions, descriptions, and examples.
### Step 1: Mode Selection
First, determine whether to create a new skill or update an existing one.
Ask:
```
I'll help you create or update a PagerDuty Skill.
What would you like to do?
1. Create a new skill
2. Update an existing skill
(1/2)
```
Store the mode as `create` or `update` and proceed to Step 2.
### Step 2: Scope Selection
Ask the user to choose the scope:
```
Is this a personal skill or a shared team skill?
1. Personal (visible only to you)
2. Shared (visible to everyone in your PagerDuty account)
(1/2)
```
Map response to scope:
- 1 → `"user"`
- 2 → `"account"`
**Important**: The same skill name can exist in both scopes independently. Identity is `(agent, scope, name)`.
### Step 3: Skill Selection (UPDATE mode only)
**For UPDATE mode, follow these steps:**
**3a. List Existing Skills:**
Call `list_skills_tool` with agent_type="sre" and the chosen scope.
If no skills exist:
```
No {scope} skills found. Let's create one instead.
```
Switch to CREATE mode and continue to Step 4.
If skills exist, display them:
```
Existing skills:
1. fetch-issue-type-runbook
Description: Use this skill to fetch issue specific runbooks
Metadata: version=1.0, author=user@example.com, team=platform
2. diagnose-database-slowness
Description: Automated diagnosis of database performance issues
Metadata: version=2.1, author=user@example.com, team=infrastructure
Which skill would you like to update? (enter number or name)
```
**3b. Fetch Current Skill:**
Use `get_skill_tool` with agent_type="sre", scope, and skill_name to retrieve the full skill document.
Display current configuration:
```
Current skill configuration:
Name: {name}
Description: {description}
Instructions: [showing first 300 chars]
{instructions[:300]}...
Examples: {len(examples) if examples else 0} example(s)
Metadata: version={version}, author={author}, team={team}, type={type}
Ready to update this skill? (y/n)
```
If "n": ask if they want to pick a different skill or exit.
Store all current values for use in interview prompts.
### Step 4: Check Skill Limit (CREATE mode only)
**For CREATE mode:**
Call `list_skills_tool` with agent_type="sre" and the chosen scope. Count results and check against limit:
- Account scope: limit is 50
- User scope: limit is 25
If limit reached:
```
⚠️ Limit reached: You already have {count} {scope} skills (the maximum for {scope} scope).
Existing skills:
1. skill-name-1
2. skill-name-2
...
You can update an existing skill or delete one first.
Would you like to switch to update mode? (y/n)
```
If yes, switch to UPDATE mode and go to Step 3a.
If no, exit with instructions to delete a skill first.
### Step 5: Understand the Workflow
Start with:
```
{if CREATE: Let's create your skill.}
{if UPDATE: Let's update your skill.}
{if UPDATE: Current description: "{current_description}"}
What should the agent do? Describe the task or workflow you want to automate during incident response.
{if UPDATE: Press Enter to keep the current workflow, or describe changes/new workflow}
```
**Listen for:**
- The trigger or context (when does this happen?)
- The goal (what problem does it solve?)
- The basic workflow (what steps are involved?)
### Step 6: Ask 1-2 Clarifying Questions
Based on their description, ask ONLY the most important clarifying questions. Examples:
- "Should the agent do this automatically during triage, or only when asked?"
- "What data will be available when this runs?" (e.g., alert details, service info)
- "What should happen if [key step] fails?"
**Don't ask about:**
- Specific tool names - you'll translate their natural language into integration references
- Every edge case - use reasonable defaults
- Success criteria in detail - infer from the workflow
Keep it to 1-2 questions maximum.
### Step 7: Draft Complete Instructions
Now YOU synthesize everything into structured instructions. Translate their natural language into:
- When to use the skill (trigger conditions)
- Prerequisites (what data/context is needed)
- Numbered execution steps referencing specific SRE Agent integrations:
- **Documents/Runbooks**: Confluence, GitHub, ServiceNow
- **Logs**: Grafana, Datadog, New Relic, AWS CloudWatch, Splunk, Dynatrace, Elasticsearch, Sumo Logic
- Basic error handling (fail gracefully, report issues, continue where possible)
- Success criteria (what indicates the task completed)
**Format the instructions with clear sections:**
```
WHEN TO USE THIS SKILL:
[trigger conditions]
PREREQUISITES:
[required data/context]
EXECUTION STEPS:
1. [first step with specific tool if applicable]
2. [second step]
...
ERROR HANDLING:
[what to do when things go wrong]
SUCCESS CRITERIA:
[what indicates success]
```
Show them the draft:
```
{if CREATE: Based on what you've described, here are the instructions I've drafted:}
{if UPDATE: Here are the updated instructions:}
[show full instructions]
Does this capture what you need? (y/n/edit)
```
If "edit": ask what to change, update, show again.
If "n" with no details: ask what needs adjustment.
**Token count check:**
After finalizing instructions, estimate token count: `len(instructions) / 4`
If > 4500 tokens (90% of 5000 limit), warn:
```
⚠️ Instructions are ~{estimated_tokens} tokens (90%+ of 5000 limit).
Consider condensing to avoid hitting the API limit.
```
### Step 8: Suggest a Name (CREATE mode) or Show Name (UPDATE mode)
**For CREATE mode:**
Based on the workflow, suggest 2-3 skill names in kebab-case:
```
Based on what this skill does, here are some name suggestions:
1. [action-target-noun] (e.g., fetch-issue-type-runbook)
2. [verb-noun-descriptor]
3. [task-action]
Which do you prefer, or would you like a different name?
```
**Validation:**
- Max 60 characters (not 64)
- Kebab-case format: `^[a-z0-9]+(-[a-z0-9]+)*$`
- Action-oriented and descriptive
- Check uniqueness: call `list_skills_tool` with the chosen scope and verify name doesn't exist
- If name exists in that scope, show error and ask for different name
- Note: Same name can exist in both scopes, but must be unique within the chosen scope
**For UPDATE mode:**
```
Current name: {current_name}
Note: Skill names cannot be changed after creation. The name will remain "{current_name}".
```
### Step 9: Draft Description
YOU create a 1-2 sentence description from the workflow. Don't ask the user to write it - interpret their workflow and draft an agent-optimized description yourself.
```
{if UPDATE: Current description: "{current_description}"}
Here's a description based on the workflow:
"{generated_description}"
Good? (y/n)
{if UPDATE: Press Enter to keep current}
```
**Validation:**
- Max 1024 characters
- Should explain what it does, when it triggers, and what problem it solves
- Written for the agent to understand, not just human-readable
- Focus on trigger conditions and outcomes
If "n": ask what to adjust and revise.
### Step 10: Quick Optional Fields
**Examples (trigger conditions/prompts):**
```
{if UPDATE and examples: Current examples: {len(examples)} example(s)
{show current examples}}
Want to {add/update/keep} examples of when to invoke this skill? (y/n{/keep if UPDATE})
```
If yes:
```
When should the agent invoke this skill? Describe the conditions or situations.
```
Listen to their response, then YOU translate it into 2-3 clear, agent-friendly trigger conditions. Format them as:
- Specific conditions in alert data: "Invoke when alert custom details contain {key}: {value}"
- User prompts: "Use when the user asks to {action}"
- Automatic triggers: "Trigger during {phase} if {condition}"
Show your draft and confirm:
```
Based on that, here are the trigger examples:
1. {example_1}
2. {example_2}
3. {example_3}
Good? (y/n)
```
If "keep" (UPDATE mode): preserve current examples.
**Metadata:**
Auto-detect author from git:
```bash
git config user.email
```
Then ask:
```
{if UPDATE: Current metadata: version={version}, author={author}, team={team}, type={type}}
Metadata:
- Author: {detected_email} {if UPDATE: (press Enter to keep current: {author})}
- Team name: {if UPDATE: [current: {team}]} [ask]
- Type (experimental/production): {if UPDATE: [current: {type}]} [ask]
- Version: {if UPDATE: {suggest_increment(current_version)} | if CREATE: 1.0}
Confirm these values? (y/n)
```
**Version increment logic (UPDATE mode):**
- Parse current version (e.g., "1.0", "1.9", "2.3")
- Suggest minor increment: 1.0 → 1.1, 1.9 → 1.10, 2.3 → 2.4
- Allow user to override with custom version
### Step 11: Final Preview
Display complete skill structure:
```
{if CREATE: Here's the complete skill:}
{if UPDATE: Here are your changes:}
Scope: {scope} ({if account: "shared with your team" | if user: "personal to you"})
Name: {name}
Description: {description}
Instructions: [{char_count} chars, ~{estimated_tokens} tokens]
{instructions}
Examples: {examples or "none"}
Connectors: [] (empty)
Metadata:
version: {version}
author: {author}
team: {team}
type: {type}
{if CREATE: Create this skill?}
{if UPDATE: Update this skill? (Note: This is a full replacement - all fields will be updated)}
(y/n/preview-json)
```
**Option: preview-json**
If user types "preview-json", show the exact API payload:
```json
{
"agent_type": "sre",
"scope": "{scope}",
"name": "{name}",
"description": "{description}",
"instructions": "{instructions}",
"examples": {examples or null},
"connectors": null,
"metadata": {metadata}
}
```
Then re-ask: "Ready to proceed? (y/n)"
### Step 12: API Execution
**For CREATE mode:**
```
Creating skill via PagerDuty API...
```
Call `mcp__pagerduty-advance-mcp-__create_skill_tool` with parameters:
- `agent_type`: "sre"
- `scope`: "account" or "user" (from Step 2)
- `name`: kebab-case string
- `description`: string
- `instructions`: string
- `examples`: array of strings or null (if empty, pass null not [])
- `connectors`: null (always)
- `metadata`: object with {version, author, team, type}
**For UPDATE mode:**
```
Updating skill via PagerDuty API...
Note: This is a full replacement. All fields will be updated.
```
Call `mcp__pagerduty-advance-mcp-__update_skill_tool` with parameters:
- `agent_type`: "sre"
- `scope`: "account" or "user" (from Step 2)
- `skill_name`: immutable skill name (required)
- `description`: string
- `instructions`: string
- `examples`: array of strings or null
- `connectors`: null (always)
- `metadata`: object with {version, author, team, type}
**Error Handling:**
Handle these common API errors:
1. **Name collision (CREATE only):**
```
❌ Error: Skill "{name}" already exists in {scope} scope.
Choose a different name or switch to update mode.
Would you like to update the existing skill instead? (y/n)
```
2. **Skill not found (UPDATE only):**
```
❌ Error: Skill "{name}" not found in {scope} scope.
The skill may have been deleted. Would you like to create it instead? (y/n)
```
3. **Skill limit reached (CREATE only):**
```
❌ Error: Maximum of {50 for account | 25 for user} {scope} skills reached.
Existing skills: [list from list_skills_tool]
You can update an existing skill or delete one first.
Would you like to switch to update mode? (y/n)
```
4. **Validation errors (name format, length, tokens):**
```
❌ Error: {error_message}
{specific fix guidance based on error}
```
Return to the specific field that failed and ask user to correct it.
5. **Authentication/API errors:**
```
❌ API Error: {error_message}
Possible causes:
- PAGERDUTY_API_KEY not set or invalid
- Account does not have Early Access (requires both PagerDuty Skills EA and Advance MCP/API EA)
- Skills EA: https://www.pagerduty.com/early-access/
- Advance MCP/API EA: https://support.pagerduty.com/main/changelog/pagerduty-advance-mcpapi-support-is-now-in-early-access-for-advance-customers
- Network connectivity issues
- PagerDuty service outage
Check your API key and Early Access status, then try again.
```
### Step 13: Success
On successful API call:
```
✅ Skill {created/updated}: {skill-name}
Scope: {scope} ({if account: "shared with your team" | if user: "personal to you"})
Your skill is now available to the SRE Agent!
Next steps:
1. The skill is immediately available in the PagerDuty platform
2. Test the skill in an incident or via the SRE Agent interface
3. Monitor skill usage and iterate as needed
{if CREATE:
Optional: Would you like to save a local JSON backup for your records? (y/n)
}
{if UPDATE:
Changes applied:
{summarize what changed: description, instructions, examples, metadata}
}
```
**Optional JSON backup (CREATE mode only):**
If user says yes, write `{skill-name}.json` in current directory:
```json
{
"name": "{name}",
"description": "{description}",
"instructions": "{instructions}",
"examples": {examples or []},
"agent_type": "sre",
"scope": "{scope}",
"connectors": [],
"metadata": {metadata}
}
```
## Key Principles
1. **Keep it short** - 2-3 clarifying questions max, then YOU draft everything
2. **Translate everything** - They describe in natural language, you convert ALL fields (description, instructions, examples) into agent-optimized format
3. **Use defaults** - Don't ask about every edge case, use reasonable error handling
4. **Show your work** - Display drafts, get confirmation, iterate
5. **Be efficient** - If they say "yes" or "fine", move on quickly
6. **Workflow-first naming** - Suggest names AFTER understanding what it does
## Available SRE Agent Integrations
When translating workflows to instructions, reference these integrations:
**Documents/Runbooks:**
- Confluence - Retrieve runbooks and documentation
- GitHub - Access runbooks and documentation
- ServiceNow - Retrieve runbooks and documentation
**Logs:**
- Grafana - Fetch and analyze logs
- Datadog - Fetch and analyze logs
- New Relic - Fetch and analyze logs
- AWS CloudWatch - Fetch and analyze logs
- Splunk - Fetch and analyze logs
- Dynatrace - Fetch and analyze logs
- Elasticsearch - Fetch and analyze logs
- Sumo Logic - Fetch and analyze logs
For the full list, see: https://support.pagerduty.com/main/docs/agent-tooling-configuration
## commands/pre-commit-risk-scoring.md
---
description: "Assess pre-commit risk by correlating PagerDuty incidents with current code changes"
argument-hint: "[pagerduty-service-name]"
allowed-tools: ["ToolSearch", "Read", "Glob", "Grep", "Bash", "Write", "AskUserQuestion", "mcp__plugin_pagerduty_pagerduty__get_service", "mcp__plugin_pagerduty_pagerduty__list_services", "mcp__plugin_pagerduty_pagerduty__list_incidents", "mcp__plugin_pagerduty_pagerduty__list_incident_notes", "mcp__plugin_pagerduty_pagerduty__list_service_change_events"]
---
You are performing a pre-commit risk assessment. Follow these steps precisely and in order. Do not skip steps. Do not silently degrade -- if a required tool is unavailable, stop and tell the user.
## Step 0: Pre-flight Checks
Before doing anything else, verify that the required MCP tools are available.
### 0a: Verify PagerDuty MCP
First, call `ToolSearch` with query `"select:mcp__plugin_pagerduty_pagerduty__get_service,mcp__plugin_pagerduty_pagerduty__list_services,mcp__plugin_pagerduty_pagerduty__list_incidents,mcp__plugin_pagerduty_pagerduty__list_incident_notes,mcp__plugin_pagerduty_pagerduty__list_service_change_events"` to load all required PagerDuty tools. If ToolSearch returns no results, STOP immediately (see error below).
Once loaded, call `mcp__plugin_pagerduty_pagerduty__list_services` with query `"test"`. This is a connectivity check.
If ToolSearch returns no PagerDuty tools, or the connectivity call fails, STOP and tell the user:
```
PagerDuty MCP server is not available. This plugin requires it.
To fix:
1. Set the PAGERDUTY_API_KEY environment variable with a valid PagerDuty API token
2. Restart Claude Code so the plugin's MCP server configuration is loaded
3. Re-run /pagerduty:pre-commit-risk-scoring
```
Do NOT proceed without PagerDuty MCP. Do NOT fall back to a degraded assessment. The entire point of this plugin is PagerDuty incident correlation.
### 0b: Verify changes exist
Run `git diff --stat` and `git diff --cached --stat` to check for uncommitted changes (unstaged and staged).
If both are empty, run `git log -1 --oneline` and tell the user:
```
No uncommitted changes detected. The most recent commit is:
<commit hash and message>
/pagerduty:pre-commit-risk-scoring analyzes uncommitted changes. Make some changes first, or if you want to assess the last commit, let me know.
```
Then STOP. Do not proceed to analyze committed history on your own.
## Step 1: Resolve Service Mapping
Determine the PagerDuty service ID for this repository. Follow the steps **in order** and stop at the first one that resolves a service.
### 1a: Use explicit argument (highest priority)
If `$ARGUMENTS` is provided, use it immediately — **do not check the cache or catalog first**.
Call `mcp__plugin_pagerduty_pagerduty__list_services` with `$ARGUMENTS` as the query.
- If exactly one service matches: use it and skip to Step 1d.
- If multiple match: present the options to the user via `AskUserQuestion` and let them pick, then skip to Step 1d.
- If no match: tell the user no service was found for that name, ask them to verify it, and STOP. Do NOT fall through to cache or repo-name detection.
### 1b: Check cached configuration
If no `$ARGUMENTS` was provided, read `.claude/risk-config.json`. If it exists and contains `pagerduty.serviceId`, validate it by calling `mcp__plugin_pagerduty_pagerduty__get_service` with that ID. If the call succeeds, use the service and skip to Step 2 — display the cached service name to the user. If the call fails (service not found or API error), discard the cached config, warn the user, and continue to Step 1c.
### 1c: Check Backstage catalog
If no cached config, check for `catalog-info.yaml` in the repository root. Look for the `pagerduty.com/service-id` annotation under `metadata.annotations`. If found, use that service ID.
Validate it by calling `mcp__plugin_pagerduty_pagerduty__get_service` with the literal service ID (e.g. `PAWX771`). Do NOT pass the ID to `list_services` — querying by raw UUID returns a 502. Extract the service name from the response. If found, skip to Step 1d.
### 1d: Auto-detect from repository name
If none of the above resolved a service:
- Get the repository name from the current directory basename, or parse it from `git remote -v` output.
- Call `mcp__plugin_pagerduty_pagerduty__list_services` with a query matching the repository name.
- If exactly one service matches: use it. Tell the user which service was detected and ask them to confirm.
- If multiple services match: present the options to the user via `AskUserQuestion` and let them pick.
- If no match: use `AskUserQuestion` to ask the user for the PagerDuty service name or ID. Search for it with `mcp__plugin_pagerduty_pagerduty__list_services` to validate and get the canonical service ID.
### 1e: Persist configuration
If the service was resolved via `$ARGUMENTS` (Step 1a), **do not write or update `.claude/risk-config.json`** — the argument is a one-time override, not a permanent mapping.
Otherwise, once a service ID is resolved, write `.claude/risk-config.json`:
```json
{
"version": "1.0",
"pagerduty": {
"serviceId": "<resolved-service-id>",
"serviceName": "<resolved-service-name>"
}
}
```
Create the `.claude/` directory first if it does not exist.
## Step 2: Check Ongoing Incidents
Call `mcp__plugin_pagerduty_pagerduty__list_incidents` with:
- `statuses`: `["triggered", "acknowledged"]`
- `service_ids`: `["<serviceId>"]`
For each active incident returned, call `mcp__plugin_pagerduty_pagerduty__list_incident_notes` to get responder context. **Cap at 5 active incidents** — if more are returned, fetch notes only for the 5 most recently triggered and note the total count.
If there are active incidents, report them prominently -- these are the highest-priority risk signal. Use this format:
```
ACTIVE INCIDENTS
[TRIGGERED] INC-12345: Database connection pool exhaustion (P1)
Triggered 2h ago. Notes: "Scaling up read replicas, ETA 30min"
[ACKNOWLEDGED] INC-12346: Elevated error rate on /api/checkout (P2)
Acknowledged 45min ago. Notes: "Investigating correlation with deploy at 14:30"
```
If there are no active incidents, note that briefly and continue.
## Step 3: Fetch Recent Incident History
**Start these calls in parallel with Step 2** — they are fully independent. Make the following three calls in parallel with each other:
1. Call `mcp__plugin_pagerduty_pagerduty__list_incidents` for the service over the last 90 days, filtered to **high urgency** (use `since` set to 90 days ago, `until` set to today, and `urgencies: ["high"]`). Include all statuses.
**Limit handling**: The API caps results at 1000 incidents. If exactly 1000 are returned, the history is partial — note this in the assessment and state the actual date range covered (i.e. the timestamp of the oldest incident returned).
2. Call `mcp__plugin_pagerduty_pagerduty__list_incidents` for the service over the last 90 days, filtered to **low urgency** (same date range, `urgencies: ["low"]`). Include all statuses.
Apply the same limit handling as above independently for this call.
3. Call `mcp__plugin_pagerduty_pagerduty__list_service_change_events` for the service to get recent change events that PagerDuty has tracked. **Before analyzing**, deduplicate change events by `summary + timestamp` — the API often returns 5–6 identical entries for the same deploy.
For incidents that warrant fetching notes, use the high-urgency list from call 1 directly — no keyword guessing needed. **Cap notes fetching at 10 incidents** (most recent first). If the high-urgency list has more than 10, note how many were skipped.
From the collected data, summarize:
- Total incident count over 90 days: high-urgency count (from call 1) + low-urgency count (from call 2), noting if either is partial due to the 1000-incident cap
- Severity distribution: high-urgency vs low-urgency counts
- Recency of the most recent resolved incident
- Common patterns in incident titles or notes (repeated keywords, affected components)
- Change events (deduplicated) and their timing relative to incidents
## Step 4: Analyze Current Changes and Correlate
**Start Steps 4a and 4b in parallel with Steps 2 and 3** — git commands are local and do not depend on PagerDuty data.
### 4a: Gather current changes
Run the following commands to understand the current diff:
- `git diff --stat` for a summary of changes (unstaged)
- `git diff --cached --stat` for staged changes
- `git diff --name-only` and `git diff --cached --name-only` for the list of changed files
- `git diff` and `git diff --cached` for the full diff content (if the diff is very large, focus on `--stat` and file names)
### 4b: Gather recent commit history
Run `git log --format="%h %s (%an, %ar)" -20` to get the last 20 commits. This provides context on what has been changing recently.
### 4c: Correlate changes with incidents
Analyze the data gathered in Steps 2-4b and look for correlations:
1. **File/directory overlap**: Compare the files and directories in the current diff with areas mentioned in incident notes or titles. Are we touching components that have been involved in recent incidents?
2. **Change event correlation**: Compare PagerDuty change events with the current diff paths. Have previous changes to these same areas preceded incidents?
3. **Structural risk patterns**: Identify high-risk file types in the current diff:
- Authentication/authorization files (auth, login, session, token, permission)
- Database migrations (migrate, schema, alembic, flyway)
- Configuration files (config, settings, env, infrastructure)
- Dependency files (requirements.txt, package.json, go.mod, Gemfile, build.gradle)
- API contracts (openapi, swagger, proto, graphql schema)
- Infrastructure (terraform, cloudformation, kubernetes, helm, dockerfile)
4. **Change magnitude**: Assess the size and spread of changes -- number of files, lines changed, number of distinct directories affected.
5. **Pattern similarity**: Does the current change resemble (in nature, scope, or affected area) changes that preceded past incidents?
## Step 5: Assign Risk Score
Based on all the data gathered, assign a risk score from 0 to 5:
- **0** -- No risk signals at all. Pure documentation, comments, or whitespace.
- **1** -- Trivial changes with no incident correlation. Test cleanup, minor refactors, no structural risk signals.
- **2** -- Some structural signals (config changes, dependency updates) or recent incidents exist, but no correlation with current changes.
- **3** -- Moderate risk. Touching areas related to recent incidents, or high-risk file types (auth, migrations, infra) with no active incidents.
- **4** -- High risk. Active incidents on the service AND changes correlate with incident-affected areas, OR large changes to critical paths with recent incident history.
- **5** -- Critical. Active P1/P2 incident AND current changes directly touch the code involved in the incident.
**Noisy alert adjustment**: Before scoring, check if incident volume is dominated by a single repeating alert title (e.g. 95 out of 100 incidents are "heap-memory-usage"). If so, call that out explicitly in the Risk Factors section and weight those incidents lower than diverse incidents across multiple alert types. The raw incident count alone is misleading in this case.
Build the score bar using filled and empty blocks. For score N, use N filled blocks (█) and (5-N) empty blocks (░):
- 0/5: `░░░░░`
- 1/5: `█░░░░`
- 2/5: `██░░░`
- 3/5: `███░░`
- 4/5: `████░`
- 5/5: `█████`
## Step 6: Present Risk Assessment
Output a compact, structured risk assessment. Be concise -- one line per finding, no filler. Use this format exactly:
```
PRE-COMMIT RISK ASSESSMENT
Service: <service-name> (<service-id>) | Changes: <N> files (+<additions>, -<deletions>)
RISK SCORE: <N>/5 [<LEVEL>] <score-bar>
Active incidents: <"None" or one-line summary per incident>
Incident history (90d): <count> incidents (<"partial: oldest covered is <date>" if capped at 1000>). <one-line summary of severity, recency, patterns>
CHANGE ANALYSIS
- <file-or-group> -- <what changed, one line>
- <file-or-group> -- <what changed, one line>
- Structural risk signals: <"None" or list>
- Incident correlation: <"None" or one-line description of correlation found>
RISK FACTORS
<numbered list, one line each. If none, say "No significant risk factors identified.">
RECOMMENDATION
<one to two sentences. Match the tone to the score level.>
```
Where `<LEVEL>` corresponds to the score:
- 0-1: `LOW`
- 2: `MODERATE`
- 3: `ELEVATED`
- 4: `HIGH`
- 5: `CRITICAL`
Guidelines:
- Be concise. Each bullet should be one line. Do not repeat information across sections.
- Do not pad findings. If incident history is sparse, say so briefly. If there are no correlations, say "None".
- Do not invent risk factors that are not supported by the data gathered.
- If there are active incidents that relate to the areas being changed, this is the most critical finding -- call it out and recommend coordinating with incident responders.
- For scores 0-2, the recommendation can be a single sentence.
- For scores 3+, include specific actionable guidance.

