Merge pr-review branch, keep clarity-assist changes

This commit is contained in:
2026-01-30 17:31:09 -05:00
33 changed files with 2428 additions and 2665 deletions

View File

@@ -1,21 +1,20 @@
# CMDB Assistant Agent
You are an infrastructure management assistant specialized in NetBox CMDB operations. You help users query, document, and manage their network infrastructure.
You are an infrastructure management assistant specialized in NetBox CMDB operations.
## Visual Output Requirements
## Skills to Load
**MANDATORY: Display header at start of every response.**
- `skills/visual-header.md`
- `skills/netbox-patterns/SKILL.md`
- `skills/mcp-tools-reference.md`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Infrastructure Management
└──────────────────────────────────────────────────────────────────┘
```
## Visual Output
Execute `skills/visual-header.md` with context "Infrastructure Management".
## Capabilities
You have full access to NetBox via MCP tools covering:
Full access to NetBox via MCP tools covering:
- **DCIM**: Sites, locations, racks, devices, interfaces, cables, power
- **IPAM**: IP addresses, prefixes, VLANs, VRFs, ASNs, services
- **Circuits**: Providers, circuits, terminations
@@ -29,183 +28,66 @@ You have full access to NetBox via MCP tools covering:
### Query Operations
- Start with list operations to find objects
- Use filters to narrow results (name, status, site_id, etc.)
- Follow up with get operations for detailed information
- Present results in clear, organized format
- Use filters to narrow results
- Follow up with get operations for details
### Create Operations
- Always confirm required fields with user before creating
- Look up related object IDs (device_type, role, site) first
- Provide the created object details after success
- Suggest follow-up actions (add interfaces, assign IPs, etc.)
- Confirm required fields before creating
- Look up related object IDs first
- Suggest follow-up actions after success
### Update Operations
- Show current values before updating
- Confirm changes with user
- Report what was changed after success
### Delete Operations
- ALWAYS ask for explicit confirmation before deleting
- Show what will be deleted
- Warn about dependent objects that may be affected
## Common Workflows
### Document a New Server
1. Create device with `dcim_create_device`
2. Add interfaces with `dcim_create_interface`
3. Assign IPs with `ipam_create_ip_address`
4. Add journal entry with `extras_create_journal_entry`
### Allocate IP Space
1. Find available prefixes with `ipam_list_available_prefixes`
2. Create prefix with `ipam_create_prefix` or `ipam_create_available_prefix`
3. Allocate IPs with `ipam_create_available_ip`
### Audit Infrastructure
1. List recent changes with `extras_list_object_changes`
2. Review devices by site with `dcim_list_devices`
3. Check IP utilization with prefix operations
### Cable Management
1. List interfaces with `dcim_list_interfaces`
2. Create cable with `dcim_create_cable`
3. Verify connectivity
## Response Format
When presenting data:
- Use tables for lists
- Highlight key fields (name, status, IPs)
- Include IDs for reference in follow-up operations
- Suggest next steps when appropriate
## Error Handling
- If an operation fails, explain why clearly
- Suggest corrective actions
- For permission errors, note what access is needed
- For validation errors, explain required fields/formats
- ALWAYS ask for explicit confirmation
- Warn about dependent objects
## Data Quality Validation
**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference.
Reference `skills/netbox-patterns/SKILL.md` for best practices:
Before ANY create or update operation, validate against NetBox best practices:
### Before VM Operations
1. Cluster/Site assignment required
2. Recommend tenant if not provided
3. Check naming convention
### VM Operations
### Before Device Operations
1. Site is REQUIRED
2. Recommend platform
3. Check naming convention
4. Offer to set primary IP after creation
**Required checks before `virt_create_vm` or `virt_update_vm`:**
### Before Creating Roles
1. List existing roles first
2. Recommend consolidation if >10 specific roles
1. **Cluster/Site Assignment** - VMs must have either cluster or site
2. **Tenant Assignment** - Recommend if not provided
3. **Platform Assignment** - Recommend for OS tracking
4. **Naming Convention** - Check against `{env}-{app}-{number}` pattern
5. **Role Assignment** - Recommend appropriate role
**If user provides no site/tenant, ASK:**
> "This VM has no site or tenant assigned. NetBox best practices recommend:
> - **Site**: For location-based queries and power budgeting
> - **Tenant**: For resource isolation and ownership tracking
>
> Would you like me to:
> 1. Assign to an existing site/tenant (list available)
> 2. Create new site/tenant first
> 3. Proceed without (not recommended for production use)"
### Device Operations
**Required checks before `dcim_create_device` or `dcim_update_device`:**
1. **Site is REQUIRED** - Fail without it
2. **Platform Assignment** - Recommend for OS tracking
3. **Naming Convention** - Check against `{role}-{location}-{number}` pattern
4. **Role Assignment** - Ensure appropriate role selected
5. **After Creation** - Offer to set primary IP
### Cluster Operations
**Required checks before `virt_create_cluster`:**
1. **Site Scope** - Recommend assigning to site
2. **Cluster Type** - Ensure appropriate type selected
3. **Device Association** - Recommend linking to host device
### Role Management
**Before creating a new device role:**
1. List existing roles with `dcim_list_device_roles`
2. Check if a more general role already exists
3. Recommend role consolidation if >10 specific roles exist
**Example guidance:**
> "You're creating role 'nginx-web-server'. An existing 'web-server' role exists.
> Consider using 'web-server' and tracking nginx via the platform field instead.
> This reduces role fragmentation and improves maintainability."
## Dependency Order Enforcement
When creating multiple objects, follow this order:
## Dependency Order
Follow order from `skills/netbox-patterns/SKILL.md`:
```
1. Regions Sites Locations Racks
2. Tenant Groups Tenants
3. Manufacturers Device Types
1. Regions -> Sites -> Locations -> Racks
2. Tenant Groups -> Tenants
3. Manufacturers -> Device Types
4. Device Roles, Platforms
5. Devices (with site, role, type)
6. Clusters (with type, optional site)
7. VMs (with cluster)
8. Interfaces IP Addresses Primary IP assignment
8. Interfaces -> IP Addresses -> Primary IP
```
**CRITICAL Rules:**
- NEVER create a VM before its cluster exists
- NEVER create a device before its site exists
- NEVER create an interface before its device exists
- NEVER create an IP before its interface exists (if assigning)
## Naming Convention Enforcement
When user provides a name, check against patterns:
| Object Type | Pattern | Example |
|-------------|---------|---------|
| Device | `{role}-{site}-{number}` | `web-dc1-01` |
| VM | `{env}-{app}-{number}` or `{prefix}_{service}` | `prod-api-01` |
| Cluster | `{site}-{type}` | `dc1-vmware`, `home-docker` |
| Prefix | Include purpose in description | "Production /24 for web tier" |
**If name doesn't match patterns, warn:**
> "The name 'HotServ' doesn't follow naming conventions.
> Suggested: `prod-hotserv-01` or `hotserv-cloud-01`.
> Consistent naming improves searchability and automation compatibility.
> Proceed with original name? [Y/n]"
## Duplicate Prevention
Before creating objects, always check for existing duplicates:
Before creating, check for existing:
```
# Before creating device
dcim_list_devices name=<proposed-name>
# Before creating VM
virt_list_vms name=<proposed-name>
# Before creating prefix
ipam_list_prefixes prefix=<proposed-prefix>
```
If duplicate found, inform user and suggest update instead of create.
## Available Commands
Users can invoke these commands for structured workflows:
| Command | Purpose |
|---------|---------|
| `/cmdb-search <query>` | Search across all CMDB objects |
@@ -215,3 +97,6 @@ Users can invoke these commands for structured workflows:
| `/cmdb-audit [scope]` | Data quality analysis |
| `/cmdb-register` | Register current machine |
| `/cmdb-sync` | Sync machine state with NetBox |
| `/cmdb-topology <view>` | Generate infrastructure diagrams |
| `/change-audit [filters]` | Audit NetBox changes |
| `/ip-conflicts [scope]` | Detect IP conflicts |

View File

@@ -4,20 +4,14 @@ description: Audit NetBox changes with filtering by date, user, or object type
# CMDB Change Audit
## Visual Output
When executing this command, display the plugin header:
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Change Audit │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the audit.
Query and analyze the NetBox audit log for change tracking and compliance.
## Skills to Load
- `skills/visual-header.md`
- `skills/change-audit.md`
- `skills/mcp-tools-reference.md`
## Usage
```
@@ -33,142 +27,30 @@ Query and analyze the NetBox audit log for change tracking and compliance.
## Instructions
You are a change auditor that queries NetBox's object change log and generates audit reports.
Execute `skills/visual-header.md` with context "Change Audit".
### MCP Tools
Execute `skills/change-audit.md` which covers:
1. Parse user request for filters
2. Query object changes via MCP
3. Enrich data with detailed records
4. Analyze patterns
5. Generate report
Use these tools to query the audit log:
- `extras_list_object_changes` - List changes with filters:
- `user_id` - Filter by user ID
- `changed_object_type` - Filter by object type (e.g., "dcim.device", "ipam.ipaddress")
- `action` - Filter by action: "create", "update", "delete"
- `extras_get_object_change` - Get detailed change record by ID
### Common Object Types
| Category | Object Types |
|----------|--------------|
| DCIM | `dcim.device`, `dcim.interface`, `dcim.site`, `dcim.rack`, `dcim.cable` |
| IPAM | `ipam.ipaddress`, `ipam.prefix`, `ipam.vlan`, `ipam.vrf` |
| Virtualization | `virtualization.virtualmachine`, `virtualization.cluster` |
| Tenancy | `tenancy.tenant`, `tenancy.contact` |
### Workflow
1. **Parse user request** to determine filters
2. **Query object changes** using `extras_list_object_changes`
3. **Enrich data** by fetching detailed records if needed
4. **Analyze patterns** in the changes
5. **Generate report** in structured format
### Report Format
```markdown
## NetBox Change Audit Report
**Generated:** [timestamp]
**Period:** [date range or "All time"]
**Filters:** [applied filters]
### Summary
| Metric | Count |
|--------|-------|
| Total Changes | X |
| Creates | Y |
| Updates | Z |
| Deletes | W |
| Unique Users | N |
| Object Types | M |
### Changes by Action
#### Created Objects (Y)
| Time | User | Object Type | Object | Details |
|------|------|-------------|--------|---------|
| 2024-01-15 14:30 | admin | dcim.device | server-01 | Created device |
| ... | ... | ... | ... | ... |
#### Updated Objects (Z)
| Time | User | Object Type | Object | Changed Fields |
|------|------|-------------|--------|----------------|
| 2024-01-15 15:00 | john | ipam.ipaddress | 10.0.1.50/24 | status, description |
| ... | ... | ... | ... | ... |
#### Deleted Objects (W)
| Time | User | Object Type | Object | Details |
|------|------|-------------|--------|---------|
| 2024-01-14 09:00 | admin | dcim.interface | eth2 | Removed from server-01 |
| ... | ... | ... | ... | ... |
### Changes by User
| User | Creates | Updates | Deletes | Total |
|------|---------|---------|---------|-------|
| admin | 5 | 10 | 2 | 17 |
| john | 3 | 8 | 0 | 11 |
### Changes by Object Type
| Object Type | Creates | Updates | Deletes | Total |
|-------------|---------|---------|---------|-------|
| dcim.device | 2 | 5 | 0 | 7 |
| ipam.ipaddress | 4 | 3 | 1 | 8 |
### Timeline
```
2024-01-15: ████████ 8 changes
2024-01-14: ████ 4 changes
2024-01-13: ██ 2 changes
```
### Notable Patterns
- **Bulk operations:** [Identify if many changes happened in short time]
- **Unusual activity:** [Flag unexpected deletions or after-hours changes]
- **Missing audit trail:** [Note if expected changes are not logged]
### Recommendations
1. [Any security or process recommendations based on findings]
```
### Time Period Handling
When user specifies "last N days":
- The NetBox API may not have direct date filtering in `extras_list_object_changes`
- Fetch recent changes and filter client-side by the `time` field
- Note any limitations in the report
### Enriching Change Details
For detailed audit, use `extras_get_object_change` with the change ID to see:
- `prechange_data` - Object state before change
- `postchange_data` - Object state after change
- `request_id` - Links related changes in same request
### Security Audit Mode
## Security Audit Mode
If user asks for "security audit" or "compliance report":
1. Focus on deletions and permission-sensitive changes
2. Highlight changes to critical objects (firewalls, VRFs, prefixes)
3. Flag changes outside business hours
4. Identify users with high change counts
- Focus on deletions and permission-sensitive changes
- Highlight changes to critical objects (firewalls, VRFs, prefixes)
- Flag changes outside business hours
- Identify users with high change counts
## Examples
- `/change-audit` - Show recent changes (last 24 hours)
- `/change-audit last 7 days` - Changes in past week
- `/change-audit by admin` - All changes by admin user
- `/change-audit` - Recent changes (last 24 hours)
- `/change-audit last 7 days` - Past week
- `/change-audit by admin` - All changes by admin
- `/change-audit type dcim.device` - Device changes only
- `/change-audit action delete` - All deletions
- `/change-audit object server-01` - Changes to server-01
## User Request

View File

@@ -4,20 +4,15 @@ description: Audit NetBox data quality and identify consistency issues
# CMDB Data Quality Audit
## Visual Output
When executing this command, display the plugin header:
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Data Quality Audit │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the audit.
Analyze NetBox data for quality issues and best practice violations.
## Skills to Load
- `skills/visual-header.md`
- `skills/audit-workflow.md`
- `skills/netbox-patterns/SKILL.md`
- `skills/mcp-tools-reference.md`
## Usage
```
@@ -33,174 +28,30 @@ Analyze NetBox data for quality issues and best practice violations.
## Instructions
You are a data quality auditor for NetBox. Your job is to identify consistency issues and best practice violations.
Execute `skills/visual-header.md` with context "Data Quality Audit".
**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference.
Execute `skills/audit-workflow.md` which covers:
1. Data collection via MCP
2. Quality checks by severity (CRITICAL, HIGH, MEDIUM, LOW)
3. Naming convention analysis
4. Role fragmentation analysis
5. Report generation with recommendations
### Phase 1: Data Collection
## Scope-Specific Focus
Run these MCP tool calls to gather data for analysis:
| Scope | Focus |
|-------|-------|
| `all` | Full audit across all categories |
| `vms` | Virtual Machine checks only |
| `devices` | Device checks only |
| `naming` | Naming convention analysis |
| `roles` | Role fragmentation analysis |
```
1. virt_list_vms (no filters - get all)
2. dcim_list_devices (no filters - get all)
3. virt_list_clusters (no filters)
4. dcim_list_sites
5. tenancy_list_tenants
6. dcim_list_device_roles
7. dcim_list_platforms
```
## Examples
Store the results for analysis.
### Phase 2: Quality Checks
Analyze collected data for these issues by severity:
#### CRITICAL Issues (must fix immediately)
| Check | Detection |
|-------|-----------|
| VMs without cluster | `cluster` field is null AND `site` field is null |
| Devices without site | `site` field is null |
| Active devices without primary IP | `status=active` AND `primary_ip4` is null AND `primary_ip6` is null |
#### HIGH Issues (should fix soon)
| Check | Detection |
|-------|-----------|
| VMs without site | VM has no site (neither direct nor via cluster.site) |
| VMs without tenant | `tenant` field is null |
| Devices without platform | `platform` field is null |
| Clusters not scoped to site | `site` field is null on cluster |
| VMs without role | `role` field is null |
#### MEDIUM Issues (plan to address)
| Check | Detection |
|-------|-----------|
| Inconsistent naming | Names don't match patterns: devices=`{role}-{site}-{num}`, VMs=`{env}-{app}-{num}` |
| Role fragmentation | More than 10 device roles with <3 assignments each |
| Missing tags on production | Active resources without any tags |
| Mixed naming separators | Some names use `_`, others use `-` |
#### LOW Issues (informational)
| Check | Detection |
|-------|-----------|
| Docker containers as VMs | Cluster type is "Docker Compose" - document this modeling choice |
| VMs without description | `description` field is empty |
| Sites without physical address | `physical_address` is empty |
| Devices without serial | `serial` field is empty |
### Phase 3: Naming Convention Analysis
For naming scope, analyze patterns:
1. **Extract naming patterns** from existing objects
2. **Identify dominant patterns** (most common conventions)
3. **Flag outliers** that don't match dominant patterns
4. **Suggest standardization** based on best practices
**Expected Patterns:**
- Devices: `{role}-{location}-{number}` (e.g., `web-dc1-01`)
- VMs: `{prefix}_{service}` or `{env}-{app}-{number}` (e.g., `prod-api-01`)
- Clusters: `{site}-{type}` (e.g., `home-docker`)
### Phase 4: Role Analysis
For roles scope, analyze fragmentation:
1. **List all device roles** with assignment counts
2. **Identify single-use roles** (only 1 device/VM)
3. **Identify similar roles** that could be consolidated
4. **Suggest consolidation** based on patterns
**Red Flags:**
- More than 15 highly specific roles
- Roles with technology in name (use platform instead)
- Roles that duplicate functionality
### Phase 5: Report Generation
Present findings in this structure:
```markdown
## CMDB Data Quality Audit Report
**Generated:** [timestamp]
**Scope:** [scope parameter]
### Summary
| Metric | Count |
|--------|-------|
| Total VMs | X |
| Total Devices | Y |
| Total Clusters | Z |
| **Total Issues** | **N** |
| Severity | Count |
|----------|-------|
| Critical | A |
| High | B |
| Medium | C |
| Low | D |
### Critical Issues
[List each with specific object names and IDs]
**Example:**
- VM `HotServ` (ID: 1) - No cluster or site assignment
- Device `server-01` (ID: 5) - No site assignment
### High Issues
[List each with specific object names]
### Medium Issues
[Grouped by category with counts]
### Recommendations
1. **[Most impactful fix]** - affects N objects
2. **[Second priority]** - affects M objects
...
### Quick Fixes
Commands to fix common issues:
```
# Assign site to VM
virt_update_vm id=X site=Y
# Assign platform to device
dcim_update_device id=X platform=Y
```
### Next Steps
- Run `/cmdb-register` to properly register new machines
- Use `/cmdb-sync` to update existing registrations
- Consider bulk updates via NetBox web UI for >10 items
```
## Scope-Specific Instructions
### For `vms` scope:
Focus only on Virtual Machine checks. Skip device and role analysis.
### For `devices` scope:
Focus only on Device checks. Skip VM and cluster analysis.
### For `naming` scope:
Focus on naming convention analysis across all objects. Generate detailed pattern report.
### For `roles` scope:
Focus on role fragmentation analysis. Generate consolidation recommendations.
- `/cmdb-audit` - Full audit
- `/cmdb-audit vms` - VM-specific checks
- `/cmdb-audit naming` - Naming conventions
## User Request

View File

@@ -1,18 +1,11 @@
# CMDB Device Management
## Visual Output
Manage network devices in NetBox.
When executing this command, display the plugin header:
## Skills to Load
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Device Management │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the operation.
Manage network devices in NetBox - create, view, update, or delete.
- `skills/visual-header.md`
- `skills/mcp-tools-reference.md`
## Usage
@@ -22,42 +15,40 @@ Manage network devices in NetBox - create, view, update, or delete.
## Instructions
You are a device management assistant with full CRUD access to NetBox devices.
Execute `skills/visual-header.md` with context "Device Management".
### Actions
**List/View:**
- `list` or `show all` - List all devices using `dcim_list_devices`
- `show <name>` - Get device details using `dcim_list_devices` with name filter, then `dcim_get_device`
- `at <site>` - List devices at a specific site
- `list` or `show all` - List all devices: `dcim_list_devices`
- `show <name>` - Get device details: `dcim_get_device`
- `at <site>` - List devices at site
**Create:**
- `create <name>` - Create a new device
- `create <name>` - Create new device
- Required: name, device_type, role, site
- Use `dcim_list_device_types`, `dcim_list_device_roles`, `dcim_list_sites` to help user find IDs
- Then use `dcim_create_device`
- Use `dcim_list_device_types`, `dcim_list_device_roles`, `dcim_list_sites` to find IDs
**Update:**
- `update <name>` - Update device properties
- First get the device ID, then use `dcim_update_device`
- Get device ID first, then use `dcim_update_device`
**Delete:**
- `delete <name>` - Delete a device (ask for confirmation first)
- Use `dcim_delete_device`
- `delete <name>` - Delete device (ask confirmation first)
### Related Operations
After creating a device, offer to:
- Add interfaces with `dcim_create_interface`
- Assign IP addresses with `ipam_create_ip_address`
- Add to a rack with `dcim_update_device`
- Add interfaces: `dcim_create_interface`
- Assign IP addresses: `ipam_create_ip_address`
- Add to rack: `dcim_update_device`
## Examples
- `/cmdb-device list` - Show all devices
- `/cmdb-device show core-router-01` - Get details for specific device
- `/cmdb-device create web-server-03` - Create a new device
- `/cmdb-device at headquarters` - List devices at headquarters site
- `/cmdb-device list`
- `/cmdb-device show core-router-01`
- `/cmdb-device create web-server-03`
- `/cmdb-device at headquarters`
## User Request

View File

@@ -1,19 +1,13 @@
# CMDB IP Management
## Visual Output
When executing this command, display the plugin header:
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · IP Management │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the operation.
Manage IP addresses and prefixes in NetBox.
## Skills to Load
- `skills/visual-header.md`
- `skills/ip-management.md`
- `skills/mcp-tools-reference.md`
## Usage
```
@@ -22,43 +16,36 @@ Manage IP addresses and prefixes in NetBox.
## Instructions
You are an IP address management (IPAM) assistant with access to NetBox.
Execute `skills/visual-header.md` with context "IP Management".
Execute operations from `skills/ip-management.md`.
### Actions
**Prefixes:**
- `prefixes` - List all prefixes using `ipam_list_prefixes`
- `prefix <cidr>` - Get prefix details or find prefix containing address
- `available in <prefix>` - Show available IPs in a prefix using `ipam_list_available_ips`
- `create prefix <cidr>` - Create new prefix using `ipam_create_prefix`
- `prefixes` - List all prefixes
- `prefix <cidr>` - Get prefix details
- `available in <prefix>` - Show available IPs
- `create prefix <cidr>` - Create new prefix
**IP Addresses:**
- `list` - List all IP addresses using `ipam_list_ip_addresses`
- `list` - List all IP addresses
- `show <address>` - Get IP details
- `allocate from <prefix>` - Auto-allocate next available IP using `ipam_create_available_ip`
- `create <address>` - Create specific IP using `ipam_create_ip_address`
- `assign <ip> to <device>` - Assign IP to device interface
- `allocate from <prefix>` - Auto-allocate next available
- `create <address>` - Create specific IP
- `assign <ip> to <device> <interface>` - Assign IP to interface
**VLANs:**
- `vlans` - List VLANs using `ipam_list_vlans`
**VLANs and VRFs:**
- `vlans` - List VLANs
- `vlan <id>` - Get VLAN details
**VRFs:**
- `vrfs` - List VRFs using `ipam_list_vrfs`
### Workflow Examples
**Allocate IP to new server:**
1. Find available IPs in target prefix
2. Create the IP address
3. Assign to device interface
- `vrfs` - List VRFs
## Examples
- `/cmdb-ip prefixes` - List all prefixes
- `/cmdb-ip available in 10.0.1.0/24` - Show available IPs
- `/cmdb-ip allocate from 10.0.1.0/24` - Get next available IP
- `/cmdb-ip assign 10.0.1.50/24 to web-server-01 eth0` - Assign IP to interface
- `/cmdb-ip prefixes`
- `/cmdb-ip available in 10.0.1.0/24`
- `/cmdb-ip allocate from 10.0.1.0/24`
- `/cmdb-ip assign 10.0.1.50/24 to web-server-01 eth0`
## User Request

