Skip to main content
Glama

Worksona MCP Server

Official
by worksona
index.ts•59.4 kB
#!/usr/bin/env node import { AgentRegistry } from './agents/registry'; import { AgentExecutor } from './agents/executor'; import { WorkflowCoordinator } from './orchestration/coordinator'; import { WorksonaAgentMemory } from './orchestration/memory'; import { ContextManager } from './utils/context'; import { Logger, info, error, success, mcp } from './utils/logger'; import * as path from 'path'; import * as fs from 'fs-extra'; class WorksonaMCPServer { private agentRegistry: AgentRegistry; private agentExecutor: AgentExecutor; private coordinator: WorkflowCoordinator; private memory: WorksonaAgentMemory; private contextManager: ContextManager; constructor() { // Initialize components const worksonaAgentsPath = this.resolveWorksonaAgentsPath(); try { this.agentRegistry = new AgentRegistry(worksonaAgentsPath); this.memory = new WorksonaAgentMemory(); this.contextManager = new ContextManager(); this.agentExecutor = new AgentExecutor(this.contextManager); this.coordinator = new WorkflowCoordinator(this.agentRegistry, this.agentExecutor); mcp('Server initialized', `Worksona agents path: ${worksonaAgentsPath}`); } catch (initError) { error('Failed to initialize MCP server', initError); process.exit(1); } } private resolveWorksonaAgentsPath(): string { // Try environment variable first if (process.env.WORKSONA_AGENTS_PATH) { return path.resolve(process.env.WORKSONA_AGENTS_PATH); } // Try bundled agents (for npm package distribution) const bundledPath = path.resolve(__dirname, '../agents'); if (fs.existsSync(bundledPath)) { return bundledPath; } throw new Error( 'Worksona agents directory not found. Please set WORKSONA_AGENTS_PATH environment variable or ensure agents directory is accessible.' ); } // Handle MCP protocol messages via STDIO private setupStdioHandler(): void { process.stdin.setEncoding('utf-8'); process.stdout.setEncoding('utf-8'); let buffer = ''; process.stdin.on('data', async (chunk) => { buffer += chunk; // Process complete JSON-RPC messages const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.trim()) { try { const request = JSON.parse(line); await this.handleRequest(request); } catch (e) { console.error('Failed to parse request:', e); } } } }); process.stdin.on('end', () => { process.exit(0); }); } private async handleRequest(request: any): Promise<void> { try { // Validate basic request structure if (!request || typeof request !== 'object') { console.error('Invalid request: not an object'); return; } if (!request.method) { console.error('Invalid request: missing method'); return; } let response: any; switch (request.method) { case 'initialize': response = { jsonrpc: '2.0', id: request.id, result: { protocolVersion: '2024-11-05', capabilities: { tools: {}, resources: {} }, serverInfo: { name: 'worksona-agents', version: '2.6.0' } } }; break; case 'tools/list': await this.ensureAgentsLoaded(); const agents = this.agentRegistry.getAllAgents(); response = { jsonrpc: '2.0', id: request.id, result: { tools: [ { name: 'activate_agent', description: 'Activate a specific Worksona agent to handle a request', inputSchema: { type: 'object', properties: { agent_name: { type: 'string', enum: agents.map(agent => agent.name) }, request: { type: 'string' }, project_context: { type: 'object' } }, required: ['agent_name', 'request'] } }, { name: 'coordinate_team', description: 'Coordinate multiple agents for complex tasks', inputSchema: { type: 'object', properties: { agents: { type: 'array', items: { type: 'string', enum: agents.map(agent => agent.name) } }, task: { type: 'string' }, coordination_type: { type: 'string', enum: ['sequential', 'parallel', 'review', 'executive'] } }, required: ['agents', 'task', 'coordination_type'] } }, { name: 'suggest_agents', description: 'Get agent suggestions for a request', inputSchema: { type: 'object', properties: { request: { type: 'string' }, max_suggestions: { type: 'number', default: 5 } }, required: ['request'] } }, { name: 'list_agents', description: 'List all available agents', inputSchema: { type: 'object', properties: { category: { type: 'string' }, capability: { type: 'string' } } } } ] } }; break; case 'tools/call': const toolResult = await this.handleToolCall(request.params.name, request.params.arguments); response = { jsonrpc: '2.0', id: request.id, result: toolResult }; break; case 'resources/read': const resourceResult = await this.handleResourceRead(request.params.uri); response = { jsonrpc: '2.0', id: request.id, result: resourceResult }; break; case 'prompts/list': // Return empty prompts to satisfy Claude Desktop's request response = { jsonrpc: '2.0', id: request.id, result: { prompts: [] } }; break; case 'resources/list': await this.ensureAgentsLoaded(); const resourceList = await this.buildResourcesList(); response = { jsonrpc: '2.0', id: request.id, result: { resources: resourceList } }; break; case 'notifications/initialized': // No response needed for notifications return; default: // Only send error response if request has an ID (not a notification) if (request.id !== undefined) { response = { jsonrpc: '2.0', id: request.id, error: { code: -32601, message: `Unknown method: ${request.method}` } }; } else { console.error(`Unknown notification method: ${request.method}`); return; } } // Only send response if we have one (notifications don't get responses) if (response) { process.stdout.write(JSON.stringify(response) + '\n'); } } catch (e) { // Only send error response if request has an ID if (request && request.id !== undefined) { const errorResponse = { jsonrpc: '2.0', id: request.id, error: { code: -32603, message: `Internal error: ${e instanceof Error ? e.message : String(e)}` } }; process.stdout.write(JSON.stringify(errorResponse) + '\n'); } else { console.error('Error handling request without ID:', e); } } } private async handleToolCall(name: string, args: any): Promise<any> { switch (name) { case 'activate_agent': return await this.handleActivateAgent(args); case 'coordinate_team': return await this.handleCoordinateTeam(args); case 'suggest_agents': return await this.handleSuggestAgents(args); case 'list_agents': return await this.handleListAgents(args); default: throw new Error(`Unknown tool: ${name}`); } } private async ensureAgentsLoaded(): Promise<void> { if (this.agentRegistry.getAllAgents().length === 0) { await this.agentRegistry.loadAllAgents(); } } private async handleActivateAgent(args: any) { await this.ensureAgentsLoaded(); const agent = this.agentRegistry.getAgent(args.agent_name); if (!agent) { throw new Error(`Agent '${args.agent_name}' not found`); } const result = await this.agentExecutor.executeAgent(agent, args.request, { projectContext: args.project_context, availableTools: agent.requirements.tools, memory: this.memory }); return { content: [ { type: 'text', text: `# šŸŽÆ ${agent.name} Agent Response\\n\\n${result.response}\\n\\n---\\nExecution time: ${result.metadata.executionTime}ms\\nTools used: ${(result.metadata.toolsUsed || []).join(', ')}` } ] }; } private async handleCoordinateTeam(args: any) { await this.ensureAgentsLoaded(); const result = await this.coordinator.executeWorkflow({ agents: args.agents, task: args.task, coordination: args.coordination_type, context: { memory: this.memory } }); let text = `# šŸŽ­ ${result.coordinationType.toUpperCase()} Team Coordination\\n\\n`; text += `**Summary**: ${result.summary}\\n\\n`; result.results.forEach((agentResult, index) => { text += `## ${index + 1}. ${agentResult.agentName}\\n`; text += `${agentResult.response}\\n\\n`; }); return { content: [ { type: 'text', text } ] }; } private async handleSuggestAgents(args: any) { await this.ensureAgentsLoaded(); const suggestions = this.agentRegistry.suggestAgentsForRequest(args.request, args.max_suggestions || 5); let text = `# šŸ” Agent Suggestions\\n\\nFor: "${args.request}"\\n\\n`; suggestions.forEach((suggestion, index) => { text += `${index + 1}. **${suggestion.agent.name}** (${suggestion.agent.category})\\n`; text += ` ${suggestion.agent.description}\\n`; text += ` Score: ${suggestion.score} - ${suggestion.reason}\\n\\n`; }); return { content: [ { type: 'text', text } ] }; } private async handleListAgents(args: any) { await this.ensureAgentsLoaded(); let agents = this.agentRegistry.getAllAgents(); if (args.category) { agents = this.agentRegistry.getAgentsByCategory(args.category); } let text = `# šŸ“‹ Available Agents (${agents.length})\\n\\n`; const categorized = agents.reduce((acc, agent) => { if (!acc[agent.category]) acc[agent.category] = []; acc[agent.category].push(agent); return acc; }, {} as Record<string, typeof agents>); Object.entries(categorized).forEach(([category, categoryAgents]) => { text += `## ${category} (${categoryAgents.length})\\n\\n`; categoryAgents.forEach(agent => { text += `- **${agent.name}**: ${agent.description}\\n`; }); text += '\\n'; }); return { content: [ { type: 'text', text } ] }; } private async buildResourcesList(): Promise<any[]> { const resources: any[] = []; // Build file-based resources from the resources directory const resourcesPath = path.resolve(__dirname, 'resources'); try { // Task templates const tasksPath = path.join(resourcesPath, 'tasks'); if (fs.existsSync(tasksPath)) { const taskFiles = fs.readdirSync(tasksPath).filter(f => f.endsWith('.md')); taskFiles.forEach(file => { const name = path.basename(file, '.md'); const filePath = path.join(tasksPath, file); resources.push({ uri: `file://${filePath}`, name: `šŸ“š ${this.formatResourceName(name)}`, description: `Task template: ${this.formatResourceName(name)}`, mimeType: "text/markdown" }); }); } // Workflows const workflowsPath = path.join(resourcesPath, 'workflows'); if (fs.existsSync(workflowsPath)) { const workflowFiles = fs.readdirSync(workflowsPath).filter(f => f.endsWith('.md')); workflowFiles.forEach(file => { const name = path.basename(file, '.md'); const filePath = path.join(workflowsPath, file); resources.push({ uri: `file://${filePath}`, name: `šŸš€ ${this.formatResourceName(name)}`, description: `Workflow: ${this.formatResourceName(name)}`, mimeType: "text/markdown" }); }); } // Examples const examplesPath = path.join(resourcesPath, 'examples'); if (fs.existsSync(examplesPath)) { const exampleFiles = fs.readdirSync(examplesPath).filter(f => f.endsWith('.md')); exampleFiles.forEach(file => { const name = path.basename(file, '.md'); const filePath = path.join(examplesPath, file); resources.push({ uri: `file://${filePath}`, name: `šŸ’” ${this.formatResourceName(name)}`, description: `Example: ${this.formatResourceName(name)}`, mimeType: "text/markdown" }); }); } // Quick actions const quickActionsPath = path.join(resourcesPath, 'quick-actions'); if (fs.existsSync(quickActionsPath)) { const quickFiles = fs.readdirSync(quickActionsPath).filter(f => f.endsWith('.md')); quickFiles.forEach(file => { const name = path.basename(file, '.md'); const filePath = path.join(quickActionsPath, file); resources.push({ uri: `file://${filePath}`, name: `⚔ ${this.formatResourceName(name)}`, description: `Quick action: ${this.formatResourceName(name)}`, mimeType: "text/markdown" }); }); } } catch (error) { console.error('Error building resources list:', error); } return resources; } private formatResourceName(name: string): string { return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1) ).join(' '); } private buildTaskTemplates(): any[] { return [ { uri: "worksona://task/api-documentation", name: "šŸ“š API Documentation", description: "Generate comprehensive API documentation with examples and schemas", mimeType: "text/markdown" }, { uri: "worksona://task/code-review", name: "šŸ” Code Review", description: "Perform thorough code review with security, performance, and best practices analysis", mimeType: "text/markdown" }, { uri: "worksona://task/database-optimization", name: "⚔ Database Optimization", description: "Analyze and optimize database performance, queries, and schema design", mimeType: "text/markdown" }, { uri: "worksona://task/security-audit", name: "šŸ”’ Security Audit", description: "Comprehensive security assessment and vulnerability analysis", mimeType: "text/markdown" }, { uri: "worksona://task/frontend-component", name: "šŸŽØ Frontend Component", description: "Create modern, accessible React/Vue components with TypeScript", mimeType: "text/markdown" }, { uri: "worksona://task/backend-api", name: "šŸ”§ Backend API", description: "Design and implement scalable REST/GraphQL APIs", mimeType: "text/markdown" } ]; } private buildWorkflowResources(): any[] { return [ { uri: "worksona://workflow/full-stack-app", name: "šŸš€ Full-Stack Application", description: "Complete application development: architecture → backend → frontend → testing", mimeType: "text/markdown" }, { uri: "worksona://workflow/security-review", name: "šŸ›”ļø Security Review Workflow", description: "Multi-stage security assessment: audit → penetration test → compliance check", mimeType: "text/markdown" }, { uri: "worksona://workflow/performance-optimization", name: "⚔ Performance Optimization", description: "Systematic performance improvement: analysis → optimization → monitoring", mimeType: "text/markdown" }, { uri: "worksona://workflow/market-research", name: "šŸ“Š Market Research", description: "Comprehensive market analysis: competitive research → trend analysis → strategy", mimeType: "text/markdown" }, { uri: "worksona://workflow/devops-setup", name: "šŸ”„ DevOps Pipeline", description: "Complete CI/CD setup: infrastructure → deployment → monitoring → automation", mimeType: "text/markdown" } ]; } private buildExamplePrompts(): any[] { return [ { uri: "worksona://example/startup-mvp", name: "šŸ’” Startup MVP Development", description: "Build a minimum viable product from idea to deployment", mimeType: "text/markdown" }, { uri: "worksona://example/legacy-modernization", name: "šŸ”„ Legacy System Modernization", description: "Migrate legacy applications to modern architecture", mimeType: "text/markdown" }, { uri: "worksona://example/ai-integration", name: "šŸ¤– AI Feature Integration", description: "Add AI capabilities to existing applications", mimeType: "text/markdown" }, { uri: "worksona://example/mobile-app", name: "šŸ“± Mobile App Development", description: "Create cross-platform mobile applications", mimeType: "text/markdown" }, { uri: "worksona://example/data-pipeline", name: "šŸ“ˆ Data Pipeline & Analytics", description: "Build data processing and analytics systems", mimeType: "text/markdown" } ]; } private buildQuickActions(): any[] { return [ { uri: "worksona://quick/bug-fix", name: "šŸ› Quick Bug Fix", description: "Rapid debugging and issue resolution", mimeType: "text/markdown" }, { uri: "worksona://quick/performance-check", name: "⚔ Performance Check", description: "Quick performance analysis and recommendations", mimeType: "text/markdown" }, { uri: "worksona://quick/security-scan", name: "šŸ” Security Scan", description: "Fast security vulnerability assessment", mimeType: "text/markdown" }, { uri: "worksona://quick/code-explanation", name: "šŸ“– Code Explanation", description: "Understand and document existing code", mimeType: "text/markdown" }, { uri: "worksona://quick/tech-decision", name: "šŸ¤” Technology Decision", description: "Get expert advice on technology choices", mimeType: "text/markdown" } ]; } private async handleResourceRead(uri: string): Promise<any> { await this.ensureAgentsLoaded(); // Handle file-based resources if (uri.startsWith("file://")) { const filePath = uri.replace("file://", ""); try { if (!fs.existsSync(filePath)) { throw new Error(`Resource file not found: ${filePath}`); } const content = fs.readFileSync(filePath, 'utf-8'); return { contents: [ { type: 'text', text: content } ] }; } catch (error) { throw new Error(`Failed to read resource file: ${error instanceof Error ? error.message : String(error)}`); } } // Legacy dynamic resource support (kept for backward compatibility) if (uri.startsWith("worksona://task/")) { const taskType = uri.replace("worksona://task/", ""); return await this.generateTaskTemplate(taskType); } if (uri.startsWith("worksona://workflow/")) { const workflowType = uri.replace("worksona://workflow/", ""); return await this.generateWorkflowTemplate(workflowType); } if (uri.startsWith("worksona://example/")) { const exampleType = uri.replace("worksona://example/", ""); return await this.generateExamplePrompt(exampleType); } if (uri.startsWith("worksona://quick/")) { const quickType = uri.replace("worksona://quick/", ""); return await this.generateQuickAction(quickType); } // Legacy agent resource support (kept for backward compatibility) if (uri.startsWith("worksona://agent/")) { const agentName = uri.replace("worksona://agent/", ""); return await this.generateAgentContext(agentName); } throw new Error(`Unknown resource: ${uri}`); } private async generateAgentContext(agentName: string): Promise<any> { const agent = this.agentRegistry.getAgent(agentName); if (!agent) { throw new Error(`Agent '${agentName}' not found`); } // Create comprehensive agent context that includes execution instructions const content = `# ${agent.name} Agent Context ## Agent Description ${agent.description} ## Specializations ${agent.capabilities?.primary?.slice(0, 5).join(', ') || 'Specialized domain tasks'} ## How to Use This Agent To activate this agent, use the \`activate_agent\` tool with: - **agent_name**: "${agent.name}" - **request**: Your specific task or question - **project_context**: (optional) Additional context about your project ## Example Usage \`\`\` activate_agent({ "agent_name": "${agent.name}", "request": "Your task description here", "project_context": { "technology": "...", "requirements": "..." } }) \`\`\` ## Agent Category ${agent.category.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase())} --- *This agent is now available in your conversation context. Use the activate_agent tool to execute tasks with this agent's expertise.*`; return { contents: [ { type: 'text', text: content } ] }; } private async generateTaskTemplate(taskType: string): Promise<any> { const templates: Record<string, any> = { 'api-documentation': { title: 'API Documentation Generator', agent: 'doc-writer', description: 'Generate comprehensive API documentation with interactive examples', prompt: `I need comprehensive API documentation for my service. Please include: 1. **API Overview** - Purpose, authentication, base URLs 2. **Endpoint Documentation** - All routes with parameters, responses, examples 3. **Schema Definitions** - Request/response models with validation rules 4. **Authentication Guide** - How to authenticate and handle tokens 5. **Error Handling** - Common error codes and troubleshooting 6. **Code Examples** - Sample requests in multiple languages 7. **Interactive Testing** - Postman collection or OpenAPI spec **My API Details:** - Technology stack: [Describe your backend technology] - Authentication method: [JWT, OAuth, API keys, etc.] - Main endpoints: [List your key API endpoints] - Special requirements: [Any specific needs or constraints] Please activate the doc-writer agent to create professional, developer-friendly documentation.`, toolCall: 'activate_agent' }, 'code-review': { title: 'Code Review Assistant', agent: 'code-reviewer', description: 'Thorough code review focusing on quality, security, and best practices', prompt: `I need a comprehensive code review. Please analyze my code for: 1. **Code Quality** - Readability, maintainability, structure 2. **Security Issues** - Vulnerabilities, input validation, authentication 3. **Performance** - Bottlenecks, optimization opportunities 4. **Best Practices** - Language-specific conventions, design patterns 5. **Testing** - Test coverage, test quality, missing test cases 6. **Documentation** - Code comments, README, inline docs 7. **Dependencies** - Security, licensing, version management **Code to Review:** [Paste your code here or provide repository details] **Context:** - Programming language: [Language/framework] - Project type: [Web app, API, library, etc.] - Team size: [Solo, small team, enterprise] - Deployment environment: [Production criticality level] Please activate the code-reviewer agent for detailed analysis.`, toolCall: 'activate_agent' }, 'database-optimization': { title: 'Database Performance Optimizer', agent: 'database-optimizer', description: 'Analyze and optimize database performance, queries, and schema', prompt: `I need database optimization help. Please analyze and improve: 1. **Query Performance** - Slow queries, execution plans, indexing 2. **Schema Design** - Normalization, relationships, data types 3. **Index Strategy** - Missing indexes, over-indexing, composite indexes 4. **Connection Management** - Pool sizing, connection leaks 5. **Monitoring Setup** - Performance metrics, alerting 6. **Scaling Strategy** - Partitioning, sharding, read replicas 7. **Maintenance Tasks** - Cleanup, archiving, backup optimization **Database Details:** - Database type: [PostgreSQL, MySQL, MongoDB, etc.] - Current size: [Number of records, storage size] - Performance issues: [Describe specific problems] - Infrastructure: [Cloud provider, on-premise, etc.] - Traffic patterns: [Read/write ratio, peak times] Please activate the database-optimizer agent for comprehensive analysis.`, toolCall: 'activate_agent' }, 'security-audit': { title: 'Security Audit Assistant', agent: 'security-auditor', description: 'Comprehensive security assessment and vulnerability analysis', prompt: `I need a thorough security audit. Please assess: 1. **Authentication & Authorization** - Login security, access controls, permissions 2. **Input Validation** - SQL injection, XSS, CSRF protection 3. **Data Protection** - Encryption, sensitive data handling, GDPR compliance 4. **Infrastructure Security** - Server hardening, network security, SSL/TLS 5. **Dependency Security** - Vulnerable packages, supply chain risks 6. **API Security** - Rate limiting, input sanitization, error handling 7. **Compliance** - Industry standards (SOC2, ISO27001, HIPAA, etc.) **System Details:** - Application type: [Web app, API, mobile app, etc.] - Technology stack: [Languages, frameworks, databases] - User data handled: [PII, financial, health, etc.] - Compliance requirements: [GDPR, HIPAA, SOX, etc.] - Current security measures: [Describe existing protections] Please activate the security-auditor agent for detailed assessment.`, toolCall: 'activate_agent' }, 'frontend-component': { title: 'Frontend Component Builder', agent: 'frontend-developer', description: 'Create modern, accessible React/Vue components with TypeScript', prompt: `I need a frontend component built with modern best practices: 1. **Component Specifications** - Functionality, props, behavior 2. **Accessibility** - ARIA labels, keyboard navigation, screen reader support 3. **Responsive Design** - Mobile-first, breakpoints, flexible layouts 4. **Type Safety** - TypeScript interfaces, prop validation 5. **Testing** - Unit tests, integration tests, accessibility tests 6. **Documentation** - Storybook stories, usage examples 7. **Performance** - Lazy loading, memoization, bundle optimization **Component Requirements:** - Framework: [React, Vue, Angular, etc.] - Component type: [Button, Form, Modal, Table, etc.] - Design system: [Material-UI, Ant Design, custom, etc.] - Functionality: [Describe what the component should do] - Styling approach: [CSS Modules, Styled Components, Tailwind, etc.] Please activate the frontend-developer agent to build the component.`, toolCall: 'activate_agent' }, 'backend-api': { title: 'Backend API Builder', agent: 'backend-architect', description: 'Design and implement scalable REST/GraphQL APIs', prompt: `I need a backend API designed and implemented: 1. **API Design** - RESTful routes or GraphQL schema, data models 2. **Authentication** - JWT, OAuth, API keys, role-based access 3. **Database Integration** - ORM setup, migrations, relationships 4. **Validation** - Input validation, error handling, data sanitization 5. **Testing** - Unit tests, integration tests, API testing 6. **Documentation** - OpenAPI/Swagger specs, endpoint documentation 7. **Deployment** - Docker, CI/CD, environment configuration **API Requirements:** - Technology: [Node.js, Python, Go, Java, etc.] - Database: [PostgreSQL, MongoDB, MySQL, etc.] - API type: [REST, GraphQL, gRPC] - Authentication needs: [User auth, service-to-service, etc.] - Key features: [Describe main functionality] - Scale requirements: [Expected load, performance needs] Please activate the backend-architect agent to design the API.`, toolCall: 'activate_agent' } }; const template = templates[taskType]; if (!template) { throw new Error(`Unknown task template: ${taskType}`); } const content = `# ${template.title} ${template.description} ## Ready-to-Use Prompt Copy and customize this prompt for your specific needs: --- ${template.prompt} --- ## How to Execute This task template will automatically use the **${template.agent}** agent. Simply: 1. **Customize the prompt** above with your specific details 2. **Copy the customized prompt** 3. **Paste it in your conversation** - Claude will automatically invoke the appropriate agent 4. **Provide additional context** as requested by the agent ## Agent Details **Primary Agent:** \`${template.agent}\` **Tool Used:** \`${template.toolCall}\` The ${template.agent} agent specializes in this type of task and will provide expert-level assistance with detailed, actionable results. --- *This is a task template resource. Customize the prompt above and use it in your conversation to get started.*`; return { contents: [ { type: 'text', text: content } ] }; } private async generateWorkflowTemplate(workflowType: string): Promise<any> { const workflows: Record<string, any> = { 'full-stack-app': { title: 'Full-Stack Application Development', description: 'Complete application development from architecture to deployment', agents: ['backend-architect', 'frontend-developer', 'database-optimizer', 'test-automator'], coordination: 'sequential', prompt: `I want to build a complete full-stack application. Please coordinate the following agents in sequence: **Phase 1: Architecture & Backend** (backend-architect) - Design system architecture and data models - Implement core API endpoints and business logic - Set up authentication and authorization - Configure database schema and relationships **Phase 2: Frontend Development** (frontend-developer) - Create responsive user interface components - Implement state management and API integration - Add user authentication flows - Ensure accessibility and mobile responsiveness **Phase 3: Database Optimization** (database-optimizer) - Optimize database queries and indexing - Set up connection pooling and caching - Configure backup and monitoring strategies - Performance tune for expected load **Phase 4: Testing & Quality** (test-automator) - Create comprehensive test suites (unit, integration, e2e) - Set up automated testing pipelines - Implement code coverage reporting - Add performance and security testing **Application Details:** - Type: [Web app, SaaS, e-commerce, etc.] - Technology preferences: [React/Vue, Node.js/Python, PostgreSQL/MongoDB] - Key features: [List main functionality] - Expected users: [Scale and user types] - Timeline: [Development timeline expectations] Please use coordinate_team with sequential coordination to execute this workflow.` }, 'security-review': { title: 'Comprehensive Security Review', description: 'Multi-stage security assessment with specialized agents', agents: ['security-auditor', 'incident-responder', 'risk-manager'], coordination: 'sequential', prompt: `I need a comprehensive security review of my system. Please coordinate these security specialists: **Stage 1: Security Audit** (security-auditor) - Perform vulnerability assessment and penetration testing - Review code for security flaws and best practices - Analyze authentication and authorization mechanisms - Check for OWASP Top 10 vulnerabilities **Stage 2: Incident Response Planning** (incident-responder) - Develop incident response procedures - Create security monitoring and alerting systems - Design breach notification and recovery processes - Set up security logging and forensics capabilities **Stage 3: Risk Management** (risk-manager) - Assess business risk and compliance requirements - Create security policies and procedures - Design employee security training programs - Establish ongoing security governance framework **System Details:** - Application type: [Web, mobile, API, etc.] - Technology stack: [Languages, frameworks, infrastructure] - Sensitive data: [PII, financial, health records, etc.] - Compliance needs: [GDPR, HIPAA, SOX, PCI-DSS, etc.] - Current security measures: [Existing protections] Please use coordinate_team with sequential coordination for thorough security review.` }, 'performance-optimization': { title: 'System Performance Optimization', description: 'Systematic performance improvement across all layers', agents: ['performance-engineer', 'database-optimizer', 'devops-engineer'], coordination: 'parallel', prompt: `I need comprehensive performance optimization. Please coordinate these specialists in parallel: **Application Performance** (performance-engineer) - Profile application code and identify bottlenecks - Optimize algorithms and data structures - Implement caching strategies (Redis, CDN, application-level) - Add performance monitoring and alerting **Database Performance** (database-optimizer) - Analyze and optimize slow queries - Design efficient indexing strategies - Implement connection pooling and query caching - Set up database monitoring and maintenance **Infrastructure Performance** (devops-engineer) - Optimize server configuration and resource allocation - Implement auto-scaling and load balancing - Set up performance monitoring and observability - Configure CDN and edge caching **Performance Goals:** - Current issues: [Describe specific performance problems] - Target metrics: [Response times, throughput, etc.] - Technology stack: [Languages, databases, infrastructure] - Traffic patterns: [Peak loads, geographic distribution] - Budget constraints: [Infrastructure spending limits] Please use coordinate_team with parallel coordination for comprehensive optimization.` }, 'market-research': { title: 'Comprehensive Market Research', description: 'Multi-faceted market analysis and strategic insights', agents: ['market-researcher', 'competitive-analyst', 'trend-analyst'], coordination: 'sequential', prompt: `I need comprehensive market research and analysis. Please coordinate these research specialists: **Phase 1: Market Analysis** (market-researcher) - Analyze target market size, growth, and segmentation - Research customer needs, pain points, and behaviors - Identify market opportunities and entry barriers - Study regulatory environment and industry standards **Phase 2: Competitive Intelligence** (competitive-analyst) - Map competitive landscape and key players - Analyze competitor strategies, strengths, and weaknesses - Research pricing models and value propositions - Identify competitive advantages and differentiation opportunities **Phase 3: Trend Analysis** (trend-analyst) - Identify emerging market trends and technologies - Analyze future market direction and disruption risks - Research innovation opportunities and timing - Provide strategic recommendations and roadmap **Research Scope:** - Industry/Market: [Specify the market or industry] - Geographic focus: [Global, regional, or specific countries] - Target customers: [B2B, B2C, demographics, etc.] - Product/Service: [What you're researching for] - Strategic goals: [Market entry, expansion, investment, etc.] - Timeline: [Research urgency and decision timeline] Please use coordinate_team with sequential coordination for thorough market analysis.` }, 'devops-setup': { title: 'Complete DevOps Pipeline Setup', description: 'End-to-end CI/CD and infrastructure automation', agents: ['devops-engineer', 'cloud-architect', 'deployment-engineer'], coordination: 'sequential', prompt: `I need a complete DevOps pipeline setup. Please coordinate these infrastructure specialists: **Phase 1: Infrastructure Design** (cloud-architect) - Design scalable cloud infrastructure architecture - Set up networking, security groups, and access controls - Configure monitoring, logging, and observability stack - Plan disaster recovery and backup strategies **Phase 2: CI/CD Pipeline** (devops-engineer) - Set up source control workflows and branching strategy - Create automated build, test, and deployment pipelines - Implement infrastructure as code (Terraform, CloudFormation) - Configure automated security scanning and compliance checks **Phase 3: Deployment Automation** (deployment-engineer) - Set up container orchestration (Kubernetes, Docker Swarm) - Implement blue-green or canary deployment strategies - Configure auto-scaling and load balancing - Set up production monitoring and alerting **Infrastructure Requirements:** - Cloud provider: [AWS, Azure, GCP, or on-premise] - Application type: [Web app, microservices, API, etc.] - Technology stack: [Languages, frameworks, databases] - Scale requirements: [Expected load, growth projections] - Compliance needs: [Security, regulatory requirements] - Budget considerations: [Cost optimization priorities] Please use coordinate_team with sequential coordination for complete DevOps setup.` } }; const workflow = workflows[workflowType]; if (!workflow) { throw new Error(`Unknown workflow template: ${workflowType}`); } const content = `# ${workflow.title} ${workflow.description} ## Multi-Agent Workflow This workflow coordinates **${workflow.agents.length} specialized agents** using **${workflow.coordination}** coordination: ${workflow.agents.map((agent: string, index: number) => `${index + 1}. **${agent}**`).join('\n')} ## Ready-to-Use Workflow Prompt Copy and customize this prompt for your specific needs: --- ${workflow.prompt} --- ## How to Execute This workflow template will automatically coordinate multiple agents: 1. **Customize the workflow prompt** above with your specific requirements 2. **Copy the customized prompt** 3. **Paste it in your conversation** - Claude will automatically use \`coordinate_team\` 4. **Monitor progress** as each agent completes their phase 5. **Provide feedback** and additional context as needed ## Workflow Details **Coordination Type:** \`${workflow.coordination}\` **Tool Used:** \`coordinate_team\` **Agents Involved:** ${workflow.agents.length} specialists The workflow will execute ${workflow.coordination === 'sequential' ? 'step-by-step with each agent building on the previous work' : 'in parallel with agents working simultaneously on different aspects'}. --- *This is a workflow template resource. Customize the prompt above and use it in your conversation to start the multi-agent workflow.*`; return { contents: [ { type: 'text', text: content } ] }; } private async generateExamplePrompt(exampleType: string): Promise<any> { const examples: Record<string, any> = { 'startup-mvp': { title: 'Startup MVP Development', description: 'Build a minimum viable product from concept to launch', scenario: 'Early-stage startup needing to validate product-market fit', prompt: `I'm building a startup MVP and need help going from idea to launch. Here's my concept: **Product Idea:** [Describe your startup idea - the problem you're solving and your solution] **Target Market:** [Who are your users? What's the market size?] **Core Features:** [List the 3-5 essential features for your MVP] **Technical Constraints:** - Budget: [Development budget and timeline] - Team: [Technical skills available in-house] - Technology preferences: [Any specific tech requirements] **Business Goals:** - Launch timeline: [When do you need to launch?] - Success metrics: [How will you measure MVP success?] - Funding stage: [Pre-seed, seeking investment, etc.] Please help me: 1. **Validate and refine** the MVP scope and features 2. **Choose the right technology stack** for rapid development 3. **Create a development roadmap** with milestones 4. **Build the core application** with essential features 5. **Set up basic analytics** and user feedback systems 6. **Plan the launch strategy** and initial user acquisition I'd like to coordinate multiple agents to handle different aspects of MVP development efficiently.`, suggestedAgents: ['product-manager', 'backend-architect', 'frontend-developer', 'marketing-writer'] }, 'legacy-modernization': { title: 'Legacy System Modernization', description: 'Migrate legacy applications to modern architecture', scenario: 'Enterprise with aging systems needing modernization', prompt: `I need to modernize a legacy system that's becoming difficult to maintain and scale: **Current System:** - Technology: [Current programming language, framework, database] - Age: [How old is the system?] - Size: [Lines of code, number of users, data volume] - Architecture: [Monolith, client-server, etc.] **Pain Points:** - Performance issues: [Specific performance problems] - Maintenance challenges: [What makes it hard to maintain?] - Integration difficulties: [Problems with other systems] - Security concerns: [Known vulnerabilities or compliance issues] **Modernization Goals:** - Target architecture: [Microservices, cloud-native, etc.] - Technology preferences: [Preferred modern stack] - Timeline: [Migration timeline and constraints] - Risk tolerance: [Big bang vs. gradual migration] **Business Requirements:** - Uptime requirements: [Acceptable downtime during migration] - Budget constraints: [Development and infrastructure budget] - Compliance needs: [Regulatory requirements to maintain] - User impact: [How to minimize disruption to users] Please help me: 1. **Assess the current system** and create a modernization strategy 2. **Design the target architecture** with modern best practices 3. **Create a migration plan** with risk mitigation 4. **Implement the modernization** in phases 5. **Ensure data integrity** throughout the migration 6. **Set up monitoring** and rollback procedures I need a coordinated approach with multiple specialists for this complex migration.`, suggestedAgents: ['legacy-modernizer', 'backend-architect', 'database-optimizer', 'devops-engineer'] }, 'ai-integration': { title: 'AI Feature Integration', description: 'Add AI capabilities to existing applications', scenario: 'Product team wanting to enhance their app with AI features', prompt: `I want to integrate AI capabilities into my existing application: **Current Application:** - Type: [Web app, mobile app, SaaS platform, etc.] - Technology stack: [Current tech stack] - User base: [Number and type of users] - Core functionality: [What does your app currently do?] **AI Integration Goals:** - AI features desired: [Chatbot, recommendations, image recognition, etc.] - Business objectives: [Improve UX, increase engagement, automate tasks] - User experience: [How should AI enhance the user journey?] - Competitive advantage: [How will AI differentiate your product?] **Technical Considerations:** - Data available: [What data do you have for training/inference?] - Performance requirements: [Real-time, batch processing, etc.] - Privacy concerns: [Data sensitivity, GDPR compliance, etc.] - Budget: [Development and operational costs for AI features] **Implementation Preferences:** - AI services: [OpenAI, AWS AI, Google AI, custom models, etc.] - Integration approach: [API-based, embedded models, hybrid] - Rollout strategy: [Beta testing, gradual rollout, feature flags] Please help me: 1. **Design the AI feature architecture** and user experience 2. **Choose the right AI services** and integration approach 3. **Implement the AI features** with proper error handling 4. **Set up data pipelines** and model management 5. **Add monitoring and analytics** for AI performance 6. **Plan the rollout strategy** and user onboarding I'd like to coordinate AI specialists with my existing development team.`, suggestedAgents: ['ai-engineer', 'backend-architect', 'frontend-developer', 'data-scientist'] }, 'mobile-app': { title: 'Mobile App Development', description: 'Create cross-platform mobile applications', scenario: 'Business needing a mobile presence for their service', prompt: `I need to develop a mobile application for my business: **App Concept:** - Purpose: [What problem does your app solve?] - Target audience: [Who will use your app?] - Platform priority: [iOS first, Android first, or both simultaneously] - App category: [Business, social, utility, gaming, etc.] **Core Features:** - Essential features: [List must-have functionality] - Nice-to-have features: [Future enhancement ideas] - Offline capabilities: [What should work without internet?] - Push notifications: [What notifications are needed?] **Technical Requirements:** - Backend needs: [User accounts, data sync, APIs, etc.] - Third-party integrations: [Payment, maps, social login, etc.] - Performance requirements: [Speed, battery usage, storage] - Security needs: [Data encryption, authentication, etc.] **Business Considerations:** - Monetization: [Free, paid, freemium, ads, in-app purchases] - Launch timeline: [When do you need to launch?] - Budget: [Development budget and ongoing costs] - Marketing plan: [How will you acquire users?] **Design Preferences:** - Design style: [Modern, minimalist, branded, etc.] - User experience: [Simple, feature-rich, specific workflows] - Accessibility: [Requirements for users with disabilities] Please help me: 1. **Refine the app concept** and feature prioritization 2. **Choose the development approach** (native, React Native, Flutter) 3. **Design the user interface** and user experience 4. **Develop the mobile application** with backend integration 5. **Set up app store optimization** and deployment 6. **Plan the launch strategy** and user acquisition I need coordination between mobile developers, backend architects, and UX specialists.`, suggestedAgents: ['mobile-developer', 'backend-architect', 'frontend-developer', 'marketing-writer'] }, 'data-pipeline': { title: 'Data Pipeline & Analytics', description: 'Build data processing and analytics systems', scenario: 'Organization needing to process and analyze large amounts of data', prompt: `I need to build a data pipeline and analytics system: **Data Sources:** - Data types: [Customer data, transaction logs, sensor data, etc.] - Data volume: [Records per day, total data size, growth rate] - Data formats: [JSON, CSV, database tables, APIs, etc.] - Update frequency: [Real-time, hourly, daily, batch] **Processing Requirements:** - Data transformations: [Cleaning, aggregation, enrichment needed] - Business logic: [Calculations, rules, validations to apply] - Data quality: [Validation rules, error handling, monitoring] - Performance needs: [Processing speed, latency requirements] **Analytics Goals:** - Reporting needs: [Dashboards, scheduled reports, ad-hoc queries] - Key metrics: [What business metrics do you need to track?] - User access: [Who needs access to what data?] - Visualization: [Charts, graphs, interactive dashboards] **Technical Infrastructure:** - Current systems: [Existing databases, tools, cloud services] - Preferred technology: [AWS, GCP, Azure, on-premise, specific tools] - Scalability needs: [Expected growth, peak loads] - Budget constraints: [Infrastructure and licensing costs] **Compliance & Security:** - Data governance: [Privacy, retention, access controls] - Regulatory requirements: [GDPR, HIPAA, industry standards] - Security needs: [Encryption, audit trails, access logging] Please help me: 1. **Design the data architecture** and pipeline flow 2. **Choose the right technology stack** for data processing 3. **Implement data ingestion** and transformation processes 4. **Build analytics and reporting** capabilities 5. **Set up monitoring and alerting** for data quality 6. **Create documentation** and operational procedures I need coordination between data engineers, analysts, and infrastructure specialists.`, suggestedAgents: ['data-engineer', 'data-scientist', 'cloud-architect', 'database-optimizer'] } }; const example = examples[exampleType]; if (!example) { throw new Error(`Unknown example prompt: ${exampleType}`); } const content = `# ${example.title} ${example.description} ## Use Case Scenario **Perfect for:** ${example.scenario} ## Complete Example Prompt Copy and customize this detailed prompt for your specific situation: --- ${example.prompt} --- ## Recommended Agent Coordination For this type of project, consider using these agents: ${example.suggestedAgents.map((agent: string, index: number) => `${index + 1}. **${agent}** - Specialized expertise for this domain`).join('\n')} ## How to Use This Example 1. **Copy the example prompt** above 2. **Customize the bracketed sections** with your specific details 3. **Paste the customized prompt** in your conversation 4. **Claude will automatically suggest** the best agents and coordination approach 5. **Provide additional context** as the agents ask follow-up questions ## Execution Options - **Single Agent:** Use \`activate_agent\` for focused expertise - **Team Coordination:** Use \`coordinate_team\` for complex, multi-faceted projects - **Agent Suggestions:** Use \`suggest_agents\` to explore other specialist options --- *This is an example prompt resource. Customize it with your specific requirements and use it to get started with your project.*`; return { contents: [ { type: 'text', text: content } ] }; } private async generateQuickAction(quickType: string): Promise<any> { const actions: Record<string, any> = { 'bug-fix': { title: 'Quick Bug Fix Assistant', agent: 'error-detective', description: 'Rapid debugging and issue resolution', prompt: `I have a bug that needs quick resolution: **Bug Description:** [Describe what's not working as expected] **Error Messages:** [Paste any error messages or logs] **Code Context:** [Paste the relevant code where the issue occurs] **Environment:** - Language/Framework: [e.g., JavaScript/React, Python/Django] - Environment: [Development, staging, production] - Recent changes: [What was changed recently?] **Expected vs Actual:** - Expected behavior: [What should happen] - Actual behavior: [What actually happens] Please activate the error-detective agent to quickly identify and fix this issue.`, timeEstimate: '15-30 minutes' }, 'performance-check': { title: 'Quick Performance Analysis', agent: 'performance-engineer', description: 'Fast performance analysis and recommendations', prompt: `I need a quick performance check for my application: **Performance Issue:** [Describe the performance problem - slow loading, high CPU, memory leaks, etc.] **System Details:** - Application type: [Web app, API, mobile app, etc.] - Technology stack: [Languages, frameworks, databases] - Current metrics: [Response times, throughput, error rates] - Infrastructure: [Cloud provider, server specs, scaling setup] **Specific Concerns:** [What specific performance aspects are you worried about?] **Quick Context:** [Paste relevant code, configuration, or monitoring data] Please activate the performance-engineer agent for rapid performance analysis and actionable recommendations.`, timeEstimate: '20-45 minutes' }, 'security-scan': { title: 'Quick Security Assessment', agent: 'security-auditor', description: 'Fast security vulnerability assessment', prompt: `I need a quick security scan of my application: **Application Details:** - Type: [Web app, API, mobile app, etc.] - Technology: [Languages, frameworks, dependencies] - Deployment: [Cloud provider, infrastructure setup] - User data: [What sensitive data is handled?] **Security Concerns:** [Any specific security issues or areas of concern?] **Code/Config to Review:** [Paste relevant code, configuration files, or security settings] **Compliance Needs:** [Any regulatory requirements - GDPR, HIPAA, etc.] Please activate the security-auditor agent for a rapid security assessment and immediate recommendations.`, timeEstimate: '25-40 minutes' }, 'code-explanation': { title: 'Code Understanding Assistant', agent: 'code-reviewer', description: 'Understand and document existing code', prompt: `I need help understanding this code: **Code to Analyze:** [Paste the code you want to understand] **Context:** - Programming language: [Language/framework] - Project type: [What kind of application is this?] - Your role: [Are you new to the project, debugging, reviewing, etc.] **Specific Questions:** [What specifically do you want to understand about this code?] **Documentation Needs:** - Code comments: [Do you need inline comments added?] - Function documentation: [Need docstrings or API docs?] - Architecture overview: [Need high-level explanation?] Please activate the code-reviewer agent to explain this code clearly and add helpful documentation.`, timeEstimate: '15-25 minutes' }, 'tech-decision': { title: 'Technology Decision Support', agent: 'backend-architect', description: 'Get expert advice on technology choices', prompt: `I need help making a technology decision: **Decision Context:** [What technology choice are you trying to make?] **Project Details:** - Project type: [Web app, mobile app, API, etc.] - Scale requirements: [Expected users, data volume, performance needs] - Team size: [How many developers, their experience level] - Timeline: [Development timeline and constraints] **Options Being Considered:** [List the technologies/approaches you're evaluating] **Key Factors:** - Performance requirements: [Speed, scalability needs] - Development speed: [Time to market priorities] - Maintenance: [Long-term maintenance considerations] - Budget: [Cost constraints for development and operations] **Specific Questions:** [What specific aspects of the decision do you need help with?] Please activate the backend-architect agent for expert technology recommendations and decision support.`, timeEstimate: '20-35 minutes' } }; const action = actions[quickType]; if (!action) { throw new Error(`Unknown quick action: ${quickType}`); } const content = `# ${action.title} ${action.description} ⚔ **Estimated Time:** ${action.timeEstimate} ## Quick Action Prompt Copy and fill in this prompt for immediate assistance: --- ${action.prompt} --- ## How to Execute This quick action will use the **${action.agent}** agent for rapid results: 1. **Fill in the prompt** above with your specific details 2. **Copy the completed prompt** 3. **Paste it in your conversation** - Claude will automatically activate the ${action.agent} agent 4. **Get quick results** and actionable recommendations 5. **Follow up** with additional questions if needed ## Agent Details **Specialist:** \`${action.agent}\` **Focus:** Fast, actionable solutions for immediate needs **Tool Used:** \`activate_agent\` The ${action.agent} agent is optimized for quick turnaround and practical solutions. --- *This is a quick action resource. Fill in the prompt above and use it for immediate assistance.*`; return { contents: [ { type: 'text', text: content } ] }; } async start(): Promise<void> { try { info('šŸš€ Starting Worksona MCP Server...'); // Pre-load agents info('šŸ“š Loading Worksona agents...'); await this.agentRegistry.loadAllAgents(); const stats = this.agentRegistry.getAgentStats(); success(`Loaded ${stats.totalAgents} agents from ${Object.keys(stats.categoryCounts).length} categories`); // Setup STDIO handler this.setupStdioHandler(); success('Worksona MCP server is running and ready for requests!'); } catch (startupError) { error('Failed to start MCP server', startupError); process.exit(1); } } } // Handle uncaught exceptions process.on('uncaughtException', (err) => { error('Uncaught Exception', err); process.exit(1); }); process.on('unhandledRejection', (reason, promise) => { error('Unhandled Rejection at:', promise, 'reason:', reason); process.exit(1); }); // Start the server if (require.main === module) { const server = new WorksonaMCPServer(); server.start().catch(err => { error('Server startup failed', err); process.exit(1); }); } export default WorksonaMCPServer;

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/worksona/-worksona-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server