cmd/- Binary entry points. Containsghost/main.go(the main CLI binary, which sets up context/signal handling and delegates to the internal command infrastructure),npm-publisher/(a CI tool that generates and publishes npm packages for each platform),generate-docs/(generates Markdown CLI reference docs todocs/cli/), andgenerate-tutorial-docs/(renders every tutorial in theallTutorials()registry todocs/tutorials/, sharing source-of-truth step data with the liveghost tutorialcommand).internal/- All core application logic (non-public Go packages).internal/tutorial/- Data definitions for Ghost's guided tutorials. EachTutorialis a struct bundlingFilename, narrative (Title/Callout/Intro), an ordered[]Step, and an optionalDeleteStep. Blocks carry CLI args, prose, expected output (markdown-only), and aTargetenum that scopes them to CLI runs, doc renders, or both.All()is the registry imported by both the live CLI command and thegenerate-tutorial-docsbinary.internal/cmd/- Cobra command implementations for all CLI commands (init, tutorial, create, fork, list, delete, pause, resume, connect, psql, sql, schema, logs, password, pricing, rename, status, id, feedback, api-key, login, logout, config, mcp, serve, version, upgrade, completion, payment, space, member, invite). Each command lives in its own file, named to match the command in snake_case (e.g.ghost payment listβpayment_list.go). Helper files likecompletion.goanderrors.gocontain shared utilities. Commands that are not yet ready for public release can be gated behind theGHOST_EXPERIMENTALenv var (seeinternal/common/app.go'sApp.Experimentalfield).internal/api/- API client layer. Includes an OpenAPI-generated REST client (client.go,types.go), shared HTTP client singleton, and request/response types. Do not editclient.goortypes.goby hand β they are generated fromopenapi.yaml(see Code Generation). Themock/subdirectory contains a generated mock ofClientWithResponsesInterfacefor use in tests.internal/config/- Configuration management. Handles config file loading (via Viper), credential storage (keyring with file fallback), and version checking.internal/common/- Shared business logic used across commands and MCP tools. Includes API client initialization, database connection/schema/query utilities, error handling with exit codes, and version update checks.internal/mcp/- Model Context Protocol (MCP) server. Exposes Ghost database operations as MCP tools for AI/LLM integration, plus a documentation search proxy. Each MCP tool lives in its own file, named to match the tool (e.g.ghost_usageβusage.go). Helper files likeutil.go,errors.go, andproxy.gocontain shared utilities. In local (stdio) mode the server can also drive a live web UI for visualization via the browser controller (browser.go) and theghost_visualize(visualize.go) andghost_ui_state(ui_state.go) tools (see Web UI & MCP Agent Bridge).internal/mcp/function/- Custom MCP function tools: Postgres functions marked with an@mcpcomment become typed MCP tools, introspected straight from the database catalog. Contains the pg_proc/pg_type introspection (introspect.go,types.go), JSON Schema generation, call construction, and execution (tools.go,scan.go), and theManager(manager.go, which also handles tool-name normalization/deduplication) that registers generated tools on the MCP server and backs theghost_mcp_tool_refreshmanagement tool ininternal/mcp. See Custom MCP Function Tools below.internal/serve/- Local web UI forghost serve(and the MCP server's in-process visualization UI). Embeds a Vite/React SPA (fromweb/dist) via//go:embed(assets.go) and runs a small in-process HTTP server (server.go). Serves the support endpoints the UI needs β/api/bootstrap(config dump),/api/databases(read-only database list),/api/state(GET/PUT of persisted UI state),/health, and the SPA asset handler β plus the query endpoints the SQL query client calls:/api/createSession,/api/sessionEvents,/api/closeSession,/api/executeQuery,/api/executeSessionQuery,/api/arrowResults,/api/cancelQuery. Queries run in-process: each request resolves the target database's connection (via the API client + stored password) into a DSN, opens a Postgres session (session.go,driver/), executes the query, and streams results as newline-delimited JSON status plus an Apache Arrow IPC stream (writer/). The DSN honors theread_onlyconfig option (the immutable read-only connection GUC), so queries run through this server β including MCP-driven visualizations β can't bypass read-only mode;/api/bootstrapreportsreadOnlyso the UI can surface a read-only indicator. Sessions and in-progress runs are tracked in an in-memoryStore(store.go). Request/response types live inapi/. The agent channel that lets MCP tools drive the UI (agent.go,agent_handler.go) is described in Web UI & MCP Agent Bridge.internal/analytics/- Analytics event tracking with sensitive data redaction for flags, positional arguments, and MCP inputs.internal/log/- Smallsloghelper package for the long-running backend commands (ghost serve,ghost mcp):log.Newbuilds the stderr logger, andNewContext/FromContextthread a request-scoped logger through the context.ErrLevelpicks debug vs error level based on context cancellation.internal/util/- General utilities: type conversion, duration formatting, path helpers, context-aware stdin reading, JSON/YAML serialization, and terminal detection.
docs/- Documentation.docs/cli/contains generated Markdown CLI reference docs (produced bycmd/generate-docs).web/- Vite + React workspace for theghost servebrowser UI. Built viascripts/build-web.sh(which uses the self-bootstrappingweb/bunwrapper) intoweb/dist/, then synced intointernal/serve/web/for the Go binary's//go:embeddirective. Uses React 18 (the widget callsfindDOMNodewhich was removed in React 19), Tailwind v3 (matches the widget's pinned version), TanStack Query for/api/databases//api/bootstrappolling, andvite-plugin-node-polyfillsfor the widget's Buffer/crypto/process/stream shims (same list web-cloud uses). The widget's worker + wasm sidecars are emitted intoassets/via a custom Vite plugin (ported from web-cloud) because Vite's static analysis misses thenew URL(<variable>, import.meta.url)references inside the widget's worker chunk. Thesrc/agent/MCP integration is described in Web UI & MCP Agent Bridge.scripts/- Build and installation scripts (install.sh, install.ps1, completions generation).openapi.yaml- OpenAPI spec used to generate the API client. Should be kept in sync with the canonical spec in theghost-apirepo (see Code Generation)..github/- GitHub Actions CI/CD workflows for testing and releases.
In local (stdio) mode, the MCP server can drive the live ghost serve web UI so an agent's queries and charts appear in a browser a human can watch. This spans three packages β internal/mcp/ (server side), internal/serve/ (the bridge + HTTP endpoints), and web/src/agent/ (the browser orchestrator).
Lazy startup (internal/mcp/browser.go). The browser controller lazily starts an in-process ghost serve server (loopback, ephemeral port) and opens a browser on first use; it's torn down on MCP shutdown. The browser-facing tools are gated to local mode (NewServerWithOptions with Options{Local: true}), since opening a browser only makes sense locally. The Go command/response shapes live in browser_types.go, kept in sync with web/src/agent/types.ts.
Tools. Two browser-backed tools dispatch commands to the browser over the agent bridge: ghost_visualize (visualize.go) runs a SQL query and/or (re-)renders a chart in the live UI, returning the result rows and a chart image; ghost_ui_state (ui_state.go) reads the current UI state. They're registered only in local mode, so the always-available ghost_sql stays a plain server-side query tool (no visualization surface leaks into remote/HTTP mode).
The agent bridge (internal/serve/agent.go, agent_handler.go). When the serve handler is constructed with a Bridge, it serves the agent channel that lets MCP tools control the UI:
/api/agent/eventsβ an SSE stream the browser subscribes to, receiving active-tab status events and dispatched commands./api/agent/respondβ the browser posts heartbeats, results, and errors keyed by request ID./api/agent/activateβ a tab claims active control ("take over").
The bridge tracks all connected tabs with exactly one active: the first tab to connect is active, the incumbent stays active when new tabs connect (they come up inactive), and on disconnect the most-recently-connected tab is promoted. A single command is in flight at a time; a request fails if the active client disconnects, another tab takes over, or no message arrives within 60s.
Browser orchestrator (web/src/agent/). useAgentBridge subscribes to the /api/agent/events SSE stream at the app level (so it survives database switches), dispatching commands (dispatch.ts) that drive the live store β selecting a database, setting editor SQL, running the query via the widget's imperative apiRef, and rendering a chart screenshot off-screen with ECharts getDataURL (screenshot.ts). It also collects chart-config type/syntax diagnostics headlessly via Monaco's TS worker (diagnostics.ts, reusing the editor's configureMonacoForCharts types) so the agent gets the same red-squiggle feedback a human sees β these surface as chart_diagnostics even when the chart renders (many type errors don't throw at runtime). Because QueryPanel remounts per database, it registers an Executor (its apiRef + results-cache client) into a module-level registry (executor.ts) that the app-level dispatcher awaits. The active-tab status is shown by AgentStatusBanner with a "take over" button.
Read-only enforcement. Visualized queries run in-process through the serve handler, whose DSN honors the read_only config option (the immutable read-only connection GUC), so MCP-driven visualizations can't bypass read-only mode. /api/bootstrap reports readOnly so the UI can surface a read-only indicator.
After editing Go code, run ./check from the repo root. It runs go install, go fmt, go mod tidy, go fix, go vet, staticcheck, and go test in one shot.
Every Ghost database can define custom MCP tools by marking Postgres functions with an @mcp comment β the first line of the COMMENT ON FUNCTION text is @mcp, and the remaining lines become the tool's description. Because the definition lives in the database itself, tools are shared across the space and travel with forks and shares.
Key mechanics (see internal/mcp/function):
- Catalog introspection: a tool's input/output schema is derived entirely from the Postgres catalog (
pg_proc/pg_type) β argument names, types, defaults, nullability, return shape, enum values, and volatility. No SQL parsing is involved. - Skipped functions: functions that can't be cleanly represented as a tool (e.g. procedures, aggregate/window functions, polymorphic or
VARIADIC "any"arguments) are skipped with a logged warning rather than failing, so one exotic function never takes down the rest of the tool surface. - VARIADIC arguments: a
VARIADICargument is exposed as an array parameter and passed through with theVARIADICkeyword. Because PostgreSQL forbids omitting arguments under named notation for a variadic call, a variadic function's tool is always called positionally (omitted defaults must be trailing). - Overloaded functions: same-named
@mcpfunctions each become their own tool, distinguished by a de-duplication suffix. - Tool naming: a tool's name joins the normalized database name and function name with
__(billing__get_user), truncating and de-duplicating as needed. The function's own Postgres schema plays no part in the name. - Two serving modes: an authoring mode used by the main
ghost mcpserver, which exposes every database's function tools alongside the standard Ghost tools and management tooling; and a stripped consumer mode (ghost mcp start --serve <database_ref>) that exposes only one database's generated tools, unprefixed, with no other Ghost tools. function_toolsconfig option: the publicfunction_toolsoption (defaulttrue) gates whether the normal MCP server exposes the function-tool feature. Whenfalse,ghost mcp start(without--serve) registers no function-tool manager, generated tools, orghost_mcp_tool_refresh, andmcp list/getand shell completion likewise omit them. Two things intentionally bypass it: the--serveconsumer mode always serves the named database's tools (it's an explicit flag with no other purpose), and the--function-toolsflag onmcp list/getalways forces full enablement (flags take precedence over config).- Refresh: function tools change via DDL, not management tools, so
ghost_mcp_tool_refreshre-introspects a database on demand and swaps its registered tools; otherwise changes are picked up on the next server start. - Annotations: the read-only hint comes from the function's own volatility declaration (
IMMUTABLE/STABLE= read-only). - Analytics: generated tool calls are tracked under the single event
Call function MCP toolwith the tool name as a property, never one event per user-defined tool name. - Read-only: generated function tools deliberately ignore the
read_onlyconfig option (marking a function@mcpis an intentional act; the volatility-derived annotations tell clients which tools write).
CLI command tests live in internal/cmd/ alongside the command files (e.g. list_test.go tests list.go). Shared test infrastructure lives in main_test.go.
Tests execute commands through Cobra's Execute() with a mock API client injected via App.SetClientFactory. The runCommand helper in main_test.go handles all the wiring: it builds the root command, injects the mock, sets up a temp config directory, disables analytics/version checks, stubs common.OpenBrowser (to prevent real browser opens), captures stdout/stderr, and returns the result.
The mock is generated by mockgen from the ClientWithResponsesInterface in internal/api/client.go. The generated mock lives at internal/api/mock/mock_client.go and is regenerated by go generate ./.... All production code uses api.ClientWithResponsesInterface (not the concrete *api.ClientWithResponses) so that the mock can be substituted.
- One
Test<Command>function per command file, using table-driven subtests. Test files must be 1:1 with source files (e.g.config_set.goβconfig_set_test.go). - Use the shared
cmdTeststruct for test cases andrunCmdTests(t, tests)to execute them. These are defined inmain_test.goand handle the standard assertion pattern (checkwantErr, thenwantStdout, thenwantStderr). - Cover all code paths: success with each output format (text, JSON, YAML), not-logged-in, API errors, network errors, nil response bodies, flag variations, and aliases.
- Order test cases to follow the code execution flow of the function under test. Error paths that occur early in the function (e.g. auth failure, network error, bad status code, nil body) should come before success-path tests. For commands with multi-step flows (e.g. fetch then delete), error paths on the second step should come before success-path tests. This makes the test table read like a walkthrough of the function's logic.
- Use
withClientErrorto simulate authentication failures,withStdinfor commands that read from stdin,withEnvfor environment variable overrides, andwithOpenBrowserto override the browser stub (e.g. to simulate a successful browser open). - Extract helper functions for mock setup that is repeated across test cases with minor variations. The helper should accept the varying parameter. For example, if several test cases mock
ForkDatabaseWithResponsewith different fork names, create asetupFork(name string)helper rather than inlining the full mock setup in each case.
Use exact output matching via assertOutput, which uses cmp.Diff for clear diffs on failure. Do not use substring matching β it's too weak to catch formatting regressions. Use backtick strings for multi-line expected output. Trailing whitespace caveat: The Write tool strips trailing spaces from lines, but some expected output (e.g. table-rendered text) has significant trailing whitespace. After writing or editing test files with backtick strings that need trailing spaces, use sed to add them back (e.g. sed -i '48s/SIZE$/SIZE /' file_test.go).
Set up mock expectations using gomock's EXPECT() API. Use validCtx for the context parameter. Return the appropriate response struct with HTTPResponse set to httpResponse(statusCode) and the relevant JSON200/JSON201/JSONDefault field populated. For network errors, return (nil, error).
Validate all parameters passed to mock expectations β do not use gomock.Any() as a shortcut when the expected value is known. For context.Context parameters, use validCtx (defined in main_test.go) which verifies the context is non-nil. For request body parameters (CreateDatabaseRequest, ForkDatabaseRequest, etc.), always specify the exact expected struct. If the parameter value is truly non-deterministic (e.g. a randomly generated password with --generate), gomock.Any() is acceptable β add a comment explaining why.
- API-only commands (list, create, delete, fork, resume, rename, logs, status, etc.) β fully testable with mock.
- Login command β testable using a fake
httptest.Serverfor the OAuth token exchange,withOpenBrowserto simulate the browser callback, andwithNewGhostClientto inject a mock for post-login API calls. Seelogin_test.gofor the pattern. - Database-connecting commands (sql, schema, psql) β test error paths only (auth errors, DB not ready, missing password). Success paths require a real database.
- Config commands β testable without a mock (pass
nilforsetupMock).
When the OpenAPI spec changes and the client is regenerated, the mock must also be regenerated. Running go generate ./... handles both. If the mock is stale, go vet will report that the mock doesn't implement the interface.
The API client and types in internal/api/ are generated from openapi.yaml using oapi-codegen. The mock client in internal/api/mock/ is generated by mockgen. Never edit internal/api/client.go, internal/api/types.go, or internal/api/mock/mock_client.go by hand. To regenerate after editing the OpenAPI spec:
go generate ./...This regenerates the types, client, and mock in the correct order (the //go:generate directives in generate.go are ordered so the mock is always built from the freshly generated client).
The typical workflow for API changes is:
- Edit the canonical
openapi.yamlin theghost-apirepo first. - Copy the updated spec into this repo's root
openapi.yaml. - Run
go generate ./...to regenerate the client, types, and mock.
Database-scoped API endpoints accept either an ID or a name, so the path parameter is database_ref (generated as api.DatabaseRef). Use databaseRef for variables holding user input that could be either form; reserve databaseID for values resolved from database.Id on an API response.
Ghost and the Ghost API are a distinct layer from the underlying Tiger Cloud platform that hosts the databases β don't conflate them. What that platform calls a "project", Ghost-facing code calls a "space" (so use spaceID, not projectID). Go identifiers have been renamed to match (e.g. config.Credentials.SpaceID); the old name survives only as legacy project_id/projectId wire keys kept for backwards compatibility β in credential storage, analytics properties, and the local serve UI (internal/serve/handler.go, whose request structs keep the ProjectID field to match its projectId JSON key).
All cobra commands must:
- Set
SilenceUsage: true - Set
ValidArgsFunctionorValidArgsfor shell completions. UseValidArgsFunctionfor dynamic completions (e.g. database IDs) andValidArgsfor static lists. Usecobra.NoFileCompletionsif no completions are needed. The important thing is that one of these is always set. Completion functions live ininternal/cmd/completion.go; any that need the config or API client must be wrapped withwithAppLoad, since theAppis not loaded automatically for completion requests. - Use
RunE(notRun) for error handling. This also matters because onlyRunEcommands are wrapped with the shared per-command logic (app loading, color configuration, version check, analytics) β seewrapCommandsinroot.go. - Use
cmd.Print*functions for output (notfmt.Print*orfmt.Fprint*) - Use
cmd.InOrStdin(),cmd.OutOrStdout(),cmd.ErrOrStderr()for any direct references to stdin/stdout/stderr (do not use os.Stdin/os.Stdout/os.Stderr directly)
Consider adding common aliases for commands (e.g. ls for list, rm for delete) to match user expectations from other CLI tools.
Commands, aliases, and flags are matched case-insensitively (configured in root.go). Always declare them in lowercase β that's the canonical form. Two names that differ only in case are a collision and must be avoided.
The slog logger (constructed via log.New in internal/log) is reserved for long-running backend processes β the MCP server (ghost mcp) and the local web server (ghost serve) β since those are the only contexts where the CLI needs structured logging. Normal CLI commands should never emit log output β it looks bad and interferes with the user-facing output.
CLI commands should write their "primary output" (i.e. the "result" of the command) to stdout (cmd.Print*) by default. This is true whether the output is structured (e.g. an ASCII table, JSON, or YAML), or simple text indicating what happened. On the other hand, the following should go to stderr (cmd.PrintErr*):
- Errors and warnings β e.g.
cmd.PrintErrf("Warning: ..."). - Interactive terminal UI β confirmation prompts (
[y/N]), password prompts, stdin-reading prompts (Enter your query (press Ctrl+D when done):), and live-updating elements like spinners and progress bars. These must go to stderr so they remain visible when stdout is redirected and don't pollute piped output. - Anything that isn't the data payload itself. When a command writes structured output (an ASCII table, JSON, YAML, or data that a user might pipe/redirect), any informational or progress messages must go to stderr to avoid polluting the data stream.
In the text-output path (the default, when --json/--yaml are not used), the entire output is considered "primary output" and goes to stdout. For example, ghost resume prints "Resuming 'mydb'...\nConnection: postgres://..." β even though "Resuming..." looks like a progress message, it's the primary output of the command and belongs on stdout. There's no need to split informational text from data in this path.
Use the lipgloss package (charm.land/lipgloss/v2) for colored/styled terminal output. The --color config option globally enables or disables color by configuring the command's stdout/stderr writers in root.go to strip ANSI sequences when color is off. For this to work, all output must go through the command's writers (cmd.Print*, cmd.OutOrStdout(), cmd.ErrOrStderr()) β never write directly to os.Stdout or os.Stderr.
TermWriter gotcha: The command's stdout/stderr writers are wrapped in util.TermWriter, which implements io.Writer but is not an *os.File. This means cmd.OutOrStdout() and cmd.ErrOrStderr() cannot be used where an *os.File is required β for example, passing them to exec.Cmd.Stdout/Stderr causes os/exec to create a pipe instead of passing the file descriptor directly, which breaks TTY detection in child processes (see psql.go for a concrete example). Use util.TryUnwrapFile() to extract the underlying *os.File when needed. Note that this bypasses color stripping, which is acceptable when the caller (e.g. a child process) manages its own terminal output.
Use BubbleTea (charm.land/bubbletea/v2) for interactive terminal menus, prompts, spinners, and progress indicators. When creating a tea.NewProgram, always pass:
tea.WithInput(cmd.InOrStdin())β always, even for write-only TUIs like spinners. On startup, BubbleTea enables the Kitty keyboard protocol, which modern terminals (Ghostty, Kitty, WezTerm) support and often have on by default. With it enabled, Ctrl+C is delivered as an escape sequence on stdin rather than as a SIGINT. If you passnil, that sequence has nowhere to go and Ctrl+C silently does nothing. Always plumb stdin and handletea.KeyPressMsgfor"ctrl+c"in your model'sUpdatemethod. For write-only programs (spinners, progress indicators), translate the keypress into acontext.CancelFunccall so any background goroutines unwind cleanly (seeinternal/common/wait.gofor the pattern).tea.WithOutput(cmd.OutOrStdout())(or the appropriate writer) β so that color stripping applies.tea.WithoutSignalHandler()β opt out of BubbleTea's default SIGINT/SIGTERM handler. Ctrl+C is already handled as a key press (above), and out-of-band signals are caught by the handler installed inmain.go, which cancels the command context. Letting BubbleTea also install a handler creates a double-handler race for the same signals.tea.WithContext(cmd.Context())β wires the parent context into BubbleTea so external cancellation (e.g. SIGTERM caught bymain.go) causes the program to exit. When the context is canceled,program.Run()returns an error wrappingtea.ErrProgramKilledand the underlying context error. Exception: if your model already has its own goroutine watchingctx.Done()and reporting cancellation back as atea.Msg(e.g.internal/common/wait.go), passingWithContextis redundant and racy β pick one mechanism.
Gate every BubbleTea program on util.IsTerminal(cmd.InOrStdin()) && util.IsTerminal(<output stream>). Both must be TTYs: stdin so the terminal can be put in raw mode for key input, output so the rendered UI is actually visible. If either is redirected (e.g. piped or sent to a file), fall back to a non-interactive code path.
Configuration is managed via Viper. The config file is stored in the config directory (default ~/.config/ghost/). There are two categories of config values:
- Public: User-facing options (e.g.
analytics,color,function_tools,read_only,version_check). Shown byghost configand included in shell completion forghost config set. - Private/Internal: Internal settings (e.g.
api_url,docs_mcp_url,releases_url). Hidden fromghost configby default (use--allto see them) and not included in shell completions, but still settable viaghost config set.
Many public config options have corresponding global CLI flags. All config values can be provided as GHOST_* environment variables (e.g. GHOST_COLOR=false). Precedence is: flags > env vars > config file > defaults.
The config directory can be overridden via --config-dir flag or GHOST_CONFIG_DIR env var. This controls where the config file (and credentials file, if the system keyring is unavailable or disabled) are stored. Note that the system keyring is global, so overriding the config directory does not isolate credentials by itself. To fully isolate both config and credentials in a single directory, disable the keyring via GHOST_KEYRING=false or ghost config set keyring false β credentials are then stored in a fallback file inside the config directory. This is useful for manual testing, and for maintaining a fully scoped CLI per environment: a dedicated config directory with keyring: false and api_url pointed at another environment (e.g. dev) keeps that environment's config and credentials entirely separate from the default login.
GHOST_CONFIG_DIRβ Override the config directory (default~/.config/ghost/).GHOST_EXPERIMENTALβ Set totrueto enable experimental CLI commands and features that haven't been publicly released yet.GHOST_*β Any public or private config value can be set viaGHOST_<KEY>env vars (e.g.GHOST_COLOR,GHOST_API_URL).
All CLI commands and MCP tool handlers receive a *common.App which holds the config and API client. The App is loaded once at the start of each command's wrapped RunE (see wrapCommands in root.go). Cobra's built-in commands (help, completion, __complete) are added after wrapCommands runs and so never load the App β this keeps them from touching the config file, the system keyring, or the network. Completion functions that need the config or API client must be wrapped with withAppLoad (see internal/cmd/completion.go). MCP tool handlers call s.app.Load(ctx) on each invocation to refresh credentials. The App's accessor methods panic if it has never been loaded β that's a programmer error, so make sure any new code path that reads the App arranges for Load to be called first.
Use the appropriate getter depending on what you need:
// Most commands: get the API client and project ID
client, projectID, err := app.GetClient()
// When you also need config (e.g. for connection strings)
cfg, client, projectID, err := app.GetAll()
// When you only need config (e.g. config commands, logout)
cfg := app.GetConfig()
// Best-effort access (doesn't error if client is unavailable).
// Only for rare cases where the API call is optional (e.g. analytics tracking).
cfg, client, projectID := app.TryGetAll()- Handle ALL errors (even if just by outputting a warning to the console). Never ignore errors or assign them to
_ - Return errors from
RunE; don't callos.Exit()directly - Use
common.ExitWithErrorFromStatusCode()for API errors - Use
common.ExitWithCode()for specific exit codes (defined ininternal/common/errors.go) - Error messages should start with a lowercase letter
- Use
errors.New()for static error strings; only usefmt.Errorf()when you need format verbs (%w,%v,%s, etc.) - Handle
Close()errors (and other deferred cleanup errors) explicitly. Usedefer x.Close()for best-effort cleanup on error/panic paths, and also callx.Close()explicitly at the end of the happy path and return its error. That way, if an earlier error occurred it's returned first; if the only error is from close, it still gets returned. This relies onClose()being idempotent, which is typical.
Commands and MCP tools that need a database password should call common.GetPassword and handle errors properly rather than silently falling back to an empty password. Check for common.ErrPasswordNotFound to provide actionable guidance:
- CLI commands: Recommend
ghost password <id>to reset the password, or adding the entry to~/.pgpassmanually. - MCP tools: Recommend
ghost_passwordto reset the password, or adding the entry to~/.pgpassmanually.
Commands that only display connection strings (e.g. ghost connect) can treat missing passwords as non-fatal warnings since the user may not need the password in the output.
Any CLI command or MCP tool that requires the database to be up and running must call common.CheckReady(database) before proceeding. This returns common.ErrPaused if the database is paused/pausing, or common.ErrNotReady if it is queued, configuring, or resuming. This applies to operations that connect to the database (sql, schema, psql), fork it, or change server-side settings like the password.
Use the handleDatabaseError helpers in internal/cmd/errors.go and internal/mcp/errors.go to translate these errors into user-friendly messages. These helpers also handle common.ErrPasswordNotFound.
Operations that only call the Ghost API (create, delete, list, pause, resume, logs, connect) do not need this check.
Commands with structured output should support --json and --yaml flags, made mutually exclusive:
cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
cmd.Flags().BoolVar(&yamlOutput, "yaml", false, "Output in YAML format")
cmd.MarkFlagsMutuallyExclusive("json", "yaml")Use util.SerializeToJSON(cmd.OutOrStdout(), output) and util.SerializeToYAML(cmd.OutOrStdout(), output) for serialization, with a default text output path (typically a table for lists or key/value output, or cmd.Printf for single items).
For the text output path, use common.NewTable(w, opts...) (in internal/common/table.go) to construct tables β both for lists (with a Header(...) row) and for key/value output (rows only, no header). It returns a *tablewriter.Table preconfigured with Ghost's standard borderless, left-aligned style, so commands don't repeat the rendition/padding boilerplate. Don't call tablewriter.NewTable directly with inline options; use this helper wherever a normal table is output, passing extra tablewriter.Option values if a specific table needs to tweak the defaults.
Header auto-formatting is disabled in this style, so headers render exactly as the literal strings you pass to Header(...) β no camel-case splitting or title-casing. Always pass headers in their final form (e.g. "LAST 4", not "LAST4"). The only table that intentionally diverges from this style is sql.go, which uses a distinct pipe-delimited layout (column separators and a header underline) for query result sets and configures tablewriter inline.
Do not add yaml: struct tags to output types. SerializeToYAML works by encoding to JSON first, then converting to YAML. This ensures consistent serialization even for types outside our control that only have json: tags. Only json: tags are needed.
Commands should never block waiting for long-running operations (like a database starting up) by default. Provide an optional --wait flag (or wait MCP tool parameter) that enables polling until the operation completes. The pattern:
- Perform the API call and output results immediately.
- If
--waitis not set, return. - If
--waitis set, callcommon.WaitForDatabaseWithProgress()(shows a spinner in TTY, falls back to plain polling otherwise). Progress is written to stderr so it doesn't interfere with JSON/YAML output on stdout.
Destructive CLI commands (e.g. delete) should prompt for confirmation unless a --confirm flag is provided. Use util.ReadLine() for the prompt (it respects context cancellation). Default to cancelling if the user doesn't type y or yes.
All interactive prompts (confirmation prompts, password prompts, interactive menus, etc.) must be gated with util.IsTerminal(cmd.InOrStdin()). If stdin is not a terminal, return an error directing the user to the non-interactive alternative (e.g. --confirm flag, positional argument). This prevents commands from hanging or reading garbage when stdin is piped or redirected. util.IsTerminal is a function variable that can be overridden in tests via withIsTerminal(true) to simulate a terminal stdin.
Each MCP tool in internal/mcp/ follows a consistent structure:
-
Tool definition:
newXxxTool() *mcp.Toolβ sets name (ghost_xxx), description, input/output schemas, and annotations (ReadOnlyHint,DestructiveHint,IdempotentHint,OpenWorldHint). Ghost tools setOpenWorldHint: false: their domain of interaction is closed (the Ghost API and the user's own databases), not an open world of arbitrary external entities. -
Handler:
(s *Server) handleXxx(ctx context.Context, req *mcp.CallToolRequest, input XxxInput) (*mcp.CallToolResult, XxxOutput, error)β returnsnil, output, nilon success. -
Input/Output types: Structs with
jsontags and aSchema() *jsonschema.Schemamethod. Use the schema property helpers ininternal/mcp/util.go(e.g.databaseIDInputProperties,waitInputProperties) for consistent descriptions and validation. Input and output helpers are separated β input helpers may setPattern,Enum,Default, etc., while output helpers typically only setDescription. Don't put example values inline inDescriptionstrings (e.g."Database status (running, paused, etc.)"). Instead, use theExamplesfield for illustrative values (e.g.Examples = []any{"running", "paused"}) or theEnumfield if the set of values is fixed and exhaustive. -
Registration:
mcp.AddTool(s.mcpServer, newXxxTool(), s.handleXxx)inserver.go'sregisterTools()method. Exception: read-only-sensitive (write) tools are registered inregisterReadOnlyTools()instead β see the Read-only guard bullet below. -
Read-only guard: A tool that mutates or destroys existing resources is disallowed in read-only mode and must be wired up for it in two places: (1) register it in
registerReadOnlyTools()/removeReadOnlyTools(), rather than directly inregisterTools(); and (2) callcheckReadOnly(cfg)in the handler after loading config, as defense-in-depth. The registration mechanism means these tools are not registered at all while read-only mode is on, and are added/removed dynamically (with atools/list_changednotification) as theread_onlyconfig changes β seereconcileReadOnlyTools(). The in-handlercheckReadOnlyguard still matters: a client might call a tool in the window before it is removed, or ignore the notification. When adding or removing a read-only-sensitive tool, keepregisterReadOnlyTools()andremoveReadOnlyTools()in sync.Read-only mode applies only to tools that mutate or destroy existing resources (
ghost_delete,ghost_rename,ghost_pause,ghost_share,ghost_share_revoke,ghost_password,ghost_api_key_create,ghost_api_key_delete). It deliberately still allows creating new resources βghost_create,ghost_fork,ghost_resume, and the dedicated variants are not gated (creating/forking databases for experimentation is low-risk). So the read-only tool set does not align 1:1 with tools whoseReadOnlyHintannotation isfalse: several non-read-only-hinted tools remain available in read-only mode. Generated function tools (internal/mcp/function) are also out of scope β they intentionally ignoreread_only. -
JSON Schema defaults are applied by the SDK: The Go MCP SDK (
go-sdk) callsresolved.ApplyDefaults()on the raw JSON input before unmarshaling into the typed input struct. This means if a schema setsDefaulton a field (e.g.schema.Properties["size"].Default = json.RawMessage("\"1x\"")), the handler is guaranteed to receive that value when the caller omits the field. Handlers can rely on this and do not need to check for zero values or apply defaults themselves. -
Optional input fields need
,omitempty:jsonschema.Formarks every struct field asrequiredunless itsjsontag includes,omitempty(or it's a pointer). An optional input field must therefore usejson:"name,omitempty"β without it the field lands in the schema'srequiredlist and clients can't omit it. Follow the existing optional fields (e.g.CreateInput.Name,ForkInput.Name) as the pattern. Required fields (e.g. a delete tool's identifier) correctly omit,omitempty.
ALWAYS pass the command context (cmd.Context()) down into any functions that perform long-running operations that may need to be cancelled or time out. This is standard Go best practice and an important rule we follow throughout this codebase. It ensures that commands exit promptly upon receiving a Ctrl+C, SIGINT, or SIGTERM.
When reading user input from stdin, always use util.ReadLine or util.ReadPassword instead of direct reads (e.g., bufio.NewReader). These functions respect context cancellation, which is important for handling Ctrl+C gracefully. ReadPassword also saves and restores terminal state, preventing the terminal from being left in an unusable state if the user cancels during password entry.
// For regular line input
line, err := util.ReadLine(cmd.Context(), cmd.InOrStdin())
// For password input (hides typed characters)
password, err := util.ReadPassword(cmd.Context(), cmd.InOrStdin())All outgoing HTTP requests must use the singleton api.HTTPClient defined in internal/api/client_util.go. This client has a built-in 30-second request timeout. The API client created by api.NewGhostClient uses it automatically. If you need to make HTTP requests outside of the API client, use api.HTTPClient directly rather than http.DefaultClient or creating a new http.Client.
If a request needs a shorter timeout, set one via the context:
ctx, cancel := context.WithTimeout(cmd.Context(), 5*time.Second)
defer cancel()-
Pre-allocate slices when the length is known. Use
make([]T, len(source))with index assignment rather thanmake([]T, 0)withappend, which may resize the backing array multiple times. -
Construct output/result types at the end. Build intermediate data (slices, computed values) first, then construct and return the struct as the final step. Avoid creating a struct early and mutating it over the course of the function.
-
Use
new()for pointer-to-expression values. As of Go 1.26,new()accepts an expression (not just a type) and returns a pointer to a new variable initialized with that expression's value. Usenew("value"),new(42), ornew(someFunc())instead of declaring a variable first. This is cleaner and avoids polluting the scope with single-use variables. For example:api.CreateDatabaseRequest{Name: new("mydb")}instead ofname := "mydb"; api.CreateDatabaseRequest{Name: &name}. This also works with type conversions:new(api.DatabaseSize("2x")). -
Use multi-line struct literals when initializing more than one field. Put each field on its own line, with a trailing comma after the last field. Only collapse a struct literal onto a single line when it sets zero or one field. For example:
// Two or more fields: one per line. api.CreateDatabaseRequest{ Name: new("mydb"), Size: new(api.DatabaseSize("2x")), } // Single field: a one-line literal is fine. api.CreateDatabaseRequest{Name: new("mydb")}
When working with API responses from the generated client, always nil-check response bodies. After checking the status code, check that the parsed response body (e.g. resp.JSON200, resp.JSON202) is not nil before accessing it. A nil body indicates a bug and should return errors.New("empty response from API").
Sensitive values (passwords, keys, queries, etc.) must never be sent in analytics events. There are three mechanisms to be aware of:
- Flags and MCP inputs: The
ignorelist ininternal/analytics/analytics.gofilters out sensitive flag names and MCP tool parameter names. Add new entries there when introducing flags or MCP parameters that carry sensitive data. - Positional arguments: The
analytics.Argsfunction ininternal/analytics/analytics.goredacts sensitive positional arguments for specific commands (e.g. the password inghost password). Update it when adding commands that accept sensitive positional arguments. - Call site: Commands are tracked in
wrapCommandsininternal/cmd/root.go. That function usesanalytics.Args(notanalytics.Property) to record args so that redaction is applied.
When adding a new command or MCP tool that handles secrets, credentials, or user-supplied queries, make sure it is covered by one of these mechanisms.
Creating a release automatically triggers a build and publish via GoReleaser. To create a new release, follow these steps:
- Make sure you are on
mainand up to date (git pull). - Find the latest existing tag to determine the current version:
git tag --sort=-v:refname | head -5 - Ask the user whether this is a major, minor, or patch bump. Do not assume.
- Compute the next semver version based on the current latest tag and the bump type.
- Create the release:
gh release create v<NEXT_VERSION> --generate-notes --latest
- Get the workflow run URL and open it in the browser:
open $(gh run list -w Release -b v<NEXT_VERSION> -L 1 --json url -q '.[0].url') - If the user asks to watch/wait for the workflow to complete:
gh run watch $(gh run list -w Release -b v<NEXT_VERSION> -L 1 --json databaseId -q '.[0].databaseId')
The tag push triggers the Release workflow, which runs GoReleaser to build binaries, Docker images, and Linux packages, then publishes them to GitHub Releases, S3, GHCR, PackageCloud, and the Homebrew tap. No manual deploy step is needed.
After adding new commands, directories, or major functionality, update:
CLAUDE.mdβ Update the Repository Structure section (e.g., the command list ininternal/cmd/) and add guidance for any new patterns introduced. Keep it concise and high-level. This file is pulled into every agent session, so unnecessary detail bloats context and distracts more than it helps. Convey the big picture β what we're building, the architecture, and the patterns to follow β and leave out anything readable from the code itself (implementation specifics, exact names, control flow, per-case behavior). Describe the intent and the pattern; let the code and its comments be the source of truth for the details.README.mdβ Update the Commands table and Usage examples as needed.docs/β Regenerate the CLI reference docs (see below).
The live ghost tutorial command and the markdown tutorials under docs/tutorials/ share a single source of truth in internal/tutorial/. Each tutorial.Tutorial bundles its filename, title/callout/intro narrative, ordered []tutorial.Step, and optional DeleteStep. Steps contain tutorial.Blocks whose Target field controls visibility: TargetAll (default), TargetCLIOnly, or TargetDocsOnly. A block can carry CLI args, an ExpectedOutput string shown only in the markdown, and side-effect tracking (CreatesDatabase/RemovesDatabase) used by the live runtime. The renderer in cmd/generate-tutorial-docs/docs.go is content-agnostic β it walks the struct without any hard-coded text or step numbers, and tutorial.FormatCommand is shared with the CLI echo so multi-statement SQL formatting stays in sync. To add a new tutorial, create a BuildXxxTutorial function in internal/tutorial/ and append it to tutorial.All(). After editing tutorial content, regenerate the docs with go run ./cmd/generate-tutorial-docs (-out defaults to ./docs/tutorials). The golden test TestAllTutorialDocsMatchGoldenFiles (in cmd/generate-tutorial-docs/) iterates the registry and fails if any on-disk markdown drifts.
The docs/cli/ directory contains generated Markdown reference documentation for every CLI command. These are produced by cmd/generate-docs, which uses Cobra's doc package to walk the command tree and emit one file per command.
Regenerate the docs whenever a CLI command is added, updated, or removed. Run from the repository root, or pass -out explicitly β the default output path is ./docs/cli relative to the working directory, and -clean will delete that directory:
go run ./cmd/generate-docs -cleanFlags:
-outβ Output directory (default./docs/cli).-formatβ Output format:markdown,man,rest, oryaml(defaultmarkdown).-frontmatterβ Prepend YAML frontmatter to Markdown files (defaulttrue).-cleanβ Remove the output directory before generating (defaultfalse).-experimentalβ Include experimental commands in the output (defaultfalse). This setsGHOST_EXPERIMENTALfor the run, overriding any inherited value, so released-only docs are produced by default.