
Byted Bytehouse Mcp
- 2 installs
- 408 repo stars
- Updated August 3, 2026
- volcengine/agentkit-samples
Starts a local ByteHouse MCP server and calls its tools to query the ByteHouse database, list tables, and build data-asset and lineage reports.
About
Launches the ByteHouse MCP server locally and calls its tools to query the ByteHouse cloud data warehouse over MCP. A developer uses it to connect to ByteHouse, inspect tables, and generate data-asset catalogs and lineage analysis.
- Bundles a Python MCP client plus start/stop/status/restart scripts for a resident ByteHouse MCP server
- Includes data-asset and lineage analyzer and top-10 large-table query helpers
Byted Bytehouse Mcp by the numbers
- 2 all-time installs (skills.sh)
- Ranked #741 of 911 Databases skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/volcengine/agentkit-samples --skill byted-bytehouse-mcpAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 408 |
| Last updated | August 3, 2026 |
| Repository | volcengine/agentkit-samples ↗ |
What it does
Starts a local ByteHouse MCP server and calls its tools to query the ByteHouse database, list tables, and build data-asset and lineage reports.
Files
ByteHouse MCP Server Skill
🔵 ByteHouse 品牌标识
「ByteHouse」—— 火山引擎云原生数据仓库,极速、稳定、安全、易用
>
本Skill基于ByteHouse官方MCP Server,提供完整的ByteHouse数据访问能力
---
描述
在本地拉起ByteHouse MCP Server并调用其tools的技能。
当以下情况时使用此 Skill: (1) 需要连接ByteHouse数据库查询数据 (2) 需要使用MCP协议与ByteHouse交互 (3) 用户提到"ByteHouse"、"MCP"、"查询数据库"、"看表" (4) 需要生成数据资产目录和血缘分析
📁 文件说明
- SKILL.md - 本文件,技能主文档
- mcp_client.py - MCP客户端模块,用于程序化调用MCP Server
- test_mcp_server.py - MCP Server测试脚本
- example_mcp_usage.py - MCP使用示例
- query_top10_tables_mcp.py - 使用MCP查询Top 10大表
- test_list_tables.py - 测试list_tables tool
- data_asset_analyzer.py - 数据资产和血缘分析工具(新增)
- start_mcp_service.sh - 启动常驻MCP Server服务
- stop_mcp_service.sh - 停止MCP Server服务
- status_mcp_service.sh - 查看MCP Server状态
- restart_mcp_service.sh - 重启MCP Server服务
前置条件
- Python 3.8+
- uv (已安装在
/root/.local/bin/uv) - ByteHouse连接信息(需自行配置)
配置信息
ByteHouse连接配置
{
"host": "<ByteHouse-host>",
"port": "<ByteHouse-port>",
"user": "<ByteHouse-user>",
"password": "<ByteHouse-password>",
"secure": true,
"verify": true
}环境变量
在使用前请设置以下环境变量:
export BYTEHOUSE_HOST="<ByteHouse-host>"
export BYTEHOUSE_PORT="<ByteHouse-port>"
export BYTEHOUSE_USER="<ByteHouse-user>"
export BYTEHOUSE_PASSWORD="<ByteHouse-password>"
export BYTEHOUSE_SECURE="true"
export BYTEHOUSE_VERIFY="true"
export BYTEHOUSE_CONNECT_TIMEOUT="30"
export BYTEHOUSE_SEND_RECEIVE_TIMEOUT="30"🎯 ByteHouse MCP Server Tools
| 序号 | Tool名称 | 功能描述 |
|---|---|---|
| 1 | list_databases | 列出所有数据库 |
| 2 | list_tables | 列出指定数据库中的所有表 |
| 3 | run_select_query | 运行SELECT查询 |
| 4 | run_dml_ddl_query | 运行DML/DDL查询 |
| 5 | get_bytehouse_table_engine_doc | 获取ByteHouse表引擎文档 |
🚀 快速开始
方法1: 测试MCP Server(推荐先测试)
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run test_mcp_server.py这会: 1. 自动安装ByteHouse MCP Server 2. 启动MCP Server 3. 列出所有可用的tools 4. 尝试调用第一个tool
方法2: 列出数据库中的表
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run test_list_tables.py方法3: 使用MCP查询Top 10大表
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run query_top10_tables_mcp.py方法4: 生成数据资产和血缘分析(新增)
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run data_asset_analyzer.py这会: 1. 获取数据库的完整schema 2. 生成数据资产目录 3. 生成血缘分析报告 4. 保存JSON文件到 output/ 目录
输出内容包括:
- 数据库schema(所有表和字段)
- 数据资产目录(表统计、标签、引擎分布)
- 血缘分析(表关系、列相似性)
方法5: 启动常驻MCP Server服务
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先在脚本中配置环境变量,然后运行
./start_mcp_service.sh这会: 1. 在后台启动MCP Server 2. 保存PID到 mcp_server.pid 3. 写入日志到 logs/mcp_server_*.log
方法6: 查看MCP Server状态
./status_mcp_service.sh方法7: 停止MCP Server
./stop_mcp_service.sh方法8: 重启MCP Server
./restart_mcp_service.sh💻 数据资产和血缘分析(新增)
功能说明
data_asset_analyzer.py 提供以下功能:
1. 完整Schema获取
- 获取指定数据库的所有表
- 获取每张表的所有字段
- 提取表引擎、注释等元数据
2. 数据资产目录生成
- 表统计(总表数、总列数)
- 引擎分布统计
- 自动标签生成
- 表资产详情
3. 血缘分析
- 表关系识别(Distributed → Local)
- 列相似性分析
- 关系可视化
使用示例
#!/usr/bin/env python3
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
from data_asset_analyzer import DataAssetAnalyzer
async def main():
analyzer = DataAssetAnalyzer()
await analyzer.connect()
# 分析数据库
result = await analyzer.analyze_database("default")
# result 包含:
# - schema: 完整的数据库schema
# - catalog: 数据资产目录
# - lineage: 血缘分析
# - files: 生成的文件路径
asyncio.run(main())输出文件
分析完成后会在 output/ 目录生成以下文件:
1. schema_{database}_{timestamp}.json - 完整的数据库schema 2. catalog_{database}_{timestamp}.json - 数据资产目录 3. lineage_{database}_{timestamp}.json - 血缘分析报告
💻 程序化使用MCP Client
使用mcp_client.py模块
#!/usr/bin/env python3
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
from mcp_client import ByteHouseMCPClient
async def main():
async with ByteHouseMCPClient() as client:
await client.connect()
# 1. 列出所有tools
tools = await client.list_tools()
print("可用的tools:", [t['name'] for t in tools])
# 2. 调用tool
# result = await client.call_tool("tool_name", {"param": "value"})
# print(result)
asyncio.run(main())直接使用MCP SDK
#!/usr/bin/env python3
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# 设置环境变量(请自行配置)
env = os.environ.copy()
env.update({
'BYTEHOUSE_HOST': '<ByteHouse-host>',
'BYTEHOUSE_PORT': '<ByteHouse-port>',
'BYTEHOUSE_USER': '<ByteHouse-user>',
'BYTEHOUSE_PASSWORD': '<ByteHouse-password>',
'BYTEHOUSE_SECURE': 'true',
'BYTEHOUSE_VERIFY': 'true',
})
# MCP Server参数
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
# 启动MCP Server并连接
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 列出tools
result = await session.list_tools()
print("Tools:", [t.name for t in result.tools])
# 调用tool
# call_result = await session.call_tool("tool_name", {"param": "value"})
asyncio.run(main())🔧 服务管理
启动服务
# 先配置环境变量,然后运行
./start_mcp_service.sh查看状态
./status_mcp_service.sh查看日志
# 查看最新日志
tail -f logs/mcp_server_*.log
# 查看特定日志文件
tail -f logs/mcp_server_20260312_184500.log停止服务
./stop_mcp_service.sh重启服务
./restart_mcp_service.sh💻 使用MCP Tools示例
示例1: 列出所有数据库
import asyncio
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# 设置环境变量(请自行配置)
env = os.environ.copy()
env.update({
'BYTEHOUSE_HOST': '<ByteHouse-host>',
'BYTEHOUSE_PORT': '<ByteHouse-port>',
'BYTEHOUSE_USER': '<ByteHouse-user>',
'BYTEHOUSE_PASSWORD': '<ByteHouse-password>',
'BYTEHOUSE_SECURE': 'true',
'BYTEHOUSE_VERIFY': 'true',
})
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 调用list_databases
result = await session.call_tool("list_databases", {})
for content in result.content:
if content.type == 'text':
print(content.text)
asyncio.run(main())示例2: 列出数据库中的表
# 调用list_tables
result = await session.call_tool("list_tables", {"database": "default"})示例3: 运行SELECT查询
# 调用run_select_query
sql = "SELECT * FROM default.conversation_feedback LIMIT 10"
result = await session.call_tool("run_select_query", {"query": sql})示例4: 查询Top 10大表
# 查询Top 10大表
sql = """
SELECT
database,
table,
sum(bytes) as total_bytes,
sum(rows) as total_rows
FROM system.parts
WHERE active = 1
GROUP BY database, table
ORDER BY total_bytes DESC
LIMIT 10
"""
result = await session.call_tool("run_select_query", {"query": sql})--- 最后更新: 2026-03-12
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.ByteHouse MCP Server Skill
🔵 ByteHouse 品牌标识
「ByteHouse」—— 火山引擎云原生数据仓库,极速、稳定、安全、易用
>
本Skill基于ByteHouse官方MCP Server,提供完整的ByteHouse数据访问能力
---
📁 文件说明
- SKILL.md - 技能主文档,包含详细使用说明
- mcp_client.py - MCP客户端模块,用于程序化调用
- test_mcp_server.py - MCP Server测试脚本
- example_mcp_usage.py - MCP使用示例
- query_top10_tables_mcp.py - 使用MCP查询Top 10大表
- test_list_tables.py - 测试list_tables tool
- data_asset_analyzer.py - 数据资产和血缘分析工具(新增)
- start_mcp_service.sh - 启动常驻MCP Server服务
- stop_mcp_service.sh - 停止服务
- status_mcp_service.sh - 查看状态
- restart_mcp_service.sh - 重启服务
- README.md - 本文件,快速入门指南
🎯 ByteHouse MCP Server Tools
| 序号 | Tool名称 | 功能描述 |
|---|---|---|
| 1 | list_databases | 列出所有数据库 |
| 2 | list_tables | 列出指定数据库中的所有表 |
| 3 | run_select_query | 运行SELECT查询 |
| 4 | run_dml_ddl_query | 运行DML/DDL查询 |
| 5 | get_bytehouse_table_engine_doc | 获取ByteHouse表引擎文档 |
🚀 快速开始
前置配置
在使用前,请先配置ByteHouse连接信息:
export BYTEHOUSE_HOST="<ByteHouse-host>"
export BYTEHOUSE_PORT="<ByteHouse-port>"
export BYTEHOUSE_USER="<ByteHouse-user>"
export BYTEHOUSE_PASSWORD="<ByteHouse-password>"
export BYTEHOUSE_SECURE="true"
export BYTEHOUSE_VERIFY="true"方法1: 测试MCP Server(推荐先测试)
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run test_mcp_server.py方法2: 列出数据库中的表
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run test_list_tables.py方法3: 使用MCP查询Top 10大表
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run query_top10_tables_mcp.py方法4: 生成数据资产和血缘分析(新增)
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先设置环境变量,然后运行
uv run data_asset_analyzer.py功能说明:
- 获取数据库完整schema(所有表和字段)
- 生成数据资产目录(表统计、引擎分布、自动标签)
- 生成血缘分析(表关系、列相似性)
- 保存JSON文件到
output/目录
输出文件:
schema_{database}_{timestamp}.json- 完整schemacatalog_{database}_{timestamp}.json- 数据资产目录lineage_{database}_{timestamp}.json- 血缘分析
方法5: 启动常驻MCP Server服务
cd /root/.openclaw/workspace/skills/bytehouse-mcp
# 先在脚本中配置环境变量,然后运行
./start_mcp_service.sh方法6: 查看服务状态
./status_mcp_service.sh方法7: 查看日志
tail -f logs/mcp_server_*.log方法8: 停止服务
./stop_mcp_service.sh💻 使用MCP Tools示例
示例1: 列出所有数据库
import asyncio
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# 设置环境变量(请自行配置)
env = os.environ.copy()
env.update({
'BYTEHOUSE_HOST': '<ByteHouse-host>',
'BYTEHOUSE_PORT': '<ByteHouse-port>',
'BYTEHOUSE_USER': '<ByteHouse-user>',
'BYTEHOUSE_PASSWORD': '<ByteHouse-password>',
'BYTEHOUSE_SECURE': 'true',
'BYTEHOUSE_VERIFY': 'true',
})
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 调用list_databases
result = await session.call_tool("list_databases", {})
for content in result.content:
if content.type == 'text':
print(content.text)
asyncio.run(main())示例2: 列出数据库中的表
# 调用list_tables
result = await session.call_tool("list_tables", {"database": "default"})示例3: 运行SELECT查询
# 调用run_select_query
sql = "SELECT * FROM default.conversation_feedback LIMIT 10"
result = await session.call_tool("run_select_query", {"query": sql})示例4: 查询Top 10大表
# 查询Top 10大表
sql = """
SELECT
database,
table,
sum(bytes) as total_bytes,
sum(rows) as total_rows
FROM system.parts
WHERE active = 1
GROUP BY database, table
ORDER BY total_bytes DESC
LIMIT 10
"""
result = await session.call_tool("run_select_query", {"query": sql})🔧 服务管理
启动服务
# 先配置环境变量,然后运行
./start_mcp_service.sh查看状态
./status_mcp_service.sh停止服务
./stop_mcp_service.sh重启服务
./restart_mcp_service.sh📚 更多信息
详细使用说明请参考 SKILL.md
--- 最后更新: 2026-03-12
#!/usr/bin/env python3
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ByteHouse MCP Server 使用示例
演示如何调用MCP Server的tools
"""
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import sys
import os
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from mcp_client import ByteHouseMCPClient
async def example_list_tools():
"""示例1: 列出所有可用的tools"""
print("=" * 80)
print("示例1: 列出所有可用的tools")
print("=" * 80)
async with ByteHouseMCPClient() as client:
await client.connect()
tools = await client.list_tools()
print(f"\n找到 {len(tools)} 个tools:\n")
for i, tool in enumerate(tools, 1):
print(f"{i}. {tool['name']}")
print(f" 描述: {tool['description']}")
print(f" 参数: {tool['inputSchema']}")
print()
async def example_query_databases():
"""示例2: 查询所有数据库"""
print("=" * 80)
print("示例2: 查询所有数据库")
print("=" * 80)
async with ByteHouseMCPClient() as client:
await client.connect()
# 注意:这里需要根据实际的tool名称来调用
# 先列出tools看看有什么可用的
tools = await client.list_tools()
print("\n可用的tools:")
for tool in tools:
print(f" - {tool['name']}")
# 这里需要根据实际的tool名称和参数来调用
# 由于不同的MCP Server提供的tools可能不同,这里先列出可用的tools
async def main():
"""主函数"""
print("\n" + "=" * 80)
print("ByteHouse MCP Server 使用示例")
print("=" * 80)
print()
print("⚠️ 请确保已设置以下环境变量:")
print(" - BYTEHOUSE_HOST")
print(" - BYTEHOUSE_PORT")
print(" - BYTEHOUSE_USER")
print(" - BYTEHOUSE_PASSWORD")
print()
try:
# 示例1: 列出所有tools
await example_list_tools()
# 示例2: 查询数据库
# await example_query_databases()
except Exception as e:
print(f"\n❌ 错误: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))
#!/usr/bin/env python3
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
MCP Client - 用于与MCP Server通信的客户端
"""
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import json
import sys
import os
from typing import Any, Dict, List, Optional
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
class ByteHouseMCPClient:
"""ByteHouse MCP客户端"""
def __init__(self):
self.session: Optional[ClientSession] = None
self._exit_stack = AsyncExitStack()
self.server_params = None
async def __aenter__(self):
await self._exit_stack.__aenter__()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
async def connect(self):
"""连接到ByteHouse MCP Server"""
# 从环境变量获取配置
env = os.environ.copy()
# MCP Server参数
self.server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
print("🔌 正在连接到ByteHouse MCP Server...")
# 启动stdio客户端
stdio_transport = await self._exit_stack.enter_async_context(
stdio_client(self.server_params)
)
# 创建会话
self.session = await self._exit_stack.enter_async_context(
ClientSession(stdio_transport[0], stdio_transport[1])
)
# 初始化会话
await self.session.initialize()
print("✅ 连接成功!")
return self
async def list_tools(self) -> List[Dict]:
"""列出所有可用的tools"""
if not self.session:
raise RuntimeError("Not connected")
result = await self.session.list_tools()
tools = []
for tool in result.tools:
tools.append({
'name': tool.name,
'description': tool.description,
'inputSchema': tool.inputSchema
})
return tools
async def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
"""调用tool"""
if not self.session:
raise RuntimeError("Not connected")
result = await self.session.call_tool(tool_name, arguments)
# 处理结果
outputs = []
for content in result.content:
if content.type == 'text':
outputs.append(content.text)
elif content.type == 'image':
outputs.append(f"[Image: {content.data[:50]}...]")
return outputs
# 便捷函数
async def run_mcp_tool(tool_name: str, arguments: Dict[str, Any] = None):
"""运行单个MCP tool"""
if arguments is None:
arguments = {}
async with ByteHouseMCPClient() as client:
await client.connect()
# 先列出tools
print("\n📋 可用的Tools:")
tools = await client.list_tools()
for tool in tools:
print(f" - {tool['name']}: {tool['description']}")
print(f"\n🚀 调用Tool: {tool_name}")
print(f" 参数: {json.dumps(arguments, ensure_ascii=False)}")
# 调用tool
result = await client.call_tool(tool_name, arguments)
print("\n📊 结果:")
for output in result:
print(output)
return result
if __name__ == "__main__":
# 测试:列出所有tools
async def main():
async with ByteHouseMCPClient() as client:
await client.connect()
print("\n📋 可用的Tools:")
tools = await client.list_tools()
for tool in tools:
print(f"\n {tool['name']}")
print(f" 描述: {tool['description']}")
print(f" 参数: {json.dumps(tool['inputSchema'], ensure_ascii=False, indent=6)}")
asyncio.run(main())
#!/usr/bin/env python3
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
使用MCP Server查询ByteHouse Top 10大表
"""
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def query_top10_tables():
"""使用MCP查询Top 10大表"""
print("=" * 80)
print("使用MCP Server查询ByteHouse Top 10大表")
print("=" * 80)
print()
print("⚠️ 请确保已设置以下环境变量:")
print(" - BYTEHOUSE_HOST")
print(" - BYTEHOUSE_PORT")
print(" - BYTEHOUSE_USER")
print(" - BYTEHOUSE_PASSWORD")
print()
# 从环境变量获取配置
env = os.environ.copy()
# MCP Server参数
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
print("\n🔌 正在连接MCP Server...")
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print("✅ 连接成功!")
# 1. 先列出所有数据库
print("\n📊 步骤1: 列出所有数据库")
print("-" * 80)
result = await session.call_tool("list_databases", {})
for content in result.content:
if content.type == 'text':
print(content.text)
# 2. 查询Top 10大表
print("\n🏆 步骤2: 查询Top 10大表")
print("-" * 80)
sql = """
SELECT
database,
table,
sum(bytes) as total_bytes,
sum(rows) as total_rows
FROM system.parts
WHERE active = 1
GROUP BY database, table
ORDER BY total_bytes DESC
LIMIT 10
"""
result = await session.call_tool("run_select_query", {"query": sql})
print("\n📊 查询结果:")
print("-" * 80)
for content in result.content:
if content.type == 'text':
print(content.text)
print("\n" + "=" * 80)
print("✅ 查询完成!")
print("=" * 80)
if __name__ == "__main__":
asyncio.run(query_top10_tables())
#!/bin/bash
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 重启ByteHouse MCP Server
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "=" * 80
echo "重启ByteHouse MCP Server"
echo "=" * 80
"$SCRIPT_DIR/stop_mcp_service.sh"
echo
sleep 2
"$SCRIPT_DIR/start_mcp_service.sh"
#!/bin/bash
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 启动ByteHouse MCP Server的脚本
# 设置环境变量(请自行配置)
# export BYTEHOUSE_HOST="<ByteHouse-host>"
# export BYTEHOUSE_PORT="<ByteHouse-port>"
# export BYTEHOUSE_USER="<ByteHouse-user>"
# export BYTEHOUSE_PASSWORD="<ByteHouse-password>"
# export BYTEHOUSE_SECURE="true"
# export BYTEHOUSE_VERIFY="true"
# export BYTEHOUSE_CONNECT_TIMEOUT="30"
# export BYTEHOUSE_SEND_RECEIVE_TIMEOUT="30"
echo "=" * 80
echo "启动ByteHouse MCP Server"
echo "=" * 80
echo "⚠️ 请确保已在脚本中配置环境变量"
echo "=" * 80
echo
# 检查环境变量是否已配置
if [ -z "$BYTEHOUSE_HOST" ] || [ -z "$BYTEHOUSE_PASSWORD" ]; then
echo "❌ 错误: 请先配置ByteHouse连接环境变量"
echo " 编辑此脚本,取消注释并配置环境变量部分"
exit 1
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$SCRIPT_DIR/logs"
PID_FILE="$SCRIPT_DIR/mcp_server.pid"
# 创建日志目录
mkdir -p "$LOG_DIR"
# 日志文件
LOG_FILE="$LOG_DIR/mcp_server_$(date +%Y%m%d_%H%M%S).log"
echo "=" * 80
echo "ByteHouse MCP Server - 常驻服务"
echo "=" * 80
echo "脚本目录: $SCRIPT_DIR"
echo "日志目录: $LOG_DIR"
echo "日志文件: $LOG_FILE"
echo "PID文件: $PID_FILE"
echo "=" * 80
echo
# 检查是否已经在运行
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE" 2>/dev/null)
if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
echo "⚠️ MCP Server已经在运行 (PID: $PID)"
echo " 如需重启,请先运行: $SCRIPT_DIR/stop_mcp_service.sh"
exit 1
else
echo "⚠️ PID文件存在但进程不存在,清理旧文件"
rm -f "$PID_FILE"
fi
fi
echo "🚀 启动ByteHouse MCP Server..."
echo
# 启动MCP Server(后台运行)
cd "$SCRIPT_DIR"
/root/.local/bin/uvx --from "git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse" mcp_bytehouse -t stdio > "$LOG_FILE" 2>&1 &
MCP_PID=$!
# 保存PID
echo $MCP_PID > "$PID_FILE"
# 等待一下检查进程
sleep 2
if kill -0 "$MCP_PID" 2>/dev/null; then
echo "✅ ByteHouse MCP Server启动成功!"
echo " PID: $MCP_PID"
echo " 日志: $LOG_FILE"
echo ""
echo "📋 管理命令:"
echo " 查看状态: $SCRIPT_DIR/status_mcp_service.sh"
echo " 查看日志: tail -f $LOG_FILE"
echo " 停止服务: $SCRIPT_DIR/stop_mcp_service.sh"
else
echo "❌ MCP Server启动失败"
echo " 查看日志: $LOG_FILE"
rm -f "$PID_FILE"
exit 1
fi
#!/bin/bash
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 查看ByteHouse MCP Server状态
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$SCRIPT_DIR/mcp_server.pid"
LOG_DIR="$SCRIPT_DIR/logs"
echo "=" * 80
echo "ByteHouse MCP Server 状态"
echo "=" * 80
if [ ! -f "$PID_FILE" ]; then
echo "❌ MCP Server未运行 (PID文件不存在)"
echo ""
echo "启动命令: $SCRIPT_DIR/start_mcp_service.sh"
exit 1
fi
PID=$(cat "$PID_FILE" 2>/dev/null)
if [ -z "$PID" ]; then
echo "❌ MCP Server未运行 (PID文件为空)"
rm -f "$PID_FILE"
exit 1
fi
if ! kill -0 "$PID" 2>/dev/null; then
echo "❌ MCP Server未运行 (进程不存在)"
rm -f "$PID_FILE"
exit 1
fi
echo "✅ MCP Server正在运行"
echo " PID: $PID"
echo ""
# 查看进程信息
echo "📊 进程信息:"
ps -p "$PID" -o pid,ppid,cmd,%cpu,%mem,etime
echo ""
# 查看最新日志
if [ -d "$LOG_DIR" ]; then
LATEST_LOG=$(ls -t "$LOG_DIR"/mcp_server_*.log 2>/dev/null | head -1)
if [ -n "$LATEST_LOG" ]; then
echo "📝 最新日志文件: $LATEST_LOG"
echo ""
echo "📋 最近20行日志:"
echo "-" * 80
tail -20 "$LATEST_LOG"
echo "-" * 80
echo ""
echo "查看完整日志: tail -f $LATEST_LOG"
fi
fi
echo ""
echo "📋 管理命令:"
echo " 停止服务: $SCRIPT_DIR/stop_mcp_service.sh"
echo " 重启服务: $SCRIPT_DIR/restart_mcp_service.sh"
#!/bin/bash
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 停止ByteHouse MCP Server
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$SCRIPT_DIR/mcp_server.pid"
echo "=" * 80
echo "停止ByteHouse MCP Server"
echo "=" * 80
if [ ! -f "$PID_FILE" ]; then
echo "⚠️ PID文件不存在,MCP Server可能未运行"
exit 0
fi
PID=$(cat "$PID_FILE" 2>/dev/null)
if [ -z "$PID" ]; then
echo "⚠️ PID文件为空"
rm -f "$PID_FILE"
exit 0
fi
echo "正在停止MCP Server (PID: $PID)..."
# 尝试优雅停止
kill "$PID" 2>/dev/null
# 等待进程结束
for i in {1..10}; do
if ! kill -0 "$PID" 2>/dev/null; then
echo "✅ MCP Server已停止"
rm -f "$PID_FILE"
exit 0
fi
sleep 1
done
# 强制停止
echo "⚠️ 进程未响应,强制停止..."
kill -9 "$PID" 2>/dev/null
sleep 1
if ! kill -0 "$PID" 2>/dev/null; then
echo "✅ MCP Server已强制停止"
else
echo "❌ 无法停止进程 (PID: $PID)"
exit 1
fi
rm -f "$PID_FILE"
#!/usr/bin/env python3
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
测试调用 list_tables tool
"""
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def test_list_tables():
"""测试list_tables tool"""
print("=" * 80)
print("测试调用 list_tables tool")
print("=" * 80)
# 从环境变量获取配置
env = os.environ.copy()
# MCP Server参数
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
print("\n🔌 正在连接MCP Server...")
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print("✅ 连接成功!")
# 1. 先列出所有数据库
print("\n📊 步骤1: 列出所有数据库")
print("-" * 80)
result = await session.call_tool("list_databases", {})
databases = []
for content in result.content:
if content.type == 'text':
print(content.text)
databases = [db.strip() for db in content.text.split('\n') if db.strip()]
# 2. 列出每个数据库的表
print(f"\n📊 步骤2: 列出每个数据库的表")
print("-" * 80)
for db in databases:
print(f"\n📁 数据库: {db}")
print("-" * 40)
try:
result = await session.call_tool("list_tables", {"database": db})
for content in result.content:
if content.type == 'text':
tables = [t.strip() for t in content.text.split('\n') if t.strip()]
print(f" 找到 {len(tables)} 张表:")
for table in tables:
print(f" - {table}")
except Exception as e:
print(f" ❌ 查询失败: {e}")
print("\n" + "=" * 80)
print("✅ 测试完成!")
print("=" * 80)
if __name__ == "__main__":
asyncio.run(test_list_tables())
#!/usr/bin/env python3
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
测试ByteHouse MCP Server
直接通过stdio与MCP Server通信
"""
# /// script
# dependencies = [
# "mcp>=1.0.0",
# ]
# ///
import asyncio
import os
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def test_mcp_server():
"""测试MCP Server"""
print("=" * 80)
print("测试ByteHouse MCP Server")
print("=" * 80)
print()
print("⚠️ 请确保已设置以下环境变量:")
print(" - BYTEHOUSE_HOST")
print(" - BYTEHOUSE_PORT")
print(" - BYTEHOUSE_USER")
print(" - BYTEHOUSE_PASSWORD")
print()
# 从环境变量获取配置
env = os.environ.copy()
# MCP Server参数
server_params = StdioServerParameters(
command='/root/.local/bin/uvx',
args=[
'--from',
'git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse',
'mcp_bytehouse',
'-t',
'stdio'
],
env=env
)
print("\n📦 正在安装和启动MCP Server...")
print(" 这可能需要几分钟时间...")
print()
try:
# 启动stdio客户端
async with stdio_client(server_params) as (read, write):
# 创建会话
async with ClientSession(read, write) as session:
# 初始化会话
print("🔌 正在初始化MCP会话...")
await session.initialize()
print("✅ 会话初始化成功!")
print()
# 列出可用的tools
print("📋 正在获取可用的tools...")
result = await session.list_tools()
print(f"\n✅ 找到 {len(result.tools)} 个tools:\n")
for i, tool in enumerate(result.tools, 1):
print(f"{i}. {tool.name}")
print(f" 描述: {tool.description}")
print(f" 参数: {tool.inputSchema}")
print()
# 如果有tools,尝试调用第一个
if result.tools:
first_tool = result.tools[0]
print(f"🚀 尝试调用第一个tool: {first_tool.name}")
print()
try:
# 尝试调用tool(使用空参数)
call_result = await session.call_tool(first_tool.name, {})
print("📊 调用结果:")
print("-" * 80)
for content in call_result.content:
if content.type == 'text':
print(content.text)
elif content.type == 'image':
print(f"[Image data: {len(content.data)} bytes]")
print("-" * 80)
except Exception as e:
print(f"⚠️ 调用tool失败 (可能需要特定参数): {e}")
print(" 但这不影响MCP Server的正常工作")
print("\n" + "=" * 80)
print("🎉 MCP Server测试成功!")
print("=" * 80)
print()
print("💡 下一步:")
print(" 1. 启动常驻服务: ./start_mcp_service.sh")
print(" 2. 查看状态: ./status_mcp_service.sh")
print(" 3. 停止服务: ./stop_mcp_service.sh")
print()
except Exception as e:
print(f"\n❌ 测试失败: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(test_mcp_server()))