mcpserver

package
v1.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: GPL-3.0 Imports: 38 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 mcpserver serves the /mcp endpoint (docs/design/mcp.md §8, ADR-0009, ADR-0010): the Model Context Protocol over Streamable HTTP in stateless mode with JSON responses, for AI agents holding an agent token.

Every request passes, in order: a loopback check (TLS off without mcp.lan_access), the Host allowlist, an Origin check, a longer write deadline, the Bearer token verifier with its own per-client failure limiter, a per-token request rate limit and a scope check. The request is then served by an *mcp.Server built for that token, holding only the tools and prompts it may use now; servers are cached by token, tools snapshot version, tokens epoch and token info, so revocations, grant changes and redeploys show on the next request. Tool calls go through the tool service (internal/service), which re-checks permissions and validates arguments: the per-token server only decides what is advertised.

Index

Constants

View Source
const (
	ValidateFlowTool  = service.AuthorToolValidateFlow
	SaveDraftTool     = service.AuthorToolSaveDraft
	GetDraftTool      = service.AuthorToolGetDraft
	DryRunTool        = service.AuthorToolDryRun
	TestNodeTool      = service.AuthorToolTestNode
	ListNodeTypesTool = "pw_list_node_types"
	AuthorFlowPrompt  = "author_flow"
)

Names of the author tools and prompt (scope author); the service audits them under the same names.

View Source
const (
	DeployFlowTool = service.DeployToolDeployFlow
	StopFlowTool   = service.DeployToolStopFlow
)

Names of the deploy tools (scope deploy).

View Source
const (
	// MaxMessageValues bounds the JSON values and object member names of a
	// message. The largest flows the author tools take (200 nodes, 400
	// connections and their settings) need about a third of it.
	MaxMessageValues = 32 << 10
	// MaxMessageDepth bounds how deep a message's arrays and objects nest.
	MaxMessageDepth = 64
	// MaxMetaBytes bounds params._meta (progress tokens and client hints).
	MaxMetaBytes = 8 << 10
)

