--- title: "SIP Manipulation Rules (SMR)" description: "Documentation for SIP Manipulation Rules" --- ## Table of Contents 1. [Overview & Transformation Architecture](#1-overview--transformation-architecture) 2. [Business & Operational Significance](#2-business--operational-significance) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Layout](#4-visual-interface--layout) 5. [Field Reference & Rule Parameters](#5-field-reference--rule-parameters) 6. [Transformation Engine Mechanics & PCRE Processing](#6-transformation-engine-mechanics--pcre-processing) 7. [Standard Enterprise Use Cases](#7-standard-enterprise-use-cases) 8. [Troubleshooting & Verification](#8-troubleshooting--verification) 9. [Model Context Protocol (MCP) AI Integration](#9-model-context-protocol-mcp-ai-integration) 10. [Glossary](#10-glossary) --- ## 1. Overview & Transformation Architecture In **Ring2All SBC**, the **SIP Manipulation Rules (SMR)** module provides a powerful regular expression transformation engine for modifying, sanitizing, injecting, and stripping SIP headers and URIs in real time. Because different telecom carriers, PBX manufacturers, and softswitches interpret RFC 3261 standards with minor discrepancies, SMR bridges interoperability gaps dynamically without modifying core source code. ``` Incoming SIP Packet SMR Transformation Pipeline Outbound SIP Packet β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ INVITE sip:+14155552671 β”‚ β”‚ 1. Match Target Header β”‚ β”‚ INVITE sip:14155552671 β”‚ β”‚ From: "Alice" │────► SMR ──►│ 2. Evaluate PCRE Regex │───► Outbound ─► From: "Alice" β”‚ β”‚ To: β”‚ β”‚ 3. Apply Replacement Patternβ”‚ β”‚ X-Tenant-ID: ring2all-01 β”‚ β”‚ Contact: ... β”‚ β”‚ 4. Order by Execution Index β”‚ β”‚ Privacy: id β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` Rules can target the **Request-URI (R-URI)**, standard identity headers (**From**, **To**, **Contact**), diversion headers (**Diversion**, **History-Info**), authentication privacy headers (**P-Asserted-Identity**, **Remote-Party-ID**), or custom proprietary headers (`X-Carrier-*`). --- ## 2. Business & Operational Significance * **Carrier Protocol Interoperability**: Resolves vendor-specific incompatibilities (e.g., stripping the leading `+` for legacy carriers that only accept digits, or injecting technical routing prefixes). * **Identity & Privacy Compliance**: Masks caller identification (`Anonymous`) while preserving cryptographically asserted identities for emergency services and lawful intercept compliance. * **Carrier Billing Attribution**: Injects custom metadata headers (e.g., `X-Tenant-ID`, `X-Account-Code`) to allow downstream wholesale carrier switches to categorize and bill traffic accurately. * **Dialed Number Normalization**: Converts local 7-digit or 10-digit national numbers into globally recognized E.164 formats before hitting least-cost routing tables. --- ## 3. 🎯 User Roles & Key Capabilities | Role | Primary Use Case | Key Capabilities | | :--- | :--- | :--- | | **SIP Interoperability Specialist** | Vendor Dialplan Normalization | Author PCRE regex rules, test URI transformations, and align SIP headers with third-party carrier specifications. | | **Carrier Onboarding Engineer** | Trunk Header Customization | Inject mandatory carrier authorization tokens and custom billing headers on egress trunk routes. | | **Security & Privacy Compliance Officer** | Caller ID & CLI Masking | Enforce caller privacy regulations by stripping PAI or rewriting From display headers on outbound calls. | | **SBC Administrator** | Execution Order Governance | Prioritize manipulation rule sequences and audit active header transformation filters. | | **AI Protocol Engineer / Interoperability Copilot** | Regex Testing & Rule Synthesis | Synthesize PCRE regex patterns, validate SIP header manipulation rules, and dynamically apply transformations via MCP. | --- ## 4. Visual Interface & Layout The SMR interface provides a list of configured transformation rules with their target headers, match patterns, and execution priorities, along with a modal editor for creating and updating rules. ### 4.1 SIP Manipulation Rules List View Displays all registered transformation rules, targets, direction, priority order, and operational status. ![SIP Manipulation Rules List View](/screenshots/sbc/settings/logic/smr/smr-list.png) ### 4.2 SMR Configuration Form Modal editor for defining target headers, PCRE regex patterns, replacement expressions, and directionality. ![SMR Configuration Form](/screenshots/sbc/settings/logic/smr/smr-form.png) --- ## 5. Field Reference & Rule Parameters | Parameter Name | Data Type | Options / Format | Description | | :--- | :--- | :--- | :--- | | **Rule Name** | String | Text (e.g., `Strip Leading Plus E.164`) | Descriptive label explaining the intent of the manipulation rule. | | **Target Header / URI** | Select | `Request-URI`, `From`, `To`, `PAI`, `Custom` | The specific SIP header or message part evaluated by this rule. | | **Header Name** | String | `X-Tenant-ID` (Conditional) | Specific header name when `Target` is set to `Custom Header`. | | **Direction** | Select | `Inbound`, `Outbound`, `Both` | Traffic flow where the rule executes: upon receiving a packet or before relaying it. | | **Match Regex (PCRE)** | String | `^\+([0-9]+)$` | Perl-Compatible Regular Expression (PCRE) matched against the target string. | | **Replacement String** | String | `$1` or `tenant-prod-100` | Replacement pattern. Supports backreferences (`$1`, `$2`) to capture groups. | | **Execution Priority** | Integer | `1` to `100` (Default `50`) | Processing order. Rules with lower numbers execute first. | | **Rule Status** | Switch | `Active` / `Disabled` | Toggle to enable or disable the rule without deleting it from the database. | --- ## 6. Transformation Engine Mechanics & PCRE Processing Under the hood, SMR executes using Kamailio's `textops`, `textopsx`, and `uac` modules: ```text # SMR Execution Flow in Kamailio routing script route[APPLY_OUTBOUND_SMR] { # Rule 10: Strip leading '+' from Request-URI if ($rU =~ "^\+([0-9]+)$") { $rU = $(rU{s.substr,1,0}); xlog("L_INFO", "[SMR] Stripped leading +: new R-URI=$rU\n"); } # Rule 20: Inject X-Tenant-ID Header if (!is_present_hf("X-Tenant-ID")) { append_hf("X-Tenant-ID: ring2all-prod\r\n"); } # Rule 30: Anonymize Caller ID if privacy requested if ($hdr(Privacy) == "id") { uac_replace_from("Anonymous", "sip:anonymous@anonymous.invalid"); } } ``` Because transformations operate directly on message buffers in shared memory, rule evaluation introduces zero measurable latency. --- ## 7. Standard Enterprise Use Cases ### Case 1: Strip Leading Plus (`+`) for Legacy Trunks * **Target**: `Request-URI` * **Direction**: `Outbound` * **Match Regex**: `^\+([0-9]+)$` * **Replacement**: `$1` * **Result**: `+14155552671` becomes `14155552671`. ### Case 2: Inject Carrier Account Metadata * **Target**: `Custom Header` (`X-Carrier-Account`) * **Direction**: `Outbound` * **Match Regex**: `.*` * **Replacement**: `ACCT-99201` * **Result**: Injects `X-Carrier-Account: ACCT-99201\r\n` into the SIP request before dispatching to the carrier. ### Case 3: Caller ID Anonymization for Outbound Calls * **Target**: `From Header` * **Direction**: `Outbound` * **Match Regex**: `^"?(.*?)"?\s*$` * **Replacement**: `"Anonymous" ` * **Result**: Masks the caller's true display name and telephone number while preserving the internal Call-ID. --- ## 8. Troubleshooting & Verification ### Validating Transformations via SIP Tracing Capture live SIP packets using the **SIP Traces & Diagnostics** module (`sip-traces`) to confirm that headers are correctly rewritten on egress: ```bash # Verify headers on outbound trunk interface grep -E "(X-Tenant-ID|From:|To:|INVITE)" /var/log/kamailio.log ``` ### Hot-Reloading Manipulation Rules via RPC ```bash smr.reload ``` --- ## 9. Model Context Protocol (MCP) AI Integration The Smart Message Routing & SIP Manipulation Rules (SMR) module integrates with the Model Context Protocol (MCP) to allow diagnostic agents to query active header modification rules, inspect regex match conditions, create new header mutations, and safely remove obsolete rules. ### Available MCP Tools | Tool Name | Operation Type | Risk Level | Description | | :--- | :--- | :--- | :--- | | `list_smr_rules` | Status Query | `read` | List all SIP Manipulation rules (header transformations, regex filters, directions, and priorities). | | `get_smr_rule_status` | Detailed Audit | `read` | Get configuration, regex matching, and header actions of a specific SMR rule. | | `create_smr_rule` | Configuration Mutation | `operational` | Create a new SIP header manipulation rule in Kamailio (e.g. rewrite PAI, strip custom headers). | | `delete_smr_rule` | Configuration Deletion | `operational` | Delete a SIP manipulation rule and regenerate Kamailio SMR routing drop-in configuration. | ### Tool Schemas & Payloads #### 1. `list_smr_rules` ##### Input Schema ```json { "type": "object", "properties": { "direction": { "type": "string", "enum": ["inbound", "outbound", "both"], "description": "Filter by message direction." }, "status": { "type": "string", "enum": ["active", "disabled"], "description": "Filter by operational status." } } } ``` ##### Output Payload Example ```json { "success": true, "data": { "totalRules": 2, "rules": [ { "id": 1, "name": "Strip Leading Plus", "direction": "outbound", "matchHeader": "Request-URI", "matchRegex": "^\\+([0-9]+)$", "actionType": "modify", "actionValue": "$1", "priority": 10, "status": "active" }, { "id": 2, "name": "Inject Carrier Token", "direction": "outbound", "matchHeader": "X-Carrier-Token", "matchRegex": ".*", "actionType": "add", "actionValue": "SEC-TOKEN-9982", "priority": 20, "status": "active" } ] } } ``` #### 2. `create_smr_rule` ##### Input Schema ```json { "type": "object", "properties": { "name": { "type": "string", "description": "Descriptive rule name (e.g. 'Strip X-Call-ID', 'Normalize E164 CLI')." }, "direction": { "type": "string", "enum": ["inbound", "outbound", "both"], "description": "Direction to apply rule." }, "matchHeader": { "type": "string", "description": "Target SIP Header (e.g. 'P-Asserted-Identity', 'X-Account-ID', 'From')." }, "matchRegex": { "type": "string", "description": "Regex pattern to match or extract (e.g. '.*', '^\\+?1([0-9]{10})$')." }, "actionType": { "type": "string", "enum": ["add", "remove", "modify", "strip_prefix"], "description": "Action to perform on the header." }, "actionValue": { "type": "string", "description": "New value or replacement expression." }, "priority": { "type": "number", "description": "Rule evaluation order (default: 10). Lower number runs first." } }, "required": ["name", "direction", "matchHeader", "actionType"] } ``` ##### Output Payload Example ```json { "success": true, "data": { "message": "SMR rule created successfully and Kamailio configuration reloaded.", "ruleId": 3 } } ``` ### Natural Language AI Prompts #### English Examples * *"List all outbound SIP manipulation rules currently active on the SBC."* * *"Create an outbound SMR rule to strip the leading plus from Request-URI for legacy carrier trunks."* * *"Inspect the configuration and regex pattern of SMR rule ID 1."* #### Spanish Examples (EspaΓ±ol) * *"Lista todas las reglas de manipulaciΓ³n SIP salientes actualmente activas en el SBC."* * *"Crea una regla SMR saliente para eliminar el signo mΓ‘s inicial del Request-URI para troncales carrier legadas."* * *"Inspecciona la configuraciΓ³n y el patrΓ³n regex de la regla SMR con ID 1."* ### Enterprise Safeguards & Access Governance 1. **PCRE Syntax Guardrails**: Regular expressions are syntax-checked prior to injection to prevent Kamailio routing script parse crashes. 2. **Automatic Configuration Regeneration**: The `create_smr_rule` tool writes drop-in configuration to `/etc/kamailio/smr_rules.cfg` and executes `kamcmd core.reload` atomically. 3. **Role Authorization**: Rule creation and deletion require `noc_network_engineer` or `sbc_system_admin` privileges. --- ## 10. Glossary * **SMR (SIP Manipulation Rules)**: A rule-based framework for parsing and modifying SIP headers and message components in real time. * **PCRE (Perl-Compatible Regular Expressions)**: A standardized regular expression library providing advanced pattern matching and capture group substitution. * **Request-URI (R-URI)**: The first line of a SIP request indicating the destination user, host, and port where the request is being addressed. * **Backreference**: A regular expression feature allowing parts of a matched string (`$1`, `$2`) to be reused inside the replacement expression.