mcp-trino-python 0.1.0__py3-none-any.whl

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.
__init__.py ADDED
File without changes
config.py ADDED
@@ -0,0 +1,39 @@
1
+ """Configuration module for Trino connection settings."""
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+
6
+ import trino
7
+ from dotenv import load_dotenv
8
+
9
+
10
+ @dataclass
11
+ class TrinoConfig:
12
+ """Configuration class for Trino connection settings."""
13
+
14
+ host: str
15
+ port: int
16
+ user: str
17
+ catalog: str | None = None
18
+ schema: str | None = None
19
+ http_scheme: str = "http"
20
+ auth: str | None = None
21
+ source: str = "mcp-trino-python"
22
+
23
+
24
+ def load_config() -> TrinoConfig:
25
+ """Load Trino configuration from environment variables."""
26
+ load_dotenv(override=True)
27
+
28
+ return TrinoConfig(
29
+ host=os.getenv("TRINO_HOST", "localhost"),
30
+ port=int(os.getenv("TRINO_PORT", "8080")),
31
+ user=os.getenv("TRINO_USER", os.getenv("USER", "trino")),
32
+ catalog=os.getenv("TRINO_CATALOG"),
33
+ schema=os.getenv("TRINO_SCHEMA"),
34
+ http_scheme=os.getenv("TRINO_HTTP_SCHEME", "http"),
35
+ auth=None
36
+ if os.getenv("TRINO_PASSWORD", None) is None
37
+ else trino.auth.BasicAuthentication(os.getenv("TRINO_USER", None), os.getenv("TRINO_PASSWORD", None)),
38
+ source="mcp-trino-python",
39
+ )
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-trino-python
3
+ Version: 0.1.0
4
+ Summary: A Model Context Protocol (MCP) connector for Trino, enabling seamless integration between MCP-compliant services and Trino query engine
5
+ License: Apache-2.0
6
+ Keywords: trino,connector,mcp
7
+ Classifier: Programming Language :: Python :: 3.11
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: loguru>=0.7.3
17
+ Requires-Dist: mcp[cli]>=1.6.0
18
+ Requires-Dist: python-dotenv>=1.1.0
19
+ Requires-Dist: trino>=0.333.0
20
+ Dynamic: license-file
21
+
22
+ # MCP Trino Server
23
+
24
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
25
+ [![VS Code](https://img.shields.io/badge/vscode-available-007ACC.svg?style=flat-square&logo=visual-studio-code&logoColor=white)](https://code.visualstudio.com/)
26
+ [![Docker](https://img.shields.io/badge/docker-available-2496ED.svg?style=flat-square&logo=docker&logoColor=white)](https://github.com/alaturqua/mcp-trino-python/pkgs/container/mcp-trino-python)
27
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=flat-square)](https://opensource.org/licenses/Apache-2.0)
28
+
29
+ The MCP Trino Server is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction)
30
+ server that provides seamless integration with Trino and Iceberg, enabling advanced
31
+ data exploration, querying, and table maintenance capabilities through a standard interface.
32
+
33
+ ## Use Cases
34
+
35
+ - Interactive data exploration and analysis in Trino
36
+ - Automated Iceberg table maintenance and optimization
37
+ - Building AI-powered tools that interact with Trino databases
38
+ - Executing and managing SQL queries with proper result formatting
39
+
40
+ ## Prerequisites
41
+
42
+ 1. A running Trino server (or Docker Compose for local development)
43
+ 2. Python 3.11 or higher
44
+ 3. Docker (optional, for containerized deployment)
45
+
46
+ ## Installation
47
+
48
+ ### Running Trino Locally
49
+
50
+ The easiest way to get started is to use the included Docker Compose configuration to run Trino locally:
51
+
52
+ ```bash
53
+ docker-compose up -d
54
+ ```
55
+
56
+ This will start a Trino server on `localhost:8080`. You can now proceed with configuring the MCP server.
57
+
58
+ ### Usage with VS Code
59
+
60
+ For quick installation, you can add the following configuration to your VS Code settings. You can do this by pressing `Ctrl + Shift + P` and typing `Preferences: Open User Settings (JSON)`.
61
+
62
+ Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.
63
+
64
+ > Note that the `mcp` key is not needed in the `.vscode/mcp.json` file.
65
+
66
+ ```json
67
+ {
68
+ "mcp": {
69
+ "servers": {
70
+ "trino": {
71
+ "command": "docker",
72
+ "args": ["run", "--rm", "ghcr.io/alaturqua/mcp-trino-python:latest"],
73
+ "env": {
74
+ "TRINO_HOST": "${input:trino_host}",
75
+ "TRINO_PORT": "${input:trino_port}",
76
+ "TRINO_USER": "${input:trino_user}"
77
+ }
78
+ }
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ ### Usage with Claude Desktop
85
+
86
+ Add the following configuration to your Claude Desktop settings:
87
+
88
+ ```json
89
+ {
90
+ "mcpServers": {
91
+ "trino": {
92
+ "command": "python",
93
+ "args": ["server.py"],
94
+ "env": {
95
+ "TRINO_HOST": "your-trino-host",
96
+ "TRINO_PORT": "8080",
97
+ "TRINO_USER": "trino"
98
+ }
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ ## Configuration
105
+
106
+ ### Environment Variables
107
+
108
+ | Variable | Description | Default |
109
+ | ----------------- | ------------------------ | --------- |
110
+ | TRINO_HOST | Trino server hostname | localhost |
111
+ | TRINO_PORT | Trino server port | 8080 |
112
+ | TRINO_USER | Trino username | trino |
113
+ | TRINO_CATALOG | Default catalog | None |
114
+ | TRINO_SCHEMA | Default schema | None |
115
+ | TRINO_HTTP_SCHEME | HTTP scheme (http/https) | http |
116
+ | TRINO_AUTH | Authentication method | None |
117
+
118
+ ## Resources
119
+
120
+ The server provides the following MCP resources:
121
+
122
+ ### Catalog and Schema Navigation
123
+
124
+ - **catalog://main** (`list_catalogs`)
125
+
126
+ - Lists all available Trino catalogs
127
+ - No parameters required
128
+
129
+ - **schema://{catalog}** (`list_schemas`)
130
+
131
+ - Lists all schemas in the specified catalog
132
+ - Parameters:
133
+ - `catalog`: Catalog name (string, required)
134
+
135
+ - **table://{catalog}/{schema}** (`list_tables`)
136
+ - Lists all tables in the specified schema
137
+ - Parameters:
138
+ - `catalog`: Catalog name (string, required)
139
+ - `schema`: Schema name (string, required)
140
+
141
+ ## Tools
142
+
143
+ ### Query and Exploration Tools
144
+
145
+ - **execute_query**
146
+
147
+ - Execute a SQL query and return formatted results
148
+ - Parameters:
149
+ - `query`: SQL query to execute (string, required)
150
+
151
+ - **show_catalog_tree**
152
+
153
+ - Show a hierarchical tree view of catalogs, schemas, and tables
154
+ - Returns a formatted tree structure with visual indicators
155
+ - No parameters required
156
+
157
+ - **show_create_table**
158
+
159
+ - Show the CREATE TABLE statement for a table
160
+ - Parameters:
161
+ - `table`: Table name (string, required)
162
+ - `catalog`: Catalog name (string, optional)
163
+ - `schema`: Schema name (string, optional)
164
+
165
+ - **show_create_view**
166
+
167
+ - Show the CREATE VIEW statement for a view
168
+ - Parameters:
169
+ - `view`: View name (string, required)
170
+ - `catalog`: Catalog name (string, optional)
171
+ - `schema`: Schema name (string, optional)
172
+
173
+ - **show_stats**
174
+ - Show statistics for a table
175
+ - Parameters:
176
+ - `table`: Table name (string, required)
177
+ - `catalog`: Catalog name (string, optional)
178
+ - `schema`: Schema name (string, optional)
179
+
180
+ ### Iceberg Table Maintenance
181
+
182
+ - **optimize**
183
+
184
+ - Optimize an Iceberg table by compacting small files
185
+ - Parameters:
186
+ - `table`: Table name (string, required)
187
+ - `catalog`: Catalog name (string, optional)
188
+ - `schema`: Schema name (string, optional)
189
+
190
+ - **optimize_manifests**
191
+
192
+ - Optimize manifest files for an Iceberg table
193
+ - Parameters:
194
+ - `table`: Table name (string, required)
195
+ - `catalog`: Catalog name (string, optional)
196
+ - `schema`: Schema name (string, optional)
197
+
198
+ - **expire_snapshots**
199
+ - Remove old snapshots from an Iceberg table
200
+ - Parameters:
201
+ - `table`: Table name (string, required)
202
+ - `retention_threshold`: Age threshold (e.g., "7d") (string, optional)
203
+ - `catalog`: Catalog name (string, optional)
204
+ - `schema`: Schema name (string, optional)
205
+
206
+ ### Query History
207
+
208
+ - **show_query_history**
209
+ - Get the history of executed queries
210
+ - Parameters:
211
+ - `limit`: Maximum number of queries to return (number, optional)
212
+
213
+ ## License
214
+
215
+ This project is licensed under the Apache 2.0 License. Please refer to the LICENSE file for the full terms.
@@ -0,0 +1,9 @@
1
+ __init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ config.py,sha256=yrcMSou2YuSs9VHJ4k7nzbrApS7yRLAz96EZK6FMuNU,1171
3
+ server.py,sha256=pOrIOCN9cRMnixPAPmNK5ljcNR1wrIdzY-5hV4vKXdA,7585
4
+ trino_client.py,sha256=gyJncqnkXi3s0jWTzxIt2IMaBZs5GbcFlUvfPYiUc5E,12902
5
+ mcp_trino_python-0.1.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
6
+ mcp_trino_python-0.1.0.dist-info/METADATA,sha256=P4xUpLLs3A03jY1SLeLco-MWirtiWd5xxX_X-JMb9Sg,7086
7
+ mcp_trino_python-0.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
8
+ mcp_trino_python-0.1.0.dist-info/top_level.txt,sha256=IaNppvaB5R57HjeQAk_6sMCitRe2OxIOGiDWrmgcpqM,36
9
+ mcp_trino_python-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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,4 @@
1
+ __init__
2
+ config
3
+ server
4
+ trino_client
server.py ADDED
@@ -0,0 +1,228 @@
1
+ """Model Context Protocol server for Trino.
2
+
3
+ This module provides a Model Context Protocol (MCP) server that exposes Trino
4
+ functionality through resources and tools, with special support for Iceberg tables.
5
+ """
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+ from mcp.server.fastmcp.prompts import base
9
+
10
+ from config import load_config
11
+ from trino_client import TrinoClient
12
+
13
+ # Initialize the MCP server and Trino client
14
+ config = load_config()
15
+ client = TrinoClient(config)
16
+ mcp = FastMCP("Trino Explorer", dependencies=["trino", "python-dotenv", "loguru"])
17
+
18
+
19
+ # Resources
20
+ @mcp.resource(
21
+ "catalog://main",
22
+ name="list_catalogs",
23
+ description="List all available Trino catalogs",
24
+ )
25
+ def list_catalogs() -> str:
26
+ """List all available Trino catalogs."""
27
+ return client.list_catalogs()
28
+
29
+
30
+ @mcp.resource(
31
+ "schema://{catalog}",
32
+ name="list_schemas",
33
+ description="List all schemas in the specified catalog",
34
+ )
35
+ def list_schemas(catalog: str) -> str:
36
+ """List all schemas in a catalog."""
37
+ return client.list_schemas(catalog)
38
+
39
+
40
+ @mcp.resource(
41
+ "table://{catalog}/{schema}",
42
+ name="list_tables",
43
+ description="List all tables in the specified schema",
44
+ )
45
+ def list_tables(catalog: str, schema: str) -> str:
46
+ """List all tables in a schema."""
47
+ return client.list_tables(catalog, schema)
48
+
49
+
50
+ # Tools
51
+ @mcp.tool(description="Show the CREATE TABLE statement for a specific table")
52
+ def show_create_table(table: str, catalog: str | None = None, schema: str | None = None) -> str:
53
+ """Show the CREATE TABLE statement for a table.
54
+
55
+ Args:
56
+ table: The name of the table
57
+ catalog: Optional catalog name (defaults to configured catalog)
58
+ schema: Optional schema name (defaults to configured schema)
59
+
60
+ Returns:
61
+ str: The CREATE TABLE statement
62
+ """
63
+ return client.show_create_table(table, catalog, schema)
64
+
65
+
66
+ @mcp.tool(description="Show the CREATE VIEW statement for a specific view")
67
+ def show_create_view(view: str, catalog: str | None = None, schema: str | None = None) -> str:
68
+ """Show the CREATE VIEW statement for a view.
69
+
70
+ Args:
71
+ view: The name of the view
72
+ catalog: Optional catalog name (defaults to configured catalog)
73
+ schema: Optional schema name (defaults to configured schema)
74
+
75
+ Returns:
76
+ str: The CREATE VIEW statement
77
+ """
78
+ return client.show_create_view(view, catalog, schema)
79
+
80
+
81
+ @mcp.tool(description="Execute a SQL query and return results in a readable format")
82
+ def execute_query(query: str) -> str:
83
+ """Execute a SQL query and return formatted results.
84
+
85
+ Args:
86
+ query: The SQL query to execute
87
+
88
+ Returns:
89
+ str: Query results formatted as a JSON string
90
+ """
91
+ return client.execute_query(query)
92
+
93
+
94
+ @mcp.tool(description="Optimize an Iceberg table's data files")
95
+ def optimize(table: str, catalog: str | None = None, schema: str | None = None) -> str:
96
+ """Optimize an Iceberg table by compacting small files.
97
+
98
+ Args:
99
+ table: The name of the table to optimize
100
+ catalog: Optional catalog name (defaults to configured catalog)
101
+ schema: Optional schema name (defaults to configured schema)
102
+
103
+ Returns:
104
+ str: Confirmation message
105
+ """
106
+ return client.optimize(table, catalog, schema)
107
+
108
+
109
+ @mcp.tool(description="Optimize manifest files for an Iceberg table")
110
+ def optimize_manifests(table: str, catalog: str | None = None, schema: str | None = None) -> str:
111
+ """Optimize manifest files for an Iceberg table.
112
+
113
+ Args:
114
+ table: The name of the table
115
+ catalog: Optional catalog name (defaults to configured catalog)
116
+ schema: Optional schema name (defaults to configured schema)
117
+
118
+ Returns:
119
+ str: Confirmation message
120
+ """
121
+ return client.optimize_manifests(table, catalog, schema)
122
+
123
+
124
+ @mcp.tool(description="Remove old snapshots from an Iceberg table")
125
+ def expire_snapshots(
126
+ table: str,
127
+ retention_threshold: str = "7d",
128
+ catalog: str | None = None,
129
+ schema: str | None = None,
130
+ ) -> str:
131
+ """Remove old snapshots from an Iceberg table.
132
+
133
+ Args:
134
+ table: The name of the table
135
+ retention_threshold: Age threshold for snapshot removal (e.g., "7d", "30d")
136
+ catalog: Optional catalog name (defaults to configured catalog)
137
+ schema: Optional schema name (defaults to configured schema)
138
+
139
+ Returns:
140
+ str: Confirmation message
141
+ """
142
+ return client.expire_snapshots(table, retention_threshold, catalog, schema)
143
+
144
+
145
+ @mcp.tool(description="Show statistics for a table")
146
+ def show_stats(table: str, catalog: str | None = None, schema: str | None = None) -> str:
147
+ """Show statistics for a table.
148
+
149
+ Args:
150
+ table: The name of the table
151
+ catalog: Optional catalog name (defaults to configured catalog)
152
+ schema: Optional schema name (defaults to configured schema)
153
+
154
+ Returns:
155
+ str: Table statistics in JSON format
156
+ """
157
+ return client.show_stats(table, catalog, schema)
158
+
159
+
160
+ @mcp.tool(name="show_query_history", description="Get the history of executed queries")
161
+ def show_query_history(limit: int | None = None) -> str:
162
+ """Get the history of executed queries.
163
+
164
+ Args:
165
+ limit: Optional maximum number of history entries to return.
166
+ If None, returns all entries.
167
+
168
+ Returns:
169
+ str: JSON-formatted string containing query history.
170
+ """
171
+ return client.get_query_history(limit)
172
+
173
+
174
+ @mcp.tool(description="Show a hierarchical tree view of catalogs, schemas, and tables")
175
+ def show_catalog_tree() -> str:
176
+ """Get a hierarchical tree view showing the full structure of catalogs, schemas, and tables.
177
+
178
+ Returns:
179
+ str: A formatted string showing the catalog > schema > table hierarchy with visual indicators
180
+ """
181
+ return client.show_catalog_tree()
182
+
183
+
184
+ # Prompts
185
+ @mcp.prompt()
186
+ def explore_data(catalog: str | None = None, schema: str | None = None) -> list[base.Message]:
187
+ """Interactive prompt to explore Trino data."""
188
+ messages = [
189
+ base.SystemMessage(
190
+ "I'll help you explore data in Trino. I can show you available catalogs, "
191
+ "schemas, and tables, and help you query the data."
192
+ )
193
+ ]
194
+
195
+ if catalog and schema:
196
+ messages.append(
197
+ base.UserMessage(
198
+ f"Show me what tables are available in the {catalog}.{schema} schema and help me query them."
199
+ )
200
+ )
201
+ elif catalog:
202
+ messages.append(base.UserMessage(f"Show me what schemas are available in the {catalog} catalog."))
203
+ else:
204
+ messages.append(base.UserMessage("Show me what catalogs are available."))
205
+
206
+ return messages
207
+
208
+
209
+ @mcp.prompt()
210
+ def maintain_iceberg(table: str, catalog: str | None = None, schema: str | None = None) -> list[base.Message]:
211
+ """Interactive prompt for Iceberg table maintenance."""
212
+ return [
213
+ base.SystemMessage(
214
+ "I'll help you maintain an Iceberg table. I can help with optimization, "
215
+ "cleaning up snapshots and orphan files, and viewing table metadata."
216
+ ),
217
+ base.UserMessage(
218
+ f"What maintenance operations should we perform on the Iceberg table "
219
+ f"{catalog + '.' if catalog else ''}{schema + '.' if schema else ''}{table}?"
220
+ ),
221
+ ]
222
+
223
+
224
+ if __name__ == "__main__":
225
+ from loguru import logger
226
+
227
+ logger.info("Starting Trino MCP server...")
228
+ mcp.run()
trino_client.py ADDED
@@ -0,0 +1,322 @@
1
+ """Client for interacting with Trino server.
2
+
3
+ This module provides a client for executing queries and managing operations on Trino,
4
+ including specific support for Iceberg table operations.
5
+ """
6
+
7
+ import json
8
+
9
+ import trino
10
+
11
+ from config import TrinoConfig
12
+
13
+
14
+ class TrinoError(Exception):
15
+ """Base class for Trino-related errors."""
16
+
17
+ def __init__(self, message: str):
18
+ """Initialize with error message."""
19
+ self.message = message
20
+ super().__init__(self.message)
21
+
22
+
23
+ class CatalogSchemaError(TrinoError):
24
+ """Error raised when catalog or schema information is missing."""
25
+
26
+ def __init__(self):
27
+ super().__init__("Both catalog and schema must be specified")
28
+
29
+
30
+ class TrinoClient:
31
+ """A client for interacting with Trino server.
32
+
33
+ This class provides methods to execute queries and perform administrative operations
34
+ on a Trino server, with special support for Iceberg table operations.
35
+
36
+ Attributes:
37
+ config (TrinoConfig): Configuration object containing Trino connection settings.
38
+ client (trino.dbapi.Connection): Active connection to the Trino server.
39
+ """
40
+
41
+ def __init__(self, config: TrinoConfig):
42
+ """Initialize the Trino client.
43
+
44
+ Args:
45
+ config (TrinoConfig): Configuration object containing Trino connection settings.
46
+ """
47
+ self.config = config
48
+ self.client = self._create_client()
49
+
50
+ def _create_client(self) -> trino.dbapi.Connection:
51
+ """Create a new Trino DB API connection.
52
+
53
+ Returns:
54
+ trino.dbapi.Connection: A new connection to the Trino server.
55
+ """
56
+ return trino.dbapi.connect(
57
+ host=self.config.host,
58
+ port=self.config.port,
59
+ user=self.config.user,
60
+ catalog=self.config.catalog,
61
+ schema=self.config.schema,
62
+ http_scheme=self.config.http_scheme,
63
+ auth=self.config.auth,
64
+ source=self.config.source,
65
+ )
66
+
67
+ def execute_query(self, query: str) -> str:
68
+ """Execute a SQL query against Trino and return results as a formatted string.
69
+
70
+ Args:
71
+ query (str): The SQL query to execute.
72
+
73
+ Returns:
74
+ str: JSON-formatted string containing query results or success message.
75
+ """
76
+ cur = self.client.cursor()
77
+ cur.execute(query)
78
+ if cur.description:
79
+ return json.dumps(
80
+ [dict(zip([col[0] for col in cur.description], row, strict=True)) for row in cur.fetchall()],
81
+ default=str,
82
+ )
83
+ return "Query executed successfully (no results to display)"
84
+
85
+ def get_query_history(self, limit: int | None = None) -> str:
86
+ """Retrieve the history of executed queries.
87
+
88
+ Args:
89
+ limit (Optional[int]): Maximum number of queries to return. If None, returns all queries.
90
+
91
+ Returns:
92
+ str: JSON-formatted string containing query history.
93
+ """
94
+ query = "SELECT * FROM system.runtime.queries"
95
+ if limit is not None:
96
+ query += f" LIMIT {limit}"
97
+ return self.execute_query(query)
98
+
99
+ def list_catalogs(self) -> str:
100
+ """List all available catalogs.
101
+
102
+ Returns:
103
+ str: Newline-separated list of catalog names.
104
+ """
105
+ catalogs = [row["Catalog"] for row in json.loads(self.execute_query("SHOW CATALOGS"))]
106
+ return "\n".join(catalogs)
107
+
108
+ def list_schemas(self, catalog: str | None = None) -> str:
109
+ """List all schemas in a catalog.
110
+
111
+ Args:
112
+ catalog: The catalog name. If None, uses configured default.
113
+
114
+ Returns:
115
+ Newline-separated list of schema names.
116
+
117
+ Raises:
118
+ CatalogSchemaError: If no catalog is specified and none is configured.
119
+ """
120
+ catalog = catalog or self.config.catalog
121
+ if not catalog:
122
+ msg = "Catalog must be specified"
123
+ raise CatalogSchemaError(msg)
124
+ query = f"SHOW SCHEMAS FROM {catalog}"
125
+ schemas = [row["Schema"] for row in json.loads(self.execute_query(query))]
126
+ return "\n".join(schemas)
127
+
128
+ def list_tables(self, catalog: str | None = None, schema: str | None = None) -> str:
129
+ """List all tables in a schema.
130
+
131
+ Args:
132
+ catalog: The catalog name. If None, uses configured default.
133
+ schema: The schema name. If None, uses configured default.
134
+
135
+ Returns:
136
+ Newline-separated list of table names.
137
+
138
+ Raises:
139
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
140
+ """
141
+ catalog = catalog or self.config.catalog
142
+ schema = schema or self.config.schema
143
+ if not catalog or not schema:
144
+ msg = "Both catalog and schema must be specified"
145
+ raise CatalogSchemaError(msg)
146
+ query = f"SHOW TABLES FROM {catalog}.{schema}"
147
+ tables = [row["Table"] for row in json.loads(self.execute_query(query))]
148
+ return "\n".join(tables)
149
+
150
+ def show_create_table(self, table: str, catalog: str | None = None, schema: str | None = None) -> str:
151
+ """Show the CREATE TABLE statement for a table.
152
+
153
+ Args:
154
+ table (str): The name of the table.
155
+ catalog (Optional[str]): The catalog name. If None, uses configured default.
156
+ schema (Optional[str]): The schema name. If None, uses configured default.
157
+
158
+ Returns:
159
+ str: The CREATE TABLE statement for the specified table.
160
+
161
+ Raises:
162
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
163
+ """
164
+ catalog = catalog or self.config.catalog
165
+ schema = schema or self.config.schema
166
+ if not catalog or not schema:
167
+ raise CatalogSchemaError()
168
+ query = f"SHOW CREATE TABLE {catalog}.{schema}.{table}"
169
+ result = json.loads(self.execute_query(query))
170
+ return result[0]["Create Table"] if result else ""
171
+
172
+ def show_create_view(self, view: str, catalog: str | None = None, schema: str | None = None) -> str:
173
+ """Show the CREATE VIEW statement for a view.
174
+
175
+ Args:
176
+ view (str): The name of the view.
177
+ catalog (Optional[str]): The catalog name. If None, uses configured default.
178
+ schema (Optional[str]): The schema name. If None, uses configured default.
179
+
180
+ Returns:
181
+ str: The CREATE VIEW statement for the specified view.
182
+
183
+ Raises:
184
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
185
+ """
186
+ catalog = catalog or self.config.catalog
187
+ schema = schema or self.config.schema
188
+ if not catalog or not schema:
189
+ raise CatalogSchemaError()
190
+ query = f"SHOW CREATE VIEW {catalog}.{schema}.{view}"
191
+ result = json.loads(self.execute_query(query))
192
+ return result[0]["Create View"] if result else ""
193
+
194
+ def show_stats(self, table: str, catalog: str | None = None, schema: str | None = None) -> str:
195
+ """Show statistics for a table.
196
+
197
+ Args:
198
+ table (str): The name of the table.
199
+ catalog (Optional[str]): The catalog name. If None, uses configured default.
200
+ schema (Optional[str]): The schema name. If None, uses configured default.
201
+
202
+ Returns:
203
+ str: JSON-formatted string containing table statistics.
204
+
205
+ Raises:
206
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
207
+ """
208
+ catalog = catalog or self.config.catalog
209
+ schema = schema or self.config.schema
210
+ if not catalog or not schema:
211
+ raise CatalogSchemaError()
212
+ query = f"SHOW STATS FOR {catalog}.{schema}.{table}"
213
+ return self.execute_query(query)
214
+
215
+ def optimize(self, table: str, catalog: str | None = None, schema: str | None = None) -> str:
216
+ """Optimize an Iceberg table by compacting small files.
217
+
218
+ Args:
219
+ table (str): The name of the table to optimize.
220
+ catalog (Optional[str]): The catalog name. If None, uses configured default.
221
+ schema (Optional[str]): The schema name. If None, uses configured default.
222
+
223
+ Returns:
224
+ str: Success message indicating the table was optimized.
225
+
226
+ Raises:
227
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
228
+ """
229
+ catalog = catalog or self.config.catalog
230
+ schema = schema or self.config.schema
231
+ if not catalog or not schema:
232
+ raise CatalogSchemaError()
233
+ query = f"ALTER TABLE {catalog}.{schema}.{table} EXECUTE optimize"
234
+ self.execute_query(query)
235
+ return f"Table {catalog}.{schema}.{table} optimized successfully"
236
+
237
+ def optimize_manifests(self, table: str, catalog: str | None = None, schema: str | None = None) -> str:
238
+ """Optimize manifest files for an Iceberg table.
239
+
240
+ This operation reorganizes and compacts the table's manifest files for improved
241
+ performance.
242
+
243
+ Args:
244
+ table (str): The name of the table.
245
+ catalog (Optional[str]): The catalog name. If None, uses configured default.
246
+ schema (Optional[str]): The schema name. If None, uses configured default.
247
+
248
+ Returns:
249
+ str: Success message indicating the manifests were optimized.
250
+
251
+ Raises:
252
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
253
+ """
254
+ catalog = catalog or self.config.catalog
255
+ schema = schema or self.config.schema
256
+ if not catalog or not schema:
257
+ raise CatalogSchemaError()
258
+ query = f"ALTER TABLE {catalog}.{schema}.{table} EXECUTE optimize_manifests"
259
+ self.execute_query(query)
260
+ return f"Manifests for table {catalog}.{schema}.{table} optimized successfully"
261
+
262
+ def expire_snapshots(
263
+ self,
264
+ table: str,
265
+ retention_threshold: str = "7d",
266
+ catalog: str | None = None,
267
+ schema: str | None = None,
268
+ ) -> str:
269
+ """Remove old snapshots from an Iceberg table.
270
+
271
+ This operation removes snapshots older than the specified retention threshold,
272
+ helping to manage storage and improve performance.
273
+
274
+ Args:
275
+ table: The name of the table.
276
+ retention_threshold: Age threshold for snapshot removal (e.g., "7d").
277
+ catalog: The catalog name. If None, uses configured default.
278
+ schema: The schema name. If None, uses configured default.
279
+
280
+ Returns:
281
+ Success message indicating snapshots were expired.
282
+
283
+ Raises:
284
+ CatalogSchemaError: If either catalog or schema is not specified and not configured.
285
+ """
286
+ catalog = catalog or self.config.catalog
287
+ schema = schema or self.config.schema
288
+ if not catalog or not schema:
289
+ msg = "Both catalog and schema must be specified"
290
+ raise CatalogSchemaError(msg)
291
+ query = (
292
+ f"ALTER TABLE {catalog}.{schema}.{table} "
293
+ f"EXECUTE expire_snapshots(retention_threshold => '{retention_threshold}')"
294
+ )
295
+ self.execute_query(query)
296
+ return f"Snapshots older than {retention_threshold} expired for table {catalog}.{schema}.{table}"
297
+
298
+ def show_catalog_tree(self) -> str:
299
+ """Show a hierarchical tree view of all catalogs, schemas, and tables.
300
+
301
+ Returns:
302
+ A formatted string showing the catalog > schema > table hierarchy.
303
+ """
304
+ tree = []
305
+ catalogs = [row["Catalog"] for row in json.loads(self.execute_query("SHOW CATALOGS"))]
306
+ for catalog in sorted(catalogs):
307
+ tree.append(f"{catalog}")
308
+ try:
309
+ schemas = [row["Schema"] for row in json.loads(self.execute_query(f"SHOW SCHEMAS FROM {catalog}"))]
310
+ for schema in sorted(schemas):
311
+ tree.append(f"{schema}")
312
+ try:
313
+ tables = [
314
+ row["Table"]
315
+ for row in json.loads(self.execute_query(f"SHOW TABLES FROM {catalog}.{schema}"))
316
+ ]
317
+ tree.extend(f" {table}" for table in sorted(tables))
318
+ except (trino.dbapi.TrinoQueryError, KeyError):
319
+ tree.append(" Unable to list tables")
320
+ except (trino.dbapi.TrinoQueryError, KeyError):
321
+ tree.append("Unable to list schemas")
322
+ return "\n".join(tree) if tree else "No catalogs found"