Development Workflow
Development Workflow
Section titled “Development Workflow”Version: 1.0.13
Status: Active
Category: Development Process
Table of Contents
Section titled “Table of Contents”- Overview
- Development Setup
- Build Process
- Testing Strategy
- Git Workflow
- Implementation Methodology
- Current Priorities
- Debugging Guide
- Performance Optimization
Overview
Section titled “Overview”This document outlines the development workflow for the puppeteer-mcp project, including setup, build processes, testing strategies, and implementation methodologies that have proven successful.
Current Project Status
Section titled “Current Project Status”- Build Status: ✅ Clean builds, zero TypeScript errors
- Test Status: ✅ 20/20 test suites passing
- ESLint Status: ✅ 78 warnings, 0 errors
- Beta Release: ✅ All systems operational
Development Setup
Section titled “Development Setup”Prerequisites
Section titled “Prerequisites”- Node.js 20+ (LTS recommended)
- npm 10+
- Chrome/Chromium (for Puppeteer)
- Git with configured hooks
Initial Setup
Section titled “Initial Setup”# Clone the repositorygit clone https://github.com/your-org/puppeteer-mcp.gitcd puppeteer-mcp
# Install dependencies (includes Puppeteer)npm install
# Verify setupnpm run typecheck # Should show 0 errorsnpm run lint # Should show warnings onlynpm test # Should pass all tests
# Start development servernpm run dev
Environment Configuration
Section titled “Environment Configuration”Create a .env
file for local development:
# Server ConfigurationNODE_ENV=developmentPORT=3000LOG_LEVEL=debug
# SecurityJWT_SECRET=your-secret-key-for-developmentAPI_KEY_SALT=your-salt-for-development
# Browser AutomationPUPPETEER_HEADLESS=trueBROWSER_POOL_MAX_SIZE=5BROWSER_IDLE_TIMEOUT=300000
# Feature FlagsENABLE_MCP=trueENABLE_GRPC=trueENABLE_WEBSOCKET=true
Build Process
Section titled “Build Process”Current Build Status
Section titled “Current Build Status”All build commands are working and produce clean output:
npm run build # ✅ Production buildnpm run dev # ✅ Development server with hot reloadnpm run typecheck # ✅ TypeScript compilation checknpm run lint # ✅ ESLint with security pluginnpm run format # ✅ Prettier formatting
Build Commands Explained
Section titled “Build Commands Explained”TypeScript Compilation
Section titled “TypeScript Compilation”npm run typecheck# Runs: tsc --noEmit# Checks types without generating files# Current status: 0 errors ✅
Linting
Section titled “Linting”npm run lint# Runs: eslint src tests --ext .ts,.tsx# Current status: 78 warnings, 0 errors ✅# Target: <50 warnings
# Fix auto-fixable issuesnpm run lint:fix
Development Server
Section titled “Development Server”npm run dev# Runs: tsx watch src/index.ts# Features:# - Hot reload on file changes# - Source map support# - Debug logging enabled# - Browser pool initialized
Production Build
Section titled “Production Build”npm run build# Runs: tsc && tsc-alias# Features:# - Optimized for production# - Path aliases resolved# - Source maps included
Testing Strategy
Section titled “Testing Strategy”Test Organization
Section titled “Test Organization”tests/├── unit/ # Unit tests for individual components├── integration/ # Integration tests for subsystems├── e2e/ # End-to-end tests across protocols└── fixtures/ # Test data and mocks
Running Tests
Section titled “Running Tests”# Run all testsnpm test # ✅ 20/20 test suites passing
# Run specific test suitesnpm test -- src/auth/npm test -- src/puppeteer/
# Run tests in watch mode (TDD)npm run test:watch
# Run with coveragenpm run test:coverage
# Run specific test typesnpm run test:unitnpm run test:integration # Currently disabled for stabilitynpm run test:e2e
# Run performance benchmarksnpm run test:benchmark
Test Categories
Section titled “Test Categories”Unit Tests
Section titled “Unit Tests”Fast, isolated tests for individual functions:
# Browser automation unit testsnpm test -- tests/unit/puppeteer/
# Auth system unit testsnpm test -- tests/unit/auth/
Integration Tests
Section titled “Integration Tests”Test component interactions:
# Currently disabled for stability# npm run test:integration
# When re-enabled, will test:# - Protocol integrations# - Database interactions# - External service calls
E2E Tests
Section titled “E2E Tests”Full system tests across all protocols:
npm run test:e2e
# Tests include:# - REST API workflows# - gRPC service calls# - WebSocket connections# - MCP tool execution# - Browser automation flows
Coverage Requirements
Section titled “Coverage Requirements”{ "global": { "branches": 80, "functions": 85, "lines": 85, "statements": 85 }, "auth": { "branches": 95, "functions": 95, "lines": 95, "statements": 95 }, "utils": { "branches": 100, "functions": 100, "lines": 100, "statements": 100 }}
Git Workflow
Section titled “Git Workflow”Branch Strategy
Section titled “Branch Strategy”main # Beta release code├── develop # Integration branch├── feature/* # New features├── fix/* # Bug fixes├── refactor/* # Code improvements└── test/* # Test improvements
Commit Process
Section titled “Commit Process”Pre-commit hooks automatically run via Husky:
- ESLint - Checks for code quality issues
- Prettier - Formats code consistently
- TypeScript - Compiles without errors
- Tests - Runs tests for changed files
Commit Message Format
Section titled “Commit Message Format”Follow conventional commits:
# Format: type(scope): subject
# Types:feat # New featurefix # Bug fixdocs # Documentation onlystyle # Formatting, missing semicolons, etcrefactor # Code change that neither fixes a bug nor adds a featureperf # Performance improvementtest # Adding missing testschore # Changes to build process or auxiliary tools
# Examples:feat(auth): add JWT refresh token supportfix(grpc): handle connection timeout properlytest(session): add edge case coveragedocs(api): update OpenAPI specrefactor(browser): extract pool management logicperf(ws): optimize message serialization
Pull Request Process
Section titled “Pull Request Process”-
Create feature branch
Terminal window git checkout -b feature/new-browser-action -
Make changes following standards
- Write tests first (TDD)
- Implement feature
- Ensure standards compliance
-
Commit changes
Terminal window git add .git commit -m "feat(browser): add pdf generation action" -
Push and create PR
Terminal window git push -u origin feature/new-browser-action# Create PR via GitHub -
PR Checklist
- Tests pass
- TypeScript compiles
- ESLint warnings not increased
- Documentation updated
- NIST tags added (if security-related)
Implementation Methodology
Section titled “Implementation Methodology”Proven Implementation Approach
Section titled “Proven Implementation Approach”This methodology has been proven successful in this project:
-
Start with Tests
// Write failing test that defines behaviorit('should generate PDF from page', async () => {const result = await executor.execute({type: 'pdf',params: { format: 'A4' },});expect(result.buffer).toBeInstanceOf(Buffer);}); -
Minimal Implementation
// Write just enough code to passasync function executePdf(params: PdfParams): Promise<Buffer> {const page = await this.getPage();return page.pdf(params);} -
Wire into System
// Integrate with existing componentsACTION_HANDLERS.set('pdf', executePdf); -
Verify Standards
- Function complexity ≤10
- File size ≤300 lines
- Security validation added
- NIST tags applied
-
Document
- Update API documentation
- Add usage examples
- Update changelog
Task Delegation Pattern
Section titled “Task Delegation Pattern”For complex features, delegate to subagents:
// Example: Implementing new WebSocket feature// Delegate these tasks in parallel:
Task 1: "Search for existing WebSocket message patterns"Task 2: "Design message schema with Zod validation"Task 3: "Implement handler following existing patterns"Task 4: "Create comprehensive test suite"Task 5: "Add security validation and NIST tags"Task 6: "Update MCP tools to support new feature"
Current Priorities
Section titled “Current Priorities”High Priority ⚠️
Section titled “High Priority ⚠️”1. Test Stability
Section titled “1. Test Stability”Goal: Fix 64 failing tests Focus: Browser automation teardown issues
# Identify failing testsnpm test -- --listTests | grep fail
# Debug specific testnpm test -- --runInBand path/to/test.ts
# Common issues:# - Resource cleanup in afterEach# - Browser pool not releasing# - Async operations not awaited
2. ESLint Cleanup
Section titled “2. ESLint Cleanup”Goal: Reduce warnings from 78 to <50 Approach: Systematic, targeted fixes
# Get warning summarynpm run lint -- --format=compact
# Fix specific rule violationsnpm run lint:fix -- --rule=@typescript-eslint/no-explicit-any
# Priority rules to fix:# - no-explicit-any# - prefer-const# - no-unused-vars
3. Browser Test Reliability
Section titled “3. Browser Test Reliability”Goal: Improve Puppeteer test cleanup Focus: Resource management
// Ensure proper cleanupafterEach(async () => { await page?.close(); await browser?.close(); await pool?.drain();});
Medium Priority 🔄
Section titled “Medium Priority 🔄”1. Type Safety Enhancement
Section titled “1. Type Safety Enhancement”Goal: Eliminate remaining any
types
# Find any usagegrep -r "any" src/ --include="*.ts" | grep -v "// eslint-disable"
# Replace with proper types# Before: any# After: unknown | specific type
2. Performance Monitoring
Section titled “2. Performance Monitoring”Goal: Add browser operation metrics
// Add timing to all browser actionsconst start = performance.now();const result = await executeAction(action);const duration = performance.now() - start;
metrics.histogram('browser.action.duration', duration, { action: action.type,});
3. Documentation Generation
Section titled “3. Documentation Generation”Goal: Create OpenAPI specs from code
# Generate OpenAPI from routesnpm run generate:openapi
# Generate TypeDocnpm run generate:docs
Future Enhancements 🚀
Section titled “Future Enhancements 🚀”-
Visual Regression Testing
- Screenshot comparison framework
- Baseline management
- Diff visualization
-
Multi-browser Support
- Firefox via Playwright
- Safari via Playwright
- Cross-browser testing
-
Advanced Monitoring
- Distributed tracing (OpenTelemetry)
- Custom dashboards
- Alert rules
-
Performance Optimization
- Browser warm pools
- Connection reuse
- Caching strategies
Maintenance Tasks 🔧
Section titled “Maintenance Tasks 🔧”Weekly
Section titled “Weekly”- Dependency updates:
npm update
- Security audit:
npm audit
- Performance benchmarks:
npm run test:benchmark
Monthly
Section titled “Monthly”- Full ESLint review
- Test coverage analysis
- Documentation review
- Performance profiling
Debugging Guide
Section titled “Debugging Guide”Common Issues and Solutions
Section titled “Common Issues and Solutions”Browser Won’t Start
Section titled “Browser Won’t Start”# Check Chrome installationwhich chromium-browser || which chrome || which google-chrome
# Test Puppeteer directlynode -e "const p = require('puppeteer'); p.launch().then(b => b.close())"
# Enable debug loggingDEBUG=puppeteer:* npm run dev
Memory Leaks
Section titled “Memory Leaks”# Monitor memory usagenpm run dev -- --inspect
# Use Chrome DevTools# 1. Open chrome://inspect# 2. Click "inspect" on Node process# 3. Take heap snapshots# 4. Look for retained objects
Test Failures
Section titled “Test Failures”# Run single test with debuggingnode --inspect-brk node_modules/.bin/jest path/to/test.ts
# Enable verbose loggingnpm test -- --verbose --runInBand
# Common fixes:# 1. Add proper async/await# 2. Increase timeouts for browser tests# 3. Ensure cleanup in afterEach# 4. Check for race conditions
TypeScript Errors
Section titled “TypeScript Errors”# Get detailed error infonpm run typecheck -- --listFiles
# Check specific filenpx tsc --noEmit src/specific/file.ts
# Common fixes:# 1. Add explicit types# 2. Use type assertions carefully# 3. Update tsconfig paths
Debug Commands
Section titled “Debug Commands”# Health checkcurl http://localhost:8443/api/v1/health
# Test specific endpointcurl -X POST http://localhost:8443/api/v1/sessions \ -H "Content-Type: application/json" \ -d '{"userId": "test-user"}'
# Monitor WebSocketwscat -c ws://localhost:8443/ws
# Test gRPC servicegrpcurl -plaintext localhost:50051 list
Performance Optimization
Section titled “Performance Optimization”Current Performance Metrics
Section titled “Current Performance Metrics”- REST API: <100ms p95 ✅
- gRPC calls: <50ms p95 ✅
- WebSocket: <10ms echo ✅
- Browser actions: <5s p95 ✅
- Startup time: <3s ✅
Optimization Strategies
Section titled “Optimization Strategies”1. Browser Pool Optimization
Section titled “1. Browser Pool Optimization”// Implement warm poolconst warmPool = new WarmBrowserPool({ min: 2, // Always keep 2 browsers ready max: 10, // Scale up to 10 under load});
// Pre-launch browsersawait warmPool.initialize();
2. Caching Strategy
Section titled “2. Caching Strategy”// Cache frequently accessed dataconst cache = new LRUCache<string, Session>({ max: 1000, ttl: 1000 * 60 * 5, // 5 minutes});
// Use cache with fallbackasync function getSession(id: string): Promise<Session> { return cache.get(id) || (await store.getSession(id));}
3. Query Optimization
Section titled “3. Query Optimization”// Batch operations when possibleasync function getSessions(ids: string[]): Promise<Session[]> { // Instead of N queries // return Promise.all(ids.map(id => store.get(id)));
// Single batch query return store.getBatch(ids);}
Performance Monitoring
Section titled “Performance Monitoring”# Run benchmarksnpm run test:benchmark
# Profile CPU usagenode --prof dist/index.jsnode --prof-process isolate-*.log > profile.txt
# Monitor in production# - Use APM tools (DataDog, New Relic)# - Custom metrics with Prometheus# - Real user monitoring (RUM)
Summary
Section titled “Summary”This workflow has been refined through the successful implementation of a beta browser automation platform. Key principles:
- Standards First: Always check and follow standards
- Test-Driven: Write tests before implementation
- Incremental: Small, focused changes
- Automated: Let tools handle formatting and checks
- Documented: Keep docs in sync with code
For additional context:
- Standards details:
docs/development/standards.md
- AI patterns:
docs/ai/routing-patterns.md
- Lessons learned:
docs/lessons/implementation.md