config

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	RequestTool   = "tool"
	RequestServer = "server"
)

Request kinds.

View Source
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"
)
View Source
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.

View Source
const SharedConfigPath = ".toolhost/toolhost.json"

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

View Source
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

func AppendServerRequest(cfgPath string, f *File, r Request) error

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

func CheckServerSpec(r Request) error

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

func DefaultPath(explicit string) string

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

func DeniedSet(reqs []Request) map[string]string

DeniedSet is the lookup form — name → deny reason, for the catalog's denied mark.

func DenyRequest added in v0.0.4

func DenyRequest(cfgPath, name, reason string) error

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

func ProjectConfigPath(dir string) string

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

func ProjectKey(dir string) string

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

func RemoveAnsweredRequests(cfgPath string, approved map[string]bool)

RemoveAnsweredRequests drops queue entries whose names are now approved — an approval is the answer to the request.

func RemoveRequest added in v0.0.4

func RemoveRequest(cfgPath, name string) error

RemoveRequest drops a queue entry — the cleanup after --accept or an explicit dismissal.

func RequestSet added in v0.0.4

func RequestSet(reqs []Request) map[string]bool

RequestSet is the lookup form — name → pending (undecided) request.

func RequestsPath added in v0.0.4

func RequestsPath(cfgPath string) string

RequestsPath is the queue file for the environment cfgPath resolves to.

func ResolveEnv

func ResolveEnv(s string) (string, error)

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

func SaveRequests(cfgPath string, reqs []Request) error

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

func StateDir(cfgPath string) string

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

func UpdateRequests(cfgPath string, fn func([]Request) ([]Request, error)) error

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.

func (*Backend) Resolved

func (b *Backend) Resolved() (*Backend, error)

Resolved returns a copy of the backend with every "env:" reference in headers and auth fields resolved. The receiver is unchanged — the file's in-memory shape keeps references, never secrets.

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 Load

func Load(path string) (*File, error)

func Update added in v0.0.4

func Update(path string, fn func(*File) error) (*File, error)

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

func (f *File) Approve(pins map[string]string) ([]string, error)

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

func (f *File) ApprovedSet() map[string]bool

ApprovedSet is the lookup form Resolve consumes.

func (*File) BackendToolsApproved added in v0.0.4

func (f *File) BackendToolsApproved(name string) []string

BackendToolsApproved returns the approved qualified names belonging to a backend's namespace — the cascade check `mcp remove` runs first.

func (*File) Disable

func (f *File) Disable(names ...string) ([]string, error)

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

func (f *File) Enable(names ...string) ([]string, error)

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

func (f *File) EnableOnly(names ...string) ([]string, error)

EnableOnly replaces the live surface with exactly the given names — the "I need just these tools" form. All must be approved.

func (*File) EnabledSet

func (f *File) EnabledSet() (map[string]bool, bool)

EnabledSet returns the allowlist and whether one is configured — (nil, false) means "all approved tools are enabled".

func (*File) IsApproved

func (f *File) IsApproved(qualified string) bool

func (*File) IsEnabled

func (f *File) IsEnabled(qualified string) bool

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

func (f *File) PruneBackendTools(name string) []string

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

func (f *File) RemoveBackend(name string) bool

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

func (f *File) ResolvedToken() (string, error)

ResolvedToken resolves the gateway bearer token.

func (*File) Revoke

func (f *File) Revoke(names ...string) []string

Revoke removes qualified names and their schema pins; returns those actually removed.

func (*File) Save

func (f *File) Save(path string) error

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.

func (*File) SetBackend added in v0.0.4

func (f *File) SetBackend(name string, b *Backend) error

SetBackend inserts or replaces one backend after validation — the `mcp add`/`requests --accept` write path. Callers Save afterwards.

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

func LoadRequests(cfgPath string) ([]Request, error)

LoadRequests reads the pending agent-request queue from the env's state dir — never the config file.

func PendingRequests added in v0.0.4

func PendingRequests(reqs []Request) []Request

PendingRequests filters the queue to undecided petitions.

Jump to

Keyboard shortcuts

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