File size: 25,724 Bytes
7a1ad33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
type PolicyRule,
PolicyDecision,
ApprovalMode,
type SafetyCheckerConfig,
type SafetyCheckerRule,
InProcessCheckerType,
} from './types.js';
import { buildArgsPatterns, isSafeRegExp } from './utils.js';
import {
isValidToolName,
ALL_BUILTIN_TOOL_NAMES,
} from '../tools/tool-names.js';
import { getToolSuggestion } from '../utils/tool-utils.js';
import levenshtein from 'fast-levenshtein';
import fs from 'node:fs/promises';
import path from 'node:path';
import toml from '@iarna/toml';
import { z, type ZodError } from 'zod';
import { isNodeError } from '../utils/errors.js';
import { MCP_TOOL_PREFIX, formatMcpToolName } from '../tools/mcp-tool.js';
/**
* Maximum Levenshtein distance to consider a name a likely typo of a built-in tool.
* Names further from all built-in tools are assumed to be intentional
* (e.g., dynamically registered agent tools) and are not warned about.
*/
const MAX_TYPO_DISTANCE = 3;
/**
* Schema for a single policy rule in the TOML file (before transformation).
*/
const PolicyRuleSchema = z.object({
toolName: z.union([z.string(), z.array(z.string())]),
subagent: z.string().optional(),
mcpName: z.string().optional(),
argsPattern: z.string().optional(),
commandPrefix: z.union([z.string(), z.array(z.string())]).optional(),
commandRegex: z.string().optional(),
decision: z.nativeEnum(PolicyDecision),
// Priority must be in range [0, 999] to prevent tier overflow.
// With tier transformation (tier + priority/1000), this ensures:
// - Tier 1 (default): range [1.000, 1.999]
// - Tier 2 (user): range [2.000, 2.999]
// - Tier 3 (admin): range [3.000, 3.999]
priority: z
.number({
required_error: 'priority is required',
invalid_type_error: 'priority must be a number',
})
.int({ message: 'priority must be an integer' })
.min(0, { message: 'priority must be >= 0' })
.max(999, {
message:
'priority must be <= 999 to prevent tier overflow. Priorities >= 1000 would jump to the next tier.',
}),
modes: z.array(z.nativeEnum(ApprovalMode)).optional(),
interactive: z.boolean().optional(),
toolAnnotations: z.record(z.any()).optional(),
allowRedirection: z.boolean().optional(),
allow_redirection: z.boolean().optional(), // deprecated snake_case for backward compatibility
denyMessage: z.string().optional(),
deny_message: z.string().optional(), // deprecated snake_case for backward compatibility
});
/**
* Schema for a single safety checker rule in the TOML file.
*/
const SafetyCheckerRuleSchema = z.object({
toolName: z.union([z.string(), z.array(z.string())]),
mcpName: z.string().optional(),
argsPattern: z.string().optional(),
commandPrefix: z.union([z.string(), z.array(z.string())]).optional(),
commandRegex: z.string().optional(),
priority: z.number().int().default(0),
modes: z.array(z.nativeEnum(ApprovalMode)).optional(),
toolAnnotations: z.record(z.any()).optional(),
checker: z.discriminatedUnion('type', [
z.object({
type: z.literal('in-process'),
name: z.nativeEnum(InProcessCheckerType),
required_context: z.array(z.string()).optional(),
config: z.record(z.unknown()).optional(),
}),
z.object({
type: z.literal('external'),
name: z.string(),
required_context: z.array(z.string()).optional(),
config: z.record(z.unknown()).optional(),
}),
]),
});
/**
* Schema for the entire policy TOML file.
*/
const PolicyFileSchema = z.object({
rule: z.array(PolicyRuleSchema).optional(),
safety_checker: z.array(SafetyCheckerRuleSchema).optional(),
});
/**
* Type for a raw policy rule from TOML (before transformation).
*/
type PolicyRuleToml = z.infer<typeof PolicyRuleSchema>;
/**
* Types of errors that can occur while loading policy files.
*/
export type PolicyFileErrorType =
| 'file_read'
| 'toml_parse'
| 'schema_validation'
| 'rule_validation'
| 'regex_compilation'
| 'tool_name_warning';
/**
* Detailed error information for policy file loading failures.
*/
export interface PolicyFileError {
filePath: string;
fileName: string;
tier: 'default' | 'extension' | 'user' | 'workspace' | 'admin';
ruleIndex?: number;
errorType: PolicyFileErrorType;
message: string;
details?: string;
suggestion?: string;
severity?: 'error' | 'warning';
}
/**
* Result of loading policies from TOML files.
*/
export interface PolicyLoadResult {
rules: PolicyRule[];
checkers: SafetyCheckerRule[];
errors: PolicyFileError[];
}
export interface PolicyFile {
path: string;
content: string;
}
/**
* Reads policy files from a directory or a single file.
*
* @param policyPath Path to a directory or a .toml file.
* @returns Array of PolicyFile objects.
*/
export async function readPolicyFiles(
policyPath: string,
): Promise<PolicyFile[]> {
let filesToLoad: string[] = [];
let baseDir = '';
try {
const stats = await fs.stat(policyPath);
if (stats.isDirectory()) {
baseDir = policyPath;
const dirEntries = await fs.readdir(policyPath, { withFileTypes: true });
filesToLoad = dirEntries
.filter((entry) => entry.isFile() && entry.name.endsWith('.toml'))
.map((entry) => entry.name);
} else if (stats.isFile() && policyPath.endsWith('.toml')) {
baseDir = path.dirname(policyPath);
filesToLoad = [path.basename(policyPath)];
}
} catch (e) {
if (isNodeError(e) && e.code === 'ENOENT') {
return [];
}
throw e;
}
const results: PolicyFile[] = [];
for (const file of filesToLoad) {
const filePath = path.join(baseDir, file);
const content = await fs.readFile(filePath, 'utf-8');
results.push({ path: filePath, content });
}
return results;
}
/**
* Converts a tier number to a human-readable tier name.
*/
function getTierName(
tier: number,
): 'default' | 'extension' | 'user' | 'workspace' | 'admin' {
if (tier === 1) return 'default';
if (tier === 2) return 'extension';
if (tier === 3) return 'workspace';
if (tier === 4) return 'user';
if (tier === 5) return 'admin';
return 'default';
}
/**
* Formats a Zod validation error into a readable error message.
*/
function formatSchemaError(error: ZodError, ruleIndex: number): string {
const issues = error.issues
.map((issue) => {
const path = issue.path.join('.');
return ` - Field "${path}": ${issue.message}`;
})
.join('\n');
return `Invalid policy rule (rule #${ruleIndex + 1}):\n${issues}`;
}
/**
* Validates shell command convenience syntax rules.
* Returns an error message if invalid, or null if valid.
*/
function validateShellCommandSyntax(
rule: PolicyRuleToml,
ruleIndex: number,
): string | null {
const hasCommandPrefix = rule.commandPrefix !== undefined;
const hasCommandRegex = rule.commandRegex !== undefined;
const hasArgsPattern = rule.argsPattern !== undefined;
if (hasCommandPrefix || hasCommandRegex) {
// Must have exactly toolName = "run_shell_command"
if (rule.toolName !== 'run_shell_command' || Array.isArray(rule.toolName)) {
return (
`Rule #${ruleIndex + 1}: commandPrefix and commandRegex can only be used with toolName = "run_shell_command"\n` +
` Found: toolName = ${JSON.stringify(rule.toolName)}\n` +
` Fix: Set toolName = "run_shell_command" (not an array)`
);
}
// Can't combine with argsPattern
if (hasArgsPattern) {
return (
`Rule #${ruleIndex + 1}: cannot use both commandPrefix/commandRegex and argsPattern\n` +
` These fields are mutually exclusive\n` +
` Fix: Use either commandPrefix/commandRegex OR argsPattern, not both`
);
}
// Can't use both commandPrefix and commandRegex
if (hasCommandPrefix && hasCommandRegex) {
return (
`Rule #${ruleIndex + 1}: cannot use both commandPrefix and commandRegex\n` +
` These fields are mutually exclusive\n` +
` Fix: Use either commandPrefix OR commandRegex, not both`
);
}
}
return null;
}
/**
* Validates that a tool name is recognized.
* Returns a warning message if the tool name is a likely typo of a built-in
* tool name, or null if valid or not close to any built-in name.
*/
function validateToolName(name: string, ruleIndex: number): string | null {
if (name.includes('__')) {
return `Rule #${ruleIndex + 1}: The "__" syntax for MCP tools is strictly deprecated. Please use the 'mcpName = "..."' property or the 'mcp_server_tool' format instead.`;
}
// A name that looks like an MCP tool (e.g., "re__ad") could be a typo of a
// built-in tool ("read_file"). We should let such names fall through to the
// Levenshtein distance check below. Non-MCP-like names that are valid can
// be safely skipped.
if (isValidToolName(name, { allowWildcards: true })) {
return null;
}
// Only warn if the name is close to a built-in name (likely typo).
// Names that are very different from all built-in names are likely
// intentional (dynamic tools, agent tools, etc.).
const allNames = [...ALL_BUILTIN_TOOL_NAMES];
const minDistance = Math.min(
...allNames.map((n) => levenshtein.get(name, n)),
);
if (minDistance > MAX_TYPO_DISTANCE) {
return null;
}
const suggestion = getToolSuggestion(name, allNames);
return `Rule #${ruleIndex + 1}: Unrecognized tool name "${name}".${suggestion}`;
}
/**
* Transforms a priority number based on the policy tier.
* Formula: tier + priority/1000
*
* @param priority The priority value from the TOML file
* @param tier The tier (1=default, 2=user, 3=admin)
* @returns The transformed priority
*/
function transformPriority(priority: number, tier: number): number {
return tier + priority / 1000;
}
/**
* Loads and parses policies from TOML files in the specified paths (directories or individual files).
*
* This function:
* 1. Scans paths for .toml files (if directory) or processes individual files
* 2. Parses and validates each file
* 3. Transforms rules (commandPrefix, arrays, mcpName, priorities)
* 4. Collects detailed error information for any failures
*
* @param policyPaths Array of paths (directories or files) to scan for policy files
* @param getPolicyTier Function to determine tier (1-4) for a path
* @returns Object containing successfully parsed rules and any errors encountered
*/
export async function loadPoliciesFromToml(
policyPaths: string[],
getPolicyTier: (path: string) => number,
): Promise<PolicyLoadResult> {
const rules: PolicyRule[] = [];
const checkers: SafetyCheckerRule[] = [];
const errors: PolicyFileError[] = [];
for (const p of policyPaths) {
const tier = getPolicyTier(p);
const tierName = getTierName(tier);
let policyFiles: PolicyFile[] = [];
try {
policyFiles = await readPolicyFiles(p);
} catch (e) {
errors.push({
filePath: p,
fileName: path.basename(p),
tier: tierName,
errorType: 'file_read',
message: `Failed to read policy path`,
details: isNodeError(e) ? e.message : String(e),
});
continue;
}
for (const { path: filePath, content: fileContent } of policyFiles) {
const file = path.basename(filePath);
try {
// Parse TOML
let parsed: unknown;
try {
parsed = toml.parse(fileContent);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const error = e as Error;
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'toml_parse',
message: 'TOML parsing failed',
details: error.message,
suggestion:
'Check for syntax errors like missing quotes, brackets, or commas',
});
continue;
}
// Validate schema
const validationResult = PolicyFileSchema.safeParse(parsed);
if (!validationResult.success) {
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'schema_validation',
message: 'Schema validation failed',
details: formatSchemaError(validationResult.error, 0),
suggestion:
'Ensure all required fields (decision, priority) are present with correct types',
});
continue;
}
// Validate shell command convenience syntax
const tomlRules = validationResult.data.rule ?? [];
for (let i = 0; i < tomlRules.length; i++) {
const rule = tomlRules[i];
const validationError = validateShellCommandSyntax(rule, i);
if (validationError) {
errors.push({
filePath,
fileName: file,
tier: tierName,
ruleIndex: i,
errorType: 'rule_validation',
message: 'Invalid shell command syntax',
details: validationError,
});
// Continue to next rule, don't skip the entire file
}
}
// Validate tool names in rules
for (let i = 0; i < tomlRules.length; i++) {
const rule = tomlRules[i];
const toolNamesRaw: string[] = Array.isArray(rule.toolName)
? rule.toolName
: [rule.toolName];
if (toolNamesRaw.some((name) => name === '')) {
errors.push({
filePath,
fileName: file,
tier: tierName,
ruleIndex: i,
errorType: 'rule_validation',
message: 'Invalid policy rule: toolName cannot be empty string',
details: `Rule #${i + 1} contains an empty toolName string. Use "*" to match all tools.`,
});
continue;
}
// We no longer skip MCP-scoped rules because we need to specifically
// warn users if they use deprecated "__" syntax for MCP tool names
const toolNames: string[] = toolNamesRaw;
for (const name of toolNames) {
const warning = validateToolName(name, i);
if (warning) {
errors.push({
filePath,
fileName: file,
tier: tierName,
ruleIndex: i,
errorType: 'tool_name_warning',
message: 'Unrecognized tool name',
details: warning,
severity: 'warning',
});
}
}
}
// Transform rules
const parsedRules: PolicyRule[] = (validationResult.data.rule ?? [])
.flatMap((rule) => {
const argsPatterns = buildArgsPatterns(
rule.argsPattern,
rule.commandPrefix,
rule.commandRegex,
);
// For each argsPattern, expand toolName arrays
return argsPatterns.flatMap((argsPattern) => {
const toolNames: string[] = Array.isArray(rule.toolName)
? rule.toolName
: [rule.toolName];
// Create a policy rule for each tool name
return toolNames.map((toolName) => {
let effectiveToolName: string = toolName;
const mcpName = rule.mcpName;
if (mcpName) {
// TODO(mcp): Decouple mcpName rules from FQN string parsing
// to support underscores in server aliases natively. Leaving
// mcpName and toolName separate here and relying on metadata
// during policy evaluation will avoid underscore splitting bugs.
// See: https://github.com/google-gemini/gemini-cli/issues/21727
effectiveToolName = formatMcpToolName(
mcpName,
effectiveToolName,
);
}
const policyRule: PolicyRule = {
toolName: effectiveToolName,
subagent: rule.subagent,
mcpName: rule.mcpName,
decision: rule.decision,
priority: transformPriority(rule.priority, tier),
modes: rule.modes,
interactive: rule.interactive,
toolAnnotations: rule.toolAnnotations,
allowRedirection:
rule.allowRedirection ?? rule.allow_redirection,
source: `${tierName.charAt(0).toUpperCase() + tierName.slice(1)}: ${file}`,
denyMessage: rule.denyMessage ?? rule.deny_message,
};
// Compile regex pattern
if (argsPattern) {
try {
new RegExp(argsPattern);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const error = e as Error;
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'regex_compilation',
message: 'Invalid regex pattern',
details: `Pattern: ${argsPattern}\nError: ${error.message}`,
suggestion:
'Check regex syntax for errors like unmatched brackets or invalid escape sequences',
});
return null;
}
if (!isSafeRegExp(argsPattern)) {
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'regex_compilation',
message: 'Unsafe regex pattern (potential ReDoS)',
details: `Pattern: ${argsPattern}`,
suggestion:
'Avoid nested quantifiers or extremely long patterns',
});
return null;
}
policyRule.argsPattern = new RegExp(argsPattern);
}
return policyRule;
});
});
})
.filter((rule): rule is PolicyRule => rule !== null);
rules.push(...parsedRules);
// Validate tool names in safety checker rules
const tomlCheckerRules = validationResult.data.safety_checker ?? [];
for (let i = 0; i < tomlCheckerRules.length; i++) {
const checker = tomlCheckerRules[i];
const checkerToolNamesRaw: string[] = Array.isArray(checker.toolName)
? checker.toolName
: [checker.toolName];
if (checkerToolNamesRaw.some((name) => name === '')) {
errors.push({
filePath,
fileName: file,
tier: tierName,
ruleIndex: i,
errorType: 'rule_validation',
message:
'Invalid safety checker rule: toolName cannot be empty string',
details: `Checker #${i + 1} contains an empty toolName string. Use "*" to match all tools.`,
});
continue;
}
if (checker.mcpName) continue;
const checkerToolNames: string[] = checkerToolNamesRaw;
for (const name of checkerToolNames) {
const warning = validateToolName(name, i);
if (warning) {
errors.push({
filePath,
fileName: file,
tier: tierName,
ruleIndex: i,
errorType: 'tool_name_warning',
message: 'Unrecognized tool name in safety checker',
details: warning,
severity: 'warning',
});
}
}
}
// Transform checkers
const parsedCheckers: SafetyCheckerRule[] = (
validationResult.data.safety_checker ?? []
)
.flatMap((checker) => {
const argsPatterns = buildArgsPatterns(
checker.argsPattern,
checker.commandPrefix,
checker.commandRegex,
);
return argsPatterns.flatMap((argsPattern) => {
const toolNames: string[] = Array.isArray(checker.toolName)
? checker.toolName
: [checker.toolName];
return toolNames.map((toolName) => {
let effectiveToolName: string;
if (checker.mcpName && toolName !== '*') {
effectiveToolName = `${MCP_TOOL_PREFIX}${checker.mcpName}_${toolName}`;
} else if (checker.mcpName) {
effectiveToolName = `${MCP_TOOL_PREFIX}${checker.mcpName}_*`;
} else {
effectiveToolName = toolName;
}
const safetyCheckerRule: SafetyCheckerRule = {
toolName: effectiveToolName,
mcpName: checker.mcpName,
priority: transformPriority(checker.priority, tier),
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
checker: checker.checker as SafetyCheckerConfig,
modes: checker.modes,
toolAnnotations: checker.toolAnnotations,
source: `${tierName.charAt(0).toUpperCase() + tierName.slice(1)}: ${file}`,
};
if (argsPattern) {
try {
new RegExp(argsPattern);
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const error = e as Error;
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'regex_compilation',
message: 'Invalid regex pattern in safety checker',
details: `Pattern: ${argsPattern}\nError: ${error.message}`,
});
return null;
}
if (!isSafeRegExp(argsPattern)) {
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'regex_compilation',
message:
'Unsafe regex pattern in safety checker (potential ReDoS)',
details: `Pattern: ${argsPattern}`,
});
return null;
}
safetyCheckerRule.argsPattern = new RegExp(argsPattern);
}
return safetyCheckerRule;
});
});
})
.filter((checker): checker is SafetyCheckerRule => checker !== null);
checkers.push(...parsedCheckers);
} catch (e) {
// Catch-all for unexpected errors
if (!isNodeError(e) || e.code !== 'ENOENT') {
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'file_read',
message: 'Failed to read policy file',
details: isNodeError(e) ? e.message : String(e),
});
}
}
}
}
return { rules, checkers, errors };
}
/**
* Validates MCP tool names in policy rules against actually discovered MCP tools.
* Called after an MCP server connects and its tools are discovered.
*
* For each policy rule that references the given MCP server, checks if the
* tool name matches any discovered tool. Emits warnings for likely typos
* using Levenshtein distance.
*
* @param serverName The MCP server name (e.g., "google-workspace")
* @param discoveredToolNames The tool names discovered from this server (simple names, not fully qualified)
* @param policyRules The current set of policy rules to validate against
* @returns Array of warning messages for unrecognized MCP tool names
*/
export function validateMcpPolicyToolNames(
serverName: string,
discoveredToolNames: string[],
policyRules: ReadonlyArray<{
toolName: string;
mcpName?: string;
source?: string;
}>,
): string[] {
const prefix = `${MCP_TOOL_PREFIX}${serverName}_`;
const warnings: string[] = [];
for (const rule of policyRules) {
if (!rule.toolName) continue;
let toolPart: string | undefined;
// The toolName is typically transformed into an FQN if mcpName was used.
if (rule.mcpName === serverName && rule.toolName.startsWith(prefix)) {
toolPart = rule.toolName.slice(prefix.length);
} else if (rule.toolName.startsWith(prefix)) {
toolPart = rule.toolName.slice(prefix.length);
} else {
continue;
}
// Skip wildcards
if (toolPart === '*') continue;
// Check if the tool exists
if (discoveredToolNames.includes(toolPart)) continue;
// Tool not found — check if it's a likely typo
if (discoveredToolNames.length === 0) continue;
const minDistance = Math.min(
...discoveredToolNames.map((n) => levenshtein.get(toolPart ?? '', n)),
);
if (minDistance > MAX_TYPO_DISTANCE) continue;
const suggestion = getToolSuggestion(toolPart, discoveredToolNames);
const source = rule.source ? ` (from ${rule.source})` : '';
warnings.push(
`Unrecognized MCP tool "${toolPart}" for server "${serverName}"${source}.${suggestion}`,
);
}
return warnings;
}
|