middleware

package
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package middleware provides the middleware chain for tool handlers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetToken added in v0.13.0

func GetToken(ctx context.Context) string

GetToken retrieves an authentication token from the context.

func MCPAuditMiddleware added in v0.7.0

func MCPAuditMiddleware(logger AuditLogger) mcp.Middleware

MCPAuditMiddleware creates MCP protocol-level middleware that logs tool calls for auditing purposes.

This middleware intercepts tools/call requests and:

  1. Records the start time
  2. Executes the tool handler
  3. Gets the PlatformContext (set by MCPToolCallMiddleware)
  4. Builds an audit event with all captured information
  5. Logs asynchronously (non-blocking) to avoid impacting response time

func MCPRuleEnforcementMiddleware added in v0.12.0

func MCPRuleEnforcementMiddleware(engine *tuning.RuleEngine, _ *tuning.HintManager) mcp.Middleware

MCPRuleEnforcementMiddleware creates MCP protocol-level middleware that enforces operational rules and adds guidance to tool responses.

This middleware intercepts tools/call responses and: 1. Checks if the tool is a query tool that should have DataHub context first 2. Adds warnings for rule violations to the response 3. Does NOT block requests - it only adds informational guidance.

func MCPSemanticEnrichmentMiddleware added in v0.7.0

func MCPSemanticEnrichmentMiddleware(
	semanticProvider semantic.Provider,
	queryProvider query.Provider,
	storageProvider storage.Provider,
	cfg EnrichmentConfig,
) mcp.Middleware

MCPSemanticEnrichmentMiddleware creates MCP protocol-level middleware that enriches tool call responses with semantic context.

This middleware intercepts tools/call responses and adds cross-service context:

  • Trino results get DataHub metadata (descriptions, owners, tags, etc.)
  • DataHub results get Trino query context (can query? sample SQL?)
  • S3 results get semantic metadata for matching datasets

func MCPToolCallMiddleware added in v0.4.0

func MCPToolCallMiddleware(authenticator Authenticator, authorizer Authorizer, toolkitLookup ToolkitLookup, transport string) mcp.Middleware

MCPToolCallMiddleware creates MCP protocol-level middleware that intercepts tools/call requests and enforces authentication and authorization.

This middleware runs at the MCP protocol level, intercepting all incoming requests before they reach tool handlers. For tools/call requests, it: 1. Extracts the tool name from the request 2. Creates a PlatformContext with the tool information 3. Looks up toolkit metadata (kind, name, connection) 4. Runs authentication to identify the user 5. Runs authorization to check if the user can access the tool 6. Either proceeds with the call or returns an access denied error

The transport parameter identifies the server transport ("stdio" or "http"). The toolkitLookup parameter is optional; if nil, toolkit metadata won't be populated.

func NewToolResultError

func NewToolResultError(errMsg string) *mcp.CallToolResult

NewToolResultError creates an error result.

func NewToolResultText

func NewToolResultText(text string) *mcp.CallToolResult

NewToolResultText creates a text result.

func WithPlatformContext

func WithPlatformContext(ctx context.Context, pc *PlatformContext) context.Context

WithPlatformContext adds platform context to the context.

func WithToken added in v0.13.0

func WithToken(ctx context.Context, token string) context.Context

WithToken adds an authentication token to the context.

Types

type AuditEvent

type AuditEvent struct {
	Timestamp         time.Time      `json:"timestamp"`
	RequestID         string         `json:"request_id"`
	SessionID         string         `json:"session_id"`
	UserID            string         `json:"user_id"`
	UserEmail         string         `json:"user_email"`
	Persona           string         `json:"persona"`
	ToolName          string         `json:"tool_name"`
	ToolkitKind       string         `json:"toolkit_kind"`
	ToolkitName       string         `json:"toolkit_name"`
	Connection        string         `json:"connection"`
	Parameters        map[string]any `json:"parameters"`
	Success           bool           `json:"success"`
	ErrorMessage      string         `json:"error_message,omitempty"`
	DurationMS        int64          `json:"duration_ms"`
	ResponseChars     int            `json:"response_chars"`
	RequestChars      int            `json:"request_chars"`
	ContentBlocks     int            `json:"content_blocks"`
	Transport         string         `json:"transport"`
	Source            string         `json:"source"`
	EnrichmentApplied bool           `json:"enrichment_applied"`
	Authorized        bool           `json:"authorized"`
}

