mcpserver

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 24 Imported by: 1 module, 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 mcpserver exposes a Runefile's non-private tasks to AI agents and IDEs as Model Context Protocol tools. Tools are run through the SAME engine the CLI uses (FR-026); secrets never appear in any tool name, description, schema, or result (FR-029, Principle VII). It is a public package so it can be embedded.

Index

Constants

View Source
const (
	AuditCompleted        = "completed"         // the task ran and exited 0
	AuditFailed           = "failed"            // the task ran and exited non-zero
	AuditRefused          = "refused"           // a policy or a missing approval stopped it
	AuditInvalidArguments = "invalid-arguments" // the arguments did not fit the task
	AuditUnknownTool      = "unknown-tool"      // no task has the name
	AuditCancelled        = "cancelled"         // the call was cancelled
	AuditTimedOut         = "timed-out"         // an approval or the call ran out of time
	AuditError            = "error"             // anything else that stopped it
)

The outcomes of a tool call.

View Source
const (
	AuditKindProtocol   = "protocol"
	AuditKindValidation = "validation"
	AuditKindPolicy     = "policy"
	// AuditKindSandbox is recorded by an engine that refuses a call because
	// no sandbox can confine it (spec 053).
	AuditKindSandbox  = "sandbox"
	AuditKindApproval = "approval"
	AuditKindInternal = "internal"
)

The kinds of error that stop a call before a task runs.

View Source
const (
	AuditPlanStored  = "stored"
	AuditPlanApplied = "applied"
)

The roles of a plan in a call.

View Source
const (
	AuditDecisionApproved  = "approved"
	AuditDecisionDeclined  = "declined"
	AuditDecisionDismissed = "dismissed"
	AuditDecisionNotGiven  = "not-given"
	AuditDecisionTimedOut  = "timed-out"
	AuditDecisionNoAnswer  = "no-answer"
	AuditDecisionCancelled = "cancelled"
	AuditDecisionChanged   = "runefile-changed"
	AuditDecisionCannotAsk = "cannot-ask"
)

The decisions about a call that needed approval.

View Source
const (
	DefaultOutputLimit = 64 << 10
	MinOutputLimit     = 1 << 10
	MaxOutputLimit     = 1 << 30
)

Bounds of the output limit: the bytes of each of stdout and stderr that a tool result carries, truncation marker included.

View Source
const DefaultApprovalTimeout = 5 * time.Minute

DefaultApprovalTimeout is how long an approval request waits when Options.ApprovalTimeout is not set.

Variables

This section is empty.

Functions

func SummaryLines added in v0.10.0

func SummaryLines(summary string, head, tail int) string

SummaryLines renders a plan's summary for a person: each line indented by two spaces with characters that are not printable escaped, and " (empty)" for a summary with no text. A rendering longer than head+tail bytes shows the lines that fit in head, a mark with the number of rendered bytes left out, and the lines that fit in tail. A line longer than its share is cut inside the line. The result does not end with a line break.

Types

type ApprovalArg added in v0.10.0

type ApprovalArg struct {
	Name   string
	Values []string
}

ApprovalArg is one parameter and what it is bound to: one value, or a variadic's elements, which may be none.

type ApprovalEngine added in v0.10.0

type ApprovalEngine interface {
	// CallApproved prepares the call as CallLists would, without running
	// anything, and calls approve with what the person must see. When
	// approve returns an error, CallApproved runs nothing and returns that
	// error unchanged. When it returns nil, CallApproved runs the call once,
	// with the [confirm] gate of exactly the tasks named in tasks passed for
	// this run only. It must not approve any other task, and must not keep
	// the approval after it returns.
	CallApproved(ctx context.Context, name string, args map[string]string,
		lists map[string][]string, tasks []string,
		approve func(context.Context, ApprovalRequest) error) (Result, error)
}

ApprovalEngine is an optional Engine extension. An engine that implements it can run a call a person approved through the client (spec 049).

type ApprovalRequest added in v0.10.0

