toolengine

package
v1.261002.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MPL-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsVirtualTool

func IsVirtualTool(normalizedName string, registry *coretool.VirtualToolRegistry) bool

IsVirtualTool reports whether the normalized MCP tool should execute server-side.

func ListAsMCPTools

func ListAsMCPTools(r *coretool.VirtualToolRegistry) []mcpgo.Tool

ListAsMCPTools converts virtual tools to mcp.Tool slice for wire protocol use.

func PopOpenAIContinuationSegment

func PopOpenAIContinuationSegment(sessionID typ.SessionID, providerUUID string, req *openai.ChatCompletionNewParams) ([]openai.ChatCompletionMessageParamUnion, bool)

PopOpenAIContinuationSegment returns the stored mixed round that req follows up on, if any.

func StoreOpenAIContinuationSegment

func StoreOpenAIContinuationSegment(sessionID typ.SessionID, providerUUID string, segment []openai.ChatCompletionMessageParamUnion)

Types

type AnthropicBetaOwner added in v1.261001.1

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

AnthropicBetaOwner is the MCP side of the Tool Round Stage: it owns the server's virtual tools, runs them through the same ToolExecutor as the existing tool loops, and keeps mixed-round results in the same continuation store.

func NewAnthropicBetaOwner added in v1.261001.1

func NewAnthropicBetaOwner(registry *coretool.VirtualToolRegistry, executor ToolExecutor, providerUUID string) *AnthropicBetaOwner

NewAnthropicBetaOwner returns the owner for one provider attempt. The provider scopes stored continuations, as in the existing tool loops.

func (*AnthropicBetaOwner) Execute added in v1.261001.1

func (*AnthropicBetaOwner) Owns added in v1.261001.1

func (o *AnthropicBetaOwner) Owns(name string) bool

func (*AnthropicBetaOwner) Resume added in v1.261001.1

func (*AnthropicBetaOwner) Suspend added in v1.261001.1

type ClientPoolGetter

type ClientPoolGetter interface {
	GetAnthropicClient(ctx context.Context, provider *typ.Provider, model string) client.AnthropicClientInterface
	GetOpenAIClient(ctx context.Context, provider *typ.Provider, model string) client.OpenAIClientInterface
}

ClientPoolGetter matches client.ClientPool interface

type EventType

type EventType int

EventType represents the type of streaming event

const (
	EventText EventType = iota
	EventToolStart
	EventToolDelta
	EventToolStop
	MessageDelta
	MessageStop
	EventUnknown
)

type FormatAdapter

type FormatAdapter interface {
	// Request/Response types
	NewRequest() any
	NewResponse() any

	// Tool extraction and classification
	ExtractTools(response any) ([]Tool, error)
	IsVirtualTool(tool Tool, registry *coretool.VirtualToolRegistry) bool
	SplitVirtualExternal(tools []Tool, registry *coretool.VirtualToolRegistry) (virtual, external []Tool, externalIDs []string)

	// Message building
	BuildAssistantMessage(response any) (any, error)
	BuildToolMessage(result ToolExecutionResult) any
	AppendToolResults(req any, resp any, results []any) (any, error)
	BuildContinuationSegment(resp any, results []ToolExecutionResult) (any, error)
	ApplyContinuation(req any, segment any) (any, error)
	FilterVirtualTools(response any, externalTools []Tool) (any, error)

	// Streaming setup
	SetupSSEHeaders(c *gin.Context)
	SendEvent(c *gin.Context, eventType string, payload []byte) error
	SendKeepAlive(c *gin.Context) error
	SendFinalMessage(c *gin.Context) error

	// Event processing (streaming only)
	ClassifyEvent(event any) EventType
	ExtractToolFromEvent(event any) (Tool, bool)
	// ShouldSuppressEvent is called for delta and stop events after ExtractToolFromEvent.
	//
	// Design note: suppress logic is format-dependent. Anthropic adapters suppress
	// virtual tool events at the start stage (bufferToolEvent in handleToolStartEvent),
	// so delta/stop events never reach the client and ShouldSuppressEvent returns false.
	// OpenAI adapters must suppress at delta stage because function names appear in
	// delta.ToolCalls, not at start; hence OpenAI's implementation checks the name here.
	ShouldSuppressEvent(event any, virtualRegistry *coretool.VirtualToolRegistry) bool
	RewriteEventIndex(event any, offset int) ([]byte, error)

	// Usage extraction
	ExtractUsage(response any) (TokenUsage, error)
}

