# JIRA MCP Integration Utility

## Purpose

Wrapper utility for Atlassian MCP tools providing simplified JIRA operations for BMAD integration tasks.

## MCP Availability Detection

### Check MCP Integration Status

Before any JIRA operations, verify MCP tools are available using your analytical capabilities:

**MCP Detection Strategy:**
Apply systematic verification to ensure JIRA tools are accessible:

- List available tools in your environment
- Filter for tools with prefix `mcp__mcp-atlassian__`
- Count matching tools to confirm availability
- Test basic connectivity if tools are found

**Availability Assessment:**
When checking MCP status, determine:

- **Available**: Atlassian MCP tools detected and accessible
- **Not Available**: No JIRA MCP tools found in environment
- **Partial**: Some tools present but not fully functional

**Setup Guidance:**
When MCP tools are not available, provide clear instructions:

```
JIRA MCP Setup Required:

1. Install Atlassian MCP tools:
   npm install -g @modelcontextprotocol/cli
   mcp install @modelcontextprotocol/atlassian

2. Configure JIRA connection:
   - JIRA instance URL (e.g., https://company.atlassian.net)
   - API token or authentication credentials
   - Project permissions

3. Verify connection:
   Test JIRA connectivity through MCP

4. Restart your IDE/environment to pick up new MCP tools
```

**Help References:**

- Natural setup: "Set up JIRA integration for our team"
- Documentation: https://docs.anthropic.com/en/docs/claude-code/mcp

**Error Handling Pattern:**
When MCP is unavailable, provide structured error response:

- Clear error message explaining the issue
- Setup instructions for resolution
- Alternative approaches if available
- Help command references

## Available Operations

### Authentication Setup

Before using JIRA operations, ensure MCP is configured with:

- JIRA instance URL
- API token or authentication credentials
- Project permissions

### Core Functions

#### 1. Search Issues

**Tool**: `mcp__mcp-atlassian__jira_search`
**Purpose**: Find issues using JQL queries

**Common Query Patterns:**

- Find by title: `summary ~ "story title"`
- Find in project: `project = PROJ`
- Find epics: `issuetype = Epic AND project = PROJ`
- Find by label: `labels = bmad-sync`

**Usage Guidelines:**

- Use JQL (JIRA Query Language) syntax
- Include field list for specific data
- Handle pagination for large results
- Filter by project when possible

#### 2. Get Issue Details

**Tool**: `mcp__mcp-atlassian__jira_get_issue`
**Purpose**: Retrieve full issue information

**Field Selection:**

- Use specific field names for efficiency
- Request "all details" for complete information
- Common fields: summary, status, assignee, priority
- Custom fields require exact IDs

#### 3. Create Issue

**Tool**: `mcp__mcp-atlassian__jira_create_issue`
**Purpose**: Create new JIRA issues

**Required Fields:**

- project_key: Target project identifier
- summary: Issue title
- issue_type: Bug, Story, Task, etc.

**Optional Fields:**

- description: Detailed information
- assignee: User identifier
- components: Component names
- additional_fields: Custom field values

#### 4. Update Issue

**Tool**: `mcp__mcp-atlassian__jira_update_issue`
**Purpose**: Update existing issues

**Capabilities:**

- All field updates
- Status transitions
- Attachment management
- Custom field modifications

#### 5. Field Detection

**Tool**: `mcp__mcp-atlassian__jira_search_fields`
**Purpose**: Auto-detect custom field IDs

**Common Searches:**

- "epic" for Epic Link field
- "sprint" for Sprint field
- "points" for Story Points field

**Usage Pattern:**

1. Search for field by keyword
2. Parse results for custom field IDs
3. Store IDs in configuration
4. Use IDs in create/update operations

#### 6. Status Transitions

**Get Transitions Tool**: `mcp__mcp-atlassian__jira_get_transitions`
**Purpose**: Get available status transitions

**Transition Tool**: `mcp__mcp-atlassian__jira_transition_issue`
**Purpose**: Change issue status

**Workflow Pattern:**

1. Get current issue status
2. Fetch available transitions
3. Find matching transition ID
4. Execute transition with required fields

#### 7. Bulk Operations

**Tool**: `mcp__mcp-atlassian__jira_batch_create_issues`
**Purpose**: Create multiple issues at once

**Format**: JSON array of issue objects
**Efficiency**: Reduces API calls for multiple issues
**Use Cases**: Story breakdowns, bulk imports

#### 8. Link Management

**Epic Linking Tool**: `mcp__mcp-atlassian__jira_link_to_epic`
**Purpose**: Link issues to epics

**General Linking Tool**: `mcp__mcp-atlassian__jira_create_issue_link`
**Purpose**: Create other issue links

