api

package
v1.0.0-rc.5 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 76 Imported by: 0

Documentation

Overview

Client link endpoints: the UI counterpart of the stack's declarative link: block. POST/DELETE write BOTH the client's own config (via the provisioner) and the stack.yaml link: entry (via stackedit), so the UI and the file never diverge. These endpoints write files in the operator's home directory — the same local-operator capability the vault and stack-editing endpoints already assume.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AgentPreview

type AgentPreview struct {
	Name        string                   `json:"name"`
	Description string                   `json:"description"`
	Body        string                   `json:"body"`
	Valid       bool                     `json:"valid"`
	Errors      []string                 `json:"errors,omitempty"`
	Findings    []skills.SecurityFinding `json:"findings,omitempty"`
	Exists      bool                     `json:"exists"`
}

AgentPreview represents a previewed agent definition from a repo (not yet imported). The kind marker for the wizard's review step: a mixed repo previews as skills plus agents, each under its own key.

type AuthRequest

type AuthRequest struct {
	Method        string `json:"method,omitempty"`        // "token" | "ssh-agent" | "ssh-key" | ""
	Token         string `json:"token,omitempty"`         // ephemeral plaintext
	CredentialRef string `json:"credentialRef,omitempty"` // e.g. "${vault:GIT_TOKEN}"
	SSHUser       string `json:"sshUser,omitempty"`
	SSHKeyPath    string `json:"sshKeyPath,omitempty"`
}