AuditEvent represents an auditable event.

type AuditLogger

type AuditLogger interface {
	// Log records an audit event.
	Log(ctx context.Context, event AuditEvent) error
}

AuditLogger logs tool calls for auditing.

func NewAuditStoreAdapter added in v0.12.0

func NewAuditStoreAdapter(store *auditpostgres.Store) AuditLogger

NewAuditStoreAdapter creates an AuditLogger that logs to a PostgreSQL audit store.

type Authenticator

type Authenticator interface {
	// Authenticate validates credentials and returns user info.
	Authenticate(ctx context.Context) (*UserInfo, error)
}

Authenticator validates authentication credentials.

type Authorizer

type Authorizer interface {
	// IsAuthorized checks if the user can use the tool.
	// Returns:
	//   - authorized: whether the user is authorized
	//   - personaName: the resolved persona name (for audit logging)
	//   - reason: reason for denial (empty if authorized)
	IsAuthorized(ctx context.Context, userID string, roles []string, toolName string) (authorized bool, personaName string, reason string)
}

Authorizer checks if a user is authorized for a tool.

func AllowAllAuthorizer

func AllowAllAuthorizer() Authorizer

AllowAllAuthorizer authorizes all requests.

type DedupMode added in v0.14.0

type DedupMode string

DedupMode controls what content is sent for previously-enriched tables.

const (
	// DedupModeReference sends a minimal reference (table name, description, note).
	DedupModeReference DedupMode = "reference"

	// DedupModeSummary sends table-level semantic_context without column_context.
	DedupModeSummary DedupMode = "summary"

	// DedupModeNone sends no enrichment at all for repeat queries.
	DedupModeNone DedupMode = "none"
)

type EnrichmentConfig

type EnrichmentConfig struct {
	// EnrichTrinoResults adds semantic context to Trino tool results.
	EnrichTrinoResults bool

	// EnrichDataHubResults adds query context to DataHub tool results.
	EnrichDataHubResults bool

	// EnrichS3Results adds semantic context to S3 tool results.
	EnrichS3Results bool

	// EnrichDataHubStorageResults adds storage context to DataHub tool results.
	EnrichDataHubStorageResults bool

	// SessionCache enables session-level metadata deduplication.
	// If nil, dedup is disabled and full enrichment is always sent.
	SessionCache *SessionEnrichmentCache

	// DedupMode controls what content is sent for previously-enriched tables.
	// Only used when SessionCache is non-nil.
	DedupMode DedupMode
}

EnrichmentConfig configures semantic enrichment.

type NoopAuditLogger

type NoopAuditLogger struct{}

NoopAuditLogger discards all audit events.

func (*NoopAuditLogger) Log

Log does nothing.

type NoopAuthenticator

type NoopAuthenticator struct {
	DefaultUserID string
	DefaultRoles  []string
}

NoopAuthenticator always succeeds authentication.

func (*NoopAuthenticator) Authenticate

func (n *NoopAuthenticator) Authenticate(_ context.Context) (*UserInfo, error)

Authenticate always returns a default user.

type NoopAuthorizer

type NoopAuthorizer struct{}

NoopAuthorizer always authorizes.

func (*NoopAuthorizer) IsAuthorized

func (*NoopAuthorizer) IsAuthorized(_ context.Context, _ string, _ []string, _ string) (authorized bool, personaName, reason string)

IsAuthorized always returns true with empty persona name.

type PlatformContext

type PlatformContext struct {
	// Request identification
	RequestID string
	SessionID string
	StartTime time.Time

	// User information
	UserID      string
	UserEmail   string
	UserClaims  map[string]any
	Roles       []string
	PersonaName string

	// Tool information
	ToolName    string
	ToolkitKind string
	ToolkitName string
	Connection  string

	// Authorization
	Authorized bool
	AuthzError string

	// Transport metadata
	Transport string // "stdio" or "http"
	Source    string // "mcp", "admin", "inspector"

	// Enrichment tracking (set by enrichment middleware, read by audit)
	EnrichmentApplied bool

	// Results (populated after handler)
	Success      bool
	ErrorMessage string
	Duration     time.Duration
}