**Link Types:**

- Blocks/Is Blocked By
- Relates To
- Duplicates
- Clones

## Common Patterns

### Auto-Detection Pattern

**Field Discovery Process:**

1. Use `jira_search_fields` with keywords:
   - "epic" for Epic Link field
   - "sprint" for Sprint field
   - "points" for Story Points field
2. Parse results for custom field IDs
3. Store in configuration for reuse
4. Apply in issue operations

**Implementation Strategy:**

- Cache discovered field IDs
- Validate fields before use
- Handle field permission errors
- Provide fallback options

### Issue Creation Pattern

**Standard Creation Flow:**

1. Prepare fields object with required fields
2. Add additional_fields for custom fields:
   - Epic link: `{'customfield_10014': epic_key}`
   - Sprint: `{'customfield_10020': sprint_id}`
   - Story points: `{'customfield_10016': points}`
3. Create issue and capture returned key
4. Add attachments if needed
5. Create links to related issues

### Status Sync Pattern

**Status Update Flow:**

1. Get issue current status
2. Get available transitions
3. Find matching transition for target status
4. Execute transition with any required fields
5. Verify status change completed

**Transition Mapping:**

- To Do → In Progress: "Start Progress"
- In Progress → Done: "Resolve Issue"
- Any → Closed: "Close Issue"

### Search Pattern

**Effective Search Strategy:**

1. Build JQL query with appropriate filters
2. Set appropriate field list for efficiency
3. Handle pagination if needed:
   - Use start_at and max_results
   - Iterate through pages
   - Aggregate results
4. Process and filter results
5. Handle no results gracefully

## Error Handling

### Automatic Retry Logic

[[LLM: Implement retry for transient failures:

1. Network errors: Retry 3 times with exponential backoff (1s, 2s, 4s)
2. Rate limits: Wait specified time or 60s default
3. Auth errors: Retry once after re-validation
4. Other errors: No automatic retry

Show user-friendly messages:

- "Connection hiccup, trying again..."
- "JIRA is busy, waiting a moment..."
- "Let me try that once more..."
  ]]

### Authentication Errors

**Common Causes:**

- Invalid API token
- Expired credentials
- Network connectivity issues

**Resolution Steps:**

- Verify MCP configuration
- Check API token validity
- Confirm project permissions
- Test with simple query first

### Field Not Found

**Common Causes:**

- Custom field doesn't exist
- No permission to view field
- Field name changed

**Resolution Steps:**

- Run field detection utility
- Check field permissions
- Try alternative field names
- Verify with JIRA admin

### Invalid Values

**Common Causes:**

- Wrong value format
- Value not in allowed list
- Type mismatch

**Resolution Steps:**

- Verify value formats
- Check allowed values via API
- Use field configuration endpoint
- Match exact case/format

### Permission Errors

**Common Causes:**

- User lacks project access
- Issue type restrictions
- Workflow permissions

**Resolution Steps:**

- Confirm user has project access
- Check issue type permissions
- Verify custom field visibility
- Review workflow restrictions

## Best Practices

### 1. Cache Field IDs

Store detected custom field IDs in configuration to avoid repeated lookups

### 2. Batch Operations

Use batch endpoints when processing multiple issues to reduce API calls

### 3. Field Validation

Verify fields exist before using them to avoid runtime errors

### 4. Error Recovery

Implement retry logic for transient failures with exponential backoff

### 5. Preview Mode

Always show what will change before executing modifications

## Integration with BMAD

When using in BMAD tasks, follow these guidelines:

### 1. Configuration Loading

- Load JIRA configuration first
- Validate required settings exist
- Use environment variables for secrets

### 2. Field Mapping

- Use field mappings from configuration
- Support both cloud and server field differences
- Handle missing custom fields gracefully

### 3. Audit Trail

- Maintain operation history in BMAD metadata
- Log all JIRA modifications
- Track sync timestamps

### 4. Error Messages

- Provide clear, actionable error messages
- Include setup instructions when needed
- Suggest alternative approaches

### 5. Performance

- Cache frequently used data
- Minimize API calls through batching
- Use appropriate field selections

## Common Integration Scenarios

### Story to JIRA Sync

1. Parse BMAD story format
2. Map to JIRA fields
3. Create or update issue
4. Store JIRA key in metadata

### Bug Analysis Workflow

1. Fetch bug details
2. Download attachments
3. Analyze content
4. Update bug with findings

### Sprint Planning

1. Get current sprint
2. List sprint issues
3. Update story points
4. Move issues to sprint

### Epic Management

1. Create epic from feature
2. Link stories to epic
3. Track epic progress
4. Update epic status
