Skip to main content
Glama

LiveKit MCP Server

Python uv MCP Code style: ruff Tests

一个高性能的 Model Context Protocol(MCP 2.0)服务器,将 AI 代理与 MantraCare LiveKit 语音与电话引擎桥接起来。

架构 • 快速开始 • 配置 • 连接客户端 • 认证 • 工具 • 开发


📖 概述

LiveKit MCP Server 允许 LLM 和 AI 编码助手(如 Antigravity、Claude、Cursor 以及自定义代理)安全地控制、检查和触发由 LiveKit(~/lkt)驱动并通过 Mantra Auth(~/mantra-auth)进行身份验证的语音电话流水线。

核心能力

  • 🚀 符合 MCP 2.0:基于官方 Python mcp SDK,使用 Server-Sent Events (SSE) 和 Streamable HTTP 传输。

  • 🔐 OAuth 2.1 与共享 JWT 安全:原生 HS256 JWT 验证,与 mantra-auth 一致,支持 Authorization: Bearer 头和 ?token= 查询参数。

  • ⚡ 极速异步核心:由 Starlette、Uvicorn 和 uv 包管理驱动。

  • 🧩 模块化工具架构:为电话、通话分析、知识库搜索和 SIP 中继提供按领域划分的工具。

  • 🧠 代理记忆:完整的 Obsidian 知识库(obsidian/)和 AGENTS.md 规则,用于保留 AI 结对编程上下文。


Related MCP server: Agent Identity MCP Server

🏛️ 系统架构

┌─────────────────────────────────────────────────────────────┐
│ AI Client (Cursor / Claude / Antigravity / Web Agent)       │
└──────────────────────────────┬──────────────────────────────┘
                               │ 1. Bearer Token / ?token= (OAuth 2.1)
                               ▼
┌─────────────────────────────────────────────────────────────┐
│ [3. mantra-auth (:3000)]                                    │
│ Next.js + Prisma OAuth 2.1 Authorization Server             │
│ - Issues HS256 JWTs and verifies via /api/oauth/introspect  │
└──────────────────────────────┬──────────────────────────────┘
                               │ Shared JWT Secret Verification
                               ▼
┌─────────────────────────────────────────────────────────────┐
│ [2. livekit-mcp (:8000)] (This Server)                      │
│ - Starlette ASGI + MCP 2.0 SSE Transport                    │
│ - Pure ASGI Auth Middleware (HS256 JWT validation)          │
│ - Public Endpoints: /health, /                              │
│ - Protected Endpoints: /sse, /messages                      │
│ - Registered Tools: greet_user, [Telephony/KB/SIP coming]   │
└──────────────────────────────┬──────────────────────────────┘
                               │ 2. Async HTTP (REST)
                               ▼
┌─────────────────────────────────────────────────────────────┐
│ [1. lkt (:8081)]                                            │
│ MantraCare LiveKit Voice Agent & Telephony Engine           │
│ - SIP Trunks (Plivo, Zadarma, VoiceLink, Twilio)            │
│ - LiveKit Cloud WebRTC Rooms & STT→LLM→TTS Voice Pipeline   │
│ - PostgreSQL (call_logs, kb_pages) & Redis (queues, locks)  │
└─────────────────────────────────────────────────────────────┘

📁 仓库结构