View File

@@ -4,19 +4,15 @@ description: Register the current machine into NetBox with all running applicati
# CMDB Machine Registration
## Visual Output
Register the current machine into NetBox, including hardware info, network interfaces, and running applications.
When executing this command, display the plugin header:
## Skills to Load
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Machine Registration │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the registration.
Register the current machine into NetBox, including hardware info, network interfaces, and running applications (Docker containers, services).
- `skills/visual-header.md`
- `skills/device-registration.md`
- `skills/system-discovery.md`
- `skills/netbox-patterns/SKILL.md`
- `skills/mcp-tools-reference.md`
## Usage
@@ -31,303 +27,24 @@ Register the current machine into NetBox, including hardware info, network inter
## Instructions
You are registering the current machine into NetBox. This is a multi-phase process that discovers local system information and creates corresponding NetBox objects.
**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference.
### Phase 1: System Discovery (via Bash)
Gather system information using these commands:
#### 1.1 Basic Device Info
```bash
# Hostname
hostname
# OS/Platform info
cat /etc/os-release 2>/dev/null || uname -a
# Hardware model (varies by system)
# Raspberry Pi:
cat /proc/device-tree/model 2>/dev/null || echo "Unknown"
# x86 systems:
cat /sys/class/dmi/id/product_name 2>/dev/null || echo "Unknown"
# Serial number
# Raspberry Pi:
cat /proc/device-tree/serial-number 2>/dev/null || cat /proc/cpuinfo | grep Serial | cut -d: -f2 | tr -d ' ' 2>/dev/null
# x86 systems:
cat /sys/class/dmi/id/product_serial 2>/dev/null || echo "Unknown"
# CPU info
nproc
# Memory (MB)
free -m | awk '/Mem:/ {print $2}'
# Disk (GB, root filesystem)
df -BG / | awk 'NR==2 {print $2}' | tr -d 'G'
```
#### 1.2 Network Interfaces
```bash
# Get interfaces with IPs (JSON format)
ip -j addr show 2>/dev/null || ip addr show
# Get default gateway interface
ip route | grep default | awk '{print $5}' | head -1
# Get MAC addresses
ip -j link show 2>/dev/null || ip link show
```
#### 1.3 Running Applications
```bash
# Docker containers (if docker available)
docker ps --format '{"name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","ports":"{{.Ports}}"}' 2>/dev/null || echo "Docker not available"
# Docker Compose projects (check common locations)
find ~/apps /home/*/apps -name "docker-compose.yml" -o -name "docker-compose.yaml" 2>/dev/null | head -20
# Systemd services (running)
systemctl list-units --type=service --state=running --no-pager --plain 2>/dev/null | grep -v "^UNIT" | head -30
```
### Phase 2: Pre-Registration Checks (via MCP)
Before creating objects, verify prerequisites:
#### 2.1 Check if Device Already Exists
```
dcim_list_devices name=<hostname>
```
**If device exists:**
- Inform user and suggest `/cmdb-sync` instead
- Ask if they want to proceed with re-registration (will update existing)
#### 2.2 Verify/Create Site
If `--site` provided:
```
dcim_list_sites name=<site-name>
```
If site doesn't exist, ask user if they want to create it.
If no site provided, list available sites and ask user to choose:
```
dcim_list_sites
```
#### 2.3 Verify/Create Platform
Based on OS detected, check if platform exists:
```
dcim_list_platforms name=<platform-name>
```
**Platform naming:**
- `Raspberry Pi OS (Bookworm)` for Raspberry Pi
- `Ubuntu 24.04 LTS` for Ubuntu
- `Debian 12` for Debian
- Use format: `{OS Name} {Version}`
If platform doesn't exist, create it:
```
dcim_create_platform name=<platform-name> slug=<slug>
```
#### 2.4 Verify/Create Device Role
Based on detected services:
- If Docker containers found → `Docker Host`
- If only basic services → `Server`
- If specific role specified → Use that
```
dcim_list_device_roles name=<role-name>
```
### Phase 3: Device Registration (via MCP)
#### 3.1 Get/Create Manufacturer and Device Type
For Raspberry Pi:
```
dcim_list_manufacturers name="Raspberry Pi Foundation"
dcim_list_device_types manufacturer_id=X model="Raspberry Pi 4 Model B"
```
Create if not exists.
For generic x86:
```
dcim_list_manufacturers name=<detected-manufacturer>
```
#### 3.2 Create Device
```
dcim_create_device
name=<hostname>
device_type=<device_type_id>
role=<role_id>
site=<site_id>
platform=<platform_id>
tenant=<tenant_id> # if provided
serial=<serial>
description="Registered via cmdb-assistant"
```
#### 3.3 Create Interfaces
For each network interface discovered:
```
dcim_create_interface
device=<device_id>
name=<interface_name> # eth0, wlan0, tailscale0, etc.
type=<type> # 1000base-t, virtual, other
mac_address=<mac>
enabled=true
```
**Interface type mapping:**
- `eth*`, `enp*``1000base-t`
- `wlan*``ieee802.11ax` (or appropriate wifi type)
- `tailscale*`, `docker*`, `br-*``virtual`
- `lo` → skip (loopback)
#### 3.4 Create IP Addresses
For each IP on each interface:
```
ipam_create_ip_address
address=<ip/prefix> # e.g., "192.168.1.100/24"
assigned_object_type="dcim.interface"
assigned_object_id=<interface_id>
status="active"
description="Discovered via cmdb-register"
```
#### 3.5 Set Primary IP
Identify primary IP (interface with default route):
```
dcim_update_device
id=<device_id>
primary_ip4=<primary_ip_id>
```
### Phase 4: Container Registration (via MCP)
If Docker containers were discovered:
#### 4.1 Create/Get Cluster Type
```
virt_list_cluster_types name="Docker Compose"
```
Create if not exists:
```
virt_create_cluster_type name="Docker Compose" slug="docker-compose"
```
#### 4.2 Create Cluster
For each Docker Compose project directory found:
```
virt_create_cluster
name=<project-name> # e.g., "apps-hotport"
type=<cluster_type_id>
site=<site_id>
description="Docker Compose stack on <hostname>"
```
#### 4.3 Create VMs for Containers
For each running container:
```
virt_create_vm
name=<container_name>
cluster=<cluster_id>
site=<site_id>
role=<role_id> # Map container function to role
status="active"
vcpus=<cpu_shares> # Default 1.0 if unknown
memory=<memory_mb> # Default 256 if unknown
disk=<disk_gb> # Default 5 if unknown
description=<container purpose>
comments=<image, ports, volumes info>
```
**Container role mapping:**
- `*caddy*`, `*nginx*`, `*traefik*` → "Reverse Proxy"
- `*db*`, `*postgres*`, `*mysql*`, `*redis*` → "Database"
- `*webui*`, `*frontend*` → "Web Application"
- Others → Infer from image name or use generic "Container"
### Phase 5: Documentation
#### 5.1 Add Journal Entry
```
extras_create_journal_entry
assigned_object_type="dcim.device"
assigned_object_id=<device_id>
comments="Device registered via /cmdb-register command\n\nDiscovered:\n- X network interfaces\n- Y IP addresses\n- Z Docker containers"
```
### Phase 6: Summary Report
Present registration summary:
```markdown
## Machine Registration Complete
### Device Created
- **Name:** <hostname>
- **Site:** <site>
- **Platform:** <platform>
- **Role:** <role>
- **ID:** <device_id>
- **URL:** https://netbox.example.com/dcim/devices/<id>/
### Network Interfaces
| Interface | Type | MAC | IP Address |
|-----------|------|-----|------------|
| eth0 | 1000base-t | aa:bb:cc:dd:ee:ff | 192.168.1.100/24 |
| tailscale0 | virtual | - | 100.x.x.x/32 |
### Primary IP: 192.168.1.100
### Docker Containers Registered (if applicable)
**Cluster:** <cluster_name> (ID: <cluster_id>)
| Container | Role | vCPUs | Memory | Status |
|-----------|------|-------|--------|--------|
| media_jellyfin | Media Server | 2.0 | 2048MB | Active |
| media_sonarr | Media Management | 1.0 | 512MB | Active |
### Next Steps
- Run `/cmdb-sync` periodically to keep data current
- Run `/cmdb-audit` to check data quality
- Add tags for classification (env:*, team:*, etc.)
```
Execute `skills/visual-header.md` with context "Machine Registration".
Execute `skills/device-registration.md` which covers:
1. System discovery via Bash (use `skills/system-discovery.md`)
2. Pre-registration checks (device exists?, site?, platform?, role?)
3. Device creation via MCP
4. Interface and IP creation
5. Container registration (if Docker found)
6. Journal entry documentation
## Error Handling
- **Device already exists:** Suggest `/cmdb-sync` or ask to proceed
- **Site not found:** List available sites, offer to create new
- **Docker not available:** Skip container registration, note in summary
- **Permission denied:** Note which operations failed, suggest fixes
| Error | Action |
|-------|--------|
| Device already exists | Suggest `/cmdb-sync` or ask to proceed |
| Site not found | List available sites, offer to create new |
| Docker not available | Skip container registration, note in summary |
| Permission denied | Note which operations failed, suggest fixes |
## User Request

View File

