serv

package module
v3.18.31 Latest Latest
Warning

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

Go to latest
Published: May 31, 2026 License: Apache-2.0 Imports: 101 Imported by: 4

Documentation

Overview

Package serv provides an API to include and use the GraphJin service with your own code. For detailed documentation visit https://graphjin.com

Example usage:

package main

import (
	"database/sql"
	"fmt"
	"time"
	"github.com/dosco/graphjin/core/v3"
	_ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
	conf := serv.Config{ AppName: "Test App" }
	conf.DB.Host := "127.0.0.1"
	conf.DB.Port := 5432
	conf.DB.DBName := "test_db"
	conf.DB.User := "postgres"
	conf.DB.Password := "postgres"

	gjs, err := serv.NewGraphJinService(conf)
	if err != nil {
		log.Fatal(err)
	}

 	if err := gjs.Start(); err != nil {
		log.Fatal(err)
	}
}

Index

Constants

View Source
const (
	ExecKindColumnNotFound = "column_not_found"
	ExecKindTableNotFound  = "table_not_found"
	ExecKindTypeMismatch   = "type_mismatch"
	ExecKindSyntaxError    = "syntax_error"
	ExecKindPermission     = "permission_denied"
	ExecKindUnknown        = ""
)
View Source
const (
	CatalogOverviewResourceURI     = "graphjin://catalog/overview"
	CatalogEntrypointsResourceURI  = "graphjin://catalog/entrypoints"
	CatalogCapabilitiesResourceURI = "graphjin://catalog/capabilities"
	QuerySyntaxResourceURI         = "graphjin://syntax/query"
	MutationSyntaxResourceURI      = "graphjin://syntax/mutation"
	WorkflowGuideResourceURI       = "graphjin://guides/workflow"
)
View Source
const JSRuntimeResourceURI = "graphjin://syntax/workflow-js"

Variables

View Source
var ErrGraphJinNotInitialized = errors.New("GraphJin not initialized - no database configured")

ErrGraphJinNotInitialized is returned when GraphJin core is not initialized

Functions

func GetConfigName

func GetConfigName() string

GetConfigName returns the name of the configuration

func InitAdmin

func InitAdmin(db *sql.DB, dbtype string) error

InitAdmin creates the admin tables

func InitTelemetry

func InitTelemetry(
	context context.Context,
	exporter trace.SpanExporter,
	serviceName, serviceInstanceID string,
) error

InitTelemetry initializes the OpenTelemetry SDK with the given exporter and service name.

func MCPAllToolNames added in v3.18.5

func MCPAllToolNames() []string

MCPAllToolNames returns the full superset of MCP tools GraphJin may expose. This is used by the CLI to publish first-class commands for every server tool.

func NewDB

func NewDB(conf *Config, openDB bool, log *zap.SugaredLogger, fs core.FS) (*sql.DB, error)

Config holds the configuration for the service

Types

type AggregationInfo added in v3.2.1

type AggregationInfo struct {
	Available   []string `json:"available"`
	Usage       string   `json:"usage"`
	Limitations []string `json:"limitations,omitempty"`
}

AggregationInfo describes available aggregation functions for a table

type AggregationsSyntax added in v3.2.1

type AggregationsSyntax struct {
	Functions []string `json:"functions"`
	Usage     string   `json:"usage"`
	WithGroup string   `json:"with_group"`
}

AggregationsSyntax describes available aggregation functions

type AnalyticsDirectivesSyntax added in v3.18.19

type AnalyticsDirectivesSyntax struct {
	Directives []string `json:"directives"`
	Usage      string   `json:"usage"`
	Arguments  string   `json:"arguments"`
	Rules      []string `json:"rules"`
	Dialects   string   `json:"dialects"`
}

AnalyticsDirectivesSyntax describes GraphJin reporting directives.

type ApplyDatabaseSetupResult added in v3.10.3

type ApplyDatabaseSetupResult struct {
	Applied       bool              `json:"applied"`
	Success       bool              `json:"success"`
	Message       string            `json:"message"`
	DatabaseAlias string            `json:"database_alias,omitempty"`
	TableCount    int               `json:"table_count"`
	Tables        []string          `json:"tables,omitempty"`
	Verification  ApplyVerification `json:"verification"`
	Errors        []string          `json:"errors,omitempty"`
	Next          *NextGuidance     `json:"next,omitempty"`
}

type ApplyVerification added in v3.10.3

type ApplyVerification struct {
	AuthStatus  string `json:"auth_status,omitempty"`
	ProbeStatus string `json:"probe_status_code,omitempty"`
	AuthError   string `json:"auth_error,omitempty"`
}

type Auth

type Auth = auth.Auth

type AuthLogin added in v3.18.4

type AuthLogin struct {
	// Enable the built-in login flow
	Enabled bool `jsonschema:"title=Enable Built-in Login,default=false"`

	// TTL of issued local JWTs (default: 720h = 30 days)
	TokenTTL time.Duration `mapstructure:"token_ttl" jsonschema:"title=Issued Token TTL"`

	// Issuer value stamped onto every locally-minted JWT. Must match
	// `auth.jwt.issuer` if that is set.
	Issuer string `jsonschema:"title=JWT Issuer Claim"`

	// Audience value stamped onto every locally-minted JWT. Must match
	// `auth.jwt.audience` if that is set. Defaults to "graphjin-cli".
	Audience string `jsonschema:"title=JWT Audience Claim"`

	// AudienceGraphjin is a convenience shortcut: when true, the issued JWT's
	// `aud` claim is set to the canonical value "graphjin-cli". Saves having
	// to remember / type the magic string. Mutually exclusive with Audience.
	AudienceGraphjin bool `mapstructure:"audience_graphjin" jsonschema:"title=Use GraphJin Default Audience (graphjin-cli)"`

	// OIDC identity provider used to authenticate humans.
	OIDC AuthLoginOIDC `jsonschema:"title=OIDC Provider"`
}

