UTCP

package module
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: MIT Imports: 30 Imported by: 0

README

UTCP-Golang

Go Report Card

Universal Tool Calling Protocol (UTCP) reference implementation in Go.

UTCP standardises how a client can discover and call "tools" (APIs) regardless of the underlying transport. Each provider describes a transport (HTTP, CLI, GraphQL and others) and lists the tools it exposes. This repository ships a lightweight Go client which can load provider definitions, register them at runtime and then invoke the discovered tools.

Features
  • Built-in transports for HTTP, CLI, Server-Sent Events, streaming HTTP, GraphQL, MCP, UDP and text-based providers.
  • Variable substitution via environment variables or .env files using UtcpDotEnv.
  • In-memory repository for storing providers and tools discovered at runtime.
  • Utilities such as OpenApiConverter to convert OpenAPI definitions into UTCP manuals.
  • Example programs demonstrating the client in the examples directory.
Examples

Each subdirectory under examples/ is a standalone Go module. When building or running an example from this repository, disable the workspace to ensure Go uses the module's own go.mod:

GOWORK=off go run ./examples/cli_transport

The library is primarily intended for experimentation and interoperability testing. The API may change without notice.

Documentation

Index

Constants

View Source
const Version = "1.0"

Variables

View Source
var (
	// ErrMCPProviderRequired indicates a function was called with the wrong provider type.
	ErrMCPProviderRequired = errors.New("can only be used with MCPProvider")
	// ErrToolCallingNotImplemented is returned by CallTool as this transport has no implementation yet.
	ErrToolCallingNotImplemented = errors.New("tool calling not implemented yet")
)

Functions

func AddTool

func AddTool(t Tool)

AddTool registers a new tool in the global context.

func RegisterTool

func RegisterTool(
	provider Provider,
	name string,
	description string,
	tags []string,
	inputs *ToolInputOutputSchema,
	outputs *ToolInputOutputSchema,
	handler ToolHandler,
)

RegisterTool is the Go equivalent of your @utcp_tool decorator. Call this from an init() function in the same package as your handler.

Types

type ApiKeyAuth

type ApiKeyAuth struct {
	AuthType AuthType `json:"auth_type"`
	APIKey   string   `json:"api_key"`  // If it starts with '$', treated as injected variable.
	VarName  string   `json:"var_name"` // Header/query param/cookie name (default: "X-Api-Key").
	Location string   `json:"location"` // Where to include the key: header, query, or cookie.
}

ApiKeyAuth holds config for API key–based authentication.

The key can be provided directly or sourced from an environment variable.

func NewApiKeyAuth

func NewApiKeyAuth(apiKey string) *ApiKeyAuth

NewApiKeyAuth constructs an ApiKeyAuth with defaults.

func (*ApiKeyAuth) Type

func (a *ApiKeyAuth) Type() AuthType

Type returns the auth type.

func (*ApiKeyAuth) Validate

func (a *ApiKeyAuth) Validate() error

Validate ensures required fields are present.

type Auth

type Auth interface {
	// Type returns the authentication type.
	Type() AuthType

	// Validate checks that all required fields are set.
	Validate() error
}

Auth is the interface all auth methods implement.

type AuthType

type AuthType string

AuthType represents the kind of authentication.

const (
	// APIKeyType indicates API key–based authentication.
	APIKeyType AuthType = "api_key"

	// BasicType indicates basic username/password authentication.
	BasicType AuthType = "basic"

	// OAuth2Type indicates OAuth2 authentication.
	OAuth2Type AuthType = "oauth2"
)

type BaseProvider

type BaseProvider struct {
	Name         string       `json:"name"`
	ProviderType ProviderType `json:"provider_type"`
}

BaseProvider holds fields common to every provider.

func (*BaseProvider) Type

func (b *BaseProvider) Type() ProviderType

type BasicAuth

type BasicAuth struct {
	AuthType AuthType `json:"auth_type"`
	Username string   `json:"username"`
	Password string   `json:"password"`
}

BasicAuth holds config for HTTP Basic authentication.

func NewBasicAuth

func NewBasicAuth(username, password string) *BasicAuth

NewBasicAuth constructs a BasicAuth.

func (*BasicAuth) Type

func (b *BasicAuth) Type() AuthType

