runtime

package
v0.260507.1 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: MPL-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const AdvisorBehaviorPrompt = `` /* 1974-byte string literal not displayed */

AdvisorBehaviorPrompt is the behavioral contract that tingly-box appends to the worker's system prompt whenever the advisor tool is injected. Behavior instructions are weighted more heavily in system prompts than in tool descriptions, so models follow them more reliably.

View Source
const AdvisorToolDescription = "" /* 209-byte string literal not displayed */

AdvisorToolDescription is the short, concise tool description shown alongside other tools. The full behavioral contract lives in AdvisorBehaviorPrompt and is appended to the worker's system prompt by the MCP injection transform.

Variables

This section is empty.

Functions

func GetAdvisorDepth added in v0.260507.1

func GetAdvisorDepth(ctx context.Context) int

GetAdvisorDepth retrieves the current adviser call depth from context.

func GetAdvisorRecordSink added in v0.260507.1

func GetAdvisorRecordSink(ctx context.Context) (*obs.Sink, bool)

GetAdvisorRecordSink retrieves the record sink from the context.

func IsMCPToolName

func IsMCPToolName(name string) bool

IsMCPToolName checks whether a tool name is a normalized MCP tool.

func NormalizeToolName

func NormalizeToolName(sourceID, toolName string) string

NormalizeToolName converts source/tool pair to normalized tool name.

func ParseNormalizedToolName

func ParseNormalizedToolName(name string) (string, string, bool)

ParseNormalizedToolName parses normalized name and returns sourceID/toolName.

func RegisterBuiltinTools

func RegisterBuiltinTools(getConfig func() *typ.MCPRuntimeConfig, setConfig func(toolType string, config interface{}) error) error

RegisterBuiltinTools ensures built-in tools are registered in the MCP configuration. If webtools already exists, it updates the command path to use the current binary's absolute path.

func WithAdvisorContext added in v0.260507.1

func WithAdvisorContext(ctx context.Context, ac *AdvisorContext) context.Context

WithAdvisorContext attaches advisor context to the context.

func WithAdvisorDepth added in v0.260507.1

func WithAdvisorDepth(ctx context.Context, depth int) context.Context

WithAdvisorDepth sets the adviser call depth in context.

func WithAdvisorRecordSink added in v0.260507.1

func WithAdvisorRecordSink(ctx context.Context, sink *obs.Sink) context.Context

WithAdvisorRecordSink attaches a record sink to the context for advisor call recording.

Types

type AdvisorContext added in v0.260507.1

type AdvisorContext struct {
	Messages      []map[string]any
	UsesRemaining *int
}

AdvisorContext holds conversation state for the advisor tool.

func GetAdvisorContext added in v0.260507.1

func GetAdvisorContext(ctx context.Context) (*AdvisorContext, bool)

GetAdvisorContext retrieves advisor context from the context.

type AdvisorFormat added in v0.260507.1

type AdvisorFormat int

AdvisorFormat indicates the API format of the advisor endpoint.

const (
	FormatOpenAI AdvisorFormat = iota
	FormatAnthropic
)

type AdvisorResponse added in v0.260507.1

type AdvisorResponse struct {
	Assessment          string `json:"assessment"`
	Recommendation      string `json:"recommendation"`
	UnsolicitedFindings string `json:"unsolicited_findings,omitempty"`
}

type BaseToolSource

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

BaseToolSource provides common functionality for all tool source implementations.

func NewBaseToolSource

func NewBaseToolSource(sourceID string, transport TransportType) *BaseToolSource

NewBaseToolSource creates a new base tool source.

func (*BaseToolSource) DisableHealthCheck

func (b *BaseToolSource) DisableHealthCheck(ctx context.Context)

DisableHealthCheck provides a default no-op implementation for on-demand connections.

func (*BaseToolSource) EnableHealthCheck

func (b *BaseToolSource) EnableHealthCheck(ctx context.Context, interval time.Duration)

EnableHealthCheck provides a default no-op implementation for on-demand connections.

func (*BaseToolSource) GetConnectionState

