mcphost

package
v0.48.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 25 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

View Source
const (
	// FilesExtension is the extension identifier.
	FilesExtension = "io.modelcontextprotocol/files"
	// ClientCapabilitiesMeta is the request _meta key under which a
	// client declares the extensions it supports.
	ClientCapabilitiesMeta = "io.modelcontextprotocol/clientCapabilities"
	// DefaultMaxInlineBytes is the maxInlineBytes advertised when
	// Config.MaxInlineBytes is zero.
	DefaultMaxInlineBytes int64 = 8 << 20
)
View Source
const MaxUploadRefBytes = 1024

MaxUploadRefBytes caps UploadTarget.Ref.

Variables

View Source
var UploadStateTTL = 30 * time.Minute

UploadStateTTL is how long a requestState stays valid.

Functions

func FileSchema added in v0.44.0

func FileSchema(desc FileInputDescriptor, description string) map[string]any

FileSchema returns the object schema for one x-mcp-file argument: the FileInput shape with the descriptor attached.

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 Call added in v0.45.0

type Call struct {
	SessionKey string
	Args       json.RawMessage
	// Files holds the x-mcp-file arguments uploaded out of band, by
	// argument name. Inline ones stay in Args (see DecodeFile).
	Files map[string]UploadedFile
}

Call is one tools/call as a CallHandler sees it.

type CallHandler added in v0.45.0

type CallHandler func(Call) (Result, error)

CallHandler is the richer form of Handler: it sees out-of-band uploads and may return download targets. Register it with ToolCall.

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

	// MaxInlineBytes is the maxInlineBytes the Host advertises for the
	// io.modelcontextprotocol/files extension (see files.go): the
	// largest total decoded size of inline file arguments it accepts in
	// one request. Zero means DefaultMaxInlineBytes. Negative switches
	// the extension off: it is not advertised, tools with x-mcp-file
	// arguments are never listed, and file arguments are refused.
	MaxInlineBytes int64
}

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

type DownloadTarget added in v0.45.0

type DownloadTarget struct {
	URL       string // absolute https URL, fetched with credentials "omit"
	Name      string // shown to the user; "file" when empty
	MimeType  string // "application/octet-stream" when empty
	Size      int64  // exact size in bytes
	Digest    string // optional sha-256, base64url without padding
	Headers   map[string]string
	ExpiresAt time.Time // zero = no expiry given
}

DownloadTarget is a file a tool hands back for the client to fetch.

type File added in v0.44.0

type File struct {
	ID       string
	Name     string // untrusted; reduce to a base name before use
	MimeType string // untrusted
	Data     []byte
}

File is a decoded, validated inline file argument.

func DecodeFile added in v0.44.0

func DecodeFile(raw json.RawMessage) (File, error)

DecodeFile decodes and validates one inline FileInput argument: id length, mimeType, a non-negative size that matches the decoded bytes, and the digest when present. A size-0 file with no data is a valid empty file. A non-empty file without data is refused here: an out-of-band file reaches a ToolCall handler as Call.Files instead.

The Host already ran this (plus maxSize, accept and the inline total) before invoking the handler; handlers call it to get the bytes.

type FileDigest added in v0.44.0

type FileDigest struct {
	Algorithm string `json:"algorithm"`
	Value     string `json:"value"` // base64url, no padding
}

FileDigest is a FileInput digest.

type FileInputDescriptor added in v0.44.0

type FileInputDescriptor struct {
	// Accept lists media types ("image/png", "image/*") or dot-prefixed
	// extensions (".pdf"). Empty accepts anything.
	Accept []string `json:"accept,omitempty"`
	// MaxSize caps each file's decoded size in bytes. Zero means no
	// per-file cap beyond the Host's maxInlineBytes.
	MaxSize int64 `json:"maxSize,omitempty"`
}

FileInputDescriptor is the value of the x-mcp-file schema keyword.

type FormField added in v0.45.0

type FormField struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

FormField is one multipart form field sent before the file part.

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) SetUploads added in v0.45.0

func (h *Host) SetUploads(p UploadProvider)

SetUploads installs the upload provider and advertises `upload` in the files extension settings. Call it before Listen. Only tools registered with ToolCall accept out-of-band files; a nil p switches uploads off.

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. A schema with a top-level x-mcp-file argument makes it a file tool; see files.go. 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.

func (*Host) ToolCall added in v0.45.0

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

ToolCall registers a tool like Tool, with a CallHandler: its file arguments may arrive out of band (Call.Files, when SetUploads is in effect) and it may return download targets (Result.Downloads).

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).

type Result added in v0.45.0

type Result struct {
	Text      string
	Downloads []DownloadTarget
}

Result is a CallHandler's success value.

type UploadForm added in v0.45.0

type UploadForm struct {
	Fields    []FormField `json:"fields,omitempty"`
	FileField string      `json:"fileField"`
}

UploadForm turns an upload into a multipart/form-data POST.

type UploadProvider added in v0.45.0

type UploadProvider interface {
	// UploadTarget mints a target for one file.
	UploadTarget(sessionKey string, spec UploadSpec) (UploadTarget, error)
	// FinishUpload confirms the client's upload of spec to the target
	// whose Ref was ref, and reports what the platform stored. It must
	// fail when nothing was uploaded.
	FinishUpload(sessionKey string, spec UploadSpec, ref string) (UploadedFile, error)
}

UploadProvider is the relay side of out-of-band uploads. sessionKey is the one mcphost resolved from the connection's token.

type UploadSpec added in v0.45.0

type UploadSpec struct {
	Tool     string // tool being called
	Param    string // x-mcp-file argument name
	FileID   string // client-chosen FileInput id
	Name     string // untrusted file name; may be empty
	MimeType string
	Size     int64  // claimed size in bytes, > 0
	Digest   string // claimed sha-256, base64url without padding; may be empty
	MaxSize  int64  // the argument's x-mcp-file maxSize; 0 = none
	Accept   []string
}

UploadSpec describes one file the client wants to upload out of band. Every field except Tool, Param, MaxSize and Accept is the client's claim and untrusted.

type UploadTarget added in v0.45.0

type UploadTarget struct {
	// URL is an absolute https URL. It is a bearer capability: make it
	// single-use and short-lived.
	URL string
	// Method is PUT (default) or POST.
	Method string
	// Headers are sent with the upload. Credential headers are refused.
	Headers map[string]string
	// Form, when set, makes the upload a multipart POST.
	Form *UploadForm
	// ExpiresAt, when non-zero, is when the target stops working.
	ExpiresAt time.Time
	// Ref is the provider's own handle for this upload (a file id, a
	// storage key). It travels inside the signed requestState and is
	// handed back to FinishUpload; at most MaxUploadRefBytes long. It is
	// readable by the client, so do not put secrets in it.
	Ref string
}

UploadTarget is where the client sends one file's bytes.

type UploadedFile added in v0.45.0

type UploadedFile struct {
	Ref      string // the provider's handle, as returned by FinishUpload
	Name     string // untrusted; reduce to a base name before use
	MimeType string // untrusted
	Size     int64  // the size the platform actually stored
}

UploadedFile is a file the platform holds after an out-of-band upload.

Jump to

Keyboard shortcuts

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