tools

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package tools provides the MCP client implementation.

MCPClient connects to external MCP servers and provides tool discovery. ToolDiscovery aggregates tools from multiple MCP servers with configurable conflict resolution strategies.

Package tools provides MCP JSON utilities.

This file contains JSON encoding/decoding helpers with size limits to prevent memory exhaustion attacks. These are shared by both MCPServer and MCPClient.

Package tools provides the MCP server implementation.

MCPServer implements the Model Context Protocol (version 2024-11-05) server, handling tool registration, resource management, and request processing. Compatible with Claude Desktop, MCP Inspector, and conforming clients.

Package tools provides tool registration and integration.

Index

Constants

View Source
const (
	// DefaultMCPProtocolVersion is the MCP protocol version implemented by this server.
	DefaultMCPProtocolVersion = "2024-11-05"

	// DefaultToolTimeout is the default timeout for tool invocations when no deadline is set.
	DefaultToolTimeout = 30 * time.Second
)

MCP protocol version and defaults.

View Source
const (
	// DefaultMaxJSONSize is the maximum size for JSON payloads (1MB).
	DefaultMaxJSONSize = 1 * 1024 * 1024
)

MCP-related limits for security.

Variables

View Source
var ErrToolConflict = errors.New("tool name conflict")

ErrToolConflict is returned when multiple servers provide tools with the same name.

Functions

func DecodeJSONFromReaderSafe

func DecodeJSONFromReaderSafe(r io.Reader, v any, maxSize int64) error

DecodeJSONFromReaderSafe decodes JSON from a reader with size limits.

func DecodeJSONSafe

func DecodeJSONSafe(data []byte, v any, maxSize int64) error

DecodeJSONSafe decodes JSON with size limits to prevent memory exhaustion.

Types

type ConflictStrategy

type ConflictStrategy int

ConflictStrategy defines how to handle tool name conflicts.

const (
	// ConflictError returns an error on conflict (default).
	ConflictError ConflictStrategy = iota
	// ConflictFirstWins keeps the first tool, ignores later ones.
	ConflictFirstWins
	// ConflictLastWins overwrites with the latest tool (legacy behavior).
	ConflictLastWins
)

type DiscoveryOption

type DiscoveryOption func(*ToolDiscovery)

DiscoveryOption configures ToolDiscovery.

func WithConflictStrategy

func WithConflictStrategy(strategy ConflictStrategy) DiscoveryOption

WithConflictStrategy sets the strategy for handling tool name conflicts.

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

Error represents an MCP error.

type Handler

type Handler func(ctx context.Context, input map[string]any) (any, error)

Handler is a function that handles tool invocations.

func TypedHandler

func TypedHandler[T any, R any](fn func(ctx context.Context, input T) (R, error)) Handler

TypedHandler creates a type-safe handler from a function. The input type T is automatically deserialized from map[string]any, and the output type R is returned as-is.

Example:

type GreetInput struct {
    Name string `json:"name"`
}

type GreetOutput struct {
    Message string `json:"message"`
}

handler := TypedHandler(func(ctx context.Context, input GreetInput) (GreetOutput, error) {
    return GreetOutput{Message: "Hello, " + input.Name}, nil
})

type InputValidationError

type InputValidationError struct {
	Field   string
	Message string
}

InputValidationError represents a validation failure for tool input.

func (*InputValidationError) Error

func (e *InputValidationError) Error() string

type MCPClient

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

MCPClient connects to external MCP servers.

func NewMCPClient

func NewMCPClient(serverURL string, transport MCPTransport) *MCPClient

NewMCPClient creates a new MCP client.

func (*MCPClient) CallTool

func (c *MCPClient) CallTool(ctx context.Context, name string, args any) (any, error)

CallTool invokes a tool on the remote server.

func (*MCPClient) Close

func (c *MCPClient) Close() error

Close closes the client connection.

func (*MCPClient) ListTools

func (c *MCPClient) ListTools(ctx context.Context) ([]*Tool, error)

ListTools fetches available tools from the server.

type MCPRequest

type MCPRequest struct {
	Method string          `json:"method"`
	Params json.RawMessage `json:"params,omitempty"`
	ID     any             `json:"id,omitempty"`
}

MCPRequest represents an incoming MCP request.

type MCPResponse