AuthLogin configures the built-in OIDC sign-in flow that issues local JWTs for `graphjin cli` / `graphjin mcp` clients. When Enabled, the service registers /api/v1/auth/* endpoints implementing RFC 8628 device-code flow against a generic OIDC identity provider.

type AuthLoginOIDC added in v3.18.4

type AuthLoginOIDC struct {
	// OIDC issuer URL — discovery happens at
	// <issuer_url>/.well-known/openid-configuration
	IssuerURL string `mapstructure:"issuer_url" jsonschema:"title=OIDC Issuer URL,example=https://accounts.google.com"`

	// Registered OAuth client ID / secret for this GraphJin deployment.
	ClientID     string `mapstructure:"client_id" jsonschema:"title=OAuth Client ID"`
	ClientSecret string `mapstructure:"client_secret" jsonschema:"title=OAuth Client Secret"`

	// Scopes requested. Defaults to ["openid","email","profile"].
	Scopes []string `jsonschema:"title=Requested Scopes"`

	// Optional post-authentication allow-lists. If both are empty, any verified
	// identity is accepted.
	AllowedEmails  []string `mapstructure:"allowed_emails" jsonschema:"title=Allowed Email Addresses"`
	AllowedDomains []string `mapstructure:"allowed_domains" jsonschema:"title=Allowed Email Domains"`
}

AuthLoginOIDC configures a generic OIDC identity provider for AuthLogin.

type CacheEntry added in v3.2.1

type CacheEntry struct {
	Data         []byte `json:"d"`
	Compressed   bool   `json:"c,omitempty"`
	OriginalSize int    `json:"o,omitempty"`
	FreshUntil   int64  `json:"f"`
	StaleUntil   int64  `json:"s"`
}

CacheEntry represents a cached response with metadata

type CacheMetrics added in v3.2.1

type CacheMetrics struct {
	Hits          atomic.Int64
	Misses        atomic.Int64
	Invalidations atomic.Int64
	BytesCached   atomic.Int64
	BytesSaved    atomic.Int64 // Compression savings
	Errors        atomic.Int64
	SWRRefreshes  atomic.Int64
}

CacheMetrics tracks cache performance

func (*CacheMetrics) HitRate added in v3.2.1

func (m *CacheMetrics) HitRate() float64

HitRate returns the cache hit rate (0.0 to 1.0)

func (*CacheMetrics) Snapshot added in v3.2.1

func (m *CacheMetrics) Snapshot() map[string]int64

Snapshot returns a point-in-time snapshot of metrics

type CachingConfig added in v3.2.1

type CachingConfig struct {
	// Disable response caching (caching is enabled by default)
	Disable bool `mapstructure:"disable" jsonschema:"title=Disable Caching,default=false"`

	// Default TTL for cached responses in seconds (hard TTL)
	TTL int `mapstructure:"ttl" jsonschema:"title=Cache TTL,default=3600"`

	// Soft TTL for stale-while-revalidate in seconds (0 = disabled)
	FreshTTL int `mapstructure:"fresh_ttl" jsonschema:"title=Fresh TTL for SWR,default=300"`

	// Tables to exclude from caching
	ExcludeTables []string `mapstructure:"exclude_tables" jsonschema:"title=Exclude Tables"`
}

CachingConfig configures response caching Caching is enabled by default using in-memory LRU cache Configure redis.url to use Redis for distributed caching Responses are cached with automatic invalidation when mutations modify related tables

type CatalogCapabilitiesResult added in v3.18.20

type CatalogCapabilitiesResult struct {
	Capabilities []CatalogItem `json:"capabilities"`
}

type CatalogCardResult added in v3.18.19

type CatalogCardResult struct {
	Card    CatalogItem              `json:"card"`
	Details []core.CatalogCardDetail `json:"details,omitempty"`
	Edges   []core.CatalogEdge       `json:"edges,omitempty"`
	Next    *NextGuidance            `json:"next,omitempty"`
}

type CatalogEntrypointsResult added in v3.18.20

type CatalogEntrypointsResult struct {
	Entrypoints []CatalogItem `json:"entrypoints"`
}

type CatalogItem added in v3.18.20

type CatalogItem struct {
	ID               string  `json:"id"`
	Kind             string  `json:"kind"`
	Name             string  `json:"name,omitempty"`
	Title            string  `json:"title,omitempty"`
	Summary          string  `json:"summary,omitempty"`
	DatabaseName     string  `json:"database_name,omitempty"`
	SchemaName       string  `json:"schema_name,omitempty"`
	TableName        string  `json:"table_name,omitempty"`
	ColumnName       string  `json:"column_name,omitempty"`
	Source           string  `json:"source,omitempty"`
	RiskLevel        string  `json:"risk_level,omitempty"`
	Confidence       string  `json:"confidence,omitempty"`
	Sensitive        bool    `json:"sensitive,omitempty"`
	Sensitivity      string  `json:"sensitivity,omitempty"`
	EvidenceJSON     string  `json:"evidence_json,omitempty"`
	ExamplesJSON     string  `json:"examples_json,omitempty"`
	SuggestedNext    string  `json:"suggested_next_json,omitempty"`
	DetailRef        string  `json:"detail_ref,omitempty"`
	DetailsJSON      string  `json:"details_json,omitempty"`
	EdgesJSON        string  `json:"edges_json,omitempty"`
	QueryJSON        string  `json:"query_json,omitempty"`
	InputSchemaJSON  string  `json:"input_schema_json,omitempty"`
	OutputSchemaJSON string  `json:"output_schema_json,omitempty"`
	SafetyJSON       string  `json:"safety_json,omitempty"`
	Enabled          bool    `json:"enabled,omitempty"`
	CapabilityKind   string  `json:"capability_kind,omitempty"`
	GraphQLQuery     string  `json:"graphql_query,omitempty"`
	GraphQLMutation  string  `json:"graphql_mutation,omitempty"`
	CreatedAt        string  `json:"created_at,omitempty"`
	UpdatedAt        string  `json:"updated_at,omitempty"`
	Score            float64 `json:"score,omitempty"`
	SearchRank       float64 `json:"search_rank,omitempty"`
}

type CatalogOverviewResource added in v3.18.19

type CatalogOverviewResource struct {
	GeneratedAt     string                   `json:"generated_at"`
	Revision        string                   `json:"revision,omitempty"`
	SourceRevisions map[string]string        `json:"source_revisions,omitempty"`
	Guidance        []string                 `json:"guidance"`
	Entrypoints     []core.CatalogEntryPoint `json:"entrypoints"`
	Capabilities    []core.CatalogCapability `json:"capabilities"`
	Cards           []core.CatalogCard       `json:"cards"`
	CardLimitHint   string                   `json:"card_limit_hint"`
}

type CatalogQueryResult added in v3.18.19

type CatalogQueryResult struct {
	GeneratedAt     string            `json:"generated_at"`
	Revision        string            `json:"revision,omitempty"`
	SourceRevisions map[string]string `json:"source_revisions,omitempty"`
	Count           int               `json:"count"`
	Limit           int               `json:"limit,omitempty"`
	Offset          int               `json:"offset,omitempty"`
	// Truncated is true when this page filled the limit and more matching items
	// likely exist. Page with offset (or narrow with search/where) until false.
	Truncated bool                         `json:"truncated"`
	Cards     []CatalogItem                `json:"cards"`
	Matches   map[string]core.CatalogMatch `json:"matches,omitempty"`
	Next      *NextGuidance                `json:"next,omitempty"`
}

type CodeSQLMutationDSL added in v3.18.18

type CodeSQLMutationDSL struct {
	ReadBeforeWrite string   `json:"read_before_write"`
	Preview         string   `json:"preview"`
	Apply           string   `json:"apply"`
	Locks           string   `json:"locks"`
	FileOps         []string `json:"file_ops"`
	Rules           []string `json:"rules"`
}

CodeSQLMutationDSL describes the GraphQL-native CodeSQL edit workflow.

type ColumnConfigInput added in v3.2.1

type ColumnConfigInput struct {
	Name       string `json:"name"`
	Type       string `json:"type,omitempty"`
	Primary    bool   `json:"primary,omitempty"`
	Array      bool   `json:"array,omitempty"`
	FullText   bool   `json:"full_text,omitempty"`
	ForeignKey string `json:"related_to,omitempty"`
}

ColumnConfigInput represents a column config for input

type ColumnStats added in v3.18.5

type ColumnStats struct {
	NullFraction *float64 `json:"null_fraction,omitempty"`
	// Negative = fraction-of-rows (postgres pg_stats convention).
	DistinctCount    *float64    `json:"distinct_count,omitempty"`
	MostCommonValues []EnumValue `json:"most_common_values,omitempty"`
	HistogramBounds  []string    `json:"histogram_bounds,omitempty"`
}

type ColumnTypeInfo added in v3.2.1

type ColumnTypeInfo struct {
	Type           string   `json:"type"`
	ValidOperators []string `json:"valid_operators"`
}

ColumnTypeInfo provides information about a column's type and valid operators

type Config

type Config struct {
	// Configuration for the GraphJin compiler core
	Core `mapstructure:",squash" jsonschema:"title=Compiler Configuration"`

	// Configuration for the GraphJin Service
	Serv `mapstructure:",squash" jsonschema:"title=Service Configuration"`
	// contains filtered or unexported fields
}

Configuration for the GraphJin service

func NewConfig

func NewConfig(config, format string) (*Config, error)

NewConfig function creates a new GraphJin configuration from the provided config string

func ReadInConfig

func ReadInConfig(configFile string) (*Config, error)

ReadInConfig function reads in the config file for the environment specified in the GO_ENV environment variable. This is the best way to create a new GraphJin config.

func ReadInConfigFS

func ReadInConfigFS(configFile string, fs afero.Fs) (*Config, error)

ReadInConfigFS is the same as ReadInConfig but it also takes a filesytem as an argument

func (*Config) AbsolutePath

func (c *Config) AbsolutePath(p string) string

AbsolutePath returns the absolute path of the file

func (*Config) SetHash

func (c *Config) SetHash(hash string)

SetHash sets the hash value of the configuration

func (*Config) SetName

func (c *Config) SetName(name string)

SetName sets the name of the configuration

func (*Config) ShouldUseJSONLogs added in v3.2.1

func (c *Config) ShouldUseJSONLogs() bool

ShouldUseJSONLogs returns true if logs should be in JSON format. Returns true if log_format is "json" OR if log_format is "auto" and production mode is enabled. Returns false otherwise (colored console output for dev mode).

type ConfigField added in v3.2.1

type ConfigField struct {
	Key         string      `json:"key"`
	Label       string      `json:"label"`
	Value       interface{} `json:"value"`
	Type        string      `json:"type"` // string, bool, int, duration, array, object, role, table
	Sensitive   bool        `json:"sensitive,omitempty"`
	Description string      `json:"description,omitempty"`
}

ConfigField represents a single config field with metadata for dynamic rendering

type ConfigSection added in v3.2.1

type ConfigSection struct {
	Name        string        `json:"name"`
	Title       string        `json:"title"`
	Description string        `json:"description,omitempty"`
	Fields      []ConfigField `json:"fields"`
}

ConfigSection represents a group of related config fields for the Web UI

type ConfigUpdateRequest added in v3.2.1

type ConfigUpdateRequest struct {
	Databases map[string]DatabaseConfigInput `json:"databases,omitempty"`
	Metadata  *core.MetadataConfig           `json:"metadata,omitempty"`
	Tables    []TableConfigInput             `json:"tables,omitempty"`
	Roles     []RoleConfigInput              `json:"roles,omitempty"`
	Blocklist []string                       `json:"blocklist,omitempty"`
	Functions []FunctionConfigInput          `json:"functions,omitempty"`
}

ConfigUpdateRequest represents the update request structure

type ConfigUpdateResult added in v3.2.1

type ConfigUpdateResult struct {
	Success   bool          `json:"success"`
	Message   string        `json:"message"`
	Changes   []string      `json:"changes,omitempty"`
	Errors    []string      `json:"errors,omitempty"`
	Databases []string      `json:"databases,omitempty"`
	Next      *NextGuidance `json:"next,omitempty"`
}

ConfigUpdateResult represents the result of a config update

type ConnectDisconnect added in v3.2.1

type ConnectDisconnect struct {
	Connect    string `json:"connect"`
	Disconnect string `json:"disconnect"`
}

ConnectDisconnect shows connect/disconnect syntax

type ConnectionTestResult added in v3.10.3

type ConnectionTestResult struct {
	Success       bool               `json:"success"`
	Candidate     DiscoveredDatabase `json:"candidate"`
	RecommendedDB string             `json:"recommended_dbname,omitempty"`
	Next          *NextGuidance      `json:"next,omitempty"`
}

type Core

type Core = core.Config

type CursorCache added in v3.2.1

type CursorCache interface {
	// Set stores a cursor and returns a short numeric ID
	Set(ctx context.Context, cursor string) (uint64, error)

	// Get retrieves a cursor by its numeric ID
	Get(ctx context.Context, id uint64) (string, error)

	// Close releases resources
	Close() error
}

CursorCache is the interface for MCP cursor caching It maps short numeric IDs to encrypted cursor strings for LLM-friendly pagination

func NewCursorCache added in v3.2.1

func NewCursorCache(redisURL string, ttl time.Duration, maxEntries int) (CursorCache, error)

NewCursorCache creates a cursor cache using Redis if available, otherwise in-memory

type DDLApplyResult added in v3.3.0

type DDLApplyResult struct {
	Success           bool     `json:"success"`
	OperationsApplied int      `json:"operations_applied"`
	TablesCreated     []string `json:"tables_created,omitempty"`
	ColumnsAdded      []string `json:"columns_added,omitempty"`
	Message           string   `json:"message"`
}

DDLApplyResult is the response from apply_schema_changes

type DDLOperationInfo added in v3.3.0

type DDLOperationInfo struct {
	Type        string `json:"type"`
	Table       string `json:"table"`
	Column      string `json:"column,omitempty"`
	SQL         string `json:"sql"`
	Destructive bool   `json:"destructive"`
}

DDLOperationInfo describes a single schema operation for JSON response

type DDLPreviewResult added in v3.3.0

type DDLPreviewResult struct {
	Operations []DDLOperationInfo `json:"operations"`
	Summary    DDLSummary         `json:"summary"`
}

DDLPreviewResult is the response from preview_schema_changes

type DDLSummary added in v3.3.0

type DDLSummary struct {
	Total          int `json:"total"`
	TablesToCreate int `json:"tables_to_create"`
	ColumnsToAdd   int `json:"columns_to_add"`
	IndexesToAdd   int `json:"indexes_to_add"`
	DestructiveOps int `json:"destructive_count"`
}

DDLSummary summarizes the schema changes

type DataQualityFlag added in v3.18.3

type DataQualityFlag struct {
	Table   string `json:"table"`
	Column  string `json:"column,omitempty"`
	Kind    string `json:"kind"`
	Message string `json:"message"`
}

type Database

type Database struct {
	ConnString string `mapstructure:"connection_string" jsonschema:"title=Connection String"`
	Type       string `` /* 137-byte string literal not displayed */
	Host       string `jsonschema:"title=Host"`
	Port       uint16 `jsonschema:"title=Port"`
	DBName     string `jsonschema:"title=Database Name"`
	User       string `jsonschema:"title=User"`
	Password   string `jsonschema:"title=Password"`
	Schema     string `jsonschema:"title=Postgres Schema"`

	// File path for SQLite databases
	Path string `jsonschema:"title=File Path (SQLite)"`

	// Size of database connection pool
	PoolSize int `mapstructure:"pool_size" jsonschema:"title=Connection Pool Size"`

	// Max number of active database connections allowed
	MaxConnections int `mapstructure:"max_connections" jsonschema:"title=Maximum Connections"`

	// Max time after which idle database connections are closed
	MaxConnIdleTime time.Duration `mapstructure:"max_connection_idle_time" jsonschema:"title=Connection Idel Time"`

	// Max time after which database connections are not reused
	MaxConnLifeTime time.Duration `mapstructure:"max_connection_life_time" jsonschema:"title=Connection Life Time"`

	// Database ping timeout is used for db health checking
	PingTimeout time.Duration `mapstructure:"ping_timeout" jsonschema:"title=Healthcheck Ping Timeout"`

	// Set up an secure TLS encrypted database connection
	EnableTLS bool `mapstructure:"enable_tls" jsonschema:"title=Enable TLS"`

	// Required for TLS. For example with Google Cloud SQL it's
	// <gcp-project-id>:<cloud-sql-instance>
	ServerName string `mapstructure:"server_name" jsonschema:"title=TLS Server Name"`

	// Required for TLS. Can be a file path or the contents of the PEM file
	ServerCert string `mapstructure:"server_cert" jsonschema:"title=Server Certificate"`

	// Required for TLS. Can be a file path or the contents of the PEM file
	ClientCert string `mapstructure:"client_cert" jsonschema:"title=Client Certificate"`

	// Required for TLS. Can be a file path or the contents of the pem file
	ClientKey string `mapstructure:"client_key" jsonschema:"title=Client Key"`

	// MSSQL: disable TLS encryption (default: true in go-mssqldb)
	Encrypt *bool `mapstructure:"encrypt" jsonschema:"title=MSSQL Encrypt"`

	// MSSQL: trust server certificate without validation
	TrustServerCertificate *bool `mapstructure:"trust_server_certificate" jsonschema:"title=MSSQL Trust Server Certificate"`

	// Snowflake key pair authentication (PKCS#8 PEM format).
	// Generate key: openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8
	PrivateKeyPath string `mapstructure:"private_key_path" jsonschema:"title=Private Key File Path (Snowflake)"`
	PrivateKeyPEM  string `mapstructure:"private_key_pem" jsonschema:"title=Private Key PEM (Snowflake)"`
	KeyPassphrase  string `mapstructure:"key_passphrase" jsonschema:"title=Key Passphrase (Snowflake)"`
}