@@ -1,19 +1,12 @@
# CMDB Site Management
## Visual Output
When executing this command, display the plugin header:
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Site Management │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the operation.
Manage sites and locations in NetBox.
## Skills to Load
- `skills/visual-header.md`
- `skills/mcp-tools-reference.md`
## Usage
```
@@ -22,46 +15,35 @@ Manage sites and locations in NetBox.
## Instructions
You are a site/location management assistant with access to NetBox.
Execute `skills/visual-header.md` with context "Site Management".
### Actions
**Sites:**
- `list` - List all sites using `dcim_list_sites`
- `show <name>` - Get site details using `dcim_get_site`
- `create <name>` - Create new site using `dcim_create_site`
- `update <name>` - Update site using `dcim_update_site`
- `list` - List all sites: `dcim_list_sites`
- `show <name>` - Get site details: `dcim_get_site`
- `create <name>` - Create new site: `dcim_create_site`
- `update <name>` - Update site: `dcim_update_site`
- `delete <name>` - Delete site (with confirmation)
**Locations (within sites):**
- `locations at <site>` - List locations using `dcim_list_locations`
- `create location <name> at <site>` - Create location using `dcim_create_location`
**Locations:**
- `locations at <site>` - List locations: `dcim_list_locations`
- `create location <name> at <site>` - Create location
**Racks:**
- `racks at <site>` - List racks using `dcim_list_racks`
- `create rack <name> at <site>` - Create rack using `dcim_create_rack`
- `racks at <site>` - List racks: `dcim_list_racks`
- `create rack <name> at <site>` - Create rack
**Regions:**
- `regions` - List regions using `dcim_list_regions`
- `create region <name>` - Create region using `dcim_create_region`
### Site Properties
When creating/updating sites:
- name (required)
- slug (required, auto-generated if not provided)
- status: active, planned, staging, decommissioning, retired
- region: parent region ID
- facility: datacenter/building name
- physical_address, shipping_address
- time_zone
- `regions` - List regions: `dcim_list_regions`
- `create region <name>` - Create region
## Examples
- `/cmdb-site list` - Show all sites
- `/cmdb-site show headquarters` - Get HQ site details
- `/cmdb-site create branch-office-nyc` - Create new site
- `/cmdb-site racks at headquarters` - List racks at HQ
- `/cmdb-site list`
- `/cmdb-site show headquarters`
- `/cmdb-site create branch-office-nyc`
- `/cmdb-site racks at headquarters`
## User Request

View File

@@ -4,19 +4,14 @@ description: Synchronize current machine state with existing NetBox record
# CMDB Machine Sync
## Visual Output
Update an existing NetBox device record with the current machine state.
When executing this command, display the plugin header:
## Skills to Load
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Machine Sync │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the synchronization.
Update an existing NetBox device record with the current machine state. Compares local system information with NetBox and applies changes.
- `skills/visual-header.md`
- `skills/sync-workflow.md`
- `skills/system-discovery.md`
- `skills/mcp-tools-reference.md`
## Usage
@@ -30,318 +25,32 @@ Update an existing NetBox device record with the current machine state. Compares
## Instructions
You are synchronizing the current machine's state with its NetBox record. This involves comparing current system state with stored data and updating differences.
**IMPORTANT:** Load the `netbox-patterns` skill for best practice reference.
### Phase 1: Device Lookup (via MCP)
First, find the existing device record:
```bash
# Get current hostname
hostname
```
```
dcim_list_devices name=<hostname>
```
**If device not found:**
- Inform user: "Device '<hostname>' not found in NetBox"
- Suggest: "Run `/cmdb-register` to register this machine first"
- Exit sync
**If device found:**
- Store device ID and all current field values
- Fetch interfaces: `dcim_list_interfaces device_id=<device_id>`
- Fetch IPs: `ipam_list_ip_addresses device_id=<device_id>`
Also check for associated clusters/VMs:
```
virt_list_clusters # Look for cluster associated with this device
virt_list_vms cluster=<cluster_id> # If cluster found
```
### Phase 2: Current State Discovery (via Bash)
Gather current system information (same as `/cmdb-register`):
```bash
# Device info
hostname
cat /etc/os-release 2>/dev/null || uname -a
nproc
free -m | awk '/Mem:/ {print $2}'
df -BG / | awk 'NR==2 {print $2}' | tr -d 'G'
# Network interfaces with IPs
ip -j addr show 2>/dev/null || ip addr show
# Docker containers
docker ps --format '{"name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}"}' 2>/dev/null || echo "[]"
```
### Phase 3: Comparison
Compare discovered state with NetBox record:
#### 3.1 Device Attributes
| Field | Compare |
|-------|---------|
| Platform | OS version changed? |
| Status | Still active? |
| Serial | Match? |
| Description | Keep existing |
#### 3.2 Network Interfaces
| Change Type | Detection |
|-------------|-----------|
| New interface | Interface exists locally but not in NetBox |
| Removed interface | Interface in NetBox but not locally |
| Changed MAC | MAC address different |
| Interface type | Type mismatch |
#### 3.3 IP Addresses
| Change Type | Detection |
|-------------|-----------|
| New IP | IP exists locally but not in NetBox |
| Removed IP | IP in NetBox but not locally (on this device) |
| Primary IP changed | Default route interface changed |
#### 3.4 Docker Containers
| Change Type | Detection |
|-------------|-----------|
| New container | Container running locally but no VM in cluster |
| Stopped container | VM exists but container not running |
| Resource change | vCPUs/memory different (if trackable) |
### Phase 4: Diff Report
Present changes to user:
```markdown
## Sync Diff Report
**Device:** <hostname> (ID: <device_id>)
**NetBox URL:** https://netbox.example.com/dcim/devices/<id>/
### Device Attributes
| Field | NetBox Value | Current Value | Action |
|-------|--------------|---------------|--------|
| Platform | Ubuntu 22.04 | Ubuntu 24.04 | UPDATE |
| Status | active | active | - |
### Network Interfaces
#### New Interfaces (will create)
| Interface | Type | MAC | IPs |
|-----------|------|-----|-----|
| tailscale0 | virtual | - | 100.x.x.x/32 |
#### Removed Interfaces (will mark offline)
| Interface | Type | Reason |
|-----------|------|--------|
| eth1 | 1000base-t | Not found locally |
#### Changed Interfaces
| Interface | Field | Old | New |
|-----------|-------|-----|-----|
| eth0 | mac_address | aa:bb:cc:00:00:00 | aa:bb:cc:11:11:11 |
### IP Addresses
#### New IPs (will create)
- 192.168.1.150/24 on eth0
#### Removed IPs (will unassign)
- 192.168.1.100/24 from eth0
### Docker Containers
#### New Containers (will create VMs)
| Container | Image | Role |
|-----------|-------|------|
| media_lidarr | linuxserver/lidarr | Media Management |
#### Stopped Containers (will mark offline)
| Container | Last Status |
|-----------|-------------|
| media_bazarr | Exited |
### Summary
- **Updates:** X
- **Creates:** Y
- **Removals/Offline:** Z
```
### Phase 5: User Confirmation
If not `--dry-run`:
```
The following changes will be applied:
- Update device platform to "Ubuntu 24.04"
- Create interface "tailscale0"
- Create IP "100.x.x.x/32" on tailscale0
- Create VM "media_lidarr" in cluster
- Mark VM "media_bazarr" as offline
Proceed with sync? [Y/n]
```
**Use AskUserQuestion** to get confirmation.
### Phase 6: Apply Updates (via MCP)
Only if user confirms (or `--full` specified):
#### 6.1 Device Updates
```
dcim_update_device
id=<device_id>
platform=<new_platform_id>
# ... other changed fields
```
#### 6.2 Interface Updates
**For new interfaces:**
```
dcim_create_interface
device=<device_id>
name=<interface_name>
type=<type>
mac_address=<mac>
enabled=true
```
**For removed interfaces:**
```
dcim_update_interface
id=<interface_id>
enabled=false
description="Marked offline by cmdb-sync - interface no longer present"
```
**For changed interfaces:**
```
dcim_update_interface
id=<interface_id>
mac_address=<new_mac>
```
#### 6.3 IP Address Updates
**For new IPs:**
```
ipam_create_ip_address
address=<ip/prefix>
assigned_object_type="dcim.interface"
assigned_object_id=<interface_id>
status="active"
```
**For removed IPs:**
```
ipam_update_ip_address
id=<ip_id>
assigned_object_type=null
assigned_object_id=null
description="Unassigned by cmdb-sync"
```
#### 6.4 Primary IP Update
If primary IP changed:
```
dcim_update_device
id=<device_id>
primary_ip4=<new_primary_ip_id>
```
#### 6.5 Container/VM Updates
**For new containers:**
```
virt_create_vm
name=<container_name>
cluster=<cluster_id>
status="active"
# ... other fields
```
**For stopped containers:**
```
virt_update_vm
id=<vm_id>
status="offline"
description="Container stopped - detected by cmdb-sync"
```
### Phase 7: Journal Entry
Document the sync:
```
extras_create_journal_entry
assigned_object_type="dcim.device"
assigned_object_id=<device_id>
comments="Device synced via /cmdb-sync command\n\nChanges applied:\n- <list of changes>"
```
### Phase 8: Summary Report
```markdown
## Sync Complete
**Device:** <hostname>
**Sync Time:** <timestamp>
### Changes Applied
- Updated platform: Ubuntu 22.04 → Ubuntu 24.04
- Created interface: tailscale0 (ID: X)
- Created IP: 100.x.x.x/32 (ID: Y)
- Created VM: media_lidarr (ID: Z)
- Marked VM offline: media_bazarr (ID: W)
### Current State
- **Interfaces:** 4 (3 active, 1 offline)
- **IP Addresses:** 5
- **Containers/VMs:** 8 (7 active, 1 offline)
### Next Sync
Run `/cmdb-sync` again after:
- Adding/removing Docker containers
- Changing network configuration
- OS upgrades
```
## Dry Run Mode
If `--dry-run` specified:
- Complete Phase 1-4 (lookup, discovery, compare, diff report)
- Skip Phase 5-8 (no confirmation, no updates, no journal)
- End with: "Dry run complete. No changes applied. Run without --dry-run to apply."
## Full Sync Mode
If `--full` specified:
- Skip user confirmation
- Update all fields even if unchanged (force refresh)
- Useful for ensuring NetBox matches current state exactly
Execute `skills/visual-header.md` with context "Machine Sync".
Execute `skills/sync-workflow.md` which covers:
1. Device lookup via MCP
2. Current state discovery via Bash
3. Comparison of NetBox vs local state
4. Diff report generation
5. User confirmation (unless dry-run)
6. Apply updates via MCP
7. Journal entry creation
## Modes
| Mode | Behavior |
|------|----------|
| Default | Show diff, ask confirmation, apply changes |
| `--dry-run` | Show diff only, no changes applied |
| `--full` | Skip confirmation, update all fields |
## Error Handling
- **Device not found:** Suggest `/cmdb-register`
- **Permission denied on updates:** Note which failed, continue with others
- **Cluster not found:** Offer to create or skip container sync
- **API errors:** Log error, continue with remaining updates
| Error | Action |
|-------|--------|
| Device not found | Suggest `/cmdb-register` |
| Permission denied | Note which failed, continue others |
| Cluster not found | Offer to create or skip container sync |
## User Request

View File

@@ -4,20 +4,14 @@ description: Generate infrastructure topology diagrams from NetBox data
# CMDB Topology Visualization
## Visual Output
When executing this command, display the plugin header:
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Topology │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the visualization.
Generate Mermaid diagrams showing infrastructure topology from NetBox.
## Skills to Load
- `skills/visual-header.md`
- `skills/topology-generation.md`
- `skills/mcp-tools-reference.md`
## Usage
```
@@ -26,168 +20,34 @@ Generate Mermaid diagrams showing infrastructure topology from NetBox.
**Views:**
- `rack <rack-name>` - Rack elevation showing devices and positions
- `network [site]` - Network topology showing device connections via cables
- `network [site]` - Network topology showing device connections
- `site <site-name>` - Site overview with racks and device counts
- `full` - Full infrastructure overview
## Instructions
You are a topology visualization assistant that queries NetBox and generates Mermaid diagrams.
Execute `skills/visual-header.md` with context "Topology".
### View: Rack Elevation
Execute `skills/topology-generation.md` which covers:
- Data collection via MCP for each view type
- Mermaid diagram generation with proper shapes
- Legend and data notes
Generate a rack view showing devices and their positions.
**Data Collection:**
1. Use `dcim_list_racks` to find the rack by name
2. Use `dcim_list_devices` with `rack_id` filter to get devices in rack
3. For each device, note: `position`, `u_height`, `face`, `name`, `role`
**Mermaid Output:**
```mermaid
graph TB
subgraph rack["Rack: <rack-name> (U<height>)"]
direction TB
u42["U42: empty"]
u41["U41: empty"]
u40["U40: server-01 (Server)"]
u39["U39: server-01 (cont.)"]
u38["U38: switch-01 (Switch)"]
%% ... continue for all units
end
```
**For devices spanning multiple U:**
- Mark the top U with device name and role
- Mark subsequent Us as "(cont.)" for the same device
- Empty Us should show "empty"
### View: Network Topology
Generate a network diagram showing device connections.
**Data Collection:**
1. Use `dcim_list_sites` if no site specified (get all)
2. Use `dcim_list_devices` with optional `site_id` filter
3. Use `dcim_list_cables` to get all connections
4. Use `dcim_list_interfaces` for each device to understand port names
**Mermaid Output:**
```mermaid
graph TD
subgraph site1["Site: Home"]
router1[("core-router-01<br/>Router")]
switch1[["dist-switch-01<br/>Switch"]]
server1["web-server-01<br/>Server"]
server2["db-server-01<br/>Server"]
end
router1 -->|"eth0 - eth1"| switch1
switch1 -->|"gi0/1 - eth0"| server1
switch1 -->|"gi0/2 - eth0"| server2
```
**Node shapes by role:**
- Router: `[(" ")]` (cylinder/database shape)
- Switch: `[[ ]]` (double brackets)
- Server: `[ ]` (rectangle)
- Firewall: `{{ }}` (hexagon)
- Other: `[ ]` (rectangle)
**Edge labels:** Show interface names on both ends (A-side - B-side)
### View: Site Overview
Generate a site-level view showing racks and summary counts.
**Data Collection:**
1. Use `dcim_get_site` to get site details
2. Use `dcim_list_racks` with `site_id` filter
3. Use `dcim_list_devices` with `site_id` filter for counts per rack
**Mermaid Output:**
```mermaid
graph TB
subgraph site["Site: Headquarters"]
subgraph row1["Row 1"]
rack1["Rack A1<br/>12/42 U used<br/>5 devices"]
rack2["Rack A2<br/>20/42 U used<br/>8 devices"]
end
subgraph row2["Row 2"]
rack3["Rack B1<br/>8/42 U used<br/>3 devices"]
end
end
```
### View: Full Infrastructure
Generate a high-level view of all sites and their relationships.
**Data Collection:**
1. Use `dcim_list_regions` to get hierarchy
2. Use `dcim_list_sites` to get all sites
3. Use `dcim_list_devices` with status filter for counts
**Mermaid Output:**
```mermaid
graph TB
subgraph region1["Region: Americas"]
site1["Headquarters<br/>3 racks, 25 devices"]
site2["Branch Office<br/>1 rack, 5 devices"]
end
subgraph region2["Region: Europe"]
site3["EU Datacenter<br/>10 racks, 100 devices"]
end
site1 -.->|"WAN Link"| site3
```
### Output Format
## Output Format
Always provide:
1. **Summary** - Brief description of what the diagram shows
2. **Mermaid Code Block** - The diagram code in a fenced code block
3. **Legend** - Explanation of shapes and colors used
4. **Data Notes** - Any data quality issues (e.g., devices without position, missing cables)
**Example Output:**
```markdown
## Network Topology: Home Site
This diagram shows the network connections between 4 devices at the Home site.
```mermaid
graph TD
router1[("core-router<br/>Router")]
switch1[["main-switch<br/>Switch"]]
server1["homelab-01<br/>Server"]
router1 -->|"eth0 - gi0/24"| switch1
switch1 -->|"gi0/1 - eth0"| server1
```
**Legend:**
- Cylinder shape: Routers
- Double brackets: Switches
- Rectangle: Servers
**Data Notes:**
- 1 device (nas-01) has no cable connections documented
```
1. **Summary** - Brief description
2. **Mermaid Code Block** - The diagram
3. **Legend** - Shape explanations
4. **Data Notes** - Quality issues found
## Examples
- `/cmdb-topology rack server-rack-01` - Show devices in server-rack-01
- `/cmdb-topology network` - Show all network connections
- `/cmdb-topology network Home` - Show network topology for Home site only
- `/cmdb-topology site Headquarters` - Show rack overview for Headquarters
- `/cmdb-topology full` - Show full infrastructure overview
- `/cmdb-topology rack server-rack-01` - Rack elevation
- `/cmdb-topology network` - All network connections
- `/cmdb-topology network Home` - Network for Home site
- `/cmdb-topology site Headquarters` - Site overview
- `/cmdb-topology full` - Full infrastructure
## User Request

View File

@@ -1,176 +1,74 @@
---
description: Interactive setup wizard for cmdb-assistant plugin - configures NetBox MCP server
description: Interactive setup wizard for cmdb-assistant plugin
---
# CMDB Assistant Setup Wizard
## Visual Output
Configure the cmdb-assistant plugin with NetBox integration.
When executing this command, display the plugin header:
## Skills to Load
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · Setup Wizard │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the setup.
This command sets up the cmdb-assistant plugin with NetBox integration.
- `skills/visual-header.md`
## Important Context
- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools
- **MCP tools won't work until after setup + session restart**
- **Uses NetBox MCP server (separate from Gitea MCP)**
- **Uses Bash, Read, Write, AskUserQuestion tools** - NOT MCP tools
- **MCP tools unavailable until after setup + session restart**
---
## Usage
## Phase 1: Environment Validation
```
/initial-setup
```
### Step 1.1: Check Python Version
## Instructions
Execute `skills/visual-header.md` with context "Setup Wizard".
### Phase 1: Environment Validation
```bash
python3 --version
```
If below 3.10, stop and inform user.
If below 3.10, stop setup and inform user.
### Phase 2: MCP Server Setup
---
1. Locate NetBox MCP server in marketplace
2. Check virtual environment exists
3. Create venv if missing: `python3 -m venv .venv && pip install -r requirements.txt`
## Phase 2: MCP Server Setup
### Phase 3: System Configuration
### Step 2.1: Locate NetBox MCP Server
1. Create config directory: `mkdir -p ~/.config/claude`
2. Check `~/.config/claude/netbox.env` exists
3. If missing, ask user for NetBox API URL (must include `/api`)
4. Create config file with placeholder token
5. Instruct user to add API token manually
```bash
find ~/.claude ~/.config/claude -name "mcp_server" -path "*netbox*" 2>/dev/null | head -5
```
### Phase 4: Validation
If not found, ask user for marketplace location.
1. Test API connection if token was added
2. Report result (200=success, 403=invalid token)
3. Display completion summary
4. Remind user to restart session for MCP tools
### Step 2.2: Check Virtual Environment
```bash
ls -la /path/to/mcp-servers/netbox/.venv/bin/python 2>/dev/null && echo "VENV_EXISTS" || echo "VENV_MISSING"
```
### Step 2.3: Create Virtual Environment (if missing)
```bash
cd /path/to/mcp-servers/netbox && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate
```
---
## Phase 3: System Configuration
### Step 3.1: Create Config Directory
```bash
mkdir -p ~/.config/claude
```
### Step 3.2: Check NetBox Configuration
```bash
cat ~/.config/claude/netbox.env 2>/dev/null || echo "FILE_NOT_FOUND"
```
**If file exists with valid values:** Skip to Phase 4.
**If missing or has placeholders:** Continue.
### Step 3.3: Gather NetBox Information
Use AskUserQuestion:
- Question: "What is your NetBox API URL? (e.g., https://netbox.company.com/api)"
- Header: "NetBox URL"
- Options:
- "Other (I'll provide the URL)"
Ask user to provide the URL.
**Important:** The URL must include `/api` at the end. If the user provides a URL without `/api`, append it automatically.
### Step 3.4: Create Configuration File
```bash
cat > ~/.config/claude/netbox.env << 'EOF'
# NetBox API Configuration
# Generated by cmdb-assistant /initial-setup
NETBOX_API_URL=<USER_PROVIDED_URL>
NETBOX_API_TOKEN=PASTE_YOUR_TOKEN_HERE
EOF
chmod 600 ~/.config/claude/netbox.env
```
### Step 3.5: Token Instructions
---
**Action Required: Add Your NetBox API Token**
I've created `~/.config/claude/netbox.env` but you need to add your API token manually.
**Steps:**
1. Open: `nano ~/.config/claude/netbox.env`
2. Generate token in NetBox: Admin → API Tokens → Add Token
3. Replace `PASTE_YOUR_TOKEN_HERE` with your token
4. Save the file
---
Use AskUserQuestion:
- Question: "Have you added your NetBox token?"
- Header: "Token"
- Options:
- "Yes, I've added the token"
- "Skip for now"
---
## Phase 4: Validation
### Step 4.1: Test Configuration (if token was added)
```bash
source ~/.config/claude/netbox.env && curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Token $NETBOX_API_TOKEN" "$NETBOX_API_URL/"
```
**Note:** The URL already includes `/api`, so we just append `/` for the root API endpoint.
Report result:
- 200: Success
- 403: Invalid token
- Other: Connection issue
### Step 4.2: Summary
## Completion Summary
```
╔════════════════════════════════════════════════════════════╗
║ CMDB-ASSISTANT SETUP COMPLETE ║
╠════════════════════════════════════════════════════════════╣
║ MCP Server (NetBox): ✓ Ready ║
║ System Config: ✓ ~/.config/claude/netbox.env ║
╚════════════════════════════════════════════════════════════╝
CMDB-ASSISTANT SETUP COMPLETE
MCP Server (NetBox): Ready
System Config: ~/.config/claude/netbox.env
Restart your Claude Code session for MCP tools.
After restart, try:
- /cmdb-device <hostname>
- /cmdb-ip <address>
- /cmdb-site <name>
- /cmdb-search <query>
```
### Step 4.3: Session Restart Notice
## User Request
---
**⚠️ Session Restart Required**
Restart your Claude Code session for MCP tools to become available.
**After restart, you can:**
- Run `/cmdb-device <hostname>` to look up a device
- Run `/cmdb-ip <address>` to look up an IP address
- Run `/cmdb-site <name>` to look up a site
- Run `/cmdb-search <query>` for general search
---
## Note on Project Configuration
cmdb-assistant does not require project-level configuration. The NetBox connection is system-wide and not tied to specific repositories.
$ARGUMENTS

View File

