Memory Trees (MTrees)
Table of Contents
Section titled “Table of Contents”- Overview & Radix Tree Architecture
- Business & Operational Significance
- 🎯 User Roles & Key Capabilities
- Visual Interface & Layout
- Field Reference & Prefix Entry Parameters
- Kamailio
m_treeRouting Mechanics - High-Performance LCR Dialplan Integration
- Troubleshooting & Verification
- Model Context Protocol (MCP) AI Integration
- Glossary
1. Overview & Radix Tree Architecture
Section titled “1. Overview & Radix Tree Architecture”In Ring2All SBC, the Memory Trees (MTrees) module provides microsecond-fast prefix lookups for telephone number routing, Least Cost Routing (LCR), and destination-based rate classification. Powered by Kamailio’s native m_tree module, MTrees stores millions of dialed digit prefixes in hierarchical Radix Trees (trie data structures) held directly inside shared memory (shm).
[Root Dialplan Tree] │ ┌──────────────────┼──────────────────┐ "+" "0" "1" │ │ ┌──────┴──────┐ Nanp Local "1" "4" │ │ NANP (+1) "4" │ UK (+44) │ ┌───┴───┐ "2" "7" │ │ London MobileWhen an inbound or outbound call traverses the SBC, the engine executes a Longest Prefix Match (LPM) against the dialed Request-URI. Because the tree is traversed character by character in RAM without querying disk or relational databases, prefix lookups complete in fractions of a microsecond ($< 5\mu s$), even under thousands of simultaneous calls per second.
2. Business & Operational Significance
Section titled “2. Business & Operational Significance”- Sub-Microsecond Dialplan Resolution: Evaluates carrier routing groups, tariff zones, and country codes instantaneously, eliminating relational database bottlenecks.
- Carrier Least Cost Routing (LCR): Automatically maps dialed numbers to carrier group identifiers (
carrier_id), ensuring calls always exit through the most cost-effective upstream provider. - Toll Fraud & High-Risk Blocking: Rapidly intercepts and drops calls targeting unassigned or high-rate international destinations (e.g., premium-rate satellite prefixes).
- Hot Configuration Reloading: Allows operations teams to update prefix dictionaries and rate cards in real time via JSON-RPC without dropping active calls or restarting the Kamailio daemon.
3. 🎯 User Roles & Key Capabilities
Section titled “3. 🎯 User Roles & Key Capabilities”| Role | Primary Use Case | Key Capabilities |
|---|---|---|
| LCR Dialplan Engineer | Dialing Rule Optimization | Maintain prefix-to-carrier routing tables, assign cost tier values, and configure regional prefixes. |
| Carrier Interconnect Analyst | Rate Card & Tariff Mapping | Import country code trees, align prefix tables with partner billing contracts, and verify destination match order. |
| SBC Routing Architect | Memory Tree Capacity Sizing | Allocate shared memory pools for large mtree datasets (500k+ records) and structure prefix hierarchy. |
| Systems Administrator | Live Tree Maintenance | Perform hot-reloads of mtree memory tables and audit tree integrity via the RPC Console. |
| AI Dialplan Copilot / Routing Optimizer | Autonomous Prefix Management | Query prefix match rules, inject real-time carrier routes, and trigger live MTree memory reloads via MCP. |
4. Visual Interface & Layout
Section titled “4. Visual Interface & Layout”The MTrees interface provides a high-density management table displaying configured prefix trees, matched prefix numbers, assigned integer payloads/values, and destination descriptions.

