mcptools

package
v0.48.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 12 Imported by: ? 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 mcptools adapts the tools of a Model Context Protocol (MCP) server into tools.Tool values an agent loop can call.

s, err := mcptools.Connect(ctx, &mcp.CommandTransport{Command: exec.Command("my-server")},
	mcptools.WithPrefix("fs_"))
if err != nil {
	return err
}
defer s.Close()
if err := s.RegisterAll(ctx, reg); err != nil {
	log.Printf("some MCP tools were skipped: %v", err)
}

The package lives outside pkg/tools so the MCP SDK is linked only by programs that import it.

Approval

Every remote tool is gated by RequiresConfirmation by default: the agent loop asks ConfirmHITL (or a PermissionAllow rule) before each call, and auto-denies when neither is configured. Tool descriptions and results come from the server and are untrusted model input, so a hostile or compromised server can attempt prompt injection; the gate keeps a human (or an explicit policy) between the model and the remote side effect. Server annotations such as readOnlyHint are never used to relax it. WithRequireApproval(false) removes the gate; combined with agent.WithSpeculativeTools(true), remote tools may then run speculatively while the model is still streaming, and a discarded speculation's remote side effect has already happened.

Use WithPrefix for servers you do not control, so their tool names cannot shadow or collide with local tools.

Bounds

A Session enforces Limits on everything the server sends: at most 512 tools, at most 64 KiB per tool definition (description plus input schema), and at most 256 KiB of result text per call. A truncated result ends with a "[truncated: N bytes omitted]" marker added on top of the cap. A negative limit disables that bound. Server error text is bounded like result text. Tool listing also rejects a non-final page without a single usable tool and a repeated pagination cursor, so a misbehaving server cannot keep the client paging forever. With the defaults a large server can still put megabytes of definitions in front of the model; register a subset via Tools, or put a tools.Selector in front of the registry.

Schema portability

Input schemas are forwarded to the model provider verbatim, and a provider that refuses one tool's schema fails the whole request. Tools therefore skips (with a reason in the joined error) any tool whose schema has a top-level allOf, anyOf, oneOf, not, enum or if/then/else (refused at the root by Anthropic) or nests deeper than 32 levels, so one incompatible tool cannot take the session down. The only rewrite is an array schema without "items" (refused by OpenAI), which gets "items": {}, meaning the same thing: any item.

Snapshot semantics

Tools lists the server once and returns an immutable snapshot. List-changed notifications are ignored; set ClientOptions.ToolListChangedHandler via WithClientOptions and rebuild the registry yourself if you need them. A Session does not reconnect. Calls on a closed Session, calls the SDK reports as mcp.ErrConnectionClosed, and JSON-RPC method-not-found errors match tools.ErrPermanent; invalid-params errors match tools.ErrUser; other failures are returned unclassified, with their text bounded.

Results

Text content is joined into Result.Text. Images, audio and resources become short placeholders such as "[image image/png, 12.0 KB]"; binary data never reaches the model as base64 text. An embedded text resource is rendered inline under a "[resource <uri>]" header. Without any text, the StructuredContent JSON follows the placeholders. When a result carries non-text content or StructuredContent, Result.Structured holds the SDK *mcp.CallToolResult for OnToolResult hooks. A result with isError set is returned as an error whose message is the (truncated) rendered text.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limits

type Limits struct {
	// MaxResultBytes caps the result text of one call (default 256 KiB).
	// Longer text is cut on a rune boundary and a short truncation marker
	// is appended on top of the cap. Error text from the server is bounded
	// the same way.
	MaxResultBytes int
	// MaxTools caps how many tools the server may list (default 512).
	// Exceeding it fails the whole listing.
	MaxTools int
	// MaxSchemaBytes caps the per-tool definition bytes: description plus
	// encoded input schema (default 64 KiB). A tool over the budget is
	// skipped.
	MaxSchemaBytes int
}

Limits bounds what a server can push into the agent. A zero field takes its default; a negative field disables that bound.

type Option

type Option func(*config)

Option configures a Session at Connect.

func WithClientOptions

func WithClientOptions(o *mcp.ClientOptions) Option

WithClientOptions passes options to the underlying MCP client, for example KeepAlive or ToolListChangedHandler. Connect copies o.

func WithLimits

func WithLimits(l Limits) Option

WithLimits overrides the default Limits.

func WithPrefix

func WithPrefix(p string) Option

WithPrefix prepends p to every tool name the model sees. The server still receives its own tool name on the wire.

func WithRequireApproval

func WithRequireApproval(b bool) Option

WithRequireApproval sets RequiresConfirmation on every remote tool (default true). See the package doc before turning it off.

type Session

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

Session is a connection to one MCP server. It is safe for concurrent use; the tools it returns share it and fail once it is closed.

func Connect

func Connect(ctx context.Context, t mcp.Transport, opts ...Option) (*Session, error)

Connect performs the MCP handshake over t and returns a Session. ctx bounds the handshake only.

func (*Session) Close

func (s *Session) Close() error

Close aborts in-flight calls and closes the connection. It is idempotent; every call returns the first result.

func (*Session) RegisterAll

func (s *Session) RegisterAll(ctx context.Context, reg tools.Registerer) error

RegisterAll registers every valid tool from Tools into reg. Like Tools, it registers what it can and returns the joined reasons for anything it could not (including Register failures such as tools.ErrDuplicateTool).

func (*Session) Tools

func (s *Session) Tools(ctx context.Context) ([]tools.Tool, error)

Tools lists the server's tools and adapts them. A tool that cannot be adapted (bad name, non-object schema, over Limits.MaxSchemaBytes, or a name that collides with an earlier tool after sanitizing) is skipped: Tools then returns the valid tools together with an errors.Join of the reasons. Listing failures and Limits.MaxTools overflow return nil tools.

Jump to

Keyboard shortcuts

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