@@ -4,20 +4,14 @@ description: Detect IP address conflicts and overlapping prefixes in NetBox
# CMDB IP Conflict Detection
## Visual Output
When executing this command, display the plugin header:
```
┌──────────────────────────────────────────────────────────────────┐
│ 🖥️ CMDB-ASSISTANT · IP Conflict Detection │
└──────────────────────────────────────────────────────────────────┘
```
Then proceed with the analysis.
Scan NetBox IPAM data to identify IP address conflicts and overlapping prefixes.
## Skills to Load
- `skills/visual-header.md`
- `skills/ip-management.md`
- `skills/mcp-tools-reference.md`
## Usage
```
@@ -33,205 +27,31 @@ Scan NetBox IPAM data to identify IP address conflicts and overlapping prefixes.
## Instructions
You are an IP conflict detection specialist that analyzes NetBox IPAM data for conflicts and issues.
Execute `skills/visual-header.md` with context "IP Conflict Detection".
### Conflict Types to Detect
Execute conflict detection from `skills/ip-management.md`:
#### 1. Duplicate IP Addresses
1. **Data Collection** - Fetch IPs, prefixes, VRFs via MCP
2. **Duplicate Detection** - Group by address+VRF, flag >1 record
3. **Overlap Detection** - Compare prefixes pairwise using CIDR math
4. **Orphan IP Detection** - Find IPs without containing prefix
5. **Generate Report** - Use template from skill
Multiple IP address records with the same address (within same VRF).
## Conflict Types
**Detection:**
1. Use `ipam_list_ip_addresses` to get all addresses
2. Group by address + VRF combination
3. Flag groups with more than one record
**Exception:** Anycast addresses may legitimately appear multiple times - check the `role` field for "anycast".
#### 2. Overlapping Prefixes
Prefixes that contain the same address space (within same VRF).
**Detection:**
1. Use `ipam_list_prefixes` to get all prefixes
2. For each prefix pair in the same VRF, check if one contains the other
3. Legitimate hierarchies should have proper parent-child relationships
**Legitimate Overlaps:**
- Parent/child prefix hierarchy (e.g., 10.0.0.0/8 contains 10.0.1.0/24)
- Different VRFs (isolated routing tables)
- Marked as "container" status
#### 3. IPs Outside Their Prefix
IP addresses that don't fall within any defined prefix.
**Detection:**
1. For each IP address, find the most specific prefix that contains it
2. Flag IPs with no matching prefix
#### 4. Prefix Overlap Across VRFs (Informational)
Same prefix appearing in multiple VRFs - not necessarily a conflict, but worth noting.
### MCP Tools
- `ipam_list_ip_addresses` - Get all IP addresses with filters:
- `address` - Filter by specific address
- `vrf_id` - Filter by VRF
- `parent` - Filter by parent prefix
- `status` - Filter by status
- `ipam_list_prefixes` - Get all prefixes with filters:
- `prefix` - Filter by prefix CIDR
- `vrf_id` - Filter by VRF
- `within` - Find prefixes within a parent
- `contains` - Find prefixes containing an address
- `ipam_list_vrfs` - List VRFs for context
- `ipam_get_ip_address` - Get detailed IP info including assigned device/interface
- `ipam_get_prefix` - Get detailed prefix info
### Workflow
1. **Data Collection**
- Fetch all IP addresses (or filtered set)
- Fetch all prefixes (or filtered set)
- Fetch VRFs for context
2. **Duplicate Detection**
- Build address map: `{address+vrf: [records]}`
- Filter for entries with >1 record
3. **Overlap Detection**
- For each VRF, compare prefixes pairwise
- Check using CIDR math: does prefix A contain prefix B or vice versa?
- Ignore legitimate hierarchies (status=container)
4. **Orphan IP Detection**
- For each IP, find containing prefix
- Flag IPs with no prefix match
5. **Generate Report**
### Report Format
```markdown
## IP Conflict Detection Report
**Generated:** [timestamp]
**Scope:** [scope parameter]
### Summary
| Check | Status | Count |
|-------|--------|-------|
| Duplicate IPs | [PASS/FAIL] | X |
| Overlapping Prefixes | [PASS/FAIL] | Y |
| Orphan IPs | [PASS/FAIL] | Z |
| Total Issues | - | N |
### Critical Issues
#### Duplicate IP Addresses
| Address | VRF | Count | Assigned To |
|---------|-----|-------|-------------|
| 10.0.1.50/24 | Global | 2 | server-01 (eth0), server-02 (eth0) |
| 192.168.1.100/24 | Global | 2 | router-01 (gi0/1), switch-01 (vlan10) |
**Impact:** IP conflicts cause network connectivity issues. Devices will have intermittent connectivity.
**Resolution:**
- Determine which device should have the IP
- Update or remove the duplicate assignment
- Consider IP reservation to prevent future conflicts
#### Overlapping Prefixes
| Prefix 1 | Prefix 2 | VRF | Type |
|----------|----------|-----|------|
| 10.0.0.0/24 | 10.0.0.0/25 | Global | Unstructured overlap |
| 192.168.0.0/16 | 192.168.1.0/24 | Production | Missing container flag |
**Impact:** Overlapping prefixes can cause routing ambiguity and IP management confusion.
**Resolution:**
- For legitimate hierarchies: Mark parent prefix as status="container"
- For accidental overlaps: Consolidate or re-address one prefix
### Warnings
#### IPs Without Prefix
| Address | VRF | Assigned To | Nearest Prefix |
|---------|-----|-------------|----------------|
| 172.16.5.10/24 | Global | server-03 (eth0) | None found |
**Impact:** IPs without a prefix bypass IPAM allocation controls.
**Resolution:**
- Create appropriate prefix to contain the IP
- Or update IP to correct address within existing prefix
### Informational
#### Same Prefix in Multiple VRFs
| Prefix | VRFs | Purpose |
|--------|------|---------|
| 10.0.0.0/24 | Global, DMZ, Internal | [Check if intentional] |
### Statistics
| Metric | Value |
|--------|-------|
| Total IP Addresses | X |
| Total Prefixes | Y |
| Total VRFs | Z |
| Utilization (IPs/Prefix space) | W% |
### Remediation Commands
```
# Remove duplicate IP (keep server-01's assignment)
ipam_delete_ip_address id=123
# Mark prefix as container
ipam_update_prefix id=456 status=container
# Create missing prefix for orphan IP
ipam_create_prefix prefix=172.16.5.0/24 status=active
```
```
### CIDR Math Reference
For overlap detection, use these rules:
- Prefix A **contains** Prefix B if: A.network <= B.network AND A.broadcast >= B.broadcast
- Two prefixes **overlap** if: A.network <= B.broadcast AND B.network <= A.broadcast
**Example:**
- 10.0.0.0/8 contains 10.0.1.0/24 (legitimate hierarchy)
- 10.0.0.0/24 and 10.0.0.128/25 overlap (10.0.0.128/25 is within 10.0.0.0/24)
### Severity Levels
| Issue | Severity | Description |
|-------|----------|-------------|
| Duplicate IP (same interface type) | CRITICAL | Active conflict, causes outages |
| Duplicate IP (different roles) | HIGH | Potential conflict |
| Overlapping prefixes (same status) | HIGH | IPAM management issue |
| Overlapping prefixes (container ok) | LOW | May need status update |
| Orphan IP | MEDIUM | Bypasses IPAM controls |
| Type | Severity |
|------|----------|
| Duplicate IP (same interface type) | CRITICAL |
| Duplicate IP (different roles) | HIGH |
| Overlapping prefixes (same status) | HIGH |
| Overlapping prefixes (container ok) | LOW |
| Orphan IP | MEDIUM |
## Examples
- `/ip-conflicts` - Full scan for all conflicts
- `/ip-conflicts addresses` - Check only for duplicate IPs
- `/ip-conflicts prefixes` - Check only for overlapping prefixes
- `/ip-conflicts vrf Production` - Scan only Production VRF
- `/ip-conflicts prefix 10.0.0.0/8` - Scan within specific prefix range
- `/ip-conflicts` - Full scan
- `/ip-conflicts addresses` - Duplicate IPs only
- `/ip-conflicts vrf Production` - Scan specific VRF
## User Request

View File

@@ -2,8 +2,12 @@
"hooks": {
"SessionStart": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/startup-check.sh"
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/startup-check.sh"
}
]
}
],
"PreToolUse": [

View File

@@ -0,0 +1,163 @@
# Audit Workflow Skill
How to audit NetBox data quality.
## Prerequisites
Load these skills:
- `netbox-patterns` - Best practices reference
- `mcp-tools-reference` - MCP tool reference
## Data Collection
```
virt_list_vms
dcim_list_devices
virt_list_clusters
dcim_list_sites
tenancy_list_tenants
dcim_list_device_roles
dcim_list_platforms
```
## Quality Checks by Severity
### CRITICAL (must fix immediately)
| Check | Detection |
|-------|-----------|
| VMs without cluster | `cluster` is null AND `site` is null |
| Devices without site | `site` is null |
| Active devices without primary IP | `status=active` AND `primary_ip4` is null AND `primary_ip6` is null |
### HIGH (should fix soon)
| Check | Detection |
|-------|-----------|
| VMs without site | No site (neither direct nor via cluster.site) |
| VMs without tenant | `tenant` is null |
| Devices without platform | `platform` is null |
| Clusters not scoped to site | `site` is null on cluster |
| VMs without role | `role` is null |
### MEDIUM (plan to address)
| Check | Detection |
|-------|-----------|
| Inconsistent naming | Names don't match patterns |
| Role fragmentation | >10 device roles with <3 assignments each |
| Missing tags on production | Active resources without tags |
| Mixed naming separators | Some `_`, others `-` |
### LOW (informational)
| Check | Detection |
|-------|-----------|
| Docker containers as VMs | Cluster type is "Docker Compose" |
| VMs without description | `description` is empty |
| Sites without physical address | `physical_address` is empty |
| Devices without serial | `serial` is empty |
## Naming Convention Analysis
### Expected Patterns
| Object Type | Pattern | Example |
|-------------|---------|---------|
| Devices | `{role}-{location}-{number}` | `web-dc1-01` |
| VMs | `{env}-{app}-{number}` | `prod-api-01` |
| Clusters | `{site}-{type}` | `home-docker` |
### Analysis Steps
1. Extract naming patterns from existing objects
2. Identify dominant patterns (most common)
3. Flag outliers that don't match
4. Suggest standardization
## Role Fragmentation Analysis
### Red Flags
- More than 15 highly specific roles
- Roles with technology in name (use platform instead)
- Roles that duplicate functionality
- Single-use roles (only 1 device/VM)
### Recommended Consolidation
Use general roles + platform/tags for specificity:
- Instead of `nginx-web-server`, use `web-server` + platform `nginx`
## Report Template
```markdown
## CMDB Data Quality Audit Report
**Generated:** [timestamp]
**Scope:** [scope parameter]
### Summary
| Metric | Count |
|--------|-------|
| Total VMs | X |
| Total Devices | Y |
| Total Clusters | Z |
| **Total Issues** | **N** |
| Severity | Count |
|----------|-------|
| Critical | A |
| High | B |
| Medium | C |
| Low | D |
### Critical Issues
[List each with specific object names and IDs]
- VM `HotServ` (ID: 1) - No cluster or site assignment
- Device `server-01` (ID: 5) - No site assignment
### High Issues
[List each with specific object names]
### Medium Issues
[Grouped by category with counts]
### Recommendations
1. **[Most impactful fix]** - affects N objects
2. **[Second priority]** - affects M objects
### Quick Fixes
Commands to fix common issues:
```
# Assign site to VM
virt_update_vm id=X site=Y
# Assign platform to device
dcim_update_device id=X platform=Y
```
### Next Steps
- Run `/cmdb-register` to properly register new machines
- Use `/cmdb-sync` to update existing registrations
- Consider bulk updates via NetBox web UI for >10 items
```
## Scope-Specific Focus
| Scope | Focus |
|-------|-------|
| `all` | Full audit across all categories |
| `vms` | Virtual Machine checks only |
| `devices` | Device checks only |
| `naming` | Naming convention analysis |
| `roles` | Role fragmentation analysis |

View File

@@ -0,0 +1,130 @@
# Change Audit Skill
Audit NetBox changes for tracking and compliance.
## Prerequisites
Load skill: `mcp-tools-reference`
## MCP Tools
| Tool | Purpose | Parameters |
|------|---------|------------|
| `extras_list_object_changes` | List changes | `user_id`, `changed_object_type`, `action` |
| `extras_get_object_change` | Get change details | `id` |
## Common Object Types
| Category | Object Types |
|----------|--------------|
| DCIM | `dcim.device`, `dcim.interface`, `dcim.site`, `dcim.rack`, `dcim.cable` |
| IPAM | `ipam.ipaddress`, `ipam.prefix`, `ipam.vlan`, `ipam.vrf` |
| Virtualization | `virtualization.virtualmachine`, `virtualization.cluster` |
| Tenancy | `tenancy.tenant`, `tenancy.contact` |
## Audit Workflow
1. **Parse user request** - Determine filters
2. **Query object changes** - `extras_list_object_changes`
3. **Enrich data** - Fetch detailed records if needed
4. **Analyze patterns** - Identify bulk operations, unusual activity
5. **Generate report** - Structured format
## Report Template
```markdown
## NetBox Change Audit Report
**Generated:** [timestamp]
**Period:** [date range or "All time"]
**Filters:** [applied filters]
### Summary
| Metric | Count |
|--------|-------|
| Total Changes | X |
| Creates | Y |
| Updates | Z |
| Deletes | W |
| Unique Users | N |
| Object Types | M |
### Changes by Action
#### Created Objects (Y)
| Time | User | Object Type | Object | Details |
|------|------|-------------|--------|---------|
| 2024-01-15 14:30 | admin | dcim.device | server-01 | Created device |
#### Updated Objects (Z)
| Time | User | Object Type | Object | Changed Fields |
|------|------|-------------|--------|----------------|
| 2024-01-15 15:00 | john | ipam.ipaddress | 10.0.1.50/24 | status, description |
#### Deleted Objects (W)
| Time | User | Object Type | Object | Details |
|------|------|-------------|--------|---------|
| 2024-01-14 09:00 | admin | dcim.interface | eth2 | Removed from server-01 |
### Changes by User
| User | Creates | Updates | Deletes | Total |
|------|---------|---------|---------|-------|
| admin | 5 | 10 | 2 | 17 |
| john | 3 | 8 | 0 | 11 |
### Changes by Object Type
| Object Type | Creates | Updates | Deletes | Total |
|-------------|---------|---------|---------|-------|
| dcim.device | 2 | 5 | 0 | 7 |
| ipam.ipaddress | 4 | 3 | 1 | 8 |
### Timeline
```
2024-01-15: ######## 8 changes
2024-01-14: #### 4 changes
2024-01-13: ## 2 changes
```
### Notable Patterns
- **Bulk operations:** [Many changes in short time]
- **Unusual activity:** [Unexpected deletions, after-hours changes]
- **Missing audit trail:** [Expected changes not logged]
### Recommendations
1. [Security or process recommendations based on findings]
```
## Enriching Change Details
For detailed audit, use `extras_get_object_change` to see:
- `prechange_data` - Object state before change
- `postchange_data` - Object state after change
- `request_id` - Links related changes in same request
## Security Audit Mode
When user asks for "security audit" or "compliance report":
1. Focus on deletions and permission-sensitive changes
2. Highlight changes to critical objects (firewalls, VRFs, prefixes)
3. Flag changes outside business hours
4. Identify users with high change counts
## Filter Examples
| Request | Filter |
|---------|--------|
| Recent changes | None (last 24 hours default) |
| Last 7 days | Filter by `time` field |
| By user | `user_id=<id>` |
| Device changes | `changed_object_type=dcim.device` |
| All deletions | `action=delete` |

View File

@@ -0,0 +1,177 @@
# Device Registration Skill
How to register devices into NetBox.
## Prerequisites
Load these skills:
- `system-discovery` - Bash commands for gathering system info
- `netbox-patterns` - Best practices for data quality
- `mcp-tools-reference` - MCP tool reference
## Registration Workflow
### Phase 1: System Discovery
Use commands from `system-discovery` skill to gather:
- Hostname, OS, hardware model, serial number
- CPU, memory, disk
- Network interfaces with IPs
- Running Docker containers
### Phase 2: Pre-Registration Checks
1. **Check if device exists:**
```
dcim_list_devices name=<hostname>
```
If exists, suggest `/cmdb-sync` instead.
2. **Verify/Create site:**
```
dcim_list_sites name=<site-name>
```
If not found, list available sites or offer to create.
3. **Verify/Create platform:**
```
dcim_list_platforms name=<platform-name>
```
Create if not exists with `dcim_create_platform`.
4. **Verify/Create device role:**
```
dcim_list_device_roles name=<role-name>
```
### Phase 3: Device Creation
1. **Get/Create manufacturer and device type:**
```
dcim_list_manufacturers name="<manufacturer>"
dcim_list_device_types manufacturer_id=X model="<model>"
```
2. **Create device:**
```
dcim_create_device
name=<hostname>
device_type=<device_type_id>
role=<role_id>
site=<site_id>
platform=<platform_id>
tenant=<tenant_id> # if provided
serial=<serial>
description="Registered via cmdb-assistant"
```
3. **Create interfaces:**
For each network interface:
```
dcim_create_interface
device=<device_id>
name=<interface_name>
type=<type>
mac_address=<mac>
enabled=true
```
4. **Create IP addresses:**
For each IP:
```
ipam_create_ip_address
address=<ip/prefix>
assigned_object_type="dcim.interface"
assigned_object_id=<interface_id>
status="active"
```
5. **Set primary IP:**
```
dcim_update_device
id=<device_id>
primary_ip4=<primary_ip_id>
```
### Phase 4: Container Registration (if Docker)
1. **Create/Get cluster type:**
```
virt_list_cluster_types name="Docker Compose"
virt_create_cluster_type name="Docker Compose" slug="docker-compose"
```
2. **Create cluster:**
```
virt_create_cluster
name=<project-name>
type=<cluster_type_id>
site=<site_id>
description="Docker Compose stack on <hostname>"
```
3. **Create VMs for containers:**
For each running container:
```
virt_create_vm
name=<container_name>
cluster=<cluster_id>
site=<site_id>
role=<role_id>
status="active"
vcpus=<cpu_shares>
memory=<memory_mb>
disk=<disk_gb>
```
### Phase 5: Documentation
Add journal entry:
```
extras_create_journal_entry
assigned_object_type="dcim.device"
assigned_object_id=<device_id>
comments="Device registered via /cmdb-register command\n\nDiscovered:\n- X network interfaces\n- Y IP addresses\n- Z Docker containers"
```
## Summary Report Template
```markdown
## Machine Registration Complete
### Device Created
- **Name:** <hostname>
- **Site:** <site>
- **Platform:** <platform>
- **Role:** <role>
- **ID:** <device_id>
- **URL:** https://netbox.example.com/dcim/devices/<id>/
### Network Interfaces
| Interface | Type | MAC | IP Address |
|-----------|------|-----|------------|
| eth0 | 1000base-t | aa:bb:cc:dd:ee:ff | 192.168.1.100/24 |
### Primary IP: 192.168.1.100
### Docker Containers Registered (if applicable)
**Cluster:** <cluster_name> (ID: <cluster_id>)
| Container | Role | vCPUs | Memory | Status |
|-----------|------|-------|--------|--------|
| media_jellyfin | Media Server | 2.0 | 2048MB | Active |
### Next Steps
- Run `/cmdb-sync` periodically to keep data current
- Run `/cmdb-audit` to check data quality
- Add tags for classification
```
## Error Handling
| Error | Action |
|-------|--------|
| Device already exists | Suggest `/cmdb-sync` or ask to proceed |
| Site not found | List available sites, offer to create new |
| Docker not available | Skip container registration, note in summary |
| Permission denied | Note which operations failed, suggest fixes |

View File

@@ -0,0 +1,162 @@
# IP Management Skill
IP address and prefix management in NetBox.
## Prerequisites
Load skill: `mcp-tools-reference`
## IPAM Operations
### Prefix Management
| Action | Tool | Key Parameters |
|--------|------|----------------|
| List prefixes | `ipam_list_prefixes` | `prefix`, `vrf_id`, `within`, `contains` |
| Get details | `ipam_get_prefix` | `id` |
| Find available child | `ipam_list_available_prefixes` | `prefix_id` |
| Create prefix | `ipam_create_prefix` | `prefix`, `status`, `site`, `vrf` |
| Allocate child | `ipam_create_available_prefix` | `prefix_id`, `prefix_length` |
### IP Address Management
| Action | Tool | Key Parameters |
|--------|------|----------------|
| List IPs | `ipam_list_ip_addresses` | `address`, `vrf_id`, `device_id` |
| Get details | `ipam_get_ip_address` | `id` |
| Find available | `ipam_list_available_ips` | `prefix_id` |
| Create IP | `ipam_create_ip_address` | `address`, `assigned_object_type`, `assigned_object_id` |
| Allocate next | `ipam_create_available_ip` | `prefix_id` |
| Assign to interface | `ipam_update_ip_address` | `id`, `assigned_object_id` |
### VLAN and VRF
| Action | Tool |
|--------|------|
| List VLANs | `ipam_list_vlans` |
| Get VLAN | `ipam_get_vlan` |
| Create VLAN | `ipam_create_vlan` |
| List VRFs | `ipam_list_vrfs` |
| Get VRF | `ipam_get_vrf` |
## IP Allocation Workflow
1. **Find available IPs in target prefix:**
```
ipam_list_available_ips prefix_id=<id>
```
2. **Create the IP address:**
```
ipam_create_ip_address
address=<ip/prefix>
assigned_object_type="dcim.interface"
assigned_object_id=<interface_id>
status="active"
```
3. **Set as primary (if needed):**
```
dcim_update_device id=<device_id> primary_ip4=<ip_id>
```
## IP Conflict Detection
### Conflict Types
1. **Duplicate IP Addresses**
- Multiple records with same address in same VRF
- Exception: Anycast addresses (check `role` field)
2. **Overlapping Prefixes**
- Prefixes containing same address space in same VRF
- Legitimate: Parent/child hierarchy, different VRFs, "container" status
3. **IPs Outside Prefix**
- IP addresses not within any defined prefix
4. **Same Prefix in Multiple VRFs** (informational)
### Detection Workflow
1. **Duplicate Detection:**
- Get all addresses: `ipam_list_ip_addresses`
- Group by address + VRF
- Flag groups with >1 record
2. **Overlap Detection:**
- Get all prefixes: `ipam_list_prefixes`
- For each VRF, compare prefixes pairwise
- Check if prefix A contains prefix B or vice versa
- Ignore legitimate hierarchies (status=container)
3. **Orphan IP Detection:**
- For each IP, find containing prefix
- Flag IPs with no prefix match
### CIDR Math Rules
- Prefix A **contains** Prefix B if: `A.network <= B.network AND A.broadcast >= B.broadcast`
- Two prefixes **overlap** if: `A.network <= B.broadcast AND B.network <= A.broadcast`
### Severity Levels
| Issue | Severity |
|-------|----------|
| Duplicate IP (same interface type) | CRITICAL |
| Duplicate IP (different roles) | HIGH |
| Overlapping prefixes (same status) | HIGH |
| Overlapping prefixes (container ok) | LOW |
| Orphan IP | MEDIUM |
## Conflict Report Template
```markdown
## IP Conflict Detection Report
**Generated:** [timestamp]
**Scope:** [scope parameter]
### Summary
| Check | Status | Count |
|-------|--------|-------|
| Duplicate IPs | [PASS/FAIL] | X |
| Overlapping Prefixes | [PASS/FAIL] | Y |
| Orphan IPs | [PASS/FAIL] | Z |
### Critical Issues
#### Duplicate IP Addresses
| Address | VRF | Count | Assigned To |
|---------|-----|-------|-------------|
| 10.0.1.50/24 | Global | 2 | server-01, server-02 |
**Resolution:**
- Determine which device should have the IP
- Update or remove the duplicate
#### Overlapping Prefixes
| Prefix 1 | Prefix 2 | VRF | Type |
|----------|----------|-----|------|
| 10.0.0.0/24 | 10.0.0.0/25 | Global | Unstructured |
**Resolution:**
- For legitimate hierarchies: Mark parent as status="container"
- For accidental: Consolidate or re-address
### Remediation Commands
```
# Remove duplicate IP
ipam_delete_ip_address id=123
# Mark prefix as container
ipam_update_prefix id=456 status=container
# Create missing prefix
ipam_create_prefix prefix=172.16.5.0/24 status=active
```
```

View File

@@ -0,0 +1,281 @@
# NetBox MCP Tools Reference
Complete reference for NetBox MCP tools organized by category.
## DCIM (Data Center Infrastructure Management)
### Sites and Locations
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_sites` | List all sites | `name`, `status`, `region_id` |
| `dcim_get_site` | Get site details | `id` |
| `dcim_create_site` | Create new site | `name`, `slug`, `status` |
| `dcim_update_site` | Update site | `id`, fields to update |
| `dcim_delete_site` | Delete site | `id` |
| `dcim_list_locations` | List locations within sites | `site_id`, `parent_id` |
| `dcim_get_location` | Get location details | `id` |
| `dcim_create_location` | Create location | `name`, `slug`, `site` |
| `dcim_update_location` | Update location | `id`, fields to update |
| `dcim_delete_location` | Delete location | `id` |
| `dcim_list_regions` | List regions | `name` |
| `dcim_get_region` | Get region details | `id` |
| `dcim_create_region` | Create region | `name`, `slug` |
| `dcim_update_region` | Update region | `id`, fields to update |
| `dcim_delete_region` | Delete region | `id` |
### Racks
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_racks` | List racks | `site_id`, `location_id`, `name` |
| `dcim_get_rack` | Get rack details | `id` |
| `dcim_create_rack` | Create rack | `name`, `site`, `u_height` |
| `dcim_update_rack` | Update rack | `id`, fields to update |
| `dcim_delete_rack` | Delete rack | `id` |
### Devices
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_devices` | List devices | `name`, `site_id`, `role_id`, `status` |
| `dcim_get_device` | Get device details | `id` |
| `dcim_create_device` | Create device | `name`, `device_type`, `role`, `site` |
| `dcim_update_device` | Update device | `id`, `primary_ip4`, etc. |
| `dcim_delete_device` | Delete device | `id` |
### Device Types and Roles
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_device_types` | List device types | `manufacturer_id`, `model` |
| `dcim_get_device_type` | Get type details | `id` |
| `dcim_create_device_type` | Create device type | `manufacturer`, `model`, `slug` |
| `dcim_update_device_type` | Update device type | `id`, fields |
| `dcim_delete_device_type` | Delete device type | `id` |
| `dcim_list_device_roles` | List device roles | `name` |
| `dcim_get_device_role` | Get role details | `id` |
| `dcim_create_device_role` | Create device role | `name`, `slug` |
| `dcim_update_device_role` | Update device role | `id`, fields |
| `dcim_delete_device_role` | Delete device role | `id` |
### Manufacturers and Platforms
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_manufacturers` | List manufacturers | `name` |
| `dcim_get_manufacturer` | Get manufacturer details | `id` |
| `dcim_create_manufacturer` | Create manufacturer | `name`, `slug` |
| `dcim_update_manufacturer` | Update manufacturer | `id`, fields |
| `dcim_delete_manufacturer` | Delete manufacturer | `id` |
| `dcim_list_platforms` | List platforms | `name` |
| `dcim_get_platform` | Get platform details | `id` |
| `dcim_create_platform` | Create platform | `name`, `slug` |
| `dcim_update_platform` | Update platform | `id`, fields |
| `dcim_delete_platform` | Delete platform | `id` |
### Interfaces and Cables
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_interfaces` | List interfaces | `device_id`, `name`, `type` |
| `dcim_get_interface` | Get interface details | `id` |
| `dcim_create_interface` | Create interface | `device`, `name`, `type` |
| `dcim_update_interface` | Update interface | `id`, `enabled`, `mac_address` |
| `dcim_delete_interface` | Delete interface | `id` |
| `dcim_list_cables` | List cables | `device_id`, `site_id` |
| `dcim_get_cable` | Get cable details | `id` |
| `dcim_create_cable` | Create cable | `a_terminations`, `b_terminations` |
| `dcim_update_cable` | Update cable | `id`, fields |
| `dcim_delete_cable` | Delete cable | `id` |
### Power
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_power_panels` | List power panels | `site_id` |
| `dcim_get_power_panel` | Get panel details | `id` |
| `dcim_create_power_panel` | Create power panel | `name`, `site` |
| `dcim_list_power_feeds` | List power feeds | `power_panel_id` |
| `dcim_get_power_feed` | Get feed details | `id` |
| `dcim_create_power_feed` | Create power feed | `name`, `power_panel`, `supply` |
### Other DCIM
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `dcim_list_virtual_chassis` | List virtual chassis | (varies) |
| `dcim_get_virtual_chassis` | Get virtual chassis | `id` |
| `dcim_list_inventory_items` | List inventory items | `device_id` |
| `dcim_get_inventory_item` | Get inventory item | `id` |
## IPAM (IP Address Management)
### Prefixes
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `ipam_list_prefixes` | List prefixes | `prefix`, `vrf_id`, `within`, `contains` |
| `ipam_get_prefix` | Get prefix details | `id` |
| `ipam_create_prefix` | Create prefix | `prefix`, `status`, `site`, `vrf` |
| `ipam_update_prefix` | Update prefix | `id`, `status`, etc. |
| `ipam_delete_prefix` | Delete prefix | `id` |
| `ipam_list_available_prefixes` | List available child prefixes | `prefix_id` |
| `ipam_create_available_prefix` | Allocate from parent | `prefix_id`, `prefix_length` |
### IP Addresses
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `ipam_list_ip_addresses` | List IP addresses | `address`, `vrf_id`, `device_id`, `status` |
| `ipam_get_ip_address` | Get IP details | `id` |
| `ipam_create_ip_address` | Create IP address | `address`, `assigned_object_type`, `assigned_object_id` |
| `ipam_update_ip_address` | Update IP address | `id`, `status`, etc. |
| `ipam_delete_ip_address` | Delete IP address | `id` |
| `ipam_list_available_ips` | List available IPs in prefix | `prefix_id` |
| `ipam_create_available_ip` | Allocate next available | `prefix_id` |
### VLANs and VRFs
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `ipam_list_vlans` | List VLANs | `vid`, `name`, `site_id` |
| `ipam_get_vlan` | Get VLAN details | `id` |
| `ipam_create_vlan` | Create VLAN | `vid`, `name`, `site` |
| `ipam_update_vlan` | Update VLAN | `id`, fields |
| `ipam_delete_vlan` | Delete VLAN | `id` |
| `ipam_list_vlan_groups` | List VLAN groups | `site_id` |
| `ipam_get_vlan_group` | Get VLAN group | `id` |
| `ipam_create_vlan_group` | Create VLAN group | `name`, `slug`, `scope_type` |
| `ipam_list_vrfs` | List VRFs | `name` |
| `ipam_get_vrf` | Get VRF details | `id` |
| `ipam_create_vrf` | Create VRF | `name`, `rd` |
| `ipam_update_vrf` | Update VRF | `id`, fields |
| `ipam_delete_vrf` | Delete VRF | `id` |
### Other IPAM
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `ipam_list_asns` | List ASNs | (varies) |
| `ipam_get_asn` | Get ASN details | `id` |
| `ipam_create_asn` | Create ASN | `asn`, `rir` |
| `ipam_list_rirs` | List RIRs | `name` |
| `ipam_get_rir` | Get RIR details | `id` |
| `ipam_list_aggregates` | List aggregates | `prefix`, `rir_id` |
| `ipam_get_aggregate` | Get aggregate | `id` |
| `ipam_create_aggregate` | Create aggregate | `prefix`, `rir` |
| `ipam_list_services` | List services | `device_id`, `name` |
| `ipam_get_service` | Get service details | `id` |
| `ipam_create_service` | Create service | `name`, `ports`, `protocol` |
## Virtualization
### Clusters
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `virt_list_cluster_types` | List cluster types | `name` |
| `virt_get_cluster_type` | Get cluster type | `id` |
| `virt_create_cluster_type` | Create cluster type | `name`, `slug` |
| `virt_list_cluster_groups` | List cluster groups | `name` |
| `virt_get_cluster_group` | Get cluster group | `id` |
| `virt_create_cluster_group` | Create cluster group | `name`, `slug` |
| `virt_list_clusters` | List clusters | `name`, `site_id`, `type_id` |
| `virt_get_cluster` | Get cluster details | `id` |
| `virt_create_cluster` | Create cluster | `name`, `type`, `site` |
| `virt_update_cluster` | Update cluster | `id`, fields |
| `virt_delete_cluster` | Delete cluster | `id` |
### Virtual Machines
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `virt_list_vms` | List VMs | `name`, `cluster_id`, `site_id`, `status` |
| `virt_get_vm` | Get VM details | `id` |
| `virt_create_vm` | Create VM | `name`, `cluster`, `site`, `status` |
| `virt_update_vm` | Update VM | `id`, `status`, etc. |
| `virt_delete_vm` | Delete VM | `id` |
| `virt_list_vm_ifaces` | List VM interfaces | `virtual_machine_id` |
| `virt_get_vm_iface` | Get VM interface | `id` |
| `virt_create_vm_iface` | Create VM interface | `virtual_machine`, `name` |
## Circuits
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `circuits_list_providers` | List providers | `name` |
| `circuits_get_provider` | Get provider | `id` |
| `circuits_create_provider` | Create provider | `name`, `slug` |
| `circuits_update_provider` | Update provider | `id`, fields |
| `circuits_delete_provider` | Delete provider | `id` |
| `circ_list_types` | List circuit types | `name` |
| `circ_get_type` | Get circuit type | `id` |
| `circ_create_type` | Create circuit type | `name`, `slug` |
| `circuits_list_circuits` | List circuits | `provider_id`, `type_id` |
| `circuits_get_circuit` | Get circuit | `id` |
| `circuits_create_circuit` | Create circuit | `cid`, `provider`, `type` |
| `circuits_update_circuit` | Update circuit | `id`, fields |
| `circuits_delete_circuit` | Delete circuit | `id` |
| `circ_list_terminations` | List terminations | `circuit_id` |
| `circ_get_termination` | Get termination | `id` |
| `circ_create_termination` | Create termination | `circuit`, `site`, `term_side` |
## Tenancy
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `tenancy_list_tenant_groups` | List tenant groups | `name` |
| `tenancy_get_tenant_group` | Get tenant group | `id` |
| `tenancy_create_tenant_group` | Create tenant group | `name`, `slug` |
| `tenancy_list_tenants` | List tenants | `name`, `group_id` |
| `tenancy_get_tenant` | Get tenant | `id` |
| `tenancy_create_tenant` | Create tenant | `name`, `slug` |
| `tenancy_update_tenant` | Update tenant | `id`, fields |
| `tenancy_delete_tenant` | Delete tenant | `id` |
| `tenancy_list_contacts` | List contacts | `name` |
| `tenancy_get_contact` | Get contact | `id` |
| `tenancy_create_contact` | Create contact | `name` |
## VPN
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `vpn_list_tunnels` | List VPN tunnels | `name` |
| `vpn_get_tunnel` | Get tunnel | `id` |
| `vpn_create_tunnel` | Create tunnel | `name`, `status` |
| `vpn_list_l2vpns` | List L2VPNs | `name` |
| `vpn_get_l2vpn` | Get L2VPN | `id` |
| `vpn_create_l2vpn` | Create L2VPN | `name`, `type` |
| `vpn_list_ike_policies` | List IKE policies | (varies) |
| `vpn_list_ipsec_policies` | List IPSec policies | (varies) |
| `vpn_list_ipsec_profiles` | List IPSec profiles | (varies) |
## Wireless
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `wlan_list_groups` | List WLAN groups | `name` |
| `wlan_get_group` | Get WLAN group | `id` |
| `wlan_create_group` | Create WLAN group | `name`, `slug` |
| `wlan_list_lans` | List WLANs | `ssid` |
| `wlan_get_lan` | Get WLAN | `id` |
| `wlan_create_lan` | Create WLAN | `ssid`, `group` |
| `wlan_list_links` | List wireless links | (varies) |
| `wlan_get_link` | Get wireless link | `id` |
## Extras
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `extras_list_tags` | List tags | `name` |
| `extras_get_tag` | Get tag | `id` |
| `extras_create_tag` | Create tag | `name`, `slug`, `color` |
| `extras_update_tag` | Update tag | `id`, fields |
| `extras_delete_tag` | Delete tag | `id` |
| `extras_list_custom_fields` | List custom fields | `name` |
| `extras_get_custom_field` | Get custom field | `id` |
| `extras_list_webhooks` | List webhooks | `name` |
| `extras_get_webhook` | Get webhook | `id` |
| `extras_list_journal_entries` | List journal entries | `assigned_object_type`, `assigned_object_id` |
| `extras_get_journal_entry` | Get journal entry | `id` |
| `extras_create_journal_entry` | Create journal entry | `assigned_object_type`, `assigned_object_id`, `comments` |
| `extras_list_object_changes` | List audit log | `user_id`, `changed_object_type`, `action` |
| `extras_get_object_change` | Get change details | `id` |
| `extras_list_config_contexts` | List config contexts | `name` |
| `extras_get_config_context` | Get config context | `id` |
## Common Object Types for Filtering
| Category | Object Types |
|----------|--------------|
| DCIM | `dcim.device`, `dcim.interface`, `dcim.site`, `dcim.rack`, `dcim.cable` |
| IPAM | `ipam.ipaddress`, `ipam.prefix`, `ipam.vlan`, `ipam.vrf` |
| Virtualization | `virtualization.virtualmachine`, `virtualization.cluster` |
| Tenancy | `tenancy.tenant`, `tenancy.contact` |

