tool

package
v0.0.0-...-ecee8c2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 22 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 defines the tool port, per-caller allowlists, the call step, the MCP client adapter (github.com/modelcontextprotocol/go-sdk) and the sandbox port for generated code.

A Tool has a name, a description and an input JSON Schema. Set is one caller's allowlist. Layer.Step runs one call as a step function: it checks the allowlist, validates the arguments with core/schema, runs the tool under its time limit with panic recovery and stores an oversized result in blob storage. An Outcome records success or the code and message a model sees; it is returned as a step result, so a resumed run never executes a completed call again (REQ-TOOL-003, ADR-0011).

MCPClient lists a server's tools under mcp_<server>__<tool> names and forwards calls over the MCP Go SDK; a server's credential is resolved per call and scrubbed from anything the server sends back. Sandbox is the port for commands run outside the host; Layer.RunSandbox resolves the spec's credential references before the driver runs, rejects files that escape the work directory or reserved environment names, and enforces the time and output limits around a driver. Stdout and stderr are carried separately, with non-UTF-8 output base64-encoded.

Status: implemented (WP-L7-02). Concrete sandbox drivers are a follow-up work package; the gate exercises the port against a simulated sandbox. See specs/tools/design.md.

Index

Constants

View Source
const (
	// DefaultTimeout bounds one call when the tool declares none.
	DefaultTimeout = 60 * time.Second

	// DefaultMaxResult is the number of bytes kept inline before a result is
	// stored in blob storage and returned by reference (REQ-TOOL-007).
	DefaultMaxResult = 256 * 1024

	// Heartbeat is the interval at which a running tool may report progress
	// and observe cancellation (REQ-TOOL-006).
	Heartbeat = time.Second
)

Defaults of the tool layer (design §3).

View Source
const DefaultSandboxOutput = 1024 * 1024

DefaultSandboxOutput is the number of output bytes kept when the spec sets no limit.

View Source
const DefaultSandboxTimeout = 60 * time.Second

DefaultSandboxTimeout bounds a command whose spec declares no time limit.

Variables

This section is empty.

Functions

func Key

func Key(run, path string, visit, index int) string

Key returns the idempotency key of one tool call (REQ-TOOL-003):

tool:<run>:<node path>:<visit>:<call index>

node path is the same one the model node uses (map index and enclosing subflows included), visit counts visits to that node or turns of the agent loop, and index counts the calls within that visit or model reply, in order. The key is stable for the run, so a resumed run returns the recorded outcome instead of running the tool again.

func MCPToolName

func MCPToolName(server, tool string) string

MCPToolName is the name under which a server's tool is offered: mcp_<server>__<tool>, the server part sanitized to [A-Za-z0-9_].

Types

type Call

type Call struct {
	Name string          `json:"name"`
	Args json.RawMessage `json:"args,omitempty"`
}

Call is one tool call as the loop or the node received it.

type Clock

type Clock interface {
	Now() time.Time
	After(d time.Duration) <-chan time.Time
}

Clock is the layer's only source of time. After must wake at its deadline; the fake clock in tests provides both, so a timeout never depends on the wall clock in the gate.

type Config

type Config struct {
	Clock            Clock
	Blob             platform.Blob
	Credentials      platform.Credentials
	Log              *slog.Logger
	DefaultTimeout   time.Duration
	DefaultMaxResult int
}

Config configures a Layer. The zero value is usable: the system clock, the package defaults, and no blob store (an oversized result then fails the layer).

type Func

type Func func(ctx context.Context, args json.RawMessage) (Result, error)

Func runs a tool. Its error carries the core code and message a model sees (REQ-TOOL-004, REQ-TOOL-011); its Details never reach a model.

type Layer

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

Layer is the tool layer: the call step, allowlist checks, argument validation, result spilling and the sandbox runner.

func New

func New(cfg Config) *Layer

New returns a layer over cfg.

func (*Layer) RunSandbox

func (l *Layer) RunSandbox(ctx context.Context, sb Sandbox, spec SandboxSpec, command []string) (Result, error)

RunSandbox runs command in sb within spec's limits. It enforces the time limit (REQ-TOOL-019) and the output limit (REQ-TOOL-020) around the driver, so every caller sees the same outcome whatever the driver does on its own. A driver that cannot start or fails is internal (REQ-TOOL-022).

func (*Layer) Step

func (l *Layer) Step(ctx context.Context, set *Set, call Call) (Outcome, error)

Step is the side effect of one call, run by a step named by the caller:

dc.Step("tool:"+call.Name, call, runtime.StepOptions{IdempotencyKey: tool.Key(...)})

It validates, checks the allowlist, runs the tool under its limits and returns an Outcome. An Outcome, success or failure, is a normal step result: the runtime never retries it. A Go error means the layer itself failed.

type MCPClient

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

MCPClient lists one server's tools and forwards calls to it. Tool names are mcp_<server>__<tool>, with every character of the server name outside [A-Za-z0-9] replaced by '_' (REQ-TOOL-012).

func NewMCPClient

func NewMCPClient(server MCPServer, creds platform.Credentials) *MCPClient

NewMCPClient returns a client for server. creds may be nil when the server names no credential.

