# Create a Custom PMD Rule Using MCP Tools (Developer Preview)

Use the MCP tools `get_ast_nodes_to_generate_xpath` and `create_custom_rule` to generate custom PMD rules for Apex and Visualforce code in MCP clients such as Agentforce Vibes. Define organization-specific coding standards and detect custom patterns by entering a prompt that describes what to flag, such as deeply nested if statements or `System.debug` usage in Apex. Code Analyzer uses `get_ast_nodes_to_generate_xpath` to extract AST nodes and generate XPath with AI, then uses `create_custom_rule` to create the rule and add it to `code-analyzer.yml`.

To create a custom PMD rule to flag deeply nested if statement, use these steps

1. [Access the Code Analyzer MCP tools](/docs/platform/salesforce-code-analyzer/guide/mcp.md)
2. In an MCP client such as Agentforce Vibes, enter a prompt like: “Help me create a rule to flag if statements that are three levels deep.”
3. The tool generates a sample code that violates the rule. Approve or refine the sample code.

```
      {
      "sampleCode": "public with sharing class NestedIfViolationExample {\n\tpublic static Integer checkDepth(Integer a, Integer b, Integer c, Integer d) {\n    \tInteger x = 0;\n    \tif (a > 0) {             \t// depth 1\n        \tif (b > 0) {         \t// depth 2\n            \tif (c > 0) {     \t// depth 3\n                \tif (d > 0) {\t// depth 4 -> VIOLATION (>= 4)\n                    \tx = 1;\n                \t}\n            \t}\n        \t}\n    \t}\n    \treturn x;\n\t}\n}\n",
      "language": "apex",
      "engine": "pmd"
    }

```

4. The tool generates the XPath by extracting the relevant AST nodes for your prompt. Modify the query as needed.
   ![MCP client generates xpath query](https://a.sfdcstatic.com/developer-website/sfdocs/code-analyzer/media/salesforce-code-analyzer/generate-xpath.png)
5. The tool creates the rule in an XML file and updates the code-analyzer.yml with the new rule.
   ![MCP client generates xpath file](https://a.sfdcstatic.com/developer-website/sfdocs/code-analyzer/media/salesforce-code-analyzer/xpath-file.png)

   ![MCP client updates config file with the rule](https://a.sfdcstatic.com/developer-website/sfdocs/code-analyzer/media/salesforce-code-analyzer/config-file.png)
6. Verify the rule by running Code Analyzer against your target codebase. For example:

```
    sf code-analyzer run --target "force-app/main/default/classes/NestedIfExample.cls"

```

```
  ![Verify the rule against a target code base](../../../media/salesforce-code-analyzer/verify-target.png)
```

You can also ask the tool to generate additional sample code that violates the rule, so you can confirm the analyzer flags the expected violations.

## See Also

- [PMD Engine](/docs/platform/salesforce-code-analyzer/guide/engine-pmd.md)
- [Use MCP Tools to Analyze Your Code](/docs/platform/salesforce-code-analyzer/guide/mcp.md)