Database configuration

type DatabaseConfigInput added in v3.2.1

type DatabaseConfigInput struct {
	Type        string `json:"type"`
	ConnString  string `json:"connection_string,omitempty"`
	Host        string `json:"host,omitempty"`
	Port        int    `json:"port,omitempty"`
	DBName      string `json:"dbname,omitempty"`
	User        string `json:"user,omitempty"`
	Password    string `json:"password,omitempty"`
	Path        string `json:"path,omitempty"`
	Schema      string `json:"schema,omitempty"`
	ReadOnly    bool   `json:"read_only,omitempty"`
	InferDBRefs *bool  `json:"infer_db_refs,omitempty"`
}

DatabaseConfigInput represents a database config for input

type DatabaseConnection added in v3.10.2

type DatabaseConnection struct {
	Name      string   `json:"name"`
	Type      string   `json:"type"`
	Host      string   `json:"host"`
	Databases []string `json:"databases"`
	Active    bool     `json:"active"`
	Error     string   `json:"error,omitempty"`
}

DatabaseConnection represents a single database server connection for list_databases

type DatabaseOverview added in v3.18.3

type DatabaseOverview struct {
	Database            string              `json:"database"`
	AnalyticsMode       bool                `json:"analytics_mode"`
	TotalTables         int                 `json:"total_tables"`
	TotalColumns        int                 `json:"total_columns"`
	ApproxRowTotal      int64               `json:"approx_row_total,omitempty"`
	Schemas             []SchemaStats       `json:"schemas,omitempty"`
	TopNamespacesByRows []NamespaceRollup   `json:"top_namespaces_by_rows,omitempty"`
	OverallDateRange    *DateRange          `json:"overall_date_range,omitempty"`
	Functions           []core.FunctionInfo `json:"functions,omitempty"`
}

type DateRange added in v3.18.3

type DateRange struct {
	Min string `json:"min,omitempty"`
	Max string `json:"max,omitempty"`
}

type DeleteConfigInput added in v3.2.1

type DeleteConfigInput struct {
	Filters []string `json:"filters,omitempty"`
	Columns []string `json:"columns,omitempty"`
	Block   bool     `json:"block,omitempty"`
}

DeleteConfigInput represents delete permissions

type DiscoverResult added in v3.9.0

type DiscoverResult struct {
	Databases    []DiscoveredDatabase `json:"databases"`
	Summary      DiscoverSummary      `json:"summary"`
	DockerStatus string               `json:"docker_status"`
	Next         *NextGuidance        `json:"next,omitempty"`
}

DiscoverResult is the top-level response structure

type DiscoverSummary added in v3.9.0

type DiscoverSummary struct {
	TotalFound     int      `json:"total_found"`
	DatabaseTypes  []string `json:"database_types"`
	ScanDurationMs int64    `json:"scan_duration_ms"`
}

DiscoverSummary summarizes the discovery scan

type DiscoverTarget added in v3.10.3

type DiscoverTarget struct {
	Type             string `json:"type,omitempty"`
	Host             string `json:"host"`
	Port             int    `json:"port,omitempty"`
	SourceLabel      string `json:"source_label,omitempty"`
	User             string `json:"user,omitempty"`
	Password         string `json:"password,omitempty"`
	DBName           string `json:"dbname,omitempty"`
	ConnectionString string `json:"connection_string,omitempty"`
}

DiscoverTarget is an explicit host target to probe (local or remote).

type DiscoveredDatabase added in v3.9.0

type DiscoveredDatabase struct {
	Type          string         `json:"type"`
	Host          string         `json:"host,omitempty"`
	Port          int            `json:"port,omitempty"`
	FilePath      string         `json:"file_path,omitempty"`
	CandidateID   string         `json:"candidate_id,omitempty"`
	Rank          int            `json:"rank,omitempty"`
	Confidence    string         `json:"confidence,omitempty"`
	Reasons       []string       `json:"reasons,omitempty"`
	NextActions   []string       `json:"next_actions,omitempty"`
	ProbeStatus   string         `json:"probe_status_code,omitempty"`
	Source        string         `json:"source"`
	Status        string         `json:"status"`
	Databases     []string       `json:"databases,omitempty"`
	AuthStatus    string         `json:"auth_status,omitempty"`
	AuthUser      string         `json:"auth_user,omitempty"`
	AuthError     string         `json:"auth_error,omitempty"`
	DockerInfo    *DockerDBInfo  `json:"docker_info,omitempty"`
	ConfigSnippet map[string]any `json:"config_snippet"`
}

DiscoveredDatabase represents a database found during discovery

type DiscoveryCost added in v3.18.5

type DiscoveryCost struct {
	UsesLiveQueries bool   `json:"uses_live_queries"`
	Scope           string `json:"scope,omitempty"`
	Cache           string `json:"cache,omitempty"`
}

type DiscoveryFullPayload added in v3.18.3

type DiscoveryFullPayload struct {
	Database         string             `json:"database"`
	Tables           []TableDetailEntry `json:"tables"`
	DatabaseOverview DatabaseOverview   `json:"database_overview"`
}

type DiscoveryManager added in v3.16.0

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

func NewDiscoveryManager added in v3.16.0

func NewDiscoveryManager(gj *core.GraphJin) *DiscoveryManager

func (*DiscoveryManager) DatabaseOverview added in v3.18.3

func (dm *DiscoveryManager) DatabaseOverview(database string) DatabaseOverview

func (*DiscoveryManager) Databases added in v3.18.3

func (dm *DiscoveryManager) Databases() []string

func (*DiscoveryManager) FullDatabaseOverview added in v3.18.3

func (dm *DiscoveryManager) FullDatabaseOverview(database string) DatabaseOverview

func (*DiscoveryManager) FullPayload added in v3.18.3

func (dm *DiscoveryManager) FullPayload(database string) *DiscoveryFullPayload

func (*DiscoveryManager) FullTables added in v3.18.3

func (dm *DiscoveryManager) FullTables(database string) []TableDetailEntry

func (*DiscoveryManager) FullTablesPage added in v3.18.5

func (dm *DiscoveryManager) FullTablesPage(database string, opts TableListOptions) []TableDetailEntry

func (*DiscoveryManager) Insights added in v3.18.3

func (dm *DiscoveryManager) Insights(database string) SchemaInsights

func (*DiscoveryManager) Invalidate added in v3.18.3

func (dm *DiscoveryManager) Invalidate()

func (*DiscoveryManager) Namespaces added in v3.18.5

func (dm *DiscoveryManager) Namespaces(ctx context.Context, database string) []NamespaceRollup

Namespaces returns one rollup entry per (database, schema). Cached.

func (*DiscoveryManager) Payload added in v3.18.3

func (dm *DiscoveryManager) Payload(database string) *DiscoveryPayload

func (*DiscoveryManager) Profile added in v3.18.3

func (dm *DiscoveryManager) Profile(database, table string) *TableProfile

func (*DiscoveryManager) RowCountsForNamespace added in v3.18.5

func (dm *DiscoveryManager) RowCountsForNamespace(ctx context.Context, database, schema string) map[string]int64

RowCountsForNamespace returns table_name -> approx_row_count for one namespace.

func (*DiscoveryManager) Subscribe added in v3.16.0

func (dm *DiscoveryManager) Subscribe(ctx context.Context, database string) (*DiscoverySubscription, error)

func (*DiscoveryManager) TableIndex added in v3.18.3

func (dm *DiscoveryManager) TableIndex(database string) []TableIndexEntry

func (*DiscoveryManager) TableIndexPage added in v3.18.5

func (dm *DiscoveryManager) TableIndexPage(_ context.Context, database string, opts TableListOptions) ListTablesResult

func (*DiscoveryManager) TableSample added in v3.18.5

func (dm *DiscoveryManager) TableSample(ctx context.Context, database, schemaName, table string) (*TableSampleResult, error)

type DiscoveryPayload added in v3.18.3

type DiscoveryPayload struct {
	Database         string            `json:"database"`
	Tables           []TableIndexEntry `json:"tables"`
	Insights         SchemaInsights    `json:"insights"`
	DatabaseOverview DatabaseOverview  `json:"database_overview"`
}

type DiscoverySubscription added in v3.16.0

type DiscoverySubscription struct {
	Result chan *DiscoveryPayload
	// contains filtered or unexported fields
}

func (*DiscoverySubscription) Unsubscribe added in v3.16.0

func (ds *DiscoverySubscription) Unsubscribe()

type DockerDBInfo added in v3.9.0

type DockerDBInfo struct {
	ContainerID   string `json:"container_id"`
	ContainerName string `json:"container_name"`
	Image         string `json:"image"`
	Ports         string `json:"ports"`
}

DockerDBInfo holds Docker container details for a discovered database

type DuplicateFlag added in v3.18.3

type DuplicateFlag struct {
	Table          string   `json:"table"`
	Schemas        []string `json:"schemas"`
	FKSchema       string   `json:"fk_schema,omitempty"`
	Recommendation string   `json:"recommendation,omitempty"`
}

type EnhancedError added in v3.2.1

type EnhancedError struct {
	Message     string `json:"message"`
	Suggestion  string `json:"suggestion,omitempty"`
	RelatedTool string `json:"related_tool,omitempty"`
	// Kind, Table, Column are populated by enhanceExecError when the
	// error came from SQL execution and the dialect was identifiable.
	// Consumers can switch on Kind without parsing the prose.
	Kind   string `json:"kind,omitempty"`
	Table  string `json:"table,omitempty"`
	Column string `json:"column,omitempty"`
	// Hint carries a structured rewrite when the schema cross-check
	// detects that the error is misleading (e.g. column actually exists
	// on the table but was dropped by a CTE projection).
	Hint string `json:"hint,omitempty"`
}

EnhancedError represents an error with recovery suggestions

type EnumProfile added in v3.18.3

type EnumProfile struct {
	Values        []EnumValue `json:"values,omitempty"`
	DistinctCount int64       `json:"distinct_count"`
	Truncated     bool        `json:"truncated,omitempty"`
}

type EnumValue added in v3.18.3

type EnumValue struct {
	Value string `json:"value"`
	Count int64  `json:"count"`
}

