This is page 1 of 2. Use http://codebase.md/nguyenvanduocit/jira-mcp?page={x} to view the full context. # Directory Structure ``` ├── .claude │ └── commands │ ├── speckit.analyze.md │ ├── speckit.checklist.md │ ├── speckit.clarify.md │ ├── speckit.constitution.md │ ├── speckit.implement.md │ ├── speckit.plan.md │ ├── speckit.specify.md │ └── speckit.tasks.md ├── .github │ ├── ISSUE_TEMPLATE │ │ ├── bug_report.md │ │ └── feature_request.md │ └── workflows │ ├── gitleaks.yaml │ ├── release.yaml │ └── scan.yaml ├── .gitignore ├── .specify │ ├── memory │ │ └── constitution.md │ ├── scripts │ │ └── bash │ │ ├── check-prerequisites.sh │ │ ├── common.sh │ │ ├── create-new-feature.sh │ │ ├── setup-plan.sh │ │ └── update-agent-context.sh │ └── templates │ ├── agent-file-template.md │ ├── checklist-template.md │ ├── plan-template.md │ ├── spec-template.md │ └── tasks-template.md ├── CHANGELOG.md ├── CLAUDE.md ├── Dockerfile ├── go.mod ├── go.sum ├── LICENSE ├── main.go ├── prompts │ └── jira_prompts.go ├── README.md ├── services │ ├── atlassian.go │ ├── httpclient.go │ └── jira.go ├── specs │ └── 001-i-want-to │ ├── api-research.md │ ├── checklists │ │ ├── implementation-readiness.md │ │ └── requirements.md │ ├── contracts │ │ └── mcp-tool-contract.json │ ├── data-model.md │ ├── plan.md │ ├── quickstart.md │ ├── research.md │ ├── spec.md │ ├── tasks.md │ ├── test-dev-api.sh │ └── test-get-build.sh ├── tools │ ├── jira_comment.go │ ├── jira_development.go │ ├── jira_history.go │ ├── jira_issue.go │ ├── jira_relationship.go │ ├── jira_search.go │ ├── jira_sprint.go │ ├── jira_status.go │ ├── jira_transition.go │ ├── jira_version.go │ └── jira_worklog.go └── util ├── jira_formatter.go └── README.md ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` # Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) # vendor/ # Go workspace file go.work # Environment variables .env # IDE specific files .idea/ .vscode/ *.swp *.swo # OS specific files .DS_Store Thumbs.db # Build directory /build/ /dist/ jira-mcp ``` -------------------------------------------------------------------------------- /util/README.md: -------------------------------------------------------------------------------- ```markdown # Jira Formatter Utilities This package provides utility functions for formatting Jira issues from golang structs to human-readable string representations. ## Functions ### `FormatJiraIssue(issue *models.IssueScheme) string` Converts a complete Jira issue struct to a detailed, formatted string representation. This function handles all available fields from the `IssueFieldsSchemeV2` struct and related schemas. **Features:** - Basic issue information (Key, ID, URL) - Complete field information (Summary, Description, Type, Status, Priority, etc.) - People information (Reporter, Assignee, Creator) with email addresses when available - Date fields (Created, Updated, Last Viewed, etc.) - Project and parent issue information - Work-related fields (Work Ratio, Story Points) - Collections (Labels, Components, Fix Versions, Affected Versions) - Relationships (Subtasks, Issue Links) - Activity summaries (Watchers, Votes, Comments count, Worklogs count) - Available transitions - Security information **Usage:** ```go import "github.com/nguyenvanduocit/jira-mcp/util" // Get a Jira issue from the API issue, _, _ := client.Issue.Get(ctx, "PROJ-123", nil, []string{"transitions", "changelog"}) // Format it for display formattedOutput := util.FormatJiraIssue(issue) fmt.Println(formattedOutput) ``` ### `FormatJiraIssueCompact(issue *models.IssueSchemeV2) string` Returns a compact, single-line representation of a Jira issue suitable for lists or search results. **Features:** - Key, Summary, Status, Assignee, Priority - Pipe-separated format for easy scanning - Null-safe handling **Usage:** ```go // For search results or lists for _, issue := range searchResults.Issues { compactLine := util.FormatJiraIssueCompact(issue) fmt.Println(compactLine) } ``` **Example Output:** ``` Key: PROJ-123 | Summary: Fix login bug | Status: In Progress | Assignee: John Doe | Priority: High ``` ## Refactoring Benefits These utility functions were extracted from duplicate formatting logic in: - `tools/jira_issue.go` - Get Issue handler - `tools/jira_search.go` - Search Issues handler **Benefits:** 1. **DRY Principle**: Eliminates code duplication 2. **Comprehensive**: Handles all fields from the Jira issue struct 3. **Consistent**: Ensures uniform formatting across all tools 4. **Maintainable**: Single location for formatting logic updates 5. **Flexible**: Provides both detailed and compact formatting options 6. **Robust**: Includes null-safe handling for all optional fields ## Implementation Notes - All fields are handled with null-safe checks to prevent panics - Optional fields gracefully show "None", "Unassigned", or are omitted when empty - Collections (arrays/slices) are formatted as lists when present - Story point estimates are extracted from changelog history when available - Email addresses are shown in parentheses when available for user fields ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown ## Jira MCP An opinionated Jira MCP server built from years of real-world software development experience. Unlike generic Jira integrations, this MCP is crafted from the daily workflows of engineers and automation QC teams. You'll find sophisticated tools designed for actual development needs—like retrieving all pull requests linked to an issue, managing complex sprint transitions, or tracking development information across your entire workflow. This isn't just another API wrapper. It's a reflection of how professionals actually use Jira: managing sprints, tracking development work, coordinating releases, and maintaining visibility across teams. Every tool is designed to solve real problems that arise in modern software development. ## Available tools ### Issue Management - **jira_get_issue** - Retrieve detailed information about a specific issue including status, assignee, description, subtasks, and available transitions - **jira_create_issue** - Create a new issue with specified details (returns key, ID, and URL) - **jira_create_child_issue** - Create a child issue (sub-task) linked to a parent issue - **jira_update_issue** - Modify an existing issue's details (supports partial updates) - **jira_list_issue_types** - List all available issue types in a project with their IDs, names, and descriptions ### Search - **jira_search_issue** - Search for issues using JQL (Jira Query Language) with customizable fields and expand options ### Sprint Management - **jira_list_sprints** - List all active and future sprints for a specific board or project - **jira_get_sprint** - Retrieve detailed information about a specific sprint by its ID - **jira_get_active_sprint** - Get the currently active sprint for a given board or project - **jira_search_sprint_by_name** - Search for sprints by name with exact or partial matching ### Status & Transitions - **jira_list_statuses** - Retrieve all available issue status IDs and their names for a project - **jira_transition_issue** - Transition an issue through its workflow using a valid transition ID ### Comments - **jira_add_comment** - Add a comment to an issue (uses Atlassian Document Format) - **jira_get_comments** - Retrieve all comments from an issue ### Worklogs - **jira_add_worklog** - Add a worklog entry to track time spent on an issue ### History & Audit - **jira_get_issue_history** - Retrieve the complete change history of an issue ### Issue Relationships - **jira_get_related_issues** - Retrieve issues that have a relationship (blocks, is blocked by, relates to, etc.) - **jira_link_issues** - Create a link between two issues, defining their relationship ### Version Management - **jira_get_version** - Retrieve detailed information about a specific project version - **jira_list_project_versions** - List all versions in a project with their details ### Development Information - **jira_get_development_information** - Retrieve branches, pull requests, and commits linked to an issue via development tool integrations (GitHub, GitLab, Bitbucket) ## Installation Copy this prompt to your AI assistant: ``` Install the Jira MCP server (https://github.com/nguyenvanduocit/jira-mcp) for my Claude Desktop or Cursor IDE. Read the MCP documentation carefully and guide me through the installation step by step. ``` If your AI assistant cannot help with this installation, it indicates either a misconfiguration or an ineffective AI tool. A capable AI assistant should be able to guide you through MCP installation. ## License MIT — see `LICENSE`. ## FOR AI > THIS SECTION IS FOR AI ONLY When working with this codebase, read these files to understand the project structure: 1. **CLAUDE.md** - Comprehensive project documentation including architecture, development commands, and coding conventions 2. **main.go** - Entry point that shows how the MCP server is initialized and tools are registered 3. **services/jira_client.go** - Singleton Jira client initialization and authentication 4. **tools/** - Individual tool implementations following consistent patterns 5. **docs/** - Detailed documentation (see structure below) Key concepts: - This is a Go-based MCP server that connects AI assistants to Jira - Each tool follows a registration + handler pattern with typed input validation - Tools are organized by category (issues, sprints, comments, worklogs, etc.) - All Jira operations use the `github.com/ctreminiom/go-atlassian` client library - Development principles documented in `.specify/memory/constitution.md` Before making changes, review: - **CLAUDE.md** for architecture patterns and development commands - **.specify/memory/constitution.md** for governance principles ## Quick start ### 1) Get an API token Create one at `https://id.atlassian.com/manage-profile/security/api-tokens`. ### 2) Add to Cursor Use Docker or a local binary (STDIO; no ports needed). #### Docker ```json { "mcpServers": { "jira": { "command": "docker", "args": [ "run", "--rm", "-i", "-e", "ATLASSIAN_HOST=https://your-company.atlassian.net", "-e", "[email protected]", "-e", "ATLASSIAN_TOKEN=your-api-token", "ghcr.io/nguyenvanduocit/jira-mcp:latest" ] } } } ``` #### Binary ```json { "mcpServers": { "jira": { "command": "/usr/local/bin/jira-mcp", "env": { "ATLASSIAN_HOST": "https://your-company.atlassian.net", "ATLASSIAN_EMAIL": "[email protected]", "ATLASSIAN_TOKEN": "your-api-token" } } } } ``` ### 3) Try it in Cursor - “Show my issues assigned to me” - “What’s in the current sprint for ABC?” - “Create a bug in ABC: Login fails on Safari” ## Configuration - **ATLASSIAN_HOST**: `https://your-company.atlassian.net` - **ATLASSIAN_EMAIL**: your Atlassian email - **ATLASSIAN_TOKEN**: API token Optional `.env` (if running locally): ```bash ATLASSIAN_HOST=https://your-company.atlassian.net [email protected] ATLASSIAN_TOKEN=your-api-token ``` HTTP mode (optional, for debugging): ```bash jira-mcp -env .env -http_port 3000 ``` Cursor config (HTTP mode): ```json { "mcpServers": { "jira": { "url": "http://localhost:3000/mcp" } } } ``` ``` -------------------------------------------------------------------------------- /CLAUDE.md: -------------------------------------------------------------------------------- ```markdown # CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview This is a Jira MCP (Model Control Protocol) connector written in Go that enables AI assistants like Claude to interact with Atlassian Jira. The project provides a comprehensive set of tools for managing Jira issues, sprints, comments, worklogs, and more through structured MCP tool calls. ## Development Commands ```bash # Build the project go build -o jira-mcp . # Run in development mode with HTTP server (requires .env file) go run . --env .env --http_port 3002 # Run tests go test ./... # Install locally go install # Use go doc to understand packages and types go doc <pkg> go doc <sym>[.<methodOrField>] ``` ## Architecture Overview ### Core Structure - **main.go** - Entry point that initializes the MCP server, validates environment variables, and registers all tools - **services/** - Service layer containing Jira client setup and authentication - **tools/** - Tool implementations organized by functionality (issues, sprints, comments, etc.) - **util/** - Utility functions for error handling and response formatting ### Key Dependencies - `github.com/ctreminiom/go-atlassian` - Go client library for Atlassian APIs - `github.com/mark3labs/mcp-go` - Go implementation of Model Control Protocol - `github.com/joho/godotenv` - Environment variable loading ### Tool Implementation Pattern Each Jira operation follows this consistent pattern using **typed handlers**: 1. **Input Struct** - Define typed input with validation tags 2. **Registration Function** (`RegisterJira<Category>Tool`) - Creates tool definitions and registers them with the MCP server 3. **Typed Handler Function** - Processes tool calls with compile-time type safety Example tool structure: ```go // 1. Define input struct with validation type GetIssueInput struct { IssueKey string `json:"issue_key" validate:"required"` Fields string `json:"fields,omitempty"` Expand string `json:"expand,omitempty"` } // 2. Registration function func RegisterJiraIssueTool(s *server.MCPServer) { tool := mcp.NewTool("jira_get_issue", mcp.WithDescription("..."), mcp.WithString("issue_key", mcp.Required(), mcp.Description("...")), mcp.WithString("fields", mcp.Description("...")), ) s.AddTool(tool, mcp.NewTypedToolHandler(jiraGetIssueHandler)) } // 3. Typed handler with automatic validation func jiraGetIssueHandler(ctx context.Context, request mcp.CallToolRequest, input GetIssueInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Direct access to validated parameters - no type assertions needed issue, response, err := client.Issue.Get(ctx, input.IssueKey, fields, expand) if err != nil { return nil, fmt.Errorf("failed to get issue: %v", err) } return mcp.NewToolResultText(util.FormatIssue(issue)), nil } ``` ### Available Tool Categories - **Issue Management** - Create, read, update issues and subtasks - **Search** - JQL-based issue searching - **Sprint Management** - List sprints, move issues between sprints - **Status & Transitions** - Get available statuses and transition issues - **Comments** - Add and retrieve issue comments (uses Atlassian Document Format) - **Worklogs** - Time tracking functionality - **History** - Issue change history and audit logs - **Relationships** - Link and relate issues - **Versions** - Project version management - **Development Information** - Retrieve branches, pull requests, and commits linked to issues ## Configuration The application requires these environment variables: - `ATLASSIAN_HOST` - Your Atlassian instance URL (e.g., https://company.atlassian.net) - `ATLASSIAN_EMAIL` - Your Atlassian account email - `ATLASSIAN_TOKEN` - API token from Atlassian Environment variables can be loaded from a `.env` file using the `--env` flag. ## Service Architecture ### Jira Client Initialization The `services.JiraClient()` function uses `sync.OnceValue` to create a singleton Jira client instance with basic authentication. This ensures efficient connection reuse across all tool calls. ### HTTP vs STDIO Modes The server can run in two modes: - **STDIO mode** (default) - Standard MCP protocol over stdin/stdout - **HTTP mode** (`--http_port` flag) - HTTP server for development and testing ## Testing and Deployment The project includes: - Docker support with multi-stage builds - GitHub Actions for automated releases - Binary releases for multiple platforms (macOS, Linux, Windows) ## Code Conventions - Use structured input types for tool parameters with JSON tags and validation - All tool handlers should return `*mcp.CallToolResult` with formatted text or JSON - Client initialization should use the singleton pattern from services package - Response formatting should be human-readable for AI consumption - Comments MUST use Atlassian Document Format (ADF) with proper structure: ```go // ADF structure for comments Body: &models.CommentNodeScheme{ Version: 1, Type: "doc", Content: []*models.CommentNodeScheme{ { Type: "paragraph", Content: []*models.CommentNodeScheme{ {Type: "text", Text: "comment text"}, }, }, }, } ``` ## Governance This project follows strict governance principles documented in `.specify/memory/constitution.md`. Key principles include: - **MCP Protocol Compliance** - All functionality MUST be exposed as MCP tools - **AI-First Output Design** - Responses formatted for LLM consumption - **Simplicity Over Abstraction** - Avoid unnecessary helper functions and layers - **Type Safety & Validation** - Use typed handlers with input structs - **Resource Efficiency** - Singleton pattern for client connections - **Error Transparency** - Include endpoint context in error messages Before implementing new features or making changes, consult the constitution for detailed requirements and patterns. ``` -------------------------------------------------------------------------------- /.github/workflows/scan.yaml: -------------------------------------------------------------------------------- ```yaml name: Security and Licence Scan on: pull_request: jobs: test: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 - name: Secret Scanning uses: trufflesecurity/trufflehog@main with: extra_args: --results=verified,unknown ``` -------------------------------------------------------------------------------- /.github/workflows/gitleaks.yaml: -------------------------------------------------------------------------------- ```yaml name: gitleaks on: pull_request: push: workflow_dispatch: schedule: - cron: "0 4 * * *" jobs: scan: name: gitleaks runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: gitleaks/gitleaks-action@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- ```dockerfile FROM golang:1.23-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . # Use build arguments for cross-compilation ARG TARGETOS ARG TARGETARCH RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -o jira-mcp . FROM alpine:latest WORKDIR /app COPY --from=builder /app/jira-mcp . # Expose port for SSE server (optional) EXPOSE 8080 ENTRYPOINT ["/app/jira-mcp"] CMD [] ``` -------------------------------------------------------------------------------- /.specify/templates/agent-file-template.md: -------------------------------------------------------------------------------- ```markdown # [PROJECT NAME] Development Guidelines Auto-generated from all feature plans. Last updated: [DATE] ## Active Technologies [EXTRACTED FROM ALL PLAN.MD FILES] ## Project Structure ``` [ACTUAL STRUCTURE FROM PLANS] ``` ## Commands [ONLY COMMANDS FOR ACTIVE TECHNOLOGIES] ## Code Style [LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE] ## Recent Changes [LAST 3 FEATURES AND WHAT THEY ADDED] <!-- MANUAL ADDITIONS START --> <!-- MANUAL ADDITIONS END --> ``` -------------------------------------------------------------------------------- /services/httpclient.go: -------------------------------------------------------------------------------- ```go package services import ( "crypto/tls" "fmt" "net/http" "net/url" "os" "sync" ) var DefaultHttpClient = sync.OnceValue(func() *http.Client { transport := &http.Transport{} proxyURL := os.Getenv("PROXY_URL") if proxyURL != "" { proxy, err := url.Parse(proxyURL) if err != nil { panic(fmt.Sprintf("Failed to parse PROXY_URL: %v", err)) } transport.Proxy = http.ProxyURL(proxy) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} } return &http.Client{Transport: transport} }) ``` -------------------------------------------------------------------------------- /services/jira.go: -------------------------------------------------------------------------------- ```go package services import ( "log" "sync" jira "github.com/ctreminiom/go-atlassian/jira/v3" "github.com/pkg/errors" ) var JiraClient = sync.OnceValue[*jira.Client](func() *jira.Client { host, mail, token := loadAtlassianCredentials() if host == "" || mail == "" || token == "" { log.Fatal("ATLASSIAN_HOST, ATLASSIAN_EMAIL, ATLASSIAN_TOKEN are required") } instance, err := jira.New(nil, host) if err != nil { log.Fatal(errors.WithMessage(err, "failed to create jira client")) } instance.Auth.SetBasicAuth(mail, token) return instance }) ``` -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- ```markdown --- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ``` -------------------------------------------------------------------------------- /services/atlassian.go: -------------------------------------------------------------------------------- ```go package services import ( "log" "os" "sync" "github.com/ctreminiom/go-atlassian/jira/agile" "github.com/pkg/errors" ) func loadAtlassianCredentials() (host, mail, token string) { host = os.Getenv("ATLASSIAN_HOST") mail = os.Getenv("ATLASSIAN_EMAIL") token = os.Getenv("ATLASSIAN_TOKEN") if host == "" || mail == "" || token == "" { log.Fatal("ATLASSIAN_HOST, ATLASSIAN_EMAIL, ATLASSIAN_TOKEN are required, please set it in MCP Config") } return host, mail, token } var AgileClient = sync.OnceValue[*agile.Client](func() *agile.Client { host, mail, token := loadAtlassianCredentials() instance, err := agile.New(nil, host) if err != nil { log.Fatal(errors.WithMessage(err, "failed to create agile client")) } instance.Auth.SetBasicAuth(mail, token) return instance }) ``` -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- ```markdown --- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here. ``` -------------------------------------------------------------------------------- /.specify/templates/checklist-template.md: -------------------------------------------------------------------------------- ```markdown # [CHECKLIST TYPE] Checklist: [FEATURE NAME] **Purpose**: [Brief description of what this checklist covers] **Created**: [DATE] **Feature**: [Link to spec.md or relevant documentation] **Note**: This checklist is generated by the `/speckit.checklist` command based on feature context and requirements. <!-- ============================================================================ IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only. The /speckit.checklist command MUST replace these with actual items based on: - User's specific checklist request - Feature requirements from spec.md - Technical context from plan.md - Implementation details from tasks.md DO NOT keep these sample items in the generated checklist file. ============================================================================ --> ## [Category 1] - [ ] CHK001 First checklist item with clear action - [ ] CHK002 Second checklist item - [ ] CHK003 Third checklist item ## [Category 2] - [ ] CHK004 Another category item - [ ] CHK005 Item with specific criteria - [ ] CHK006 Final item in this category ## Notes - Check items off as completed: `[x]` - Add comments or findings inline - Link to relevant resources or documentation - Items are numbered sequentially for easy reference ``` -------------------------------------------------------------------------------- /specs/001-i-want-to/checklists/requirements.md: -------------------------------------------------------------------------------- ```markdown # Specification Quality Checklist: Retrieve Development Information from Jira Issue **Purpose**: Validate specification completeness and quality before proceeding to planning **Created**: 2025-10-07 **Feature**: [spec.md](../spec.md) ## Content Quality - [x] No implementation details (languages, frameworks, APIs) - [x] Focused on user value and business needs - [x] Written for non-technical stakeholders - [x] All mandatory sections completed ## Requirement Completeness - [x] No [NEEDS CLARIFICATION] markers remain - [x] Requirements are testable and unambiguous - [x] Success criteria are measurable - [x] Success criteria are technology-agnostic (no implementation details) - [x] All acceptance scenarios are defined - [x] Edge cases are identified - [x] Scope is clearly bounded - [x] Dependencies and assumptions identified ## Feature Readiness - [x] All functional requirements have clear acceptance criteria - [x] User scenarios cover primary flows - [x] Feature meets measurable outcomes defined in Success Criteria - [x] No implementation details leak into specification ## Notes **Clarification Resolved**: FR-011 now specifies using Jira's standard `/rest/dev-status/1.0/issue/detail` endpoint via the go-atlassian client. **Validation Status**: ✅ All checklist items pass. Specification is ready for `/speckit.plan` phase. ``` -------------------------------------------------------------------------------- /specs/001-i-want-to/test-get-build.sh: -------------------------------------------------------------------------------- ```bash #!/bin/bash # Load environment variables from .env file set -a source "$(dirname "$0")/../../.env" set +a JIRA_HOST="${ATLASSIAN_HOST}" JIRA_EMAIL="${ATLASSIAN_EMAIL}" JIRA_TOKEN="${ATLASSIAN_TOKEN}" ISSUE_KEY="SHTP-6050" echo "=========================================" echo "Step 1: Getting numeric issue ID for ${ISSUE_KEY}" echo "=========================================" ISSUE_RESPONSE=$(curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/api/3/issue/${ISSUE_KEY}?fields=id") echo "$ISSUE_RESPONSE" | jq '.' ISSUE_ID=$(echo "$ISSUE_RESPONSE" | jq -r '.id') if [ -z "$ISSUE_ID" ] || [ "$ISSUE_ID" = "null" ]; then echo "ERROR: Could not get issue ID" exit 1 fi echo "" echo "Issue ID: ${ISSUE_ID}" echo "" echo "=========================================" echo "Step 2: Getting development summary" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/summary?issueId=${ISSUE_ID}" | jq '.' echo "" echo "=========================================" echo "Step 8: Getting build information - cloud-providers" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=cloud-providers&dataType=build" | jq '.' ``` -------------------------------------------------------------------------------- /.specify/scripts/bash/setup-plan.sh: -------------------------------------------------------------------------------- ```bash #!/usr/bin/env bash set -e # Parse command line arguments JSON_MODE=false ARGS=() for arg in "$@"; do case "$arg" in --json) JSON_MODE=true ;; --help|-h) echo "Usage: $0 [--json]" echo " --json Output results in JSON format" echo " --help Show this help message" exit 0 ;; *) ARGS+=("$arg") ;; esac done # Get script directory and load common functions SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/common.sh" # Get all paths and variables from common functions eval $(get_feature_paths) # Check if we're on a proper feature branch (only for git repos) check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1 # Ensure the feature directory exists mkdir -p "$FEATURE_DIR" # Copy plan template if it exists TEMPLATE="$REPO_ROOT/.specify/templates/plan-template.md" if [[ -f "$TEMPLATE" ]]; then cp "$TEMPLATE" "$IMPL_PLAN" echo "Copied plan template to $IMPL_PLAN" else echo "Warning: Plan template not found at $TEMPLATE" # Create a basic plan file if template doesn't exist touch "$IMPL_PLAN" fi # Output results if $JSON_MODE; then printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","SPECS_DIR":"%s","BRANCH":"%s","HAS_GIT":"%s"}\n' \ "$FEATURE_SPEC" "$IMPL_PLAN" "$FEATURE_DIR" "$CURRENT_BRANCH" "$HAS_GIT" else echo "FEATURE_SPEC: $FEATURE_SPEC" echo "IMPL_PLAN: $IMPL_PLAN" echo "SPECS_DIR: $FEATURE_DIR" echo "BRANCH: $CURRENT_BRANCH" echo "HAS_GIT: $HAS_GIT" fi ``` -------------------------------------------------------------------------------- /tools/jira_status.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "strings" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for typed tools type ListStatusesInput struct { ProjectKey string `json:"project_key" validate:"required"` } func RegisterJiraStatusTool(s *server.MCPServer) { jiraStatusListTool := mcp.NewTool("jira_list_statuses", mcp.WithDescription("Retrieve all available issue status IDs and their names for a specific Jira project"), mcp.WithString("project_key", mcp.Required(), mcp.Description("Project identifier (e.g., KP, PROJ)")), ) s.AddTool(jiraStatusListTool, mcp.NewTypedToolHandler(jiraGetStatusesHandler)) } func jiraGetStatusesHandler(ctx context.Context, request mcp.CallToolRequest, input ListStatusesInput) (*mcp.CallToolResult, error) { client := services.JiraClient() issueTypes, response, err := client.Project.Statuses(ctx, input.ProjectKey) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get statuses: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get statuses: %v", err) } if len(issueTypes) == 0 { return mcp.NewToolResultText("No issue types found for this project."), nil } var result strings.Builder result.WriteString("Available Statuses:\n") for _, issueType := range issueTypes { result.WriteString(fmt.Sprintf("\nIssue Type: %s\n", issueType.Name)) for _, status := range issueType.Statuses { result.WriteString(fmt.Sprintf(" - %s: %s\n", status.Name, status.ID)) } } return mcp.NewToolResultText(result.String()), nil } ``` -------------------------------------------------------------------------------- /tools/jira_transition.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "github.com/ctreminiom/go-atlassian/pkg/infra/models" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for typed tools type TransitionIssueInput struct { IssueKey string `json:"issue_key" validate:"required"` TransitionID string `json:"transition_id" validate:"required"` Comment string `json:"comment,omitempty"` } func RegisterJiraTransitionTool(s *server.MCPServer) { jiraTransitionTool := mcp.NewTool("jira_transition_issue", mcp.WithDescription("Transition an issue through its workflow using a valid transition ID. Get available transitions from jira_get_issue"), mcp.WithString("issue_key", mcp.Required(), mcp.Description("The issue to transition (e.g., KP-123)")), mcp.WithString("transition_id", mcp.Required(), mcp.Description("Transition ID from available transitions list")), mcp.WithString("comment", mcp.Description("Optional comment to add with transition")), ) s.AddTool(jiraTransitionTool, mcp.NewTypedToolHandler(jiraTransitionIssueHandler)) } func jiraTransitionIssueHandler(ctx context.Context, request mcp.CallToolRequest, input TransitionIssueInput) (*mcp.CallToolResult, error) { client := services.JiraClient() var options *models.IssueMoveOptionsV3 if input.Comment != "" { options = &models.IssueMoveOptionsV3{ Fields: &models.IssueScheme{}, } } response, err := client.Issue.Move(ctx, input.IssueKey, input.TransitionID, options) if err != nil { if response != nil { return nil, fmt.Errorf("transition failed: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("transition failed: %v", err) } return mcp.NewToolResultText("Issue transition completed successfully"), nil } ``` -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- ```yaml name: Release Please and GoReleaser on: push: branches: - main permissions: contents: write pull-requests: write packages: write jobs: release-please: runs-on: ubuntu-latest outputs: release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} steps: - uses: googleapis/release-please-action@v4 id: release with: token: ${{ secrets.GITHUB_TOKEN }} release-type: go goreleaser: needs: release-please if: ${{ needs.release-please.outputs.release_created }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Go uses: actions/setup-go@v5 - name: Run GoReleaser uses: goreleaser/goreleaser-action@v6 with: distribution: goreleaser version: latest args: release --clean env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} docker: needs: release-please if: ${{ needs.release-please.outputs.release_created }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Login to GitHub Container Registry uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.repository_owner }} password: ${{ secrets.GITHUB_TOKEN }} - name: Extract metadata for Docker id: meta uses: docker/metadata-action@v5 with: images: ghcr.io/${{ github.repository }} tags: | type=semver,pattern={{version}},value=${{ needs.release-please.outputs.tag_name }} type=semver,pattern={{major}}.{{minor}},value=${{ needs.release-please.outputs.tag_name }} type=semver,pattern={{major}},value=${{ needs.release-please.outputs.tag_name }} type=raw,value=latest - name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . platforms: linux/amd64,linux/arm64 push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} provenance: false sbom: false cache-from: type=gha cache-to: type=gha,mode=max ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.plan.md: -------------------------------------------------------------------------------- ```markdown --- description: Execute the implementation planning workflow using the plan template to generate design artifacts. --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Outline 1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH. 2. **Load context**: Read FEATURE_SPEC and `.specify.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied). 3. **Execute plan workflow**: Follow the structure in IMPL_PLAN template to: - Fill Technical Context (mark unknowns as "NEEDS CLARIFICATION") - Fill Constitution Check section from constitution - Evaluate gates (ERROR if violations unjustified) - Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION) - Phase 1: Generate data-model.md, contracts/, quickstart.md - Phase 1: Update agent context by running the agent script - Re-evaluate Constitution Check post-design 4. **Stop and report**: Command ends after Phase 2 planning. Report branch, IMPL_PLAN path, and generated artifacts. ## Phases ### Phase 0: Outline & Research 1. **Extract unknowns from Technical Context** above: - For each NEEDS CLARIFICATION → research task - For each dependency → best practices task - For each integration → patterns task 2. **Generate and dispatch research agents**: ``` For each unknown in Technical Context: Task: "Research {unknown} for {feature context}" For each technology choice: Task: "Find best practices for {tech} in {domain}" ``` 3. **Consolidate findings** in `research.md` using format: - Decision: [what was chosen] - Rationale: [why chosen] - Alternatives considered: [what else evaluated] **Output**: research.md with all NEEDS CLARIFICATION resolved ### Phase 1: Design & Contracts **Prerequisites:** `research.md` complete 1. **Extract entities from feature spec** → `data-model.md`: - Entity name, fields, relationships - Validation rules from requirements - State transitions if applicable 2. **Generate API contracts** from functional requirements: - For each user action → endpoint - Use standard REST/GraphQL patterns - Output OpenAPI/GraphQL schema to `/contracts/` 3. **Agent context update**: - Run `.specify/scripts/bash/update-agent-context.sh claude` - These scripts detect which AI agent is in use - Update the appropriate agent-specific context file - Add only new technology from current plan - Preserve manual additions between markers **Output**: data-model.md, /contracts/*, quickstart.md, agent-specific file ## Key rules - Use absolute paths - ERROR on gate failures or unresolved clarifications ``` -------------------------------------------------------------------------------- /.specify/scripts/bash/create-new-feature.sh: -------------------------------------------------------------------------------- ```bash #!/usr/bin/env bash set -e JSON_MODE=false ARGS=() for arg in "$@"; do case "$arg" in --json) JSON_MODE=true ;; --help|-h) echo "Usage: $0 [--json] <feature_description>"; exit 0 ;; *) ARGS+=("$arg") ;; esac done FEATURE_DESCRIPTION="${ARGS[*]}" if [ -z "$FEATURE_DESCRIPTION" ]; then echo "Usage: $0 [--json] <feature_description>" >&2 exit 1 fi # Function to find the repository root by searching for existing project markers find_repo_root() { local dir="$1" while [ "$dir" != "/" ]; do if [ -d "$dir/.git" ] || [ -d "$dir/.specify" ]; then echo "$dir" return 0 fi dir="$(dirname "$dir")" done return 1 } # Resolve repository root. Prefer git information when available, but fall back # to searching for repository markers so the workflow still functions in repositories that # were initialised with --no-git. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" if git rev-parse --show-toplevel >/dev/null 2>&1; then REPO_ROOT=$(git rev-parse --show-toplevel) HAS_GIT=true else REPO_ROOT="$(find_repo_root "$SCRIPT_DIR")" if [ -z "$REPO_ROOT" ]; then echo "Error: Could not determine repository root. Please run this script from within the repository." >&2 exit 1 fi HAS_GIT=false fi cd "$REPO_ROOT" SPECS_DIR="$REPO_ROOT/specs" mkdir -p "$SPECS_DIR" HIGHEST=0 if [ -d "$SPECS_DIR" ]; then for dir in "$SPECS_DIR"/*; do [ -d "$dir" ] || continue dirname=$(basename "$dir") number=$(echo "$dirname" | grep -o '^[0-9]\+' || echo "0") number=$((10#$number)) if [ "$number" -gt "$HIGHEST" ]; then HIGHEST=$number; fi done fi NEXT=$((HIGHEST + 1)) FEATURE_NUM=$(printf "%03d" "$NEXT") BRANCH_NAME=$(echo "$FEATURE_DESCRIPTION" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//') WORDS=$(echo "$BRANCH_NAME" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//') BRANCH_NAME="${FEATURE_NUM}-${WORDS}" if [ "$HAS_GIT" = true ]; then git checkout -b "$BRANCH_NAME" else >&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME" fi FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME" mkdir -p "$FEATURE_DIR" TEMPLATE="$REPO_ROOT/.specify/templates/spec-template.md" SPEC_FILE="$FEATURE_DIR/spec.md" if [ -f "$TEMPLATE" ]; then cp "$TEMPLATE" "$SPEC_FILE"; else touch "$SPEC_FILE"; fi # Set the SPECIFY_FEATURE environment variable for the current session export SPECIFY_FEATURE="$BRANCH_NAME" if $JSON_MODE; then printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$BRANCH_NAME" "$SPEC_FILE" "$FEATURE_NUM" else echo "BRANCH_NAME: $BRANCH_NAME" echo "SPEC_FILE: $SPEC_FILE" echo "FEATURE_NUM: $FEATURE_NUM" echo "SPECIFY_FEATURE environment variable set to: $BRANCH_NAME" fi ``` -------------------------------------------------------------------------------- /.specify/scripts/bash/common.sh: -------------------------------------------------------------------------------- ```bash #!/usr/bin/env bash # Common functions and variables for all scripts # Get repository root, with fallback for non-git repositories get_repo_root() { if git rev-parse --show-toplevel >/dev/null 2>&1; then git rev-parse --show-toplevel else # Fall back to script location for non-git repos local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" (cd "$script_dir/../../.." && pwd) fi } # Get current branch, with fallback for non-git repositories get_current_branch() { # First check if SPECIFY_FEATURE environment variable is set if [[ -n "${SPECIFY_FEATURE:-}" ]]; then echo "$SPECIFY_FEATURE" return fi # Then check git if available if git rev-parse --abbrev-ref HEAD >/dev/null 2>&1; then git rev-parse --abbrev-ref HEAD return fi # For non-git repos, try to find the latest feature directory local repo_root=$(get_repo_root) local specs_dir="$repo_root/specs" if [[ -d "$specs_dir" ]]; then local latest_feature="" local highest=0 for dir in "$specs_dir"/*; do if [[ -d "$dir" ]]; then local dirname=$(basename "$dir") if [[ "$dirname" =~ ^([0-9]{3})- ]]; then local number=${BASH_REMATCH[1]} number=$((10#$number)) if [[ "$number" -gt "$highest" ]]; then highest=$number latest_feature=$dirname fi fi fi done if [[ -n "$latest_feature" ]]; then echo "$latest_feature" return fi fi echo "main" # Final fallback } # Check if we have git available has_git() { git rev-parse --show-toplevel >/dev/null 2>&1 } check_feature_branch() { local branch="$1" local has_git_repo="$2" # For non-git repos, we can't enforce branch naming but still provide output if [[ "$has_git_repo" != "true" ]]; then echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2 return 0 fi if [[ ! "$branch" =~ ^[0-9]{3}- ]]; then echo "ERROR: Not on a feature branch. Current branch: $branch" >&2 echo "Feature branches should be named like: 001-feature-name" >&2 return 1 fi return 0 } get_feature_dir() { echo "$1/specs/$2"; } get_feature_paths() { local repo_root=$(get_repo_root) local current_branch=$(get_current_branch) local has_git_repo="false" if has_git; then has_git_repo="true" fi local feature_dir=$(get_feature_dir "$repo_root" "$current_branch") cat <<EOF REPO_ROOT='$repo_root' CURRENT_BRANCH='$current_branch' HAS_GIT='$has_git_repo' FEATURE_DIR='$feature_dir' FEATURE_SPEC='$feature_dir/spec.md' IMPL_PLAN='$feature_dir/plan.md' TASKS='$feature_dir/tasks.md' RESEARCH='$feature_dir/research.md' DATA_MODEL='$feature_dir/data-model.md' QUICKSTART='$feature_dir/quickstart.md' CONTRACTS_DIR='$feature_dir/contracts' EOF } check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; } check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; } ``` -------------------------------------------------------------------------------- /tools/jira_history.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "time" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // GetIssueHistoryInput defines the input parameters for getting issue history type GetIssueHistoryInput struct { IssueKey string `json:"issue_key" validate:"required"` } // HistoryItem represents a single change in the issue history type HistoryItem struct { Field string `json:"field"` FromString string `json:"from_string"` ToString string `json:"to_string"` } // HistoryEntry represents a single history entry with multiple changes type HistoryEntry struct { Date string `json:"date"` Author string `json:"author"` Changes []HistoryItem `json:"changes"` } // GetIssueHistoryOutput defines the output structure for issue history type GetIssueHistoryOutput struct { IssueKey string `json:"issue_key"` History []HistoryEntry `json:"history"` Count int `json:"count"` } func RegisterJiraHistoryTool(s *server.MCPServer) { jiraGetIssueHistoryTool := mcp.NewTool("jira_get_issue_history", mcp.WithDescription("Retrieve the complete change history of a Jira issue"), mcp.WithString("issue_key", mcp.Required(), mcp.Description("The unique identifier of the Jira issue (e.g., KP-2, PROJ-123)")), ) s.AddTool(jiraGetIssueHistoryTool, mcp.NewTypedToolHandler(jiraGetIssueHistoryHandler)) } func jiraGetIssueHistoryHandler(ctx context.Context, request mcp.CallToolRequest, input GetIssueHistoryInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Get issue with changelog expanded issue, response, err := client.Issue.Get(ctx, input.IssueKey, nil, []string{"changelog"}) if err != nil { if response != nil { return mcp.NewToolResultError(fmt.Sprintf("failed to get issue history: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint)), nil } return mcp.NewToolResultError(fmt.Sprintf("failed to get issue history: %v", err)), nil } if len(issue.Changelog.Histories) == 0 { return mcp.NewToolResultText(fmt.Sprintf("No history found for issue %s", input.IssueKey)), nil } // Build structured output var historyEntries []HistoryEntry // Process each history entry for _, history := range issue.Changelog.Histories { var formattedDate string // Parse the created time createdTime, err := time.Parse("2006-01-02T15:04:05.999-0700", history.Created) if err != nil { // If parse fails, use the original string formattedDate = history.Created } else { // Format the time in a more readable format formattedDate = createdTime.Format("2006-01-02 15:04:05") } // Process change items var changes []HistoryItem for _, item := range history.Items { fromString := item.FromString if fromString == "" { fromString = "(empty)" } toString := item.ToString if toString == "" { toString = "(empty)" } changes = append(changes, HistoryItem{ Field: item.Field, FromString: fromString, ToString: toString, }) } historyEntries = append(historyEntries, HistoryEntry{ Date: formattedDate, Author: history.Author.DisplayName, Changes: changes, }) } output := GetIssueHistoryOutput{ IssueKey: input.IssueKey, History: historyEntries, Count: len(historyEntries), } return mcp.NewToolResultJSON(output) } ``` -------------------------------------------------------------------------------- /tools/jira_comment.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "github.com/ctreminiom/go-atlassian/pkg/infra/models" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for typed tools type AddCommentInput struct { IssueKey string `json:"issue_key" validate:"required"` Comment string `json:"comment" validate:"required"` } type GetCommentsInput struct { IssueKey string `json:"issue_key" validate:"required"` } func RegisterJiraCommentTools(s *server.MCPServer) { jiraAddCommentTool := mcp.NewTool("jira_add_comment", mcp.WithDescription("Add a comment to a Jira issue"), mcp.WithString("issue_key", mcp.Required(), mcp.Description("The unique identifier of the Jira issue (e.g., KP-2, PROJ-123)")), mcp.WithString("comment", mcp.Required(), mcp.Description("The comment text to add to the issue")), ) s.AddTool(jiraAddCommentTool, mcp.NewTypedToolHandler(jiraAddCommentHandler)) jiraGetCommentsTool := mcp.NewTool("jira_get_comments", mcp.WithDescription("Retrieve all comments from a Jira issue"), mcp.WithString("issue_key", mcp.Required(), mcp.Description("The unique identifier of the Jira issue (e.g., KP-2, PROJ-123)")), ) s.AddTool(jiraGetCommentsTool, mcp.NewTypedToolHandler(jiraGetCommentsHandler)) } func jiraAddCommentHandler(ctx context.Context, request mcp.CallToolRequest, input AddCommentInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Create proper ADF structure: document → paragraph → text commentPayload := &models.CommentPayloadScheme{ Body: &models.CommentNodeScheme{ Version: 1, Type: "doc", Content: []*models.CommentNodeScheme{ { Type: "paragraph", Content: []*models.CommentNodeScheme{ { Type: "text", Text: input.Comment, }, }, }, }, }, } comment, response, err := client.Issue.Comment.Add(ctx, input.IssueKey, commentPayload, nil) if err != nil { if response != nil { return nil, fmt.Errorf("failed to add comment: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to add comment: %v", err) } result := fmt.Sprintf("Comment added successfully!\nID: %s\nAuthor: %s\nCreated: %s", comment.ID, comment.Author.DisplayName, comment.Created) return mcp.NewToolResultText(result), nil } func jiraGetCommentsHandler(ctx context.Context, request mcp.CallToolRequest, input GetCommentsInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Retrieve up to 50 comments starting from the first one. // Passing 0 for maxResults results in Jira returning only the first comment. comments, response, err := client.Issue.Comment.Gets(ctx, input.IssueKey, "", nil, 0, 50) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get comments: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get comments: %v", err) } if len(comments.Comments) == 0 { return mcp.NewToolResultText("No comments found for this issue."), nil } var result string for _, comment := range comments.Comments { authorName := "Unknown" if comment.Author != nil { authorName = comment.Author.DisplayName } result += fmt.Sprintf("ID: %s\nAuthor: %s\nCreated: %s\nUpdated: %s\nBody: %s\n\n", comment.ID, authorName, comment.Created, comment.Updated, comment.Body) } return mcp.NewToolResultText(result), nil } ``` -------------------------------------------------------------------------------- /tools/jira_worklog.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "strconv" "time" "github.com/ctreminiom/go-atlassian/pkg/infra/models" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for typed tools type AddWorklogInput struct { IssueKey string `json:"issue_key" validate:"required"` TimeSpent string `json:"time_spent" validate:"required"` Comment string `json:"comment,omitempty"` Started string `json:"started,omitempty"` } func RegisterJiraWorklogTool(s *server.MCPServer) { jiraAddWorklogTool := mcp.NewTool("jira_add_worklog", mcp.WithDescription("Add a worklog to a Jira issue to track time spent on the issue"), mcp.WithString("issue_key", mcp.Required(), mcp.Description("The unique identifier of the Jira issue (e.g., KP-2, PROJ-123)")), mcp.WithString("time_spent", mcp.Required(), mcp.Description("Time spent working on the issue (e.g., 3h, 30m, 1h 30m)")), mcp.WithString("comment", mcp.Description("Comment describing the work done")), mcp.WithString("started", mcp.Description("When the work began, in ISO 8601 format (e.g., 2023-05-01T10:00:00.000+0000). Defaults to current time.")), ) s.AddTool(jiraAddWorklogTool, mcp.NewTypedToolHandler(jiraAddWorklogHandler)) } func jiraAddWorklogHandler(ctx context.Context, request mcp.CallToolRequest, input AddWorklogInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Convert timeSpent to seconds (this is a simplification - in a real implementation // you would need to parse formats like "1h 30m" properly) timeSpentSeconds, err := parseTimeSpent(input.TimeSpent) if err != nil { return nil, fmt.Errorf("invalid time_spent format: %v", err) } // Get started time if provided, otherwise use current time var started string if input.Started != "" { started = input.Started } else { // Format current time in ISO 8601 format started = time.Now().Format("2006-01-02T15:04:05.000-0700") } options := &models.WorklogOptionsScheme{ Notify: true, AdjustEstimate: "auto", } payload := &models.WorklogADFPayloadScheme{ TimeSpentSeconds: timeSpentSeconds, Started: started, } // Add comment if provided if input.Comment != "" { payload.Comment = &models.CommentNodeScheme{ Type: "text", Text: input.Comment, } } // Call the Jira API to add the worklog worklog, response, err := client.Issue.Worklog.Add(ctx, input.IssueKey, payload, options) if err != nil { if response != nil { return nil, fmt.Errorf("failed to add worklog: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to add worklog: %v", err) } result := fmt.Sprintf(`Worklog added successfully! Issue: %s Worklog ID: %s Time Spent: %s (%d seconds) Date Started: %s Author: %s`, input.IssueKey, worklog.ID, input.TimeSpent, worklog.TimeSpentSeconds, worklog.Started, worklog.Author.DisplayName, ) return mcp.NewToolResultText(result), nil } // parseTimeSpent converts time formats like "3h", "30m", "1h 30m" to seconds func parseTimeSpent(timeSpent string) (int, error) { // This is a simplified version - a real implementation would be more robust // For this example, we'll just handle hours (h) and minutes (m) // Simple case: if it's just a number, treat it as seconds seconds, err := strconv.Atoi(timeSpent) if err == nil { return seconds, nil } // Otherwise, try to parse as a duration duration, err := time.ParseDuration(timeSpent) if err == nil { return int(duration.Seconds()), nil } // If all else fails, return an error return 0, fmt.Errorf("could not parse time: %s", timeSpent) } ``` -------------------------------------------------------------------------------- /prompts/jira_prompts.go: -------------------------------------------------------------------------------- ```go package prompts import ( "context" "fmt" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" ) // RegisterJiraPrompts registers all Jira-related prompts with the MCP server func RegisterJiraPrompts(s *server.MCPServer) { // Prompt 1: List all development work for an issue and its subtasks s.AddPrompt(mcp.NewPrompt("issue_development_tree", mcp.WithPromptDescription("List all development work (branches, PRs, commits) for a Jira issue and all its child issues/subtasks"), mcp.WithArgument("issue_key", mcp.ArgumentDescription("The Jira issue key to analyze (e.g., PROJ-123)"), mcp.RequiredArgument(), ), ), func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error) { issueKey := request.Params.Arguments["issue_key"] if issueKey == "" { return nil, fmt.Errorf("issue_key is required") } return mcp.NewGetPromptResult( "Development work tree for issue and subtasks", []mcp.PromptMessage{ mcp.NewPromptMessage( mcp.RoleUser, mcp.NewTextContent(fmt.Sprintf(`Please analyze all development work for issue %s and its child issues: 1. First, use jira_get_issue with issue_key=%s and expand=subtasks to retrieve the parent issue and all its subtasks 2. Then, use jira_get_development_information to get branches, pull requests, and commits for the parent issue %s 3. For each subtask found, call jira_get_development_information to get their development work 4. Format the results as a hierarchical tree showing: - Parent issue: %s - Development work (branches, PRs, commits) - Each subtask: - Development work (branches, PRs, commits) Please provide a clear summary of all development activity across the entire issue tree.`, issueKey, issueKey, issueKey, issueKey)), ), }, ), nil }) // Prompt 2: List all issues and their development work for a release/version s.AddPrompt(mcp.NewPrompt("release_development_overview", mcp.WithPromptDescription("List all issues and their development work (branches, PRs, commits) for a specific release/version"), mcp.WithArgument("version", mcp.ArgumentDescription("The version/release name (e.g., v1.0.0, Sprint 23)"), mcp.RequiredArgument(), ), mcp.WithArgument("project_key", mcp.ArgumentDescription("The Jira project key (e.g., PROJ, KP)"), mcp.RequiredArgument(), ), ), func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error) { version := request.Params.Arguments["version"] projectKey := request.Params.Arguments["project_key"] if version == "" { return nil, fmt.Errorf("version is required") } if projectKey == "" { return nil, fmt.Errorf("project_key is required") } return mcp.NewGetPromptResult( "Development overview for release", []mcp.PromptMessage{ mcp.NewPromptMessage( mcp.RoleUser, mcp.NewTextContent(fmt.Sprintf(`Please provide a comprehensive development overview for release "%s" in project %s: 1. First, use jira_search_issue with JQL: fixVersion = "%s" AND project = %s 2. For each issue found in the search results, call jira_get_development_information to retrieve: - Branches associated with the issue - Pull requests (status, reviewers, etc.) - Commits and code changes 3. Organize the results by issue and provide a summary that includes: - Total number of issues in the release - List each issue with its key, summary, and status - Development work for each issue (branches, PRs, commits) - Overall statistics (total PRs, merged PRs, open branches, etc.) Please format the output clearly so it's easy to review the entire release's development status.`, version, projectKey, version, projectKey)), ), }, ), nil }) } ``` -------------------------------------------------------------------------------- /tools/jira_version.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "strings" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for version tools type GetVersionInput struct { VersionID string `json:"version_id" validate:"required"` } type ListProjectVersionsInput struct { ProjectKey string `json:"project_key" validate:"required"` } func RegisterJiraVersionTool(s *server.MCPServer) { jiraGetVersionTool := mcp.NewTool("jira_get_version", mcp.WithDescription("Retrieve detailed information about a specific Jira project version including its name, description, release date, and status"), mcp.WithString("version_id", mcp.Required(), mcp.Description("The unique identifier of the version to retrieve (e.g., 10000)")), ) s.AddTool(jiraGetVersionTool, mcp.NewTypedToolHandler(jiraGetVersionHandler)) jiraListProjectVersionsTool := mcp.NewTool("jira_list_project_versions", mcp.WithDescription("List all versions in a Jira project with their details including names, descriptions, release dates, and statuses"), mcp.WithString("project_key", mcp.Required(), mcp.Description("Project identifier to list versions for (e.g., KP, PROJ)")), ) s.AddTool(jiraListProjectVersionsTool, mcp.NewTypedToolHandler(jiraListProjectVersionsHandler)) } func jiraGetVersionHandler(ctx context.Context, request mcp.CallToolRequest, input GetVersionInput) (*mcp.CallToolResult, error) { client := services.JiraClient() version, response, err := client.Project.Version.Get(ctx, input.VersionID, nil) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get version: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get version: %v", err) } var result strings.Builder result.WriteString(fmt.Sprintf("Version Details:\n\n")) result.WriteString(fmt.Sprintf("ID: %s\n", version.ID)) result.WriteString(fmt.Sprintf("Name: %s\n", version.Name)) if version.Description != "" { result.WriteString(fmt.Sprintf("Description: %s\n", version.Description)) } if version.ProjectID != 0 { result.WriteString(fmt.Sprintf("Project ID: %d\n", version.ProjectID)) } result.WriteString(fmt.Sprintf("Released: %t\n", version.Released)) result.WriteString(fmt.Sprintf("Archived: %t\n", version.Archived)) if version.ReleaseDate != "" { result.WriteString(fmt.Sprintf("Release Date: %s\n", version.ReleaseDate)) } if version.Self != "" { result.WriteString(fmt.Sprintf("URL: %s\n", version.Self)) } return mcp.NewToolResultText(result.String()), nil } func jiraListProjectVersionsHandler(ctx context.Context, request mcp.CallToolRequest, input ListProjectVersionsInput) (*mcp.CallToolResult, error) { client := services.JiraClient() versions, response, err := client.Project.Version.Gets(ctx, input.ProjectKey) if err != nil { if response != nil { return nil, fmt.Errorf("failed to list project versions: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to list project versions: %v", err) } if len(versions) == 0 { return mcp.NewToolResultText(fmt.Sprintf("No versions found for project %s.", input.ProjectKey)), nil } var result strings.Builder result.WriteString(fmt.Sprintf("Project %s Versions:\n\n", input.ProjectKey)) for i, version := range versions { if i > 0 { result.WriteString("\n") } result.WriteString(fmt.Sprintf("ID: %s\n", version.ID)) result.WriteString(fmt.Sprintf("Name: %s\n", version.Name)) if version.Description != "" { result.WriteString(fmt.Sprintf("Description: %s\n", version.Description)) } status := "In Development" if version.Released { status = "Released" } if version.Archived { status = "Archived" } result.WriteString(fmt.Sprintf("Status: %s\n", status)) if version.ReleaseDate != "" { result.WriteString(fmt.Sprintf("Release Date: %s\n", version.ReleaseDate)) } if version.Released { result.WriteString(fmt.Sprintf("Start Date: %t\n", version.Released)) } } return mcp.NewToolResultText(result.String()), nil } ``` -------------------------------------------------------------------------------- /.specify/templates/spec-template.md: -------------------------------------------------------------------------------- ```markdown # Feature Specification: [FEATURE NAME] **Feature Branch**: `[###-feature-name]` **Created**: [DATE] **Status**: Draft **Input**: User description: "$ARGUMENTS" ## User Scenarios & Testing *(mandatory)* <!-- IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance. Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them, you should still have a viable MVP (Minimum Viable Product) that delivers value. Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical. Think of each story as a standalone slice of functionality that can be: - Developed independently - Tested independently - Deployed independently - Demonstrated to users independently --> ### User Story 1 - [Brief Title] (Priority: P1) [Describe this user journey in plain language] **Why this priority**: [Explain the value and why it has this priority level] **Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"] **Acceptance Scenarios**: 1. **Given** [initial state], **When** [action], **Then** [expected outcome] 2. **Given** [initial state], **When** [action], **Then** [expected outcome] --- ### User Story 2 - [Brief Title] (Priority: P2) [Describe this user journey in plain language] **Why this priority**: [Explain the value and why it has this priority level] **Independent Test**: [Describe how this can be tested independently] **Acceptance Scenarios**: 1. **Given** [initial state], **When** [action], **Then** [expected outcome] --- ### User Story 3 - [Brief Title] (Priority: P3) [Describe this user journey in plain language] **Why this priority**: [Explain the value and why it has this priority level] **Independent Test**: [Describe how this can be tested independently] **Acceptance Scenarios**: 1. **Given** [initial state], **When** [action], **Then** [expected outcome] --- [Add more user stories as needed, each with an assigned priority] ### Edge Cases <!-- ACTION REQUIRED: The content in this section represents placeholders. Fill them out with the right edge cases. --> - What happens when [boundary condition]? - How does system handle [error scenario]? ## Requirements *(mandatory)* <!-- ACTION REQUIRED: The content in this section represents placeholders. Fill them out with the right functional requirements. For Jira MCP context: Requirements should specify MCP tools, parameters, and expected output. Example: "System MUST expose jira_create_issue tool accepting project_key, summary, description" --> ### Functional Requirements - **FR-001**: System MUST [specific MCP tool capability, e.g., "expose jira_<operation> tool"] - **FR-002**: Tool MUST [input validation, e.g., "validate required parameters via typed input struct"] - **FR-003**: Tool MUST [output format, e.g., "return human-readable text formatted for LLM consumption"] - **FR-004**: Tool MUST [error handling, e.g., "include endpoint and response body in error messages"] - **FR-005**: System MUST [resource behavior, e.g., "reuse singleton Jira client connection"] *Example of marking unclear requirements:* - **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?] - **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified] ### Key Entities *(include if feature involves data)* - **[Entity 1]**: [What it represents, key attributes without implementation] - **[Entity 2]**: [What it represents, relationships to other entities] ## Success Criteria *(mandatory)* <!-- ACTION REQUIRED: Define measurable success criteria. These must be technology-agnostic and measurable. --> ### Measurable Outcomes - **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"] - **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"] - **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"] - **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"] ``` -------------------------------------------------------------------------------- /tools/jira_search.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "encoding/json" "fmt" "net/http" "net/url" "strconv" "strings" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" "github.com/nguyenvanduocit/jira-mcp/util" jira "github.com/ctreminiom/go-atlassian/jira/v3" "github.com/ctreminiom/go-atlassian/pkg/infra/models" ) // Input types for typed tools type SearchIssueInput struct { JQL string `json:"jql" validate:"required"` Fields string `json:"fields,omitempty"` Expand string `json:"expand,omitempty"` } // searchIssuesJQL performs JQL search using the new /rest/api/3/search/jql endpoint func searchIssuesJQL(ctx context.Context, client *jira.Client, jql string, fields []string, expand []string, startAt, maxResults int) (*models.IssueSearchScheme, error) { // Prepare query parameters params := url.Values{} params.Set("jql", jql) if len(fields) > 0 { params.Set("fields", strings.Join(fields, ",")) } if len(expand) > 0 { params.Set("expand", strings.Join(expand, ",")) } if startAt > 0 { params.Set("startAt", strconv.Itoa(startAt)) } if maxResults > 0 { params.Set("maxResults", strconv.Itoa(maxResults)) } // Build the URL endpoint := fmt.Sprintf("%s/rest/api/3/search/jql?%s", client.Site.String(), params.Encode()) // Create HTTP request req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } // Add authentication headers - the client already has basic auth configured if client.Auth != nil && client.Auth.HasBasicAuth() { username, password := client.Auth.GetBasicAuth() req.SetBasicAuth(username, password) } req.Header.Set("Accept", "application/json") // Perform the request resp, err := client.HTTP.Do(req) if err != nil { return nil, fmt.Errorf("failed to perform request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, resp.Status) } // Parse the response var searchResult models.IssueSearchScheme if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { return nil, fmt.Errorf("failed to decode response: %w", err) } return &searchResult, nil } func RegisterJiraSearchTool(s *server.MCPServer) { jiraSearchTool := mcp.NewTool("jira_search_issue", mcp.WithDescription("Search for Jira issues using JQL (Jira Query Language). Returns key details like summary, status, assignee, and priority for matching issues"), mcp.WithString("jql", mcp.Required(), mcp.Description("JQL query string (e.g., 'project = SHTP AND status = \"In Progress\"')")), mcp.WithString("fields", mcp.Description("Comma-separated list of fields to retrieve (e.g., 'summary,status,assignee'). If not specified, all fields are returned.")), mcp.WithString("expand", mcp.Description("Comma-separated list of fields to expand for additional details (e.g., 'transitions,changelog,subtasks,description').")), ) s.AddTool(jiraSearchTool, mcp.NewTypedToolHandler(jiraSearchHandler)) } func jiraSearchHandler(ctx context.Context, request mcp.CallToolRequest, input SearchIssueInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Parse fields parameter var fields []string if input.Fields != "" { fields = strings.Split(strings.ReplaceAll(input.Fields, " ", ""), ",") } // Parse expand parameter var expand []string = []string{"transitions", "changelog", "subtasks", "description"} if input.Expand != "" { expand = strings.Split(strings.ReplaceAll(input.Expand, " ", ""), ",") } searchResult, err := searchIssuesJQL(ctx, client, input.JQL, fields, expand, 0, 30) if err != nil { return nil, fmt.Errorf("failed to search issues: %v", err) } if len(searchResult.Issues) == 0 { return mcp.NewToolResultText("No issues found matching the search criteria."), nil } var sb strings.Builder for index, issue := range searchResult.Issues { // Use the comprehensive formatter for each issue formattedIssue := util.FormatJiraIssue(issue) sb.WriteString(formattedIssue) if index < len(searchResult.Issues) - 1 { sb.WriteString("\n===\n") } } return mcp.NewToolResultText(sb.String()), nil } ``` -------------------------------------------------------------------------------- /.specify/templates/plan-template.md: -------------------------------------------------------------------------------- ```markdown # Implementation Plan: [FEATURE] **Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link] **Input**: Feature specification from `/specs/[###-feature-name]/spec.md` **Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow. ## Summary [Extract from feature spec: primary requirement + technical approach from research] ## Technical Context <!-- ACTION REQUIRED: Replace the content in this section with the technical details for the project. The structure here is presented in advisory capacity to guide the iteration process. --> **Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION] **Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION] **Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A] **Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION] **Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION] **Project Type**: [single/web/mobile - determines source structure] **Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION] **Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION] **Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION] ## Constitution Check *GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* **MCP Protocol Compliance:** - [ ] All features exposed via MCP tools (no direct API bypass) - [ ] Tool names follow `jira_<operation>` convention - [ ] STDIO mode primary, HTTP mode development-only **AI-First Output:** - [ ] Responses formatted for LLM readability - [ ] Error messages include diagnostic context (endpoint, response body) - [ ] Output uses `util.Format*` functions or similar formatting **Simplicity:** - [ ] No unnecessary abstraction layers (managers, facades, orchestrators) - [ ] Direct client calls preferred over wrappers - [ ] Complexity violations documented in "Complexity Tracking" below **Type Safety:** - [ ] Input structs defined with JSON tags and validation - [ ] Typed handlers used (`mcp.NewTypedToolHandler`) **Resource Efficiency:** - [ ] Singleton pattern for client connections (`services.JiraClient()`) - [ ] No per-request client creation **Testing Gates:** - [ ] Integration tests for new tool categories - [ ] Contract tests for tool registration and parameters ## Project Structure ### Documentation (this feature) ``` specs/[###-feature]/ ├── plan.md # This file (/speckit.plan command output) ├── research.md # Phase 0 output (/speckit.plan command) ├── data-model.md # Phase 1 output (/speckit.plan command) ├── quickstart.md # Phase 1 output (/speckit.plan command) ├── contracts/ # Phase 1 output (/speckit.plan command) └── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan) ``` ### Source Code (repository root) <!-- ACTION REQUIRED: Replace the placeholder tree below with the concrete layout for this feature. Delete unused options and expand the chosen structure with real paths (e.g., apps/admin, packages/something). The delivered plan must not include Option labels. --> ``` # [REMOVE IF UNUSED] Option 1: Single project (DEFAULT) src/ ├── models/ ├── services/ ├── cli/ └── lib/ tests/ ├── contract/ ├── integration/ └── unit/ # [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected) backend/ ├── src/ │ ├── models/ │ ├── services/ │ └── api/ └── tests/ frontend/ ├── src/ │ ├── components/ │ ├── pages/ │ └── services/ └── tests/ # [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected) api/ └── [same as backend above] ios/ or android/ └── [platform-specific structure: feature modules, UI flows, platform tests] ``` **Structure Decision**: [Document the selected structure and reference the real directories captured above] ## Complexity Tracking *Fill ONLY if Constitution Check has violations that must be justified* | Violation | Why Needed | Simpler Alternative Rejected Because | |-----------|------------|-------------------------------------| | [e.g., 4th project] | [current need] | [why 3 projects insufficient] | | [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] | ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.implement.md: -------------------------------------------------------------------------------- ```markdown --- description: Execute the implementation plan by processing and executing all tasks defined in tasks.md --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Outline 1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. 2. **Check checklists status** (if FEATURE_DIR/checklists/ exists): - Scan all checklist files in the checklists/ directory - For each checklist, count: * Total items: All lines matching `- [ ]` or `- [X]` or `- [x]` * Completed items: Lines matching `- [X]` or `- [x]` * Incomplete items: Lines matching `- [ ]` - Create a status table: ``` | Checklist | Total | Completed | Incomplete | Status | |-----------|-------|-----------|------------|--------| | ux.md | 12 | 12 | 0 | ✓ PASS | | test.md | 8 | 5 | 3 | ✗ FAIL | | security.md | 6 | 6 | 0 | ✓ PASS | ``` - Calculate overall status: * **PASS**: All checklists have 0 incomplete items * **FAIL**: One or more checklists have incomplete items - **If any checklist is incomplete**: * Display the table with incomplete item counts * **STOP** and ask: "Some checklists are incomplete. Do you want to proceed with implementation anyway? (yes/no)" * Wait for user response before continuing * If user says "no" or "wait" or "stop", halt execution * If user says "yes" or "proceed" or "continue", proceed to step 3 - **If all checklists are complete**: * Display the table showing all checklists passed * Automatically proceed to step 3 3. Load and analyze the implementation context: - **REQUIRED**: Read tasks.md for the complete task list and execution plan - **REQUIRED**: Read plan.md for tech stack, architecture, and file structure - **IF EXISTS**: Read data-model.md for entities and relationships - **IF EXISTS**: Read contracts/ for API specifications and test requirements - **IF EXISTS**: Read research.md for technical decisions and constraints - **IF EXISTS**: Read quickstart.md for integration scenarios 4. Parse tasks.md structure and extract: - **Task phases**: Setup, Tests, Core, Integration, Polish - **Task dependencies**: Sequential vs parallel execution rules - **Task details**: ID, description, file paths, parallel markers [P] - **Execution flow**: Order and dependency requirements 5. Execute implementation following the task plan: - **Phase-by-phase execution**: Complete each phase before moving to the next - **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together - **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks - **File-based coordination**: Tasks affecting the same files must run sequentially - **Validation checkpoints**: Verify each phase completion before proceeding 6. Implementation execution rules: - **Setup first**: Initialize project structure, dependencies, configuration - **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios - **Core development**: Implement models, services, CLI commands, endpoints - **Integration work**: Database connections, middleware, logging, external services - **Polish and validation**: Unit tests, performance optimization, documentation 7. Progress tracking and error handling: - Report progress after each completed task - Halt execution if any non-parallel task fails - For parallel tasks [P], continue with successful tasks, report failed ones - Provide clear error messages with context for debugging - Suggest next steps if implementation cannot proceed - **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file. 8. Completion validation: - Verify all required tasks are completed - Check that implemented features match the original specification - Validate that tests pass and coverage meets requirements - Confirm the implementation follows the technical plan - Report final status with summary of completed work Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/tasks` first to regenerate the task list. ``` -------------------------------------------------------------------------------- /.specify/scripts/bash/check-prerequisites.sh: -------------------------------------------------------------------------------- ```bash #!/usr/bin/env bash # Consolidated prerequisite checking script # # This script provides unified prerequisite checking for Spec-Driven Development workflow. # It replaces the functionality previously spread across multiple scripts. # # Usage: ./check-prerequisites.sh [OPTIONS] # # OPTIONS: # --json Output in JSON format # --require-tasks Require tasks.md to exist (for implementation phase) # --include-tasks Include tasks.md in AVAILABLE_DOCS list # --paths-only Only output path variables (no validation) # --help, -h Show help message # # OUTPUTS: # JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]} # Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md # Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc. set -e # Parse command line arguments JSON_MODE=false REQUIRE_TASKS=false INCLUDE_TASKS=false PATHS_ONLY=false for arg in "$@"; do case "$arg" in --json) JSON_MODE=true ;; --require-tasks) REQUIRE_TASKS=true ;; --include-tasks) INCLUDE_TASKS=true ;; --paths-only) PATHS_ONLY=true ;; --help|-h) cat << 'EOF' Usage: check-prerequisites.sh [OPTIONS] Consolidated prerequisite checking for Spec-Driven Development workflow. OPTIONS: --json Output in JSON format --require-tasks Require tasks.md to exist (for implementation phase) --include-tasks Include tasks.md in AVAILABLE_DOCS list --paths-only Only output path variables (no prerequisite validation) --help, -h Show this help message EXAMPLES: # Check task prerequisites (plan.md required) ./check-prerequisites.sh --json # Check implementation prerequisites (plan.md + tasks.md required) ./check-prerequisites.sh --json --require-tasks --include-tasks # Get feature paths only (no validation) ./check-prerequisites.sh --paths-only EOF exit 0 ;; *) echo "ERROR: Unknown option '$arg'. Use --help for usage information." >&2 exit 1 ;; esac done # Source common functions SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/common.sh" # Get feature paths and validate branch eval $(get_feature_paths) check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1 # If paths-only mode, output paths and exit (support JSON + paths-only combined) if $PATHS_ONLY; then if $JSON_MODE; then # Minimal JSON paths payload (no validation performed) printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \ "$REPO_ROOT" "$CURRENT_BRANCH" "$FEATURE_DIR" "$FEATURE_SPEC" "$IMPL_PLAN" "$TASKS" else echo "REPO_ROOT: $REPO_ROOT" echo "BRANCH: $CURRENT_BRANCH" echo "FEATURE_DIR: $FEATURE_DIR" echo "FEATURE_SPEC: $FEATURE_SPEC" echo "IMPL_PLAN: $IMPL_PLAN" echo "TASKS: $TASKS" fi exit 0 fi # Validate required directories and files if [[ ! -d "$FEATURE_DIR" ]]; then echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2 echo "Run /speckit.specify first to create the feature structure." >&2 exit 1 fi if [[ ! -f "$IMPL_PLAN" ]]; then echo "ERROR: plan.md not found in $FEATURE_DIR" >&2 echo "Run /speckit.plan first to create the implementation plan." >&2 exit 1 fi # Check for tasks.md if required if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2 echo "Run /speckit.tasks first to create the task list." >&2 exit 1 fi # Build list of available documents docs=() # Always check these optional docs [[ -f "$RESEARCH" ]] && docs+=("research.md") [[ -f "$DATA_MODEL" ]] && docs+=("data-model.md") # Check contracts directory (only if it exists and has files) if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then docs+=("contracts/") fi [[ -f "$QUICKSTART" ]] && docs+=("quickstart.md") # Include tasks.md if requested and it exists if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then docs+=("tasks.md") fi # Output results if $JSON_MODE; then # Build JSON array of documents if [[ ${#docs[@]} -eq 0 ]]; then json_docs="[]" else json_docs=$(printf '"%s",' "${docs[@]}") json_docs="[${json_docs%,}]" fi printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$FEATURE_DIR" "$json_docs" else # Text output echo "FEATURE_DIR:$FEATURE_DIR" echo "AVAILABLE_DOCS:" # Show status of each potential document check_file "$RESEARCH" "research.md" check_file "$DATA_MODEL" "data-model.md" check_dir "$CONTRACTS_DIR" "contracts/" check_file "$QUICKSTART" "quickstart.md" if $INCLUDE_TASKS; then check_file "$TASKS" "tasks.md" fi fi ``` -------------------------------------------------------------------------------- /specs/001-i-want-to/test-dev-api.sh: -------------------------------------------------------------------------------- ```bash #!/bin/bash # Load environment variables from .env file set -a source "$(dirname "$0")/../../.env" set +a JIRA_HOST="${ATLASSIAN_HOST}" JIRA_EMAIL="${ATLASSIAN_EMAIL}" JIRA_TOKEN="${ATLASSIAN_TOKEN}" ISSUE_KEY="SHTP-6050" echo "=========================================" echo "Step 1: Getting numeric issue ID for ${ISSUE_KEY}" echo "=========================================" ISSUE_RESPONSE=$(curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/api/3/issue/${ISSUE_KEY}?fields=id") echo "$ISSUE_RESPONSE" | jq '.' ISSUE_ID=$(echo "$ISSUE_RESPONSE" | jq -r '.id') if [ -z "$ISSUE_ID" ] || [ "$ISSUE_ID" = "null" ]; then echo "ERROR: Could not get issue ID" exit 1 fi echo "" echo "Issue ID: ${ISSUE_ID}" echo "" echo "=========================================" echo "Step 2: Getting development summary" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/summary?issueId=${ISSUE_ID}" | jq '.' echo "" echo "=========================================" echo "Step 3: Getting development details (repository) - GitLab" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=GitLab&dataType=repository" | jq '.' echo "" echo "=========================================" echo "Step 4: Getting development details (branch) - GitLab" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=GitLab&dataType=branch" | jq '.' echo "" echo "=========================================" echo "Step 5: Getting development details (pullrequest) - GitLab" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=GitLab&dataType=pullrequest" | jq '.' echo "" echo "=========================================" echo "Step 6: Getting development details (commit) - GitLab" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=GitLab&dataType=commit" | jq '.' echo "" echo "=========================================" echo "Step 7: Getting build information - All types" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&dataType=build" | jq '.' echo "" echo "=========================================" echo "Step 8: Getting build information - cloud-providers" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=cloud-providers&dataType=build" | jq '.' echo "" echo "=========================================" echo "Step 9: Getting deployment information - All types" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&dataType=deployment" | jq '.' echo "" echo "=========================================" echo "Step 10: Getting deployment-environment information" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&dataType=deployment-environment" | jq '.' echo "" echo "=========================================" echo "Step 11: Getting review information" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&dataType=review" | jq '.' echo "" echo "=========================================" echo "Step 12: Getting ALL development details - GitLab" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}&applicationType=GitLab" | jq '.' echo "" echo "=========================================" echo "Step 13: Getting ALL development details - No filters" echo "=========================================" curl -s -u "${JIRA_EMAIL}:${JIRA_TOKEN}" \ -H "Accept: application/json" \ "${JIRA_HOST}/rest/dev-status/latest/issue/detail?issueId=${ISSUE_ID}" | jq '.' ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.constitution.md: -------------------------------------------------------------------------------- ```markdown --- description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync. --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Outline You are updating the project constitution at `.specify/memory/constitution.md`. This file is a TEMPLATE containing placeholder tokens in square brackets (e.g. `[PROJECT_NAME]`, `[PRINCIPLE_1_NAME]`). Your job is to (a) collect/derive concrete values, (b) fill the template precisely, and (c) propagate any amendments across dependent artifacts. Follow this execution flow: 1. Load the existing constitution template at `.specify/memory/constitution.md`. - Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`. **IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly. 2. Collect/derive values for placeholders: - If user input (conversation) supplies a value, use it. - Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded). - For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous. - `CONSTITUTION_VERSION` must increment according to semantic versioning rules: * MAJOR: Backward incompatible governance/principle removals or redefinitions. * MINOR: New principle/section added or materially expanded guidance. * PATCH: Clarifications, wording, typo fixes, non-semantic refinements. - If version bump type ambiguous, propose reasoning before finalizing. 3. Draft the updated constitution content: - Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left). - Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance. - Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing non‑negotiable rules, explicit rationale if not obvious. - Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations. 4. Consistency propagation checklist (convert prior checklist into active validations): - Read `.specify/templates/plan-template.md` and ensure any "Constitution Check" or rules align with updated principles. - Read `.specify/templates/spec-template.md` for scope/requirements alignment—update if constitution adds/removes mandatory sections or constraints. - Read `.specify/templates/tasks-template.md` and ensure task categorization reflects new or removed principle-driven task types (e.g., observability, versioning, testing discipline). - Read each command file in `.specify/templates/commands/*.md` (including this one) to verify no outdated references (agent-specific names like CLAUDE only) remain when generic guidance is required. - Read any runtime guidance docs (e.g., `README.md`, `docs/quickstart.md`, or agent-specific guidance files if present). Update references to principles changed. 5. Produce a Sync Impact Report (prepend as an HTML comment at top of the constitution file after update): - Version change: old → new - List of modified principles (old title → new title if renamed) - Added sections - Removed sections - Templates requiring updates (✅ updated / ⚠ pending) with file paths - Follow-up TODOs if any placeholders intentionally deferred. 6. Validation before final output: - No remaining unexplained bracket tokens. - Version line matches report. - Dates ISO format YYYY-MM-DD. - Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate). 7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite). 8. Output a final summary to the user with: - New version and bump rationale. - Any files flagged for manual follow-up. - Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`). Formatting & Style Requirements: - Use Markdown headings exactly as in the template (do not demote/promote levels). - Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks. - Keep a single blank line between sections. - Avoid trailing whitespace. If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps. If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items. Do not create a new template; always operate on the existing `.specify/memory/constitution.md` file. ``` -------------------------------------------------------------------------------- /tools/jira_relationship.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "strings" "github.com/ctreminiom/go-atlassian/pkg/infra/models" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for typed tools type GetRelatedIssuesInput struct { IssueKey string `json:"issue_key" validate:"required"` } type LinkIssuesInput struct { InwardIssue string `json:"inward_issue" validate:"required"` OutwardIssue string `json:"outward_issue" validate:"required"` LinkType string `json:"link_type" validate:"required"` Comment string `json:"comment,omitempty"` } func RegisterJiraRelationshipTool(s *server.MCPServer) { jiraRelationshipTool := mcp.NewTool("jira_get_related_issues", mcp.WithDescription("Retrieve issues that have a relationship with a given issue, such as blocks, is blocked by, relates to, etc."), mcp.WithString("issue_key", mcp.Required(), mcp.Description("The unique identifier of the Jira issue (e.g., KP-2, PROJ-123)")), ) s.AddTool(jiraRelationshipTool, mcp.NewTypedToolHandler(jiraRelationshipHandler)) jiraLinkTool := mcp.NewTool("jira_link_issues", mcp.WithDescription("Create a link between two Jira issues, defining their relationship (e.g., blocks, duplicates, relates to)"), mcp.WithString("inward_issue", mcp.Required(), mcp.Description("The key of the inward issue (e.g., KP-1, PROJ-123)")), mcp.WithString("outward_issue", mcp.Required(), mcp.Description("The key of the outward issue (e.g., KP-2, PROJ-123)")), mcp.WithString("link_type", mcp.Required(), mcp.Description("The type of link between issues (e.g., Duplicate, Blocks, Relates)")), mcp.WithString("comment", mcp.Description("Optional comment to add when creating the link")), ) s.AddTool(jiraLinkTool, mcp.NewTypedToolHandler(jiraLinkHandler)) } func jiraRelationshipHandler(ctx context.Context, request mcp.CallToolRequest, input GetRelatedIssuesInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Get the issue with the 'issuelinks' field issue, response, err := client.Issue.Get(ctx, input.IssueKey, nil, []string{"issuelinks"}) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get issue: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get issue: %v", err) } if issue.Fields.IssueLinks == nil || len(issue.Fields.IssueLinks) == 0 { return mcp.NewToolResultText(fmt.Sprintf("Issue %s has no linked issues.", input.IssueKey)), nil } var sb strings.Builder sb.WriteString(fmt.Sprintf("Related issues for %s:\n\n", input.IssueKey)) for _, link := range issue.Fields.IssueLinks { // Determine the relationship type and related issue var relatedIssue string var relationshipType string var direction string if link.InwardIssue != nil { relatedIssue = link.InwardIssue.Key relationshipType = link.Type.Inward direction = "inward" } else if link.OutwardIssue != nil { relatedIssue = link.OutwardIssue.Key relationshipType = link.Type.Outward direction = "outward" } else { continue // Skip if no related issue } var summary string if direction == "inward" && link.InwardIssue.Fields.Summary != "" { summary = link.InwardIssue.Fields.Summary } else if direction == "outward" && link.OutwardIssue.Fields.Summary != "" { summary = link.OutwardIssue.Fields.Summary } var status string if direction == "inward" && link.InwardIssue.Fields.Status != nil { status = link.InwardIssue.Fields.Status.Name } else if direction == "outward" && link.OutwardIssue.Fields.Status != nil { status = link.OutwardIssue.Fields.Status.Name } else { status = "Unknown" } sb.WriteString(fmt.Sprintf("Relationship: %s\n", relationshipType)) sb.WriteString(fmt.Sprintf("Issue: %s\n", relatedIssue)) sb.WriteString(fmt.Sprintf("Summary: %s\n", summary)) sb.WriteString(fmt.Sprintf("Status: %s\n", status)) sb.WriteString("\n") } return mcp.NewToolResultText(sb.String()), nil } func jiraLinkHandler(ctx context.Context, request mcp.CallToolRequest, input LinkIssuesInput) (*mcp.CallToolResult, error) { client := services.JiraClient() // Create the link payload payload := &models.LinkPayloadSchemeV3{ InwardIssue: &models.LinkedIssueScheme{ Key: input.InwardIssue, }, OutwardIssue: &models.LinkedIssueScheme{ Key: input.OutwardIssue, }, Type: &models.LinkTypeScheme{ Name: input.LinkType, }, } // Add comment if provided if input.Comment != "" { payload.Comment = &models.CommentPayloadScheme{ Body: &models.CommentNodeScheme{ Type: "text", Text: input.Comment, }, } } // Create the link response, err := client.Issue.Link.Create(ctx, payload) if err != nil { if response != nil { return nil, fmt.Errorf("failed to link issues: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to link issues: %v", err) } return mcp.NewToolResultText(fmt.Sprintf("Successfully linked issues %s and %s with link type \"%s\"", input.InwardIssue, input.OutwardIssue, input.LinkType)), nil } ``` -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- ```go package main import ( "context" "errors" "flag" "fmt" "log" "os" "strings" "github.com/joho/godotenv" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/prompts" "github.com/nguyenvanduocit/jira-mcp/tools" ) func main() { envFile := flag.String("env", "", "Path to environment file (optional when environment variables are set directly)") httpPort := flag.String("http_port", "", "Port for HTTP server. If not provided, will use stdio") flag.Parse() // Load environment file if specified if *envFile != "" { if err := godotenv.Load(*envFile); err != nil { fmt.Printf("⚠️ Warning: Error loading env file %s: %v\n", *envFile, err) } else { fmt.Printf("✅ Loaded environment variables from %s\n", *envFile) } } // Check required environment variables requiredEnvs := []string{"ATLASSIAN_HOST", "ATLASSIAN_EMAIL", "ATLASSIAN_TOKEN"} missingEnvs := []string{} for _, env := range requiredEnvs { if os.Getenv(env) == "" { missingEnvs = append(missingEnvs, env) } } if len(missingEnvs) > 0 { fmt.Println("❌ Configuration Error: Missing required environment variables") fmt.Println() fmt.Println("Missing variables:") for _, env := range missingEnvs { fmt.Printf(" - %s\n", env) } fmt.Println() fmt.Println("📋 Setup Instructions:") fmt.Println("1. Get your Atlassian API token from: https://id.atlassian.com/manage-profile/security/api-tokens") fmt.Println("2. Set the environment variables:") fmt.Println() fmt.Println(" Option A - Using .env file:") fmt.Println(" Create a .env file with:") fmt.Println(" ATLASSIAN_HOST=https://your-domain.atlassian.net") fmt.Println(" [email protected]") fmt.Println(" ATLASSIAN_TOKEN=your-api-token") fmt.Println() fmt.Println(" Option B - Using environment variables:") fmt.Println(" export ATLASSIAN_HOST=https://your-domain.atlassian.net") fmt.Println(" export [email protected]") fmt.Println(" export ATLASSIAN_TOKEN=your-api-token") fmt.Println() fmt.Println(" Option C - Using Docker:") fmt.Printf(" docker run -e ATLASSIAN_HOST=https://your-domain.atlassian.net \\\n") fmt.Printf(" -e [email protected] \\\n") fmt.Printf(" -e ATLASSIAN_TOKEN=your-api-token \\\n") fmt.Printf(" ghcr.io/nguyenvanduocit/jira-mcp:latest\n") fmt.Println() os.Exit(1) } fmt.Println("✅ All required environment variables are set") fmt.Printf("🔗 Connected to: %s\n", os.Getenv("ATLASSIAN_HOST")) mcpServer := server.NewMCPServer( "Jira MCP", "1.0.1", server.WithLogging(), server.WithPromptCapabilities(true), server.WithResourceCapabilities(true, true), server.WithRecovery(), ) // Register all Jira tools tools.RegisterJiraIssueTool(mcpServer) tools.RegisterJiraSearchTool(mcpServer) tools.RegisterJiraSprintTool(mcpServer) tools.RegisterJiraStatusTool(mcpServer) tools.RegisterJiraTransitionTool(mcpServer) tools.RegisterJiraWorklogTool(mcpServer) tools.RegisterJiraCommentTools(mcpServer) tools.RegisterJiraHistoryTool(mcpServer) tools.RegisterJiraRelationshipTool(mcpServer) tools.RegisterJiraVersionTool(mcpServer) tools.RegisterJiraDevelopmentTool(mcpServer) // Register all Jira prompts prompts.RegisterJiraPrompts(mcpServer) if *httpPort != "" { fmt.Println() fmt.Println("🚀 Starting Jira MCP Server in HTTP mode...") fmt.Printf("📡 Server will be available at: http://localhost:%s/mcp\n", *httpPort) fmt.Println() fmt.Println("📋 Cursor Configuration:") fmt.Println("Add the following to your Cursor MCP settings (.cursor/mcp.json):") fmt.Println() fmt.Println("```json") fmt.Println("{") fmt.Println(" \"mcpServers\": {") fmt.Println(" \"jira\": {") fmt.Printf(" \"url\": \"http://localhost:%s/mcp\"\n", *httpPort) fmt.Println(" }") fmt.Println(" }") fmt.Println("}") fmt.Println("```") fmt.Println() fmt.Println("💡 Tips:") fmt.Println("- Restart Cursor after adding the configuration") fmt.Println("- Test the connection by asking Claude: 'List my Jira projects'") fmt.Println("- Use '@jira' in Cursor to reference Jira-related context") fmt.Println() fmt.Println("🔄 Server starting...") httpServer := server.NewStreamableHTTPServer(mcpServer, server.WithEndpointPath("/mcp")) if err := httpServer.Start(fmt.Sprintf(":%s", *httpPort)); err != nil && !isContextCanceled(err) { log.Fatalf("❌ Server error: %v", err) } } else { if err := server.ServeStdio(mcpServer); err != nil && !isContextCanceled(err) { log.Fatalf("❌ Server error: %v", err) } } } // IsContextCanceled checks if the error is related to context cancellation func isContextCanceled(err error) bool { if err == nil { return false } // Check if it's directly context.Canceled if errors.Is(err, context.Canceled) { return true } // Check if the error message contains context canceled errMsg := strings.ToLower(err.Error()) return strings.Contains(errMsg, "context canceled") || strings.Contains(errMsg, "operation was canceled") || strings.Contains(errMsg, "context deadline exceeded") } ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.tasks.md: -------------------------------------------------------------------------------- ```markdown --- description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts. --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Outline 1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. 2. **Load design documents**: Read from FEATURE_DIR: - **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities) - **Optional**: data-model.md (entities), contracts/ (API endpoints), research.md (decisions), quickstart.md (test scenarios) - Note: Not all projects have all documents. Generate tasks based on what's available. 3. **Execute task generation workflow** (follow the template structure): - Load plan.md and extract tech stack, libraries, project structure - **Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.)** - If data-model.md exists: Extract entities → map to user stories - If contracts/ exists: Each file → map endpoints to user stories - If research.md exists: Extract decisions → generate setup tasks - **Generate tasks ORGANIZED BY USER STORY**: - Setup tasks (shared infrastructure needed by all stories) - **Foundational tasks (prerequisites that must complete before ANY user story can start)** - For each user story (in priority order P1, P2, P3...): - Group all tasks needed to complete JUST that story - Include models, services, endpoints, UI components specific to that story - Mark which tasks are [P] parallelizable - If tests requested: Include tests specific to that story - Polish/Integration tasks (cross-cutting concerns) - **Tests are OPTIONAL**: Only generate test tasks if explicitly requested in the feature spec or user asks for TDD approach - Apply task rules: - Different files = mark [P] for parallel - Same file = sequential (no [P]) - If tests requested: Tests before implementation (TDD order) - Number tasks sequentially (T001, T002...) - Generate dependency graph showing user story completion order - Create parallel execution examples per user story - Validate task completeness (each user story has all needed tasks, independently testable) 4. **Generate tasks.md**: Use `.specify.specify/templates/tasks-template.md` as structure, fill with: - Correct feature name from plan.md - Phase 1: Setup tasks (project initialization) - Phase 2: Foundational tasks (blocking prerequisites for all user stories) - Phase 3+: One phase per user story (in priority order from spec.md) - Each phase includes: story goal, independent test criteria, tests (if requested), implementation tasks - Clear [Story] labels (US1, US2, US3...) for each task - [P] markers for parallelizable tasks within each story - Checkpoint markers after each story phase - Final Phase: Polish & cross-cutting concerns - Numbered tasks (T001, T002...) in execution order - Clear file paths for each task - Dependencies section showing story completion order - Parallel execution examples per story - Implementation strategy section (MVP first, incremental delivery) 5. **Report**: Output path to generated tasks.md and summary: - Total task count - Task count per user story - Parallel opportunities identified - Independent test criteria for each story - Suggested MVP scope (typically just User Story 1) Context for task generation: $ARGUMENTS The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context. ## Task Generation Rules **IMPORTANT**: Tests are optional. Only generate test tasks if the user explicitly requested testing or TDD approach in the feature specification. **CRITICAL**: Tasks MUST be organized by user story to enable independent implementation and testing. 1. **From User Stories (spec.md)** - PRIMARY ORGANIZATION: - Each user story (P1, P2, P3...) gets its own phase - Map all related components to their story: - Models needed for that story - Services needed for that story - Endpoints/UI needed for that story - If tests requested: Tests specific to that story - Mark story dependencies (most stories should be independent) 2. **From Contracts**: - Map each contract/endpoint → to the user story it serves - If tests requested: Each contract → contract test task [P] before implementation in that story's phase 3. **From Data Model**: - Map each entity → to the user story(ies) that need it - If entity serves multiple stories: Put in earliest story or Setup phase - Relationships → service layer tasks in appropriate story phase 4. **From Setup/Infrastructure**: - Shared infrastructure → Setup phase (Phase 1) - Foundational/blocking tasks → Foundational phase (Phase 2) - Examples: Database schema setup, authentication framework, core libraries, base configurations - These MUST complete before any user story can be implemented - Story-specific setup → within that story's phase 5. **Ordering**: - Phase 1: Setup (project initialization) - Phase 2: Foundational (blocking prerequisites - must complete before user stories) - Phase 3+: User Stories in priority order (P1, P2, P3...) - Within each story: Tests (if requested) → Models → Services → Endpoints → Integration - Final Phase: Polish & Cross-Cutting Concerns - Each user story phase should be a complete, independently testable increment ``` -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- ```markdown # Changelog ## [1.17.1](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.17.0...v1.17.1) (2025-10-09) ### Bug Fixes * disable provenance and SBOM to prevent unknown/unknown platform entry ([2acf42f](https://github.com/nguyenvanduocit/jira-mcp/commit/2acf42f1c1fbb43f078c2c4828bf0fd23493c026)) ## [1.17.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.16.0...v1.17.0) (2025-10-09) ### Features * add ARM64 support for Docker images ([d535e52](https://github.com/nguyenvanduocit/jira-mcp/commit/d535e52a3c966ca2af3f67d386282ed640e7b387)) ## [1.16.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.15.0...v1.16.0) (2025-10-07) ### Features * add build information support and prompts functionality ([d3df256](https://github.com/nguyenvanduocit/jira-mcp/commit/d3df256f80a181e80eca0510583e9771c47b9a58)) ## [1.15.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.14.0...v1.15.0) (2025-10-07) ### Features * add development information tool for Jira issues ([b0c2ec8](https://github.com/nguyenvanduocit/jira-mcp/commit/b0c2ec84de8d71be7ddb7cdaf976c31ea803ef8b)) ## [1.14.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.13.0...v1.14.0) (2025-09-23) ### Features * add jira_ prefix to all tool names for better LLM discoverability ([f44cd03](https://github.com/nguyenvanduocit/jira-mcp/commit/f44cd03a7c467255192f65404cfc15cc53ae0b76)) ## [1.13.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.12.1...v1.13.0) (2025-09-23) ### Features * **docs:** rewrite README with clear USP and 2‑minute quick start ([69b7b20](https://github.com/nguyenvanduocit/jira-mcp/commit/69b7b20166c424efe485fa2403193105012f2973)) ## [1.12.1](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.12.0...v1.12.1) (2025-09-23) ### Bug Fixes * migrate JQL search to new API endpoint ([bf6b6a2](https://github.com/nguyenvanduocit/jira-mcp/commit/bf6b6a2a105c5e34a0cbc6c3495f711d70cd47aa)) ## [1.12.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.11.0...v1.12.0) (2025-09-08) ### Features * upgrade to Jira API v3 ([1b65607](https://github.com/nguyenvanduocit/jira-mcp/commit/1b6560750ac0f4d37b5cc2fdf004d15932b4346b)) ## [1.11.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.10.0...v1.11.0) (2025-06-11) ### Features * support streamable http ([a67657a](https://github.com/nguyenvanduocit/jira-mcp/commit/a67657a9649b53ec02a5b2a4eb0789810bc7b372)) ## [1.10.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.9.0...v1.10.0) (2025-06-11) ### Features * update foỏmat of sprint ([d378f75](https://github.com/nguyenvanduocit/jira-mcp/commit/d378f7510fb21b8f4fd3ee677d3a1cf54c2ad025)) ## [1.9.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.8.0...v1.9.0) (2025-06-06) ### Features * add get_active_sprint tool ([3095319](https://github.com/nguyenvanduocit/jira-mcp/commit/30953192ce5e88d4940fea09f7a2331ae2516b54)) * **sprint:** add get_active_sprint tool ([89724b2](https://github.com/nguyenvanduocit/jira-mcp/commit/89724b26b7e9c19dfc16d1c8d81455801145fb27)) * **sprint:** enhance list_sprints and get_active_sprint tools with project_key support ([f31cac4](https://github.com/nguyenvanduocit/jira-mcp/commit/f31cac4701ef0e88e2c2b73cc950770c6b5cda02)) ## [1.8.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.7.0...v1.8.0) (2025-06-05) ### Features * **tools:** enhance issue tools with flexible field selection ([40fef1d](https://github.com/nguyenvanduocit/jira-mcp/commit/40fef1dcaa4ef0ed7833cd6db24e3e31c0a35f73)) ## [1.7.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.6.0...v1.7.0) (2025-06-05) ### Features * **jira:** enhance issue retrieval with changelog and story point estimate ([6e9902c](https://github.com/nguyenvanduocit/jira-mcp/commit/6e9902c464430ffc759124792fe0907697d80fab)) ### Bug Fixes * retrieve all issue comments ([a7cfae5](https://github.com/nguyenvanduocit/jira-mcp/commit/a7cfae5e459fd50b3a62f80223bddfc659a5453b)) ## [1.6.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.5.0...v1.6.0) (2025-05-06) ### Features * bump version ([cd2a85c](https://github.com/nguyenvanduocit/jira-mcp/commit/cd2a85c42c8594240e8718524ac0082acf1b7db7)) ## [1.5.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.4.0...v1.5.0) (2025-04-18) ### Features * **docker:** add GitHub Container Registry support ([f939b62](https://github.com/nguyenvanduocit/jira-mcp/commit/f939b629e764d4fe470f6954cc0d281eccde913f)) * **sprint:** add get_sprint tool to retrieve details of a specific sprint ([6756a1c](https://github.com/nguyenvanduocit/jira-mcp/commit/6756a1c79ed0692aeac9d12287fd92ef6bc5f1c2)) ## [1.4.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.3.0...v1.4.0) (2025-04-18) ### Features * **tools:** simplify tool naming and add issue relationship features ([02279ea](https://github.com/nguyenvanduocit/jira-mcp/commit/02279ead729b7a9bd6e78d6ed7903931d39c1580)) ## [1.3.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.2.0...v1.3.0) (2025-04-17) ### Features * **jira:** add issue history and relationship tools ([fc44bd4](https://github.com/nguyenvanduocit/jira-mcp/commit/fc44bd4384775260bf8ea7a0373c89d7053b6450)) ## [1.2.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.1.0...v1.2.0) (2025-04-15) ### Features * **docker:** add Docker support with build and run instructions ([979cd45](https://github.com/nguyenvanduocit/jira-mcp/commit/979cd459663c0004c566cda658efbf9fca50bf52)) * **docker:** add Docker support with build and run instructions ([078062e](https://github.com/nguyenvanduocit/jira-mcp/commit/078062ed7ba2686483a9df4c6000462d5b4fed3a)) ## [1.1.0](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.0.1...v1.1.0) (2025-04-04) ### Features * **jira:** add worklog functionality ([82ea857](https://github.com/nguyenvanduocit/jira-mcp/commit/82ea85767653ea5de4f20beb6585d9f694696a9a)) ## [1.0.1](https://github.com/nguyenvanduocit/jira-mcp/compare/v1.0.0...v1.0.1) (2025-04-04) ### Bug Fixes * **api:** update Jira comment API implementation ([12798ee](https://github.com/nguyenvanduocit/jira-mcp/commit/12798ee285f0b8d5c70689db87fa60b74e72376d)) ## 1.0.0 (2025-03-25) ### Features * add gitleaks workflow for secret scanning ([9bb46a0](https://github.com/nguyenvanduocit/jira-mcp/commit/9bb46a0f63793934470a1701a42d2413f29898f8)) * init ([6e960c0](https://github.com/nguyenvanduocit/jira-mcp/commit/6e960c048f69fe61baee42c3061aef0a44602be3)) ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.analyze.md: -------------------------------------------------------------------------------- ```markdown --- description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation. --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Goal Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/tasks` has successfully produced a complete `tasks.md`. ## Operating Constraints **STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually). **Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/analyze`. ## Execution Steps ### 1. Initialize Analysis Context Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths: - SPEC = FEATURE_DIR/spec.md - PLAN = FEATURE_DIR/plan.md - TASKS = FEATURE_DIR/tasks.md Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command). ### 2. Load Artifacts (Progressive Disclosure) Load only the minimal necessary context from each artifact: **From spec.md:** - Overview/Context - Functional Requirements - Non-Functional Requirements - User Stories - Edge Cases (if present) **From plan.md:** - Architecture/stack choices - Data Model references - Phases - Technical constraints **From tasks.md:** - Task IDs - Descriptions - Phase grouping - Parallel markers [P] - Referenced file paths **From constitution:** - Load `.specify/memory/constitution.md` for principle validation ### 3. Build Semantic Models Create internal representations (do not include raw artifacts in output): - **Requirements inventory**: Each functional + non-functional requirement with a stable key (derive slug based on imperative phrase; e.g., "User can upload file" → `user-can-upload-file`) - **User story/action inventory**: Discrete user actions with acceptance criteria - **Task coverage mapping**: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases) - **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements ### 4. Detection Passes (Token-Efficient Analysis) Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary. #### A. Duplication Detection - Identify near-duplicate requirements - Mark lower-quality phrasing for consolidation #### B. Ambiguity Detection - Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria - Flag unresolved placeholders (TODO, TKTK, ???, `<placeholder>`, etc.) #### C. Underspecification - Requirements with verbs but missing object or measurable outcome - User stories missing acceptance criteria alignment - Tasks referencing files or components not defined in spec/plan #### D. Constitution Alignment - Any requirement or plan element conflicting with a MUST principle - Missing mandated sections or quality gates from constitution #### E. Coverage Gaps - Requirements with zero associated tasks - Tasks with no mapped requirement/story - Non-functional requirements not reflected in tasks (e.g., performance, security) #### F. Inconsistency - Terminology drift (same concept named differently across files) - Data entities referenced in plan but absent in spec (or vice versa) - Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note) - Conflicting requirements (e.g., one requires Next.js while other specifies Vue) ### 5. Severity Assignment Use this heuristic to prioritize findings: - **CRITICAL**: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality - **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion - **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case - **LOW**: Style/wording improvements, minor redundancy not affecting execution order ### 6. Produce Compact Analysis Report Output a Markdown report (no file writes) with the following structure: ## Specification Analysis Report | ID | Category | Severity | Location(s) | Summary | Recommendation | |----|----------|----------|-------------|---------|----------------| | A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version | (Add one row per finding; generate stable IDs prefixed by category initial.) **Coverage Summary Table:** | Requirement Key | Has Task? | Task IDs | Notes | |-----------------|-----------|----------|-------| **Constitution Alignment Issues:** (if any) **Unmapped Tasks:** (if any) **Metrics:** - Total Requirements - Total Tasks - Coverage % (requirements with >=1 task) - Ambiguity Count - Duplication Count - Critical Issues Count ### 7. Provide Next Actions At end of report, output a concise Next Actions block: - If CRITICAL issues exist: Recommend resolving before `/implement` - If only LOW/MEDIUM: User may proceed, but provide improvement suggestions - Provide explicit command suggestions: e.g., "Run /specify with refinement", "Run /plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'" ### 8. Offer Remediation Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.) ## Operating Principles ### Context Efficiency - **Minimal high-signal tokens**: Focus on actionable findings, not exhaustive documentation - **Progressive disclosure**: Load artifacts incrementally; don't dump all content into analysis - **Token-efficient output**: Limit findings table to 50 rows; summarize overflow - **Deterministic results**: Rerunning without changes should produce consistent IDs and counts ### Analysis Guidelines - **NEVER modify files** (this is read-only analysis) - **NEVER hallucinate missing sections** (if absent, report them accurately) - **Prioritize constitution violations** (these are always CRITICAL) - **Use examples over exhaustive rules** (cite specific instances, not generic patterns) - **Report zero issues gracefully** (emit success report with coverage statistics) ## Context $ARGUMENTS ``` -------------------------------------------------------------------------------- /specs/001-i-want-to/spec.md: -------------------------------------------------------------------------------- ```markdown # Feature Specification: Retrieve Development Information from Jira Issue **Feature Branch**: `001-i-want-to` **Created**: 2025-10-07 **Status**: Draft **Input**: User description: "i want to have tool to get all branch, merge request, from a jira issue" ## User Scenarios & Testing *(mandatory)* ### User Story 1 - View Linked Development Work (Priority: P1) As an AI assistant user or developer, I want to retrieve all branches and merge requests associated with a specific Jira issue so that I can understand what code changes are related to that issue and their current status. **Why this priority**: This is the core functionality that delivers immediate value by providing visibility into development activity linked to a Jira issue. It enables users to track code changes, review progress, and understand the implementation status of an issue. **Independent Test**: Can be fully tested by requesting development information for a Jira issue that has linked branches and merge requests, and verifying that the returned data includes branch names, merge request titles, states, and URLs. **Acceptance Scenarios**: 1. **Given** a Jira issue with linked branches and merge requests, **When** the user requests development information for that issue, **Then** the system returns a list of all branches with their names and repositories 2. **Given** a Jira issue with linked branches and merge requests, **When** the user requests development information for that issue, **Then** the system returns a list of all merge requests with their titles, states (open/merged/closed), and URLs 3. **Given** a Jira issue with no linked development work, **When** the user requests development information, **Then** the system returns an empty result or clear message indicating no development work is linked 4. **Given** an invalid issue key, **When** the user requests development information, **Then** the system returns a clear error message explaining the issue was not found --- ### User Story 2 - Filter Development Information by Type (Priority: P2) As a user, I want to optionally filter the development information to retrieve only branches or only merge requests so that I can focus on the specific information I need. **Why this priority**: This enhances usability by allowing users to retrieve targeted information, reducing noise when they only need specific types of development data. **Independent Test**: Can be tested by requesting only branches for an issue that has both branches and merge requests, and verifying only branch information is returned. **Acceptance Scenarios**: 1. **Given** a Jira issue with both branches and merge requests, **When** the user requests only branches, **Then** the system returns only branch information and excludes merge request data 2. **Given** a Jira issue with both branches and merge requests, **When** the user requests only merge requests, **Then** the system returns only merge request information and excludes branch data 3. **Given** a Jira issue with development work, **When** the user requests all development information (no filter), **Then** the system returns both branches and merge requests --- ### User Story 3 - View Commit Information (Priority: P3) As a user, I want to see commits associated with a Jira issue so that I can understand the specific code changes that have been made. **Why this priority**: This provides additional detail about the work done, but branches and merge requests are more commonly used for tracking development progress at a high level. **Independent Test**: Can be tested by requesting development information for an issue with linked commits, and verifying commit messages, authors, and timestamps are returned. **Acceptance Scenarios**: 1. **Given** a Jira issue with linked commits, **When** the user requests development information including commits, **Then** the system returns commit messages, authors, dates, and commit IDs 2. **Given** commits from multiple repositories, **When** the user requests development information, **Then** commits are grouped or labeled by repository --- ### Edge Cases - What happens when a Jira issue has development information from multiple repositories or Git hosting services (GitHub, GitLab, Bitbucket)? - How does the system handle issues where development information exists but the user lacks permissions to view the linked repositories? - What happens when branch or merge request data is incomplete or the external Git service is unavailable? - How does the system handle very large numbers of branches or merge requests (e.g., 50+ branches)? - What happens when development information includes both Cloud and Data Center Jira instances? ## Requirements *(mandatory)* ### Functional Requirements - **FR-001**: System MUST expose a `jira_get_development_information` tool that accepts an issue key parameter - **FR-002**: Tool MUST retrieve branches linked to the specified Jira issue, including branch name, repository name, and repository URL - **FR-003**: Tool MUST retrieve merge requests (pull requests) linked to the specified Jira issue, including title, state, URL, author, and creation date - **FR-004**: Tool MUST retrieve commit information linked to the specified Jira issue, including commit message, author, timestamp, and commit ID - **FR-005**: Tool MUST validate that the issue_key parameter is provided and follows valid Jira issue key format (e.g., PROJ-123) - **FR-006**: Tool MUST return human-readable formatted text suitable for LLM consumption, organizing information by type (branches, merge requests, commits) - **FR-007**: Tool MUST handle errors gracefully, including invalid issue keys, non-existent issues, permission errors, and API failures - **FR-008**: Tool MUST support optional filtering parameters to retrieve only specific types of development information (branches, merge requests, or commits) - **FR-009**: System MUST reuse the singleton Jira client connection established by the services package - **FR-010**: Tool MUST handle cases where no development information is linked to an issue by returning a clear message - **FR-011**: System MUST use Jira's standard `/rest/dev-status/1.0/issue/detail` endpoint via the go-atlassian client to retrieve development information ### Key Entities - **Development Information**: Aggregated data about code development activity related to a Jira issue, including branches, merge requests, and commits - **Branch**: A Git branch linked to a Jira issue, containing name, repository identifier, and URL - **Merge Request**: A pull request or merge request linked to a Jira issue, containing title, state (open/merged/closed/declined), URL, author, and timestamps - **Commit**: A Git commit linked to a Jira issue, containing message, author, timestamp, commit ID, and repository information - **Repository**: The source code repository where branches, commits, and merge requests exist, identified by name, URL, and hosting service type ## Success Criteria *(mandatory)* ### Measurable Outcomes - **SC-001**: Users can retrieve complete development information for a Jira issue in a single tool call - **SC-002**: The tool returns results within 3 seconds for issues with up to 50 linked development items - **SC-003**: The formatted output clearly distinguishes between branches, merge requests, and commits with appropriate grouping and labels - **SC-004**: 100% of valid Jira issue keys return either development information or a clear "no development work linked" message - **SC-005**: Error messages clearly identify the issue (invalid key format, issue not found, permission denied, API error) in 100% of failure cases - **SC-006**: The tool successfully handles development information from all major Git hosting services (GitHub, GitLab, Bitbucket) supported by Jira ## Assumptions - The Atlassian instance has development tool integrations configured (e.g., GitHub, GitLab, Bitbucket integrations enabled) - Users have appropriate Jira permissions to view development information for the issues they query - The go-atlassian library provides access to Jira's development information APIs - Development information is retrieved from Jira's stored data, not by directly querying Git hosting services - The default behavior (when no filter is specified) is to return all types of development information - Branch and merge request URLs point to the external Git hosting service and are provided by Jira's development information API ``` -------------------------------------------------------------------------------- /util/jira_formatter.go: -------------------------------------------------------------------------------- ```go package util import ( "fmt" "strings" "github.com/ctreminiom/go-atlassian/pkg/infra/models" ) // FormatJiraIssue converts a Jira issue struct to a formatted string representation // It handles all available fields from IssueFieldsSchemeV2 and related schemas func FormatJiraIssue(issue *models.IssueScheme) string { var sb strings.Builder // Basic issue information sb.WriteString(fmt.Sprintf("Key: %s\n", issue.Key)) if issue.ID != "" { sb.WriteString(fmt.Sprintf("ID: %s\n", issue.ID)) } if issue.Self != "" { sb.WriteString(fmt.Sprintf("URL: %s\n", issue.Self)) } // Fields information if issue.Fields != nil { fields := issue.Fields // Summary and Description if fields.Summary != "" { sb.WriteString(fmt.Sprintf("Summary: %s\n", fields.Summary)) } if fields.Description != nil { sb.WriteString(fmt.Sprintf("Description: %s\n", fields.Description)) } // Issue Type if fields.IssueType != nil { sb.WriteString(fmt.Sprintf("Type: %s\n", fields.IssueType.Name)) if fields.IssueType.Description != "" { sb.WriteString(fmt.Sprintf("Type Description: %s\n", fields.IssueType.Description)) } } // Status if fields.Status != nil { sb.WriteString(fmt.Sprintf("Status: %s\n", fields.Status.Name)) if fields.Status.Description != "" { sb.WriteString(fmt.Sprintf("Status Description: %s\n", fields.Status.Description)) } } // Priority if fields.Priority != nil { sb.WriteString(fmt.Sprintf("Priority: %s\n", fields.Priority.Name)) } else { sb.WriteString("Priority: None\n") } // Resolution if fields.Resolution != nil { sb.WriteString(fmt.Sprintf("Resolution: %s\n", fields.Resolution.Name)) if fields.Resolution.Description != "" { sb.WriteString(fmt.Sprintf("Resolution Description: %s\n", fields.Resolution.Description)) } } // Resolution Date if fields.Resolutiondate != "" { sb.WriteString(fmt.Sprintf("Resolution Date: %s\n", fields.Resolutiondate)) } // People if fields.Reporter != nil { sb.WriteString(fmt.Sprintf("Reporter: %s", fields.Reporter.DisplayName)) if fields.Reporter.EmailAddress != "" { sb.WriteString(fmt.Sprintf(" (%s)", fields.Reporter.EmailAddress)) } sb.WriteString("\n") } else { sb.WriteString("Reporter: Unassigned\n") } if fields.Assignee != nil { sb.WriteString(fmt.Sprintf("Assignee: %s", fields.Assignee.DisplayName)) if fields.Assignee.EmailAddress != "" { sb.WriteString(fmt.Sprintf(" (%s)", fields.Assignee.EmailAddress)) } sb.WriteString("\n") } else { sb.WriteString("Assignee: Unassigned\n") } if fields.Creator != nil { sb.WriteString(fmt.Sprintf("Creator: %s", fields.Creator.DisplayName)) if fields.Creator.EmailAddress != "" { sb.WriteString(fmt.Sprintf(" (%s)", fields.Creator.EmailAddress)) } sb.WriteString("\n") } // Dates if fields.Created != "" { sb.WriteString(fmt.Sprintf("Created: %s\n", fields.Created)) } if fields.Updated != "" { sb.WriteString(fmt.Sprintf("Updated: %s\n", fields.Updated)) } if fields.LastViewed != "" { sb.WriteString(fmt.Sprintf("Last Viewed: %s\n", fields.LastViewed)) } if fields.StatusCategoryChangeDate != "" { sb.WriteString(fmt.Sprintf("Status Category Change Date: %s\n", fields.StatusCategoryChangeDate)) } // Project information if fields.Project != nil { sb.WriteString(fmt.Sprintf("Project: %s", fields.Project.Name)) if fields.Project.Key != "" { sb.WriteString(fmt.Sprintf(" (%s)", fields.Project.Key)) } sb.WriteString("\n") } // Parent issue if fields.Parent != nil { sb.WriteString(fmt.Sprintf("Parent: %s", fields.Parent.Key)) if fields.Parent.Fields != nil && fields.Parent.Fields.Summary != "" { sb.WriteString(fmt.Sprintf(" - %s", fields.Parent.Fields.Summary)) } sb.WriteString("\n") } // Work information if fields.Workratio > 0 { sb.WriteString(fmt.Sprintf("Work Ratio: %d\n", fields.Workratio)) } // Labels if len(fields.Labels) > 0 { sb.WriteString(fmt.Sprintf("Labels: %s\n", strings.Join(fields.Labels, ", "))) } // Components if len(fields.Components) > 0 { sb.WriteString("Components:\n") for _, component := range fields.Components { sb.WriteString(fmt.Sprintf("- %s", component.Name)) if component.Description != "" { sb.WriteString(fmt.Sprintf(" (%s)", component.Description)) } sb.WriteString("\n") } } // Fix Versions if len(fields.FixVersions) > 0 { sb.WriteString("Fix Versions:\n") for _, version := range fields.FixVersions { sb.WriteString(fmt.Sprintf("- %s", version.Name)) if version.Description != "" { sb.WriteString(fmt.Sprintf(" (%s)", version.Description)) } sb.WriteString("\n") } } // Affected Versions if len(fields.Versions) > 0 { sb.WriteString("Affected Versions:\n") for _, version := range fields.Versions { sb.WriteString(fmt.Sprintf("- %s", version.Name)) if version.Description != "" { sb.WriteString(fmt.Sprintf(" (%s)", version.Description)) } sb.WriteString("\n") } } // Security Level if fields.Security != nil { sb.WriteString(fmt.Sprintf("Security Level: %s\n", fields.Security.Name)) } // Subtasks if len(fields.Subtasks) > 0 { sb.WriteString("Subtasks:\n") for _, subtask := range fields.Subtasks { sb.WriteString(fmt.Sprintf("- %s", subtask.Key)) if subtask.Fields != nil && subtask.Fields.Summary != "" { sb.WriteString(fmt.Sprintf(": %s", subtask.Fields.Summary)) } if subtask.Fields != nil && subtask.Fields.Status != nil { sb.WriteString(fmt.Sprintf(" [%s]", subtask.Fields.Status.Name)) } sb.WriteString("\n") } } // Issue Links if len(fields.IssueLinks) > 0 { sb.WriteString("Issue Links:\n") for _, link := range fields.IssueLinks { if link.OutwardIssue != nil { sb.WriteString(fmt.Sprintf("- %s %s", link.Type.Outward, link.OutwardIssue.Key)) if link.OutwardIssue.Fields != nil && link.OutwardIssue.Fields.Summary != "" { sb.WriteString(fmt.Sprintf(": %s", link.OutwardIssue.Fields.Summary)) } sb.WriteString("\n") } if link.InwardIssue != nil { sb.WriteString(fmt.Sprintf("- %s %s", link.Type.Inward, link.InwardIssue.Key)) if link.InwardIssue.Fields != nil && link.InwardIssue.Fields.Summary != "" { sb.WriteString(fmt.Sprintf(": %s", link.InwardIssue.Fields.Summary)) } sb.WriteString("\n") } } } // Watchers if fields.Watcher != nil { sb.WriteString(fmt.Sprintf("Watchers: %d\n", fields.Watcher.WatchCount)) } // Votes if fields.Votes != nil { sb.WriteString(fmt.Sprintf("Votes: %d\n", fields.Votes.Votes)) } // Comments (summary only to avoid too much text) if fields.Comment != nil && fields.Comment.Total > 0 { sb.WriteString(fmt.Sprintf("Comments: %d total\n", fields.Comment.Total)) } // Worklogs (summary only) if fields.Worklog != nil && fields.Worklog.Total > 0 { sb.WriteString(fmt.Sprintf("Worklogs: %d entries\n", fields.Worklog.Total)) } } // Available Transitions if len(issue.Transitions) > 0 { sb.WriteString("\nAvailable Transitions:\n") for _, transition := range issue.Transitions { sb.WriteString(fmt.Sprintf("- %s (ID: %s)\n", transition.Name, transition.ID)) } } // Story point estimate from changelog (if available) if issue.Changelog != nil && issue.Changelog.Histories != nil { storyPoint := "" for _, history := range issue.Changelog.Histories { for _, item := range history.Items { if item.Field == "Story point estimate" && item.ToString != "" { storyPoint = item.ToString } } } if storyPoint != "" { sb.WriteString(fmt.Sprintf("Story Point Estimate: %s\n", storyPoint)) } } return sb.String() } // FormatJiraIssueCompact returns a compact single-line representation of a Jira issue // Useful for search results or lists func FormatJiraIssueCompact(issue *models.IssueScheme) string { if issue == nil { return "" } var parts []string parts = append(parts, fmt.Sprintf("Key: %s", issue.Key)) if issue.Fields != nil { fields := issue.Fields if fields.Summary != "" { parts = append(parts, fmt.Sprintf("Summary: %s", fields.Summary)) } if fields.Status != nil { parts = append(parts, fmt.Sprintf("Status: %s", fields.Status.Name)) } if fields.Assignee != nil { parts = append(parts, fmt.Sprintf("Assignee: %s", fields.Assignee.DisplayName)) } else { parts = append(parts, "Assignee: Unassigned") } if fields.Priority != nil { parts = append(parts, fmt.Sprintf("Priority: %s", fields.Priority.Name)) } } return strings.Join(parts, " | ") } ``` -------------------------------------------------------------------------------- /specs/001-i-want-to/plan.md: -------------------------------------------------------------------------------- ```markdown # Implementation Plan: Retrieve Development Information from Jira Issue **Branch**: `001-i-want-to` | **Date**: 2025-10-07 | **Spec**: [spec.md](./spec.md) **Input**: Feature specification from `/specs/001-i-want-to/spec.md` ## Summary This feature adds a new MCP tool `jira_get_development_information` that retrieves branches, merge requests (pull requests), and commits linked to a Jira issue via Jira's Development Information API (`/rest/dev-status/1.0/issue/detail`). The tool will follow the existing pattern of typed handlers, singleton Jira client usage, and LLM-optimized text output. ## Technical Context **Language/Version**: Go 1.23.2 **Primary Dependencies**: - `github.com/ctreminiom/go-atlassian v1.6.1` (Jira API client) - `github.com/mark3labs/mcp-go v0.32.0` (MCP protocol) **Storage**: N/A (stateless API wrapper) **Testing**: Go standard testing (`go test ./...`), integration tests with live Jira instance **Target Platform**: Cross-platform (macOS, Linux, Windows) via compiled Go binary **Project Type**: Single project - MCP server binary **Performance Goals**: Response within 3 seconds for issues with up to 50 linked development items **Constraints**: Relies on Jira's stored development information (GitHub, GitLab, Bitbucket integrations must be configured in Jira) **Scale/Scope**: Single new MCP tool with 3-4 optional filter parameters ## Constitution Check *GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* ### Initial Check (Pre-Phase 0) ✅ **MCP Protocol Compliance:** - [x] All features exposed via MCP tools (no direct API bypass) - New tool `jira_get_development_information` - [x] Tool names follow `jira_<operation>` convention - Tool named `jira_get_development_information` - [x] STDIO mode primary, HTTP mode development-only - Inherits existing server modes **AI-First Output:** - [x] Responses formatted for LLM readability - Will use human-readable text with clear sections for branches, merge requests, commits - [x] Error messages include diagnostic context (endpoint, response body) - Following existing error handling pattern - [x] Output uses `util.Format*` functions or similar formatting - Will create `util.FormatDevelopmentInfo` if needed (only if reused 3+ times per constitution) **Simplicity:** - [x] No unnecessary abstraction layers (managers, facades, orchestrators) - Direct API call in handler - [x] Direct client calls preferred over wrappers - Handler calls `client` directly - [x] Complexity violations documented in "Complexity Tracking" below - No violations **Type Safety:** - [x] Input structs defined with JSON tags and validation - `GetDevelopmentInfoInput` struct with `issue_key` required field - [x] Typed handlers used (`mcp.NewTypedToolHandler`) - Will use `mcp.NewTypedToolHandler(jiraGetDevelopmentInfoHandler)` **Resource Efficiency:** - [x] Singleton pattern for client connections (`services.JiraClient()`) - Uses existing singleton - [x] No per-request client creation - Reuses `services.JiraClient()` **Testing Gates:** - [x] Integration tests for new tool categories - Will add test to verify tool registration and basic response - [x] Contract tests for tool registration and parameters - Will verify required parameters enforced ### Post-Phase 1 Design Review ✅ **MCP Protocol Compliance:** - [x] Tool contract defined in `contracts/mcp-tool-contract.json` with complete input schema - [x] Tool name confirmed: `jira_get_development_information` - [x] All parameters properly typed (string for issue_key, boolean for filters) **AI-First Output:** - [x] Output format designed in research.md - plain text with === section dividers - [x] Hierarchical formatting: sections for branches/PRs/commits with indentation - [x] Error messages include endpoint context (verified in contract) - [x] **CONFIRMED**: No util function - inline string builder formatting (per research Task 2) **Simplicity:** - [x] Single tool file: `tools/jira_development.go` - [x] Direct API calls using `client.NewRequest()` and `client.Call()` - [x] No wrapper services or helper classes - [x] Inline formatting functions within handler (formatBranches, formatPullRequests, formatCommits) **Type Safety:** - [x] Input struct defined in data-model.md: `GetDevelopmentInfoInput` with validate tags - [x] Response structs defined: DevStatusResponse, Branch, PullRequest, Repository, Commit, Author - [x] All JSON tags specified - [x] Validation: `validate:"required"` on issue_key field **Resource Efficiency:** - [x] Uses existing `services.JiraClient()` singleton - [x] Single API call per tool invocation (convert issue key → fetch dev info) - [x] No caching layer (keeps it simple) **Testing Gates:** - [x] Test plan documented in contract: unit tests for registration, integration tests for API calls - [x] Test file locations specified: `tools/jira_development_test.go`, `tests/development_test.go` **Design Quality:** - [x] Data model complete with entity relationships documented - [x] API contract specifies all request/response formats - [x] Quickstart guide provides usage examples - [x] Research decisions documented with rationale ### Compliance Status: ✅ PASSED All constitution principles are satisfied. No violations. Ready for `/speckit.tasks` to generate implementation tasks. ## Project Structure ### Documentation (this feature) ``` specs/001-i-want-to/ ├── plan.md # This file ├── research.md # Phase 0: API research and response format decisions ├── data-model.md # Phase 1: Development information entities ├── quickstart.md # Phase 1: Usage examples ├── contracts/ # Phase 1: API response schema │ └── dev-info-schema.json └── tasks.md # Phase 2: Implementation tasks (generated by /speckit.tasks) ``` ### Source Code (repository root) ``` # Single project structure (matches existing) tools/ ├── jira_issue.go ├── jira_comment.go ├── jira_sprint.go ├── jira_development.go # NEW: Development info tool registration and handler └── ... services/ └── jira.go # Existing: Singleton client util/ └── formatter.go # Potentially NEW: FormatDevelopmentInfo (only if complex) main.go # Updated: Register new tool tests/ # NEW: Integration test for development info tool └── development_test.go ``` **Structure Decision**: This follows the existing single-project Go structure. The new tool will be implemented in `tools/jira_development.go` following the same pattern as `tools/jira_issue.go`. No new directories or architectural changes needed. ## Complexity Tracking *No complexity violations identified. The implementation follows existing patterns with no additional abstraction layers.* ## Phase 0: Research Tasks ### Research Task 1: go-atlassian Development Information API **Objective**: Determine the exact method and response structure for retrieving development information from the go-atlassian library. **Questions to Answer**: 1. Does `go-atlassian` provide a method for `/rest/dev-status/1.0/issue/detail` endpoint? 2. What is the response structure (types, fields)? 3. How are branches, merge requests, and commits organized in the response? 4. What error cases exist (issue not found, no dev info, permission denied)? 5. Are there any pagination or rate limiting considerations? **Research Method**: - Review go-atlassian documentation and source code - Check for methods in client Issue service or Development service - Test with live Jira instance if available ### Research Task 2: Output Formatting Best Practices **Objective**: Define the optimal text format for LLM consumption of development information. **Questions to Answer**: 1. How should branches, merge requests, and commits be grouped and labeled? 2. What level of detail is appropriate for each item (full metadata vs. summary)? 3. How to handle empty results (no development info linked)? 4. What formatting makes state information (open/merged/closed) clear? **Research Method**: - Review existing `util.Format*` functions in codebase - Consider markdown-style formatting with headers and bullet lists - Design for clarity without verbose JSON ### Research Task 3: Filter Parameter Design **Objective**: Determine the optimal parameter structure for filtering by development information type. **Questions to Answer**: 1. Should filters be separate boolean flags (`include_branches`, `include_commits`) or an enum/string array? 2. What is the default behavior (all types vs. explicit opt-in)? 3. How do other Jira MCP tools handle optional filtering? **Research Method**: - Review existing tool parameters in `tools/` directory - Check go-atlassian API capabilities for filtering - Consider LLM usability (simpler is better) **Output**: `research.md` with decisions and rationale for all three research tasks. ``` -------------------------------------------------------------------------------- /tools/jira_sprint.go: -------------------------------------------------------------------------------- ```go package tools import ( "context" "fmt" "strconv" "strings" "github.com/ctreminiom/go-atlassian/pkg/infra/models" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "github.com/nguyenvanduocit/jira-mcp/services" ) // Input types for typed tools type ListSprintsInput struct { BoardID string `json:"board_id,omitempty"` ProjectKey string `json:"project_key,omitempty"` } type GetSprintInput struct { SprintID string `json:"sprint_id" validate:"required"` } type GetActiveSprintInput struct { BoardID string `json:"board_id,omitempty"` ProjectKey string `json:"project_key,omitempty"` } type SearchSprintByNameInput struct { Name string `json:"name" validate:"required"` BoardID string `json:"board_id,omitempty"` ProjectKey string `json:"project_key,omitempty"` ExactMatch bool `json:"exact_match,omitempty"` } func RegisterJiraSprintTool(s *server.MCPServer) { jiraListSprintTool := mcp.NewTool("jira_list_sprints", mcp.WithDescription("List all active and future sprints for a specific Jira board or project. Requires either board_id or project_key."), mcp.WithString("board_id", mcp.Description("Numeric ID of the Jira board (can be found in board URL). Optional if project_key is provided.")), mcp.WithString("project_key", mcp.Description("The project key (e.g., KP, PROJ, DEV). Optional if board_id is provided.")), ) s.AddTool(jiraListSprintTool, mcp.NewTypedToolHandler(jiraListSprintHandler)) jiraGetSprintTool := mcp.NewTool("jira_get_sprint", mcp.WithDescription("Retrieve detailed information about a specific Jira sprint by its ID"), mcp.WithString("sprint_id", mcp.Required(), mcp.Description("Numeric ID of the sprint to retrieve")), ) s.AddTool(jiraGetSprintTool, mcp.NewTypedToolHandler(jiraGetSprintHandler)) jiraGetActiveSprintTool := mcp.NewTool("jira_get_active_sprint", mcp.WithDescription("Get the currently active sprint for a given board or project. Requires either board_id or project_key."), mcp.WithString("board_id", mcp.Description("Numeric ID of the Jira board. Optional if project_key is provided.")), mcp.WithString("project_key", mcp.Description("The project key (e.g., KP, PROJ, DEV). Optional if board_id is provided.")), ) s.AddTool(jiraGetActiveSprintTool, mcp.NewTypedToolHandler(jiraGetActiveSprintHandler)) jiraSearchSprintByNameTool := mcp.NewTool("jira_search_sprint_by_name", mcp.WithDescription("Search for sprints by name across boards or projects. Supports both exact and partial name matching."), mcp.WithString("name", mcp.Required(), mcp.Description("Sprint name to search for (case-insensitive)")), mcp.WithString("board_id", mcp.Description("Numeric ID of the Jira board to search in. Optional if project_key is provided.")), mcp.WithString("project_key", mcp.Description("The project key (e.g., KP, PROJ, DEV) to search in. Optional if board_id is provided.")), mcp.WithBoolean("exact_match", mcp.Description("If true, only return sprints with exact name match. Default is false (partial matching).")), ) s.AddTool(jiraSearchSprintByNameTool, mcp.NewTypedToolHandler(searchSprintByNameHandler)) } // Helper function to get board IDs either from direct board_id or by finding boards for a project func getBoardIDsFromInput(ctx context.Context, boardID, projectKey string) ([]int, error) { if boardID == "" && projectKey == "" { return nil, fmt.Errorf("either board_id or project_key argument is required") } if boardID != "" { boardIDInt, err := strconv.Atoi(boardID) if err != nil { return nil, fmt.Errorf("invalid board_id: %v", err) } return []int{boardIDInt}, nil } if projectKey != "" { boards, response, err := services.AgileClient().Board.Gets(ctx, &models.GetBoardsOptions{ ProjectKeyOrID: projectKey, }, 0, 50) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get boards: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get boards: %v", err) } if len(boards.Values) == 0 { return nil, fmt.Errorf("no boards found for project: %s", projectKey) } var boardIDs []int for _, board := range boards.Values { boardIDs = append(boardIDs, board.ID) } return boardIDs, nil } return nil, fmt.Errorf("either board_id or project_key argument is required") } func jiraGetSprintHandler(ctx context.Context, request mcp.CallToolRequest, input GetSprintInput) (*mcp.CallToolResult, error) { sprintID, err := strconv.Atoi(input.SprintID) if err != nil { return nil, fmt.Errorf("invalid sprint_id: %v", err) } sprint, response, err := services.AgileClient().Sprint.Get(ctx, sprintID) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get sprint: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get sprint: %v", err) } result := fmt.Sprintf(`Sprint Details: ID: %d Name: %s State: %s Start Date: %s End Date: %s Complete Date: %s Origin Board ID: %d Goal: %s`, sprint.ID, sprint.Name, sprint.State, sprint.StartDate, sprint.EndDate, sprint.CompleteDate, sprint.OriginBoardID, sprint.Goal, ) return mcp.NewToolResultText(result), nil } func jiraListSprintHandler(ctx context.Context, request mcp.CallToolRequest, input ListSprintsInput) (*mcp.CallToolResult, error) { boardIDs, err := getBoardIDsFromInput(ctx, input.BoardID, input.ProjectKey) if err != nil { return nil, err } var allSprints []string for _, boardID := range boardIDs { sprints, response, err := services.AgileClient().Board.Sprints(ctx, boardID, 0, 50, []string{"active", "future"}) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get sprints: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get sprints: %v", err) } for _, sprint := range sprints.Values { allSprints = append(allSprints, fmt.Sprintf("ID: %d\nName: %s\nState: %s\nStartDate: %s\nEndDate: %s\nBoard ID: %d\n", sprint.ID, sprint.Name, sprint.State, sprint.StartDate, sprint.EndDate, boardID)) } } if len(allSprints) == 0 { return mcp.NewToolResultText("No sprints found."), nil } result := strings.Join(allSprints, "\n") return mcp.NewToolResultText(result), nil } func jiraGetActiveSprintHandler(ctx context.Context, request mcp.CallToolRequest, input GetActiveSprintInput) (*mcp.CallToolResult, error) { boardIDs, err := getBoardIDsFromInput(ctx, input.BoardID, input.ProjectKey) if err != nil { return nil, err } // Loop through boards and return the first active sprint found for _, boardID := range boardIDs { sprints, response, err := services.AgileClient().Board.Sprints(ctx, boardID, 0, 50, []string{"active"}) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get active sprint: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } continue // Try next board if this one fails } if len(sprints.Values) > 0 { sprint := sprints.Values[0] result := fmt.Sprintf(`Active Sprint: ID: %d Name: %s State: %s Start Date: %s End Date: %s Board ID: %d`, sprint.ID, sprint.Name, sprint.State, sprint.StartDate, sprint.EndDate, boardID, ) return mcp.NewToolResultText(result), nil } } return mcp.NewToolResultText("No active sprint found."), nil } func searchSprintByNameHandler(ctx context.Context, request mcp.CallToolRequest, input SearchSprintByNameInput) (*mcp.CallToolResult, error) { boardIDs, err := getBoardIDsFromInput(ctx, input.BoardID, input.ProjectKey) if err != nil { return nil, err } var matchingSprints []string searchTerm := strings.ToLower(input.Name) for _, boardID := range boardIDs { // Get all sprints (active, future, and closed) for comprehensive search sprints, response, err := services.AgileClient().Board.Sprints(ctx, boardID, 0, 100, []string{"active", "future", "closed"}) if err != nil { if response != nil { return nil, fmt.Errorf("failed to get sprints: %s (endpoint: %s)", response.Bytes.String(), response.Endpoint) } return nil, fmt.Errorf("failed to get sprints: %v", err) } for _, sprint := range sprints.Values { sprintNameLower := strings.ToLower(sprint.Name) var isMatch bool if input.ExactMatch { isMatch = sprintNameLower == searchTerm } else { isMatch = strings.Contains(sprintNameLower, searchTerm) } if isMatch { matchingSprints = append(matchingSprints, fmt.Sprintf(`ID: %d Name: %s State: %s Start Date: %s End Date: %s Complete Date: %s Board ID: %d Goal: %s`, sprint.ID, sprint.Name, sprint.State, sprint.StartDate, sprint.EndDate, sprint.CompleteDate, boardID, sprint.Goal)) } } } if len(matchingSprints) == 0 { matchType := "containing" if input.ExactMatch { matchType = "with exact name" } return mcp.NewToolResultText(fmt.Sprintf("No sprints found %s '%s'.", matchType, input.Name)), nil } result := strings.Join(matchingSprints, "\n\n") return mcp.NewToolResultText(result), nil } ``` -------------------------------------------------------------------------------- /.specify/templates/tasks-template.md: -------------------------------------------------------------------------------- ```markdown --- description: "Task list template for feature implementation" --- # Tasks: [FEATURE NAME] **Input**: Design documents from `/specs/[###-feature-name]/` **Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/ **Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification. **Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story. ## Format: `[ID] [P?] [Story] Description` - **[P]**: Can run in parallel (different files, no dependencies) - **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3) - Include exact file paths in descriptions ## Path Conventions - **Single project**: `src/`, `tests/` at repository root - **Web app**: `backend/src/`, `frontend/src/` - **Mobile**: `api/src/`, `ios/src/` or `android/src/` - Paths shown below assume single project - adjust based on plan.md structure <!-- ============================================================================ IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only. The /speckit.tasks command MUST replace these with actual tasks based on: - User stories from spec.md (with their priorities P1, P2, P3...) - Feature requirements from plan.md - Entities from data-model.md - Endpoints from contracts/ Tasks MUST be organized by user story so each story can be: - Implemented independently - Tested independently - Delivered as an MVP increment DO NOT keep these sample tasks in the generated tasks.md file. ============================================================================ --> ## Phase 1: Setup (Shared Infrastructure) **Purpose**: Project initialization and basic structure - [ ] T001 Create project structure per implementation plan - [ ] T002 Initialize Go module with MCP dependencies (`github.com/mark3labs/mcp-go`, `github.com/ctreminiom/go-atlassian`) - [ ] T003 [P] Configure linting and formatting tools (golangci-lint, gofmt) --- ## Phase 2: Foundational (Blocking Prerequisites) **Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented **⚠️ CRITICAL**: No user story work can begin until this phase is complete Examples of foundational tasks (adjust based on your project): - [ ] T004 Setup database schema and migrations framework - [ ] T005 [P] Implement authentication/authorization framework - [ ] T006 [P] Setup API routing and middleware structure - [ ] T007 Create base models/entities that all stories depend on - [ ] T008 Configure error handling and logging infrastructure - [ ] T009 Setup environment configuration management **Checkpoint**: Foundation ready - user story implementation can now begin in parallel --- ## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP **Goal**: [Brief description of what this story delivers] **Independent Test**: [How to verify this story works on its own] ### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️ **NOTE: Write these tests FIRST, ensure they FAIL before implementation** - [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py - [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py ### Implementation for User Story 1 - [ ] T012 [P] [US1] Define `<Operation>Input` struct with JSON tags and validation in tools/jira_[category].go - [ ] T013 [US1] Implement `RegisterJira<Category>Tool` registration function in tools/jira_[category].go - [ ] T014 [US1] Implement `jira<Operation>Handler` typed handler in tools/jira_[category].go - [ ] T015 [US1] Add formatter function in util/jira_formatter.go (if output used by 3+ tools) - [ ] T016 [US1] Register tool in main.go via `tools.RegisterJira<Category>Tool(mcpServer)` - [ ] T017 [US1] Add integration test in tools/jira_[category]_test.go **Checkpoint**: At this point, User Story 1 should be fully functional and testable independently --- ## Phase 4: User Story 2 - [Title] (Priority: P2) **Goal**: [Brief description of what this story delivers] **Independent Test**: [How to verify this story works on its own] ### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️ - [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py - [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py ### Implementation for User Story 2 - [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py - [ ] T021 [US2] Implement [Service] in src/services/[service].py - [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py - [ ] T023 [US2] Integrate with User Story 1 components (if needed) **Checkpoint**: At this point, User Stories 1 AND 2 should both work independently --- ## Phase 5: User Story 3 - [Title] (Priority: P3) **Goal**: [Brief description of what this story delivers] **Independent Test**: [How to verify this story works on its own] ### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️ - [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py - [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py ### Implementation for User Story 3 - [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py - [ ] T027 [US3] Implement [Service] in src/services/[service].py - [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py **Checkpoint**: All user stories should now be independently functional --- [Add more user story phases as needed, following the same pattern] --- ## Phase N: Polish & Cross-Cutting Concerns **Purpose**: Improvements that affect multiple user stories - [ ] TXXX [P] Documentation updates in docs/ - [ ] TXXX Code cleanup and refactoring - [ ] TXXX Performance optimization across all stories - [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/ - [ ] TXXX Security hardening - [ ] TXXX Run quickstart.md validation --- ## Dependencies & Execution Order ### Phase Dependencies - **Setup (Phase 1)**: No dependencies - can start immediately - **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories - **User Stories (Phase 3+)**: All depend on Foundational phase completion - User stories can then proceed in parallel (if staffed) - Or sequentially in priority order (P1 → P2 → P3) - **Polish (Final Phase)**: Depends on all desired user stories being complete ### User Story Dependencies - **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories - **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable - **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable ### Within Each User Story - Tests (if included) MUST be written and FAIL before implementation - Models before services - Services before endpoints - Core implementation before integration - Story complete before moving to next priority ### Parallel Opportunities - All Setup tasks marked [P] can run in parallel - All Foundational tasks marked [P] can run in parallel (within Phase 2) - Once Foundational phase completes, all user stories can start in parallel (if team capacity allows) - All tests for a user story marked [P] can run in parallel - Models within a story marked [P] can run in parallel - Different user stories can be worked on in parallel by different team members --- ## Parallel Example: User Story 1 ```bash # Launch all tests for User Story 1 together (if tests requested): Task: "Contract test for [endpoint] in tests/contract/test_[name].py" Task: "Integration test for [user journey] in tests/integration/test_[name].py" # Launch all models for User Story 1 together: Task: "Create [Entity1] model in src/models/[entity1].py" Task: "Create [Entity2] model in src/models/[entity2].py" ``` --- ## Implementation Strategy ### MVP First (User Story 1 Only) 1. Complete Phase 1: Setup 2. Complete Phase 2: Foundational (CRITICAL - blocks all stories) 3. Complete Phase 3: User Story 1 4. **STOP and VALIDATE**: Test User Story 1 independently 5. Deploy/demo if ready ### Incremental Delivery 1. Complete Setup + Foundational → Foundation ready 2. Add User Story 1 → Test independently → Deploy/Demo (MVP!) 3. Add User Story 2 → Test independently → Deploy/Demo 4. Add User Story 3 → Test independently → Deploy/Demo 5. Each story adds value without breaking previous stories ### Parallel Team Strategy With multiple developers: 1. Team completes Setup + Foundational together 2. Once Foundational is done: - Developer A: User Story 1 - Developer B: User Story 2 - Developer C: User Story 3 3. Stories complete and integrate independently --- ## Notes - [P] tasks = different files, no dependencies - [Story] label maps task to specific user story for traceability - Each user story should be independently completable and testable - Verify tests fail before implementing - Commit after each task or logical group - Stop at any checkpoint to validate story independently - Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.clarify.md: -------------------------------------------------------------------------------- ```markdown --- description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec. --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Outline Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file. Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit.plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases. Execution steps: 1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields: - `FEATURE_DIR` - `FEATURE_SPEC` - (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.) - If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment. 2. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked). Functional Scope & Behavior: - Core user goals & success criteria - Explicit out-of-scope declarations - User roles / personas differentiation Domain & Data Model: - Entities, attributes, relationships - Identity & uniqueness rules - Lifecycle/state transitions - Data volume / scale assumptions Interaction & UX Flow: - Critical user journeys / sequences - Error/empty/loading states - Accessibility or localization notes Non-Functional Quality Attributes: - Performance (latency, throughput targets) - Scalability (horizontal/vertical, limits) - Reliability & availability (uptime, recovery expectations) - Observability (logging, metrics, tracing signals) - Security & privacy (authN/Z, data protection, threat assumptions) - Compliance / regulatory constraints (if any) Integration & External Dependencies: - External services/APIs and failure modes - Data import/export formats - Protocol/versioning assumptions Edge Cases & Failure Handling: - Negative scenarios - Rate limiting / throttling - Conflict resolution (e.g., concurrent edits) Constraints & Tradeoffs: - Technical constraints (language, storage, hosting) - Explicit tradeoffs or rejected alternatives Terminology & Consistency: - Canonical glossary terms - Avoided synonyms / deprecated terms Completion Signals: - Acceptance criteria testability - Measurable Definition of Done style indicators Misc / Placeholders: - TODO markers / unresolved decisions - Ambiguous adjectives ("robust", "intuitive") lacking quantification For each category with Partial or Missing status, add a candidate question opportunity unless: - Clarification would not materially change implementation or validation strategy - Information is better deferred to planning phase (note internally) 3. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints: - Maximum of 10 total questions across the whole session. - Each question must be answerable with EITHER: * A short multiple‑choice selection (2–5 distinct, mutually exclusive options), OR * A one-word / short‑phrase answer (explicitly constrain: "Answer in <=5 words"). - Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation. - Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved. - Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness). - Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests. - If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic. 4. Sequential questioning loop (interactive): - Present EXACTLY ONE question at a time. - For multiple‑choice questions render options as a Markdown table: | Option | Description | |--------|-------------| | A | <Option A description> | | B | <Option B description> | | C | <Option C description> | (add D/E as needed up to 5) | Short | Provide a different short answer (<=5 words) | (Include only if free-form alternative is appropriate) - For short‑answer style (no meaningful discrete options), output a single line after the question: `Format: Short answer (<=5 words)`. - After the user answers: * Validate the answer maps to one option or fits the <=5 word constraint. * If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance). * Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question. - Stop asking further questions when: * All critical ambiguities resolved early (remaining queued items become unnecessary), OR * User signals completion ("done", "good", "no more"), OR * You reach 5 asked questions. - Never reveal future queued questions in advance. - If no valid questions exist at start, immediately report no critical ambiguities. 5. Integration after EACH accepted answer (incremental update approach): - Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents. - For the first integrated answer in this session: * Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing). * Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today. - Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`. - Then immediately apply the clarification to the most appropriate section(s): * Functional ambiguity → Update or add a bullet in Functional Requirements. * User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario. * Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly. * Non-functional constraint → Add/modify measurable criteria in Non-Functional / Quality Attributes section (convert vague adjective to metric or explicit target). * Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it). * Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once. - If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text. - Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite). - Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact. - Keep each inserted clarification minimal and testable (avoid narrative drift). 6. Validation (performed after EACH write plus final pass): - Clarifications session contains exactly one bullet per accepted answer (no duplicates). - Total asked (accepted) questions ≤ 5. - Updated sections contain no lingering vague placeholders the new answer was meant to resolve. - No contradictory earlier statement remains (scan for now-invalid alternative choices removed). - Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`. - Terminology consistency: same canonical term used across all updated sections. 7. Write the updated spec back to `FEATURE_SPEC`. 8. Report completion (after questioning loop ends or early termination): - Number of questions asked & answered. - Path to updated spec. - Sections touched (list names). - Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota or better suited for planning), Clear (already sufficient), Outstanding (still Partial/Missing but low impact). - If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit.plan` or run `/speckit.clarify` again later post-plan. - Suggested next command. Behavior rules: - If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding. - If spec file missing, instruct user to run `/speckit.specify` first (do not create a new spec here). - Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions). - Avoid speculative tech stack questions unless the absence blocks functional clarity. - Respect user early termination signals ("stop", "done", "proceed"). - If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing. - If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale. Context for prioritization: $ARGUMENTS ``` -------------------------------------------------------------------------------- /specs/001-i-want-to/contracts/mcp-tool-contract.json: -------------------------------------------------------------------------------- ```json { "$schema": "https://json-schema.org/draft-07/schema#", "title": "Jira Get Development Information Tool Contract", "description": "MCP tool contract for retrieving development information (branches, pull requests, commits) linked to a Jira issue", "type": "object", "properties": { "tool": { "type": "object", "properties": { "name": { "type": "string", "const": "jira_get_development_information" }, "description": { "type": "string", "const": "Retrieve branches, pull requests, and commits linked to a Jira issue via development tool integrations (GitHub, GitLab, Bitbucket). Returns human-readable formatted text showing all development work associated with the issue." }, "inputSchema": { "type": "object", "properties": { "issue_key": { "type": "string", "description": "The Jira issue key (e.g., PROJ-123)", "pattern": "^[A-Z]+-[0-9]+$", "examples": ["PROJ-123", "KP-42", "TEAM-999"] }, "include_branches": { "type": "boolean", "description": "Include branches in the response (default: true)", "default": true }, "include_pull_requests": { "type": "boolean", "description": "Include pull requests in the response (default: true)", "default": true }, "include_commits": { "type": "boolean", "description": "Include commits in the response (default: true)", "default": true } }, "required": ["issue_key"], "additionalProperties": false } }, "required": ["name", "description", "inputSchema"] }, "handler": { "type": "object", "properties": { "type": { "type": "string", "const": "typed" }, "signature": { "type": "string", "const": "func(ctx context.Context, request mcp.CallToolRequest, input GetDevelopmentInfoInput) (*mcp.CallToolResult, error)" } } }, "responses": { "type": "object", "properties": { "success": { "type": "object", "properties": { "format": { "type": "string", "const": "text" }, "contentType": { "type": "string", "const": "plain/text" }, "structure": { "type": "string", "description": "Formatted text with sections for branches, pull requests, and commits, separated by === dividers" }, "example": { "type": "string", "const": "Development Information for PROJ-123:\n\n=== Branches (2) ===\n\nBranch: feature/PROJ-123-login\nRepository: company/backend-api\nLast Commit: abc1234 - \"Add login endpoint\"\nURL: https://github.com/company/backend-api/tree/feature/PROJ-123-login\n\n=== Pull Requests (1) ===\n\nPR #42: Add login functionality\nStatus: OPEN\nAuthor: John Doe ([email protected])\nRepository: company/backend-api\nURL: https://github.com/company/backend-api/pull/42\nLast Updated: 2025-10-07 14:30:00" } } }, "empty": { "type": "object", "properties": { "format": { "type": "string", "const": "text" }, "message": { "type": "string", "const": "Development Information for {issue_key}:\n\nNo branches, pull requests, or commits found.\n\nThis may mean:\n- No development work has been linked to this issue\n- The Jira-GitHub/GitLab/Bitbucket integration is not configured\n- You lack permissions to view development information" } } }, "error": { "type": "object", "properties": { "format": { "type": "string", "const": "error" }, "cases": { "type": "array", "items": [ { "type": "object", "properties": { "case": { "const": "invalid_issue_key" }, "httpStatus": { "const": 400 }, "message": { "const": "invalid issue key format: {issue_key} (expected format: PROJ-123)" } } }, { "type": "object", "properties": { "case": { "const": "issue_not_found" }, "httpStatus": { "const": 404 }, "message": { "const": "failed to retrieve development information: issue not found (endpoint: /rest/api/3/issue/{issue_key})" } } }, { "type": "object", "properties": { "case": { "const": "unauthorized" }, "httpStatus": { "const": 401 }, "message": { "const": "failed to retrieve development information: authentication failed (endpoint: /rest/dev-status/1.0/issue/detail)" } } }, { "type": "object", "properties": { "case": { "const": "api_error" }, "httpStatus": { "const": 500 }, "message": { "const": "failed to retrieve development information: {error_message} (endpoint: {endpoint})" } } } ] } } } } } }, "examples": [ { "description": "Get all development information for an issue", "request": { "issue_key": "PROJ-123" }, "response": { "type": "success", "output": "Development Information for PROJ-123:\n\n=== Branches (2) ===\n..." } }, { "description": "Get only branches and pull requests", "request": { "issue_key": "PROJ-123", "include_commits": false }, "response": { "type": "success", "output": "Development Information for PROJ-123:\n\n=== Branches (2) ===\n...\n=== Pull Requests (1) ===\n..." } }, { "description": "Get only branches", "request": { "issue_key": "PROJ-123", "include_branches": true, "include_pull_requests": false, "include_commits": false }, "response": { "type": "success", "output": "Development Information for PROJ-123:\n\n=== Branches (2) ===\n..." } }, { "description": "Issue with no development information", "request": { "issue_key": "PROJ-456" }, "response": { "type": "empty", "output": "Development Information for PROJ-456:\n\nNo branches, pull requests, or commits found..." } }, { "description": "Invalid issue key format", "request": { "issue_key": "invalid-key" }, "response": { "type": "error", "error": "invalid issue key format: invalid-key (expected format: PROJ-123)" } } ], "registration": { "location": "main.go", "function": "tools.RegisterJiraDevelopmentTool(mcpServer)", "pattern": "All Jira tools are registered in main.go via RegisterJira*Tool functions" }, "implementation": { "file": "tools/jira_development.go", "inputStruct": "GetDevelopmentInfoInput", "handler": "jiraGetDevelopmentInfoHandler", "client": "services.JiraClient() (singleton)", "formatting": "Inline string builder (no util function)" }, "dependencies": { "external": [ { "name": "go-atlassian", "version": "v1.6.1", "usage": "client.NewRequest() and client.Call() for custom API endpoint" }, { "name": "mcp-go", "version": "v0.32.0", "usage": "MCP tool registration and typed handler" } ], "internal": [ { "package": "services", "function": "JiraClient()", "usage": "Singleton Jira client instance" } ] }, "apiEndpoints": { "primary": { "path": "/rest/dev-status/1.0/issue/detail", "method": "GET", "parameters": { "issueId": "Numeric issue ID (not issue key)", "applicationType": "Optional: github, bitbucket, or stash", "dataType": "Optional: repository, pullrequest, or branch" }, "documentation": "Undocumented internal API - no official Atlassian documentation" }, "secondary": { "path": "/rest/api/3/issue/{issueKeyOrId}", "method": "GET", "usage": "Convert issue key to numeric ID before calling dev-status endpoint" } }, "testing": { "unit": { "location": "tools/jira_development_test.go", "coverage": [ "Tool registration succeeds", "Input validation enforces required fields", "Handler signature matches typed pattern" ] }, "integration": { "location": "tests/development_test.go", "prerequisites": [ "Live Jira instance with dev integration configured", "Test issue with linked branches/PRs/commits" ], "coverage": [ "Retrieve development information for valid issue", "Handle issue with no development information", "Handle invalid issue key", "Filter by include flags" ] } } } ``` -------------------------------------------------------------------------------- /.claude/commands/speckit.specify.md: -------------------------------------------------------------------------------- ```markdown --- description: Create or update the feature specification from a natural language feature description. --- ## User Input ```text $ARGUMENTS ``` You **MUST** consider the user input before proceeding (if not empty). ## Outline The text the user typed after `/speckit.specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command. Given that feature description, do this: 1. Run the script `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS"` from repo root and parse its JSON output for BRANCH_NAME and SPEC_FILE. All file paths must be absolute. **IMPORTANT** You must only ever run this script once. The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for. 2. Load `.specify/templates/spec-template.md` to understand required sections. 3. Follow this execution flow: 1. Parse user description from Input If empty: ERROR "No feature description provided" 2. Extract key concepts from description Identify: actors, actions, data, constraints 3. For unclear aspects: - Make informed guesses based on context and industry standards - Only mark with [NEEDS CLARIFICATION: specific question] if: - The choice significantly impacts feature scope or user experience - Multiple reasonable interpretations exist with different implications - No reasonable default exists - **LIMIT: Maximum 3 [NEEDS CLARIFICATION] markers total** - Prioritize clarifications by impact: scope > security/privacy > user experience > technical details 4. Fill User Scenarios & Testing section If no clear user flow: ERROR "Cannot determine user scenarios" 5. Generate Functional Requirements Each requirement must be testable Use reasonable defaults for unspecified details (document assumptions in Assumptions section) 6. Define Success Criteria Create measurable, technology-agnostic outcomes Include both quantitative metrics (time, performance, volume) and qualitative measures (user satisfaction, task completion) Each criterion must be verifiable without implementation details 7. Identify Key Entities (if data involved) 8. Return: SUCCESS (spec ready for planning) 4. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings. 5. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria: a. **Create Spec Quality Checklist**: Generate a checklist file at `FEATURE_DIR/checklists/requirements.md` using the checklist template structure with these validation items: ```markdown # Specification Quality Checklist: [FEATURE NAME] **Purpose**: Validate specification completeness and quality before proceeding to planning **Created**: [DATE] **Feature**: [Link to spec.md] ## Content Quality - [ ] No implementation details (languages, frameworks, APIs) - [ ] Focused on user value and business needs - [ ] Written for non-technical stakeholders - [ ] All mandatory sections completed ## Requirement Completeness - [ ] No [NEEDS CLARIFICATION] markers remain - [ ] Requirements are testable and unambiguous - [ ] Success criteria are measurable - [ ] Success criteria are technology-agnostic (no implementation details) - [ ] All acceptance scenarios are defined - [ ] Edge cases are identified - [ ] Scope is clearly bounded - [ ] Dependencies and assumptions identified ## Feature Readiness - [ ] All functional requirements have clear acceptance criteria - [ ] User scenarios cover primary flows - [ ] Feature meets measurable outcomes defined in Success Criteria - [ ] No implementation details leak into specification ## Notes - Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan` ``` b. **Run Validation Check**: Review the spec against each checklist item: - For each item, determine if it passes or fails - Document specific issues found (quote relevant spec sections) c. **Handle Validation Results**: - **If all items pass**: Mark checklist complete and proceed to step 6 - **If items fail (excluding [NEEDS CLARIFICATION])**: 1. List the failing items and specific issues 2. Update the spec to address each issue 3. Re-run validation until all items pass (max 3 iterations) 4. If still failing after 3 iterations, document remaining issues in checklist notes and warn user - **If [NEEDS CLARIFICATION] markers remain**: 1. Extract all [NEEDS CLARIFICATION: ...] markers from the spec 2. **LIMIT CHECK**: If more than 3 markers exist, keep only the 3 most critical (by scope/security/UX impact) and make informed guesses for the rest 3. For each clarification needed (max 3), present options to user in this format: ```markdown ## Question [N]: [Topic] **Context**: [Quote relevant spec section] **What we need to know**: [Specific question from NEEDS CLARIFICATION marker] **Suggested Answers**: | Option | Answer | Implications | |--------|--------|--------------| | A | [First suggested answer] | [What this means for the feature] | | B | [Second suggested answer] | [What this means for the feature] | | C | [Third suggested answer] | [What this means for the feature] | | Custom | Provide your own answer | [Explain how to provide custom input] | **Your choice**: _[Wait for user response]_ ``` 4. **CRITICAL - Table Formatting**: Ensure markdown tables are properly formatted: - Use consistent spacing with pipes aligned - Each cell should have spaces around content: `| Content |` not `|Content|` - Header separator must have at least 3 dashes: `|--------|` - Test that the table renders correctly in markdown preview 5. Number questions sequentially (Q1, Q2, Q3 - max 3 total) 6. Present all questions together before waiting for responses 7. Wait for user to respond with their choices for all questions (e.g., "Q1: A, Q2: Custom - [details], Q3: B") 8. Update the spec by replacing each [NEEDS CLARIFICATION] marker with the user's selected or provided answer 9. Re-run validation after all clarifications are resolved d. **Update Checklist**: After each validation iteration, update the checklist file with current pass/fail status 6. Report completion with branch name, spec file path, checklist results, and readiness for the next phase (`/speckit.clarify` or `/speckit.plan`). **NOTE:** The script creates and checks out the new branch and initializes the spec file before writing. ## General Guidelines ## Quick Guidelines - Focus on **WHAT** users need and **WHY**. - Avoid HOW to implement (no tech stack, APIs, code structure). - Written for business stakeholders, not developers. - DO NOT create any checklists that are embedded in the spec. That will be a separate command. ### Section Requirements - **Mandatory sections**: Must be completed for every feature - **Optional sections**: Include only when relevant to the feature - When a section doesn't apply, remove it entirely (don't leave as "N/A") ### For AI Generation When creating this spec from a user prompt: 1. **Make informed guesses**: Use context, industry standards, and common patterns to fill gaps 2. **Document assumptions**: Record reasonable defaults in the Assumptions section 3. **Limit clarifications**: Maximum 3 [NEEDS CLARIFICATION] markers - use only for critical decisions that: - Significantly impact feature scope or user experience - Have multiple reasonable interpretations with different implications - Lack any reasonable default 4. **Prioritize clarifications**: scope > security/privacy > user experience > technical details 5. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item 6. **Common areas needing clarification** (only if no reasonable default exists): - Feature scope and boundaries (include/exclude specific use cases) - User types and permissions (if multiple conflicting interpretations possible) - Security/compliance requirements (when legally/financially significant) **Examples of reasonable defaults** (don't ask about these): - Data retention: Industry-standard practices for the domain - Performance targets: Standard web/mobile app expectations unless specified - Error handling: User-friendly messages with appropriate fallbacks - Authentication method: Standard session-based or OAuth2 for web apps - Integration patterns: RESTful APIs unless specified otherwise ### Success Criteria Guidelines Success criteria must be: 1. **Measurable**: Include specific metrics (time, percentage, count, rate) 2. **Technology-agnostic**: No mention of frameworks, languages, databases, or tools 3. **User-focused**: Describe outcomes from user/business perspective, not system internals 4. **Verifiable**: Can be tested/validated without knowing implementation details **Good examples**: - "Users can complete checkout in under 3 minutes" - "System supports 10,000 concurrent users" - "95% of searches return results in under 1 second" - "Task completion rate improves by 40%" **Bad examples** (implementation-focused): - "API response time is under 200ms" (too technical, use "Users see results instantly") - "Database can handle 1000 TPS" (implementation detail, use user-facing metric) - "React components render efficiently" (framework-specific) - "Redis cache hit rate above 80%" (technology-specific) ```