SurrealDB MCP 服务器

SurrealDB MCP 服务器是一个标准化接口,使AI助手能够通过Model Context Protocol与SurrealDB数据库进行交互,支持执行复杂查询、CRUD操作、图形关系管理等核心功能。

  • by lfnovo
  • Python
  • 本地部署
  • 7 星标
  • 更新于
在 GitHub 查看 lfnovo/surreal-mcp

使用说明

SurealDB MCP服务器

模型上下文协议(MCP)服务器,使AI助手能够与SurrealDB数据库进行交互

=� 概述

SurrealDB MCP服务器弥合了人工智能助手和SurrealDB之间的差距,通过模型上下文协议为数据库操作提供了标准化的接口。这使LLM能够:

  • 执行复杂的SurrealQL查询
  • 对记录执行CRUD操作
  • 管理图形关系
  • 高效处理批量操作
  • 使用SurrealDB的独特功能,如记录ID和图边

特性

  • 完全支持SurrealQL:直接执行任何SurrealQL查询
  • 全面的CRUD操作:轻松创建、阅读、更新、删除
  • 图形数据库操作:创建和遍历记录之间的关系
  • 批量操作:高效的多记录插入
  • 智能更新:完整更新、合并和补丁
  • 类型安全:正确处理SurrealDB的记录ID
  • 连接池:高效的数据库连接管理
  • 多数据库支持:每次工具调用覆盖命名空间/数据库
  • 详细文件:用于人工智能理解的广泛文档字符串

=� 先决条件

  • Python 3.10或更高版本
  • SurrealDB实例(本地或远程)
  • MCP兼容客户端(克劳德桌面、MCP CLI等)

=� 安装

使用uvx(最简单-无需安装)

# Run directly from PyPI (once published)
uvx surreal-mcp

# Or run from GitHub
uvx --from git+https://github.com/yourusername/surreal-mcp.git surreal-mcp

使用紫外线(建议用于开发)

# Clone the repository
git clone https://github.com/yourusername/surreal-mcp.git
cd surreal-mcp

# Install dependencies
uv sync

# Run the server (multiple ways)
uv run surreal-mcp
# or
uv run python -m surreal_mcp
# or
uv run python main.py

使用pip

# Clone the repository
git clone https://github.com/yourusername/surreal-mcp.git
cd surreal-mcp

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install package
pip install -e .

# Run the server
surreal-mcp
# or
python -m surreal_mcp

� 配置

服务器使用环境变量进行配置。

必需变量(启动时)

变量 描述 示例
SURREAL_URL SurrealDB连接URL ws://localhost:8000/rpc
SURREAL_USER 数据库用户名 root
SURREAL_PASSWORD 数据库密码 root

可选变量(每次工具调用都可以覆盖)

变量 描述 示例
SURREAL_NAMESPACE 默认SurrealDB命名空间 test
SURREAL_DATABASE 默认SurrealDB数据库 test

备注:如果 SURREAL_NAMESPACE 和 SURREAL_DATABASE 未设置为环境变量,您必须提供 namespace 和 database 每个工具调用中的参数。

设置环境变量

您可以复制 .env.example 到 .env 并更新您的值:

cp .env.example .env
# Edit .env with your database credentials

或者手动设置它们:

export SURREAL_URL="ws://localhost:8000/rpc"
export SURREAL_USER="root"
export SURREAL_PASSWORD="root"
export SURREAL_NAMESPACE="test"
export SURREAL_DATABASE="test"

MCP客户端配置

添加到您的MCP客户端设置中(例如,Claude Desktop):

使用uvx(推荐):

{
  "mcpServers": {
    "surrealdb": {
      "command": "uvx",
      "args": ["surreal-mcp"],
      "env": {
        "SURREAL_URL": "ws://localhost:8000/rpc",
        "SURREAL_USER": "root",
        "SURREAL_PASSWORD": "root",
        "SURREAL_NAMESPACE": "test",
        "SURREAL_DATABASE": "test"
      }
    }
  }
}

使用本地安装:

{
  "mcpServers": {
    "surrealdb": {
      "command": "uv",
      "args": ["run", "surreal-mcp"],
      "env": {
        "SURREAL_URL": "ws://localhost:8000/rpc",
        "SURREAL_USER": "root",
        "SURREAL_PASSWORD": "root",
        "SURREAL_NAMESPACE": "test",
        "SURREAL_DATABASE": "test"
      }
    }
  }
}

='可用工具

所有工具支持可选 namespace 和 database 参数来覆盖环境变量的默认值。

1.查询

执行复杂操作的原始SurrealQL查询。

-- Example: Complex query with graph traversal
SELECT *, ->purchased->product FROM user WHERE age > 25
# Query with namespace/database override
query("SELECT * FROM user", namespace="production", database="main")

2.选择

按ID从表或特定记录中检索所有记录。

# Get all users
select("user")

# Get specific user
select("user", "john")

