tools

package
v0.11.9 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: EUPL-1.2 Imports: 12 Imported by: 0

Documentation

Overview

Package tools implements the application-layer MCP proxy infrastructure for F099: tool interception and routing in AI agent workflows.

Architecture Overview

The package sits in the application layer and coordinates between domain ports and infrastructure adapters. It has two primary concerns:

  1. ProxyService — lifecycle management of the MCP proxy subprocess (stdio path) or in-process HTTP router (HTTP path).
  2. Router — in-process dispatch of tool calls to registered ToolProvider adapters.

Both components accept domain-level ports (ports.ToolProvider, ports.Logger, ports.Tracer) and do not import any infrastructure package, preserving the hexagonal dependency rule.

Two Proxy Paths

## Stdio Path (Claude, Gemini, Codex, OpenCode)

ProxyService.StartForStdio writes a temporary JSON config file and spawns:

awf mcp-serve --config=<path>

The subprocess runs the MCP server protocol over stdin/stdout. The provider's CLI receives the config path via a provider-specific flag (e.g., --mcp-config for Claude). Cleanup kills the subprocess and removes the temp file; it is idempotent.

## HTTP Path (OpenAI Compatible)

ProxyService.StartForHTTP builds an in-process Router containing the same tool providers as the stdio path, but does not spawn a subprocess. The Router is injected directly into the OpenAI Compatible provider via SetToolRouter, enabling the multi-turn tool-call loop (T012) to dispatch calls without a round-trip through the network.

ProxyConfig

ProxyConfig drives which tools are exposed:

  • Enable: master switch; both StartForStdio and StartForHTTP return a noop when false.
  • InterceptBuiltins: when true, the built-in tool provider (bash, glob, grep, read, write, edit) is included as the first registered provider.
  • PluginTools: each entry names a plugin and the subset of its operations to expose. PluginToolAdapter translates operation schemas to ports.ToolDefinition values and routes CallTool invocations back through the OperationProvider port.

Router

Router implements a flat, name-keyed dispatch table over multiple ToolProvider adapters. Registration is append-only; name collisions return an error with the TOOL_COLLISION error code so callers can surface it explicitly rather than silently shadowing tools.

ListTools returns all definitions from all registered providers in registration order. CallTool dispatches to the provider that owns the named tool, then logs timing and result via the Tracer and Logger ports. Unregistered tool names return UNKNOWN_TOOL.

ProviderFactory

ProxyService accepts a ProviderFactory function at construction time rather than building providers directly. This injects T013's real adapter construction without requiring ProxyService to import the infrastructure/tools/builtins package. It also enables unit tests to supply a stub factory returning fixed providers.

Error Codes

Domain-level error codes from internal/domain/errors are used for all structured errors returned by this package:

  • TOOL_COLLISION — two providers registered the same tool name.
  • UNKNOWN_TOOL — CallTool received a name not registered by any provider.

Lifecycle Contract

Both StartForStdio and StartForHTTP return a cleanup func() error. Callers MUST invoke cleanup after the agent exits, regardless of success or failure. Cleanup functions are idempotent: a second call returns nil without side effects.

Defer order in execution paths:

  1. MCP injector cleanup (stops the subprocess / releases in-process resources)
  2. ToolProxyService cleanup (removes temp config files)

The reverse-defer ordering in Go (LIFO) ensures the injector runs before the service teardown, matching the startup order of proxy-then-injector.

Thread Safety

Router uses a sync.RWMutex. Register acquires the write lock; ListTools and CallTool acquire the read lock. ProxyService itself is not designed for concurrent StartForStdio or StartForHTTP calls on the same instance; each workflow step creates a fresh call.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CoexistenceProviders

func CoexistenceProviders() []string

CoexistenceProviders returns the agent provider names that operate the MCP proxy in coexistence mode: they register the proxy server but cannot block built-in tool access at the CLI level. A fresh slice is returned on each call to prevent callers from mutating the canonical list.

This list is the single source of truth for both the static-validation warning (application layer) and the runtime warn path (infrastructure providers). It lives in the application layer — not the domain — because the values are infrastructure provider names ("codex", "copilot", "opencode"), which are infrastructure concerns that the domain must not depend on.

Types

type PluginToolSpec

type PluginToolSpec struct {
	Plugin string   `json:"plugin"`
	Expose []string `json:"expose"`
}

PluginToolSpec describes which tools from a named plugin to expose via the proxy.

The JSON tags must match the format consumed by `awf mcp-serve` (interfaces/cli/mcp_serve.go), which reads the on-disk config written by ProxyService.StartForStdio. Renaming a tag here without updating the subprocess reader will silently break tool discovery.

type ProviderFactory

type ProviderFactory func(cfg ProxyConfig) ([]ports.ToolProvider, error)

ProviderFactory creates tool providers from a proxy config. Injected so T013 can supply the real factory without modifying ProxyService.

type ProxyConfig

type ProxyConfig struct {
	Enable            bool
	InterceptBuiltins bool
	PluginTools       []PluginToolSpec
}

ProxyConfig describes what the MCP proxy should expose to clients. Enable must be true for the proxy to start; when false, StartForStdio and StartForHTTP return a noop immediately without spawning any subprocess.

type ProxyService

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

ProxyService orchestrates the MCP tool proxy lifecycle for a workflow step.

func NewProxyService

func NewProxyService(cliExec ports.CLIExecutor, tracer ports.Tracer, logger ports.Logger, providerFactory ProviderFactory) *ProxyService

NewProxyService creates a configured ProxyService.

func (*ProxyService) StartForHTTP

func (s *ProxyService) StartForHTTP(ctx context.Context, cfg ProxyConfig) (router *Router, cleanup func() error, err error)

StartForHTTP builds an in-process router for OpenAI Compatible transport. Returns (nil, noopCleanup, nil) when cfg.Enable is false or no tools are configured.

func (*ProxyService) StartForStdio

func (s *ProxyService) StartForStdio(ctx context.Context, cfg ProxyConfig) (mcpConfigPath string, cleanup func() error, err error)

StartForStdio writes a tmp MCP config and spawns `awf mcp-serve --config=<path>`. Returns ("", noopCleanup, nil) when cfg.Enable is false or no tools are configured. cleanup is idempotent: second call returns nil.

type Router

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

Router dispatches tool calls to the provider that registered each tool name.

func NewRouter

func NewRouter(tracer ports.Tracer, logger ports.Logger) *Router

func (*Router) CallTool

func (r *Router) CallTool(ctx context.Context, name string, args map[string]any) (*ports.ToolResult, error)

func (*Router) Close

func (r *Router) Close(ctx context.Context) error

func (*Router) ListTools

func (r *Router) ListTools(ctx context.Context) ([]ports.ToolDefinition, error)

func (*Router) Register

func (r *Router) Register(ctx context.Context, provider ports.ToolProvider) error

Register adds a provider's tools to the router. Returns a collision error if any tool name is already registered. The context is propagated to provider.ListTools so callers can enforce deadlines/cancellation on the initial tool discovery handshake.

func (*Router) SetRecorder

func (r *Router) SetRecorder(rec ports.Recorder)

SetRecorder attaches an optional transcript recorder for capturing tool.call / tool.result events.

func (*Router) SetRunID

func (r *Router) SetRunID(id string)

SetRunID sets the workflow run identifier stamped onto emitted tool.call / tool.result events so tool exchanges can be correlated to their originating workflow run.

Jump to

Keyboard shortcuts

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