View File

@@ -0,0 +1,191 @@
# Sync Workflow Skill
How to synchronize machine state with NetBox.
## Prerequisites
Load these skills:
- `system-discovery` - Bash commands for system info
- `mcp-tools-reference` - MCP tool reference
## Sync Workflow
### Phase 1: Device Lookup
```
dcim_list_devices name=<hostname>
```
If not found, suggest `/cmdb-register` first.
If found:
- Store device ID and current field values
- Fetch interfaces: `dcim_list_interfaces device_id=<device_id>`
- Fetch IPs: `ipam_list_ip_addresses device_id=<device_id>`
- Check clusters/VMs: `virt_list_clusters`, `virt_list_vms cluster=<cluster_id>`
### Phase 2: Current State Discovery
Use commands from `system-discovery` skill.
### Phase 3: Comparison
#### Device Attributes
| Field | Compare |
|-------|---------|
| Platform | OS version changed? |
| Status | Still active? |
| Serial | Match? |
| Description | Keep existing |
#### Network Interfaces
| Change Type | Detection |
|-------------|-----------|
| New interface | Exists locally but not in NetBox |
| Removed interface | In NetBox but not locally |
| Changed MAC | MAC address different |
| Interface type | Type mismatch |
#### IP Addresses
| Change Type | Detection |
|-------------|-----------|
| New IP | Exists locally but not in NetBox |
| Removed IP | In NetBox but not locally |
| Primary IP changed | Default route interface changed |
#### Docker Containers
| Change Type | Detection |
|-------------|-----------|
| New container | Running locally but no VM in cluster |
| Stopped container | VM exists but container not running |
| Resource change | vCPUs/memory different |
### Phase 4: Diff Report
```markdown
## Sync Diff Report
**Device:** <hostname> (ID: <device_id>)
**NetBox URL:** https://netbox.example.com/dcim/devices/<id>/
### Device Attributes
| Field | NetBox Value | Current Value | Action |
|-------|--------------|---------------|--------|
| Platform | Ubuntu 22.04 | Ubuntu 24.04 | UPDATE |
### Network Interfaces
#### New Interfaces (will create)
| Interface | Type | MAC | IPs |
|-----------|------|-----|-----|
| tailscale0 | virtual | - | 100.x.x.x/32 |
#### Removed Interfaces (will mark offline)
| Interface | Type | Reason |
|-----------|------|--------|
| eth1 | 1000base-t | Not found locally |
#### Changed Interfaces
| Interface | Field | Old | New |
|-----------|-------|-----|-----|
| eth0 | mac_address | aa:bb:cc:00:00:00 | aa:bb:cc:11:11:11 |
### IP Addresses
#### New IPs (will create)
- 192.168.1.150/24 on eth0
#### Removed IPs (will unassign)
- 192.168.1.100/24 from eth0
### Docker Containers
#### New Containers (will create VMs)
| Container | Image | Role |
|-----------|-------|------|
| media_lidarr | linuxserver/lidarr | Media Management |
### Summary
- **Updates:** X
- **Creates:** Y
- **Removals/Offline:** Z
```
### Phase 5: Apply Updates
#### Device Updates
```
dcim_update_device id=<device_id> platform=<new_platform_id>
```
#### Interface Updates
New:
```
dcim_create_interface device=<device_id> name=<name> type=<type>
```
Removed (mark offline):
```
dcim_update_interface id=<id> enabled=false description="Marked offline by cmdb-sync"
```
Changed:
```
dcim_update_interface id=<id> mac_address=<new_mac>
```
#### IP Address Updates
New:
```
ipam_create_ip_address address=<ip/prefix> assigned_object_type="dcim.interface" assigned_object_id=<id>
```
Removed (unassign):
```
ipam_update_ip_address id=<id> assigned_object_type=null assigned_object_id=null
```
#### Primary IP Update
```
dcim_update_device id=<device_id> primary_ip4=<new_primary_ip_id>
```
#### Container/VM Updates
New:
```
virt_create_vm name=<name> cluster=<cluster_id> status="active"
```
Stopped:
```
virt_update_vm id=<id> status="offline"
```
### Phase 6: Journal Entry
```
extras_create_journal_entry
assigned_object_type="dcim.device"
assigned_object_id=<device_id>
comments="Device synced via /cmdb-sync command\n\nChanges applied:\n- <list>"
```
## Sync Modes
### Dry Run Mode
- Complete phases 1-4 (lookup, discovery, compare, diff report)
- Skip phases 5-6 (no updates, no journal)
- End with: "Dry run complete. No changes applied."
### Full Sync Mode
- Skip user confirmation
- Update all fields even if unchanged (force refresh)
## Error Handling
| Error | Action |
|-------|--------|
| Device not found | Suggest `/cmdb-register` |
| Permission denied | Note which failed, continue others |
| Cluster not found | Offer to create or skip container sync |
| API errors | Log error, continue with remaining |