FormatAdapter abstracts differences between API formats (Anthropic/OpenAI)

type ForwardContextGetter

type ForwardContextGetter interface {
	NewForwardContext(ctx context.Context, provider *typ.Provider) *forwarding.ForwardContext
}

ForwardContextGetter provides ForwardContext

type ForwardResult

type ForwardResult struct {
	Message         any
	Cancel          context.CancelFunc
	AnthropicClient client.AnthropicClientInterface
	OpenAIClient    client.OpenAIClientInterface
}

ForwardResult wraps non-streaming response with cancel func

type Forwarder

type Forwarder interface {
	ForwardStream(ctx context.Context, provider any, model string, req any) (StreamHandle, error)
	ForwardNonStream(ctx context.Context, provider any, model string, req any) (any, error)
}

Forwarder handles forwarding requests to upstream providers

type GenericLoopProcessor

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

GenericLoopProcessor implements format-agnostic non-streaming MCP tool handling

func NewGenericLoopProcessor

func NewGenericLoopProcessor(
	ctx context.Context,
	s ServerOps,
	provider *typ.Provider,
	hc *protocol.HandleContext,
	virtualRegistry *coretool.VirtualToolRegistry,
	recorder ProtocolRecorder,
	adapter FormatAdapter,
	forwarder Forwarder,
	toolExecutor ToolExecutor,
	config InterceptorConfig,
) *GenericLoopProcessor

NewGenericLoopProcessor creates a new generic non-streaming processor

func (*GenericLoopProcessor) Run

func (p *GenericLoopProcessor) Run(req any) (any, error)

Run executes the non-streaming processor loop. An error raised after a server tool ran is a stage.CommittedError.

type GenericStreamInterceptor

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

GenericStreamInterceptor implements format-agnostic streaming MCP tool handling

func NewGenericStreamInterceptor

func NewGenericStreamInterceptor(
	c *gin.Context,
	s ServerOps,
	provider *typ.Provider,
	hc *protocol.HandleContext,
	virtualRegistry *coretool.VirtualToolRegistry,
	recorder ProtocolRecorder,
	adapter FormatAdapter,
	forwarder Forwarder,
	toolExecutor ToolExecutor,
	config InterceptorConfig,
) *GenericStreamInterceptor

NewGenericStreamInterceptor creates a new generic streaming interceptor

func (*GenericStreamInterceptor) Run

func (i *GenericStreamInterceptor) Run(req any) error

Run executes the streaming interceptor loop. An error raised after a server tool ran is a stage.CommittedError.

type InterceptorConfig

type InterceptorConfig struct {
	MaxRounds        int
	EnableGuardrails bool
	DisableUsage     bool
	ResponseModel    string
	// OnBeforeRound is called at the start of each round after round 0.
	// Use this to reset per-round state that lives outside the interceptor
	// (e.g. guardrails stream accumulator). The interceptor does not know
	// what this callback does — it only calls it.
	OnBeforeRound func(round int) error
}

InterceptorConfig configures the generic interceptors

type OpenAIChatAdapter

type OpenAIChatAdapter struct{}

OpenAIChatAdapter implements FormatAdapter for OpenAI Chat Completions API

func NewOpenAIChatAdapter

func NewOpenAIChatAdapter() *OpenAIChatAdapter

NewOpenAIChatAdapter creates a new OpenAI Chat adapter

func (*OpenAIChatAdapter) AppendToolResults

func (o *OpenAIChatAdapter) AppendToolResults(req, resp any, results []any) (any, error)

func (*OpenAIChatAdapter) ApplyContinuation

func (o *OpenAIChatAdapter) ApplyContinuation(req any, segment any) (any, error)

func (*OpenAIChatAdapter) BuildAssistantMessage

func (o *OpenAIChatAdapter) BuildAssistantMessage(response any) (any, error)

func (*OpenAIChatAdapter) BuildContinuationSegment

func (o *OpenAIChatAdapter) BuildContinuationSegment(resp any, results []ToolExecutionResult) (any, error)

func (*OpenAIChatAdapter) BuildToolMessage