func (b *BaseToolSource) GetConnectionState() ConnectionState

GetConnectionState returns the current connection state.

func (*BaseToolSource) GetConnectionStatus

func (b *BaseToolSource) GetConnectionStatus() ConnectionStatus

GetConnectionStatus returns the current connection status.

func (*BaseToolSource) GetSourceID

func (b *BaseToolSource) GetSourceID() string

GetSourceID returns the source ID.

func (*BaseToolSource) GetType

func (b *BaseToolSource) GetType() TransportType

GetType returns the transport type.

func (*BaseToolSource) HealthCheck

func (b *BaseToolSource) HealthCheck(ctx context.Context) error

HealthCheck provides a default no-op health check for on-demand connections.

type ConnectionError

type ConnectionError struct {
	Source string
	Reason string
	Err    error
}

ConnectionError represents a connection-related error.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

type ConnectionState

type ConnectionState string

ConnectionState represents the current state of a tool source connection.

const (
	StateDisconnected ConnectionState = "disconnected"
	StateConnecting   ConnectionState = "connecting"
	StateConnected    ConnectionState = "connected"
	StateError        ConnectionState = "error"
)

type ConnectionStatus

type ConnectionStatus struct {
	State         ConnectionState `json:"state"`
	LastConnected time.Time       `json:"last_connected,omitempty"`
	LastError     error           `json:"last_error,omitempty"`
	RetryCount    int             `json:"retry_count,omitempty"`
}

ConnectionStatus represents the current status of a tool source connection.

type DefaultErrorClassifier

type DefaultErrorClassifier struct{}

DefaultErrorClassifier provides default error classification.

func (*DefaultErrorClassifier) IsPermanent

func (c *DefaultErrorClassifier) IsPermanent(err error) bool

IsPermanent checks if an error is permanent (auth failures, not found, etc.).

func (*DefaultErrorClassifier) IsTransient

func (c *DefaultErrorClassifier) IsTransient(err error) bool

IsTransient checks if an error is transient (temporary network issues, timeouts, etc.).

type EnvRefIssue added in v0.260507.1

type EnvRefIssue struct {
	SourceID  string
	FieldPath string
	VarName   string
}

EnvRefIssue describes a missing environment reference in MCP runtime config.

func ExpandMCPRuntimeEnvRefs added in v0.260507.1

func ExpandMCPRuntimeEnvRefs(cfg *typ.MCPRuntimeConfig) []EnvRefIssue

ExpandMCPRuntimeEnvRefs expands ${VAR} references in all string fields of MCP runtime config. Missing variables are left as-is and returned as issues.

func ValidateEnabledMCPSourceEnvRefs added in v0.260507.1

func ValidateEnabledMCPSourceEnvRefs(sources []typ.MCPSourceConfig) []EnvRefIssue

ValidateEnabledMCPSourceEnvRefs checks ${VAR} references for enabled sources only. Missing variables are returned as issues.

type ErrorClassifier

type ErrorClassifier interface {
	IsTransient(err error) bool
	IsPermanent(err error) bool
}

ErrorClassifier classifies errors as transient or permanent.

type ExponentialBackoffStrategy

type ExponentialBackoffStrategy struct {
	InitialInterval time.Duration
	MaxInterval     time.Duration
	Multiplier      float64
	MaxRetries      int
}

ExponentialBackoffStrategy implements exponential backoff with jitter.

func NewExponentialBackoffStrategy

func NewExponentialBackoffStrategy() *ExponentialBackoffStrategy

NewExponentialBackoffStrategy creates a new exponential backoff strategy.

func (*ExponentialBackoffStrategy) NextRetry

func (s *ExponentialBackoffStrategy) NextRetry(retryCount int) time.Duration

NextRetry returns the duration to wait before the next retry.

func (*ExponentialBackoffStrategy) ShouldRetry

func (s *ExponentialBackoffStrategy) ShouldRetry(retryCount int) bool

ShouldRetry determines if another retry should be attempted.

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
}

HTTPError represents an HTTP error with status code.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HTTPToolSource

type HTTPToolSource struct {
	*BaseToolSource
	// contains filtered or unexported fields
}

