# @specforge/mcp

MCP (Model Context Protocol) server for SpecForge - enables AI agents to interact with your projects, specifications, epics, and tickets.

## Installation

```bash
npm install -g @specforge/mcp
```

Or install locally:

```bash
npm install @specforge/mcp
```

## Getting Your API Key

1. Log in to the SpecForge webapp
2. Navigate to **Settings > API Keys**
3. Click **Create New API Key**
4. Select the permissions you need (read, write, or both)
5. Copy the key immediately - it's only shown once!

API keys have the format: `sf_live_xxxxxxxxxxxxxxxxxxxxxx`

## Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `SPECFORGE_API_KEY` | Yes | Your API key from the webapp |
| `SPECFORGE_API_URL` | Yes | The MCP API Gateway URL from your deployment |
| `SPECFORGE_DEBUG` | No | Set to `true` to enable debug logging |

## AI Client Configuration

### Claude Desktop

Add to `~/.config/claude/claude_desktop_config.json` (Linux/macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

```json
{
  "mcpServers": {
    "specforge": {
      "command": "specforge",
      "env": {
        "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
        "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
      }
    }
  }
}
```

### Claude Code (CLI)

Add to `~/.claude/settings.json`:

```json
{
  "mcpServers": {
    "specforge": {
      "command": "specforge",
      "env": {
        "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
        "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
      }
    }
  }
}
```

Or set environment variables in your shell and run:

```bash
export SPECFORGE_API_KEY="sf_live_your_api_key_here"
export SPECFORGE_API_URL="https://your-api-gateway-url.amazonaws.com/prod"
specforge
```

### Cursor

Add to your Cursor MCP configuration:

```json
{
  "mcpServers": {
    "specforge": {
      "command": "npx",
      "args": ["-y", "@specforge/mcp"],
      "env": {
        "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
        "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
      }
    }
  }
}
```

### GitHub Copilot VS Code Extension

Add to your VS Code `settings.json`:

```json
{
  "github.copilot.advanced": {
    "mcp": {
      "servers": {
        "specforge": {
          "command": "specforge",
          "env": {
            "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
            "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
          }
        }
      }
    }
  }
}
```

### GitHub Copilot CLI

Create a config file at `~/.config/gh-copilot/mcp.json`:

```json
{
  "servers": {
    "specforge": {
      "command": "specforge",
      "env": {
        "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
        "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
      }
    }
  }
}
```

### OpenAI Codex CLI

Configure using environment variables:

```bash
export SPECFORGE_API_KEY="sf_live_your_api_key_here"
export SPECFORGE_API_URL="https://your-api-gateway-url.amazonaws.com/prod"

# Then configure your Codex CLI to use the MCP server
codex --mcp-server specforge
```

### ChatGPT Desktop

Add to ChatGPT Desktop's MCP configuration:

```json
{
  "mcpServers": {
    "specforge": {
      "command": "specforge",
      "env": {
        "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
        "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
      }
    }
  }
}
```

### Windsurf

Add to Windsurf's settings:

```json
{
  "mcp": {
    "servers": {
      "specforge": {
        "command": "specforge",
        "env": {
          "SPECFORGE_API_KEY": "sf_live_your_api_key_here",
          "SPECFORGE_API_URL": "https://your-api-gateway-url.amazonaws.com/prod"
        }
      }
    }
  }
}
```

### Generic MCP Client

For any MCP-compatible client, the server uses stdio transport:

```bash
# Start the server with environment variables
SPECFORGE_API_KEY="sf_live_xxx" SPECFORGE_API_URL="https://xxx" specforge
```

The server communicates via JSON-RPC over stdin/stdout.

## Available Tools

The SpecForge MCP server provides the following tool categories:

### Core Operations
- `list_projects` - List all accessible projects
- `get_project` - Get project details
- `list_specifications` - List specifications in a project
- `get_specification` - Get specification details
- `list_epics` - List epics in a specification
- `get_epic` - Get epic details
- `list_tickets` - List tickets in an epic
- `get_ticket` - Get ticket details with implementation steps

### Context & AI Tools
- `get_implementation_context` - Get full context for implementing a ticket
- `get_next_actionable_tickets` - Get tickets ready to work on
- `get_blocked_tickets` - Get blocked tickets with reasons
- `get_critical_path` - Get the critical implementation path

### Workflow & Tracking
- `start_work_session` - Start working on a ticket
- `complete_work_session` - Mark work complete with summary
- `report_progress` - Report progress on a ticket

### Testing Tools
- `report_test_results` - Report test results for a ticket
- `get_ticket_test_status` - Get test status
- `validate_ticket_completion` - Validate completion criteria

### Discovery Tools
- `discover_work_session` - Report bugs, tech debt, or new requirements
- `get_pending_discoveries` - Get unresolved discoveries
- `resolve_discovery` - Mark a discovery as resolved

### Status & Analytics
- `get_specification_status` - Get specification progress
- `get_epic_status` - Get epic progress
- `get_implementation_summary` - Get overall project summary
- `get_blockers_report` - Get blocking dependencies

### Search Tools
- `search_tickets` - Search tickets by text
- `find_tickets_by_file` - Find tickets affecting a file
- `find_tickets_by_tag` - Find tickets with specific tags
- `find_related_tickets` - Find related tickets

### Git Integration
- `link_commit` - Link a commit to a ticket
- `link_pull_request` - Link a PR to a ticket
- `get_ticket_commits` - Get commits for a ticket
- `get_ticket_prs` - Get PRs for a ticket

### Blueprint Management
- `blueprint` - Manage specification blueprints (diagrams, mockups, ADRs)
  - Operations: `create`, `get`, `update`, `list`, `delete`, `link`, `unlink`, `get_for_ticket`
  - Categories: flowchart, architecture, state, sequence, erd, mockup, adr, component, deployment, api
  - See [Blueprint Documentation](/docs/mcp/tools/blueprint.md)

### Project Sharing
- `list_project_members` - List all members of a project
- `invite_to_project` - Invite a user by email
- `remove_project_member` - Remove a member from project
- `update_member_role` - Change a member's role (owner, editor, viewer)
- `list_invitations` - List pending invitations
- `accept_project_invitation` - Accept an invitation
- `decline_project_invitation` - Decline an invitation
- See [Project Sharing Documentation](/docs/mcp/collaboration/)

## CLI Commands

The SpecForge MCP package includes a CLI for project configuration and management.

### Quick Reference

| Command | Description |
|---------|-------------|
| `login` | Authenticate with your API key |
| `init` | Initialize SpecForge in a project |
| `configure` | Configure output preferences |
| `doctor` | Diagnose configuration issues |
| `status` | Show specification status |
| `projects` | List accessible projects |
| `specs` | List specifications |
| `switch` | Switch project/specification context |
| `tickets` | List tickets |
| `ticket <id>` | Show ticket details |
| `next` | Get next actionable ticket |
| `blocked` | List blocked tickets |
| `session` | Show session status |
| `session start` | Start implementation session |
| `session end` | End current session |
| `call <tool>` | Directly call an MCP tool |
| `tools` | List available MCP tools |
| `test` | Test API connection |
| `whoami` | Show current user/config |
| `autopilot run` | Start autonomous implementation |
| `autopilot status` | Show autopilot session status |
| `autopilot pause` | Pause active session |
| `autopilot resume` | Resume paused session |
| `autopilot abort` | Stop and cleanup session |

### Setup Commands

#### login

```bash
specforge login [--api-key <key>] [--force]
```

Authenticate with the SpecForge API.

| Option | Description |
|--------|-------------|
| `--api-key <key>` | Provide API key non-interactively (for CI/scripts) |
| `-f, --force` | Overwrite existing authentication |

Examples:
```bash
specforge login                    # Interactive login
specforge login --api-key sf_live_xxx  # Non-interactive
specforge login --force            # Re-authenticate
```

#### init

```bash
specforge init [--project <id>] [--spec <id>] [--format <format>] [--force]
```

Initialize SpecForge in the current directory.

| Option | Description |
|--------|-------------|
| `--project <id>` | Project ID (non-interactive mode) |
| `--spec <id>` | Specification ID (non-interactive mode) |
| `--format <format>` | Output format: json or toon |
| `-f, --force` | Overwrite existing configuration |

Creates:
- `.mcp.json` - Claude Code MCP server configuration
- `.specforge.json` - Project-specific settings

Examples:
```bash
specforge init                          # Interactive setup
specforge init --project proj_abc       # Set project
specforge init --project proj_abc --spec spec_xyz --format toon
```

#### configure

```bash
specforge configure [--format <format>] [--project <id>]
```

Configure default preferences.

#### doctor

```bash
specforge doctor [--json]
```

Diagnose configuration and connection issues.

| Option | Description |
|--------|-------------|
| `--json` | Output as JSON for scripting |

Check categories:
- Configuration - Config files presence
- Authentication - API key format and validity
- Connection - API connectivity and response time
- Project Access - Access to configured project/specification

### Navigation Commands

#### switch

```bash
specforge switch [--project <id>] [--spec <id>]
```

Switch between projects or specifications.

#### projects

```bash
specforge projects [--json] [--toon]
```

List all accessible projects.

#### specs

```bash
specforge specs [--project <id>] [--status <status>] [--json]
```

List specifications for the current or specified project.

### Query Commands

#### status

```bash
specforge status [--spec <id>] [--json]
```

Show current specification status with progress metrics.

#### tickets

```bash
specforge tickets [--epic <id>] [--status <status>] [--limit <n>] [--json]
```

List tickets for the current specification.

#### ticket

```bash
specforge ticket <id> [--json] [--context]
```

Show full details for a specific ticket.

| Option | Description |
|--------|-------------|
| `--json` | Output as JSON |
| `--context` | Include implementation context |

#### next

```bash
specforge next [--spec <id>] [--count <n>] [--json]
```

Get the next actionable tickets (dependencies satisfied).

#### blocked

```bash
specforge blocked [--spec <id>] [--json]
```

List blocked tickets with blocking reasons.

### Session Commands

#### session

```bash
specforge session [--json]
```

Show current implementation session status.

#### session start

```bash
specforge session start [specId] [--mode <mode>] [--max-tickets <n>] [--stop-on-failure] [--force]
```

Start a new implementation session.

| Option | Description |
|--------|-------------|
| `[specId]` | Target specification (uses current if omitted) |
| `--mode <mode>` | Session mode: single, autonomous, guided |
| `--max-tickets <n>` | Maximum tickets to process |
| `--stop-on-failure` | Stop on first failure |
| `--force` | End existing session and start new |

#### session end

```bash
specforge session end [--status <status>] [--summary <text>]
```

End the current implementation session.

| Option | Description |
|--------|-------------|
| `--status <status>` | End status: completed or aborted |
| `--summary <text>` | Custom session summary |

### Debug Commands

#### call

```bash
specforge call <tool> [--args <json>] [--format <format>] [--raw]
```

Directly call an MCP tool with JSON arguments.

Examples:
```bash
specforge call list_projects
specforge call get_ticket --args='{"ticketId":"abc123"}'
specforge call list_tickets --format toon
```

#### tools

```bash
specforge tools [--category <category>] [--search <query>] [--json]
```

List available MCP tools with optional filtering.

#### test

```bash
specforge test
```

Test API connection and authentication. Shows response time and user info.

#### whoami

```bash
specforge whoami [--json]
```

Show current user information and configuration settings.

### Autopilot Commands

Autopilot enables autonomous ticket implementation using Claude Code. See [full documentation](/docs/mcp/autopilot/).

#### autopilot run

```bash
specforge autopilot run [options]
```

Start autonomous ticket implementation.

| Option | Description |
|--------|-------------|
| `-s, --spec <id>` | Specification ID |
| `-e, --epic <id>` | Only implement tickets from this epic |
| `-p, --parallel <n>` | Number of parallel workers (1-10) |
| `-c, --max-cost <usd>` | Maximum cost in USD |
| `-n, --dry-run` | Show plan without executing |
| `-w, --watch` | Watch mode with live dashboard |
| `-r, --resume <id>` | Resume a previous run |

Examples:
```bash
specforge autopilot run --dry-run      # Preview
specforge autopilot run --parallel 2   # Run with 2 workers
specforge autopilot run --max-cost 10  # Limit to $10
specforge autopilot run --watch        # Live dashboard
```

#### autopilot status

```bash
specforge autopilot status [options]
```

Show current autopilot session status.

| Option | Description |
|--------|-------------|
| `-w, --watch` | Live updates (2s refresh) |
| `-v, --verbose` | Show detailed dashboard |
| `--json` | Output as JSON |

#### autopilot pause / resume / abort

```bash
specforge autopilot pause              # Pause gracefully
specforge autopilot resume             # Resume latest session
specforge autopilot abort --force      # Stop and cleanup
```

### Configuration Files

| File | Location | Purpose |
|------|----------|---------|
| Global config | `~/.specforge/config.json` | API key, default format |
| Project config | `.specforge.json` | Project/spec IDs, format override |
| MCP config | `.mcp.json` | Claude Code integration |

Configuration priority (highest to lowest):
1. Environment variables
2. Project config (`.specforge.json`)
3. Global config (`~/.specforge/config.json`)
4. Default values

### Environment Variables

| Variable | Description |
|----------|-------------|
| `SPECFORGE_API_KEY` | API key (overrides config) |
| `SPECFORGE_API_URL` | API endpoint URL |
| `SPECFORGE_FORMAT` | Output format (json/toon) |
| `SPECFORGE_DEBUG` | Enable debug mode (true/false) |

### Exit Codes

| Code | Name | Description |
|------|------|-------------|
| 0 | SUCCESS | Successful execution |
| 1 | ERROR | General error |
| 2 | AUTH_ERROR | Authentication failed |
| 3 | CONFIG_ERROR | Configuration error |
| 4 | NETWORK_ERROR | Network/API error |
| 5 | NOT_FOUND | Resource not found |
| 6 | VALIDATION_ERROR | Input validation error |

### Automation & CI/CD

Non-interactive usage for scripts:

```bash
# Authenticate via environment or flag
export SPECFORGE_API_KEY="sf_live_xxx"
specforge login --api-key $SPECFORGE_API_KEY

# Initialize non-interactively
specforge init --project $PROJECT_ID --spec $SPEC_ID --format json --force

# Check health (exits 1 on failure)
specforge doctor --json

# Get tickets as JSON for processing
specforge tickets --json | jq '.[]'

# Get next actionable ticket ID
specforge next --json | jq -r '.tickets[0].id'
```

### Global Options

These options work with any command:

| Option | Description |
|--------|-------------|
| `--debug` | Enable debug output |
| `--no-color` | Disable colored output |
| `--json` | Output in JSON format |
| `-v, --version` | Show version |
| `-h, --help` | Show command help |

## Troubleshooting

### "SPECFORGE_API_KEY environment variable is required"

Make sure you've set the `SPECFORGE_API_KEY` environment variable with your API key from the SpecForge webapp.

```bash
# Check if it's set
echo $SPECFORGE_API_KEY

# Set it
export SPECFORGE_API_KEY="sf_live_your_key_here"
```

### "Invalid API key format"

API keys must start with `sf_live_`. If your key doesn't match this format, regenerate it in the webapp.

### "SPECFORGE_API_URL environment variable is required"

You need to provide the API Gateway URL from your SpecForge deployment. This is output when you deploy the backend.

### Connection Timeouts

If you're experiencing connection issues:

1. Verify your API URL is correct
2. Check your network connection
3. Enable debug mode to see detailed logs:

```bash
export SPECFORGE_DEBUG=true
specforge
```

### Debug Mode

Enable debug logging to troubleshoot issues:

```bash
export SPECFORGE_DEBUG=true
```

This will output detailed logs to stderr, including:
- Configuration loaded
- Tool calls received
- API requests made
- Response data

### Server Not Starting

1. Ensure Node.js 18+ is installed
2. Check that the package is installed globally: `npm list -g @specforge/mcp`
3. Try reinstalling: `npm install -g @specforge/mcp`

### Permission Denied

If you get "permission denied" when running `specforge`:

```bash
# On macOS/Linux
chmod +x $(which specforge)

# Or run with node directly
node $(npm root -g)/@specforge/mcp/dist/index.js
```

## Development

To contribute to the MCP server:

```bash
# Clone the repo
git clone https://github.com/your-org/specforge.git
cd specforge/mcp

# Install dependencies
npm install

# Build
npm run build

# Link for local testing
npm link

# Run in development mode
npm run dev
```

## License

MIT