AuthRequest is the optional auth payload accepted on /api/skills/sources/* endpoints. Raw Token values are transient; CredentialRef (e.g. "${vault:GIT_TOKEN}") is resolved against the live vault on every request.

type ClientStatus

type ClientStatus struct {
	Name       string `json:"name"`
	Slug       string `json:"slug"`
	Detected   bool   `json:"detected"`
	Linked     bool   `json:"linked"`
	Transport  string `json:"transport"`
	ConfigPath string `json:"configPath,omitempty"`
	// EffectiveScope is the backend-computed per-client tool access scope when a
	// `clients:` block is configured: the servers and prefixed tools this client
	// can reach. nil when no access scoping is in effect, so the frontend can
	// distinguish "unscoped (legacy)" from "scoped to nothing".
	EffectiveScope *mcp.ClientScopeResult `json:"effectiveScope,omitempty"`
	// Declared reports whether the stack's link: block lists this client;
	// LinkEntry carries the declared options when it does. Desired state,
	// distinct from Linked (actual config-file state).
	Declared  bool           `json:"declared,omitempty"`
	LinkEntry *LinkEntryInfo `json:"linkEntry,omitempty"`
	// Drifted reports that a recorded gridctl entry in this client's
	// config was edited since gridctl wrote it (wiring ownership).
	Drifted bool `json:"drifted,omitempty"`
	// Notes carries the provisioner's client-specific post-link guidance
	// (provisioner.PostLinkNoter); absent for clients without caveats.
	Notes []string `json:"notes,omitempty"`
}

ClientStatus describes an LLM client's detection and link state.

type FeatureStatus

type FeatureStatus struct {
	Name        string `json:"name"`
	Stage       string `json:"stage"`
	Description string `json:"description"`
}

FeatureStatus is one enabled experimental flag as exposed on /api/status. Read-only display metadata: the UI never toggles flags (they are configured in stack.yaml and cannot be changed from the browser).

type LinkEntryInfo

type LinkEntryInfo struct {
	Group     string `json:"group,omitempty"`
	ClientID  string `json:"clientId,omitempty"`
	Name      string `json:"name,omitempty"`
	Discovery string `json:"discovery,omitempty"`
}

LinkEntryInfo is the wire shape of a declared link: entry's options.

type MCPServerSourceStatus

type MCPServerSourceStatus struct {
	Type     string `json:"type"`
	URL      string `json:"url,omitempty"`
	Ref      string `json:"ref,omitempty"`
	Package  string `json:"package,omitempty"`
	Version  string `json:"version,omitempty"`
	Commit   string `json:"commit,omitempty"`
	Artifact string `json:"artifact,omitempty"`
}

MCPServerSourceStatus reports declared source identity plus immutable provenance read from the actual image's labels.

type MCPServerStatus

type MCPServerStatus struct {
	Execution             *execution.Report              `json:"execution,omitempty"`
	Name                  string                         `json:"name"`
	Transport             string                         `json:"transport"`
	Endpoint              string                         `json:"endpoint"`
	ContainerID           string                         `json:"containerId,omitempty"`
	Initialized           bool                           `json:"initialized"`
	ToolCount             int                            `json:"toolCount"`
	Tools                 []string                       `json:"tools"`
	PromptCount           int                            `json:"promptCount"`
	MCPResourceCount      int                            `json:"mcpResourceCount"`
	ResourceTemplateCount int                            `json:"resourceTemplateCount"`
	Capabilities          mcp.DownstreamCapabilityStatus `json:"capabilities"`
	ResourceCollisions    int                            `json:"resourceCollisions"`
	ResourceListError     string                         `json:"resourceListError,omitempty"`
	External              bool                           `json:"external"`
	LocalProcess          bool                           `json:"localProcess"`
	SSH                   bool                           `json:"ssh"`
	SSHHost               string                         `json:"sshHost,omitempty"`
	OpenAPI               bool                           `json:"openapi"`
	OpenAPISpec           string                         `json:"openapiSpec,omitempty"`
	OutputFormat          string                         `json:"outputFormat,omitempty"`
	Healthy               *bool                          `json:"healthy,omitempty"`
	LastCheck             *string                        `json:"lastCheck,omitempty"`
	HealthError           string                         `json:"healthError,omitempty"`
	ToolWhitelist         []string                       `json:"toolWhitelist,omitempty"`
	// ProtocolVersion is the MCP protocol version the downstream server
	// reported at initialize; empty for lax servers and OpenAPI adapters.
	ProtocolVersion string `json:"protocolVersion,omitempty"`
	// ProtocolGeneration is the resolved protocol era ("handshake" or
	// "stateless"); empty for OpenAPI adapters and unresolved servers.
	ProtocolGeneration string `json:"protocolGeneration,omitempty"`
	// RegistrationFailed marks a server that never registered with the
	// gateway; the UI shows it as failed instead of omitting the node.
	RegistrationFailed bool `json:"registrationFailed,omitempty"`

	// Description is the operator note from the stack. Empty when unset.
	// Headers are not projected here.
	Description string `json:"description,omitempty"`

	Replicas  []mcp.ReplicaStatus  `json:"replicas,omitempty"`
	Autoscale *mcp.AutoscaleStatus `json:"autoscale,omitempty"`

	// AuthStatus reports downstream authorization state ("authorized" or
	// "needs_auth"); empty for servers without tracked auth state.
	AuthStatus string     `json:"authStatus,omitempty"`
	AuthIssuer string     `json:"authIssuer,omitempty"`
	AuthExpiry *time.Time `json:"authExpiry,omitempty"`

	Kind   string                 `json:"kind,omitempty"`
	Image  string                 `json:"image,omitempty"`
	Source *MCPServerSourceStatus `json:"source,omitempty"`

	// StderrTail is the last server-stderr lines from the log ring for an
	// unhealthy server. Healthy servers omit it. Lines have already passed
	// through the gateway logger, including redaction.
	StderrTail []string `json:"stderrTail,omitempty"`

	// Enabled is false for a server that is declared but not registered.
	// Omitted on registered servers so existing payloads stay unchanged.
	Enabled *bool `json:"enabled,omitempty"`

	// Overrides lists field names applied from the active override file.
	Overrides []string `json:"overrides,omitempty"`

	// SubscriptionStream is the downstream subscriptions/listen state:
	// "open", "closed", or "unsupported". Omitted for servers that do not
	// use that stream.
	SubscriptionStream string `json:"subscriptionStream,omitempty"`
}

MCPServerStatus mirrors the mcp.MCPServerStatus type for API responses.

type ResourceStatus

type ResourceStatus struct {
	Name   string `json:"name"`
	Image  string `json:"image"`
	Status string `json:"status"`
}

ResourceStatus contains status information for a resource container.

type Server

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

Server provides the combined API server for gridctl.

func NewServer

func NewServer(gateway *mcp.Gateway, staticFS fs.FS) *Server

NewServer creates a new API server.

func (*Server) Close

func (s *Server) Close()

Close performs cleanup of the API server's managed resources.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the main HTTP handler.

func (*Server) LogBuffer

func (s *Server) LogBuffer() *logging.LogBuffer

LogBuffer returns the log buffer for gateway logs.

func (*Server) MetricsAccumulator

func (s *Server) MetricsAccumulator() *metrics.Accumulator

MetricsAccumulator returns the token metrics accumulator.

func (*Server) PinStore

func (s *Server) PinStore() *pins.PinStore

PinStore returns the wired pin store, or nil when schema pinning is not configured. Exposed so callers and tests can confirm whether pin management is active.

func (*Server) RegistryServer

func (s *Server) RegistryServer() *registry.Server

RegistryServer returns the registry server.

func (*Server) ReloadHandler

func (s *Server) ReloadHandler() *reload.Handler

ReloadHandler returns the reload handler.

func (*Server) SetAgentsManager

func (s *Server) SetAgentsManager(m *agentsync.Manager)

SetAgentsManager injects the agent projection manager. Tests use it to keep projection handlers away from the real home directory.

func (*Server) SetAllowedHosts

func (s *Server) SetAllowedHosts(hosts []string)

SetAllowedHosts sets extra Host header values accepted across the whole HTTP surface. Loopback hosts are always accepted, so an empty list is the secure default.

func (*Server) SetAllowedOrigins

func (s *Server) SetAllowedOrigins(origins []string)

SetAllowedOrigins sets the CORS allowed origins for the server.

func (*Server) SetAuth

func (s *Server) SetAuth(authType, token, header string)

SetAuth configures authentication for the server. When configured, operational routes require a valid token; the UI, probes, terminal CORS preflight, and state-validated OAuth callback remain public.

func (*Server) SetCardPinStore

func (s *Server) SetCardPinStore(ps *pins.PinStore)

SetCardPinStore supplies mandatory card trust independently of legacy pinning. Both fields share the same store when legacy tool pinning is enabled.

func (*Server) SetContextPinStore

func (s *Server) SetContextPinStore(store *ctxpins.Store)

SetContextPinStore overrides the context pin store. Call it before the first request; the store is stateless, so a later write through another Store on the same path is visible on the next call.

func (*Server) SetContextsManager

func (s *Server) SetContextsManager(m *contexts.Manager)

SetContextsManager overrides the global-context manager. Must be called before the server handles its first request (it races with the lazy sync.Once initialization otherwise); tests call it during setup. The pinner is not attached here: direct Manager calls in tests are not the server path, and skillLockPath may still be unset. contextsMgr attaches once on first use, including for an injected manager.

func (*Server) SetDockerClient

func (s *Server) SetDockerClient(cli dockerclient.DockerClient)

SetDockerClient sets the Docker client for container operations.

func (*Server) SetFeatures

func (s *Server) SetFeatures(get func() []FeatureStatus)

SetFeatures sets a getter for the enabled experimental flag list. The getter (rather than a static slice) lets hot reloads of `experimental:` reach /api/status without re-wiring; it must be safe for concurrent calls.

func (*Server) SetGatewayAddr

func (s *Server) SetGatewayAddr(addr string)

SetGatewayAddr sets the base URL of this server (e.g. "http://localhost:8180"). Used to build the MCP config JSON for CLI proxy sessions so the claude CLI can reach gridctl's MCP gateway at <gatewayAddr>/sse.

func (*Server) SetHookPinStore

func (s *Server) SetHookPinStore(ps *hookpins.Store)

SetHookPinStore injects the hook pin store. Tests use it so pin handlers never touch the real home directory.

func (*Server) SetHooksManager

func (s *Server) SetHooksManager(m *hooksync.Manager)

SetHooksManager injects the hook projection manager. Tests use it to keep projection handlers away from the real home directory. Pack handlers built by packsMgr pick up the same manager.

func (*Server) SetLimitsStatusFunc

func (s *Server) SetLimitsStatusFunc(fn func() limits.StatusReport)

SetLimitsStatusFunc installs the closure GET /api/limits reads. The builder wires a closure over the live limits policy so hot-reload swaps are reflected without re-wiring.

func (*Server) SetLogBuffer

func (s *Server) SetLogBuffer(buffer *logging.LogBuffer)

SetLogBuffer sets the log buffer for gateway logs.

func (*Server) SetMetricsAccumulator

func (s *Server) SetMetricsAccumulator(acc *metrics.Accumulator)

SetMetricsAccumulator sets the token metrics accumulator.

func (*Server) SetModelPolicyProvider

func (s *Server) SetModelPolicyProvider(provider func() (skillPolicy, agentPolicy *registry.ModelPolicy))

SetModelPolicyProvider wires the live model preference policies into the API (the controller points it at the gateway instance's compiled scopes, which hot reload keeps current). nil (the default) means no stack policy is available and responses carry declarations only.

func (*Server) SetOAuth

func (s *Server) SetOAuth(v *resourceauth.Verifier, cfg resourceauth.Config)

SetOAuth enables resource-server mode. The verifier may still be waiting on discovery; protected routes answer 503 until a key set is available. AuthEnabled is true even though no gateway token is stored.

func (*Server) SetOAuthBroker

func (s *Server) SetOAuthBroker(b *mcpauth.Broker)

SetOAuthBroker wires the downstream OAuth broker: enables the /api/servers/{name}/auth/* endpoints and mounts the /oauth/callback route (outside the inbound auth middleware).

func (*Server) SetOpenAPIPreviewer

func (s *Server) SetOpenAPIPreviewer(p *openapipreview.Previewer)

SetOpenAPIPreviewer wires an externally-constructed previewer. The API server owns the limiter; the previewer's cache comes from the gateway builder, mirroring how SetProber works.

func (*Server) SetOverrideSelection

func (s *Server) SetOverrideSelection(path string, noOverride bool)

SetOverrideSelection records the daemon's startup override selection. An empty path discovers stack.override.yaml. noOverride suppresses it.

func (*Server) SetPacksManagers

func (s *Server) SetPacksManagers(m *packops.Managers)

SetPacksManagers injects the pack engine. Tests use it to keep pack handlers away from the real home directory.

func (*Server) SetPinStore

func (s *Server) SetPinStore(ps *pins.PinStore)

SetPinStore sets the pin store for schema pin management.

func (*Server) SetPolicyStatusFunc

func (s *Server) SetPolicyStatusFunc(fn func() toolpolicy.StatusReport)

SetPolicyStatusFunc installs the closure GET /api/policy reads. The builder wires a closure over the live policy and the pre-whitelist catalog so hot-reload swaps are reflected without re-wiring.

func (*Server) SetProber

func (s *Server) SetProber(p *probe.Prober)

SetProber wires an externally-constructed prober. The API server owns the limiter but the prober's cache and spawner come from the gateway builder.

func (*Server) SetProvisionerRegistry

func (s *Server) SetProvisionerRegistry(r *provisioner.Registry, serverName string)

SetProvisionerRegistry sets the provisioner registry for client detection.

func (*Server) SetRegistryServer

func (s *Server) SetRegistryServer(r *registry.Server)

SetRegistryServer sets the registry server for skill management.

func (*Server) SetReloadHandler

func (s *Server) SetReloadHandler(h *reload.Handler)

SetReloadHandler sets the reload handler for hot reload support.

func (*Server) SetResetExit

func (s *Server) SetResetExit(exit func(int))

SetResetExit overrides the process-exit function the purge finalizer calls. Tests use it to observe self-termination without dying.

func (*Server) SetResetManagers

func (s *Server) SetResetManagers(m *resetops.Managers)

SetResetManagers injects the reset engine. Tests use it to keep the reset handlers away from the real home directory.

func (*Server) SetResetRuntime

func (s *Server) SetResetRuntime(rt resetops.Runtime)

SetResetRuntime injects the container-teardown runtime for reset.

func (*Server) SetRunRecorder

func (s *Server) SetRunRecorder(r *runs.Recorder)

SetRunRecorder installs the stack-owned run recorder. Nil disables live status.

func (*Server) SetServerCard

func (s *Server) SetServerCard(description, publicURL string)

SetServerCard records card-only gateway fields. They are not used for link URLs, SetGatewayAddr, or the reload snapshot.

func (*Server) SetSkillPinStore

func (s *Server) SetSkillPinStore(ps *skillpins.Store)

SetSkillPinStore sets the skill pin store for skill governance management.

func (*Server) SetSkillSourcePaths

func (s *Server) SetSkillSourcePaths(lockPath, configPath string)

SetSkillSourcePaths overrides the skill lock-file and skills.yaml paths used by /api/skills/* handlers. Empty values keep the global defaults.

func (*Server) SetSkillUpdateCachePath

func (s *Server) SetSkillUpdateCachePath(path string)

SetSkillUpdateCachePath overrides the skill update cache path. Empty keeps the global default. Tests use this to isolate from $HOME/.gridctl/cache.

func (*Server) SetStackFile

func (s *Server) SetStackFile(path string)

SetStackFile sets the path to the stack YAML file for spec endpoints.

func (*Server) SetStackName

func (s *Server) SetStackName(name string)

SetStackName sets the stack name for container lookups.

func (*Server) SetStartWatcher

func (s *Server) SetStartWatcher(fn func(stackPath string))

SetStartWatcher sets a callback that activates live-reload file watching for the given stack path. Called by POST /api/stack/initialize after cold-loading.

func (*Server) SetStartupOrigins

func (s *Server) SetStartupOrigins(mode string, count int)

SetStartupOrigins records the security-report origin mode and allowlist count. mode is computed by the builder from the effective bind, never from the hardcoded localhost gateway address.

func (*Server) SetTokenizerName

func (s *Server) SetTokenizerName(name string)

SetTokenizerName sets the active tokenizer mode for display in /api/status.

func (*Server) SetTraceBuffer

func (s *Server) SetTraceBuffer(buf *tracing.Buffer)

SetTraceBuffer sets the distributed tracing ring buffer.

func (*Server) SetVaultStore

func (s *Server) SetVaultStore(v *vault.Store)

SetVaultStore sets the vault store for secrets management.

func (*Server) SetWiringManager

func (s *Server) SetWiringManager(m *wiring.Manager)

SetWiringManager injects the wiring ownership manager. Tests use it to keep link handlers away from the real home directory.

func (*Server) SkillPinStore

func (s *Server) SkillPinStore() *skillpins.Store

SkillPinStore returns the wired skill pin store, or nil when skill pinning is not configured.

type ServerInfo

type ServerInfo struct {
	Name      string `json:"name"`
	Version   string `json:"version"`
	Tokenizer string `json:"tokenizer,omitempty"`
}

ServerInfo mirrors the mcp.ServerInfo type for API responses.

type SkillDiffResponse

type SkillDiffResponse struct {
	Skill       string `json:"skill"`
	Local       string `json:"local"`
	Upstream    string `json:"upstream"`
	UnifiedDiff string `json:"unifiedDiff,omitempty"`
	Drifted     bool   `json:"drifted"`
}

SkillDiffResponse is the body of the per-skill compare-with-upstream endpoint.

type SkillPreview

type SkillPreview struct {
	Name        string                   `json:"name"`
	Description string                   `json:"description"`
	Body        string                   `json:"body"`
	Valid       bool                     `json:"valid"`
	Errors      []string                 `json:"errors,omitempty"`
	Warnings    []string                 `json:"warnings,omitempty"`
	Findings    []skills.SecurityFinding `json:"findings,omitempty"`
	Exists      bool                     `json:"exists"`
}

SkillPreview represents a previewed skill from a repo (not yet imported).

type SkillSourceEntry

type SkillSourceEntry struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	State       string `json:"state"`
	IsRemote    bool   `json:"isRemote"`
	ContentHash string `json:"contentHash,omitempty"`
	// HasLocalEdits is true when the on-disk SKILL.md diverges from the hash
	// snapshotted at the last import/sync (i.e. the user edited it locally).
	HasLocalEdits bool `json:"hasLocalEdits"`
	// SupportingFilesInstalled distinguishes a complete package that ships no
	// managed files from a legacy import that may have omitted them.
	SupportingFilesInstalled bool `json:"supportingFilesInstalled"`
}

SkillSourceEntry represents a single skill within a source.

type SkillSourceStatus

type SkillSourceStatus struct {
	Name           string             `json:"name"`
	Repo           string             `json:"repo"`
	Kind           string             `json:"kind"`
	Ref            string             `json:"ref,omitempty"`
	Path           string             `json:"path,omitempty"`
	AutoUpdate     bool               `json:"autoUpdate"`
	UpdateInterval string             `json:"updateInterval"`
	Skills         []SkillSourceEntry `json:"skills"`
	LastFetched    string             `json:"lastFetched,omitempty"`
	CommitSHA      string             `json:"commitSha,omitempty"`
	UpdateAvail    bool               `json:"updateAvailable"`
	// DriftedSkills lists the skills in this source whose on-disk SKILL.md has
	// local edits (drift) that a sync would otherwise overwrite.
	DriftedSkills []string `json:"driftedSkills,omitempty"`
	// PackMember is the pack name when this source was imported as a named
	// external source of that pack. Empty for every other source.
	PackMember string `json:"packMember,omitempty"`
}

SkillSourceStatus represents a skill source with its update status.

type SkillSyncResult

type SkillSyncResult struct {
	Skill    string `json:"skill"`
	Imported int    `json:"imported,omitempty"`
	// ImportedAgents counts agent definitions the same update refreshed
	// (Update re-imports the whole source, so agents ride along).
	ImportedAgents int      `json:"importedAgents,omitempty"`
	Warnings       []string `json:"warnings,omitempty"`
	Error          string   `json:"error,omitempty"`
	// Skipped, when set, is the reason a drifted skill was left untouched
	// (e.g. "local edits"). Its tracking metadata is still advanced.
	Skipped string `json:"skipped,omitempty"`
	// Backup is the file name of the pre-overwrite SKILL.md backup written
	// when a drifted skill was force-overwritten.
	Backup string `json:"backup,omitempty"`
}

SkillSyncResult is the per-skill outcome within a sync.

type SourceSyncResult

type SourceSyncResult struct {
	Name   string            `json:"name"`
	Repo   string            `json:"repo"`
	Pinned bool              `json:"pinned,omitempty"`
	Skills []SkillSyncResult `json:"skills,omitempty"`
	Error  string            `json:"error,omitempty"`
}

SourceSyncResult is the per-source outcome of a bulk sync.

type SourceSyncSummary

type SourceSyncSummary struct {
	Sources       []SourceSyncResult `json:"sources"`
	SyncedSources int                `json:"syncedSources"`
	UpdatedSkills int                `json:"updatedSkills"`
	SkippedSkills int                `json:"skippedSkills"`
	FailedSources int                `json:"failedSources"`
	PinnedSources int                `json:"pinnedSources"`
}

SourceSyncSummary is the aggregate response from a bulk sync.

type SourceUpdateSummary

type SourceUpdateSummary struct {
	Name      string `json:"name"`
	Repo      string `json:"repo"`
	Current   string `json:"currentSha"`
	Latest    string `json:"latestSha,omitempty"`
	HasUpdate bool   `json:"hasUpdate"`
	Error     string `json:"error,omitempty"`
}

SourceUpdateSummary represents update status for a single source.

type StackRecipe

type StackRecipe struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Category    string `json:"category"`
	Spec        string `json:"spec"`
}

StackRecipe is a pre-built stack template.

type UpdateSummary

type UpdateSummary struct {
	Available int                   `json:"available"`
	Sources   []SourceUpdateSummary `json:"sources"`
}

UpdateSummary represents pending updates across all sources.

type WizardDraft

type WizardDraft struct {
	ID           string                 `json:"id"`
	Name         string                 `json:"name"`
	ResourceType string                 `json:"resourceType"`
	FormData     map[string]interface{} `json:"formData"`
	CreatedAt    string                 `json:"createdAt"`
	UpdatedAt    string                 `json:"updatedAt"`
}

WizardDraft represents a saved wizard draft.

Jump to

Keyboard shortcuts

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