func (o *OpenAIChatAdapter) BuildToolMessage(result ToolExecutionResult) any

func (*OpenAIChatAdapter) ClassifyEvent

func (o *OpenAIChatAdapter) ClassifyEvent(event any) EventType

func (*OpenAIChatAdapter) ExtractToolFromEvent

func (o *OpenAIChatAdapter) ExtractToolFromEvent(event any) (Tool, bool)

func (*OpenAIChatAdapter) ExtractTools

func (o *OpenAIChatAdapter) ExtractTools(response any) ([]Tool, error)

func (*OpenAIChatAdapter) ExtractUsage

func (o *OpenAIChatAdapter) ExtractUsage(response any) (TokenUsage, error)

func (*OpenAIChatAdapter) FilterVirtualTools

func (o *OpenAIChatAdapter) FilterVirtualTools(response any, externalTools []Tool) (any, error)

func (*OpenAIChatAdapter) IsVirtualTool

func (o *OpenAIChatAdapter) IsVirtualTool(tool Tool, registry *coretool.VirtualToolRegistry) bool

IsVirtualTool delegates to the package-level classifier so every adapter answers the same question the same way. It used to be copied per adapter, which meant a new class of server-executed tool had to be remembered in four places.

func (*OpenAIChatAdapter) NewRequest

func (o *OpenAIChatAdapter) NewRequest() any

func (*OpenAIChatAdapter) NewResponse

func (o *OpenAIChatAdapter) NewResponse() any

func (*OpenAIChatAdapter) RewriteEventIndex

func (o *OpenAIChatAdapter) RewriteEventIndex(event any, offset int) ([]byte, error)

func (*OpenAIChatAdapter) SendEvent

func (o *OpenAIChatAdapter) SendEvent(c *gin.Context, eventType string, payload []byte) error

func (*OpenAIChatAdapter) SendFinalMessage

func (o *OpenAIChatAdapter) SendFinalMessage(c *gin.Context) error

func (*OpenAIChatAdapter) SendKeepAlive

func (o *OpenAIChatAdapter) SendKeepAlive(c *gin.Context) error

func (*OpenAIChatAdapter) SetupSSEHeaders

func (o *OpenAIChatAdapter) SetupSSEHeaders(c *gin.Context)

func (*OpenAIChatAdapter) ShouldSuppressEvent

func (o *OpenAIChatAdapter) ShouldSuppressEvent(event any, virtualRegistry *coretool.VirtualToolRegistry) bool

func (*OpenAIChatAdapter) SplitVirtualExternal

func (o *OpenAIChatAdapter) SplitVirtualExternal(
	tools []Tool,
	registry *coretool.VirtualToolRegistry,
) (virtual, external []Tool, externalIDs []string)

type OpenAIChatForwarder

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

OpenAIChatForwarder implements Forwarder for OpenAI Chat API

func NewOpenAIChatForwarder

func NewOpenAIChatForwarder(clientPool ClientPoolGetter, ctxGetter ForwardContextGetter) *OpenAIChatForwarder

func (*OpenAIChatForwarder) ForwardNonStream

func (f *OpenAIChatForwarder) ForwardNonStream(
	ctx context.Context,
	provider any,
	model string,
	req any,
) (any, error)

func (*OpenAIChatForwarder) ForwardStream

func (f *OpenAIChatForwarder) ForwardStream(
	ctx context.Context,
	provider any,
	model string,
	req any,
) (StreamHandle, error)

type OpenAIChatStreamHandle

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

OpenAIChatStreamHandle wraps OpenAI stream

func (*OpenAIChatStreamHandle) Close

func (h *OpenAIChatStreamHandle) Close() error

func (*OpenAIChatStreamHandle) Current

func (h *OpenAIChatStreamHandle) Current() any

func (*OpenAIChatStreamHandle) Err

func (h *OpenAIChatStreamHandle) Err() error

func (*OpenAIChatStreamHandle) Next

func (h *OpenAIChatStreamHandle) Next() bool

type OpenAIChunkTool

type OpenAIChunkTool struct {
	ToolCall openai.ChatCompletionChunkChoiceDeltaToolCall
}

OpenAIChunkTool implements Tool interface for OpenAI ChatCompletionChunk tool calls

func (*OpenAIChunkTool) Arguments