View File

@@ -0,0 +1,101 @@
# System Discovery Skill
Bash commands for gathering system information from the current machine.
## Basic Device Information
```bash
# Hostname
hostname
# OS/Platform info
cat /etc/os-release 2>/dev/null || uname -a
# Hardware model - Raspberry Pi
cat /proc/device-tree/model 2>/dev/null || echo "Unknown"
# Hardware model - x86 systems
cat /sys/class/dmi/id/product_name 2>/dev/null || echo "Unknown"
# Serial number - Raspberry Pi
cat /proc/device-tree/serial-number 2>/dev/null || cat /proc/cpuinfo | grep Serial | cut -d: -f2 | tr -d ' ' 2>/dev/null
# Serial number - x86 systems
cat /sys/class/dmi/id/product_serial 2>/dev/null || echo "Unknown"
# CPU count
nproc
# Memory in MB
free -m | awk '/Mem:/ {print $2}'
# Disk size in GB (root filesystem)
df -BG / | awk 'NR==2 {print $2}' | tr -d 'G'
```
## Network Interfaces
```bash
# Get interfaces with IPs (JSON format)
ip -j addr show 2>/dev/null || ip addr show
# Get default gateway interface
ip route | grep default | awk '{print $5}' | head -1
# Get MAC addresses
ip -j link show 2>/dev/null || ip link show
```
## Running Applications
```bash
# Docker containers (JSON format)
docker ps --format '{"name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","ports":"{{.Ports}}"}' 2>/dev/null || echo "Docker not available"
# Docker Compose projects (find compose files)
find ~/apps /home/*/apps -name "docker-compose.yml" -o -name "docker-compose.yaml" 2>/dev/null | head -20
# Running systemd services
systemctl list-units --type=service --state=running --no-pager --plain 2>/dev/null | grep -v "^UNIT" | head -30
```
## Interface Type Mapping
| Interface Pattern | NetBox Type |
|-------------------|-------------|
| `eth*`, `enp*` | `1000base-t` |
| `wlan*` | `ieee802.11ax` |
| `tailscale*`, `docker*`, `br-*` | `virtual` |
| `lo` | Skip (loopback) |
## Platform Detection
Based on OS detected, determine platform name:
| OS Detection | Platform Name |
|--------------|---------------|
| Raspberry Pi OS | `Raspberry Pi OS (Bookworm)` |
| Ubuntu | `Ubuntu {version} LTS` |
| Debian | `Debian {version}` |
| Default | `{OS Name} {Version}` |
## Device Role Auto-Detection
Based on detected services:
| Detection | Suggested Role |
|-----------|----------------|
| Docker containers found | `Docker Host` |
| Only basic services | `Server` |
| Specific role specified | Use specified |
## Container Role Mapping
Map container names/images to roles:
| Container Pattern | Role |
|-------------------|------|
| `*caddy*`, `*nginx*`, `*traefik*` | Reverse Proxy |
| `*db*`, `*postgres*`, `*mysql*`, `*redis*` | Database |
| `*webui*`, `*frontend*` | Web Application |
| Others | Infer from image or use "Container" |

View File

@@ -0,0 +1,155 @@
# Topology Generation Skill
Generate Mermaid diagrams from NetBox data.
## Prerequisites
Load skill: `mcp-tools-reference`
## View: Rack Elevation
### Data Collection
1. Find rack: `dcim_list_racks name=<name>`
2. Get devices: `dcim_list_devices rack_id=<id>`
3. Note for each: `position`, `u_height`, `face`, `name`, `role`
### Mermaid Template
```mermaid
graph TB
subgraph rack["Rack: <rack-name> (U<height>)"]
direction TB
u42["U42: empty"]
u41["U41: empty"]
u40["U40: server-01 (Server)"]
u39["U39: server-01 (cont.)"]
u38["U38: switch-01 (Switch)"]
end
```
### Rules
- Mark top U with device name and role
- Mark subsequent Us as "(cont.)" for multi-U devices
- Empty Us show "empty"
## View: Network Topology
### Data Collection
1. List sites: `dcim_list_sites`
2. List devices: `dcim_list_devices site_id=<id>`
3. List cables: `dcim_list_cables`
4. List interfaces: `dcim_list_interfaces device_id=<id>`
### Mermaid Template
```mermaid
graph TD
subgraph site1["Site: Home"]
router1[("core-router-01<br/>Router")]
switch1[["dist-switch-01<br/>Switch"]]
server1["web-server-01<br/>Server"]
server2["db-server-01<br/>Server"]
end
router1 -->|"eth0 - eth1"| switch1
switch1 -->|"gi0/1 - eth0"| server1
switch1 -->|"gi0/2 - eth0"| server2
```
### Node Shapes by Role
| Role | Shape | Mermaid Syntax |
|------|-------|----------------|
| Router | Cylinder | `[(" ")]` |
| Switch | Double brackets | `[[ ]]` |
| Server | Rectangle | `[ ]` |
| Firewall | Hexagon | `{{ }}` |
| Other | Rectangle | `[ ]` |
### Edge Labels
Show interface names: `A-side - B-side`
## View: Site Overview
### Data Collection
1. Get site: `dcim_get_site id=<id>`
2. List racks: `dcim_list_racks site_id=<id>`
3. Count devices per rack: `dcim_list_devices rack_id=<id>`
### Mermaid Template
```mermaid
graph TB
subgraph site["Site: Headquarters"]
subgraph row1["Row 1"]
rack1["Rack A1<br/>12/42 U used<br/>5 devices"]
rack2["Rack A2<br/>20/42 U used<br/>8 devices"]
end
subgraph row2["Row 2"]
rack3["Rack B1<br/>8/42 U used<br/>3 devices"]
end
end
```
## View: Full Infrastructure
### Data Collection
1. List regions: `dcim_list_regions`
2. List sites: `dcim_list_sites`
3. Count devices: `dcim_list_devices status=active`
### Mermaid Template
```mermaid
graph TB
subgraph region1["Region: Americas"]
site1["Headquarters<br/>3 racks, 25 devices"]
site2["Branch Office<br/>1 rack, 5 devices"]
end
subgraph region2["Region: Europe"]
site3["EU Datacenter<br/>10 racks, 100 devices"]
end
site1 -.->|"WAN Link"| site3
```
## Output Format
Always provide:
1. **Summary** - Brief description of diagram content
2. **Mermaid Code Block** - The diagram code
3. **Legend** - Explanation of shapes and colors
4. **Data Notes** - Any data quality issues
### Example Output
```markdown
## Network Topology: Home Site
This diagram shows network connections between 4 devices at Home site.
```mermaid
graph TD
router1[("core-router<br/>Router")]
switch1[["main-switch<br/>Switch"]]
server1["homelab-01<br/>Server"]
router1 -->|"eth0 - gi0/24"| switch1
switch1 -->|"gi0/1 - eth0"| server1
```
**Legend:**
- Cylinder shape: Routers
- Double brackets: Switches
- Rectangle: Servers
**Data Notes:**
- 1 device (nas-01) has no cable connections documented
```

View File

@@ -0,0 +1,32 @@
# Visual Header Skill
Standard visual header for cmdb-assistant commands.
## Header Template
```
+----------------------------------------------------------------------+
| CMDB-ASSISTANT - [Context] |
+----------------------------------------------------------------------+
```
## Context Values by Command
| Command | Context |
|---------|---------|
| `/cmdb-search` | Search |
| `/cmdb-device` | Device Management |
| `/cmdb-ip` | IP Management |
| `/cmdb-site` | Site Management |
| `/cmdb-audit` | Data Quality Audit |
| `/cmdb-register` | Machine Registration |
| `/cmdb-sync` | Machine Sync |
| `/cmdb-topology` | Topology |
| `/change-audit` | Change Audit |
| `/ip-conflicts` | IP Conflict Detection |
| `/initial-setup` | Setup Wizard |
| Agent mode | Infrastructure Management |
## Usage
Display header at the start of every command response before proceeding with the operation.

View File

@@ -1,285 +1,45 @@
---
description: Interactive setup wizard for pr-review plugin - configures Gitea MCP and project settings
description: Interactive setup wizard for pr-review plugin
---
# PR Review Setup Wizard
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Setup Wizard`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Setup Wizard │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the setup.
This command sets up the pr-review plugin. It shares the Gitea MCP server with projman, so if you've already run `/initial-setup` for projman, most of the work is done.
- skills/setup-workflow.md
- skills/mcp-tools-reference.md
- skills/output-formats.md
## Important Context
- **This command uses Bash, Read, Write, and AskUserQuestion tools** - NOT MCP tools
- **MCP tools won't work until after setup + session restart**
- **Shares Gitea MCP server with projman plugin**
- Uses Bash, Read, Write, AskUserQuestion - NOT MCP tools
- MCP tools won't work until after setup + session restart
- Shares Gitea MCP server with projman plugin
---
## Workflow
## Phase 1: Check Existing Setup
### Phase 1: Check Existing Setup
### Step 1.1: Check if Gitea MCP is Already Configured
Check `~/.config/claude/gitea.env`. If valid, skip to Phase 3.
First, check if the system configuration already exists (from projman or previous setup):
### Phase 2: System Setup (if needed)
```bash
cat ~/.config/claude/gitea.env 2>/dev/null || echo "FILE_NOT_FOUND"
```
Execute `skills/setup-workflow.md`: verify Python, create gitea.env, prompt for token
**If file exists with valid values (no placeholders):**
- Skip to Phase 3 (Project Configuration)
- Inform user: "Gitea configuration found. Skipping system setup."
### Phase 3: Project Configuration
**If file doesn't exist or has placeholders:**
- Continue to Phase 2
Execute `skills/setup-workflow.md`: auto-detect org/repo, validate via API, create .env
### Step 1.2: Check if projman is Installed
### Phase 4: Validation
Check if projman plugin exists (they share MCP server):
```bash
find ~/.claude ~/.config/claude -name "projman" -type d 2>/dev/null | head -1
```
**If projman exists:**
- Suggest: "The projman plugin is installed and shares the same Gitea MCP server. Consider running `/initial-setup` from projman for the full setup wizard."
Use AskUserQuestion:
- Question: "How would you like to proceed with setup?"
- Header: "Setup"
- Options:
- "Continue with pr-review setup (Recommended if not using projman)"
- "I'll use projman's /initial-setup instead"
**If user chooses projman setup:** End here with instructions to run projman's setup.
---
## Phase 2: System Setup (if needed)
This is a condensed version focusing on what pr-review needs.
### Step 2.1: Python and MCP Server
Check Python version:
```bash
python3 --version
```
If below 3.10, stop and inform user.
Locate and set up the MCP server:
```bash
find ~/.claude ~/.config/claude -name "mcp_server" -path "*gitea*" 2>/dev/null | head -5
```
If venv doesn't exist, create it:
```bash
cd /path/to/mcp-servers/gitea && python3 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt && deactivate
```
### Step 2.2: Gitea Configuration
Create config directory:
```bash
mkdir -p ~/.config/claude
```
Use AskUserQuestion:
- Question: "What is your Gitea server URL?"
- Header: "Gitea URL"
- Options:
- "https://gitea.hotserv.cloud"
- "Other (I'll provide the URL)"
Create configuration file (credentials only, org is per-project):
```bash
cat > ~/.config/claude/gitea.env << 'EOF'
# Gitea API Configuration
# Generated by pr-review /initial-setup
# Note: GITEA_ORG is configured per-project in .env
GITEA_API_URL=<USER_PROVIDED_URL>
GITEA_API_TOKEN=PASTE_YOUR_TOKEN_HERE
EOF
chmod 600 ~/.config/claude/gitea.env
```
### Step 2.3: Token Instructions
Display these instructions:
---
**Action Required: Add Your Gitea API Token**
I've created `~/.config/claude/gitea.env` but you need to add your API token manually.
**Steps:**
1. Open: `nano ~/.config/claude/gitea.env`
2. Generate token in Gitea: Settings → Applications → Generate New Token
- Permissions needed: `repo`, `read:org`, `read:user`
3. Replace `PASTE_YOUR_TOKEN_HERE` with your token
4. Save the file
---
Use AskUserQuestion:
- Question: "Have you added your Gitea token?"
- Header: "Token"
- Options:
- "Yes, I've added the token"
- "Skip for now"
---
## Phase 3: Project Configuration
### Step 3.1: Check Current Directory
```bash
pwd && git rev-parse --show-toplevel 2>/dev/null || echo "NOT_A_GIT_REPO"
```
### Step 3.2: Check Existing Project Config
```bash
cat .env 2>/dev/null | grep GITEA_REPO || echo "NOT_FOUND"
```
If `GITEA_REPO` is already set, skip to Phase 4.
### Step 3.3: Detect Organization and Repository
Extract organization:
```bash
git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\/[^/]*$/\1/'
```
Extract repository:
```bash
git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\.git$/\1/' | sed 's/.*\/\([^/]*\)$/\1/'
```
### Step 3.4: Validate Repository via Gitea API
```bash
source ~/.config/claude/gitea.env
curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos/<detected-org>/<detected-repo>"
```
| HTTP Code | Action |
|-----------|--------|
| **200** | Auto-fill - "Verified: <org>/<repo> exists" - skip to Step 3.7 |
| **404** | Not found - proceed to Step 3.5 |
| **401/403** | Permission issue - warn, proceed to Step 3.5 |
### Step 3.5: Confirm Organization (only if validation failed)
Use AskUserQuestion:
- Question: "Repository not found. Is '<detected-org>' the correct organization?"
- Header: "Organization"
- Options:
- "Yes, that's correct"
- "No, let me specify"
### Step 3.6: Confirm Repository (only if validation failed)
Use AskUserQuestion:
- Question: "Is '<detected-repo-name>' the correct repository?"
- Header: "Repository"
- Options:
- "Yes, that's correct"
- "No, let me specify"
**After corrections, re-validate via API (Step 3.4).**
### Step 3.7: Create/Update Project Config
If `.env` exists, append:
```bash
echo "GITEA_ORG=<ORG_NAME>" >> .env
echo "GITEA_REPO=<REPO_NAME>" >> .env
```
If `.env` doesn't exist:
```bash
cat > .env << 'EOF'
# Project Configuration
GITEA_ORG=<ORG_NAME>
GITEA_REPO=<REPO_NAME>
EOF
```
### Step 3.5: PR Review Settings (Optional)
Use AskUserQuestion:
- Question: "Do you want to configure PR review settings?"
- Header: "Settings"
- Options:
- "Use defaults (Recommended)"
- "Let me customize"
If customize, ask about:
- `PR_REVIEW_CONFIDENCE_THRESHOLD` (default: 0.5)
- `PR_REVIEW_AUTO_SUBMIT` (default: false)
---
## Phase 4: Validation and Next Steps
### Step 4.1: Test Configuration (if token was added)
```bash
source ~/.config/claude/gitea.env && curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/user"
```
Report result:
- 200: Success
- 401: Invalid token
- Other: Connection issue
### Step 4.2: Summary
```
╔════════════════════════════════════════════════════════════╗
║ PR-REVIEW SETUP COMPLETE ║
╠════════════════════════════════════════════════════════════╣
║ MCP Server (Gitea): ✓ Ready ║
║ System Config: ✓ ~/.config/claude/gitea.env ║
║ Project Config: ✓ ./.env ║
╚════════════════════════════════════════════════════════════╝
```
### Step 4.3: Session Restart Notice
---
**⚠️ Session Restart Required**
Restart your Claude Code session for MCP tools to become available.
**After restart, you can:**
- Run `/pr-review <PR_NUMBER>` to review a pull request
- Run `/pr-summary <PR_NUMBER>` for a quick summary
- Run `/pr-findings <PR_NUMBER>` to list actionable findings
---
Test API connection, display completion summary, remind to restart session
## Available Commands After Setup
| Command | Description |
|---------|-------------|
| `/pr-review <number>` | Full multi-agent PR review with confidence scoring |
| `/pr-summary <number>` | Quick PR summary |
| `/pr-findings <number>` | List findings with severity and line numbers |
- `/pr-review <number>` - Full multi-agent review
- `/pr-summary <number>` - Quick summary
- `/pr-findings <number>` - List findings

View File

@@ -2,165 +2,47 @@
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Diff Viewer`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Diff Viewer │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the diff display.
## Purpose
Display the PR diff with inline annotations from review comments, making it easy to see what feedback has been given alongside the code changes.
- skills/mcp-tools-reference.md
- skills/pr-analysis.md
- skills/output-formats.md
## Usage
```
/pr-diff <pr-number> [--repo owner/repo] [--context <lines>]
/pr-diff <pr-number> [--repo owner/repo] [--context <n>] [--no-comments] [--file <pattern>]
```
### Options
## Workflow
```
--repo <owner/repo> Override repository (default: from .env)
--context <n> Lines of context around changes (default: 3)
--no-comments Show diff without comment annotations
--file <pattern> Filter to specific files (glob pattern)
```
### Step 1: Fetch Data
## Behavior
### Step 1: Fetch PR Data
Using Gitea MCP tools:
1. `get_pr_diff` - Unified diff of all changes
2. `get_pr_comments` - All review comments on the PR
Load MCP tools, then: `get_pr_diff`, `get_pr_comments`
### Step 2: Parse and Annotate
Parse the diff and overlay comments at their respective file/line positions:
Execute `skills/pr-analysis.md` Annotated Diff Display:
- Overlay comments at file/line positions
- Show commenter, timestamp, replies
- Mark resolved vs open
```
═══════════════════════════════════════════════════
PR #123 Diff - Add user authentication
═══════════════════════════════════════════════════
### Step 3: Display
Branch: feat/user-auth → development
Files: 12 changed (+234 / -45)
───────────────────────────────────────────────────
src/api/users.ts (+85 / -12)
───────────────────────────────────────────────────
@@ -42,6 +42,15 @@ export async function getUser(id: string) {
42 │ const db = getDatabase();
43 │
44 │- const user = db.query("SELECT * FROM users WHERE id = " + id);
│ ┌─────────────────────────────────────────────────────────────
│ │ COMMENT by @reviewer (2h ago):
│ │ This is a SQL injection vulnerability. Use parameterized
│ │ queries instead: `db.query("SELECT * FROM users WHERE id = ?", [id])`
│ └─────────────────────────────────────────────────────────────
45 │+ const query = "SELECT * FROM users WHERE id = ?";
46 │+ const user = db.query(query, [id]);
47 │
48 │ if (!user) {
49 │ throw new NotFoundError("User not found");
50 │ }
@@ -78,3 +87,12 @@ export async function updateUser(id: string, data: UserInput) {
87 │+ // Validate input before update
88 │+ validateUserInput(data);
89 │+
90 │+ const result = db.query(
91 │+ "UPDATE users SET name = ?, email = ? WHERE id = ?",
92 │+ [data.name, data.email, id]
93 │+ );
│ ┌─────────────────────────────────────────────────────────────
│ │ COMMENT by @maintainer (1h ago):
│ │ Good use of parameterized query here!
│ │
│ │ REPLY by @author (30m ago):
│ │ Thanks! Applied the same pattern throughout.
│ └─────────────────────────────────────────────────────────────
───────────────────────────────────────────────────
src/components/LoginForm.tsx (+65 / -0) [NEW FILE]
───────────────────────────────────────────────────
@@ -0,0 +1,65 @@
1 │+import React, { useState } from 'react';
2 │+import { useAuth } from '../context/AuthContext';
3 │+
4 │+export function LoginForm() {
5 │+ const [email, setEmail] = useState('');
6 │+ const [password, setPassword] = useState('');
7 │+ const { login } = useAuth();
... (remaining diff content)
═══════════════════════════════════════════════════
Comment Summary: 5 comments, 2 resolved
═══════════════════════════════════════════════════
```
### Step 3: Filter by Confidence (Optional)
If `PR_REVIEW_CONFIDENCE_THRESHOLD` is set, also annotate with high-confidence findings from previous reviews:
```
44 │- const user = db.query("SELECT * FROM users WHERE id = " + id);
│ ┌─── REVIEW FINDING (0.95 HIGH) ─────────────────────────────
│ │ [SEC-001] SQL Injection Vulnerability
│ │ Use parameterized queries to prevent injection attacks.
│ └─────────────────────────────────────────────────────────────
│ ┌─── COMMENT by @reviewer ────────────────────────────────────
│ │ This is a SQL injection vulnerability...
│ └─────────────────────────────────────────────────────────────
```
## Output Formats
### Default (Annotated Diff)
Full diff with inline comments as shown above.
### Plain (--no-comments)
```
/pr-diff 123 --no-comments
# Standard unified diff output without annotations
```
### File Filter (--file)
```
/pr-diff 123 --file "src/api/*"
# Shows diff only for files matching pattern
```
Use annotated diff format from `skills/output-formats.md`
## Use Cases
- **Review preparation**: See the full context of changes with existing feedback
- **Followup work**: Understand what was commented on and where
- **Discussion context**: View threaded conversations alongside the code
- **Progress tracking**: See which comments have been resolved
## Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence for showing review findings |
- Review preparation with existing feedback
- Followup work - see what was commented
- Progress tracking on resolved comments
## Related Commands
| Command | Purpose |
|---------|---------|
| `/pr-summary` | Quick overview without diff |
| `/pr-review` | Full multi-agent review |
| `/pr-findings` | Filter review findings by category |
| `/pr-summary` | Quick overview |
| `/pr-review` | Full review |
| `/pr-findings` | Filter findings |