type MCPResponse struct {
	Result any    `json:"result,omitempty"`
	Error  *Error `json:"error,omitempty"`
	ID     any    `json:"id,omitempty"`
}

MCPResponse represents an MCP response.

type MCPServer

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

MCPServer represents an MCP (Model Context Protocol) server.

func NewMCPServer

func NewMCPServer(name string, opts ...MCPServerOption) *MCPServer

NewMCPServer creates a new MCP server.

func (*MCPServer) GetResource

func (s *MCPServer) GetResource(uri string) *Resource

GetResource retrieves a resource by URI.

func (*MCPServer) GetServerInfo

func (s *MCPServer) GetServerInfo() *ServerInfo

GetServerInfo returns server metadata.

func (*MCPServer) GetTool

func (s *MCPServer) GetTool(name string) *Tool

GetTool retrieves a tool by name.

func (*MCPServer) HandleRequest

func (s *MCPServer) HandleRequest(ctx context.Context, req *MCPRequest) *MCPResponse

HandleRequest processes an MCP request.

func (*MCPServer) ListResources

func (s *MCPServer) ListResources() []*Resource

ListResources returns all registered resources.

func (*MCPServer) ListTools

func (s *MCPServer) ListTools() []*Tool

ListTools returns all registered tools.

func (*MCPServer) RegisterResource

func (s *MCPServer) RegisterResource(res *Resource) error

RegisterResource adds a resource.

func (*MCPServer) RegisterTool

func (s *MCPServer) RegisterTool(tool *Tool) error

RegisterTool adds a tool to the server.

func (*MCPServer) RegisterTools

func (s *MCPServer) RegisterTools(tools ...*Tool) error

RegisterTools adds multiple tools.

func (*MCPServer) UnregisterTool

func (s *MCPServer) UnregisterTool(name string)

UnregisterTool removes a tool.

type MCPServerOption

type MCPServerOption func(*MCPServer)

MCPServerOption configures an MCP server.

func WithMCPDescription

func WithMCPDescription(desc string) MCPServerOption

WithMCPDescription sets the server description.

func WithMCPMaxJSONSize

func WithMCPMaxJSONSize(maxSize int64) MCPServerOption

WithMCPMaxJSONSize sets the maximum JSON payload size.

func WithMCPVersion

func WithMCPVersion(version string) MCPServerOption

WithMCPVersion sets the server version.

func WithProtocolVersion

func WithProtocolVersion(version string) MCPServerOption

WithProtocolVersion sets the MCP protocol version.

func WithToolTimeout added in v0.3.0

func WithToolTimeout(timeout time.Duration) MCPServerOption

WithToolTimeout sets the default timeout for tool invocations. This timeout is applied when the incoming context has no deadline.

type MCPTransport

type MCPTransport interface {
	Send(ctx context.Context, req *MCPRequest) (*MCPResponse, error)
	Close() error
}

MCPTransport handles MCP communication.

type Registry

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

Registry manages tool registration and invocation.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new tool registry.

func (*Registry) Get

func (r *Registry) Get(name string) (*Tool, bool)

Get retrieves a tool by name.

func (*Registry) Invoke

func (r *Registry) Invoke(ctx context.Context, name string, input map[string]any) (any, error)

Invoke invokes a tool by name.

func (*Registry) List

func (r *Registry) List() []*Tool

List returns all registered tools.

func (*Registry) Register

func (r *Registry) Register(tool *Tool) error

Register registers a tool.

func (*Registry) ToMCPFormat

func (r *Registry) ToMCPFormat() map[string]any

ToMCPFormat converts registered tools to MCP server format. This is a placeholder for MCP server generation.

type Resource