Bounds of a message's JSON, checked before anything decodes it (docs/design/mcp.md §8). The body limit bounds a message's bytes, not what decoding it costs: a decoded value costs from a few dozen bytes (a number) to a few hundred (an empty object becomes a Go map), each time the SDK or the endpoint decodes it (the SDK decodes params._meta twice on every request and a call's arguments once more before the tool sees them), so 1 MiB of "{}" cost over 100 MiB a request.

View Source
const (
	// DefaultRequestsPerMinute and DefaultRequestBurst bound each token's
	// requests (§8: 30 a minute, bursts of 10).
	DefaultRequestsPerMinute = 30
	DefaultRequestBurst      = 10
	// DefaultAuthFailuresPerMinute bounds failed authentications per client
	// address; past it the client gets 429 until a slot frees.
	DefaultAuthFailuresPerMinute = 10
	// DefaultMaxServers bounds the cached per-token servers.
	DefaultMaxServers = 32
	// DefaultMaxRequestBodyBytes bounds a request body. A tool call carries
	// arguments of at most 64 KiB in practice (string properties are capped
	// at 256 characters unless the admin raises maxLength, and approvals
	// refuse arguments over 64 KiB), and batches are refused, so 1 MiB
	// leaves room for long strings while keeping a Pi's memory safe from a
	// flood of large bodies (the SDK's default is 4 MiB). What decoding a
	// body costs is bounded apart (MaxMessageValues, MaxMessageDepth,
	// MaxMetaBytes).
	DefaultMaxRequestBodyBytes = 1 << 20
	// DefaultWriteDeadline covers the longest tool timeout (30 s) plus
	// margin; the server's WriteTimeout (15 s) would cut slow calls.
	DefaultWriteDeadline = 35 * time.Second
	// DefaultListTTL is the ttlMs advertised with list results (cacheScope
	// private): short, so a revoked grant soon disappears from clients.
	DefaultListTTL = 5 * time.Second
	// DefaultResultWait bounds how long pw_get_result waits for a running
	// call before answering "running" again (well inside the write
	// deadline).
	DefaultResultWait = 10 * time.Second
)

Defaults of Options.

View Source
const (
	ListFlowsTool      = service.ReadToolListFlows
	GetFlowTool        = service.ReadToolGetFlow
	ListRunsTool       = service.ReadToolListRuns
	GetRunTool         = service.ReadToolGetRun
	SystemStatusTool   = service.ReadToolSystemStatus
	DiagnoseFlowPrompt = "diagnose_flow"
)

Names of the read tools and prompt (scope read); the read views audit agent reads under the tools' names.

View Source
const (
	// DefaultAuditRetentionInterval is how often the MCP audit is pruned.
	DefaultAuditRetentionInterval = time.Hour
	// DefaultAuditMaxRows caps the ordinary audit rows kept within the
	// 30-day retention. A row holds at most ~1 KiB (a 512-byte argument
	// preview, a tool name the service caps at 128 bytes, a token name of at
	// most 64 and IDs), so ordinary rows stay within ~50 MiB on a Raspberry
	// Pi's SD card even when a token calls at its full rate (30/min) for the
	// whole period. Privileged rows are outside the cap and kept the full
	// 30 days: they are only what the admin let the token do on the device
	// (a privileged tool's run or queued approval, with the privileged flag
	// and a grant; a privileged flow's deploy or stop that reached the
	// lifecycle path, at agent deploy `all`), bounded by the tool's own
	// limits and the token's rate. Refusals are ordinary rows, so a loop of
	// refused calls or deploys cannot grow the table past the cap.
	DefaultAuditMaxRows = 50_000
)
View Source
const GetResultTool = "pw_get_result"

GetResultTool is the built-in tool that reads the result of an earlier call (scope call).

View Source
const MaxGoalChars = 2000

MaxGoalChars bounds author_flow's goal.

View Source
const MaxRawInputSchemaBytes = toolschema.MaxSchemaBytes

MaxRawInputSchemaBytes bounds a RawInput schema, as toolschema bounds the closed ones.

View Source
const Path = "/mcp"

Path is where the endpoint is mounted.

View Source
const StaticToolPrefix = "pw_"

StaticToolPrefix starts the name of every built-in tool. Flow tools may not use it (trigger-tool refuses such names), so the two never clash.

Variables

View Source
var ProtocolVersions = []string{"2026-07-28", "2025-11-25", "2025-06-18"}

ProtocolVersions are the MCP protocol versions /mcp negotiates (the ones its tests cover), newest first.

Functions

func RefusePlainHTTP

func RefusePlainHTTP(w http.ResponseWriter, r *http.Request, httpsURL string, log zerolog.Logger)

RefusePlainHTTP answers /mcp on the plain-HTTP listener while PiWorker serves HTTPS: 400 with the HTTPS URL to use, never a redirect. A client following a redirect (Go's http.Client keeps the Authorization header for the same host on another port) would keep working while sending its token in clear text on every request; refusing makes the misconfiguration fail on the first one. The token's id is logged (its secret never) so the admin knows which token to revoke.

func RunAuditRetention

func RunAuditRetention(ctx context.Context, p AuditPruner, opts RetentionOptions)

RunAuditRetention prunes the MCP audit once now, then at every interval, until ctx ends. Failures are logged and retried at the next interval.

func StructuredResult

func StructuredResult(v any) (*mcp.CallToolResult, error)

StructuredResult is the result of a built-in tool answering v: v as the structured content (wrapped as {"result": v} unless it encodes to a JSON object) and its JSON as the text block.

Types

type AuditPruner

type AuditPruner interface {
	PruneMCPAudit(now time.Time, maxRows int) (int64, error)
}

AuditPruner deletes expired MCP audit data (*storage.SQLiteStore).

type AuditRecorder

type AuditRecorder interface {
	Record(entry storage.MCPAuditEntry)
}

AuditRecorder records the agent reads the endpoint serves itself (*service.AuditWriter): pw_list_node_types and the author_flow prompt run no service, so no service audits them.

type AuthoringService

type AuthoringService interface {
	Validate(ctx context.Context, actor service.Actor, req service.ValidateRequest) (service.ValidateResult, error)
	SaveDraft(ctx context.Context, actor service.Actor, in service.DraftInput) (service.DraftResult, error)
	GetDraft(ctx context.Context, actor service.Actor, draftID string) (service.DraftView, error)
	DryRun(ctx context.Context, actor service.Actor, req service.DryRunRequest) (flow.DryRunResult, error)
	TestNode(ctx context.Context, actor service.Actor, req service.TestNodeRequest) (flow.TestNodeResult, error)
}

AuthoringService serves agent authoring (*service.Authoring): validating, drafting, dry-running and node tests, with the service's rules (scope, mcp.author_enabled, limits, redaction, audit). The endpoint only checks the shape of the arguments.

type DeployLevelReader

type DeployLevelReader interface {
	AgentDeployLevel() (storage.AgentDeployLevel, error)
}

DeployLevelReader reads the agent deploy level (*storage.SQLiteStore). Changing the level bumps the tokens epoch, which is when the endpoint reads it again.

type DeployService

type DeployService interface {
	Deploy(ctx context.Context, actor service.Actor, req service.DeployRequest) (service.DeployResult, error)
	Stop(ctx context.Context, actor service.Actor, flowID string) (service.DeployResult, error)
}

DeployService serves agent deploys (*service.Authoring): the agent deploy level, the token re-check and the editor's lifecycle path are the service's.

type Handler

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

Handler serves /mcp.

func New

func New(opts Options) (*Handler, error)

New builds the endpoint.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves an MCP request.

type NodeConfigView

type NodeConfigView struct {
	Properties map[string]NodePropertyView `json:"properties"`
	Required   []string                    `json:"required"`
}

NodeConfigView is a node type's config schema.

type NodePortView

type NodePortView struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	DataType string `json:"dataType"`
	Multiple bool   `json:"multiple"`
	Required bool   `json:"required"`
}

NodePortView is a port of a node type.

type NodePropertyView

type NodePropertyView struct {
	Type            string   `json:"type,omitempty"`
	Title           string   `json:"title,omitempty"`
	Description     string   `json:"description,omitempty"`
	Default         any      `json:"default,omitempty"`
	Enum            []string `json:"enum,omitempty"`
	Minimum         *float64 `json:"minimum,omitempty"`
	Maximum         *float64 `json:"maximum,omitempty"`
	Unit            string   `json:"unit,omitempty"`
	CaseInsensitive bool     `json:"caseInsensitive,omitempty"`
	Sensitive       bool     `json:"sensitive,omitempty"`
	AgentVisible    bool     `json:"agentVisible,omitempty"`
	Destination     bool     `json:"destination,omitempty"`
	RiskSwitch      bool     `json:"riskSwitch,omitempty"`
	Operation       bool     `json:"operation,omitempty"`
	Rate            bool     `json:"rate,omitempty"`
}

NodePropertyView is one setting of a node type, with the markers that say how PiWorker treats it (present only when true): sensitive (a credential: drafts may set only a {{secret.NAME}} reference), agentVisible (shown to agents; other values read "<redacted>"), destination (where the node sends data or connects), riskSwitch (an opt-in that widens what the node may do; agents may not turn it on), operation (what selects the action a request performs), rate (how often a trigger fires or how many messages a node lets through).

type NodeTypeList

type NodeTypeList struct {
	// Types are ordered by category (input, processing, output) and type.
	Types []NodeTypeView `json:"types"`
	// Total counts the types matching the filters, listed or not.
	Total int `json:"total"`
	// Truncated: types or documentation were left out, or documentation
	// cut, to keep the list within maxNodeTypeListBytes. Documentation a
	// list without filters omits does not count.
	Truncated bool `json:"truncated"`
}

NodeTypeList is what pw_list_node_types answers: registry metadata only, never a flow or a secret.

type NodeTypeLister

type NodeTypeLister interface {
	List() []node.NodeTypeInfo
}

NodeTypeLister lists the registered node types (*node.Registry).

type NodeTypeView

type NodeTypeView struct {
	Type        string         `json:"type"`
	Name        string         `json:"name"`
	Category    string         `json:"category"`
	Risk        node.Risk      `json:"risk"`
	Description string         `json:"description"`
	Inputs      []NodePortView `json:"inputs"`
	Outputs     []NodePortView `json:"outputs"`
	Config      NodeConfigView `json:"config"`
	// Documentation is the type's markdown documentation, cut to
	// maxNodeTypeDocBytes.
	Documentation string `json:"documentation,omitempty"`
	// DocumentationOmitted: left out of a list without filters, or to keep
	// the list small (ask for the category or the type alone).
	DocumentationOmitted bool `json:"documentationOmitted,omitempty"`
}

NodeTypeView is one node type as agents author with it.

type Options

type Options struct {
	// Tools serves the published flow tools (required).
	Tools ToolService
	// Tokens verifies Bearer tokens (required).
	Tokens TokenVerifier
	// Rejections counts the tool calls the endpoint refuses itself (flow
	// tool arguments that are not a JSON object, built-in tool arguments
	// outside the tool's schema), like the tool service counts its own
	// refusals; nil counts nothing.
	Rejections RejectionCounter
	// StaticTools and Prompts are the built-in tools and prompts besides
	// pw_get_result, which is always present.
	StaticTools []StaticTool
	Prompts     []StaticPrompt
	// AuthorEnabled is mcp.author_enabled: the built-in tools and prompts
	// of the author scope are served only when it is set.
	AuthorEnabled bool
	// DeployLevel reads the agent deploy level: the built-in tools and
	// prompts of the deploy scope are served only while it is above off
	// (read again on every tokens epoch; a failed read counts as off). nil
	// serves none.
	DeployLevel DeployLevelReader
	// TLS is set when PiWorker serves HTTPS itself. Without it only loopback
	// clients are served, unless LANAccess (mcp.lan_access).
	TLS       bool
	LANAccess bool
	// HostAllowed is the Host allowlist (api.HostGuard.Allowed); nil allows
	// every Host (the router's guard then applies).
	HostAllowed func(host string) bool
	// AllowedOrigins are browser origins accepted besides this server's own.
	AllowedOrigins []string
	// Version is reported as the server's implementation version.
	Version string
	Logger  zerolog.Logger
	Now     func() time.Time

	// Limits (0 means the default).
	RequestsPerMinute     int
	RequestBurst          int
	AuthFailuresPerMinute int
	MaxServers            int
	MaxRequestBodyBytes   int64
	WriteDeadline         time.Duration
	ListTTL               time.Duration
	ResultWait            time.Duration
}

Options configures the endpoint.

type RawInput

type RawInput struct {
	// Schema is a JSON Schema of type object, at most
	// MaxRawInputSchemaBytes.
	Schema json.RawMessage
	// MaxBytes bounds the arguments' JSON (1 to DefaultMaxRequestBodyBytes).
	MaxBytes int
	// Validate returns the problems of decoded arguments (none: valid).
	// Messages must not quote argument values.
	Validate func(args map[string]any) []toolschema.Issue
}

RawInput is the escape hatch of StaticTool for arguments outside toolschema's closed subset. Schema is advertised to clients as written; the endpoint enforces MaxBytes on the arguments' JSON as the client sent it, decodes them as every tool's (a JSON object, no duplicate names, valid UTF-8) and runs Validate before the handler. Validate must enforce at least what Schema describes (closed objects, types, bounds): the endpoint does not interpret Schema. Its refusals are invalid_arguments, counted in the rejections like every built-in tool's.

type ReadService

type ReadService interface {
	ListFlows(ctx context.Context, actor service.Actor) (service.FlowList, error)
	GetFlow(ctx context.Context, actor service.Actor, flowID string) (service.FlowView, error)
	ListRuns(ctx context.Context, actor service.Actor, flowID string, limit int, before string) (service.RunList, error)
	GetRun(ctx context.Context, actor service.Actor, flowID, runID string) (service.RunView, error)
	SystemStatus(ctx context.Context, actor service.Actor) (service.SystemStatusView, error)
	DiagnoseFlow(ctx context.Context, actor service.Actor, flowID string) (string, error)
}

ReadService serves the read views (*service.Reads): what an agent with the read scope may observe of flows, runs and the system, redacted and bounded by the service.

type RejectionCounter

type RejectionCounter interface {
	Reject(tokenID, reason string, at time.Time)
}

RejectionCounter counts refused calls per token, reason and minute (*service.AuditWriter).

type RetentionOptions

type RetentionOptions struct {
	// Interval between prunes (default DefaultAuditRetentionInterval).
	Interval time.Duration
	// Ticks, when set, replaces the interval's ticker (tests).
	Ticks <-chan time.Time
	// MaxRows is passed to PruneMCPAudit (default DefaultAuditMaxRows).
	MaxRows int
	Now     func() time.Time
	Logger  zerolog.Logger
}

RetentionOptions configures RunAuditRetention.

type StaticPrompt

type StaticPrompt struct {
	Prompt  *mcp.Prompt
	Scope   string
	Handler func(ctx context.Context, actor service.Actor, args map[string]string) (*mcp.GetPromptResult, error)
}

StaticPrompt is a built-in prompt, advertised to tokens holding Scope. Handler checks its own arguments. A returned *service.ToolError becomes a JSON-RPC invalid-params error with its message, a *jsonrpc.Error is sent as it is, and any other error is logged and answered as an internal error without details.

func AuthorPrompts

func AuthorPrompts(audit AuditRecorder) []StaticPrompt

AuthorPrompts returns the author prompt (scope author; listed only with mcp.author_enabled): author_flow{goal}, the authoring steps, audited through audit (may be nil) as prompt:author_flow without the goal (agent text).

func ReadPrompts

func ReadPrompts(reads ReadService) []StaticPrompt

ReadPrompts returns the read prompts (scope read): diagnose_flow{flowId}.

type StaticTool

type StaticTool struct {
	Name        string
	Title       string
	Description string
	// InputSchema is a JSON object schema in the closed subset of
	// internal/toolschema; clients see its compiled (canonical) form.
	// Every built-in tool uses it, except the few whose arguments are
	// flows (RawInput).
	InputSchema json.RawMessage
	// RawInput, instead of InputSchema, is the input contract of a tool
	// whose arguments do not fit the closed subset (flow-shaped arguments:
	// nested objects, free-form node settings, any JSON payload).
	RawInput *RawInput
	// OutputSchema, when set, describes the structured content of the
	// tool's successful results.
	OutputSchema json.RawMessage
	// Annotations are advertised explicitly (every hint is sent).
	Annotations flow.Annotations
	// Scope is the token scope (storage.Scope*) the tool needs.
	Scope   string
	Handler StaticToolHandler
}

StaticTool is a built-in tool (pw_*), advertised to tokens holding Scope. Its arguments are validated against InputSchema (or by RawInput) before Handler runs.

func AuthorTools

func AuthorTools(authoring AuthoringService, types NodeTypeLister, audit AuditRecorder) []StaticTool

AuthorTools returns the author tools (scope author; listed only with mcp.author_enabled): pw_validate_flow, pw_save_draft, pw_get_draft, pw_dry_run and pw_test_node serve authoring, pw_list_node_types reads types (audited through audit, which may be nil). Arguments are checked against their contracts before the service runs; the service's refusals are isError results with their codes (conflict carries error.currentVersion, a flow's problems error.flowIssues).

