Documentation
¶
Overview ¶
Package platform provides the main platform orchestration.
Index ¶
- Constants
- Variables
- func MigrateConfig(r io.Reader, w io.Writer, targetVersion string) error
- func MigrateConfigBytes(data []byte, targetVersion string) ([]byte, error)
- func PeekVersion(data []byte) string
- type APIGatewayConfig
- type APIGatewayEmbedJobsConfig
- type APIGatewayMemoryConfig
- type APIGatewaySelfConnectionConfig
- type APIKeyAuthConfig
- type APIKeyDef
- type APIKeyDefinition
- type APIKeyStore
- type AdminConfig
- type AppConfig
- type AuditConfig
- type AuthConfig
- type BasicAuthConfig
- type BrowserSessionConfig
- type CSPAppConfig
- type CacheConfig
- type ClientLoggingConfig
- type Closer
- type Component
- type Config
- func (c *Config) ApplyConfigEntry(key, value string)
- func (c *Config) SetToolDescriptionOverride(name, value string)
- func (c *Config) SetToolsDeny(deny []string)
- func (c *Config) ToolDescriptionOverridesSnapshot() map[string]string
- func (c *Config) ToolsAllowSnapshot() []string
- func (c *Config) ToolsDenySnapshot() []string
- func (c *Config) Validate() error
- type ConfigEnvelope
- type ConfigMeta
- type ConfigVersionInfo
- type ConnectionInstance
- type ConnectionReloadOp
- type ConnectionRulesDef
- type ConnectionSource
- type ConnectionSourceMap
- type ConnectionStore
- type ContextDef
- type CostEstimationConfig
- type CustomResourceDef
- type DCRConfig
- type DatabaseConfig
- type ElicitationConfig
- type EmbeddingConfig
- type EnrichmentConfig
- func (c *EnrichmentConfig) EffectiveMemoryContextBudgetBytes() int
- func (c *EnrichmentConfig) EffectiveMemoryLimit() int
- func (c *EnrichmentConfig) EffectiveMemorySummaryBytes() int
- func (c *EnrichmentConfig) EffectiveSchemaPreviewMaxColumns() int
- func (c *EnrichmentConfig) EffectiveSemanticFallbackTopK() int
- func (c *EnrichmentConfig) IsColumnContextFilteringEnabled() bool
- func (c *EnrichmentConfig) IsDataHubQueryEnrichmentEnabled() bool
- func (c *EnrichmentConfig) IsDataHubStorageEnrichmentEnabled() bool
- func (c *EnrichmentConfig) IsS3SemanticEnrichmentEnabled() bool
- func (c *EnrichmentConfig) IsSearchSchemaPreviewEnabled() bool
- func (c *EnrichmentConfig) IsSemanticFallbackEnabled() bool
- func (c *EnrichmentConfig) IsTrinoSemanticEnrichmentEnabled() bool
- func (c *EnrichmentConfig) IsUnwrapJSONEnabled() bool
- type Features
- type GatewayIdentityResolver
- type IconDef
- type IconsConfig
- type ImplementorConfig
- type Info
- type KnowledgeApplyConfig
- type KnowledgeApplyInfo
- type KnowledgeConfig
- type Lifecycle
- func (l *Lifecycle) IsStarted() bool
- func (l *Lifecycle) OnComponent(start, stop func(context.Context) error)
- func (l *Lifecycle) OnStart(callback func(context.Context) error)
- func (l *Lifecycle) OnStop(callback func(context.Context) error)
- func (l *Lifecycle) RegisterCloser(c Closer)
- func (l *Lifecycle) RegisterComponent(c Component)
- func (l *Lifecycle) Start(ctx context.Context) error
- func (l *Lifecycle) Stop(ctx context.Context) error
- type MCPAppsConfig
- type ManagedResourcesCfg
- type MemoryConfig
- type NoopAPIKeyStore
- type NoopConnectionStore
- func (*NoopConnectionStore) Delete(_ context.Context, _, _ string) error
- func (*NoopConnectionStore) Get(_ context.Context, _, _ string) (*ConnectionInstance, error)
- func (*NoopConnectionStore) List(_ context.Context) ([]ConnectionInstance, error)
- func (*NoopConnectionStore) Persistent() bool
- func (*NoopConnectionStore) Set(_ context.Context, _ ConnectionInstance) error
- type OAuthClientConfig
- type OAuthConfig
- type OAuthRateLimitConfig
- type OAuthRateLimitRule
- type OIDCAuthConfig
- type ObservabilityConfig
- type OllamaEmbedConfig
- type Option
- func WithAuditLogger(logger middleware.AuditLogger) Option
- func WithAuthenticator(auth middleware.Authenticator) Option
- func WithAuthorizer(authz middleware.Authorizer) Option
- func WithConfig(cfg *Config) Option
- func WithConnectionStore(store ConnectionStore) Option
- func WithDB(db *sql.DB) Option
- func WithPersonaRegistry(reg *persona.Registry) Option
- func WithQueryProvider(provider query.Provider) Option
- func WithRuleEngine(engine *tuning.RuleEngine) Option
- func WithSemanticProvider(provider semantic.Provider) Option
- func WithSessionStore(store session.Store) Option
- func WithStorageProvider(provider storage.Provider) Option
- func WithToolkitRegistry(reg *registry.Registry) Option
- type Options
- type PIIConsentConfig
- type PersonaDef
- type PersonaInfo
- type PersonasConfig
- type Platform
- func (p *Platform) APIGatewayCatalogStore() apigatewaycatalog.Store
- func (p *Platform) APIGatewayEmbedJobsStore() catalogindex.Store
- func (p *Platform) APIGatewayRawMaxBytes() int64
- func (p *Platform) APIKeyAuthenticator() *auth.APIKeyAuthenticator
- func (p *Platform) APIKeyStore() APIKeyStore
- func (p *Platform) AllPromptInfos() []registry.PromptInfo
- func (p *Platform) AuditStore() *auditpostgres.Store
- func (p *Platform) AuthEventStore() authevents.Store
- func (p *Platform) AuthEventWriter() *authevents.Writer
- func (p *Platform) Authenticator() middleware.Authenticator
- func (p *Platform) BrandLogoSVG() string
- func (p *Platform) BrandURL() string
- func (p *Platform) Broadcaster() session.Broadcaster
- func (p *Platform) BrowserSessionAuth() *browsersession.Authenticator
- func (p *Platform) BrowserSessionFlow() *browsersession.Flow
- func (p *Platform) Close() error
- func (p *Platform) Config() *Config
- func (p *Platform) ConfigStore() configstore.Store
- func (p *Platform) ConnOAuthStore() connoauth.Store
- func (p *Platform) ConnectionSources() *ConnectionSourceMap
- func (p *Platform) ConnectionStore() ConnectionStore
- func (p *Platform) DB() *sql.DB
- func (p *Platform) EmbeddingProvider() embedding.Provider
- func (p *Platform) EnrichmentStore() enrichment.Store
- func (p *Platform) FileDefaults() map[string]string
- func (p *Platform) FilePersonaNames() map[string]bool
- func (p *Platform) IndexJobsReporter() *indexjobs.Reporter
- func (p *Platform) KnowledgeChangesetStore() knowledgekit.ChangesetStore
- func (p *Platform) KnowledgeDataHubWriter() knowledgekit.DataHubWriter
- func (p *Platform) KnowledgeInsightStore() knowledgekit.InsightStore
- func (p *Platform) KnowledgeRouter() *knowledge.Router
- func (p *Platform) LoadManagedResources()
- func (p *Platform) MCPServer() *mcp.Server
- func (p *Platform) MemoryStore() memory.Store
- func (p *Platform) Metrics() *observability.Metrics
- func (p *Platform) NewGatewayIdentityResolver() *GatewayIdentityResolver
- func (p *Platform) NewObservabilityAuthorizer() proxy.Authorizer
- func (p *Platform) OAuthServer() *oauth.Server
- func (p *Platform) ObservabilityAuthMiddleware() func(http.Handler) http.Handler
- func (p *Platform) PersonaRegistry() *persona.Registry
- func (p *Platform) PersonaStore() personastore.Store
- func (p *Platform) PlatformTools() []ToolInfo
- func (p *Platform) PortalAssetStore() portal.AssetStore
- func (p *Platform) PortalCollectionStore() portal.CollectionStore
- func (p *Platform) PortalKnowledgePageStore() knowledgepage.Store
- func (p *Platform) PortalS3Client() portal.S3Client
- func (p *Platform) PortalShareStore() portal.ShareStore
- func (p *Platform) PortalThreadStore() portal.ThreadStore
- func (p *Platform) PortalVersionStore() portal.VersionStore
- func (p *Platform) PromptStore() prompt.Store
- func (p *Platform) PublishAPIKeyReload()
- func (p *Platform) PublishCatalogReload(catalogID string)
- func (p *Platform) PublishConnectionReload(kind, name string, op ConnectionReloadOp)
- func (p *Platform) PublishPersonaReload()
- func (p *Platform) QueryProvider() query.Provider
- func (p *Platform) RegisterManagedResource(res *resource.Resource)
- func (p *Platform) RegisterRuntimePrompt(pr *prompt.Prompt)
- func (p *Platform) ResolveImplementorLogo() string
- func (p *Platform) ResourceS3Client() resource.S3Client
- func (p *Platform) ResourceStore() resource.Store
- func (p *Platform) RestEncryptor() *fieldcrypt.RestFieldEncryptor
- func (p *Platform) RuleEngine() *tuning.RuleEngine
- func (p *Platform) SemanticProvider() semantic.Provider
- func (p *Platform) SessionStore() session.Store
- func (p *Platform) ShutdownMetricsListener(ctx context.Context) error
- func (p *Platform) Start(ctx context.Context) error
- func (p *Platform) StartConnOAuthRefresher(resolver connoauth.ConfigResolver, multiReplica bool)
- func (p *Platform) StartMetricsListener(ctx context.Context) error
- func (p *Platform) Stop(ctx context.Context) error
- func (p *Platform) StopConnOAuthRefresher(ctx context.Context) error
- func (p *Platform) StorageProvider() storage.Provider
- func (p *Platform) ToolkitRegistry() *registry.Registry
- func (p *Platform) UnregisterManagedResource(uri string)
- func (p *Platform) UnregisterRuntimePrompt(name string)
- func (p *Platform) UserStore() user.Store
- func (p *Platform) WireAPIGatewayCatalogStore(store apigatewaycatalog.Store)
- func (p *Platform) WireAPIGatewayCatalogStoreFromDB()
- func (p *Platform) WireAPIGatewayEmbedJobsFromDB()
- func (p *Platform) WireAPIGatewayEmbeddingProvider()
- func (p *Platform) WireAPIGatewayMemBudget()
- func (p *Platform) WireAPIGatewayMetrics()
- func (p *Platform) WireAPIGatewayRoutePolicy()
- func (p *Platform) WireAPIGatewayTokenStore()
- func (p *Platform) WireAdminSelfConnection(listenAddr string)
- func (p *Platform) WireGatewayBroadcaster()
- func (p *Platform) WireGatewayIntegrations()
- func (p *Platform) WireGatewayTokenStore()
- func (p *Platform) WireRuntime(rc RuntimeConfig)
- func (p *Platform) WireToolkitMetrics()
- type PortalConfig
- type PortalExportConfig
- type PortalRateLimitConfig
- type PostgresAPIKeyStore
- type PostgresConnectionStore
- func (s *PostgresConnectionStore) Delete(ctx context.Context, kind, name string) error
- func (s *PostgresConnectionStore) Get(ctx context.Context, kind, name string) (*ConnectionInstance, error)
- func (s *PostgresConnectionStore) List(ctx context.Context) ([]ConnectionInstance, error)
- func (*PostgresConnectionStore) Persistent() bool
- func (s *PostgresConnectionStore) Set(ctx context.Context, inst ConnectionInstance) error
- type ProgressConfig
- type PrometheusConfig
- type PromptArgumentConfig
- type PromptConfig
- type QueryConfig
- type RateLimitConfig
- type ResourcesConfig
- type ReviewQueueInfo
- type RoleMappingConfig
- type RulesConfig
- type RuntimeConfig
- type SemanticConfig
- type ServerConfig
- type SessionDedupConfig
- type SessionGateConfig
- type SessionHandlesConfig
- type SessionsConfig
- type ShutdownConfig
- type StalenessConfig
- type StorageConfig
- type StreamableConfig
- type TLSConfig
- type ToolInfo
- type ToolRulesDef
- type ToolsConfig
- type TuningConfig
- type URNMappingConfig
- type UpstreamIDPConfig
- type VersionConverter
- type VersionInfo
- type VersionRegistry
- type VersionStatus
- type WorkflowConfig
Constants ¶
const ( // ConfigKeyServerDescription is the config_entries key for the live // server description override. Exported so admin handlers can use // the same canonical key (a divergent rename in either package // would silently misroute admin writes from platform reads). ConfigKeyServerDescription = "server.description" // ConfigKeyServerAgentInstructions is the config_entries key for // the live MCP `instructions` field (server-side agent guidance). ConfigKeyServerAgentInstructions = "server.agent_instructions" // ConfigKeyToolsDeny is the config_entries key for the JSON-encoded // platform-wide tool deny list (controls tools/list visibility). ConfigKeyToolsDeny = "tools.deny" )
Constants for repeated identifiers used throughout the platform package. Defined in one place so the same literal does not appear repeatedly across platform.go, info_tool.go, prompt_tool.go, etc.
const ( SessionStoreMemory = "memory" SessionStoreDatabase = "database" )
Session store backend names.
const ( // AuditDeliveryAsync (the default) enqueues each event on the bounded async // writer: the tool call is never blocked, but a sustained store outage sheds // events (counted by audit_events_dropped_total). AuditDeliveryAsync = "async" // AuditDeliverySync writes each event on the request goroutine with a // per-write timeout. It trades tool-call latency for backpressure and zero // queue-overflow drops, which compliance deployments require. AuditDeliverySync = "sync" )
Audit delivery modes select how an audit event travels from the middleware to the store. See AuditConfig.Delivery.
const ( SourceFile = "file" SourceDatabase = "database" //nolint:goconst // same value as SessionStoreDatabase but different semantic domain SourceBoth = "both" )
Source constants for personas and other config resources.
const CurrentConfigVersion = "v1"
CurrentConfigVersion is the current config API version.
Variables ¶
var ErrAPIKeyNotFound = errors.New("api key not found")
ErrAPIKeyNotFound is returned when an API key does not exist in the database.
var ErrConnectionNotFound = errors.New("connection instance not found")
ErrConnectionNotFound is returned when a connection instance does not exist.
Functions ¶
func MigrateConfig ¶ added in v0.16.0
MigrateConfig reads YAML from r, migrates it to targetVersion, and writes the result to w. If targetVersion is empty, the current version is used. Environment variable references (${VAR}) are preserved in the output.
func MigrateConfigBytes ¶ added in v0.16.0
MigrateConfigBytes migrates raw YAML config bytes to targetVersion. If targetVersion is empty, the current version is used. This function does NOT expand environment variables so ${VAR} references are preserved in the output.
func PeekVersion ¶ added in v0.16.0
PeekVersion extracts the apiVersion from raw YAML bytes. Returns "v1" if the field is missing or empty (backward compatibility).
Types ¶
type APIGatewayConfig ¶ added in v1.64.0
type APIGatewayConfig struct {
// EmbedJobs tunes the api-gateway embedding job queue.
EmbedJobs APIGatewayEmbedJobsConfig `yaml:"embed_jobs"`
// Memory bounds the gateway's response-body memory footprint across
// all connections so a burst of large responses cannot OOMKill the
// pod (issue #535).
Memory APIGatewayMemoryConfig `yaml:"memory"`
// SelfConnection configures the built-in platform-admin connection
// that points the API gateway at the platform's own admin REST API.
SelfConnection APIGatewaySelfConnectionConfig `yaml:"self_connection"`
}
APIGatewayConfig holds platform-level tuning for the api-kind toolkit. Connection-level configuration (base_url, auth_mode, credentials, etc.) lives in the connection store; this struct is for cluster-wide knobs that affect every api connection, primarily the embedding-job queue's concurrency.
type APIGatewayEmbedJobsConfig ¶ added in v1.64.0
type APIGatewayEmbedJobsConfig struct {
// Workers is the number of goroutines per pod that claim and
// process jobs in parallel. Multiple goroutines share the queue;
// the lease + SKIP LOCKED predicate in Claim prevents two
// goroutines (in the same pod or across pods) from picking the
// same job. Zero or negative falls back to 1, which preserves
// the pre-#430 single-goroutine behavior. Production deployments
// with many specs and a fast embedder benefit from 2-4; CPU-only
// embedders typically saturate at 1 because the bottleneck is
// the embedding model, not the gateway. See #430.
Workers int `yaml:"workers"`
// EmbedTimeout caps an individual batched embedding HTTP call the
// worker issues to Ollama's /api/embed endpoint. The shared
// embedding.DefaultTimeout (30s) is tuned for the singular
// /api/embeddings path used by request-path callers (memory recall,
// capture_insight, etc.) where Ollama returns in 1-3s. The batched
// path can take 60+ seconds for a 32-text chunk on CPU-only Ollama;
// using the 30s default makes the worker timeout-storm on every
// spec write (#445). Zero or negative falls back to 5 minutes,
// which covers a 32-text batch on CPU Ollama with margin. Operators
// on GPU embedders can lower this to keep the failure floor tight.
EmbedTimeout time.Duration `yaml:"embed_timeout"`
// BatchSize is the number of operations the worker hands to
// the embedding provider per upstream EmbedBatch call.
// Smaller batches keep one slow chunk's lost progress small
// at the cost of more per-call overhead; larger batches
// amortize that overhead. Zero or negative falls back to
// 32 (embedjobs.DefaultEmbedBatchSize), the value that
// shipped before this knob was operator-controlled.
//
// Tune lower (e.g. 16) when a CPU-only provider's per-batch
// latency exceeds EmbedTimeout on full chunks; tune higher
// (e.g. 64) on GPU providers where per-call overhead
// dominates per-text compute. See #479.
BatchSize int `yaml:"batch_size"`
// LeaseDuration is the lifetime a Claim stamps on a job and
// the cadence the worker's heartbeat goroutine renews it.
// The reaper releases leases past this window so a pod that
// genuinely crashed mid-embed has its job picked up by
// another worker. Zero or negative falls back to 10 minutes
// (embedjobs.DefaultLeaseDuration), the value that shipped
// before this knob was operator-controlled.
//
// On CPU-only embedders processing large specs (~150+ ops),
// total compute can exceed 10 minutes even though every
// individual batch finishes in 2-3 minutes. The heartbeat
// (lease_duration / 3 cadence) keeps the lease alive while
// chunks are completing, so this value caps "pod went
// silent" rather than "embed batch is slow" — but it must
// still be greater than EmbedTimeout so a single batch can
// finish inside one lease window before the heartbeat fires
// its first renewal. See #479.
LeaseDuration time.Duration `yaml:"lease_duration"`
// RetentionDays bounds how long finished index_jobs history is
// kept. The queue records one row per reconciler sweep per unit
// (every 5 minutes, on every replica), so succeeded history grows
// without limit; the retainer periodically deletes succeeded and
// resolved-failed rows older than this window. Open failures
// (status='failed' with no resolved_at) and in-flight rows
// (pending / running) are never purged regardless of age, so the
// failure-triage surface and the active queue are unaffected.
//
// Zero falls back to 14 days (indexjobs.DefaultRetentionDays), a
// window that keeps a useful span of throughput / latency / job-log
// history for the admin Indexing dashboard while bounding the table.
// A negative value disables retention entirely (history grows
// unbounded), for deployments that prefer to manage cleanup
// externally. See #523.
RetentionDays int `yaml:"retention_days"`
}
APIGatewayEmbedJobsConfig tunes the per-pod embedding worker.
type APIGatewayMemoryConfig ¶ added in v1.77.0
type APIGatewayMemoryConfig struct {
// MaxInFlightBytes is the global ceiling on bytes committed to
// api_invoke_endpoint response-body buffering across all api
// connections. A buffered read that would push committed bytes past
// this is rejected with a structured 429 (retryable) before the
// buffer is allocated. 0 = disabled (no global cap; per-connection
// max_response_bytes still applies per request). api_export is exempt:
// it streams directly to S3 (issue #537) and never buffers the full
// body, so it does not consume this budget.
//
// Sizing: budget roughly 3x the raw body size per concurrent large
// request (raw body + decoded copy + JSON-escaped envelope copy) and
// leave headroom for GC and the other toolkits' working set. A safe
// target keeps
// max_in_flight_bytes ≈ (container_memory_limit × 0.6) / 3
// so peak buffering stays well under the heap even at full
// utilization. Do NOT set this to the whole container limit or
// GOMEMLIMIT — that leaves no room for the transient marshaling
// copies or for GC.
MaxInFlightBytes int64 `yaml:"max_in_flight_bytes"`
// RawMaxBytes caps a single raw passthrough response on the
// /api/v1/gateway/{connection}/invoke-raw REST route
// (all-or-nothing). An upstream whose declared Content-Length
// exceeds this is rejected with 413 (non-retryable) before any bytes
// are streamed. 0 = no cap: the raw path streams (io.Copy) instead
// of buffering, so process memory stays bounded regardless of body
// size — the cap is a policy guard, not a memory guard.
RawMaxBytes int64 `yaml:"raw_max_bytes"`
}
APIGatewayMemoryConfig bounds the memory the api gateway commits to response-body handling, the structural fix for issue #535: per-request size caps bound a single call, but nothing bounded the SUM of concurrent calls, so a burst of large responses (each under its cap) could collectively exhaust the heap and get the container OOMKilled.
type APIGatewaySelfConnectionConfig ¶ added in v1.78.0
type APIGatewaySelfConnectionConfig struct {
// Enabled gates self-registration. Nil = auto (on when prerequisites
// are met); set explicitly to override.
Enabled *bool `yaml:"enabled"`
// BaseURL overrides the loopback admin API base URL the connection
// targets. Empty derives http://127.0.0.1:<port> from the server
// listen address. Set this only when the admin API is reachable at a
// different loopback address than the main listener.
BaseURL string `yaml:"base_url"`
}
APIGatewaySelfConnectionConfig configures the built-in "platform-admin" API-gateway connection (issue #543), which lets an admin drive the platform's own /api/v1/admin/* surface through api_list_endpoints / api_invoke_endpoint. Its catalog is sourced from the OpenAPI document embedded in the binary, so it stays in sync with the running version with no manual catalog maintenance.
Auto-enabled when the prerequisites are met (HTTP transport with the admin API mounted, a database, and the API-gateway toolkit). Set enabled: false to opt out.
func (APIGatewaySelfConnectionConfig) SelfConnectionEnabled ¶ added in v1.78.0
func (c APIGatewaySelfConnectionConfig) SelfConnectionEnabled(prereqsMet bool) bool
SelfConnectionEnabled reports whether the built-in platform-admin connection should self-register, given whether its runtime prerequisites are satisfied. A nil Enabled defaults to the prerequisite result (auto); an explicit value overrides it but an operator cannot force it on when the prerequisites are absent.
type APIKeyAuthConfig ¶
APIKeyAuthConfig configures API key authentication.
type APIKeyDef ¶
type APIKeyDef struct {
Key string `yaml:"key"`
Name string `yaml:"name"`
Email string `yaml:"email"`
Description string `yaml:"description"`
Roles []string `yaml:"roles"`
}
APIKeyDef defines an API key.
type APIKeyDefinition ¶ added in v1.49.0
type APIKeyDefinition struct {
Name string `json:"name"`
KeyHash string `json:"key_hash"`
Email string `json:"email,omitempty"`
Description string `json:"description,omitempty"`
Roles []string `json:"roles"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
}
APIKeyDefinition represents a database-managed API key.
type APIKeyStore ¶ added in v1.49.0
type APIKeyStore interface {
List(ctx context.Context) ([]APIKeyDefinition, error)
Set(ctx context.Context, def APIKeyDefinition) error
Delete(ctx context.Context, name string) error
}
APIKeyStore manages API key persistence.
type AdminConfig ¶ added in v0.17.0
type AdminConfig struct {
Enabled *bool `yaml:"enabled"`
Persona string `yaml:"persona"` // required admin persona (default: "admin")
PathPrefix string `yaml:"path_prefix"` // URL prefix (default: "/api/v1/admin")
}
AdminConfig configures the admin REST API. Enabled by default (nil = enabled); set enabled: false to disable. The mounted routes still sit behind the platform's normal persona/role auth, so enabling exposes the route, not unauthenticated access.
func (*AdminConfig) IsEnabled ¶ added in v1.97.0
func (c *AdminConfig) IsEnabled() bool
IsEnabled reports whether the admin REST API is enabled, defaulting to true when not explicitly set.
type AppConfig ¶ added in v0.10.0
type AppConfig struct {
// Enabled controls whether this app is active.
Enabled bool `yaml:"enabled"`
// Tools lists the tool names this app attaches to.
Tools []string `yaml:"tools"`
// AssetsPath is the absolute filesystem path to the app's assets directory.
// This should point to a directory containing the app's HTML/JS/CSS files.
// Optional for built-in apps that use embedded assets; setting it overrides the embedded content.
AssetsPath string `yaml:"assets_path"`
// ResourceURI is the MCP resource URI for this app (e.g., "ui://query-results").
// If not specified, defaults to "ui://<app-name>".
ResourceURI string `yaml:"resource_uri"`
// EntryPoint is the main HTML file within AssetsPath (e.g., "index.html").
// Defaults to "index.html" if not specified.
EntryPoint string `yaml:"entry_point"`
// CSP defines Content Security Policy requirements for the app.
CSP *CSPAppConfig `yaml:"csp"`
// Config holds app-specific configuration that will be injected
// into the HTML as JSON.
Config map[string]any `yaml:"config"`
}
AppConfig configures an individual MCP App.
type AuditConfig ¶
type AuditConfig struct {
Enabled *bool `yaml:"enabled"`
LogToolCalls *bool `yaml:"log_tool_calls"`
// LogParameters controls whether tool-call arguments are stored on the
// event. Enabled by default (nil = enabled); set log_parameters: false to
// store a null Parameters field when the arguments may carry sensitive data
// that even redaction cannot make safe to retain.
LogParameters *bool `yaml:"log_parameters"`
// RedactKeys lists top-level argument keys whose values are replaced with
// "[REDACTED]" in the middleware, before the event ever leaves the request
// path. Matching is case-insensitive; nested keys are not matched (top-level
// only, by design).
RedactKeys []string `yaml:"redact_keys"`
// Delivery selects the store-write path: "async" (default) or "sync". See
// the Audit delivery mode constants.
Delivery string `yaml:"delivery"`
RetentionDays int `yaml:"retention_days"`
}
AuditConfig configures audit logging. Enabled by default when a database is available. Set enabled: false to disable. LogToolCalls is also enabled by default (nil = enabled) whenever audit is enabled; set log_tool_calls: false to keep audit on but skip per-tool-call rows.
func (*AuditConfig) DeliveryMode ¶ added in v1.101.0
func (c *AuditConfig) DeliveryMode() string
DeliveryMode returns the effective audit delivery mode, defaulting to async when unset. An unrecognized value also resolves to async here; callers that must reject a typo (config validation, boot) use ValidateDelivery instead.
func (*AuditConfig) IsParameterLoggingEnabled ¶ added in v1.101.0
func (c *AuditConfig) IsParameterLoggingEnabled() bool
IsParameterLoggingEnabled reports whether tool-call parameters are stored on audit events. Defaults to true (nil = enabled); set log_parameters: false to store a null Parameters field.
func (*AuditConfig) IsToolCallLoggingEnabled ¶ added in v1.97.0
func (c *AuditConfig) IsToolCallLoggingEnabled() bool
IsToolCallLoggingEnabled reports whether per-tool-call audit logging is enabled. It requires audit itself to be enabled and defaults to true when log_tool_calls is not explicitly set.
func (*AuditConfig) ValidateDelivery ¶ added in v1.101.0
func (c *AuditConfig) ValidateDelivery() error
ValidateDelivery rejects an unrecognized audit.delivery value so a typo like "synch" fails fast at boot instead of silently resolving to async and dropping the durability guarantee a compliance deployment asked for.
type AuthConfig ¶
type AuthConfig struct {
OIDC OIDCAuthConfig `yaml:"oidc"`
APIKeys APIKeyAuthConfig `yaml:"api_keys"`
BrowserSession BrowserSessionConfig `yaml:"browser_session"`
AllowAnonymous bool `yaml:"allow_anonymous"` // default: false
}
AuthConfig configures authentication.
type BasicAuthConfig ¶ added in v1.69.0
BasicAuthConfig holds optional HTTP basic-auth credentials forwarded to Prometheus. Both empty means no auth header is sent.
type BrowserSessionConfig ¶ added in v0.32.0
type BrowserSessionConfig struct {
Enabled bool `yaml:"enabled"`
CookieName string `yaml:"cookie_name"` // default: "mcp_session"
TTL time.Duration `yaml:"ttl"` // default: 8h
SigningKey string `yaml:"signing_key"` // base64-encoded HMAC key
Secure *bool `yaml:"secure"` // HTTPS-only cookie; defaults to true, set false only for local HTTP
Domain string `yaml:"domain"`
// SameSite is the cookie SameSite attribute: "lax" (default), "strict", or
// "none". "none" requires secure=true and makes X-CSRF-Token the sole CSRF
// defense (a startup warning is logged).
SameSite string `yaml:"same_site"`
}
BrowserSessionConfig configures cookie-based browser sessions.
func (*BrowserSessionConfig) IsSecure ¶ added in v1.96.0
func (b *BrowserSessionConfig) IsSecure() bool
IsSecure reports whether the session cookie carries the Secure attribute, defaulting to true (nil); set secure: false only for local HTTP.
type CSPAppConfig ¶ added in v0.11.0
type CSPAppConfig struct {
// ResourceDomains lists origins for static resources (scripts, images, styles, fonts).
ResourceDomains []string `yaml:"resource_domains"`
// ConnectDomains lists origins for network requests (fetch/XHR/WebSocket).
ConnectDomains []string `yaml:"connect_domains"`
// FrameDomains lists origins for nested iframes.
FrameDomains []string `yaml:"frame_domains"`
// ClipboardWrite requests write access to the clipboard.
ClipboardWrite bool `yaml:"clipboard_write"`
}
CSPAppConfig defines Content Security Policy requirements for an MCP App.
type CacheConfig ¶
CacheConfig configures caching.
type ClientLoggingConfig ¶ added in v0.20.0
type ClientLoggingConfig struct {
Enabled *bool `yaml:"enabled"`
}
ClientLoggingConfig configures server-to-client log message notifications. Enabled by default (nil = enabled); set enabled: false to disable.
func (*ClientLoggingConfig) IsEnabled ¶ added in v1.96.1
func (c *ClientLoggingConfig) IsEnabled() bool
IsEnabled reports whether client logging is enabled, defaulting to true when not explicitly set.
type Config ¶
type Config struct {
APIVersion string `yaml:"apiVersion"`
Meta ConfigMeta `yaml:"config"`
Server ServerConfig `yaml:"server"`
Auth AuthConfig `yaml:"auth"`
OAuth OAuthConfig `yaml:"oauth"`
Database DatabaseConfig `yaml:"database"`
Personas PersonasConfig `yaml:"personas"`
Toolkits map[string]any `yaml:"toolkits"`
Tools ToolsConfig `yaml:"tools"`
Semantic SemanticConfig `yaml:"semantic"`
Query QueryConfig `yaml:"query"`
Storage StorageConfig `yaml:"storage"`
Enrichment EnrichmentConfig `yaml:"enrichment"`
Tuning TuningConfig `yaml:"tuning"`
// EnrichmentDeprecated accepts the legacy "injection" key so configs written
// before the rename to "enrichment" still load. applyEnrichmentCompat folds it
// onto Enrichment and warns. Remove in a future apiVersion.
EnrichmentDeprecated *EnrichmentConfig `yaml:"injection"`
Audit AuditConfig `yaml:"audit"`
MCPApps MCPAppsConfig `yaml:"mcpapps"`
Sessions SessionsConfig `yaml:"sessions"`
Knowledge KnowledgeConfig `yaml:"knowledge"`
Memory MemoryConfig `yaml:"memory"`
Portal PortalConfig `yaml:"portal"`
Admin AdminConfig `yaml:"admin"`
Resources ResourcesConfig `yaml:"resources"`
Progress ProgressConfig `yaml:"progress"`
ClientLogging ClientLoggingConfig `yaml:"client_logging"`
Icons IconsConfig `yaml:"icons"`
Elicitation ElicitationConfig `yaml:"elicitation"`
Workflow WorkflowConfig `yaml:"workflow"`
SessionGate SessionGateConfig `yaml:"session_gate"`
RateLimit RateLimitConfig `yaml:"rate_limit"`
APIGateway APIGatewayConfig `yaml:"apigateway"`
Observability ObservabilityConfig `yaml:"observability"`
// contains filtered or unexported fields
}
Config holds the complete platform configuration.
func LoadConfig ¶
LoadConfig loads configuration from a file. The path is expected to come from command line arguments, controlled by the administrator.
func LoadConfigFromBytes ¶ added in v0.16.0
LoadConfigFromBytes loads configuration from raw YAML bytes. Environment variables are expanded before parsing. The apiVersion field is validated against the default version registry.
func (*Config) ApplyConfigEntry ¶ added in v1.48.0
ApplyConfigEntry updates a live config field for a whitelisted config entry key.
In addition to the static keys, any key matching tool.<name>.description is treated as a per-tool description override and written into Tools.DescriptionOverrides. An empty value removes the override so the tool reverts to its default (built-in or file-config) description.
The "tools.deny" key carries a JSON-encoded []string. An empty/blank value clears the deny list. A malformed JSON value is logged and IGNORED — the existing live slice is left untouched so a corrupt config_entries row can't silently open up tools that were supposed to be hidden by the file config.
Writes to the runtime-mutable Tools.* fields go through the runtimeMu lock so concurrent reads (notably the description-override middleware and tools.deny visibility checks) see consistent state.
func (*Config) SetToolDescriptionOverride ¶ added in v1.57.0
SetToolDescriptionOverride writes a single per-tool description override under the runtime lock. An empty value removes the override.
func (*Config) SetToolsDeny ¶ added in v1.57.0
SetToolsDeny replaces the tools.deny slice atomically under the runtime lock.
func (*Config) ToolDescriptionOverridesSnapshot ¶ added in v1.57.0
ToolDescriptionOverridesSnapshot returns a shallow copy of the live description overrides map. Callers may mutate the returned map without affecting the live config.
func (*Config) ToolsAllowSnapshot ¶ added in v1.57.0
ToolsAllowSnapshot returns a copy of tools.allow. Currently allow is not mutable at runtime, but callers should still go through this accessor in case that changes.
func (*Config) ToolsDenySnapshot ¶ added in v1.57.0
ToolsDenySnapshot returns a copy of the current tools.deny slice. Callers may mutate the returned slice without affecting the live config.
type ConfigEnvelope ¶ added in v0.16.0
type ConfigEnvelope struct {
APIVersion string `yaml:"apiVersion"`
}
ConfigEnvelope is a minimal struct for peeking at the apiVersion field without parsing the full config.
type ConfigMeta ¶ added in v1.96.0
type ConfigMeta struct {
// Strict controls how unrecognized YAML keys are handled. When nil (the
// default for this release) unknown keys are logged as a prominent warning
// and ignored, so existing configs keep loading while operators are alerted
// to drift. Set `config.strict: true` to reject unknown keys with a hard
// error instead (recommended: catches typos and stale keys at startup).
//
// A future release will flip the default so unknown keys are an error
// unless `config.strict: false` is set as a temporary escape hatch.
Strict *bool `yaml:"strict"`
}
ConfigMeta holds meta-configuration controlling how the config file itself is parsed. It is read from the top-level `config:` block.
func (ConfigMeta) IsStrict ¶ added in v1.96.0
func (m ConfigMeta) IsStrict() bool
IsStrict reports whether unrecognized YAML keys should be a hard error. Defaults to false (warn-and-continue) for this release.
type ConfigVersionInfo ¶ added in v0.16.0
type ConfigVersionInfo struct {
APIVersion string `json:"api_version"`
SupportedVersions []string `json:"supported_versions"`
LatestVersion string `json:"latest_version"`
}
ConfigVersionInfo provides information about the config API version.
type ConnectionInstance ¶ added in v1.48.0
type ConnectionInstance struct {
Kind string `json:"kind" example:"trino"`
Name string `json:"name" example:"acme-warehouse"`
Config map[string]any `json:"config"`
Description string `json:"description" example:"Production data warehouse"`
CreatedBy string `json:"created_by" example:"admin@example.com"`
UpdatedAt time.Time `json:"updated_at" example:"2026-01-15T14:30:00Z"`
}
ConnectionInstance represents a database-managed toolkit backend connection.
type ConnectionReloadOp ¶ added in v1.101.0
type ConnectionReloadOp int
ConnectionReloadOp is the intent behind a connection reload broadcast. It is carried through the reload bus so a peer applying a deletion never has to read the store: a delete is a one-shot event whose row is already gone, so a transient store-read failure on the peer could otherwise leave the connection live and callable until an unrelated reload or a restart (issue #885 review).
const ( // ReloadUpsert marks a created or updated connection: the peer reads the // store for the new config and re-materializes it (keeping the live config // in place if the read transiently fails, per #885). ReloadUpsert ConnectionReloadOp = iota // ReloadDelete marks a deleted connection: the peer removes it from every // matching live toolkit without reading the store. ReloadDelete )
func (ConnectionReloadOp) String ¶ added in v1.101.0
func (o ConnectionReloadOp) String() string
String renders the op for the reload-bus wire payload and logs.
type ConnectionRulesDef ¶ added in v1.48.0
type ConnectionRulesDef struct {
Allow []string `yaml:"allow,omitempty"`
Deny []string `yaml:"deny,omitempty"`
}
ConnectionRulesDef defines connection access rules in config.
type ConnectionSource ¶ added in v1.48.0
type ConnectionSource = connsource.Source
ConnectionSource is re-exported from the connsource package (extracted for the package-size budget) so existing platform callers keep the name.
func ConnectionSourceFromInstance ¶ added in v1.48.0
func ConnectionSourceFromInstance(inst ConnectionInstance) ConnectionSource
ConnectionSourceFromInstance builds a ConnectionSource from a DB instance.
type ConnectionSourceMap ¶ added in v1.48.0
type ConnectionSourceMap = connsource.Map
ConnectionSourceMap is re-exported from the connsource package; existing callers keep the name and NewConnectionSourceMap constructs one.
func NewConnectionSourceMap ¶ added in v1.48.0
func NewConnectionSourceMap() *ConnectionSourceMap
NewConnectionSourceMap creates an empty connection source map.
type ConnectionStore ¶ added in v1.48.0
type ConnectionStore interface {
List(ctx context.Context) ([]ConnectionInstance, error)
Get(ctx context.Context, kind, name string) (*ConnectionInstance, error)
Set(ctx context.Context, inst ConnectionInstance) error
Delete(ctx context.Context, kind, name string) error
// Persistent reports whether the store survives process restarts.
// True for database-backed implementations, false for noop / in-memory
// stubs. The platform uses this to decide whether to auto-activate
// features whose state would be lost without persistence (e.g. the
// mcp gateway toolkit, where authcode-grant connections rely on the
// token store keeping refresh tokens across restarts).
Persistent() bool
}
ConnectionStore manages connection instance persistence.
Implementations must declare via Persistent() whether they back saves with durable storage. Code that auto-activates features based on the presence of a connection store (e.g. mergeDBConnectionsIntoConfig) uses this signal instead of a type assertion against a specific stub — so adding a new transient/test implementation in the future does not silently flip auto-enable behavior on for code paths that assume persistence.
type ContextDef ¶ added in v1.48.0
type ContextDef struct {
DescriptionPrefix string `yaml:"description_prefix,omitempty"`
DescriptionOverride string `yaml:"description_override,omitempty"`
AgentInstructionsSuffix string `yaml:"agent_instructions_suffix,omitempty"`
AgentInstructionsOverride string `yaml:"agent_instructions_override,omitempty"`
}
ContextDef defines per-persona context overrides.
type CostEstimationConfig ¶ added in v0.21.0
type CostEstimationConfig struct {
// Enabled controls whether query cost estimation triggers elicitation.
// Enabled by default (nil = enabled); set enabled: false to disable.
Enabled *bool `yaml:"enabled"`
// RowThreshold is the estimated row count above which confirmation is requested.
// Default: 1000000 (1 million rows).
RowThreshold int64 `yaml:"row_threshold"`
}
CostEstimationConfig configures query cost estimation.
func (*CostEstimationConfig) IsEnabled ¶ added in v1.96.1
func (c *CostEstimationConfig) IsEnabled() bool
IsEnabled reports whether cost estimation is enabled, defaulting to true when not explicitly set.
type CustomResourceDef ¶ added in v0.29.0
type CustomResourceDef struct {
URI string `yaml:"uri"`
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
MIMEType string `yaml:"mime_type"`
Content string `yaml:"content,omitempty"` // inline text/JSON/SVG
ContentFile string `yaml:"content_file,omitempty"` // absolute or relative path
}
CustomResourceDef defines a user-configured static MCP resource.
type DCRConfig ¶
type DCRConfig struct {
Enabled bool `yaml:"enabled"`
// AllowedRedirectPatterns are regex patterns for redirect URIs that
// dynamically registered clients may use. The registration endpoint is
// unauthenticated, so registration is denied when this is empty unless
// AllowAllRedirectURIs explicitly opts out of pattern matching.
AllowedRedirectPatterns []string `yaml:"allowed_redirect_patterns"`
AllowAllRedirectURIs bool `yaml:"allow_all_redirect_uris"`
}
DCRConfig configures Dynamic Client Registration.
type DatabaseConfig ¶
DatabaseConfig configures the database connection.
type ElicitationConfig ¶ added in v0.21.0
type ElicitationConfig struct {
// Enabled is the master switch for all elicitation features.
// Enabled by default (nil = enabled); set enabled: false to disable.
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 user confirmation for expensive operations.
func (*ElicitationConfig) IsEnabled ¶ added in v1.96.1
func (c *ElicitationConfig) IsEnabled() bool
IsEnabled reports whether elicitation is enabled, defaulting to true when not explicitly set.
type EmbeddingConfig ¶ added in v1.52.0
type EmbeddingConfig struct {
Provider string `yaml:"provider"` // "ollama" or "noop"
Ollama OllamaEmbedConfig `yaml:"ollama"`
}
EmbeddingConfig configures the embedding provider for vector search.
type EnrichmentConfig ¶ added in v1.88.0
type EnrichmentConfig struct {
// The four cross-enrichment flags default to true (nil = enabled). They are
// the platform's core differentiator and are read-only: each no-ops safely
// when its provider (semantic / query / storage) is absent, so defaulting on
// is safe and removes the need to opt every deployment into enrichment. Set
// the flag to false explicitly to disable. Read via the Is*Enabled helpers.
TrinoSemanticEnrichment *bool `yaml:"trino_semantic_enrichment"`
DataHubQueryEnrichment *bool `yaml:"datahub_query_enrichment"`
S3SemanticEnrichment *bool `yaml:"s3_semantic_enrichment"`
DataHubStorageEnrichment *bool `yaml:"datahub_storage_enrichment"`
EstimateRowCounts bool `yaml:"estimate_row_counts"`
SessionDedup SessionDedupConfig `yaml:"session_dedup"`
// UnwrapJSON defaults the unwrap_json parameter to true on trino_query
// and trino_execute, so single-row VARCHAR-of-JSON responses (e.g. from
// OpenSearch/Elasticsearch raw_query) are returned as parsed objects
// instead of double-encoded strings. Defaults to true (nil = enabled).
UnwrapJSON *bool `yaml:"unwrap_json"`
// ColumnContextFiltering limits column-level semantic enrichment to
// columns referenced in the SQL query. Saves tokens when queries
// touch a subset of a wide table. Defaults to true (nil = enabled).
ColumnContextFiltering *bool `yaml:"column_context_filtering"`
// SearchSchemaPreview adds a bounded column-name+type preview to
// datahub_search query_context, eliminating the intermediate
// datahub_get_schema or trino_describe_table call before writing SQL.
// Defaults to true (nil = enabled).
SearchSchemaPreview *bool `yaml:"search_schema_preview"`
// SchemaPreviewMaxColumns caps how many columns appear in each
// schema preview. Defaults to 15 (nil = 15).
SchemaPreviewMaxColumns *int `yaml:"schema_preview_max_columns"`
// SemanticFallback enables the issue #444 fallback path: when a
// URN-equality lookup for a Trino table misses on the semantic
// provider, the platform calls SearchTables with Mode=semantic
// and surfaces the top hit as a SUGGESTED match (annotated with
// match_kind=semantic so the model knows it is similarity-
// inferred, not URN-resolved). Audit rows record
// enrichment_match_kind so operators can measure false-positive
// rate. Default off. Requires the semantic provider to support
// the "semantic" search mode (DataHub does as of v1.8.1).
SemanticFallback *bool `yaml:"semantic_fallback"`
// SemanticFallbackTopK is how many similarity-search hits the
// fallback surfaces per miss. Default 1. Caps at 10 to keep
// suggested-match output bounded; operators wanting broader
// recall should adjust persona scope or query patterns, not
// flood the response with low-rank suggestions.
SemanticFallbackTopK *int `yaml:"semantic_fallback_top_k"`
// MemoryLimit caps how many memory records the platform recalls and
// renders into the memory_context enrichment block per tool call.
// Defaults to 5 (nil = 5). Issue #761.
MemoryLimit *int `yaml:"memory_limit"`
// MemoryContextBudgetBytes bounds the byte size of the rendered memory
// summaries appended per tool call. Records beyond the budget are listed
// as compact id+reference stubs (still fetchable, not dropped); at least
// one record is always rendered. Defaults to 1500 (nil = 1500). Set to 0
// to disable the budget (render every recalled record). Issue #761.
MemoryContextBudgetBytes *int `yaml:"memory_context_budget_bytes"`
// MemorySummaryBytes caps each rendered memory record to a summary-first
// excerpt so the agent fetches the full record by reference only when it
// matters. Defaults to 280 (nil = 280). Set to 0 to render full content.
// Issue #761.
MemorySummaryBytes *int `yaml:"memory_summary_bytes"`
}
EnrichmentConfig configures cross-enrichment.
func (*EnrichmentConfig) EffectiveMemoryContextBudgetBytes ¶ added in v1.99.0
func (c *EnrichmentConfig) EffectiveMemoryContextBudgetBytes() int
EffectiveMemoryContextBudgetBytes returns the configured memory_context byte budget, defaulting to 1500 when unset. A configured 0 disables the budget (every recalled record is rendered); negative values are treated as the default rather than as "disabled" to avoid a stray sign silently unbounding the payload.
func (*EnrichmentConfig) EffectiveMemoryLimit ¶ added in v1.99.0
func (c *EnrichmentConfig) EffectiveMemoryLimit() int
EffectiveMemoryLimit returns the configured memory-enrichment record limit, defaulting to 5 when unset and flooring non-positive values at the default.
func (*EnrichmentConfig) EffectiveMemorySummaryBytes ¶ added in v1.99.0
func (c *EnrichmentConfig) EffectiveMemorySummaryBytes() int
EffectiveMemorySummaryBytes returns the configured per-record summary cap, defaulting to 280 when unset. A configured 0 disables truncation (full content is rendered); negative values fall back to the default.
func (*EnrichmentConfig) EffectiveSchemaPreviewMaxColumns ¶ added in v1.88.0
func (c *EnrichmentConfig) EffectiveSchemaPreviewMaxColumns() int
EffectiveSchemaPreviewMaxColumns returns the configured max columns for schema preview, defaulting to 15 when not explicitly set.
func (*EnrichmentConfig) EffectiveSemanticFallbackTopK ¶ added in v1.88.0
func (c *EnrichmentConfig) EffectiveSemanticFallbackTopK() int
EffectiveSemanticFallbackTopK returns the configured top-K for the semantic fallback, clamped to [1, maxSemanticFallbackTopK]. Returns defaultSemanticFallbackTopK when unset; clamps to bounds when set outside the valid range.
func (*EnrichmentConfig) IsColumnContextFilteringEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsColumnContextFilteringEnabled() bool
IsColumnContextFilteringEnabled returns whether column context filtering is enabled, defaulting to true when not explicitly set.
func (*EnrichmentConfig) IsDataHubQueryEnrichmentEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsDataHubQueryEnrichmentEnabled() bool
IsDataHubQueryEnrichmentEnabled reports whether DataHub results are enriched with query/availability context, defaulting to true when not explicitly set.
func (*EnrichmentConfig) IsDataHubStorageEnrichmentEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsDataHubStorageEnrichmentEnabled() bool
IsDataHubStorageEnrichmentEnabled reports whether DataHub results are enriched with storage context, defaulting to true when not explicitly set.
func (*EnrichmentConfig) IsS3SemanticEnrichmentEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsS3SemanticEnrichmentEnabled() bool
IsS3SemanticEnrichmentEnabled reports whether S3 results are enriched with semantic context, defaulting to true when not explicitly set.
func (*EnrichmentConfig) IsSearchSchemaPreviewEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsSearchSchemaPreviewEnabled() bool
IsSearchSchemaPreviewEnabled returns whether search schema preview is enabled, defaulting to true when not explicitly set.
func (*EnrichmentConfig) IsSemanticFallbackEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsSemanticFallbackEnabled() bool
IsSemanticFallbackEnabled returns whether the issue #444 fallback is enabled. Defaults to false; operators opt in explicitly because similarity matches are heuristic and may surface false positives.
func (*EnrichmentConfig) IsTrinoSemanticEnrichmentEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsTrinoSemanticEnrichmentEnabled() bool
IsTrinoSemanticEnrichmentEnabled reports whether Trino results are enriched with semantic context, defaulting to true when not explicitly set. The enrichment no-ops when no semantic provider is configured.
func (*EnrichmentConfig) IsUnwrapJSONEnabled ¶ added in v1.88.0
func (c *EnrichmentConfig) IsUnwrapJSONEnabled() bool
IsUnwrapJSONEnabled returns whether unwrap_json defaults to true, defaulting to true when not explicitly set.
type Features ¶ added in v0.9.0
type Features struct {
SemanticEnrichment bool `json:"semantic_enrichment"`
QueryEnrichment bool `json:"query_enrichment"`
StorageEnrichment bool `json:"storage_enrichment"`
AuditLogging bool `json:"audit_logging"`
KnowledgeCapture bool `json:"knowledge_capture"`
KnowledgeApply *KnowledgeApplyInfo `json:"knowledge_apply,omitempty"`
ManagedResources bool `json:"managed_resources"`
}
Features describes enabled platform features.
type GatewayIdentityResolver ¶ added in v1.69.0
type GatewayIdentityResolver struct {
// contains filtered or unexported fields
}
GatewayIdentityResolver resolves an inbound REST request's auth context to a display identity for the inbound metric's identity label. It reuses the platform's existing authenticator rather than forking auth. Returns "unknown" when nothing resolves so the label is always bounded. Structurally satisfies gatewayhttp.IdentityResolver (kept concrete here so the platform package does not import gatewayhttp).
func (*GatewayIdentityResolver) ResolveIdentity ¶ added in v1.69.0
func (r *GatewayIdentityResolver) ResolveIdentity(ctx context.Context) string
ResolveIdentity authenticates the token already placed on ctx and returns a display name: the API key name for API-key auth, else the OIDC email, else the raw subject, else "unknown".
type IconDef ¶ added in v0.21.0
type IconDef struct {
// Source is the icon URL (HTTP/HTTPS) or data URI.
Source string `yaml:"src"`
// MIMEType is the optional MIME type (e.g., "image/svg+xml").
MIMEType string `yaml:"mime_type,omitempty"`
}
IconDef defines an icon for config-driven injection.
type IconsConfig ¶ added in v0.21.0
type IconsConfig struct {
// Enabled is the master switch for icon injection.
// Enabled by default (nil = enabled); set enabled: false to disable.
Enabled *bool `yaml:"enabled"`
// Tools maps tool names to their icon definitions.
Tools map[string]IconDef `yaml:"tools"`
// Resources maps resource URI templates to their icon definitions.
Resources map[string]IconDef `yaml:"resources"`
// Prompts maps prompt names to their icon definitions.
Prompts map[string]IconDef `yaml:"prompts"`
}
IconsConfig configures visual metadata for tools, resources, and prompts.
func (*IconsConfig) IsEnabled ¶ added in v1.96.1
func (c *IconsConfig) IsEnabled() bool
IsEnabled reports whether icon injection is enabled, defaulting to true when not explicitly set.
type ImplementorConfig ¶ added in v1.38.5
type ImplementorConfig struct {
Name string `yaml:"name"` // display name (e.g., "ACME Corp")
Logo string `yaml:"logo"` // URL to logo SVG (fetched at startup for inline rendering)
URL string `yaml:"url"` // link URL (e.g., "https://acme.com")
}
ImplementorConfig configures the optional implementor brand shown in the far-left zone of the public viewer header (e.g., "ACME Corp").
type Info ¶ added in v0.14.0
type Info struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
SessionID string `json:"session_id,omitempty"`
SessionExpiresAt string `json:"session_expires_at,omitempty"`
AgentInstructions string `json:"agent_instructions,omitempty"`
Toolkits []string `json:"toolkits"`
ToolkitDescriptions map[string]string `json:"toolkit_descriptions,omitempty"`
PortalURL string `json:"portal_url,omitempty"`
Persona *PersonaInfo `json:"persona,omitempty"`
Prompts []registry.PromptInfo `json:"prompts,omitempty"`
Features Features `json:"features"`
ConfigVersion ConfigVersionInfo `json:"config_version"`
}
Info contains information about the platform deployment.
type KnowledgeApplyConfig ¶ added in v0.16.0
type KnowledgeApplyConfig struct {
Enabled *bool `yaml:"enabled"`
DataHubConnection string `yaml:"datahub_connection"`
RequireConfirmation bool `yaml:"require_confirmation"`
}
KnowledgeApplyConfig configures the apply_knowledge tool. Enabled by default when a database is available (nil = enabled); set enabled: false to disable. Still gated behind database availability.
func (*KnowledgeApplyConfig) IsEnabled ¶ added in v1.97.0
func (c *KnowledgeApplyConfig) IsEnabled() bool
IsEnabled reports whether apply_knowledge is enabled, defaulting to true when not explicitly set.
type KnowledgeApplyInfo ¶ added in v0.16.0
type KnowledgeApplyInfo struct {
Enabled bool `json:"enabled"`
DataHubConnection string `json:"datahub_connection,omitempty"`
ReviewQueue *ReviewQueueInfo `json:"review_queue,omitempty"`
}
KnowledgeApplyInfo provides information about the knowledge apply feature.
type KnowledgeConfig ¶ added in v0.16.0
type KnowledgeConfig struct {
Enabled *bool `yaml:"enabled"`
Apply KnowledgeApplyConfig `yaml:"apply"`
Pages knowledgepage.PageGuardsConfig `yaml:"pages"` // write guards (#705); see knowledgepage
// ReflexiveCapture configures auto-capture of query-error corrections (#635):
// when a query errors and a later related query on the same connection
// succeeds in the same session, the platform mints a "misconception + fix"
// memory. Captures enter review (reviewed sink-class), so the blast radius is
// a pending insight, not live catalog state. Auto-enabled with the memory
// subsystem; see pkg/platform/reflexivecapture.
ReflexiveCapture reflexivecapture.Config `yaml:"reflexive_capture"`
// SearchProviderTimeout bounds each knowledge provider arm in the `search`
// fan-out; default 5s, a negative value disables it.
SearchProviderTimeout time.Duration `yaml:"search_provider_timeout"`
// SearchEmbedTimeout bounds the serial intent-embedding step in `search`,
// independent of the fan-out bound; default 5s, a negative value disables it.
SearchEmbedTimeout time.Duration `yaml:"search_embed_timeout"`
}
KnowledgeConfig configures the knowledge capture feature. Enabled by default when a database is available. Set enabled: false to disable.
type Lifecycle ¶
type Lifecycle struct {
// contains filtered or unexported fields
}
Lifecycle manages the startup and shutdown of platform components.
func (*Lifecycle) OnComponent ¶ added in v1.96.0
OnComponent registers a component's start and stop callbacks as one unit. Either callback may be nil. This is the preferred registration path: it keeps the start/stop pairing structural rather than relying on matched registration order across two lists.
If the lifecycle has already been started, the start callback is invoked immediately with context.Background() and any error is logged. This handles late-wiring paths (toolkit setup that happens inside the HTTP server assembly, after platform.Start has already run) which otherwise silently never fire. The stop callback still runs at shutdown.
func (*Lifecycle) OnStart ¶
OnStart registers a callback to run on startup. Prefer OnComponent when the component also has a stop half.
func (*Lifecycle) OnStop ¶
OnStop registers a callback to run on shutdown. Prefer OnComponent when the component also has a start half.
func (*Lifecycle) RegisterCloser ¶
RegisterCloser registers a closer to be closed on shutdown.
func (*Lifecycle) RegisterComponent ¶
RegisterComponent registers a component with the lifecycle.
type MCPAppsConfig ¶ added in v0.10.0
type MCPAppsConfig struct {
// Enabled is the master switch for MCP Apps support.
// Nil (not set) defaults to true — the built-in platform-info app is always registered.
// Set to false explicitly to disable all MCP Apps.
Enabled *bool `yaml:"enabled"`
// Apps configures individual MCP Apps.
Apps map[string]AppConfig `yaml:"apps"`
}
MCPAppsConfig configures MCP Apps support for interactive UI components.
func (*MCPAppsConfig) IsEnabled ¶ added in v0.28.1
func (c *MCPAppsConfig) IsEnabled() bool
IsEnabled returns whether MCP Apps support is enabled. Defaults to true when not explicitly set.
type ManagedResourcesCfg ¶ added in v1.54.0
type ManagedResourcesCfg struct {
Enabled *bool `yaml:"enabled"` // nil = auto (enabled when DB available)
URIScheme string `yaml:"uri_scheme"` // default: "mcp"
S3Connection string `yaml:"s3_connection"` // name of S3 toolkit instance
S3Bucket string `yaml:"s3_bucket"` // bucket for resource blobs (default: "managed-resources")
}
ManagedResourcesCfg configures human-uploaded resources stored in S3/Postgres. Enabled by default when a database is available. Set enabled: false to disable.
type MemoryConfig ¶ added in v1.52.0
type MemoryConfig struct {
Enabled *bool `yaml:"enabled"`
Embedding EmbeddingConfig `yaml:"embedding"`
Staleness StalenessConfig `yaml:"staleness"`
}
MemoryConfig configures the persistent memory layer. Memory is enabled by default when a database is available. Set enabled: false to explicitly disable.
type NoopAPIKeyStore ¶ added in v1.49.0
type NoopAPIKeyStore struct{}
NoopAPIKeyStore is a no-op implementation for when no database is available.
func (*NoopAPIKeyStore) Delete ¶ added in v1.49.0
func (*NoopAPIKeyStore) Delete(_ context.Context, _ string) error
Delete returns ErrAPIKeyNotFound for the noop store.
func (*NoopAPIKeyStore) List ¶ added in v1.49.0
func (*NoopAPIKeyStore) List(_ context.Context) ([]APIKeyDefinition, error)
List returns nil for the noop store.
func (*NoopAPIKeyStore) Set ¶ added in v1.49.0
func (*NoopAPIKeyStore) Set(_ context.Context, _ APIKeyDefinition) error
Set is a no-op.
type NoopConnectionStore ¶ added in v1.48.0
type NoopConnectionStore struct{}
NoopConnectionStore is a no-op implementation for when no database is available.
func (*NoopConnectionStore) Delete ¶ added in v1.48.0
func (*NoopConnectionStore) Delete(_ context.Context, _, _ string) error
Delete always returns ErrConnectionNotFound.
func (*NoopConnectionStore) Get ¶ added in v1.48.0
func (*NoopConnectionStore) Get(_ context.Context, _, _ string) (*ConnectionInstance, error)
Get always returns ErrConnectionNotFound.
func (*NoopConnectionStore) List ¶ added in v1.48.0
func (*NoopConnectionStore) List(_ context.Context) ([]ConnectionInstance, error)
List returns an empty slice.
func (*NoopConnectionStore) Persistent ¶ added in v1.57.2
func (*NoopConnectionStore) Persistent() bool
Persistent reports that the noop store has no durable backing.
func (*NoopConnectionStore) Set ¶ added in v1.48.0
func (*NoopConnectionStore) Set(_ context.Context, _ ConnectionInstance) error
Set is a no-op.
type OAuthClientConfig ¶ added in v0.3.0
type OAuthClientConfig struct {
ID string `yaml:"id"`
Secret string `yaml:"secret"` // #nosec G117 -- API key secret from admin YAML config
RedirectURIs []string `yaml:"redirect_uris"`
}
OAuthClientConfig defines a pre-registered OAuth client.
type OAuthConfig ¶
type OAuthConfig struct {
Enabled bool `yaml:"enabled"`
Issuer string `yaml:"issuer"`
SigningKey string `yaml:"signing_key"` // Base64-encoded HMAC key for JWT signing
// PreviousSigningKeys are base64-encoded HMAC keys retained for verification
// only after a signing-key rotation. New tokens are always signed with
// SigningKey; tokens minted with a prior key still verify while that key
// remains here. Rotate in two phases (add the new key here as verify-only
// everywhere first, then promote it to signing_key) so no replica signs with
// a key its peers have not yet learned; see the "Rotating the signing key"
// runbook in docs/auth/oauth-server.md.
PreviousSigningKeys []string `yaml:"previous_signing_keys"`
// AllowEphemeralSigningKey permits an HTTP deployment to boot without a
// configured signing_key, generating a per-process key instead. UNSAFE for
// multi-replica deployments: each replica mints tokens its peers reject.
// Intended only for single-replica HTTP dev setups. Default false.
AllowEphemeralSigningKey bool `yaml:"allow_ephemeral_signing_key"`
Clients []OAuthClientConfig `yaml:"clients"`
DCR DCRConfig `yaml:"dcr"`
RateLimit OAuthRateLimitConfig `yaml:"rate_limit"`
Upstream *UpstreamIDPConfig `yaml:"upstream,omitempty"`
}
OAuthConfig configures the OAuth server.
type OAuthRateLimitConfig ¶ added in v1.101.0
type OAuthRateLimitConfig struct {
Enabled *bool `yaml:"enabled"`
// TrustedProxies lists CIDRs whose X-Forwarded-For headers are trusted for
// client attribution. Empty (the default) trusts none: the direct peer
// address is used and forwarding headers are ignored, which is the correct
// safe default when the deployment's proxy topology is unknown.
TrustedProxies []string `yaml:"trusted_proxies"`
Token OAuthRateLimitRule `yaml:"token"` // default: 60 rpm, burst 10
Register OAuthRateLimitRule `yaml:"register"` // default: 10 rpm, burst 3
}
OAuthRateLimitConfig configures rate limiting for the unauthenticated OAuth /token and /register endpoints. Limiting is on by default (Enabled nil == enabled); each endpoint has a per-IP limit plus an internal global backstop that bounds total throughput regardless of client attribution.
type OAuthRateLimitRule ¶ added in v1.101.0
type OAuthRateLimitRule struct {
RequestsPerMinute int `yaml:"requests_per_minute"`
Burst int `yaml:"burst"`
}
OAuthRateLimitRule configures a single endpoint's per-IP limit.
type OIDCAuthConfig ¶
type OIDCAuthConfig struct {
Enabled bool `yaml:"enabled"`
Issuer string `yaml:"issuer"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"` // #nosec G117 -- OIDC secret from admin config
Audience string `yaml:"audience"`
RoleClaimPath string `yaml:"role_claim_path"`
RolePrefix string `yaml:"role_prefix"`
Scopes []string `yaml:"scopes"` // default: [openid, profile, email]
}
OIDCAuthConfig configures OIDC authentication.
type ObservabilityConfig ¶ added in v1.69.0
type ObservabilityConfig struct {
Prometheus PrometheusConfig `yaml:"prometheus"`
}
ObservabilityConfig configures the portal-facing observability features that read from Prometheus. The metrics emitters themselves are configured via environment (see pkg/observability/config.go); this YAML section configures the authenticated PromQL query proxy that the portal uses to read those metrics back.
type OllamaEmbedConfig ¶ added in v1.52.0
type OllamaEmbedConfig struct {
URL string `yaml:"url"`
Model string `yaml:"model"`
Timeout time.Duration `yaml:"timeout"`
// MaxInputBytes caps the byte length of each text sent to Ollama.
// Zero selects embedding.DefaultMaxInputBytes. Raise it only when
// running an embedding model with a larger context than
// nomic-embed-text's 2048 tokens. See embedding.DefaultMaxInputBytes
// and #623.
MaxInputBytes int `yaml:"max_input_bytes"`
}
OllamaEmbedConfig configures the Ollama embedding provider.
type Option ¶
type Option func(*Options)
Option is a functional option for configuring the platform.
func WithAuditLogger ¶
func WithAuditLogger(logger middleware.AuditLogger) Option
WithAuditLogger sets the audit logger. The logger is invoked synchronously on the tool-call path and must not block on storage; wrap a slow sink in audit.NewAsyncWriter (see Options.AuditLogger). Supplying a logger skips the platform's default async-writer wrapping.
func WithAuthenticator ¶
func WithAuthenticator(auth middleware.Authenticator) Option
WithAuthenticator sets the authenticator.
func WithAuthorizer ¶
func WithAuthorizer(authz middleware.Authorizer) Option
WithAuthorizer sets the authorizer.
func WithConnectionStore ¶ added in v1.57.2
func WithConnectionStore(store ConnectionStore) Option
WithConnectionStore sets the connection store.
When supplied, the platform skips its own connection-store initialization (which derives Postgres vs noop from the database configuration) and uses the injected store directly. The store's Persistent() return value still drives auto-enable behavior, so stateless test stubs that report Persistent()=false reproduce the no-database deployment shape.
func WithPersonaRegistry ¶
WithPersonaRegistry sets the persona registry.
func WithQueryProvider ¶
WithQueryProvider sets the query provider.
func WithRuleEngine ¶
func WithRuleEngine(engine *tuning.RuleEngine) Option
WithRuleEngine sets the rule engine.
func WithSemanticProvider ¶
WithSemanticProvider sets the semantic provider.
func WithSessionStore ¶ added in v0.15.0
WithSessionStore sets the session store.
func WithStorageProvider ¶
WithStorageProvider sets the storage provider.
func WithToolkitRegistry ¶
WithToolkitRegistry sets the toolkit registry.
type Options ¶
type Options struct {
// Config is the platform configuration.
Config *Config
// Database connection (optional, will be created from config if not provided).
DB *sql.DB
// SemanticProvider (optional, will be created from config if not provided).
SemanticProvider semantic.Provider
// QueryProvider (optional, will be created from config if not provided).
QueryProvider query.Provider
// StorageProvider (optional, will be created from config if not provided).
StorageProvider storage.Provider
// Authenticator (optional, will be created from config if not provided).
Authenticator middleware.Authenticator
// Authorizer (optional, will be created from config if not provided).
Authorizer middleware.Authorizer
// AuditLogger (optional, will be created from config if not provided).
// The audit middleware invokes Log synchronously on the tool-call path
// (the enqueue is expected to be non-blocking), so an injected logger
// MUST NOT block on storage — wrap a slow sink in audit.NewAsyncWriter,
// as the default config-created logger does (#884). The config-created
// path is already backed by a bounded async writer.
AuditLogger middleware.AuditLogger
// PersonaRegistry (optional, will be created from config if not provided).
PersonaRegistry *persona.Registry
// ToolkitRegistry (optional, will be created if not provided).
ToolkitRegistry *registry.Registry
// RuleEngine (optional, will be created from config if not provided).
RuleEngine *tuning.RuleEngine
// SessionStore (optional, will be created from config if not provided).
SessionStore session.Store
// ConnectionStore (optional, will be created from config if not provided).
// Allows tests to inject a controlled instance store without standing
// up a real database, and lets advanced embedders provide alternative
// persistence backends.
ConnectionStore ConnectionStore
}
Options configures the platform.
type PIIConsentConfig ¶ added in v0.21.0
type PIIConsentConfig struct {
// Enabled controls whether PII table access triggers elicitation.
// Enabled by default (nil = enabled); set enabled: false to disable.
Enabled *bool `yaml:"enabled"`
}
PIIConsentConfig configures PII access consent.
func (*PIIConsentConfig) IsEnabled ¶ added in v1.96.1
func (c *PIIConsentConfig) IsEnabled() bool
IsEnabled reports whether PII consent prompting is enabled, defaulting to true when not explicitly set.
type PersonaDef ¶
type PersonaDef struct {
DisplayName string `yaml:"display_name"`
Description string `yaml:"description,omitempty"`
Roles []string `yaml:"roles"`
Tools ToolRulesDef `yaml:"tools"`
Connections ConnectionRulesDef `yaml:"connections"`
Context ContextDef `yaml:"context"`
Priority int `yaml:"priority,omitempty"`
}
PersonaDef defines a persona.
type PersonaInfo ¶ added in v0.12.0
type PersonaInfo struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
Description string `json:"description,omitempty"`
}
PersonaInfo provides summary information about a persona.
type PersonasConfig ¶
type PersonasConfig struct {
Definitions map[string]PersonaDef `yaml:",inline"`
DefaultPersona string `yaml:"default_persona"`
RoleMapping RoleMappingConfig `yaml:"role_mapping"`
}
PersonasConfig holds persona definitions.
type Platform ¶
type Platform struct {
// contains filtered or unexported fields
}
Platform is the main platform facade.
func (*Platform) APIGatewayCatalogStore ¶ added in v1.61.5
func (p *Platform) APIGatewayCatalogStore() apigatewaycatalog.Store
APIGatewayCatalogStore returns the catalog store currently wired into the first api gateway toolkit, or nil when no toolkit has one wired. Used by the admin layer to share the same store for both reads (toolkit) and writes (admin CRUD).
func (*Platform) APIGatewayEmbedJobsStore ¶ added in v1.62.0
func (p *Platform) APIGatewayEmbedJobsStore() catalogindex.Store
APIGatewayEmbedJobsStore returns the api-catalog admin view of the index-jobs queue (enqueue + read-side queries for the UI), or nil when no queue is wired. The admin handler reads this.
func (*Platform) APIGatewayRawMaxBytes ¶ added in v1.77.0
APIGatewayRawMaxBytes returns the configured all-or-nothing size cap for the raw passthrough REST route, for the REST shim to enforce as a 413. 0 = no cap (the streamed path is memory-bounded regardless).
func (*Platform) APIKeyAuthenticator ¶ added in v0.17.0
func (p *Platform) APIKeyAuthenticator() *auth.APIKeyAuthenticator
APIKeyAuthenticator returns the API key authenticator, or nil if API keys are disabled.
func (*Platform) APIKeyStore ¶ added in v1.49.0
func (p *Platform) APIKeyStore() APIKeyStore
APIKeyStore returns the API key definition store, or nil if not initialized.
func (*Platform) AllPromptInfos ¶ added in v1.51.0
func (p *Platform) AllPromptInfos() []registry.PromptInfo
AllPromptInfos returns all prompt metadata (platform + toolkit). Delegates to the prompt layer owner; read by the admin and portal prompt REST handlers.
func (*Platform) AuditStore ¶ added in v0.17.0
func (p *Platform) AuditStore() *auditpostgres.Store
AuditStore returns the PostgreSQL audit store, or nil if audit is disabled.
func (*Platform) AuthEventStore ¶ added in v1.61.0
func (p *Platform) AuthEventStore() authevents.Store
AuthEventStore returns the read-side handle for connection lifecycle events. Used by the admin layer to render the OAuth History panel. Nil when no database is configured.
func (*Platform) AuthEventWriter ¶ added in v1.61.0
func (p *Platform) AuthEventWriter() *authevents.Writer
AuthEventWriter returns the writer wrapping AuthEventStore. nil-safe — every call site can pass this directly to a component without nil-checks; the Writer methods short-circuit when the receiver is nil. Wired into the admin handler and the toolkit auth paths.
func (*Platform) Authenticator ¶ added in v0.17.0
func (p *Platform) Authenticator() middleware.Authenticator
Authenticator returns the platform authenticator.
func (*Platform) BrandLogoSVG ¶ added in v1.38.5
BrandLogoSVG returns the resolved brand logo SVG content (from portal.logo or mcpapps platform-info config), or empty string if none is configured. Delegates to the branding owner.
func (*Platform) BrandURL ¶ added in v1.38.5
BrandURL returns the resolved brand URL from the mcpapps platform-info config (brand_url), or empty string if not configured. Delegates to the branding owner.
func (*Platform) Broadcaster ¶ added in v1.58.0
func (p *Platform) Broadcaster() session.Broadcaster
Broadcaster returns the platform's session broadcaster. Always non-nil after New — initSessions runs during platform construction and wires either a postgres LISTEN/NOTIFY broadcaster or an in-memory one.
func (*Platform) BrowserSessionAuth ¶ added in v0.32.0
func (p *Platform) BrowserSessionAuth() *browsersession.Authenticator
BrowserSessionAuth returns the cookie-based authenticator, or nil if browser sessions are disabled.
func (*Platform) BrowserSessionFlow ¶ added in v0.32.0
func (p *Platform) BrowserSessionFlow() *browsersession.Flow
BrowserSessionFlow returns the OIDC login flow, or nil if browser sessions are disabled.
func (*Platform) Close ¶
Close closes all platform resources in the correct order:
- Flush enrichment state, stop session cache, close session store
- Close audit logger + audit store (goroutine stops, can still use DB)
- Close providers and toolkit registry (trino, datahub, s3)
- Close database connection (last — nothing else needs it)
func (*Platform) ConfigStore ¶ added in v0.17.0
func (p *Platform) ConfigStore() configstore.Store
ConfigStore returns the config store.
func (*Platform) ConnOAuthStore ¶ added in v1.60.1
ConnOAuthStore returns the unified OAuth-token store backing the connection_oauth_tokens table. Used by the admin layer's unified OAuth handler and (via toolkit OAuthKindHandlers) by per-kind Authenticators. Nil when no database is configured — the platform falls back to the legacy per-kind in-memory stores in that case.
func (*Platform) ConnectionSources ¶ added in v1.48.0
func (p *Platform) ConnectionSources() *ConnectionSourceMap
ConnectionSources returns the connection→DataHub source mapping.
func (*Platform) ConnectionStore ¶ added in v1.48.0
func (p *Platform) ConnectionStore() ConnectionStore
ConnectionStore returns the connection instance store, or nil if not initialized.
func (*Platform) DB ¶ added in v1.57.0
DB returns the platform's database handle, or nil when running without a database. Exposed so consumers can build their own DB-backed stores (e.g., pkcestore.PostgresStore for multi-replica OAuth) without needing platform-side wiring per store.
func (*Platform) EmbeddingProvider ¶ added in v1.61.11
EmbeddingProvider returns the platform's embedding provider, or nil when no provider was configured. Exposed so the admin handler can compute and persist per-operation vectors at spec-write time (the path that replaces the in-process embedding warmer).
func (*Platform) EnrichmentStore ¶ added in v1.57.0
func (p *Platform) EnrichmentStore() enrichment.Store
EnrichmentStore returns the gateway enrichment rule store. Nil when no database is configured (the gateway toolkit still works without enrichment rules — they're optional).
func (*Platform) FileDefaults ¶ added in v1.48.0
FileDefaults returns the original file-based config values for whitelisted keys. Used to revert to file defaults when a DB override is deleted.
func (*Platform) FilePersonaNames ¶ added in v1.50.3
FilePersonaNames returns a copy of the persona names loaded from the config file.
func (*Platform) IndexJobsReporter ¶ added in v1.73.0
IndexJobsReporter returns the cross-kind index-jobs reporter the admin Indexing dashboard reads (per-kind counts, coverage, job list, re-index), or nil when no queue is wired (no database or no configured embedding provider). The dashboard renders a degraded empty state for the nil case.
func (*Platform) KnowledgeChangesetStore ¶ added in v0.17.0
func (p *Platform) KnowledgeChangesetStore() knowledgekit.ChangesetStore
KnowledgeChangesetStore returns the changeset store, or nil if knowledge apply is disabled.
func (*Platform) KnowledgeDataHubWriter ¶ added in v0.17.0
func (p *Platform) KnowledgeDataHubWriter() knowledgekit.DataHubWriter
KnowledgeDataHubWriter returns the DataHub writer, or nil if knowledge apply is disabled.
func (*Platform) KnowledgeInsightStore ¶ added in v0.17.0
func (p *Platform) KnowledgeInsightStore() knowledgekit.InsightStore
KnowledgeInsightStore returns the insight store, or nil if knowledge is disabled.
func (*Platform) KnowledgeRouter ¶ added in v1.88.0
KnowledgeRouter returns the unified search federation, or nil when no searchable source is configured. The portal's GET /api/v1/portal/search REST endpoint wraps it so the browser surfaces the same grouped, scope-enforced results as the MCP search tool.
func (*Platform) LoadManagedResources ¶ added in v1.55.7
func (p *Platform) LoadManagedResources()
LoadManagedResources registers all existing managed resources with the MCP server so they're visible on the first resources/list call. Delegates to the resourcelayer owner, passing the live p.mcpServer; called during platform initialization after finalizeSetup has created the server.
func (*Platform) MemoryStore ¶ added in v1.52.0
MemoryStore returns the memory store, or nil if memory is disabled.
func (*Platform) Metrics ¶ added in v1.64.0
func (p *Platform) Metrics() *observability.Metrics
Metrics exposes the platform's observability recorder. Returns nil when metrics are disabled; the type is nil-safe so callers can record unconditionally.
func (*Platform) NewGatewayIdentityResolver ¶ added in v1.69.0
func (p *Platform) NewGatewayIdentityResolver() *GatewayIdentityResolver
NewGatewayIdentityResolver builds the resolver from the platform's authenticator. Nil authenticator yields a resolver that always returns "unknown".
func (*Platform) NewObservabilityAuthorizer ¶ added in v1.69.0
func (p *Platform) NewObservabilityAuthorizer() proxy.Authorizer
NewObservabilityAuthorizer returns the proxy.Authorizer backed by the platform's auth stack. Used by cmd to build the PromQL proxy handler.
func (*Platform) OAuthServer ¶ added in v0.3.0
OAuthServer returns the OAuth server, or nil if not enabled.
func (*Platform) ObservabilityAuthMiddleware ¶ added in v1.69.1
ObservabilityAuthMiddleware resolves the portal browser-session cookie into a pre-authenticated user so the PromQL proxy (which the portal SPA calls directly) accepts cookie auth in addition to Bearer/API-key tokens. Without it, cookie-only portal requests carry no credentials the proxy can read and get bounced to the login page.
func (*Platform) PersonaRegistry ¶
PersonaRegistry returns the persona registry.
func (*Platform) PersonaStore ¶ added in v1.49.0
func (p *Platform) PersonaStore() personastore.Store
PersonaStore returns the persona definition store, or nil if not initialized.
func (*Platform) PlatformTools ¶ added in v0.18.2
PlatformTools returns tools registered directly on the platform outside of any toolkit.
func (*Platform) PortalAssetStore ¶ added in v0.32.0
func (p *Platform) PortalAssetStore() portal.AssetStore
PortalAssetStore returns the portal asset store, or nil if portal is disabled.
func (*Platform) PortalCollectionStore ¶ added in v1.47.0
func (p *Platform) PortalCollectionStore() portal.CollectionStore
PortalCollectionStore returns the portal collection store, or nil if portal is disabled.
func (*Platform) PortalKnowledgePageStore ¶ added in v1.88.0
func (p *Platform) PortalKnowledgePageStore() knowledgepage.Store
PortalKnowledgePageStore returns the canonical knowledge-page store, or nil when the portal is disabled.
func (*Platform) PortalS3Client ¶ added in v0.32.0
PortalS3Client returns the portal S3 client, or nil if portal is disabled.
func (*Platform) PortalShareStore ¶ added in v0.32.0
func (p *Platform) PortalShareStore() portal.ShareStore
PortalShareStore returns the portal share store, or nil if portal is disabled.
func (*Platform) PortalThreadStore ¶ added in v1.84.0
func (p *Platform) PortalThreadStore() portal.ThreadStore
PortalThreadStore returns the portal feedback thread store, or nil if portal is disabled.
func (*Platform) PortalVersionStore ¶ added in v1.43.0
func (p *Platform) PortalVersionStore() portal.VersionStore
PortalVersionStore returns the portal version store, or nil if portal is disabled.
func (*Platform) PromptStore ¶ added in v1.51.0
PromptStore returns the prompt definition store, or nil if not initialized. Delegates to the prompt layer owner.
func (*Platform) PublishAPIKeyReload ¶ added in v1.70.1
func (p *Platform) PublishAPIKeyReload()
PublishAPIKeyReload announces an API-key change to peer replicas.
func (*Platform) PublishCatalogReload ¶ added in v1.70.1
PublishCatalogReload announces an API-catalog spec change to peer replicas. Implements admin.ReloadNotifier. Safe when the layer is nil.
func (*Platform) PublishConnectionReload ¶ added in v1.70.1
func (p *Platform) PublishConnectionReload(kind, name string, op ConnectionReloadOp)
PublishConnectionReload announces a connection config change to peer replicas. op distinguishes an upsert (peers read the store) from a delete (peers remove without a store read). Implements admin.ReloadNotifier. Safe when the layer is nil.
func (*Platform) PublishPersonaReload ¶ added in v1.70.1
func (p *Platform) PublishPersonaReload()
PublishPersonaReload announces a persona change to peer replicas.
func (*Platform) QueryProvider ¶
QueryProvider returns the query provider.
func (*Platform) RegisterManagedResource ¶ added in v1.55.7
RegisterManagedResource registers a managed resource with the MCP server so it appears in the SDK's native resource list. Delegates to the resourcelayer owner, passing the live p.mcpServer (created after the resource layer is built); wired as the create callback of the REST resources API.
func (*Platform) RegisterRuntimePrompt ¶ added in v1.51.0
RegisterRuntimePrompt records a prompt's metadata at runtime after a create/update. Delegates to the prompt layer owner; called by the admin and portal prompt REST handlers.
func (*Platform) ResolveImplementorLogo ¶ added in v1.38.5
ResolveImplementorLogo fetches (once, then caches) the implementor logo SVG from portal.implementor.logo, or empty string if no logo URL is configured or the fetch fails. Delegates to the branding owner.
func (*Platform) ResourceS3Client ¶ added in v1.54.0
ResourceS3Client returns the S3 client for managed resources (nil if not configured).
func (*Platform) ResourceStore ¶ added in v1.54.0
ResourceStore returns the managed resource store (nil if not enabled).
func (*Platform) RestEncryptor ¶ added in v1.57.0
func (p *Platform) RestEncryptor() *fieldcrypt.RestFieldEncryptor
RestEncryptor returns the platform's at-rest field encryption adapter, or nil when no database is configured. Sub-package stores can pass this to their constructors so secrets they persist use the same key and format as connection credentials.
func (*Platform) RuleEngine ¶
func (p *Platform) RuleEngine() *tuning.RuleEngine
RuleEngine returns the rule engine.
func (*Platform) SemanticProvider ¶
SemanticProvider returns the semantic provider.
func (*Platform) SessionStore ¶ added in v0.15.0
SessionStore returns the session store.
func (*Platform) ShutdownMetricsListener ¶ added in v1.64.0
ShutdownMetricsListener stops the /metrics listener and flushes the meter provider. Both calls are nil-safe.
func (*Platform) StartConnOAuthRefresher ¶ added in v1.61.0
func (p *Platform) StartConnOAuthRefresher(resolver connoauth.ConfigResolver, multiReplica bool)
StartConnOAuthRefresher launches the background refresh loop with the supplied ConfigResolver. The platform exposes the start as a post-init step so the resolver — which depends on the per-kind OAuthKindHandlers wired by main.go — can be passed in at the correct point in the startup sequence (after ConnectionStore + OAuthKindHandlers exist, before the HTTP server starts taking traffic). Idempotent across replicas: the locker (NoopLocker for single-replica, PostgresLocker for multi-replica) keeps races out of the IdP side.
func (*Platform) StartMetricsListener ¶ added in v1.64.0
StartMetricsListener starts the /metrics HTTP listener if metrics are enabled. Safe to call when disabled (returns nil immediately).
func (*Platform) StopConnOAuthRefresher ¶ added in v1.61.0
StopConnOAuthRefresher cancels the refresher loop. Called by the lifecycle shutdown path so an in-flight refresh has up to ctx's deadline to settle before the process exits.
func (*Platform) StorageProvider ¶
StorageProvider returns the storage provider.
func (*Platform) ToolkitRegistry ¶
ToolkitRegistry returns the toolkit registry.
func (*Platform) UnregisterManagedResource ¶ added in v1.55.7
UnregisterManagedResource removes a managed resource from the MCP server's resource list. Delegates to the resourcelayer owner; wired as the delete callback of the REST resources API.
func (*Platform) UnregisterRuntimePrompt ¶ added in v1.51.0
UnregisterRuntimePrompt drops a database prompt's tracked metadata. Delegates to the prompt layer owner; called by the admin and portal prompt REST handlers.
func (*Platform) UserStore ¶ added in v1.85.0
UserStore returns the known-users directory store (nil when no database is configured). Delegates to the userdir owner.
func (*Platform) WireAPIGatewayCatalogStore ¶ added in v1.61.5
func (p *Platform) WireAPIGatewayCatalogStore(store apigatewaycatalog.Store)
WireAPIGatewayCatalogStore attaches the catalog.Store the toolkit uses to load OpenAPI specs referenced by connection.catalog_id. Mirrors WireAPIGatewayTokenStore in placement and lifecycle: safe to call multiple times, no-op when the catalog store is unwired (file-only deployments without a database).
After wiring the store, every already-registered connection is reloaded so connections that registered before the store became available pick up their catalog content immediately. Without this reload, the initial NewMulti call (which runs before platform-level wiring) would leave connections in the "catalog_id set but zero ops" state until the next admin save.
func (*Platform) WireAPIGatewayCatalogStoreFromDB ¶ added in v1.61.5
func (p *Platform) WireAPIGatewayCatalogStoreFromDB()
WireAPIGatewayCatalogStoreFromDB builds a Postgres-backed catalog store from the platform's *sql.DB and wires it into every api gateway toolkit. No-op when the platform was built without a database (file-only deployments).
func (*Platform) WireAPIGatewayEmbedJobsFromDB ¶ added in v1.62.0
func (p *Platform) WireAPIGatewayEmbedJobsFromDB()
WireAPIGatewayEmbedJobsFromDB initializes the shared index-jobs queue (pkg/platform/indexqueue) and wires its Start/Stop into the lifecycle. It translates platform config into indexqueue.Config — resolving worker tuning and retention, choosing the worker embedder, and reporting which optional consumers are enabled by the presence of their platform sub-store — then delegates assembly to the owner.
No-op unless the platform has BOTH a database connection AND a configured embedding provider: a queue without a worker that can embed is just an accumulating backlog, and standing the queue up against the noop provider would fill the vector tables with zero vectors the health endpoints report as "indexed" while ranking silently degrades (#429). File-mode and no-embedding deployments fall back to lexical ranking with no queue.
Idempotent: a second call is a no-op.
func (*Platform) WireAPIGatewayEmbeddingProvider ¶ added in v1.59.0
func (p *Platform) WireAPIGatewayEmbeddingProvider()
WireAPIGatewayEmbeddingProvider attaches the platform's embedding provider to every live api gateway toolkit. Enables the "semantic" and "hybrid" ranking modes of api_list_endpoints; when the platform was built without an embedding provider (memory disabled or explicitly noop) the call is a no-op and the toolkit silently falls back to lexical for any non-lexical request.
func (*Platform) WireAPIGatewayMemBudget ¶ added in v1.77.0
func (p *Platform) WireAPIGatewayMemBudget()
WireAPIGatewayMemBudget creates the process-wide in-flight memory budget (issue #535) and injects the same handle into every registered api gateway toolkit so buffered reads across all connections and both api_invoke_endpoint and api_export are accounted against one ceiling. Idempotent: the budget is created once and re-injected on subsequent calls (so toolkits registered later still pick it up). A zero/unset max yields a disabled (unlimited) budget that is still safe to call.
func (*Platform) WireAPIGatewayMetrics ¶ added in v1.64.0
func (p *Platform) WireAPIGatewayMetrics()
WireAPIGatewayMetrics pushes the platform's metrics recorder into every registered apigateway toolkit. Intended to run once at startup, before any MCP/HTTP listener starts accepting requests.
Idempotent against the same recorder: Toolkit.SetMetrics uses instrumentClient, which skips connections already wrapped for the same (connection, metrics) pair so a second call does not produce nested transports (and therefore double-recorded observations).
No-op when metrics are disabled or when no apigateway toolkit is loaded. Connections added to a toolkit BEFORE this call still get instrumented because Toolkit.SetMetrics walks the existing connection map.
func (*Platform) WireAPIGatewayRoutePolicy ¶ added in v1.59.0
func (p *Platform) WireAPIGatewayRoutePolicy()
WireAPIGatewayRoutePolicy installs a per-(connection, method, path) authorization gate on every live api gateway toolkit. No-op when the platform's authorizer is not the persona-based implementation (custom authorizers may opt in later via their own wiring).
Mirrors WireGatewayTokenStore / WireGatewayBroadcaster in placement and lifecycle. Safe to call before or after RegisterTools.
func (*Platform) WireAPIGatewayTokenStore ¶ added in v1.59.0
func (p *Platform) WireAPIGatewayTokenStore()
WireAPIGatewayTokenStore attaches the unified connoauth.Store to every live api gateway toolkit. Mirrors WireGatewayTokenStore in placement and lifecycle. Safe to call multiple times — the toolkit's SetConnOAuthStore re-threads any already-materialized authorization_code Authenticators.
func (*Platform) WireAdminSelfConnection ¶ added in v1.78.0
WireAdminSelfConnection registers a lifecycle hook that seeds the built-in platform-admin API-gateway connection, which points the gateway at the platform's own /api/v1/admin/* surface so an admin can operate the platform through api_list_endpoints / api_invoke_endpoint.
listenAddr is the server's bind address (e.g. ":8080"); the loopback base URL is derived from its port unless overridden in config. The caller is responsible for invoking this only when the admin REST API is actually mounted (HTTP transport), which together with a wired catalog store and api-gateway toolkit forms the feature's prerequisites. A disabled feature, or any absent prerequisite, makes this a no-op.
Idempotent: the seed re-runs on every boot. The catalog spec is re-upserted from the embedded OpenAPI document so a release that adds admin endpoints re-indexes them with no manual catalog action; the embed pipeline dedups unchanged operations by text hash.
func (*Platform) WireGatewayBroadcaster ¶ added in v1.58.0
func (p *Platform) WireGatewayBroadcaster()
WireGatewayBroadcaster attaches the platform's session broadcaster to every live gateway toolkit so SSE long-poll subscribers receive tools/list_changed events whenever a gateway connection is added, removed, or comes up after re-auth.
Mirrors WireGatewayTokenStore in placement and lifecycle. Safe to call before or after RegisterTools — gateway toolkits read the notifier atomically per call, so wiring order does not matter.
func (*Platform) WireGatewayIntegrations ¶ added in v1.100.2
func (p *Platform) WireGatewayIntegrations()
WireGatewayIntegrations runs the post-construction wiring the gateway and api-gateway toolkits need before the HTTP root handler is built, in dependency order. Every step is idempotent and no-ops when no gateway / api-gateway toolkit is loaded, so an entry point calls it unconditionally.
The order is load-bearing: the token store, broadcaster, route policy, api-gateway token store, embedding provider, and catalog store are wired first; the embed-job queue is wired LAST because it depends on the catalog store and embedding provider already being in place. Encapsulating the sequence here (rather than as a bare call list in the composition root) makes the ordering contract a single testable unit and keeps cmd/main.go thin.
func (*Platform) WireGatewayTokenStore ¶ added in v1.57.2
func (p *Platform) WireGatewayTokenStore()
WireGatewayTokenStore attaches the unified connoauth.Store to every live gateway toolkit in the registry so authorization_code grants survive process restarts. No-op when no database is configured.
Lives on Platform (not in cmd/main.go) so the post-construction wiring step is part of the platform contract — testable without spinning up a full main, and discoverable for any future entry-point that builds a Platform.
Calling SetConnOAuthStore on a gateway toolkit that already has placeholder authorization_code connections will retry their dial path so persisted tokens come live without requiring an additional admin action. This is what makes auto-enabled gateway toolkits work on a fresh boot.
func (*Platform) WireRuntime ¶ added in v1.100.3
func (p *Platform) WireRuntime(rc RuntimeConfig)
WireRuntime performs the post-Start, transport-aware wiring sequence in one code-defined order. It replaces the loose run of Wire* calls that used to sit in main.go, whose correct sequence was "documented nowhere but main.go itself" (#756): a reordering compiled and passed unit tests yet failed at runtime.
The order encodes a real data-flow dependency, not a convention:
- WireAPIGatewayMetrics and WireAPIGatewayMemBudget instrument the api-gateway toolkits and install the process-wide in-flight memory budget (OOM guard, #535). Both transports.
- WireGatewayIntegrations wires the gateway/api-gateway stores — including the api-catalog store and the embed-jobs queue. HTTP only.
- WireAdminSelfConnection then seeds the platform-admin self-connection, which READS the catalog store and embed-jobs queue that WireGatewayIntegrations just wired. Run it before that step and the seed finds no catalog store and silently no-ops — the exact "compiles, unit tests pass, fails at runtime" trap #756 calls out.
Every step is individually idempotent and nil-safe, so WireRuntime is safe to call once per boot regardless of which subsystems are configured.
func (*Platform) WireToolkitMetrics ¶ added in v1.70.0
func (p *Platform) WireToolkitMetrics()
WireToolkitMetrics pushes the recorder into every registered toolkit that implements SetMetrics. It MUST run before the registry registers tool handlers: the S3 toolkit installs an mcp-s3 middleware in SetMetrics that is only effective if present at registration time. apigateway also implements SetMetrics; wiring it here as well is idempotent (see WireAPIGatewayMetrics). Runs when metrics OR tracing is enabled so toolkits that emit spans (S3) are instrumented for tracing-only deployments; each toolkit's SetMetrics decides what it installs given the (possibly disabled) recorder.
type PortalConfig ¶ added in v0.32.0
type PortalConfig struct {
Enabled *bool `yaml:"enabled"`
Title string `yaml:"title"` // sidebar/branding title (default: "MCP Data Platform")
Tagline string `yaml:"tagline"` // login-screen subtitle (default: "Sign in to access the platform.")
OIDCButtonLabel string `yaml:"oidc_button_label"` // login-screen SSO button text (default: "Sign in with OIDC")
Logo string `yaml:"logo"` // URL to logo (fallback for both themes)
LogoLight string `yaml:"logo_light"` // URL to logo for light theme
LogoDark string `yaml:"logo_dark"` // URL to logo for dark theme
S3Connection string `yaml:"s3_connection"` // name of the S3 toolkit instance to use
S3Bucket string `yaml:"s3_bucket"` // bucket for artifact storage (default: "portal-assets")
S3Prefix string `yaml:"s3_prefix"` // key prefix within the bucket (default: "artifacts/")
PublicBaseURL string `yaml:"public_base_url"` // base URL for portal links (e.g., "https://portal.example.com")
MaxContentSize int `yaml:"max_content_size"` // max artifact size in bytes (default: 10MB)
Implementor ImplementorConfig `yaml:"implementor"` // optional implementor brand (far-left header zone)
RateLimit PortalRateLimitConfig `yaml:"rate_limit"`
Export PortalExportConfig `yaml:"export"` // trino_export configuration
}
PortalConfig configures the asset portal for saving AI-generated artifacts. Enabled by default when a database is available. Set enabled: false to disable.
type PortalExportConfig ¶ added in v1.56.0
type PortalExportConfig struct {
Enabled *bool `yaml:"enabled"` // auto-enabled when portal+trino are configured
MaxRows int `yaml:"max_rows"` // hard row cap (default: 100000)
MaxBytes int64 `yaml:"max_bytes"` // hard byte cap (default: 100MB)
DefaultTimeout string `yaml:"default_timeout"` // default query timeout (default: "5m")
MaxTimeout string `yaml:"max_timeout"` // max query timeout (default: "10m")
}
PortalExportConfig configures the trino_export tool.
type PortalRateLimitConfig ¶ added in v0.32.0
type PortalRateLimitConfig struct {
RequestsPerMinute int `yaml:"requests_per_minute"` // default: 60
BurstSize int `yaml:"burst_size"` // default: 10
// TrustedProxies lists CIDRs whose X-Forwarded-For headers are trusted for
// client attribution, mirroring oauth.rate_limit.trusted_proxies. Empty (the
// default) trusts none: the direct peer address is used and forwarding
// headers are ignored, which is the correct safe default when the
// deployment's proxy topology is unknown. Set this to your reverse-proxy or
// ingress CIDRs so per-client limiting attributes to the real client instead
// of collapsing onto the proxy IP.
TrustedProxies []string `yaml:"trusted_proxies"`
}
PortalRateLimitConfig configures rate limiting for the public portal viewer.
type PostgresAPIKeyStore ¶ added in v1.49.0
type PostgresAPIKeyStore struct {
// contains filtered or unexported fields
}
PostgresAPIKeyStore implements APIKeyStore backed by PostgreSQL.
func NewPostgresAPIKeyStore ¶ added in v1.49.0
func NewPostgresAPIKeyStore(db *sql.DB) *PostgresAPIKeyStore
NewPostgresAPIKeyStore creates a new PostgreSQL-backed API key store.
func (*PostgresAPIKeyStore) Delete ¶ added in v1.49.0
func (s *PostgresAPIKeyStore) Delete(ctx context.Context, name string) error
Delete removes an API key definition by name.
func (*PostgresAPIKeyStore) List ¶ added in v1.49.0
func (s *PostgresAPIKeyStore) List(ctx context.Context) ([]APIKeyDefinition, error)
List returns all API key definitions.
func (*PostgresAPIKeyStore) Set ¶ added in v1.49.0
func (s *PostgresAPIKeyStore) Set(ctx context.Context, def APIKeyDefinition) error
Set creates or updates an API key definition.
type PostgresConnectionStore ¶ added in v1.48.0
type PostgresConnectionStore struct {
// contains filtered or unexported fields
}
PostgresConnectionStore implements ConnectionStore backed by PostgreSQL. Sensitive config fields (password, token, secret_access_key, etc.) are encrypted at rest using AES-256-GCM when an encryption key is configured.
func NewPostgresConnectionStore ¶ added in v1.48.0
func NewPostgresConnectionStore(db *sql.DB, encryptor *fieldcrypt.FieldEncryptor) *PostgresConnectionStore
NewPostgresConnectionStore creates a new PostgreSQL-backed connection store. The encryptor may be nil (encryption disabled — values stored in plain text).
func (*PostgresConnectionStore) Delete ¶ added in v1.48.0
func (s *PostgresConnectionStore) Delete(ctx context.Context, kind, name string) error
Delete removes a connection instance by kind and name.
func (*PostgresConnectionStore) Get ¶ added in v1.48.0
func (s *PostgresConnectionStore) Get(ctx context.Context, kind, name string) (*ConnectionInstance, error)
Get returns a single connection instance by kind and name.
func (*PostgresConnectionStore) List ¶ added in v1.48.0
func (s *PostgresConnectionStore) List(ctx context.Context) ([]ConnectionInstance, error)
List returns all connection instances ordered by kind and name.
func (*PostgresConnectionStore) Persistent ¶ added in v1.57.2
func (*PostgresConnectionStore) Persistent() bool
Persistent reports that PostgreSQL-backed storage survives restarts.
func (*PostgresConnectionStore) Set ¶ added in v1.48.0
func (s *PostgresConnectionStore) Set(ctx context.Context, inst ConnectionInstance) error
Set creates or updates a connection instance. Sensitive config fields are encrypted before storage.
type ProgressConfig ¶ added in v0.20.0
type ProgressConfig struct {
Enabled *bool `yaml:"enabled"`
}
ProgressConfig configures progress notifications during tool execution. Enabled by default (nil = enabled); set enabled: false to disable.
func (*ProgressConfig) IsEnabled ¶ added in v1.96.1
func (c *ProgressConfig) IsEnabled() bool
IsEnabled reports whether progress notifications are enabled, defaulting to true when not explicitly set.
type PrometheusConfig ¶ added in v1.69.0
type PrometheusConfig struct {
URL string `yaml:"url"`
Timeout time.Duration `yaml:"timeout"`
BasicAuth BasicAuthConfig `yaml:"basic_auth"`
// RateLimitPerSecond caps proxied queries per persona per second.
// Zero selects the default (10).
RateLimitPerSecond int `yaml:"rate_limit_per_second"`
}
PrometheusConfig points the PromQL query proxy at a Prometheus instance. An empty URL leaves the proxy unconfigured: its endpoints return 503 so the portal can render a clean empty state.
type PromptArgumentConfig ¶ added in v1.38.0
type PromptArgumentConfig struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Required bool `yaml:"required"`
}
PromptArgumentConfig defines an argument for a platform-level MCP prompt.
type PromptConfig ¶ added in v0.11.0
type PromptConfig struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Content string `yaml:"content"`
Arguments []PromptArgumentConfig `yaml:"arguments"`
}
PromptConfig defines a platform-level MCP prompt.
type QueryConfig ¶
type QueryConfig struct {
Provider string `yaml:"provider"` // "trino", "noop"
Instance string `yaml:"instance"`
URNMapping URNMappingConfig `yaml:"urn_mapping"`
}
QueryConfig configures the query provider.
type RateLimitConfig ¶ added in v1.102.0
type RateLimitConfig struct {
// Enabled toggles the limiter. Enabled by default (nil = enabled); set
// enabled: false to remove the limiter from the chain entirely. The
// generous default keeps default-on safe for existing deployments.
Enabled *bool `yaml:"enabled"`
// RequestsPerMinute is the sustained per-user tools/call rate. Non-positive
// values fall back to the default (defaultRateLimitRPM).
RequestsPerMinute int `yaml:"requests_per_minute"`
// Burst is the token-bucket depth: the largest instantaneous burst a single
// user may issue before the sustained rate governs. Non-positive values fall
// back to the default (defaultRateLimitBurst).
Burst int `yaml:"burst"`
// ExemptTools lists tool names that are never rate limited. platform_info is
// always exempt (added implicitly) so a throttled agent can still re-read
// the platform guidance it needs to back off intelligently; add others here.
ExemptTools []string `yaml:"exempt_tools"`
}
RateLimitConfig configures the per-identity token-bucket limiter on authenticated MCP tools/call requests (issue #929). It is a safety net, not a throughput throttle: the default limit is generous enough that ordinary interactive and agent use never touches it, but a runaway agent loop or a compromised account hammering an expensive tool is bounded before it can saturate the audit pipeline, the shared database pool, or an upstream (Trino, DataHub, S3, a proxied MCP server).
The limit is per authenticated user (see PlatformContext.RateLimitKey), not per IP: a multi-user connector delivers every user's traffic from one egress address, so per-IP limiting would be both useless (one bucket for everyone) and harmful (one busy user starves the rest). Keying on identity matches the abuse shape the limiter exists to catch — a single runaway authenticated principal — regardless of source address.
The bucket is in-memory per replica: behind a load balancer the effective ceiling is (replica count x the configured limit). This is intentional for a backstop — distributed coordination (Redis/DB round-trips on the hot tool path) is not warranted to bound abuse that per-replica limiting already bounds. Size the limit with the per-replica semantics in mind.
func (*RateLimitConfig) EffectiveBurst ¶ added in v1.102.0
func (c *RateLimitConfig) EffectiveBurst() int
EffectiveBurst returns the configured bucket depth, or the default when the operator left it unset or non-positive.
func (*RateLimitConfig) EffectiveRPM ¶ added in v1.102.0
func (c *RateLimitConfig) EffectiveRPM() int
EffectiveRPM returns the configured sustained rate, or the default when the operator left it unset or non-positive.
func (*RateLimitConfig) IsEnabled ¶ added in v1.102.0
func (c *RateLimitConfig) IsEnabled() bool
IsEnabled reports whether the per-user tool-call rate limiter is enabled, defaulting to true when not explicitly set.
type ResourcesConfig ¶ added in v0.20.0
type ResourcesConfig struct {
// Enabled gates the schema/glossary/availability resource templates and the
// DataHub->Trino resource links (ResourceLinksEnabled). Read-only serving, so
// it defaults to true (nil = enabled); set false to disable. Read via IsEnabled.
Enabled *bool `yaml:"enabled"`
Custom []CustomResourceDef `yaml:"custom"` // always registered when non-empty
Managed ManagedResourcesCfg `yaml:"managed"` // human-uploaded resources via portal
}
ResourcesConfig configures MCP resource templates and managed resources.
func (*ResourcesConfig) IsEnabled ¶ added in v1.83.0
func (c *ResourcesConfig) IsEnabled() bool
IsEnabled reports whether the resource templates and DataHub->Trino resource links are served, defaulting to true when not explicitly set.
type ReviewQueueInfo ¶ added in v1.100.0
type ReviewQueueInfo struct {
Pending int `json:"pending"`
OldestPendingAgeDays int `json:"oldest_pending_age_days,omitempty"`
PendingOver30d int `json:"pending_over_30d,omitempty"`
}
ReviewQueueInfo summarizes the pending apply_knowledge review queue so an agent can nudge a reviewer about aging review debt, e.g. "6 insights pending review, oldest 94 days" (#764). It is present only for a caller who can reach apply_knowledge and only when the queue is non-empty.
type RoleMappingConfig ¶
RoleMappingConfig configures role mapping.
type RulesConfig ¶
type RulesConfig struct {
QualityThreshold float64 `yaml:"quality_threshold"`
}
RulesConfig configures operational rules.
type RuntimeConfig ¶ added in v1.100.3
type RuntimeConfig struct {
// Transport is the resolved server transport ("stdio", "http", or "sse").
Transport string
// Address is the server's listen address (e.g. ":8080"). It supplies the
// port for the loopback base URL of the platform-admin self-connection.
Address string
}
RuntimeConfig carries the transport-dependent inputs the entry point resolves after config overrides are applied — the runtime transport and listen address. These are not known at platform.New / Start time (the factory constructs and starts the platform before flags/config decide the transport), so they are threaded in through WireRuntime rather than the constructor.
type SemanticConfig ¶
type SemanticConfig struct {
Provider string `yaml:"provider"` // "datahub", "noop"
Instance string `yaml:"instance"`
Cache CacheConfig `yaml:"cache"`
URNMapping URNMappingConfig `yaml:"urn_mapping"`
Lineage datahubsemantic.LineageConfig `yaml:"lineage"`
}
SemanticConfig configures the semantic layer.
type ServerConfig ¶
type ServerConfig struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
Description string `yaml:"description"`
Tags []string `yaml:"tags"` // Discovery keywords for routing
AgentInstructions string `yaml:"agent_instructions"` // Inline operational guidance for AI agents
Prompts []PromptConfig `yaml:"prompts"` // Platform-level MCP prompts
BuiltinPrompts map[string]bool `yaml:"builtin_prompts"` // Enable/disable built-in workflow prompts
Transport string `yaml:"transport"` // "stdio", "http" (or "sse" for backward compat)
Address string `yaml:"address"`
TLS TLSConfig `yaml:"tls"`
Streamable StreamableConfig `yaml:"streamable"`
Shutdown ShutdownConfig `yaml:"shutdown"`
}
ServerConfig configures the MCP server.
type SessionDedupConfig ¶ added in v0.14.0
SessionDedupConfig configures session-level metadata deduplication. It lives in the dedup sub-package (extracted to keep pkg/platform under its size budget); the alias keeps the platform.SessionDedupConfig name stable for callers.
type SessionGateConfig ¶ added in v0.31.0
type SessionGateConfig struct {
// Enabled activates the session initialization gate.
Enabled bool `yaml:"enabled"`
// InitTool is the tool that initializes the session (default: "platform_info").
InitTool string `yaml:"init_tool"`
// ExemptTools lists tool names that bypass the gate (e.g., "list_connections").
ExemptTools []string `yaml:"exempt_tools"`
}
SessionGateConfig configures the session initialization gate that requires agents to call platform_info before using any other tool.
type SessionHandlesConfig ¶ added in v1.98.0
type SessionHandlesConfig struct {
// Enabled activates handle minting, schema advertisement, and validation.
// Default on (nil = enabled); set enabled: false for byte-identical legacy
// transport-session behavior.
Enabled *bool `yaml:"enabled"`
// TTL is the handle lifetime, refreshed on use. Defaults to 8h.
TTL time.Duration `yaml:"ttl"`
// Require refuses any gated tool call that does not carry a valid
// platform_info-minted handle (SESSION_REQUIRED). A transport session is not
// accepted as a fallback (issue #800). Default on (nil = required); set
// require: false for a softer landing during rollout, where a handle-less
// call falls back to the transport session instead of being refused.
Require *bool `yaml:"require"`
}
SessionHandlesConfig configures explicit session handles (issue #792): the platform_info-minted session_id that the model passes back on every tool call, replacing reliance on the transport-level Mcp-Session-Id header.
func (SessionHandlesConfig) HandleTTL ¶ added in v1.98.0
func (c SessionHandlesConfig) HandleTTL() time.Duration
HandleTTL returns the configured handle lifetime, or the 8h default when unset or non-positive.
func (SessionHandlesConfig) IsEnabled ¶ added in v1.98.0
func (c SessionHandlesConfig) IsEnabled() bool
IsEnabled reports whether explicit session handles are enabled, defaulting to true when not explicitly set.
func (SessionHandlesConfig) IsRequired ¶ added in v1.98.0
func (c SessionHandlesConfig) IsRequired() bool
IsRequired reports whether a valid platform_info-minted handle is required on every gated tool call, defaulting to true when not explicitly set.
type SessionsConfig ¶ added in v0.15.0
type SessionsConfig struct {
// Store selects the session storage backend: "memory" (default) or "database".
Store string `yaml:"store"`
// TTL is the session lifetime. Defaults to streamable.session_timeout.
TTL time.Duration `yaml:"ttl"`
// CleanupInterval is how often the cleanup routine runs. Defaults to 1m.
CleanupInterval time.Duration `yaml:"cleanup_interval"`
// BroadcastChannel overrides the postgres LISTEN/NOTIFY channel name
// used for cross-replica MCP notification fan-out. Defaults to
// "mcp_notifications". Override when multiple deployments share a
// single postgres instance and must NOT cross-broadcast
// tools/list_changed events to each other's downstream agents.
BroadcastChannel string `yaml:"broadcast_channel"`
// Handles configures explicit session handles (issue #792). When enabled,
// platform_info mints a session_id that the model threads back as an
// ordinary argument on every subsequent tool call — the pattern the MCP
// 2026-07-28 spec recommends after removing the protocol-level session and
// the Mcp-Session-Id header (SEP-2567).
Handles SessionHandlesConfig `yaml:"handles"`
}
SessionsConfig configures session externalization.
type ShutdownConfig ¶ added in v0.15.0
type ShutdownConfig struct {
// GracePeriod is the maximum time to drain in-flight requests after
// receiving a shutdown signal. Defaults to 25s (fits within K8s 30s
// terminationGracePeriodSeconds with headroom for pre-shutdown delay).
GracePeriod time.Duration `yaml:"grace_period"`
// PreShutdownDelay is the time to sleep after marking the pod as
// not-ready and before starting the HTTP drain. This gives the K8s
// load balancer time to deregister the pod. Defaults to 2s.
PreShutdownDelay time.Duration `yaml:"pre_shutdown_delay"`
}
ShutdownConfig configures graceful shutdown timing.
type StalenessConfig ¶ added in v1.52.0
type StalenessConfig struct {
Enabled bool `yaml:"enabled"`
Interval time.Duration `yaml:"interval"`
BatchSize int `yaml:"batch_size"`
}
StalenessConfig configures the memory staleness watcher.
type StorageConfig ¶
type StorageConfig struct {
Provider string `yaml:"provider"` // "s3", "noop"
Instance string `yaml:"instance"`
}
StorageConfig configures the storage provider.
type StreamableConfig ¶ added in v0.13.0
type StreamableConfig struct {
// SessionTimeout is how long an idle session persists before cleanup.
// Defaults to 30 minutes.
SessionTimeout time.Duration `yaml:"session_timeout"`
// Stateless disables session tracking (no Mcp-Session-Id validation).
Stateless bool `yaml:"stateless"`
}
StreamableConfig configures the Streamable HTTP transport.
type TLSConfig ¶
type TLSConfig struct {
Enabled bool `yaml:"enabled"`
CertFile string `yaml:"cert_file"`
KeyFile string `yaml:"key_file"`
}
TLSConfig configures TLS.
type ToolInfo ¶ added in v0.18.2
ToolInfo describes a tool registered directly on the platform (not via a toolkit).
type ToolRulesDef ¶
ToolRulesDef defines tool access rules.
type ToolsConfig ¶ added in v0.18.0
type ToolsConfig struct {
Allow []string `yaml:"allow"`
Deny []string `yaml:"deny"`
DescriptionOverrides map[string]string `yaml:"description_overrides"`
}
ToolsConfig configures global tool visibility filtering for tools/list responses. This is a visibility filter to reduce token usage — not a security boundary. Persona auth continues to gate tools/call independently.
type TuningConfig ¶
type TuningConfig struct {
Rules RulesConfig `yaml:"rules"`
PromptsDir string `yaml:"prompts_dir"`
}
TuningConfig configures AI tuning.
type URNMappingConfig ¶ added in v0.6.0
type URNMappingConfig struct {
// Platform overrides the platform name used in DataHub URN building.
// For example, if Trino queries a PostgreSQL database, set this to "postgres"
// so URNs match DataHub's platform identifier.
Platform string `yaml:"platform"`
// CatalogMapping maps catalog names between systems.
// For semantic provider: maps Trino catalogs to DataHub catalogs (rdbms → warehouse)
// For query provider: maps DataHub catalogs to Trino catalogs (warehouse → rdbms)
CatalogMapping map[string]string `yaml:"catalog_mapping"`
}
URNMappingConfig configures URN translation between query engines and metadata catalogs. This is necessary when Trino catalog/platform names differ from DataHub's metadata catalog names.
type UpstreamIDPConfig ¶ added in v0.3.0
type UpstreamIDPConfig struct {
Issuer string `yaml:"issuer"` // OIDC issuer URL (any OIDC-compliant IdP, e.g. Keycloak)
ClientID string `yaml:"client_id"` // MCP Server's client ID in the upstream IdP
ClientSecret string `yaml:"client_secret"` // #nosec G117 -- MCP Server's client secret from admin YAML config
RedirectURI string `yaml:"redirect_uri"` // Callback URL (e.g., http://localhost:8080/oauth/callback)
// AuthorizationEndpoint and TokenEndpoint optionally override OIDC discovery.
// By default the broker discovers these from
// <issuer>/.well-known/openid-configuration; set them only for IdPs whose
// discovery document is broken or unreachable. Discovery is skipped entirely
// only when BOTH are set.
AuthorizationEndpoint string `yaml:"authorization_endpoint,omitempty"`
TokenEndpoint string `yaml:"token_endpoint,omitempty"`
}
UpstreamIDPConfig configures the upstream identity provider (e.g., Keycloak).
type VersionConverter ¶ added in v0.16.0
VersionConverter converts raw YAML bytes directly to the latest Config. A nil converter means the version uses standard YAML unmarshalling.
type VersionInfo ¶ added in v0.16.0
type VersionInfo struct {
// Version is the version string (e.g., "v1").
Version string
// Status is the lifecycle state of this version.
Status VersionStatus
// DeprecationMessage is shown when a deprecated version is loaded.
DeprecationMessage string
// MigrationGuide is shown when a removed version is loaded.
MigrationGuide string
// Converter transforms raw YAML bytes into a Config. Nil means
// standard YAML unmarshalling is used (i.e., the version matches
// the current schema).
Converter VersionConverter
}
VersionInfo describes a config API version.
type VersionRegistry ¶ added in v0.16.0
type VersionRegistry struct {
// contains filtered or unexported fields
}
VersionRegistry holds known config API versions.
func DefaultRegistry ¶ added in v0.16.0
func DefaultRegistry() *VersionRegistry
DefaultRegistry returns the standard version registry with v1 registered.
func NewVersionRegistry ¶ added in v0.16.0
func NewVersionRegistry() *VersionRegistry
NewVersionRegistry creates an empty version registry.
func (*VersionRegistry) Current ¶ added in v0.16.0
func (r *VersionRegistry) Current() string
Current returns the current version string.
func (*VersionRegistry) Get ¶ added in v0.16.0
func (r *VersionRegistry) Get(version string) (*VersionInfo, bool)
Get returns the version info for the given version string.
func (*VersionRegistry) IsDeprecated ¶ added in v0.16.0
func (r *VersionRegistry) IsDeprecated(version string) bool
IsDeprecated returns true if the version exists and is deprecated.
func (*VersionRegistry) ListSupported ¶ added in v0.16.0
func (r *VersionRegistry) ListSupported() []string
ListSupported returns all non-removed version strings, sorted.
func (*VersionRegistry) Register ¶ added in v0.16.0
func (r *VersionRegistry) Register(info *VersionInfo)
Register adds a version to the registry. If current is empty and this is the first VersionCurrent entry, it becomes the current version.
type VersionStatus ¶ added in v0.16.0
type VersionStatus int
VersionStatus represents the lifecycle state of a config version.
const ( // VersionCurrent is an actively supported version. VersionCurrent VersionStatus = iota // VersionDeprecated is a version that still works but emits warnings. VersionDeprecated // VersionRemoved is a version that is no longer supported. VersionRemoved )
func (VersionStatus) String ¶ added in v0.16.0
func (s VersionStatus) String() string
String returns a human-readable representation of the version status.
type WorkflowConfig ¶ added in v0.27.0
type WorkflowConfig struct {
// RequireSearch is the search-first hard gate. Enabled by default
// (nil = enabled); set require_search: false to fully disable gating.
// When enabled, query tools are refused (the handler never runs) until a
// discovery tool has been called at least once in the session.
RequireSearch *bool `yaml:"require_search"`
// DiscoveryTools lists tool names that satisfy the gate.
// Defaults to just "search", the universal discovery front door.
DiscoveryTools []string `yaml:"discovery_tools"`
// QueryTools lists tool names that are gated by discovery.
// Defaults to trino_query and trino_execute.
QueryTools []string `yaml:"query_tools"`
}
WorkflowConfig configures the search-first gate that refuses Trino query tools until a discovery tool has been called in the session.
func (*WorkflowConfig) IsRequireSearchEnabled ¶ added in v1.97.0
func (c *WorkflowConfig) IsRequireSearchEnabled() bool
IsRequireSearchEnabled reports whether the search-first gate is enabled, defaulting to true when not explicitly set.
Source Files
¶
- admin_self_connection.go
- apigateway_embed_jobs.go
- apikey_store.go
- config.go
- config_migrate.go
- config_version.go
- connection_source.go
- connection_store.go
- connections_tool.go
- custom_resources.go
- find_tools_tool.go
- info_tool.go
- lifecycle.go
- middleware_chain.go
- observability.go
- options.go
- platform.go
- reload.go
- resource_templates.go
- runtime.go
- tool_schemas.go
- tools_index.go
- user_directory.go
- validation.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fieldcrypt provides AES-256-GCM encryption of sensitive fields within connection-config maps, plus the RestFieldEncryptor adapter used by sub-package stores (gateway OAuth tokens, PKCE state).
|
Package fieldcrypt provides AES-256-GCM encryption of sensitive fields within connection-config maps, plus the RestFieldEncryptor adapter used by sub-package stores (gateway OAuth tokens, PKCE state). |
|
Package instructions owns the agent-facing instruction text the platform presents through platform_info: the platform-owned "how to operate" baseline (#646), the full instruction composition (baseline beneath the admin business context, persona tuning, and runtime notes), and the platform_info tool's own title and description.
|
Package instructions owns the agent-facing instruction text the platform presents through platform_info: the platform-owned "how to operate" baseline (#646), the full instruction composition (baseline beneath the admin business context, persona tuning, and runtime notes), and the platform_info tool's own title and description. |
|
Package personastore persists database-managed persona definitions, independent of the platform assembly.
|
Package personastore persists database-managed persona definitions, independent of the platform assembly. |