Skip to main content
Glama
README.md
# Kamailio MCP Server

An AI-powered **and** shell-callable control plane and developer platform for [Kamailio](https://www.kamailio.org). Connect any MCP-compatible AI client (Claude Desktop, Cursor, Cline, Continue) for natural-language operations — or use the same primitives via the `kamailio-mcp` CLI for shell scripts, CI pipelines, and external Web Applications / Admin UI Portals.

---

## Features

| Feature | Description |
|---|---|
| **Dynamic Documentation Engine** | Scrapes, parses, and indexes Kamailio module documentation directly from URL patterns (e.g., `https://kamailio.org/docs/modules/6.0.x/`, `https://kamailio.org/docs/modules/6.1.x/`, `.../modules/acc.html`). |
| **App-Building Form Schema Generator** | Exports machine-readable **JSONSchema** definitions (`doc_get_module_schema`) for module parameters, enabling dynamic Web UI forms (React/Vue/Next.js) to render valid config controls automatically. |
| **AST Config Parser** | Parses `kamailio.cfg` into a structured JSON parse tree (`cfg_parse_structure`) to render interactive block diagrams and visual routing node graphs. |
| **Scenario Builder** | 8 Jinja2 scenario templates (`residential_pbx`, `class4_sbc`, `load_balancer`, `sip_router`, `webrtc_gateway`, `presence_server`, `stir_shaken`, `registrar_proxy`) with preprocessor flag composition (`WITH_PGSQL`, `WITH_AUTH`, `WITH_NAT`, `WITH_TLS`, `WITH_DISPATCHER`, `WITH_DROUTING`, `WITH_WEBRTC`). |
| **Semantic Config Linter** | Rule-based checker verifying syntax, module load ordering (e.g. `tm` before `rr`), required modparams, NAT gaps, anti-flood protections (`pike`/`htable`/`secfilter`), and native `kamailio -c -f` validation. |
| **PostgreSQL & DB-Agnostic Engine** | Full async database CRUD management for subscribers, dispatchers, routing rules, user locations, and addresses. Pre-seeded with PostgreSQL 16 schema. |
| **JSONRPC Operational Tools** | Live execution of RPC methods (`core.uptime`, `ul.dump`, `dispatcher.reload`, `drouting.reload`, `htable.dump`, `dialog.list`). |
| **Docker Ready** | Single-command Docker Compose stack including Kamailio 6.0, PostgreSQL 16 (pre-seeded), and `kamailio-mcp`. |

---

## What You Can Do With This MCP Server

`kamailio-mcp` bridges AI assistants (like Claude, Cursor, and Continue), web applications, and automation pipelines directly with Kamailio SIP servers and their databases.

```
┌────────────────────────────────────────────────────────────────────────┐
│                        AI Clients & Web UIs                            │
│           (Claude Desktop / Cursor / Web Admin Portals / CI)           │
└──────────────────────────────────┬─────────────────────────────────────┘
                                   │  MCP Protocol / CLI
                                   ▼
┌────────────────────────────────────────────────────────────────────────┐
│                          Kamailio MCP Server                           │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────────┐  │
│  │ Config & Linter  │  │ Live JSONRPC Ops │  │ DB & Provisioning    │  │
│  └────────┬─────────┘  └────────┬─────────┘  └──────────┬───────────┘  │
└───────────┼─────────────────────┼───────────────────────┼──────────────┘
            │                     │                       │
            ▼                     ▼                       ▼
   kamailio.cfg / AST      Kamailio JSONRPC       PostgreSQL / MySQL
   (Templates & Lint)     (Port 8080/8081)         (Port 5432/3306)
```

### 1. 🧠 AI-Assisted SIP Engineering & Natural Language Ops
- **Ask AI in Plain English**: Query your live server with prompts like *"Show all active SIP registrations"*, *"Is Kamailio healthy and what is its uptime?"*, or *"Reload the dispatcher gateway table"*.
- **Config Troubleshooting & Generation**: Have AI design complete routing blocks, fix NAT traversal logic, or add security filters (`pike`, `htable`, `secfilter`).
- **Interactive Documentation Assistant**: Search module docs, query parameter types, and compare changes across Kamailio versions (e.g. 5.5.x vs 6.0.x) on the fly.

### 2. ⚙️ Automated Configuration Management & Linting
- **Generate Production Topologies**: Instantly build pre-tested `kamailio.cfg` templates for:
  - **Class 4 SBC** / Wholesale SIP trunking
  - **Residential PBX & Registrar** with NAT traversal (RTPengine)
  - **SIP Load Balancer & Dispatcher**
  - **WebRTC to SIP Gateway**
  - **STIR/SHAKEN** Authentication & Verification Proxy
- **Smart Capacity Tuning**: Automatically calculate optimal shared memory (`-m`), private memory (`-M`), and worker process children counts based on your target CPS (Calls Per Second) and concurrent dialogs.
- **Semantic Linting & AST Parsing**: Check configuration syntax, module loading order (e.g., ensuring `tm` loads before `rr`), required modparams, and parse configs into JSON ASTs for visual route builders.

### 3. ⚡ Real-Time Operational Control (JSONRPC)
- **Live Diagnostics**: Execute JSONRPC methods (`core.uptime`, `ul.dump`, `htable.dump`, `dialog.list`) without SSH-ing into the server.
- **Zero-Downtime Reloads**: Dynamically reload routing tables (`dispatcher.reload`, `drouting.reload`, `htable.reload`) while traffic continues flowing.
- **Health Checks**: Run structured health audits verifying both JSONRPC responsiveness and database connectivity.

### 4. 🗄️ Telephony & Database Provisioning
- **Subscriber Management**: Add, list, and search SIP subscribers (`subscriber_create`, `subscriber_list`) with automatic HA1/HA1B password hashing.
- **Dispatcher Gateway Provisioning**: Add new media servers/gateways (FreeSWITCH, Asterisk, SBCs) to dispatcher sets with custom load-balancing algorithms and priority weights.
- **User Location (UsrLoc) Lookups**: Inspect registered endpoints, contacts, user agents, and NAT IP/port mappings.

### 5. 🖥️ Build Custom Web Admin Portals & DevOps Pipelines
- **Dynamic Form Generation**: Use `doc_get_module_schema` to export machine-readable **JSONSchema** definitions of Kamailio modules so your frontend (React, Vue, Next.js) can generate config UIs automatically.
- **CI/CD Integration**: Run `kamailio-mcp cfg lint` in GitHub Actions or GitLab CI to catch broken configs before production deployments.
- **CLI & Scripting Ready**: Every MCP tool is also accessible directly via the `kamailio-mcp` CLI for bash scripts and cron jobs.

---

## Prerequisites & Installing Dependencies

### 1. System Prerequisites

On Linux (Debian / Ubuntu / Debian-based systems), install Python 3.10+, `pip`, `venv`, compiler tools, and PostgreSQL client header dependencies:

```bash
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y \
    python3 \
    python3-pip \
    python3-venv \
    python3-dev \
    build-essential \
    libpq-dev \
    curl

# Fedora / RHEL / Rocky Linux
sudo dnf install -y \
    python3 \
    python3-pip \
    python3-devel \
    gcc \
    postgresql-devel
```

### 2. Installing Python Package & Dependencies

We recommend using a Python virtual environment to isolate dependencies:

```bash
# Navigate to the repository
cd /usr/share/kamalio-mcp-server

# Create virtual environment
python3 -m venv .venv

# Activate virtual environment
source .venv/bin/activate

# Upgrade pip
pip install --upgrade pip

# Option A: Install with PostgreSQL support (Recommended)
pip install -e ".[postgres]"

# Option B: Install with MySQL support
pip install -e ".[mysql]"

# Option C: Install all development and testing dependencies
pip install -e ".[postgres,mysql,dev]"
```

Or simply use the `Makefile`:

```bash
make install
```

### 3. Configuration

Copy the example `.env` file and adjust settings:

```bash
cp .env.example .env
```

Key environment variables:

| Variable | Default | Description |
|---|---|---|
| `KAMAILIO_MCP_RPC_URL` | `http://127.0.0.1:8080/jsonrpc` | Kamailio JSONRPC HTTP endpoint |
| `KAMAILIO_MCP_DB_URL` | `postgresql+asyncpg://kamailio:kamailio@127.0.0.1:5432/kamailio` | Database connection string |
| `KAMAILIO_MCP_VERSION` | `6.0.x` | Target Kamailio release line |
| `KAMAILIO_MCP_DOCS_URL_PATTERN` | `https://kamailio.org/docs/modules/{version}/` | Documentation URL pattern |
| `KAMAILIO_MCP_TRANSPORT` | `stdio` | Transport (`stdio`, `sse`, `streamable-http`) |

---

## Deployment Instructions

### 1. Full Stack via Docker Compose (Quick Start)

Launch Kamailio 6.0, PostgreSQL 16 (pre-seeded with Kamailio tables), and `kamailio-mcp` with a single command:

```bash
docker compose -f docker/docker-compose.yml up -d
```

This brings up:
- **kamailio** -- Kamailio listening on SIP UDP/TCP port `5060` and JSONRPC on port `8081` (host).
- **postgres** -- PostgreSQL 16 initialized with Kamailio's official table schemas on port `5432`.
- **kamailio-mcp** -- MCP server running on port `8080` for SSE and HTTP clients.

To check logs:
```bash
docker compose -f docker/docker-compose.yml logs -f kamailio-mcp
```

### 2. Running Individual Services via Docker Compose

You can launch and manage any of the three services independently depending on your workflow:

#### A. Run Only PostgreSQL Database
Starts the pre-seeded PostgreSQL 16 instance on port `5432`:
```bash
docker compose -f docker/docker-compose.yml up -d postgres
# or via Makefile
make docker-up-db
```

#### B. Run Only Kamailio SIP Server
Starts Kamailio (and its PostgreSQL dependency) with JSONRPC exposed on host port `8081`:
```bash
docker compose -f docker/docker-compose.yml up -d kamailio
# or via Makefile
make docker-up-kamailio
```

#### C. Run Only the Kamailio MCP Server
Starts only the MCP server container on port `8080`:
```bash
docker compose -f docker/docker-compose.yml up -d kamailio-mcp
# or via Makefile
make docker-up-mcp
```

#### Monitoring & Stopping Individual Services
```bash
# View service-specific logs
docker compose -f docker/docker-compose.yml logs -f postgres
docker compose -f docker/docker-compose.yml logs -f kamailio
docker compose -f docker/docker-compose.yml logs -f kamailio-mcp

# Stop a single service without affecting others
docker compose -f docker/docker-compose.yml stop kamailio
docker compose -f docker/docker-compose.yml stop kamailio-mcp

# Stop all services (preserves data volumes)
make docker-stop
```

### 3. Running Standalone Docker Containers (`docker run`)

If you prefer running standalone containers without Docker Compose, use standard `docker run` commands with a shared bridge network:

```bash
# 1. Create a dedicated Docker network
docker network create kamailio-net

# 2. Run PostgreSQL 16 (with pre-seeded schema)
docker run -d \
  --name kamailio-postgres \
  --network kamailio-net \
  -p 5432:5432 \
  -e POSTGRES_USER=kamailio \
  -e POSTGRES_PASSWORD=kamailio \
  -e POSTGRES_DB=kamailio \
  -v $(pwd)/docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql \
  -v kamailio_pgdata:/var/lib/postgresql/data \
  postgres:16-alpine

# 3. Run Kamailio SIP Server
docker run -d \
  --name kamailio-node \
  --network kamailio-net \
  -p 5060:5060/udp \
  -p 5060:5060/tcp \
  -p 8081:8080 \
  -v $(pwd)/docker/kamailio/kamailio.cfg:/etc/kamailio/kamailio.cfg \
  kamailio/kamailio-ci:5.5.2-alpine \
  kamailio -DD -E -f /etc/kamailio/kamailio.cfg

# 4. Build and Run Kamailio MCP Server
docker build -t kamailio-mcp:latest -f docker/Dockerfile .

docker run -d \
  --name kamailio-mcp-server \
  --network kamailio-net \
  -p 8080:8080 \
  -e KAMAILIO_MCP_RPC_URL="http://kamailio-node:8080/jsonrpc" \
  -e KAMAILIO_MCP_DB_URL="postgresql+asyncpg://kamailio:kamailio@kamailio-postgres:5432/kamailio" \
  -e KAMAILIO_MCP_TRANSPORT="streamable-http" \
  -e KAMAILIO_MCP_HOST="0.0.0.0" \
  -e KAMAILIO_MCP_PORT="8080" \
  kamailio-mcp:latest
```

### 4. Hybrid & External Deployment Scenarios

#### Scenario A: Local Python MCP + Containerized Kamailio & PostgreSQL
Ideal for local development, hot reloading, and debugging MCP Python code directly on your host machine while Kamailio and PostgreSQL run inside Docker:

```bash
# 1. Start DB and Kamailio containers
make docker-up-kamailio

# 2. Run MCP server locally on host pointing to exposed host ports
export KAMAILIO_MCP_RPC_URL="http://127.0.0.1:8081/jsonrpc"
export KAMAILIO_MCP_DB_URL="postgresql+asyncpg://kamailio:kamailio@127.0.0.1:5432/kamailio"
kamailio-mcp serve --transport sse --host 127.0.0.1 --port 8080
```

#### Scenario B: Containerized MCP Server + Existing External Kamailio Server
If you already run a production Kamailio cluster or standalone instance on a remote server/VM, run only the MCP container and point it to the remote IP:

```bash
docker run -d \
  --name kamailio-mcp-server \
  -p 8080:8080 \
  -e KAMAILIO_MCP_RPC_URL="http://<REMOTE_KAMAILIO_IP>:8080/jsonrpc" \
  -e KAMAILIO_MCP_DB_URL="postgresql+asyncpg://kamailio:password@<REMOTE_DB_IP>:5432/kamailio" \
  -e KAMAILIO_MCP_API_KEY="your_secret_api_key" \
  -e KAMAILIO_MCP_TRANSPORT="streamable-http" \
  kamailio-mcp:latest
```

### Remote Access via Ngrok (No Public IP / Domain Required)

If your Kamailio server or MCP control plane is behind a local NAT, home router, or private cloud instance without a public IP or static domain, you can securely expose the MCP server using **ngrok**:

#### Step 1: Run Kamailio MCP in Network Mode (SSE or Streamable HTTP)

Start the server on `0.0.0.0:8080`:

```bash
# Via CLI
kamailio-mcp serve --transport sse --host 0.0.0.0 --port 8080

# Or via Docker Compose
docker compose -f docker/docker-compose.yml up -d
```

#### Step 2: Install and Configure Ngrok

```bash
# Install ngrok CLI (Debian/Ubuntu)
curl -sSL https://ngrok-agent.s3.amazonaws.com/ngrok.asc | sudo tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null
echo "deb https://ngrok-agent.s3.amazonaws.com buster main" | sudo tee /etc/apt/sources.list.d/ngrok.list
sudo apt-get update && sudo apt-get install ngrok

# Authenticate ngrok agent (sign up at https://dashboard.ngrok.com)
ngrok config add-authtoken YOUR_NGROK_AUTHTOKEN
```

#### Step 3: Start HTTP Tunnel to Port 8080

```bash
ngrok http 8080
```

`ngrok` will output a public HTTPS forwarding URL:
```text
Forwarding   https://a1b2c3d4.ngrok-free.app -> http://localhost:8080
```

#### Step 4: Connect Remote AI Clients or Web Apps

Point your remote MCP clients, web applications, or low-code portals to the ngrok URL:
- **SSE Endpoint**: `https://a1b2c3d4.ngrok-free.app/sse`
- **Streamable HTTP Endpoint**: `https://a1b2c3d4.ngrok-free.app/mcp`

> [!SECURITY TIP]
> When exposing your server publicly via ngrok, enforce API key authentication by setting `KAMAILIO_MCP_API_KEY=your_secret_key` and passing `Authorization: Bearer your_secret_key` in request headers.

---

## Architecture: Where to Run the MCP Server?

| Deployment Model | How it Works | Best Used For |
|---|---|---|
| **Same Server / Colocated** | `kamailio-mcp` runs directly on the same host/VM/container network as Kamailio and PostgreSQL. | CLI scripts, SSH terminal sessions, local development, maximum performance, and keeping ports `8080` & `5432` private. |
| **Local Workstation -> Remote Kamailio** | `kamailio-mcp` runs on your local machine (via Claude/Cursor/CLI `stdio`) and connects to remote Kamailio & PostgreSQL over VPN / private network. | Using desktop AI tools (Claude Desktop, Cursor, Continue) on your workstation while managing remote staging/production Kamailio instances. |

---

## MCP Client Integration

### 1. Claude Desktop (Recommended)

Claude Desktop runs MCP servers locally over `stdio` without needing OAuth or public network exposure.

Edit your configuration file:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "kamailio": {
      "command": "kamailio-mcp",
      "args": ["serve", "--transport", "stdio"],
      "env": {
        "KAMAILIO_MCP_RPC_URL": "http://127.0.0.1:8080/jsonrpc",
        "KAMAILIO_MCP_DB_URL": "postgresql+asyncpg://kamailio:kamailio@localhost:5432/kamailio"
      }
    }
  }
}
```

> [!NOTE]
> - **Local Python / Venv**: If using a virtual environment, specify the full path (e.g. `"/usr/share/kamalio-mcp-server/.venv/bin/kamailio-mcp"`).
> - **Zero-Install with Docker (`stdio`)**: You can also run the server directly inside a Docker container via `stdio` without installing Python on your host:
>   ```json
>   "kamailio": {
>     "command": "docker",
>     "args": [
>       "run", "-i", "--rm", "--network", "kamailio-net",
>       "-e", "KAMAILIO_MCP_RPC_URL=http://kamailio-node:8080/jsonrpc",
>       "-e", "KAMAILIO_MCP_DB_URL=postgresql+asyncpg://kamailio:kamailio@kamailio-postgres:5432/kamailio",
>       "kamailio-mcp:latest", "kamailio-mcp", "serve", "--transport", "stdio"
>     ]
>   }
>   ```

---

### 2. Claude.ai (Web Remote MCP) & OAuth Troubleshooting

> [!IMPORTANT]
> When adding a custom Remote MCP URL to **Claude.ai (Web)**, Claude’s cloud backend attempts **OAuth 2.0 Dynamic Client Registration (RFC 7591)**. If you see the error:
> ```text
> Couldn’t register with Kamalio MCP’s sign-in service. You can try again, or add an OAuth Client ID in the connector settings.
> ```
> **Why this happens**: `kamailio-mcp` is a lightweight FastMCP server and does not include an OAuth 2.0 identity provider out of the box.
>
> **Solution**: Use **Claude Desktop**, **Cursor**, or **CLI clients** via `stdio` (no OAuth required). If you must use Claude.ai Web, ensure the server is exposed via public HTTPS (e.g. `ngrok`), select **No Authentication / API Key** in Claude connector settings if supported, or place an OAuth2 proxy (e.g. Cloudflare Access, Auth0) in front of the `/sse` endpoint.

---

### 3. Cursor

Add to `.cursor/mcp.json` or `~/.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "kamailio": {
      "command": "kamailio-mcp",
      "args": ["serve", "--transport", "stdio"],
      "env": {
        "KAMAILIO_MCP_RPC_URL": "http://127.0.0.1:8080/jsonrpc",
        "KAMAILIO_MCP_DB_URL": "postgresql+asyncpg://kamailio:kamailio@localhost:5432/kamailio"
      }
    }
  }
}
```

---

### 4. Gemini CLI / Antigravity / Codex CLI

For CLI-based AI agents, register the MCP server in your agent configuration (e.g. `mcp_servers.json` or command flags):

```json
{
  "mcpServers": {
    "kamailio": {
      "command": "kamailio-mcp",
      "args": ["serve", "--transport", "stdio"],
      "env": {
        "KAMAILIO_MCP_RPC_URL": "http://127.0.0.1:8080/jsonrpc",
        "KAMAILIO_MCP_DB_URL": "postgresql+asyncpg://kamailio:kamailio@localhost:5432/kamailio"
      }
    }
  }
}
```

---

### 5. Cline (VS Code Extension)

In VS Code, open the Cline settings tab -> **MCP Servers** -> **Edit Settings (`cline_mcp_settings.json`)**:

```json
{
  "mcpServers": {
    "kamailio": {
      "command": "kamailio-mcp",
      "args": ["serve", "--transport", "stdio"],
      "env": {
        "KAMAILIO_MCP_RPC_URL": "http://127.0.0.1:8080/jsonrpc",
        "KAMAILIO_MCP_DB_URL": "postgresql+asyncpg://kamailio:kamailio@localhost:5432/kamailio"
      }
    }
  }
}
```

---

### 6. Continue (VS Code / JetBrains)

Add to `~/.continue/config.json`:

```json
{
  "experimental": {
    "modelContextProtocolServers": [
      {
        "transport": {
          "type": "stdio",
          "command": "kamailio-mcp",
          "args": ["serve", "--transport", "stdio"],
          "env": {
            "KAMAILIO_MCP_RPC_URL": "http://127.0.0.1:8080/jsonrpc",
            "KAMAILIO_MCP_DB_URL": "postgresql+asyncpg://kamailio:kamailio@localhost:5432/kamailio"
          }
        }
      }
    ]
  }
}
```

---

## Building Applications & Admin Portals Around Kamailio

`kamailio-mcp` provides structured schema exporters so external web apps (React, Vue, Next.js, Angular) can build dynamic UIs without hardcoding Kamailio parameters:

1. **Get JSONSchema for Dynamic UI Forms**:
   ```bash
   kamailio-mcp docs get-schema dispatcher
   ```
   *Returns full parameter types, defaults, and descriptions for the dispatcher module.*

2. **Parse Config AST for Visual Routing Diagrams**:
   ```bash
   kamailio-mcp cfg parse /etc/kamailio/kamailio.cfg
   ```
   *Returns JSON parse tree of loaded modules, modparams, and route logic blocks.*

3. **Programmatically Generate Scenarios**:
   ```bash
   kamailio-mcp cfg generate residential_pbx --param domain=sip.example.com --param db_driver=postgres
   ```

4. **Lint & Validate Config Snippets**:
   ```bash
   kamailio-mcp cfg lint /etc/kamailio/kamailio.cfg
   ```

---

## Makefile Quick Reference

Run `make` or `make help` in the project root to view all shortcut tasks:

| Command | Description |
|---|---|
| `make help` | Display colored help menu of available tasks |
| `make install` | Install package in editable mode with PostgreSQL and dev tools |
| `make test` | Execute full unit test suite with `pytest` |
| `make lint` | Run code quality checks with `ruff` |
| `make run-stdio` | Start MCP server in `stdio` mode (for Claude Desktop / Cursor) |
| `make run-sse` | Start MCP server in `sse` network mode listening on `0.0.0.0:8080` |
| `make docker-build` | Build Docker images for Kamailio, PostgreSQL, and MCP server |
| `make docker-up` | Launch full Docker Compose stack in background |
| `make docker-up-db` | Launch only PostgreSQL database container |
| `make docker-up-kamailio` | Launch only Kamailio (and its PostgreSQL dependency) |
| `make docker-up-mcp` | Launch only the `kamailio-mcp` server container |
| `make docker-rebuild` | Rebuild images and recreate containers with updated code/settings |
| `make docker-rebuild-mcp` | Rebuild image and recreate `kamailio-mcp` container after code changes |
| `make docker-rebuild-kamailio` | Recreate and restart Kamailio container with updated configuration |
| `make docker-rebuild-db` | Recreate and restart PostgreSQL database container |
| `make docker-restart` | Restart all running Docker Compose services |
| `make docker-restart-mcp` | Restart `kamailio-mcp` server container |
| `make docker-restart-kamailio` | Restart Kamailio container |
| `make docker-restart-db` | Restart PostgreSQL container |
| `make docker-logs-db` | Follow logs for PostgreSQL database container |
| `make docker-logs-kamailio` | Follow logs for Kamailio container |
| `make docker-logs-mcp` | Follow logs for `kamailio-mcp` server container |
| `make docker-stop` | Stop running Docker Compose containers (preserves volumes) |
| `make docker-down` | Tear down running Docker Compose stack and network |

---

## License

Apache-2.0 License.