regexguard
regexguard-mcp-server
一个 MCP 服务器,让任何 AI 代理在发布正则表达式之前,都能对其刚刚生成的正则表达式进行合理性检查——既检查它实际匹配的内容,也检查它是否安全,能否针对不可信输入运行。完全本地化:无需 API 密钥,无需网络调用,除了 MCP SDK 和 Zod 之外没有其他依赖。
为什么
正则表达式是出了名的容易引入 bug 的地方,而且这种 bug 在你碰巧测试的所有示例中看起来都正常。特别是两种失败模式,既常见又容易用肉眼忽略:
它匹配的内容和你认为的不一样。
explain_regex将模式转换为真实的语法树,并用通俗易懂的英语描述它,因此“这真的要求至少一个数字吗?”这个问题能快速得到答案,而不必依赖你自己对嵌套括号的解读。它是一个拒绝服务攻击向量。 带有嵌套量词(
(a+)+)或重复组内歧义交替((a|a)+)的正则表达式,可能使回溯引擎在精心构造(甚至偶然)的不匹配输入上花费指数级时间——这就是 ReDoS,一个真实且被反复利用的漏洞类别,也是任何代理在未针对对抗性输入测试的情况下编写的正则表达式中可能存在的缺陷。check_redos_risk会标记结构形状,而从不执行该模式——对不可信或故意恶意的正则表达式源码运行它是安全的。
Related MCP server: cron-mcp
工具
explain_regex
将模式解析为 AST,并返回它匹配内容的通俗易懂的英文描述。
check_redos_risk
静态分析模式的结构,查找嵌套量词和重复组内的歧义交替——这是灾难性回溯的两个经典原因。返回 "safe"、"high" 或 "critical",并为发现的每个问题提供具体发现。
两个工具共享一个解析器
(src/services/parser.ts):一个真正的递归下降正则表达式解析器(字面量、字符类、简写类、锚点、捕获/非捕获/命名组、环视、交替、量词、反向引用),而不是针对模式原始源码的字符串匹配启发式方法的集合。
这是一个启发式结构检查,不是形式化验证器——check_redos_risk 可以告诉你一个模式具有教科书式的指数爆炸形状;它不能证明一个模式在所有输入上都是快速的,而且存在它当前检测到的两种形状之外的 ReDoS 模式。将 "safe" 结果视为“没有发现明显问题”,而不是保证。
安装和配置
git clone https://github.com/wedo911/regexguard-mcp-server.git
cd regexguard-mcp-server
npm install
npm run build将其添加到你的 MCP 客户端配置中(例如 claude_desktop_config.json,或项目的 .mcp.json 用于 Claude Code):
{
"mcpServers": {
"regexguard": {
"command": "node",
"args": ["/absolute/path/to/regexguard-mcp-server/dist/index.js"]
}
}
}运行测试
npm run build
node --test tests/parser.test.mjs tests/explain.test.mjs tests/redosCheck.test.mjs44 个测试覆盖了解析器语法、解释输出,以及 ReDoS 检查的真阳性((a+)+、(a*)*、(a|a)+、(a|ab)+、嵌套在非捕获组内的模式)和真阴性((cat|dog)+、一个现实的用户名模式、一个现实的电子邮件模式、兄弟(而非嵌套)重复),因此普通模式上的误报率是一个经过测试的属性,而不是一个希望。
无需客户端即可试用
npx @modelcontextprotocol/inspector --cli node dist/index.js \
--method tools/call --tool-name check_redos_risk \
--tool-arg pattern='^(([a-zA-Z0-9])+([\.-]?([a-zA-Z0-9])+)*)$'许可证
MIT——参见 LICENSE。
Available Tools
2 toolscheck_redos_riskCheck Regex for Catastrophic Backtracking (ReDoS) RiskARead-onlyIdempotent
Statically analyze a regex's structure for the two classic causes of catastrophic backtracking: nested quantifiers (e.g. "(a+)+") and ambiguous alternation inside a repeated group (e.g. "(a|a)+"). Both can make a backtracking regex engine take exponential time on a crafted or even accidental non-matching input -- a real, exploitable denial-of-service vector, and a common defect in regexes generated without testing against adversarial input.
This tool NEVER executes the pattern -- it only parses and inspects the pattern's source structure, so it's safe to run on untrusted or deliberately malicious patterns without risk of hanging.
Args:
pattern (string, 1-1000 chars): the regex source, without delimiters.
Returns: For JSON format: { "parsed": boolean, "error": string | null, "risk": "safe" | "high" | "critical", "findings": [ { "category": "nested_quantifier" | "ambiguous_alternation", "severity": "high" | "critical", "message": string } ] }
Examples:
Use when: "is this regex I just generated safe to run against user input?" -> pass the pattern before using it
Use when: reviewing a regex from an untrusted source before adding it to a codebase
Don't use when: you need proof a regex is fast on all inputs -- this is a heuristic structural check (no false negatives are guaranteed to be caught), not a formal verifier
Error Handling:
Returns an error (not an exception) if the pattern doesn't parse.
| Name | Required | Description | Default |
|---|---|---|---|
| pattern | Yes | The regex source, without the surrounding slashes, e.g. "^(a+)+$". |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already indicate read-only, idempotent, non-destructive. The description adds critical behavioral context: the tool never executes the pattern, is safe on untrusted or malicious input, returns errors rather than exceptions on parse failure, and is heuristic with possible missed risks. This is significant added transparency with no contradiction.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured with headings for purpose, usage, arguments, return format, examples, and error handling. Every section contributes useful operational information and the purpose is front-loaded within the first sentence.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Since no output schema exists, the description provides the full JSON return structure, error behavior, and usage boundaries, making the tool actionable. Minor ambiguity about regex flavor is acceptable given the structural check nature, and the description is otherwise complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%: the pattern parameter is fully described with type, min/max length, and an example in the schema. The description repeats the 'without delimiters' point but adds no new semantic meaning beyond what the schema already provides. Baseline 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb and resource: statically analyzing a regex's structure for the two classic causes of catastrophic backtracking (nested quantifiers and ambiguous alternation). This clearly distinguishes it from a generic regex explainer like the sibling explain_regex, even without naming it.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Provides explicit 'Use when' scenarios (generated regex before use, reviewing untrusted regex) and a clear 'Don't use when' caution that it is a heuristic structural check, not a formal verifier. This gives the agent clear selection criteria and exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
explain_regexExplain a RegexARead-onlyIdempotent
Parse a regular expression into a real syntax tree and describe in plain English what it matches. Use this to sanity-check a regex you (or someone else) wrote actually does what you intended, before shipping it.
Args:
pattern (string, 1-1000 chars): the regex source, without delimiters (no leading/trailing "/").
Returns: For JSON format: { "explanation": string, "parsed": boolean, "error": string | null } explanation is empty and error is set if the pattern could not be parsed (e.g. unbalanced parentheses, unsupported syntax).
Examples:
Use when: "does this regex actually require the string to start with a letter?" -> pass the pattern, read the explanation
Don't use when: you need to actually run the regex against text -- this tool never executes the pattern, only analyzes its source
Error Handling:
Returns an error (not an exception) if the pattern doesn't parse, with the parser's best guess at where the problem is.
| Name | Required | Description | Default |
|---|---|---|---|
| pattern | Yes | The regex source, without the surrounding slashes, e.g. "^[a-z0-9_]{3,16}$". |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Beyond the annotations, the description discloses important behavioral traits: the tool never executes the pattern, returns a parsed boolean, returns an error rather than throwing an exception on unparseable input, and provides the parser's best guess at the problem. This adds real context beyond the readOnly/idempotent hints and contains no contradiction.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured with Args, Returns, Examples, and Error Handling sections, and it front-loads the core purpose. It is slightly redundant with the schema in the Args section, but the overall organization makes it easy for an agent to parse and apply.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With only one parameter and no output schema, the description fully compensates by specifying the exact JSON return shape, the meaning of each field, error behavior, and a concrete usage example. An agent has enough information to call the tool correctly and interpret its result.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, and the description's Args section essentially repeats the schema: pattern string, 1-1000 chars, no delimiters. It adds no new semantic information beyond what the input schema already provides, so the baseline score of 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb and resource: 'Parse a regular expression into a real syntax tree and describe in plain English what it matches.' It also clearly differentiates the tool from running a regex by explicitly saying it 'never executes the pattern, only analyzes its source,' which distinguishes it from execution-oriented tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives explicit use guidance: 'Use this to sanity-check a regex... before shipping it' and includes both a 'Use when' example and a 'Don't use when' exclusion. It does not explicitly name check_redos_risk as the alternative for security risk assessment, so it misses the full when/when-not/alternatives pattern, but the context is otherwise clear.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
2 tool updates
v1.0.0- First observed
check_redos_risk - First observed
explain_regex
TDQS
Scored across 2 tools
The two tools have clearly distinct purposes: explain_regex describes what a pattern matches, while check_redos_risk analyzes vulnerability to catastrophic backtracking. They share input format but have no functional overlap, making misselection unlikely.
Both tools follow a consistent verb_noun snake_case pattern (explain_regex and check_redos_risk). The naming is predictable and aligns with the domain.
With only two tools, the server is minimally scoped, but for a dedicated regex-analysis utility this is reasonable and each tool addresses a core need. Slightly under typical range but appropriate for the narrow focus.
The server covers the essential aspects of regex analysis: comprehension (explain_regex) and security risk (check_redos_risk). Syntax validation is implicitly handled via parse errors. There are no obvious missing operations within the stated purpose.
Maintenance
Related MCP Connectors
Explain a regex in plain English and detect catastrophic backtracking risk.
Security scanner for AI agents: prompt injection, leaked secrets, PII, and SSRF-risk URL detection.
1The WAF for agents. Pattern-based + heuristic firewall scans prompts, RAG documents, tool argume...
Detects catastrophic-backtracking (ReDoS) regex risk via AST parsing, with JS-safe rewrites.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceRegexForge gives AI agents a reliable way to get a regex without asking an LLM to hallucinate one. Pass in labeled examples (strings that should match, strings that shouldn't) plus an optional description; get back the regex, a proof matrix showing it handles every example, and a backtracking-risk audit flagging catastrophic-backtracking patterns. Pure symbolic synthesis over a template bank with-
- AlicenseAqualityBmaintenanceEnables AI agents to parse, validate, explain, and preview cron expressions, surfacing common silent bugs before deployment.445 npmMIT
- AlicenseAqualityDmaintenanceProvides tools to test regex patterns for correctness, performance (ReDoS), and memory usage, and suggests safe rewrites. Enables LLMs to iterate on regex generation with verifiable feedback.9MIT
- AlicenseAqualityFmaintenanceDependency security & health auditing for AI agents with no account or API key required.22MIT