type ErrorInfo added in v3.2.1

type ErrorInfo struct {
	Message    string         `json:"message"`
	Extensions map[string]any `json:"extensions,omitempty"`
}

ErrorInfo represents an error from query execution

type ExampleQuery added in v3.10.2

type ExampleQuery struct {
	Description string `json:"description"`
	Query       string `json:"query"`
}

ExampleQuery represents an example GraphQL query for a table

type ExecErrorClass added in v3.18.8

type ExecErrorClass struct {
	Kind   string
	Table  string
	Column string
}

ExecErrorClass is the parsed shape of a driver-level error.

type ExecuteResult added in v3.2.1

type ExecuteResult struct {
	Data   json.RawMessage `json:"data"`
	Errors []ErrorInfo     `json:"errors,omitempty"`
}

ExecuteResult represents the result of a query execution

type FKDisambiguationCandidate added in v3.18.8

type FKDisambiguationCandidate struct {
	Column  string `json:"column"`
	Snippet string `json:"snippet"`
}

type FKDisambiguationEntry added in v3.18.8

type FKDisambiguationEntry struct {
	Target     string                      `json:"target"`
	Ambiguous  bool                        `json:"ambiguous"`
	Candidates []FKDisambiguationCandidate `json:"candidates"`
	SyntaxHint string                      `json:"syntax_hint"`
}

FKDisambiguationEntry signals multiple FKs to the same target; needs @through(column:).

type FilterOperators added in v3.2.1

type FilterOperators struct {
	Comparison []string `json:"comparison"`
	List       []string `json:"list"`
	Null       []string `json:"null"`
	Text       []string `json:"text"`
	JSON       []string `json:"json"`
	Spatial    []string `json:"spatial"`
}

FilterOperators groups filter operators by category

type FixQueryErrorResult added in v3.18.8

type FixQueryErrorResult struct {
	Title         string   `json:"title"`
	GuideMarkdown string   `json:"guide_markdown"`
	Kind          string   `json:"kind"`
	Diagnosis     string   `json:"diagnosis"`
	RepairedQuery string   `json:"repaired_query,omitempty"`
	FollowUpTools []string `json:"follow_up_tools,omitempty"`
}

FixQueryErrorResult is the structured tool-result envelope for fix_query_error.

type ForeignKeyRef added in v3.18.3

type ForeignKeyRef struct {
	Column   string `json:"column"`
	Target   string `json:"target"`
	Database string `json:"database,omitempty"`
}

type FunctionConfigInput added in v3.2.1

type FunctionConfigInput struct {
	Name       string `json:"name"`
	Schema     string `json:"schema,omitempty"`
	ReturnType string `json:"return_type"`
}

FunctionConfigInput represents a function config for input

type GraphQLHelpResult added in v3.18.20

type GraphQLHelpResult struct {
	For                   string         `json:"for"`
	Summary               string         `json:"summary"`
	Bootstrap             []string       `json:"bootstrap,omitempty"`
	TopicRoutes           []HelpRoute    `json:"topic_routes,omitempty"`
	ReplacesTools         []ToolReplaces `json:"replaces_tools,omitempty"`
	RecommendedFirstQuery string         `json:"recommended_first_query"`
	GraphQLQuery          string         `json:"graphql_query"`
	GraphQLVariables      map[string]any `json:"graphql_variables"`
	CatalogRows           []CatalogItem  `json:"catalog_rows"`
	Examples              []string       `json:"examples,omitempty"`
	Safety                map[string]any `json:"safety,omitempty"`
	Next                  *NextGuidance  `json:"next,omitempty"`
}

type HealthResult added in v3.10.2

type HealthResult struct {
	Status       string         `json:"status"`
	DatabaseType string         `json:"database_type,omitempty"`
	PingLatency  string         `json:"ping_latency,omitempty"`
	SchemaReady  bool           `json:"schema_ready"`
	TableCount   int            `json:"table_count"`
	PoolStats    *PoolStatsInfo `json:"pool_stats,omitempty"`
	Error        string         `json:"error,omitempty"`
}

HealthResult represents the health check response

type HelpRoute added in v3.18.21

type HelpRoute struct {
	Need        string `json:"need"`
	For         string `json:"for"`
	FirstCall   string `json:"first_call"`
	DetailQuery string `json:"detail_query"`
}

type HookFn

type HookFn func(*core.Result)

type HttpService

type HttpService struct {
	atomic.Value
	// contains filtered or unexported fields
}

func NewGraphJinService

func NewGraphJinService(conf *Config, options ...Option) (*HttpService, error)

NewGraphJinService a new service

func (*HttpService) Attach

func (s *HttpService) Attach(mux Mux) error

Attach route to the internal http service

func (*HttpService) AttachWithNS

func (s *HttpService) AttachWithNS(mux Mux, namespace string) error

AttachWithNS a namespaced route to the internal http service

func (*HttpService) Close added in v3.18.16

func (s *HttpService) Close() error

Close shuts down the in-process service resources owned by HttpService. It is useful for embedded use and tests that do not call Start().

func (*HttpService) Deploy

func (s *HttpService) Deploy(conf *Config, options ...Option) error

Deploy a new configuration

func (*HttpService) GetDB

func (s *HttpService) GetDB() *sql.DB

GetDB fetching internal db client (returns any connection from the pool)

func (*HttpService) GetGraphJin

func (s *HttpService) GetGraphJin() *core.GraphJin

GetGraphJin fetching internal GraphJin core

func (*HttpService) GraphQL

func (s *HttpService) GraphQL(ah auth.HandlerFunc) http.Handler

GraphQLis the http handler the GraphQL endpoint

func (*HttpService) GraphQLWithNS

func (s *HttpService) GraphQLWithNS(ah auth.HandlerFunc, ns string) http.Handler

GraphQLWithNS is the http handler the namespaced GraphQL endpoint

func (*HttpService) MCPHandler added in v3.2.1

func (s *HttpService) MCPHandler() http.Handler

MCPHandler returns an HTTP handler for MCP HTTP transport (stateless) This uses StreamableHTTPServer which handles POST requests directly

func (*HttpService) MCPHandlerWithAuth added in v3.2.1

func (s *HttpService) MCPHandlerWithAuth(ah auth.HandlerFunc) http.Handler

MCPHandlerWithAuth returns an HTTP handler for MCP HTTP transport with authentication This wraps the MCP handler with the same auth middleware as GraphQL/REST endpoints

func (*HttpService) MCPMessageHandler added in v3.2.1

func (s *HttpService) MCPMessageHandler() http.Handler

MCPMessageHandler returns an HTTP handler for MCP HTTP transport (stateless) This uses StreamableHTTPServer which handles POST requests directly without SSE

func (*HttpService) MCPMessageHandlerWithAuth added in v3.2.1

func (s *HttpService) MCPMessageHandlerWithAuth(ah auth.HandlerFunc) http.Handler

MCPMessageHandlerWithAuth returns an HTTP handler for MCP HTTP transport with authentication

func (*HttpService) OpenAPI added in v3.2.1

func (s *HttpService) OpenAPI() http.Handler

OpenAPI is the http handler for the OpenAPI specification endpoint

func (*HttpService) OpenAPIWithNS added in v3.2.1

func (s *HttpService) OpenAPIWithNS(ns string) http.Handler

OpenAPIWithNS is the http handler for the namespaced OpenAPI specification endpoint

func (*HttpService) REST

func (s *HttpService) REST(ah auth.HandlerFunc) http.Handler

REST is the http handler the REST endpoint

func (*HttpService) RESTWithNS

func (s *HttpService) RESTWithNS(ah auth.HandlerFunc, ns string) http.Handler

RESTWithNS is the http handler the namespaced REST endpoint

func (*HttpService) Reload

func (s *HttpService) Reload() error

Reload re-runs database discover and reinitializes service.

func (*HttpService) RunMCPStdio added in v3.2.1

func (s *HttpService) RunMCPStdio(ctx context.Context) error

RunMCPStdio runs the MCP server using stdio transport (for CLI/Claude Desktop) Auth credentials can be provided via environment variables: - GRAPHJIN_USER_ID: User ID for the session - GRAPHJIN_USER_ROLE: User role for the session

func (*HttpService) Start

func (s *HttpService) Start() error

Start the service listening on the configured port

func (*HttpService) WebUI

func (s *HttpService) WebUI(routePrefix, gqlEndpoint string) http.Handler

WebUI is the http handler the web ui endpoint

func (*HttpService) Workflows added in v3.12.0

func (s *HttpService) Workflows(ah auth.HandlerFunc) http.Handler

Workflows is the http handler for named JS workflows.

func (*HttpService) WorkflowsWithNS added in v3.12.0

func (s *HttpService) WorkflowsWithNS(ah auth.HandlerFunc, ns string) http.Handler

WorkflowsWithNS is the namespaced http handler for named JS workflows.

type HubTable added in v3.18.3

type HubTable struct {
	Name    string `json:"name"`
	FKCount int    `json:"fk_count"`
}

type IndexInfo added in v3.18.5

type IndexInfo struct {
	Name    string   `json:"name"`
	Columns []string `json:"columns"`
	Unique  bool     `json:"unique,omitempty"`
	Primary bool     `json:"primary,omitempty"`
	Type    string   `json:"type,omitempty"`
}

type InsertConfigInput added in v3.2.1

type InsertConfigInput struct {
	Filters []string          `json:"filters,omitempty"`
	Columns []string          `json:"columns,omitempty"`
	Presets map[string]string `json:"presets,omitempty"`
	Block   bool              `json:"block,omitempty"`
}

InsertConfigInput represents insert permissions

type JSRuntimeAPI added in v3.12.0

type JSRuntimeAPI struct {
	Runtime         string              `json:"runtime"`
	RuntimeStatus   string              `json:"runtime_status"`
	EntryPoint      string              `json:"entry_point"`
	WorkflowTimeout int                 `json:"workflow_timeout_seconds"`
	Globals         []JSRuntimeGlobal   `json:"globals"`
	Functions       []JSRuntimeFunction `json:"functions"`
	Notes           []string            `json:"notes,omitempty"`
}

JSRuntimeAPI describes the functions exposed in the GraphJin JS runtime.

type JSRuntimeFunction added in v3.12.0

type JSRuntimeFunction struct {
	Name        string         `json:"name"`
	Tool        string         `json:"tool,omitempty"`
	Description string         `json:"description,omitempty"`
	Arguments   map[string]any `json:"arguments,omitempty"`
	Required    []string       `json:"required,omitempty"`
}

JSRuntimeFunction describes one callable function in the JS runtime.

type JSRuntimeGlobal added in v3.12.0

type JSRuntimeGlobal struct {
	Name        string `json:"name"`
	Type        string `json:"type"`
	Description string `json:"description"`
}

JSRuntimeGlobal describes one global in the JS runtime.

type JWTConfig

type JWTConfig = auth.JWTConfig

type ListDatabasesResult added in v3.10.2

type ListDatabasesResult struct {
	Connections    []DatabaseConnection `json:"connections"`
	TotalDatabases int                  `json:"total_databases"`
}

ListDatabasesResult is the response from list_databases

type ListNamespacesResult added in v3.18.5

type ListNamespacesResult struct {
	Database   string            `json:"database,omitempty"`
	Namespaces []NamespaceRollup `json:"namespaces"`
	Count      int               `json:"count"`
}

