Documentation
¶
Overview ¶
Package connect provides functionality to register MCPProxy as an MCP server in various client configuration files (Claude Code, Cursor, VS Code, Windsurf, Codex, Gemini, ZCode).
Index ¶
- Constants
- Variables
- func ConfigPath(clientID, homeDir string) string
- func DerivePreconditionToken(key []byte, state PreconditionState) string
- func DisplayPath(path, homeDir string) string
- type AccessError
- type AccessOutcome
- type ClientDef
- type ClientStatus
- type ConnectOptions
- type ConnectPreview
- type ConnectResult
- type CredentialIntent
- type CredentialMinter
- type EntrySummary
- type IssuedCredential
- type PreconditionState
- type Service
- func (s *Service) ClientSecret(clientID string) (secret string, found bool, err error)
- func (s *Service) Connect(clientID, serverName string, force bool) (*ConnectResult, error)
- func (s *Service) ConnectWithOptions(clientID, serverName string, opts ConnectOptions) (res *ConnectResult, err error)
- func (s *Service) ConnectWithPrecondition(clientID, serverName string, force bool, preconditionToken string) (res *ConnectResult, err error)
- func (s *Service) DetectAppDataDenial() (denied bool, remediation string)
- func (s *Service) Disconnect(clientID, serverName string) (res *ConnectResult, err error)
- func (s *Service) GetAllStatus() []ClientStatus
- func (s *Service) GetConnectedCount() int
- func (s *Service) GetConnectedIDs() []string
- func (s *Service) GetStatus(clientID string) (ClientStatus, error)
- func (s *Service) Preview(clientID, serverName string) (*ConnectPreview, error)
- func (s *Service) PreviewWithIntent(clientID, serverName string, intent CredentialIntent) (*ConnectPreview, error)
- func (s *Service) Undo(clientID, serverName, backupName string) (res *ConnectResult, err error)
- func (s *Service) UndoWithIntent(clientID, serverName, backupName string, intent CredentialIntent) (res *ConnectResult, err error)
- func (s *Service) WithConfigProvider(fn func() (listenAddr, apiKey string, requireMCPAuth bool)) *Service
- func (s *Service) WithCredentialMinter(m CredentialMinter) *Service
- func (s *Service) WithRequireMCPAuth(v bool) *Service
Constants ¶
const ( EndpointMatchThis = "this" EndpointMatchOther = "other" EndpointMatchUnknown = "unknown" )
EndpointMatch values for ClientStatus.EndpointMatch.
Variables ¶
var ( // ErrNoCredentialMinter: require_mcp_auth is on but no minter is wired. // Connect never falls back to the admin API key (fail closed). ErrNoCredentialMinter = errors.New("connect needs the client-credential store to mint a credential") // ErrKeylessRequiresAuthOff: a credential-less entry cannot work while // /mcp demands authentication. ErrKeylessRequiresAuthOff = errors.New("keyless connect is only possible while require_mcp_auth is off") // ErrKeylessWithProfile: a keyless client is unidentified, so it cannot // carry a profile binding. ErrKeylessWithProfile = errors.New("keyless connect cannot carry a profile or mode: an unidentified client has no binding") )
Errors returned by the connect credential path. All of them are raised BEFORE anything is written to a client config.
Functions ¶
func ConfigPath ¶
ConfigPath returns the expected configuration file path for the given client on the current operating system. homeDir overrides os.UserHomeDir when non-empty (useful for testing).
func DerivePreconditionToken ¶ added in v0.53.0
func DerivePreconditionToken(key []byte, state PreconditionState) string
DerivePreconditionToken computes the opaque precondition token that binds a rendered connect preview to the exact operation and pre-write state it described (Spec 091 FR-005).
It is an HMAC-SHA256, hex-encoded, over a canonical LENGTH-PREFIXED encoding of every field, so:
- no two distinct states share a preimage — a byte moved from one field into the next changes the encoding, which a delimiter- or concatenation-based scheme would not catch;
- the token is KEYED with a per-core-instance random in-memory key, so it is not an offline confirmation oracle: an attacker who knows everything about the state except a masked or weak credential still cannot test guesses.
The token is never persisted and never leaves this process except as an opaque string in the preview response.
func DisplayPath ¶ added in v0.70.0
DisplayPath returns path with a leading match of homeDir (or, when homeDir is empty, os.UserHomeDir() — %USERPROFILE% on Windows, since that is what os.UserHomeDir resolves through there) replaced by "~", for compact display in tables and UI rows (FR-037). The full path remains available via ConfigPath/config_path; this is cosmetic only and never changes what is written to disk. Returns path unchanged when it does not live under the home directory, or when the home directory cannot be resolved.
Types ¶
type AccessError ¶ added in v0.41.0
type AccessError struct {
Client string // client id/name
Path string // config path attempted
Outcome AccessOutcome // accessDenied (could also wrap malformed)
Remediation string // actionable fix text
Err error // underlying OS cause
}
AccessError is returned by connect/disconnect (and surfaced by GetStatus via the Remediation field) when a client-config access is permission-denied. It is errors.As-discoverable so the REST layer can map it to the right field, and unwraps to the underlying OS error so errors.Is(err, fs.ErrPermission) still holds (data-model.md AccessError).
func (*AccessError) Error ¶ added in v0.41.0
func (e *AccessError) Error() string
func (*AccessError) Unwrap ¶ added in v0.41.0
func (e *AccessError) Unwrap() error
Unwrap exposes the underlying OS error for errors.Is/errors.As.
type AccessOutcome ¶ added in v0.41.0
type AccessOutcome = string
AccessOutcome classifies an attempt to read or write a client config file (Spec 075 FR-003). It is an alias of string so it interoperates with the existing untyped access* constants and the ClientStatus.AccessState wire field, while giving classifier signatures a documented, enum-like type.
Valid values are the access* constants in connect.go: accessAccessible, accessAbsent, accessDenied, accessMalformed. (accessUnknown is the overall, not-content-checked status default, not a classification outcome.)
type ClientDef ¶
type ClientDef struct {
ID string // Unique identifier, e.g. "claude-code"
Name string // Human-readable name, e.g. "Claude Code"
Format string // File format: "json" or "toml"
// ServerKey is the human-readable label for the config section server
// entries live under ("mcpServers", "servers", ...), and doubles as the
// literal top-level key for every client except those special-cased in
// serversMapPath (e.g. ZCode's "mcp.servers" is a nested path, not a
// literal top-level key).
ServerKey string
Supported bool // Whether this client can be connected (directly or via a bridge)
Reason string // Explanation when Supported is false
Note string // Optional caveat shown for supported clients (e.g. bridge requirement)
Bridge bool // Connects via a stdio bridge; Connect can create the config when absent
Icon string // Icon identifier for frontend use
// ClientInfoNames lists the aliases this client is known to send as its MCP
// `initialize` request's `clientInfo.name` (Spec 109-b). Used to match a
// live session/activation record back to this client id (e.g. presence's
// "connected but never seen" detection). Best-effort: recorded from public
// client documentation and observed behavior, NOT verified here against a
// live `initialize` from every client (this environment has no way to spin
// up Cursor/Windsurf/etc. and inspect their handshake) — a wrong or missing
// alias only means a client is misclassified as "never seen" one release
// longer, never a security issue, so this is a reasonable place to make an
// informed assumption rather than block (see source comments below).
ClientInfoNames []string
// ReloadHint is the per-client, human-readable instruction for making a
// freshly-written config take effect (FR-037/FR-042): most of these
// clients only read their MCP config at startup or on an explicit
// reload command, so a `connect` that succeeds is not yet a client that
// has picked up the new server. Best-effort wording (not verified against
// a live client in this environment); see the per-client comment for its
// source.
ReloadHint string
}
ClientDef describes a known MCP client and its configuration file format.
func FindClient ¶
FindClient looks up a client definition by ID. Returns nil if not found.
func GetAllClients ¶
func GetAllClients() []ClientDef
GetAllClients returns the definitions of all known clients.
type ClientStatus ¶
type ClientStatus struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
ConfigPath string `json:"config_path" yaml:"config_path"`
Exists bool `json:"exists" yaml:"exists"` // config file exists on disk
Connected bool `json:"connected" yaml:"connected"` // mcpproxy entry present in config
Supported bool `json:"supported" yaml:"supported"` // client can be connected (directly or via a bridge)
Reason string `json:"reason,omitempty" yaml:"reason,omitempty"` // why not supported
Note string `json:"note,omitempty" yaml:"note,omitempty"` // caveat for supported clients (e.g. bridge requirement)
Bridge bool `json:"bridge,omitempty" yaml:"bridge,omitempty"` // connects via a stdio bridge; connectable even without an existing config
Icon string `json:"icon" yaml:"icon"`
ServerName string `json:"server_name,omitempty" yaml:"server_name,omitempty"` // name under which mcpproxy is registered
// CredentialState reports what the client's entry carries (FR-025):
// client|admin_key|none|revoked|expired, or "unknown" in the stat-only
// listing, which never reads a config (Spec 075). Absent when the client is
// not connected. Administrator-only, like the rest of the connect reads.
CredentialState string `json:"credential_state,omitempty" yaml:"credential_state,omitempty"`
// DisplayPath is ConfigPath with the home directory shortened to "~"
// (FR-037). Cosmetic only; the full path stays in ConfigPath.
DisplayPath string `json:"display_path,omitempty" yaml:"display_path,omitempty"`
// ReloadHint is this client's instruction for making a newly-written
// config take effect (FR-037/FR-042). Empty for an unsupported client.
ReloadHint string `json:"reload_hint,omitempty" yaml:"reload_hint,omitempty"`
// AccessState classifies the per-client content access (Spec 075, additive).
// Empty/"unknown" in the content-read-free overall status; resolved to
// "accessible"/"absent"/"malformed" (and "denied" in US2) by on-demand reads.
AccessState string `json:"access_state" yaml:"access_state"`
// CheckedPaths lists every config location the existence check consults,
// highest precedence first. For most clients this is just ConfigPath; for
// OpenCode it names both opencode.jsonc and opencode.json (#922), so a
// "no config found" UI can say exactly which files were looked for.
CheckedPaths []string `json:"checked_paths,omitempty" yaml:"checked_paths,omitempty"`
// Remediation carries actionable fix text, populated only when access is denied.
Remediation string `json:"remediation,omitempty" yaml:"remediation,omitempty"`
// ProxyURL is THIS instance's MCP endpoint — the address a client would be
// pointed at by a connect. Derived from config only (no file read), so it is
// populated by both the stat-only listing and the on-demand read.
ProxyURL string `json:"proxy_url,omitempty" yaml:"proxy_url,omitempty"`
// RegisteredURL is the endpoint the client's existing entry actually points
// at, projected through exactly the same sanitizer as a Spec 091 preview's
// entry summary: scheme, host and path only — query (the ?apikey= carrier),
// userinfo and fragment are dropped, and a value that is not an absolute URL
// is not echoed at all. Note this is scheme+host+PATH, matching the preview:
// a credential embedded in a path segment by a third-party config would
// survive, exactly as it already does on the preview surface. Deliberately
// identical so the two surfaces cannot disagree about what an entry says.
// Empty when nothing was read or the entry carries no URL-shaped value.
// Resolved only by GetStatus.
RegisteredURL string `json:"registered_url,omitempty" yaml:"registered_url,omitempty"`
// EndpointMatch says how RegisteredURL relates to ProxyURL. It exists
// because Connected only ever meant "an mcpproxy-shaped entry is present":
// an entry merely *named* mcpproxy counts, even when it points at another
// instance on another port (audit F18). One of:
// "this" — the entry's endpoint is this instance
// "other" — the entry points somewhere else (a different instance)
// "unknown" — the entry has no comparable endpoint (e.g. a stdio command)
// Empty when Connected is false or nothing was read.
EndpointMatch string `json:"endpoint_match,omitempty" yaml:"endpoint_match,omitempty"`
}
ClientStatus describes the current state of a client's configuration with respect to an MCPProxy entry. See ConnectResult's comment above: fields here also carry matching `yaml` tags so `mcpproxy connect --list`/`--all -o yaml` doesn't fall back to yaml.v3's collapsed default keys.
type ConnectOptions ¶ added in v0.70.0
type ConnectOptions struct {
Force bool
PreconditionToken string
Intent CredentialIntent
}
ConnectOptions carries the optional parts of a connect: the overwrite flag, the Spec 091 preview token, and the credential Intent (Spec 108).
type ConnectPreview ¶ added in v0.47.0
type ConnectPreview struct {
Client string `json:"client"`
ConfigPath string `json:"config_path"`
// DisplayPath is ConfigPath with the home directory shortened to "~"
// (FR-037), matching ClientStatus/ConnectResult so the same client's path
// renders identically across the status list, the preview, and the
// post-connect result. Cosmetic only; the full path stays in ConfigPath.
DisplayPath string `json:"display_path,omitempty"`
Format string `json:"format"` // "json" | "toml"
ServerKey string `json:"server_key"` // mcpServers / servers / mcp_servers / mcp
ServerName string `json:"server_name"` // key written into the config ("mcpproxy")
Entry map[string]interface{} `json:"entry"` // exact entry (masked) that will be written
EntryText string `json:"entry_text"` // entry rendered in the client's format (masked)
EntryExists bool `json:"entry_exists"` // an entry with this name already exists (overwrite/force case)
// ContainsAPIKey is always false since Spec 108: connect never writes the
// instance admin API key. Kept on the wire so existing consumers still
// decode; the credential a write embeds is Credential below.
ContainsAPIKey bool `json:"contains_api_key"`
Bridge bool `json:"bridge,omitempty"` // connects via a stdio bridge (config created if absent)
// Credential is the masked per-client credential the write would embed
// (`mcp_cli_••••`, never `mcp_agt_`), empty for a keyless entry. Profile and
// Mode echo the requested binding (Profile "" is All servers) and Keyless
// echoes the intent (Spec 108 FR-024).
Credential string `json:"credential,omitempty"`
Profile string `json:"profile"`
Mode string `json:"mode"`
Keyless bool `json:"keyless"`
// AccessState classifies the on-demand config read used to determine
// EntryExists (Spec 075): accessible|absent|malformed. A denied read never
// reaches here — it is returned as a typed *AccessError (403 + remediation).
AccessState string `json:"access_state"`
// ExistingEntrySummary describes the entry this connect would REPLACE, and
// is populated only when EntryExists (Spec 091 FR-003). It is built by
// construction from non-secret projections — see EntrySummary — so no
// arbitrary value from the user's config can ride out in a preview. It is
// display-only: drift detection uses PreconditionToken, never this.
ExistingEntrySummary *EntrySummary `json:"existing_entry_summary,omitempty"`
// PreconditionToken is the opaque, keyed digest of the raw pre-write state
// this preview describes plus the exact entry that would be written (Spec
// 091 FR-005). A caller echoes it on the subsequent write; the core
// recomputes and refuses with a discriminated conflict when anything has
// drifted — externally (the file or the target entry changed) or
// proxy-side (credential rotation, auth toggle, address change).
PreconditionToken string `json:"precondition_token"`
// ConnectRefusal carries, verbatim, the reason a connect would refuse for
// this client regardless of user intent — today only a non-create-capable
// client (OpenCode) whose config is absent. It is produced by the SAME guard
// the write runs, so the form can hide the Connect control and show the
// reason instead of letting the user discover it by clicking (Spec 091
// FR-003). Empty means connectable.
ConnectRefusal string `json:"connect_refusal,omitempty"`
}
ConnectPreview describes the exact change a subsequent Connect would make to a client config, WITHOUT modifying the file or creating a backup (Spec 078 US1). The entry is derived from the same buildServerEntry used by the real write, so what is previewed equals what is written for the same client and configuration (FR-002); the embedded API key is masked for display (FR-004).
type ConnectResult ¶
type ConnectResult struct {
Success bool `json:"success" yaml:"success"`
Client string `json:"client" yaml:"client"`
ConfigPath string `json:"config_path" yaml:"config_path"`
BackupPath string `json:"backup_path,omitempty" yaml:"backup_path,omitempty"`
ServerName string `json:"server_name" yaml:"server_name"`
Action string `json:"action" yaml:"action"` // "created", "updated", "already_exists", "removed", "not_found"
Message string `json:"message" yaml:"message"`
// DisplayPath is ConfigPath with the home directory shortened to "~"
// (FR-037). Populated for every result whose ConfigPath is known.
DisplayPath string `json:"display_path,omitempty" yaml:"display_path,omitempty"`
// ReloadHint is this client's instruction for making the write take
// effect (FR-037/FR-042), e.g. "Restart Cursor to load MCPProxy". Empty
// for an unknown client.
ReloadHint string `json:"reload_hint,omitempty" yaml:"reload_hint,omitempty"`
// Credential is the masked client credential the write embedded
// (`mcp_cli_••••`); the real secret is never returned (FR-024). Empty for a
// keyless entry, a disconnect and every refusal.
Credential string `json:"credential,omitempty" yaml:"credential,omitempty"`
// TokenName is the client credential's token name (`client-<id>`).
TokenName string `json:"token_name,omitempty" yaml:"token_name,omitempty"`
// Profile and Mode are the binding of the credential this write minted or
// kept. Profile "" means the built-in All servers scope.
Profile string `json:"profile,omitempty" yaml:"profile,omitempty"`
Mode string `json:"mode,omitempty" yaml:"mode,omitempty"`
// Keyless is true when the entry was written with no credential.
Keyless bool `json:"keyless,omitempty" yaml:"keyless,omitempty"`
// Rotation is "finalized" when the write replaced an active credential's
// secret (staged rotation, FR-021a), empty otherwise.
Rotation string `json:"rotation,omitempty" yaml:"rotation,omitempty"`
// CredentialRevoked names the credential that was revoked: by an undo,
// because the restored config no longer holds it (plan D16), or by a
// disconnect, which cuts the client off (a later undo of that disconnect
// does not bring the credential back).
CredentialRevoked string `json:"credential_revoked,omitempty" yaml:"credential_revoked,omitempty"`
// CredentialRevokeError is set when a disconnect removed the entry but
// revoking the client credential failed. The disconnect still succeeded;
// the credential is still active and `mcpproxy client forget <id>`
// retries the revoke.
CredentialRevokeError string `json:"credential_revoke_error,omitempty" yaml:"credential_revoke_error,omitempty"`
}
ConnectResult describes the outcome of a connect or disconnect operation. Struct fields below carry matching `yaml` tags alongside their `json` ones: gopkg.in/yaml.v3 ignores json tags entirely and falls back to lowercased, separator-free field names for any field without its own yaml tag, which would make `mcpproxy connect ... -o yaml` disagree with the documented snake_case keys `-o json` and swagger.yaml both use (the same reasoning as output.StructuredError's yaml tags).
type CredentialIntent ¶ added in v0.70.0
type CredentialIntent struct {
Profile *string
Mode *string
Keyless bool
// Actor attribution for the profile_change record (FR-030).
ActorKind string
ActorName string
Surface string
}
CredentialIntent is what the caller asked connect to mint. A nil Profile or Mode means "not specified": a fresh credential defaults to the built-in "All servers" scope (empty profile, switchable) and a reconnect keeps the binding the client already has. Profile "" is an explicit All servers.
type CredentialMinter ¶ added in v0.70.0
type CredentialMinter interface {
// Issue validates the intent, runs the FR-008a guard over the candidate
// state, and mints a fresh credential or stages a rotation.
Issue(clientID string, intent CredentialIntent) (*IssuedCredential, error)
// CheckIdle refuses (connect_in_progress) while another connect of
// clientID holds the in-flight claim. A keyless connect mints nothing and
// so never calls Issue, but it still writes the client's config and must
// honour the same claim (FR-021a).
CheckIdle(clientID string) error
// Commit finalizes a successful write (fresh: records the mint; rotation:
// finalizes it and applies any binding change).
Commit(clientID string, intent CredentialIntent, issued *IssuedCredential) error
// Abort undoes Issue after a failed write (fresh: forget; rotation:
// rollback, the old secret keeps working).
Abort(clientID string, intent CredentialIntent, issued *IssuedCredential) error
// Release ends the in-flight claim Issue took without committing or
// aborting: the write outcome is ambiguous, so the reconciler resolves the
// staged rotation from what the config actually holds (FR-021a).
Release(clientID string, issued *IssuedCredential)
// PreviewBinding reports the profile and mode Issue would apply for this
// intent (a reconnect with no profile keeps the recorded binding),
// minting and staging nothing.
PreviewBinding(clientID string, intent CredentialIntent) (profile, mode string, err error)
// Classify reports the credential state of a `mcp_cli_` secret found in
// clientID's config: client|revoked|expired, or none for anything that is
// not a credential of this client.
Classify(clientID, secret string) profile.CredentialState
// HeldByRecord reports whether secret is the primary or pending secret of
// clientID's credential record.
HeldByRecord(clientID, secret string) bool
// ForgetUnheld revokes clientID's active credential when the config now
// holds a different secret (undo of a connect that minted). It returns the
// revoked token name, or "" when nothing was revoked.
ForgetUnheld(clientID, restoredSecret string, intent CredentialIntent) (string, error)
}
CredentialMinter mints, commits and aborts client credentials for connect, and classifies secrets found in a client config. Implemented by runtime.ClientsService.
type EntrySummary ¶ added in v0.53.0
type EntrySummary struct {
// EntryName is the key the entry actually lives under, which may differ
// from the requested server_name when the write adopts an equivalent entry.
EntryName string `json:"entry_name"`
Type string `json:"type,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Command string `json:"command,omitempty"`
HeaderNames []string `json:"header_names"`
EnvNames []string `json:"env_names"`
}
EntrySummary is the sanitized, display-only description of the client-config entry a connect would replace (Spec 091 FR-003).
It exists because the preview must tell the user WHAT is being overwritten without ever echoing config content: the pending entry is masked at construction (entryParams substitutes the mask constant), which cannot sanitize arbitrary user-authored content in an EXISTING entry. So the preview renders no existing content at all — only this fixed set of parsed projections, built by construction from a whitelist:
entry name | transport type | endpoint (query, userinfo and fragment stripped) | command | header NAMES | env NAMES
Nothing else from the entry can reach the response: unknown fields are not copied, values of headers/env are never read, and a URL-shaped field is emitted only after being reparsed into scheme://host/path. Secrecy therefore holds structurally rather than by masking heuristics (research D2).
The summary is display-only: it is NEVER used for drift comparison — that is the precondition token's job over the raw value (FR-005).
type IssuedCredential ¶ added in v0.70.0
type IssuedCredential struct {
Secret string
TokenName string
Profile string
Mode string
// Rotating is true when the credential is a staged rotation over an
// active one (both secrets authenticate until Commit/Abort, FR-021a).
Rotating bool
// Pending carries opaque minter state for Commit (a reconnect that
// also changes the binding applies it after the write succeeds).
Pending interface{}
// ClaimToken is the opaque per-connect token the minter set at Issue; it
// ties Release/Commit/Abort to that connect's in-flight claim.
ClaimToken string
}
IssuedCredential is a credential a minter has produced for one connect write. Secret is the raw `mcp_cli_` value to embed; it is never logged, never put in a precondition token digest and never returned by an API.
type PreconditionState ¶ added in v0.53.0
type PreconditionState struct {
// ClientID scopes the token to one client's connect flow.
ClientID string
// ConfigPath is which file is being written.
ConfigPath string
// Requested is the entry name the caller asked for — the key the write
// creates when nothing is adopted. It is NOT implied by ResolvedEntryName:
// that one is empty for every absent target, so without this a preview for
// one name validated a write under any other.
Requested string
// FileExists distinguishes create from update (a file appearing or
// vanishing between preview and write).
FileExists bool
// ResolvedEntryName is the key the write would replace, AFTER the same
// equivalent-entry adoption the write performs. Empty when none resolved.
ResolvedEntryName string
// RawResolvedEntry is that entry's value; nil when there is none. It
// includes values the sanitized summary deliberately hides, so a credential
// rotation inside the existing entry drifts.
RawResolvedEntry json.RawMessage
// PendingEntry is the entry the proxy would write right now, so proxy-side
// drift (API-key rotation, require_mcp_auth toggle, listen-address change)
// invalidates the preview too — otherwise a credential could be embedded
// without the FR-004 notice ever having been shown.
PendingEntry json.RawMessage
// Intent is the credential intent the operation was previewed with
// (profile, mode, keyless, and whether auth is required). The real secret
// is unknown at preview time and never enters the digest — PendingEntry
// carries a fixed placeholder instead — so an auth toggle or a changed
// intent still drifts the token (Spec 108 D17).
Intent json.RawMessage
}
PreconditionState is everything a precondition token binds a rendered preview to: the operation it described AND the pre-write state it observed. Two operations that would touch the config differently must differ in at least one field here, or a token minted for one authorizes the other.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides connect/disconnect operations for MCP client configurations.
func NewService ¶
NewService creates a Service that will inject the given listen address and optional API key into client configurations.
func NewServiceWithHome ¶
NewServiceWithHome creates a Service with a custom home directory (for testing).
func NewServiceWithReader ¶ added in v0.41.0
func NewServiceWithReader(listenAddr, apiKey, homeDir string, readFile func(string) ([]byte, error)) *Service
NewServiceWithReader creates a Service with a custom content reader (for testing the access-classification seam without a real OS denial).
func (*Service) ClientSecret ¶ added in v0.70.0
ClientSecret reads clientID's config on demand and returns the credential secret its mcpproxy entry carries ("" when none). It is the reconciler's ClientConfigReader (FR-021a). found is false when there is no entry.
func (*Service) Connect ¶
func (s *Service) Connect(clientID, serverName string, force bool) (*ConnectResult, error)
Connect registers MCPProxy in the specified client's configuration file. serverName defaults to "mcpproxy" if empty. If force is false and an entry already exists, an error is returned.
This is the tokenless entry point kept for the Web UI, the CLI and every existing caller; ConnectWithPrecondition adds the Spec 091 drift guard.
func (*Service) ConnectWithOptions ¶ added in v0.70.0
func (s *Service) ConnectWithOptions(clientID, serverName string, opts ConnectOptions) (res *ConnectResult, err error)
ConnectWithPrecondition is Connect guarded by the opaque token a preview returned (Spec 091 FR-005). When preconditionToken is non-empty, the core re-resolves the raw pre-write state and the entry it would write, recomputes the token, and refuses with the discriminated "precondition_failed" action — writing nothing and taking no backup — if anything drifted since the preview: the file appearing or vanishing, the resolved (possibly adopted) entry changing in any way, or the proxy's own configuration changing what would be written. force=true rides WITH the token for a replace-classified flow and never rescues a stale one.
An empty token means exactly today's behavior, so existing consumers are unaffected (contracts §2).
Credential (Spec 108 FR-024): the write embeds a per-client `mcp_cli_` credential minted by the injected CredentialMinter, or nothing (--keyless, only while require_mcp_auth is off). It never embeds the admin API key. A fresh credential is minted only once every refusal that does not depend on it has passed, so a refused write mints nothing; a write that then fails aborts the mint (fresh: forgotten; reconnect: the staged rotation rolls back and the old secret keeps working, FR-021a).
func (*Service) ConnectWithPrecondition ¶ added in v0.53.0
func (s *Service) ConnectWithPrecondition(clientID, serverName string, force bool, preconditionToken string) (res *ConnectResult, err error)
ConnectWithPrecondition is ConnectWithOptions with the default credential intent (All servers for a fresh credential, the existing binding kept on a reconnect).
func (*Service) DetectAppDataDenial ¶ added in v0.43.0
DetectAppDataDenial probes installed client configs for a persisted macOS App-Data (TCC) permission denial, for the doctor diagnostic (Spec 075 US3, FR-007/008). It walks the supported clients and, for the first whose config file exists (os.Stat metadata only), performs a single content read through the seam; if that read classifies as accessDenied it reports the denial with the canonical, one-command remediation. It returns (false, "") when no installed client config is permission-denied — including when none are installed — so the check never raises a false positive on a machine that simply has no clients or has granted access (FR-008, T022).
Unlike GetAllStatus this DOES read content: the doctor command is an explicit user action, the one place a macOS App-Data prompt may legitimately appear.
func (*Service) Disconnect ¶
func (s *Service) Disconnect(clientID, serverName string) (res *ConnectResult, err error)
Disconnect removes the MCPProxy entry from the specified client's configuration.
func (*Service) GetAllStatus ¶
func (s *Service) GetAllStatus() []ClientStatus
GetAllStatus returns the connection status for every known client.
It determines "installed" via os.Stat metadata only and performs ZERO config content reads (Spec 075 FR-001): no client config file is opened, so simply viewing status raises no macOS App-Data privacy prompt. AccessState is left as "unknown" and Connected stays false for installed clients until an explicit per-client read via GetStatus.
func (*Service) GetConnectedCount ¶ added in v0.29.0
GetConnectedCount returns the number of supported clients in which mcpproxy is currently registered. Used as the "has any client connected?" wizard predicate (Spec 046).
func (*Service) GetConnectedIDs ¶ added in v0.29.0
GetConnectedIDs returns the identifiers of supported clients in which mcpproxy is currently registered. Identifiers come from the fixed per-client adapter table; user-entered values never appear here.
func (*Service) GetStatus ¶ added in v0.41.0
func (s *Service) GetStatus(clientID string) (ClientStatus, error)
GetStatus returns the status for a single client, reading its config contents on demand (Spec 075 FR-002). This is the scoped, explicit-action path where a macOS App-Data prompt may legitimately appear. It resolves Connected and AccessState (accessible/absent/malformed; "denied" is added in US2).
func (*Service) Preview ¶ added in v0.47.0
func (s *Service) Preview(clientID, serverName string) (*ConnectPreview, error)
Preview computes the exact entry a Connect would write for the given client, without modifying the config or creating a backup (Spec 078 FR-001). It reads the config on demand only to classify create-vs-overwrite (FR-003) and to resolve the Spec 075 access state; a permission denial surfaces as the same typed *AccessError that connect/disconnect return (FR-012).
func (*Service) PreviewWithIntent ¶ added in v0.70.0
func (s *Service) PreviewWithIntent(clientID, serverName string, intent CredentialIntent) (*ConnectPreview, error)
PreviewWithIntent is Preview for a specific credential intent: the entry carries the masked client credential (or none when keyless), and the intent rides into the precondition token so a write with a different intent is refused as drift.
func (*Service) Undo ¶ added in v0.47.0
func (s *Service) Undo(clientID, serverName, backupName string) (res *ConnectResult, err error)
Undo reverts the connect that produced the named backup, restoring the client config to its exact pre-connect state (Spec 078 US3 / FR-008). backupName is the bare filename (filepath.Base) of the backup the connect returned, NOT a path — undo resolves the full path itself against the client's own config directory (see the resolution/validation below):
- backupName != "": the config is restored byte-for-byte from that backup — this is the only revert that can bring back a pre-existing same-named entry a force-connect overwrote (surgical disconnect cannot).
- backupName == "": the preceding connect created the file (no prior file existed, ConnectResult.backup_path was empty); undo deletes the file so the pre-connect "no file" state is restored.
Safety first: Undo refuses (Action "conflict") unless the CURRENT file is byte-identical to what that connect produced — i.e. the backup content with exactly the mcpproxy entry applied, reconstructed via the same buildServerEntry/marshal path the write used. Any other content means the user (or another tool) changed the file since the connect, and a restore would clobber those edits. Callers should fall back to Disconnect (surgical entry removal) in that case. A missing backup refuses with Action "not_found". Every mutation takes its own safety backup before touching the file, and a permission denial anywhere surfaces as the same typed *AccessError as connect/disconnect (403 + remediation at the REST boundary).
Note the drift check also intentionally refuses when the effective listen address / API key / require_mcp_auth changed since the connect: the entry the service would write today no longer matches the one on disk, so mcpproxy can no longer prove the file is untouched.
func (*Service) UndoWithIntent ¶ added in v0.70.0
func (s *Service) UndoWithIntent(clientID, serverName, backupName string, intent CredentialIntent) (res *ConnectResult, err error)
UndoWithIntent is Undo with the actor attribution the credential revocation record needs (Spec 108 plan D16). A connect that minted or rotated a client credential is undone as "as if it never happened": the drift check replays the write with the credential the file holds (accepted only when it is that client's own `mcp_cli_` secret), and after a successful restore the client's active credential is forgotten unless the restored entry still holds it — the result names it in credential_revoked. A live orphan secret is never left behind.
func (*Service) WithConfigProvider ¶ added in v0.47.0
func (s *Service) WithConfigProvider(fn func() (listenAddr, apiKey string, requireMCPAuth bool)) *Service
WithConfigProvider installs a live-config accessor so the service reflects runtime changes to listen/api_key/require_mcp_auth (hot-reloaded via the file watcher or the wizard's require_mcp_auth toggle) rather than a startup snapshot. Wired only for the long-lived HTTP server; CLI one-shots leave it nil. Returns the receiver for chaining.
func (*Service) WithCredentialMinter ¶ added in v0.70.0
func (s *Service) WithCredentialMinter(m CredentialMinter) *Service
WithCredentialMinter installs the minter connect uses to obtain client credentials. Returns the receiver for chaining.
func (*Service) WithRequireMCPAuth ¶ added in v0.47.0
WithRequireMCPAuth sets whether the /mcp endpoint requires authentication, which decides whether connect embeds a credential in client configs at all. Threaded from config.RequireMCPAuth at the wiring sites, alongside listenAddr and apiKey. Returns the receiver for chaining.