type ApprovalRequest struct {
	// Args are the called task's parameters with the values it will run
	// with, defaults included, in declaration order.
	Args []ApprovalArg
	// Confirmations give the confirmation message of each task named in
	// CallApproved's tasks. A task with no entry is shown with a default
	// question.
	Confirmations []Confirmation
	// Plan describes the stored plan the call would apply. The engine of a
	// task with AppliesPlan sets it. Nil for every other call.
	Plan *PlanApproval
}

ApprovalRequest is what an engine reports about a call that needs approval. Every string must already be masked: this package escapes and cuts them but knows no secret.

type AuditApproval added in v0.10.0

type AuditApproval struct {
	Asked    bool // whether a request was sent to the client
	Decision string
	Tasks    []string // the tasks the request covered
}

AuditApproval is the decision about a call that needed approval.

type AuditArg added in v0.10.0

type AuditArg struct {
	Name     string
	Values   []string
	Variadic bool
}

AuditArg is one parameter and what the task was bound to.

type AuditAuthFailure added in v0.10.0

type AuditAuthFailure struct {
	Time       time.Time
	Remote     string
	Suppressed int // failures not reported since the last one
}

AuditAuthFailure is a request refused for its bearer token. Nothing the request asserted about itself is in it.

type AuditCall added in v0.10.0

type AuditCall struct {
	ID       string    // unique invocation id, 16 hex digits
	Start    time.Time // carries the monotonic reading
	Session  AuditSession
	Tool     string // the name the call asked for
	Task     string // the task of that tool; "" for an unknown tool
	Supplied any    // decoded arguments, redacted and bounded; nil when none
	Identity AuditIdentity
}

AuditCall is what is known about a tool call when it starts.

type AuditEnd added in v0.10.0

type AuditEnd struct {
	Time     time.Time
	Duration time.Duration
	Outcome  string
	// ExitCode is nil unless a run produced one. A refused call has none.
	ExitCode  *int
	ErrorKind string // "" when a task ran
	Error     string // redacted and bounded
	Effective []AuditArg
	Approval  *AuditApproval
	Grants    []string
	Plan      *AuditPlan
}

AuditEnd is how a tool call ended.

type AuditEngine added in v0.10.0

type AuditEngine interface {
	// AuditIdentity reports the project identity now.
	AuditIdentity(ctx context.Context) AuditIdentity
	// Redact masks the engine's secrets in s.
	Redact(s string) string
}

AuditEngine is an optional Engine extension. The server asks the engine of the load a call runs against, so the answers belong to that load.

type AuditIdentity added in v0.10.0

type AuditIdentity struct {
	Runefile         string
	DefinitionDigest string // hex SHA-256
	ConfigDigest     string // hex SHA-256
	GitState         string // "commit", "unborn", "none" or "unavailable"
	GitCommit        string
	GitDirty         *bool // nil when git did not say
}

AuditIdentity is what a call ran against.

type AuditPlan added in v0.10.0

type AuditPlan struct{ Role, ID, Digest string }

AuditPlan is the stored plan a call made or applied.

type AuditRequest added in v0.10.0

type AuditRequest struct {
	Time     time.Time
	Duration time.Duration
	Session  AuditSession
	Method   string
	Failed   bool
	Error    string // redacted and bounded; "" when it succeeded
}

AuditRequest is a handled request that is not a tool call.

type AuditSession added in v0.10.0

type AuditSession struct {
	// ID is derived from the server and the protocol session. It is never
	// the protocol's own session id, which a client presents as a handle.
	ID        string
	Transport string // "stdio" or "http"
	Auth      string // "process" or "bearer-token"
	// ClientName and ClientVersion are what the client reported in the
	// handshake. They are attribution, not a verified identity.
	ClientName    string
	ClientVersion string
}

AuditSession is the session a request arrived on.

type Auditor added in v0.10.0

type Auditor interface {
	// CallStarted records the start of a tool call. When it returns an
	// error the call is refused: nothing runs, and the error's text is the
	// tool result.
	CallStarted(ctx context.Context, call AuditCall) error
	// CallEnded records how the call ended. When it returns an error the
	// result of the call is unchanged, and one text block that carries the
	// error's text is added to it.
	CallEnded(ctx context.Context, call AuditCall, end AuditEnd) error
	// Request records a handled request that is not a tool call. A failure
	// to record it is the Auditor's to report: the client is served.
	Request(ctx context.Context, req AuditRequest)
	// AuthFailed records a request refused for its bearer token.
	AuthFailed(ctx context.Context, failure AuditAuthFailure)
}

