cliclient

package
v0.70.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetClientVersion added in v0.24.0

func SetClientVersion(v string)

SetClientVersion sets the version reported in the X-MCPProxy-Client header.

Types

type APIError

type APIError struct {
	Message   string `json:"error"`
	RequestID string `json:"request_id,omitempty"`
}

APIError represents an error from the API that includes request_id for log correlation. T023: Added for CLI error display with request ID

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) FormatWithRequestID

func (e *APIError) FormatWithRequestID() string

FormatWithRequestID returns a formatted error message including the request ID.

func (*APIError) HasRequestID

func (e *APIError) HasRequestID() bool

HasRequestID returns true if the error has a request ID for log correlation.

type ActivityFilterParams

type ActivityFilterParams interface {
	ToQueryParams() url.Values
}

ActivityFilterParams contains options for filtering activity records.

type AddServerRequest

type AddServerRequest struct {
	Name           string            `json:"name"`
	URL            string            `json:"url,omitempty"`
	Command        string            `json:"command,omitempty"`
	Args           []string          `json:"args,omitempty"`
	Env            map[string]string `json:"env,omitempty"`
	Headers        map[string]string `json:"headers,omitempty"`
	WorkingDir     string            `json:"working_dir,omitempty"`
	Protocol       string            `json:"protocol,omitempty"`
	Enabled        *bool             `json:"enabled,omitempty"`
	Quarantined    *bool             `json:"quarantined,omitempty"`
	ReconnectOnUse *bool             `json:"reconnect_on_use,omitempty"`
	// TrustMode is the per-server trust tier (spec 086): auto|scan|manual.
	// Empty is omitted from the wire so the daemon applies its own default; a
	// non-empty value is validated CLI-side before the request is built and
	// again by the REST layer (GH #938).
	TrustMode string `json:"trust_mode,omitempty"`
}

AddServerRequest represents the request body for adding a server.

type AddServerResult

type AddServerResult struct {
	Name        string `json:"name"`
	ID          int    `json:"id"`
	Quarantined bool   `json:"quarantined"`
}

AddServerResult represents the result of adding a server.

type AttentionResponse added in v0.70.0

type AttentionResponse struct {
	Count       int                       `json:"count"`
	GeneratedAt string                    `json:"generated_at"`
	Items       []contracts.AttentionItem `json:"items"`
}

