mcphost

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package mcphost implements a generic, self-hosted MCP server that a consumer advertises to an ACP agent as a stdio MCP server. It exposes consumer-registered tools to the agent while running the MCP JSON-RPC state machine in the consumer's own process, reached over a per-process unix socket with per-session token authentication.

Transport design (deliberately minimal, stdlib-only, no MCP SDK):

  • The agent spawns a redirector subprocess over MCP **stdio** (newline-delimited JSON-RPC 2.0). Stdio needs no port and no capability negotiation, so it works on every deployment.
  • That subprocess is a **thin reconnecting proxy** (see RunRedir): it dials the host's unix socket, writes one newline-terminated preamble line `{"token":"<tok>"}`, then forwards lines in both directions. It knows just enough MCP to replay `initialize` after a reconnect.
  • The Host owns the MCP state machine: it runs the loop once per accepted socket connection, after the preamble token is resolved to a session key. The session key is bound server-side from the token, so a client can never spoof which session it attaches to.

Surviving a consumer re-exec

A consumer that hot-reloads by syscall.Exec'ing its own new binary in place (same PID) tears the Host down and builds a fresh one, while the agent's redirector subprocess — a child of the AGENT, not of the consumer — keeps running untouched. Three things make that seamless, and a consumer that reloads MUST use all three:

  • Config.Dir pins the socket to a stable path instead of a fresh MkdirTemp one, so the successor binds where the redirector is already pointed.
  • ExportTokens/SeedTokens carry the sessionKey→token registry across the exec through the ENVIRONMENT (never disk — that would create a new secret at rest), so the successor still recognises tokens the predecessor minted.
  • CloseForExec shuts the predecessor down without unlinking the socket or removing a caller-supplied directory; plain Close is the real-shutdown path that cleans up.

The redirector rides out the gap by redialling with backoff and replaying `initialize`, because the successor's per-connection MCP state is gone. Nothing is required of consumers that do not reload: every one of these is additive and off by default.