HTTPToolSource implements ToolSource for HTTP-based MCP servers. This is a persistent connection type with health monitoring.

func NewHTTPToolSource

func NewHTTPToolSource(sourceConfig typ.MCPSourceConfig, sc *sessionCache) (*HTTPToolSource, error)

NewHTTPToolSource creates a new HTTP tool source.

func (*HTTPToolSource) CallTool

func (s *HTTPToolSource) CallTool(ctx context.Context, toolName string, arguments string) (string, error)

CallTool executes a tool from the HTTP MCP server.

func (*HTTPToolSource) Connect

func (s *HTTPToolSource) Connect(ctx context.Context) error

Connect establishes an HTTP connection to the MCP server.

func (*HTTPToolSource) DisableHealthCheck

func (s *HTTPToolSource) DisableHealthCheck(ctx context.Context)

DisableHealthCheck stops health monitoring.

func (*HTTPToolSource) Disconnect

func (s *HTTPToolSource) Disconnect(ctx context.Context) error

Disconnect closes the HTTP connection.

func (*HTTPToolSource) EnableHealthCheck

func (s *HTTPToolSource) EnableHealthCheck(ctx context.Context, interval time.Duration)

EnableHealthCheck starts periodic health monitoring.

func (*HTTPToolSource) GetSourceConfig

func (s *HTTPToolSource) GetSourceConfig() interface{}

GetSourceConfig returns the source configuration.

func (*HTTPToolSource) HealthCheck

func (s *HTTPToolSource) HealthCheck(ctx context.Context) error

HealthCheck verifies the HTTP connection is still active.

func (*HTTPToolSource) IsConnected

func (s *HTTPToolSource) IsConnected() bool

IsConnected returns whether the HTTP connection is active.

func (*HTTPToolSource) ListTools

func (s *HTTPToolSource) ListTools(ctx context.Context) ([]ToolDefinition, error)

ListTools returns all tools from the HTTP MCP server.

func (*HTTPToolSource) Reconnect

func (s *HTTPToolSource) Reconnect(ctx context.Context) error

Reconnect implements ReconnectableSource interface.

type HealthMonitor

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

HealthMonitor provides health monitoring for persistent connections.

func NewHealthMonitor

func NewHealthMonitor(source ToolSource, errorClassifier ErrorClassifier) *HealthMonitor

NewHealthMonitor creates a new health monitor.

func (*HealthMonitor) Start

func (h *HealthMonitor) Start(ctx context.Context, interval time.Duration)

Start begins health monitoring with the specified interval.

func (*HealthMonitor) Stop

func (h *HealthMonitor) Stop(ctx context.Context)

Stop stops health monitoring.

type InvalidToolNameError

type InvalidToolNameError struct {
	Name string
}

InvalidToolNameError indicates an invalid tool name.

func (*InvalidToolNameError) Error

func (e *InvalidToolNameError) Error() string

type ReconnectableSource

type ReconnectableSource interface {
	ToolSource
	Reconnect(ctx context.Context) error
}

ReconnectableSource extends ToolSource with reconnection capability.

type Runtime

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

Runtime handles MCP tool source discovery and tool execution.

func NewRuntime

func NewRuntime(getConfig configProvider) *Runtime

NewRuntime creates a new MCP runtime.

func (*Runtime) CallTool

func (r *Runtime) CallTool(ctx context.Context, normalizedName string, arguments string) (string, error)

CallTool executes a normalized MCP tool call and returns serialized result. Dispatches virtual tools first (kernel mode), then remote tools (user mode).

func (*Runtime) Close

func (r *Runtime) Close()

Close releases all MCP sessions and tool source connections.

func (*Runtime) GetAdvisorMaxUses added in v0.260507.1

func (r *Runtime) GetAdvisorMaxUses() int

GetAdvisorMaxUses returns the MaxUsesPerRequest from the advisor source config. Returns 0 if no advisor is configured or the value is not positive.

func (*Runtime) GetConfig

func (r *Runtime) GetConfig() *typ.MCPRuntimeConfig