type ListTablesResult added in v3.18.5

type ListTablesResult struct {
	Database        string            `json:"database,omitempty"`
	Databases       []string          `json:"databases,omitempty"`
	Schema          string            `json:"schema,omitempty"`
	Tables          []TableIndexEntry `json:"tables"`
	Count           int               `json:"count"`
	Total           int               `json:"total"`
	TopTablesByRows []TableRef        `json:"top_tables_by_rows,omitempty"`
	NextCursor      string            `json:"next_cursor,omitempty"`
	HasMore         bool              `json:"has_more,omitempty"`
}

type MCPCLIResource added in v3.18.5

type MCPCLIResource struct {
	Command string
	URI     string
	Short   string
}

MCPCLIResource describes a first-class CLI shortcut for a static MCP resource. The server owns this catalog so GraphJin's client and server surfaces stay aligned.

func MCPCLIResources added in v3.18.5

func MCPCLIResources() []MCPCLIResource

MCPCLIResources returns the static resource shortcuts GraphJin CLI should expose.

type MCPConfig added in v3.2.1

type MCPConfig struct {
	// Disable the MCP server. MCP is enabled by default except for legacy
	// database-only prod/agentic configs, where it must be explicitly enabled.
	Disable bool `mapstructure:"disable" jsonschema:"title=Disable MCP Server,default=false"`

	// Allow mutation operations via raw MCP GraphQL execution.
	// Auto-enabled in dev mode. Default: false
	AllowMutations bool `mapstructure:"allow_mutations" jsonschema:"title=Allow Mutations,default=false"`

	// Allow arbitrary GraphQL queries (vs only saved queries from allow-list)
	// Auto-enabled in dev mode. Default: false
	AllowRawQueries bool `mapstructure:"allow_raw_queries" jsonschema:"title=Allow Raw Queries,default=false"`

	// LegacyDiscovery registers the older MCP discovery/syntax tools and legacy
	// HTTP helper endpoints such as /api/v1/discovery and /api/v1/workflows.
	// Disabled by default in sources used because catalog/control-plane GraphQL
	// is now the primary AI discovery and action surface.
	LegacyDiscovery bool `mapstructure:"legacy_discovery" jsonschema:"title=Enable Legacy Discovery Tools,default=false"`

	// Default user ID for stdio transport (CLI). Can be overridden by GRAPHJIN_USER_ID env var.
	StdioUserID string `mapstructure:"stdio_user_id" jsonschema:"title=Stdio User ID"`

	// Default user role for stdio transport (CLI). Can be overridden by GRAPHJIN_USER_ROLE env var.
	StdioUserRole string `mapstructure:"stdio_user_role" jsonschema:"title=Stdio User Role"`

	// Run in MCP-only mode - disables GraphQL, REST saved-query API, WebUI, and OpenAPI endpoints.
	// Health check and MCP endpoints remain available. Legacy HTTP helper endpoints
	// also remain available only when legacy_discovery is enabled.
	Only bool `mapstructure:"only" jsonschema:"title=MCP Only Mode,default=false"`

	// CursorCacheTTL in seconds for cursor ID cache (default: 1800 = 30 min)
	// Cursors are cached to allow short numeric IDs for LLM-friendly pagination
	CursorCacheTTL int `mapstructure:"cursor_cache_ttl" jsonschema:"title=Cursor Cache TTL,default=1800"`

	// CursorCacheSize max entries for in-memory cursor cache fallback (default: 10000)
	CursorCacheSize int `mapstructure:"cursor_cache_size" jsonschema:"title=Cursor Cache Size,default=10000"`

	// AllowConfigUpdates enables MCP tools that can modify GraphJin configuration
	// WARNING: Allows LLMs to change database connections, table configs, and roles
	// Only enable in trusted environments. Default: false
	AllowConfigUpdates bool `mapstructure:"allow_config_updates" jsonschema:"title=Allow Config Updates,default=false"`

	// AllowSchemaReload enables the MCP reload_schema tool for manual schema refresh
	// Useful when user adds tables and wants immediate discovery without waiting for poll
	// Default: false (auto-enabled in dev mode if not explicitly set)
	AllowSchemaReload bool `mapstructure:"allow_schema_reload" jsonschema:"title=Allow Schema Reload,default=false"`

	// AllowSchemaUpdates enables MCP tools to preview and apply database schema changes (DDL)
	// Uses db.graphql format. Auto-enabled in dev mode. Default: false
	AllowSchemaUpdates bool `mapstructure:"allow_schema_updates" jsonschema:"title=Allow Schema Updates,default=false"`

	// AllowWorkflowUpdates enables workflow writes through gj_workflow and,
	// when legacy MCP discovery is enabled, the save_workflow compatibility tool.
	// Saved workflows are discoverable via workflow catalog items. Execution
	// through gj_workflow_execution is controlled by normal read_only table/source
	// configuration because it is an insert-shaped managed mutation.
	// Auto-enabled in dev mode. Default: false
	AllowWorkflowUpdates bool `mapstructure:"allow_workflow_updates" jsonschema:"title=Allow Workflow Updates,default=false"`

	// AllowWorkflowExecution enables the execute_workflow compatibility tool
	// when legacy MCP discovery is enabled. GraphQL execution through
	// gj_workflow_execution is controlled by normal read_only table/source config.
	// Auto-enabled in dev mode. Default: false
	AllowWorkflowExecution bool `mapstructure:"allow_workflow_execution" jsonschema:"title=Allow Workflow Execution,default=false"`

	// AllowDevTools enables advanced introspection MCP tools (explain_query, explore_relationships, audit_role_permissions).
	// These expose SQL, relationship graphs, and role permissions — useful for development/debugging.
	// Auto-enabled in dev mode. Default: false
	AllowDevTools bool `mapstructure:"allow_dev_tools" jsonschema:"title=Allow Dev Tools,default=false"`

	// DefaultDBAllowed when true allows configuring and discovering system/default
	// databases (e.g. postgres, mysql, master). Default: false
	DefaultDBAllowed bool `mapstructure:"default_db_allowed" jsonschema:"title=Allow Default Databases,default=false"`

	// WorkflowTimeout in seconds for JavaScript workflow execution.
	// Workflows that exceed this duration are interrupted. Default: 5
	WorkflowTimeout int `mapstructure:"workflow_timeout" jsonschema:"title=Workflow Timeout (seconds),default=5"`
	// contains filtered or unexported fields
}

MCPConfig configures the Model Context Protocol (MCP) server MCP enables AI assistants to interact with GraphJin via function calling

Transport is implicit based on context: - CLI (`graphjin mcp`) uses stdio transport for Claude Desktop and CLI clients - HTTP service uses SSE/HTTP transport at /api/v1/mcp endpoint

Authentication: - HTTP transport uses the same auth as GraphQL/REST (JWT, headers, etc.) - Stdio transport uses env vars (GRAPHJIN_USER_ID, GRAPHJIN_USER_ROLE) or config values

type MCPConfigResponse added in v3.2.1

type MCPConfigResponse struct {
	ActiveDatabase string                         `json:"active_database,omitempty"`
	Sources        []core.SourceConfig            `json:"sources,omitempty"`
	Databases      map[string]core.DatabaseConfig `json:"databases,omitempty"`
	Relationships  []core.RelationshipConfig      `json:"relationships,omitempty"`
	Metadata       core.MetadataConfig            `json:"metadata,omitempty"`
	Tables         []core.Table                   `json:"tables,omitempty"`
	Roles          []RoleInfo                     `json:"roles,omitempty"`
	Blocklist      []string                       `json:"blocklist,omitempty"`
	Functions      []core.Function                `json:"functions,omitempty"`
	Resolvers      []core.ResolverConfig          `json:"resolvers,omitempty"`
	MCP            MCPConfig                      `json:"mcp,omitempty"`
}

MCPConfigResponse represents a section of the configuration for MCP

type MemoryCache added in v3.2.1

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

MemoryCache provides in-memory LRU response caching with row-level invalidation

func NewMemoryCache added in v3.2.1

func NewMemoryCache(conf CachingConfig, maxEntries int) (*MemoryCache, error)

NewMemoryCache creates a new in-memory LRU cache

func (*MemoryCache) Close added in v3.2.1

func (mc *MemoryCache) Close() error

Close stops the SWR worker pool and purges the cache.

func (*MemoryCache) Get added in v3.2.1

func (mc *MemoryCache) Get(ctx context.Context, key string) ([]byte, bool, bool)

Get retrieves a cached response Returns (data, isStale, found)

func (*MemoryCache) InvalidateRows added in v3.2.1

func (mc *MemoryCache) InvalidateRows(ctx context.Context, refs []core.RowRef) error

InvalidateRows invalidates cache entries for specific rows

func (*MemoryCache) InvalidateTables added in v3.18.18

func (mc *MemoryCache) InvalidateTables(ctx context.Context, tables []string) error

InvalidateTables invalidates cache entries that reference any of the given tables.

func (*MemoryCache) Metrics added in v3.2.1

func (mc *MemoryCache) Metrics() *CacheMetrics

Metrics returns the cache metrics

func (*MemoryCache) Set added in v3.2.1

func (mc *MemoryCache) Set(
	ctx context.Context,
	key string,
	data []byte,
	refs []core.RowRef,
	queryStartTime time.Time,
) error

Set stores a response with row-level indices

func (*MemoryCache) SetWithOptions added in v3.18.18

func (mc *MemoryCache) SetWithOptions(
	ctx context.Context,
	key string,
	data []byte,
	refs []core.RowRef,
	queryStartTime time.Time,
	opts core.CacheEntryOptions,
) error

SetWithOptions stores a response with dependency indices and per-entry TTL caps.

func (*MemoryCache) SubmitRefresh added in v3.18.14

func (mc *MemoryCache) SubmitRefresh(key string, fn core.RefreshFn) bool

SubmitRefresh enqueues a stale-while-revalidate refresh on the worker pool. Returns false if SWR is disabled or the pool is full.

func (*MemoryCache) SubmitRefreshWithOptions added in v3.18.18

func (mc *MemoryCache) SubmitRefreshWithOptions(key string, fn core.RefreshFnWithOptions) bool

SubmitRefreshWithOptions enqueues an option-aware stale-while-revalidate refresh.

type MemoryCursorCache added in v3.2.1

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

MemoryCursorCache uses in-memory LRU as fallback

func NewMemoryCursorCache added in v3.2.1

func NewMemoryCursorCache(maxEntries int, ttl time.Duration) *MemoryCursorCache

NewMemoryCursorCache creates a new in-memory cursor cache

func (*MemoryCursorCache) Close added in v3.2.1

func (c *MemoryCursorCache) Close() error

Close stops the cleanup goroutine

func (*MemoryCursorCache) Get added in v3.2.1

func (c *MemoryCursorCache) Get(ctx context.Context, id uint64) (string, error)

Get retrieves a cursor by its numeric ID

func (*MemoryCursorCache) Set added in v3.2.1

func (c *MemoryCursorCache) Set(ctx context.Context, cursor string) (uint64, error)

Set stores a cursor and returns a short numeric ID

type MistakeExample added in v3.2.1

type MistakeExample struct {
	Wrong  string `json:"wrong"`
	Right  string `json:"right"`
	Reason string `json:"reason"`
}

MistakeExample shows a common mistake and how to fix it

type MutationOperations added in v3.2.1

