|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; |
| 10 | +import { z } from 'zod'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Registers the `find_examples` tool with the MCP server. |
| 14 | + * |
| 15 | + * This tool allows users to search for best-practice Angular code examples |
| 16 | + * from a local SQLite database. |
| 17 | + * |
| 18 | + * @param server The MCP server instance. |
| 19 | + * @param exampleDatabasePath The path to the SQLite database file containing the examples. |
| 20 | + */ |
| 21 | +export async function registerFindExampleTool( |
| 22 | + server: McpServer, |
| 23 | + exampleDatabasePath: string, |
| 24 | +): Promise<void> { |
| 25 | + let db: import('node:sqlite').DatabaseSync | undefined; |
| 26 | + let queryStatement: import('node:sqlite').StatementSync | undefined; |
| 27 | + |
| 28 | + server.registerTool( |
| 29 | + 'find_examples', |
| 30 | + { |
| 31 | + title: 'Find Angular Code Examples', |
| 32 | + description: |
| 33 | + 'Before writing or modifying any Angular code including templates, ' + |
| 34 | + '**ALWAYS** use this tool to find current best-practice examples. ' + |
| 35 | + 'This is critical for ensuring code quality and adherence to modern Angular standards. ' + |
| 36 | + 'This tool searches a curated database of approved Angular code examples and returns the most relevant results for your query. ' + |
| 37 | + 'Example Use Cases: ' + |
| 38 | + "1) Creating new components, directives, or services (e.g., query: 'standalone component' or 'signal input'). " + |
| 39 | + "2) Implementing core features (e.g., query: 'lazy load route', 'httpinterceptor', or 'route guard'). " + |
| 40 | + "3) Refactoring existing code to use modern patterns (e.g., query: 'ngfor trackby' or 'form validation').", |
| 41 | + inputSchema: { |
| 42 | + query: z.string().describe( |
| 43 | + `Performs a full-text search using FTS5 syntax. The query should target relevant Angular concepts. |
| 44 | +
|
| 45 | +Key Syntax Features (see https://www.sqlite.org/fts5.html for full documentation): |
| 46 | + - AND (default): Space-separated terms are combined with AND. |
| 47 | + - Example: 'standalone component' (finds results with both "standalone" and "component") |
| 48 | + - OR: Use the OR operator to find results with either term. |
| 49 | + - Example: 'validation OR validator' |
| 50 | + - NOT: Use the NOT operator to exclude terms. |
| 51 | + - Example: 'forms NOT reactive' |
| 52 | + - Grouping: Use parentheses () to group expressions. |
| 53 | + - Example: '(validation OR validator) AND forms' |
| 54 | + - Phrase Search: Use double quotes "" for exact phrases. |
| 55 | + - Example: '"template-driven forms"' |
| 56 | + - Prefix Search: Use an asterisk * for prefix matching. |
| 57 | + - Example: 'rout*' (matches "route", "router", "routing") |
| 58 | +
|
| 59 | +Examples of queries: |
| 60 | + - Find standalone components: 'standalone component' |
| 61 | + - Find ngFor with trackBy: 'ngFor trackBy' |
| 62 | + - Find signal inputs: 'signal input' |
| 63 | + - Find lazy loading a route: 'lazy load route' |
| 64 | + - Find forms with validation: 'form AND (validation OR validator)'`, |
| 65 | + ), |
| 66 | + }, |
| 67 | + annotations: { |
| 68 | + readOnlyHint: true, |
| 69 | + openWorldHint: false, |
| 70 | + }, |
| 71 | + }, |
| 72 | + async ({ query }) => { |
| 73 | + if (!db || !queryStatement) { |
| 74 | + suppressSqliteWarning(); |
| 75 | + |
| 76 | + const { DatabaseSync } = await import('node:sqlite'); |
| 77 | + db = new DatabaseSync(exampleDatabasePath, { readOnly: true }); |
| 78 | + queryStatement = db.prepare('SELECT * from examples WHERE examples MATCH ? ORDER BY rank;'); |
| 79 | + } |
| 80 | + |
| 81 | + const sanitizedQuery = sanitizeSearchQuery(query); |
| 82 | + |
| 83 | + // Query database and return results as text content |
| 84 | + const content = []; |
| 85 | + for (const exampleRecord of queryStatement.all(sanitizedQuery)) { |
| 86 | + content.push({ type: 'text' as const, text: exampleRecord['content'] as string }); |
| 87 | + } |
| 88 | + |
| 89 | + return { |
| 90 | + content, |
| 91 | + }; |
| 92 | + }, |
| 93 | + ); |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * Sanitizes a search query for FTS5 by tokenizing and quoting terms. |
| 98 | + * |
| 99 | + * This function processes a raw search string and prepares it for an FTS5 full-text search. |
| 100 | + * It correctly handles quoted phrases, logical operators (AND, OR, NOT), parentheses, |
| 101 | + * and prefix searches (ending with an asterisk), ensuring that individual search |
| 102 | + * terms are properly quoted to be treated as literals by the search engine. |
| 103 | + * |
| 104 | + * @param query The raw search query string. |
| 105 | + * @returns A sanitized query string suitable for FTS5. |
| 106 | + */ |
| 107 | +export function sanitizeSearchQuery(query: string): string { |
| 108 | + // This regex tokenizes the query string into parts: |
| 109 | + // 1. Quoted phrases (e.g., "foo bar") |
| 110 | + // 2. Parentheses ( and ) |
| 111 | + // 3. FTS5 operators (AND, OR, NOT, NEAR) |
| 112 | + // 4. Words, which can include a trailing asterisk for prefix search (e.g., foo*) |
| 113 | + const tokenizer = /"([^"]*)"|([()])|\b(AND|OR|NOT|NEAR)\b|([^\s()]+)/g; |
| 114 | + let match; |
| 115 | + const result: string[] = []; |
| 116 | + let lastIndex = 0; |
| 117 | + |
| 118 | + while ((match = tokenizer.exec(query)) !== null) { |
| 119 | + // Add any whitespace or other characters between tokens |
| 120 | + if (match.index > lastIndex) { |
| 121 | + result.push(query.substring(lastIndex, match.index)); |
| 122 | + } |
| 123 | + |
| 124 | + const [, quoted, parenthesis, operator, term] = match; |
| 125 | + |
| 126 | + if (quoted !== undefined) { |
| 127 | + // It's a quoted phrase, keep it as is. |
| 128 | + result.push(`"${quoted}"`); |
| 129 | + } else if (parenthesis) { |
| 130 | + // It's a parenthesis, keep it as is. |
| 131 | + result.push(parenthesis); |
| 132 | + } else if (operator) { |
| 133 | + // It's an operator, keep it as is. |
| 134 | + result.push(operator); |
| 135 | + } else if (term) { |
| 136 | + // It's a term that needs to be quoted. |
| 137 | + if (term.endsWith('*')) { |
| 138 | + result.push(`"${term.slice(0, -1)}"*`); |
| 139 | + } else { |
| 140 | + result.push(`"${term}"`); |
| 141 | + } |
| 142 | + } |
| 143 | + lastIndex = tokenizer.lastIndex; |
| 144 | + } |
| 145 | + |
| 146 | + // Add any remaining part of the string |
| 147 | + if (lastIndex < query.length) { |
| 148 | + result.push(query.substring(lastIndex)); |
| 149 | + } |
| 150 | + |
| 151 | + return result.join(''); |
| 152 | +} |
| 153 | + |
| 154 | +/** |
| 155 | + * Suppresses the experimental warning emitted by Node.js for the `node:sqlite` module. |
| 156 | + * |
| 157 | + * This is a workaround to prevent the console from being cluttered with warnings |
| 158 | + * about the experimental status of the SQLite module, which is used by this tool. |
| 159 | + */ |
| 160 | +function suppressSqliteWarning() { |
| 161 | + const originalProcessEmit = process.emit; |
| 162 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 163 | + process.emit = function (event: string, error?: unknown): any { |
| 164 | + if ( |
| 165 | + event === 'warning' && |
| 166 | + error instanceof Error && |
| 167 | + error.name === 'ExperimentalWarning' && |
| 168 | + error.message.includes('SQLite') |
| 169 | + ) { |
| 170 | + return false; |
| 171 | + } |
| 172 | + |
| 173 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any, prefer-rest-params |
| 174 | + return originalProcessEmit.apply(process, arguments as any); |
| 175 | + }; |
| 176 | +} |
0 commit comments