# Directory Structure
```
├── .gitignore
├── AGENTS.md
├── CLAUDE.md
├── package.json
├── pnpm-lock.yaml
├── README.md
├── src
│ ├── index.ts
│ ├── server.ts
│ ├── tools
│ │ ├── design_confirmed.ts
│ │ ├── design.ts
│ │ ├── execute.ts
│ │ ├── goal.ts
│ │ ├── requirements_confirmed.ts
│ │ ├── requirements.ts
│ │ ├── tasks_confirmed.ts
│ │ ├── tasks.ts
│ │ └── workflow.ts
│ └── utils
│ ├── template.ts
│ └── workflow.ts
├── templates
│ ├── ask-goal.md
│ ├── execute-task.md
│ ├── gen-design.md
│ ├── gen-requirement.md
│ └── gen-tasks.md
└── tsconfig.json
```
# Files
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Build outputs
dist/
build/
*.tsbuildinfo
# TypeScript cache
*.tsbuildinfo
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# MacOS
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Windows
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# Linux
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# IDE and Editor files
.vscode/
.idea/
*.swp
*.swo
*~
# Cursor AI IDE
.cursor/
# History files (often created by various tools)
.history/
# Claude files
.claude/
# Smithery files
.smithery/
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# MCP Server specific
# Add any MCP-specific files that shouldn't be tracked
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
# Spec-driven Development MCP Server
[](https://smithery.ai/server/@kevinlin/spec-coding-mcp)
An MCP server that brings AI-guided spec-driven development workflow to any AI-powered IDEs beyonnd Kiro. Transform your development process with structured, step-by-step guidance from idea to implementation.
## What is Spec-driven Development?
Spec-driven development is a methodology that emphasizes creating detailed specifications before writing code. This approach helps ensure clear requirements, better design decisions, and more maintainable code. Our MCP server guides you through this process with AI assistance.
## Features
- **Complete Development Workflow**: From goal collection to task execution
- **AI-Powered Guidance**: Step-by-step instructions for each development phase
- **Structured Documentation**: Generates organized specs in EARS format
- **Template-Based**: Uses proven templates for requirements, design, and tasks
## Installation
### Installing via Smithery
To install spec-coding-mcp for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@kevinlin/spec-coding-mcp):
```bash
npx -y @smithery/cli install @kevinlin/spec-coding-mcp --client claude
```
### Using npx (Recommended)
```bash
# Always get the latest version
npx spec-coding-mcp@latest
# Or simply (will also get latest)
npx spec-coding-mcp
```
### Using npm
```bash
npm install -g spec-coding-mcp
spec-coding-mcp
```
## Usage
### With Cursor
Add to your Cursor MCP settings:
```json
{
"mcpServers": {
"spec-coding-mcp": {
"command": "npx",
"args": ["spec-coding-mcp@latest"],
"env": {},
"disabled": false
}
}
}
```
### Available Tools
1. **spec_coding_workflow_start** - Start the development workflow
2. **spec_coding_goal_confirmed** - Confirm feature goals
3. **spec_coding_requirements_start** - Begin requirements gathering
4. **spec_coding_requirements_confirmed** - Confirm requirements completion
5. **spec_coding_design_start** - Start design documentation
6. **spec_coding_design_confirmed** - Confirm design completion
7. **spec_coding_tasks_start** - Begin task planning
8. **spec_coding_tasks_confirmed** - Confirm task planning completion
9. **spec_coding_execute_start** - Start task execution
## Workflow Stages & Example
The spec-driven development process follows five distinct stages. Here's how it works with a real example - building a user authentication feature:
### 1. Goal Collection - Define What You Want to Build
**Purpose**: Establish clear, specific objectives for your feature.
**Example Interaction**:
```
User: I want to build a user authentication feature
Assistant: Let me start the spec-driven development workflow for you.
[calls spec_coding_workflow_start]
Let's define your feature goals:
1. What specific authentication methods do you want to support?
2. Do you need social login (Google, GitHub, etc.)?
3. What user roles and permissions are required?
User: I need email/password login with JWT tokens, plus Google OAuth, and basic user/admin roles.
Assistant: Perfect! Let me confirm:
- Feature: User authentication system
- Methods: Email/password + Google OAuth
- Tokens: JWT-based
- Roles: User and Admin
- Feature name: "user-authentication"
Is this correct?
User: Yes, that's exactly what I need.
[calls spec_coding_goal_confirmed with feature_name="user-authentication"]
```
### 2. Requirements Gathering - Create Detailed EARS-format Requirements
**Purpose**: Transform your goals into specific, testable requirements using the EARS (Easy Approach to Requirements Syntax) format.
**Example Interaction**:
```
Assistant: Great! Now let's gather detailed requirements.
[calls spec_coding_requirements_start]
[Assistant generates detailed EARS-format requirements in docs/specs/user-authentication/requirements.md]
- WHEN a user provides valid email/password THEN the system SHALL authenticate them
- GIVEN a user wants Google OAuth WHEN they click "Sign in with Google" THEN the system SHALL redirect to Google
- WHERE user roles are needed IF user is admin THEN they SHALL access admin features
User: The requirements look comprehensive. Approved!
[calls spec_coding_requirements_confirmed]
```
### 3. Design Documentation - Technical Architecture and Design
**Purpose**: Create detailed technical specifications including architecture, component design, data models, and API specifications.
**Example Interaction**:
```
Assistant: Now let's create the technical design.
[calls spec_coding_design_start]
[Assistant creates detailed design document including:]
- Database schema for users, sessions, oauth_tokens
- Authentication middleware architecture
- JWT token structure and validation flow
- Google OAuth integration endpoints
- Role-based access control implementation
User: Design looks good, proceed!
[calls spec_coding_design_confirmed]
```
### 4. Task Planning - Break Down into Executable Tasks
**Purpose**: Decompose the feature into specific, prioritized development tasks with clear dependencies.
**Example Interaction**:
```
Assistant: Let's break this down into executable tasks.
[calls spec_coding_tasks_start]
[Assistant creates numbered task list:]
1. Set up database models (User, Session, OAuthToken)
2. Implement JWT token service
3. Create email/password authentication endpoints
4. Integrate Google OAuth flow
5. Build role-based middleware
6. Add frontend login/register forms
7. Write integration tests
User: Task breakdown is perfect!
[calls spec_coding_tasks_confirmed]
```
### 5. Task Execution - Implement the Code
**Purpose**: Execute the planned tasks systematically, implementing the feature according to specifications.
**Example Interaction**:
```
Assistant: Time to implement! Let's start coding.
[calls spec_coding_execute_start]
[Assistant implements each task step by step:]
- Creates User model with email, password_hash, role fields
- Builds JWT service with sign/verify methods
- Implements /auth/login and /auth/register endpoints
- Integrates Google OAuth with Passport.js
- Creates role-checking middleware
- Builds React login/register components
- Writes comprehensive test suite
```
## Generated Project Structure
Throughout the workflow, the following documentation structure is created:
```
docs/specs/{feature_name}/
├── requirements.md # EARS-format requirements
├── design.md # Technical architecture
└── tasks.md # Implementation checklist
```
## Development
### Prerequisites
Make sure you have Node.js 18+ installed.
### Setup
```bash
# Install dependencies with pnpm (recommended)
pnpm install
# Or with npm
npm install
```
### Running the Project
```bash
# Development mode with pnpm
pnpm dev
# Or with npm
npm run dev
# Build with pnpm
pnpm build
# Or with npm
npm run build
# Start built version with pnpm
pnpm start
# Or with npm
npm start
# Test with pnpm (when available)
pnpm test
# Or with npm
npm test
```
### Publishing
To publish the package to npm:
```bash
# Build the project
pnpm build
# Publish to npm (will automatically run prepublishOnly script)
npm publish
```
## Contributing & License
### Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
### License
MIT
### Attribution
This project was inspired by and builds upon concepts from [vibedevtools](https://github.com/yinwm/vibedevtools) by [@yinwm](https://github.com/yinwm), a collection of development efficiency tools.
```
--------------------------------------------------------------------------------
/AGENTS.md:
--------------------------------------------------------------------------------
```markdown
# Agent Development Guidelines
## Build & Test Commands
- **Build**: `npm run build` - Compiles TypeScript to dist/
- **Dev**: `npm run dev` - Runs with tsx for development
- **Start**: `npm run start` - Runs compiled version from dist/
- **Test**: `npx vitest` - Runs tests (vitest configured but no test scripts in package.json)
## Code Style & Conventions
- **Language**: TypeScript with ES2022 target, ESNext modules
- **Imports**: Use `.js` extensions for local imports (ES modules)
- **Naming**: camelCase for functions/variables, snake_case for tool names
- **Functions**: Export async functions, use descriptive names
- **Types**: Use strict TypeScript, explicit types in function signatures
- **Error Handling**: Use try/catch with descriptive error messages
- **Logging**: Use `console.error()` with `[MCP]` prefix for debugging
- **File Structure**: src/ for source, tools/ for MCP tools, utils/ for helpers
- **Templates**: Store in templates/ directory, use template variables with `{variable}`
- **Imports Style**: Group external imports first, then local imports with relative paths
## Architecture
- **MCP Server**: Uses @modelcontextprotocol/sdk for tool definitions and handlers
- **Tool Pattern**: Each tool in separate file with async function export
- **Session Management**: Use nanoid for session IDs (12 char alphanumeric)
- **Template System**: Read from templates/ with variable substitution
```
--------------------------------------------------------------------------------
/CLAUDE.md:
--------------------------------------------------------------------------------
```markdown
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Development Commands
```bash
# Development mode
npm run dev
# Build the project
npm run build
# Start built version
npm start
# Install dependencies (Node.js 18+ required)
npm install
```
## Project Architecture
This is an MCP (Model Context Protocol) server that implements a spec-driven development workflow. The architecture follows a tool-based approach where each workflow stage is implemented as a separate MCP tool.
### Core Components
- **Entry Point** (`src/index.ts`): Starts the MCP server with stdio transport
- **Server** (`src/server.ts`): Defines all 9 workflow tools and handles tool execution
- **Workflow Tools** (`src/tools/`): Each file implements a specific workflow stage
- **Utilities** (`src/utils/`): Shared workflow logic and templates
### Workflow Architecture
The spec-driven development workflow consists of 5 sequential stages, each with specific tools:
1. **Goal Confirmation**: `spec_coding_workflow_start` → `spec_coding_goal_confirmed`
2. **Requirements Gathering**: `spec_coding_requirements_start` → `spec_coding_requirements_confirmed`
3. **Design Documentation**: `spec_coding_design_start` → `spec_coding_design_confirmed`
4. **Task Planning**: `spec_coding_tasks_start` → `spec_coding_tasks_confirmed`
5. **Task Execution**: `spec_coding_execute_start`
Each stage generates documentation in `docs/specs/{feature_name}/` directory:
- `requirements.md` (EARS format)
- `design.md` (technical architecture)
- `tasks.md` (implementation checklist)
### Tool Implementation Pattern
All workflow tools follow a consistent pattern:
- Accept `session_id` and `feature_name` parameters
- Return structured text responses with guidance
- Use templates from `src/utils/template.ts`
- Track workflow state through step progression
### TypeScript Configuration
- ES2022 target with ESNext modules
- Strict mode enabled with comprehensive type checking
- Output to `dist/` directory
- Source maps and declarations generated
### Code Style Guidelines
From `.cursor/rules/typescript.mdc`:
- Prefer interfaces over types for object definitions
- Use PascalCase for types, camelCase for variables
- Explicit return types for public functions
- Avoid JSDoc documentation
- Use async/await over Promises
- Implement proper error handling with custom error types
```
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
```
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
```typescript
#!/usr/bin/env node
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { createServer } from './server.js';
async function main() {
console.error('[MCP] Starting spec-coding-mcp server...');
const server = createServer();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('[MCP] spec-coding-mcp server started successfully');
}
main().catch((error) => {
console.error('[MCP] Fatal error:', error);
process.exit(1);
});
```
--------------------------------------------------------------------------------
/src/utils/template.ts:
--------------------------------------------------------------------------------
```typescript
import { readFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
export async function readTemplate(
templateName: string,
variables: Record<string, string> = {}
): Promise<string> {
// From src/utils go up two levels to the project root, then enter templates
const templatePath = join(__dirname, '../../templates', templateName);
console.error(`[MCP] Reading template: ${templatePath}`);
let content = await readFile(templatePath, 'utf-8');
// Replace variables
Object.entries(variables).forEach(([key, value]) => {
const regex = new RegExp(`\{${key}\}`, 'g');
content = content.replace(regex, value);
});
return content;
}
```
--------------------------------------------------------------------------------
/src/tools/design_confirmed.ts:
--------------------------------------------------------------------------------
```typescript
export interface DesignConfirmedParams {
session_id: string;
feature_name: string;
}
export async function designConfirmed(
params: DesignConfirmedParams
): Promise<string> {
const { session_id, feature_name } = params;
console.error(`[MCP] Design confirmed for feature: ${feature_name}`);
return `# ✅ Design Document Completed
## Generated Design Document:
📄 "docs/specs/${feature_name}/design.md"
The design document contains the complete technical architecture, component design, and implementation plan.
---
## Next Stage: Task Planning (4/5)
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. Requirements Gathering ✅
- [x] 3. **Design Document** ✅
- [ ] 4. **Task Planning** ← Next Stage
- [ ] 5. Task Execution
Now please call \`spec_coding_tasks_start\` to begin the task planning stage.
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\`
- Requirements: ✅ Completed
- Design: ✅ Completed`;
}
```
--------------------------------------------------------------------------------
/src/tools/goal.ts:
--------------------------------------------------------------------------------
```typescript
export interface GoalConfirmedParams {
session_id: string;
feature_name: string;
goal_summary: string;
}
export async function goalConfirmed(params: GoalConfirmedParams): Promise<string> {
const { session_id, feature_name, goal_summary } = params;
console.error(`[MCP] Goal confirmed for session ${session_id} with feature: ${feature_name}`);
return `# ✅ Feature Goal Confirmed
## Confirmed Feature Goal:
- **Feature Name**: \`${feature_name}\`
- **Feature Description**: ${goal_summary}
- **Project Directory**: \`docs/specs/${feature_name}/\`
---
## Next Stage: Requirements Gathering (2/5)
### Workflow Progress:
- [x] 1. **Goal Collection** ✅
- [ ] 2. **Requirements Gathering** ← Next Stage
- [ ] 3. Design Documentation
- [ ] 4. Task Planning
- [ ] 5. Task Execution
Now please call \`spec_coding_requirements_start\` to begin detailed requirements gathering.
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\``;
}
```
--------------------------------------------------------------------------------
/src/tools/requirements_confirmed.ts:
--------------------------------------------------------------------------------
```typescript
export interface RequirementsConfirmedParams {
session_id: string;
feature_name: string;
}
export async function requirementsConfirmed(
params: RequirementsConfirmedParams
): Promise<string> {
const { session_id, feature_name } = params;
console.error(`[MCP] Requirements confirmed for feature: ${feature_name}`);
return `# ✅ Requirements Gathering Completed
## Generated Requirements Document:
📄 "docs/specs/${feature_name}/requirements.md"
The requirements document contains complete user stories and EARS-format acceptance criteria.
---
## Next Stage: Design Document (3/5)
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. **Requirements Gathering** ✅
- [ ] 3. **Design Document** ← Next Stage
- [ ] 4. Task Planning
- [ ] 5. Task Execution
Now please call \`spec_coding_design_start\` to begin the technical design stage.
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\`
- Requirements: ✅ Completed`;
}
```
--------------------------------------------------------------------------------
/src/tools/tasks_confirmed.ts:
--------------------------------------------------------------------------------
```typescript
export interface TasksConfirmedParams {
session_id: string;
feature_name: string;
}
export async function tasksConfirmed(
params: TasksConfirmedParams
): Promise<string> {
const { session_id, feature_name } = params;
console.error(`[MCP] Tasks confirmed for feature: ${feature_name}`);
return `# ✅ Task Planning Completed
## Generated Tasks Document:
📄 "docs/specs/${feature_name}/tasks.md"
The tasks document contains a detailed list of development tasks, each with clear descriptions, acceptance criteria, and execution order.
---
## Next Stage: Task Execution (5/5)
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. Requirements Gathering ✅
- [x] 3. Design Document ✅
- [x] 4. **Task Planning** ✅
- [ ] 5. **Task Execution** ← Final Stage
Now please call \`spec_coding_execute_start\` to begin the task execution stage.
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\`
- Requirements: ✅ Completed
- Design: ✅ Completed
- Tasks: ✅ Completed`;
}
```
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
```json
{
"name": "spec-coding-mcp",
"version": "1.0.1",
"description": "MCP server for AI-powered IDE to follow spec-driven development",
"main": "dist/index.js",
"type": "module",
"bin": {
"spec-coding-mcp": "dist/index.js"
},
"scripts": {
"build": "tsc",
"dev": "tsx src/index.ts",
"start": "node dist/index.js",
"prepublishOnly": "npm run build"
},
"keywords": [
"mcp",
"spec-driven",
"workflow",
"ai",
"development",
"requirements",
"design",
"tasks"
],
"author": "kevinlin",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/kevinlin/spec-coding-mcp.git"
},
"homepage": "https://github.com/kevinlin/spec-coding-mcp#readme",
"bugs": {
"url": "https://github.com/kevinlin/spec-coding-mcp/issues"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.17.0",
"nanoid": "^5.1.5"
},
"devDependencies": {
"@types/node": "^22.13.10",
"tsx": "^4.20.3",
"typescript": "^5.8.3",
"vitest": "^3.2.4"
},
"engines": {
"node": ">=18.0.0"
}
}
```
--------------------------------------------------------------------------------
/src/tools/design.ts:
--------------------------------------------------------------------------------
```typescript
import { readTemplate } from '../utils/template.js';
export interface DesignStartParams {
session_id: string;
feature_name: string;
}
export async function designStart(
params: DesignStartParams
): Promise<string> {
const { session_id, feature_name } = params;
console.error(`[MCP] Starting design phase for feature: ${feature_name}`);
// Use gen-design.md template
const template = await readTemplate('gen-design.md', {
feature_name,
session_id
});
return `# 📝 Design Documentation Stage (3/5)
## Feature: ${feature_name}
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. Requirements Gathering ✅
- [x] 3. **Design Documentation** ← Current Stage
- [ ] 4. Task Planning
- [ ] 5. Task Execution
---
${template}
---
**Important**:
- Please create design document according to the above guidelines
- **Only when you explicitly confirm the design is complete can you call** \`spec_coding_design_confirmed\` tool
- **Never** call the next stage tool before the user **explicitly confirms the design**
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\`
- Requirements: \`docs/specs/${feature_name}/requirements.md\``;
}
```
--------------------------------------------------------------------------------
/src/tools/requirements.ts:
--------------------------------------------------------------------------------
```typescript
import { readTemplate } from '../utils/template.js';
export interface RequirementsStartParams {
session_id: string;
feature_name: string;
}
export async function requirementsStart(
params: RequirementsStartParams
): Promise<string> {
const { session_id, feature_name } = params;
console.error(`[MCP] Starting requirements collection for feature: ${feature_name}`);
// Use gen-requirement.md template
const template = await readTemplate('gen-requirement.md', {
feature_name,
session_id
});
return `# 📋 Requirements Gathering Stage (2/5)
## Feature: ${feature_name}
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. **Requirements Gathering** ← Current Stage
- [ ] 3. Design Documentation
- [ ] 4. Task Planning
- [ ] 5. Task Execution
---
${template}
---
**Important**:
- Please generate requirements document according to the above guidelines
- **Only when you explicitly confirm the requirements are complete can you call** \`spec_coding_requirements_confirmed\` tool
- **Never** call the next stage tool before the user **explicitly confirms the requirements**
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\``;
}
```
--------------------------------------------------------------------------------
/src/tools/execute.ts:
--------------------------------------------------------------------------------
```typescript
import { readTemplate } from '../utils/template.js';
export interface ExecuteStartParams {
session_id: string;
feature_name: string;
task_id?: string;
}
export async function executeStart(
params: ExecuteStartParams
): Promise<string> {
const { session_id, feature_name, task_id = 'next_uncompleted' } = params;
console.error(`[MCP] Starting execution for feature: ${feature_name}, task: ${task_id}`);
// 使用 execute-task.md 模板
const template = await readTemplate('execute-task.md', {
feature_name,
session_id,
task_id
});
return `# ⚙️ Task Execution Stage (5/5)
## Feature: ${feature_name}
Congratulations! Now entering the final execution stage. Based on the completed requirements, design, and task planning, let's start executing development tasks one by one.
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. Requirements Gathering ✅
- [x] 3. Design Documentation ✅
- [x] 4. Task Planning ✅
- [x] 5. **Task Execution** ← Current Stage
---
${template}
---
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\`
- Current Task: \`${task_id}\`
- All Documents: ✅ Completed
Now please start executing the development tasks!`;
}
```
--------------------------------------------------------------------------------
/templates/ask-goal.md:
--------------------------------------------------------------------------------
```markdown
### 0. Goal Confirmation
First, establish a clear understanding of the development goal through iterative dialogue with the user. This is the foundation for all subsequent work.
Don't proceed to any other workflow stage until the goal is completely clear and confirmed by the user.
**Constraints:**
- The model MUST engage in thorough dialogue with the user to understand their development goals
- The model MUST ask clarifying questions about:
- What problem the feature solves
- Who will use the feature
- What the expected outcome should be
- Any technical constraints or requirements
- The model MUST NOT proceed to the next stage until the user explicitly confirms the goal
- The model MUST summarize the understood goal and wait for user confirmation
- The model MUST generate a suitable feature_name based on the confirmed goal (e.g., 'user-authentication', 'payment-integration')
- The model SHOULD ask targeted questions to clarify ambiguous aspects
- The model SHOULD suggest refinements if the goal seems too broad or unclear
- The model MUST use the exact phrase "Goal confirmation complete" when ready to proceed
- The model MUST NOT call any other tools until the user has explicitly approved the goal summary
```
--------------------------------------------------------------------------------
/src/tools/tasks.ts:
--------------------------------------------------------------------------------
```typescript
import { readTemplate } from '../utils/template.js';
export interface TasksStartParams {
session_id: string;
feature_name: string;
}
export async function tasksStart(
params: TasksStartParams
): Promise<string> {
const { session_id, feature_name } = params;
console.error(`[MCP] Starting tasks planning for feature: ${feature_name}`);
// Use gen-tasks.md template
const template = await readTemplate('gen-tasks.md', {
feature_name,
session_id
});
return `# 📋 Task Planning Stage (4/5)
## Feature: ${feature_name}
### Workflow Progress:
- [x] 1. Goal Collection ✅
- [x] 2. Requirements Gathering ✅
- [x] 3. Design Documentation ✅
- [x] 4. **Task Planning** ← Current Stage
- [ ] 5. Task Execution
---
${template}
---
**Important**:
- Please create task list according to the above guidelines
- **Only when you explicitly confirm the task planning is complete can you call** \`spec_coding_tasks_confirmed\` tool
- **Never** call the next stage tool before the user **explicitly confirms the tasks**
**Session Information**:
- Session ID: \`${session_id}\`
- Feature Name: \`${feature_name}\`
- Requirements: \`docs/specs/${feature_name}/requirements.md\`
- Design: \`docs/specs/${feature_name}/design.md\``;
}
```
--------------------------------------------------------------------------------
/src/tools/workflow.ts:
--------------------------------------------------------------------------------
```typescript
import { customAlphabet } from 'nanoid';
import { readTemplate } from '../utils/template.js';
const generateSessionId = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 12);
export async function workflowStart(): Promise<string> {
const session_id = generateSessionId();
console.error(`[MCP] Starting workflow with session_id: ${session_id}`);
// Use ask-goal.md template
const template = await readTemplate('ask-goal.md', {
session_id
});
return `# 🚀 Spec-driven Development Workflow Started
## Current Stage: Goal Collection (1/5)
Welcome to the Spec-driven development workflow! I'll help you complete the entire development process from requirements to code.
### Workflow Overview:
- [ ] 1. **Goal Collection** ← Current Stage
- [ ] 2. Requirements Gathering
- [ ] 3. Design Documentation
- [ ] 4. Task Planning
- [ ] 5. Task Execution
---
${template}
---
**Session Information**:
- Session ID: \`${session_id}\`
**Important**:
- Please discuss the feature goals with me thoroughly until the goals are completely clear
- **Only when you explicitly confirm the goals can you call** \`spec_coding_goal_confirmed\` tool
- **Never** call the next stage tool before the user **explicitly confirms the goals**`;
}
```
--------------------------------------------------------------------------------
/templates/execute-task.md:
--------------------------------------------------------------------------------
```markdown
First you will
requirements: 'docs/specs/{feature_name}/requirements.md'
design: 'docs/specs/{feature_name}/design.md'
tasks: 'docs/specs/{feature_name}/tasks.md'
Find first unimplemented task in the task list in the docs/specs/{feature_name}/tasks.md file.
Follow these instructions for user requests related to spec tasks. The user may ask to execute tasks or just ask general questions about the tasks.
## Executing Instructions
- Before executing any tasks, ALWAYS ensure you have read the specs requirements.md, design.md and tasks.md files. Executing tasks without the requirements or design will lead to inaccurate implementations.
- Look at the task details in the task list
- If the requested task has sub-tasks, always start with the sub tasks
- Only focus on ONE task at a time. Do not implement functionality for other tasks.
- Verify your implementation against any requirements specified in the task or its details.
- Once you complete the requested task, stop and let the user review. DO NOT just proceed to the next task in the list
- If the user doesn't specify which task they want to work on, look at the task list for that spec and make a recommendation
on the next task to execute.
Remember, it is VERY IMPORTANT that you only execute one task at a time. Once you finish a task, stop. Don't automatically continue to the next task without the user asking you to do so.
## Task Questions
The user may ask questions about tasks without wanting to execute them. Don't always start executing tasks in cases like this.
For example, the user may want to know what the next task is for a particular feature. In this case, just provide the information and don't start any tasks.
When you are done with a task, modify the docs/specs/{feature_name}/tasks.md file to mark the task as implemented.
```
--------------------------------------------------------------------------------
/templates/gen-requirement.md:
--------------------------------------------------------------------------------
```markdown
### 1. Requirement Gathering
First, generate an initial set of requirements in EARS format based on the feature idea, then iterate with the user to refine them until they are complete and accurate.
Don't focus on code exploration in this phase. Instead, just focus on writing requirements which will later be turned into
a design.
**Constraints:**
- The model MUST create a 'docs/specs/{feature_name}/requirements.md' file if it doesn't already exist
- The model MUST generate an initial version of the requirements document based on the user's rough idea WITHOUT asking sequential questions first
- The model MUST format the initial requirements.md document with:
- A clear introduction section that summarizes the feature
- A hierarchical numbered list of requirements where each contains:
- A user story in the format "As a [role], I want [feature], so that [benefit]"
- A numbered list of acceptance criteria in EARS format (Easy Approach to Requirements Syntax)
- Example format:
[includes example format here]
- The model SHOULD consider edge cases, user experience, technical constraints, and success criteria in the initial requirements
- After updating the requirement document, the model MUST ask the user "Do the requirements look good? If so, we can move on to the design." using the 'userInput' tool.
- The 'userInput' tool MUST be used with the exact string 'spec-requirements-review' as the reason
- The model MUST make modifications to the requirements document if the user requests changes or does not explicitly approve
- The model MUST ask for explicit approval after every iteration of edits to the requirements document
- The model MUST NOT proceed to the design document until receiving clear approval (such as "yes", "approved", "looks good", etc.)
- The model MUST continue the feedback-revision cycle until explicit approval is received
- The model SHOULD suggest specific areas where the requirements might need clarification or expansion
- The model MAY ask targeted questions about specific aspects of the requirements that need clarification
- The model MAY suggest options when the user is unsure about a particular aspect
- The model MUST proceed to the design phase after the user accepts the requirements
```
--------------------------------------------------------------------------------
/src/utils/workflow.ts:
--------------------------------------------------------------------------------
```typescript
// Workflow step definitions
export interface WorkflowStep {
step_number: number;
name: string;
description: string;
tool: string;
deliverable: string;
}
export interface WorkflowOverview {
total_steps: number;
current_step: string; // Change to step name
current_step_number: number; // Keep number for progress display
steps: WorkflowStep[];
}
// Step name constants
export const STEP_NAMES = {
GOAL_CONFIRMATION: 'Goal Confirmation',
REQUIREMENTS: 'Requirements Gathering',
DESIGN: 'Design Documentation',
TASKS: 'Task Planning',
EXECUTION: 'Task Execution'
} as const;
// Workflow step constants
export const WORKFLOW_STEPS: WorkflowStep[] = [
{
step_number: 1,
name: STEP_NAMES.GOAL_CONFIRMATION,
description: 'Clarify the feature development goal through conversation',
tool: 'spec_coding_workflow_start → spec_coding_goal_confirmed',
deliverable: 'Clear feature goal and feature_name'
},
{
step_number: 2,
name: STEP_NAMES.REQUIREMENTS,
description: 'Generate requirements document in EARS format',
tool: 'spec_coding_requirements_start → spec_coding_requirements_confirmed',
deliverable: 'docs/specs/{feature_name}/requirements.md'
},
{
step_number: 3,
name: STEP_NAMES.DESIGN,
description: 'Create technical design document based on requirements',
tool: 'spec_coding_design_start → spec_coding_design_confirmed',
deliverable: 'docs/specs/{feature_name}/design.md'
},
{
step_number: 4,
name: STEP_NAMES.TASKS,
description: 'Generate executable development task list',
tool: 'spec_coding_tasks_start → spec_coding_tasks_confirmed',
deliverable: 'docs/specs/{feature_name}/tasks.md'
},
{
step_number: 5,
name: STEP_NAMES.EXECUTION,
description: 'Execute development tasks one by one',
tool: 'spec_coding_execute_start',
deliverable: 'Actual code implementation'
}
];
// Get workflow overview helper function
export function getWorkflowOverview(currentStepName: string): WorkflowOverview {
const currentStep = WORKFLOW_STEPS.find(step => step.name === currentStepName);
const stepNumber = currentStep?.step_number || 1;
return {
total_steps: WORKFLOW_STEPS.length,
current_step: currentStepName,
current_step_number: stepNumber,
steps: WORKFLOW_STEPS
};
}
```
--------------------------------------------------------------------------------
/templates/gen-design.md:
--------------------------------------------------------------------------------
```markdown
### 2. Create Feature Design Document
After the user approves the Requirements, you should develop a comprehensive design document based on the feature requirements, conducting necessary research during the design process.
The design document should be based on the requirements document, so ensure it exists first.
**Constraints:**
- The model MUST create a 'docs/specs/{feature_name}/design.md' file if it doesn't already exist
- The model MUST identify areas where research is needed based on the feature requirements
- The model MUST conduct research and build up context in the conversation thread
- The model SHOULD NOT create separate research files, but instead use the research as context for the design and implementation plan
- The model MUST summarize key findings that will inform the feature design
- The model SHOULD cite sources and include relevant links in the conversation
- The model MUST create a detailed design document at 'docs/specs/{feature_name}/design.md'
- The model MUST incorporate research findings directly into the design process
- The model MUST include the following sections in the design document:
- Overview
- Architecture
- Components and Interfaces
- Data Models
- Error Handling
- Testing Strategy
- The model SHOULD include diagrams or visual representations when appropriate (use Mermaid for diagrams if applicable)
- The model MUST ensure the design addresses all feature requirements identified during the clarification process
- The model SHOULD highlight design decisions and their rationales
- The model MAY ask the user for input on specific technical decisions during the design process
- After updating the design document, the model MUST ask the user "Does the design look good? If so, we can move on to the implementation plan." using the 'userInput' tool.
- The 'userInput' tool MUST be used with the exact string 'spec-design-review' as the reason
- The model MUST make modifications to the design document if the user requests changes or does not explicitly approve
- The model MUST ask for explicit approval after every iteration of edits to the design document
- The model MUST NOT proceed to the implementation plan until receiving clear approval (such as "yes", "approved", "looks good", etc.)
- The model MUST continue the feedback-revision cycle until explicit approval is received
- The model MUST incorporate all user feedback into the design document before proceeding
- The model MUST offer to return to feature requirements clarification if gaps are identified during design
```
--------------------------------------------------------------------------------
/templates/gen-tasks.md:
--------------------------------------------------------------------------------
```markdown
# Specification Implementation Plan Prompt
**Workflow Stage:** Implementation Planning
```
### 3. Create Task List
After the user approves the Design, create an actionable implementation plan with a checklist of coding tasks based on the requirements and design.
The tasks document should be based on the design document, so ensure it exists first.
requirements: 'docs/specs/{feature_name}/requirements.md'
design: 'docs/specs/{feature_name}/design.md'
**Constraints:**
- The model MUST create a 'docs/specs/{feature_name}/tasks.md' file if it doesn't already exist
- The model MUST return to the design step if the user indicates any changes are needed to the design
- The model MUST return to the requirement step if the user indicates that we need additional requirements
- The model MUST create an implementation plan at 'docs/specs/{feature_name}/tasks.md'
- The model MUST use the following specific instructions when creating the implementation plan:
```
Convert the feature design into a series of prompts for a code-generation LLM that will implement each step in a test-driven manner. Prioritize best practices, incremental progress, and early testing, ensuring no big jumps in complexity at any stage. Make sure that each prompt builds on the previous prompts, and ends with wiring things together. There should be no hanging or orphaned code that isn't integrated into a previous step. Focus ONLY on tasks that involve writing, modifying, or testing code.
```
- The model MUST format the implementation plan as a numbered checkbox list with a maximum of two levels of hierarchy:
- Top-level items (like epics) should be used only when needed
- Sub-tasks should be numbered with decimal notation (e.g., 1.1, 1.2, 2.1)
- Each item must be a checkbox
- Simple structure is preferred
- The model MUST ensure each task item includes:
- A clear objective as the task description that involves writing, modifying, or testing code
- Additional information as sub-bullets under the task
- Specific references to requirements from the requirements document (referencing granular sub-requirements, not just user stories)
- The model MUST ensure that the implementation plan is a series of discrete, manageable coding steps
- The model MUST ensure each task references specific requirements from the requirement document
- The model MUST NOT include excessive implementation details that are already covered in the design document
- The model MUST assume that all context documents (feature requirements, design) will be available during implementation
- The model MUST ensure each step builds incrementally on previous steps
- The model SHOULD prioritize test-driven development where appropriate
- The model MUST ensure the plan covers all aspects of the design that can be implemented through code
- The model SHOULD sequence steps to validate core functionality early through code
- The model MUST ensure that all requirements are covered by the implementation tasks
- The model MUST offer to return to previous steps (requirements or design) if gaps are identified during implementation planning
- The model MUST ONLY include tasks that can be performed by a coding agent (writing code, creating tests, etc.)
- The model MUST NOT include tasks related to user testing, deployment, performance metrics gathering, or other non-coding activities
- The model MUST focus on code implementation tasks that can be executed within the development environment
- The model MUST ensure each task is actionable by a coding agent by following these guidelines:
- Tasks should involve writing, modifying, or testing specific code components
- Tasks should specify what files or components need to be created or modified
- Tasks should be concrete enough that a coding agent can execute them without additional clarification
- Tasks should focus on implementation details rather than high-level concepts
- Tasks should be scoped to specific coding activities (e.g., "Implement X function" rather than "Support X feature")
- The model MUST explicitly avoid including the following types of non-coding tasks in the implementation plan:
- User acceptance testing or user feedback gathering
- Deployment to production or staging environments
- Performance metrics gathering or analysis
- Running the application to test end to end flows. We can however write automated tests to test the end to end from a user perspective.
- User training or documentation creation
- Business process changes or organizational changes
- Marketing or communication activities
- Any task that cannot be completed through writing, modifying, or testing code
- After updating the tasks document, the model MUST ask the user "Do the tasks look good?" using the 'userInput' tool.
- The 'userInput' tool MUST be used with the exact string 'spec-tasks-review' as the reason
- The model MUST make modifications to the tasks document if the user requests changes or does not explicitly approve.
- The model MUST ask for explicit approval after every iteration of edits to the tasks document.
- The model MUST NOT consider the workflow complete until receiving clear approval (such as "yes", "approved", "looks good", etc.).
- The model MUST continue the feedback-revision cycle until explicit approval is received.
- The model MUST stop once the task document has been approved.
**This workflow is ONLY for creating design and planning artifacts. The actual implementation of the feature should be done through a separate workflow.**
- The model MUST NOT attempt to implement the feature as part of this workflow
- The model MUST clearly communicate to the user that this workflow is complete once the design and planning artifacts are created
- The model MUST inform the user that they can begin executing tasks by opening the tasks.md file, and clicking "Start task" next to task items.
```
```
--------------------------------------------------------------------------------
/src/server.ts:
--------------------------------------------------------------------------------
```typescript
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { workflowStart } from './tools/workflow.js';
import { goalConfirmed } from './tools/goal.js';
import { requirementsStart } from './tools/requirements.js';
import { requirementsConfirmed } from './tools/requirements_confirmed.js';
import { designStart } from './tools/design.js';
import { designConfirmed } from './tools/design_confirmed.js';
import { tasksStart } from './tools/tasks.js';
import { tasksConfirmed } from './tools/tasks_confirmed.js';
import { executeStart } from './tools/execute.js';
export function createServer() {
const server = new Server(
{
name: 'spec-coding-mcp',
version: '1.0.0'
},
{
capabilities: { tools: {} }
}
);
// Tool definitions
const tools = [
{
name: 'spec_coding_workflow_start',
description: 'Start the specs workflow and begin the goal collection phase',
inputSchema: {
type: 'object',
properties: {},
required: []
}
},
{
name: 'spec_coding_goal_confirmed',
description: 'Confirm the completion of the feature goal, set the feature_name, and proceed to the requirements collection phase',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name generated based on the goal (e.g., user-auth)'
},
goal_summary: {
type: 'string',
description: 'Brief description of the feature goal'
}
},
required: ['session_id', 'feature_name', 'goal_summary']
}
},
{
name: 'spec_coding_requirements_start',
description: 'Start the requirements collection phase and provide guidance for requirements gathering',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
}
},
required: ['session_id', 'feature_name']
}
},
{
name: 'spec_coding_requirements_confirmed',
description: 'Confirm the completion of requirements collection and proceed to the design phase',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
}
},
required: ['session_id', 'feature_name']
}
},
{
name: 'spec_coding_design_start',
description: 'Start the design documentation phase and provide guidance for creating design documents',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
}
},
required: ['session_id', 'feature_name']
}
},
{
name: 'spec_coding_design_confirmed',
description: 'Confirm the completion of the design document and proceed to the task planning phase',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
}
},
required: ['session_id', 'feature_name']
}
},
{
name: 'spec_coding_tasks_start',
description: 'Start the task planning phase and provide guidance for creating the task list',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
}
},
required: ['session_id', 'feature_name']
}
},
{
name: 'spec_coding_tasks_confirmed',
description: 'Confirm the completion of task planning and proceed to the execution phase',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
}
},
required: ['session_id', 'feature_name']
}
},
{
name: 'spec_coding_execute_start',
description: 'Start the task execution phase and provide guidance for task execution',
inputSchema: {
type: 'object',
properties: {
session_id: {
type: 'string',
description: 'Session identifier'
},
feature_name: {
type: 'string',
description: 'Feature name'
},
task_id: {
type: 'string',
description: 'Optional: Specify the task ID to execute; if not specified, the next unfinished task will be executed'
}
},
required: ['session_id', 'feature_name']
}
}
];
// Register the handler for listing tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
console.error('[MCP] Handling list tools request');
return { tools };
});
// Register the handler for tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
console.error(`[MCP] Handling tool call: ${name}`, args);
try {
let result: any;
switch (name) {
case 'spec_coding_workflow_start':
result = await workflowStart();
break;
case 'spec_coding_goal_confirmed':
result = await goalConfirmed(args as any);
break;
case 'spec_coding_requirements_start':
result = await requirementsStart(args as any);
break;
case 'spec_coding_requirements_confirmed':
result = await requirementsConfirmed(args as any);
break;
case 'spec_coding_design_start':
result = await designStart(args as any);
break;
case 'spec_coding_design_confirmed':
result = await designConfirmed(args as any);
break;
case 'spec_coding_tasks_start':
result = await tasksStart(args as any);
break;
case 'spec_coding_tasks_confirmed':
result = await tasksConfirmed(args as any);
break;
case 'spec_coding_execute_start':
result = await executeStart(args as any);
break;
default:
throw new Error(`Unknown tool: ${name}`);
}
console.error(`[MCP] Tool ${name} completed successfully`);
return {
content: [{
type: 'text',
text: result
}]
};
} catch (error: any) {
console.error(`[MCP] Tool ${name} failed:`, error);
return {
content: [{
type: 'text',
text: `Error: ${error.message}`
}],
isError: true
};
}
});
return server;
}
```