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;
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'semantic search' but doesn't explain what this entails—e.g., how results are ranked, whether it's a read-only operation, or any limitations like rate limits or authentication needs. For a tool with no annotation coverage, this leaves critical behavioral traits unspecified.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's function without unnecessary words. It is front-loaded with the core purpose ('Find design patterns...'), making it easy to understand at a glance. Every part of the sentence earns its place by conveying essential information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (semantic search with 4 parameters) and the absence of both annotations and an output schema, the description is insufficient. It doesn't cover behavioral aspects like result format, error handling, or how semantic search works, nor does it explain the relationship between parameters and outcomes. This leaves significant gaps for an AI agent to use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, meaning all parameters are documented in the schema itself. The description adds no additional meaning beyond the schema, such as explaining the 'semantic search' process in relation to the 'query' parameter or how 'categories' affect results. Since the schema does the heavy lifting, the baseline score of 3 is appropriate, but no extra value is provided.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Find design patterns matching a problem description using semantic search.' It specifies the verb ('Find'), resource ('design patterns'), and method ('semantic search'), making the intent unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'search_patterns' or 'count_patterns,' which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'search_patterns' and 'count_patterns' available, it fails to indicate scenarios where this tool is preferred, such as for semantic versus keyword-based searches, or how it differs from 'get_pattern_details.' This lack of comparative context leaves the agent without clear usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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