Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): add scoped path-cleaning-rules-update tool (#70999)

Paul D'Ambrab6b2744153fb
diff --git a/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md b/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md
index 33fa475c3b93..ef953fba7834 100644
--- a/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md
+++ b/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.md
@@ -1,6 +1,6 @@
---
name: managing-path-cleaning-rules
-description: 'Inspects URL paths and proposes, tests, orders, and applies project-level path cleaning rules so dynamic segments (numeric IDs, UUIDs, slugs, dates) collapse into readable aliases. Use when the user says "clean the paths", "normalize URLs", "group similar pages", "too many distinct paths", "/users/123 and /users/456 are the same page", "set up path cleaning", or asks why a Web analytics or Paths breakdown is fragmented across thousands of nearly-identical URLs. Covers regex syntax (re2), alias placeholder convention, rule ordering, the test workflow, and applying rules via the project-settings-update MCP tool.'
+description: 'Inspects URL paths and proposes, tests, orders, and applies project-level path cleaning rules so dynamic segments (numeric IDs, UUIDs, slugs, dates) collapse into readable aliases. Use when the user says "clean the paths", "normalize URLs", "group similar pages", "too many distinct paths", "/users/123 and /users/456 are the same page", "set up path cleaning", or asks why a Web analytics or Paths breakdown is fragmented across thousands of nearly-identical URLs. Covers regex syntax (re2), alias placeholder convention, rule ordering, the test workflow, and applying rules via the path-cleaning-rules-update MCP tool.'
---
# Managing path cleaning rules
@@ -131,22 +131,29 @@ make the more specific rule unreachable.
### 6. Apply via MCP
-Use the `project-settings-update` tool with the full list (the field is
-replaced, not merged):
+Prefer the `path-cleaning-rules-update` tool. It reads the current rules,
+applies granular operations (`append`, `insert`, `replace`, `remove`,
+`reorder`), auto-numbers `order`, and — unless you pass `confirm: true` —
+returns a **preview** of the resulting rules without saving. Pass
+`sample_paths` to see how the resulting set rewrites real paths.
+
+First call it without `confirm` to get the preview, surface that to the user,
+then re-send the same call with `"confirm": true` to save:
```json
{
- "path_cleaning_filters": [
- { "regex": "/users/me/profile", "alias": "/users/me/profile", "order": 0 },
- { "regex": "/users/\\d+/profile", "alias": "/users/<id>/profile", "order": 1 },
- { "regex": "/users/[a-z0-9-]+", "alias": "/users/<slug>", "order": 2 }
- ]
+ "operations": [{ "action": "append", "alias": "/users/<id>/profile", "regex": "/users/\\d+/profile" }],
+ "sample_paths": ["/users/123/profile", "/users/me/profile"]
}
```
-Always **read the existing rules first** (project settings include
-`path_cleaning_filters`) and merge — overwriting silently destroys whatever the
-team has already configured.
+Because the tool does the read-modify-write for you, you don't have to fetch
+the full list, renumber `order`, or risk clobbering existing rules — the common
+failure mode when editing `path_cleaning_filters` directly.
+
+If you must fall back to `project-settings-update` (whole-list overwrite),
+always **read the existing rules first** and merge — overwriting silently
+destroys whatever the team has already configured.
## Where the rules apply
@@ -173,8 +180,10 @@ The rules are stored once per project — they are not insight-scoped.
- **Escaping `/`** — re2 does not require it. `\/` works but adds noise.
- **Case sensitivity** — re2 is case-sensitive by default. Use `(?i)` at the
start of the pattern for case-insensitive matching, e.g. `(?i)/users/\d+`.
-- **Replacing the whole list** — `path_cleaning_filters` is overwrite, not
- append. Always start from the current list.
+- **Replacing the whole list** — the raw `path_cleaning_filters` field is
+ overwrite, not append. Use `path-cleaning-rules-update` (which does the
+ read-modify-write for you) instead of hand-editing the field; if you must
+ edit it directly, always start from the current list.
- **Rules apply globally** — adding a rule can change historical numbers in
every Web analytics / Paths chart that has cleaning enabled. Warn the user
before applying anything destructive.
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 21e5c51da6f4..0ad4774bcb94 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6524,6 +6524,20 @@
"readOnlyHint": true
}
},
+ "path-cleaning-rules-update": {
+ "description": "Safely add, replace, remove, or reorder a project's path cleaning rules (Team.path_cleaning_filters) without hand-managing the whole list. Reads the current rules, applies your ordered operations, auto-numbers them, and (unless confirm:true) returns a PREVIEW of the resulting rules — plus how they rewrite any sample_paths — without saving. Path cleaning normalizes $pathname/$entry_pathname so pages sharing a template (/users/123, /users/456) collapse into one row (/users/<id>) in Web analytics, Paths, and apply_path_cleaning HogQL. Prefer this over project-settings-update for path cleaning: it avoids clobbering existing rules and renumbering by hand. Rules apply sequentially (order matters) and globally wherever cleaning is enabled, changing historical numbers — surface the preview to the user, then re-run with confirm:true.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Edit path cleaning rules with granular ops, a preview step, and safe read-modify-write.",
+ "title": "Update path cleaning rules",
+ "required_scopes": ["project:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"persons-bulk-delete": {
"description": "Delete up to 1000 persons by PostHog person UUIDs or distinct IDs. Optionally delete associated events and recordings. Pass either `ids` (person UUIDs) or `distinct_ids`. Returns 202 Accepted. This operation is irreversible.",
"category": "Persons",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 61a84b3015a3..33f786fcf926 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -393,6 +393,20 @@
"readOnlyHint": false
}
},
+ "path-cleaning-rules-update": {
+ "description": "Safely add, replace, remove, or reorder a project's path cleaning rules (Team.path_cleaning_filters) without hand-managing the whole list. Reads the current rules, applies your ordered operations, auto-numbers them, and (unless confirm:true) returns a PREVIEW of the resulting rules — plus how they rewrite any sample_paths — without saving. Path cleaning normalizes $pathname/$entry_pathname so pages sharing a template (/users/123, /users/456) collapse into one row (/users/<id>) in Web analytics, Paths, and apply_path_cleaning HogQL. Prefer this over project-settings-update for path cleaning: it avoids clobbering existing rules and renumbering by hand. Rules apply sequentially (order matters) and globally wherever cleaning is enabled, changing historical numbers — surface the preview to the user, then re-run with confirm:true.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Edit path cleaning rules with granular ops, a preview step, and safe read-modify-write.",
+ "title": "Update path cleaning rules",
+ "required_scopes": ["project:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"switch-project": {
"description": "Switch the active PostHog project for subsequent tool calls. Call this proactively whenever the user names a project or workspace they want to operate on. Use `projects-get` to resolve a project name to an id. If the project isn't found, the user may be referring to a project in a different organization, in which case call `organizations-list` and `switch-organization` first, then retry `projects-get`. Default to the active project when no specific project is mentioned.",
"category": "Organization & project management",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 9bd62c820dfe..3b1c0dc15d91 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -518,6 +518,138 @@
},
"required": ["orgId"]
},
+ "PathCleaningRulesUpdateSchema": {
+ "type": "object",
+ "properties": {
+ "operations": {
+ "minItems": 1,
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "const": "append"
+ },
+ "alias": {
+ "type": "string",
+ "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported."
+ },
+ "regex": {
+ "type": "string",
+ "minLength": 1,
+ "description": "A re2 pattern matched against the path, e.g. \"/users/\\\\d+/profile\". No need to escape \"/\". Anchor with ^ / $ when you mean it."
+ }
+ },
+ "required": ["action", "alias", "regex"],
+ "description": "Add a new rule at the end of the ordered list (runs last)."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "const": "insert"
+ },
+ "index": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991,
+ "description": "Zero-based position to insert the rule at. Existing rules shift down."
+ },
+ "alias": {
+ "type": "string",
+ "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported."
+ },
+ "regex": {
+ "type": "string",
+ "minLength": 1,
+ "description": "A re2 pattern matched against the path, e.g. \"/users/\\\\d+/profile\". No need to escape \"/\". Anchor with ^ / $ when you mean it."
+ }
+ },
+ "required": ["action", "index", "alias", "regex"],
+ "description": "Insert a new rule at a specific position — use when it must run before more general rules."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "const": "replace"
+ },
+ "target_alias": {
+ "type": "string",
+ "description": "The alias of the existing rule to target (must match an existing rule exactly). Use \"\" to target a rule whose alias is empty."
+ },
+ "alias": {
+ "description": "New alias. Omit to keep the current alias.",
+ "type": "string"
+ },
+ "regex": {
+ "description": "New regex. Omit to keep the current regex.",
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": ["action", "target_alias"],
+ "description": "Replace the alias and/or regex of an existing rule, keeping its position."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "const": "remove"
+ },
+ "target_alias": {
+ "type": "string",
+ "description": "The alias of the existing rule to target (must match an existing rule exactly). Use \"\" to target a rule whose alias is empty."
+ }
+ },
+ "required": ["action", "target_alias"],
+ "description": "Remove an existing rule by alias."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "const": "reorder"
+ },
+ "ordered_aliases": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "The full set of current aliases in the new desired order (including \"\" for any empty-alias rule and any duplicates). Must be a permutation of the existing aliases."
+ }
+ },
+ "required": ["action", "ordered_aliases"],
+ "description": "Reorder the existing rules. Order matters: rules apply sequentially, each feeding the next."
+ }
+ ]
+ },
+ "description": "Ordered list of edits to apply to the current path cleaning rules, in sequence."
+ },
+ "sample_paths": {
+ "description": "Optional real paths (e.g. \"/users/123/profile\") to preview against, up to 25. The response shows how the resulting rule set rewrites each one. Approximate (JS regex, not re2) — use execute-sql with replaceRegexpAll to confirm edge cases.",
+ "maxItems": 25,
+ "type": "array",
+ "items": {
+ "type": "string",
+ "maxLength": 2048
+ }
+ },
+ "confirm": {
+ "default": false,
+ "description": "Must be true to persist. When false (default) the tool returns a preview of the resulting rules (and any sample-path rewrites) WITHOUT saving — surface it to the user, then re-run with confirm:true.",
+ "type": "boolean"
+ }
+ },
+ "required": ["operations"]
+ },
"ProjectGetAllSchema": {
"type": "object",
"properties": {}
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index e3e68e2e372f..27f210b788f3 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -690,6 +690,21 @@ export class ApiClient {
return { success: false, error: error as Error }
}
},
+
+ updatePathCleaningFilters: async ({
+ projectId,
+ filters,
+ }: {
+ projectId: string
+ filters: Array<{ alias: string; regex: string; order: number }>
+ }): Promise<Result<Schemas.ProjectBackwardCompat>> => {
+ // path_cleaning_filters is a whole-list field on the project — the caller is
+ // responsible for having merged the desired rules into `filters` first.
+ return this.fetchJson<Schemas.ProjectBackwardCompat>(`${this.baseUrl}/api/projects/${projectId}/`, {
+ method: 'PATCH',
+ body: JSON.stringify({ path_cleaning_filters: filters }),
+ })
+ },
}
}
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 2ac3d86421c1..554b28bdd655 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -341,6 +341,96 @@ export const EventDefinitionUpdateSchema = z.object({
data: EventDefinitionUpdateInputSchema.describe('The event definition data to update'),
})
+const PathCleaningAliasField = z
+ .string()
+ .describe(
+ 'The human-readable replacement, e.g. "/users/<id>/profile". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a "?page=N" fragment). Not a regex template — backreferences are not supported.'
+ )
+const PathCleaningRegexField = z
+ .string()
+ .min(1)
+ .describe(
+ 'A re2 pattern matched against the path, e.g. "/users/\\\\d+/profile". No need to escape "/". Anchor with ^ / $ when you mean it.'
+ )
+const PathCleaningTargetAlias = z
+ .string()
+ .describe(
+ 'The alias of the existing rule to target (must match an existing rule exactly). Use "" to target a rule whose alias is empty.'
+ )
+
+export const PathCleaningRulesUpdateSchema = z.object({
+ operations: z
+ .array(
+ z.discriminatedUnion('action', [
+ z
+ .object({
+ action: z.literal('append'),
+ alias: PathCleaningAliasField,
+ regex: PathCleaningRegexField,
+ })
+ .describe('Add a new rule at the end of the ordered list (runs last).'),
+ z
+ .object({
+ action: z.literal('insert'),
+ index: z
+ .number()
+ .int()
+ .min(0)
+ .describe('Zero-based position to insert the rule at. Existing rules shift down.'),
+ alias: PathCleaningAliasField,
+ regex: PathCleaningRegexField,
+ })
+ .describe(
+ 'Insert a new rule at a specific position — use when it must run before more general rules.'
+ ),
+ z
+ .object({
+ action: z.literal('replace'),
+ target_alias: PathCleaningTargetAlias,
+ alias: PathCleaningAliasField.optional().describe('New alias. Omit to keep the current alias.'),
+ regex: PathCleaningRegexField.optional().describe('New regex. Omit to keep the current regex.'),
+ })
+ .describe('Replace the alias and/or regex of an existing rule, keeping its position.'),
+ z
+ .object({
+ action: z.literal('remove'),
+ target_alias: PathCleaningTargetAlias,
+ })
+ .describe('Remove an existing rule by alias.'),
+ z
+ .object({
+ action: z.literal('reorder'),
+ ordered_aliases: z
+ .array(z.string())
+ .describe(
+ 'The full set of current aliases in the new desired order (including "" for any empty-alias rule and any duplicates). Must be a permutation of the existing aliases.'
+ ),
+ })
+ .describe(
+ 'Reorder the existing rules. Order matters: rules apply sequentially, each feeding the next.'
+ ),
+ ])
+ )
+ .min(1)
+ .describe('Ordered list of edits to apply to the current path cleaning rules, in sequence.'),
+ sample_paths: z
+ // Bounded (count + length) so a pathological user-supplied regex can't burn unbounded
+ // CPU backtracking over the preview. A handful of representative paths is the point.
+ .array(z.string().max(2048))
+ .max(25)
+ .optional()
+ .describe(
+ 'Optional real paths (e.g. "/users/123/profile") to preview against, up to 25. The response shows how the resulting rule set rewrites each one. Approximate (JS regex, not re2) — use execute-sql with replaceRegexpAll to confirm edge cases.'
+ ),
+ confirm: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(
+ 'Must be true to persist. When false (default) the tool returns a preview of the resulting rules (and any sample-path rewrites) WITHOUT saving — surface it to the user, then re-run with confirm:true.'
+ ),
+})
+
export const ProjectSetActiveSchema = z.object({
projectId: z.number().int().positive(),
})
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index b82a6aa583f8..14c0453e6727 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -35,6 +35,7 @@ import {
import getProjects from './projects/getProjects'
import setActiveProject from './projects/setActive'
import updateEventDefinition from './projects/updateEventDefinition'
+import updatePathCleaning from './projects/updatePathCleaning'
// Replay
import sessionRecordingSummarize from './replay/sessionRecordingSummarize'
// Skills (deprecation aliases for the llma-skill-* → skill-* rename)
@@ -62,6 +63,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
'projects-get': getProjects,
'switch-project': setActiveProject,
'event-definition-update': updateEventDefinition,
+ 'path-cleaning-rules-update': updatePathCleaning,
// Experiments (results is hand-written; CRUD + lifecycle are codegen)
'experiment-results-get': getExperimentResults,
diff --git a/services/mcp/src/tools/projects/updatePathCleaning.ts b/services/mcp/src/tools/projects/updatePathCleaning.ts
new file mode 100644
index 000000000000..7d5b2d75f7f5
--- /dev/null
+++ b/services/mcp/src/tools/projects/updatePathCleaning.ts
@@ -0,0 +1,298 @@
+import type { z } from 'zod'
+
+import { PathCleaningRulesUpdateSchema } from '@/schema/tool-inputs'
+import type { Context, ToolBase } from '@/tools/types'
+
+const schema = PathCleaningRulesUpdateSchema
+
+type Params = z.infer<typeof schema>
+type Operation = Params['operations'][number]
+
+/** A path cleaning rule as the LLM works with it — order is managed by this tool, not the caller. */
+export type PathCleaningRule = { alias: string; regex: string }
+/** A rule as stored on the project (`Team.path_cleaning_filters`), with an explicit order. */
+export type StoredPathCleaningRule = PathCleaningRule & { order: number }
+
+type SamplePreview = { path: string; before: string; after: string }
+
+type Result = {
+ applied: boolean
+ message: string
+ changes: string[]
+ resulting_rules: StoredPathCleaningRule[]
+ sample_preview?: SamplePreview[]
+ settings_url: string
+}
+
+/**
+ * Coerce the raw `path_cleaning_filters` value (typed `unknown` in the API schema) into a
+ * clean list. Preserves the stored ARRAY order: the backend (`apply_path_cleaning` →
+ * `Team.path_cleaning_filter_models`) applies rules in array order and ignores the `order`
+ * field for sequencing, so re-sorting by `order` here could silently resequence untouched
+ * rules on save. The `order` field is carried through only as display metadata.
+ */
+export function normalizePathCleaningFilters(raw: unknown): StoredPathCleaningRule[] {
+ if (!Array.isArray(raw)) {
+ return []
+ }
+ return (
+ raw
+ .map((entry, index) => {
+ const rule = (entry ?? {}) as Record<string, unknown>
+ const alias = typeof rule.alias === 'string' ? rule.alias : ''
+ const regex = typeof rule.regex === 'string' ? rule.regex : ''
+ const order = typeof rule.order === 'number' ? rule.order : index
+ return { alias, regex, order }
+ })
+ // An empty `alias` is a valid rule (it deletes the matched text), so only drop
+ // entries with no `regex` to match on — keeping an existing empty-alias rule
+ // instead of silently deleting it on the next confirmed edit.
+ .filter((rule) => rule.regex !== '')
+ )
+}
+
+/** Reassign contiguous `order` values 0..n-1 so the caller never has to manage them. */
+export function renumber(rules: PathCleaningRule[]): StoredPathCleaningRule[] {
+ return rules.map((rule, index) => ({ ...rule, order: index }))
+}
+
+function assertValidRegex(regex: string): void {
+ // The backend compiles these as re2; JS RegExp is only a best-effort typo check to fail
+ // fast on obviously-broken patterns (e.g. unbalanced parens). Strip a leading re2 inline
+ // flag group like `(?i)` first — it's valid re2 (and documented for path cleaning) but
+ // throws in JS. Patterns valid in re2 but not JS still save fine; the backend is the
+ // authority and rejects genuinely invalid ones on write.
+ const withoutLeadingInlineFlags = regex.replace(/^\(\?[imsUx]+\)/, '')
+ try {
+ new RegExp(withoutLeadingInlineFlags)
+ } catch (error) {
+ throw new Error(`Invalid regex "${regex}": ${(error as Error).message}`)
+ }
+}
+
+/**
+ * Apply the ordered operations to a copy of the current rules, returning the new list and a
+ * human-readable change log. Throws with an actionable message on any invalid operation
+ * (unknown target alias, bad regex, non-permutation reorder) so nothing is half-applied.
+ */
+export function applyOperations(
+ current: PathCleaningRule[],
+ operations: Operation[]
+): { rules: PathCleaningRule[]; changes: string[] } {
+ const rules: PathCleaningRule[] = current.map((rule) => ({ ...rule }))
+ const changes: string[] = []
+
+ // Aliases are NOT guaranteed unique (two regexes can map to the same alias), so an
+ // alias-targeted op is only safe when exactly one rule carries it — otherwise we'd
+ // silently edit an arbitrary one. Reject the ambiguous case rather than guess.
+ const resolveSingle = (alias: string, verb: string): number => {
+ const matches = rules.reduce<number[]>((acc, rule, i) => {
+ if (rule.alias === alias) {
+ acc.push(i)
+ }
+ return acc
+ }, [])
+ if (matches.length === 0) {
+ throw new Error(
+ `Cannot ${verb}: no rule with alias "${alias}". Existing aliases: ${rules.map((rule) => rule.alias).join(', ')}`
+ )
+ }
+ if (matches.length > 1) {
+ throw new Error(
+ `Cannot ${verb}: alias "${alias}" matches ${matches.length} rules, so targeting it is ambiguous. Make the aliases distinct first, or edit the full list via project-settings-update.`
+ )
+ }
+ return matches[0]!
+ }
+
+ for (const op of operations) {
+ switch (op.action) {
+ case 'append': {
+ assertValidRegex(op.regex)
+ rules.push({ alias: op.alias, regex: op.regex })
+ changes.push(`Appended "${op.alias}" (${op.regex}) — runs last`)
+ break
+ }
+ case 'insert': {
+ assertValidRegex(op.regex)
+ const index = Math.min(op.index, rules.length)
+ rules.splice(index, 0, { alias: op.alias, regex: op.regex })
+ changes.push(`Inserted "${op.alias}" (${op.regex}) at position ${index}`)
+ break
+ }
+ case 'replace': {
+ const index = resolveSingle(op.target_alias, 'replace')
+ if (op.regex !== undefined) {
+ assertValidRegex(op.regex)
+ }
+ const previous = rules[index]!
+ const next = { alias: op.alias ?? previous.alias, regex: op.regex ?? previous.regex }
+ rules[index] = next
+ changes.push(`Replaced "${op.target_alias}" → alias "${next.alias}", regex ${next.regex}`)
+ break
+ }
+ case 'remove': {
+ const index = resolveSingle(op.target_alias, 'remove')
+ rules.splice(index, 1)
+ changes.push(`Removed "${op.target_alias}"`)
+ break
+ }
+ case 'reorder': {
+ // Group rules by alias so duplicate aliases are handled without loss: the
+ // permutation check is a true multiset comparison, and the rebuild consumes
+ // same-alias rules in their original relative order.
+ const groups = new Map<string, PathCleaningRule[]>()
+ for (const rule of rules) {
+ const list = groups.get(rule.alias)
+ if (list) {
+ list.push(rule)
+ } else {
+ groups.set(rule.alias, [rule])
+ }
+ }
+ const requestedCounts = new Map<string, number>()
+ for (const alias of op.ordered_aliases) {
+ requestedCounts.set(alias, (requestedCounts.get(alias) ?? 0) + 1)
+ }
+ const isPermutation =
+ op.ordered_aliases.length === rules.length &&
+ [...requestedCounts].every(([alias, count]) => (groups.get(alias)?.length ?? 0) === count)
+ if (!isPermutation) {
+ throw new Error(
+ `Cannot reorder: ordered_aliases must be exactly the current aliases, once each (including duplicates). Current: ${rules
+ .map((rule) => rule.alias)
+ .join(', ')}`
+ )
+ }
+ const queues = new Map([...groups].map(([alias, list]) => [alias, [...list]]))
+ const reordered = op.ordered_aliases.map((alias) => queues.get(alias)!.shift()!)
+ rules.splice(0, rules.length, ...reordered)
+ changes.push(`Reordered to: ${op.ordered_aliases.join(' → ')}`)
+ break
+ }
+ }
+ }
+
+ return { rules, changes }
+}
+
+/**
+ * Compile a re2 pattern into a JS RegExp for the approximate preview. Translates a leading
+ * re2 inline-flag group (e.g. `(?i)`) into JS flags so patterns accepted by the tool don't
+ * silently drop out of the preview. Returns null for patterns JS can't represent.
+ */
+function compileForPreview(regex: string): RegExp | null {
+ const match = regex.match(/^\(\?([imsUx]+)\)/)
+ const inlineFlags = match ? match[1]! : ''
+ const pattern = match ? regex.slice(match[0].length) : regex
+ // Map the re2 flags JS supports; ignore U/x (no JS equivalent, and rare in path cleaning).
+ let flags = 'g'
+ if (inlineFlags.includes('i')) {
+ flags += 'i'
+ }
+ if (inlineFlags.includes('m')) {
+ flags += 'm'
+ }
+ if (inlineFlags.includes('s')) {
+ flags += 's'
+ }
+ try {
+ return new RegExp(pattern, flags)
+ } catch {
+ // A rule using re2-only syntax may not compile under JS RegExp — skip it in the
+ // approximate preview rather than failing the whole call.
+ return null
+ }
+}
+
+/** Chain a path through every rule in order, mirroring ClickHouse `replaceRegexpAll` per rule. */
+function applyChain(path: string, rules: PathCleaningRule[]): string {
+ let out = path
+ for (const rule of rules) {
+ const re = compileForPreview(rule.regex)
+ if (re === null) {
+ continue
+ }
+ // `alias` is a literal; escape `$` so JS's replace() doesn't treat it as a group ref.
+ out = out.replace(re, rule.alias.replace(/\$/g, '$$$$'))
+ }
+ return out
+}
+
+function buildSamplePreview(
+ before: PathCleaningRule[],
+ after: PathCleaningRule[],
+ samplePaths: string[]
+): SamplePreview[] {
+ return samplePaths.map((path) => ({
+ path,
+ before: applyChain(path, before),
+ after: applyChain(path, after),
+ }))
+}
+
+export const updatePathCleaningHandler: ToolBase<typeof schema, Result>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const projectId = await context.stateManager.getProjectId()
+
+ const projectResult = await context.api.projects().get({ projectId })
+ if (!projectResult.success) {
+ throw new Error(`Failed to read current path cleaning rules: ${projectResult.error.message}`)
+ }
+
+ const currentStored = normalizePathCleaningFilters(
+ (projectResult.data as { path_cleaning_filters?: unknown }).path_cleaning_filters
+ )
+ const currentRules: PathCleaningRule[] = currentStored.map(({ alias, regex }) => ({ alias, regex }))
+
+ const { rules, changes } = applyOperations(currentRules, params.operations)
+ const resultingRules = renumber(rules)
+
+ const samplePreview = params.sample_paths?.length
+ ? buildSamplePreview(currentRules, rules, params.sample_paths)
+ : undefined
+
+ const settingsUrl = `${context.api.getProjectBaseUrl(projectId)}/settings/project#path-cleaning`
+
+ if (!params.confirm) {
+ return {
+ applied: false,
+ message: `Preview only — nothing saved. ${changes.length} change(s) would apply, leaving ${resultingRules.length} rule(s). Re-run with confirm:true to save.`,
+ changes,
+ resulting_rules: resultingRules,
+ sample_preview: samplePreview,
+ settings_url: settingsUrl,
+ }
+ }
+
+ const updateResult = await context.api.projects().updatePathCleaningFilters({
+ projectId,
+ filters: resultingRules,
+ })
+ if (!updateResult.success) {
+ throw new Error(`Failed to save path cleaning rules: ${updateResult.error.message}`)
+ }
+
+ const saved = normalizePathCleaningFilters(
+ (updateResult.data as { path_cleaning_filters?: unknown }).path_cleaning_filters
+ )
+
+ return {
+ applied: true,
+ message: `Saved ${saved.length} path cleaning rule(s). These apply globally wherever path cleaning is enabled and can change historical numbers.`,
+ changes,
+ resulting_rules: saved,
+ sample_preview: samplePreview,
+ settings_url: settingsUrl,
+ }
+}
+
+const tool = (): ToolBase<typeof schema, Result> => ({
+ name: 'path-cleaning-rules-update',
+ schema,
+ handler: updatePathCleaningHandler,
+})
+
+export default tool
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json
new file mode 100644
index 000000000000..a1f1ebe4f72a
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/path-cleaning-rules-update.json
@@ -0,0 +1,133 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "confirm": {
+ "default": false,
+ "description": "Must be true to persist. When false (default) the tool returns a preview of the resulting rules (and any sample-path rewrites) WITHOUT saving — surface it to the user, then re-run with confirm:true.",
+ "type": "boolean"
+ },
+ "operations": {
+ "description": "Ordered list of edits to apply to the current path cleaning rules, in sequence.",
+ "items": {
+ "oneOf": [
+ {
+ "description": "Add a new rule at the end of the ordered list (runs last).",
+ "properties": {
+ "action": {
+ "const": "append",
+ "type": "string"
+ },
+ "alias": {
+ "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported.",
+ "type": "string"
+ },
+ "regex": {
+ "description": "A re2 pattern matched against the path, e.g. \"/users/\\\\d+/profile\". No need to escape \"/\". Anchor with ^ / $ when you mean it.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["action", "alias", "regex"],
+ "type": "object"
+ },
+ {
+ "description": "Insert a new rule at a specific position — use when it must run before more general rules.",
+ "properties": {
+ "action": {
+ "const": "insert",
+ "type": "string"
+ },
+ "alias": {
+ "description": "The human-readable replacement, e.g. \"/users/<id>/profile\". Use angle-bracket placeholders (<id>, <uuid>, <slug>) by convention. An empty string is valid — it deletes the matched text (e.g. to strip a \"?page=N\" fragment). Not a regex template — backreferences are not supported.",
+ "type": "string"
+ },
+ "index": {
+ "description": "Zero-based position to insert the rule at. Existing rules shift down.",
+ "maximum": 9007199254740991,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "regex": {
+ "description": "A re2 pattern matched against the path, e.g. \"/users/\\\\d+/profile\". No need to escape \"/\". Anchor with ^ / $ when you mean it.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["action", "index", "alias", "regex"],
+ "type": "object"
+ },
+ {
+ "description": "Replace the alias and/or regex of an existing rule, keeping its position.",
+ "properties": {
+ "action": {
+ "const": "replace",
+ "type": "string"
+ },
+ "alias": {
+ "description": "New alias. Omit to keep the current alias.",
+ "type": "string"
+ },
+ "regex": {
+ "description": "New regex. Omit to keep the current regex.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "target_alias": {
+ "description": "The alias of the existing rule to target (must match an existing rule exactly). Use \"\" to target a rule whose alias is empty.",
+ "type": "string"
+ }
+ },
+ "required": ["action", "target_alias"],
+ "type": "object"
+ },
+ {
+ "description": "Remove an existing rule by alias.",
+ "properties": {
+ "action": {
+ "const": "remove",
+ "type": "string"
+ },
+ "target_alias": {
+ "description": "The alias of the existing rule to target (must match an existing rule exactly). Use \"\" to target a rule whose alias is empty.",
+ "type": "string"
+ }
+ },
+ "required": ["action", "target_alias"],
+ "type": "object"
+ },
+ {
+ "description": "Reorder the existing rules. Order matters: rules apply sequentially, each feeding the next.",
+ "properties": {
+ "action": {
+ "const": "reorder",
+ "type": "string"
+ },
+ "ordered_aliases": {
+ "description": "The full set of current aliases in the new desired order (including \"\" for any empty-alias rule and any duplicates). Must be a permutation of the existing aliases.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["action", "ordered_aliases"],
+ "type": "object"
+ }
+ ]
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "sample_paths": {
+ "description": "Optional real paths (e.g. \"/users/123/profile\") to preview against, up to 25. The response shows how the resulting rule set rewrites each one. Approximate (JS regex, not re2) — use execute-sql with replaceRegexpAll to confirm edge cases.",
+ "items": {
+ "maxLength": 2048,
+ "type": "string"
+ },
+ "maxItems": 25,
+ "type": "array"
+ }
+ },
+ "required": ["operations"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/path-cleaning-rules-update.test.ts b/services/mcp/tests/unit/path-cleaning-rules-update.test.ts
new file mode 100644
index 000000000000..703e6003c1ff
--- /dev/null
+++ b/services/mcp/tests/unit/path-cleaning-rules-update.test.ts
@@ -0,0 +1,322 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import updatePathCleaning, {
+ applyOperations,
+ normalizePathCleaningFilters,
+ type PathCleaningRule,
+ renumber,
+ updatePathCleaningHandler,
+} from '@/tools/projects/updatePathCleaning'
+import type { Context } from '@/tools/types'
+
+describe('normalizePathCleaningFilters', () => {
+ it('preserves stored array order (not the order field) and drops only entries with no regex', () => {
+ // The backend applies rules in array order and ignores `order`, so normalize must NOT
+ // re-sort — doing so would silently resequence untouched rules on save. Order-field
+ // values here are deliberately non-monotonic to prove no sorting happens.
+ const raw = [
+ { alias: '/b', regex: '/b/\\d+', order: 2 },
+ { alias: '/a', regex: '/a/\\d+', order: 0 },
+ { alias: '', regex: '\\?page=\\d+$', order: 1 }, // empty alias = delete matched text; valid
+ { alias: '/c', regex: '', order: 3 }, // no regex = meaningless; dropped
+ ]
+ expect(normalizePathCleaningFilters(raw)).toEqual([
+ { alias: '/b', regex: '/b/\\d+', order: 2 },
+ { alias: '/a', regex: '/a/\\d+', order: 0 },
+ { alias: '', regex: '\\?page=\\d+$', order: 1 },
+ ])
+ })
+
+ it('falls back to array index when order is missing', () => {
+ const raw = [
+ { alias: '/first', regex: '/first' },
+ { alias: '/second', regex: '/second' },
+ ]
+ expect(normalizePathCleaningFilters(raw).map((r) => r.alias)).toEqual(['/first', '/second'])
+ })
+
+ it('returns [] for non-array input', () => {
+ expect(normalizePathCleaningFilters(undefined)).toEqual([])
+ expect(normalizePathCleaningFilters(null)).toEqual([])
+ expect(normalizePathCleaningFilters('nope')).toEqual([])
+ })
+})
+
+describe('renumber', () => {
+ it('assigns contiguous order 0..n-1', () => {
+ const rules: PathCleaningRule[] = [
+ { alias: '/a', regex: '/a' },
+ { alias: '/b', regex: '/b' },
+ ]
+ expect(renumber(rules)).toEqual([
+ { alias: '/a', regex: '/a', order: 0 },
+ { alias: '/b', regex: '/b', order: 1 },
+ ])
+ })
+})
+
+describe('applyOperations', () => {
+ const base: PathCleaningRule[] = [
+ { alias: '/users/<id>', regex: '/users/\\d+' },
+ { alias: '/signup/<id>', regex: '/signup/[0-9a-f-]+' },
+ ]
+
+ it('appends and inserts rules at the right positions', () => {
+ const { rules } = applyOperations(base, [
+ { action: 'append', alias: '/end', regex: '/end/\\d+' },
+ { action: 'insert', index: 0, alias: '/start', regex: '/start/\\d+' },
+ ])
+ expect(rules.map((r) => r.alias)).toEqual(['/start', '/users/<id>', '/signup/<id>', '/end'])
+ })
+
+ it('clamps an out-of-range insert index to the end', () => {
+ const { rules } = applyOperations(base, [{ action: 'insert', index: 99, alias: '/z', regex: '/z' }])
+ expect(rules[rules.length - 1]!.alias).toBe('/z')
+ })
+
+ it('replaces an existing rule while keeping its position, preserving omitted fields', () => {
+ const { rules } = applyOperations(base, [
+ { action: 'replace', target_alias: '/signup/<id>', regex: '^/signup/[^/]+$' },
+ ])
+ expect(rules[1]).toEqual({ alias: '/signup/<id>', regex: '^/signup/[^/]+$' })
+ })
+
+ it('removes a rule by alias', () => {
+ const { rules } = applyOperations(base, [{ action: 'remove', target_alias: '/users/<id>' }])
+ expect(rules.map((r) => r.alias)).toEqual(['/signup/<id>'])
+ })
+
+ it('reorders when given a permutation of current aliases', () => {
+ const { rules } = applyOperations(base, [
+ { action: 'reorder', ordered_aliases: ['/signup/<id>', '/users/<id>'] },
+ ])
+ expect(rules.map((r) => r.alias)).toEqual(['/signup/<id>', '/users/<id>'])
+ })
+
+ it('throws on replace/remove of an unknown alias', () => {
+ expect(() => applyOperations(base, [{ action: 'remove', target_alias: '/nope' }])).toThrow(/no rule with alias/)
+ expect(() => applyOperations(base, [{ action: 'replace', target_alias: '/nope', regex: '/x' }])).toThrow(
+ /no rule with alias/
+ )
+ })
+
+ it('throws when reorder is not a permutation', () => {
+ expect(() => applyOperations(base, [{ action: 'reorder', ordered_aliases: ['/users/<id>'] }])).toThrow(
+ /must be exactly the current aliases/
+ )
+ })
+
+ it('throws on an invalid regex before anything is saved', () => {
+ expect(() => applyOperations(base, [{ action: 'append', alias: '/bad', regex: '/users/(' }])).toThrow(
+ /Invalid regex/
+ )
+ })
+
+ it('accepts a valid re2 inline-flag regex that JS RegExp alone would reject', () => {
+ // (?i) is valid re2 and documented for case-insensitive path cleaning, but throws in JS.
+ const { rules } = applyOperations(base, [{ action: 'append', alias: '/ci', regex: '(?i)/ci/[0-9]+' }])
+ expect(rules[rules.length - 1]).toEqual({ alias: '/ci', regex: '(?i)/ci/[0-9]+' })
+ })
+
+ it('does not mutate the input array', () => {
+ applyOperations(base, [{ action: 'remove', target_alias: '/users/<id>' }])
+ expect(base.map((r) => r.alias)).toEqual(['/users/<id>', '/signup/<id>'])
+ })
+
+ // Aliases are not unique — these guard the duplicate-alias handling.
+ const dupes: PathCleaningRule[] = [
+ { alias: '/x', regex: '/x/a' },
+ { alias: '/x', regex: '/x/b' },
+ { alias: '/y', regex: '/y' },
+ ]
+
+ it('reorders duplicate-aliased rules without dropping any', () => {
+ const { rules } = applyOperations(dupes, [{ action: 'reorder', ordered_aliases: ['/y', '/x', '/x'] }])
+ // All three rules survive; same-alias rules keep their original relative order.
+ expect(rules).toEqual([
+ { alias: '/y', regex: '/y' },
+ { alias: '/x', regex: '/x/a' },
+ { alias: '/x', regex: '/x/b' },
+ ])
+ })
+
+ it('rejects a reorder that would drop a duplicate-aliased rule', () => {
+ // ["/y","/x"] has the right distinct aliases but the wrong multiset (2 vs 3 rules).
+ expect(() => applyOperations(dupes, [{ action: 'reorder', ordered_aliases: ['/y', '/x'] }])).toThrow(
+ /must be exactly the current aliases/
+ )
+ })
+
+ it('rejects a reorder with a repeated alias beyond its real count', () => {
+ expect(() =>
+ applyOperations(base, [{ action: 'reorder', ordered_aliases: ['/users/<id>', '/users/<id>'] }])
+ ).toThrow(/must be exactly the current aliases/)
+ })
+
+ it('refuses to replace or remove an ambiguous (duplicated) alias instead of guessing', () => {
+ expect(() => applyOperations(dupes, [{ action: 'remove', target_alias: '/x' }])).toThrow(/ambiguous/)
+ expect(() => applyOperations(dupes, [{ action: 'replace', target_alias: '/x', regex: '/z' }])).toThrow(
+ /ambiguous/
+ )
+ })
+
+ it('creates and targets an empty-alias (delete matched text) rule', () => {
+ const created = applyOperations(
+ [{ alias: '/x', regex: '/x' }],
+ [{ action: 'append', alias: '', regex: '\\?page=\\d+$' }]
+ )
+ expect(created.rules).toEqual([
+ { alias: '/x', regex: '/x' },
+ { alias: '', regex: '\\?page=\\d+$' },
+ ])
+ // The empty-alias rule can then be targeted by "" for removal.
+ const removed = applyOperations(created.rules, [{ action: 'remove', target_alias: '' }])
+ expect(removed.rules).toEqual([{ alias: '/x', regex: '/x' }])
+ })
+})
+
+function createMockContext(overrides: {
+ currentFilters: unknown
+ getMock?: ReturnType<typeof vi.fn>
+ updateMock?: ReturnType<typeof vi.fn>
+}): Context {
+ const getMock =
+ overrides.getMock ??
+ vi.fn().mockResolvedValue({ success: true, data: { path_cleaning_filters: overrides.currentFilters } })
+ const updateMock =
+ overrides.updateMock ??
+ vi.fn().mockImplementation(async ({ filters }: { filters: unknown }) => ({
+ success: true,
+ data: { path_cleaning_filters: filters },
+ }))
+ return {
+ api: {
+ projects: () => ({ get: getMock, updatePathCleaningFilters: updateMock }),
+ getProjectBaseUrl: () => 'https://us.posthog.com/project/2',
+ } as any,
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('2') } as any,
+ env: {} as any,
+ sessionManager: {} as any,
+ cache: {} as any,
+ getDistinctId: async () => 'test-distinct-id',
+ trackEvent: async () => {},
+ }
+}
+
+describe('path-cleaning-rules-update handler', () => {
+ const current = [{ alias: '/signup/<id>', regex: '/signup/[0-9a-f-]+', order: 0 }]
+
+ it('previews without saving when confirm is not set', async () => {
+ const updateMock = vi.fn()
+ const context = createMockContext({ currentFilters: current, updateMock })
+
+ const result = await updatePathCleaningHandler(context, {
+ operations: [{ action: 'append', alias: '/shared/<hash>', regex: '^/shared/[^/]+$' }],
+ sample_paths: ['/shared/abc123'],
+ confirm: false,
+ })
+
+ expect(updateMock).not.toHaveBeenCalled()
+ expect(result.applied).toBe(false)
+ expect(result.resulting_rules).toEqual([
+ { alias: '/signup/<id>', regex: '/signup/[0-9a-f-]+', order: 0 },
+ { alias: '/shared/<hash>', regex: '^/shared/[^/]+$', order: 1 },
+ ])
+ expect(result.sample_preview).toEqual([
+ { path: '/shared/abc123', before: '/shared/abc123', after: '/shared/<hash>' },
+ ])
+ })
+
+ it('saves the renumbered rules when confirm is true', async () => {
+ const updateMock = vi.fn().mockImplementation(async ({ filters }: { filters: unknown }) => ({
+ success: true,
+ data: { path_cleaning_filters: filters },
+ }))
+ const context = createMockContext({ currentFilters: current, updateMock })
+
+ const result = await updatePathCleaningHandler(context, {
+ operations: [
+ { action: 'append', alias: '/embedded/<hash>', regex: '^/embedded/[^/]+$' },
+ { action: 'remove', target_alias: '/signup/<id>' },
+ ],
+ confirm: true,
+ })
+
+ expect(updateMock).toHaveBeenCalledOnce()
+ expect(updateMock.mock.calls[0]![0].filters).toEqual([
+ { alias: '/embedded/<hash>', regex: '^/embedded/[^/]+$', order: 0 },
+ ])
+ expect(result.applied).toBe(true)
+ })
+
+ it('previews before against the OLD rules and after against the NEW rules', async () => {
+ // Existing rule already rewrites the sample path (before is a non-trivial rewrite);
+ // the appended rule then matches that output and rewrites further, so after differs.
+ // Guards against before/after being swapped or both computed from the same rule set.
+ const existing = [{ alias: '/users/<id>', regex: '/users/[0-9]+', order: 0 }]
+ const context = createMockContext({ currentFilters: existing })
+
+ const result = await updatePathCleaningHandler(context, {
+ operations: [{ action: 'append', alias: '/users/<id>/anon', regex: '/users/<id>$' }],
+ sample_paths: ['/users/42'],
+ confirm: false,
+ })
+
+ expect(result.sample_preview).toEqual([{ path: '/users/42', before: '/users/<id>', after: '/users/<id>/anon' }])
+ })
+
+ it('keeps a literal $ in an alias through the preview', async () => {
+ const context = createMockContext({ currentFilters: [] })
+ const result = await updatePathCleaningHandler(context, {
+ operations: [{ action: 'append', alias: '/price/$amount', regex: '/price/[0-9]+' }],
+ sample_paths: ['/price/500'],
+ confirm: false,
+ })
+ // Not "/price/$&" or "/price/" — the alias $ must survive JS String.replace semantics.
+ expect(result.sample_preview).toEqual([{ path: '/price/500', before: '/price/500', after: '/price/$amount' }])
+ })
+
+ it('reflects a (?i) inline-flag rule in the preview instead of dropping it', async () => {
+ // (?i) throws under a naive JS RegExp; the preview must translate it to the JS `i`
+ // flag so an accepted rule doesn't silently vanish from before/after.
+ const context = createMockContext({ currentFilters: [] })
+ const result = await updatePathCleaningHandler(context, {
+ operations: [{ action: 'append', alias: '/user/<id>', regex: '(?i)/USER/[0-9]+' }],
+ sample_paths: ['/user/42'],
+ confirm: false,
+ })
+ expect(result.sample_preview).toEqual([{ path: '/user/42', before: '/user/42', after: '/user/<id>' }])
+ })
+
+ it('chains preview rules in order, each feeding the next', async () => {
+ const context = createMockContext({ currentFilters: [] })
+ const result = await updatePathCleaningHandler(context, {
+ operations: [
+ { action: 'append', alias: '/a/<id>', regex: '/a/[0-9]+' },
+ // Second rule only matches the output of the first — proves sequential chaining.
+ { action: 'append', alias: '/a/<id>/clean', regex: '/a/<id>$' },
+ ],
+ sample_paths: ['/a/7'],
+ confirm: false,
+ })
+ expect(result.sample_preview![0]!.after).toBe('/a/<id>/clean')
+ })
+
+ it('surfaces a read failure without attempting a write', async () => {
+ const updateMock = vi.fn()
+ const getMock = vi.fn().mockResolvedValue({ success: false, error: new Error('boom') })
+ const context = createMockContext({ currentFilters: current, getMock, updateMock })
+
+ await expect(
+ updatePathCleaningHandler(context, {
+ operations: [{ action: 'remove', target_alias: '/signup/<id>' }],
+ confirm: true,
+ })
+ ).rejects.toThrow(/Failed to read current path cleaning rules: boom/)
+ expect(updateMock).not.toHaveBeenCalled()
+ })
+
+ it('exposes the expected tool name', () => {
+ expect(updatePathCleaning().name).toBe('path-cleaning-rules-update')
+ })
+})