Documentation
¶
Index ¶
- Variables
- func InitializeAnalytics(cfg *AnalyticsConfig) error
- func IsAnalyticsEnabled() bool
- func IsReadOnlyStatement(stmtType StatementType) bool
- func IsWriteStatement(stmtType StatementType) bool
- func ListAvailableConnections() ([]string, error)
- func NewServer(opts *ServerOptions) *mcp.Server
- func ResolveConnection(name string) (*dbmgr.Connection, error)
- func ResolveConnectionOrDefault(name string) (*dbmgr.Connection, error)
- func Run(ctx context.Context, server *mcp.Server) error
- func RunHTTP(ctx context.Context, server *mcp.Server, opts *HTTPOptions, ...) error
- func ShutdownAnalytics()
- func TrackError(ctx context.Context, toolName, requestID, operation string, errMsg string)
- func TrackServerStart(ctx context.Context, transport string, securityMode string, ...)
- func TrackToolCall(ctx context.Context, toolName, requestID string, success bool, ...)
- func ValidateColumnsInput(input *ColumnsInput, connectionCount int) error
- func ValidateConfirmInput(input *ConfirmInput) error
- func ValidateQueryInput(input *QueryInput, connectionCount int) error
- func ValidateSQLStatement(query string, allowWrite bool, securityLevel SecurityLevel, ...) error
- func ValidateSchemasInput(input *SchemasInput, connectionCount int) error
- func ValidateTablesInput(input *TablesInput, connectionCount int) error
- type AnalyticsConfig
- type ColumnInfo
- type ColumnsInput
- type ColumnsOutput
- type ConfirmInput
- type ConfirmOutput
- type ConnectionInfo
- type ConnectionsInput
- type ConnectionsOutput
- type HTTPOptions
- type PendingConfirmation
- type PendingInfo
- type PendingInput
- type PendingOutput
- type QueryInput
- type QueryOutput
- type SchemaDetail
- type SchemasInput
- type SchemasOutput
- type SecurityLevel
- type SecurityOptions
- type ServerOptions
- type StatementType
- type TableInfo
- type TablesInput
- type TablesOutput
- type ToolEnablement
- type TransportType
Constants ¶
This section is empty.
Variables ¶
var ( ErrWriteNotAllowed = errors.New("write operations are not allowed in read-only mode") ErrMultipleStatements = errors.New("multiple SQL statements are not allowed") ErrDangerousFunction = errors.New("dangerous database function detected") ErrDestructiveOperation = errors.New("destructive operation detected") )
SQL validation errors
var ( ErrQueryRequired = errors.New("query is required and cannot be empty") ErrTableRequired = errors.New("table is required - specify which table to describe") ErrTokenRequired = errors.New("token is required - use the confirmation_token from the previous query response") ErrTokenInvalid = errors.New("token is not a valid confirmation token format") ErrConnectionRequired = errors.New("connection is required when multiple connections are configured (use whodb_connections to list available connections)") )
Input validation errors - designed to be helpful for AI assistants
var Version = "dev"
Version is set at build time.
Functions ¶
func InitializeAnalytics ¶
func InitializeAnalytics(cfg *AnalyticsConfig) error
InitializeAnalytics sets up PostHog analytics for the MCP server. Analytics are enabled by default and can be disabled via: - WHODB_MCP_ANALYTICS_DISABLED=true environment variable - --no-analytics flag
func IsAnalyticsEnabled ¶
func IsAnalyticsEnabled() bool
IsAnalyticsEnabled returns whether analytics are currently active.
func IsReadOnlyStatement ¶
func IsReadOnlyStatement(stmtType StatementType) bool
IsReadOnlyStatement returns true if the statement type is read-only.
func IsWriteStatement ¶
func IsWriteStatement(stmtType StatementType) bool
IsWriteStatement returns true if the statement type modifies data.
func ListAvailableConnections ¶
ListAvailableConnections returns all available connection names from saved connections and environment profiles (for example, WHODB_POSTGRES='[...]' or WHODB_MYSQL_1='{...}').
func NewServer ¶
func NewServer(opts *ServerOptions) *mcp.Server
NewServer creates a new WhoDB MCP server with all tools registered.
func ResolveConnection ¶
func ResolveConnection(name string) (*dbmgr.Connection, error)
ResolveConnection resolves a connection name to a database.Connection using saved connections and environment profiles (for example, WHODB_POSTGRES='[...]' or WHODB_MYSQL_1='{...}').
func ResolveConnectionOrDefault ¶
func ResolveConnectionOrDefault(name string) (*dbmgr.Connection, error)
ResolveConnectionOrDefault resolves a connection by name, or returns the default connection if name is empty and exactly one connection is available. Returns an error if name is empty and zero or multiple connections exist.
func ShutdownAnalytics ¶
func ShutdownAnalytics()
ShutdownAnalytics flushes pending events and closes the analytics client.
func TrackError ¶
TrackError captures an MCP error event.
func TrackServerStart ¶
func TrackServerStart(ctx context.Context, transport string, securityMode string, props map[string]any)
TrackServerStart captures an MCP server start event.
func TrackToolCall ¶
func TrackToolCall(ctx context.Context, toolName, requestID string, success bool, durationMs int64, props map[string]any)
TrackToolCall captures an MCP tool invocation event.
func ValidateColumnsInput ¶
func ValidateColumnsInput(input *ColumnsInput, connectionCount int) error
ValidateColumnsInput validates the input for whodb_columns tool.
func ValidateConfirmInput ¶
func ValidateConfirmInput(input *ConfirmInput) error
ValidateConfirmInput validates the input for whodb_confirm tool.
func ValidateQueryInput ¶
func ValidateQueryInput(input *QueryInput, connectionCount int) error
ValidateQueryInput validates the input for whodb_query tool.
func ValidateSQLStatement ¶
func ValidateSQLStatement(query string, allowWrite bool, securityLevel SecurityLevel, allowMultiStatement bool, allowDestructive bool) error
ValidateSQLStatement validates a SQL statement against security rules. Parameters:
- allowWrite: permits INSERT/UPDATE/DELETE/CREATE/ALTER
- allowDestructive: permits DROP/TRUNCATE (requires explicit opt-in via --allow-drop or --confirm-writes)
func ValidateSchemasInput ¶
func ValidateSchemasInput(input *SchemasInput, connectionCount int) error
ValidateSchemasInput validates the input for whodb_schemas tool.
func ValidateTablesInput ¶
func ValidateTablesInput(input *TablesInput, connectionCount int) error
ValidateTablesInput validates the input for whodb_tables tool.
Types ¶
type AnalyticsConfig ¶
type AnalyticsConfig struct {
// Enabled controls whether analytics are active. Default: true
Enabled bool
// AppVersion is the CLI version for tracking.
AppVersion string
}
AnalyticsConfig holds MCP analytics configuration.
type ColumnInfo ¶
type ColumnInfo struct {
Name string `json:"name"`
Type string `json:"type"`
IsPrimary bool `json:"is_primary"`
IsForeignKey bool `json:"is_foreign_key"`
ReferencedTable string `json:"referenced_table,omitempty"`
ReferencedColumn string `json:"referenced_column,omitempty"`
}
ColumnInfo represents information about a database column.
type ColumnsInput ¶
type ColumnsInput struct {
// Connection is the name of a saved connection or environment profile.
Connection string `json:"connection" jsonschema:"Connection name (optional if only one exists)"`
// Schema containing the table
Schema string `json:"schema,omitempty" jsonschema:"Schema name (uses default if omitted)"`
// Table name to describe
Table string `json:"table" jsonschema:"Table name to describe"`
}
ColumnsInput is the input for the whodb_columns tool.
type ColumnsOutput ¶
type ColumnsOutput struct {
Columns []ColumnInfo `json:"columns"`
Table string `json:"table"`
Schema string `json:"schema"`
Error string `json:"error,omitempty"`
RequestID string `json:"request_id,omitempty"` // Unique ID for request tracing
}
ColumnsOutput is the output for the whodb_columns tool.
func HandleColumns ¶
func HandleColumns(ctx context.Context, req *mcp.CallToolRequest, input ColumnsInput) (*mcp.CallToolResult, ColumnsOutput, error)
HandleColumns describes columns in a table.
func (ColumnsOutput) MarshalJSON ¶
func (o ColumnsOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null.
type ConfirmInput ¶
type ConfirmInput struct {
// Token is the confirmation token from a previous query response
Token string `json:"token" jsonschema:"Confirmation token from a previous whodb_query response"`
}
ConfirmInput is the input for the whodb_confirm tool.
type ConfirmOutput ¶
type ConfirmOutput struct {
Columns []string `json:"columns"`
ColumnTypes []string `json:"column_types,omitempty"`
Rows [][]any `json:"rows"`
Error string `json:"error,omitempty"`
Message string `json:"message,omitempty"`
RequestID string `json:"request_id,omitempty"` // Unique ID for request tracing
}
ConfirmOutput is the output for the whodb_confirm tool.
func HandleConfirm ¶
func HandleConfirm(ctx context.Context, req *mcp.CallToolRequest, input ConfirmInput, secOpts *SecurityOptions) (*mcp.CallToolResult, ConfirmOutput, error)
HandleConfirm confirms and executes a pending write operation.
func (ConfirmOutput) MarshalJSON ¶
func (o ConfirmOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null, which the MCP SDK's output schema validator requires.
type ConnectionInfo ¶
type ConnectionInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
Database string `json:"database,omitempty"`
Schema string `json:"schema,omitempty"`
Source string `json:"source"` // "env" or "saved"
}
ConnectionInfo represents a connection (without sensitive data).
type ConnectionsInput ¶
type ConnectionsInput struct{}
ConnectionsInput is the input for the whodb_connections tool.
type ConnectionsOutput ¶
type ConnectionsOutput struct {
Connections []ConnectionInfo `json:"connections"`
Error string `json:"error,omitempty"`
RequestID string `json:"request_id,omitempty"` // Unique ID for request tracing
}
ConnectionsOutput is the output for the whodb_connections tool.
func HandleConnections ¶
func HandleConnections(ctx context.Context, req *mcp.CallToolRequest, input ConnectionsInput) (*mcp.CallToolResult, ConnectionsOutput, error)
HandleConnections lists all available connections.
func (ConnectionsOutput) MarshalJSON ¶
func (o ConnectionsOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null.
type HTTPOptions ¶
type HTTPOptions struct {
// Host to bind to (default: "localhost").
Host string
// Port to listen on (default: 3000).
Port int
}
HTTPOptions configures the HTTP transport.
type PendingConfirmation ¶
PendingConfirmation stores a query awaiting user confirmation
type PendingInfo ¶
type PendingInfo struct {
Token string `json:"token"`
Query string `json:"query"`
Connection string `json:"connection"`
ExpiresAt string `json:"expires_at"` // ISO 8601
}
PendingInfo represents a pending confirmation visible to the LLM.
type PendingInput ¶
type PendingInput struct{}
PendingInput is the input for the whodb_pending tool (no parameters needed).
type PendingOutput ¶
type PendingOutput struct {
Pending []PendingInfo `json:"pending"`
Error string `json:"error,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
PendingOutput is the output for the whodb_pending tool.
func HandlePending ¶
func HandlePending(ctx context.Context, req *mcp.CallToolRequest, input PendingInput, secOpts *SecurityOptions) (*mcp.CallToolResult, PendingOutput, error)
HandlePending lists all non-expired pending confirmations.
func (PendingOutput) MarshalJSON ¶
func (o PendingOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null.
type QueryInput ¶
type QueryInput struct {
// Connection is the name of a saved connection or environment profile.
Connection string `json:"connection" jsonschema:"Connection name (optional if only one exists)"`
// Query is the SQL query to execute
Query string `json:"query" jsonschema:"SQL query to execute"`
// Parameters for parameterized queries (optional).
// Use placeholders in the query ($1, $2 for Postgres; ? for MySQL/SQLite).
// Example: query="SELECT * FROM users WHERE id = $1", parameters=[42]
Parameters []any `json:"parameters,omitempty" jsonschema:"Parameterized query values ($1/$2 for Postgres or ? for MySQL/SQLite)"`
}
QueryInput is the input for the whodb_query tool.
type QueryOutput ¶
type QueryOutput struct {
Columns []string `json:"columns"`
ColumnTypes []string `json:"column_types,omitempty"`
Rows [][]any `json:"rows"`
Error string `json:"error,omitempty"`
Warning string `json:"warning,omitempty"`
ConfirmationRequired bool `json:"confirmation_required,omitempty"`
ConfirmationToken string `json:"confirmation_token,omitempty"`
ConfirmationQuery string `json:"confirmation_query,omitempty"`
ConfirmationExpiry string `json:"confirmation_expiry,omitempty"` // ISO 8601 timestamp when the token expires
RequestID string `json:"request_id,omitempty"` // Unique ID for request tracing
}
QueryOutput is the output for the whodb_query tool.
func HandleQuery ¶
func HandleQuery(ctx context.Context, req *mcp.CallToolRequest, input QueryInput, secOpts *SecurityOptions) (*mcp.CallToolResult, QueryOutput, error)
HandleQuery executes a SQL query against the specified connection with security validation.
func (QueryOutput) MarshalJSON ¶
func (o QueryOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null, which the MCP SDK's output schema validator requires.
type SchemaDetail ¶
SchemaDetail holds a schema name and optionally its tables.
type SchemasInput ¶
type SchemasInput struct {
// Connection is the name of a saved connection or environment profile.
Connection string `json:"connection" jsonschema:"Connection name (optional if only one exists)"`
// IncludeTables returns the tables within each schema in a single call.
// Reduces round-trips when you need both schemas and tables.
IncludeTables bool `json:"include_tables,omitempty" jsonschema:"Set true to also return tables within each schema in a single call"`
}
SchemasInput is the input for the whodb_schemas tool.
type SchemasOutput ¶
type SchemasOutput struct {
Schemas []string `json:"schemas"`
Details []SchemaDetail `json:"details,omitempty"` // Populated when include_tables=true
Error string `json:"error,omitempty"`
RequestID string `json:"request_id,omitempty"` // Unique ID for request tracing
}
SchemasOutput is the output for the whodb_schemas tool.
func HandleSchemas ¶
func HandleSchemas(ctx context.Context, req *mcp.CallToolRequest, input SchemasInput) (*mcp.CallToolResult, SchemasOutput, error)
HandleSchemas lists all schemas in the database.
func (SchemasOutput) MarshalJSON ¶
func (o SchemasOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null.
type SecurityLevel ¶
type SecurityLevel string
SecurityLevel defines the strictness of SQL validation for MCP access control.
const ( SecurityLevelStrict SecurityLevel = "strict" // Blocks writes + dangerous functions SecurityLevelStandard SecurityLevel = "standard" // Blocks writes SecurityLevelMinimal SecurityLevel = "minimal" // Only blocks DROP/TRUNCATE/DELETE without WHERE )
type SecurityOptions ¶
type SecurityOptions struct {
ReadOnly bool
ConfirmWrites bool
SecurityLevel SecurityLevel
QueryTimeout time.Duration
MaxRows int
AllowMultiStatement bool
AllowDrop bool
DefaultConnection string // Injected connection when not specified
AllowedConnections []string // If set, only these connections are accessible
}
SecurityOptions contains runtime security settings for query execution
type ServerOptions ¶
type ServerOptions struct {
// Logger for server messages (defaults to stderr).
Logger *slog.Logger
// Instructions provides guidance to LLMs on how to use this server.
Instructions string
// ReadOnly prevents INSERT, UPDATE, DELETE, DROP, CREATE, ALTER, TRUNCATE operations.
// Default: true
ReadOnly bool
// ConfirmWrites enables human-in-the-loop confirmation for write operations.
// When enabled, write operations return a confirmation token that must be approved.
// Default: false
ConfirmWrites bool
// SecurityLevel controls the strictness of query validation.
// Options: "strict", "standard", "minimal". Default: "standard"
SecurityLevel SecurityLevel
// QueryTimeout is the maximum time a query can run before being cancelled.
// Default: 30 seconds
QueryTimeout time.Duration
// MaxRows limits the number of rows returned by queries.
// Default: 0 (unlimited). Set via --max-rows to enable truncation.
MaxRows int
// AllowMultiStatement permits multiple SQL statements in one query (separated by semicolons).
// WARNING: Enabling this increases SQL injection risk.
// Default: false
AllowMultiStatement bool
// AllowDrop permits DROP/TRUNCATE operations even in allow-write mode.
// Without this, DROP is blocked unless --confirm-writes is used
// Default: false
AllowDrop bool
// EnabledTools specifies which tools to enable. If empty, all tools are enabled.
// Valid values: "query", "schemas", "tables", "columns", "connections", "confirm"
EnabledTools []string
// DisabledTools specifies which tools to disable. Takes precedence over EnabledTools.
// Valid values: "query", "schemas", "tables", "columns", "connections", "confirm"
DisabledTools []string
// DefaultConnection is the connection to use when none is specified.
// This simplifies AI interaction when working with a single database.
DefaultConnection string
// AllowedConnections restricts which connections can be used.
// When set, only these connections are visible and accessible.
// If DefaultConnection is not set, the first allowed connection becomes the default.
AllowedConnections []string
}
ServerOptions configures the MCP server.
type StatementType ¶
type StatementType string
StatementType represents the type of SQL statement.
const ( StatementSelect StatementType = "SELECT" StatementInsert StatementType = "INSERT" StatementUpdate StatementType = "UPDATE" StatementDelete StatementType = "DELETE" StatementDrop StatementType = "DROP" StatementCreate StatementType = "CREATE" StatementAlter StatementType = "ALTER" StatementTruncate StatementType = "TRUNCATE" StatementShow StatementType = "SHOW" StatementDescribe StatementType = "DESCRIBE" StatementExplain StatementType = "EXPLAIN" StatementWith StatementType = "WITH" StatementUnknown StatementType = "UNKNOWN" )
func DetectStatementType ¶
func DetectStatementType(query string) StatementType
DetectStatementType returns the type of SQL statement.
type TableInfo ¶
type TableInfo struct {
Name string `json:"name"`
Attributes map[string]string `json:"attributes,omitempty"`
Columns []ColumnInfo `json:"columns,omitempty"` // Populated when include_columns=true
}
TableInfo represents information about a database table.
type TablesInput ¶
type TablesInput struct {
// Connection is the name of a saved connection or environment profile.
Connection string `json:"connection" jsonschema:"Connection name (optional if only one exists)"`
// Schema to list tables from (uses default if not specified)
Schema string `json:"schema,omitempty" jsonschema:"Schema name (uses default if omitted)"`
// IncludeColumns returns column details for each table in a single call.
// Reduces round-trips when you need both tables and their columns.
IncludeColumns bool `json:"include_columns,omitempty" jsonschema:"Set true to also return column details for each table in a single call"`
}
TablesInput is the input for the whodb_tables tool.
type TablesOutput ¶
type TablesOutput struct {
Tables []TableInfo `json:"tables"`
Schema string `json:"schema"`
Error string `json:"error,omitempty"`
RequestID string `json:"request_id,omitempty"` // Unique ID for request tracing
}
TablesOutput is the output for the whodb_tables tool.
func HandleTables ¶
func HandleTables(ctx context.Context, req *mcp.CallToolRequest, input TablesInput) (*mcp.CallToolResult, TablesOutput, error)
HandleTables lists all tables in a schema.
func (TablesOutput) MarshalJSON ¶
func (o TablesOutput) MarshalJSON() ([]byte, error)
MarshalJSON ensures nil slices are serialized as [] instead of null.
type ToolEnablement ¶
ToolEnablement tracks which tools should be registered.
type TransportType ¶
type TransportType string
TransportType specifies the transport mechanism for the MCP server.
const ( // TransportStdio uses stdin/stdout for communication (default, for CLI integration). TransportStdio TransportType = "stdio" // TransportHTTP runs as an HTTP server with streaming support. TransportHTTP TransportType = "http" )