Auditor records what a server is asked to do. Every value it receives is already redacted and bounded. It is called from many goroutines.

type CallAudit added in v0.10.0

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

CallAudit is the record of the call a context belongs to. An engine uses it to add what only it knows. Every method is safe on a nil receiver, so an engine need not check whether the server records.

func AuditFromContext added in v0.10.0

func AuditFromContext(ctx context.Context) *CallAudit

AuditFromContext returns the record of the tool call ctx belongs to, or nil when the server records nothing.

func (*CallAudit) ID added in v0.10.0

func (c *CallAudit) ID() string

ID is the invocation id of the call, or "" when nothing is recorded.

func (*CallAudit) SetEffective added in v0.10.0

func (c *CallAudit) SetEffective(args []AuditArg)

SetEffective records the arguments the task was bound to. The values must already be masked. A value of a secret-named parameter is replaced whatever it holds, and long values and long lists are cut.

func (*CallAudit) SetErrorKind added in v0.10.0

func (c *CallAudit) SetErrorKind(kind string)

SetErrorKind records why the engine ran nothing: AuditKindValidation or AuditKindPolicy. The first kind recorded for a call stays.

func (*CallAudit) SetPlan added in v0.10.0

func (c *CallAudit) SetPlan(role, id, digest string)

SetPlan records the stored plan the call made (AuditPlanStored) or applied (AuditPlanApplied).

type Change added in v0.9.0

type Change struct{ Added, Removed, Changed int }

Change counts what a Replace did to the tool list.

type Confirmation added in v0.10.0

type Confirmation struct{ Task, Message string }

Confirmation is one destructive task and the message its author wrote.

type Engine

type Engine interface {
	// Tasks returns the exposable (non-private) tasks with their metadata.
	Tasks() []TaskInfo
	// Call runs a task by display name with string arguments, capturing output.
	Call(ctx context.Context, name string, args map[string]string) (Result, error)
}

Engine is the host the MCP server runs tasks against. The CLI implements it.

type HTTPConfig

type HTTPConfig struct {
	Addr  string // e.g. 127.0.0.1:7777
	Token string // required bearer token
	// Warn, when set, is called once with a one-line message when the
	// transport has bound an address that is not loopback: without TLS the
	// bearer token then crosses the network in cleartext. It is called before
	// any request is served, on the goroutine that started the transport.
	Warn func(message string)
}

HTTPConfig configures the opt-in Streamable HTTP transport.

type ListEngine added in v0.7.0

type ListEngine interface {
	CallLists(ctx context.Context, name string, args map[string]string, lists map[string][]string) (Result, error)
}

ListEngine is an optional Engine extension. When the engine implements it, array arguments reach it with their elements intact (spec 030); a plain string for a variadic is one element, or none when empty. args still holds every value, arrays joined by single spaces, exactly as Call receives it.

type Options