func DeployTools

func DeployTools(deploys DeployService) []StaticTool

DeployTools returns the deploy tools (scope deploy; listed only while the agent deploy level is above off): pw_deploy_flow{flowId, draftId?} and pw_stop_flow{flowId}.

func ReadTools

func ReadTools(reads ReadService) []StaticTool

ReadTools returns the read tools (scope read) serving reads: pw_list_flows, pw_get_flow, pw_list_runs, pw_get_run and pw_system_status. Their arguments are validated against their input schemas before the view runs; a view's *service.ToolError (forbidden, flow_not_found, run_not_found) is an isError result with its code.

type StaticToolHandler

type StaticToolHandler func(ctx context.Context, actor service.Actor, args map[string]any) (*mcp.CallToolResult, error)

StaticToolHandler serves a built-in tool. args were validated against the tool's input schema (or by its RawInput). A returned *service.ToolError becomes an isError result with its code; any other error is logged and answered as a failure without details.

type TokenVerifier

type TokenVerifier interface {
	Verify(raw string) (agentauth.TokenInfo, error)
	// VerifyCached accepts a token from the verifier's cache alone, never
	// looking one up in the store (ok false: not decided).
	VerifyCached(raw string) (info agentauth.TokenInfo, ok bool, err error)
	// KnownID reports whether id names a real (active) token, without
	// reading a token, so the failure limiter can keep real tokens apart
	// from made-up ones.
	KnownID(id string) (bool, error)
	Epoch() int64
}

TokenVerifier verifies agent tokens (*agentauth.TokenVerifier).

type ToolService

type ToolService interface {
	List(actor service.Actor) (version uint64, tools []flow.ToolInfo)
	Call(ctx context.Context, actor service.Actor, ref service.ToolRef, args map[string]any) (flow.CallResult, error)
	Result(ctx context.Context, actor service.Actor, runID string) (flow.CallResult, error)
}

ToolService is the tool service the endpoint adapts (*service.Tools).

Jump to

Keyboard shortcuts

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