type MutationOperations struct {
	Insert      string `json:"insert"`
	BulkInsert  string `json:"bulk_insert"`
	Update      string `json:"update"`
	BulkUpdate  string `json:"bulk_update"`
	UpdateWhere string `json:"update_where"`
	Upsert      string `json:"upsert"`
	Delete      string `json:"delete"`
}

MutationOperations shows mutation operation syntax

type MutationSyntaxReference added in v3.2.1

type MutationSyntaxReference struct {
	AnalyticsModeRules []string           `json:"analytics_mode_rules,omitempty"`
	Operations         MutationOperations `json:"operations"`
	CodeSQL            CodeSQLMutationDSL `json:"codesql,omitempty"`
	NestedMutations    NestedMutationInfo `json:"nested_mutations"`
	ConnectDisconnect  ConnectDisconnect  `json:"connect_disconnect"`
	Returning          ReturningInfo      `json:"returning"`
	Validation         ValidationSyntax   `json:"validation"`
	CommonMistakes     []MistakeExample   `json:"common_mistakes"`
	Examples           []QueryExample     `json:"examples"`
}

MutationSyntaxReference contains the GraphJin mutation DSL reference

type Mux

type Mux interface {
	Handle(string, http.Handler)
	ServeHTTP(http.ResponseWriter, *http.Request)
}

type NamespaceRollup added in v3.18.5

type NamespaceRollup = corediscovery.NamespaceRollup

type NamespaceRoute added in v3.18.3

type NamespaceRoute struct {
	Database   string `json:"database"`
	TableCount int    `json:"table_count"`
	Default    bool   `json:"default,omitempty"`
}

type NestedMutationInfo added in v3.2.1

type NestedMutationInfo struct {
	Description string `json:"description"`
	Example     string `json:"example"`
}

NestedMutationInfo describes nested mutations

type NextGuidance added in v3.11.0

type NextGuidance struct {
	StateCode       string       `json:"state_code"`
	RecommendedTool string       `json:"recommended_tool,omitempty"`
	Options         []NextOption `json:"options,omitempty"`
}

NextGuidance contains the recommended next MCP tool call and alternatives.

type NextOption added in v3.11.0

type NextOption struct {
	Tool         string         `json:"tool"`
	Priority     int            `json:"priority"`
	Reason       string         `json:"reason,omitempty"`
	When         string         `json:"when,omitempty"`
	RequiredArgs []string       `json:"required_args,omitempty"`
	OptionalArgs []string       `json:"optional_args,omitempty"`
	ArgsTemplate map[string]any `json:"args_template,omitempty"`
}

NextOption is a machine-readable next-step option for MCP orchestration.

type NumericStats added in v3.18.3

type NumericStats struct {
	Min   string `json:"min,omitempty"`
	Max   string `json:"max,omitempty"`
	Avg   string `json:"avg,omitempty"`
	Sum   string `json:"sum,omitempty"`
	Count int64  `json:"count"`
}

type OnboardingStatusResult added in v3.10.3

type OnboardingStatusResult struct {
	ConfiguredDatabases []string      `json:"configured_databases"`
	ActiveDatabase      string        `json:"active_database,omitempty"`
	SchemaReady         bool          `json:"schema_ready"`
	TableCount          int           `json:"table_count"`
	Warnings            []string      `json:"warnings,omitempty"`
	Next                *NextGuidance `json:"next,omitempty"`
}

type Option

type Option func(*graphjinService) error

func OptionSetDB

func OptionSetDB(db *sql.DB) Option

OptionSetDB sets a new db client. The connection is stored under the DefaultDBName key in the dbs map for backward compatibility.

func OptionSetFS

func OptionSetFS(fs core.FS) Option

OptionSetFS sets service filesystem

func OptionSetHookFunc

func OptionSetHookFunc(fn HookFn) Option

OptionSetHookFunc sets a function to be called on every request

func OptionSetLogOutput added in v3.2.1

func OptionSetLogOutput(output zapcore.WriteSyncer) Option

OptionSetLogOutput sets the log output writer (e.g., os.Stderr for MCP stdio mode)

func OptionSetNamespace

func OptionSetNamespace(namespace string) Option

OptionSetNamespace sets service namespace

func OptionSetZapLogger

func OptionSetZapLogger(zlog *zap.Logger) Option

OptionSetZapLogger sets service structured logger

type OrderingSyntax added in v3.2.1

type OrderingSyntax struct {
	Simple     string `json:"simple"`
	Multiple   string `json:"multiple"`
	Nested     string `json:"nested"`
	CustomList string `json:"custom_list"`
	NullsFirst string `json:"nulls_first"`
	NullsLast  string `json:"nulls_last"`
}

OrderingSyntax shows ordering options

type PaginationSyntax added in v3.2.1

type PaginationSyntax struct {
	LimitOffset    string `json:"limit_offset"`
	ForwardCursor  string `json:"forward_cursor"`
	BackwardCursor string `json:"backward_cursor"`
	CursorField    string `json:"cursor_field"`
	Distinct       string `json:"distinct"`
}

PaginationSyntax shows pagination options

type Payload

type Payload struct {
	Data   json.RawMessage `json:"data,omitempty"`
	Errors []core.Error    `json:"errors,omitempty"`
}

type PoolStatsInfo added in v3.10.2

type PoolStatsInfo struct {
	MaxOpenConnections int    `json:"max_open_connections"`
	OpenConnections    int    `json:"open_connections"`
	InUse              int    `json:"in_use"`
	Idle               int    `json:"idle"`
	WaitCount          int64  `json:"wait_count"`
	WaitDuration       string `json:"wait_duration"`
}

PoolStatsInfo represents database connection pool statistics

type QueryConfigInput added in v3.2.1

type QueryConfigInput struct {
	Limit            int      `json:"limit,omitempty"`
	Filters          []string `json:"filters,omitempty"`
	Columns          []string `json:"columns,omitempty"`
	DisableFunctions bool     `json:"disable_functions,omitempty"`
	Block            bool     `json:"block,omitempty"`
}

QueryConfigInput represents query permissions

type QueryExample added in v3.2.1

type QueryExample struct {
	Description string `json:"description"`
	Query       string `json:"query"`
	Variables   string `json:"variables,omitempty"`
}

QueryExample represents an annotated query example

type QueryExamplesForSyntax added in v3.2.1

type QueryExamplesForSyntax struct {
	Basic         []QueryExample `json:"basic"`
	Filtering     []QueryExample `json:"filtering"`
	Relationships []QueryExample `json:"relationships"`
	Pagination    []QueryExample `json:"pagination"`
	Aggregations  []QueryExample `json:"aggregations"`
	Analytics     []QueryExample `json:"analytics"`
	Recursive     []QueryExample `json:"recursive"`
	Spatial       []QueryExample `json:"spatial"`
	RemoteJoins   []QueryExample `json:"remote_joins"`
}

QueryExamplesForSyntax contains categorized query examples

type QueryPattern added in v3.18.8

type QueryPattern struct {
	Name              string `json:"name"`
	Title             string `json:"title"`
	Question          string `json:"question"`
	Rule              string `json:"rule"`
	Why               string `json:"why"`
	WrongExample      string `json:"wrong_example,omitempty"`
	WrongReason       string `json:"wrong_reason,omitempty"`
	RightExample      string `json:"right_example"`
	AutoTraversalNote string `json:"auto_traversal_note,omitempty"`
}

type QuerySyntaxReference added in v3.2.1

type QuerySyntaxReference struct {
	AnalyticsModeRules  []string                  `json:"analytics_mode_rules,omitempty"`
	Patterns            []QueryPattern            `json:"patterns,omitempty"`
	FilterOperators     FilterOperators           `json:"filter_operators"`
	LogicalOperators    []string                  `json:"logical_operators"`
	Pagination          PaginationSyntax          `json:"pagination"`
	Ordering            OrderingSyntax            `json:"ordering"`
	Aggregations        AggregationsSyntax        `json:"aggregations"`
	AnalyticsDirectives AnalyticsDirectivesSyntax `json:"analytics_directives"`
	Recursive           RecursiveSyntax           `json:"recursive"`
	FullTextSearch      string                    `json:"full_text_search"`
	Directives          map[string]string         `json:"directives"`
	Variables           VariablesSyntax           `json:"variables"`
	JSONPaths           string                    `json:"json_paths"`
	CommonMistakes      []MistakeExample          `json:"common_mistakes"`
	Examples            QueryExamplesForSyntax    `json:"examples"`
}

QuerySyntaxReference contains the complete GraphJin query DSL reference

type QueryTemplate added in v3.18.3

type QueryTemplate struct {
	Name        string `json:"name"`
	Kind        string `json:"kind"`
	Table       string `json:"table"`
	Description string `json:"description,omitempty"`
	Query       string `json:"query"`
}

type RateLimiter

type RateLimiter struct {
	// The number of events per second
	Rate float64 `jsonschema:"title=Connection Rate"`

	// Bucket a burst of at most 'bucket' number of events
	Bucket int `jsonschema:"title=Bucket Size"`

	// The header that contains the client ip
	IPHeader string `mapstructure:"ip_header" jsonschema:"title=IP From HTTP Header,example=X-Forwarded-For"`
}

RateLimiter sets the API rate limits

type RecursiveSyntax added in v3.2.1

type RecursiveSyntax struct {
	FindParents  string `json:"find_parents"`
	FindChildren string `json:"find_children"`
}

RecursiveSyntax shows recursive query options

type RedisCache added in v3.2.1

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

RedisCache provides Redis-based response caching with row-level invalidation

func NewRedisCache added in v3.2.1

func NewRedisCache(redisURL string, conf CachingConfig) (*RedisCache, error)

NewRedisCache creates a new Redis cache instance

func (*RedisCache) Close added in v3.2.1

func (c *RedisCache) Close() error

Close closes the Redis connection and worker pool

func (*RedisCache) Get added in v3.2.1

func (c *RedisCache) Get(ctx context.Context, key string) ([]byte, bool, bool)

Get retrieves a cached response Returns (data, isStale, found)

func (*RedisCache) InvalidateRows added in v3.2.1

func (c *RedisCache) InvalidateRows(ctx context.Context, refs []core.RowRef) error

InvalidateRows invalidates cache entries for specific rows (called after mutations)

func (*RedisCache) InvalidateTables added in v3.18.18

func (c *RedisCache) InvalidateTables(ctx context.Context, tables []string) error

InvalidateTables invalidates cache entries associated with whole tables.

func (*RedisCache) Metrics added in v3.2.1

func (c *RedisCache) Metrics() *CacheMetrics

Metrics returns the cache metrics

func (*RedisCache) Set added in v3.2.1

func (c *RedisCache) Set(
	ctx context.Context,
	key string,
	data []byte,
	refs []core.RowRef,
	queryStartTime time.Time,
) error

Set stores a response with row-level indices

func (*RedisCache) SetWithOptions added in v3.18.18

func (c *RedisCache) SetWithOptions(
	ctx context.Context,
	key string,
	data []byte,
	refs []core.RowRef,
	queryStartTime time.Time,
	opts core.CacheEntryOptions,
) error

SetWithOptions stores a response with dependency indices and per-entry TTL caps.

func (*RedisCache) SubmitRefresh added in v3.18.14

func (c *RedisCache) SubmitRefresh(key string, fn core.RefreshFn) bool