func (t *OpenAIChunkTool) Arguments() string

func (*OpenAIChunkTool) ID

func (t *OpenAIChunkTool) ID() string

func (*OpenAIChunkTool) Name

func (t *OpenAIChunkTool) Name() string

type OpenAIMessageTool

type OpenAIMessageTool struct {
	ToolCall openai.ChatCompletionMessageToolCallUnion
}

OpenAIMessageTool implements Tool interface for OpenAI ChatCompletionMessage tool calls

func (*OpenAIMessageTool) Arguments

func (t *OpenAIMessageTool) Arguments() string

func (*OpenAIMessageTool) ID

func (t *OpenAIMessageTool) ID() string

func (*OpenAIMessageTool) Name

func (t *OpenAIMessageTool) Name() string

type OpenAITool

type OpenAITool = OpenAIMessageTool

For now, use the message tool type

type ProtocolRecorder

type ProtocolRecorder interface {
	RecordError(err error)
	SetAssembledResponse(resp any)
	RecordResponse(provider any, model string)
}

ProtocolRecorder abstracts protocol recording operations

type ResponseDecision

type ResponseDecision int

ResponseDecision represents the decision after classifying a response

const (
	DecisionNoTools ResponseDecision = iota
	DecisionPureVirtual
	DecisionPureExternal
	DecisionMixed
)

type ServerOps

type ServerOps interface {
	TrackUsage(c *gin.Context, input, output, cache int)
	CallMCPTool(ctx context.Context, toolName, arguments string, messages []map[string]any) (string, error)
	GetRecorder() ProtocolRecorder
}

ServerOps abstracts server operations needed by interceptors/processors

type ServerToolExecutor

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

ServerToolExecutor implements ToolExecutor by wrapping server's MCP tool execution

func NewServerToolExecutor

func NewServerToolExecutor(s ToolExecutorServer) *ServerToolExecutor

func (*ServerToolExecutor) ExecuteTool

func (e *ServerToolExecutor) ExecuteTool(
	ctx context.Context,
	tool Tool,
	messages []map[string]any,
) (ToolExecutionResult, error)

func (*ServerToolExecutor) ExecuteToolWithContext

func (e *ServerToolExecutor) ExecuteToolWithContext(
	ctx context.Context,
	tool Tool,
	messages []map[string]any,
) (context.Context, ToolExecutionResult, error)

func (*ServerToolExecutor) ExecuteTools

func (e *ServerToolExecutor) ExecuteTools(
	ctx context.Context,
	tools []Tool,
	messages []map[string]any,
) ([]ToolExecutionResult, error)

type StreamHandle

type StreamHandle interface {
	Next() bool
	Current() any
	Err() error
	Close() error
}

StreamHandle represents a generic streaming response

type TokenUsage

type TokenUsage struct {
	InputTokens  int
	OutputTokens int
	CacheTokens  int
}

TokenUsage represents token usage information

type Tool

type Tool interface {
	ID() string
	Name() string
	Arguments() string
}

Tool represents a tool call in a format-agnostic way

type ToolExecutionResult

type ToolExecutionResult struct {
	ToolUseID string
	Contents  []coretool.ToolContent
	IsError   bool
}

ToolExecutionResult represents the result of executing a tool

func (ToolExecutionResult) TextContent

func (r ToolExecutionResult) TextContent() string

TextContent returns the concatenated text of all text content items.

type ToolExecutor

type ToolExecutor interface {
	ExecuteToolWithContext(ctx context.Context, tool Tool, messages []map[string]any) (context.Context, ToolExecutionResult, error)
	ExecuteTool(ctx context.Context, tool Tool, messages []map[string]any) (ToolExecutionResult, error)
	ExecuteTools(ctx context.Context, tools []Tool, messages []map[string]any) ([]ToolExecutionResult, error)
}

ToolExecutor handles execution of virtual tools

type ToolExecutorServer

type ToolExecutorServer interface {
	CallMCPToolWithHooks(ctx context.Context, toolName, arguments string, messages []map[string]any) (context.Context, coretool.ToolResult, error)
	CallMCPTool(ctx context.Context, toolName, arguments string, messages []map[string]any) (string, error)
}

ToolExecutorServer defines the server methods needed for tool execution

Jump to

Keyboard shortcuts

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