Documentation
¶
Overview ¶
Package config is the driven adapter for the JSON config file — the only state toolhost keeps. Approval is a list of qualified names in this file; `toolhost approve` edits it, `serve` reads it at boot.
Index ¶
- Constants
- Variables
- func AppendRequests(cfgPath string, approved map[string]bool, reason string, names ...string) ([]string, error)
- func AppendServerRequest(cfgPath string, f *File, r Request) error
- func CheckServerSpec(r Request) error
- func ConfigHome() string
- func DefaultPath(explicit string) string
- func DeniedSet(reqs []Request) map[string]string
- func DenyRequest(cfgPath, name, reason string) error
- func ProjectConfigPath(dir string) string
- func ProjectKey(dir string) string
- func RemoveAnsweredRequests(cfgPath string, approved map[string]bool)
- func RemoveRequest(cfgPath, name string) error
- func RequestSet(reqs []Request) map[string]bool
- func RequestsPath(cfgPath string) string
- func ResolveEnv(s string) (string, error)
- func SaveRequests(cfgPath string, reqs []Request) error
- func StateDir(cfgPath string) string
- func UpdateRequests(cfgPath string, fn func([]Request) ([]Request, error)) error
- type Auth
- type Backend
- type Degraded
- type DegradedMark
- type Fault
- type File
- func (f *File) Approve(pins map[string]string) ([]string, error)
- func (f *File) ApprovedSet() map[string]bool
- func (f *File) BackendToolsApproved(name string) []string
- func (f *File) Disable(names ...string) ([]string, error)
- func (f *File) Enable(names ...string) ([]string, error)
- func (f *File) EnableAll()
- func (f *File) EnableOnly(names ...string) ([]string, error)
- func (f *File) EnabledSet() (map[string]bool, bool)
- func (f *File) IsApproved(qualified string) bool
- func (f *File) IsEnabled(qualified string) bool
- func (f *File) PruneBackendTools(name string) []string
- func (f *File) RemoveBackend(name string) bool
- func (f *File) ResolvedToken() (string, error)
- func (f *File) Revoke(names ...string) []string
- func (f *File) Save(path string) error
- func (f *File) SetBackend(name string, b *Backend) error
- type Request
Constants ¶
const ( RequestTool = "tool" RequestServer = "server" )
Request kinds.
const ( DefaultListen = "127.0.0.1:8080" DefaultAuditLog = "toolhost_audit.jsonl" // DefaultAuditMaxMB is the audit log's rotation cap. DefaultAuditMaxMB = 10 // ModeStateless is the default serving mode — sessionless Streamable // HTTP. ModeStateful opts into session-bearing mode for older clients // that need held sessions for pushed notifications/tools/list_changed. ModeStateless = "stateless" ModeStateful = "stateful" // DefaultCallTimeout bounds upstream calls when the config doesn't say. DefaultCallTimeout = "60s" )
const RequestsFile = "toolhost_requests.json"
RequestsFile is the env's agent-request queue — runtime state, kept out of the config so a committed toolhost.json is never mutated by agents.
SharedConfigPath is the committed environment — a hidden, namespaced path so an agent working in the folder never mistakes it for project content. Opt-in only, written by `init --shared`.
Variables ¶
var ErrStale = errors.New("config changed on disk since it was read")
ErrStale is a save refused because the file changed on disk after this copy was read: writing it would undo someone else's change.
Functions ¶
func AppendRequests ¶ added in v0.0.4
func AppendRequests(cfgPath string, approved map[string]bool, reason string, names ...string) ([]string, error)
AppendRequests queues qualified tool names (deduped, newest-last) in the env's request file — what gateway__request records. Approved names are refused: the request is already answered. A name a human denied is refused too — denial is a verdict, not a speed bump.
func AppendServerRequest ¶ added in v0.0.4
AppendServerRequest queues a proposed backend — the agent supplies the spec it can see (name, transport, url or command+args); the human materializes it into config on --accept. Name collisions with existing backends or denied proposals refuse.
func CheckServerSpec ¶ added in v0.0.4
CheckServerSpec refuses a server petition that carries both a command and a URL. Such a spec could show the human one thing and run another: a stdio backend runs its command and ignores its URL.
func ConfigHome ¶ added in v0.0.2
func ConfigHome() string
ConfigHome is toolhost's canonical home — $TOOLHOST_HOME if set, else ~/.toolhost. The user's global config lives here along with every environment's state: credentials, audit logs, and request queues never live in project folders.
func DefaultPath ¶ added in v0.0.2
DefaultPath resolves which config a command reads when -c isn't given, nearest scope first: a private environment keyed for this folder, then the committed ./.toolhost/toolhost.json, then the global home config. Mirrors the agents' own local > project > user precedence.
func DeniedSet ¶ added in v0.0.4
DeniedSet is the lookup form — name → deny reason, for the catalog's denied mark.
func DenyRequest ¶ added in v0.0.4
DenyRequest marks one queued petition denied — the verdict stays on record so the agent sees it rather than re-asking.
func ProjectConfigPath ¶ added in v0.0.4
ProjectConfigPath is the private environment for a folder — keyed under the user's home, never written into the folder itself.
func ProjectKey ¶ added in v0.0.4
ProjectKey turns a directory's absolute path into a stable, filesystem- safe environment id: basename slug + short path hash, so two same-named projects in different trees never collide.
func RemoveAnsweredRequests ¶ added in v0.0.4
RemoveAnsweredRequests drops queue entries whose names are now approved — an approval is the answer to the request.
func RemoveRequest ¶ added in v0.0.4
RemoveRequest drops a queue entry — the cleanup after --accept or an explicit dismissal.
func RequestSet ¶ added in v0.0.4
RequestSet is the lookup form — name → pending (undecided) request.
func RequestsPath ¶ added in v0.0.4
RequestsPath is the queue file for the environment cfgPath resolves to.
func ResolveEnv ¶
ResolveEnv expands an "env:NAME" reference; anything else passes through unchanged. Unset or empty fails closed — a config pointing at a missing variable is broken, not merely incomplete.
Credential fields stay as references inside File — Save round-trips the reference, never the resolved secret, so toolhost.json can carry pointers and be committed safely. Resolution happens at the boundary: ResolvedToken for the gateway token, Backend.Resolved for upstream creds.
func SaveRequests ¶ added in v0.0.4
SaveRequests replaces the whole queue. It reads nothing first, so it is for seeding a queue; anything that reads the queue and writes it back goes through UpdateRequests.
func StateDir ¶ added in v0.0.4
StateDir is where an environment's runtime state lives — tokens, audit log, request queue. Global config and private envs keep state beside themselves (inside the home); a config anywhere else (a committed ./toolhost.json, an explicit -c path) gets a keyed state dir so the folder holding the config stays pure declaration.
func UpdateRequests ¶ added in v0.0.4
UpdateRequests is the queue's read-modify-write. It holds the queue lock across load, fn and write, so a petition the agent files and a verdict the human gives at the same moment both land.
Types ¶
type Auth ¶
type Auth struct {
// Type: "none" (default), "bearer" (a static token sent as
// Authorization: Bearer — the API-key shape), "client_credentials"
// (machine OAuth; token endpoint discovered via the server's Protected
// Resource Metadata), "oauth" (interactive auth-code + PKCE; run
// `toolhost mcp auth <backend>` to grant).
Type string `json:"type"`
// bearer:
Token string `json:"token,omitempty"`
// client_credentials + oauth:
ClientID string `json:"client_id,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
Scopes []string `json:"scopes,omitempty"`
// oauth only: loopback redirect the AS redirects the browser to.
// Must match the registered/registered-via-DCR redirect URI.
RedirectURL string `json:"redirect_url,omitempty"`
}
Auth configures how toolhost authenticates TO an upstream server — orthogonal to the bearer token that authenticates agents to toolhost.
type Backend ¶
type Backend struct {
// Transport is "stdio" (local subprocess), "http" (remote streamable-HTTP
// MCP server), or "sse" (legacy HTTP+SSE MCP server).
Transport string `json:"transport"`
// stdio transport:
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
// EnvAllowlist names host environment variables forwarded to the
// subprocess beyond the safe baseline (PATH, HOME, ...). Credentials
// should reach a backend by being named — here, or via env values
// holding "env:" references — never by inheriting everything.
EnvAllowlist []string `json:"env_allowlist,omitempty"`
// EnvInherit forwards the entire host environment: every credential in
// the gateway's shell reaches the backend. The least-safe option —
// prefer Env + EnvAllowlist.
EnvInherit bool `json:"env_inherit,omitempty"`
// http/sse transports:
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Auth *Auth `json:"auth,omitempty"`
// Passthrough marks this upstream as a federated toolhost gateway: its
// tool names arrive already qualified ("cbm__search_graph") and are
// trusted as-is instead of being re-namespaced. Its own gateway__*
// meta-tools are dropped — the outer gateway has its own control plane.
Passthrough bool `json:"passthrough,omitempty"`
// Disabled parks the backend: the entry stays, nothing dials, and its
// tools leave the surface. `toolhost mcp enable` reconnects it. The
// tools' approvals stay pinned — parking is not revocation.
Disabled bool `json:"disabled,omitempty"`
// Cwd is the working directory a stdio backend spawns in — unset means
// inherit the gateway process's directory.
Cwd string `json:"cwd,omitempty"`
// CallTimeout overrides the top-level call_timeout for this backend —
// a Go duration ("30s", "2m"). A client-supplied tighter deadline still
// wins; this bounds how long a hung backend may hold a call.
CallTimeout string `json:"call_timeout,omitempty"`
}
Backend describes one upstream MCP server.
type Degraded ¶ added in v0.0.5
type Degraded struct {
// Config is the config's real path, set by MarkDegraded.
Config string `json:"config"`
PID int `json:"pid"`
// Listen is the gateway's address, or empty for a stdio gateway.
Listen string `json:"listen,omitempty"`
// ConfigError is set while the config on disk doesn't load and the
// previous one keeps serving.
ConfigError *Fault `json:"config_error,omitempty"`
// ResolveError is set while the tools don't resolve and none serve.
ResolveError *Fault `json:"resolve_error,omitempty"`
}
Degraded is one gateway's record.
func ReportedDegraded ¶ added in v0.0.5
ReportedDegraded returns the records of running gateways for the config at cfgPath. It changes nothing on disk.
type DegradedMark ¶ added in v0.0.5
type DegradedMark struct {
// contains filtered or unexported fields
}
DegradedMark is a gateway's hold on its record.
func MarkDegraded ¶ added in v0.0.5
func MarkDegraded(cfgPath string, d Degraded) (*DegradedMark, error)
MarkDegraded writes d as this process's record for the config at cfgPath and holds the record's lock until Clear.
func (*DegradedMark) Clear ¶ added in v0.0.5
func (m *DegradedMark) Clear()
Clear removes the record, then releases and removes its lock. The record goes first: a record whose lock is free is never read as true.
func (*DegradedMark) Update ¶ added in v0.0.5
func (m *DegradedMark) Update(d Degraded) error
Update replaces the record's contents.
type File ¶
type File struct {
Listen string `json:"listen"`
Token string `json:"token"`
AuditLog string `json:"audit_log"`
Backends map[string]*Backend `json:"backends"`
// Mode selects the front-door serving mode — "stateless" (default) or
// "stateful". Stateless is the primary design (SEP-2567 sessionless +
// the 2026-07-28 spec): no Mcp-Session-Id, every request independent.
// Legacy-protocol clients still work sessionlessly there — initialize,
// tools/list, tools/call each stand alone; they cannot receive
// tools/list_changed without a held session. Modern clients can subscribe
// through subscriptions/listen. "stateful" is the opt-in compat mode for
// older clients that must hold Mcp-Session-Id.
Mode string `json:"mode,omitempty"`
// Approved is the qualified-name list ("backend__tool") that Resolve
// intersects with discovery. discovered ≠ approved: everything not on
// this list is invisible and uncallable.
Approved []string `json:"approved"`
// ApprovedSchemas binds an approval to the contract reviewed at
// approve time: qualified name → "sha256:…" of the tool's canonical
// input+output schema. If the upstream's schema changes, the approval
// lapses — the tool drops off the surface until a human re-approves
// (which pins the new schema). Approved names with no entry here are
// unbound: approvals made before schema binding keep working until
// re-approved.
ApprovedSchemas map[string]string `json:"approved_schemas,omitempty"`
// Enabled is the live-surface allowlist, third tier of the invariant:
// nil (absent) means every approved tool is enabled; a non-nil list
// means only enabled∩approved is visible. Pointer so "absent" and
// "explicitly empty" stay distinct — [] must not collapse into all.
Enabled *[]string `json:"enabled,omitempty"`
// CallTimeout bounds every upstream tool call — a Go duration,
// default "60s". A caller's tighter deadline still wins. Per-backend
// call_timeout overrides it. A hung backend can never hold a call
// forever.
CallTimeout string `json:"call_timeout,omitempty"`
// AuditMaxMB caps the audit log size in MiB — past it the log rotates
// to <audit_log>.1 (one generation kept; evidence is append-mostly and
// recent history is what introspection needs). Absent or non-positive
// means the default.
AuditMaxMB int `json:"audit_max_mb,omitempty"`
// contains filtered or unexported fields
}
File is the on-disk config document.
func Update ¶ added in v0.0.4
Update is the read-modify-write for a config file. It holds the config lock across load, fn and save, so no other toolhost writer can land in between. fn must not wait on the network: dial first, then mutate. A change that leaves the bytes as they were writes nothing.
func (*File) Approve ¶
Approve adds qualified names bound to their schema pins (name → SchemaHash of the contract reviewed; "" = unbound). Returns the names that changed: newly approved, or already-approved with a refreshed pin — the latter is how a drifted schema gets re-affirmed, and it MUST count as a change or the caller skips saving the pin. Approved names drop out of `requested` — the request has been answered.
func (*File) ApprovedSet ¶
ApprovedSet is the lookup form Resolve consumes.
func (*File) BackendToolsApproved ¶ added in v0.0.4
BackendToolsApproved returns the approved qualified names belonging to a backend's namespace — the cascade check `mcp remove` runs first.
func (*File) Disable ¶
Disable hides approved tools without un-approving them. The first disable materializes the allowlist as approved ∖ names — after that, the live surface is always explicit.
func (*File) Enable ¶
Enable adds qualified names to the live surface. No-op (nil) while no allowlist exists — without one, every approved tool is already enabled. Enabled names must be approved first; enabling is never a backdoor around approval.
func (*File) EnableAll ¶
func (f *File) EnableAll()
EnableAll clears the allowlist — every approved tool is enabled again.
func (*File) EnableOnly ¶
EnableOnly replaces the live surface with exactly the given names — the "I need just these tools" form. All must be approved.
func (*File) EnabledSet ¶
EnabledSet returns the allowlist and whether one is configured — (nil, false) means "all approved tools are enabled".
func (*File) IsApproved ¶
func (*File) IsEnabled ¶
IsEnabled reports whether a qualified tool is on the live surface: enabled (no list, or listed) AND approved.
func (*File) PruneBackendTools ¶ added in v0.0.4
PruneBackendTools drops every approved/enabled name in a backend's namespace — the explicit --prune-approvals form of mcp remove.
func (*File) RemoveBackend ¶ added in v0.0.4
RemoveBackend drops a backend entry and reports whether anything changed. Approval cleanup is the caller's decision — pruning policy silently is how envelopes leak.
func (*File) ResolvedToken ¶
ResolvedToken resolves the gateway bearer token.
func (*File) Revoke ¶
Revoke removes qualified names and their schema pins; returns those actually removed.
func (*File) Save ¶
Save writes the config back atomically (0600 — it carries the token) — tmp+rename so the serve watcher never reads a torn file. A copy that came from Load is written only if the file still holds the bytes it was read from; otherwise Save returns ErrStale and writes nothing. A File built in memory has no snapshot and replaces whatever is there. Read-modify-write callers should use Update.
type Request ¶
type Request struct {
Kind string `json:"kind"` // "tool" | "server"
Name string `json:"name"` // qualified tool name, or proposed backend name
Reason string `json:"reason,omitempty"`
At time.Time `json:"at"`
// server petitions — the proposed backend spec:
Transport string `json:"transport,omitempty"` // "stdio" | "http"
URL string `json:"url,omitempty"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
// the human's verdict:
Denied bool `json:"denied,omitempty"`
DenyReason string `json:"deny_reason,omitempty"`
}
Request is one agent-filed petition. Kind "tool" asks approval for a discovered qualified name; kind "server" proposes a whole new backend — the human materializes it into config with `toolhost requests --accept`. A denied petition stays on record so the agent sees the verdict rather than re-asking blindly; a human clears it by re-requesting or accepting.
func LoadRequests ¶ added in v0.0.4
LoadRequests reads the pending agent-request queue from the env's state dir — never the config file.
func PendingRequests ¶ added in v0.0.4
PendingRequests filters the queue to undecided petitions.