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
- Variables
- func ConfigDocsTemplate(variant string) string
- func ConfigJSONSchema() []byte
- func ConfigKeyScope(key string) (scope string, reload string)
- func EnsureArtifactStore(conf *Config, dbs map[string]*sql.DB) error
- func GetConfigName() string
- func InitAdmin(db *sql.DB, dbtype string) error
- func InitTelemetry(context context.Context, exporter trace.SpanExporter, ...) error
- func MCPAllToolNames() []string
- func NewDB(conf *Config, openDB bool, log *zap.SugaredLogger, fs core.FS) (*sql.DB, error)
- type AgentConfig
- type AggregationInfo
- type AggregationsSyntax
- type AnalyticsDirectivesSyntax
- type ApplyDatabaseSetupResult
- type ApplyVerification
- type Auth
- type AuthLogin
- type AuthLoginOIDC
- type CacheEntry
- type CacheMetrics
- type CachingConfig
- type CatalogCapabilitiesResult
- type CatalogCardResult
- type CatalogEntrypointsResult
- type CatalogItem
- type CatalogOverviewResource
- type CatalogQueryResult
- type CatalogSearchConfig
- type CodeSQLMutationDSL
- type ColumnConfigInput
- type ColumnStats
- type ColumnTypeInfo
- type Config
- type ConfigUpdateRequest
- type ConfigUpdateResult
- type ConnectDisconnect
- type ConnectionTestResult
- type Core
- type CursorCache
- type DDLApplyResult
- type DDLOperationInfo
- type DDLPreviewResult
- type DDLSummary
- type DataQualityFlag
- type Database
- type DatabaseConfigInput
- type DatabaseConnection
- type DatabaseOverview
- type DateRange
- type DeleteConfigInput
- type DiscoverResult
- type DiscoverSummary
- type DiscoverTarget
- type DiscoveredDatabase
- type DiscoveryCacheConfig
- type DiscoveryCost
- type DiscoveryFullPayload
- type DiscoveryManager
- func (dm *DiscoveryManager) DatabaseOverview(database string) DatabaseOverview
- func (dm *DiscoveryManager) Databases() []string
- func (dm *DiscoveryManager) FullDatabaseOverview(database string) DatabaseOverview
- func (dm *DiscoveryManager) FullPayload(database string) *DiscoveryFullPayload
- func (dm *DiscoveryManager) FullTables(database string) []TableDetailEntry
- func (dm *DiscoveryManager) FullTablesPage(database string, opts TableListOptions) []TableDetailEntry
- func (dm *DiscoveryManager) Insights(database string) SchemaInsights
- func (dm *DiscoveryManager) Invalidate()
- func (dm *DiscoveryManager) Namespaces(ctx context.Context, database string) []NamespaceRollup
- func (dm *DiscoveryManager) Payload(database string) *DiscoveryPayload
- func (dm *DiscoveryManager) Profile(database, table string) *TableProfile
- func (dm *DiscoveryManager) RowCountsForNamespace(ctx context.Context, database, schema string) map[string]int64
- func (dm *DiscoveryManager) Subscribe(ctx context.Context, database string) (*DiscoverySubscription, error)
- func (dm *DiscoveryManager) TableIndex(database string) []TableIndexEntry
- func (dm *DiscoveryManager) TableIndexPage(_ context.Context, database string, opts TableListOptions) ListTablesResult
- func (dm *DiscoveryManager) TableSample(ctx context.Context, database, schemaName, table string) (*TableSampleResult, error)
- type DiscoveryPayload
- type DiscoverySubscription
- type DockerDBInfo
- type DuplicateFlag
- type EnhancedError
- type EnumProfile
- type EnumValue
- type ErrorInfo
- type ExampleQuery
- type ExecErrorClass
- type ExecuteResult
- type FKDisambiguationCandidate
- type FKDisambiguationEntry
- type FilterOperators
- type FixQueryErrorResult
- type ForeignKeyRef
- type FunctionConfigInput
- type GraphQLHelpResult
- type HealthResult
- type HelpRoute
- type HookFn
- type HttpService
- func (s *HttpService) Agent(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) AgentStatus(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) AgentStatusWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) AgentWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) Attach(mux Mux) error
- func (s *HttpService) AttachWithNS(mux Mux, namespace string) error
- func (s *HttpService) Close() error
- func (s *HttpService) ConsoleBootstrap(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) ConsoleBootstrapWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) Deploy(conf *Config, options ...Option) error
- func (s *HttpService) EvalReports(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) EvalReportsWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) EvalScore(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) EvalScoreWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) GetDB() *sql.DB
- func (s *HttpService) GetGraphJin() *core.GraphJin
- func (s *HttpService) GraphQL(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) GraphQLWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) MCPHandler() http.Handler
- func (s *HttpService) MCPHandlerWithAuth(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) MCPMessageHandler() http.Handler
- func (s *HttpService) MCPMessageHandlerWithAuth(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) OpenAPI() http.Handler
- func (s *HttpService) OpenAPIWithNS(ns string) http.Handler
- func (s *HttpService) REST(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) RESTWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) Reload() error
- func (s *HttpService) RunMCPStdio(ctx context.Context) error
- func (s *HttpService) Shutdown(ctx context.Context) error
- func (s *HttpService) Start() error
- func (s1 *HttpService) Watches(ah auth.HandlerFunc) http.Handler
- func (s1 *HttpService) WatchesWithNS(ah auth.HandlerFunc, ns string) http.Handler
- func (s *HttpService) WebUI(routePrefix, gqlEndpoint string) http.Handler
- func (s *HttpService) Workflows(ah auth.HandlerFunc) http.Handler
- func (s *HttpService) WorkflowsWithNS(ah auth.HandlerFunc, ns string) http.Handler
- type HubTable
- type IndexInfo
- type InsertConfigInput
- type JSRuntimeAPI
- type JSRuntimeFunction
- type JSRuntimeGlobal
- type JWTConfig
- type KeystoreConfig
- type ListDatabasesResult
- type ListNamespacesResult
- type ListTablesResult
- type MCPCLIResource
- type MCPCapabilityProfile
- type MCPCatalogCapability
- type MCPConfig
- type MCPConfigResponse
- type MCPOAuthConfig
- type MCPRootProfile
- type MCPToolEvent
- type MemoryCache
- func (mc *MemoryCache) Close() error
- func (mc *MemoryCache) Get(ctx context.Context, key string) ([]byte, bool, bool)
- func (mc *MemoryCache) InvalidateRows(ctx context.Context, refs []core.RowRef) error
- func (mc *MemoryCache) InvalidateTables(ctx context.Context, tables []string) error
- func (mc *MemoryCache) Metrics() *CacheMetrics
- func (mc *MemoryCache) Set(ctx context.Context, key string, data []byte, refs []core.RowRef, ...) error
- func (mc *MemoryCache) SetWithOptions(ctx context.Context, key string, data []byte, refs []core.RowRef, ...) error
- func (mc *MemoryCache) SubmitRefresh(key string, fn core.RefreshFn) bool
- func (mc *MemoryCache) SubmitRefreshWithOptions(key string, fn core.RefreshFnWithOptions) bool
- type MemoryCursorCache
- type MistakeExample
- type MutationOperations
- type MutationSyntaxReference
- type Mux
- type NamespaceRollup
- type NamespaceRoute
- type NestedMutationInfo
- type NextGuidance
- type NextOption
- type NumericStats
- type OnboardingStatusResult
- type OperatorSeed
- type Option
- func OptionDisableQueryLearning() Option
- func OptionSetAgentClientFactory(factory gjagent.ClientFactory) Option
- func OptionSetAgentNow(now func() time.Time) Option
- func OptionSetDB(db *sql.DB) Option
- func OptionSetDatabases(dbs map[string]*sql.DB) Option
- func OptionSetFS(fs core.FS) Option
- func OptionSetHookFunc(fn HookFn) Option
- func OptionSetLogOutput(output zapcore.WriteSyncer) Option
- func OptionSetMCPToolRecorder(recorder func(MCPToolEvent)) Option
- func OptionSetNamespace(namespace string) Option
- func OptionSetOperatorSeed(seed OperatorSeed) Option
- func OptionSetRuntimeSchemaDDLDir(dir string) Option
- func OptionSetSemanticEmbeddingClient(client SemanticEmbeddingClient) Option
- func OptionSetZapLogger(zlog *zap.Logger) Option
- type OrderingSyntax
- type PaginationSyntax
- type Payload
- type PoolStatsInfo
- type QueryConfigInput
- type QueryExample
- type QueryExamplesForSyntax
- type QueryPattern
- type QuerySyntaxReference
- type QueryTemplate
- type RateLimiter
- type RecursiveSyntax
- type RedisCache
- func (c *RedisCache) Close() error
- func (c *RedisCache) Get(ctx context.Context, key string) ([]byte, bool, bool)
- func (c *RedisCache) InvalidateRows(ctx context.Context, refs []core.RowRef) error
- func (c *RedisCache) InvalidateTables(ctx context.Context, tables []string) error
- func (c *RedisCache) Metrics() *CacheMetrics
- func (c *RedisCache) Set(ctx context.Context, key string, data []byte, refs []core.RowRef, ...) error
- func (c *RedisCache) SetWithOptions(ctx context.Context, key string, data []byte, refs []core.RowRef, ...) error
- func (c *RedisCache) SubmitRefresh(key string, fn core.RefreshFn) bool
- func (c *RedisCache) SubmitRefreshWithOptions(key string, fn core.RefreshFnWithOptions) bool
- type RedisConfig
- type RedisCursorCache
- type RelationshipPath
- type RelationshipRef
- type ResolverConfigInput
- type ResponseCache
- type ReturningInfo
- type RoleConfigInput
- type RoleInfo
- type RoleTableConfigInput
- type RuntimeEventsConfig
- type SWRWorkerPool
- type SchemaInsights
- type SchemaStats
- type SecretsConfig
- type SemanticCatalogSearchConfig
- type SemanticEmbeddingClient
- type Serv
- type SetHeaderInput
- type SetupPlanResult
- type TableConfigInput
- type TableDetailEntry
- type TableIndexEntry
- type TableListOptions
- type TableProfile
- type TableRef
- type TableSampleResult
- type TableSchemaWithAggregations
- type ToolReplaces
- type UpdateConfigInput
- type UploadsConfig
- type UpsertConfigInput
- type ValidationSyntax
- type VariablesSyntax
- type WatchSeed
- type WhereValidationError
- type WhereValidationResult
- type WorkflowGuide
- type WorkflowInfo
- type WorkflowMeta
- type WorkflowVariable
Constants ¶
const ( ConfigScopeServ = "serv" // server settings (host, auth, rate limiting, agent, ...) ConfigScopeCore = "core" // compiler-core settings (sources, tables, roles, ...) ConfigScopeMixed = "mixed" // a proposed update spanning both config halves )
Config scope constants classify a top-level config key by which half of the config it belongs to.
const ( ExecKindColumnNotFound = "column_not_found" ExecKindTableNotFound = "table_not_found" ExecKindTypeMismatch = "type_mismatch" ExecKindSyntaxError = "syntax_error" ExecKindPermission = "permission_denied" ExecKindUnknown = "" )
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" )
const ( WatchEventsUnseenResourceURI = "graphjin://watch-events/unseen" WatchEventsUnseenResourceTemplateURI = WatchEventsUnseenResourceURI + "/{watch_id}" )
const JSRuntimeResourceURI = "graphjin://syntax/workflow-js"
Variables ¶
var ErrGraphJinNotInitialized = errors.New("GraphJin not initialized - no database configured")
ErrGraphJinNotInitialized is returned when GraphJin core is not initialized
Functions ¶
func ConfigDocsTemplate ¶ added in v3.18.44
ConfigDocsTemplate returns the annotated example config template for the given variant ("dev", "prod", or "agentic"); any other value returns dev. These are the annotated counterparts to the templates `graphjin serve new` scaffolds, exposed for `graphjin config docs` (offline, no server).
func ConfigJSONSchema ¶ added in v3.18.44
func ConfigJSONSchema() []byte
ConfigJSONSchema returns the JSON Schema describing the full GraphJin configuration file (serv.Config, core sections included). It powers editor autocomplete via yaml-language-server modelines, the dev-mode /api/v1/config/schema.json endpoint, and `graphjin config schema`.
func ConfigKeyScope ¶ added in v3.18.44
ConfigKeyScope reports whether a top-level config key is a server ("serv") or compiler-core ("core") setting, and — for server settings the runtime config machinery can patch — whether a change applies live ("hot") or needs a restart ("restart"). reload is "" for keys that are not runtime-writable via gj_config/update_current_config. The key is the first dotted segment, e.g. "rate_limiter" for "rate_limiter.rate".
func EnsureArtifactStore ¶ added in v3.18.42
EnsureArtifactStore creates the artifact (and watch) store tables for the configured artifact source. Demo tooling calls this after seeding and before generating its schema-DDL cache, so the cached schema, which core loads in place of live discovery in demo mode — includes the store tables that gj_artifacts/gj_watch role rules and internal-store queries compile against.
func GetConfigName ¶
func GetConfigName() string
GetConfigName returns the name of the configuration
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.
Types ¶
type AgentConfig ¶ added in v3.18.42
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"`
HasuraCompatible string `json:"hasura_compatible"`
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 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"`
// Match is carried internally from the service-owned catalog search into
// the top-level explain map. It is deliberately omitted from each card so
// explanations have one stable, non-duplicated response shape.
Match core.CatalogMatch `json:"-"`
}
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"`
CapabilityProfile *MCPCapabilityProfile `json:"capability_profile,omitempty"`
Next *NextGuidance `json:"next,omitempty"`
}
type CatalogSearchConfig ¶ added in v3.18.46
type CatalogSearchConfig struct {
Semantic SemanticCatalogSearchConfig `mapstructure:"semantic" jsonschema:"title=Semantic Catalog Search"`
}
CatalogSearchConfig configures catalog retrieval extensions.
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"`
// Name of another config file in the same directory to inherit and
// override (one level only; the inherited file cannot itself inherit).
// Example: prod.yml sets `inherits: dev` to start from dev.yml values.
Inherits string `mapstructure:"inherits" jsonschema:"title=Inherit From Config File"`
// contains filtered or unexported fields
}
Configuration for the GraphJin service
func NewConfig ¶
NewConfig function creates a new GraphJin configuration from the provided config string
func ReadInConfig ¶
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 ¶
ReadInConfigFS is the same as ReadInConfig but it also takes a filesytem as an argument
func (*Config) AbsolutePath ¶
AbsolutePath returns the absolute path of the file
func (*Config) EffectiveSettings ¶ added in v3.18.44
EffectiveSettings returns all config settings after defaults, one-level inheritance, and GJ_/SJ_ environment overrides have been applied. Keys are viper's canonical lower-cased dotted keys. Intended for tooling such as `graphjin config get` and `graphjin config explain`.
func (*Config) ShouldUseJSONLogs ¶ added in v3.2.1
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 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"`
Scope string `json:"scope,omitempty"`
ReloadMode string `json:"reload_mode,omitempty"`
ReloadStrategy string `json:"reload_strategy,omitempty"`
ChangedSources []string `json:"changed_sources,omitempty"`
ReloadFallback bool `json:"reload_fallback,omitempty"`
Valid bool `json:"valid,omitempty"`
Applied bool `json:"applied,omitempty"`
Mode string `json:"mode,omitempty"`
PreviewID string `json:"preview_id,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
CatalogRevision string `json:"catalog_revision,omitempty"`
ChangeSummaryJSON string `json:"change_summary_json,omitempty"`
FindingsJSON string `json:"findings_json,omitempty"`
ErrorsJSON string `json:"errors_json,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 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
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 Database ¶
type Database struct {
ConnString string `mapstructure:"connection_string" jsonschema:"title=Connection String"`
Type string `` /* 152-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)"`
// Cassandra / Amazon Keyspaces consistency level (default LOCAL_QUORUM).
Consistency string `mapstructure:"consistency" jsonschema:"title=Cassandra Consistency Level"`
}
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 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 DiscoveryCacheConfig ¶ added in v3.18.46
type DiscoveryCacheConfig struct {
// Enabled starts GraphJin Service from validated filesystem generations and
// moves schema refreshes onto the coordinated generation path.
Enabled *bool `mapstructure:"enabled" jsonschema:"title=Enable Discovery Cache,default=true"`
// Path stores immutable full schema snapshots, manifests, activation
// receipts, and semantic indexes. Horizontal replicas must share this path.
Path string `mapstructure:"path" jsonschema:"title=Discovery Cache Path,default=.graphjin/discovery"`
// RefreshInterval controls background live-schema checks after startup.
RefreshInterval time.Duration `mapstructure:"refresh_interval" jsonschema:"title=Discovery Refresh Interval,default=5m"`
// StartupWait bounds cold follower and explicit refresh activation waits.
StartupWait time.Duration `mapstructure:"startup_wait" jsonschema:"title=Discovery Startup Wait,default=2m"`
// RetainGenerations is the number of activated generations kept when the
// configured filesystem supports deletion.
RetainGenerations int `mapstructure:"retain_generations" jsonschema:"title=Retained Discovery Generations,default=2"`
}
DiscoveryCacheConfig configures service-owned schema discovery generations. Enabled is a pointer so an embedded Go configuration can distinguish an omitted value (enabled) from an explicit false.
type DiscoveryCost ¶ added in v3.18.5
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 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 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
ExampleQuery represents an example GraphQL query for a table
type ExecErrorClass ¶ added in v3.18.8
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"`
// Truncation marks result lists that reached their compiled row limit —
// pages, not populations. Callers must not aggregate over them.
Truncation *gjagent.TruncationInfo `json:"truncation,omitempty"`
}
ExecuteResult represents the result of a query execution
type FKDisambiguationCandidate ¶ added in v3.18.8
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 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"`
CapabilityProfile *MCPCapabilityProfile `json:"capability_profile,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 HttpService ¶
func NewGraphJinService ¶
func NewGraphJinService(conf *Config, options ...Option) (*HttpService, error)
NewGraphJinService a new service
func (*HttpService) Agent ¶ added in v3.18.42
func (s *HttpService) Agent(ah auth.HandlerFunc) http.Handler
Agent is the HTTP handler for the server-side GraphJin agent endpoint.
func (*HttpService) AgentStatus ¶ added in v3.18.42
func (s *HttpService) AgentStatus(ah auth.HandlerFunc) http.Handler
AgentStatus is the HTTP handler for the server-side GraphJin agent readiness endpoint.
func (*HttpService) AgentStatusWithNS ¶ added in v3.18.42
func (s *HttpService) AgentStatusWithNS(ah auth.HandlerFunc, ns string) http.Handler
AgentStatusWithNS is the namespaced HTTP handler for the server-side GraphJin agent readiness endpoint.
func (*HttpService) AgentWithNS ¶ added in v3.18.42
func (s *HttpService) AgentWithNS(ah auth.HandlerFunc, ns string) http.Handler
AgentWithNS is the namespaced HTTP handler for the server-side GraphJin agent endpoint.
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(). Close releases everything the service owns and does not return until the background workers it started have actually stopped.
It runs the same shutdown a listening server runs when Serve returns. It used to run a second, subtly different one: it closed the core and the databases without first cancelling the watch and revision workers or waiting for them. A caller that closed a service and then touched its database files — which is exactly what an evaluation reset does between episodes — could have those files replaced underneath a goroutine still holding them open, and SQLite reported the result as a malformed database several seconds later, in an unrelated request.
Two shutdown sequences for one service is how those diverge in the first place, so there is now one.
func (*HttpService) ConsoleBootstrap ¶ added in v3.20.4
func (s *HttpService) ConsoleBootstrap(ah auth.HandlerFunc) http.Handler
ConsoleBootstrap exposes only the caller-safe information needed to choose the console workspace and navigation. It is advisory UI metadata; GraphJin's normal root and action authorization remains authoritative for every request.
func (*HttpService) ConsoleBootstrapWithNS ¶ added in v3.20.4
func (s *HttpService) ConsoleBootstrapWithNS(ah auth.HandlerFunc, ns string) http.Handler
ConsoleBootstrapWithNS is the namespaced console bootstrap endpoint.
func (*HttpService) Deploy ¶
func (s *HttpService) Deploy(conf *Config, options ...Option) error
Deploy a new configuration
func (*HttpService) EvalReports ¶ added in v3.20.5
func (s *HttpService) EvalReports(ah auth.HandlerFunc) http.Handler
func (*HttpService) EvalReportsWithNS ¶ added in v3.20.5
func (s *HttpService) EvalReportsWithNS(ah auth.HandlerFunc, ns string) http.Handler
func (*HttpService) EvalScore ¶ added in v3.20.72
func (s *HttpService) EvalScore(ah auth.HandlerFunc) http.Handler
func (*HttpService) EvalScoreWithNS ¶ added in v3.20.72
func (s *HttpService) EvalScoreWithNS(ah auth.HandlerFunc, ns string) http.Handler
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 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 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) Shutdown ¶ added in v3.18.44
func (s *HttpService) Shutdown(ctx context.Context) error
Shutdown gracefully stops the running HTTP server so that a blocking Start returns. In-flight requests are drained until the context deadline, after which the server is force-closed. It is safe to call more than once and before Start (a no-op when the server was never started). Callers that embed the service and run their own signal handling use this to unblock Start; the service resources (databases, cache, etc.) are then released as Start returns, or explicitly via Close.
func (*HttpService) Start ¶
func (s *HttpService) Start() error
Start the service listening on the configured port
func (*HttpService) Watches ¶ added in v3.18.42
func (s1 *HttpService) Watches(ah auth.HandlerFunc) http.Handler
func (*HttpService) WatchesWithNS ¶ added in v3.18.42
func (s1 *HttpService) WatchesWithNS(ah auth.HandlerFunc, ns string) http.Handler
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 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 KeystoreConfig ¶ added in v3.18.35
type KeystoreConfig struct {
Key string `mapstructure:"key" jsonschema:"title=Keystore Key" jsonschema_extras:"x-graphjin-sensitive=secret"`
Path string `mapstructure:"path" jsonschema:"title=Keystore Path"`
}
KeystoreConfig configures the local encrypted keystore.
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
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 MCPCapabilityProfile ¶ added in v3.18.35
type MCPCapabilityProfile struct {
Mode string `json:"mode,omitempty"`
SourcesMode bool `json:"sources_mode"`
RoleClass string `json:"role_class"`
Authenticated bool `json:"authenticated"`
CatalogRevision string `json:"catalog_revision,omitempty"`
AvailableTools []string `json:"available_tools,omitempty"`
AllowedActions []string `json:"allowed_actions,omitempty"`
AvailableRoots []MCPRootProfile `json:"available_roots,omitempty"`
BlockedRoots []MCPRootProfile `json:"blocked_roots,omitempty"`
VisibleCapabilities []MCPCatalogCapability `json:"visible_capabilities,omitempty"`
RecommendedEntrypoint string `json:"recommended_entrypoint,omitempty"`
SafetyNotes []string `json:"safety_notes,omitempty"`
}
type MCPCatalogCapability ¶ added in v3.18.35
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"`
// OAuth exposes standards-compatible authorization discovery for remote MCP clients.
OAuth MCPOAuthConfig `mapstructure:"oauth" jsonschema:"title=MCP OAuth Configuration"`
// 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"`
// IncludeToolsWithAgent keeps the low-level MCP tools (query_catalog,
// graphql_help, execute_saved_query, execute_graphql, validate_where_clause,
// schema tools) registered even when the ask_graphjin_agent tool is enabled.
// Dev and agentic configs expose both the agent and primitives by default.
// Set false to make the agent the only front-door tool.
IncludeToolsWithAgent bool `` /* 187-byte string literal not displayed */
// LegacyDiscovery keeps legacy HTTP helper endpoints such as
// /api/v1/discovery and /api/v1/workflows available for compatibility.
// It no longer expands the MCP tool surface; MCP is catalog-first.
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 GraphJin DDL (db.ddl) 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.
// 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 keeps the legacy HTTP workflow execution surface
// available when legacy discovery is enabled. MCP workflow execution uses
// catalog discovery plus gj_workflow_execution.
// 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 any `json:"sources,omitempty"`
System core.SystemConfig `json:"system,omitempty"`
Workflows core.WorkflowsConfig `json:"workflows,omitempty"`
Databases any `json:"databases,omitempty"`
Relationships any `json:"relationships,omitempty"`
Metadata core.MetadataConfig `json:"metadata,omitempty"`
Tables any `json:"tables,omitempty"`
Roles any `json:"roles,omitempty"`
Blocklist []string `json:"blocklist,omitempty"`
Functions any `json:"functions,omitempty"`
Resolvers any `json:"resolvers,omitempty"`
MCP MCPConfig `json:"mcp,omitempty"`
}
MCPConfigResponse represents a section of the configuration for MCP
type MCPOAuthConfig ¶ added in v3.18.37
type MCPOAuthConfig struct {
// Enable OAuth metadata/challenge support for the MCP HTTP endpoint.
Enabled bool `mapstructure:"enabled" jsonschema:"title=Enable MCP OAuth,default=false"`
// Mode selects the authorization-server strategy: builtin uses auth_login
// to run an authorization-code + PKCE flow; external advertises the
// configured AuthorizationServers and validates bearer tokens via auth.jwt.
Mode string `mapstructure:"mode" jsonschema:"title=MCP OAuth Mode,enum=builtin,enum=external"`
// Resource is the expected OAuth audience/resource value. Defaults to the
// public /api/v1/mcp URL for the incoming request.
Resource string `mapstructure:"resource" jsonschema:"title=MCP OAuth Resource"`
// Issuer is the authorization server issuer. In builtin mode it defaults to
// the public origin of the incoming request.
Issuer string `mapstructure:"issuer" jsonschema:"title=MCP OAuth Issuer"`
// AuthorizationServers are advertised by protected-resource metadata in
// external mode. Defaults to Issuer when empty.
AuthorizationServers []string `mapstructure:"authorization_servers" jsonschema:"title=MCP OAuth Authorization Servers"`
// Scopes advertised and accepted by the MCP authorization server.
Scopes []string `mapstructure:"scopes" jsonschema:"title=MCP OAuth Scopes"`
// DynamicClientRegistration exposes RFC 7591 registration in builtin mode.
DynamicClientRegistration bool `mapstructure:"dynamic_client_registration" jsonschema:"title=Enable MCP OAuth Dynamic Client Registration,default=true"`
// ClientIDMetadataDocuments lets clients use CIMD URLs instead of DCR.
ClientIDMetadataDocuments bool `mapstructure:"client_id_metadata_documents" jsonschema:"title=Enable MCP OAuth Client ID Metadata Documents,default=true"`
// AccessTokenTTL controls builtin-mode access token lifetime.
AccessTokenTTL time.Duration `mapstructure:"access_token_ttl" jsonschema:"title=MCP OAuth Access Token TTL"`
// RefreshTokenTTL controls builtin-mode refresh token lifetime.
RefreshTokenTTL time.Duration `mapstructure:"refresh_token_ttl" jsonschema:"title=MCP OAuth Refresh Token TTL"`
}
MCPOAuthConfig configures standards-compatible OAuth discovery and token handling for hosted MCP HTTP clients.
type MCPRootProfile ¶ added in v3.18.35
type MCPToolEvent ¶ added in v3.20.72
type MCPToolEvent struct {
SessionID string
Tool string
Arguments map[string]any
IsError bool
DurationMS int64
}
MCPToolEvent is one tool call made over MCP.
It exists so an evaluation harness can grade an agent it does not host. An external agent connects over MCP and does the work itself; what the harness needs is the same account of what was done that its own agent reports, and the server is the only place that account can come from.
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
Get retrieves a cached response Returns (data, isStale, found)
func (*MemoryCache) InvalidateRows ¶ added in v3.2.1
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
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"`
InsertConflictGet string `json:"insert_conflict_get"`
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"`
OpenAPICall string `json:"openapi_call"`
}
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 NamespaceRollup ¶ added in v3.18.5
type NamespaceRollup = corediscovery.NamespaceRollup
type NamespaceRoute ¶ added in v3.18.3
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 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 OperatorSeed ¶ added in v3.20.72
type OperatorSeed struct {
UserID string
// Role is the role seeded watches run under. Watch subscriptions execute
// with the owner's stored role, so this is what decides what a standing
// question can see — keep it least-privilege.
Role string
// ConsoleRole is the role the console adopts, when it differs from Role.
// Reading the control-plane roots the console renders needs wider access
// than running a watch does, so the two are allowed to diverge rather than
// forcing watches to run with console-shaped privileges.
ConsoleRole string
AccountID string
Watches []WatchSeed
// Report receives one line per watch so the caller can render progress in
// its own status stream. It is never called with an error the caller is
// expected to handle: seeding is best-effort by design.
Report func(name, status, message string)
}
OperatorSeed declares the local development operator a zero-configuration project boots as: the owner of everything the project seeds, and the identity the console offers when the browser has none.
type Option ¶
type Option func(*graphjinService) error
func OptionDisableQueryLearning ¶ added in v3.20.5
func OptionDisableQueryLearning() Option
OptionDisableQueryLearning suppresses dev-mode named-query and fragment auto-save for this embedded service instance. Existing saved queries remain discoverable and executable. This is intended for deterministic evaluation and other read-only harnesses whose catalog must not mutate while measured.
func OptionSetAgentClientFactory ¶ added in v3.19.0
func OptionSetAgentClientFactory(factory gjagent.ClientFactory) Option
OptionSetAgentClientFactory injects a server-side agent model client. An injected client is treated exactly like configured provider credentials.
func OptionSetAgentNow ¶ added in v3.20.72
OptionSetAgentNow fixes the clock every server-owned agent entrypoint reads, which is what the agent is told "today" is.
It exists for evaluation and rollout environments, where a run that crosses midnight otherwise asks two different questions of the same frozen data. Production leaves it unset and the agent reads the wall clock.
func OptionSetDB ¶
OptionSetDB sets a new db client. The connection is stored under the DefaultDBName key in the dbs map for backward compatibility.
func OptionSetDatabases ¶ added in v3.18.35
OptionSetDatabases sets named database clients for multi-database embeddings.
func OptionSetHookFunc ¶
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 OptionSetMCPToolRecorder ¶ added in v3.20.72
func OptionSetMCPToolRecorder(recorder func(MCPToolEvent)) Option
OptionSetMCPToolRecorder reports every MCP tool call to the given function.
It is for evaluation, not for production observability: the recorder runs inline with the call, so it must not block. Nil disables recording, which is the default.
func OptionSetNamespace ¶
OptionSetNamespace sets service namespace
func OptionSetOperatorSeed ¶ added in v3.20.72
func OptionSetOperatorSeed(seed OperatorSeed) Option
OptionSetOperatorSeed registers standing watches to create once, after the engine is up and before the watch runner starts. Seeding failures are reported and skipped; they never fail service startup.
func OptionSetRuntimeSchemaDDLDir ¶ added in v3.18.35
OptionSetRuntimeSchemaDDLDir sets where the core stores generated schema-DDL restart snapshots, relative to the service filesystem root.
func OptionSetSemanticEmbeddingClient ¶ added in v3.18.46
func OptionSetSemanticEmbeddingClient(client SemanticEmbeddingClient) Option
OptionSetSemanticEmbeddingClient replaces the Ax embedding adapter. It is primarily intended for deterministic tests and private provider adapters.
func OptionSetZapLogger ¶
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 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
Get retrieves a cached response Returns (data, isStale, found)
func (*RedisCache) InvalidateRows ¶ added in v3.2.1
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
type RelationshipPath ¶ added in v3.18.3
type RelationshipRef ¶ added in v3.18.5
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 SecretsConfig ¶ added in v3.18.35
type SecretsConfig struct {
Keystore KeystoreConfig `mapstructure:"keystore" jsonschema:"title=Encrypted Keystore"`
}
SecretsConfig configures secret storage for write-only config inputs.
type SemanticCatalogSearchConfig ¶ added in v3.18.46
type SemanticCatalogSearchConfig struct {
// Enabled adds Ax-backed semantic recall to the lexical catalog baseline.
Enabled bool `mapstructure:"enabled" jsonschema:"title=Enable Semantic Catalog Search,default=false"`
// Provider is the Ax embedding provider name.
Provider string `mapstructure:"provider" jsonschema:"title=Embedding Provider,default=openai"`
// EmbeddingModel is required when semantic search is enabled and forms part
// of the persisted embedding-space fingerprint.
EmbeddingModel string `mapstructure:"embedding_model" jsonschema:"title=Embedding Model"`
// APIKeyEnv names the environment variable containing the provider key.
APIKeyEnv string `mapstructure:"api_key_env" jsonschema:"title=Embedding API Key Environment Variable,default=OPENAI_API_KEY"`
// BaseURL optionally overrides the provider endpoint and forms part of the
// persisted embedding-space fingerprint.
BaseURL string `mapstructure:"base_url" jsonschema:"title=Embedding Provider Base URL"`
// Dimensions selects tiny (768), small (1536), medium (3072), or the
// provider-native default. Named sizes are validated strictly.
Dimensions string `mapstructure:"dimensions" jsonschema:"title=Embedding Dimensions,default=small,enum=tiny,enum=small,enum=medium,enum=default"`
}
SemanticCatalogSearchConfig configures the service-owned Ax embedding layer.
type SemanticEmbeddingClient ¶ added in v3.18.46
type SemanticEmbeddingClient interface {
Embed(ctx context.Context, texts []string, dimensions *int) ([][]float32, error)
}
SemanticEmbeddingClient is the narrow embedding seam used by semantic catalog indexing. Tests can supply a deterministic fake without any provider calls; production uses the Ax adapter below.
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"`
// Stops the catalog from sampling the small value sets of enum-like columns
// (status, severity, plan, and similar). Those sets let an agent filter on a
// real value instead of inventing one, so leaving this off is recommended;
// set it when even low-cardinality values must not appear in catalog cards.
DisableColumnValueSampling bool `mapstructure:"disable_column_value_sampling" jsonschema:"title=Disable Catalog Column Value Sampling,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. Defaults on in dev and agentic modes, off in prod.
WebUI bool `mapstructure:"web_ui" jsonschema:"title=Enable Web UI,default=false"`
// Evaluation report state directory for the non-production Trainer console.
// Relative paths resolve from config_path. Set to "off" to disable the API.
EvalStateDir string `mapstructure:"eval_state_dir" jsonschema:"title=Evaluation Report State Directory"`
// 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"`
// Server-side GraphJin discovery/answer agent configuration
Agent AgentConfig `mapstructure:"agent" jsonschema:"title=GraphJin Agent Configuration"`
// Local encrypted secrets configuration
Secrets SecretsConfig `mapstructure:"secrets" jsonschema:"title=Secrets"`
// Redis configuration
Redis RedisConfig `mapstructure:"redis" jsonschema:"title=Redis Configuration"`
// Coordinated, filesystem-backed database discovery cache.
DiscoveryCache DiscoveryCacheConfig `mapstructure:"discovery_cache" jsonschema:"title=Discovery Cache Configuration"`
// Catalog retrieval configuration.
CatalogSearch CatalogSearchConfig `mapstructure:"catalog_search" jsonschema:"title=Catalog Search 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
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 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 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 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:
Inlined as base64 into the variable at its declared path (default — Storage is empty):
{ filename, content_type, size, data (base64) }
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 WatchSeed ¶ added in v3.20.72
type WatchSeed struct {
Name string
Description string
Query string
SavedQueryName string
VariablesJSON string
DeliveryJSON string
AbsenceJSON string
EnrichJSON string
}
WatchSeed is one standing question a project boots with. The fields are exactly the gj_watch mutation input, so a seeded watch and a hand-written one are the same object created through the same path.
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.
Source Files
¶
- admin.go
- afero.go
- agent_capability.go
- agent_http.go
- agent_runtime.go
- annotations.go
- api.go
- artifact_overlay.go
- artifacts.go
- auth_login.go
- cache.go
- cache_memory.go
- cache_redis.go
- cache_swr.go
- caller_actions.go
- cassandra.go
- catalog_cache.go
- catalog_column_values.go
- clickhouse.go
- client.go
- codesql.go
- codesql_mutation.go
- config.go
- config_preview.go
- config_schema.go
- console_http.go
- control_plane_graphql.go
- control_store_internal.go
- db.go
- deploy.go
- discovery.go
- discovery_cache.go
- discovery_colstats.go
- discovery_gen.go
- discovery_generations.go
- discovery_indexes.go
- discovery_sample.go
- discovery_schema.go
- discovery_types.go
- eval_reports_http.go
- eval_score_http.go
- exec_error_augment.go
- exec_error_classify.go
- filewatch.go
- fstable.go
- fstable_gcs.go
- fstable_s3.go
- fstable_watch.go
- fuzz.go
- health.go
- http.go
- identity.go
- init.go
- internal_names.go
- iplimiter.go
- managed_artifacts.go
- mcp.go
- mcp_agent.go
- mcp_audit.go
- mcp_capability_profile.go
- mcp_catalog.go
- mcp_config.go
- mcp_config_docs.go
- mcp_cursor.go
- mcp_cursor_cache.go
- mcp_db_guard.go
- mcp_ddl.go
- mcp_discover.go
- mcp_explain.go
- mcp_explore.go
- mcp_fix_query_error.go
- mcp_fragments.go
- mcp_guidance_tools.go
- mcp_health.go
- mcp_insights.go
- mcp_instructions.go
- mcp_js_runtime.go
- mcp_mode_blocks.go
- mcp_next.go
- mcp_next_surface.go
- mcp_oauth.go
- mcp_onboarding.go
- mcp_prompts.go
- mcp_query_patterns.go
- mcp_recorder.go
- mcp_schema.go
- mcp_search.go
- mcp_surface.go
- mcp_syntax.go
- mcp_tools.go
- mcp_watch_resources.go
- mcp_workflow_mgmt.go
- metadata.go
- migrate.go
- nanodb_system.go
- openapi_request_headers.go
- projection_poll.go
- revision_signal.go
- routes.go
- runtime_events.go
- schema_reload.go
- secret_keystore.go
- security_defaults.go
- security_report.go
- semantic_coverage.go
- semantic_documents.go
- semantic_index.go
- semantic_query.go
- serv.go
- source_capabilities.go
- sources.go
- sqllog.go
- sse.go
- system_policy.go
- tasks.go
- tasks_agent.go
- tasks_verify.go
- telemetry.go
- upload.go
- watch_cleanup.go
- watch_coord.go
- watch_delivery.go
- watch_flow.go
- watch_http.go
- watch_review.go
- watch_runner.go
- watch_seed.go
- watches.go
- webui.go
- window.go
- workflow_registry.go
- workflows.go
- ws.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
mcpcompat/mcp
Package mcp provides the small, GraphJin-owned registration surface used by the service.
|
Package mcp provides the small, GraphJin-owned registration surface used by the service. |
|
mcpcompat/server
Package server adapts GraphJin's stable internal MCP registration surface to the official modelcontextprotocol/go-sdk server and transports.
|
Package server adapts GraphJin's stable internal MCP registration surface to the official modelcontextprotocol/go-sdk server and transports. |
|
tools
command
Generates the JSON Schema for the GraphJin service configuration (serv.Config).
|
Generates the JSON Schema for the GraphJin service configuration (serv.Config). |