mcp-trino-python 0.7.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.
src/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: trino.auth.BasicAuthentication | 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
+ )
src/server.py ADDED
@@ -0,0 +1,603 @@
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
+ from pydantic import Field
10
+
11
+ from config import load_config
12
+ from trino_client import TrinoClient
13
+
14
+ # Initialize the MCP server and Trino client
15
+ config = load_config()
16
+ client = TrinoClient(config)
17
+
18
+
19
+ # Initialize the MCP server with context
20
+ mcp = FastMCP(
21
+ name="Trino Explorer",
22
+ instructions="This Model Context Protocol (MCP) server provides access to Trino Query Engine.",
23
+ dependencies=["trino", "python-dotenv", "loguru"],
24
+ )
25
+
26
+
27
+ # Tools
28
+ @mcp.tool(description="List all available catalogs")
29
+ def show_catalogs() -> str:
30
+ """List all available catalogs."""
31
+ return client.list_catalogs()
32
+
33
+
34
+ @mcp.tool(description="List all schemas in a catalog")
35
+ def show_schemas(catalog: str = Field(description="The name of the catalog")) -> str:
36
+ """List all schemas in a catalog.
37
+
38
+ Args:
39
+ catalog: The name of the catalog
40
+
41
+ Returns:
42
+ str: List of schemas in the specified catalog
43
+ """
44
+ return client.list_schemas(catalog)
45
+
46
+
47
+ @mcp.tool(description="List all tables in a schema")
48
+ def show_tables(
49
+ catalog: str = Field(description="The name of the catalog"),
50
+ schema_name: str = Field(description="The name of the schema"),
51
+ ) -> str:
52
+ """List all tables in a schema.
53
+
54
+ Args:
55
+ catalog: The name of the catalog
56
+ schema_name: The name of the schema
57
+
58
+ Returns:
59
+ str: List of tables in the specified schema
60
+ """
61
+ return client.list_tables(catalog, schema_name)
62
+
63
+
64
+ @mcp.tool(description="Describe a table")
65
+ def describe_table(
66
+ catalog: str = Field(description="The catalog name"),
67
+ schema_name: str = Field(description="The schema name"),
68
+ table: str = Field(description="The name of the table"),
69
+ ) -> str:
70
+ """Describe a table.
71
+
72
+ Args:
73
+ catalog (str): The catalog name
74
+ schema_name (str): The schema name
75
+ table (str): The name of the table
76
+
77
+ Returns:
78
+ str: Table description in JSON format
79
+ """
80
+ return client.describe_table(catalog, schema_name, table)
81
+
82
+
83
+ @mcp.tool(description="Show the CREATE TABLE statement for a specific table")
84
+ def show_create_table(
85
+ catalog: str = Field(description="catalog name "),
86
+ schema_name: str = Field(description="schema name "),
87
+ table: str = Field(description="The name of the table"),
88
+ ) -> str:
89
+ """Show the CREATE TABLE statement for a table.
90
+
91
+ Args:
92
+ catalog: catalog name
93
+ schema_name: schema name
94
+ table: The name of the table
95
+
96
+ Returns:
97
+ str: The CREATE TABLE statement
98
+ """
99
+ return client.show_create_table(catalog, schema_name, table)
100
+
101
+
102
+ @mcp.tool(description="Show the CREATE VIEW statement for a specific view")
103
+ def show_create_view(
104
+ catalog: str = Field(description="catalog name "),
105
+ schema_name: str = Field(description="schema name "),
106
+ view: str = Field(description="The name of the view"),
107
+ ) -> str:
108
+ """Show the CREATE VIEW statement for a view.
109
+
110
+ Args:
111
+ catalog: catalog name
112
+ schema_name: schema name
113
+ view: The name of the view
114
+
115
+ Returns:
116
+ str: The CREATE VIEW statement
117
+ """
118
+ return client.show_create_view(catalog, schema_name, view)
119
+
120
+
121
+ @mcp.tool(description="Execute a SQL query and return results in a readable format")
122
+ def execute_query(query: str = Field(description="The SQL query to execute")) -> str:
123
+ """Execute a SQL query and return formatted results.
124
+
125
+ Args:
126
+ query: The SQL query to execute
127
+
128
+ Returns:
129
+ str: Query results formatted as a JSON string
130
+ """
131
+ return client.execute_query(query)
132
+
133
+
134
+ @mcp.tool(description="Optimize an Iceberg table's data files")
135
+ def optimize(
136
+ catalog: str = Field(description="catalog name "),
137
+ schema_name: str = Field(description="schema name "),
138
+ table: str = Field(description="The name of the table to optimize"),
139
+ ) -> str:
140
+ """Optimize an Iceberg table by compacting small files.
141
+
142
+ Args:
143
+ catalog: catalog name
144
+ schema_name: schema name
145
+ table: The name of the table to optimize
146
+
147
+ Returns:
148
+ str: Confirmation message
149
+ """
150
+ return client.optimize(catalog, schema_name, table)
151
+
152
+
153
+ @mcp.tool(description="Optimize manifest files for an Iceberg table")
154
+ def optimize_manifests(
155
+ catalog: str = Field(description="catalog name "),
156
+ schema_name: str = Field(description="schema name "),
157
+ table: str = Field(description="The name of the table"),
158
+ ) -> str:
159
+ """Optimize manifest files for an Iceberg table.
160
+
161
+ Args:
162
+ catalog: catalog name
163
+ schema_name: schema name
164
+ table: The name of the table
165
+
166
+ Returns:
167
+ str: Confirmation message
168
+ """
169
+ return client.optimize_manifests(catalog, schema_name, table)
170
+
171
+
172
+ @mcp.tool(description="Remove old snapshots from an Iceberg table")
173
+ def expire_snapshots(
174
+ catalog: str = Field(description="catalog name "),
175
+ schema_name: str = Field(description="schema name "),
176
+ retention_threshold: str = Field(
177
+ description="Age threshold for snapshot removal (e.g., '7d', '30d')", default="7d"
178
+ ),
179
+ table: str = Field(description="The name of the table"),
180
+ ) -> str:
181
+ """Remove old snapshots from an Iceberg table.
182
+
183
+ Args:
184
+ catalog: catalog name
185
+ schema_name: schema name
186
+ table: The name of the table
187
+ retention_threshold: Age threshold for snapshot removal (e.g., "7d", "30d")
188
+
189
+ Returns:
190
+ str: Confirmation message
191
+ """
192
+ return client.expire_snapshots(catalog, schema_name, table, retention_threshold)
193
+
194
+
195
+ @mcp.tool(description="Show statistics for a table")
196
+ def show_stats(
197
+ catalog: str = Field(description="catalog name "),
198
+ schema_name: str = Field(description="schema name "),
199
+ table: str = Field(description="The name of the table"),
200
+ ) -> str:
201
+ """Show statistics for a table.
202
+
203
+ Args:
204
+ catalog: catalog name
205
+ schema_name: schema name
206
+ table: The name of the table
207
+
208
+ Returns:
209
+ str: Table statistics in JSON format
210
+ """
211
+ return client.show_stats(catalog, schema_name, table)
212
+
213
+
214
+ @mcp.tool(name="show_query_history", description="Get the history of executed queries")
215
+ def show_query_history(
216
+ limit: int = Field(description="maximum number of history entries to return", default=None),
217
+ ) -> str:
218
+ """Get the history of executed queries.
219
+
220
+ Args:
221
+ limit: maximum number of history entries to return.
222
+ If None, returns all entries.
223
+
224
+ Returns:
225
+ str: JSON-formatted string containing query history.
226
+ """
227
+ return client.get_query_history(limit)
228
+
229
+
230
+ @mcp.tool(description="Show a hierarchical tree view of catalogs, schemas, and tables")
231
+ def show_catalog_tree() -> str:
232
+ """Get a hierarchical tree view showing the full structure of catalogs, schemas, and tables.
233
+
234
+ Returns:
235
+ str: A formatted string showing the catalog > schema > table hierarchy with visual indicators
236
+ """
237
+ return client.show_catalog_tree()
238
+
239
+
240
+ @mcp.tool(description="Show Iceberg table properties")
241
+ def show_table_properties(
242
+ catalog: str = Field(description="catalog name "),
243
+ schema_name: str = Field(description="schema name "),
244
+ table: str = Field(description="The name of the table"),
245
+ ) -> str:
246
+ """Show Iceberg table properties.
247
+
248
+ Args:
249
+ catalog: catalog name
250
+ schema_name: schema name
251
+ table: The name of the table
252
+
253
+ Returns:
254
+ str: JSON-formatted table properties
255
+ """
256
+ return client.show_table_properties(catalog, schema_name, table)
257
+
258
+
259
+ @mcp.tool(description="Show Iceberg table history/changelog")
260
+ def show_table_history(
261
+ catalog: str = Field(description="catalog name "),
262
+ schema_name: str = Field(description="schema name "),
263
+ table: str = Field(description="The name of the table"),
264
+ ) -> str:
265
+ """Show Iceberg table history/changelog.
266
+
267
+ The history contains:
268
+ - made_current_at: When snapshot became active
269
+ - snapshot_id: Identifier of the snapshot
270
+ - parent_id: Identifier of the parent snapshot
271
+ - is_current_ancestor: Whether snapshot is an ancestor of current
272
+
273
+ Args:
274
+ catalog: catalog name
275
+ schema_name: schema name
276
+ table: The name of the table
277
+
278
+ Returns:
279
+ str: JSON-formatted table history
280
+ """
281
+ return client.show_table_history(catalog, schema_name, table)
282
+
283
+
284
+ @mcp.tool(description="Show metadata for the table")
285
+ def show_metadata_log_entries(
286
+ catalog: str = Field(description="catalog name "),
287
+ schema_name: str = Field(description="schema name "),
288
+ table: str = Field(description="The name of the table"),
289
+ ) -> str:
290
+ """Show Iceberg table metadata log entries.
291
+
292
+ The metadata log contains:
293
+ - timestamp: When metadata was created
294
+ - file: Location of the metadata file
295
+ - latest_snapshot_id: ID of latest snapshot when metadata was updated
296
+ - latest_schema_id: ID of latest schema when metadata was updated
297
+ - latest_sequence_number: Data sequence number of metadata file
298
+
299
+ Args:
300
+ catalog: catalog name
301
+ schema_name: schema name
302
+ table: The name of the table
303
+
304
+ Returns:
305
+ str: JSON-formatted metadata log entries
306
+ """
307
+ return client.show_metadata_log_entries(catalog, schema_name, table)
308
+
309
+
310
+ @mcp.tool(description="Show Iceberg table snapshots")
311
+ def show_snapshots(
312
+ catalog: str = Field(description="catalog name "),
313
+ schema_name: str = Field(description="schema name "),
314
+ table: str = Field(description="The name of the table"),
315
+ ) -> str:
316
+ """Show Iceberg table snapshots.
317
+
318
+ The snapshots table contains:
319
+ - committed_at: When snapshot became active
320
+ - snapshot_id: Identifier for the snapshot
321
+ - parent_id: Identifier for the parent snapshot
322
+ - operation: Type of operation (append/replace/overwrite/delete)
323
+ - manifest_list: List of Avro manifest files
324
+ - summary: Summary of changes from previous snapshot
325
+
326
+ Args:
327
+ catalog: catalog name
328
+ schema_name: schema name
329
+ table: The name of the table
330
+
331
+ Returns:
332
+ str: JSON-formatted table snapshots
333
+ """
334
+ return client.show_snapshots(catalog, schema_name, table)
335
+
336
+
337
+ @mcp.tool(description="Show Iceberg table manifests")
338
+ def show_manifests(
339
+ catalog: str = Field(description="catalog name"),
340
+ schema_name: str = Field(description="schema name"),
341
+ table: str = Field(description="The name of the table"),
342
+ all_snapshots: bool = False,
343
+ ) -> str:
344
+ """Show Iceberg table manifests for current or all snapshots.
345
+
346
+ The manifests table contains:
347
+ - path: Manifest file location
348
+ - length: Manifest file length
349
+ - partition_spec_id: ID of partition spec used
350
+ - added_snapshot_id: ID of snapshot when manifest was added
351
+ - added_data_files_count: Number of data files with status ADDED
352
+ - added_rows_count: Total rows in ADDED files
353
+ - existing_data_files_count: Number of EXISTING files
354
+ - existing_rows_count: Total rows in EXISTING files
355
+ - deleted_data_files_count: Number of DELETED files
356
+ - deleted_rows_count: Total rows in DELETED files
357
+ - partition_summaries: Partition range metadata
358
+
359
+ Args:
360
+ catalog: catalog name
361
+ schema_name: schema name
362
+ table: The name of the table
363
+ all_snapshots: If True, show manifests from all snapshots
364
+
365
+ Returns:
366
+ str: JSON-formatted table manifests
367
+ """
368
+ return client.show_manifests(catalog, schema_name, table, all_snapshots)
369
+
370
+
371
+ @mcp.tool(description="Show Iceberg table partitions")
372
+ def show_partitions(
373
+ catalog: str = Field(description="catalog name "),
374
+ schema_name: str = Field(description="schema name "),
375
+ table: str = Field(description="The name of the table"),
376
+ ) -> str:
377
+ """Show Iceberg table partitions.
378
+
379
+ The partitions table contains:
380
+ - partition: Mapping of partition column names to values
381
+ - record_count: Number of records in partition
382
+ - file_count: Number of files in partition
383
+ - total_size: Total size of files in partition
384
+ - data: Partition range metadata with min/max values and null/nan counts
385
+
386
+ Args:
387
+ catalog: catalog name
388
+ schema_name: schema name
389
+ table: The name of the table
390
+
391
+ Returns:
392
+ str: JSON-formatted table partitions
393
+ """
394
+ return client.show_partitions(catalog, schema_name, table)
395
+
396
+
397
+ @mcp.tool(description="Show Iceberg table data files")
398
+ def show_files(
399
+ catalog: str = Field(description="catalog name "),
400
+ schema_name: str = Field(description="schema name "),
401
+ table: str = Field(description="The name of the table"),
402
+ ) -> str:
403
+ """Show Iceberg table data files in current snapshot.
404
+
405
+ The files table contains:
406
+ - content: Type of content (0=DATA, 1=POSITION_DELETES, 2=EQUALITY_DELETES)
407
+ - file_path: Data file location
408
+ - file_format: Format of the data file
409
+ - record_count: Number of records in file
410
+ - file_size_in_bytes: File size
411
+ - column_sizes: Column ID to size mapping
412
+ - value_counts: Column ID to value count mapping
413
+ - null_value_counts: Column ID to null count mapping
414
+ - nan_value_counts: Column ID to NaN count mapping
415
+ - lower_bounds: Column ID to lower bound mapping
416
+ - upper_bounds: Column ID to upper bound mapping
417
+ - key_metadata: Encryption key metadata
418
+ - split_offsets: Recommended split locations
419
+ - equality_ids: Field IDs for equality deletes
420
+
421
+ Args:
422
+ catalog: catalog name
423
+ schema_name: schema name
424
+ table: The name of the table
425
+
426
+ Returns:
427
+ str: JSON-formatted table files info
428
+ """
429
+ return client.show_files(catalog, schema_name, table)
430
+
431
+
432
+ @mcp.tool(description="Show Iceberg table manifest entries")
433
+ def show_entries(
434
+ catalog: str = Field(description="catalog name "),
435
+ schema_name: str = Field(description="schema name "),
436
+ table: str = Field(description="The name of the table"),
437
+ all_snapshots: bool = False,
438
+ ) -> str:
439
+ """Show Iceberg table manifest entries for current or all snapshots.
440
+
441
+ The entries table contains:
442
+ - status: Status of entry (0=EXISTING, 1=ADDED, 2=DELETED)
443
+ - snapshot_id: ID of the snapshot
444
+ - sequence_number: Data sequence number
445
+ - file_sequence_number: File sequence number
446
+ - data_file: File metadata including path, format, size etc
447
+ - readable_metrics: Human-readable file metrics
448
+
449
+ Args:
450
+ catalog: catalog name
451
+ schema_name: schema name
452
+ table: The name of the table
453
+ all_snapshots: If True, show entries from all snapshots
454
+
455
+ Returns:
456
+ str: JSON-formatted manifest entries
457
+ """
458
+ return client.show_entries(catalog, schema_name, table, all_snapshots)
459
+
460
+
461
+ @mcp.tool(description="Show Iceberg table references (branches and tags)")
462
+ def show_refs(
463
+ catalog: str = Field(description="catalog name "),
464
+ schema_name: str = Field(description="schema name "),
465
+ table: str = Field(description="The name of the table"),
466
+ ) -> str:
467
+ """Show Iceberg table references (branches and tags).
468
+
469
+ The refs table contains:
470
+ - name: Name of the reference
471
+ - type: Type of reference (BRANCH or TAG)
472
+ - snapshot_id: ID of referenced snapshot
473
+ - max_reference_age_in_ms: Max age before reference expiry
474
+ - min_snapshots_to_keep: Min snapshots to keep (branches only)
475
+ - max_snapshot_age_in_ms: Max snapshot age in branch
476
+
477
+ Args:
478
+ catalog: catalog name
479
+ schema_name: schema name
480
+ table: The name of the table
481
+
482
+ Returns:
483
+ str: JSON-formatted table references
484
+ """
485
+ return client.show_refs(catalog, schema_name, table)
486
+
487
+
488
+ # Prompts
489
+ @mcp.prompt(title="Explore Trino Data")
490
+ def explore_data(catalog: str, schema_name: str) -> list[base.Message]:
491
+ """Interactive prompt to explore Trino data.
492
+
493
+ Args:
494
+ catalog: The name of the catalog to explore
495
+ schema_name: The name of the schema to explore
496
+
497
+ Returns:
498
+ list[base.Message]: A list of messages to guide the conversation
499
+ """
500
+ messages = [
501
+ base.AssistantMessage(
502
+ "I'll help you explore data in Trino. I can show you available catalogs, "
503
+ "schemas, and tables, and help you query the data."
504
+ )
505
+ ]
506
+
507
+ if catalog and schema_name:
508
+ messages.append(
509
+ base.UserMessage(
510
+ f"Show me what tables are available in the {catalog}.{schema_name} schema and help me query them."
511
+ )
512
+ )
513
+ elif catalog:
514
+ messages.append(base.UserMessage(f"Show me what schemas are available in the {catalog} catalog."))
515
+ else:
516
+ messages.append(base.UserMessage("Show me what catalogs are available."))
517
+
518
+ return messages
519
+
520
+
521
+ @mcp.prompt(title="Maintain Iceberg Table")
522
+ def maintain_iceberg(table: str, catalog: str, schema_name: str) -> list[base.Message]:
523
+ """Interactive prompt for Iceberg table maintenance."""
524
+ return [
525
+ base.AssistantMessage(
526
+ "I'll help you maintain an Iceberg table. I can help with optimization, "
527
+ "cleaning up snapshots and orphan files, and viewing table metadata."
528
+ ),
529
+ base.UserMessage(
530
+ f"What maintenance operations should we perform on the Iceberg table "
531
+ f"{catalog + '.' if catalog else ''}{schema_name + '.' if schema_name else ''}{table}?"
532
+ ),
533
+ ]
534
+
535
+
536
+ if __name__ == "__main__":
537
+ import argparse
538
+ import sys
539
+
540
+ from loguru import logger
541
+
542
+ # Configure logging
543
+ logger.remove()
544
+ logger.add(sys.stderr, level="INFO", format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
545
+
546
+ parser = argparse.ArgumentParser(
547
+ description="MCP Trino Server - Model Context Protocol connector for Trino",
548
+ formatter_class=argparse.RawDescriptionHelpFormatter,
549
+ epilog="""
550
+ Transport modes:
551
+ stdio Standard I/O (default) - for local MCP clients like VS Code
552
+ streamable-http HTTP with streaming support (recommended for remote/web access)
553
+ sse Server-Sent Events (legacy HTTP transport)
554
+
555
+ Examples:
556
+ # Run with stdio (default, for VS Code integration)
557
+ python server.py
558
+
559
+ # Run with Streamable HTTP on port 8000
560
+ python server.py --transport streamable-http --host 0.0.0.0 --port 8000
561
+
562
+ # Run with SSE transport
563
+ python server.py --transport sse --host 127.0.0.1 --port 8001
564
+ """,
565
+ )
566
+ parser.add_argument(
567
+ "--host",
568
+ default="127.0.0.1",
569
+ help="Host to bind to (default: 127.0.0.1, use 0.0.0.0 for all interfaces)",
570
+ )
571
+ parser.add_argument(
572
+ "--port",
573
+ type=int,
574
+ default=8000,
575
+ help="Port to listen on (default: 8000)",
576
+ )
577
+ parser.add_argument(
578
+ "--transport",
579
+ choices=["stdio", "streamable-http", "sse"],
580
+ default="stdio",
581
+ help="Transport type (default: stdio)",
582
+ )
583
+ args = parser.parse_args()
584
+
585
+ logger.info(f"Starting Trino MCP server with {args.transport} transport")
586
+
587
+ if args.transport == "stdio":
588
+ logger.info("Using stdio transport for local MCP communication")
589
+ mcp.run(transport="stdio")
590
+ elif args.transport == "streamable-http":
591
+ logger.info(f"Starting Streamable HTTP server on http://{args.host}:{args.port}/mcp")
592
+ mcp.run(transport="streamable-http", host=args.host, port=args.port)
593
+ elif args.transport == "sse":
594
+ logger.info(f"Starting SSE server on http://{args.host}:{args.port}/sse")
595
+ mcp.run(transport="sse", host=args.host, port=args.port)
596
+
597
+
598
+ def main():
599
+ """Entry point for the MCP Trino server."""
600
+ import sys
601
+
602
+ sys.argv = sys.argv[:1] # Reset args for mcp.run
603
+ mcp.run(transport="stdio")