# Select from a different database
select("user", namespace="other_ns", database="other_db")

3.创建

使用自动生成的ID创建新记录。

create("user", {
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30
})

4.更新

替换整个记录内容(保留ID和时间戳)。

update("user:john", {
    "name": "John Smith",
    "email": "john.smith@example.com",
    "age": 31
})

5.删除

从数据库中永久删除记录。

delete("user:john")

6.合并

在不影响其他字段的情况下部分更新特定字段。

merge("user:john", {
    "email": "newemail@example.com",
    "verified": True
})

7.补丁

将JSON补丁操作(RFC 6902)应用于记录。

patch("user:john", [
    {"op": "replace", "path": "/email", "value": "new@example.com"},
    {"op": "add", "path": "/verified", "value": True}
])

8.扰乱市场

创建或更新具有特定ID的记录。

upsert("settings:global", {
    "theme": "dark",
    "language": "en"
})

9.插入

高效地批量插入多条记录。

insert("product", [
    {"name": "Laptop", "price": 999.99},
    {"name": "Mouse", "price": 29.99},
    {"name": "Keyboard", "price": 79.99}
])

10.相关

在记录之间创建图形关系。

relate(
    "user:john",           # from
    "purchased",           # relation name
    "product:laptop-123",  # to
    {"quantity": 1, "date": "2024-01-15"}  # relation data
)

=� 例子

基本CRUD操作

# Create a user
user = create("user", {"name": "Alice", "email": "alice@example.com"})

# Update specific fields
merge(user["id"], {"verified": True, "last_login": "2024-01-01"})

# Query with conditions
results = query("SELECT * FROM user WHERE verified = true ORDER BY created DESC")

# Delete when done
delete(user["id"])

处理关系

# Create entities
user = create("user", {"name": "John"})
product = create("product", {"name": "Laptop", "price": 999})

# Create relationship
relate(user["id"], "purchased", product["id"], {
    "quantity": 1,
    "total": 999,
    "date": "2024-01-15"
})

# Query relationships
purchases = query(f"SELECT * FROM {user['id']}->purchased->product")

批量操作

# Insert multiple records
products = insert("product", [
    {"name": "Laptop", "category": "Electronics", "price": 999},
    {"name": "Mouse", "category": "Electronics", "price": 29},
    {"name": "Desk", "category": "Furniture", "price": 299}
])

# Bulk update with query
query("UPDATE product SET on_sale = true WHERE category = 'Electronics'")

<<<<<<<头

<� 建筑

=======

多数据库操作

通过使用 namespace 和 database 参数:

# Create a record in the production database
create("user", {"name": "Alice"}, namespace="prod", database="main")

# Query from staging database
select("user", namespace="staging", database="main")

# Copy data between databases
users = select("user", namespace="staging", database="main")
for user in users["data"]:
    create("user", user, namespace="prod", database="main")

行为总结:

场景 结果
Env vars set, no params Uses pooled connection (best performance)
Env vars set, params provided Uses override connection with specified namespace/database
No env vars, params provided Uses override connection with specified namespace/database
No env vars, no params Fails with clear error message

<� Architecture

main

The server is built with:

  • FastMCP: Simplified MCP server implementation
  • SurrealDB Python SDK: Official database client
  • Connection Pooling: Efficient connection management
  • Async/Await: Non-blocking database operations

>� Testing

The project includes a comprehensive test suite using pytest.

Prerequisites

  • SurrealDB instance running locally
  • Test database access (uses temporary test databases)

Running Tests

# Make sure SurrealDB is running
surreal start --user root --pass root

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=surreal_mcp

# Run specific test file
uv run pytest tests/test_tools.py

# Run specific test class or method
uv run pytest tests/test_tools.py::TestQueryTool
uv run pytest tests/test_tools.py::TestQueryTool::test_query_simple

# Run with verbose output
uv run pytest -v

# Run only tests matching a pattern
uv run pytest -k "test_create"

Test Structure

tests/
├── __init__.py
├── conftest.py              # Fixtures and test configuration
├── test_tools.py            # Tests for all MCP tools
├── test_server.py           # Tests for server configuration
└── test_namespace_override.py  # Tests for namespace/database override

Writing Tests

The test suite includes fixtures for common test data:

  • clean_db - Ensures clean database state
  • sample_user_data - Sample user data
  • created_user - Pre-created user record
  • created_product - Pre-created product record

Example test:

@pytest.mark.asyncio
async def test_create_user(clean_db, sample_user_data):
    result = await mcp._tools["create"].func(
        table="user",
        data=sample_user_data
    )
    assert result["success"] is True
    assert result["data"]["email"] == sample_user_data["email"]

> Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. 提交您的更改(git commit -m 'Add some AmazingFeature')
  4. 推到分支(git push origin feature/AmazingFeature)
  5. 打开拉取请求

=� 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

=O致谢

=� 支持


Made with d for the SurrealDB and MCP communities