mcp-bytehouse 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ *config.yaml
2
+ __pycache__/
3
+ .idea
4
+ .DS_Store
5
+ .venv/
6
+ *.egg-info/
7
+ .env
8
+ .vscode/
9
+ .history/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: mcp_bytehouse
3
+ Version: 0.2.0
4
+ Summary: An MCP server for ByteHouse.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: clickhouse-connect>=0.8.0
9
+ Requires-Dist: mcp[cli]>=1.12.0
10
+ Requires-Dist: pip-system-certs>=4.0
11
+ Requires-Dist: python-dotenv>=1.0.1
12
+ Requires-Dist: uvicorn>=0.34.0
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest; extra == 'dev'
15
+ Requires-Dist: ruff; extra == 'dev'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # ByteHouse MCP Server
19
+
20
+ An MCP server for ByteHouse. ByteHouse MCP Server serves as a communication bridge between large language models and ByteHouse instances, capable of efficiently transmitting information to achieve seamless docking and collaboration between the two. It also provides intelligent services throughout the entire life cycle for ByteHouse data development, query optimization, and cluster operation and maintenance. During data development, it offers precise guidance and suggestions to improve efficiency and quality. In terms of query optimization, it supports the analysis of statements and the optimization of performance. In the aspect of cluster operation and maintenance, it provides services such as monitoring the status, warning of risks, and automatic diagnosis and repair to ensure the efficient operation of the system.
21
+
22
+ ## Features
23
+
24
+ ### Tools
25
+
26
+ * `run_select_query`
27
+ - Execute SQL queries on your ByteHouse cluster.
28
+ - Input: `sql` (string): The SQL query to execute.
29
+ - All ByteHouse queries are run with `readonly = 1` to ensure they are safe.
30
+
31
+ * `list_databases`
32
+ - List all databases on your ByteHouse cluster.
33
+
34
+ * `list_tables`
35
+ - List all tables in a database.
36
+ - Input: `database` (string): The name of the database.
37
+
38
+ * `run_dml_ddl_query`
39
+ - Execute DML or DDL queries on your ByteHouse cluster.
40
+ - Input: `sql` (string): The SQL query to execute.
41
+
42
+ ## Configuration
43
+
44
+ ### Running the Server
45
+
46
+ ```bash
47
+ # Run the server with stdio transport (default)
48
+ mcp-bytehouse
49
+
50
+ # Run the server with SSE transport
51
+ mcp-bytehouse --transport sse
52
+ ```
53
+
54
+ 1. Open the Claude Desktop configuration file located at:
55
+ - On macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
56
+ - On Windows: `%APPDATA%/Claude/claude_desktop_config.json`
57
+
58
+ 2. Add the following:
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "mcp-bytehouse": {
64
+ "command": "uvx",
65
+ "args": [
66
+ "--from",
67
+ "git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse",
68
+ "mcp_bytehouse",
69
+ ],
70
+ "env": {
71
+ "BYTEHOUSE_HOST": "<ByteHouse-host>",
72
+ "BYTEHOUSE_PORT": "<ByteHouse-port>",
73
+ "BYTEHOUSE_USER": "<ByteHouse-user>",
74
+ "BYTEHOUSE_PASSWORD": "<ByteHouse-password>",
75
+ "BYTEHOUSE_SECURE": "true",
76
+ "BYTEHOUSE_VERIFY": "true",
77
+ "BYTEHOUSE_CONNECT_TIMEOUT": "30",
78
+ "BYTEHOUSE_SEND_RECEIVE_TIMEOUT": "30"
79
+ }
80
+ }
81
+ }
82
+ }
83
+ ```
84
+
85
+ ## License
86
+
87
+ This project is licensed under the Apache License.
@@ -0,0 +1,70 @@
1
+ # ByteHouse MCP Server
2
+
3
+ An MCP server for ByteHouse. ByteHouse MCP Server serves as a communication bridge between large language models and ByteHouse instances, capable of efficiently transmitting information to achieve seamless docking and collaboration between the two. It also provides intelligent services throughout the entire life cycle for ByteHouse data development, query optimization, and cluster operation and maintenance. During data development, it offers precise guidance and suggestions to improve efficiency and quality. In terms of query optimization, it supports the analysis of statements and the optimization of performance. In the aspect of cluster operation and maintenance, it provides services such as monitoring the status, warning of risks, and automatic diagnosis and repair to ensure the efficient operation of the system.
4
+
5
+ ## Features
6
+
7
+ ### Tools
8
+
9
+ * `run_select_query`
10
+ - Execute SQL queries on your ByteHouse cluster.
11
+ - Input: `sql` (string): The SQL query to execute.
12
+ - All ByteHouse queries are run with `readonly = 1` to ensure they are safe.
13
+
14
+ * `list_databases`
15
+ - List all databases on your ByteHouse cluster.
16
+
17
+ * `list_tables`
18
+ - List all tables in a database.
19
+ - Input: `database` (string): The name of the database.
20
+
21
+ * `run_dml_ddl_query`
22
+ - Execute DML or DDL queries on your ByteHouse cluster.
23
+ - Input: `sql` (string): The SQL query to execute.
24
+
25
+ ## Configuration
26
+
27
+ ### Running the Server
28
+
29
+ ```bash
30
+ # Run the server with stdio transport (default)
31
+ mcp-bytehouse
32
+
33
+ # Run the server with SSE transport
34
+ mcp-bytehouse --transport sse
35
+ ```
36
+
37
+ 1. Open the Claude Desktop configuration file located at:
38
+ - On macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
39
+ - On Windows: `%APPDATA%/Claude/claude_desktop_config.json`
40
+
41
+ 2. Add the following:
42
+
43
+ ```json
44
+ {
45
+ "mcpServers": {
46
+ "mcp-bytehouse": {
47
+ "command": "uvx",
48
+ "args": [
49
+ "--from",
50
+ "git+https://github.com/volcengine/mcp-server@main#subdirectory=server/mcp_server_bytehouse",
51
+ "mcp_bytehouse",
52
+ ],
53
+ "env": {
54
+ "BYTEHOUSE_HOST": "<ByteHouse-host>",
55
+ "BYTEHOUSE_PORT": "<ByteHouse-port>",
56
+ "BYTEHOUSE_USER": "<ByteHouse-user>",
57
+ "BYTEHOUSE_PASSWORD": "<ByteHouse-password>",
58
+ "BYTEHOUSE_SECURE": "true",
59
+ "BYTEHOUSE_VERIFY": "true",
60
+ "BYTEHOUSE_CONNECT_TIMEOUT": "30",
61
+ "BYTEHOUSE_SEND_RECEIVE_TIMEOUT": "30"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## License
69
+
70
+ This project is licensed under the Apache License.
@@ -0,0 +1,87 @@
1
+ ## MCP Server 产品名称
2
+ ByteHouse MCP Server
3
+ ## 版本信息
4
+ v25.4
5
+ ## 产品描述
6
+ ByteHouse MCP Server有着不可替代的作用。它可以实现大语言模型(LLMs)与ByteHouse的高效协同。在数据开发方面,大语言模型能够根据开发者的自然语言描述生成相应的代码,而ByteHouse MCP Server则可以将这些代码准确地应用到ByteHouse实例中,避免了开发者手动编写代码时可能出现的错误和繁琐过程,大大提高了数据开发的效率。在查询优化环节,大语言模型可以分析查询需求和数据特点,提出优化建议,ByteHouse MCP Server则能将这些建议转化为实际的优化策略应用于ByteHouse实例,从而提升查询性能。对于集群运维,大语言模型可以预测潜在的问题和风险,ByteHouse MCP Server会及时将这些信息反馈给ByteHouse实例,并协助采取相应的措施进行预防和处理。
7
+ ## 分类
8
+ 大数据
9
+ ## 标签
10
+ 企业版,云数仓版,Search,智能助手
11
+
12
+ ## 产品视频
13
+ <video src="https://lf3-static.bytednsdoc.com/obj/eden-cn/lm_sth/ljhwZthlaukjlkulzlp/ark/mcpserverhub/readme_videos/bytehouse_mcp.mp4" controls>
14
+ </video>
15
+
16
+ ## Tools
17
+ 本 MCP Server 产品提供以下 Tools (工具/能力):
18
+ ### list_database
19
+ 在进行数据管理和操作时,有时我们需要了解当前 ByteHouse 实例中所包含的数据库情况。此时,可以执行特定的查询操作,该工具操作的目的是查询当前 ByteHouse 实例下的所有数据库,通过此查询,系统将会返回该实例下存在的所有数据库。
20
+ ### list_tables
21
+ 查询当前ByteHouse实例中指定数据库下的所有数据表,并将查询到的所有数据表信息进行返回
22
+ ### run_select_query
23
+ 通过交互式执行 SELECT 查询语句来进行数据分析工作。在面对各种复杂的数据环境时,该助手能够精准地依据用户所提供的 SELECT 查询语句,在相应的数据库中进行数据检索操作,最终返回精确的查询结果。而且,更为重要的是,它不会仅仅止步于返回查询结果,还会对这些查询结果进一步进行全面且深入的分析说明。它会从多个维度去剖析这些数据,例如数据的分布规律、数据之间的关联关系、数据所反映出的潜在趋势等等,从而为用户提供更为详尽且有价值的信息,帮助用户更好地理解和利用这些数据。
24
+ ### run_dml_ddl_query
25
+ 能够实现可交互地执行数据操作语言(DML)以及数据定义语言(DDL)的 SQL 语句。在使用者输入相关的 DML/DDL SQL 语句后,该助手会迅速对语句进行处理并执行,之后及时反馈执行结果,同时还会对执行结果给出详细的解释,帮助使用者更好地理解操作的过程和最终产生的影响。
26
+ ## 最容易被唤起的 Prompt示例
27
+ ### list_database
28
+ 我想要查询当前所使用的集群环境中,都存在哪些数据库。具体来说,希望获取该集群内所有已创建数据库的名称等相关信息,以便进一步对这些数据库进行管理、分析或者使用等操作。
29
+ ### list_tables
30
+ 我想要查询数据库名为 {database name} 的这个数据库中具体包含了哪些数据表。
31
+ ### run_select_query
32
+ 帮忙查询一下集群存储目前的水位情况,包括各个存储节点当前的使用容量、剩余容量以及占总容量的百分比等详细信息。
33
+ ## 可适配平台
34
+ 火山方舟,Cursor,Visual Studio Code,Trae
35
+
36
+ ## 服务开通链接 (整体产品)
37
+ 如下产品开通任意一个即可
38
+
39
+ 企业版: `https://console.volcengine.com/bytehouse-ce`
40
+ 云数仓版: `https://console.volcengine.com/bytehouse`
41
+
42
+ ## 鉴权方式
43
+ 用户开通Bytehouse企业版或Bytehouse云数仓版实例,在集群管理获取IP、端口、用户名、密码,并配置到MCP configure
44
+
45
+ ## 安装部署
46
+ 如下已本地部署为例进行说明,操作系统macOS:
47
+
48
+ ### Setp 1
49
+ 在方舟平台开通大模型服务(豆包或DeepSeek),并获取API KEY
50
+
51
+ ### Setp 2
52
+ 本地安装Cursor,Visual Studio Code,Trae
53
+
54
+ ### Setp 3
55
+ 下载mcp-bytehouse安装包,执行如下命令运行mcp-bytehouse 服务
56
+
57
+ <font color="red"> ***注意!Python版本需要3.12***</font>
58
+
59
+ ```
60
+ export BYTEHOUSE_HOST="<your_bytehouse_host>"
61
+ export BYTEHOUSE_PORT="<your_bytehouse_port>"
62
+ export BYTEHOUSE_USER="<your_bytehouse_user>"
63
+ export BYTEHOUSE_PASSWORD="<your_bytehouse_password>"
64
+ export BYTEHOUSE_SECURE="true"
65
+ export BYTEHOUSE_VERIFY="true"
66
+ export BYTEHOUSE_CONNECT_TIMEOUT="60"
67
+ export BYTEHOUSE_SEND_RECEIVE_TIMEOUT="60"
68
+
69
+ pip install -r requirements.txt
70
+ python3 -m mcp_bytehouse.main -t sse
71
+ ```
72
+ ### Setp 4
73
+ 本地cursor,Visual Studio Code,Trae 安装插件Cline
74
+
75
+ ### Setp 5
76
+ Cline配置大模型地址及其API KEY,同时按照如下模版配置mcp configure
77
+ ```
78
+ {
79
+ "mcpServers": {
80
+ "mcp_bytehouse":{
81
+ "url":"https://<your_hostname>:8000/sse"
82
+ }
83
+ }
84
+ }
85
+ ```
86
+ ## License
87
+ Apache License
@@ -0,0 +1,15 @@
1
+ from .mcp_server import (
2
+ create_clickhouse_client,
3
+ list_databases,
4
+ list_tables,
5
+ run_select_query,
6
+ run_dml_ddl_query,
7
+ )
8
+
9
+ __all__ = [
10
+ "list_databases",
11
+ "list_tables",
12
+ "run_select_query",
13
+ "create_clickhouse_client",
14
+ "run_dml_ddl_query",
15
+ ]
@@ -0,0 +1,20 @@
1
+ import argparse
2
+ from .mcp_server import mcp
3
+
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser(description="Run the ByteHouse MCP Server")
7
+ parser.add_argument(
8
+ "--transport",
9
+ "-t",
10
+ choices=["sse", "stdio", "streamable-http"],
11
+ default="stdio",
12
+ help="Transport protocol to use (sse or stdio)",
13
+ )
14
+ args = parser.parse_args()
15
+
16
+ mcp.run(transport=args.transport)
17
+
18
+
19
+ if __name__ == "__main__":
20
+ main()
@@ -0,0 +1,142 @@
1
+ """Environment configuration for the MCP ClickHouse server.
2
+
3
+ This module handles all environment variable configuration with sensible defaults
4
+ and type conversion.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ import os
9
+ from typing import Optional
10
+
11
+
12
+ @dataclass
13
+ class ClickHouseConfig:
14
+ """Configuration for ClickHouse connection settings.
15
+
16
+ This class handles all environment variable configuration with sensible defaults
17
+ and type conversion. It provides typed methods for accessing each configuration value.
18
+
19
+ Required environment variables:
20
+ BYTEHOUSE_HOST: The hostname of the ClickHouse server
21
+ BYTEHOUSE_USER: The username for authentication
22
+ BYTEHOUSE_PASSWORD: The password for authentication
23
+
24
+ Optional environment variables (with defaults):
25
+ BYTEHOUSE_PORT: The port number (default: 8443 if secure=True, 8123 if secure=False)
26
+ BYTEHOUSE_SECURE: Enable HTTPS (default: true)
27
+ BYTEHOUSE_VERIFY: Verify SSL certificates (default: true)
28
+ BYTEHOUSE_CONNECT_TIMEOUT: Connection timeout in seconds (default: 30)
29
+ BYTEHOUSE_SEND_RECEIVE_TIMEOUT: Send/receive timeout in seconds (default: 300)
30
+ BYTEHOUSE_DATABASE: Default database to use (default: None)
31
+ """
32
+
33
+ def __init__(self):
34
+ """Initialize the configuration from environment variables."""
35
+ self._validate_required_vars()
36
+
37
+ @property
38
+ def host(self) -> str:
39
+ """Get the ClickHouse host."""
40
+ return os.environ["BYTEHOUSE_HOST"]
41
+
42
+ @property
43
+ def port(self) -> int:
44
+ """Get the ClickHouse port.
45
+
46
+ Defaults to 8443 if secure=True, 8123 if secure=False.
47
+ Can be overridden by BYTEHOUSE_PORT environment variable.
48
+ """
49
+ if "BYTEHOUSE_PORT" in os.environ:
50
+ return int(os.environ["BYTEHOUSE_PORT"])
51
+ return 8443 if self.secure else 8123
52
+
53
+ @property
54
+ def username(self) -> str:
55
+ """Get the ClickHouse username."""
56
+ return os.environ["BYTEHOUSE_USER"]
57
+
58
+ @property
59
+ def password(self) -> str:
60
+ """Get the ClickHouse password."""
61
+ return os.environ["BYTEHOUSE_PASSWORD"]
62
+
63
+ @property
64
+ def database(self) -> Optional[str]:
65
+ """Get the default database name if set."""
66
+ return os.getenv("BYTEHOUSE_DATABASE")
67
+
68
+ @property
69
+ def secure(self) -> bool:
70
+ """Get whether HTTPS is enabled.
71
+
72
+ Default: True
73
+ """
74
+ return os.getenv("BYTEHOUSE_SECURE", "true").lower() == "true"
75
+
76
+ @property
77
+ def verify(self) -> bool:
78
+ """Get whether SSL certificate verification is enabled.
79
+
80
+ Default: True
81
+ """
82
+ return os.getenv("BYTEHOUSE_VERIFY", "true").lower() == "true"
83
+
84
+ @property
85
+ def connect_timeout(self) -> int:
86
+ """Get the connection timeout in seconds.
87
+
88
+ Default: 30
89
+ """
90
+ return int(os.getenv("BYTEHOUSE_CONNECT_TIMEOUT", "30"))
91
+
92
+ @property
93
+ def send_receive_timeout(self) -> int:
94
+ """Get the send/receive timeout in seconds.
95
+
96
+ Default: 300 (ClickHouse default)
97
+ """
98
+ return int(os.getenv("BYTEHOUSE_SEND_RECEIVE_TIMEOUT", "300"))
99
+
100
+ def get_client_config(self) -> dict:
101
+ """Get the configuration dictionary for BYTEHOUSE_connect client.
102
+
103
+ Returns:
104
+ dict: Configuration ready to be passed to BYTEHOUSE_connect.get_client()
105
+ """
106
+ config = {
107
+ "host": self.host,
108
+ "port": self.port,
109
+ "username": self.username,
110
+ "password": self.password,
111
+ "secure": self.secure,
112
+ "verify": self.verify,
113
+ "connect_timeout": self.connect_timeout,
114
+ "send_receive_timeout": self.send_receive_timeout,
115
+ "client_name": "mcp_bytehouse",
116
+ }
117
+
118
+ # Add optional database if set
119
+ if self.database:
120
+ config["database"] = self.database
121
+
122
+ return config
123
+
124
+ def _validate_required_vars(self) -> None:
125
+ """Validate that all required environment variables are set.
126
+
127
+ Raises:
128
+ ValueError: If any required environment variable is missing.
129
+ """
130
+ missing_vars = []
131
+ for var in ["BYTEHOUSE_HOST", "BYTEHOUSE_USER", "BYTEHOUSE_PASSWORD"]:
132
+ if var not in os.environ:
133
+ missing_vars.append(var)
134
+
135
+ if missing_vars:
136
+ raise ValueError(
137
+ f"Missing required environment variables: {', '.join(missing_vars)}"
138
+ )
139
+
140
+
141
+ # Global instance for easy access
142
+ config = ClickHouseConfig()