5. Field Reference & Prefix Entry Parameters
Section titled “5. Field Reference & Prefix Entry Parameters”| Field Name | Data Type | Database Field | Description |
|---|---|---|---|
| Tree Name | String | m_tree.tname |
Identifier of the prefix tree (e.g., lcr_tree, blacklist_tree, rates_tree). |
| Prefix Pattern | String | m_tree.tprefix |
Dialed number prefix in E.164 format or national format (e.g., +1, +4420, +52). |
| Assigned Value | String / Integer | m_tree.tvalue |
Integer payload or identifier returned upon match (e.g., Carrier ID 10, Tier 1). |
| Description | String | description |
Human-readable destination label (e.g., United States / Canada NANP, Spain Standard). |
| Match Mode | Enum | Core Logic | The tree engine always performs Longest Prefix Matching (LPM). If +4420 and +44 exist, a call to +442079460000 matches +4420. |
6. Kamailio m_tree Routing Mechanics
Section titled “6. Kamailio m_tree Routing Mechanics”In the Kamailio routing script, MTrees are queried using the mt_match() function:
# Execute Longest Prefix Match against Request-URI username ($rU)route[EVALUATE_LCR_PREFIX] { # Match Request-URI against "lcr_tree" and store assigned value in $avp(carrier_group) if (mt_match("lcr_tree", "$rU", "0")) { xlog("L_INFO", "[MTREE] Matched prefix for $rU -> Carrier Group: $avp(carrier_group)\n");
# Pass carrier group to Dispatcher module ds_select_dst("$avp(carrier_group)", "4"); } else { xlog("L_WARN", "[MTREE] No route prefix found for dialed number: $rU\n"); sl_send_reply("404", "Destination Prefix Not Found"); exit; }}The third argument "0" specifies exact match mode with longest prefix fallback, returning the associated value directly into the target AVP variable.
7. High-Performance LCR Dialplan Integration
Section titled “7. High-Performance LCR Dialplan Integration”MTrees provide the foundational lookup layer for advanced routing logic:
- Prefix Ingestion: Thousands of E.164 country and area codes are loaded into PostgreSQL table
mtree_vals. - In-Memory Compilation: Upon engine startup or reload, Kamailio reads records into an in-memory trie structure.
- Dispatcher Group Handoff: The integer value associated with the prefix directly corresponds to a Kamailio
dispatchergroup set containing primary and backup carrier gateways. - Sub-Millisecond Execution: Call dispatching is completed entirely within the first SIP worker cycle, minimizing Post-Dial Delay (PDD).
8. Troubleshooting & Verification
Section titled “8. Troubleshooting & Verification”Inspecting Loaded Trees via RPC Console
Section titled “Inspecting Loaded Trees via RPC Console”Execute the mtree.list command in the RPC Console to verify that prefix records are resident in memory:
mtree.listSample output:
{ "jsonrpc": "2.0", "result": [ { "tree": "lcr_tree", "prefix": "+1", "value": "10" }, { "tree": "lcr_tree", "prefix": "+44", "value": "20" }, { "tree": "lcr_tree", "prefix": "+52", "value": "30" } ], "id": 1}Hot-Reloading Prefix Trees
Section titled “Hot-Reloading Prefix Trees”After adding or modifying prefixes in the Web UI, reload the memory tree without restarting Kamailio:
mtree.reload lcr_tree9. Model Context Protocol (MCP) AI Integration
Section titled “9. Model Context Protocol (MCP) AI Integration”The Memory Trees (MTrees) subsystem integrates with the Model Context Protocol (MCP) to allow diagnostic agents to query prefix patterns, dynamically insert destination routes, remove obsolete prefixes, and hot-reload radix trees in Kamailio memory.
Available MCP Tools
Section titled “Available MCP Tools”| Tool Name | Operation Type | Risk Level | Description |
|---|---|---|---|
list_mtrees |
Status Query | read |
List configured radix prefix trees and entries with optional filtering by tree name. |
create_mtree_entry |
Configuration Mutation | operational |
Add a new telephone number prefix pattern and associated integer payload to an MTree. |
delete_mtree_entry |
Configuration Deletion | operational |
Remove an existing prefix record from an MTree table by ID. |
reload_mtrees |
Operational Reload | operational |
Issue an in-memory hot reload command (mtree.reload) to Kamailio via JSON-RPC. |
Tool Schemas & Payloads
Section titled “Tool Schemas & Payloads”1. list_mtrees
Section titled “1. list_mtrees”Input Schema
Section titled “Input Schema”{ "type": "object", "properties": { "tree_name": { "type": "string", "description": "Optional name of the tree to filter (e.g. 'lcr_tree', 'blacklist_tree')." } }}Output Payload Example
Section titled “Output Payload Example”{ "success": true, "data": { "total": 3, "entries": [ { "id": 1, "tree_name": "lcr_tree", "prefix": "+1", "value": "10", "description": "NANP USA / Canada" }, { "id": 2, "tree_name": "lcr_tree", "prefix": "+44", "value": "20", "description": "United Kingdom" } ] }}2. create_mtree_entry
Section titled “2. create_mtree_entry”Input Schema
Section titled “Input Schema”{ "type": "object", "properties": { "tree_name": { "type": "string", "description": "Name of the target radix tree (e.g. 'lcr_tree')." }, "prefix": { "type": "string", "description": "Dialed number prefix pattern in E.164 or national format (e.g. '+52')." }, "value": { "type": "string", "description": "Integer payload or carrier group ID returned upon match (e.g. '30')." }, "description": { "type": "string", "description": "Destination label or routing comment." } }, "required": ["tree_name", "prefix", "value"]}Output Payload Example
Section titled “Output Payload Example”{ "success": true, "data": { "message": "MTree prefix entry created successfully.", "id": 4 }}3. reload_mtrees
Section titled “3. reload_mtrees”Input Schema
Section titled “Input Schema”{ "type": "object", "properties": { "tree_name": { "type": "string", "description": "Optional specific tree name to reload, or reload all trees if omitted." } }}Output Payload Example
Section titled “Output Payload Example”{ "success": true, "data": { "message": "Memory tree 'lcr_tree' reloaded successfully into Kamailio.", "rpc_response": "MTree lcr_tree reloaded" }}Natural Language AI Prompts
Section titled “Natural Language AI Prompts”English Examples
Section titled “English Examples”- “List all prefix entries configured in the ‘lcr_tree’ memory tree.”
- “Add prefix ‘+52’ with carrier value ‘30’ to ‘lcr_tree’ for Mexico destination routing.”
- “Hot-reload the ‘lcr_tree’ radix tree in Kamailio shared memory.”
Spanish Examples (Español)
Section titled “Spanish Examples (Español)”- “Lista todas las entradas de prefijos configuradas en el árbol de memoria ‘lcr_tree’.”
- “Agrega el prefijo ‘+52’ con valor de carrier ‘30’ a ‘lcr_tree’ para enrutamiento a México.”
- “Recarga en caliente el árbol radix ‘lcr_tree’ en la memoria compartida de Kamailio.”
Enterprise Safeguards & Access Governance
Section titled “Enterprise Safeguards & Access Governance”- E.164 Prefix Validation: Digit prefixes are normalized and validated to prevent syntax corruption of the radix tree.
- In-Flight Call Protection: The
reload_mtreescommand switches memory pointer trees atomically without dropping active calls or increasing PDD. - Role Authorization: Prefix additions, deletions, and tree reloads mandate
lcr_carrier_managerorsbc_system_adminrole profiles.
10. Glossary
Section titled “10. Glossary”- MTree (Memory Tree): An in-memory radix tree data structure in Kamailio optimized for sub-microsecond longest prefix matching.
- LPM (Longest Prefix Match): An algorithm where the entry with the longest matching prefix is selected from multiple candidates (e.g., matching
+4420over+44). - LCR (Least Cost Routing): Directing outgoing telephone calls to the telecom carrier offering the lowest termination cost for a given destination.
- Radix Tree / Trie: An ordered tree data structure used to store an associative array where the keys are usually strings.

