|
| 1 | +import { z } from "zod"; |
| 2 | +import { tool } from "../../tool"; |
| 3 | +import { mcpError, toContent } from "../../util"; |
| 4 | +import { testRuleset } from "../../../gcp/rules"; |
| 5 | +import { resolve } from "path"; |
| 6 | +import { Client } from "../../../apiv2"; |
| 7 | +import { updateRulesWithClient } from "../../../rtdb"; |
| 8 | +import { getErrMsg } from "../../../error"; |
| 9 | +import { getDefaultDatabaseInstance } from "../../../getDefaultDatabaseInstance"; |
| 10 | + |
| 11 | +interface SourcePosition { |
| 12 | + fileName?: string; |
| 13 | + line?: number; |
| 14 | + column?: number; |
| 15 | + currentOffset?: number; |
| 16 | + endOffset?: number; |
| 17 | +} |
| 18 | + |
| 19 | +interface Issue { |
| 20 | + sourcePosition: SourcePosition; |
| 21 | + description: string; |
| 22 | + severity: string; |
| 23 | +} |
| 24 | + |
| 25 | +function formatRulesetIssues(issues: Issue[], rulesSource: string): string { |
| 26 | + const sourceLines = rulesSource.split("\n"); |
| 27 | + const formattedOutput: string[] = []; |
| 28 | + |
| 29 | + for (const issue of issues) { |
| 30 | + const { sourcePosition, description, severity } = issue; |
| 31 | + |
| 32 | + let issueString = `${severity}: ${description} [Ln ${sourcePosition.line}, Col ${sourcePosition.column}]`; |
| 33 | + |
| 34 | + if (sourcePosition.line) { |
| 35 | + const lineIndex = sourcePosition.line - 1; |
| 36 | + if (lineIndex >= 0 && lineIndex < sourceLines.length) { |
| 37 | + const errorLine = sourceLines[lineIndex]; |
| 38 | + issueString += `\n\`\`\`\n${errorLine}`; |
| 39 | + |
| 40 | + if ( |
| 41 | + sourcePosition.column && |
| 42 | + sourcePosition.currentOffset && |
| 43 | + sourcePosition.endOffset && |
| 44 | + sourcePosition.column > 0 && |
| 45 | + sourcePosition.endOffset > sourcePosition.currentOffset |
| 46 | + ) { |
| 47 | + const startColumnOnLine = sourcePosition.column - 1; |
| 48 | + const errorTokenLength = sourcePosition.endOffset - sourcePosition.currentOffset; |
| 49 | + |
| 50 | + if ( |
| 51 | + startColumnOnLine >= 0 && |
| 52 | + errorTokenLength > 0 && |
| 53 | + startColumnOnLine <= errorLine.length |
| 54 | + ) { |
| 55 | + const padding = " ".repeat(startColumnOnLine); |
| 56 | + const carets = "^".repeat(errorTokenLength); |
| 57 | + issueString += `\n${padding}${carets}\n\`\`\``; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + formattedOutput.push(issueString); |
| 63 | + } |
| 64 | + return formattedOutput.join("\n\n"); |
| 65 | +} |
| 66 | + |
| 67 | +export const validate_rules = tool( |
| 68 | + { |
| 69 | + name: "validate_rules", |
| 70 | + description: |
| 71 | + "Use this to check Firebase Security Rules for Firestore, Storage, or Realtime Database for syntax and validation errors.", |
| 72 | + inputSchema: z.object({ |
| 73 | + type: z.enum(["firestore", "storage", "rtdb"]), |
| 74 | + source: z |
| 75 | + .string() |
| 76 | + .optional() |
| 77 | + .describe("The rules source code to check. Provide either this or a path."), |
| 78 | + source_file: z |
| 79 | + .string() |
| 80 | + .optional() |
| 81 | + .describe( |
| 82 | + "A file path, relative to the project root, to a file containing the rules source you want to validate. Provide this or source, not both.", |
| 83 | + ), |
| 84 | + }), |
| 85 | + annotations: { |
| 86 | + title: "Validate Firebase Security Rules", |
| 87 | + readOnlyHint: true, |
| 88 | + }, |
| 89 | + _meta: { |
| 90 | + requiresProject: true, |
| 91 | + requiresAuth: true, |
| 92 | + }, |
| 93 | + }, |
| 94 | + async ({ type, source, source_file }, { projectId, config, host }) => { |
| 95 | + let rulesSourceContent: string; |
| 96 | + if (source && source_file) { |
| 97 | + return mcpError("Must supply `source` or `source_file`, not both."); |
| 98 | + } else if (source_file) { |
| 99 | + try { |
| 100 | + const filePath = resolve(source_file, host.cachedProjectDir!); |
| 101 | + if (filePath.includes("../")) |
| 102 | + return mcpError("Cannot read files outside of the project directory."); |
| 103 | + rulesSourceContent = config.readProjectFile(source_file); |
| 104 | + } catch (e: any) { |
| 105 | + return mcpError(`Failed to read source_file '${source_file}': ${e.message}`); |
| 106 | + } |
| 107 | + } else if (source) { |
| 108 | + rulesSourceContent = source; |
| 109 | + } else { |
| 110 | + return mcpError("Must supply at least one of `source` or `source_file`."); |
| 111 | + } |
| 112 | + |
| 113 | + if (type === "rtdb") { |
| 114 | + const dbUrl = await getDefaultDatabaseInstance(projectId); |
| 115 | + const client = new Client({ urlPrefix: dbUrl }); |
| 116 | + try { |
| 117 | + await updateRulesWithClient(client, source, { dryRun: true }); |
| 118 | + } catch (e: unknown) { |
| 119 | + host.logger.debug(`failed to validate rules at url ${dbUrl}`); |
| 120 | + // TODO: This really should only return an MCP error if we couldn't validate |
| 121 | + // If the rules are invalid, we should return that as content |
| 122 | + return mcpError(getErrMsg(e)); |
| 123 | + } |
| 124 | + return toContent("The inputted rules are valid!"); |
| 125 | + } |
| 126 | + |
| 127 | + // Firestore and Storage |
| 128 | + const result = await testRuleset(projectId, [ |
| 129 | + { name: "test.rules", content: rulesSourceContent }, |
| 130 | + ]); |
| 131 | + |
| 132 | + if (result.body?.issues?.length) { |
| 133 | + const issues = result.body.issues as unknown as Issue[]; |
| 134 | + let out = `Found ${issues.length} issues in rules source:\n\n`; |
| 135 | + out += formatRulesetIssues(issues, rulesSourceContent); |
| 136 | + return toContent(out); |
| 137 | + } |
| 138 | + |
| 139 | + return toContent("OK: No errors detected."); |
| 140 | + }, |
| 141 | +); |
0 commit comments