Security: each ACP session is minted a fresh random token bound to its session key in a registry. Only a same-uid process holding that token (delivered via the spawned subprocess's env) can attach, and only to the one session the token maps to. The socket lives in a private 0700 directory and the socket file itself is chmod'd 0600.

mcphost contains zero consumer-specific logic: tool names, schemas, and behaviour are all supplied by the consumer via Host.Tool.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MaybeRunRedir

func MaybeRunRedir(cfg RedirConfig) (handled bool, err error)

MaybeRunRedir inspects os.Args: if os.Args[1] matches the configured subcommand or one of its aliases, it runs the redirector and returns handled=true with the run result. Otherwise it returns handled=false and the consumer continues normal startup. Call it early in main.

func RunRedir

func RunRedir(cfg RedirConfig) error

RunRedir is the redirector entrypoint. It reads the socket path and token from the env the parent set, dials the socket, and proxies MCP JSON-RPC lines between the agent's stdio and the host, reconnecting across a host restart. See redirect for the proxy's semantics.

Types

type Config

type Config struct {
	// Dir, when non-empty, is a FIXED directory the Host uses for its
	// socket — typically one under the consumer's StateDir. It is created
	// if missing and tightened to 0700, and it is NEVER removed by Close:
	// the Host did not create it in the general case and the whole point
	// of a fixed path is that it outlives the process.
	//
	// Set this if the consumer re-execs itself in place and needs the
	// socket path to be stable across the exec. Leave it empty (the
	// default) to get a fresh private MkdirTemp directory under BaseDir,
	// which Close does remove.
	Dir string
	// BaseDir is the directory under which the private socket directory is
	// created. Ignored when Dir is set. Defaults to $XDG_RUNTIME_DIR, then
	// os.TempDir().
	BaseDir string
	// DirPrefix is the MkdirTemp prefix for the private socket directory.
	// Ignored when Dir is set. Defaults to "mcphost-".
	DirPrefix string
	// SocketName is the socket file name inside the socket directory.
	// Defaults to "mcp.sock".
	SocketName string

	// RedirCommand is the executable the agent spawns for the redirector.
	// Defaults to os.Executable().
	RedirCommand string
	// RedirSubcommand is the argv token the redirector binary dispatches
	// on (e.g. "mcp-serve"). Required.
	RedirSubcommand string

	// ServerName is the MCP server name advertised to the agent in the
	// session/new McpServer config (e.g. "poe"). Required.
	ServerName string
	// ServerInfoName is the serverInfo.name returned from initialize.
	// Defaults to ServerName.
	ServerInfoName string
	// ServerInfoVersion is the serverInfo.version returned from
	// initialize. Defaults to "1".
	ServerInfoVersion string

	// EnvSocket / EnvToken are the env var names carrying the socket path
	// and per-session token to the spawned redirector. Required.
	EnvSocket string
	EnvToken  string
}

Config configures a Host. Zero-value fields fall back to the documented defaults; RedirSubcommand, ServerName, EnvSocket and EnvToken are required.

type Handler

type Handler func(sessionKey string, args json.RawMessage) (string, error)

Handler implements one registered tool. It receives the session key resolved server-side from the connection's preamble token (never client-supplied, so it cannot be spoofed) plus the raw JSON arguments object from the tools/call request. It returns the success text shown to the agent, or an error whose message is surfaced as an MCP tool error (isError). Argument decoding and validation are the handler's responsibility.

type Host

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

Host owns the unix socket, the token→sessionKey registry, the set of registered tools, and the accept loop that runs the MCP JSON-RPC loop over each accepted connection.

func New

func New(cfg Config) (*Host, error)

New creates a Host: it validates the config, prepares the private 0700 socket directory, and computes the socket path. It does not bind the socket yet — register tools with Tool (and, on a reload, seed the token registry with SeedTokens), then call Listen.

func (*Host) Close

func (h *Host) Close() error

Close performs a real shutdown: it stops accepting, drops live connections, waits for in-flight handlers, unlinks the socket, and removes the socket directory if this Host created it. A directory supplied via Config.Dir is left alone.

func (*Host) CloseForExec added in v0.13.0

func (h *Host) CloseForExec() error

CloseForExec is the reload counterpart of Close: it stops accepting, drops live connections and waits for in-flight handlers, but leaves the socket file and its directory in place so the successor process binds the same path the agents' redirectors are already pointed at.

Use it immediately before syscall.Exec, having first captured ExportTokens for the successor's environment. Redirectors see their connection drop and redial with backoff, so the gap is invisible as long as the successor binds promptly.

func (*Host) ExportTokens added in v0.13.0

func (h *Host) ExportTokens() string

ExportTokens serialises the sessionKey→token registry into an opaque, env-safe blob (base64 of JSON, no padding, no shell metacharacters).

It exists for one purpose: a consumer that re-execs itself in place can hand the blob to its successor in an environment variable, so tokens already delivered to running agents keep working. Pass it to SeedTokens on the successor, before Listen.

The blob is a bearer credential for every live session. Put it in the environment of the process you are becoming and nowhere else — in particular do NOT write it to a file, which would create a new secret at rest for no reason. An empty registry still yields a non-empty blob.

func (*Host) Listen

func (h *Host) Listen() error

Listen binds the unix socket, tightens it to 0600, and starts accepting connections. Call Close (real shutdown) or CloseForExec (reload) to stop.

A socket file already sitting at the path is dealt with first. It is stale in both of the cases we care about: after a same-PID exec the previous holder WAS this very process and is gone, and after a crash nobody is listening — so unlinking it is correct rather than racy. The case we must not get wrong is a genuinely live holder (a second consumer instance pointed at the same Config.Dir), so we dial the socket first and refuse to steal the path if anything answers.

func (*Host) SeedTokens added in v0.13.0

func (h *Host) SeedTokens(blob string) error

SeedTokens restores a registry exported by a predecessor's ExportTokens, merging it into this Host's registry. Call it after New and before Listen.

An empty blob is a no-op returning nil, so a consumer can pass its reload env var through unconditionally on a cold start. A malformed or future-versioned blob is an error: silently starting with no tokens is exactly the failure this feature exists to prevent, so the consumer gets to decide (mint fresh sessions, or refuse to come up).

func (*Host) ServerConfigForSession

func (h *Host) ServerConfigForSession(sessionKey string) []acp.McpServer

ServerConfigForSession mints a fresh token bound to sessionKey and returns the acp McpServer(s) to advertise for that session's session/new. The server is a Stdio McpServer whose Command is the configured redirector binary, Args the redirector subcommand, and Env carries the socket path and token. Any previous token for the same session key is invalidated.

func (*Host) SocketPath

func (h *Host) SocketPath() string

SocketPath returns the unix socket path (known before Listen).

func (*Host) Tool

func (h *Host) Tool(name, description string, inputSchema map[string]any, handler Handler)

Tool registers a tool by name with its JSON input schema and handler. Registration order is preserved in tools/list. Registering the same name twice replaces the earlier entry in place. Not safe to call concurrently with the accept loop; register all tools before Listen.

type RedirConfig

type RedirConfig struct {
	// Subcommand is the primary argv token the redirector dispatches on.
	Subcommand string
	// Aliases are additional accepted argv tokens (e.g. a deprecated
	// legacy name).
	Aliases []string
	// EnvSocket / EnvToken are the env var names carrying the socket path
	// and token.
	EnvSocket string
	EnvToken  string
}

RedirConfig configures the redirector entrypoint. Subcommand and the env var names must match the Host that spawned it (they run in the same consumer binary).

Jump to

Keyboard shortcuts

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