GetConfig returns the current MCP runtime configuration.

func (*Runtime) HasServerTools

func (r *Runtime) HasServerTools() bool

HasServerTools returns true if there are any server tools configured

func (*Runtime) ListClientSourceToolsForMCP added in v0.260507.1

func (r *Runtime) ListClientSourceToolsForMCP(ctx context.Context) (map[string][]SourceTool, error)

ListClientSourceToolsForMCP returns source tools that are eligible for MCP client exposure. Rules:

  • source must be enabled
  • source must be client tool (is_client_tool=true)
  • tool must come from non-virtual source (ListSourceTools contract)

func (*Runtime) ListEnabledServerToolNames

func (r *Runtime) ListEnabledServerToolNames(ctx context.Context) map[string]struct{}

ListEnabledServerToolNames returns normalized MCP tool names that are callable by server-side MCP execution paths. This includes:

  • injected server-side virtual tools (via ListServerToolsForInjection)
  • backward-compatible aliases for server-only virtual tools (e.g. advisor source id)

Results are cached with a short TTL to avoid repeated full source enumeration.

func (*Runtime) ListServerToolsForInjection added in v0.260507.1

func (r *Runtime) ListServerToolsForInjection(ctx context.Context) []openai.ChatCompletionToolUnionParam

ListServerToolsForInjection returns MCP tools that should be injected into upstream model requests. Injection is intentionally restricted to server-side virtual tools. Client-facing non-virtual tools must be exposed through MCP transport endpoints instead.

func (*Runtime) ListSourceTools

func (r *Runtime) ListSourceTools(ctx context.Context) (map[string][]SourceTool, error)

ListSourceTools returns all MCP tools grouped by source with their original names. This is used by local mode to expose tools to external MCP clients.

func (*Runtime) RegisterAdviser added in v0.260507.1

func (r *Runtime) RegisterAdviser(cfg typ.AdvisorConfig, cp *client.ClientPool)

RegisterAdviser registers the adviser as a virtual tool in the runtime.

func (*Runtime) SetClientPool added in v0.260507.1

func (r *Runtime) SetClientPool(cp *client.ClientPool)

SetClientPool injects the client pool into the runtime's tool source factory.

func (*Runtime) VirtualRegistry added in v0.260507.1

func (r *Runtime) VirtualRegistry() *VirtualToolRegistry

VirtualRegistry returns the runtime's virtual tool registry, or nil if the runtime is nil.

type SSEToolSource

type SSEToolSource struct {
	*BaseToolSource
	// contains filtered or unexported fields
}

SSEToolSource implements ToolSource for SSE-based MCP servers. This is a persistent connection type with health monitoring.

func NewSSEToolSource

func NewSSEToolSource(sourceConfig typ.MCPSourceConfig, sc *sessionCache) (*SSEToolSource, error)

NewSSEToolSource creates a new SSE tool source.

func (*SSEToolSource) CallTool

func (s *SSEToolSource) CallTool(ctx context.Context, toolName string, arguments string) (string, error)

CallTool executes a tool from the SSE MCP server.

func (*SSEToolSource) Connect

func (s *SSEToolSource) Connect(ctx context.Context) error

Connect establishes an SSE connection to the MCP server.

func (*SSEToolSource) DisableHealthCheck

func (s *SSEToolSource) DisableHealthCheck(ctx context.Context)

DisableHealthCheck stops health monitoring.

func (*SSEToolSource) Disconnect

func (s *SSEToolSource) Disconnect(ctx context.Context) error

Disconnect closes the SSE connection.

func (*SSEToolSource) EnableHealthCheck

func (s *SSEToolSource) EnableHealthCheck(ctx context.Context, interval time.Duration)

EnableHealthCheck starts periodic health monitoring.

func (*SSEToolSource) GetSourceConfig

func (s *SSEToolSource) GetSourceConfig() interface{}

GetSourceConfig returns the source configuration.

func (*SSEToolSource) HealthCheck

func (s *SSEToolSource) HealthCheck(ctx context.Context) error

HealthCheck verifies the SSE connection is still active.