type Resource struct {
	URI         string         `json:"uri"`
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	MimeType    string         `json:"mimeType,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

Resource represents an MCP resource.

type ServerInfo

type ServerInfo struct {
	Name         string   `json:"name"`
	Version      string   `json:"version"`
	Description  string   `json:"description,omitempty"`
	Capabilities []string `json:"capabilities"`
}

ServerInfo contains server metadata.

type Tool

type Tool struct {
	// Name is the tool name.
	Name string

	// Description describes what the tool does.
	Description string

	// InputSchema is the JSON schema for the tool's input.
	InputSchema map[string]any

	// Handler is the function that executes the tool.
	Handler Handler
}

Tool represents a tool available to the AI.

func Define added in v0.6.0

func Define[I, O any](name, description string, fn func(context.Context, I) (O, error)) *Tool

Define creates a type-safe tool with schema inferred from the input type. The input type's JSON schema is automatically generated from struct tags.

Example:

type SearchInput struct {
    Query string `json:"query" desc:"Search query" required:"true"`
    Limit int    `json:"limit" desc:"Max results" max:"100"`
}

type SearchOutput struct {
    Results []string `json:"results"`
}

searchTool := tools.Define("search", "Search the web",
    func(ctx context.Context, in SearchInput) (SearchOutput, error) {
        results := doSearch(in.Query, in.Limit)
        return SearchOutput{Results: results}, nil
    },
)

func DefineAsync added in v0.6.0

func DefineAsync(name, description string, fn func(context.Context, string) error) *Tool

DefineAsync creates a tool that runs asynchronously and returns immediately. The handler runs in a goroutine and results can be retrieved later.

Example:

downloadTool := tools.DefineAsync("download", "Download a file",
    func(ctx context.Context, url string) error {
        return downloadFile(url)
    },
)

func DefineSimple added in v0.6.0

func DefineSimple(name, description string, fn func(string) (string, error)) *Tool

DefineSimple creates a tool with a single string input and output. Perfect for simple transformations or queries.

Example:

reverseTool := tools.DefineSimple("reverse", "Reverse a string",
    func(s string) (string, error) {
        runes := []rune(s)
        for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
            runes[i], runes[j] = runes[j], runes[i]
        }
        return string(runes), nil
    },
)

func DefineWithSchema added in v0.6.0

func DefineWithSchema(name, description string, inputSchema map[string]any, fn Handler) *Tool

DefineWithSchema creates a tool with an explicit schema. Use when you need precise control over the schema.

Example:

calcTool := tools.DefineWithSchema("calc", "Calculate expression",
    map[string]any{
        "type": "object",
        "properties": map[string]any{
            "expression": map[string]any{
                "type": "string",
                "pattern": "^[0-9+\\-*/()\\s]+$",
            },
        },
        "required": []string{"expression"},
    },
    func(ctx context.Context, input map[string]any) (any, error) {
        expr := input["expression"].(string)
        return evaluate(expr), nil
    },
)

func NewTool

func NewTool(name, description string, schema map[string]any, handler Handler) *Tool

NewTool creates a new tool.

func TypedTool

func TypedTool[T any, R any](
	name, description string,
	schema map[string]any,
	fn func(ctx context.Context, input T) (R, error),
) *Tool

TypedTool creates a new tool with a typed handler.

func (*Tool) Invoke

func (t *Tool) Invoke(ctx context.Context, input map[string]any) (any, error)

Invoke invokes the tool with the given input after validation.

func (*Tool) ValidateInput

func (t *Tool) ValidateInput(input map[string]any) error

ValidateInput validates input against the tool's InputSchema. Returns nil if validation passes, or an error describing the validation failure.

type ToolDiscovery

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

ToolDiscovery discovers tools from multiple MCP servers.

func NewToolDiscovery

func NewToolDiscovery(opts ...DiscoveryOption) *ToolDiscovery

NewToolDiscovery creates a new tool discovery service.

func (*ToolDiscovery) AddServer

func (d *ToolDiscovery) AddServer(client *MCPClient)

AddServer adds an MCP server to discover tools from.

func (*ToolDiscovery) Close

func (d *ToolDiscovery) Close() error

Close closes all client connections.

func (*ToolDiscovery) Discover

func (d *ToolDiscovery) Discover(ctx context.Context) error

Discover fetches tools from all registered servers.

func (*ToolDiscovery) GetToolSource

func (d *ToolDiscovery) GetToolSource(name string) string

GetToolSource returns the server URL that provided the named tool.

func (*ToolDiscovery) GetTools

func (d *ToolDiscovery) GetTools() []*Tool

GetTools returns all discovered tools.

type ToolRegistry added in v0.3.0

type ToolRegistry interface {
	Register(tool *Tool) error
	Get(name string) (*Tool, bool)
	List() []*Tool
	Invoke(ctx context.Context, name string, input map[string]any) (any, error)
}

ToolRegistry defines the contract for tool registration and invocation.

Directories

Path Synopsis
Package schema provides JSON Schema generation from Go types.
Package schema provides JSON Schema generation from Go types.

Jump to

Keyboard shortcuts

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