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
- Variables
- func DecodeJSONFromReaderSafe(r io.Reader, v any, maxSize int64) error
- func DecodeJSONSafe(data []byte, v any, maxSize int64) error
- type ConflictStrategy
- type DiscoveryOption
- type Error
- type Handler
- type InputValidationError
- type MCPClient
- type MCPRequest
- type MCPResponse
- type MCPServer
- func (s *MCPServer) GetResource(uri string) *Resource
- func (s *MCPServer) GetServerInfo() *ServerInfo
- func (s *MCPServer) GetTool(name string) *Tool
- func (s *MCPServer) HandleRequest(ctx context.Context, req *MCPRequest) *MCPResponse
- func (s *MCPServer) ListResources() []*Resource
- func (s *MCPServer) ListTools() []*Tool
- func (s *MCPServer) RegisterResource(res *Resource) error
- func (s *MCPServer) RegisterTool(tool *Tool) error
- func (s *MCPServer) RegisterTools(tools ...*Tool) error
- func (s *MCPServer) UnregisterTool(name string)
- type MCPServerOption
- type MCPTransport
- type Registry
- type Resource
- type ServerInfo
- type Tool
- func Define[I, O any](name, description string, fn func(context.Context, I) (O, error)) *Tool
- func DefineAsync(name, description string, fn func(context.Context, string) error) *Tool
- func DefineSimple(name, description string, fn func(string) (string, error)) *Tool
- func DefineWithSchema(name, description string, inputSchema map[string]any, fn Handler) *Tool
- func NewTool(name, description string, schema map[string]any, handler Handler) *Tool
- func TypedTool[T any, R any](name, description string, schema map[string]any, ...) *Tool
- type ToolDiscovery
- type ToolRegistry
Constants ¶
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.
const (
// DefaultMaxJSONSize is the maximum size for JSON payloads (1MB).
DefaultMaxJSONSize = 1 * 1024 * 1024
)
MCP-related limits for security.
Variables ¶
var ErrToolConflict = errors.New("tool name conflict")
ErrToolConflict is returned when multiple servers provide tools with the same name.
Functions ¶
func DecodeJSONFromReaderSafe ¶
DecodeJSONFromReaderSafe decodes JSON from a reader with size limits.
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 ¶
Handler is a function that handles tool invocations.
func TypedHandler ¶
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 ¶
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.
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 ¶
GetResource retrieves a resource by URI.
func (*MCPServer) GetServerInfo ¶
func (s *MCPServer) GetServerInfo() *ServerInfo
GetServerInfo returns server metadata.
func (*MCPServer) HandleRequest ¶
func (s *MCPServer) HandleRequest(ctx context.Context, req *MCPRequest) *MCPResponse
HandleRequest processes an MCP request.
func (*MCPServer) ListResources ¶
ListResources returns all registered resources.
func (*MCPServer) RegisterResource ¶
RegisterResource adds a resource.
func (*MCPServer) RegisterTool ¶
RegisterTool adds a tool to the server.
func (*MCPServer) RegisterTools ¶
RegisterTools adds multiple tools.
func (*MCPServer) UnregisterTool ¶
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 (*Registry) ToMCPFormat ¶
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
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
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
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
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 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.
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.