SubmitRefresh enqueues a stale-while-revalidate refresh on the worker pool. Returns false if SWR is disabled, the pool is full, or the cache is unavailable.

func (*RedisCache) SubmitRefreshWithOptions added in v3.18.18

func (c *RedisCache) SubmitRefreshWithOptions(key string, fn core.RefreshFnWithOptions) bool

SubmitRefreshWithOptions enqueues an option-aware stale-while-revalidate refresh.

type RedisConfig added in v3.2.1

type RedisConfig struct {
	// Redis connection URL (e.g., redis://localhost:6379/0)
	URL string `mapstructure:"url" jsonschema:"title=Redis URL"`
}

RedisConfig configures Redis connection

type RedisCursorCache added in v3.2.1

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

RedisCursorCache uses Redis for distributed cursor caching

func NewRedisCursorCache added in v3.2.1

func NewRedisCursorCache(redisURL string, ttl time.Duration) (*RedisCursorCache, error)

NewRedisCursorCache creates a new Redis cursor cache

func (*RedisCursorCache) Close added in v3.2.1

func (c *RedisCursorCache) Close() error

Close closes the Redis connection

func (*RedisCursorCache) Get added in v3.2.1

func (c *RedisCursorCache) Get(ctx context.Context, id uint64) (string, error)

Get retrieves a cursor by its numeric ID

func (*RedisCursorCache) Set added in v3.2.1

func (c *RedisCursorCache) Set(ctx context.Context, cursor string) (uint64, error)

Set stores a cursor and returns a short numeric ID

type RelationshipPath added in v3.18.3

type RelationshipPath struct {
	From  string          `json:"from"`
	To    string          `json:"to"`
	Steps []core.PathStep `json:"steps,omitempty"`
}

type RelationshipRef added in v3.18.5

type RelationshipRef struct {
	Table  string `json:"table"`
	Column string `json:"column,omitempty"`
	Type   string `json:"type,omitempty"`
}

type ResolverConfigInput added in v3.6.0

type ResolverConfigInput struct {
	Name        string           `json:"name"`
	Type        string           `json:"type"`
	Schema      string           `json:"schema,omitempty"`
	Table       string           `json:"table"`
	Column      string           `json:"column,omitempty"`
	StripPath   string           `json:"strip_path,omitempty"`
	URL         string           `json:"url,omitempty"`
	Debug       bool             `json:"debug,omitempty"`
	PassHeaders []string         `json:"pass_headers,omitempty"`
	SetHeaders  []SetHeaderInput `json:"set_headers,omitempty"`
}

ResolverConfigInput represents a resolver config for input

type ResponseCache added in v3.2.1

type ResponseCache interface {
	// Get retrieves a cached response
	// Returns (data, isStale, found)
	Get(ctx context.Context, key string) ([]byte, bool, bool)

	// Set stores a response with dependency refs for invalidation.
	Set(ctx context.Context, key string, data []byte, refs []core.RowRef, queryStartTime time.Time) error

	// InvalidateRows invalidates cache entries for dependency refs.
	InvalidateRows(ctx context.Context, refs []core.RowRef) error

	// InvalidateTables invalidates cache entries for whole tables when row-level
	// tracking is insufficient, such as external source reindexing.
	InvalidateTables(ctx context.Context, tables []string) error

	// SubmitRefresh enqueues a stale-while-revalidate refresh on the worker pool.
	// Returns false if SWR is disabled or the pool is full/shutdown.
	SubmitRefresh(key string, fn core.RefreshFn) bool

	// Metrics returns the cache metrics
	Metrics() *CacheMetrics

	// Close releases resources
	Close() error
}

ResponseCache defines the interface for response caching backends. Both RedisCache and MemoryCache implement this interface.

type ReturningInfo added in v3.2.1

type ReturningInfo struct {
	Description string `json:"description"`
	Example     string `json:"example"`
}

ReturningInfo describes the returning clause behavior

type RoleConfigInput added in v3.2.1

type RoleConfigInput struct {
	Name    string                 `json:"name"`
	Comment string                 `json:"comment,omitempty"`
	Match   string                 `json:"match,omitempty"`
	Tables  []RoleTableConfigInput `json:"tables,omitempty"`
}

RoleConfigInput represents a role config for input

type RoleInfo added in v3.2.1

type RoleInfo struct {
	Name    string           `json:"name"`
	Comment string           `json:"comment,omitempty"`
	Match   string           `json:"match,omitempty"`
	Tables  []core.RoleTable `json:"tables,omitempty"`
}

RoleInfo provides role information safe for JSON serialization

type RoleTableConfigInput added in v3.2.1

type RoleTableConfigInput struct {
	Name     string             `json:"name"`
	Schema   string             `json:"schema,omitempty"`
	Database string             `json:"database,omitempty"`
	ReadOnly bool               `json:"read_only,omitempty"`
	Query    *QueryConfigInput  `json:"query,omitempty"`
	Insert   *InsertConfigInput `json:"insert,omitempty"`
	Update   *UpdateConfigInput `json:"update,omitempty"`
	Upsert   *UpsertConfigInput `json:"upsert,omitempty"`
	Delete   *DeleteConfigInput `json:"delete,omitempty"`
}

RoleTableConfigInput represents a role table config for input

type RuntimeEventsConfig added in v3.18.31

type RuntimeEventsConfig struct {
	// MaxEvents is the maximum number of recent event rows retained.
	MaxEvents int `mapstructure:"max_events" jsonschema:"title=Runtime Event Limit,default=1000"`

	// TTLSeconds controls how long event rows are retained.
	TTLSeconds int `mapstructure:"ttl_seconds" jsonschema:"title=Runtime Event TTL Seconds,default=86400"`
}

RuntimeEventsConfig configures bounded agentic runtime observability rows.

type SWRWorkerPool added in v3.2.1

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

SWRWorkerPool runs background stale-while-revalidate refreshes. Concurrent submissions for the same key are deduplicated via singleflight, and the job channel is bounded so a thundering-herd of stale hits cannot spawn unbounded goroutines.

func NewSWRWorkerPool added in v3.2.1

func NewSWRWorkerPool(size int, target swrTarget) *SWRWorkerPool

NewSWRWorkerPool starts a fixed-size pool of refresh workers.

func (*SWRWorkerPool) Shutdown added in v3.2.1

func (p *SWRWorkerPool) Shutdown()

Shutdown drains and stops workers. Safe to call once.

func (*SWRWorkerPool) TrySubmit added in v3.2.1

func (p *SWRWorkerPool) TrySubmit(key string, fn core.RefreshFn) bool

TrySubmit enqueues a refresh job. Returns false if the pool is full or shutting down — the caller should treat that as "skip this refresh."

func (*SWRWorkerPool) TrySubmitWithOptions added in v3.18.18

func (p *SWRWorkerPool) TrySubmitWithOptions(key string, fn core.RefreshFnWithOptions) bool

TrySubmitWithOptions enqueues a refresh job with per-entry cache options.

type SchemaInsights added in v3.18.3

type SchemaInsights struct {
	Database          string             `json:"database"`
	DatabaseOverview  *DatabaseOverview  `json:"database_overview,omitempty"`
	HubTables         []HubTable         `json:"hub_tables,omitempty"`
	RelationshipPaths []RelationshipPath `json:"relationship_paths,omitempty"`
	NamespaceRouting  []NamespaceRoute   `json:"namespace_routing,omitempty"`
	QueryTemplates    []QueryTemplate    `json:"query_templates,omitempty"`
	DuplicateFlags    []DuplicateFlag    `json:"duplicate_flags,omitempty"`
	DataQualityFlags  []DataQualityFlag  `json:"data_quality_flags,omitempty"`
}

type SchemaStats added in v3.18.3

type SchemaStats struct {
	Name           string `json:"name"`
	TableCount     int    `json:"table_count"`
	ApproxRowTotal int64  `json:"approx_row_total"`
}

type Serv

type Serv struct {
	// Application name is used in log and debug messages
	AppName string `mapstructure:"app_name" jsonschema:"title=Application Name"`

	// Legacy production switch. Prefer top-level mode for new configs.
	Production bool `jsonschema:"title=Production Mode,default=false"`

	// The default path to find all configuration files and scripts
	ConfigPath string `mapstructure:"config_path" jsonschema:"title=Config Path"`

	// Logging level must be one of debug, error, warn, info
	LogLevel string `mapstructure:"log_level" jsonschema:"title=Log Level,enum=debug,enum=error,enum=warn,enum=info"`

	// Logging Format: "auto" (default, colored console in dev, JSON in production),
	// "json" (always JSON), or "simple" (always colored console)
	LogFormat string `mapstructure:"log_format" jsonschema:"title=Logging Format,enum=auto,enum=json,enum=simple"`

	// The host and port the service runs on. Example localhost:8080
	HostPort string `mapstructure:"host_port" jsonschema:"title=Host and Port"`

	// Host to run the service on
	Host string `jsonschema:"title=Host"`

	// Port to run the service on
	Port string `jsonschema:"title=Port"`

	// Enables HTTP compression
	HTTPGZip bool `mapstructure:"http_compress" jsonschema:"title=Enable Compression,default=true"`

	// Sets the API rate limits
	RateLimiter RateLimiter `mapstructure:"rate_limiter" jsonschema:"title=Set API Rate Limiting"`

	// Enables the Server-Timing HTTP header
	ServerTiming bool `mapstructure:"server_timing" jsonschema:"title=Server Timing HTTP Header,default=true"`

	// Enable the web UI. Disabled in production
	WebUI bool `mapstructure:"web_ui" jsonschema:"title=Enable Web UI,default=false"`

	// Enable OpenTrace request tracing
	EnableTracing bool `mapstructure:"enable_tracing" jsonschema:"title=Enable Tracing,default=true"`

	// Enables reloading the service on config changes. Disabled in production
	WatchAndReload bool `mapstructure:"reload_on_config_change" jsonschema:"title=Reload Config"`

	// Enable blocking requests with a HTTP 401 on auth failure
	AuthFailBlock bool `mapstructure:"auth_fail_block" jsonschema:"title=Block Request on Authorization Failure"`

	// Sets the HTTP CORS Access-Control-Allow-Origin header
	AllowedOrigins []string `mapstructure:"cors_allowed_origins" jsonschema:"title=HTTP CORS Allowed Origins"`

	// Sets the HTTP CORS Access-Control-Allow-Headers header
	AllowedHeaders []string `mapstructure:"cors_allowed_headers" jsonschema:"title=HTTP CORS Allowed Headers"`

	// Enables debug logs for CORS
	DebugCORS bool `mapstructure:"cors_debug" jsonschema:"title=Log CORS"`

	// Sets the HTTP Cache-Control header
	CacheControl string `mapstructure:"cache_control" jsonschema:"title=Enable Cache-Control"`

	// Sets the default authentication used by the service
	Auth Auth `jsonschema:"title=Authentication"`

	// Database configuration
	DB Database `mapstructure:"database" jsonschema:"title=Database"`

	// MCP (Model Context Protocol) server configuration
	MCP MCPConfig `mapstructure:"mcp" jsonschema:"title=MCP Configuration"`

	// Redis configuration
	Redis RedisConfig `mapstructure:"redis" jsonschema:"title=Redis Configuration"`

	// Runtime event configuration
	RuntimeEvents RuntimeEventsConfig `mapstructure:"runtime_events" jsonschema:"title=Runtime Events Configuration"`

	// Response caching configuration
	Caching CachingConfig `mapstructure:"caching" jsonschema:"title=Caching Configuration"`

	// Multipart upload configuration (graphql-multipart-request-spec)
	Uploads UploadsConfig `mapstructure:"uploads" jsonschema:"title=Multipart Uploads"`

	// Built-in OIDC login that mints local JWTs for the CLI / MCP client
	AuthLogin AuthLogin `mapstructure:"auth_login" jsonschema:"title=Built-in Login (OIDC)"`
}