livekit-mcp/
├── .env.example                # Sample environment variables
├── .gitignore                  # Git ignore definitions
├── .python-version             # Python version pin (3.11)
├── AGENTS.md                   # Agent Memory instructions
├── dev.sh                      # Development startup script
├── pyproject.toml              # UV package specification & build settings
├── uv.lock                     # Deterministic lockfile
├── README.md                   # Project documentation
│
├── obsidian/                   # Permanent Agentic Knowledge Base
│   ├── Home.md                 # Project navigation hub
│   ├── Architecture/           # System design, data flow, security & APIs
│   ├── Context/                # Stack, project summary & repository map
│   ├── Development/            # Sprint tracking, TODO & Changelog
│   ├── Features/               # Feature specifications (tools, auth)
│   └── Knowledge/              # Coding standards & architectural conventions
│
├── src/
│   └── livekit_mcp/
│       ├── __init__.py
│       ├── config.py           # Pydantic Settings & environment validation
│       ├── server.py           # MCPServer & Starlette app factory
│       ├── main.py             # CLI runner with Uvicorn
│       ├── auth/
│       │   ├── __init__.py
│       │   ├── jwt.py          # HS256 JWT decoding & claims validation
│       │   └── middleware.py   # Pure ASGI auth middleware (headers & ?token=)
│       ├── clients/
│       │   ├── __init__.py
│       │   ├── lkt_client.py   # Async HTTP client for lkt FastAPI (:8081)
│       │   └── auth_client.py  # Async HTTP client for mantra-auth (:3000)
│       └── tools/
│           ├── __init__.py
│           └── greeting.py     # Initial `greet_user` verification tool
│
└── tests/
    ├── __init__.py
    ├── conftest.py             # Fixtures for tokens, settings & test client
    ├── test_config.py          # Configuration unit tests
    ├── test_auth.py            # JWT verification & claims unit tests
    ├── test_greeting.py        # Tool registration & execution tests
    └── test_server.py          # Endpoints, SSE & Auth integration tests

🚀 快速开始

1. 前提条件

  • Python:3.11 或更高版本

  • uv:快速 Python 包管理器(安装 uv)

    curl -LsSf https://astral.sh/uv/install.sh | sh

2. 安装与设置

  1. 克隆仓库并进入目录:

    cd ~/livekit-mcp
  2. 创建你的环境配置:

    cp .env.example .env
  3. 使用 uv 安装依赖:

    uv sync

3. 运行服务器

启动带自动重载的开发服务器:

./dev.sh

或者直接使用 uv 运行:

uv run python -m livekit_mcp.main

服务器将在 http://localhost:8000 上可用。


⚙️ 配置

所有设置都在 src/livekit_mcp/config.py 中通过 pydantic-settings 管理,并从 .env 加载:

变量

类型

默认值

描述

HOST

string

0.0.0.0

服务器绑定地址

PORT

integer

8000

服务器监听端口

ENVIRONMENT

string

development

development、test 或 production

LOG_LEVEL

string

INFO

日志级别(DEBUG、INFO、WARNING、ERROR)

AUTH_ENABLED

boolean

true

对受保护端点强制执行 JWT 认证

JWT_SECRET

string

your-super-secret-...

用于 HS256 JWT 签名验证的共享密钥

JWT_ALGORITHM

string

HS256

JWT 签名算法(与 mantra-auth 一致)

AUTH_SERVER_URL

string

http://localhost:3000

Mantra Auth 服务器的基础 URL

JWT_ISSUER

string

http://localhost:3000

预期的 JWT 签发者声明(iss)

JWT_AUDIENCE

string

(空)

可选的预期受众声明(aud)

LKT_API_BASE_URL

string

http://localhost:8081

LKT Voice Agent API 的基础 URL

LKT_API_TIMEOUT

float

15.0

LKT 调用的 HTTP 请求超时时间(秒)

LIVEKIT_URL

string

(空)

直接连接 LiveKit Cloud 的 WebSocket URL(可选)

LIVEKIT_API_KEY

string

(空)

直接连接 LiveKit Cloud 的 API 密钥(可选)

LIVEKIT_API_SECRET

string

(空)

直接连接 LiveKit Cloud 的 API 密钥(Secret)(可选)


📡 端点

端点

方法

需要认证

描述

/health

GET

❌ 否

公开的健康与就绪检查,返回服务状态

/

GET

❌ 否

服务状态和端点元数据

/sse

GET

✅ 是

为 MCP 客户端打开一个持久的 Server-Sent Events (SSE) 流

/messages

POST

✅ 是

用于 MCP 请求的 JSON-RPC 2.0 端点(工具执行、列表)

健康检查示例

curl http://localhost:8000/health
{
  "status": "healthy",
  "service": "livekit-mcp",
  "version": "0.1.0",
  "auth_enabled": true,
  "environment": "development",
  "lkt_api_configured": true,
  "timestamp": "2026-08-20T12:30:00.000000+00:00"
}

