Skip to main content
Glama

Design Patterns MCP Server

by apolosan
README.mdโ€ข17.3 kB
# Design Patterns MCP Server ๐ŸŽฏ An intelligent MCP (Model Context Protocol) server that provides design pattern recommendations using semantic search and vector embeddings. This project offers access to a comprehensive catalog of **555+ design patterns** through a natural language interface. ## ๐Ÿ“‹ Overview The **Design Patterns MCP Server** is a specialized server that integrates with AI assistants (like Claude, Cursor) to provide intelligent design pattern recommendations. It uses advanced semantic search technologies to find the most appropriate patterns based on natural language problem descriptions. ### โœจ Key Features - ๐Ÿ” **Intelligent Semantic Search**: Find patterns using natural problem descriptions - ๐Ÿ“š **Comprehensive Catalog**: 555+ patterns organized in 20+ categories - ๐ŸŽฏ **Contextual Recommendations**: Suggestions based on programming language and domain - โšก **Vector Search**: Uses SQLite with vector extensions for efficient search - ๐ŸŒ **Multi-language**: Support for multiple programming languages - ๐Ÿ”ง **MCP Integration**: Compatible with Claude Code, Cursor and other MCP clients - ๐Ÿš€ **High Performance**: Object Pool pattern prevents memory leaks, 30-40% faster queries - ๐Ÿ’พ **Smart Caching**: LRU cache with 85%+ hit rate - ๐Ÿ—๏ธ **SOLID Architecture**: Clean, maintainable, and testable codebase ### ๐Ÿ†• Recent Improvements (v0.2.1) **Architecture Refactoring (October 2025)** - โœ… **Object Pool Pattern**: Eliminates memory leaks with bounded prepared statements - โœ… **Service Layer**: Centralized business logic with `PatternService` - โœ… **Facade Pattern**: Simplified handlers via `PatternHandlerFacade` - โœ… **Dependency Injection**: Full DI Container integration for testability - โœ… **Performance**: 30-40% faster on repeated queries with smart caching - โœ… **Code Quality**: 40% reduction in main server file (704โ†’422 lines) - โœ… **Pattern Catalog**: Expanded to 555+ patterns with code examples ### ๐Ÿ—‚๏ธ Available Pattern Categories - **GoF Patterns**: Classic patterns (Creational, Structural, Behavioral) - **Architectural Patterns**: MVC, MVP, MVVM, Clean Architecture, Hexagonal - **Microservices Patterns**: Circuit Breaker, Event Sourcing, CQRS, Saga - **Cloud Patterns**: Auto-scaling, Load Balancing, Service Discovery - **AI/ML Patterns**: Model Training, RAG, Few-Shot Learning, Continual Learning - **React Patterns**: Hooks, Server Components, Suspense, React 19 features - **Enterprise Patterns**: Repository, Unit of Work, Dependency Injection - **Security Patterns**: Authentication, Authorization, Data Protection - **Performance Patterns**: Caching, Lazy Loading, Object Pool, Connection Pooling - **Concurrency Patterns**: Producer-Consumer, Thread Pool, Actor Model - **Integration Patterns**: Message Queue, Event Bus, API Gateway - **Data Access Patterns**: Active Record, Data Mapper, Query Object - **Testing Patterns**: Test Double, Page Object, Builder Pattern for tests - **Functional Patterns**: Monads, Functors, Higher-Order Functions - **Reactive Patterns**: Observer, Publisher-Subscriber, Reactive Streams - **DDD Patterns**: Aggregate, Value Object, Domain Service, Bounded Context - **Game Development Patterns**: State Machine, Component System, Object Pool - **Mobile Patterns**: Model-View-Intent, Redux-like patterns, Offline-First - **IoT Patterns**: Device Twin, Telemetry Ingestion, Edge Processing - **Blockchain/Web3 Patterns**: DeFi, NFT, DAO, Cross-chain - **Anti-Patterns**: Practices to avoid and their solutions ## ๐Ÿ—๏ธ Project Architecture ### Refactored Architecture (v0.2.x) ``` src/ โ”œโ”€โ”€ adapters/ # Adapters for external services (LLM, Embeddings) โ”œโ”€โ”€ builders/ # Builders for complex objects โ”œโ”€โ”€ cli/ # Command line interface โ”œโ”€โ”€ core/ # Core domain logic and DI Container โ”‚ โ””โ”€โ”€ container.ts # Dependency Injection Container with TOKENS โ”œโ”€โ”€ db/ # Database configuration and migrations โ”œโ”€โ”€ facades/ # Facade pattern implementations โ”‚ โ””โ”€โ”€ pattern-handler-facade.ts # Simplifies MCP handlers โ”œโ”€โ”€ factories/ # Factories for object creation โ”œโ”€โ”€ lib/ # Auxiliary libraries and MCP utilities โ”œโ”€โ”€ models/ # Data models and types (unified Pattern interface) โ”œโ”€โ”€ repositories/ # Data access layer (Repository Pattern) โ”‚ โ”œโ”€โ”€ interfaces.ts # Repository contracts โ”‚ โ””โ”€โ”€ pattern-repository.ts # SQLite implementation โ”œโ”€โ”€ services/ # Business services and orchestration โ”‚ โ”œโ”€โ”€ cache.ts # LRU Cache service โ”‚ โ”œโ”€โ”€ database-manager.ts # Database operations with Object Pool โ”‚ โ”œโ”€โ”€ pattern-service.ts # Service Layer for business logic โ”‚ โ”œโ”€โ”€ statement-pool.ts # Object Pool for prepared statements โ”‚ โ””โ”€โ”€ semantic-search.ts # Semantic search operations โ”œโ”€โ”€ strategies/ # Strategy pattern implementations โ”œโ”€โ”€ types/ # TypeScript type definitions โ”œโ”€โ”€ utils/ # Utility functions โ””โ”€โ”€ mcp-server.ts # MCP server data/ โ”œโ”€โ”€ patterns/ # JSON files with 555+ pattern definitions โ””โ”€โ”€ design-patterns.db # SQLite database with embeddings ``` ### ๐Ÿ”ง Main Components **Core Services** - **DatabaseManager**: SQLite operations with Object Pool (prevents memory leaks) - **StatementPool**: LRU-based pool for prepared statements (max 100) - **CacheService**: In-memory LRU cache with TTL and metrics **Business Logic** - **PatternService**: Service Layer orchestrating pattern operations - **PatternRepository**: Data access abstraction (Repository Pattern) - **SemanticSearchService**: Semantic search with embeddings - **PatternMatcher**: Pattern matching and ranking logic **Integration** - **PatternHandlerFacade**: Facade simplifying MCP handlers - **VectorOperationsService**: Vector search using sqlite-vec - **LLMBridgeService**: Interface for language models (optional) - **EmbeddingServiceAdapter**: Adapter for embedding services **Infrastructure** - **SimpleContainer**: Dependency Injection container - **MigrationManager**: Database migrations - **PatternSeeder**: Initial data seeding ## ๐Ÿš€ Installation and Setup ### Prerequisites - Node.js >= 18.0.0 - npm >= 8.0.0 or Bun >= 1.0.0 ### Installation ```bash # Clone the repository git clone https://github.com/your-org/design-patterns-mcp.git cd design-patterns-mcp # Install dependencies npm install # Configure environment variables (optional) cp .env.example .env # Build the project npm run build # Setup the database npm run db:setup ``` ### MCP Configuration Add to your MCP configuration file (`.mcp.json` or Claude Desktop config): ```json { "mcpServers": { "design-patterns": { "command": "node", "args": ["dist/src/mcp-server.js"], "cwd": "/path/to/design-patterns-mcp", "env": { "LOG_LEVEL": "info", "DATABASE_PATH": "./data/design-patterns.db" } } } } ``` ## ๐Ÿ“– Usage ### Finding Patterns with Natural Language Use natural language descriptions to find appropriate design patterns through Claude Code: **For object creation problems:** - "I need to create complex objects with many optional configurations" - "How can I create different variations of similar objects?" - "What pattern helps with step-by-step object construction?" **For behavioral problems:** - "I need to notify multiple components when data changes" - "How to decouple command execution from the invoker?" - "What pattern helps with state-dependent behavior?" **For architectural problems:** - "How to structure a microservices communication system?" - "What pattern helps with distributed system resilience?" - "How to implement clean separation between layers?" **For React development:** - "How to manage state in React 18/19?" - "What patterns work with React Server Components?" - "How to optimize React performance?" ### MCP Tool Functions - **find_patterns**: Semantic search for patterns using problem descriptions - Returns ranked recommendations with confidence scores - Supports category filtering and programming language preferences - **search_patterns**: Keyword or semantic search with filtering options - Supports hybrid search (keyword + semantic) - Filter by category, tags, complexity - **get_pattern_details**: Get comprehensive information about specific patterns - Includes code examples in multiple languages - Shows similar patterns and relationships - Displays implementations and use cases - **count_patterns**: Statistics about available patterns by category - Optional detailed breakdown by category ## ๐Ÿ› ๏ธ Available Commands ```bash # Development npm run build # Build for production npm run dev # Run in development mode npm start # Start production server # Testing & Quality npm test # Run all tests npm run lint # Check code quality npm run lint:fix # Fix linting issues npm run typecheck # Check TypeScript types # Database npm run db:setup # Complete database setup (migrate + seed + embeddings) npm run migrate # Run database migrations npm run seed # Populate with initial data npm run generate-embeddings # Generate embeddings for semantic search ``` ## ๐ŸŽฏ Usage Examples ### Problem-Based Pattern Discovery **Distributed Systems:** - "I need a pattern for handling service failures gracefully" โ†’ Circuit Breaker, Bulkhead - "How to implement eventual consistency in distributed data?" โ†’ Event Sourcing, CQRS - "What pattern helps with service discovery and load balancing?" โ†’ Service Registry, API Gateway **Data Validation:** - "I need to validate complex business rules on input data" โ†’ Specification Pattern - "How to compose validation rules dynamically?" โ†’ Chain of Responsibility - "What pattern separates validation logic from business logic?" โ†’ Strategy Pattern **Performance Optimization:** - "I need to cache expensive computations efficiently" โ†’ Cache-Aside, Write-Through - "How to implement lazy loading for large datasets?" โ†’ Lazy Loading, Virtual Proxy - "What pattern helps with connection pooling?" โ†’ Object Pool Pattern ### Category-Specific Searches **Enterprise Applications:** - "Show me enterprise patterns for data access" โ†’ Repository, Unit of Work, Data Mapper - "What patterns help with dependency injection?" โ†’ DI Container, Service Locator - "How to implement domain-driven design?" โ†’ Aggregate, Value Object, Bounded Context **Security Implementation:** - "I need authentication and authorization patterns" โ†’ RBAC, OAuth 2.0, JWT - "What patterns help with secure data handling?" โ†’ Encryption at Rest, Defense in Depth - "How to implement role-based access control?" โ†’ RBAC Pattern, Policy-Based Access ## ๐Ÿ”ง Advanced Configuration ### Environment Variables ```env # Database configuration DATABASE_PATH=./data/design-patterns.db # Logging configuration LOG_LEVEL=info # debug | info | warn | error # LLM integration (optional) ENABLE_LLM=false LLM_PROVIDER=ollama LLM_MODEL=llama3.2 # Performance tuning MAX_CONCURRENT_REQUESTS=10 CACHE_MAX_SIZE=1000 CACHE_TTL=3600000 # 1 hour in ms POOL_MAX_SIZE=100 # Prepared statement pool size ``` ### Using the Refactored Server ```typescript import { createDesignPatternsServer, TOKENS } from './mcp-server.js'; const server = createDesignPatternsServer({ databasePath: './data/design-patterns.db', logLevel: 'info', enableLLM: false, maxConcurrentRequests: 10, }); await server.initialize(); await server.start(); // Access services via DI Container (for testing) const container = server.getContainer(); const patternService = container.get(TOKENS.PATTERN_SERVICE); const cache = container.get(TOKENS.CACHE_SERVICE); ``` ### Performance Monitoring ```typescript // Get Object Pool metrics const db = container.get(TOKENS.DATABASE_MANAGER); const poolMetrics = db.getPoolMetrics(); console.log(poolMetrics); // { // size: 87, // hits: 15420, // misses: 234, // evictions: 12, // hitRate: 0.985 // 98.5% // } // Get Cache metrics const cache = container.get(TOKENS.CACHE_SERVICE); const cacheStats = cache.getStats(); console.log(cacheStats); // { // hits: 8765, // misses: 1234, // size: 876, // hitRate: 0.876 // 87.6% // } ``` ## ๐Ÿ“Š Performance and Scalability ### Performance Characteristics - **Vector Search**: Uses sqlite-vec for efficient search in large volumes - **Object Pool**: Bounded prepared statement cache (max 100) prevents memory leaks - **Intelligent Cache**: LRU cache with 85%+ hit rate in production - **Query Performance**: 30-40% faster on repeated queries vs uncached - **Optimized Indexes**: Specific indexes for different search types - **Pagination**: Support for large result sets - **Metrics**: Built-in performance and usage metrics ### Benchmarks (from tests) ``` Database Queries: - COUNT query: 5.03ms - SELECT with LIMIT: 2.08ms - Filtered SELECT: 3.94ms - Concurrent queries (5): 0.95ms total, 0.19ms avg Cache Operations: - Set operation: 0.09ms - Get operation (hit): 0.08ms - Load test (1000 ops): 1.99ms total, 0.002ms avg Pattern Matching: - First query: 1526ms (includes embedding generation) - Subsequent queries: 100-300ms - Cached queries: 0.05ms (2767x speedup) Throughput: - Sustained operations: 13,592 ops/second - Memory usage: Stable at 16-38MB ``` ## ๐Ÿงช Testing The project includes a comprehensive test suite with **116 passing tests**: - **Contract Tests**: Validate MCP protocol compliance - **Integration Tests**: Test interaction between components - **Performance Tests**: Evaluate search and vectorization performance - **Unit Tests**: Test individual components in isolation ```bash # Run specific test suites npm run test:unit -- --grep "PatternMatcher" npm run test:integration -- --grep "database" npm run test:performance -- --timeout 30000 npm run test:contract # MCP protocol compliance ``` ### Test Coverage - MCP Protocol: โœ… 100% - Core Services: โœ… 95%+ - Performance: โœ… Comprehensive benchmarks - Database: โœ… Full migration & seeding tests ## ๐Ÿ—๏ธ Architecture Patterns Used This project practices what it preaches by implementing: | Pattern | Location | Purpose | | ------------------------ | ------------------------------------ | ---------------------------- | | **Repository** | `repositories/pattern-repository.ts` | Data access abstraction | | **Service Layer** | `services/pattern-service.ts` | Business logic orchestration | | **Object Pool** | `services/statement-pool.ts` | Resource management | | **Facade** | `facades/pattern-handler-facade.ts` | Simplified interface | | **Dependency Injection** | `core/container.ts` | Inversion of control | | **Strategy** | `strategies/search-strategy.ts` | Interchangeable algorithms | | **Factory** | `factories/service-factory.ts` | Object creation | | **Singleton** | Via DI Container | Single instance management | | **Adapter** | `adapters/llm-adapter.ts` | External service integration | ## ๐Ÿค Contributing We welcome contributions! Here's how: 1. Fork the project 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Make your changes following our code style 4. Run tests (`npm test`) and ensure they pass 5. Run linting (`npm run lint:fix`) 6. Commit your changes (`git commit -am 'Add amazing feature'`) 7. Push to the branch (`git push origin feature/amazing-feature`) 8. Open a Pull Request ### Development Guidelines - Follow SOLID principles - Write tests for new features - Update documentation - Use TypeScript strict mode - Follow existing code patterns ## ๐Ÿ“œ License This project is licensed under the MIT License. See [LICENSE](./LICENSE) for details. ## ๐Ÿ”— Useful Links - [Model Context Protocol](https://modelcontextprotocol.io/) - [SQLite Vector Extension](https://github.com/asg017/sqlite-vec) - [Design Patterns Catalog](https://refactoring.guru/design-patterns) - [SOLID Principles](https://en.wikipedia.org/wiki/SOLID) - [Refactoring Guide](./REFACTORING_GUIDE.md) ## ๐Ÿ“ž Support - ๐Ÿ› **Issues**: Report bugs through [GitHub Issues](https://github.com/your-org/design-patterns-mcp/issues) - ๐Ÿ’ฌ **Discussions**: Join [GitHub Discussions](https://github.com/your-org/design-patterns-mcp/discussions) - ๐Ÿ“ง **Email**: apolosan@protonmail.com - ๐Ÿ“š **Documentation**: Comprehensive architecture and refactoring details available in project documentation ## ๐Ÿ™ Acknowledgments - Design patterns from the software engineering community - MCP protocol by Anthropic - SQLite and sqlite-vec for efficient storage and search - Open source contributors --- **Version**: 0.2.1 **Last Updated**: October 2025 **Patterns**: 555+ **Tests**: 116 passing **Performance**: 30-40% improvement vs v0.1.x

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/apolosan/design_patterns_mcp'

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