Configuration for the GraphJin Service

type SetHeaderInput added in v3.6.0

type SetHeaderInput struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

SetHeaderInput represents a header name-value pair for resolver config

type SetupPlanResult added in v3.10.3

type SetupPlanResult struct {
	Candidates  []DiscoveredDatabase `json:"candidates"`
	Checklist   []string             `json:"selection_checklist"`
	Recommended string               `json:"recommended_candidate_id,omitempty"`
	Next        *NextGuidance        `json:"next,omitempty"`
}

type TableConfigInput added in v3.2.1

type TableConfigInput struct {
	Name      string              `json:"name"`
	Source    string              `json:"source,omitempty"`
	Database  string              `json:"database,omitempty"`
	ReadOnly  bool                `json:"read_only,omitempty"`
	Blocklist []string            `json:"blocklist,omitempty"`
	Columns   []ColumnConfigInput `json:"columns,omitempty"`
	OrderBy   map[string][]string `json:"order_by,omitempty"`
}

TableConfigInput represents a table config for input

type TableDetailEntry added in v3.18.3

type TableDetailEntry struct {
	TableIndexEntry
	Schema  *core.TableSchema `json:"schema,omitempty"`
	Profile *TableProfile     `json:"profile,omitempty"`
}

type TableIndexEntry added in v3.18.3

type TableIndexEntry struct {
	Name        string `json:"name"`
	Schema      string `json:"schema,omitempty"`
	Database    string `json:"database,omitempty"`
	Type        string `json:"type,omitempty"`
	Comment     string `json:"comment,omitempty"`
	ColumnCount int    `json:"column_count,omitempty"`
	// nil = unknown (catalog stats unavailable); 0 = measured zero.
	RowCountApprox    *int64          `json:"row_count_approx,omitempty"`
	PrimaryKeys       []string        `json:"primary_keys,omitempty"`
	ForeignKeys       []ForeignKeyRef `json:"foreign_keys,omitempty"`
	KeyColumns        []string        `json:"key_columns,omitempty"`
	ColumnTypeSummary map[string]int  `json:"column_type_summary,omitempty"`
	JoinTargets       []string        `json:"join_targets,omitempty"`
	DuplicateIn       []string        `json:"duplicate_in,omitempty"`
}

type TableListOptions added in v3.18.5

type TableListOptions struct {
	Search string
	Schema string
	Limit  int
	Cursor string
}

type TableProfile added in v3.18.3

type TableProfile struct {
	RowCountApprox *int64                  `json:"row_count_approx,omitempty"`
	DateRanges     map[string]DateRange    `json:"date_ranges,omitempty"`
	EnumValues     map[string]EnumProfile  `json:"enum_values,omitempty"`
	NumericStats   map[string]NumericStats `json:"numeric_stats,omitempty"`
	ColumnStats    map[string]ColumnStats  `json:"column_stats,omitempty"`
	SampleRows     []map[string]any        `json:"sample_rows,omitempty"`
}

type TableRef added in v3.18.3

type TableRef struct {
	Name           string `json:"name"`
	Schema         string `json:"schema,omitempty"`
	RowCountApprox int64  `json:"row_count_approx"`
}

type TableSampleResult added in v3.18.5

type TableSampleResult struct {
	Database string        `json:"database"`
	Schema   string        `json:"schema,omitempty"`
	Table    string        `json:"table"`
	Status   string        `json:"status"`
	Stats    *TableProfile `json:"stats,omitempty"`

	PrimaryKeys           []string                `json:"primary_keys,omitempty"`
	ForeignKeys           []ForeignKeyRef         `json:"foreign_keys,omitempty"`
	OutgoingRels          []RelationshipRef       `json:"outgoing_relationships,omitempty"`
	IncomingRels          []RelationshipRef       `json:"incoming_relationships,omitempty"`
	FKDisambiguation      []FKDisambiguationEntry `json:"fk_disambiguation,omitempty"`
	Indexes               []IndexInfo             `json:"indexes,omitempty"`
	Aggregations          *AggregationInfo        `json:"aggregations,omitempty"`
	ExampleQueries        []ExampleQuery          `json:"example_queries,omitempty"`
	AnalyticsModeRules    []string                `json:"analytics_mode_rules,omitempty"`
	AggregationHint       string                  `json:"aggregation_hint,omitempty"`
	TemporalFilterWarning string                  `json:"temporal_filter_warning,omitempty"`

	Cost DiscoveryCost `json:"cost"`
}

type TableSchemaWithAggregations added in v3.2.1

type TableSchemaWithAggregations struct {
	*core.TableSchema
	Aggregations   AggregationInfo `json:"aggregations"`
	ExampleQueries []ExampleQuery  `json:"example_queries,omitempty"`
}

TableSchemaWithAggregations extends TableSchema with aggregation information

type ToolReplaces added in v3.18.21

type ToolReplaces struct {
	Tool        string `json:"tool"`
	Replacement string `json:"replacement"`
	For         string `json:"for,omitempty"`
}

type UpdateConfigInput added in v3.2.1

type UpdateConfigInput struct {
	Filters []string          `json:"filters,omitempty"`
	Columns []string          `json:"columns,omitempty"`
	Presets map[string]string `json:"presets,omitempty"`
	Block   bool              `json:"block,omitempty"`
}

UpdateConfigInput represents update permissions

type UploadsConfig added in v3.18.14

type UploadsConfig struct {
	// Enable multipart/form-data parsing on /api/v1/graphql
	Enabled bool `mapstructure:"enabled" jsonschema:"title=Enable Uploads,default=false"`

	// MaxSize is the per-request multipart body limit in bytes.
	// Defaults to 25 MB when zero.
	MaxSize int64 `mapstructure:"max_size" jsonschema:"title=Max Upload Size (bytes),default=26214400"`

	// AllowedMIME, when non-empty, restricts the accepted content types.
	// Glob patterns are supported: "image/*", "application/pdf".
	AllowedMIME []string `mapstructure:"allowed_mime" jsonschema:"title=Allowed MIME Types"`

	// Storage names a filesystems[].name to stream uploads into. When
	// empty, the legacy inline-base64 mode is used. When set, files
	// are written to the backend and the variable becomes the object
	// metadata instead of inlined data.
	Storage string `mapstructure:"storage" jsonschema:"title=Filesystem Table for Streaming"`

	// StorageKeyPrefix is prepended to the backend key for every
	// uploaded file. Useful for namespacing by tenant or role.
	// Example: "avatars/{date}/" — the {date} marker is substituted
	// at request time with YYYY/MM/DD.
	StorageKeyPrefix string `mapstructure:"storage_key_prefix" jsonschema:"title=Storage Key Prefix"`
}

UploadsConfig configures the multipart-form upload endpoint following the graphql-multipart-request-spec (https://github.com/jaydenseric/graphql-multipart-request-spec).

When Enabled, /api/v1/graphql accepts multipart/form-data POSTs in addition to application/json. Files are then either:

  1. Inlined as base64 into the variable at its declared path (default — Storage is empty):

    { filename, content_type, size, data (base64) }

  2. Streamed to a configured filesystem table (Storage="avatars"), with the variable replaced by the resulting object metadata:

    { key, content_type, size, url, etag, modified_at }

Mode 2 keeps large bodies out of the GraphQL request/response and lets mutations write a single JSONB column whose value is a stable, queryable file reference.

type UpsertConfigInput added in v3.2.1

type UpsertConfigInput struct {
	Filters []string          `json:"filters,omitempty"`
	Columns []string          `json:"columns,omitempty"`
	Presets map[string]string `json:"presets,omitempty"`
	Block   bool              `json:"block,omitempty"`
}

UpsertConfigInput represents upsert permissions

type ValidationSyntax added in v3.2.1

type ValidationSyntax struct {
	Directive string   `json:"directive"`
	Options   []string `json:"options"`
	Example   string   `json:"example"`
}

ValidationSyntax shows validation directive options

type VariablesSyntax added in v3.2.1

type VariablesSyntax struct {
	Declaration string   `json:"declaration"`
	Types       []string `json:"types"`
	Example     string   `json:"example"`
}

VariablesSyntax shows how to use variables in queries

type WhereValidationError added in v3.2.1

type WhereValidationError struct {
	Path       string `json:"path"`
	Error      string `json:"error"`
	Message    string `json:"message"`
	ColumnType string `json:"column_type,omitempty"`
	Suggestion string `json:"suggestion,omitempty"`
}

WhereValidationError represents a single validation error

type WhereValidationResult added in v3.2.1

type WhereValidationResult struct {
	Valid          bool                      `json:"valid"`
	Errors         []WhereValidationError    `json:"errors,omitempty"`
	Warnings       []string                  `json:"warnings,omitempty"`
	CompilerErrors []string                  `json:"compiler_errors,omitempty"`
	ValidatedBy    string                    `json:"validated_by,omitempty"`
	ExampleQuery   string                    `json:"example_query,omitempty"`
	ColumnInfo     map[string]ColumnTypeInfo `json:"column_info,omitempty"`
}

WhereValidationResult represents the result of where clause validation

type WorkflowGuide added in v3.2.1

type WorkflowGuide struct {
	QueryWorkflow      []string          `json:"query_workflow"`
	MutationWorkflow   []string          `json:"mutation_workflow"`
	Tips               []string          `json:"tips"`
	AnalyticsModeRules []string          `json:"analytics_mode_rules,omitempty"`
	QueryPatterns      []QueryPattern    `json:"query_patterns,omitempty"`
	ToolSequences      map[string]string `json:"tool_sequences"`
}

WorkflowGuide contains the recommended workflow for using GraphJin MCP tools

type WorkflowInfo added in v3.14.0

type WorkflowInfo struct {
	Name             string             `json:"name"`
	Description      string             `json:"description"`
	Tags             []string           `json:"tags,omitempty"`
	Variables        []WorkflowVariable `json:"variables,omitempty"`
	CreatedAt        string             `json:"created_at,omitempty"`
	UpdatedAt        string             `json:"updated_at,omitempty"`
	WorkflowRevision string             `json:"workflow_revision,omitempty"`
}

WorkflowInfo is returned by list_workflows.

type WorkflowMeta added in v3.14.0

type WorkflowMeta struct {
	Description string             `json:"description"`
	Tags        []string           `json:"tags,omitempty"`
	Variables   []WorkflowVariable `json:"variables,omitempty"`
	CreatedAt   string             `json:"created_at,omitempty"`
	UpdatedAt   string             `json:"updated_at,omitempty"`
}

WorkflowMeta holds discoverable metadata for a saved workflow.

type WorkflowVariable added in v3.14.1

type WorkflowVariable struct {
	Name        string `json:"name"`
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

WorkflowVariable describes one input variable expected by a saved workflow.

Directories

Path Synopsis
internal
tools command

Jump to

Keyboard shortcuts

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