func (*MCPClient) Call

func (c *MCPClient) Call(ctx context.Context, call Call) (Result, error)

Call forwards one call to the server. The credential, when configured, is resolved at the call and never recorded. A call that cannot be forwarded is unavailable; a failure the server reports is vendor_error (REQ-TOOL-013…015, REQ-TOOL-025).

func (*MCPClient) Close

func (c *MCPClient) Close() error

Close releases any resources held by the client. Listings and calls open and close their own session, so there is nothing left to close.

func (*MCPClient) Tools

func (c *MCPClient) Tools(ctx context.Context, existing *Set) ([]Tool, error)

Tools returns the server's tools with prefixed names, descriptions and input schemas. A name that collides with a tool already in existing is rejected with code conflict (REQ-TOOL-024).

The list is read from the server before every offer (REQ-TOOL-016), so a server that changed its tools — with or without a "list changed" notification — is always seen by the next model turn. Re-reading is the deterministic option the design allows; a cached list keyed on the SDK's notification would race the gate's clock.

type MCPServer

type MCPServer struct {
	Name    string
	CredRef string // "cred://<name>", optional
	Dial    func(ctx context.Context, credential []byte) (mcp.Transport, error)
}

MCPServer configures one MCP server. Dial opens a transport to the server; when CredRef is set, the credential is resolved at the point of use and the secret is passed to Dial only (REQ-TOOL-017).

type Outcome

type Outcome struct {
	Result  Result    `json:"result,omitempty"`
	Code    core.Code `json:"code,omitempty"`
	Message string    `json:"message,omitempty"`
	Failed  bool      `json:"failed,omitempty"`
}

Outcome is what a caller gets back: one of Result, or Code and Message.

func RunStep

func RunStep(ctx context.Context, set *Set, call Call, now func() time.Time) (Outcome, error)

RunStep keeps the package-level contract of design §2: run one call with now as the layer's clock. It has no blob store, so a tool that needs to spill an oversized result must be run through a Layer with a Blob.

func (Outcome) Text

func (o Outcome) Text() string

Text renders what a model sees for the call (REQ-TOOL-011): the result's content, or on failure the code and the message, never Details.

type Result

type Result struct {
	Content    json.RawMessage // or a JSON string, for a tool whose result is text; a sandbox result with both streams is an object
	BlobRef    string          // set instead of Content when the result exceeded MaxResult
	ExitStatus int             // set by a sandbox command (REQ-TOOL-021)
	Truncated  bool            // set by a sandbox result whose output was cut (REQ-TOOL-020)
}

Result is a successful tool result.

type Runner

type Runner func(ctx context.Context, set *Set, call Call) (Outcome, error)

Runner runs one call as the side effect of a durable step. The agent loop supplies it; a *Layer's Step is the production implementation (RunStep is the package-level convenience). It must not retry a failed call: an Outcome records the failure and the step succeeds, and a Go error means the layer itself failed.

type Sandbox

type Sandbox interface {
	Run(ctx context.Context, spec SandboxSpec, command []string) (SandboxResult, error)
}

Sandbox is the port for commands run outside the host. A driver gives the command no host files, environment, instance metadata or network beyond the spec, and stops it when ctx is cancelled.

type SandboxResult

type SandboxResult struct {
	ExitStatus int
	Stdout     []byte
	Stderr     []byte
	Truncated  bool
}

SandboxResult is what a driver returns. A non-zero ExitStatus is a normal result (REQ-TOOL-021); an error means the sandbox itself failed.

type SandboxSpec

type SandboxSpec struct {
	Image     string            // or a driver-specific base
	TimeLimit time.Duration     // 0 = DefaultSandboxTimeout
	MaxOutput int               // bytes kept in total; 0 = DefaultSandboxOutput
	Network   []string          // hosts or CIDRs; empty = no network
	Files     map[string][]byte // the only files the command sees, under its work dir
	CredRefs  map[string]string // env var name -> cred:// name, resolved by RunSandbox before the run
}

SandboxSpec describes one command's sandbox. It is the only state a driver may give the command: Files is its whole work directory, Network is its only network and CredRefs are resolved at the run (REQ-TOOL-018).

type Set

type Set struct {
	Tools []Tool // sorted by Name, so replay is deterministic
}

Set is one caller's tools: the registry names an agent was given.

func (*Set) Get

func (s *Set) Get(name string) (Tool, bool)

Get returns the tool called name.

func (*Set) Merge

func (s *Set) Merge(other *Set) error

Merge adds another set's tools to s, keeping the set sorted. A name that appears in both sets is rejected with code conflict: a duplicate would make Get return whichever came first, which could route a call to the wrong server with its credential.

func (*Set) Names

func (s *Set) Names() []string

Names returns the set's tool names, in order.

type Tool

type Tool struct {
	Name        string          // as the model sees it; from an MCP server, mcp_<server>__<tool>
	Description string          // what the model reads
	Input       json.RawMessage // JSON Schema
	Timeout     time.Duration   // 0 = the layer's default
	MaxResult   int             // bytes kept before the result is stored by reference; 0 = default
	Run         Func
}

Tool is what one caller may call.

Jump to

Keyboard shortcuts

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