@vasperacapital/vaspera-mcp-server 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/middleware/auth.ts","../src/middleware/usage.ts","../src/middleware/rate-limit.ts","../src/tools/types.ts","../src/ai/client.ts","../src/tools/explode-backlog.ts","../src/tools/infer-prd.ts","../src/tools/synthesize-prd.ts","../src/tools/generate-architecture.ts","../src/tools/handoff-package.ts","../src/tools/synthesize-requirements.ts","../src/tools/review-prd.ts","../src/tools/sync-to-tracker.ts","../src/tools/reverse-engineer-flows.ts","../src/tools/generate-test-specs.ts","../src/tools/explain-codebase.ts","../src/tools/validate-implementation.ts","../src/tools/suggest-refactors.ts","../src/tools/generate-api-docs.ts","../src/tools/dependency-audit.ts","../src/tools/estimate-migration.ts","../src/tools/index.ts","../src/server.ts","../src/cli.ts"],"sourcesContent":["import { QUOTA_LIMITS, type SubscriptionTier } from '@vasperacapital/vaspera-shared';\n\n// Response type from validate-key API\ninterface ValidateKeyResponse {\n valid: boolean;\n user?: {\n id: string;\n email: string;\n subscriptionTier: string;\n };\n key?: {\n id: string;\n scopes: string[];\n };\n quota?: {\n limit: number;\n used: number;\n remaining: number;\n };\n error?: {\n code: string;\n message: string;\n };\n}\n\nexport interface ValidationResult {\n valid: boolean;\n userId?: string;\n apiKeyId?: string;\n tier?: SubscriptionTier;\n scopes?: string[];\n quota?: {\n limit: number;\n used: number;\n remaining: number;\n };\n error?: {\n code: string;\n message: string;\n };\n}\n\n// API endpoint for validation (configured via environment)\nconst VALIDATE_KEY_URL = process.env.VASPERA_API_URL || 'https://vaspera.dev';\n\n/**\n * Validate an API key against the VasperaPM backend\n */\nexport async function validateApiKey(apiKey: string | undefined): Promise<ValidationResult> {\n if (!apiKey) {\n return {\n valid: false,\n error: {\n code: 'VPM-API-KEY-001',\n message: 'API key is required. Set VASPERA_API_KEY environment variable.',\n },\n };\n }\n\n // Validate key format\n if (!apiKey.startsWith('vpm_live_') && !apiKey.startsWith('vpm_test_')) {\n return {\n valid: false,\n error: {\n code: 'VPM-API-KEY-002',\n message: 'Invalid API key format. Keys must start with vpm_live_ or vpm_test_',\n },\n };\n }\n\n try {\n const response = await fetch(`${VALIDATE_KEY_URL}/api/validate-key`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ apiKey }),\n });\n\n const data = (await response.json()) as ValidateKeyResponse;\n\n if (!response.ok || !data.valid) {\n return {\n valid: false,\n error: data.error || {\n code: 'VPM-API-KEY-002',\n message: 'Invalid API key',\n },\n };\n }\n\n return {\n valid: true,\n userId: data.user?.id,\n apiKeyId: data.key?.id,\n tier: data.user?.subscriptionTier as SubscriptionTier,\n scopes: data.key?.scopes || [],\n quota: data.quota,\n };\n } catch (error) {\n console.error('API key validation error:', error);\n\n // Fall back to offline validation for test keys in development\n if (process.env.NODE_ENV === 'development' && apiKey.startsWith('vpm_test_')) {\n console.error('Using offline test mode');\n return {\n valid: true,\n userId: 'test-user',\n apiKeyId: 'test-key',\n tier: 'free',\n scopes: ['*'],\n quota: {\n limit: QUOTA_LIMITS.free,\n used: 0,\n remaining: QUOTA_LIMITS.free,\n },\n };\n }\n\n return {\n valid: false,\n error: {\n code: 'VPM-INTERNAL-001',\n message: 'Failed to validate API key. Please try again.',\n },\n };\n }\n}\n\n/**\n * Check if a scope is allowed for the given validation result\n */\nexport function hasScope(validation: ValidationResult, requiredScope: string): boolean {\n if (!validation.valid || !validation.scopes) return false;\n return validation.scopes.includes('*') || validation.scopes.includes(requiredScope);\n}\n","export interface UsageEvent {\n userId: string;\n apiKeyId: string;\n toolName: string;\n tokensUsed: number;\n latencyMs: number;\n success: boolean;\n errorCode?: string;\n metadata?: Record<string, unknown>;\n}\n\n// API endpoint for usage tracking (configured via environment)\nconst USAGE_API_URL = process.env.VASPERA_API_URL || 'https://vaspera.dev';\nconst INTERNAL_SERVICE_KEY = process.env.INTERNAL_SERVICE_KEY;\n\n/**\n * Track a usage event to the VasperaPM backend\n */\nexport async function trackUsage(event: UsageEvent): Promise<void> {\n // Skip tracking if no service key configured\n if (!INTERNAL_SERVICE_KEY) {\n console.error('INTERNAL_SERVICE_KEY not configured, skipping usage tracking');\n return;\n }\n\n try {\n const response = await fetch(`${USAGE_API_URL}/api/usage`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${INTERNAL_SERVICE_KEY}`,\n },\n body: JSON.stringify({\n userId: event.userId,\n apiKeyId: event.apiKeyId,\n toolName: event.toolName,\n tokensUsed: event.tokensUsed,\n latencyMs: event.latencyMs,\n success: event.success,\n errorCode: event.errorCode,\n metadata: event.metadata,\n requestId: generateRequestId(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n console.error('Failed to track usage:', error);\n }\n } catch (error) {\n console.error('Usage tracking error:', error);\n // Don't throw - usage tracking should not fail the request\n }\n}\n\n/**\n * Generate a unique request ID for tracking\n */\nfunction generateRequestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `req_${timestamp}_${random}`;\n}\n\n/**\n * Calculate approximate tokens from text\n * Uses a simple estimation of ~4 characters per token\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Calculate total tokens from input and output\n */\nexport function calculateTokens(input: string, output: string): number {\n return estimateTokens(input) + estimateTokens(output);\n}\n","import type { SubscriptionTier } from '@vasperacapital/vaspera-shared';\n\nexport interface RateLimitResult {\n allowed: boolean;\n remaining: number;\n limit: number;\n resetsAt?: Date;\n}\n\n// Rate limits per minute by tier\nconst RATE_LIMITS: Record<SubscriptionTier, number> = {\n free: 5, // 5 requests per minute\n starter: 20, // 20 requests per minute\n pro: 60, // 60 requests per minute (1 per second)\n enterprise: 300, // 300 requests per minute (5 per second)\n};\n\n// In-memory rate limit store (for single instance)\n// In production, use Redis or similar for distributed rate limiting\nconst rateLimitStore = new Map<string, { count: number; resetAt: number }>();\n\n// Cleanup old entries every minute\nsetInterval(() => {\n const now = Date.now();\n for (const [key, value] of rateLimitStore.entries()) {\n if (value.resetAt < now) {\n rateLimitStore.delete(key);\n }\n }\n}, 60000);\n\n/**\n * Check if a request is allowed under rate limits\n */\nexport async function checkRateLimit(\n userId: string,\n tier: SubscriptionTier\n): Promise<RateLimitResult> {\n const limit = RATE_LIMITS[tier] || RATE_LIMITS.free;\n const windowMs = 60000; // 1 minute window\n const now = Date.now();\n\n const key = `rate:${userId}`;\n let entry = rateLimitStore.get(key);\n\n // Initialize or reset if window expired\n if (!entry || entry.resetAt < now) {\n entry = {\n count: 0,\n resetAt: now + windowMs,\n };\n rateLimitStore.set(key, entry);\n }\n\n // Check if over limit\n if (entry.count >= limit) {\n return {\n allowed: false,\n remaining: 0,\n limit,\n resetsAt: new Date(entry.resetAt),\n };\n }\n\n // Increment counter\n entry.count++;\n rateLimitStore.set(key, entry);\n\n return {\n allowed: true,\n remaining: limit - entry.count,\n limit,\n resetsAt: new Date(entry.resetAt),\n };\n}\n\n/**\n * Reset rate limit for a user (e.g., after upgrade)\n */\nexport function resetRateLimit(userId: string): void {\n rateLimitStore.delete(`rate:${userId}`);\n}\n\n/**\n * Get current rate limit status without incrementing\n */\nexport function getRateLimitStatus(\n userId: string,\n tier: SubscriptionTier\n): RateLimitResult {\n const limit = RATE_LIMITS[tier] || RATE_LIMITS.free;\n const key = `rate:${userId}`;\n const entry = rateLimitStore.get(key);\n\n if (!entry || entry.resetAt < Date.now()) {\n return {\n allowed: true,\n remaining: limit,\n limit,\n };\n }\n\n return {\n allowed: entry.count < limit,\n remaining: Math.max(0, limit - entry.count),\n limit,\n resetsAt: new Date(entry.resetAt),\n };\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * Result returned by a tool handler\n */\nexport interface ToolResult {\n content: Array<{\n type: 'text';\n text: string;\n } | {\n type: 'resource';\n resource: {\n uri: string;\n mimeType: string;\n text?: string;\n blob?: string;\n };\n }>;\n tokensUsed?: number;\n}\n\n/**\n * Tool handler function signature\n */\nexport type ToolHandler = (\n args: Record<string, unknown>,\n validation: ValidationResult\n) => Promise<ToolResult>;\n\n/**\n * Tool definition with handler\n */\nexport interface ToolDefinition {\n tool: Tool;\n handler: ToolHandler;\n requiredScope?: string;\n}\n\n/**\n * Helper to create a text result\n */\nexport function textResult(text: string, tokensUsed?: number): ToolResult {\n return {\n content: [{ type: 'text', text }],\n tokensUsed,\n };\n}\n\n/**\n * Helper to create a JSON result\n */\nexport function jsonResult(data: unknown, tokensUsed?: number): ToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n tokensUsed,\n };\n}\n\n/**\n * Helper to create an error result\n */\nexport function errorResult(message: string): ToolResult {\n return {\n content: [{ type: 'text', text: `Error: ${message}` }],\n };\n}\n\n/**\n * Helper to create a markdown result\n */\nexport function markdownResult(markdown: string, tokensUsed?: number): ToolResult {\n return {\n content: [{ type: 'text', text: markdown }],\n tokensUsed,\n };\n}\n","import Anthropic from '@anthropic-ai/sdk';\n\n// Singleton AI client\nlet anthropicClient: Anthropic | null = null;\n\n/**\n * Get the Anthropic client instance\n */\nexport function getAnthropicClient(): Anthropic {\n if (!anthropicClient) {\n const apiKey = process.env.ANTHROPIC_API_KEY;\n if (!apiKey) {\n throw new Error('ANTHROPIC_API_KEY environment variable is required');\n }\n anthropicClient = new Anthropic({ apiKey });\n }\n return anthropicClient;\n}\n\n/**\n * Default model for VasperaPM tools\n */\nexport const DEFAULT_MODEL = 'claude-sonnet-4-20250514';\n\n/**\n * Model options by capability tier\n */\nexport const MODELS = {\n fast: 'claude-3-5-haiku-20241022', // Quick responses, lower cost\n balanced: 'claude-sonnet-4-20250514', // Good balance of speed and quality\n powerful: 'claude-sonnet-4-20250514', // Best quality for complex tasks\n} as const;\n\nexport type ModelTier = keyof typeof MODELS;\n\n/**\n * Create a completion with Claude\n */\nexport async function createCompletion(options: {\n systemPrompt: string;\n userMessage: string;\n model?: ModelTier;\n maxTokens?: number;\n temperature?: number;\n}): Promise<{\n text: string;\n inputTokens: number;\n outputTokens: number;\n}> {\n const client = getAnthropicClient();\n const model = MODELS[options.model || 'balanced'];\n\n const response = await client.messages.create({\n model,\n max_tokens: options.maxTokens || 4096,\n temperature: options.temperature ?? 0.7,\n system: options.systemPrompt,\n messages: [\n {\n role: 'user',\n content: options.userMessage,\n },\n ],\n });\n\n // Extract text from response\n const textContent = response.content.find((c) => c.type === 'text');\n const text = textContent?.type === 'text' ? textContent.text : '';\n\n return {\n text,\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n };\n}\n\n/**\n * Create a structured JSON completion with Claude\n */\nexport async function createJsonCompletion<T>(options: {\n systemPrompt: string;\n userMessage: string;\n model?: ModelTier;\n maxTokens?: number;\n}): Promise<{\n data: T;\n inputTokens: number;\n outputTokens: number;\n}> {\n const result = await createCompletion({\n ...options,\n systemPrompt: `${options.systemPrompt}\\n\\nIMPORTANT: Respond ONLY with valid JSON. No markdown, no explanation, just the JSON object.`,\n temperature: 0.3, // Lower temperature for structured output\n });\n\n // Parse JSON from response\n let jsonText = result.text.trim();\n\n // Handle markdown code blocks\n if (jsonText.startsWith('```json')) {\n jsonText = jsonText.slice(7);\n } else if (jsonText.startsWith('```')) {\n jsonText = jsonText.slice(3);\n }\n if (jsonText.endsWith('```')) {\n jsonText = jsonText.slice(0, -3);\n }\n jsonText = jsonText.trim();\n\n try {\n const data = JSON.parse(jsonText) as T;\n return {\n data,\n inputTokens: result.inputTokens,\n outputTokens: result.outputTokens,\n };\n } catch (error) {\n throw new Error(`Failed to parse AI response as JSON: ${result.text.substring(0, 200)}`);\n }\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * explode_backlog tool - Breaks down high-level features into detailed user stories\n */\nexport const explodeBacklogTool: ToolDefinition = {\n tool: {\n name: 'explode_backlog',\n description: `Break down high-level features or epics into detailed, actionable user stories.\n\nTakes a feature description and generates:\n- User stories with acceptance criteria\n- Story point estimates\n- Priority recommendations\n- Dependencies between stories\n\nBest for: Converting feature ideas into sprint-ready backlog items.`,\n inputSchema: {\n type: 'object',\n properties: {\n feature: {\n type: 'string',\n description: 'The feature or epic to break down into user stories',\n },\n context: {\n type: 'string',\n description: 'Optional context about the product, tech stack, or constraints',\n },\n format: {\n type: 'string',\n enum: ['markdown', 'json', 'jira', 'linear'],\n default: 'markdown',\n description: 'Output format for the stories',\n },\n maxStories: {\n type: 'number',\n default: 10,\n description: 'Maximum number of stories to generate',\n },\n },\n required: ['feature'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const feature = args.feature as string;\n const context = args.context as string | undefined;\n const format = (args.format as string) || 'markdown';\n const maxStories = (args.maxStories as number) || 10;\n\n if (!feature || feature.trim().length === 0) {\n return errorResult('Feature description is required');\n }\n\n const systemPrompt = `You are an expert product manager and agile coach. Your task is to break down features into well-structured user stories.\n\nFor each user story, provide:\n1. A clear title following the format: \"As a [user], I want [goal] so that [benefit]\"\n2. Detailed acceptance criteria (at least 3 per story)\n3. Story point estimate (1, 2, 3, 5, 8, or 13)\n4. Priority (High, Medium, Low)\n5. Any dependencies on other stories\n\nGuidelines:\n- Stories should be independent when possible\n- Each story should be completable in a single sprint\n- Include edge cases and error handling in acceptance criteria\n- Consider both happy path and error scenarios\n- Stories should be testable\n\n${context ? `Product Context: ${context}` : ''}`;\n\n const userMessage = `Break down the following feature into ${maxStories} or fewer detailed user stories:\n\nFeature: ${feature}\n\n${format === 'json' ? 'Output as a JSON array of story objects.' :\n format === 'jira' ? 'Format for Jira import (CSV-compatible).' :\n format === 'linear' ? 'Format for Linear import.' :\n 'Output in clean markdown format.'}`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 4096,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to generate user stories: ${message}`);\n }\n },\n\n requiredScope: 'tools:explode_backlog',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * infer_prd_from_code tool - Generates a PRD from existing codebase\n */\nexport const inferPrdTool: ToolDefinition = {\n tool: {\n name: 'infer_prd_from_code',\n description: `Analyze code and generate a Product Requirements Document (PRD).\n\nTakes code snippets, file structures, or repository descriptions and infers:\n- Product overview and purpose\n- Feature list with descriptions\n- User personas and use cases\n- Technical requirements\n- Non-functional requirements\n\nBest for: Documenting existing products or understanding inherited codebases.`,\n inputSchema: {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description: 'Code snippets, file structure, or repository content to analyze',\n },\n repoDescription: {\n type: 'string',\n description: 'Optional description of the repository or project',\n },\n techStack: {\n type: 'string',\n description: 'Technology stack used (e.g., \"Next.js, TypeScript, PostgreSQL\")',\n },\n focusAreas: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific areas to focus on (e.g., [\"authentication\", \"payments\"])',\n },\n },\n required: ['code'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const code = args.code as string;\n const repoDescription = args.repoDescription as string | undefined;\n const techStack = args.techStack as string | undefined;\n const focusAreas = args.focusAreas as string[] | undefined;\n\n if (!code || code.trim().length === 0) {\n return errorResult('Code content is required');\n }\n\n const systemPrompt = `You are an expert product manager who specializes in reverse-engineering products from code. Your task is to analyze code and generate a comprehensive PRD.\n\nThe PRD should include:\n1. **Product Overview** - What the product does and its purpose\n2. **Target Users** - Who uses this product and why\n3. **Core Features** - List of main features with descriptions\n4. **User Stories** - Key user journeys\n5. **Technical Requirements** - Architecture and technical constraints\n6. **Non-Functional Requirements** - Performance, security, scalability\n7. **Future Considerations** - Potential improvements or extensions\n\nGuidelines:\n- Infer purpose from code patterns and naming conventions\n- Identify API endpoints and their purposes\n- Note database schema and data models\n- Consider error handling and edge cases\n- Look for authentication/authorization patterns\n\n${techStack ? `Tech Stack: ${techStack}` : ''}\n${repoDescription ? `Repository Description: ${repoDescription}` : ''}\n${focusAreas?.length ? `Focus Areas: ${focusAreas.join(', ')}` : ''}`;\n\n const userMessage = `Analyze the following code and generate a comprehensive PRD:\n\n\\`\\`\\`\n${code.length > 15000 ? code.substring(0, 15000) + '\\n... [truncated]' : code}\n\\`\\`\\`\n\nGenerate a detailed PRD in markdown format.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 4096,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to generate PRD: ${message}`);\n }\n },\n\n requiredScope: 'tools:infer_prd',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * synthesize_master_prd tool - Combines multiple documents into a unified PRD\n */\nexport const synthesizePrdTool: ToolDefinition = {\n tool: {\n name: 'synthesize_master_prd',\n description: `Synthesize multiple input documents into a unified Master PRD.\n\nTakes multiple sources (meeting notes, emails, specs, designs) and creates:\n- Unified product vision\n- Consolidated requirements\n- Prioritized feature list\n- Clear success metrics\n- Risk assessment\n\nBest for: Creating a single source of truth from scattered documentation.`,\n inputSchema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n title: { type: 'string' },\n content: { type: 'string' },\n type: {\n type: 'string',\n enum: ['meeting_notes', 'email', 'spec', 'design', 'feedback', 'other'],\n },\n },\n required: ['content'],\n },\n description: 'Array of documents to synthesize',\n },\n productName: {\n type: 'string',\n description: 'Name of the product',\n },\n targetAudience: {\n type: 'string',\n description: 'Description of the target users',\n },\n constraints: {\n type: 'string',\n description: 'Any constraints (timeline, budget, tech limitations)',\n },\n },\n required: ['documents'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const documents = args.documents as Array<{ title?: string; content: string; type?: string }>;\n const productName = args.productName as string | undefined;\n const targetAudience = args.targetAudience as string | undefined;\n const constraints = args.constraints as string | undefined;\n\n if (!documents || documents.length === 0) {\n return errorResult('At least one document is required');\n }\n\n const systemPrompt = `You are an expert product manager who excels at synthesizing scattered information into clear, actionable PRDs.\n\nCreate a Master PRD with the following sections:\n1. **Executive Summary** - High-level overview\n2. **Product Vision** - What we're building and why\n3. **Target Users** - Who benefits and their needs\n4. **Goals & Success Metrics** - How we measure success\n5. **Features & Requirements** - Detailed feature list with priorities\n6. **User Journeys** - Key workflows\n7. **Technical Considerations** - Architecture implications\n8. **Risks & Mitigations** - What could go wrong\n9. **Timeline & Milestones** - High-level roadmap\n10. **Open Questions** - Items needing clarification\n\nGuidelines:\n- Resolve contradictions between documents by noting them\n- Extract implicit requirements from feedback and discussions\n- Identify gaps that need stakeholder input\n- Prioritize based on user impact and business value\n\n${productName ? `Product Name: ${productName}` : ''}\n${targetAudience ? `Target Audience: ${targetAudience}` : ''}\n${constraints ? `Constraints: ${constraints}` : ''}`;\n\n // Format documents for the prompt\n const formattedDocs = documents.map((doc, i) => {\n const title = doc.title || `Document ${i + 1}`;\n const type = doc.type || 'other';\n return `### ${title} (${type})\\n${doc.content}`;\n }).join('\\n\\n---\\n\\n');\n\n const userMessage = `Synthesize the following documents into a comprehensive Master PRD:\n\n${formattedDocs.length > 20000 ? formattedDocs.substring(0, 20000) + '\\n... [truncated]' : formattedDocs}\n\nCreate a unified PRD that captures all requirements and resolves any conflicts.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to synthesize PRD: ${message}`);\n }\n },\n\n requiredScope: 'tools:synthesize_prd',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * generate_architecture tool - Creates technical architecture from requirements\n */\nexport const generateArchitectureTool: ToolDefinition = {\n tool: {\n name: 'generate_architecture',\n description: `Generate a technical architecture document from product requirements.\n\nTakes a PRD or feature description and creates:\n- System architecture diagram (in Mermaid)\n- Component breakdown\n- Data models and schemas\n- API design recommendations\n- Technology stack suggestions\n- Scalability considerations\n\nBest for: Translating product requirements into technical specifications.`,\n inputSchema: {\n type: 'object',\n properties: {\n requirements: {\n type: 'string',\n description: 'Product requirements or PRD content',\n },\n existingStack: {\n type: 'string',\n description: 'Existing technology stack to build upon',\n },\n constraints: {\n type: 'object',\n properties: {\n budget: { type: 'string' },\n timeline: { type: 'string' },\n team: { type: 'string' },\n compliance: { type: 'array', items: { type: 'string' } },\n },\n description: 'Technical and business constraints',\n },\n focus: {\n type: 'string',\n enum: ['backend', 'frontend', 'fullstack', 'infrastructure', 'data'],\n default: 'fullstack',\n description: 'Architecture focus area',\n },\n },\n required: ['requirements'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const requirements = args.requirements as string;\n const existingStack = args.existingStack as string | undefined;\n const constraints = args.constraints as Record<string, unknown> | undefined;\n const focus = (args.focus as string) || 'fullstack';\n\n if (!requirements || requirements.trim().length === 0) {\n return errorResult('Requirements are required');\n }\n\n const systemPrompt = `You are a senior solutions architect specializing in modern software systems. Your task is to create a comprehensive technical architecture document.\n\nInclude the following sections:\n1. **Architecture Overview** - High-level system design\n2. **System Diagram** - Mermaid diagram showing components\n3. **Components** - Detailed breakdown of each component\n4. **Data Models** - Entity relationships and schemas\n5. **API Design** - Endpoint structure and contracts\n6. **Technology Recommendations** - Stack choices with rationale\n7. **Security Architecture** - Auth, encryption, access control\n8. **Scalability Plan** - How the system grows\n9. **Infrastructure** - Deployment and hosting\n10. **Risks & Trade-offs** - Technical debt and decisions\n\nGuidelines:\n- Use Mermaid syntax for diagrams\n- Consider SOLID principles and clean architecture\n- Recommend proven, maintainable technologies\n- Include performance considerations\n- Address data integrity and consistency\n\nFocus Area: ${focus}\n${existingStack ? `Existing Stack: ${existingStack}` : ''}\n${constraints ? `Constraints: ${JSON.stringify(constraints)}` : ''}`;\n\n const userMessage = `Create a technical architecture for the following requirements:\n\n${requirements.length > 12000 ? requirements.substring(0, 12000) + '\\n... [truncated]' : requirements}\n\nGenerate a comprehensive architecture document with Mermaid diagrams.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to generate architecture: ${message}`);\n }\n },\n\n requiredScope: 'tools:generate_architecture',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * handoff_package tool - Creates complete developer handoff packages\n */\nexport const handoffPackageTool: ToolDefinition = {\n tool: {\n name: 'handoff_package',\n description: `Create a complete developer handoff package from PM artifacts.\n\nTakes PRD, designs, and specs to generate:\n- Implementation guide\n- Acceptance criteria checklist\n- Edge cases and error handling\n- Testing requirements\n- Definition of Done\n\nBest for: Preparing work for engineering sprint planning.`,\n inputSchema: {\n type: 'object',\n properties: {\n prd: {\n type: 'string',\n description: 'Product Requirements Document content',\n },\n designs: {\n type: 'string',\n description: 'Design descriptions or Figma links',\n },\n techSpecs: {\n type: 'string',\n description: 'Technical specifications or architecture docs',\n },\n targetTeam: {\n type: 'string',\n enum: ['frontend', 'backend', 'fullstack', 'mobile', 'devops'],\n default: 'fullstack',\n description: 'Target development team',\n },\n sprintDuration: {\n type: 'number',\n default: 2,\n description: 'Sprint duration in weeks',\n },\n },\n required: ['prd'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const prd = args.prd as string;\n const designs = args.designs as string | undefined;\n const techSpecs = args.techSpecs as string | undefined;\n const targetTeam = (args.targetTeam as string) || 'fullstack';\n const sprintDuration = (args.sprintDuration as number) || 2;\n\n if (!prd || prd.trim().length === 0) {\n return errorResult('PRD content is required');\n }\n\n const systemPrompt = `You are an expert technical program manager who creates flawless developer handoff packages.\n\nCreate a handoff package with:\n1. **Summary** - What we're building and why\n2. **Implementation Guide**\n - Step-by-step implementation order\n - Dependencies between components\n - Critical path items\n3. **Acceptance Criteria** - Testable requirements for each feature\n4. **Edge Cases** - All the \"what if\" scenarios\n5. **Error Handling** - How errors should be handled\n6. **Testing Requirements**\n - Unit test requirements\n - Integration test scenarios\n - E2E test flows\n7. **Definition of Done** - Checklist for completion\n8. **Questions for PM** - Clarifications needed\n9. **Risks** - Implementation risks to discuss\n\nGuidelines:\n- Be extremely specific - no ambiguity\n- Include code examples where helpful\n- Consider accessibility requirements\n- Note performance expectations\n- List any feature flags needed\n\nTarget Team: ${targetTeam}\nSprint Duration: ${sprintDuration} weeks`;\n\n let userMessage = `Create a developer handoff package from:\n\n## PRD\n${prd.length > 10000 ? prd.substring(0, 10000) + '\\n... [truncated]' : prd}`;\n\n if (designs) {\n userMessage += `\\n\\n## Design Specs\\n${designs}`;\n }\n\n if (techSpecs) {\n userMessage += `\\n\\n## Technical Specs\\n${techSpecs}`;\n }\n\n userMessage += '\\n\\nCreate a comprehensive handoff package.';\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to create handoff package: ${message}`);\n }\n },\n\n requiredScope: 'tools:handoff_package',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * synthesize_requirements tool - Extracts and consolidates requirements from various sources\n */\nexport const synthesizeRequirementsTool: ToolDefinition = {\n tool: {\n name: 'synthesize_requirements',\n description: `Extract and synthesize requirements from various input sources.\n\nTakes meeting notes, emails, slack threads, user feedback, or any unstructured input and produces:\n- Functional requirements (what the system must do)\n- Non-functional requirements (performance, security, scalability)\n- User stories in standard format\n- Acceptance criteria for each requirement\n- Requirement dependencies and priorities\n\nBest for: Converting messy stakeholder input into structured requirements.`,\n inputSchema: {\n type: 'object',\n properties: {\n sources: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n content: { type: 'string' },\n type: {\n type: 'string',\n enum: ['meeting_notes', 'email', 'slack', 'feedback', 'interview', 'survey', 'other'],\n },\n stakeholder: { type: 'string' },\n date: { type: 'string' },\n },\n required: ['content'],\n },\n description: 'Array of source documents to analyze',\n },\n context: {\n type: 'string',\n description: 'Product or feature context to help interpretation',\n },\n outputFormat: {\n type: 'string',\n enum: ['user_stories', 'requirements_doc', 'both'],\n default: 'both',\n description: 'Output format preference',\n },\n priorityFramework: {\n type: 'string',\n enum: ['moscow', 'rice', 'kano', 'value_effort'],\n default: 'moscow',\n description: 'Prioritization framework to use',\n },\n },\n required: ['sources'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const sources = args.sources as Array<{\n content: string;\n type?: string;\n stakeholder?: string;\n date?: string;\n }>;\n const context = args.context as string | undefined;\n const outputFormat = (args.outputFormat as string) || 'both';\n const priorityFramework = (args.priorityFramework as string) || 'moscow';\n\n if (!sources || sources.length === 0) {\n return errorResult('At least one source document is required');\n }\n\n const priorityDescriptions: Record<string, string> = {\n moscow: 'MoSCoW (Must have, Should have, Could have, Won\\'t have)',\n rice: 'RICE (Reach, Impact, Confidence, Effort)',\n kano: 'Kano Model (Basic, Performance, Excitement)',\n value_effort: 'Value/Effort Matrix (Quick wins, Big bets, Fill-ins, Time sinks)',\n };\n\n const systemPrompt = `You are a senior business analyst expert at extracting clear requirements from ambiguous stakeholder input.\n\nYour task is to analyze the provided sources and produce structured requirements.\n\nOutput Sections:\n1. **Executive Summary** - Key themes and scope overview\n2. **Functional Requirements** - What the system must do\n - ID, Description, Priority, Source reference\n3. **Non-Functional Requirements** - Quality attributes\n - Performance, Security, Scalability, Accessibility, etc.\n4. **User Stories** - In \"As a [role], I want [feature], so that [benefit]\" format\n - Include acceptance criteria for each\n5. **Requirement Dependencies** - Which requirements depend on others\n6. **Priority Matrix** - Using ${priorityDescriptions[priorityFramework]}\n7. **Gaps & Ambiguities** - What's unclear or missing\n8. **Recommended Clarifications** - Questions for stakeholders\n\nGuidelines:\n- Extract implicit requirements (things stakeholders assume but didn't state)\n- Note conflicting requirements and flag for resolution\n- Use unique IDs for traceability (REQ-001, US-001, etc.)\n- Map each requirement back to its source\n- Consider edge cases mentioned in discussions\n\n${context ? `Product Context: ${context}` : ''}`;\n\n // Format sources for the prompt\n const formattedSources = sources\n .map((source, i) => {\n const meta = [\n source.type ? `Type: ${source.type}` : null,\n source.stakeholder ? `Stakeholder: ${source.stakeholder}` : null,\n source.date ? `Date: ${source.date}` : null,\n ]\n .filter(Boolean)\n .join(' | ');\n\n return `### Source ${i + 1}${meta ? ` (${meta})` : ''}\\n${source.content}`;\n })\n .join('\\n\\n---\\n\\n');\n\n const userMessage = `Analyze these sources and extract structured requirements:\n\n${formattedSources.length > 15000 ? formattedSources.substring(0, 15000) + '\\n... [truncated]' : formattedSources}\n\nOutput format preference: ${outputFormat}\nPrioritization framework: ${priorityFramework}\n\nExtract all requirements with proper structure and traceability.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to synthesize requirements: ${message}`);\n }\n },\n\n requiredScope: 'tools:synthesize_requirements',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * review_prd tool - Comprehensive PRD review and critique\n */\nexport const reviewPrdTool: ToolDefinition = {\n tool: {\n name: 'review_prd',\n description: `Review and critique a Product Requirements Document.\n\nAnalyzes a PRD against best practices and provides:\n- Completeness assessment\n- Clarity and ambiguity analysis\n- Gap identification\n- Risk assessment\n- Improvement suggestions\n- Readiness score\n\nBest for: Quality assurance before engineering handoff.`,\n inputSchema: {\n type: 'object',\n properties: {\n prd: {\n type: 'string',\n description: 'The PRD content to review',\n },\n reviewFocus: {\n type: 'array',\n items: {\n type: 'string',\n enum: [\n 'completeness',\n 'clarity',\n 'technical_feasibility',\n 'user_value',\n 'metrics',\n 'edge_cases',\n 'security',\n 'accessibility',\n ],\n },\n default: ['completeness', 'clarity', 'technical_feasibility'],\n description: 'Areas to focus the review on',\n },\n targetAudience: {\n type: 'string',\n enum: ['engineering', 'stakeholders', 'both'],\n default: 'engineering',\n description: 'Primary audience for the PRD',\n },\n strictness: {\n type: 'string',\n enum: ['lenient', 'standard', 'strict'],\n default: 'standard',\n description: 'How strict the review should be',\n },\n },\n required: ['prd'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const prd = args.prd as string;\n const reviewFocus = (args.reviewFocus as string[]) || [\n 'completeness',\n 'clarity',\n 'technical_feasibility',\n ];\n const targetAudience = (args.targetAudience as string) || 'engineering';\n const strictness = (args.strictness as string) || 'standard';\n\n if (!prd || prd.trim().length === 0) {\n return errorResult('PRD content is required for review');\n }\n\n const strictnessGuide: Record<string, string> = {\n lenient: 'Be constructive and focus on major issues only. Assume good intent and fill in reasonable gaps.',\n standard: 'Balance thoroughness with practicality. Flag important issues but don\\'t nitpick.',\n strict: 'Apply rigorous standards. Flag all issues, ambiguities, and potential problems. This PRD should be bulletproof.',\n };\n\n const systemPrompt = `You are a senior product management coach who has reviewed thousands of PRDs. Your job is to provide actionable, constructive feedback.\n\nReview the PRD with these priorities:\n${reviewFocus.map((f) => `- ${f}`).join('\\n')}\n\nProvide a structured review with:\n\n1. **Overall Assessment**\n - Readiness Score (1-10)\n - Summary judgment (Ready / Needs Work / Major Revision Needed)\n\n2. **Strengths**\n - What's done well\n\n3. **Completeness Analysis**\n - Required sections present/missing\n - Depth of coverage\n\n4. **Clarity Issues**\n - Ambiguous requirements (quote specific text)\n - Missing definitions\n - Unclear scope boundaries\n\n5. **Technical Feasibility Concerns**\n - Potentially challenging requirements\n - Missing technical considerations\n - Architecture implications not addressed\n\n6. **Gap Analysis**\n - Missing use cases\n - Unaddressed edge cases\n - Missing acceptance criteria\n\n7. **Risk Assessment**\n - Implementation risks\n - Timeline risks\n - Dependency risks\n\n8. **Specific Recommendations**\n - Prioritized list of improvements\n - Suggested rewrites for unclear sections\n\n9. **Questions for PM**\n - Clarifications needed before engineering can start\n\nReview Strictness: ${strictnessGuide[strictness]}\nTarget Audience: ${targetAudience}`;\n\n const userMessage = `Review this PRD and provide comprehensive feedback:\n\n${prd.length > 15000 ? prd.substring(0, 15000) + '\\n... [truncated]' : prd}\n\nProvide a thorough review with actionable feedback.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to review PRD: ${message}`);\n }\n },\n\n requiredScope: 'tools:review_prd',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { jsonResult, errorResult } from './types.js';\nimport { createJsonCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\ninterface TrackerItem {\n type: 'epic' | 'story' | 'task' | 'bug' | 'subtask';\n title: string;\n description: string;\n acceptanceCriteria?: string[];\n priority: 'highest' | 'high' | 'medium' | 'low' | 'lowest';\n labels?: string[];\n estimate?: string;\n parentRef?: string;\n customFields?: Record<string, string>;\n}\n\ninterface SyncOutput {\n platform: string;\n projectKey?: string;\n items: TrackerItem[];\n importInstructions: string;\n}\n\n/**\n * sync_to_tracker tool - Format requirements for project management tools\n */\nexport const syncToTrackerTool: ToolDefinition = {\n tool: {\n name: 'sync_to_tracker',\n description: `Format requirements and user stories for import into project management tools.\n\nTakes requirements or a PRD and generates properly formatted items for:\n- Jira (Epics, Stories, Tasks, Subtasks)\n- Linear (Projects, Issues, Sub-issues)\n- GitHub Issues (Issues with labels and milestones)\n- Asana (Projects, Tasks, Subtasks)\n- Notion (Database entries)\n\nOutput includes import instructions and properly structured data.\n\nBest for: Automated backlog population from requirements documents.`,\n inputSchema: {\n type: 'object',\n properties: {\n requirements: {\n type: 'string',\n description: 'Requirements document, PRD, or user stories to convert',\n },\n platform: {\n type: 'string',\n enum: ['jira', 'linear', 'github', 'asana', 'notion'],\n default: 'jira',\n description: 'Target project management platform',\n },\n projectKey: {\n type: 'string',\n description: 'Project key/identifier (e.g., PROJ for Jira)',\n },\n epicName: {\n type: 'string',\n description: 'Parent epic name for all generated items',\n },\n defaultLabels: {\n type: 'array',\n items: { type: 'string' },\n description: 'Default labels to apply to all items',\n },\n includeEstimates: {\n type: 'boolean',\n default: true,\n description: 'Whether to include effort estimates',\n },\n estimateUnit: {\n type: 'string',\n enum: ['story_points', 'hours', 't_shirt'],\n default: 'story_points',\n description: 'Estimation unit to use',\n },\n },\n required: ['requirements'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const requirements = args.requirements as string;\n const platform = (args.platform as string) || 'jira';\n const projectKey = args.projectKey as string | undefined;\n const epicName = args.epicName as string | undefined;\n const defaultLabels = (args.defaultLabels as string[]) || [];\n const includeEstimates = args.includeEstimates !== false;\n const estimateUnit = (args.estimateUnit as string) || 'story_points';\n\n if (!requirements || requirements.trim().length === 0) {\n return errorResult('Requirements content is required');\n }\n\n const platformConfig: Record<string, { hierarchy: string; estimateFormat: string }> = {\n jira: {\n hierarchy: 'Epic > Story > Task > Subtask',\n estimateFormat: 'Story points (fibonacci: 1, 2, 3, 5, 8, 13) or time (1h, 2h, 4h, 1d, 2d)',\n },\n linear: {\n hierarchy: 'Project > Issue > Sub-issue',\n estimateFormat: 'Linear points (0, 1, 2, 3, 5, 8)',\n },\n github: {\n hierarchy: 'Milestone > Issue',\n estimateFormat: 'T-shirt sizes in labels (size:S, size:M, size:L, size:XL)',\n },\n asana: {\n hierarchy: 'Project > Section > Task > Subtask',\n estimateFormat: 'Hours or days',\n },\n notion: {\n hierarchy: 'Database > Entry (with relations)',\n estimateFormat: 'Number property or select (S/M/L/XL)',\n },\n };\n\n const config = platformConfig[platform];\n if (!config) {\n return errorResult(`Unsupported platform: ${platform}`);\n }\n\n const systemPrompt = `You are an expert at structuring work items for project management tools.\n\nConvert the requirements into structured items for ${platform.toUpperCase()}.\n\nPlatform hierarchy: ${config.hierarchy}\nEstimate format: ${config.estimateFormat}\n${epicName ? `Parent Epic: ${epicName}` : ''}\n${defaultLabels.length > 0 ? `Default Labels: ${defaultLabels.join(', ')}` : ''}\n\nOutput a JSON object with this structure:\n{\n \"platform\": \"${platform}\",\n \"projectKey\": \"${projectKey || 'PROJECT'}\",\n \"items\": [\n {\n \"type\": \"epic|story|task|bug|subtask\",\n \"title\": \"Clear, actionable title\",\n \"description\": \"Detailed description with context\",\n \"acceptanceCriteria\": [\"Criterion 1\", \"Criterion 2\"],\n \"priority\": \"highest|high|medium|low|lowest\",\n \"labels\": [\"label1\", \"label2\"],\n \"estimate\": \"${includeEstimates ? 'Appropriate estimate' : 'null'}\",\n \"parentRef\": \"Reference to parent item if subtask/child\",\n \"customFields\": {}\n }\n ],\n \"importInstructions\": \"Step-by-step instructions for importing into ${platform}\"\n}\n\nGuidelines:\n- Create a logical hierarchy (epics contain stories, stories contain tasks)\n- Write clear, actionable titles (start with verb)\n- Include enough context in descriptions for developers\n- Add acceptance criteria for stories\n- Use appropriate priority based on business value and dependencies\n- Keep items appropriately sized (stories should be completable in 1 sprint)\n- Reference parent items for hierarchy\n${includeEstimates ? `- Include ${estimateUnit} estimates based on complexity` : '- Do not include estimates'}`;\n\n const userMessage = `Convert these requirements into ${platform} items:\n\n${requirements.length > 12000 ? requirements.substring(0, 12000) + '\\n... [truncated]' : requirements}\n\nGenerate structured items ready for import.`;\n\n try {\n const result = await createJsonCompletion<SyncOutput>({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n // Validate and enhance the output\n const output = result.data;\n output.platform = platform;\n if (projectKey) output.projectKey = projectKey;\n\n // Add default labels to all items\n if (defaultLabels.length > 0 && output.items) {\n output.items = output.items.map((item) => ({\n ...item,\n labels: [...new Set([...(item.labels || []), ...defaultLabels])],\n }));\n }\n\n return jsonResult(output, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to format for tracker: ${message}`);\n }\n },\n\n requiredScope: 'tools:sync_to_tracker',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * reverse_engineer_user_flows tool - Extract user flows from code\n */\nexport const reverseEngineerFlowsTool: ToolDefinition = {\n tool: {\n name: 'reverse_engineer_user_flows',\n description: `Analyze code to extract and document user flows and journeys.\n\nTakes source code (routes, components, handlers) and produces:\n- User journey maps\n- Flow diagrams (Mermaid)\n- Screen/state transitions\n- API call sequences\n- Error handling paths\n- Edge case flows\n\nBest for: Documenting existing features or understanding inherited codebases.`,\n inputSchema: {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description: 'Source code to analyze (routes, components, controllers)',\n },\n codeType: {\n type: 'string',\n enum: ['frontend', 'backend', 'fullstack', 'api'],\n default: 'fullstack',\n description: 'Type of code being analyzed',\n },\n featureName: {\n type: 'string',\n description: 'Name of the feature being analyzed',\n },\n outputFormat: {\n type: 'string',\n enum: ['flows', 'diagrams', 'documentation', 'all'],\n default: 'all',\n description: 'What to include in output',\n },\n includeErrorFlows: {\n type: 'boolean',\n default: true,\n description: 'Whether to document error handling flows',\n },\n },\n required: ['code'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const code = args.code as string;\n const codeType = (args.codeType as string) || 'fullstack';\n const featureName = args.featureName as string | undefined;\n const outputFormat = (args.outputFormat as string) || 'all';\n const includeErrorFlows = args.includeErrorFlows !== false;\n\n if (!code || code.trim().length === 0) {\n return errorResult('Source code is required for analysis');\n }\n\n const systemPrompt = `You are a senior engineer expert at reverse engineering user flows from code.\n\nAnalyze the provided code and extract user flows.\n\nOutput Sections:\n1. **Overview**\n - Feature summary\n - Entry points identified\n - Key actors/roles\n\n2. **User Flows**\n - Primary happy path\n - Alternative paths\n ${includeErrorFlows ? '- Error flows and recovery paths' : ''}\n - Edge cases\n\n3. **Flow Diagram** (Mermaid)\n \\`\\`\\`mermaid\n flowchart TD\n Start --> Action --> Decision{Condition}\n Decision -->|Yes| Success\n Decision -->|No| Error\n \\`\\`\\`\n\n4. **State Transitions**\n - UI states (loading, error, success, empty)\n - Data states\n - User state changes\n\n5. **API Sequence** (if applicable)\n \\`\\`\\`mermaid\n sequenceDiagram\n participant User\n participant Frontend\n participant API\n participant Database\n \\`\\`\\`\n\n6. **Components/Screens**\n - List of screens/components involved\n - Their responsibilities\n - Data dependencies\n\n7. **User Stories Derived**\n - Inferred user stories from the code\n\n8. **Gaps & Recommendations**\n - Missing error handling\n - Undocumented edge cases\n - Suggested improvements\n\nCode Type: ${codeType}\n${featureName ? `Feature: ${featureName}` : ''}`;\n\n const userMessage = `Analyze this code and extract user flows:\n\n\\`\\`\\`\n${code.length > 15000 ? code.substring(0, 15000) + '\\n// ... [truncated]' : code}\n\\`\\`\\`\n\nDocument all user flows with diagrams.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to reverse engineer flows: ${message}`);\n }\n },\n\n requiredScope: 'tools:reverse_engineer_flows',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * generate_test_specs tool - Create comprehensive test specifications\n */\nexport const generateTestSpecsTool: ToolDefinition = {\n tool: {\n name: 'generate_test_specs',\n description: `Generate comprehensive test specifications from requirements or code.\n\nTakes PRD, user stories, or source code and produces:\n- Test plan overview\n- Unit test specifications\n- Integration test scenarios\n- E2E test cases\n- Edge case coverage\n- Test data requirements\n- Accessibility testing checklist\n\nBest for: Ensuring comprehensive test coverage before or during development.`,\n inputSchema: {\n type: 'object',\n properties: {\n input: {\n type: 'string',\n description: 'PRD, user stories, or source code to generate tests from',\n },\n inputType: {\n type: 'string',\n enum: ['prd', 'user_stories', 'code', 'api_spec'],\n default: 'prd',\n description: 'Type of input provided',\n },\n testTypes: {\n type: 'array',\n items: {\n type: 'string',\n enum: ['unit', 'integration', 'e2e', 'api', 'performance', 'security', 'accessibility'],\n },\n default: ['unit', 'integration', 'e2e'],\n description: 'Types of tests to generate',\n },\n framework: {\n type: 'string',\n enum: ['jest', 'vitest', 'pytest', 'playwright', 'cypress', 'generic'],\n default: 'generic',\n description: 'Testing framework for syntax hints',\n },\n coverage: {\n type: 'string',\n enum: ['minimal', 'standard', 'comprehensive'],\n default: 'standard',\n description: 'How thorough the test coverage should be',\n },\n },\n required: ['input'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const input = args.input as string;\n const inputType = (args.inputType as string) || 'prd';\n const testTypes = (args.testTypes as string[]) || ['unit', 'integration', 'e2e'];\n const framework = (args.framework as string) || 'generic';\n const coverage = (args.coverage as string) || 'standard';\n\n if (!input || input.trim().length === 0) {\n return errorResult('Input (PRD, user stories, or code) is required');\n }\n\n const coverageGuide: Record<string, string> = {\n minimal: 'Focus on happy paths and critical functionality only',\n standard: 'Cover happy paths, common edge cases, and error scenarios',\n comprehensive: 'Cover all paths, edge cases, error scenarios, boundary conditions, and negative testing',\n };\n\n const systemPrompt = `You are a QA architect expert at creating comprehensive test specifications.\n\nGenerate test specs from the provided ${inputType}.\n\nTest Types to Include: ${testTypes.join(', ')}\nFramework: ${framework}\nCoverage Level: ${coverageGuide[coverage]}\n\nOutput Sections:\n\n1. **Test Plan Overview**\n - Scope and objectives\n - Test strategy\n - Risk-based prioritization\n\n2. **Unit Tests** (if requested)\n - Function/method level tests\n - Mock requirements\n - Edge cases per function\n ${framework !== 'generic' ? `- ${framework} code snippets` : ''}\n\n3. **Integration Tests** (if requested)\n - Component interaction tests\n - API contract tests\n - Database integration tests\n\n4. **E2E Tests** (if requested)\n - User journey scenarios\n - Critical path coverage\n - Cross-browser/device requirements\n\n5. **API Tests** (if requested)\n - Endpoint coverage\n - Request/response validation\n - Error response testing\n\n6. **Performance Tests** (if requested)\n - Load testing scenarios\n - Response time expectations\n - Concurrent user tests\n\n7. **Security Tests** (if requested)\n - Authentication/authorization tests\n - Input validation tests\n - OWASP considerations\n\n8. **Accessibility Tests** (if requested)\n - WCAG compliance checks\n - Screen reader compatibility\n - Keyboard navigation\n\n9. **Test Data Requirements**\n - Fixtures needed\n - Test user personas\n - Mock data specifications\n\n10. **Acceptance Criteria Traceability**\n - Map each test to a requirement\n - Coverage matrix\n\nFormat each test case as:\n\\`\\`\\`\nTest ID: TC-XXX\nTitle: [Descriptive title]\nPreconditions: [Setup required]\nSteps:\n1. [Action]\n2. [Action]\nExpected Result: [What should happen]\nPriority: High/Medium/Low\n\\`\\`\\``;\n\n const userMessage = `Generate test specifications from this ${inputType}:\n\n${input.length > 12000 ? input.substring(0, 12000) + '\\n... [truncated]' : input}\n\nCreate comprehensive test specs covering: ${testTypes.join(', ')}`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to generate test specs: ${message}`);\n }\n },\n\n requiredScope: 'tools:generate_test_specs',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * explain_codebase tool - Generate comprehensive codebase documentation\n */\nexport const explainCodebaseTool: ToolDefinition = {\n tool: {\n name: 'explain_codebase',\n description: `Analyze code and generate comprehensive documentation for product managers.\n\nTakes source code and produces PM-friendly documentation:\n- Architecture overview\n- Feature inventory\n- Data flow explanations\n- User-facing functionality mapping\n- Technical debt assessment\n- Business logic documentation\n\nBest for: Onboarding PMs to existing codebases or creating technical context.`,\n inputSchema: {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description: 'Source code to analyze and explain',\n },\n projectName: {\n type: 'string',\n description: 'Name of the project',\n },\n codeContext: {\n type: 'string',\n description: 'Additional context about the codebase',\n },\n audience: {\n type: 'string',\n enum: ['pm', 'stakeholder', 'new_engineer', 'executive'],\n default: 'pm',\n description: 'Target audience for the documentation',\n },\n focus: {\n type: 'array',\n items: {\n type: 'string',\n enum: [\n 'architecture',\n 'features',\n 'data_flow',\n 'business_logic',\n 'tech_debt',\n 'dependencies',\n 'security',\n ],\n },\n default: ['architecture', 'features', 'business_logic'],\n description: 'Areas to focus documentation on',\n },\n detailLevel: {\n type: 'string',\n enum: ['overview', 'detailed', 'deep_dive'],\n default: 'detailed',\n description: 'Level of detail in explanations',\n },\n },\n required: ['code'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const code = args.code as string;\n const projectName = args.projectName as string | undefined;\n const codeContext = args.codeContext as string | undefined;\n const audience = (args.audience as string) || 'pm';\n const focus = (args.focus as string[]) || ['architecture', 'features', 'business_logic'];\n const detailLevel = (args.detailLevel as string) || 'detailed';\n\n if (!code || code.trim().length === 0) {\n return errorResult('Source code is required for analysis');\n }\n\n const audienceGuide: Record<string, string> = {\n pm: 'Focus on product features, user value, and business logic. Avoid deep technical jargon.',\n stakeholder: 'High-level overview focusing on capabilities, risks, and business implications.',\n new_engineer: 'Technical detail with onboarding focus. Explain patterns, conventions, and gotchas.',\n executive: 'Strategic summary focusing on capabilities, technical health, and risks.',\n };\n\n const systemPrompt = `You are a staff engineer who excels at explaining complex codebases to non-technical stakeholders.\n\nAnalyze the code and create documentation for: ${audience}\n${audienceGuide[audience]}\n\nDocumentation Focus: ${focus.join(', ')}\nDetail Level: ${detailLevel}\n${projectName ? `Project: ${projectName}` : ''}\n${codeContext ? `Context: ${codeContext}` : ''}\n\nOutput Sections (include based on focus):\n\n1. **Executive Summary**\n - What this code does in plain English\n - Key capabilities\n - Technology stack\n\n2. **Architecture Overview** (if in focus)\n - System diagram (Mermaid)\n - Key components and their roles\n - How pieces fit together\n\n3. **Feature Inventory** (if in focus)\n - List of user-facing features found\n - Feature completeness assessment\n - Hidden/admin features\n\n4. **Data Flow** (if in focus)\n - How data moves through the system\n - Key entities and relationships\n - Data transformations\n\n5. **Business Logic Documentation** (if in focus)\n - Core algorithms explained\n - Business rules implemented\n - Validation and constraints\n\n6. **Technical Debt Assessment** (if in focus)\n - Code quality observations\n - Maintenance concerns\n - Refactoring opportunities\n\n7. **Dependencies** (if in focus)\n - External services used\n - Third-party libraries\n - Integration points\n\n8. **Security Considerations** (if in focus)\n - Authentication/authorization patterns\n - Data protection measures\n - Potential concerns\n\n9. **Glossary**\n - Technical terms explained\n - Domain-specific vocabulary\n\nGuidelines:\n- Use analogies for complex concepts\n- Include \"What this means for product\" sections\n- Highlight risks and opportunities\n- Be honest about limitations and unknowns`;\n\n const userMessage = `Analyze and document this codebase:\n\n\\`\\`\\`\n${code.length > 15000 ? code.substring(0, 15000) + '\\n// ... [truncated]' : code}\n\\`\\`\\`\n\nCreate comprehensive documentation for a ${audience}.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to explain codebase: ${message}`);\n }\n },\n\n requiredScope: 'tools:explain_codebase',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * validate_implementation tool - Check code against requirements\n */\nexport const validateImplementationTool: ToolDefinition = {\n tool: {\n name: 'validate_implementation',\n description: `Validate that code implementation matches requirements.\n\nCompares source code against PRD/requirements and produces:\n- Requirements coverage report\n- Gap analysis\n- Deviation documentation\n- Compliance checklist\n- Acceptance criteria verification\n\nBest for: Pre-release validation and QA support.`,\n inputSchema: {\n type: 'object',\n properties: {\n requirements: {\n type: 'string',\n description: 'PRD, user stories, or requirements to validate against',\n },\n code: {\n type: 'string',\n description: 'Implementation code to validate',\n },\n strictness: {\n type: 'string',\n enum: ['lenient', 'standard', 'strict'],\n default: 'standard',\n description: 'How strictly to validate',\n },\n checkTypes: {\n type: 'array',\n items: {\n type: 'string',\n enum: [\n 'functional',\n 'edge_cases',\n 'error_handling',\n 'performance',\n 'security',\n 'accessibility',\n 'ux',\n ],\n },\n default: ['functional', 'edge_cases', 'error_handling'],\n description: 'Types of validation to perform',\n },\n },\n required: ['requirements', 'code'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const requirements = args.requirements as string;\n const code = args.code as string;\n const strictness = (args.strictness as string) || 'standard';\n const checkTypes = (args.checkTypes as string[]) || [\n 'functional',\n 'edge_cases',\n 'error_handling',\n ];\n\n if (!requirements || requirements.trim().length === 0) {\n return errorResult('Requirements are required for validation');\n }\n\n if (!code || code.trim().length === 0) {\n return errorResult('Code is required for validation');\n }\n\n const strictnessGuide: Record<string, string> = {\n lenient:\n 'Accept reasonable interpretations. Flag only clear deviations from requirements.',\n standard:\n 'Check for requirement coverage and reasonable edge case handling. Flag gaps and concerns.',\n strict:\n 'Exact requirement matching. Every stated requirement must be verifiably implemented. Flag any ambiguity.',\n };\n\n const systemPrompt = `You are a QA lead expert at validating implementations against requirements.\n\nCompare the code against the requirements and produce a validation report.\n\nStrictness: ${strictnessGuide[strictness]}\nValidation Types: ${checkTypes.join(', ')}\n\nOutput Sections:\n\n1. **Validation Summary**\n - Overall Score (0-100%)\n - Verdict: Pass / Pass with Concerns / Fail\n - Critical issues count\n\n2. **Requirements Coverage Matrix**\n | Requirement | Status | Evidence | Notes |\n |-------------|--------|----------|-------|\n | REQ-1 | ✅ Met | Line 42 | - |\n | REQ-2 | ⚠️ Partial | - | Missing edge case |\n | REQ-3 | ❌ Not Met | - | Not implemented |\n\n3. **Functional Validation** (if checked)\n - Each requirement with implementation evidence\n - Quote code that implements each requirement\n\n4. **Edge Case Coverage** (if checked)\n - Expected edge cases from requirements\n - Which are handled in code\n - Which are missing\n\n5. **Error Handling Review** (if checked)\n - Error scenarios from requirements\n - Implementation of each\n - Missing error handling\n\n6. **Performance Validation** (if checked)\n - Performance requirements stated\n - Code patterns that address them\n - Potential performance issues\n\n7. **Security Validation** (if checked)\n - Security requirements stated\n - Implementation verification\n - Security concerns found\n\n8. **Accessibility Validation** (if checked)\n - A11y requirements stated\n - Implementation verification\n - Missing accessibility features\n\n9. **UX Validation** (if checked)\n - UX requirements stated\n - Implementation verification\n - UX concerns\n\n10. **Gaps & Deviations**\n - Requirements not implemented\n - Implementations that deviate from requirements\n - Over-engineering concerns\n\n11. **Recommendations**\n - Prioritized list of issues to fix\n - Suggestions for improvement\n\n12. **Acceptance Criteria Checklist**\n - [ ] Criterion 1: Status\n - [ ] Criterion 2: Status`;\n\n // Truncate inputs if too long\n const reqTrunc =\n requirements.length > 8000\n ? requirements.substring(0, 8000) + '\\n... [truncated]'\n : requirements;\n const codeTrunc =\n code.length > 10000 ? code.substring(0, 10000) + '\\n// ... [truncated]' : code;\n\n const userMessage = `Validate this implementation against the requirements:\n\n## Requirements\n${reqTrunc}\n\n## Implementation Code\n\\`\\`\\`\n${codeTrunc}\n\\`\\`\\`\n\nProduce a comprehensive validation report.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to validate implementation: ${message}`);\n }\n },\n\n requiredScope: 'tools:validate_implementation',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * suggest_refactors tool - Identify refactoring opportunities\n */\nexport const suggestRefactorsTool: ToolDefinition = {\n tool: {\n name: 'suggest_refactors',\n description: `Analyze code and suggest refactoring opportunities for product planning.\n\nTakes source code and identifies:\n- Technical debt items\n- Refactoring opportunities\n- Architecture improvements\n- Performance optimizations\n- Maintainability issues\n\nProduces PM-friendly documentation for sprint planning.\n\nBest for: Technical debt prioritization and architecture evolution planning.`,\n inputSchema: {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description: 'Source code to analyze for refactoring opportunities',\n },\n codeContext: {\n type: 'string',\n description: 'Context about the codebase or feature',\n },\n priorities: {\n type: 'array',\n items: {\n type: 'string',\n enum: [\n 'performance',\n 'maintainability',\n 'scalability',\n 'security',\n 'testing',\n 'readability',\n ],\n },\n default: ['maintainability', 'performance'],\n description: 'What to prioritize in suggestions',\n },\n riskTolerance: {\n type: 'string',\n enum: ['low', 'medium', 'high'],\n default: 'medium',\n description: 'Risk tolerance for suggested changes',\n },\n teamSize: {\n type: 'string',\n enum: ['small', 'medium', 'large'],\n default: 'medium',\n description: 'Team size context for effort estimates',\n },\n },\n required: ['code'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const code = args.code as string;\n const codeContext = args.codeContext as string | undefined;\n const priorities = (args.priorities as string[]) || ['maintainability', 'performance'];\n const riskTolerance = (args.riskTolerance as string) || 'medium';\n const teamSize = (args.teamSize as string) || 'medium';\n\n if (!code || code.trim().length === 0) {\n return errorResult('Source code is required for analysis');\n }\n\n const riskGuide: Record<string, string> = {\n low: 'Only suggest low-risk, incremental improvements. No major restructuring.',\n medium: 'Balance impact with risk. Include moderate restructuring where beneficial.',\n high: 'Include high-impact architectural changes. Transformative improvements acceptable.',\n };\n\n const systemPrompt = `You are a staff engineer specializing in code quality and technical debt management.\n\nAnalyze the code and suggest refactoring opportunities.\n\nPriorities: ${priorities.join(', ')}\nRisk Tolerance: ${riskGuide[riskTolerance]}\nTeam Context: ${teamSize} team\n${codeContext ? `Context: ${codeContext}` : ''}\n\nOutput Sections:\n\n1. **Executive Summary**\n - Overall code health score (1-10)\n - Top 3 priorities\n - Estimated total refactoring effort\n\n2. **Quick Wins** (Low effort, immediate impact)\n For each:\n - Issue description\n - Impact: [Performance/Maintainability/etc.]\n - Effort: Small\n - Risk: Low\n - Code location hint\n - Suggested approach\n\n3. **Medium-Term Improvements** (Moderate effort)\n For each:\n - Issue description\n - Business impact (why PM should care)\n - Effort: Medium (sprint-sized)\n - Risk assessment\n - Dependencies\n - Suggested approach\n\n4. **Strategic Refactors** (Significant effort)\n For each:\n - Current state and problem\n - Target state and benefits\n - Business justification\n - Effort: Large (multi-sprint)\n - Risk and mitigation\n - Incremental approach\n\n5. **Technical Debt Inventory**\n | Item | Type | Severity | Effort | Risk | Priority |\n |------|------|----------|--------|------|----------|\n\n6. **Anti-Patterns Identified**\n - Pattern name\n - Where found\n - Why it's problematic\n - Recommended pattern\n\n7. **Testing Debt**\n - Missing test coverage areas\n - Suggested testing improvements\n\n8. **Dependency Concerns**\n - Outdated dependencies\n - Security vulnerabilities risk\n - Upgrade recommendations\n\n9. **Sprint Planning Recommendations**\n - Suggested sprint allocation for tech debt\n - Recommended sequence of refactors\n - What to pair with feature work\n\n10. **Business Case Summary**\n - PM-friendly explanation of why these matter\n - Risk of not addressing\n - Velocity impact\n\nGuidelines:\n- Frame everything in terms of business impact\n- Provide concrete before/after examples where helpful\n- Consider incremental approaches\n- Note any blockers or dependencies`;\n\n const userMessage = `Analyze this code and suggest refactoring opportunities:\n\n\\`\\`\\`\n${code.length > 15000 ? code.substring(0, 15000) + '\\n// ... [truncated]' : code}\n\\`\\`\\`\n\nProvide comprehensive refactoring suggestions for sprint planning.`;\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to suggest refactors: ${message}`);\n }\n },\n\n requiredScope: 'tools:suggest_refactors',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { jsonResult, markdownResult, errorResult } from './types.js';\nimport { createCompletion, createJsonCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\ninterface OpenAPISpec {\n openapi: string;\n info: {\n title: string;\n version: string;\n description: string;\n };\n servers: Array<{ url: string; description: string }>;\n paths: Record<string, object>;\n components: {\n schemas: Record<string, object>;\n securitySchemes?: Record<string, object>;\n };\n security?: Array<Record<string, string[]>>;\n tags?: Array<{ name: string; description: string }>;\n}\n\ninterface ApiDocsOutput {\n format: string;\n spec: OpenAPISpec | object;\n summary: string;\n endpoints: number;\n}\n\n/**\n * generate_api_docs tool - Generate API documentation from code\n */\nexport const generateApiDocsTool: ToolDefinition = {\n tool: {\n name: 'generate_api_docs',\n description: `Generate API documentation from source code.\n\nAnalyzes API routes and generates:\n- OpenAPI 3.1 specification\n- Endpoint summaries\n- Request/response schemas\n- Authentication requirements\n- Example payloads\n\nSupports REST APIs in TypeScript/JavaScript, Python, Go, and more.\n\nBest for: Creating or updating API documentation from code.`,\n inputSchema: {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description: 'API route code to analyze (routes, controllers, handlers)',\n },\n framework: {\n type: 'string',\n enum: ['nextjs', 'express', 'fastify', 'hono', 'flask', 'fastapi', 'gin', 'generic'],\n default: 'generic',\n description: 'API framework being used',\n },\n format: {\n type: 'string',\n enum: ['openapi', 'markdown', 'both'],\n default: 'openapi',\n description: 'Output documentation format',\n },\n baseUrl: {\n type: 'string',\n description: 'Base URL for the API',\n },\n title: {\n type: 'string',\n description: 'API title for documentation',\n },\n version: {\n type: 'string',\n default: '1.0.0',\n description: 'API version',\n },\n includeExamples: {\n type: 'boolean',\n default: true,\n description: 'Whether to generate example payloads',\n },\n },\n required: ['code'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const code = args.code as string;\n const framework = (args.framework as string) || 'generic';\n const format = (args.format as string) || 'openapi';\n const baseUrl = (args.baseUrl as string) || 'https://api.example.com';\n const title = (args.title as string) || 'API Documentation';\n const version = (args.version as string) || '1.0.0';\n const includeExamples = args.includeExamples !== false;\n\n if (!code || code.trim().length === 0) {\n return errorResult('API code is required for documentation generation');\n }\n\n const frameworkHints: Record<string, string> = {\n nextjs: 'Next.js App Router with route.ts files. Look for GET, POST, PUT, DELETE, PATCH exports.',\n express: 'Express.js with app.get(), app.post(), router patterns.',\n fastify: 'Fastify with fastify.get(), schema definitions.',\n hono: 'Hono framework with app.get(), c.json() patterns.',\n flask: 'Flask with @app.route decorators.',\n fastapi: 'FastAPI with @app.get() decorators and Pydantic models.',\n gin: 'Gin framework with r.GET(), r.POST() patterns.',\n generic: 'Generic API code - infer patterns from the code.',\n };\n\n const systemPrompt = `You are an API documentation expert who generates OpenAPI 3.1 specifications from code.\n\nFramework: ${framework}\n${frameworkHints[framework]}\n\nGenerate a complete OpenAPI 3.1 specification with:\n1. All endpoints with methods (GET, POST, PUT, DELETE, PATCH)\n2. Path parameters extracted from route patterns\n3. Query parameters from code analysis\n4. Request body schemas from TypeScript types or validation\n5. Response schemas for success and error cases\n6. Authentication requirements if detected\n7. Logical grouping with tags\n${includeExamples ? '8. Realistic example values for all schemas' : ''}\n\nOutput a JSON object with:\n{\n \"openapi\": \"3.1.0\",\n \"info\": { \"title\": \"${title}\", \"version\": \"${version}\", \"description\": \"...\" },\n \"servers\": [{ \"url\": \"${baseUrl}\", \"description\": \"...\" }],\n \"paths\": { \"/path\": { \"get\": {...}, \"post\": {...} } },\n \"components\": { \"schemas\": {...}, \"securitySchemes\": {...} },\n \"tags\": [{ \"name\": \"...\", \"description\": \"...\" }]\n}\n\nBe thorough - extract every endpoint, parameter, and type from the code.`;\n\n const userMessage = `Generate OpenAPI documentation from this ${framework} API code:\n\n\\`\\`\\`\n${code.length > 15000 ? code.substring(0, 15000) + '\\n// ... [truncated]' : code}\n\\`\\`\\`\n\nGenerate complete OpenAPI 3.1 specification.`;\n\n try {\n if (format === 'markdown') {\n // Generate markdown documentation\n const mdPrompt = `You are an API documentation expert. Generate clear, comprehensive markdown API documentation.\n\nInclude:\n1. Overview and authentication\n2. Each endpoint with method, path, description\n3. Parameters table (name, type, required, description)\n4. Request body examples\n5. Response examples\n6. Error codes\n\nFramework: ${framework}`;\n\n const result = await createCompletion({\n systemPrompt: mdPrompt,\n userMessage: `Document this API:\\n\\n\\`\\`\\`\\n${code.length > 12000 ? code.substring(0, 12000) + '\\n// ...' : code}\\n\\`\\`\\``,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n return markdownResult(result.text, result.inputTokens + result.outputTokens);\n }\n\n // Generate OpenAPI spec\n const result = await createJsonCompletion<ApiDocsOutput>({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 6000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n if (format === 'both') {\n // Also generate markdown summary\n const mdResult = await createCompletion({\n systemPrompt: 'Summarize this OpenAPI spec as readable markdown documentation.',\n userMessage: JSON.stringify(result.data, null, 2),\n model: 'fast',\n maxTokens: 2000,\n });\n\n return {\n content: [\n {\n type: 'text',\n text: `# ${title}\\n\\n${mdResult.text}\\n\\n---\\n\\n## OpenAPI Specification\\n\\n\\`\\`\\`json\\n${JSON.stringify(result.data, null, 2)}\\n\\`\\`\\``,\n },\n ],\n tokensUsed: totalTokens + mdResult.inputTokens + mdResult.outputTokens,\n };\n }\n\n return jsonResult(result.data, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to generate API docs: ${message}`);\n }\n },\n\n requiredScope: 'tools:generate_api_docs',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * dependency_audit tool - Audit project dependencies\n */\nexport const dependencyAuditTool: ToolDefinition = {\n tool: {\n name: 'dependency_audit',\n description: `Audit project dependencies for security, updates, and health.\n\nAnalyzes package.json, requirements.txt, go.mod, or similar and provides:\n- Security vulnerability assessment\n- Outdated package identification\n- License compliance check\n- Bundle size impact analysis\n- Maintenance health scores\n- Upgrade recommendations with breaking change warnings\n\nBest for: Pre-release dependency review and security audits.`,\n inputSchema: {\n type: 'object',\n properties: {\n manifest: {\n type: 'string',\n description: 'Dependency manifest content (package.json, requirements.txt, etc.)',\n },\n lockfile: {\n type: 'string',\n description: 'Optional lockfile content for version pinning analysis',\n },\n manifestType: {\n type: 'string',\n enum: ['npm', 'yarn', 'pnpm', 'pip', 'poetry', 'go', 'cargo', 'maven', 'gradle'],\n default: 'npm',\n description: 'Package manager type',\n },\n checkTypes: {\n type: 'array',\n items: {\n type: 'string',\n enum: ['security', 'updates', 'licenses', 'maintenance', 'size', 'duplicates'],\n },\n default: ['security', 'updates', 'maintenance'],\n description: 'Types of checks to perform',\n },\n severity: {\n type: 'string',\n enum: ['all', 'moderate', 'high', 'critical'],\n default: 'moderate',\n description: 'Minimum severity level to report',\n },\n },\n required: ['manifest'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const manifest = args.manifest as string;\n const lockfile = args.lockfile as string | undefined;\n const manifestType = (args.manifestType as string) || 'npm';\n const checkTypes = (args.checkTypes as string[]) || ['security', 'updates', 'maintenance'];\n const severity = (args.severity as string) || 'moderate';\n\n if (!manifest || manifest.trim().length === 0) {\n return errorResult('Dependency manifest is required');\n }\n\n const severityLevels: Record<string, string> = {\n all: 'Report all issues including informational',\n moderate: 'Report moderate severity and above',\n high: 'Report only high and critical issues',\n critical: 'Report only critical issues',\n };\n\n const systemPrompt = `You are a security-focused DevOps engineer performing a comprehensive dependency audit.\n\nPackage Manager: ${manifestType}\nCheck Types: ${checkTypes.join(', ')}\nSeverity Threshold: ${severityLevels[severity]}\n\nProvide a thorough audit report with:\n\n1. **Executive Summary**\n - Overall health score (A-F)\n - Critical issues count\n - Recommended actions\n\n2. **Security Vulnerabilities** (if checked)\n | Package | Version | Vulnerability | Severity | CVE | Fix Version |\n |---------|---------|---------------|----------|-----|-------------|\n - Include known CVEs where applicable\n - Note if no known vulnerabilities\n\n3. **Outdated Packages** (if checked)\n | Package | Current | Latest | Type | Breaking Changes |\n |---------|---------|--------|------|------------------|\n - Distinguish patch, minor, major updates\n - Flag breaking changes in major updates\n\n4. **License Compliance** (if checked)\n | Package | License | Risk Level | Notes |\n |---------|---------|------------|-------|\n - Flag copyleft licenses (GPL, AGPL)\n - Note license compatibility issues\n\n5. **Maintenance Health** (if checked)\n | Package | Last Update | Weekly Downloads | Issues | Health |\n |---------|-------------|------------------|--------|--------|\n - Flag abandoned packages (>2 years no update)\n - Note packages with many open issues\n\n6. **Size Impact** (if checked)\n | Package | Size | Gzipped | Alternatives |\n |---------|------|---------|--------------|\n - Identify heavy dependencies\n - Suggest lighter alternatives\n\n7. **Duplicate Dependencies** (if checked)\n - Identify packages included multiple times\n - Note version conflicts\n\n8. **Recommendations**\n - Prioritized list of actions\n - Safe upgrade paths\n - Packages to consider replacing\n\nBase your analysis on common knowledge about popular packages. Be conservative with security assessments - note when you're uncertain.`;\n\n let userMessage = `Audit these dependencies:\n\n## Manifest (${manifestType})\n\\`\\`\\`\n${manifest.length > 10000 ? manifest.substring(0, 10000) + '\\n... [truncated]' : manifest}\n\\`\\`\\``;\n\n if (lockfile) {\n userMessage += `\\n\\n## Lockfile\\n\\`\\`\\`\\n${lockfile.length > 5000 ? lockfile.substring(0, 5000) + '\\n... [truncated]' : lockfile}\\n\\`\\`\\``;\n }\n\n userMessage += '\\n\\nProvide a comprehensive dependency audit.';\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to audit dependencies: ${message}`);\n }\n },\n\n requiredScope: 'tools:dependency_audit',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolDefinition } from './types.js';\nimport { markdownResult, errorResult } from './types.js';\nimport { createCompletion } from '../ai/client.js';\nimport type { ValidationResult } from '../middleware/auth.js';\n\n/**\n * estimate_migration tool - Estimate migration effort\n */\nexport const estimateMigrationTool: ToolDefinition = {\n tool: {\n name: 'estimate_migration',\n description: `Estimate the effort required for a code migration or major upgrade.\n\nAnalyzes current code and target state to provide:\n- Effort estimation (story points, days)\n- Risk assessment\n- Breaking changes analysis\n- Migration path recommendations\n- Rollback strategy\n\nSupports: Framework upgrades, language migrations, architecture changes, dependency updates.\n\nBest for: Sprint planning for major technical initiatives.`,\n inputSchema: {\n type: 'object',\n properties: {\n currentCode: {\n type: 'string',\n description: 'Current codebase sample to analyze',\n },\n migrationType: {\n type: 'string',\n enum: [\n 'framework_upgrade',\n 'language_migration',\n 'architecture_change',\n 'dependency_upgrade',\n 'database_migration',\n 'cloud_migration',\n 'monolith_to_microservices',\n 'other',\n ],\n description: 'Type of migration being planned',\n },\n from: {\n type: 'string',\n description: 'Current technology/version (e.g., \"React 17\", \"Python 2.7\")',\n },\n to: {\n type: 'string',\n description: 'Target technology/version (e.g., \"React 18\", \"Python 3.11\")',\n },\n codebaseSize: {\n type: 'string',\n enum: ['small', 'medium', 'large', 'enterprise'],\n default: 'medium',\n description: 'Approximate codebase size',\n },\n teamSize: {\n type: 'number',\n default: 3,\n description: 'Number of developers available for migration',\n },\n constraints: {\n type: 'string',\n description: 'Any constraints (timeline, budget, parallel development)',\n },\n },\n required: ['migrationType', 'from', 'to'],\n },\n } as Tool,\n\n handler: async (args: Record<string, unknown>, validation: ValidationResult) => {\n const currentCode = args.currentCode as string | undefined;\n const migrationType = args.migrationType as string;\n const from = args.from as string;\n const to = args.to as string;\n const codebaseSize = (args.codebaseSize as string) || 'medium';\n const teamSize = (args.teamSize as number) || 3;\n const constraints = args.constraints as string | undefined;\n\n if (!migrationType || !from || !to) {\n return errorResult('Migration type, from, and to are required');\n }\n\n const sizeMultipliers: Record<string, string> = {\n small: '<10k LOC, few dependencies',\n medium: '10k-50k LOC, moderate complexity',\n large: '50k-200k LOC, many integrations',\n enterprise: '>200k LOC, complex architecture',\n };\n\n const systemPrompt = `You are a senior technical architect who specializes in migration planning.\n\nEstimate the effort for migrating from \"${from}\" to \"${to}\".\n\nMigration Type: ${migrationType}\nCodebase Size: ${codebaseSize} (${sizeMultipliers[codebaseSize]})\nTeam Size: ${teamSize} developers\n${constraints ? `Constraints: ${constraints}` : ''}\n\nProvide a comprehensive migration estimate with:\n\n1. **Executive Summary**\n - Total estimated effort (story points and calendar time)\n - Risk level (Low/Medium/High/Critical)\n - Recommended approach (Big bang / Incremental / Strangler fig)\n\n2. **Effort Breakdown**\n | Phase | Tasks | Story Points | Calendar Days | Parallel? |\n |-------|-------|--------------|---------------|-----------|\n - Phase 1: Assessment & Planning\n - Phase 2: Infrastructure Setup\n - Phase 3: Code Migration\n - Phase 4: Testing & Validation\n - Phase 5: Deployment & Cutover\n\n3. **Breaking Changes Analysis**\n | Area | Impact | Effort | Notes |\n |------|--------|--------|-------|\n - API changes\n - Dependency updates\n - Configuration changes\n - Data format changes\n\n4. **Risk Assessment**\n | Risk | Probability | Impact | Mitigation |\n |------|-------------|--------|------------|\n\n5. **Migration Path**\n - Step-by-step migration strategy\n - Dependencies between steps\n - Parallel work opportunities\n\n6. **Testing Strategy**\n - Unit test updates needed\n - Integration test requirements\n - Performance benchmarking\n - Regression testing approach\n\n7. **Rollback Strategy**\n - Feature flags approach\n - Database rollback plan\n - Traffic shifting strategy\n\n8. **Resource Requirements**\n - Skills needed\n - Infrastructure for parallel environments\n - Tools and automation\n\n9. **Assumptions & Caveats**\n - What could change the estimate\n - Unknown risks\n\n10. **Sprint Breakdown** (for ${teamSize} developers)\n - Sprint 1: ...\n - Sprint 2: ...\n - etc.\n\nBe realistic and include buffer for unknowns. Better to overestimate than underestimate.`;\n\n let userMessage = `Estimate migration effort for:\n\n**From:** ${from}\n**To:** ${to}\n**Type:** ${migrationType}`;\n\n if (currentCode) {\n userMessage += `\\n\\n**Sample of Current Code:**\\n\\`\\`\\`\\n${currentCode.length > 8000 ? currentCode.substring(0, 8000) + '\\n// ...' : currentCode}\\n\\`\\`\\``;\n }\n\n userMessage += '\\n\\nProvide a comprehensive migration estimate.';\n\n try {\n const result = await createCompletion({\n systemPrompt,\n userMessage,\n model: 'balanced',\n maxTokens: 5000,\n });\n\n const totalTokens = result.inputTokens + result.outputTokens;\n\n return markdownResult(result.text, totalTokens);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return errorResult(`Failed to estimate migration: ${message}`);\n }\n },\n\n requiredScope: 'tools:estimate_migration',\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolHandler, ToolDefinition } from './types.js';\n\n// Import all tool definitions\nimport { explodeBacklogTool } from './explode-backlog.js';\nimport { inferPrdTool } from './infer-prd.js';\nimport { synthesizePrdTool } from './synthesize-prd.js';\nimport { generateArchitectureTool } from './generate-architecture.js';\nimport { handoffPackageTool } from './handoff-package.js';\nimport { synthesizeRequirementsTool } from './synthesize-requirements.js';\nimport { reviewPrdTool } from './review-prd.js';\nimport { syncToTrackerTool } from './sync-to-tracker.js';\nimport { reverseEngineerFlowsTool } from './reverse-engineer-flows.js';\nimport { generateTestSpecsTool } from './generate-test-specs.js';\nimport { explainCodebaseTool } from './explain-codebase.js';\nimport { validateImplementationTool } from './validate-implementation.js';\nimport { suggestRefactorsTool } from './suggest-refactors.js';\nimport { generateApiDocsTool } from './generate-api-docs.js';\nimport { dependencyAuditTool } from './dependency-audit.js';\nimport { estimateMigrationTool } from './estimate-migration.js';\n\n// Register all tools\nconst toolDefinitions: ToolDefinition[] = [\n // Phase 3: Initial tools\n explodeBacklogTool,\n inferPrdTool,\n synthesizePrdTool,\n generateArchitectureTool,\n handoffPackageTool,\n // Phase 4: Additional PM tools\n synthesizeRequirementsTool,\n reviewPrdTool,\n syncToTrackerTool,\n // Phase 5: Code-first tools\n reverseEngineerFlowsTool,\n generateTestSpecsTool,\n explainCodebaseTool,\n validateImplementationTool,\n suggestRefactorsTool,\n // Phase 6: Advanced tools\n generateApiDocsTool,\n dependencyAuditTool,\n estimateMigrationTool,\n];\n\n// Export tools array for MCP server\nexport const tools: Tool[] = toolDefinitions.map((t) => t.tool);\n\n// Export handlers map for MCP server\nexport const toolHandlers: Record<string, ToolHandler> = Object.fromEntries(\n toolDefinitions.map((t) => [t.tool.name, t.handler])\n);\n\n// Export individual tools for testing\nexport {\n explodeBacklogTool,\n inferPrdTool,\n synthesizePrdTool,\n generateArchitectureTool,\n handoffPackageTool,\n synthesizeRequirementsTool,\n reviewPrdTool,\n syncToTrackerTool,\n reverseEngineerFlowsTool,\n generateTestSpecsTool,\n explainCodebaseTool,\n validateImplementationTool,\n suggestRefactorsTool,\n generateApiDocsTool,\n dependencyAuditTool,\n estimateMigrationTool,\n};\n\n// Export types\nexport type { ToolHandler, ToolDefinition, ToolResult } from './types.js';\nexport { textResult, jsonResult, errorResult, markdownResult } from './types.js';\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ErrorCode,\n McpError,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { validateApiKey } from './middleware/auth.js';\nimport { trackUsage } from './middleware/usage.js';\nimport { checkRateLimit } from './middleware/rate-limit.js';\nimport { tools, toolHandlers } from './tools/index.js';\n\nconst VERSION = '0.1.1';\n\nconst server = new Server(\n {\n name: 'vaspera-pm',\n version: VERSION,\n },\n {\n capabilities: {\n tools: {},\n },\n }\n);\n\n// List available tools\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return { tools };\n});\n\n// Handle tool calls\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n // Extract API key from environment or args\n const apiKey = process.env.VASPERA_API_KEY || (args as Record<string, unknown>)?._apiKey as string | undefined;\n\n // Validate API key\n const validation = await validateApiKey(apiKey);\n if (!validation.valid) {\n return {\n content: [{ type: 'text', text: `Authentication failed: ${validation.error?.message || 'Invalid API key'}` }],\n isError: true,\n };\n }\n\n // Check rate limit\n const rateCheck = await checkRateLimit(validation.userId!, validation.tier!);\n if (!rateCheck.allowed) {\n return {\n content: [{ type: 'text', text: `Rate limit exceeded. ${rateCheck.remaining} calls remaining. Resets at ${rateCheck.resetsAt?.toISOString()}` }],\n isError: true,\n };\n }\n\n // Check quota\n if (validation.quota && validation.quota.remaining <= 0) {\n return {\n content: [{ type: 'text', text: `Monthly quota exceeded. Upgrade your plan for more API calls.` }],\n isError: true,\n };\n }\n\n // Execute tool\n const startTime = Date.now();\n let result;\n let success = true;\n let errorCode: string | undefined;\n let tokensUsed = 0;\n\n try {\n const handler = toolHandlers[name];\n if (!handler) {\n throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);\n }\n\n // Remove internal _apiKey from args before passing to handler\n const cleanArgs = { ...args as Record<string, unknown> };\n delete cleanArgs._apiKey;\n\n const toolResult = await handler(cleanArgs, validation);\n result = toolResult.content;\n tokensUsed = toolResult.tokensUsed || 0;\n } catch (error) {\n success = false;\n errorCode = error instanceof McpError ? error.code.toString() : 'TOOL_ERROR';\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n result = [{ type: 'text' as const, text: `Error: ${errorMessage}` }];\n }\n\n const latencyMs = Date.now() - startTime;\n\n // Track usage asynchronously\n trackUsage({\n userId: validation.userId!,\n apiKeyId: validation.apiKeyId!,\n toolName: name,\n tokensUsed,\n latencyMs,\n success,\n errorCode,\n metadata: { args: sanitizeArgs(args as Record<string, unknown>) },\n }).catch((err) => {\n console.error('Failed to track usage:', err);\n });\n\n return {\n content: result,\n isError: !success,\n };\n});\n\n// Sanitize args for logging (remove sensitive data)\nfunction sanitizeArgs(args: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!args) return {};\n\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (key.toLowerCase().includes('key') || key.toLowerCase().includes('secret') || key.toLowerCase().includes('token')) {\n sanitized[key] = '[REDACTED]';\n } else if (typeof value === 'string' && value.length > 500) {\n sanitized[key] = value.substring(0, 500) + '...[truncated]';\n } else {\n sanitized[key] = value;\n }\n }\n return sanitized;\n}\n\n// Start server (exported for CLI)\nexport async function startServer(): Promise<void> {\n const transport = new StdioServerTransport();\n await server.connect(transport);\n console.error(`VasperaPM MCP Server v${VERSION} running`);\n}\n\n// Allow direct execution\nif (import.meta.url === `file://${process.argv[1]}`) {\n startServer().catch((error) => {\n console.error('Failed to start MCP server:', error);\n process.exit(1);\n });\n}\n","#!/usr/bin/env node\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { createInterface } from 'readline';\n\n// ASCII Art Banner\nconst BANNER = `\n\\x1b[36m╔═══════════════════════════════════════════════════════════════╗\n║ ║\n║ ██╗ ██╗ █████╗ ███████╗██████╗ ███████╗██████╗ █████╗ ║\n║ ██║ ██║██╔══██╗██╔════╝██╔══██╗██╔════╝██╔══██╗██╔══██╗ ║\n║ ██║ ██║███████║███████╗██████╔╝█████╗ ██████╔╝███████║ ║\n║ ╚██╗ ██╔╝██╔══██║╚════██║██╔═══╝ ██╔══╝ ██╔══██╗██╔══██║ ║\n║ ╚████╔╝ ██║ ██║███████║██║ ███████╗██║ ██║██║ ██║ ║\n║ ╚═══╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ║\n║ ║\n║ \\x1b[33mAI-Powered Product Management\\x1b[36m ║\n║ ║\n╚═══════════════════════════════════════════════════════════════╝\\x1b[0m\n`;\n\nconst VERSION = '0.1.1';\n\nconst HELP = `\n\\x1b[1mUsage:\\x1b[0m vasperapm <command> [options]\n\n\\x1b[1mCommands:\\x1b[0m\n \\x1b[32minstall\\x1b[0m Configure VasperaPM with Claude Code\n \\x1b[32mconnect\\x1b[0m Set up your API key and integrations\n \\x1b[32mserve\\x1b[0m Start the MCP server (used by Claude Code)\n \\x1b[32mstatus\\x1b[0m Check your current configuration\n \\x1b[32mhelp\\x1b[0m Show this help message\n\n\\x1b[1mExamples:\\x1b[0m\n $ vasperapm install # Set up VasperaPM with Claude Code\n $ vasperapm connect # Configure API key interactively\n $ vasperapm status # Check configuration status\n\n\\x1b[1mDocumentation:\\x1b[0m\n https://github.com/rcolkitt/VasperaPM\n\n\\x1b[1mGet an API Key:\\x1b[0m\n https://vasperapm.com/dashboard\n`;\n\n// Get Claude config path\nfunction getClaudeConfigPath(): string {\n return join(homedir(), '.claude', 'claude_desktop_config.json');\n}\n\n// Get VasperaPM config path\nfunction getVasperaConfigPath(): string {\n return join(homedir(), '.vasperapm', 'config.json');\n}\n\n// Read JSON file safely\nfunction readJsonFile(path: string): Record<string, unknown> | null {\n try {\n if (!existsSync(path)) return null;\n return JSON.parse(readFileSync(path, 'utf-8'));\n } catch {\n return null;\n }\n}\n\n// Write JSON file safely\nfunction writeJsonFile(path: string, data: Record<string, unknown>): void {\n const dir = path.substring(0, path.lastIndexOf('/'));\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n writeFileSync(path, JSON.stringify(data, null, 2));\n}\n\n// Prompt for input\nfunction prompt(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\n// Print success message\nfunction success(message: string): void {\n console.log(`\\x1b[32m✓\\x1b[0m ${message}`);\n}\n\n// Print error message\nfunction error(message: string): void {\n console.log(`\\x1b[31m✗\\x1b[0m ${message}`);\n}\n\n// Print info message\nfunction info(message: string): void {\n console.log(`\\x1b[36mℹ\\x1b[0m ${message}`);\n}\n\n// Print warning message\nfunction warn(message: string): void {\n console.log(`\\x1b[33m⚠\\x1b[0m ${message}`);\n}\n\n// Install command - Configure Claude Code\nasync function install(): Promise<void> {\n console.log(BANNER);\n console.log('\\x1b[1mInstalling VasperaPM for Claude Code...\\x1b[0m\\n');\n\n const configPath = getClaudeConfigPath();\n let config = readJsonFile(configPath) as { mcpServers?: Record<string, unknown> } | null;\n\n if (!config) {\n config = { mcpServers: {} };\n info('Creating Claude Code configuration...');\n }\n\n if (!config.mcpServers) {\n config.mcpServers = {};\n }\n\n // Check if already installed\n if (config.mcpServers['vaspera-pm']) {\n warn('VasperaPM is already installed in Claude Code.');\n const answer = await prompt('\\nDo you want to reinstall? (y/N): ');\n if (answer.toLowerCase() !== 'y') {\n info('Installation cancelled.');\n return;\n }\n }\n\n // Get API key\n const vasperaConfig = readJsonFile(getVasperaConfigPath()) as { apiKey?: string } | null;\n let apiKey = vasperaConfig?.apiKey || process.env.VASPERA_API_KEY || '';\n\n if (!apiKey) {\n console.log('\\n\\x1b[1mAPI Key Setup\\x1b[0m');\n console.log('Get your API key at: \\x1b[36mhttps://vasperapm.com/dashboard\\x1b[0m\\n');\n apiKey = await prompt('Enter your VasperaPM API key (or press Enter to use test mode): ');\n\n if (!apiKey) {\n apiKey = 'vpm_test_local_development_key_for_testing';\n info('Using test mode API key (limited features)');\n }\n }\n\n // Add VasperaPM to Claude config\n config.mcpServers['vaspera-pm'] = {\n command: 'vasperapm',\n args: ['serve'],\n env: {\n VASPERA_API_KEY: apiKey,\n NODE_ENV: apiKey.includes('test') ? 'development' : 'production',\n },\n };\n\n writeJsonFile(configPath, config);\n\n // Save API key to VasperaPM config\n const vasperaDir = join(homedir(), '.vasperapm');\n if (!existsSync(vasperaDir)) {\n mkdirSync(vasperaDir, { recursive: true });\n }\n writeJsonFile(getVasperaConfigPath(), { apiKey });\n\n console.log('\\n');\n success('VasperaPM installed successfully!');\n console.log('\\n\\x1b[1mNext steps:\\x1b[0m');\n console.log(' 1. Restart Claude Code (or VSCode)');\n console.log(' 2. Look for VasperaPM tools in the MCP panel');\n console.log(' 3. Try: \"Generate a PRD for a todo app\"\\n');\n\n console.log('\\x1b[1mAvailable Tools:\\x1b[0m');\n console.log(' \\x1b[33m•\\x1b[0m generate_prd - Create PRDs from context');\n console.log(' \\x1b[33m•\\x1b[0m infer_prd_from_code - Analyze code to generate PRD');\n console.log(' \\x1b[33m•\\x1b[0m generate_code - Generate code from PRD');\n console.log(' \\x1b[33m•\\x1b[0m sync_jira/linear/github - Sync with PM tools');\n console.log(' \\x1b[33m•\\x1b[0m generate_api_spec - Create OpenAPI specs');\n console.log(' \\x1b[33m•\\x1b[0m generate_test_cases - Create test plans\\n');\n}\n\n// Connect command - Set up API key and integrations\nasync function connect(): Promise<void> {\n console.log(BANNER);\n console.log('\\x1b[1mConnect VasperaPM to your services...\\x1b[0m\\n');\n\n // API Key setup\n console.log('\\x1b[1m1. API Key\\x1b[0m');\n const vasperaConfig = readJsonFile(getVasperaConfigPath()) as { apiKey?: string } | null;\n\n if (vasperaConfig?.apiKey) {\n const masked = vasperaConfig.apiKey.substring(0, 12) + '...' + vasperaConfig.apiKey.substring(vasperaConfig.apiKey.length - 4);\n info(`Current API key: ${masked}`);\n const answer = await prompt('Update API key? (y/N): ');\n if (answer.toLowerCase() !== 'y') {\n success('Keeping existing API key');\n } else {\n const newKey = await prompt('Enter new API key: ');\n if (newKey) {\n writeJsonFile(getVasperaConfigPath(), { ...vasperaConfig, apiKey: newKey });\n success('API key updated');\n }\n }\n } else {\n console.log('Get your API key at: \\x1b[36mhttps://vasperapm.com/dashboard\\x1b[0m\\n');\n const apiKey = await prompt('Enter your VasperaPM API key: ');\n if (apiKey) {\n writeJsonFile(getVasperaConfigPath(), { apiKey });\n success('API key saved');\n } else {\n warn('No API key provided. Some features will be limited.');\n }\n }\n\n console.log('\\n\\x1b[1m2. Integrations\\x1b[0m');\n console.log('Configure integrations at: \\x1b[36mhttps://vasperapm.com/dashboard/integrations\\x1b[0m\\n');\n console.log(' \\x1b[33m•\\x1b[0m Jira - Sync PRDs to Jira epics/stories');\n console.log(' \\x1b[33m•\\x1b[0m Linear - Export tasks to Linear projects');\n console.log(' \\x1b[33m•\\x1b[0m GitHub - Create issues and track progress\\n');\n\n success('Connection setup complete!');\n console.log('\\nRun \\x1b[36mvasperapm status\\x1b[0m to check your configuration.\\n');\n}\n\n// Status command - Check configuration\nasync function status(): Promise<void> {\n console.log(BANNER);\n console.log('\\x1b[1mVasperaPM Status\\x1b[0m\\n');\n\n // Check VasperaPM config\n const vasperaConfig = readJsonFile(getVasperaConfigPath()) as { apiKey?: string } | null;\n if (vasperaConfig?.apiKey) {\n const masked = vasperaConfig.apiKey.substring(0, 12) + '...' + vasperaConfig.apiKey.substring(vasperaConfig.apiKey.length - 4);\n success(`API Key: ${masked}`);\n\n if (vasperaConfig.apiKey.includes('_live_')) {\n info('Mode: Production');\n } else if (vasperaConfig.apiKey.includes('_test_')) {\n info('Mode: Test/Development');\n }\n } else {\n warn('API Key: Not configured');\n console.log(' Run \\x1b[36mvasperapm connect\\x1b[0m to set up your API key\\n');\n }\n\n // Check Claude Code config\n const claudeConfig = readJsonFile(getClaudeConfigPath()) as { mcpServers?: Record<string, unknown> } | null;\n if (claudeConfig?.mcpServers?.['vaspera-pm']) {\n success('Claude Code: Installed');\n } else {\n warn('Claude Code: Not installed');\n console.log(' Run \\x1b[36mvasperapm install\\x1b[0m to set up Claude Code integration\\n');\n }\n\n // Version info\n console.log(`\\n\\x1b[1mVersion:\\x1b[0m ${VERSION}`);\n console.log('\\x1b[1mDocs:\\x1b[0m https://github.com/rcolkitt/VasperaPM\\n');\n}\n\n// Serve command - Start MCP server\nasync function serve(): Promise<void> {\n // Import and run the MCP server\n const { startServer } = await import('./server.js');\n await startServer();\n}\n\n// Main CLI\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n const command = args[0]?.toLowerCase();\n\n switch (command) {\n case 'install':\n await install();\n break;\n case 'connect':\n await connect();\n break;\n case 'serve':\n await serve();\n break;\n case 'status':\n await status();\n break;\n case 'help':\n case '--help':\n case '-h':\n console.log(BANNER);\n console.log(HELP);\n break;\n case '--version':\n case '-v':\n console.log(`vasperapm v${VERSION}`);\n break;\n case undefined:\n console.log(BANNER);\n console.log(HELP);\n break;\n default:\n error(`Unknown command: ${command}`);\n console.log(HELP);\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n error(err.message);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,oBAA2C;AAgDpD,eAAsB,eAAe,QAAuD;AAC1F,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL,OAAO;AAAA,MACP,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AAGA,MAAI,CAAC,OAAO,WAAW,WAAW,KAAK,CAAC,OAAO,WAAW,WAAW,GAAG;AACtE,WAAO;AAAA,MACL,OAAO;AAAA,MACP,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AAEA,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,gBAAgB,qBAAqB;AAAA,MACnE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU,EAAE,OAAO,CAAC;AAAA,IACjC,CAAC;AAED,UAAM,OAAQ,MAAM,SAAS,KAAK;AAElC,QAAI,CAAC,SAAS,MAAM,CAAC,KAAK,OAAO;AAC/B,aAAO;AAAA,QACL,OAAO;AAAA,QACP,OAAO,KAAK,S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AK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,QAAM,IAAI,OAAO;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["error","error","error","error","error","error","error","error","error","error","error","error","error","error","error","error","result","error","error","error","success","error","VERSION","startServer"]}
@@ -0,0 +1,3 @@
1
+ declare function startServer(): Promise<void>;
2
+
3
+ export { startServer };
@@ -1,6 +1,4 @@
1
- #!/usr/bin/env node
2
-
3
- // src/index.ts
1
+ // src/server.ts
4
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
4
  import {
@@ -2542,11 +2540,12 @@ var toolHandlers = Object.fromEntries(
2542
2540
  toolDefinitions.map((t) => [t.tool.name, t.handler])
2543
2541
  );
2544
2542
 
2545
- // src/index.ts
2543
+ // src/server.ts
2544
+ var VERSION = "0.1.1";
2546
2545
  var server = new Server(
2547
2546
  {
2548
2547
  name: "vaspera-pm",
2549
- version: "1.0.0"
2548
+ version: VERSION
2550
2549
  },
2551
2550
  {
2552
2551
  capabilities: {
@@ -2633,13 +2632,18 @@ function sanitizeArgs(args) {
2633
2632
  }
2634
2633
  return sanitized;
2635
2634
  }
2636
- async function main() {
2635
+ async function startServer() {
2637
2636
  const transport = new StdioServerTransport();
2638
2637
  await server.connect(transport);
2639
- console.error("VasperaPM MCP Server v1.0.0 running");
2638
+ console.error(`VasperaPM MCP Server v${VERSION} running`);
2640
2639
  }
2641
- main().catch((error) => {
2642
- console.error("Failed to start MCP server:", error);
2643
- process.exit(1);
2644
- });
2645
- //# sourceMappingURL=index.js.map
2640
+ if (import.meta.url === `file://${process.argv[1]}`) {
2641
+ startServer().catch((error) => {
2642
+ console.error("Failed to start MCP server:", error);
2643
+ process.exit(1);
2644
+ });
2645
+ }
2646
+ export {
2647
+ startServer
2648
+ };
2649
+ //# sourceMappingURL=server.js.map