tool

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 13 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 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

This section is empty.

Variables

View Source
var ErrApprovalPending = errors.New("approval pending")

ErrApprovalPending means a human has been asked but has not decided yet.

View Source
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 Add

func Add[In any](s *mcp.Server, env *Env, spec Spec, h Handler[In])

Add registers h on s with env's guard rails.

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.

func Denied

func Denied(format string, args ...any) error

Denied returns an error wrapping ErrDenied.

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 that was handed a web approval link calls the tool again with the same arguments plus approval_id once a human has approved it.

type Caller

type Caller struct {
	User      string
	Transport 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) Has

func (c Caller) Has(scope string) bool

Has reports whether the caller has scope.

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
}

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.

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

func (d *Direct) Plan(ctx context.Context, c Caller, raw json.RawMessage) (Plan, string, error)

Plan returns the plan and the summary a person must see before approving.

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.

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
	// contains filtered or unexported fields
}

Env is shared by all tools of one server.

func (*Env) Direct

func (env *Env) Direct(name string) *Direct

Direct returns the named direct write, or nil if the tool is disabled or was not registered for direct use.

type Handler

type Handler[In any] func(ctx context.Context, c Caller, in In) (string, error)

Handler implements a tool. The returned text is redacted and truncated by Add before reaching the client.

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

func (*Policy) Validate

func (p *Policy) Validate() error

Validate rejects malformed patterns and patterns matching no offered tool.

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 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. Keep it to small, reversible writes.
	Direct bool
}

WriteSpec describes a state-changing tool. Its scope is always ops:write.

Jump to

Keyboard shortcuts

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