Skip to main content
Glama
apolosan

Design Patterns MCP Server

by apolosan

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
NameRequiredDescriptionDefault
queryYesNatural language description of the problem or requirements
categoriesNoOptional: Pattern categories to search in
maxResultsNoMaximum number of recommendations to return
programmingLanguageNoTarget programming language for implementation examples

Implementation Reference

  • 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'),
          },
        ],
      };
    }
  • 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;
      }
    }

Latest Blog Posts

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