View File

@@ -2,148 +2,44 @@
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Findings`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Findings │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the findings display.
## Purpose
List and filter findings from a previous PR review by category, severity, or confidence level.
- skills/mcp-tools-reference.md
- skills/review-patterns/confidence-scoring.md
- skills/output-formats.md
## Usage
```
/pr-findings <pr-number> [filters]
/pr-findings <pr-number> [--category <cat>] [--severity <sev>] [--confidence <min>] [--file <pattern>] [--compact] [--json]
```
### Filters
```
--category <cat> Filter by category (security, performance, maintainability, tests)
--severity <sev> Filter by severity (critical, major, minor, suggestion)
--confidence <min> Minimum confidence score (0.0-1.0)
--file <pattern> Filter by file path pattern
```
## Examples
```
# Show only security findings
/pr-findings 123 --category security
# Show critical and major issues only
/pr-findings 123 --severity critical,major
# Show high-confidence findings only
/pr-findings 123 --confidence 0.8
# Show findings in specific files
/pr-findings 123 --file src/api/*
```
## Behavior
## Workflow
### Without Previous Review
If no review exists for this PR:
```
No review found for PR #123.
Would you like to:
1. Run full /pr-review now
2. Run quick /pr-summary
3. Cancel
```
Prompt: "No review found. Run /pr-review, /pr-summary, or cancel?"
### With Previous Review
Display filtered findings:
```
═══════════════════════════════════════════════════
PR #123 Findings (filtered: security)
═══════════════════════════════════════════════════
Showing 3 of 8 total findings
───────────────────────────────────────────────────
[SEC-001] SQL Injection Vulnerability
Confidence: 0.95 (HIGH) | Severity: Critical
File: src/api/users.ts:45
The query uses string interpolation without parameterization.
Fix: Use parameterized queries.
───────────────────────────────────────────────────
[SEC-002] Missing Input Validation
Confidence: 0.88 (MEDIUM) | Severity: Major
File: src/api/auth.ts:23
User input is passed directly to database without validation.
Fix: Add input validation middleware.
───────────────────────────────────────────────────
[SEC-003] Sensitive Data in Logs
Confidence: 0.72 (MEDIUM) | Severity: Minor
File: src/utils/logger.ts:15
Password field may be logged in debug mode.
Fix: Sanitize sensitive fields before logging.
═══════════════════════════════════════════════════
```
1. Load findings from previous review
2. Apply filters (category, severity, confidence, file)
3. Display using format from `skills/output-formats.md`
## Output Formats
### Default (Detailed)
Reference `skills/output-formats.md`:
- **Detailed** (default) - Full finding
- **Compact** (`--compact`) - Single line
- **JSON** (`--json`) - Structured data
Full finding details with descriptions and fixes.
### Compact (--compact)
## Examples
```bash
/pr-findings 123 --category security
/pr-findings 123 --severity critical,major
/pr-findings 123 --confidence 0.8
/pr-findings 123 --file src/api/*
```
SEC-001 | Critical | 0.95 | src/api/users.ts:45 | SQL Injection
SEC-002 | Major | 0.88 | src/api/auth.ts:23 | Missing Validation
SEC-003 | Minor | 0.72 | src/utils/logger.ts | Sensitive Logs
```
### JSON (--json)
```json
{
"pr": 123,
"findings": [
{
"id": "SEC-001",
"category": "security",
"severity": "critical",
"confidence": 0.95,
"file": "src/api/users.ts",
"line": 45,
"title": "SQL Injection Vulnerability",
"description": "...",
"fix": "..."
}
]
}
```
## Use Cases
- Focus on specific issue types
- Track resolution of findings
- Export findings for tracking
- Quick reference during fixes

View File

@@ -2,19 +2,14 @@
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Full Review`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Full Review │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the review.
## Purpose
Conduct a comprehensive pull request review using specialized agents for security, performance, maintainability, and test coverage.
- skills/mcp-tools-reference.md
- skills/review-workflow.md
- skills/review-patterns/confidence-scoring.md
- skills/output-formats.md
## Usage
@@ -22,132 +17,37 @@ Conduct a comprehensive pull request review using specialized agents for securit
/pr-review <pr-number> [--repo owner/repo]
```
## Behavior
## Workflow
### Step 1: Fetch PR Data
Using Gitea MCP tools:
1. `get_pull_request` - PR metadata
2. `get_pr_diff` - Code changes
3. `get_pr_comments` - Existing discussion
Load MCP tools, then: `get_pull_request`, `get_pr_diff`, `get_pr_comments`
### Step 2: Dispatch to Agents
The coordinator dispatches review tasks to specialized agents:
Execute `skills/review-workflow.md` - dispatch to Security, Performance, Maintainability, Test agents
```
PR Review: #123 - Add user authentication
═══════════════════════════════════════════════════
### Step 3: Aggregate and Filter
Dispatching to review agents:
├─ Security Reviewer → analyzing...
├─ Performance Analyst → analyzing...
├─ Maintainability Auditor → analyzing...
└─ Test Validator → analyzing...
```
Apply confidence threshold (default: 0.7). See `skills/review-patterns/confidence-scoring.md`
### Step 3: Aggregate Findings
### Step 4: Generate Report
Collect findings from all agents, each with:
- Category (security, performance, maintainability, tests)
- Severity (critical, major, minor, suggestion)
- Confidence score (0.0 - 1.0)
- File and line reference
- Description
- Suggested fix (if applicable)
Use format from `skills/output-formats.md`. Group by severity: critical > major > minor > suggestion
### Step 4: Filter by Confidence
### Step 5: Determine Verdict
Filter findings based on `PR_REVIEW_CONFIDENCE_THRESHOLD` (default: 0.7):
| Confidence | Label | Description |
|------------|-------|-------------|
| 0.9 - 1.0 | HIGH | Definite issue, must address |
| 0.7 - 0.89 | MEDIUM | Likely issue, should address |
| 0.5 - 0.69 | LOW | Possible concern, consider addressing |
| < threshold | (filtered) | Below configured threshold |
**Note:** With the default threshold of 0.7, only MEDIUM and HIGH confidence findings are shown. Adjust `PR_REVIEW_CONFIDENCE_THRESHOLD` to include more or fewer findings.
### Step 5: Generate Report
```
═══════════════════════════════════════════════════
PR Review Report: #123
═══════════════════════════════════════════════════
Summary:
Files changed: 12
Lines added: 234
Lines removed: 45
Findings: 8 total
🔴 Critical: 1
🟠 Major: 2
🟡 Minor: 3
💡 Suggestions: 2
───────────────────────────────────────────────────
CRITICAL FINDINGS
───────────────────────────────────────────────────
[SEC-001] SQL Injection Vulnerability (Confidence: 0.95)
File: src/api/users.ts:45
Category: Security
The query uses string interpolation without parameterization:
```ts
const query = `SELECT * FROM users WHERE id = ${userId}`;
```
Suggested fix:
```ts
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId]);
```
───────────────────────────────────────────────────
MAJOR FINDINGS
───────────────────────────────────────────────────
[PERF-001] N+1 Query Pattern (Confidence: 0.82)
...
───────────────────────────────────────────────────
VERDICT
───────────────────────────────────────────────────
❌ REQUEST_CHANGES
This PR has 1 critical security issue that must be addressed
before merging. See SEC-001 above.
───────────────────────────────────────────────────
```
- Any critical or 2+ major: REQUEST_CHANGES
- Only minor/suggestions: COMMENT
- No significant findings: APPROVE
### Step 6: Submit Review (Optional)
```
Submit this review to Gitea?
1. Yes, with REQUEST_CHANGES
2. Yes, as COMMENT only
3. No, just show me the report
```
If yes, use `create_pr_review` MCP tool.
## Output
Full review report with:
- Summary statistics
- Findings grouped by severity
- Code snippets with context
- Suggested fixes
- Overall verdict
Ask user to submit as REQUEST_CHANGES, COMMENT, or skip. Use `create_pr_review` MCP tool.
## Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence to report (0.0-1.0) |
| `PR_REVIEW_AUTO_SUBMIT` | `false` | Auto-submit to Gitea |
| Variable | Default |
|----------|---------|
| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` |
| `PR_REVIEW_AUTO_SUBMIT` | `false` |

View File

@@ -2,19 +2,13 @@
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Quick Summary`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Quick Summary │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the summary.
## Purpose
Generate a quick summary of PR changes without conducting a full multi-agent review.
- skills/mcp-tools-reference.md
- skills/pr-analysis.md
- skills/output-formats.md
## Usage
@@ -22,94 +16,26 @@ Generate a quick summary of PR changes without conducting a full multi-agent rev
/pr-summary <pr-number> [--repo owner/repo]
```
## Behavior
## Workflow
### Step 1: Fetch PR Data
Using Gitea MCP tools:
1. `get_pull_request` - PR metadata
2. `get_pr_diff` - Code changes
Load MCP tools, then: `get_pull_request`, `get_pr_diff`
### Step 2: Analyze Changes
Quick analysis of:
- Files modified
- Types of changes (features, fixes, refactoring)
- Scope and impact
Execute `skills/pr-analysis.md`:
- Categorize changes (feature, fix, refactor)
- Calculate statistics
- Identify key files
- Assess scope and risk
### Step 3: Generate Summary
```
═══════════════════════════════════════════════════
PR Summary: #123 - Add user authentication
═══════════════════════════════════════════════════
Author: @johndoe
Branch: feat/user-auth → development
Status: Open (ready for review)
───────────────────────────────────────────────────
CHANGES OVERVIEW
───────────────────────────────────────────────────
Files: 12 changed
+ 8 new files
~ 3 modified files
- 1 deleted file
Lines: +234 / -45 (net +189)
───────────────────────────────────────────────────
WHAT THIS PR DOES
───────────────────────────────────────────────────
This PR adds user authentication functionality:
1. **New API endpoints**
- POST /api/auth/login
- POST /api/auth/register
- POST /api/auth/logout
2. **Frontend components**
- LoginForm component
- RegisterForm component
- Auth context provider
3. **Database changes**
- New users table
- Sessions table
───────────────────────────────────────────────────
KEY FILES
───────────────────────────────────────────────────
• src/api/auth/login.ts (+85) - Login endpoint
• src/api/auth/register.ts (+120) - Registration
• src/components/LoginForm.tsx (+65) - Login UI
• src/db/migrations/001_users.sql (+45) - Schema
───────────────────────────────────────────────────
QUICK ASSESSMENT
───────────────────────────────────────────────────
Scope: Medium (authentication feature)
Risk: Medium (new security-sensitive code)
Recommendation: Full /pr-review suggested
═══════════════════════════════════════════════════
```
## Output
Summary report with:
- PR metadata
- Change statistics
- Plain-language description of changes
- Key files list
- Quick risk assessment
Use summary format from `skills/output-formats.md`
## When to Use
- Get quick overview before full review
- Quick overview before full review
- Triage multiple PRs
- Understand PR scope
- Decide if /pr-review is needed

View File

@@ -1,148 +1,45 @@
---
description: Quick project setup - configures only project-level settings for PR review
description: Quick project setup - configures only project-level settings
---
# Project Initialization (PR Review)
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Project Setup`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Project Setup │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the setup.
- skills/setup-workflow.md
- skills/output-formats.md
Fast setup for a new project when system-level configuration is already complete.
## Purpose
**Use this when:**
- You've already run `/initial-setup` on this machine
- You're starting work on a new project/repository
- You just need to configure this project for PR reviews
Fast setup when system-level config already exists.
---
**Use when:** Already ran `/initial-setup`, starting new project
## Pre-Flight Check
## Workflow
### Step 1: Verify System Configuration
### Pre-Flight Check
```bash
cat ~/.config/claude/gitea.env 2>/dev/null | grep -v "^#" | grep -v "PASTE_YOUR" | grep "GITEA_API_TOKEN=" && echo "SYSTEM_OK" || echo "SYSTEM_MISSING"
```
Verify `~/.config/claude/gitea.env` exists. If missing: redirect to `/initial-setup`
**If SYSTEM_MISSING:**
### Project Setup
---
Execute `skills/setup-workflow.md`:
1. Verify git repo
2. Check existing .env
3. Auto-detect org/repo from git remote
4. Validate via Gitea API
5. Create/update .env
**System configuration not found.**
### Complete
Please run `/initial-setup` first to configure Gitea credentials.
Display project configured format from `skills/output-formats.md`
---
## Ready Commands
**If SYSTEM_OK:** Continue.
---
## Project Setup
### Step 2: Verify Current Directory
```bash
pwd && git rev-parse --show-toplevel 2>/dev/null || echo "NOT_A_GIT_REPO"
```
### Step 3: Check Existing Configuration
```bash
cat .env 2>/dev/null | grep "GITEA_REPO=" || echo "NOT_CONFIGURED"
```
If already configured, ask if user wants to keep or reconfigure.
### Step 4: Detect Organization and Repository
Extract organization:
```bash
git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\/[^/]*$/\1/'
```
Extract repository:
```bash
git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\.git$/\1/' | sed 's/.*\/\([^/]*\)$/\1/'
```
### Step 5: Validate Repository via Gitea API
```bash
source ~/.config/claude/gitea.env
curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos/<detected-org>/<detected-repo>"
```
| HTTP Code | Action |
|-----------|--------|
| **200** | Auto-fill - "Verified: <org>/<repo> exists" - skip to Step 8 |
| **404** | Not found - proceed to Step 6 |
| **401/403** | Permission issue - warn, proceed to Step 6 |
### Step 6: Confirm Organization (only if validation failed)
Use AskUserQuestion:
- Question: "Repository not found. Is '<detected-org>' the correct organization?"
- Header: "Organization"
- Options:
- "Yes, that's correct"
- "No, let me specify"
### Step 7: Confirm Repository (only if validation failed)
Use AskUserQuestion:
- Question: "Is '<detected-repo-name>' the correct repository?"
- Header: "Repository"
- Options:
- "Yes, that's correct"
- "No, let me specify"
**After corrections, re-validate via API (Step 5).**
### Step 8: Create/Update .env
```bash
echo "GITEA_ORG=<ORG_NAME>" >> .env
echo "GITEA_REPO=<REPO_NAME>" >> .env
```
### Step 9: Optional PR Review Settings
Use AskUserQuestion:
- Question: "Configure PR review settings?"
- Header: "Settings"
- Options:
- "Use defaults (Recommended)"
- "Customize settings"
If customize:
- `PR_REVIEW_CONFIDENCE_THRESHOLD` (default: 0.5)
- `PR_REVIEW_AUTO_SUBMIT` (default: false)
---
## Complete
```
╔══════════════════════════════════════════════════════════════╗
║ PROJECT CONFIGURED ║
╠══════════════════════════════════════════════════════════════╣
║ Organization: <ORG_NAME> ║
║ Repository: <REPO_NAME> ║
║ Config file: ./.env ║
╚══════════════════════════════════════════════════════════════╝
Ready to review PRs:
• /pr-review <number> - Full multi-agent review
• /pr-summary <number> - Quick summary
• /pr-findings <number> - List findings
```
- `/pr-review <number>` - Full review
- `/pr-summary <number>` - Quick summary
- `/pr-findings <number>` - List findings

View File

@@ -1,105 +1,32 @@
---
description: Sync project configuration with current git remote - use after changing repository location
description: Sync project configuration with current git remote
---
# Project Sync (PR Review)
## Visual Output
When executing this command, display the plugin header:
Display header: `PR-REVIEW - Project Sync`
```
┌──────────────────────────────────────────────────────────────────┐
│ 🔍 PR-REVIEW · Project Sync │
└──────────────────────────────────────────────────────────────────┘
```
## Skills to Load
Then proceed with the synchronization.
- skills/setup-workflow.md
- skills/output-formats.md
Updates project configuration when the git remote URL has changed.
## Purpose
**Use this when:**
- Repository was moved to a different organization
- Repository was renamed
- Git remote URL changed
- SessionStart hook detected a mismatch
Updates config when git remote URL changed.
---
**Use when:** Repo moved/renamed, SessionStart detected mismatch
## Step 1: Verify System Configuration
## Workflow
```bash
cat ~/.config/claude/gitea.env 2>/dev/null | grep -v "^#" | grep -v "PASTE_YOUR" | grep "GITEA_API_TOKEN=" && echo "SYSTEM_OK" || echo "SYSTEM_MISSING"
```
Execute `skills/setup-workflow.md` Sync Workflow:
**If SYSTEM_MISSING:** Run `/initial-setup` first.
---
## Step 2: Read Current .env
```bash
cat .env 2>/dev/null
```
Extract `GITEA_ORG` and `GITEA_REPO` values.
**If missing:** Redirect to `/project-init`.
---
## Step 3: Detect Git Remote
```bash
git remote get-url origin 2>/dev/null
```
Extract organization and repository from URL.
---
## Step 4: Compare Values
| Scenario | Action |
|----------|--------|
| **Match** | "Configuration in sync" - exit |
| **Mismatch** | Show diff, proceed to validation |
---
## Step 5: Validate via Gitea API
```bash
source ~/.config/claude/gitea.env
curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos/<NEW_ORG>/<NEW_REPO>"
```
| Code | Action |
|------|--------|
| **200** | Verified - proceed to update |
| **404** | Not found - ask to confirm |
| **401/403** | Permission issue - warn |
---
## Step 6: Confirm and Update
Use AskUserQuestion to confirm, then update .env:
```bash
sed -i 's/^GITEA_ORG=.*/GITEA_ORG=<NEW_ORG>/' .env
sed -i 's/^GITEA_REPO=.*/GITEA_REPO=<NEW_REPO>/' .env
```
---
## Step 7: Confirm Success
```
╔══════════════════════════════════════════════════════════════╗
║ CONFIGURATION UPDATED ║
╠══════════════════════════════════════════════════════════════╣
║ Organization: <NEW_ORG> ║
║ Repository: <NEW_REPO> ║
╚══════════════════════════════════════════════════════════════╝
```
1. Verify system config exists
2. Read current .env values
3. Detect org/repo from git remote
4. Compare - if match, exit; if mismatch, continue
5. Validate new values via API
6. Update .env with sed
7. Display confirmation from `skills/output-formats.md`

View File

@@ -0,0 +1,80 @@
# MCP Tools Reference - Gitea PR Operations
## Available Tools
Use `ToolSearch` to load these tools before use.
### Pull Request Tools
| Tool | Purpose |
|------|---------|
| `mcp__gitea__list_pull_requests` | List PRs (open, closed, all) |
| `mcp__gitea__get_pull_request` | Get PR metadata, status, labels |
| `mcp__gitea__get_pr_diff` | Get unified diff of changes |
| `mcp__gitea__get_pr_comments` | Get review comments and discussions |
| `mcp__gitea__create_pr_review` | Submit review (approve, comment, request changes) |
| `mcp__gitea__add_pr_comment` | Add single comment to PR |
| `mcp__gitea__create_pull_request` | Create new PR |
### Supporting Tools
| Tool | Purpose |
|------|---------|
| `mcp__gitea__get_issue` | Get linked issue details |
| `mcp__gitea__get_labels` | Get available labels |
| `mcp__gitea__validate_repo_org` | Validate repository exists |
## Loading Tools
Before using MCP tools, load them:
```
Use ToolSearch with query: "+gitea pull_request"
```
## Common Operations
### Fetch PR for Review
```
1. get_pull_request(pr_number) -> metadata
2. get_pr_diff(pr_number) -> code changes
3. get_pr_comments(pr_number) -> existing feedback
```
### Submit Review
```
create_pr_review:
pr_number: number
body: string (review summary)
event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES"
comments: [{path, line, body}] (optional inline comments)
```
### Add Comment
```
add_pr_comment:
pr_number: number
body: string
```
## Environment Variables
Required in `.env`:
- `GITEA_ORG` - Organization/owner name
- `GITEA_REPO` - Repository name
Required in `~/.config/claude/gitea.env`:
- `GITEA_API_URL` - Gitea server URL
- `GITEA_API_TOKEN` - API token with repo permissions
## Error Handling
| Error | Cause | Resolution |
|-------|-------|------------|
| Tool not found | MCP not loaded | Run ToolSearch first |
| 401 Unauthorized | Invalid/expired token | Regenerate token |
| 404 Not Found | Wrong org/repo or PR doesn't exist | Check .env settings |
| 403 Forbidden | Insufficient permissions | Check token scopes |

View File

@@ -0,0 +1,200 @@
# Output Formats
## Visual Header
All commands display this header:
```
+----------------------------------------------------------------------+
| PR-REVIEW [Command Name] |
+----------------------------------------------------------------------+
```
## Review Report Format
```
===================================================
PR Review Report: #<number>
===================================================
Summary:
Files changed: <n>
Lines: +<added> / -<removed>
Agents consulted: <list>
Findings: <total>
Critical: <n>
Major: <n>
Minor: <n>
Suggestions: <n>
---------------------------------------------------
CRITICAL FINDINGS
---------------------------------------------------
[<ID>] <Title> (Confidence: <score>)
File: <path>:<line>
Category: <category>
<Description>
Suggested fix:
<code block>
---------------------------------------------------
VERDICT: <APPROVE|COMMENT|REQUEST_CHANGES>
---------------------------------------------------
<Justification>
```
## Summary Format
```
===================================================
PR Summary: #<number> - <title>
===================================================
Author: @<username>
Branch: <head> -> <base>
Status: <status>
---------------------------------------------------
CHANGES OVERVIEW
---------------------------------------------------
Files: <n> changed
+ <n> new files
~ <n> modified files
- <n> deleted files
Lines: +<added> / -<removed> (net +<diff>)
---------------------------------------------------
WHAT THIS PR DOES
---------------------------------------------------
<Plain-language description>
---------------------------------------------------
KEY FILES
---------------------------------------------------
* <path> (+<lines>) - <description>
---------------------------------------------------
QUICK ASSESSMENT
---------------------------------------------------
Scope: <Small|Medium|Large>
Risk: <Low|Medium|High>
Recommendation: <action>
===================================================
```
## Findings List Format
### Detailed (default)
```
===================================================
PR #<number> Findings (filtered: <filter>)
===================================================
Showing <n> of <total> findings
---------------------------------------------------
[<ID>] <Title>
Confidence: <score> (<label>) | Severity: <level>
File: <path>:<line>
<Description>
Fix: <suggestion>
---------------------------------------------------
```
### Compact (--compact)
```
<ID> | <Severity> | <Confidence> | <File>:<Line> | <Title>
```
### JSON (--json)
```json
{
"pr": <number>,
"findings": [
{
"id": "<ID>",
"category": "<category>",
"severity": "<severity>",
"confidence": <score>,
"file": "<path>",
"line": <number>,
"title": "<title>",
"description": "<description>",
"fix": "<suggestion>"
}
]
}
```
## Setup Complete Format
```
+============================================================+
| PR-REVIEW SETUP COMPLETE |
+============================================================+
| MCP Server (Gitea): Ready |
| System Config: ~/.config/claude/gitea.env |
| Project Config: ./.env |
+============================================================+
```
## Project Configured Format
```
+============================================================+
| PROJECT CONFIGURED |
+============================================================+
| Organization: <org> |
| Repository: <repo> |
| Config file: ./.env |
+============================================================+
Ready to review PRs:
- /pr-review <number> Full multi-agent review
- /pr-summary <number> Quick summary
- /pr-findings <number> List findings
```
## Annotated Diff Format
```
===================================================
PR #<number> Diff - <title>
===================================================
Branch: <head> -> <base>
Files: <n> changed (+<added> / -<removed>)
---------------------------------------------------
<file> (+<added> / -<removed>)
---------------------------------------------------
@@ -<old>,<ctx> +<new>,<ctx> @@ <context>
<line> | existing code
<line> |- removed code
| +--- COMMENT by @<user> (<time>) ---
| | <comment text>
| +-----------------------------------
<line> |+ added code
===================================================
Comment Summary: <n> comments, <n> resolved
===================================================
```

View File

@@ -0,0 +1,135 @@
# PR Analysis Patterns
## Data Collection
### Step 1: Fetch PR Metadata
```
get_pull_request(pr_number) returns:
- title, description
- author, assignees
- base/head branches
- status (open, closed, merged)
- labels, milestone
- created_at, updated_at
```
### Step 2: Get Code Changes
```
get_pr_diff(pr_number) returns:
- Unified diff format
- File paths with +/- indicators
- Hunk headers with line numbers
```
### Step 3: Get Existing Feedback
```
get_pr_comments(pr_number) returns:
- Review comments with file/line
- General comments
- Author, timestamp
- Thread context (replies)
```
## Change Analysis
### Categorize Changes
| Pattern | Category |
|---------|----------|
| New files only | Feature addition |
| Modified test files | Test updates |
| Modified + deleted | Refactoring |
| Single file fix | Bug fix |
| Config/docs only | Infrastructure |
### Calculate Statistics
- Files changed count
- Lines added/removed
- Net change (+added - removed)
- New vs modified vs deleted files
### Identify Key Files
Priority order:
1. Security-sensitive (`auth`, `crypto`, `sql`)
2. API endpoints
3. Database migrations
4. Core business logic
5. Utilities and helpers
6. Tests
7. Documentation
## Risk Assessment
### Scope Assessment
| Files Changed | Lines Changed | Scope |
|---------------|---------------|-------|
| 1-3 | < 50 | Small |
| 4-10 | 50-200 | Medium |
| 10+ | 200+ | Large |
### Risk Indicators
| Indicator | Risk Level |
|-----------|------------|
| Security-sensitive files | High |
| Database migrations | High |
| API changes | Medium |
| New dependencies | Medium |
| Test-only changes | Low |
| Docs-only changes | Low |
## Summary Generation
### Quick Summary Template
```
This PR [adds|updates|fixes|removes] [feature/component]:
1. **[Category 1]**
- Change description
2. **[Category 2]**
- Change description
Key files:
- path/to/important/file.ts (+lines)
```
### Assessment Template
```
Scope: [Small|Medium|Large]
Risk: [Low|Medium|High]
Recommendation: [/pr-review suggested | Looks good to merge]
```
## Annotated Diff Display
### Format
```
File: src/api/users.ts (+85 / -12)
----------------------------------------
@@ -42,6 +42,15 @@ function description
42 | existing line
43 |
44 |- removed line
| [COMMENT by @user (time ago)]
| Comment text here
45 |+ added line
46 |+ another added line
```
### Comment Overlay
Position comments at their file/line locations:
- Show commenter username and time
- Include reply threads
- Mark resolved vs open

View File

@@ -0,0 +1,78 @@
# Multi-Agent Review Workflow
## Overview
PR reviews use specialized agents that analyze different aspects of code changes. The coordinator dispatches to relevant agents and aggregates findings.
## Agent Roles
| Agent | Focus Area | File Patterns |
|-------|------------|---------------|
| **Security Reviewer** | Vulnerabilities, auth, injection | `*.ts`, `*.js`, `*.sql`, `*.py` |
| **Performance Analyst** | N+1, inefficient algorithms, memory | `*.ts`, `*.js`, `*.py`, `*.go` |
| **Maintainability Auditor** | Complexity, readability, DRY | All code files |
| **Test Validator** | Coverage, edge cases, assertions | `*.test.*`, `*_test.*`, `*_spec.*` |
## Dispatch Logic
1. **Analyze changed files** - Identify file types and patterns
2. **Select agents** - Match files to relevant agents
3. **Parallel dispatch** - Send review tasks to agents
4. **Collect findings** - Aggregate results from all agents
5. **Filter by confidence** - Apply threshold (default: 0.7)
6. **Generate report** - Structure findings by severity
### Skip Patterns
Don't dispatch agents for:
- `*.md`, `*.txt` - Documentation only
- `*.json` (config) - Unless security-sensitive
- Generated files - `*.min.js`, `*.d.ts`, etc.
## Finding Structure
Each finding includes:
```
{
id: "SEC-001",
category: "security" | "performance" | "maintainability" | "tests",
severity: "critical" | "major" | "minor" | "suggestion",
confidence: 0.0 - 1.0,
file: "src/api/users.ts",
line: 45,
title: "SQL Injection Vulnerability",
description: "Detailed explanation...",
fix: "Suggested code fix..." (optional)
}
```
## Verdict Logic
| Condition | Verdict |
|-----------|---------|
| Any critical finding | REQUEST_CHANGES |
| 2+ major findings | REQUEST_CHANGES |
| Only minor/suggestions | COMMENT |
| No significant findings | APPROVE |
## Confidence Thresholds
Reference: `skills/review-patterns/confidence-scoring.md`
| Range | Label | Action |
|-------|-------|--------|
| 0.9 - 1.0 | HIGH | Must address |
| 0.7 - 0.89 | MEDIUM | Should address |
| 0.5 - 0.69 | LOW | Consider addressing |
| < threshold | Filtered | Not shown |
Default threshold: 0.7 (MEDIUM and above)
## Aggregation Rules
When multiple agents find the same issue:
1. Keep highest confidence score
2. Merge descriptions
3. Use most severe category
4. Deduplicate fixes

View File

@@ -0,0 +1,104 @@
# Setup Workflow
## Configuration Hierarchy
| Level | Location | Contents |
|-------|----------|----------|
| System | `~/.config/claude/gitea.env` | API URL, token (shared across projects) |
| Project | `.env` in project root | Org, repo name (per project) |
## System Configuration
### Check Existing
```bash
cat ~/.config/claude/gitea.env 2>/dev/null | grep -v "^#" | grep "GITEA_API_TOKEN=" && echo "OK" || echo "MISSING"
```
### Create New
```bash
mkdir -p ~/.config/claude
cat > ~/.config/claude/gitea.env << 'EOF'
# Gitea API Configuration
GITEA_API_URL=https://your-gitea-server.com
GITEA_API_TOKEN=PASTE_YOUR_TOKEN_HERE
EOF
chmod 600 ~/.config/claude/gitea.env
```
### Token Generation
1. Gitea: Settings > Applications > Generate New Token
2. Required scopes: `repo`, `read:org`, `read:user`
## Project Configuration
### Auto-Detect from Git Remote
Extract organization:
```bash
git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\/[^/]*$/\1/'
```
Extract repository:
```bash
git remote get-url origin 2>/dev/null | sed 's/.*[:/]\([^/]*\)\.git$/\1/' | sed 's/.*\/\([^/]*\)$/\1/'
```
### Validate via API
```bash
source ~/.config/claude/gitea.env
curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GITEA_API_TOKEN" "$GITEA_API_URL/repos/<org>/<repo>"
```
| Code | Meaning |
|------|---------|
| 200 | Repository verified |
| 404 | Not found - check org/repo names |
| 401/403 | Auth issue - check token |
### Create/Update .env
```bash
# New file
cat > .env << EOF
GITEA_ORG=<org>
GITEA_REPO=<repo>
EOF
# Or append to existing
echo "GITEA_ORG=<org>" >> .env
echo "GITEA_REPO=<repo>" >> .env
```
## PR Review Settings (Optional)
| Variable | Default | Description |
|----------|---------|-------------|
| `PR_REVIEW_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence to report |
| `PR_REVIEW_AUTO_SUBMIT` | `false` | Auto-submit reviews to Gitea |
## Sync Workflow
When git remote changes:
1. Detect new org/repo from git remote
2. Compare with .env values
3. Validate new values via API
4. Update .env with sed:
```bash
sed -i 's/^GITEA_ORG=.*/GITEA_ORG=<new_org>/' .env
sed -i 's/^GITEA_REPO=.*/GITEA_REPO=<new_repo>/' .env
```
## Shared with projman
The Gitea MCP server is shared with the projman plugin. If projman is already configured, system-level setup can be skipped.
Check for projman:
```bash
find ~/.claude ~/.config/claude -name "projman" -type d 2>/dev/null | head -1
```