PlatformContext holds platform-specific context for a request.

func GetPlatformContext

func GetPlatformContext(ctx context.Context) *PlatformContext

GetPlatformContext retrieves platform context from the context.

func MustGetPlatformContext

func MustGetPlatformContext(ctx context.Context) *PlatformContext

MustGetPlatformContext retrieves platform context or panics.

func NewPlatformContext

func NewPlatformContext(requestID string) *PlatformContext

NewPlatformContext creates a new platform context.

type SessionEnrichmentCache added in v0.14.0

type SessionEnrichmentCache struct {
	// contains filtered or unexported fields
}

SessionEnrichmentCache tracks which tables have been enriched per client session, enabling deduplication of large semantic metadata blocks.

func NewSessionEnrichmentCache added in v0.14.0

func NewSessionEnrichmentCache(entryTTL, sessionTimeout time.Duration) *SessionEnrichmentCache

NewSessionEnrichmentCache creates a new session enrichment cache.

func (*SessionEnrichmentCache) EntryTTL added in v0.15.3

func (c *SessionEnrichmentCache) EntryTTL() time.Duration

EntryTTL returns the configured entry TTL for diagnostics.

func (*SessionEnrichmentCache) ExportSessions added in v0.15.0

func (c *SessionEnrichmentCache) ExportSessions() map[string]map[string]time.Time

ExportSessions returns all session dedup states for persistence. Each map entry maps a session ID to its sent-table timestamps.

func (*SessionEnrichmentCache) LoadSession added in v0.15.0

func (c *SessionEnrichmentCache) LoadSession(sessionID string, sentTables map[string]time.Time)

LoadSession pre-populates dedup state for a session from external storage. This is used on startup to restore enrichment dedup continuity from the session store.

func (*SessionEnrichmentCache) MarkSent added in v0.14.0

func (c *SessionEnrichmentCache) MarkSent(sessionID, tableKey string)

MarkSent records that full enrichment was sent for the given table in this session.

func (*SessionEnrichmentCache) SessionCount added in v0.14.0

func (c *SessionEnrichmentCache) SessionCount() int

SessionCount returns the number of tracked sessions.

func (*SessionEnrichmentCache) StartCleanup added in v0.14.0

func (c *SessionEnrichmentCache) StartCleanup(interval time.Duration)

StartCleanup starts a background goroutine that evicts idle sessions.

func (*SessionEnrichmentCache) Stop added in v0.14.0

func (c *SessionEnrichmentCache) Stop()

Stop stops the background cleanup goroutine.

func (*SessionEnrichmentCache) WasSentRecently added in v0.14.0

func (c *SessionEnrichmentCache) WasSentRecently(sessionID, tableKey string) bool

WasSentRecently returns true if the table was enriched within the entry TTL for this session.

type TableRef added in v0.9.3

type TableRef struct {
	Catalog  string
	Schema   string
	Table    string
	FullPath string
	Source   string // "FROM", "JOIN", "TABLE_FUNCTION"
}

TableRef represents an extracted table reference from SQL.

func ExtractTablesFromSQL added in v0.9.3

func ExtractTablesFromSQL(sql string) []TableRef

ExtractTablesFromSQL extracts all table references from SQL. Uses regex for Trino-specific functions and standard table patterns. Combines ES raw_query indices with regular table references (e.g., JOINs). Filters out CTE references to only return physical tables.

type ToolkitLookup added in v0.12.1

type ToolkitLookup interface {
	// GetToolkitForTool returns toolkit info (kind, name, connection) for a tool.
	// Returns Found=false if the tool is not found in any registered toolkit.
	GetToolkitForTool(toolName string) registry.ToolkitMatch
}

ToolkitLookup provides toolkit metadata for a given tool name.

type UserInfo

type UserInfo struct {
	UserID   string
	Email    string
	Claims   map[string]any
	Roles    []string
	AuthType string // "oidc", "apikey", etc.
}

UserInfo holds authenticated user information.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL