tool

package
v0.0.0-...-be7b520 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Overview

Package tool defines the interface for tools that can be executed by the upstream service.

Package tool is a generated GoMock package.

Index

Constants

View Source
const (

	// HealthStatusUnhealthy indicates that a service is in an unhealthy state.
	HealthStatusUnhealthy = "unhealthy"
)

Variables

View Source
var ErrToolNotFound = errors.New("unknown tool")

ErrToolNotFound is returned when a requested tool cannot be found.

Functions

func CalculateConfigHash

func CalculateConfigHash(t *configv1.ToolDefinition) (string, error)

CalculateConfigHash computes the SHA256 hash of a configuration tool definition.

func CalculateHash

func CalculateHash(t *v1.Tool) (string, error)

CalculateHash computes the SHA256 hash of a runtime tool definition.

func ConvertMCPToolToProto

func ConvertMCPToolToProto(tool *mcp.Tool) (*pb.Tool, error)

ConvertMCPToolToProto transforms an *mcp.Tool, which uses a flexible schema representation, into a protobuf-defined *pb.Tool with a structured input schema. This is used to standardize tool definitions within the system.

Parameters:

  • tool: *mcp.Tool. The MCP tool definition to convert.

Returns:

  • *pb.Tool: The corresponding protobuf tool definition.
  • error: An error if conversion fails (e.g. invalid schema).

func ConvertMcpFieldsToInputSchemaProperties

func ConvertMcpFieldsToInputSchemaProperties(fields []*protobufparser.McpField) (*structpb.Struct, error)

ConvertMcpFieldsToInputSchemaProperties converts a slice of McpField, which represent fields from a protobuf message, into a structpb.Struct that can be used as the `properties` field in a JSON schema.

Parameters:

  • fields: []*protobufparser.McpField. The list of fields to convert.

Returns:

  • *structpb.Struct: A struct representing the properties JSON schema.
  • error: An error if conversion fails.

func ConvertProtoToMCPTool

func ConvertProtoToMCPTool(pbTool *pb.Tool) (*mcp.Tool, error)

ConvertProtoToMCPTool transforms a protobuf-defined *pb.Tool into an *mcp.Tool. This is the reverse of convertMCPToolToProto and is used when exposing internally defined tools to the outside world.

Parameters:

  • pbTool: *pb.Tool. The protobuf tool definition to convert.

Returns:

  • *mcp.Tool: The corresponding MCP tool definition.
  • error: An error if conversion fails.

func ConvertToolDefinitionToProto

func ConvertToolDefinitionToProto(toolDef *configv1.ToolDefinition, inputSchema, outputSchema *structpb.Struct) (*pb.Tool, error)

ConvertToolDefinitionToProto transforms a *configv1.ToolDefinition into a *pb.Tool.

Parameters:

  • toolDef: *configv1.ToolDefinition. The tool definition from configuration.
  • inputSchema: *structpb.Struct. The input schema for the tool.
  • outputSchema: *structpb.Struct. The output schema for the tool.

Returns:

  • *pb.Tool: The protobuf tool definition.
  • error: An error if conversion fails.

func EvaluateCallPolicy

func EvaluateCallPolicy(policies []*configv1.CallPolicy, toolName, callID string, arguments []byte) (bool, error)

EvaluateCallPolicy checks if a call should be allowed based on the policies.

Summary: Evaluates call policies against a tool execution.

If arguments is nil, it performs a static check (ignoring rules with argument_regex). It returns true if the call is allowed, false otherwise.

Parameters:

  • policies: []*configv1.CallPolicy. The list of policies to evaluate.
  • toolName: string. The name of the tool being called.
  • callID: string. The unique ID of the call.
  • arguments: []byte. The arguments of the call (can be nil).

Returns:

  • bool: True if the call is allowed, false otherwise.
  • error: An error if evaluation fails.

func EvaluateCompiledCallPolicy

func EvaluateCompiledCallPolicy(policies []*CompiledCallPolicy, toolName, callID string, arguments []byte) (bool, error)

EvaluateCompiledCallPolicy checks if a call should be allowed based on the compiled policies.

Summary: Evaluates compiled call policies.

Parameters:

  • policies: []*CompiledCallPolicy. The list of compiled policies to evaluate.
  • toolName: string. The name of the tool being called.
  • callID: string. The unique ID of the call.
  • arguments: []byte. The arguments of the call (can be nil).

Returns:

  • bool: True if the call is allowed, false otherwise.
  • error: An error if evaluation fails.

func GetFullyQualifiedToolName

func GetFullyQualifiedToolName(serviceID, methodName string) string

GetFullyQualifiedToolName constructs a fully qualified tool name from a service ID and a method name.

Summary: Constructs a fully qualified tool name.

Parameters:

  • serviceID: string. The unique identifier of the service.
  • methodName: string. The name of the tool/method within the service.

Returns:

  • string: The combined, fully qualified tool name.

func GetJSONSchemaForScalarType

func GetJSONSchemaForScalarType(scalarType, description string) (*jsonschema.Schema, error)

GetJSONSchemaForScalarType maps a protobuf scalar type (e.g., "TYPE_STRING", "TYPE_INT32") to its corresponding JSON schema type ("string", "integer"). It is a helper function for building JSON schemas from protobuf definitions.

Parameters:

  • scalarType: string. The protobuf scalar type name.
  • description: string. The description for the schema.

Returns:

  • *jsonschema.Schema: The generated JSON schema.
  • error: An error if the scalar type is unsupported.

func NewContextWithCacheControl

func NewContextWithCacheControl(ctx context.Context, cc *CacheControl) context.Context

NewContextWithCacheControl creates a new context with the given CacheControl.

Summary: Embeds CacheControl into the context.

Parameters:

  • ctx: context.Context. The context to extend.
  • cc: *CacheControl. The CacheControl instance to embed.

Returns:

  • context.Context: A new context containing the CacheControl.

func NewContextWithSampler deprecated

func NewContextWithSampler(ctx context.Context, s Sampler) context.Context

NewContextWithSampler creates a new context with the given Sampler.

Deprecated: Use NewContextWithSession instead.

func NewContextWithSession

func NewContextWithSession(ctx context.Context, s Session) context.Context

NewContextWithSession creates a new context with the given Session.

ctx is the context for the request. s is the s.

Returns the result.

func NewContextWithTool

func NewContextWithTool(ctx context.Context, t Tool) context.Context

NewContextWithTool creates a new context with the given tool embedded.

Summary: Embeds a tool into the context.

Parameters:

  • ctx: context.Context. The context to extend.
  • t: Tool. The tool instance to embed in the context.

Returns:

  • context.Context: A new context containing the tool.

func ParseToolName

func ParseToolName(toolName string) (namespace string, tool string, err error)

ParseToolName deconstructs a fully qualified tool name into its namespace (service ID) and the bare tool name.

Summary: Parses a fully qualified tool name.

Parameters:

  • toolName: string. The fully qualified tool name to parse.

Returns:

  • namespace: string. The service ID/namespace.
  • tool: string. The bare tool name.
  • err: error. An error if the tool name is invalid.

func SanitizeJSONSchema

func SanitizeJSONSchema(schema any) (*structpb.Struct, error)

SanitizeJSONSchema attempts to fix common schema issues that cause strict MCP clients to fail. It takes a raw map[string]interface{} (or compatible) and returns a *structpb.Struct. This function does NOT modify the input schema.

func ShouldExport

func ShouldExport(name string, policy *configv1.ExportPolicy) bool

ShouldExport determines whether a named item (tool, prompt, or resource) should be exported.

Summary: Checks if an item should be exported based on policy.

Parameters:

  • name: string. The name of the item.
  • policy: *configv1.ExportPolicy. The export policy to evaluate.

Returns:

  • bool: True if the item should be exported, false otherwise.

func VerifyConfigIntegrity

func VerifyConfigIntegrity(t *configv1.ToolDefinition) error

VerifyConfigIntegrity checks if the config tool definition matches its expected hash.

func VerifyIntegrity

func VerifyIntegrity(t *v1.Tool) error

VerifyIntegrity checks if the tool definition matches its expected hash.

Types

type Action

type Action int

Action defines the decision made by a pre-call hook.

Summary: Enumeration of possible hook actions.

const (
	// ActionAllow indicates that the action is allowed to proceed.
	//
	// Summary: Allow action.
	ActionAllow Action = 0
	// ActionDeny indicates that the action is denied and should be blocked.
	//
	// Summary: Deny action.
	ActionDeny Action = 1
	// ActionSaveCache indicates that the result should be saved to the cache.
	//
	// Summary: Save to cache action.
	ActionSaveCache Action = 2
	// ActionDeleteCache indicates that the associated cache entry should be invalidated.
	//
	// Summary: Delete from cache action.
	ActionDeleteCache Action = 3
)

type CacheControl

type CacheControl struct {
	Action Action
}

CacheControl is a mutable struct to pass cache control instructions via context.

Summary: Context-based cache control instructions.

func GetCacheControl

func GetCacheControl(ctx context.Context) (*CacheControl, bool)

GetCacheControl retrieves the CacheControl from the context.

Summary: Retrieves CacheControl from the context.

Parameters:

  • ctx: context.Context. The context to search.

Returns:

  • *CacheControl: The CacheControl instance if found.
  • bool: True if CacheControl exists, false otherwise.

type Callable

type Callable interface {
	// Call executes the callable with the given request.
	//
	// Parameters:
	//   - ctx: The context for the request.
	//   - req: The execution request details.
	//
	// Returns:
	//   - any: The result of the execution.
	//   - error: An error if the operation fails.
	Call(ctx context.Context, req *ExecutionRequest) (any, error)
}

Callable is an interface that represents a callable tool.

Summary: Interface for executing a tool.

type CallableTool

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

CallableTool implements the Tool interface for a tool that is executed by a Callable.

func NewCallableTool

func NewCallableTool(toolDef *configv1.ToolDefinition, serviceConfig *configv1.UpstreamServiceConfig, callable Callable, inputSchema, outputSchema *structpb.Struct) (*CallableTool, error)

NewCallableTool creates a new CallableTool.

Summary: Creates a new tool that wraps a Callable interface.

Parameters:

  • toolDef: *configv1.ToolDefinition. The definition of the tool.
  • serviceConfig: *configv1.UpstreamServiceConfig. The configuration of the service the tool belongs to.
  • callable: Callable. The callable implementation for execution.
  • inputSchema: *structpb.Struct. The input schema for the tool.
  • outputSchema: *structpb.Struct. The output schema for the tool.

Returns:

  • *CallableTool: A pointer to the created CallableTool.
  • error: An error if creation fails.

func (*CallableTool) Callable

func (t *CallableTool) Callable() Callable

Callable returns the underlying Callable of the tool.

Summary: Retrieves the underlying Callable interface.

Returns:

  • Callable: The underlying callable.

func (*CallableTool) Execute

func (t *CallableTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the tool.

Summary: Executes the underlying callable.

Parameters:

  • ctx: context.Context. The context for the request.
  • req: *ExecutionRequest. The request object containing parameters.

Returns:

  • any: The result of the execution.
  • error: An error if the operation fails.

func (CallableTool) GetCacheConfig

func (t CallableTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the tool, or nil if caching is disabled.

Summary: Retrieves the cache configuration (always nil for baseTool).

Returns:

  • *configv1.CacheConfig: Always returns nil.

func (CallableTool) MCPTool

func (t CallableTool) MCPTool() *mcp.Tool

MCPTool returns the MCP tool definition.

Summary: Retrieves the MCP-compliant tool definition.

Returns:

  • *mcp.Tool: The MCP tool definition.

Side Effects:

  • Lazily converts the proto definition to MCP format on first call.

func (CallableTool) Tool

func (t CallableTool) Tool() *v1.Tool

Tool returns the protobuf definition of the tool.

Summary: Retrieves the protobuf definition.

Returns:

  • *v1.Tool: The protobuf tool definition.

type CommandTool

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

CommandTool implements the Tool interface for a tool that is executed as a local command-line process.

Summary: Tool implementation for command-line services (via executor).

It maps tool inputs to command-line arguments and environment variables.

func (*CommandTool) Execute

func (t *CommandTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the command-line tool.

Summary: Executes the command-line tool via executor.

It constructs a command with arguments and environment variables derived from the tool inputs, runs the command, and returns its output.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The execution request.

Returns:

  • any: The execution result.
  • error: An error if execution fails.

func (*CommandTool) GetCacheConfig

func (t *CommandTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the command-line tool.

Returns:

  • *configv1.CacheConfig: The cache configuration, if any.

func (*CommandTool) MCPTool

func (t *CommandTool) MCPTool() *mcp.Tool

MCPTool returns the MCP-compliant tool definition.

It lazily converts the internal protobuf definition to the MCP format on first access.

Returns:

  • *mcp.Tool: The MCP tool definition.

func (*CommandTool) Tool

func (t *CommandTool) Tool() *v1.Tool

Tool returns the protobuf definition of the command-line tool.

Returns:

  • *v1.Tool: The underlying protobuf definition.

type CompiledCallPolicy

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

CompiledCallPolicy holds a compiled version of a call policy.

Summary: Represents a pre-compiled call policy for efficient evaluation.

func CompileCallPolicies

func CompileCallPolicies(policies []*configv1.CallPolicy) ([]*CompiledCallPolicy, error)

CompileCallPolicies compiles a list of call policies into an efficient runtime format.

Summary: Compiles call policies for runtime usage.

Parameters:

  • policies: []*configv1.CallPolicy. The list of policies to compile.

Returns:

  • []*CompiledCallPolicy: The compiled policies.
  • error: An error if compilation fails (e.g., invalid regex).

func NewCompiledCallPolicy

func NewCompiledCallPolicy(policy *configv1.CallPolicy) (*CompiledCallPolicy, error)

NewCompiledCallPolicy compiles a single call policy.

Summary: Compiles a single call policy.

Parameters:

  • policy: *configv1.CallPolicy. The policy to compile.

Returns:

  • *CompiledCallPolicy: The compiled policy.
  • error: An error if compilation fails.

type ExecutionFunc

type ExecutionFunc func(ctx context.Context, req *ExecutionRequest) (any, error)

ExecutionFunc represents the next middleware in the chain.

Summary: Function signature for tool execution middleware.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The request payload.

Returns:

  • any: The execution result.
  • error: An error if execution fails.

type ExecutionMiddleware

type ExecutionMiddleware interface {
	// Execute performs the middleware logic wrapping the next handler in the chain.
	//
	// Parameters:
	//   - ctx: context.Context. The context for the execution.
	//   - req: *ExecutionRequest. The execution request.
	//   - next: ExecutionFunc. The next handler in the chain.
	//
	// Returns:
	//   - any: The result of the execution.
	//   - error: An error if execution fails.
	Execute(ctx context.Context, req *ExecutionRequest, next ExecutionFunc) (any, error)
}

ExecutionMiddleware defines the interface for middleware that intercepts tool execution.

type ExecutionRequest

type ExecutionRequest struct {
	// ToolName is the name of the tool to be executed.
	ToolName string `json:"name"`
	// ToolInputs is the raw JSON message of the tool inputs. It is used by
	// tools that need to unmarshal the inputs into a specific struct.
	ToolInputs stdjson.RawMessage `json:"toolInputs"`
	// Arguments is a map of the tool inputs. It is used by tools that need to
	// access the inputs as a map.
	Arguments map[string]interface{} `json:"arguments"`
	// DryRun indicates whether the tool should be executed in dry-run mode.
	// In dry-run mode, the tool should validate inputs and return a preview
	// of the execution without performing any side effects.
	DryRun bool `json:"dryRun"`
	// Tool is the resolved tool instance. Populated internally to avoid re-lookup.
	Tool Tool `json:"-"`
}

ExecutionRequest represents a request to execute a specific tool, including its name and input arguments as a raw JSON message.

Summary: Request payload for tool execution.

type GRPCTool

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

GRPCTool implements the Tool interface for a tool that is exposed via a gRPC endpoint.

Summary: Tool implementation for gRPC services.

It handles the marshalling of JSON inputs to protobuf messages and invoking the gRPC method.

func NewGRPCTool

func NewGRPCTool(tool *v1.Tool, poolManager *pool.Manager, serviceID string, method protoreflect.MethodDescriptor, callDefinition *configv1.GrpcCallDefinition, resilienceConfig *configv1.ResilienceConfig) *GRPCTool

NewGRPCTool creates a new GRPCTool instance.

Summary: Initializes a new GRPCTool.

Parameters:

  • tool: *v1.Tool. The protobuf definition of the tool.
  • poolManager: *pool.Manager. The connection pool manager for gRPC connections.
  • serviceID: string. The identifier for the service.
  • method: protoreflect.MethodDescriptor. The gRPC method descriptor.
  • callDefinition: *configv1.GrpcCallDefinition. The configuration for the gRPC call.
  • resilienceConfig: *configv1.ResilienceConfig. The resilience configuration.

Returns:

  • *GRPCTool: The initialized GRPCTool.

func (*GRPCTool) Execute

func (t *GRPCTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the gRPC tool.

Summary: Executes the gRPC tool call.

It retrieves a client from the pool, unmarshals the JSON input into a protobuf request message, invokes the gRPC method, and marshals the protobuf response back to JSON.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The execution request.

Returns:

  • any: The execution result (usually a map or JSON string).
  • error: An error if execution fails.

func (*GRPCTool) GetCacheConfig

func (t *GRPCTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the gRPC tool.

Returns:

  • *configv1.CacheConfig: The cache configuration, if any.

func (*GRPCTool) MCPTool

func (t *GRPCTool) MCPTool() *mcp.Tool

MCPTool returns the MCP-compliant tool definition.

It lazily converts the internal protobuf definition to the MCP format on first access.

Returns:

  • *mcp.Tool: The MCP tool definition.

func (*GRPCTool) Tool

func (t *GRPCTool) Tool() *v1.Tool

Tool returns the protobuf definition of the gRPC tool.

Returns:

  • *v1.Tool: The underlying protobuf definition.

type HTTPTool

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

HTTPTool implements the Tool interface for a tool exposed via an HTTP endpoint.

Summary: Tool implementation for HTTP services.

It constructs and sends an HTTP request based on the tool definition and input, handling parameter mapping, authentication, and transformations.

func NewHTTPTool

func NewHTTPTool(tool *v1.Tool, poolManager *pool.Manager, serviceID string, authenticator auth.UpstreamAuthenticator, callDefinition *configv1.HttpCallDefinition, cfg *configv1.ResilienceConfig, policies []*configv1.CallPolicy, callID string) *HTTPTool

NewHTTPTool creates a new HTTPTool instance.

Summary: Initializes a new HTTPTool.

Parameters:

  • tool: *v1.Tool. The protobuf definition of the tool.
  • poolManager: *pool.Manager. The connection pool manager for HTTP connections.
  • serviceID: string. The identifier for the service.
  • authenticator: auth.UpstreamAuthenticator. The authenticator for upstream requests.
  • callDefinition: *configv1.HttpCallDefinition. The configuration for the HTTP call.
  • cfg: *configv1.ResilienceConfig. The resilience configuration.
  • policies: []*configv1.CallPolicy. The security policies for the call.
  • callID: string. The unique identifier for the call.

Returns:

  • *HTTPTool: The initialized HTTPTool.

func (*HTTPTool) Execute

func (t *HTTPTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the HTTP tool.

Summary: Executes the HTTP tool call.

It builds an HTTP request by mapping input parameters to the path, query, and body, applies any configured transformations, sends the request, and processes the response.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The execution request.

Returns:

  • any: The execution result.
  • error: An error if execution fails.

func (*HTTPTool) GetCacheConfig

func (t *HTTPTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the HTTP tool.

Returns:

  • *configv1.CacheConfig: The cache configuration, if any.

func (*HTTPTool) MCPTool

func (t *HTTPTool) MCPTool() *mcp.Tool

MCPTool returns the MCP-compliant tool definition.

It lazily converts the internal protobuf definition to the MCP format on first access.

Returns:

  • *mcp.Tool: The MCP tool definition.

func (*HTTPTool) Tool

func (t *HTTPTool) Tool() *v1.Tool

Tool returns the protobuf definition of the HTTP tool.

Returns:

  • *v1.Tool: The underlying protobuf definition.

type LocalCommandTool

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

LocalCommandTool implements the Tool interface for a tool that is executed as a local command-line process.

Summary: Tool implementation for local command-line services.

It maps tool inputs to command-line arguments and environment variables.

func (*LocalCommandTool) Execute

func (t *LocalCommandTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the command-line tool.

Summary: Executes the local command-line tool.

It constructs a command with arguments and environment variables derived from the tool inputs, runs the command, and returns its output.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The execution request.

Returns:

  • any: The execution result.
  • error: An error if execution fails.

func (*LocalCommandTool) GetCacheConfig

func (t *LocalCommandTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the command-line tool.

Returns:

  • *configv1.CacheConfig: The cache configuration, if any.

func (*LocalCommandTool) MCPTool

func (t *LocalCommandTool) MCPTool() *mcp.Tool

MCPTool returns the MCP-compliant tool definition.

It lazily converts the internal protobuf definition to the MCP format on first access.

Returns:

  • *mcp.Tool: The MCP tool definition.

func (*LocalCommandTool) Tool

func (t *LocalCommandTool) Tool() *v1.Tool

Tool returns the protobuf definition of the command-line tool.

Returns:

  • *v1.Tool: The underlying protobuf definition.

type MCPServerProvider

type MCPServerProvider interface {
	// Server returns the underlying MCP server instance.
	//
	// Returns:
	//   - *mcp.Server: The MCP server instance.
	Server() *mcp.Server
}

MCPServerProvider defines an interface for components that can provide an instance of an *mcp.Server.

This interface is used to decouple the Manager from the concrete server implementation, avoiding circular dependencies.

type MCPTool

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

MCPTool implements the Tool interface for a tool that is exposed via another MCP-compliant service.

Summary: Tool implementation for proxying to MCP services.

It acts as a proxy, forwarding the tool call to the downstream MCP service.

func NewMCPTool

func NewMCPTool(tool *v1.Tool, client client.MCPClient, callDefinition *configv1.MCPCallDefinition) *MCPTool

NewMCPTool creates a new MCPTool instance.

Summary: Initializes a new MCPTool.

Parameters:

  • tool: *v1.Tool. The protobuf definition of the tool.
  • client: client.MCPClient. The MCP client for downstream communication.
  • callDefinition: *configv1.MCPCallDefinition. The configuration for the MCP call.

Returns:

  • *MCPTool: The initialized MCPTool.

func (*MCPTool) Execute

func (t *MCPTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the MCP tool.

Summary: Executes the MCP tool call.

It forwards the tool call, including its name and arguments, to the downstream MCP service using the configured client and applies any necessary transformations to the request and response.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The execution request.

Returns:

  • any: The execution result.
  • error: An error if execution fails.

func (*MCPTool) GetCacheConfig

func (t *MCPTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the MCP tool.

Returns:

  • *configv1.CacheConfig: The cache configuration, if any.

func (*MCPTool) MCPTool

func (t *MCPTool) MCPTool() *mcp.Tool

MCPTool returns the MCP-compliant tool definition.

It lazily converts the internal protobuf definition to the MCP format on first access.

Returns:

  • *mcp.Tool: The MCP tool definition.

func (*MCPTool) Tool

func (t *MCPTool) Tool() *v1.Tool

Tool returns the protobuf definition of the MCP tool.

Returns:

  • *v1.Tool: The underlying protobuf definition.

type Manager

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

Manager is the central component for managing tools in MCP Any.

It handles tool registration, retrieval, execution, and profile-based filtering. It is thread-safe and supports efficient lookups via caching and indexing.

func NewManager

func NewManager(bus *bus.Provider) *Manager

NewManager creates and initializes a new Tool Manager.

Parameters:

  • bus: *bus.Provider. The event bus provider for publishing tool execution events.

Returns:

  • *Manager: A pointer to the newly created Manager.

func (*Manager) AddMiddleware

func (tm *Manager) AddMiddleware(middleware ExecutionMiddleware)

AddMiddleware adds a middleware to the tool manager.

The middleware will be executed as part of the tool execution chain.

Parameters:

  • middleware: ExecutionMiddleware. The middleware instance to add.

func (*Manager) AddServiceInfo

func (tm *Manager) AddServiceInfo(serviceID string, info *ServiceInfo)

AddServiceInfo registers metadata about a service.

It processes the service configuration to set up hooks and call policies.

Parameters:

  • serviceID: string. The unique identifier for the service.
  • info: *ServiceInfo. The ServiceInfo struct containing the service's metadata and configuration.

func (*Manager) AddTool

func (tm *Manager) AddTool(tool Tool) error

AddTool registers a new tool with the manager.

It performs validation, sanitization, and integrity checks. If an MCP server is configured, it also registers the tool with the server.

Parameters:

  • tool: Tool. The tool instance to be added.

Returns:

  • error: An error if validation fails or the tool cannot be added.

func (*Manager) ClearToolsForService

func (tm *Manager) ClearToolsForService(serviceID string)

ClearToolsForService removes all tools associated with a given service ID.

It efficiently cleans up internal indices and caches.

Parameters:

  • serviceID: string. The unique identifier for the service.

Side Effects:

  • Removes entries from the tools map and secondary indices.
  • Invalidates internal caches.

func (*Manager) ExecuteTool

func (tm *Manager) ExecuteTool(ctx context.Context, req *ExecutionRequest) (any, error)

ExecuteTool finds a tool by its name and executes it.

It handles the entire lifecycle of a tool call, including: 1. Resolving the tool. 2. Checking service health. 3. Running pre-execution hooks and policies. 4. Executing the tool logic. 5. Running post-execution hooks. 6. Running middlewares.

Parameters:

  • ctx: context.Context. The context for the tool execution.
  • req: *ExecutionRequest. The request containing the tool name and input arguments.

Returns:

  • any: The result of the execution (type varies by tool).
  • error: An error if the tool is not found, execution is denied, or the tool fails.

Errors:

  • ErrToolNotFound: If the tool cannot be found (includes fuzzy matching suggestions).

Side Effects:

  • Executes the tool logic (which may have side effects).
  • Runs pre/post-execution hooks.
  • Logs execution details.

func (*Manager) GetAllowedServiceIDs

func (tm *Manager) GetAllowedServiceIDs(profileID string) (map[string]bool, bool)

GetAllowedServiceIDs returns a map of allowed service IDs for a given profile.

The returned map uses the service ID as the key and a boolean true as the value.

Parameters:

  • profileID: string. The identifier of the profile.

Returns:

  • map[string]bool: A map of allowed service IDs.
  • bool: True if the profile exists and has cached allowed services.

func (*Manager) GetServiceInfo

func (tm *Manager) GetServiceInfo(serviceID string) (*ServiceInfo, bool)

GetServiceInfo retrieves the metadata for a registered service.

It returns a copy of the service info with secrets stripped from the configuration for security.

Parameters:

  • serviceID: string. The unique identifier for the service.

Returns:

  • *ServiceInfo: The service information.
  • bool: True if the service was found, false otherwise.

func (*Manager) GetTool

func (tm *Manager) GetTool(toolName string) (Tool, bool)

GetTool retrieves a tool from the manager by its fully qualified name.

It first attempts to look up the tool by its exact ID (useful if the client sends the ID). If that fails, it looks up the tool by its client-facing name (using the name map).

Parameters:

  • toolName: string. The name or ID of the tool to retrieve.

Returns:

  • Tool: The tool instance.
  • bool: True if the tool was found, false otherwise.

func (*Manager) GetToolCountForService

func (tm *Manager) GetToolCountForService(serviceID string) int

GetToolCountForService returns the number of tools registered for a given service.

It first checks if the service is healthy; if not, it returns 0.

Parameters:

  • serviceID: string. The unique identifier of the service.

Returns:

  • int: The number of active tools for the service.

func (*Manager) IsServiceAllowed

func (tm *Manager) IsServiceAllowed(serviceID, profileID string) bool

IsServiceAllowed checks if a service is allowed for a given profile.

Parameters:

  • serviceID: string. The unique identifier of the service.
  • profileID: string. The identifier of the profile to check.

Returns:

  • bool: True if the service is allowed, false otherwise.

func (*Manager) ListMCPTools

func (tm *Manager) ListMCPTools() []*mcp.Tool

ListMCPTools returns a slice containing all the tools currently registered with the manager in MCP format.

It maintains a cache of the MCP tool definitions to minimize overhead.

Returns:

  • []*mcp.Tool: A slice of MCP tool definitions.

Side Effects:

  • Updates internal caches if they are invalid.

func (*Manager) ListServices

func (tm *Manager) ListServices() []*ServiceInfo

ListServices returns a list of all currently registered services.

It strips secrets from the service configurations before returning them.

Returns:

  • []*ServiceInfo: A slice of ServiceInfo structs.

func (*Manager) ListTools

func (tm *Manager) ListTools() []Tool

ListTools returns a list of all tools currently registered with the manager.

It uses a read-through cache to avoid rebuilding the list on every call.

Returns:

  • []Tool: A slice of Tool instances.

func (*Manager) SetMCPServer

func (tm *Manager) SetMCPServer(mcpServer MCPServerProvider)

SetMCPServer provides the Manager with a reference to the MCP server.

This allows the manager to register tool handlers directly with the server.

Parameters:

  • mcpServer: MCPServerProvider. The MCP server provider interface.

func (*Manager) SetProfiles

func (tm *Manager) SetProfiles(enabled []string, defs []*configv1.ProfileDefinition)

SetProfiles sets the enabled profiles and their definitions for filtering.

This method updates the internal state used for profile-based access control. It pre-computes allowed services for each profile to optimize lookup performance.

Parameters:

  • enabled: []string. A list of names of the currently active profiles.
  • defs: []*configv1.ProfileDefinition. The definitions of all available profiles.

func (*Manager) ToolMatchesProfile

func (tm *Manager) ToolMatchesProfile(tool Tool, profileID string) bool

ToolMatchesProfile checks if a tool matches a given profile.

It delegates to the internal toolMatchesProfile method.

Parameters:

  • tool: Tool. The tool definition.
  • profileID: string. The identifier of the profile.

Returns:

  • bool: True if the tool matches the profile, false otherwise.

type ManagerInterface

type ManagerInterface interface {
	// AddTool registers a new tool with the manager.
	//
	// Parameters:
	//   - tool: Tool. The tool definition to register.
	//
	// Returns:
	//   - error: An error if the tool cannot be registered (e.g., duplicate name).
	AddTool(tool Tool) error

	// GetTool retrieves a tool by its unique name or ID.
	//
	// Parameters:
	//   - toolName: string. The name or ID of the tool to retrieve.
	//
	// Returns:
	//   - Tool: The tool instance if found.
	//   - bool: True if the tool was found, false otherwise.
	GetTool(toolName string) (Tool, bool)

	// ListTools returns a list of all currently registered tools.
	//
	// Returns:
	//   - []Tool: A slice of registered tools.
	ListTools() []Tool

	// ListMCPTools returns a list of all registered tools formatted for the MCP protocol.
	//
	// This method is optimized for the MCP `tools/list` request.
	//
	// Returns:
	//   - []*mcp.Tool: A slice of MCP tool definitions.
	ListMCPTools() []*mcp.Tool

	// ClearToolsForService removes all tools associated with a specific service ID.
	//
	// This is typically used when a service is reloaded or removed.
	//
	// Parameters:
	//   - serviceID: string. The unique identifier of the service.
	ClearToolsForService(serviceID string)

	// ExecuteTool executes a specific tool with the provided request parameters.
	//
	// Parameters:
	//   - ctx: context.Context. The context for the execution.
	//   - req: *ExecutionRequest. The request containing the tool name and arguments.
	//
	// Returns:
	//   - any: The result of the tool execution.
	//   - error: An error if execution fails.
	ExecuteTool(ctx context.Context, req *ExecutionRequest) (any, error)

	// SetMCPServer sets the MCP server provider for the manager.
	//
	// This allows the manager to register tool handlers with the underlying MCP server.
	//
	// Parameters:
	//   - mcpServer: MCPServerProvider. The provider interface.
	SetMCPServer(mcpServer MCPServerProvider)

	// AddMiddleware adds a middleware to the tool execution chain.
	//
	// Parameters:
	//   - middleware: ExecutionMiddleware. The middleware to add.
	AddMiddleware(middleware ExecutionMiddleware)

	// AddServiceInfo adds metadata for a registered service.
	//
	// Parameters:
	//   - serviceID: string. The unique identifier of the service.
	//   - info: *ServiceInfo. The metadata associated with the service.
	AddServiceInfo(serviceID string, info *ServiceInfo)

	// GetServiceInfo retrieves metadata for a service by its ID.
	//
	// Parameters:
	//   - serviceID: string. The unique identifier of the service.
	//
	// Returns:
	//   - *ServiceInfo: The service metadata if found.
	//   - bool: True if the service info was found, false otherwise.
	GetServiceInfo(serviceID string) (*ServiceInfo, bool)

	// ListServices returns a list of all services known to the manager.
	//
	// Returns:
	//   - []*ServiceInfo: A slice of service metadata.
	ListServices() []*ServiceInfo

	// SetProfiles configures the active profiles and their definitions.
	//
	// This is used for filtering tools based on user profiles and permissions.
	//
	// Parameters:
	//   - enabled: []string. A list of enabled profile names.
	//   - defs: []*configv1.ProfileDefinition. The detailed definitions of the profiles.
	SetProfiles(enabled []string, defs []*configv1.ProfileDefinition)

	// IsServiceAllowed checks if a specific service is accessible under a given profile.
	//
	// Parameters:
	//   - serviceID: string. The unique identifier of the service.
	//   - profileID: string. The identifier of the profile to check against.
	//
	// Returns:
	//   - bool: True if the service is allowed, false otherwise.
	IsServiceAllowed(serviceID, profileID string) bool

	// ToolMatchesProfile checks if a specific tool is accessible under a given profile.
	//
	// Parameters:
	//   - tool: Tool. The tool to check.
	//   - profileID: string. The identifier of the profile to check against.
	//
	// Returns:
	//   - bool: True if the tool matches the profile's criteria, false otherwise.
	ToolMatchesProfile(tool Tool, profileID string) bool

	// GetAllowedServiceIDs returns a set of allowed service IDs for a given profile.
	//
	// This is optimized for quick lookups during filtering.
	//
	// Parameters:
	//   - profileID: string. The identifier of the profile.
	//
	// Returns:
	//   - map[string]bool: A map where keys are allowed service IDs.
	//   - bool: True if the profile exists.
	GetAllowedServiceIDs(profileID string) (map[string]bool, bool)

	// GetToolCountForService returns the number of tools registered for a given service.
	//
	// Parameters:
	//   - serviceID: string. The unique identifier of the service.
	//
	// Returns:
	//   - int: The count of registered tools.
	GetToolCountForService(serviceID string) int
}

ManagerInterface defines the contract for a tool manager.

It outlines the methods required for managing the lifecycle, registration, discovery, and execution of tools within the MCP Any server.

type MockManagerInterface

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

MockManagerInterface is a mock of ManagerInterface interface.

func NewMockManagerInterface

func NewMockManagerInterface(ctrl *gomock.Controller) *MockManagerInterface

NewMockManagerInterface creates a new mock instance.

ctrl is the ctrl.

Returns the result.

func (*MockManagerInterface) AddMiddleware

func (m *MockManagerInterface) AddMiddleware(middleware ExecutionMiddleware)

AddMiddleware mocks base method.

middleware is the middleware.

func (*MockManagerInterface) AddServiceInfo

func (m *MockManagerInterface) AddServiceInfo(serviceID string, info *ServiceInfo)

AddServiceInfo mocks base method.

serviceID is the serviceID. info is the info.

func (*MockManagerInterface) AddTool

func (m *MockManagerInterface) AddTool(tool Tool) error

AddTool mocks base method.

tool represents the tool definition.

Returns an error if the operation fails.

func (*MockManagerInterface) ClearToolsForService

func (m *MockManagerInterface) ClearToolsForService(serviceID string)

ClearToolsForService mocks base method.

serviceID is the serviceID.

func (*MockManagerInterface) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

Returns the result.

func (*MockManagerInterface) ExecuteTool

func (m *MockManagerInterface) ExecuteTool(ctx context.Context, req *ExecutionRequest) (any, error)

ExecuteTool mocks base method.

ctx is the context for the request. req is the request object.

Returns the result. Returns an error if the operation fails.

func (*MockManagerInterface) GetAllowedServiceIDs

func (m *MockManagerInterface) GetAllowedServiceIDs(profileID string) (map[string]bool, bool)

GetAllowedServiceIDs mocks base method.

profileID is the profileID.

Returns the result. Returns true if successful.

func (*MockManagerInterface) GetServiceInfo

func (m *MockManagerInterface) GetServiceInfo(serviceID string) (*ServiceInfo, bool)

GetServiceInfo mocks base method.

serviceID is the serviceID.

Returns the result. Returns true if successful.

func (*MockManagerInterface) GetTool

func (m *MockManagerInterface) GetTool(toolName string) (Tool, bool)

GetTool mocks base method.

toolName is the toolName.

Returns the result. Returns true if successful.

func (*MockManagerInterface) GetToolCountForService

func (m *MockManagerInterface) GetToolCountForService(serviceID string) int

GetToolCountForService mocks base method.

serviceID is the serviceID.

Returns the result.

func (*MockManagerInterface) IsServiceAllowed

func (m *MockManagerInterface) IsServiceAllowed(serviceID, profileID string) bool

IsServiceAllowed mocks base method.

serviceID is the serviceID. profileID is the profileID.

Returns true if successful.

func (*MockManagerInterface) ListMCPTools

func (m *MockManagerInterface) ListMCPTools() []*mcp.Tool

ListMCPTools mocks base method.

Returns the result.

func (*MockManagerInterface) ListServices

func (m *MockManagerInterface) ListServices() []*ServiceInfo

ListServices mocks base method.

Returns the result.

func (*MockManagerInterface) ListTools

func (m *MockManagerInterface) ListTools() []Tool

ListTools mocks base method.

Returns the result.

func (*MockManagerInterface) SetMCPServer

func (m *MockManagerInterface) SetMCPServer(mcpServer MCPServerProvider)

SetMCPServer mocks base method.

mcpServer is the mcpServer.

func (*MockManagerInterface) SetProfiles

func (m *MockManagerInterface) SetProfiles(enabled []string, defs []*v1.ProfileDefinition)

SetProfiles mocks base method.

enabled is the enabled. defs is the defs.

func (*MockManagerInterface) ToolMatchesProfile

func (m *MockManagerInterface) ToolMatchesProfile(tool Tool, profileID string) bool

ToolMatchesProfile mocks base method.

tool represents the tool definition. profileID is the profileID.

Returns true if successful.

type MockManagerInterfaceMockRecorder

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

MockManagerInterfaceMockRecorder is the mock recorder for MockManagerInterface.

func (*MockManagerInterfaceMockRecorder) AddMiddleware

func (mr *MockManagerInterfaceMockRecorder) AddMiddleware(middleware any) *gomock.Call

AddMiddleware indicates an expected call of AddMiddleware.

middleware is the middleware.

Returns the result.

func (*MockManagerInterfaceMockRecorder) AddServiceInfo

func (mr *MockManagerInterfaceMockRecorder) AddServiceInfo(serviceID, info any) *gomock.Call

AddServiceInfo indicates an expected call of AddServiceInfo.

serviceID is the serviceID. info is the info.

Returns the result.

func (*MockManagerInterfaceMockRecorder) AddTool

func (mr *MockManagerInterfaceMockRecorder) AddTool(tool any) *gomock.Call

AddTool indicates an expected call of AddTool.

tool represents the tool definition.

Returns the result.

func (*MockManagerInterfaceMockRecorder) ClearToolsForService

func (mr *MockManagerInterfaceMockRecorder) ClearToolsForService(serviceID any) *gomock.Call

ClearToolsForService indicates an expected call of ClearToolsForService.

serviceID is the serviceID.

Returns the result.

func (*MockManagerInterfaceMockRecorder) ExecuteTool

func (mr *MockManagerInterfaceMockRecorder) ExecuteTool(ctx, req any) *gomock.Call

ExecuteTool indicates an expected call of ExecuteTool.

ctx is the context for the request. req is the request object.

Returns the result.

func (*MockManagerInterfaceMockRecorder) GetAllowedServiceIDs

func (mr *MockManagerInterfaceMockRecorder) GetAllowedServiceIDs(profileID any) *gomock.Call

GetAllowedServiceIDs indicates an expected call of GetAllowedServiceIDs.

profileID is the profileID.

Returns the result.

func (*MockManagerInterfaceMockRecorder) GetServiceInfo

func (mr *MockManagerInterfaceMockRecorder) GetServiceInfo(serviceID any) *gomock.Call

GetServiceInfo indicates an expected call of GetServiceInfo.

serviceID is the serviceID.

Returns the result.

func (*MockManagerInterfaceMockRecorder) GetTool

func (mr *MockManagerInterfaceMockRecorder) GetTool(toolName any) *gomock.Call

GetTool indicates an expected call of GetTool.

toolName is the toolName.

Returns the result.

func (*MockManagerInterfaceMockRecorder) GetToolCountForService

func (mr *MockManagerInterfaceMockRecorder) GetToolCountForService(serviceID any) *gomock.Call

GetToolCountForService indicates an expected call of GetToolCountForService.

serviceID is the serviceID.

Returns the result.

func (*MockManagerInterfaceMockRecorder) IsServiceAllowed

func (mr *MockManagerInterfaceMockRecorder) IsServiceAllowed(serviceID, profileID any) *gomock.Call

IsServiceAllowed indicates an expected call of IsServiceAllowed.

serviceID is the serviceID. profileID is the profileID.

Returns the result.

func (*MockManagerInterfaceMockRecorder) ListMCPTools

func (mr *MockManagerInterfaceMockRecorder) ListMCPTools() *gomock.Call

ListMCPTools indicates an expected call of ListMCPTools.

Returns the result.

func (*MockManagerInterfaceMockRecorder) ListServices

func (mr *MockManagerInterfaceMockRecorder) ListServices() *gomock.Call

ListServices indicates an expected call of ListServices.

Returns the result.

func (*MockManagerInterfaceMockRecorder) ListTools

func (mr *MockManagerInterfaceMockRecorder) ListTools() *gomock.Call

ListTools indicates an expected call of ListTools.

Returns the result.

func (*MockManagerInterfaceMockRecorder) SetMCPServer

func (mr *MockManagerInterfaceMockRecorder) SetMCPServer(mcpServer any) *gomock.Call

SetMCPServer indicates an expected call of SetMCPServer.

mcpServer is the mcpServer.

Returns the result.

func (*MockManagerInterfaceMockRecorder) SetProfiles

func (mr *MockManagerInterfaceMockRecorder) SetProfiles(enabled, defs any) *gomock.Call

SetProfiles indicates an expected call of SetProfiles.

enabled is the enabled. defs is the defs.

Returns the result.

func (*MockManagerInterfaceMockRecorder) ToolMatchesProfile

func (mr *MockManagerInterfaceMockRecorder) ToolMatchesProfile(tool, profileID any) *gomock.Call

ToolMatchesProfile indicates an expected call of ToolMatchesProfile.

tool represents the tool definition. profileID is the profileID.

Returns the result.

type MockTool

type MockTool struct {
	ToolFunc           func() *v1.Tool
	MCPToolFunc        func() *mcp.Tool
	ExecuteFunc        func(ctx context.Context, req *ExecutionRequest) (any, error)
	GetCacheConfigFunc func() *configv1.CacheConfig
}

MockTool is a mock implementation of the Tool interface for testing purposes.

func (*MockTool) Execute

func (m *MockTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute calls the mock ExecuteFunc if set, otherwise returns nil.

ctx is the context for the request. req is the request object.

Returns the result. Returns an error if the operation fails.

func (*MockTool) GetCacheConfig

func (m *MockTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig calls the mock GetCacheConfigFunc if set, otherwise returns nil.

Returns the result.

func (*MockTool) MCPTool

func (m *MockTool) MCPTool() *mcp.Tool

MCPTool returns the MCP tool definition.

Returns the result.

func (*MockTool) Tool

func (m *MockTool) Tool() *v1.Tool

Tool returns the protobuf definition of the mock tool.

Returns the result.

type OpenAPITool

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

OpenAPITool implements the Tool interface for a tool defined in an OpenAPI specification.

Summary: Tool implementation for OpenAPI services.

It constructs and sends an HTTP request based on the OpenAPI operation definition.

func NewOpenAPITool

func NewOpenAPITool(tool *v1.Tool, client client.HTTPClient, parameterDefs map[string]string, method, url string, authenticator auth.UpstreamAuthenticator, callDefinition *configv1.OpenAPICallDefinition) *OpenAPITool

NewOpenAPITool creates a new OpenAPITool instance.

Summary: Initializes a new OpenAPITool.

Parameters:

  • tool: *v1.Tool. The protobuf definition of the tool.
  • client: client.HTTPClient. The HTTP client for requests.
  • parameterDefs: map[string]string. Mapping of parameter names to their locations.
  • method: string. The HTTP method.
  • url: string. The URL template.
  • authenticator: auth.UpstreamAuthenticator. The authenticator for upstream requests.
  • callDefinition: *configv1.OpenAPICallDefinition. The configuration for the OpenAPI call.

Returns:

  • *OpenAPITool: The initialized OpenAPITool.

func (*OpenAPITool) Execute

func (t *OpenAPITool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the OpenAPI tool.

Summary: Executes the OpenAPI tool call.

It constructs an HTTP request based on the operation's method, URL, and parameter definitions, sends the request, and processes the response, applying transformations as needed.

Parameters:

  • ctx: context.Context. The execution context.
  • req: *ExecutionRequest. The execution request.

Returns:

  • any: The execution result.
  • error: An error if execution fails.

func (*OpenAPITool) GetCacheConfig

func (t *OpenAPITool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the OpenAPI tool.

Returns:

  • *configv1.CacheConfig: The cache configuration, if any.

func (*OpenAPITool) MCPTool

func (t *OpenAPITool) MCPTool() *mcp.Tool

MCPTool returns the MCP-compliant tool definition.

It lazily converts the internal protobuf definition to the MCP format on first access.

Returns:

  • *mcp.Tool: The MCP tool definition.

func (*OpenAPITool) Tool

func (t *OpenAPITool) Tool() *v1.Tool

Tool returns the protobuf definition of the OpenAPI tool.

Returns:

  • *v1.Tool: The underlying protobuf definition.

type PolicyHook

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

PolicyHook implements PreCallHook using CallPolicy.

func NewPolicyHook

func NewPolicyHook(policy *configv1.CallPolicy) *PolicyHook

NewPolicyHook creates a new PolicyHook with the given call policy.

policy is the policy.

Returns the result.

func (*PolicyHook) ExecutePre

func (h *PolicyHook) ExecutePre(
	_ context.Context,
	req *ExecutionRequest,
) (Action, *ExecutionRequest, error)

ExecutePre executes the policy check before a tool is called.

_ is an unused parameter. req is the request object.

Returns the result. Returns the result. Returns an error if the operation fails.

type PostCallHook

type PostCallHook interface {
	// ExecutePost runs the hook. It returns the potentially modified result
	// (or original if unchanged) and an error.
	ExecutePost(ctx context.Context, req *ExecutionRequest, result any) (any, error)
}

PostCallHook defines the interface for hooks executed after a tool call.

Summary: Interface for post-execution hooks.

type PreCallHook

type PreCallHook interface {
	// ExecutePre runs the hook. It returns an action (Allow/Deny),
	// a potentially modified request (or nil if unchanged), and an error.
	ExecutePre(ctx context.Context, req *ExecutionRequest) (Action, *ExecutionRequest, error)
}

PreCallHook defines the interface for hooks executed before a tool call.

Summary: Interface for pre-execution hooks.

type Sampler

type Sampler = Session

Sampler is an alias for Session for backward compatibility.

func GetSampler deprecated

func GetSampler(ctx context.Context) (Sampler, bool)

GetSampler retrieves the Sampler from the context.

Deprecated: Use GetSession instead.

type ServiceInfo

type ServiceInfo struct {
	// Name is the unique name of the service.
	Name string
	// Config is the configuration of the upstream service.
	Config *configv1.UpstreamServiceConfig
	// Fds is the FileDescriptorSet associated with the service (for gRPC/protobuf).
	Fds *descriptorpb.FileDescriptorSet

	// PreHooks are the cached pre-call hooks for the service.
	PreHooks []PreCallHook
	// PostHooks are the cached post-call hooks for the service.
	PostHooks []PostCallHook

	// CompiledPolicies are the pre-compiled call policies for the service.
	CompiledPolicies []*CompiledCallPolicy

	// HealthStatus indicates the health of the service ("healthy", "unhealthy", "unknown").
	HealthStatus string
}

ServiceInfo holds metadata about a registered upstream service, including its configuration and any associated protobuf file descriptors.

Summary: Metadata for a registered service.

type ServiceRegistry

type ServiceRegistry interface {
	// GetTool retrieves a tool by name.
	//
	// Parameters:
	//   - toolName: The name of the tool to retrieve.
	//
	// Returns:
	//   - Tool: The tool instance if found.
	//   - bool: True if the tool exists, false otherwise.
	GetTool(toolName string) (Tool, bool)

	// GetServiceInfo retrieves metadata for a service.
	//
	// Parameters:
	//   - serviceID: The unique identifier of the service.
	//
	// Returns:
	//   - *ServiceInfo: The service metadata info if found.
	//   - bool: True if the service exists, false otherwise.
	GetServiceInfo(serviceID string) (*ServiceInfo, bool)
}

ServiceRegistry defines an interface for a component that can look up tools and service information. It is used for dependency injection to decouple components from the main service registry.

Summary: Interface for tool and service lookup.

type Session

type Session interface {
	// CreateMessage requests a message creation (sampling) from the client.
	//
	// ctx is the context for the request.
	// params is the params.
	//
	// Returns the result.
	// Returns an error if the operation fails.
	CreateMessage(ctx context.Context, params *mcp.CreateMessageParams) (*mcp.CreateMessageResult, error)

	// ListRoots requests the list of roots from the client.
	//
	// ctx is the context for the request.
	//
	// Returns the result.
	// Returns an error if the operation fails.
	ListRoots(ctx context.Context) (*mcp.ListRootsResult, error)
}

Session defines the interface for tools to interact with the client session. It includes capabilities like Sampling (CreateMessage) and Roots inspection.

func GetSession

func GetSession(ctx context.Context) (Session, bool)

GetSession retrieves the Session from the context.

ctx is the context for the request.

Returns the result. Returns true if successful.

type SigningRoundTripper

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

SigningRoundTripper signs the request using the webhook signer.

func (*SigningRoundTripper) RoundTrip

func (s *SigningRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes the HTTP request with a signature.

req is the request object.

Returns the response. Returns an error if the operation fails.

type Tool

type Tool interface {
	// Tool returns the protobuf definition of the tool.
	//
	// Returns:
	//   - *v1.Tool: The protobuf tool definition.
	Tool() *v1.Tool
	// MCPTool returns the MCP tool definition.
	//
	// Returns:
	//   - *mcp.Tool: The MCP tool definition.
	MCPTool() *mcp.Tool
	// Execute runs the tool with the provided context and request, returning
	// the result or an error.
	//
	// Parameters:
	//   - ctx: context.Context. The execution context.
	//   - req: *ExecutionRequest. The request payload.
	//
	// Returns:
	//   - any: The execution result.
	//   - error: An error if execution fails.
	Execute(ctx context.Context, req *ExecutionRequest) (any, error)
	// GetCacheConfig returns the cache configuration for the tool.
	//
	// Returns:
	//   - *configv1.CacheConfig: The cache configuration, or nil if none.
	GetCacheConfig() *configv1.CacheConfig
}

Tool is the fundamental interface for any executable tool in the system.

Summary: Interface for defining and executing tools.

Each implementation represents a different type of underlying service (e.g., gRPC, HTTP, command-line).

func GetFromContext

func GetFromContext(ctx context.Context) (Tool, bool)

GetFromContext retrieves a tool from the context if present.

Summary: Retrieves a tool from the context.

Parameters:

  • ctx: context.Context. The context to search.

Returns:

  • Tool: The tool instance from the context.
  • bool: True if a tool was found, false otherwise.

func NewCommandTool

func NewCommandTool(
	tool *v1.Tool,
	service *configv1.CommandLineUpstreamService,
	callDefinition *configv1.CommandLineCallDefinition,
	policies []*configv1.CallPolicy,
	callID string,
) Tool

NewCommandTool creates a new CommandTool instance.

Summary: Initializes a new CommandTool.

Parameters:

  • tool: *v1.Tool. The protobuf definition of the tool.
  • service: *configv1.CommandLineUpstreamService. The service configuration.
  • callDefinition: *configv1.CommandLineCallDefinition. The call configuration.
  • policies: []*configv1.CallPolicy. The security policies.
  • callID: string. The unique identifier for the call.

Returns:

  • Tool: The created CommandTool.

func NewLocalCommandTool

func NewLocalCommandTool(
	tool *v1.Tool,
	service *configv1.CommandLineUpstreamService,
	callDefinition *configv1.CommandLineCallDefinition,
	policies []*configv1.CallPolicy,
	callID string,
) Tool

NewLocalCommandTool creates a new LocalCommandTool instance.

Summary: Initializes a new LocalCommandTool.

Parameters:

  • tool: *v1.Tool. The protobuf definition of the tool.
  • service: *configv1.CommandLineUpstreamService. The service configuration.
  • callDefinition: *configv1.CommandLineCallDefinition. The call configuration.
  • policies: []*configv1.CallPolicy. The security policies.
  • callID: string. The unique identifier for the call.

Returns:

  • Tool: The created LocalCommandTool.

type WebhookClient

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

WebhookClient handles the communication with an external webhook.

func NewWebhookClient

func NewWebhookClient(config *configv1.WebhookConfig) *WebhookClient

NewWebhookClient creates a new WebhookClient.

config holds the configuration settings.

Returns the result.

func (*WebhookClient) Call

func (c *WebhookClient) Call(ctx context.Context, eventType string, data any) (*cloudevents.Event, error)

Call sends a cloud event to the webhook and returns the response event.

ctx is the context for the request. eventType is the eventType. data is the data.

Returns the result. Returns an error if the operation fails.

type WebhookHook

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

WebhookHook supports modification of requests and responses via external webhook using CloudEvents.

func NewWebhookHook

func NewWebhookHook(config *configv1.WebhookConfig) *WebhookHook

NewWebhookHook creates a new WebhookHook.

config holds the configuration settings.

Returns the result.

func (*WebhookHook) ExecutePost

func (h *WebhookHook) ExecutePost(
	ctx context.Context,
	req *ExecutionRequest,
	result any,
) (any, error)

ExecutePost executes the webhook notification after a tool is called.

ctx is the context for the request. req is the request object. result is the result.

Returns the result. Returns an error if the operation fails.

func (*WebhookHook) ExecutePre

func (h *WebhookHook) ExecutePre(
	ctx context.Context,
	req *ExecutionRequest,
) (Action, *ExecutionRequest, error)

ExecutePre executes the webhook notification before a tool is called.

ctx is the context for the request. req is the request object.

Returns the result. Returns the result. Returns an error if the operation fails.

type WebhookStatus

type WebhookStatus struct {
	// Code is the status code returned by the webhook.
	Code int `json:"code"`
	// Message is a descriptive message returned by the webhook.
	Message string `json:"message"`
}

WebhookStatus represents the status returned by the webhook.

type WebrtcTool

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

WebrtcTool implements the Tool interface for a tool that is exposed via a WebRTC data channel. It handles the signaling and establishment of a peer connection to communicate with the remote service. This is useful for scenarios requiring low-latency, peer-to-peer communication directly from the server.

func NewWebrtcTool

func NewWebrtcTool(
	tool *v1.Tool,
	poolManager *pool.Manager,
	serviceID string,
	authenticator auth.UpstreamAuthenticator,
	callDefinition *configv1.WebrtcCallDefinition,
) (*WebrtcTool, error)

NewWebrtcTool creates a new WebrtcTool.

tool is the protobuf definition of the tool. poolManager is used to get a client from the connection pool. serviceID identifies the specific service connection pool. authenticator handles adding authentication credentials to the signaling request. callDefinition contains the configuration for the WebRTC call, such as parameter mappings and transformers.

func (*WebrtcTool) Close

func (t *WebrtcTool) Close() error

Close is a placeholder for any cleanup logic. Currently, it is a no-op as the peer connection is created and closed within the Execute method.

func (*WebrtcTool) Execute

func (t *WebrtcTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the WebRTC tool. It establishes a new peer connection, negotiates the session via an HTTP signaling server, sends the tool inputs over the data channel, and waits for a response.

func (*WebrtcTool) GetCacheConfig

func (t *WebrtcTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the WebRTC tool.

Returns the result.

func (*WebrtcTool) MCPTool

func (t *WebrtcTool) MCPTool() *mcp.Tool

MCPTool returns the MCP tool definition.

Returns the result.

func (*WebrtcTool) Tool

func (t *WebrtcTool) Tool() *v1.Tool

Tool returns the protobuf definition of the WebRTC tool.

Returns the result.

type WebsocketTool

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

WebsocketTool implements the Tool interface for a tool exposed via a WebSocket connection. It handles sending and receiving messages over a persistent WebSocket connection managed by a connection pool.

func NewWebsocketTool

func NewWebsocketTool(
	tool *v1.Tool,
	poolManager *pool.Manager,
	serviceID string,
	authenticator auth.UpstreamAuthenticator,
	callDefinition *configv1.WebsocketCallDefinition,
) *WebsocketTool

NewWebsocketTool creates a new WebsocketTool.

tool is the protobuf definition of the tool. poolManager is used to get a WebSocket client from the connection pool. serviceID identifies the specific WebSocket service connection pool. authenticator handles adding authentication credentials to the connection request. callDefinition contains the configuration for the WebSocket call, such as parameter mappings and transformers.

func (*WebsocketTool) Execute

func (t *WebsocketTool) Execute(ctx context.Context, req *ExecutionRequest) (any, error)

Execute handles the execution of the WebSocket tool. It retrieves a connection from the pool, sends the tool inputs as a message, and waits for a single response message, which it then processes and returns.

func (*WebsocketTool) GetCacheConfig

func (t *WebsocketTool) GetCacheConfig() *configv1.CacheConfig

GetCacheConfig returns the cache configuration for the WebSocket tool.

Returns the result.

func (*WebsocketTool) MCPTool

func (t *WebsocketTool) MCPTool() *mcp.Tool

MCPTool returns the MCP tool definition.

Returns the result.

func (*WebsocketTool) Tool

func (t *WebsocketTool) Tool() *v1.Tool

Tool returns the protobuf definition of the WebSocket tool.

Returns the result.

Directories

Path Synopsis
Package browser provides a browser automation tool.
Package browser provides a browser automation tool.

Jump to

Keyboard shortcuts

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