🔐 认证

服务器实现了与 mantra-auth 兼容的 OAuth 2.1 / HS256 共享 JWT 认证。

提供凭据

  1. Authorization 头部(标准):

    GET /sse HTTP/1.1
    Host: localhost:8000
    Authorization: Bearer <your-jwt-access-token>
  2. 查询参数(适用于 SSE / EventSource 客户端):

    GET /sse?token=<your-jwt-access-token> HTTP/1.1
    Host: localhost:8000

预期的 JWT 声明

{
  "sub": "user-123",
  "aud": "client-app",
  "iss": "http://localhost:3000",
  "exp": 1755694800,
  "iat": 1755691200,
  "scope": "openid profile telephony:call",
  "token_type": "access_token"
}

开发提示:在 .env 中设置 AUTH_ENABLED=false,可在本地测试期间禁用令牌验证。


🛠️ 可用工具

1. greet_user

一个验证工具,用于确认 MCP 连接、参数解析和服务器状态。

  • 参数:

    • name(字符串,必填):调用该工具的用户或代理的名称。

    • message(字符串,可选):自定义问候消息。

  • 返回:

    👋 Hello, Alice!
    
    Welcome to MantraCare LiveKit MCP!
    
    --- System Status ---
    • Service: LiveKit MCP Server
    • Status: Operational & Ready
    • Timestamp: 2026-08-20T12:30:00.000000+00:00
    • Protocol: MCP 2.0 (SSE / HTTP)

🔌 连接 MCP 客户端

1. Antigravity / Gemini CLI(~/.gemini/config/mcp_config.json)

{
  "mcpServers": {
    "livekit": {
      "serverUrl": "http://localhost:8000/sse"
    }
  }
}

2. Cursor IDE(.cursor/mcp.json)

{
  "mcpServers": {
    "livekit": {
      "url": "http://localhost:8000/sse",
      "headers": {
        "Authorization": "Bearer <YOUR_JWT_TOKEN>"
      }
    }
  }
}

3. Claude Desktop(claude_desktop_config.json)

{
  "mcpServers": {
    "livekit": {
      "command": "uv",
      "args": [
        "--directory",
        "/home/fardeen/livekit-mcp",
        "run",
        "python",
        "-m",
        "livekit_mcp.main"
      ],
      "env": {
        "AUTH_ENABLED": "false"
      }
    }
  }
}

🧪 开发与测试

运行测试

项目包含一套全面的测试套件,覆盖配置、JWT 验证、中间件和工具:

uv run pytest -v

代码格式化与静态检查

使用 ruff 执行整洁的编码规范:

# Check code
uv run ruff check .

# Auto-fix issues & format
uv run ruff check --fix .
uv run ruff format .

添加新工具

要向 livekit-mcp 添加新工具:

  1. 在 src/livekit_mcp/tools/<domain>.py 中创建一个模块。

  2. 定义一个注册函数:

    from mcp.server.mcpserver import MCPServer
    
    def register_telephony_tools(server: MCPServer) -> None:
        @server.tool(name="trigger_call", description="Trigger an outbound call")
        async def trigger_call(phone_number: str, prompt: str) -> str:
            # Call LktClient here
            return f"Call initiated to {phone_number}"
  3. 在 src/livekit_mcp/server.py 中的 create_mcp_server() 内注册该函数。

  4. 在 tests/test_<domain>.py 中添加单元测试。


📚 代理记忆

本仓库遵循 Agentic Memory 模式。在进行架构更改之前,请查看 obsidian/ 中的 Obsidian 知识库:

  • obsidian/Home.md — 项目导航中心

  • obsidian/Architecture/Overview.md — 系统设计与拓扑

  • obsidian/Development/Current Sprint.md — 当前开发状态

  • obsidian/Development/TODO.md — 即将推出的路线图

  • obsidian/Knowledge/Coding Standards.md — 代码约定


📄 许可证

专有软件 © MantraCare。保留所有权利。

Related MCP Connectors

Related MCP Servers