GetDiagnostics retrieves diagnostics information from daemon. AttentionResponse is the GET /api/v1/attention success `data` payload (contracts/rest-api.md#attention, Spec 109 FR-001).

type BulkOperationResult

type BulkOperationResult struct {
	Total      int               `json:"total"`
	Successful int               `json:"successful"`
	Failed     int               `json:"failed"`
	Errors     map[string]string `json:"errors"`
}

BulkOperationResult holds the results of a bulk operation across multiple servers.

type CallToolResult

type CallToolResult struct {
	Content  []interface{}          `json:"content"`
	IsError  bool                   `json:"isError"`
	Metadata map[string]interface{} `json:"_meta,omitempty"`
}

CallToolResult represents tool call result.

type CatalogSearchResponse added in v0.70.0

type CatalogSearchResponse struct {
	Query       string                     `json:"query"`
	Results     []registries.CatalogResult `json:"results"`
	Sections    *CatalogSections           `json:"sections"`
	Unavailable []registries.SourceError   `json:"unavailable"`
}

CatalogSearchResponse mirrors GET /api/v1/catalog/search's response body (contracts/rest-api.md#catalog).

type CatalogSections added in v0.70.0

type CatalogSections struct {
	Official []registries.CatalogResult `json:"official"`
	Popular  []registries.CatalogResult `json:"popular"`
}

CatalogSections mirrors the REST empty-query landing sections.

type Client

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

Client provides HTTP API access for CLI commands.

func NewClient

func NewClient(endpoint string, logger *zap.SugaredLogger) *Client

NewClient creates a new CLI HTTP client. If endpoint is a socket path, creates a client with socket dialer.

func NewClientWithAPIKey

func NewClientWithAPIKey(endpoint, apiKey string, logger *zap.SugaredLogger) *Client

NewClientWithAPIKey creates a new CLI HTTP client with API key authentication. If endpoint is a socket path, creates a client with socket dialer.

func NewClientWithBearer added in v0.41.0

func NewClientWithBearer(endpoint, bearerToken string, logger *zap.SugaredLogger) *Client

NewClientWithBearer creates a CLI HTTP client that authenticates with a JWT Bearer token. The server edition user/JWT endpoints (e.g. the per-user credential broker surfaces, spec 074) sit behind session-or-Bearer auth rather than the API-key group, so callers must present a user token.

func (*Client) AddFromRegistry added in v0.35.0

func (c *Client) AddFromRegistry(ctx context.Context, registryID, serverID, name string, env map[string]string, enabled *bool) (*contracts.AddedServerSummary, error)

AddFromRegistry adds an upstream server from a registry reference via the daemon (spec 070 keystone). The daemon re-derives the runnable config from the registry entry — the client only sends optional overrides. On failure it returns a *RegistryAddError carrying the stable code.

func (*Client) AddRegistrySource added in v0.36.0

func (c *Client) AddRegistrySource(ctx context.Context, sourceURL, protocol, id, name string) (*contracts.RegistrySummary, error)

AddRegistrySource adds a user-supplied registry source via the daemon (MCP-866). POST /api/v1/registries → data.registry. On failure it returns a *RegistryAddError carrying the stable cross-surface code.

func (*Client) AddServer

func (c *Client) AddServer(ctx context.Context, req *AddServerRequest) (*AddServerResult, error)

AddServer adds a new upstream server via the daemon API.

func (*Client) ApproveTools added in v0.21.0

func (c *Client) ApproveTools(ctx context.Context, serverName string, toolNames []string, approveAll bool) (int, error)

ApproveTools approves specific tools or all tools for a server (Spec 032).

func (*Client) BlockTools added in v0.42.0

func (c *Client) BlockTools(ctx context.Context, serverName string, toolNames []string, blockAll bool) (int, error)

BlockTools blocks specific tools or all pending/changed tools for a server (Spec 032). Block atomically approves AND disables the tool so it is never left in the approved+enabled state — mirroring the Web UI "Block" action.

func (*Client) CallTool

func (c *Client) CallTool(
	ctx context.Context,
	toolName string,
	args map[string]interface{},
) (*CallToolResult, error)

CallTool calls a tool on an upstream server via daemon API.

func (*Client) CatalogSearch added in v0.70.0

func (c *Client) CatalogSearch(ctx context.Context, q, source, tag string, limit int) (*CatalogSearchResponse, error)

CatalogSearch calls GET /api/v1/catalog/search (Spec 109 FR-060/066), the backend for `mcpproxy catalog search|show`.

func (*Client) CodeExec

func (c *Client) CodeExec(
	ctx context.Context,
	code string,
	input map[string]interface{},
	timeoutMS int,
	maxToolCalls int,
	allowedServers []string,
	opts ...CodeExecOptions,
) (*CodeExecResult, error)

CodeExec executes JavaScript or TypeScript code via the daemon API.

func (*Client) DisableAll

func (c *Client) DisableAll(ctx context.Context) (*BulkOperationResult, error)

T080: DisableAll disables all configured servers.

func (*Client) DoRaw added in v0.20.0

func (c *Client) DoRaw(ctx context.Context, method, path string, body []byte) (*http.Response, error)

DoRaw performs a raw HTTP request to the API and returns the response. The caller is responsible for closing the response body. The body parameter can be nil for methods that don't require a request body.

func (*Client) EditRegistrySource added in v0.37.0

func (c *Client) EditRegistrySource(ctx context.Context, id, name, sourceURL, serversURL string) (*contracts.RegistrySummary, error)

EditRegistrySource updates a user-added custom registry source via the daemon (MCP-1072). PUT /api/v1/registries/{id} → data.registry. Empty fields are left unchanged. On failure it returns a *RegistryAddError carrying the stable cross-surface code (registry_not_found, registry_shadows_builtin, registries_locked, invalid_registry_url).

func (*Client) EnableAll

func (c *Client) EnableAll(ctx context.Context) (*BulkOperationResult, error)

T080: EnableAll enables all configured servers.

func (*Client) GetActivityDetail

func (c *Client) GetActivityDetail(ctx context.Context, activityID string) (map[string]interface{}, error)

GetActivityDetail retrieves details for a specific activity record.

func (*Client) GetActivitySummary

func (c *Client) GetActivitySummary(ctx context.Context, period, groupBy string, scope url.Values) (map[string]interface{}, error)

GetActivitySummary retrieves activity summary statistics.

func (*Client) GetAttention added in v0.70.0

func (c *Client) GetAttention(ctx context.Context) (*AttentionResponse, error)

GetAttention fetches the one needs-attention list every surface reads from — `mcpproxy attention`, the first line of `status`, and the first section of `doctor` (Spec 109 FR-003/FR-004) all call this.

func (*Client) GetCodeScripts added in v0.57.0

func (c *Client) GetCodeScripts(ctx context.Context) (dir string, entries []codescripts.Entry, err error)

GetCodeScripts lists the stored scripts the DAEMON can execute (Spec 097), together with the directory it read them from. Asking the daemon rather than listing locally is the point: a listing that disagreed with the process which actually resolves scripts would be worse than none.

func (*Client) GetDiagnostics

func (c *Client) GetDiagnostics(ctx context.Context) (map[string]interface{}, error)

func (*Client) GetGlobalTools added in v0.33.0

func (c *Client) GetGlobalTools(ctx context.Context) ([]map[string]interface{}, error)

GetGlobalTools retrieves all tools across every configured server from the consolidated GET /api/v1/tools endpoint (Spec 050). The returned slice contains one map per tool with the same fields as the web page's data source.

func (*Client) GetGlobalToolsView added in v0.70.0

func (c *Client) GetGlobalToolsView(ctx context.Context, query url.Values) ([]map[string]interface{}, map[string]interface{}, error)

GetGlobalToolsView is GetGlobalToolsWithQuery that also returns the response's `counts` ({visible, hidden}), present only for a non-administrator profile view-as (nil otherwise).

func (*Client) GetGlobalToolsWithQuery added in v0.70.0

func (c *Client) GetGlobalToolsWithQuery(ctx context.Context, query url.Values) ([]map[string]interface{}, error)

GetGlobalToolsWithQuery is GetGlobalTools with query parameters (Spec 108 FR-032: `client` or `profile` turn the listing into a view-as, adding an access verdict and profile_tier to every row).

func (*Client) GetInfo

func (c *Client) GetInfo(ctx context.Context) (map[string]interface{}, error)

GetInfo retrieves server info including version and update status.

func (*Client) GetInfoWithRefresh

func (c *Client) GetInfoWithRefresh(ctx context.Context, refresh bool) (map[string]interface{}, error)

GetInfoWithRefresh retrieves server info with optional update check refresh. When refresh is true, forces an immediate update check against GitHub.

func (*Client) GetServerLogs

func (c *Client) GetServerLogs(ctx context.Context, serverName string, tail int) ([]contracts.LogEntry, error)

GetServerLogs retrieves logs for a specific server.

func (*Client) GetServerTools

func (c *Client) GetServerTools(ctx context.Context, serverName string) ([]map[string]interface{}, error)

GetServerTools retrieves tools for a specific server from daemon.

func (*Client) GetServers

func (c *Client) GetServers(ctx context.Context) ([]map[string]interface{}, error)

GetServers retrieves list of servers from daemon.

func (*Client) GetServersWithQuery added in v0.70.0

func (c *Client) GetServersWithQuery(ctx context.Context, query url.Values) ([]map[string]interface{}, error)

GetServersWithQuery is GetServers with query parameters (Spec 108 FR-032: `profile` restricts the rows to that profile's effective servers).

func (*Client) GetStatus added in v0.19.0

func (c *Client) GetStatus(ctx context.Context) (map[string]interface{}, error)

GetStatus retrieves server status including running state, listen address, and upstream stats.

func (*Client) GetTelemetryPayload added in v0.24.0

func (c *Client) GetTelemetryPayload(ctx context.Context) (map[string]interface{}, error)

GetTelemetryPayload retrieves the next telemetry heartbeat payload that mcpproxy would send, rendered with live runtime stats attached. Spec 042. No network call is made by the daemon — the payload reflects the current in-memory state.

func (*Client) GetTokenStats added in v0.70.0

func (c *Client) GetTokenStats(ctx context.Context) (map[string]interface{}, error)

GetTokenStats retrieves token savings statistics (GET /api/v1/stats/tokens, contracts.ServerTokenMetrics). Spec 109-k: 'mcpproxy status' uses this for its "Token savings:" summary line. Administrator-only — a non-admin caller (e.g. an agent token) gets a 403, which the caller treats like "unavailable" rather than a hard failure.

func (*Client) GetToolApprovals added in v0.21.0

func (c *Client) GetToolApprovals(ctx context.Context, serverName string) ([]ToolApprovalRecord, error)

GetToolApprovals fetches tool approval records for a server (Spec 032).

func (*Client) GetToolDiff added in v0.21.0

func (c *Client) GetToolDiff(ctx context.Context, serverName, toolName string) (*ToolApprovalRecord, error)

GetToolDiff fetches the diff for a changed tool (Spec 032).

func (*Client) InvokeDiagnosticFix added in v0.25.0

func (c *Client) InvokeDiagnosticFix(ctx context.Context, server, code, fixerKey, mode string) (*DiagnosticFixResult, error)

InvokeDiagnosticFix runs a registered fixer via the daemon's fix endpoint. Destructive fixers default to dry_run on the server side; callers must pass mode="execute" to mutate state. Spec 044.

func (*Client) ListActivities

func (c *Client) ListActivities(ctx context.Context, filter ActivityFilterParams) ([]map[string]interface{}, int, error)

ListActivities retrieves activity records with filtering.

func (*Client) ListRegistries added in v0.35.0

func (c *Client) ListRegistries(ctx context.Context) ([]map[string]interface{}, error)

ListRegistries returns the MCP server registries known to the daemon (spec 070). Mirrors GetServers: GET /api/v1/registries → data.registries.

func (*Client) PatchServer added in v0.31.0

func (c *Client) PatchServer(ctx context.Context, serverName string, body []byte) error

PatchServer issues a partial update against PATCH /api/v1/servers/{name}.

The body is sent as raw JSON so callers can include JSON null values for header / env deletion under JSON Merge Patch semantics (RFC 7396). Building the body as `map[string]any{"X": nil}` would round-trip through encoding/json fine, but `map[string]*string` is cleaner for fixed-shape callers that want type safety — both forms are supported because callers pass already-marshaled bytes.

Example body shapes:

{"headers": {"X-New": "value"}}                  -- upsert
{"headers": {"X-Stale": null}}                   -- delete
{"headers": {"X-Set": "v", "X-Old": null}}       -- combined
{"env": {"API_KEY": null}, "enabled": true}      -- env delete + enable

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks if the daemon is reachable.

func (*Client) Preflight added in v0.58.0

Preflight runs a required-tools preflight against the daemon (Spec 098).

The verdict is DATA, not an error: a 200 carrying `blocked` comes back as a response with no error, and the caller turns it into an exit code. Only a request the daemon refused (400/503) or a transport failure is an error here.

func (*Client) RemoveRegistrySource added in v0.37.0

func (c *Client) RemoveRegistrySource(ctx context.Context, id string) (*contracts.RegistrySummary, error)

RemoveRegistrySource removes a user-added custom registry source via the daemon (MCP-1057). DELETE /api/v1/registries/{id} → data.registry. On failure it returns a *RegistryAddError carrying the stable cross-surface code (registry_not_found, registry_shadows_builtin, registries_locked).

func (*Client) RemoveServer

func (c *Client) RemoveServer(ctx context.Context, serverName string) error

RemoveServer removes an upstream server via the daemon API.

func (*Client) RestartAll

func (c *Client) RestartAll(ctx context.Context) (*BulkOperationResult, error)

T079: RestartAll restarts all configured servers.

func (*Client) SearchRegistry added in v0.35.0

func (c *Client) SearchRegistry(ctx context.Context, registryID, tag, query string, limit int) ([]map[string]interface{}, error)

SearchRegistry searches the servers in a registry via the daemon (spec 070). GET /api/v1/registries/{id}/servers?q=&tag=&limit= → data.servers.

func (*Client) ServerAction

func (c *Client) ServerAction(ctx context.Context, serverName, action string) error

ServerAction performs an action on a server (enable, disable, restart).

func (*Client) SetAllToolsEnabled added in v0.31.0

func (c *Client) SetAllToolsEnabled(ctx context.Context, serverName string, enabled bool) (int, error)

SetAllToolsEnabled bulk-toggles every known tool for a server. Returns the number of tools whose state actually changed (already-correct tools are skipped on the server side).

func (*Client) SetToolEnabled added in v0.31.0

func (c *Client) SetToolEnabled(ctx context.Context, serverName, toolName string, enabled bool) error

SetToolEnabled flips an individual tool's enabled state for a server. The daemon synthesizes an approval record on demand if the tool has never been quarantined or toggled before — see Runtime.SetToolEnabled.

func (*Client) TriggerOAuthLogin

func (c *Client) TriggerOAuthLogin(ctx context.Context, serverName string) error

TriggerOAuthLogin initiates OAuth authentication flow for a server. Returns *contracts.OAuthFlowError for structured OAuth errors (Spec 020). Use TriggerOAuthLoginWithResult when the caller needs the auth URL / browser status.

func (*Client) TriggerOAuthLoginWithResult added in v0.66.0

func (c *Client) TriggerOAuthLoginWithResult(ctx context.Context, serverName string) (*OAuthLoginResult, error)

TriggerOAuthLoginWithResult initiates the OAuth flow for a server and returns the daemon's browser status and authorization URL so the CLI can print the URL when the browser could not be opened (headless hosts, SSH sessions). Returns *contracts.OAuthFlowError for structured OAuth errors (Spec 020).

func (*Client) TriggerOAuthLogout

func (c *Client) TriggerOAuthLogout(ctx context.Context, serverName string) error

TriggerOAuthLogout clears OAuth token and disconnects a server.

type CodeExecError

type CodeExecError struct {
	Message string `json:"message"`
	Code    string `json:"code"`
}

CodeExecError represents execution error.

type CodeExecOptions added in v0.21.0

type CodeExecOptions struct {
	Language string // Source language: "javascript" (default) or "typescript"

	// Script names a server-side stored script to execute instead of inline
	// code (Spec 097). Only the NAME travels: the daemon's code_execution
	// handler is the single execution-time resolver, so a stored script means
	// the same thing over MCP, REST and both CLI modes.
	Script string
}

CodeExecOptions contains optional parameters for code execution via the daemon API.

type CodeExecResult

type CodeExecResult struct {
	OK        bool                   `json:"ok"`
	Result    interface{}            `json:"result,omitempty"`
	Error     *CodeExecError         `json:"error,omitempty"`
	Stats     map[string]interface{} `json:"stats,omitempty"`
	RequestID string                 `json:"request_id,omitempty"` // T023: For error correlation
}

CodeExecResult represents code execution result.

type DiagnosticFixResult added in v0.25.0

type DiagnosticFixResult struct {
	Outcome    string `json:"outcome"` // "success" | "failed" | "blocked"
	Mode       string `json:"mode"`    // "dry_run" | "execute"
	Preview    string `json:"preview,omitempty"`
	FailureMsg string `json:"failure_msg,omitempty"`
	DurationMs int64  `json:"duration_ms,omitempty"`
}

DiagnosticFixResult is the response from POST /api/v1/diagnostics/fix. Spec 044.

type OAuthLoginResult added in v0.66.0

type OAuthLoginResult struct {
	ServerName    string
	CorrelationID string
	AuthURL       string
	BrowserOpened bool
	BrowserError  string
	Message       string
}

OAuthLoginResult carries the fields of the daemon's OAuthStartResponse that the CLI needs to guide a user through a headless login: whether the daemon managed to open a browser and, if not, the authorization URL to visit manually.

type RegistryAddError added in v0.35.0

type RegistryAddError struct {
	Code          string
	Message       string
	MissingInputs []string
	RequestID     string
}

RegistryAddError is the client-side projection of a failed add-from-registry (spec 070). It carries the stable cross-surface Code and, for missing_required_input, the names of the inputs the user must supply so the CLI can name the exact --env keys.

func (*RegistryAddError) Error added in v0.35.0

func (e *RegistryAddError) Error() string

type ToolApprovalRecord added in v0.21.0

type ToolApprovalRecord struct {
	ServerName          string `json:"server_name"`
	ToolName            string `json:"tool_name"`
	Status              string `json:"status"`
	ApprovedHash        string `json:"approved_hash"`
	CurrentHash         string `json:"current_hash"`
	Hash                string `json:"hash"`
	Description         string `json:"description"`
	PreviousDescription string `json:"previous_description,omitempty"`
	CurrentDescription  string `json:"current_description,omitempty"`
	PreviousSchema      string `json:"previous_schema,omitempty"`
	CurrentSchema       string `json:"current_schema,omitempty"`
	Schema              string `json:"schema,omitempty"`
}

ToolApprovalRecord represents a tool approval record from the API (Spec 032)

Jump to

Keyboard shortcuts

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