func (*SSEToolSource) IsConnected

func (s *SSEToolSource) IsConnected() bool

IsConnected returns whether the SSE connection is active.

func (*SSEToolSource) ListTools

func (s *SSEToolSource) ListTools(ctx context.Context) ([]ToolDefinition, error)

ListTools returns all tools from the SSE MCP server.

func (*SSEToolSource) Reconnect

func (s *SSEToolSource) Reconnect(ctx context.Context) error

Reconnect implements ReconnectableSource interface.

type SessionContext added in v0.260507.1

type SessionContext struct {
	SessionID      string
	BuildLogs      []string
	LastWorkerResp string
	CreatedAt      time.Time
}

SessionContext holds session-persistent heavy data.

type SessionStore added in v0.260507.1

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

SessionStore is an in-memory KV with TTL sweeper.

func NewSessionStore added in v0.260507.1

func NewSessionStore(ttl time.Duration) *SessionStore

func (*SessionStore) Destroy added in v0.260507.1

func (s *SessionStore) Destroy(sessionID string)

func (*SessionStore) Get added in v0.260507.1

func (s *SessionStore) Get(sessionID string) (*SessionContext, bool)

func (*SessionStore) Put added in v0.260507.1

func (s *SessionStore) Put(ctx *SessionContext)

func (*SessionStore) StartSweeper added in v0.260507.1

func (s *SessionStore) StartSweeper(interval time.Duration) *time.Ticker

func (*SessionStore) Sweep added in v0.260507.1

func (s *SessionStore) Sweep()

type SourceNotFoundError

type SourceNotFoundError struct {
	ID string
}

SourceNotFoundError indicates that a source was not found.

func (*SourceNotFoundError) Error

func (e *SourceNotFoundError) Error() string

type SourceTool

type SourceTool struct {
	SourceID    string
	SourceName  string
	Name        string
	Description string
	InputSchema json.RawMessage
}

SourceTool represents a tool from a specific MCP source with its original name.

type StdioToolSource

type StdioToolSource struct {
	*BaseToolSource
	// contains filtered or unexported fields
}

StdioToolSource implements ToolSource for stdio-based MCP servers. This is an on-demand connection type - the subprocess is started when needed.

func NewStdioToolSource

func NewStdioToolSource(sourceConfig typ.MCPSourceConfig, sc *sessionCache) (*StdioToolSource, error)

NewStdioToolSource creates a new stdio tool source.

func (*StdioToolSource) CallTool

func (s *StdioToolSource) CallTool(ctx context.Context, toolName string, arguments string) (string, error)

CallTool executes a tool from the stdio MCP server.

func (*StdioToolSource) Connect

func (s *StdioToolSource) Connect(ctx context.Context) error

Connect establishes a stdio connection to the MCP server.

func (*StdioToolSource) DisableHealthCheck

func (s *StdioToolSource) DisableHealthCheck(ctx context.Context)

DisableHealthCheck is a no-op for on-demand connections.

func (*StdioToolSource) Disconnect

func (s *StdioToolSource) Disconnect(ctx context.Context) error

Disconnect closes the stdio connection. For stdio, this terminates the subprocess.

func (*StdioToolSource) EnableHealthCheck

func (s *StdioToolSource) EnableHealthCheck(ctx context.Context, interval time.Duration)

EnableHealthCheck is a no-op for on-demand connections.

func (*StdioToolSource) GetSourceConfig

func (s *StdioToolSource) GetSourceConfig() interface{}

GetSourceConfig returns the source configuration.

func (*StdioToolSource) HealthCheck

func (s *StdioToolSource) HealthCheck(ctx context.Context) error

HealthCheck verifies the stdio connection is still active.

func (*StdioToolSource) IsConnected

func (s *StdioToolSource) IsConnected() bool

IsConnected returns whether the stdio connection is active.

func (*StdioToolSource) ListTools

func (s *StdioToolSource) ListTools(ctx context.Context) ([]ToolDefinition, error)

ListTools returns all tools from the stdio MCP server.

type ToolDefinition

type ToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"input_schema,omitempty"`
}

ToolDefinition represents a tool's metadata and schema.

type ToolExecutionError

type ToolExecutionError struct {
	ToolName string
	Message  string
}

ToolExecutionError represents an error during tool execution.

func (*ToolExecutionError) Error

func (e *ToolExecutionError) Error() string

type ToolSource

type ToolSource interface {
	// Connection management
	Connect(ctx context.Context) error
	Disconnect(ctx context.Context) error
	IsConnected() bool
	GetConnectionState() ConnectionState
	GetConnectionStatus() ConnectionStatus

	// Tool operations
	ListTools(ctx context.Context) ([]ToolDefinition, error)
	CallTool(ctx context.Context, toolName string, arguments string) (string, error)

	// Health monitoring (for persistent connections)
	HealthCheck(ctx context.Context) error
	EnableHealthCheck(ctx context.Context, interval time.Duration)
	DisableHealthCheck(ctx context.Context)

	// Metadata
	GetType() TransportType
	GetSourceID() string
	GetSourceConfig() interface{} // Returns source-specific config
}

ToolSource is the unified interface for all MCP tool sources. All transport types (stdio, http, sse, builtin) implement this interface.

type ToolSourceFactory

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

ToolSourceFactory creates tool sources based on configuration.

func NewToolSourceFactory

func NewToolSourceFactory(sc *sessionCache, cp *client.ClientPool) *ToolSourceFactory

NewToolSourceFactory creates a new tool source factory.

func (*ToolSourceFactory) CreateToolSource

func (f *ToolSourceFactory) CreateToolSource(sourceConfig typ.MCPSourceConfig) (ToolSource, error)

CreateToolSource creates a tool source based on the transport type.

func (*ToolSourceFactory) SetClientPool added in v0.260507.1

func (f *ToolSourceFactory) SetClientPool(cp *client.ClientPool)

SetClientPool sets the client pool on the factory.

type TransportType

type TransportType string

TransportType represents the type of transport for a tool source.

const (
	TransportStdio TransportType = "stdio"
	TransportHTTP  TransportType = "http"
	TransportSSE   TransportType = "sse"
)

type UnsupportedTransportError

type UnsupportedTransportError struct {
	Transport string
}

UnsupportedTransportError indicates an unsupported transport type.

func (*UnsupportedTransportError) Error

func (e *UnsupportedTransportError) Error() string

type VirtualTool added in v0.260507.1

type VirtualTool struct {
	Name        string
	Description string
	InputSchema mcp.ToolInputSchema
	Handler     VirtualToolHandler
	// IsClientTool indicates whether this tool should be exposed to client requests.
	// If false, the tool is only available for internal server-side logic.
	IsClientTool bool
}

VirtualTool is an in-process MCP tool definition.

func NewAdvisorVirtualTool added in v0.260507.1

func NewAdvisorVirtualTool(cfg typ.AdvisorConfig, cp *client.ClientPool, store *SessionStore) VirtualTool

type VirtualToolHandler added in v0.260507.1

type VirtualToolHandler func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)

VirtualToolHandler executes an in-process MCP tool.

type VirtualToolRegistry added in v0.260507.1

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

VirtualToolRegistry holds registered in-process tools.

func NewVirtualToolRegistry added in v0.260507.1

func NewVirtualToolRegistry() *VirtualToolRegistry

func (*VirtualToolRegistry) Get added in v0.260507.1

func (r *VirtualToolRegistry) Get(name string) (VirtualTool, bool)

func (*VirtualToolRegistry) List added in v0.260507.1

func (r *VirtualToolRegistry) List() []mcp.Tool

func (*VirtualToolRegistry) ListVirtualTools added in v0.260507.1

func (r *VirtualToolRegistry) ListVirtualTools() []VirtualTool

ListVirtualTools returns the full VirtualTool list with IsClientTool information. This is used by Runtime to filter tools based on client exposure.

func (*VirtualToolRegistry) Register added in v0.260507.1

func (r *VirtualToolRegistry) Register(tool VirtualTool)

Jump to

Keyboard shortcuts

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