type Options struct {
	// AllowDestructive names the destructive ([confirm]) tasks that may be
	// called or run. A call is refused before the engine runs when the task
	// itself, or any task in its DestructiveReach, is destructive and not named
	// here, unless AskApproval puts the call to the person at the client.
	// There is no value that permits all of them. The Engine must still
	// approve the confirmation of exactly these tasks, wherever a run reaches
	// them; the rune CLI adapter does.
	AllowDestructive []string
	// AllowDestructiveFlag is the command-line flag that sets AllowDestructive,
	// such as "--allow-destructive". When set, a destructive refusal tells the
	// caller to add the task to it. Leave it empty where no grant is possible,
	// such as the endpoint of a rune agent task: the refusal then offers no
	// remedy.
	AllowDestructiveFlag string
	// AskApproval asks the person at the client to approve a call that can run
	// a destructive task AllowDestructive does not name, when the client stated
	// MCP form elicitation and the Engine is an ApprovalEngine. The call runs
	// once only on an explicit yes. Without both, and when this is false, such
	// a call is refused.
	AskApproval bool
	// ApprovalTimeout is how long an approval request waits for an answer.
	// Zero or less means DefaultApprovalTimeout.
	ApprovalTimeout time.Duration
	// RunCommand is the command a person runs a task of this server with,
	// such as "rune" or "rune -f /repo/Runefile". When set, the refusal given
	// to a client that cannot be asked, and the result of a request that was
	// not approved, say to run it with the called task's name.
	RunCommand string
	// AllowList, when non-empty, exposes only these tasks as tools. A task
	// outside it is not listed and cannot be called. It never adds a task the
	// Engine does not offer.
	AllowList []string
	// DenyList names tasks that are not exposed as tools, whether or not
	// AllowList names them.
	DenyList []string
	// OutputLimit caps the bytes of Result.Stdout and of Result.Stderr that a
	// tool result carries, marker included. A result carries each stream
	// twice, in its text and in its structured content (spec 044), and the
	// cap holds for each. Zero or less means DefaultOutputLimit. Other values
	// are raised to MinOutputLimit or lowered to MaxOutputLimit.
	OutputLimit int
	// Version reported to clients.
	Version string
	// Instructions, when non-empty, is delivered to clients as the MCP
	// server instructions in the initialize result. Rune uses it for the
	// [context] hook's project-health text (spec 021 FR-002). It must
	// already be masked; this package never processes it.
	Instructions string
	// Reloadable says the server's tasks may be replaced with Replace. The
	// server then states the tools capability with listChanged from the
	// start, even with no tool.
	Reloadable bool
	// Audit, when set, is told about every request the server handles. A
	// tool call is reported before anything of it runs, and again when it
	// ends (spec 052). Nil records nothing.
	Audit Auditor
}

Options configures authorization for the server.

type OutputBuffer added in v0.9.0

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

OutputBuffer is an io.Writer that keeps the beginning and the end of what is written to it and never holds more than its limit in bytes. It is safe for concurrent use. The zero value has DefaultOutputLimit.

func NewOutputBuffer added in v0.9.0

func NewOutputBuffer(limit int) *OutputBuffer

NewOutputBuffer returns a buffer with the given limit, adjusted as Options.OutputLimit is.

func (*OutputBuffer) String added in v0.9.0

func (b *OutputBuffer) String() string

String returns everything written when it is within the limit. Otherwise it returns the beginning, a "[truncated N bytes]" line, and the end, at most limit bytes in all.

func (*OutputBuffer) Write added in v0.9.0

func (b *OutputBuffer) Write(p []byte) (int, error)

Write keeps what fits and drops the rest. It always returns len(p), nil.

type ParamInfo

type ParamInfo struct {
	Name     string
	Required bool
	Variadic bool
	// Kind is the declared constraint kind: "", "string", "number", "boolean",
	// "path", or "enum". "" means unannotated and produces the pre-023 schema
	// byte-for-byte (spec 023).
	Kind string
	// Enum is the closed value list when Kind is "enum", in source order.
	Enum []string
	// Description is the author's [param-doc] text for this parameter.
	Description string
	// AgentValues, when not empty, lists the only values an agent may pass for
	// this parameter. The tool's schema enumerates them in place of Enum, and
	// the tool's description states them. The server does not refuse a call by
	// them: the Engine must, because only it knows the value a default gives.
	// Not for a variadic parameter.
	AgentValues []string
}

ParamInfo describes a task parameter for input-schema derivation.

type PlanApproval added in v0.10.0

type PlanApproval struct {
	ID      string // the plan's id
	Task    string // the task that made it
	Created string // RFC 3339, UTC
	Digest  string // hex SHA-256 of the artifact
	Size    int64  // bytes of the artifact
	Summary string // the stored summary, in full; the server cuts it
	// Notes are shown above the summary, one line each, after "Note: ".
	Notes []string
}

PlanApproval is what a person is shown about a plan (spec 051). Every string must already be masked: this package escapes and cuts them but knows no secret.

type Result

type Result struct {
	// Stdout and Stderr must already be masked by the engine: this package
	// only caps them, and every tool's output schema tells clients they hold
	// no secret (spec 044).
	Stdout   string
	Stderr   string
	ExitCode int
	// FixSuggestion is the captured output of the task's || failure hooks
	// (spec 022). Like Options.Instructions, it must already be masked and
	// size-capped by the engine; this package never processes it, only
	// renders it as a delimited section after the exit marker and returns it
	// as the fixSuggestion field of the structured content (spec 044). Empty
	// means no section and no field.
	FixSuggestion string
}

