Documentation
¶
Overview ¶
Package trino provides a Trino toolkit adapter for the MCP data platform.
Package trino provides a Trino toolkit adapter for the MCP data platform.
Package trino provides a Trino toolkit adapter for the MCP data platform.
Index ¶
- Constants
- Variables
- type AnnotationConfig
- type Config
- type ConnectionDescription
- type ConnectionRequiredMiddleware
- type ConnectionStore
- type CostEstimationConfig
- type ElicitationConfig
- type ElicitationDeclinedError
- type ElicitationMiddleware
- type ErrorSanitizerMiddleware
- type ExportAsset
- type ExportAssetRef
- type ExportAssetStore
- type ExportConfig
- type ExportDeps
- type ExportProvenance
- type ExportProvenanceCall
- type ExportS3Client
- type ExportShareCreator
- type ExportUserContext
- type ExportVersion
- type ExportVersionStore
- type Formatter
- type LocationInterceptor
- type MultiConfig
- type PIIConsentConfig
- type ProgressInjector
- type ReadOnlyInterceptor
- func (i *ReadOnlyInterceptor) AcceptsWrites(conn string) bool
- func (*ReadOnlyInterceptor) After(_ context.Context, _ *trinotools.ToolContext, result *mcp.CallToolResult, ...) (*mcp.CallToolResult, error)
- func (i *ReadOnlyInterceptor) Before(ctx context.Context, tc *trinotools.ToolContext) (context.Context, error)
- func (i *ReadOnlyInterceptor) ForgetConnection(name string)
- func (i *ReadOnlyInterceptor) Intercept(ctx context.Context, sql string, _ trinotools.ToolName) (string, error)
- func (i *ReadOnlyInterceptor) SetConnection(name string, readOnly bool)
- type SchemaTable
- type ScratchConfig
- type Toolkit
- func (t *Toolkit) AcceptsWrites(connection string) bool
- func (t *Toolkit) AddConnection(name string, config map[string]any) error
- func (*Toolkit) AnswerContracts() []toolkit.AnswerContract
- func (t *Toolkit) Close() error
- func (t *Toolkit) Config() Config
- func (t *Toolkit) Connection() string
- func (t *Toolkit) ConsentMiddleware() mcp.Middleware
- func (t *Toolkit) Exec(ctx context.Context, connection, sql string) error
- func (t *Toolkit) FitResult(tool string, args json.RawMessage, res *mcp.CallToolResult, budget int) bool
- func (t *Toolkit) HasConnection(name string) bool
- func (*Toolkit) Kind() string
- func (t *Toolkit) ListConnections() []toolkit.ConnectionDetail
- func (t *Toolkit) ListTables(ctx context.Context, connection, catalog, schema string) ([]SchemaTable, bool, error)
- func (t *Toolkit) Manager() *multiserver.Manager
- func (t *Toolkit) Name() string
- func (t *Toolkit) ProbeConnection(ctx context.Context, name string) connprobe.Result
- func (t *Toolkit) Query(ctx context.Context, connection, sql string, opts trinoclient.QueryOptions) (*trinoclient.QueryResult, error)
- func (t *Toolkit) QueryLimits() (defaultRows, maxRows int, timeout time.Duration)
- func (t *Toolkit) RegisterTools(s *mcp.Server)
- func (t *Toolkit) RemoveConnection(name string) error
- func (t *Toolkit) ScratchConnections() []string
- func (t *Toolkit) ScratchTarget(connection string) (ScratchConfig, bool)
- func (t *Toolkit) ServesConnection(ctx context.Context, name string) bool
- func (t *Toolkit) SetConnectionStore(s ConnectionStore)
- func (t *Toolkit) SetExportDeps(deps ExportDeps)
- func (t *Toolkit) SetMetrics(m *observability.Metrics)
- func (t *Toolkit) SetQueryProvider(provider query.Provider)
- func (t *Toolkit) SetSemanticProvider(provider semantic.Provider)
- func (t *Toolkit) TableExists(ctx context.Context, connection, catalog, schema, table string) (bool, error)
- func (t *Toolkit) TableLocation(ctx context.Context, connection, catalog, schema, table string) (location string, found bool, err error)
- func (t *Toolkit) Tools() []string
- func (t *Toolkit) ValidateConnection(name string, config map[string]any) error
- type TypedFormatter
Constants ¶
const ConfigSchemaJSON = `` /* 2910-byte string literal not displayed */
ConfigSchemaJSON declares what a trino connection's config takes.
A connection stored through the admin API is a freeform object on the wire, so until this existed the only way to learn a key's name was to read a deployment's configuration file — which an operator with no cluster access cannot do, and which is how a connection came to be created with values that could never work (#1805). It is a declaration, not a gate: a key not named here is stored and ignored, which the discovery endpoint says plainly.
const MaxRowsKey = "portal.export.max_rows"
MaxRowsKey is the configuration key of the deployment's export row cap, named wherever the cap is: the tool description, a cut's report, platform_info.
Variables ¶
var ErrConnectionNotFound = errors.New("trino connection not found")
ErrConnectionNotFound is what a ConnectionStore reports for a name it does not hold.
var ErrConnectionRefused = errors.New("trino connection refused")
ErrConnectionRefused wraps every connection the Trino client refuses to open, so a caller can tell a configuration the client will never accept from a transient failure.
var SecretKeys = []string{"password"}
SecretKeys are the configuration keys a trino connection may name a stored secret in as {{secret:<name>}} (#1806). The value is read as the connection's client is built.
Functions ¶
This section is empty.
Types ¶
type AnnotationConfig ¶ added in v0.20.0
type AnnotationConfig = toolkit.AnnotationConfig
AnnotationConfig holds tool annotation overrides from configuration.
type Config ¶
type Config struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
User string `yaml:"user"`
Password string `yaml:"password"` // #nosec G117 -- Trino credential from admin YAML config
Catalog string `yaml:"catalog"`
Schema string `yaml:"schema"`
// SSL and SSLVerify are tri-state: nil means the key was absent, which is
// what lets a non-default connection say plain HTTP. The multiserver
// manager reads a nil SSL as "auto-detect from the host", and its
// auto-detect turns HTTPS on for any host that is not localhost, so a
// connection that set `ssl: false` has to be distinguishable from one that
// never mentioned SSL. Read them through IsSSLEnabled and
// IsSSLVerifyEnabled, which supply the primary connection's defaults:
// SSL off, verification on.
SSL *bool `yaml:"ssl"`
SSLVerify *bool `yaml:"ssl_verify"`
Timeout time.Duration `yaml:"timeout"`
DefaultLimit int `yaml:"default_limit"`
MaxLimit int `yaml:"max_limit"`
ReadOnly bool `yaml:"read_only"`
// ConnectionName is accepted for compatibility and has no effect. The
// platform identifies a Trino connection by its instance name, which is
// what the manager routes on and what Connection() reports (#1396).
ConnectionName string `yaml:"connection_name"`
Description string `yaml:"description"` // Human-readable description of this connection's purpose
Titles map[string]string `yaml:"titles"`
Descriptions map[string]string `yaml:"descriptions"`
Annotations map[string]AnnotationConfig `yaml:"annotations"`
// ProgressEnabled enables progress notifications for query execution.
// Injected by the platform from progress.enabled config.
ProgressEnabled bool `yaml:"progress_enabled"`
// Elicitation configures user confirmation for expensive operations.
// Injected by the platform from elicitation config.
Elicitation ElicitationConfig `yaml:"elicitation"`
// Scratch names the catalog and schema table registrations are written
// into on this connection. Unset means registration is unavailable here.
Scratch ScratchConfig `yaml:"scratch"`
}
Config holds Trino toolkit configuration.
func ParseConfig ¶
ParseConfig parses a Trino toolkit configuration from a map.
func (Config) IsSSLEnabled ¶ added in v1.125.2
IsSSLEnabled reports whether this connection speaks HTTPS. A config that never mentioned SSL is plain HTTP, which is what the field has always meant on the primary connection.
func (Config) IsSSLVerifyEnabled ¶ added in v1.125.2
IsSSLVerifyEnabled reports whether certificate verification is on, defaulting to true when the config did not say.
type ConnectionDescription ¶ added in v0.26.0
ConnectionDescription holds display information about a connection for error messages when the connection parameter is missing.
type ConnectionRequiredMiddleware ¶ added in v0.26.0
type ConnectionRequiredMiddleware struct {
// contains filtered or unexported fields
}
ConnectionRequiredMiddleware rejects tool calls that omit the connection parameter when multiple Trino connections are configured. The error message lists all available connections with their descriptions so the LLM can choose the correct one.
func NewConnectionRequiredMiddleware ¶ added in v0.26.0
func NewConnectionRequiredMiddleware(connections []ConnectionDescription) *ConnectionRequiredMiddleware
NewConnectionRequiredMiddleware creates a middleware that enforces explicit connection selection. The connections slice describes all available backends.
func (*ConnectionRequiredMiddleware) After ¶ added in v0.26.0
func (*ConnectionRequiredMiddleware) After( _ context.Context, _ *trinotools.ToolContext, result *mcp.CallToolResult, handlerErr error, ) (*mcp.CallToolResult, error)
After is a no-op — validation happens before execution.
func (*ConnectionRequiredMiddleware) Before ¶ added in v0.26.0
func (m *ConnectionRequiredMiddleware) Before(ctx context.Context, tc *trinotools.ToolContext) (context.Context, error)
Before checks that the connection parameter is set for tools that need it.
type ConnectionStore ¶ added in v1.149.0
type ConnectionStore interface {
// GetConnection returns the stored configuration of one connection,
// reporting a name it does not hold with an error satisfying
// ErrConnectionNotFound.
GetConnection(ctx context.Context, name string) (map[string]any, error)
}
ConnectionStore reads the connections an operator saved. The platform wires its database-backed store; a deployment that keeps connections in its configuration file alone wires none and serves what it was handed.
type CostEstimationConfig ¶ added in v0.21.0
type CostEstimationConfig struct {
Enabled bool `yaml:"enabled"`
RowThreshold int64 `yaml:"row_threshold"`
}
CostEstimationConfig configures query cost estimation.
type ElicitationConfig ¶ added in v0.21.0
type ElicitationConfig struct {
// Enabled is the master switch for all elicitation features.
Enabled bool `yaml:"enabled"`
// CostEstimation configures query cost estimation and confirmation.
CostEstimation CostEstimationConfig `yaml:"cost_estimation"`
// PIIConsent configures PII access consent.
PIIConsent PIIConsentConfig `yaml:"pii_consent"`
}
ElicitationConfig configures elicitation triggers for the Trino toolkit.
type ElicitationDeclinedError ¶ added in v0.21.0
ElicitationDeclinedError is a confirmation prompt (cost estimation, PII consent) that did not come back accepted. Unanswered tells the two ways apart (#2586): the person declined, or nobody answered (the client canceled or gave up waiting), which is not a person saying no and is recorded under its own category.
func (*ElicitationDeclinedError) Error ¶ added in v0.21.0
func (e *ElicitationDeclinedError) Error() string
func (*ElicitationDeclinedError) ErrorCategory ¶ added in v0.21.0
func (e *ElicitationDeclinedError) ErrorCategory() string
ErrorCategory implements middleware.CategorizedError.
type ElicitationMiddleware ¶ added in v0.21.0
type ElicitationMiddleware struct {
// contains filtered or unexported fields
}
ElicitationMiddleware intercepts Trino query execution to request user confirmation when queries exceed cost thresholds or access PII data. The platform installs Middleware in its tools/call chain.
Each connection carries its own settings (the platform injects them into every instance, and an instance's own elicitation block wins), and the estimate's EXPLAIN runs on the connection the call names. The toolkit keeps both current as connections are added and removed (#2052: the middleware used to be built only by the single-connection constructor the platform never called, so neither prompt ever ran).
func (*ElicitationMiddleware) ForgetConnection ¶ added in v1.143.0
func (em *ElicitationMiddleware) ForgetConnection(name string)
ForgetConnection drops a removed connection's settings.
func (*ElicitationMiddleware) Middleware ¶ added in v1.143.0
func (em *ElicitationMiddleware) Middleware() mcp.Middleware
Middleware is the receiving middleware that puts the prompts in front of a trino_query (#2052). It runs as a tools/call layer rather than inside the mcp-trino toolkit because a client on 2026-07-28 is asked by returning input requests from the call and answering its retry, which a toolkit middleware can neither return nor read. An older client is asked in band, as before. The platform places it inside authorization and the gates, so a call nobody may make is never estimated or prompted for.
func (*ElicitationMiddleware) SetConnection ¶ added in v1.143.0
func (em *ElicitationMiddleware) SetConnection(name string, cfg ElicitationConfig)
SetConnection records the elicitation settings of a connection added or replaced at runtime.
func (*ElicitationMiddleware) SetSemanticProvider ¶ added in v0.21.0
func (em *ElicitationMiddleware) SetSemanticProvider(p semantic.Provider)
SetSemanticProvider updates the semantic provider (called after toolkit init).
type ErrorSanitizerMiddleware ¶ added in v1.96.0
type ErrorSanitizerMiddleware struct{}
ErrorSanitizerMiddleware scrubs internal topology from upstream engine errors before they reach tool callers. The full original error is logged at debug level for operators.
func (*ErrorSanitizerMiddleware) After ¶ added in v1.96.0
func (*ErrorSanitizerMiddleware) After(_ context.Context, tc *trinotools.ToolContext, result *mcp.CallToolResult, handlerErr error) (*mcp.CallToolResult, error)
After sanitizes the handler error and any error-result text.
func (*ErrorSanitizerMiddleware) Before ¶ added in v1.96.0
func (*ErrorSanitizerMiddleware) Before(ctx context.Context, _ *trinotools.ToolContext) (context.Context, error)
Before implements trinotools.ToolMiddleware; it passes through unchanged.
type ExportAsset ¶ added in v1.56.0
type ExportAsset struct {
ID string
OwnerID string
OwnerEmail string
Name string
Description string
ContentType string
S3Bucket string
S3Key string
SizeBytes int64
Tags []string
Provenance ExportProvenance
SessionID string
IdempotencyKey string
// VersionMetadata is what the export records about its content on the
// version written with the asset (#2057): the cut, nil for a complete
// result. The asset takes it from that version.
VersionMetadata map[string]any
}
ExportAsset is the asset data needed for insert.
type ExportAssetRef ¶ added in v1.56.0
type ExportAssetRef struct {
ID string
SizeBytes int64
// Metadata is the asset's metadata, which records whether the export
// that wrote it was cut (#2057).
Metadata map[string]any
}
ExportAssetRef is returned by idempotency key lookup.
type ExportAssetStore ¶ added in v1.56.0
type ExportAssetStore interface {
InsertExportAsset(ctx context.Context, asset ExportAsset) error
GetByIdempotencyKey(ctx context.Context, ownerID, key string) (*ExportAssetRef, error)
}
ExportAssetStore is the subset of portal.AssetStore needed by trino_export. Defined here to avoid import cycles (portal → registry → trino).
type ExportConfig ¶ added in v1.56.0
type ExportConfig struct {
MaxRows int `yaml:"max_rows"`
MaxBytes int64 `yaml:"max_bytes"`
DefaultTimeout time.Duration `yaml:"default_timeout"`
MaxTimeout time.Duration `yaml:"max_timeout"`
}
ExportConfig holds configuration for the trino_export tool.
func ResolveExportConfig ¶ added in v1.142.0
func ResolveExportConfig(cfg ExportConfig) ExportConfig
ResolveExportConfig is cfg with the defaults trino_export applies filled in, for a reader that reports the limits the tool runs under (platform_info, #2057).
type ExportDeps ¶ added in v1.56.0
type ExportDeps struct {
AssetStore ExportAssetStore
VersionStore ExportVersionStore
S3Client ExportS3Client
// ResourceLander lands a result in a managed resource by path instead of in
// a new asset (#1663). nil leaves the asset destination the only one, which
// is what a deployment with no managed-resource library has.
ResourceLander toolkit.ResourceLander
S3Bucket string
S3Prefix string
BaseURL string
Config ExportConfig
// GetUserContext extracts user identity from the request context.
// Injected by the platform to avoid importing middleware.
GetUserContext func(ctx context.Context) *ExportUserContext
}
ExportDeps holds portal-side dependencies injected into the Trino toolkit. All types are defined locally to avoid import cycles (portal → registry → trino).
type ExportProvenance ¶ added in v1.56.0
type ExportProvenance struct {
ToolCalls []ExportProvenanceCall
SessionID string
UserID string
}
ExportProvenance records provenance for an exported asset.
type ExportProvenanceCall ¶ added in v1.56.0
ExportProvenanceCall represents a tool call in the provenance chain.
type ExportS3Client ¶ added in v1.56.0
type ExportS3Client interface {
PutObject(ctx context.Context, bucket, key string, data []byte, contentType string) error
// DeleteObject removes an uploaded export no row came to name (#1903).
DeleteObject(ctx context.Context, bucket, key string) error
}
ExportS3Client is the subset of portal.S3Client needed by trino_export.
type ExportShareCreator ¶ added in v1.56.0
type ExportShareCreator interface {
}
ExportShareCreator creates public share links for exported assets.
type ExportUserContext ¶ added in v1.56.0
type ExportUserContext struct {
UserID string
UserEmail string
SessionID string
// RunOutputKey, set when a managed-script run made the call, turns the
// export's name into the script's output identity, so a named export
// inside a run writes the next version of one asset (#1854). Nil
// otherwise.
RunOutputKey func(name string) string
}
ExportUserContext holds user identity extracted from the request context.
type ExportVersion ¶ added in v1.56.0
type ExportVersion struct {
ID string
AssetID string
S3Key string
S3Bucket string
ContentType string
SizeBytes int64
CreatedBy string
ChangeSummary string
// Metadata records a cut export on the version, and through it on the
// asset (#2057). Nil for a complete one.
Metadata map[string]any
}
ExportVersion is the version data for creating a new version.
type ExportVersionStore ¶ added in v1.56.0
type ExportVersionStore interface {
CreateExportVersion(ctx context.Context, version ExportVersion) (int, error)
}
ExportVersionStore is the subset of portal.VersionStore needed by trino_export.
type Formatter ¶ added in v1.56.0
type Formatter interface {
// Format serializes columns and rows into the target format.
Format(columns []string, rows [][]any) ([]byte, error)
// ContentType returns the MIME type for the formatted output.
ContentType() string
// FileExtension returns the file extension (including dot) for the format.
FileExtension() string
}
Formatter converts query results into a specific output format.
func NewFormatter ¶ added in v1.121.0
NewFormatter returns a Formatter for the given format name. Supported formats: csv, json, jsonl, markdown, parquet, text.
It is exported because trino_export is not the only writer of these formats: a managed script's platform.export writes the same four from rows it computed itself, and it writes them with this implementation rather than a second one that would drift. The format an author sees in a draft preview is therefore byte-for-byte the format a platform run persists.
type LocationInterceptor ¶ added in v1.159.0
type LocationInterceptor struct{}
LocationInterceptor refuses, in every SQL a person sends through the Trino tools, a statement that points a table, a schema or a partition at one of the platform's own buckets (#2616). A catalog that registers tables over managed resources holds credentials that reach the resource bucket by design, so an external table a person creates over another library's prefix reads it whatever the S3 tools refuse.
A location the check cannot read is refused too: a location property or a procedure argument assembled from parts (concat, ||, a cast, a Unicode escape string) and a table that copies another's properties. The platform's own registrations run through Toolkit.Exec, which runs no query interceptor, so they are unaffected.
func (LocationInterceptor) Intercept ¶ added in v1.159.0
func (LocationInterceptor) Intercept(_ context.Context, sql string, _ trinotools.ToolName) (string, error)
Intercept refuses the statement when it reaches a platform bucket or names a location the check cannot read.
type MultiConfig ¶ added in v0.26.0
type MultiConfig struct {
// DefaultConnection is the name of the default connection.
DefaultConnection string
// Instances maps connection names to their parsed configurations.
Instances map[string]Config
}
MultiConfig holds configuration for a multi-connection Trino toolkit.
func ParseMultiConfig ¶ added in v0.26.0
ParseMultiConfig builds a MultiConfig from the aggregate factory's instance map.
func (MultiConfig) Refused ¶ added in v1.139.0
func (mc MultiConfig) Refused() map[string]error
Refused reports, by connection name, each connection the Trino client would refuse to open, judged on the settings the client is built from. Nil when it would open every one.
func (MultiConfig) Validate ¶ added in v1.139.0
func (mc MultiConfig) Validate() error
Validate reports every connection the Trino client would refuse to open, all of them at once (#2014).
The client validates a connection's settings when it is built, and since mcp-trino v1.6.0 that includes refusing a password over plain HTTP. The refusal used to surface only when the server was constructed, after the database had already been migrated, which left a deployment that could run neither the new release nor the one before it. Validate runs the client's own check over each connection's effective settings, the ones the client is built from (a connection inherits what it leaves unset from the default connection), so a caller can refuse the configuration before anything is changed.
type PIIConsentConfig ¶ added in v0.21.0
type PIIConsentConfig struct {
Enabled bool `yaml:"enabled"`
}
PIIConsentConfig configures PII access consent.
type ProgressInjector ¶ added in v0.20.0
type ProgressInjector struct{}
ProgressInjector is a trinotools.ToolMiddleware that creates an mcpProgressNotifier per-request from the ServerSession and progress token stored in context by MCPToolCallMiddleware.
func (*ProgressInjector) After ¶ added in v0.20.0
func (*ProgressInjector) After( _ context.Context, _ *trinotools.ToolContext, result *mcp.CallToolResult, handlerErr error, ) (*mcp.CallToolResult, error)
After is a no-op — progress notifications are sent during tool execution, not after.
func (*ProgressInjector) Before ¶ added in v0.20.0
func (*ProgressInjector) Before(ctx context.Context, _ *trinotools.ToolContext) (context.Context, error)
Before reads the server session and progress token from context and, if both are present, creates an mcpProgressNotifier and stores it in context via trinotools.WithProgressNotifier.
type ReadOnlyInterceptor ¶ added in v0.2.0
type ReadOnlyInterceptor struct {
// contains filtered or unexported fields
}
ReadOnlyInterceptor blocks write operations on read-only connections. It delegates write detection to the upstream mcp-trino IsWriteSQL function.
A multi-connection toolkit routes every one of its connections through a single interceptor, so the decision is per connection: Before records the connection the call named — or the default connection, when it named none, matching multiserver.Manager.Client("") — on the context, and Intercept rejects write SQL unless that connection is configured write-capable. Such an interceptor therefore registers as both a query interceptor and a tool middleware; with only the interceptor registered no connection resolves and every write is refused, so a wiring mistake closes the door rather than opening it.
A nil readOnly map means every connection is read-only unconditionally. That is the single-connection case, where the connection argument selects nothing, and trino_export, which is SELECT-only whatever the deployment configures.
func NewConnectionReadOnlyInterceptor ¶ added in v1.120.1
func NewConnectionReadOnlyInterceptor(defaultConn string, readOnly map[string]bool) *ReadOnlyInterceptor
NewConnectionReadOnlyInterceptor creates a query interceptor that rejects write SQL only on the connections whose readOnly entry is true. defaultConn names the connection a call that omits the connection argument resolves to.
func NewReadOnlyInterceptor ¶ added in v0.2.0
func NewReadOnlyInterceptor() *ReadOnlyInterceptor
NewReadOnlyInterceptor creates a query interceptor that rejects write SQL on every connection.
func (*ReadOnlyInterceptor) AcceptsWrites ¶ added in v1.126.0
func (i *ReadOnlyInterceptor) AcceptsWrites(conn string) bool
AcceptsWrites reports whether a named connection may run write SQL, asked ahead of time rather than from inside a call.
It is checkWritable's question with the connection supplied instead of resolved from the context, and it answers identically: an interceptor with no per-connection settings refuses, a name it holds no setting for is not one the toolkit routes to and refuses, and a connection marked read-only refuses. A surface that offers a connection has to reach the same answer this will reach when the statement runs, or it offers a choice the write then refuses.
func (*ReadOnlyInterceptor) After ¶ added in v1.120.1
func (*ReadOnlyInterceptor) After( _ context.Context, _ *trinotools.ToolContext, result *mcp.CallToolResult, handlerErr error, ) (*mcp.CallToolResult, error)
After is a no-op — enforcement happens in Intercept, before execution.
func (*ReadOnlyInterceptor) Before ¶ added in v1.120.1
func (i *ReadOnlyInterceptor) Before(ctx context.Context, tc *trinotools.ToolContext) (context.Context, error)
Before records the connection this tool call is bound for so Intercept can apply that connection's read-only setting.
func (*ReadOnlyInterceptor) ForgetConnection ¶ added in v1.120.1
func (i *ReadOnlyInterceptor) ForgetConnection(name string)
ForgetConnection drops a removed connection's read-only setting.
func (*ReadOnlyInterceptor) Intercept ¶ added in v0.2.0
func (i *ReadOnlyInterceptor) Intercept(ctx context.Context, sql string, _ trinotools.ToolName) (string, error)
Intercept checks if the query is a write operation and blocks it when the connection it is bound for may not accept writes.
func (*ReadOnlyInterceptor) SetConnection ¶ added in v1.120.1
func (i *ReadOnlyInterceptor) SetConnection(name string, readOnly bool)
SetConnection records whether a connection added at runtime is read-only. A no-op on the unconditional interceptor, where every connection already is.
type SchemaTable ¶ added in v1.146.1
type SchemaTable struct {
Name string
// View is true for a view, which has no location of its own.
View bool
}
SchemaTable is one table or view a schema holds, as information_schema names it.
type ScratchConfig ¶ added in v1.125.0
type ScratchConfig struct {
Catalog string `yaml:"catalog"`
Schema string `yaml:"schema"`
// StatementTimeout bounds each statement Exec runs on the connection, in
// place of the connection's query timeout. Zero leaves the connection's.
// A CREATE TABLE on a Hive catalog with a file metastore over slow object
// storage can take longer than the query that wrote the file, and a
// deadline that expires while the coordinator goes on to create the table
// leaves a table the platform has no record of (#2131).
StatementTimeout time.Duration `yaml:"statement_timeout"`
}
ScratchConfig names where a table registration writes on a connection.
It is a target, not a boundary: the platform's read_only flag is a statement-prefix denylist and nothing in this toolkit restricts a catalog or schema, so what keeps a registration off the warehouse is the Trino identity the connection authenticates as, not these two fields.
func (ScratchConfig) Configured ¶ added in v1.125.0
func (s ScratchConfig) Configured() bool
Configured reports whether this target names somewhere to write.
type Toolkit ¶
type Toolkit struct {
// contains filtered or unexported fields
}
Toolkit wraps mcp-trino toolkit for the platform.
func NewMulti ¶ added in v0.26.0
func NewMulti(cfg MultiConfig) (*Toolkit, error)
NewMulti creates a multi-connection Trino toolkit that routes requests to the correct backend based on the "connection" parameter in each tool call. This replaces the previous pattern of creating N separate single-client toolkits that would clobber each other's tool registrations.
func (*Toolkit) AcceptsWrites ¶ added in v1.126.0
AcceptsWrites reports whether Exec would be allowed to run write SQL on a connection, without running any.
It mirrors checkExecWritable exactly, including the two asymmetries that are easy to get backwards: a toolkit with no interceptor at all is a single-connection toolkit that was not configured read-only, so writes are ALLOWED; and an empty connection name resolves to the default, as it does everywhere else here.
It exists so a surface can decline to offer a connection whose registration would be refused at DDL time. A form offering a connection the registration then refuses is the same defect as a registration refusing a connection the form offered.
func (*Toolkit) AddConnection ¶ added in v1.48.0
AddConnection adds a named connection at runtime. Requires multi-connection mode (created via NewMulti).
func (*Toolkit) AnswerContracts ¶ added in v1.138.0
func (*Toolkit) AnswerContracts() []toolkit.AnswerContract
AnswerContracts is what trino_execute always answers when it answers JSON (#1953): the body a managed script's test is held to when it declares the answer a write statement gets.
func (*Toolkit) Connection ¶ added in v0.12.1
Connection returns the name a tool call binds when it names none: the identity audit records it under, a persona's connection rules match, and the connection source map is keyed by.
That name is the instance name in both modes. The multi-connection manager routes by instance, and this toolkit reports its connections by instance through ListConnections, so config.ConnectionName is a label nothing else in the platform can reach: returning it named a connection no persona rule could match, no `connection` argument could carry, and no source-map lookup could resolve (#1396).
func (*Toolkit) ConsentMiddleware ¶ added in v1.143.0
func (t *Toolkit) ConsentMiddleware() mcp.Middleware
ConsentMiddleware is the tools/call layer that asks the caller to confirm a trino_query estimated over its connection's row threshold, or reading a column tagged PII (#2052). The platform places it in its receiving chain, inside authorization and the gates.
func (*Toolkit) Exec ¶ added in v1.125.0
Exec runs a statement against a named connection and discards its rows.
It is the platform's one write path into Trino. The two direct callers of Manager().Client(name).Query -- the HTTP query func and trino_export -- run SELECT and reach the client without passing the read-only check, so neither is a model for a statement that writes. Exec runs the same ReadOnlyInterceptor the MCP tools run, against the same per-connection read_only settings that AddConnection and RemoveConnection maintain, so a read_only connection refuses DDL here exactly as trino_execute would.
Authorization above this line is the caller's: Exec asks whether the connection accepts writes, never whether this person may use it.
func (*Toolkit) FitResult ¶ added in v1.136.0
func (t *Toolkit) FitResult(tool string, args json.RawMessage, res *mcp.CallToolResult, budget int) bool
FitResult holds a trino_query result to a model client's context budget (#1878) by keeping the head of its rows: the most whole rows whose rendering, in the format the caller asked for, fits. The result is flagged, and the trino_export call that writes every row to an asset is handed back when this deployment registers it. Called by the platform's result-budget middleware, and only for a result past the budget. A result it cannot read, or one whose header alone is past the budget, is declined, and reaches the model whole.
func (*Toolkit) HasConnection ¶ added in v1.48.0
HasConnection returns true if a connection with the given name exists.
func (*Toolkit) ListConnections ¶ added in v0.26.0
func (t *Toolkit) ListConnections() []toolkit.ConnectionDetail
ListConnections returns details for all connections managed by this toolkit. Implements toolkit.ConnectionLister.
func (*Toolkit) ListTables ¶ added in v1.146.1
func (t *Toolkit) ListTables(ctx context.Context, connection, catalog, schema string) ([]SchemaTable, bool, error)
ListTables returns the tables and views a schema on a connection holds, by name, and whether the list was cut at maxSchemaTables (#2136). It is a read of information_schema, so it runs past no write check.
func (*Toolkit) Manager ¶ added in v1.57.0
func (t *Toolkit) Manager() *multiserver.Manager
Manager returns the multi-connection manager when the toolkit was constructed in multi-mode (the typical platform startup path). Returns nil for single-connection toolkits. Callers that need a per-connection client (gateway enrichment, cross-toolkit lookups) use this to look up a client by name.
func (*Toolkit) ProbeConnection ¶ added in v1.133.4
ProbeConnection opens the named connection and runs SELECT 1 against it, which is what a caller means by "does this connection work": the DSN parses, the coordinator is reachable, and the credential authenticates.
It is the check that was missing when a connection whose user and password were stored as unexpanded "${...}" placeholders was created, listed and read back as a healthy connection, and failed every query afterwards at DSN construction (#1805).
On a connection that accepts writes and names a scratch target it also checks what webhook sources need of that catalog, which otherwise surfaced only when an administrator first created a source (#1888); see probeScratch.
Implements connprobe.Prober.
func (*Toolkit) Query ¶ added in v1.141.0
func (t *Toolkit) Query(ctx context.Context, connection, sql string, opts trinoclient.QueryOptions) (*trinoclient.QueryResult, error)
Query runs one read statement against a named connection (empty is the default) and returns its result, recorded like every other statement the toolkit sends (telemetry.go). It runs no read-only check: it is for a caller that issues a SELECT of its own; a statement that writes goes through Exec.
func (*Toolkit) QueryLimits ¶ added in v1.142.0
QueryLimits is trino_query's row limits and query timeout as this toolkit configured them, for platform_info to report (#2057).
func (*Toolkit) RegisterTools ¶
RegisterTools registers Trino tools with the MCP server. The platform provides a unified list_connections tool, so the per-toolkit trino_list_connections is excluded.
func (*Toolkit) RemoveConnection ¶ added in v1.48.0
RemoveConnection removes a named connection at runtime. Requires multi-connection mode (created via NewMulti).
func (*Toolkit) ScratchConnections ¶ added in v1.152.0
ScratchConnections names the connections a table can be created on: each that has a scratch catalog and schema and accepts writes, sorted. It is the list a form's source is placed on when the binding names none (#2178).
func (*Toolkit) ScratchTarget ¶ added in v1.125.0
func (t *Toolkit) ScratchTarget(connection string) (ScratchConfig, bool)
ScratchTarget returns the catalog and schema table registrations write into on a connection, and whether that connection has one. An empty name resolves to the default connection, matching multiserver.Manager.Client("").
func (*Toolkit) ServesConnection ¶ added in v1.149.0
ServesConnection reports whether this toolkit serves the named connection, taking on one another replica saved when the announcement of that save has not reached this instance yet. An empty name is the default connection, which is always served.
func (*Toolkit) SetConnectionStore ¶ added in v1.149.0
func (t *Toolkit) SetConnectionStore(s ConnectionStore)
SetConnectionStore wires the store a request for a connection this instance does not serve is answered from. Passing nil leaves this instance serving only the connections it was handed.
func (*Toolkit) SetExportDeps ¶ added in v1.56.0
func (t *Toolkit) SetExportDeps(deps ExportDeps)
SetExportDeps injects portal dependencies for trino_export.
func (*Toolkit) SetMetrics ¶ added in v1.141.0
func (t *Toolkit) SetMetrics(m *observability.Metrics)
SetMetrics installs the recorder the toolkit's Trino calls report to. The platform calls it on every toolkit that has one (WireToolkitMetrics) when metrics or tracing is on.
func (*Toolkit) SetQueryProvider ¶
SetQueryProvider sets the query execution provider for enrichment.
func (*Toolkit) SetSemanticProvider ¶
SetSemanticProvider sets the semantic metadata provider for enrichment.
func (*Toolkit) TableExists ¶ added in v1.126.6
func (t *Toolkit) TableExists(ctx context.Context, connection, catalog, schema, table string) (bool, error)
TableExists reports whether a catalog on a connection holds a table, by asking its information_schema rather than by querying the table: a table that exists but cannot be read is still a table, and one whose metadata is gone is not, whatever its files say.
It is a read, so it runs past no write check; the identifiers come from a registration row and are quoted here rather than trusted, because the connection's catalog names them and this is the one place they meet SQL text.
func (*Toolkit) TableLocation ¶ added in v1.146.1
func (t *Toolkit) TableLocation(ctx context.Context, connection, catalog, schema, table string) (location string, found bool, err error)
TableLocation reports the external_location a table on a connection was created with, and whether the table exists at all. A table that exists with no external location reads as found with an empty location.
It is how a registration learns whether a table it has no record of is one an earlier registration of the same file created (#2131): the location is the one fact the table carries about where it came from. It is a read, and runs past no write check.
func (*Toolkit) Tools ¶
Tools returns the list of tool names that would be provided by this toolkit.
func (*Toolkit) ValidateConnection ¶ added in v1.139.0
ValidateConnection reports whether the Trino client would refuse to open a connection with this configuration, judged with what it inherits from the default connection, without adding it (#2014). The admin API asks it before storing a connection.
A single-connection toolkit takes no connection at run time, which AddConnection reports; there is nothing here to judge it against.
type TypedFormatter ¶ added in v1.135.0
type TypedFormatter interface {
Formatter
FormatTyped(columns []tabletype.Column, rows [][]any) ([]byte, error)
}
TypedFormatter is a Formatter that writes each column as its own type, and so needs the types. trino_export hands it the types Trino reported for the query's columns; a writer with no types (a managed script's rows) calls Format, which infers them.