Type returns the auth type.

func (*BasicAuth) Validate

func (b *BasicAuth) Validate() error

Validate ensures required fields are present.

type CliProvider

type CliProvider struct {
	BaseProvider
	CommandName string            `json:"command_name"`
	EnvVars     map[string]string `json:"env_vars,omitempty"`
	WorkingDir  *string           `json:"working_dir,omitempty"`
}

CliProvider represents a CLI tool.

type CliTransport

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

CliTransport is a CLI-based transport for UTCP client. It discovers and executes tools via external command-line calls.

func NewCliTransport

func NewCliTransport(logger func(format string, args ...interface{})) *CliTransport

NewCliTransport creates a new CliTransport with an optional logger.

func (*CliTransport) CallTool

func (t *CliTransport) CallTool(
	ctx context.Context,
	toolName string,
	args map[string]interface{},
	prov Provider,
	l *string,
) (interface{}, error)

CallTool executes a registered CLI tool with arguments.

func (*CliTransport) Close

func (t *CliTransport) Close() error

Close cleans up resources (no-op).

func (*CliTransport) DeregisterToolProvider

func (t *CliTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider is a no-op for CLI transport.

func (*CliTransport) RegisterToolProvider

func (t *CliTransport) RegisterToolProvider(
	ctx context.Context,
	prov Provider,
) ([]Tool, error)

RegisterToolProvider discovers tools by executing provider.CommandName and parsing UTCPManual JSON.

type ClientTransport

type ClientTransport interface {
	// RegisterToolProvider registers a tool provider (e.g. via the /utcp endpoint)
	// and returns the list of tools it exposes.
	RegisterToolProvider(ctx context.Context, manualProvider Provider) ([]Tool, error)

	// DeregisterToolProvider removes a previously registered provider.
	DeregisterToolProvider(ctx context.Context, manualProvider Provider) error

	// CallTool invokes a named tool with the given arguments on a specific provider.
	// It returns whatever the tool returns (often map[string]interface{} or a typed result).
	CallTool(ctx context.Context, toolName string, arguments map[string]any, toolProvider Provider, l *string) (any, error)
}

ClientTransport defines how a client registers, deregisters, and invokes UTCP tools.

type GRPCClientTransport added in v1.2.0

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

GRPCClientTransport implements ClientTransport over gRPC using the UTCPService. It expects the remote server to implement the grpcpb.UTCPService service.

func NewGRPCClientTransport added in v1.2.0

func NewGRPCClientTransport(logger func(format string, args ...interface{})) *GRPCClientTransport

NewGRPCClientTransport creates a new GRPCClientTransport with optional logger.

func (*GRPCClientTransport) CallTool added in v1.2.0

func (t *GRPCClientTransport) CallTool(ctx context.Context, toolName string, args map[string]any, prov Provider, l *string) (any, error)

CallTool invokes the CallTool RPC on the UTCPService.

func (*GRPCClientTransport) Close added in v1.2.0

func (t *GRPCClientTransport) Close() error

Close cleans up (no-op).

func (*GRPCClientTransport) DeregisterToolProvider added in v1.2.0

func (t *GRPCClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider is a no-op for gRPC transport.

func (*GRPCClientTransport) RegisterToolProvider added in v1.2.0

func (t *GRPCClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider fetches the manual from the remote UTCPService.

type GRPCProvider

type GRPCProvider struct {
	BaseProvider
	Host        string `json:"host"`
	Port        int    `json:"port"`
	ServiceName string `json:"service_name"`
	MethodName  string `json:"method_name"`
	UseSSL      bool   `json:"use_ssl"`
	Auth        *Auth  `json:"auth,omitempty"`
}

GRPCProvider represents a gRPC service.

type GraphQLClientTransport

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

GraphQLClientTransport is a simple, robust, production-ready GraphQL transport using gql. Stateless, per-operation. Supports all GraphQL features.

func NewGraphQLClientTransport

func NewGraphQLClientTransport(logger func(msg string, err error)) *GraphQLClientTransport

NewGraphQLClientTransport creates a new transport instance.

func (*GraphQLClientTransport) CallTool

func (t *GraphQLClientTransport) CallTool(ctx context.Context, toolName string, arguments map[string]any, toolProvider Provider, l *string) (any, error)

CallTool executes a GraphQL operation by name.

func (*GraphQLClientTransport) Close

func (t *GraphQLClientTransport) Close() error

Close clears cached tokens.

func (*GraphQLClientTransport) DeregisterToolProvider

func (t *GraphQLClientTransport) DeregisterToolProvider(ctx context.Context, manualProv Provider) error

DeregisterToolProvider is a no-op for stateless transport.

func (*GraphQLClientTransport) RegisterToolProvider

func (t *GraphQLClientTransport) RegisterToolProvider(ctx context.Context, manualProv Provider) ([]Tool, error)

RegisterToolProvider discovers schema and registers tools.

type GraphQLProvider

type GraphQLProvider struct {
	BaseProvider
	URL           string            `json:"url"`
	OperationType string            `json:"operation_type"` // query, mutation, subscription
	OperationName *string           `json:"operation_name,omitempty"`
	Auth          *Auth             `json:"auth,omitempty"`
	Headers       map[string]string `json:"headers,omitempty"`
	HeaderFields  []string          `json:"header_fields,omitempty"`
}

GraphQLProvider represents a GraphQL endpoint.

type HttpClientTransport

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

HttpClientTransport implements ClientTransportInterface for HTTP-based tool providers.

func NewHttpClientTransport

func NewHttpClientTransport(logger func(format string, args ...interface{})) *HttpClientTransport

NewHttpClientTransport constructs a new HttpClientTransport.

func (*HttpClientTransport) CallTool

func (t *HttpClientTransport) CallTool(ctx context.Context, toolName string, args map[string]any, p Provider, l *string) (any, error)

CallTool calls a specific tool on the HTTP provider.

func (*HttpClientTransport) DeregisterToolProvider

func (t *HttpClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider is a no-op for CLI transport.

func (*HttpClientTransport) RegisterToolProvider

func (t *HttpClientTransport) RegisterToolProvider(ctx context.Context, p Provider) ([]Tool, error)

RegisterToolProvider discovers tools from a REST HttpProvider.

type HttpProvider

type HttpProvider struct {
	BaseProvider
	HTTPMethod   string            `json:"http_method"` // GET, POST, PUT, DELETE, PATCH
	URL          string            `json:"url"`
	ContentType  string            `json:"content_type"` // default application/json
	Auth         *Auth             `json:"auth,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	BodyField    *string           `json:"body_field,omitempty"` // name of the single input field
	HeaderFields []string          `json:"header_fields,omitempty"`
}

HttpProvider represents RESTful HTTP/HTTPS API.

type InMemoryToolRepository

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

func (InMemoryToolRepository) GetProvider

func (r InMemoryToolRepository) GetProvider(ctx context.Context, providerName string) (*Provider, error)

func (InMemoryToolRepository) GetProviders

func (r InMemoryToolRepository) GetProviders(ctx context.Context) ([]Provider, error)

func (InMemoryToolRepository) GetTool

func (r InMemoryToolRepository) GetTool(ctx context.Context, toolName string) (*Tool, error)

func (InMemoryToolRepository) GetTools

func (r InMemoryToolRepository) GetTools(ctx context.Context) ([]Tool, error)

func (InMemoryToolRepository) GetToolsByProvider

func (r InMemoryToolRepository) GetToolsByProvider(ctx context.Context, providerName string) ([]Tool, error)

func (InMemoryToolRepository) RemoveProvider

func (r InMemoryToolRepository) RemoveProvider(ctx context.Context, providerName string) error

func (InMemoryToolRepository) RemoveTool

func (r InMemoryToolRepository) RemoveTool(ctx context.Context, toolName string) error

func (*InMemoryToolRepository) SaveProviderWithTools

func (r *InMemoryToolRepository) SaveProviderWithTools(ctx context.Context, provider Provider, tools []Tool) error

type LoggerFunc

type LoggerFunc func(format string, args ...interface{})

LoggerFunc defines the signature for optional logging callbacks. It matches fmt.Printf to ease integration with standard loggers.

type MCPProvider

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

MCPProvider is the concrete provider your transport expects.

func NewMCPProvider

func NewMCPProvider(name string) *MCPProvider

NewMCPProvider constructs one with the given name.

func (*MCPProvider) Name

func (p *MCPProvider) Name() string

Name returns the provider’s human‐readable name.

func (*MCPProvider) Type

func (p *MCPProvider) Type() ProviderType

Type satisfies your Provider interface.

type MCPTransport

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

MCPTransport implements ClientTransport over MCPProvider.

func NewMCPTransport

func NewMCPTransport(logger LoggerFunc) *MCPTransport

NewMCPTransport initializes the transport with a 30 s timeout.

func NewMCPTransportWithClient

func NewMCPTransportWithClient(client *http.Client, logger LoggerFunc) *MCPTransport

NewMCPTransportWithClient allows injecting a custom HTTP client.

func (*MCPTransport) CallTool

func (t *MCPTransport) CallTool(
	ctx context.Context,
	toolName string,
	params map[string]any,
	provider Provider,
	version *string,
) (any, error)

CallTool only accepts *MCPProvider and returns the “not implemented” error.

func (*MCPTransport) DeregisterToolProvider

func (t *MCPTransport) DeregisterToolProvider(
	ctx context.Context,
	provider Provider,
) error

DeregisterToolProvider only accepts *MCPProvider; logs its Name().

func (*MCPTransport) RegisterToolProvider

func (t *MCPTransport) RegisterToolProvider(
	ctx context.Context,
	provider Provider,
) ([]Tool, error)

RegisterToolProvider only accepts *MCPProvider; logs its Name().

type McpConfig

type McpConfig struct {
	McpServers map[string]McpServer `json:"mcpServers"`
}

type McpHttpServer

type McpHttpServer struct {
	Transport string `json:"transport"` // always "http"
	URL       string `json:"url"`
}

McpHttpServer config for HTTP transport.

type McpServer

type McpServer interface{}

McpServer is a union of the two MCP transports.

type McpStdioServer

type McpStdioServer struct {
	Transport string            `json:"transport"` // always "stdio"
	Command   string            `json:"command"`
	Args      []string          `json:"args,omitempty"`
	Env       map[string]string `json:"env,omitempty"`
}

McpStdioServer config for stdio transport.

type OAuth2Auth

type OAuth2Auth struct {
	AuthType     AuthType `json:"auth_type"`
	TokenURL     string   `json:"token_url"`
	ClientID     string   `json:"client_id"`
	ClientSecret string   `json:"client_secret"`
	Scope        *string  `json:"scope,omitempty"` // Optional OAuth2 scope.
}

OAuth2Auth holds config for OAuth2 authentication.

func NewOAuth2Auth

func NewOAuth2Auth(tokenURL, clientID, clientSecret string, scope *string) *OAuth2Auth

NewOAuth2Auth constructs an OAuth2Auth.

func (*OAuth2Auth) Type

func (o *OAuth2Auth) Type() AuthType

Type returns the auth type.

func (*OAuth2Auth) Validate

func (o *OAuth2Auth) Validate() error

Validate ensures required fields are present.

type OAuth2TokenResponse

type OAuth2TokenResponse struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
	Scope       string `json:"scope"`
}

OAuth2TokenResponse holds the response fields from an OAuth2 token endpoint.

type OpenAPIConverter

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

OpenAPIConverter helps converting OpenAPI specs into a UtcpManual.

func NewOpenAPIConverter

func NewOpenAPIConverter(raw interface{}, url, name string) *OpenAPIConverter

NewOpenAPIConverter creates a new converter for OpenAPI raw definitions.

func (*OpenAPIConverter) Convert

func (c *OpenAPIConverter) Convert() UtcpManual

Convert processes the OpenAPI spec and returns a UtcpManual.

type Provider

type Provider interface {
	// Type returns the discriminator.
	Type() ProviderType
}

Provider is implemented by all concrete provider types.

func UnmarshalProvider

func UnmarshalProvider(data []byte) (Provider, error)

UnmarshalProvider inspects "provider_type" and returns the right struct.

type ProviderType

type ProviderType string

ProviderType is the kind of provider.

const (
	ProviderHTTP       ProviderType = "http"
	ProviderSSE        ProviderType = "sse"
	ProviderHTTPStream ProviderType = "http_stream"
	ProviderCLI        ProviderType = "cli"
	ProviderWebSocket  ProviderType = "websocket"
	ProviderGRPC       ProviderType = "grpc"
	ProviderGraphQL    ProviderType = "graphql"
	ProviderTCP        ProviderType = "tcp"
	ProviderUDP        ProviderType = "udp"
	ProviderWebRTC     ProviderType = "webrtc"
	ProviderMCP        ProviderType = "mcp"
	ProviderText       ProviderType = "text"
)

type SSEClientTransport

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

SSEClientTransport implements Server-Sent Events over HTTP for UTCP tools.

func NewSSETransport

func NewSSETransport(logger func(format string, args ...interface{})) *SSEClientTransport

NewSSETransport constructs a new SSEClientTransport.

func (*SSEClientTransport) CallTool

func (t *SSEClientTransport) CallTool(ctx context.Context, toolName string, args map[string]interface{}, prov Provider, l *string) (interface{}, error)

CallTool invokes a named tool over SSE by POSTing inputs and decoding JSON output.

func (*SSEClientTransport) DeregisterToolProvider

func (t *SSEClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider cleans up any resources (no-op for SSE).

func (*SSEClientTransport) RegisterToolProvider

func (t *SSEClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider registers an SSE-based provider by fetching its tool list.

type SSEProvider

type SSEProvider struct {
	BaseProvider
	URL          string            `json:"url"`
	EventType    *string           `json:"event_type,omitempty"`
	Reconnect    bool              `json:"reconnect"`     // default true
	RetryTimeout int               `json:"retry_timeout"` // ms, default 30000
	Auth         *Auth             `json:"auth,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	BodyField    *string           `json:"body_field,omitempty"`
	HeaderFields []string          `json:"header_fields,omitempty"`
}

SSEProvider represents Server-Sent Events.

type StreamableHTTPClientTransport

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

StreamableHTTPClientTransport implements HTTP with streaming support.

func NewStreamableHTTPTransport

func NewStreamableHTTPTransport(logger func(format string, args ...interface{})) *StreamableHTTPClientTransport

NewStreamableHTTPTransport constructs a new StreamableHTTPClientTransport.

func (*StreamableHTTPClientTransport) CallTool

func (t *StreamableHTTPClientTransport) CallTool(ctx context.Context, toolName string, args map[string]interface{}, prov Provider, l *string) (interface{}, error)

CallTool invokes a named tool via HTTP POST for streaming providers.

func (*StreamableHTTPClientTransport) DeregisterToolProvider

func (t *StreamableHTTPClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider clears any streaming-specific state (no-op).

func (*StreamableHTTPClientTransport) RegisterToolProvider

func (t *StreamableHTTPClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider registers an HTTP streaming provider by fetching its tool list.

type StreamableHttpProvider

type StreamableHttpProvider struct {
	BaseProvider
	URL          string            `json:"url"`
	HTTPMethod   string            `json:"http_method"`  // GET, POST
	ContentType  string            `json:"content_type"` // default application/octet-stream
	ChunkSize    int               `json:"chunk_size"`   // bytes, default 4096
	Timeout      int               `json:"timeout"`      // ms, default 60000
	Headers      map[string]string `json:"headers,omitempty"`
	Auth         *Auth             `json:"auth,omitempty"`
	BodyField    *string           `json:"body_field,omitempty"`
	HeaderFields []string          `json:"header_fields,omitempty"`
}

StreamableHttpProvider is HTTP chunked transfer encoding.

type TCPClientTransport added in v1.1.9

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

TCPClientTransport implements ClientTransport over raw TCP sockets.

func NewTCPClientTransport added in v1.1.9

func NewTCPClientTransport(logger func(format string, args ...interface{})) *TCPClientTransport

NewTCPClientTransport creates a new instance with an optional logger.

func (*TCPClientTransport) CallTool added in v1.1.9

func (t *TCPClientTransport) CallTool(ctx context.Context, toolName string, args map[string]any, prov Provider, l *string) (any, error)

CallTool connects to the provider and sends a tool invocation request.

func (*TCPClientTransport) Close added in v1.1.9

func (t *TCPClientTransport) Close() error

Close cleans up resources (no-op).

func (*TCPClientTransport) DeregisterToolProvider added in v1.1.9

func (t *TCPClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider is a no-op for TCP transport.

func (*TCPClientTransport) RegisterToolProvider added in v1.1.9

func (t *TCPClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider connects to the TCP provider and retrieves its manual.

type TCPProvider

type TCPProvider struct {
	BaseProvider
	Host    string `json:"host"`
	Port    int    `json:"port"`
	Timeout int    `json:"timeout"` // ms, default 30000

}

TCPProvider represents a raw TCP socket.

type TagSearchStrategy

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

TagSearchStrategy implements a tool search strategy based on tags and description keywords.

func NewTagSearchStrategy

func NewTagSearchStrategy(repo ToolRepository, descriptionWeight float64) *TagSearchStrategy

NewTagSearchStrategy creates a new TagSearchStrategy with the given repository and description weight.

func (*TagSearchStrategy) SearchTools

func (s *TagSearchStrategy) SearchTools(ctx context.Context, query string, limit int) ([]Tool, error)

SearchTools returns tools ordered by relevance to the query, using explicit tags and description keywords.

type TextClientTransport

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

TextClientTransport is a simple in-memory/text-based transport.

func NewTextTransport

func NewTextTransport(prefix string) *TextClientTransport

NewTextTransport constructs a TextClientTransport.

func (*TextClientTransport) CallTool

func (t *TextClientTransport) CallTool(ctx context.Context, toolName string, args map[string]interface{}, prov Provider, l *string) (interface{}, error)

CallTool invokes a named in-memory tool handler.

func (*TextClientTransport) DeregisterToolProvider

func (t *TextClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider cleans up in-memory tools.

func (*TextClientTransport) RegisterToolProvider

func (t *TextClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider loads tool definitions from a local text (JSON) file.

type TextProvider

type TextProvider struct {
	BaseProvider
	FilePath string `json:"file_path"`
}

TextProvider reads tool defs from a file.

type TextTransport

type TextTransport interface {
	ClientTransport
	SetBasePath(path string)
}

TextTransport interface for setting base path kept here for tests relying on it

type Tool

type Tool struct {
	Name                string                `json:"name"`
	Description         string                `json:"description"`
	Inputs              ToolInputOutputSchema `json:"inputs"`
	Outputs             ToolInputOutputSchema `json:"outputs"`
	Tags                []string              `json:"tags"`
	AverageResponseSize *int                  `json:"average_response_size,omitempty"`
	Provider            Provider              `json:"tool_provider"`
	Handler             ToolHandler           `json:"-"`
}

Tool holds the metadata for a single UTCP tool.

func GetTools

func GetTools() []Tool

GetTools returns all registered tools.

type ToolHandler

type ToolHandler func(ctx map[string]interface{}, inputs map[string]interface{}) (outputs map[string]interface{}, err error)

ToolHandler is the signature your Go tool functions must satisfy. The first argument is your execution context (if any), here we use a generic map. You can replace `map[string]interface{}` with a concrete struct or interface as needed.

type ToolInputOutputSchema

type ToolInputOutputSchema struct {
	Type        string                 `json:"type"`                 // e.g. "object", "array", "string"
	Properties  map[string]interface{} `json:"properties,omitempty"` // field schemas
	Required    []string               `json:"required,omitempty"`
	Description string                 `json:"description,omitempty"`
	Title       string                 `json:"title,omitempty"`
	Items       map[string]interface{} `json:"items,omitempty"` // for arrays
	Enum        []interface{}          `json:"enum,omitempty"`
	Minimum     *float64               `json:"minimum,omitempty"`
	Maximum     *float64               `json:"maximum,omitempty"`
	Format      string                 `json:"format,omitempty"` // e.g. "date-time"
}

ToolInputOutputSchema mirrors your JSON schema description.

type ToolProvider

type ToolProvider interface {
	Type() string
	Name() string
}

ProviderUnion is your existing Go interface/union for providers.

type ToolRepository

type ToolRepository interface {
	// SaveProviderWithTools saves a provider and its associated tools.
	SaveProviderWithTools(ctx context.Context, provider Provider, tools []Tool) error

	// RemoveProvider removes a provider and all its tools by name.
	// Returns an error if the provider does not exist.
	RemoveProvider(ctx context.Context, providerName string) error

	// RemoveTool removes a single tool by name.
	// Returns an error if the tool does not exist.
	RemoveTool(ctx context.Context, toolName string) error

	// GetTool retrieves a tool by name.
	// Returns (nil, nil) if the tool is not found.
	GetTool(ctx context.Context, toolName string) (*Tool, error)

	// GetTools returns all tools in the repository.
	GetTools(ctx context.Context) ([]Tool, error)

	// GetToolsByProvider returns all tools for a specific provider.
	// Returns (nil, nil) if the provider is not found.
	GetToolsByProvider(ctx context.Context, providerName string) ([]Tool, error)

	// GetProvider retrieves a provider by name.
	// Returns (nil, nil) if the provider is not found.
	GetProvider(ctx context.Context, providerName string) (*Provider, error)

	// GetProviders returns all providers in the repository.
	GetProviders(ctx context.Context) ([]Provider, error)
}

ToolRepository defines the contract for persisting providers and their tools.

func NewInMemoryToolRepository

func NewInMemoryToolRepository() ToolRepository

type ToolSearchStrategy

type ToolSearchStrategy interface {
	// SearchTools returns up to `limit` tools matching `query`.
	// A limit of 0 means “no limit” (return all matches).
	//
	// ctx carries deadlines, cancellation signals, and other request-scoped values.
	SearchTools(ctx context.Context, query string, limit int) ([]Tool, error)
}

ToolSearchStrategy is an interface for any component that knows how to search for tools based on a query.

type UDPProvider

type UDPProvider struct {
	BaseProvider
	Host    string `json:"host"`
	Port    int    `json:"port"`
	Timeout int    `json:"timeout"`
}

UDPProvider represents a UDP socket.

type UDPTransport added in v1.1.9

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

UDPTransport implements the ClientTransport interface over UDP.

func NewUDPTransport added in v1.1.9

func NewUDPTransport(logger func(format string, args ...interface{})) *UDPTransport

NewUDPTransport constructs a UDPTransport with optional logging.

func (*UDPTransport) CallTool added in v1.1.9

func (t *UDPTransport) CallTool(ctx context.Context, toolName string, args map[string]any, prov Provider, l *string) (any, error)

CallTool sends a JSON request with tool name and arguments and waits for the response.

func (*UDPTransport) DeregisterToolProvider added in v1.1.9

func (t *UDPTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider is a no-op for UDPTransport.

func (*UDPTransport) RegisterToolProvider added in v1.1.9

func (t *UDPTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider discovers tools by sending a DISCOVER message to the server.

type UtcpClient

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

UtcpClient holds all state and implements UtcpClientInterface.

func NewUTCPClient

func NewUTCPClient(
	ctx context.Context,
	cfg *UtcpClientConfig,
	repo ToolRepository,
	strat ToolSearchStrategy,
) (*UtcpClient, error)

NewUtcpClient constructs a new client, loading providers if configured.

func (*UtcpClient) CallTool

func (c *UtcpClient) CallTool(
	ctx context.Context,
	toolName string,
	args map[string]any,
) (any, error)

func (*UtcpClient) DeregisterToolProvider

func (c *UtcpClient) DeregisterToolProvider(ctx context.Context, providerName string) error

func (*UtcpClient) RegisterToolProvider

func (c *UtcpClient) RegisterToolProvider(
	ctx context.Context,
	prov Provider,
) ([]Tool, error)

RegisterToolProvider applies variable substitution, picks the right transport, and registers tools.

func (*UtcpClient) SearchTools

func (c *UtcpClient) SearchTools(query string, limit int) ([]Tool, error)

type UtcpClientConfig

type UtcpClientConfig struct {
	// Variables explicitly passed in (takes precedence)
	Variables map[string]string

	// Optional path to a providers‐definition file
	ProvidersFilePath string

	// A list of providers to load from (e.g. .env, AWS SSM, Vault, etc.)
	LoadVariablesFrom []UtcpVariablesConfig
}

UtcpClientConfig holds your resolved variables and provider settings.

func NewClientConfig

func NewClientConfig() *UtcpClientConfig

NewClientConfig constructs a config with sensible defaults.

type UtcpClientInterface

type UtcpClientInterface interface {
	RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)
	DeregisterToolProvider(ctx context.Context, providerName string) error
	CallTool(ctx context.Context, toolName string, args map[string]any) (any, error)
	SearchTools(ctx context.Context, query string, limit int) ([]Tool, error)
}

UtcpClientInterface defines the public API.

type UtcpDotEnv

type UtcpDotEnv struct {
	EnvFilePath string
}

UtcpDotEnv implements UtcpVariablesConfig by loading a .env file.

func NewDotEnv

func NewDotEnv(path string) *UtcpDotEnv

func (*UtcpDotEnv) Get

func (u *UtcpDotEnv) Get(key string) (string, error)

Get loads the file and looks up a single key.

func (*UtcpDotEnv) Load

func (u *UtcpDotEnv) Load() (map[string]string, error)

Load reads the .env file and returns a map of key→value.

type UtcpManual

type UtcpManual struct {
	Version string
	Tools   []Tool
	Name    string // optional, for OpenAPI-derived manuals
}

UtcpManual represents a manual with a version and a set of tools.

func NewUtcpManualFromMap

func NewUtcpManualFromMap(m map[string]interface{}) UtcpManual

NewUtcpManualFromMap constructs a UtcpManual from a raw map representation.

type UtcpVariableNotFound

type UtcpVariableNotFound struct {
	VariableName string
}

UtcpVariableNotFound is returned when a requested variable isn't present.

func (*UtcpVariableNotFound) Error

func (e *UtcpVariableNotFound) Error() string

type UtcpVariablesConfig

type UtcpVariablesConfig interface {
	// Load returns all variables available from this provider.
	Load() (map[string]string, error)
	// Get returns a single variable value or an error if not present.
	Get(key string) (string, error)
}

UtcpVariablesConfig is the interface for any variable‐loading strategy.

type WebRTCClientTransport added in v1.1.9

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

WebRTCClientTransport implements ClientTransport using WebRTC data channels.

func NewWebRTCClientTransport added in v1.1.9

func NewWebRTCClientTransport(logger func(format string, args ...interface{})) *WebRTCClientTransport

NewWebRTCClientTransport creates a new transport instance.

func (*WebRTCClientTransport) CallTool added in v1.1.9

func (t *WebRTCClientTransport) CallTool(ctx context.Context, toolName string, args map[string]any, prov Provider, l *string) (any, error)

CallTool sends a request over the WebRTC data channel and waits for a response.

func (*WebRTCClientTransport) DeregisterToolProvider added in v1.1.9

func (t *WebRTCClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

DeregisterToolProvider closes the WebRTC connection.

func (*WebRTCClientTransport) RegisterToolProvider added in v1.1.9

func (t *WebRTCClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

RegisterToolProvider connects to the remote peer and returns its tools.

type WebRTCProvider

type WebRTCProvider struct {
	BaseProvider
	SignalingServer string `json:"signaling_server"`
	PeerID          string `json:"peer_id"`
	DataChannelName string `json:"data_channel_name"`
}

WebRTCProvider represents a WebRTC data channel.

type WebSocketClientTransport added in v1.1.9

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

func NewWebSocketTransport added in v1.1.9

func NewWebSocketTransport(logger func(format string, args ...interface{})) *WebSocketClientTransport

func (*WebSocketClientTransport) CallTool added in v1.1.9

func (t *WebSocketClientTransport) CallTool(ctx context.Context, toolName string, args map[string]any, prov Provider, l *string) (any, error)

func (*WebSocketClientTransport) DeregisterToolProvider added in v1.1.9

func (t *WebSocketClientTransport) DeregisterToolProvider(ctx context.Context, prov Provider) error

func (*WebSocketClientTransport) RegisterToolProvider added in v1.1.9

func (t *WebSocketClientTransport) RegisterToolProvider(ctx context.Context, prov Provider) ([]Tool, error)

type WebSocketProvider

type WebSocketProvider struct {
	BaseProvider
	URL          string            `json:"url"`
	Protocol     *string           `json:"protocol,omitempty"`
	KeepAlive    bool              `json:"keep_alive"`
	Auth         *Auth             `json:"auth,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	HeaderFields []string          `json:"header_fields,omitempty"`
}

WebSocketProvider represents a WebSocket connection.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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