Result is the outcome of running a task on behalf of an agent.

type Server

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

Server wraps an mcp.Server built from a Runefile's tasks.

func New

func New(engine Engine, opts Options) *Server

New builds an MCP server exposing engine's tasks as tools, except those opts.AllowList and opts.DenyList hide.

func (*Server) Exposure added in v0.9.0

func (s *Server) Exposure() (exposed, exposable int)

Exposure reports how many tasks are exposed as tools and how many the Engine offered.

func (*Server) MCP

func (s *Server) MCP() *mcp.Server

MCP returns the underlying mcp.Server (for transports/tests).

func (*Server) Replace added in v0.9.0

func (s *Server) Replace(engine Engine, outputLimit int) Change

Replace makes engine the server's engine and its tasks the server's tools, under the Options given to New. outputLimit is as Options.OutputLimit. Calls in progress finish on the engine they started with. Connected clients are notified when the tool list differs. Safe for concurrent use.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(ctx context.Context, cfg HTTPConfig) error

ServeHTTP starts the Streamable HTTP transport. It binds the configured address (localhost by default) and requires a bearer token before any list/call (SC-010). An address that is not loopback is bound as asked, not refused: the transport has no TLS, so the token then crosses the network in cleartext, and cfg.Warn is told.

func (*Server) ServeStdio

func (s *Server) ServeStdio(ctx context.Context) error

ServeStdio runs the MCP server over stdio (always available, auth inherited from the local process/session).

func (*Server) SetInstructions added in v0.9.0

func (s *Server) SetInstructions(text string)

SetInstructions sets the instructions that sessions started from now on receive. It must already be masked, as Options.Instructions.

func (*Server) StartHTTP

func (s *Server) StartHTTP(cfg HTTPConfig) (addr string, stop func(), err error)

StartHTTP binds and serves the HTTP transport in a background goroutine, returning the bound address and a stop function. Used by the (agent) executor to expose project tasks to the agent it drives.

type TaskInfo

type TaskInfo struct {
	Name   string // display name (namespaced mod::task becomes mod__task as a tool)
	Doc    string
	Params []ParamInfo
	// Destructive marks the task itself destructive. A call is refused unless
	// the task is granted or, with Options.AskApproval, the person at the
	// client approves the call. The tool advertises DestructiveHint.
	Destructive bool
	// DestructiveReach names the destructive tasks a run of this task can
	// reach through its dependencies and hooks: each once, not the task
	// itself, in the order a run first reaches them. A call is refused unless
	// every one is granted or, with Options.AskApproval, named in an approval
	// the person gives for the call. A non-empty list sets DestructiveHint. Nil
	// leaves the engine alone to decline such a task when a run reaches it.
	DestructiveReach []string
	// Network says the task, or anything a run of it can reach, uses the
	// network. The tool advertises OpenWorldHint.
	Network bool
	// ReadOnly says the task declares itself read-only. The tool advertises
	// ReadOnlyHint. A descriptor that leaves it false makes no read-only claim.
	ReadOnly bool
	// Returns is the task's [returns] outcome description (spec 023 US3),
	// composed into the tool description as a "Returns:" trailer so agents can
	// verify results against it. Like Doc and Instructions, it must already be
	// masked and size-capped by the engine; this package never processes it.
	Returns string
	// AppliesPlan, when not empty, names the task whose stored plan this task
	// applies (spec 051). The tool is advertised as destructive and says so in
	// its description. Every call is put to the person at the client through
	// the ApprovalEngine, whatever Options.AllowDestructive names: a grant
	// does not approve a plan. Without Options.AskApproval, an ApprovalEngine
	// and a client that can show a form, the call is refused.
	AppliesPlan string
}

TaskInfo is the agent-facing view of a task. Private tasks are never included. Params lists the only argument names a call may use: a call naming any other is refused before the engine runs (spec 032).

Jump to

Keyboard shortcuts

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