Documentation
¶
Index ¶
- Constants
- Variables
- type AgentActivateRequest
- type AgentActivateResponse
- type AgentCommand
- type AgentRespondRequest
- type AgentRespondResponse
- type ArrowResultsRequest
- type Bridge
- type CancelQueryRequest
- type CancelQueryResponse
- type ChartConfigHistoryEntry
- type CloseSessionRequest
- type CloseSessionResponse
- type CreateSessionRequest
- type CreateSessionResponse
- type Database
- type DatabasesResponse
- type EditorHistoryEntry
- type ExecuteQueryRequest
- type ExecuteRequest
- type ExecuteSessionQueryRequest
- type GetBootstrapResponse
- type GetStateResponse
- type Handler
- type HandlerConfig
- type HealthResponse
- type InvalidBoolQueryParamError
- type InvalidContentTypeError
- type InvalidJSONBodyError
- type InvalidRunIDError
- type InvalidSessionIDError
- type Middleware
- type RequiredFieldError
- type RequiredQueryParamError
- type ResultsUnavailableError
- type Router
- func (r *Router) DELETE(path string, handler http.HandlerFunc, middleware ...Middleware)
- func (r *Router) GET(path string, handler http.HandlerFunc, middleware ...Middleware)
- func (r *Router) MethodNotAllowed(handler http.HandlerFunc, middleware ...Middleware)
- func (r *Router) NotFound(handler http.HandlerFunc, middleware ...Middleware)
- func (r *Router) PATCH(path string, handler http.HandlerFunc, middleware ...Middleware)
- func (r *Router) POST(path string, handler http.HandlerFunc, middleware ...Middleware)
- func (r *Router) PUT(path string, handler http.HandlerFunc, middleware ...Middleware)
- type Run
- type RunFormatError
- type RunIDConflictError
- type SaveStateRequest
- type Server
- type ServiceRequest
- type Session
- type SessionEventsRequest
- type SessionIDConflictError
- type State
- type Store
- func (s *Store) AcquireSession(sessionID uuid.UUID) (*Session, error)
- func (s *Store) Close()
- func (s *Store) DeleteRun(run *Run)
- func (s *Store) DeleteSession(session *Session)
- func (s *Store) GetRun(runID uuid.UUID) (*Run, error)
- func (s *Store) GetSession(sessionID uuid.UUID) (*Session, error)
- func (s *Store) InsertRun(run *Run) error
- func (s *Store) InsertSession(session *Session) error
- func (s *Store) LoadState() (State, error)
- func (s *Store) ReleaseSession(session *Session)
- func (s *Store) SaveState(state State) error
- func (s *Store) TryCloseSession(ctx context.Context, session *Session)
- func (s *Store) TryDeleteRun(ctx context.Context, run *Run)
- func (s *Store) TryDeleteSession(ctx context.Context, session *Session)
Constants ¶
const SessionOpenTimeout = 10 * time.Second
SessionOpenTimeout is the maximum amount of time that the service will wait while attempting to open a database connection before returning an error.
Variables ¶
var ( // ErrNoActiveClient is returned when a request is attempted but no browser // client is connected to drive it. ErrNoActiveClient = errors.New("no active browser client is connected") // ErrClientDisconnected is returned when the active client disconnects // while a request is in flight. ErrClientDisconnected = errors.New("browser client disconnected") // ErrClientSuperseded is returned when control is taken over by another // client while a request was in flight. ErrClientSuperseded = errors.New("another browser tab took over control") // ErrAgentIdleTimeout is returned when the active client sends no message // (heartbeat or response) within agentIdleTimeout. ErrAgentIdleTimeout = errors.New("timed out waiting for the browser; is the tab still open?") )
Bridge errors surfaced to MCP tools (and ultimately the agent).
Functions ¶
This section is empty.
Types ¶
type AgentActivateRequest ¶ added in v0.24.0
type AgentActivateRequest struct {
ClientID string `json:"clientId"`
}
AgentActivateRequest is the request body of POST /api/agent/activate. A browser tab posts its own client ID to become the active controlling tab (the "take over" action).
func (AgentActivateRequest) Validate ¶ added in v0.24.0
func (r AgentActivateRequest) Validate() error
Validate returns an error if a required field is missing.
type AgentActivateResponse ¶ added in v0.24.0
type AgentActivateResponse struct {
Success bool `json:"success"`
}
AgentActivateResponse is the response body of POST /api/agent/activate.
type AgentCommand ¶ added in v0.24.0
type AgentCommand struct {
ID string `json:"id"`
Type string `json:"type"`
Payload json.RawMessage `json:"payload,omitempty"`
}
AgentCommand is a single command dispatched to the browser to execute (e.g. run a query, reconfigure the chart, read UI state). Payload is an opaque JSON blob whose shape depends on Type; the MCP tools and the web orchestrator agree on it.
type AgentRespondRequest ¶ added in v0.24.0
type AgentRespondRequest struct {
ClientID string `json:"clientId"`
RequestID string `json:"requestId"`
Type agentResponseType `json:"type"`
Data json.RawMessage `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
AgentRespondRequest is the request body of POST /api/agent/respond. The browser posts heartbeats, command results, and errors back over this endpoint, keyed by the originating client and request IDs.
func (AgentRespondRequest) Validate ¶ added in v0.24.0
func (r AgentRespondRequest) Validate() error
Validate returns an error if a required field is missing.
type AgentRespondResponse ¶ added in v0.24.0
type AgentRespondResponse struct {
Success bool `json:"success"`
}
AgentRespondResponse is the response body of POST /api/agent/respond.
type ArrowResultsRequest ¶
type ArrowResultsRequest struct {
ServiceRequest
RunID uuid.UUID `json:"runId"`
}
ArrowResultsRequest is the request body of POST /api/arrowResults.
func (ArrowResultsRequest) Validate ¶
func (r ArrowResultsRequest) Validate() error
Validate returns an error if a required field is missing.
type Bridge ¶ added in v0.24.0
type Bridge struct {
// contains filtered or unexported fields
}
Bridge is the communication channel between MCP tools (server side) and the browser UI (client side). Browser tabs subscribe to a Server-Sent Events stream; MCP tools dispatch commands to the single active client and await a response delivered back over a separate HTTP endpoint.
At most one command is in flight at a time (callers serialize via Request). Exactly one connected client is "active" at any moment; commands are only dispatched to it and responses are only accepted from it.
func (*Bridge) Activate ¶ added in v0.24.0
Activate makes the given client the active one (the "take over" action). Any in-flight request dispatched to the previously-active client is failed. It is a no-op (returning false) if the client ID is unknown.
func (*Bridge) HasActiveClient ¶ added in v0.24.0
HasActiveClient reports whether a client is currently connected and active.
func (*Bridge) Request ¶ added in v0.24.0
func (b *Bridge) Request(ctx context.Context, commandType string, payload any) (json.RawMessage, error)
Request dispatches a command of the given type (with the given JSON- serializable payload) to the active browser client and waits for its response. Calls are serialized: a second Request blocks until the first completes. The request fails if the active client disconnects, another tab takes over, or no message (heartbeat or response) arrives within agentIdleTimeout.
type CancelQueryRequest ¶
type CancelQueryRequest struct {
ServiceRequest
RunID uuid.UUID `json:"runId"`
}
CancelQueryRequest is the request body of POST /api/cancelQuery.
func (CancelQueryRequest) Validate ¶
func (r CancelQueryRequest) Validate() error
Validate returns an error if a required field is missing.
type CancelQueryResponse ¶
type CancelQueryResponse struct {
Success bool `json:"success"`
}
CancelQueryResponse is the response body of the POST /api/cancelQuery endpoint.
type ChartConfigHistoryEntry ¶ added in v0.24.0
ChartConfigHistoryEntry is one entry in the chart config history: the full chart config source and when it was last recorded (epoch milliseconds). The web client owns dedup (identical configs are promoted, not duplicated).
type CloseSessionRequest ¶
type CloseSessionRequest struct {
ServiceRequest
SessionID uuid.UUID `json:"sessionId"`
}
CloseSessionRequest is the request body of POST /api/closeSession.
func (CloseSessionRequest) Validate ¶
func (r CloseSessionRequest) Validate() error
Validate returns an error if a required field is missing.
type CloseSessionResponse ¶
type CloseSessionResponse struct {
Success bool `json:"success"`
}
CloseSessionResponse is the response body of the POST /api/closeSession endpoint.
type CreateSessionRequest ¶
type CreateSessionRequest struct {
ServiceRequest
}
CreateSessionRequest is the request body of POST /api/createSession.
type CreateSessionResponse ¶
CreateSessionResponse is the response body of the POST /api/createSession endpoint.
type Database ¶
type Database struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Type string `json:"type"`
}
Database is a single entry in a DatabasesResponse.
type DatabasesResponse ¶
type DatabasesResponse struct {
Databases []Database `json:"databases"`
}
DatabasesResponse is the response body of the GET /api/databases endpoint.
type EditorHistoryEntry ¶ added in v0.25.0
EditorHistoryEntry is one entry in the editor history: the full editor contents at the time it was recorded and when (epoch milliseconds). The web client owns dedup (identical contents are promoted, not duplicated).
type ExecuteQueryRequest ¶
type ExecuteQueryRequest struct {
ExecuteRequest
}
ExecuteQueryRequest is the request body of POST /api/executeQuery.
type ExecuteRequest ¶
type ExecuteRequest struct {
ServiceRequest
RunID uuid.UUID `json:"runId"`
Query string `json:"query"`
Statements []string `json:"statements"`
}
ExecuteRequest holds the fields common to the executeQuery and executeSessionQuery endpoints. Clients send both a top-level query (legacy) and a statements array (the editor text split by the client's SQL parser); statements is preferred when present.
func (ExecuteRequest) Validate ¶
func (r ExecuteRequest) Validate() error
Validate returns an error if a required field is missing.
type ExecuteSessionQueryRequest ¶
type ExecuteSessionQueryRequest struct {
ExecuteRequest
SessionID uuid.UUID `json:"sessionId"`
}
ExecuteSessionQueryRequest is the request body of POST /api/executeSessionQuery.
func (ExecuteSessionQueryRequest) Validate ¶
func (r ExecuteSessionQueryRequest) Validate() error
Validate returns an error if a required field is missing.
type GetBootstrapResponse ¶
type GetBootstrapResponse struct {
ProjectID string `json:"projectId"`
Version string `json:"version"`
// ReadOnly reflects the read_only config option. When true, queries run by
// this server use an immutable read-only connection, so the UI surfaces a
// read-only indicator to the user.
ReadOnly bool `json:"readOnly"`
// UIQueryHistoryLimit reflects the ui_query_history_limit config option:
// the maximum number of recent query runs (and their results) the UI keeps
// in the in-memory results cache before evicting the oldest.
UIQueryHistoryLimit int `json:"uiQueryHistoryLimit"`
}
GetBootstrapResponse is the response body of the GET /api/bootstrap endpoint.
type GetStateResponse ¶
type GetStateResponse struct {
State
}
GetStateResponse is the response body of the GET /api/state endpoint.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
func NewHandler ¶
func NewHandler(config HandlerConfig) *Handler
func (*Handler) NewSession ¶
NewSession opens new database Session given a DSN. It returns an api.NormalizedError if the database connection could not be established, or if the connection attempt took longer than SessionOpenTimeout.
type HandlerConfig ¶
type HandlerConfig struct {
App *common.App
Store *Store
Logger *slog.Logger
// Bridge is the optional agent communication channel. When non-nil, the
// agent SSE/respond/activate endpoints are served, letting MCP tools drive
// this UI. It is nil for a plain `ghost serve` (no MCP-driven control).
Bridge *Bridge
}
type HealthResponse ¶
type HealthResponse struct {
Success bool `json:"success"`
}
HealthResponse is the response body of the GET /health endpoint.
type InvalidBoolQueryParamError ¶
InvalidBoolQueryParamError is returned when a query param expected to be a boolean cannot be parsed as one.
func (*InvalidBoolQueryParamError) Error ¶
func (e *InvalidBoolQueryParamError) Error() string
type InvalidContentTypeError ¶
type InvalidContentTypeError struct {
Required string
}
func (*InvalidContentTypeError) Error ¶
func (e *InvalidContentTypeError) Error() string
type InvalidJSONBodyError ¶
type InvalidJSONBodyError struct {
Err error
}
func (*InvalidJSONBodyError) Error ¶
func (e *InvalidJSONBodyError) Error() string
type InvalidRunIDError ¶
func (*InvalidRunIDError) Error ¶
func (e *InvalidRunIDError) Error() string
type InvalidSessionIDError ¶
func (*InvalidSessionIDError) Error ¶
func (e *InvalidSessionIDError) Error() string
type RequiredFieldError ¶
type RequiredFieldError struct {
Field string
}
RequiredFieldError is the error type returned when a required request body field is missing.
func (*RequiredFieldError) Error ¶
func (e *RequiredFieldError) Error() string
Error implements the error interface.
type RequiredQueryParamError ¶
type RequiredQueryParamError struct {
ParamName string
}
RequiredQueryParamError is returned when a required query param is missing or empty.
func (*RequiredQueryParamError) Error ¶
func (e *RequiredQueryParamError) Error() string
type ResultsUnavailableError ¶
type ResultsUnavailableError struct {
}
func (*ResultsUnavailableError) Error ¶
func (e *ResultsUnavailableError) Error() string
type Router ¶
type Router struct {
*httprouter.Router
// contains filtered or unexported fields
}
func NewRouter ¶
func NewRouter(middleware ...Middleware) *Router
func (*Router) DELETE ¶
func (r *Router) DELETE(path string, handler http.HandlerFunc, middleware ...Middleware)
func (*Router) GET ¶
func (r *Router) GET(path string, handler http.HandlerFunc, middleware ...Middleware)
func (*Router) MethodNotAllowed ¶
func (r *Router) MethodNotAllowed(handler http.HandlerFunc, middleware ...Middleware)
func (*Router) NotFound ¶
func (r *Router) NotFound(handler http.HandlerFunc, middleware ...Middleware)
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, handler http.HandlerFunc, middleware ...Middleware)
func (*Router) POST ¶
func (r *Router) POST(path string, handler http.HandlerFunc, middleware ...Middleware)
func (*Router) PUT ¶
func (r *Router) PUT(path string, handler http.HandlerFunc, middleware ...Middleware)
type Run ¶
type Run struct {
// Unique identifier for the run.
ID uuid.UUID
// The list of SQL statements that the run is executing. Either this field
// or Query will be present, but not both.
Statements []string
// The text of the SQL query that the run is executing. Either this field
// or Statements will be present, but not both.
Query string
// Destinations and formats to write arrow records to.
Outputs writer.Outputs
// A function which, when called, triggers cancellation of the run.
Cancel context.CancelFunc
}
Run represents an in-progress query. After being created via NewRun, it is passed to Session.Query, which executes the query against the database. All runs are stored in the Store until they complete or are canceled.
func NewRun ¶
NewRun creates a new Run from an ExecuteRequest, configured to stream results as Arrow over the results endpoint. It returns the fully initialized run, along with a context that is canceled when the run is canceled (via Run.Cancel or Run.Close). Runs do not time out.
func (*Run) Close ¶
func (r *Run) Close()
Close cancels the run if it's still in progress, and cleans up associated resources.
func (*Run) FinalQuery ¶
FinalQuery returns the run's query (or final statement in the statement list), which should be passed to driver.Driver.Query to execute the query. If there are additional statements in the statement list, they should be executed via Run.LeadingStatements before this query is executed.
func (*Run) LeadingStatements ¶
LeadingStatements returns all of the statements in the run's statement list except the last (which is returned from Run.FinalQuery instead). Returns an empty list if the statement list is empty (because the Query field is being used instead) or only contains a single statement. The intention is for these statements to be executed sequentially via driver.Driver.Query, but without returning any results, before the run's final query is executed.
type RunFormatError ¶
type RunFormatError struct {
RunID uuid.UUID
Format api.OutputFormat
}
func (*RunFormatError) Error ¶
func (e *RunFormatError) Error() string
type RunIDConflictError ¶
func (*RunIDConflictError) Error ¶
func (e *RunIDConflictError) Error() string
type SaveStateRequest ¶
type SaveStateRequest struct {
State
}
SaveStateRequest is the request body of the PUT /api/state endpoint.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a wrapper around http.Server that encapsulates some standard configuration and boilerplate for starting and stopping the server.
func NewServer ¶
NewServer creates a new instance of Server. The host may be empty to bind all interfaces, though callers should generally pass a loopback address (e.g. "localhost"). To start the server, call Server.Start.
func (*Server) Close ¶
Close immediately shuts down the HTTP server started by Server.Start, closing all active connections without waiting for in-flight requests to complete. If Server.Start has not been called successfully, or if the HTTP server has already been closed, Close is a no-op. Note that it is not safe to call this method concurrently with itself or Server.Start.
func (*Server) Errors ¶
Errors returns a channel on which server errors are returned. Returns a nil channel if the server is not running (e.g. Server.Start has not yet been called or if Server.Close has already been called).
func (*Server) Start ¶
Start starts listening for incoming HTTP requests on the configured host and port. If the port is 0, an ephemeral port is chosen, and the stored port is subsequently updated to the chosen port (useful in automated tests). Note that the context argument only controls the cancellation of this function itself - once started, the server can only be stopped by calling Server.Close.
func (*Server) URL ¶
URL returns the http URL clients should connect to (with the OS-chosen port if the configured port was 0). Only accurate after Server.Start has been called.
type ServiceRequest ¶
type ServiceRequest struct {
ProjectID string `json:"projectId"`
ServiceID string `json:"serviceId"`
}
ServiceRequest holds the fields common to every query endpoint: the project and database ("service") the request targets.
func (ServiceRequest) Validate ¶
func (r ServiceRequest) Validate() error
Validate returns an error if a required field is missing.
type Session ¶
type Session struct {
// Unique identifier for the session, which is automatically generated when
// the session is created.
ID uuid.UUID
// contains filtered or unexported fields
}
Session represents a user's database connection. Ephemeral sessions are closed automatically after a run, but long-lived sessions are stored in the Store until explicitly removed, or until the session times out.
func (*Session) Broken ¶
Broken reports whether the underlying database connection has been broken, at which point the session can no longer be used. This is set to true after a query using the session returns a fatal error, or if a database ping fails.
func (*Session) Close ¶
Close attempts to close the underlying database connection. It will wait for any in-progress queries to finish before closing the connection and returning.
func (*Session) Events ¶
Events returns a channel on which session status events are returned. Pings the database periodically to check the health of the connection and generate status events. The channel is closed when the context is canceled, the session is closed, or a connection ping fails. In the future, this could return other types of session events as well (e.g. NOTICE or LISTEN/NOTIFY messages).
type SessionEventsRequest ¶
type SessionEventsRequest struct {
ServiceRequest
SessionID uuid.UUID `json:"sessionId"`
}
SessionEventsRequest is the request body of POST /api/sessionEvents.
func (SessionEventsRequest) Validate ¶
func (r SessionEventsRequest) Validate() error
Validate returns an error if a required field is missing.
type SessionIDConflictError ¶
func (*SessionIDConflictError) Error ¶
func (e *SessionIDConflictError) Error() string
type State ¶
type State struct {
SelectedDatabaseID string `json:"selectedDatabaseId,omitempty"`
EditorHeight int `json:"editorHeight,omitempty"`
EditorSQL string `json:"editorSql,omitempty"`
SchemaPaneWidth int `json:"schemaPaneWidth,omitempty"`
// SchemaPaneVisible is a pointer so that an explicit false (pane hidden) is
// persisted; the web client defaults a missing value to true.
SchemaPaneVisible *bool `json:"schemaPaneVisible,omitempty"`
SchemaTreeExpanded map[string][]string `json:"schemaTreeExpanded,omitempty"`
// ShowInternalObjects controls whether the schema browser includes system
// schemas and extension-owned objects. Defaults to false (a plain bool, not
// a pointer, since the web client also defaults a missing value to false).
ShowInternalObjects bool `json:"showInternalObjects,omitempty"`
// ResultView selects what's shown below the query editor: the results table,
// the rendered chart, or the chart config editor.
ResultView string `json:"resultView,omitempty"`
// ChartConfig is the user's chart config source (the body of the chart
// function), persisted so it survives reloads.
ChartConfig string `json:"chartConfig,omitempty"`
// ChartEditorWidth is the width (px) of the chart config editor pane in the
// editor/preview split.
ChartEditorWidth int `json:"chartEditorWidth,omitempty"`
// EditorHistory is the list of past editor drafts (full editor contents
// recorded as the user edits), newest first. Each PUT replaces it wholesale;
// the web client owns dedup and capping. (Query history — distinct runs and
// their results — is kept in-memory only by the web client and never
// persisted here.)
EditorHistory []EditorHistoryEntry `json:"editorHistory,omitempty"`
// ChartConfigHistory is the list of previously used chart configs, newest
// first. Like EditorHistory, each PUT replaces it wholesale; the web client
// owns dedup and capping.
ChartConfigHistory []ChartConfigHistoryEntry `json:"chartConfigHistory,omitempty"`
}
State is the persisted UI state for `ghost serve`, shared by the GET and PUT /api/state endpoints. A PUT replaces the stored state wholesale, so clients send the full snapshot; omitempty just keeps zero-valued fields out of the JSON.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store maintains in-memory lookups of all current sessions and in-progress runs (keyed by ID), and persists the serve UI state to disk.
func NewStore ¶
NewStore initializes and returns a new Store instance. configDir is the directory in which the serve UI state file is persisted.
func (*Store) AcquireSession ¶
AcquireSession retrieves a session from the store and returns it. It also pauses the session timeout, if active (i.e. if it was not already paused by another acquisition). ReleaseSession should be called when the session is done being used to reset the timeout.
func (*Store) Close ¶
func (s *Store) Close()
Close attempts to close all outstanding database sessions and remove them from the store. It waits for any in-progress queries to complete before returning. Errors closing or removing database connections are logged.
func (*Store) DeleteSession ¶
func (*Store) GetSession ¶
GetSession retrieves a session from the store and returns it. It does not pause or extend the session timeout. If the session is being retrieved in order to be used by an end-user (e.g. in order to run a query or listen for session status events), Store.AcquireSession should be used instead.
func (*Store) InsertSession ¶
func (*Store) LoadState ¶
LoadState reads the persisted serve UI state from the store's state file. A missing file is not an error - it yields a zero State.
func (*Store) ReleaseSession ¶
ReleaseSession resets the session timeout that was paused by a call to Store.AcquireSession, if there are no other callers still using the session. It should always be called when a session obtained via that method is done being used. Failure to call it could create a leaked session that is never closed.
func (*Store) SaveState ¶
SaveState persists the serve UI state to the store's state file. Writes are atomic (temp file + rename) and serialized via stateLock so concurrent PUTs can't interleave.