find_patterns
Discover design patterns for programming problems using semantic search. Describe your challenge in natural language to receive pattern recommendations with implementation examples.
Instructions
Find design patterns matching a problem description using semantic search
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | Natural language description of the problem or requirements | |
| categories | No | Optional: Pattern categories to search in | |
| maxResults | No | Maximum number of recommendations to return | |
| programmingLanguage | No | Target programming language for implementation examples |
Implementation Reference
- src/mcp-server.ts:321-351 (handler)Main execution handler for the 'find_patterns' tool. Validates input, delegates to PatternMatcher service, formats and returns the recommendations as MCP CallToolResult.private async handleFindPatterns(args: unknown): Promise<CallToolResult> { const validatedArgs = InputValidator.validateFindPatternsArgs(args); const request = { id: crypto.randomUUID(), query: validatedArgs.query, categories: validatedArgs.categories, maxResults: validatedArgs.maxResults, programmingLanguage: validatedArgs.programmingLanguage, }; const recommendations = await this.patternMatcher.findMatchingPatterns(request); return { content: [ { type: 'text', text: `Found ${recommendations.length} pattern recommendations:\n\n` + recommendations .map( (rec, index) => `${index + 1}. **${rec.pattern.name}** (${rec.pattern.category})\n` + ` Confidence: ${(rec.confidence * 100).toFixed(1)}%\n` + ` Rationale: ${rec.justification.primaryReason}\n` + ` Benefits: ${rec.justification.benefits.join(', ')}\n` ) .join('\n'), }, ], }; }
- src/mcp-server.ts:158-186 (registration)Registration of the 'find_patterns' tool in the ListToolsRequestSchema handler, including name, description, and input schema definition.{ name: 'find_patterns', description: 'Find design patterns matching a problem description using semantic search', inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Natural language description of the problem or requirements', }, categories: { type: 'array', items: { type: 'string' }, description: 'Optional: Pattern categories to search in', }, maxResults: { type: 'number', description: 'Maximum number of recommendations to return', default: 5, }, programmingLanguage: { type: 'string', description: 'Target programming language for implementation examples', }, }, required: ['query'], }, },
- Detailed input validation and sanitization for 'find_patterns' tool arguments, enforcing types, lengths, allowed values, and throwing MCP errors on invalid input.static validateFindPatternsArgs(args: unknown): { query: string; categories: string[]; maxResults: number; programmingLanguage?: string; } { if (typeof args !== 'object' || args === null) { throw new McpError(ErrorCode.InvalidParams, 'Invalid arguments: expected object'); } const obj = args as Record<string, unknown>; const queryResult = this.validateSearchQuery(obj.query); this.throwIfInvalid(queryResult); const categoriesResult = this.validateCategories(obj.categories); this.throwIfInvalid(categoriesResult); const maxResultsResult = this.validateMaxResults(obj.maxResults); this.throwIfInvalid(maxResultsResult); const langResult = this.validateProgrammingLanguage(obj.programmingLanguage); this.throwIfInvalid(langResult); return { query: queryResult.sanitized as string, categories: (categoriesResult.sanitized as string[]) ?? [], maxResults: (maxResultsResult.sanitized as number) ?? 5, programmingLanguage: langResult.sanitized as string | undefined, }; }
- Core helper implementing the pattern matching algorithm: caching, hybrid semantic/keyword search via performMatching, recommendation building, sorting and limiting results.async findMatchingPatterns(request: PatternRequest): Promise<PatternRecommendation[]> { try { // Check cache first const cacheKey = `pattern_match:${request.query}:${JSON.stringify({ categories: request.categories?.sort(), maxResults: request.maxResults, programmingLanguage: request.programmingLanguage, })}`; const cachedResult = this.cache.get(cacheKey); if (cachedResult) { return cachedResult as PatternRecommendation[]; } const matches = await this.performMatching(request); const recommendations = this.buildRecommendations(matches, request); // Sort by confidence and limit results recommendations.sort((a, b) => b.confidence - a.confidence); const finalResults = recommendations.slice(0, request.maxResults ?? this.config.maxResults); // Cache the results for 30 minutes this.cache.set(cacheKey, finalResults, 1800000); return finalResults; } catch (error) { structuredLogger.error('pattern-matcher', 'Pattern matching failed', error as Error); throw error; } }