Documentation
¶
Overview ¶
Package tool is the only way providers expose MCP tools.
Add wraps every handler with the same guard rails: scope check, timeout, output redaction and truncation, and an audit record. Providers return plain text and never touch mcp.CallToolResult themselves.
Index ¶
- Constants
- Variables
- func Add[In any](s *mcp.Server, env *Env, spec Spec, h Handler[In])
- func AddWrite[In WriteInput](s *mcp.Server, env *Env, spec WriteSpec, h WriteHandler[In])
- func Denied(format string, args ...any) error
- func SplitUndo(text string) (result, undoURL string)
- func WithCheckSink(ctx context.Context, sink func(Check)) context.Context
- type Approval
- type ApprovalResolver
- type ApprovalResult
- type Caller
- type Check
- type ConfirmRequest
- type Confirmer
- type Direct
- func (d *Direct) Plan(ctx context.Context, c Caller, raw json.RawMessage) (Plan, string, error)
- func (d *Direct) Run(ctx context.Context, c Caller, raw json.RawMessage, approved string) (string, error)
- func (d *Direct) ValidateLink(ctx context.Context, c Caller, raw json.RawMessage) (Plan, string, error)
- type Env
- type Handler
- type Health
- type InputRequired
- type Plan
- type Policy
- type Spec
- type Undo
- type WriteHandler
- type WriteInput
- type WriteSpec
Constants ¶
const UndoPrefix = "undo_url: "
UndoPrefix starts the last line of a write result that offers an undo link.
Variables ¶
var ErrApprovalPending = errors.New("approval pending")
ErrApprovalPending means a human has been asked but has not decided yet.
var ErrDenied = errors.New("denied by policy")
ErrDenied marks policy refusals (allowlist misses etc.) so that they are audited as "denied" rather than "error".
Functions ¶
func AddWrite ¶
func AddWrite[In WriteInput](s *mcp.Server, env *Env, spec WriteSpec, h WriteHandler[In])
AddWrite registers a write tool on s. Without env.Confirm every call is denied, so writes can never run unconfirmed.
Types ¶
type Approval ¶
type Approval struct {
ApprovalID string `` /* 138-byte string literal not displayed */
}
Approval is embedded in the input struct of every write tool. A client may retrieve a web approval outcome with the same arguments plus approval_id.
type ApprovalResolver ¶ added in v0.4.0
type ApprovalResolver interface {
ResolveApproval(context.Context, ConfirmRequest) error
}
ApprovalResolver retrieves a stored web outcome without planning a new write. The original plan remains bound to the stored invocation, not current state.
type ApprovalResult ¶ added in v0.4.0
ApprovalResult carries an already audited web execution outcome. It prevents a waiting call or retry from applying or auditing it again.
func (*ApprovalResult) Error ¶ added in v0.4.0
func (r *ApprovalResult) Error() string
type Caller ¶
type Caller struct {
User string
Transport string
// Source records link suggestion provenance, never a tool argument.
Source string
Scopes []string
// Tools optionally restricts this identity to matching tool-name globs.
Tools []string
}
Caller is the authenticated identity behind a tool call.
func (Caller) AllowsTool ¶ added in v0.4.0
AllowsTool reports the caller's tool policy.
type Check ¶ added in v0.5.0
Check observes the target of an applied write. Approval pages poll it to tell the person whether the action restored the service, not only whether the API accepted the change.
type ConfirmRequest ¶
type ConfirmRequest struct {
Caller Caller
Tool string
// Title is the tool's human-readable title, for approval screens only.
Title string
// Args are redacted arguments for display only, without approval_id.
// ArgsHash binds the canonical unredacted arguments, without approval_id.
Args map[string]any
ArgsHash [sha256.Size]byte
Summary string
// Target, NoWindow and FullReviewRequired are copied from the tool's Plan.
Target string
NoWindow bool
FullReviewRequired bool
ApprovalID string
// MaxArgBytes is the tool's argument limit, defaulting to 16 KiB.
MaxArgBytes int
// Run re-plans and applies the approved invocation, recording its audit.
Run func(context.Context) (string, error)
// Pending records creation before waiting for a web decision.
Pending func()
}
ConfirmRequest is what a Confirmer needs to obtain human approval.
func (ConfirmRequest) SummaryLimit ¶
func (r ConfirmRequest) SummaryLimit() int
SummaryLimit bounds approval summaries, allowing 16 KiB of framing beyond the argument limit and retaining a 64 KiB minimum for small write tools.
type Confirmer ¶
type Confirmer interface {
Confirm(ctx context.Context, req *mcp.CallToolRequest, r ConfirmRequest) (method string, err error)
}
Confirmer obtains a human decision that the model cannot forge. It returns the method used ("elicitation", "web") on approval, an error wrapping ErrDenied on refusal, or an error wrapping ErrApprovalPending whose message tells the model what the human must do next. InputRequired requests input through MCP's multi round-trip flow. ApprovalResult carries a stored, already audited execution result instead of authorizing an apply.
type Direct ¶
type Direct struct {
// Title names the tool for people.
Title string
// contains filtered or unexported fields
}
Direct runs one write tool for a person approving it in a browser, with no MCP client to retry the call. Plan and Run make the same checks as the MCP path. The approval itself is the caller's job.
func (*Direct) Run ¶
func (d *Direct) Run(ctx context.Context, c Caller, raw json.RawMessage, approved string) (string, error)
Run plans again and applies only if the summary still equals approved.
func (*Direct) ValidateLink ¶ added in v0.4.0
func (d *Direct) ValidateLink(ctx context.Context, c Caller, raw json.RawMessage) (Plan, string, error)
ValidateLink plans with read scope only. It cannot apply or grant approval. Use web target restrictions because the resulting link will execute there.
type Env ¶
type Env struct {
Audit *audit.Logger
MaxOutputBytes int
Timeout time.Duration
// Fallback is the caller used when the request carries no token
// (stdio). HTTP transports must always authenticate.
Fallback *Caller
// Confirm obtains human approval for write tools. Nil denies all writes.
Confirm Confirmer
// Policy filters tools during registration. Nil allows every tool.
Policy *Policy
// UndoURL builds an approval link for an undo action, or "" when the
// server offers no link for it. Nil disables undo links.
UndoURL func(Undo) string
// Remediation is a read-only provider callback shared with browser choices.
Remediation func(context.Context, Caller, string, string, string, string) (action.Options, error)
// HostOptions evaluates live choices for a host unit or container.
HostOptions func(ctx context.Context, c Caller, kind, name string) (action.Options, error)
// contains filtered or unexported fields
}
Env is shared by all tools of one server.
type Handler ¶
Handler implements a tool. The returned text is redacted and truncated by Add before reaching the client.
type Health ¶ added in v0.5.0
type Health struct {
// Done means the result will not change by waiting: the target is
// healthy, or it failed in a way that needs another action.
Done bool
// Healthy means the target serves as intended.
Healthy bool
// Detail is a short, fixed-format description such as "ready 2/2".
Detail string
}
Health is one observation of a target after an applied write.
type InputRequired ¶
type InputRequired struct {
Requests mcp.InputRequestMap
State string
}
InputRequired is returned by a Confirmer to ask the client for input.
func (*InputRequired) Error ¶
func (e *InputRequired) Error() string
Error implements error without exposing the request state.
type Plan ¶
type Plan struct {
Summary string
// Target names the system the write acts on (for example a Kubernetes
// cluster) when one server reaches several. Approval screens show it
// prominently and approval windows are granted per target. Empty means
// the server's only system.
Target string
// NoWindow requires a fresh human approval for every call, even when the
// tool is listed in approval.window_tools.
NoWindow bool
// FullReviewRequired means the summary omits content that needs review
// through the complete arguments, unless an approval window applies.
// The arguments must be unmasked even when a window applies.
FullReviewRequired bool
// Undo reverses this write once applied; results offer it as a link.
Undo *Undo `json:"-"`
// Check observes the target after a web-approved apply, so the approval
// page can report whether the service recovered. Nil means no check.
Check Check `json:"-"`
// Data belongs to this invocation and is never shown or serialized.
Data any `json:"-"`
}
Plan is the side-effect-free preview of a write. Summary is shown to the human approver verbatim, so it must name the exact target and effect.
type Policy ¶
type Policy struct {
// contains filtered or unexported fields
}
Policy filters registration and records all tools offered by enabled providers. Configure it before registration and call Validate after registration completes.
func NewPolicy ¶
func NewPolicy(cfg config.ToolPolicy) *Policy
NewPolicy snapshots the server-wide tool policy for one server's registration.
type Spec ¶
type Spec struct {
Name string
Title string
Description string
// ReadOnly must be true for every tool that does not change state.
ReadOnly bool
Scope string
}
Spec describes a tool. Scope defaults to ops:read.
type Undo ¶ added in v0.4.0
Undo is a catalog action that reverses an applied write. It is only ever offered as a fresh approval link; nothing applies it automatically.
type WriteHandler ¶
type WriteHandler[In WriteInput] struct { Plan func(ctx context.Context, c Caller, in In) (Plan, error) Apply func(ctx context.Context, c Caller, in In, p Plan) (string, error) }
WriteHandler splits a write into a side-effect-free Plan (input validation, allowlist checks, current state) and Apply. Apply runs only after Plan succeeded and a human confirmed the plan's summary.
type WriteInput ¶
type WriteInput interface {
// contains filtered or unexported methods
}
WriteInput is satisfied by any struct embedding Approval.
type WriteSpec ¶
type WriteSpec struct {
Name string
Title string
Description string
// Idempotent marks tools whose repetition has no further effect.
Idempotent bool
// Scope required in addition to human approval; default ops:write.
Scope string
// MaxArgBytes caps the raw JSON arguments (default 16 KiB). Raise it only
// for tools that carry document content.
MaxArgBytes int
// Direct also lets a person run this tool from a browser approval page,
// without an MCP client. See Direct. Use only for catalog actions with bounded effects.
Direct bool
}
WriteSpec describes a state-changing tool. Its scope is always ops:write.