feat(kit): central tools for harnesses through the egress proxy and gateway task-tool RPCs
This commit is contained in:
41 files changed
+2187
-189
No files matched your search
@@ -1,182 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
|
||||
var errUnknownMCPTransport = errors.New("unknown MCP transport")
|
||||
|
||||
// mcpProviderSet holds the resources needed to clean up MCP providers.
|
||||
type mcpProviderSet struct {
|
||||
providers []toolprovider.Engine
|
||||
registry *tools.Registry
|
||||
}
|
||||
|
||||
type mcpProviderBuilder func(config.MCPServer, mcp.SamplingHandler) (toolprovider.Engine, string, error)
|
||||
|
||||
// startMCPProviders starts the configured MCP servers and registers their
|
||||
// tools. sampling answers sampling requests when non-nil. Returns nil with
|
||||
// no servers.
|
||||
func startMCPProviders(
|
||||
ctx context.Context,
|
||||
servers []config.MCPServer,
|
||||
sampling mcp.SamplingHandler,
|
||||
log *slog.Logger,
|
||||
) (*mcpProviderSet, error) {
|
||||
return startMCPProvidersWith(ctx, servers, sampling, log, buildMCPProvider)
|
||||
}
|
||||
|
||||
func startMCPProvidersWith(
|
||||
ctx context.Context,
|
||||
servers []config.MCPServer,
|
||||
sampling mcp.SamplingHandler,
|
||||
log *slog.Logger,
|
||||
build mcpProviderBuilder,
|
||||
) (*mcpProviderSet, error) {
|
||||
if len(servers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
set := &mcpProviderSet{registry: tools.NewRegistry()}
|
||||
var firstErr error
|
||||
for _, server := range servers {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
if name == "" {
|
||||
log.Warn("mcp server skipped: empty name")
|
||||
continue
|
||||
}
|
||||
|
||||
provider, transportType, err := build(server, sampling)
|
||||
if errors.Is(err, errUnknownMCPTransport) {
|
||||
log.Warn("mcp server skipped: unknown transport", "name", name, "transport", transportType)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
firstErr = retainFirstError(firstErr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
toolCount, err := startMCPProvider(ctx, name, provider, set.registry, log)
|
||||
if err != nil {
|
||||
firstErr = retainFirstError(firstErr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
set.providers = append(set.providers, provider)
|
||||
log.Info("mcp provider started", "name", name, "transport", transportType, "tools", toolCount)
|
||||
}
|
||||
|
||||
if len(set.providers) == 0 {
|
||||
return nil, firstErr
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func buildMCPProvider(server config.MCPServer, sampling mcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
transportType := strings.ToLower(strings.TrimSpace(server.Transport))
|
||||
if transportType == "" {
|
||||
transportType = "stdio"
|
||||
}
|
||||
|
||||
transport, err := mcpTransportForServer(name, transportType, server)
|
||||
if err != nil {
|
||||
return nil, transportType, err
|
||||
}
|
||||
return mcptoolprovider.New(name, transport, server.ParallelToolCalls, mcptoolprovider.WithSamplingHandler(sampling)), transportType, nil
|
||||
}
|
||||
|
||||
func mcpTransportForServer(
|
||||
name string,
|
||||
transportType string,
|
||||
server config.MCPServer,
|
||||
) (mcptoolprovider.LifecycleTransport, error) {
|
||||
switch transportType {
|
||||
case "stdio":
|
||||
command := strings.TrimSpace(server.Command)
|
||||
if command == "" {
|
||||
return nil, fmt.Errorf("MCP stdio server %q requires a command", name)
|
||||
}
|
||||
// Share the npm cache volume across task containers.
|
||||
return mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), server.Args...),
|
||||
Env: mcp.NpmCacheEnv(command, storage.MCPNPMCacheMountDir),
|
||||
}), nil
|
||||
case "http", "streamablehttp":
|
||||
url := strings.TrimSpace(server.URL)
|
||||
if url == "" {
|
||||
return nil, fmt.Errorf("MCP http server %q requires a url", name)
|
||||
}
|
||||
return mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
|
||||
Endpoint: url,
|
||||
Headers: server.Headers,
|
||||
}), nil
|
||||
case "sse":
|
||||
sseEndpoint := strings.TrimSpace(server.SSEEndpoint)
|
||||
if sseEndpoint == "" {
|
||||
return nil, fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
|
||||
}
|
||||
return mcp.NewSSETransport(mcp.SSETransportConfig{
|
||||
SSEEndpoint: sseEndpoint,
|
||||
MessageEndpoint: strings.TrimSpace(server.MessageEndpoint),
|
||||
Headers: server.Headers,
|
||||
}), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errUnknownMCPTransport, transportType)
|
||||
}
|
||||
}
|
||||
|
||||
func startMCPProvider(
|
||||
ctx context.Context,
|
||||
name string,
|
||||
provider toolprovider.Engine,
|
||||
registry *tools.Registry,
|
||||
log *slog.Logger,
|
||||
) (int, error) {
|
||||
if err := provider.Start(ctx); err != nil {
|
||||
log.Warn("mcp provider start failed", "name", name, "err", err)
|
||||
return 0, err
|
||||
}
|
||||
|
||||
entries, err := provider.Discover(ctx)
|
||||
if err != nil {
|
||||
log.Warn("mcp tool discovery failed", "name", name, "err", err)
|
||||
_ = provider.Stop(ctx)
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if err := registry.Register(entry); err != nil {
|
||||
log.Warn("mcp tool registration failed", "tool", entry.Name, "err", err)
|
||||
}
|
||||
}
|
||||
return len(entries), nil
|
||||
}
|
||||
|
||||
func retainFirstError(firstErr, err error) error {
|
||||
if firstErr != nil {
|
||||
return firstErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *mcpProviderSet) cleanup(ctx context.Context, log *slog.Logger) {
|
||||
for _, provider := range s.providers {
|
||||
if err := provider.Stop(ctx); err != nil {
|
||||
log.Warn("mcp provider stop failed", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
// taskSamplingHandler answers MCP sampling requests with the task's model.
|
||||
// Without a runtime or model the request is refused. record receives each
|
||||
// call's model ref and token usage.
|
||||
func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig, record func(context.Context, string, chat.Usage)) mcp.SamplingHandler {
|
||||
return func(ctx context.Context, req mcp.SamplingRequest) (mcp.SamplingResult, error) {
|
||||
if llm == nil {
|
||||
return mcp.SamplingResult{}, errors.New("mcp sampling: no model runtime is configured")
|
||||
}
|
||||
model, err := config.ResolveModel(cfg.Models, "", config.PurposeAgent)
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
||||
}
|
||||
messages, err := modelloop.SamplingMessages(req)
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, err
|
||||
}
|
||||
limits := cfg.ModelLimits[model]
|
||||
options := core.GenerateOptions{
|
||||
Messages: messages,
|
||||
System: req.SystemPrompt,
|
||||
MaxSteps: 1,
|
||||
MaxTokens: modelloop.SamplingMaxTokens(req.MaxTokens, limits.MaxOutputTokens),
|
||||
}
|
||||
if req.Temperature != nil {
|
||||
options.Temperature = float32(*req.Temperature)
|
||||
}
|
||||
result, err := llm.Chat(ctx, model, options)
|
||||
record(ctx, model, result.TotalUsage)
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
||||
}
|
||||
return mcp.SamplingResult{
|
||||
Model: model,
|
||||
Role: "assistant",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: result.Text},
|
||||
StopReason: string(result.FinishReason),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// samplingUsageRecorder records a task's MCP sampling calls against the task.
|
||||
// A failed write is logged, never fails the call.
|
||||
func samplingUsageRecorder(store workflow.Store, t *workflow.Task, log *slog.Logger) func(context.Context, string, chat.Usage) {
|
||||
return func(ctx context.Context, model string, used chat.Usage) {
|
||||
if store == nil || t == nil {
|
||||
return
|
||||
}
|
||||
record := usage.Record{
|
||||
Source: usage.SourceTask, TaskID: t.ID, Attempt: t.Attempt, Workflow: t.Workflow, Step: "mcp-sampling",
|
||||
InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens),
|
||||
CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(),
|
||||
}.WithRef(model)
|
||||
if err := store.RecordUsage(ctx, record); err != nil && log != nil {
|
||||
log.Warn("record model usage failed", "model", model, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/prsource"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
@@ -177,14 +178,14 @@ func applyToolLimits(agent agentrun.Runner, policy config.ToolPolicy, allow []st
|
||||
// stageRunners builds the runner every agent stage uses. llm is the task's
|
||||
// shared model runtime (the one its MCP providers answer sampling from); the
|
||||
// registry path reuses it rather than building a second one.
|
||||
func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerFactory, llm *runtime.Runtime, log *slog.Logger) (agentrun.Runner, error) {
|
||||
func stageRunners(req taskrun.Request, mcpSet *taskmcp.Set, newRunner runnerFactory, llm *runtime.Runtime, log *slog.Logger) (agentrun.Runner, error) {
|
||||
if req.Harness != nil {
|
||||
// The built-in loop has no route to a model from a Kit container.
|
||||
return agentexec.HarnessStages{Runner: agentexec.NewHarnessRunner(nil), Spec: *req.Harness}, nil
|
||||
}
|
||||
var agent agentrun.Runner
|
||||
if mcpSet != nil && mcpSet.registry != nil {
|
||||
agent = modelloop.NewLoopRunner(llm, log, mcpSet.registry)
|
||||
if mcpSet != nil && mcpSet.Registry != nil {
|
||||
agent = modelloop.NewLoopRunner(llm, log, mcpSet.Registry)
|
||||
} else {
|
||||
agent = newRunner(req.Providers, req.Cfg.ModelLimits, log)
|
||||
}
|
||||
@@ -224,19 +225,9 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
|
||||
}
|
||||
defer restoreWorktreeOwnership(trees, workDir, log)()
|
||||
|
||||
// The MCP providers a task hosts share the same model runtime its agent
|
||||
// stages run on, so a server-initiated sampling request is answered from
|
||||
// the task's own model rather than a second provider client.
|
||||
var llm *runtime.Runtime
|
||||
if len(req.MCPServers) > 0 {
|
||||
llm = modelloop.NewRuntime(req.Providers, req.Cfg.ModelLimits)
|
||||
}
|
||||
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, taskSamplingHandler(llm, req.Cfg, samplingUsageRecorder(dependencies.store, req.Task, log)), log)
|
||||
llm, mcpSet := taskMCPProviders(ctx, req, dependencies, log)
|
||||
if mcpSet != nil {
|
||||
defer mcpSet.cleanup(ctx, log)
|
||||
}
|
||||
if mcpErr != nil {
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr)
|
||||
defer mcpSet.Close(ctx, log)
|
||||
}
|
||||
|
||||
agent, err := stageRunners(req, mcpSet, newRunner, llm, log)
|
||||
@@ -342,3 +333,15 @@ func CompilePinnedWorkflow(req *taskrun.Request, steps *workflow.Manager) (workf
|
||||
}
|
||||
return wf, nil
|
||||
}
|
||||
|
||||
func taskMCPProviders(ctx context.Context, req taskrun.Request, deps taskDependencies, log *slog.Logger) (*runtime.Runtime, *taskmcp.Set) {
|
||||
if req.Harness != nil || len(req.MCPServers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
llm := modelloop.NewRuntime(req.Providers, req.Cfg.ModelLimits)
|
||||
set, err := taskmcp.Start(ctx, req.MCPServers, taskmcp.SamplingHandler(llm, req.Cfg, taskmcp.UsageRecorder(deps.store, req.Task, log)), log, storage.MCPNPMCacheMountDir)
|
||||
if err != nil {
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", err)
|
||||
}
|
||||
return llm, set
|
||||
}
|
||||
@@ -13,9 +13,12 @@ import (
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/fetch"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/tasktools"
|
||||
)
|
||||
|
||||
const relayName = "archie-egress-relay"
|
||||
@@ -62,7 +65,14 @@ func (b *boot) setupKitLauncher(ctx context.Context) {
|
||||
// Without a harness secret store, Register refuses a Kit with a
|
||||
// required OAuth credential.
|
||||
oauthStore, _ := b.stateStore.(egress.OAuthStore)
|
||||
proxy := egress.NewProxy(ca, egress.ProxyOptions{Resolver: resolver, OAuthStore: oauthStore})
|
||||
gateway, cleanup, err := b.connectTaskTools()
|
||||
if err != nil {
|
||||
_ = ln.Close()
|
||||
log.Warn("kit task tools unavailable", "err", err)
|
||||
return
|
||||
}
|
||||
b.addCleanup(cleanup)
|
||||
proxy := egress.NewProxy(ca, egress.ProxyOptions{Resolver: resolver, OAuthStore: oauthStore, TaskTools: gateway})
|
||||
srv := &http.Server{Handler: proxy, ReadHeaderTimeout: 30 * time.Second}
|
||||
go func() {
|
||||
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
@@ -107,3 +117,11 @@ func shutdownEgress(networks *egress.Networks, srv *http.Server, log *slog.Logge
|
||||
_ = srv.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (b *boot) connectTaskTools() (*tasktools.Client, func(), error) {
|
||||
id, err := servicekit.Identity(b.cfg.TLS, presence.Daemon)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return tasktools.Dial(b.cfg.Services.Get(config.ServiceNameGateway).Target, id)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
@@ -68,4 +69,4 @@ func (m modelEgress) Open(token, org string, providers map[string]config.Provide
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m modelEgress) Close(token string) { m.proxy.Revoke(token) }
|
||||
func (m modelEgress) Close(ctx context.Context, token string) { m.proxy.Revoke(ctx, token) }
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -30,7 +31,9 @@ func (b *server) serveGatewayListener(ctx context.Context, listener net.Listener
|
||||
// begins accepting the moment it is called, and a unit whose
|
||||
// TimeoutStartSec expires first would restart a healthy process.
|
||||
b.announceReady()
|
||||
return serveGateway(ctx, listener, contract, b.chatSessionStore, b.chatCatalog(), opts)
|
||||
taskTools := &taskToolsServer{gateway: b, authority: b.stateStore, configFor: b.taskToolsConfig, sessions: make(map[[32]byte]*taskToolSession)}
|
||||
defer taskTools.Close(ctx)
|
||||
return serveGateway(ctx, listener, contract, b.chatSessionStore, b.chatCatalog(), opts, taskTools)
|
||||
}
|
||||
|
||||
func (b *server) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
|
||||
@@ -98,9 +101,10 @@ func gatewayServerOpts(listen string, id *rpctls.Identity, principals access.Pri
|
||||
}, nil
|
||||
}
|
||||
|
||||
func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract, sessions gateway.SessionStore, catalog gatewayrpc.Catalog, opts []grpc.ServerOption) error {
|
||||
func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract, sessions gateway.SessionStore, catalog gatewayrpc.Catalog, opts []grpc.ServerOption, taskTools pb.TaskToolsServiceServer) error {
|
||||
server := grpc.NewServer(append(servicekit.ServerLimits(), opts...)...)
|
||||
gatewayrpc.RegisterServer(server, contract, sessions, catalog)
|
||||
pb.RegisterTaskToolsServiceServer(server, taskTools)
|
||||
// Serve's bounded drain returns before the session store and tools close.
|
||||
return servicekit.Serve(ctx, server, listener)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package archiegateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"mime"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
func executeTaskTool(ctx context.Context, entry tools.ToolEntry, input json.RawMessage, limit int) (result *mcp.CallToolResult, err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
result = nil
|
||||
err = fmt.Errorf("tool execution failed")
|
||||
}
|
||||
}()
|
||||
if !entry.Available() {
|
||||
return nil, fmt.Errorf("tool is unavailable")
|
||||
}
|
||||
schema, err := json.Marshal(taskToolSchema(entry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool schema unavailable")
|
||||
}
|
||||
if len(input) == 0 {
|
||||
input = json.RawMessage(`{}`)
|
||||
}
|
||||
if reason, ok := agentexec.ValidateCaptureArgs(agentrun.CaptureTool{Name: entry.Name, Parameters: schema}, input); !ok {
|
||||
return nil, fmt.Errorf("%s", reason)
|
||||
}
|
||||
var args map[string]any
|
||||
if err := json.Unmarshal(input, &args); err != nil {
|
||||
return nil, fmt.Errorf("arguments must be an object")
|
||||
}
|
||||
out, err := entry.Handler(ctx, args)
|
||||
if err != nil {
|
||||
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: "tool execution failed"}}}, nil
|
||||
}
|
||||
if entry.MaxResultSizeChars != 0 {
|
||||
limit = entry.MaxResultSizeChars
|
||||
}
|
||||
if media, ok := out.(tools.MultimodalResult); ok {
|
||||
return taskToolMedia(entry.Name, media, limit)
|
||||
}
|
||||
raw, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode tool result")
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: tools.CapPayload(entry.Name, string(raw), limit, "")}}}, nil
|
||||
}
|
||||
|
||||
func taskToolMedia(name string, media tools.MultimodalResult, limit int) (*mcp.CallToolResult, error) {
|
||||
result := &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: tools.CapPayload(name, media.Summary, limit, "")}}}
|
||||
root, err := os.OpenRoot(media.SubdirHint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool media unavailable")
|
||||
}
|
||||
defer root.Close()
|
||||
for _, file := range media.Files {
|
||||
relative, err := filepath.Rel(media.SubdirHint, file)
|
||||
if err != nil || !filepath.IsLocal(relative) {
|
||||
return nil, fmt.Errorf("tool media outside provider directory")
|
||||
}
|
||||
raw, err := root.ReadFile(relative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tool media")
|
||||
}
|
||||
mimeType := mime.TypeByExtension(filepath.Ext(file))
|
||||
switch mimeType {
|
||||
case "image/png", "image/jpeg", "image/gif", "image/webp":
|
||||
result.Content = append(result.Content, &mcp.ImageContent{Data: raw, MIMEType: mimeType})
|
||||
case "audio/wav", "audio/mpeg":
|
||||
result.Content = append(result.Content, &mcp.AudioContent{Data: raw, MIMEType: mimeType})
|
||||
default:
|
||||
result.Content = append(result.Content, &mcp.EmbeddedResource{Resource: &mcp.ResourceContents{URI: "archie-media:///" + filepath.Base(file), MIMEType: mimeType, Blob: raw}})
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func taskToolSchema(entry tools.ToolEntry) tools.JSONSchema {
|
||||
schema := entry.ResolvedSchema()
|
||||
if schema == nil {
|
||||
return tools.JSONSchema{"type": "object", "properties": map[string]any{}}
|
||||
}
|
||||
return schema
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package archiegateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
func TestTaskToolResults(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, input string
|
||||
output any
|
||||
limit int
|
||||
badPath bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "text limit", input: `{"value":"valid"}`, output: strings.Repeat("a", 200), limit: 40},
|
||||
{name: "schema enforced", input: `{"value":true}`, wantErr: true},
|
||||
{name: "media", input: `{"value":"valid"}`},
|
||||
{name: "media cannot escape", input: `{"value":"valid"}`, badPath: true, wantErr: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
file := filepath.Join(root, "image.png")
|
||||
if tt.badPath {
|
||||
file = filepath.Join(t.TempDir(), "outside.png")
|
||||
}
|
||||
if err := os.WriteFile(file, []byte("image-data"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := tt.output
|
||||
if output == nil {
|
||||
output = tools.MultimodalResult{Summary: "image", SubdirHint: root, Files: []string{file}}
|
||||
}
|
||||
called := false
|
||||
entry := tools.ToolEntry{Name: "tool", Schema: tools.JSONSchema{"type": "object", "properties": map[string]any{"value": map[string]any{"type": "string"}}, "required": []string{"value"}}, Handler: func(context.Context, map[string]any) (any, error) { called = true; return output, nil }}
|
||||
result, err := executeTaskTool(t.Context(), entry, json.RawMessage(tt.input), tt.limit)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("error %v, want error %v", err, tt.wantErr)
|
||||
}
|
||||
if tt.name == "schema enforced" && called {
|
||||
t.Fatal("invalid arguments executed")
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
raw, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(raw), root) {
|
||||
t.Fatal("host media path escaped")
|
||||
}
|
||||
if tt.name == "media" {
|
||||
image, ok := result.Content[1].(*mcp.ImageContent)
|
||||
if !ok || string(image.Data) != "image-data" {
|
||||
t.Fatalf("media result %s", raw)
|
||||
}
|
||||
}
|
||||
text, ok := result.Content[0].(*mcp.TextContent)
|
||||
if !ok {
|
||||
t.Fatal("missing text content")
|
||||
}
|
||||
if tt.limit > 0 && strings.Contains(text.Text, strings.Repeat("a", 200)) {
|
||||
t.Fatal("tool result limit was ignored")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package archiegateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
type taskToolSession struct {
|
||||
mu sync.Mutex
|
||||
lifetime context.Context //nolint:containedctx // Providers belong to the run, not one RPC.
|
||||
providers *taskmcp.Set
|
||||
configHash [32]byte
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type taskToolAuthority interface {
|
||||
TaskPrincipalForCredential(context.Context, string) (*task.Task, identity.IdentityID, error)
|
||||
PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error)
|
||||
GetInstalled(context.Context, string) (storepkg.Installed, error)
|
||||
TaskModels(context.Context, int64) (config.OrgModels, error)
|
||||
RecordUsage(context.Context, usage.Record) error
|
||||
}
|
||||
|
||||
type taskToolsServer struct {
|
||||
pb.UnimplementedTaskToolsServiceServer
|
||||
gateway *server
|
||||
authority taskToolAuthority
|
||||
configFor func(context.Context) (config.Config, error)
|
||||
mu sync.Mutex
|
||||
sessions map[[32]byte]*taskToolSession
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) authorize(ctx context.Context, credential string) (context.Context, *task.Task, config.Config, []string, error) {
|
||||
if access.SourceFromContext(ctx) != "archied" {
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.PermissionDenied, "task tools require the daemon")
|
||||
}
|
||||
if credential == "" {
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.Unauthenticated, "task grant required")
|
||||
}
|
||||
t, principal, err := s.authority.TaskPrincipalForCredential(ctx, credential)
|
||||
if err != nil {
|
||||
s.close(ctx, credential)
|
||||
code := codes.Unauthenticated
|
||||
if errors.Is(err, storecontract.ErrUnavailable) {
|
||||
code = codes.Unavailable
|
||||
}
|
||||
return nil, nil, config.Config{}, nil, status.Error(code, "task grant unavailable")
|
||||
}
|
||||
if t.Status != "running" {
|
||||
s.close(ctx, credential)
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.PermissionDenied, "task is not running")
|
||||
}
|
||||
p, err := s.authority.PrincipalFor(ctx, principal)
|
||||
if err != nil || string(p.Org) != t.OrgOrDefault() {
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.PermissionDenied, "task identity unavailable")
|
||||
}
|
||||
ctx = org.WithScope(org.WithOrg(access.WithPrincipal(access.WithActor(ctx, string(principal)), p), p.Org), p.Org)
|
||||
iface, err := task.ParseWorkflowInterface(t.WorkflowDefinitionYAML)
|
||||
if err != nil {
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.FailedPrecondition, "task workflow unavailable")
|
||||
}
|
||||
cfg, err := s.configFor(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.Unavailable, "task tool settings unavailable")
|
||||
}
|
||||
profile, err := cfg.Containers.Profile(iface.Profile)
|
||||
if err != nil || profile.Kit == "" {
|
||||
return nil, nil, config.Config{}, nil, status.Error(codes.FailedPrecondition, "task has no Kit profile")
|
||||
}
|
||||
packaged := workflow.PackageOf(t.WorkflowDefinitionYAML)
|
||||
var accepted []string
|
||||
if packaged != "" {
|
||||
installed, err := s.authority.GetInstalled(ctx, packaged)
|
||||
if err == nil && installed.AcceptedAuthority != nil {
|
||||
accepted = installed.AcceptedAuthority.Tools
|
||||
}
|
||||
}
|
||||
return ctx, t, cfg, storepkg.AllowedTools(profile.Tools, packaged != "", accepted), nil
|
||||
}
|
||||
|
||||
func taskToolAllowed(entry tools.ToolEntry, allowed []string) bool {
|
||||
return entry.Toolset != "workspace" && entry.Name != "send_file" && !entry.Classification.IsApprovalRequired() && (allowed == nil || slices.Contains(allowed, entry.Name))
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) entries(ctx context.Context, t *task.Task, cfg config.Config, credential string, allowed []string) ([]tools.ToolEntry, error) {
|
||||
entries := []tools.ToolEntry{}
|
||||
if allowed != nil && len(allowed) == 0 {
|
||||
s.close(ctx, credential)
|
||||
return entries, nil
|
||||
}
|
||||
for _, entry := range s.gateway.toolReg.All() {
|
||||
// Task MCP providers have their own sampling identity and lifecycle.
|
||||
if entry.Toolset != "mcp" && taskToolAllowed(entry, allowed) {
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
}
|
||||
providers, err := s.providers(ctx, t, cfg, credential)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if providers != nil {
|
||||
for _, entry := range providers.Registry.All() {
|
||||
if taskToolAllowed(entry, allowed) {
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) providers(ctx context.Context, t *task.Task, cfg config.Config, credential string) (*taskmcp.Set, error) {
|
||||
if len(cfg.Tools.MCPServers) == 0 {
|
||||
s.close(ctx, credential)
|
||||
return nil, nil
|
||||
}
|
||||
models, err := s.authority.TaskModels(ctx, t.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("task sampling model: %w", err)
|
||||
}
|
||||
own := cfg.Providers
|
||||
cfg.Providers = maps.Clone(s.gateway.cfgHolder.Get().Providers)
|
||||
cfg = cfg.WithOrgModels(models)
|
||||
keys := map[string]string{}
|
||||
for name := range models.Providers {
|
||||
provider, ok := own[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("task provider settings unavailable")
|
||||
}
|
||||
if provider.APIKey != (config.SecretRef{}) {
|
||||
value, err := s.gateway.secrets.Resolve(provider.APIKey)
|
||||
if err != nil || value == "" {
|
||||
return nil, fmt.Errorf("task provider credential unavailable")
|
||||
}
|
||||
keys[name] = value
|
||||
}
|
||||
}
|
||||
encoded, err := json.Marshal(struct {
|
||||
Servers []config.MCPServer
|
||||
Models map[string]string
|
||||
Providers map[string]config.Provider
|
||||
Keys map[string]string
|
||||
Limits map[string]config.ModelLimits
|
||||
}{cfg.Tools.MCPServers, cfg.Models, cfg.Providers, keys, cfg.ModelLimits})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.loadProviders(ctx, t, cfg, credential, keys, sha256.Sum256(encoded))
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) loadProviders(ctx context.Context, t *task.Task, cfg config.Config, credential string, keys map[string]string, hash [32]byte) (*taskmcp.Set, error) {
|
||||
key := sha256.Sum256([]byte(credential))
|
||||
s.mu.Lock()
|
||||
current := s.sessions[key]
|
||||
if current == nil || current.lifetime.Err() != nil {
|
||||
lifetime, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
current = &taskToolSession{lifetime: lifetime, cancel: cancel}
|
||||
s.sessions[key] = current
|
||||
}
|
||||
s.mu.Unlock()
|
||||
current.mu.Lock()
|
||||
defer current.mu.Unlock()
|
||||
if err := current.lifetime.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if current.providers != nil {
|
||||
if current.configHash == hash {
|
||||
return current.providers, nil
|
||||
}
|
||||
current.providers.Close(context.WithoutCancel(ctx), s.gateway.log)
|
||||
current.providers = nil
|
||||
}
|
||||
// Cancel an unfinished startup with its RPC; a ready provider stays run-scoped.
|
||||
stop := context.AfterFunc(ctx, current.cancel)
|
||||
defer stop()
|
||||
llm := modelloop.NewRuntimeWithKeys(agentexec.ProvidersFromConfig(cfg.Providers), cfg.ModelLimits, keys)
|
||||
cacheDir := ""
|
||||
if cfg.WorkDir != "" {
|
||||
cacheDir = filepath.Join(cfg.WorkDir, "mcp-npm-cache")
|
||||
}
|
||||
providers, err := taskmcp.Start(current.lifetime, cfg.Tools.MCPServers, s.taskSampling(llm, cfg, t, credential), s.gateway.log, cacheDir) //nolint:contextcheck // The run owns provider process lifetime.
|
||||
if err != nil || ctx.Err() != nil {
|
||||
current.cancel()
|
||||
if providers != nil {
|
||||
providers.Close(context.WithoutCancel(ctx), s.gateway.log)
|
||||
}
|
||||
return nil, errors.Join(err, ctx.Err())
|
||||
}
|
||||
current.providers, current.configHash = providers, hash
|
||||
return providers, nil
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) ListTaskTools(ctx context.Context, req *pb.ListTaskToolsRequest) (*pb.ListTaskToolsResponse, error) {
|
||||
ctx, t, cfg, allowed, err := s.authorize(ctx, req.RunCredential)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := s.entries(ctx, t, cfg, req.RunCredential, allowed)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unavailable, "task tool providers unavailable")
|
||||
}
|
||||
set, err := modelloop.BuildToolSetFrom(entries, modelloop.ToolSetOptions{})
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unavailable, "task tool discovery failed")
|
||||
}
|
||||
result := []*mcp.Tool{}
|
||||
for _, entry := range entries {
|
||||
tool, ok := set[entry.Name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
result = append(result, &mcp.Tool{Name: tool.Name, Description: tool.Description, InputSchema: tool.Parameters})
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "encode task tools")
|
||||
}
|
||||
return &pb.ListTaskToolsResponse{ToolsJson: data}, nil
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) CallTaskTool(ctx context.Context, req *pb.CallTaskToolRequest) (*pb.CallTaskToolResponse, error) {
|
||||
ctx, t, cfg, allowed, err := s.authorize(ctx, req.RunCredential)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := s.entries(ctx, t, cfg, req.RunCredential, allowed)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unavailable, "task tool providers unavailable")
|
||||
}
|
||||
entry, ok := findTaskTool(entries, req.Name)
|
||||
if !ok {
|
||||
return nil, status.Error(codes.PermissionDenied, "tool is not allowed for this task")
|
||||
}
|
||||
result, err := executeTaskTool(ctx, entry, req.ArgumentsJson, cfg.Tools.Policy.MaxResultChars)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "task tool call failed: "+err.Error())
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "encode task tool result")
|
||||
}
|
||||
return &pb.CallTaskToolResponse{ResultJson: data}, nil
|
||||
}
|
||||
|
||||
func findTaskTool(entries []tools.ToolEntry, name string) (tools.ToolEntry, bool) {
|
||||
for _, entry := range entries {
|
||||
if entry.Name == name {
|
||||
return entry, true
|
||||
}
|
||||
}
|
||||
return tools.ToolEntry{}, false
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) CloseTaskTools(ctx context.Context, req *pb.CloseTaskToolsRequest) (*pb.CloseTaskToolsResponse, error) {
|
||||
if access.SourceFromContext(ctx) != "archied" {
|
||||
return nil, status.Error(codes.PermissionDenied, "task tools require the daemon")
|
||||
}
|
||||
s.close(ctx, req.RunCredential)
|
||||
return &pb.CloseTaskToolsResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) close(parent context.Context, credential string) {
|
||||
key := sha256.Sum256([]byte(credential))
|
||||
s.mu.Lock()
|
||||
current := s.sessions[key]
|
||||
delete(s.sessions, key)
|
||||
s.mu.Unlock()
|
||||
if current == nil {
|
||||
return
|
||||
}
|
||||
current.cancel()
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 10*time.Second)
|
||||
defer cancel()
|
||||
current.mu.Lock()
|
||||
defer current.mu.Unlock()
|
||||
if current.providers != nil {
|
||||
current.providers.Close(ctx, s.gateway.log)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) Close(parent context.Context) {
|
||||
s.mu.Lock()
|
||||
sessions := s.sessions
|
||||
s.sessions = make(map[[32]byte]*taskToolSession)
|
||||
s.mu.Unlock()
|
||||
for _, session := range sessions {
|
||||
session.cancel()
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 10*time.Second)
|
||||
session.mu.Lock()
|
||||
if session.providers != nil {
|
||||
session.providers.Close(ctx, s.gateway.log)
|
||||
}
|
||||
session.mu.Unlock()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func (b *server) taskToolsConfig(ctx context.Context) (config.Config, error) {
|
||||
base := b.cfgHolder.Get()
|
||||
// These documents belong to the task's org; absence must not inherit
|
||||
// the instance's MCP credentials or agent profiles.
|
||||
base.Tools.MCPServers = nil
|
||||
base.Containers.Profiles = nil
|
||||
base.Providers = nil
|
||||
cfg, _, err := b.controlPlane.RuntimeConfig(ctx, base)
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
func (s *taskToolsServer) taskSampling(llm *runtime.Runtime, cfg config.Config, t *task.Task, credential string) protocol.SamplingHandler {
|
||||
sample := taskmcp.SamplingHandler(llm, cfg.ForTask(), taskmcp.UsageRecorder(s.authority, t, s.gateway.log))
|
||||
return func(ctx context.Context, request protocol.SamplingRequest) (protocol.SamplingResult, error) {
|
||||
live, _, err := s.authority.TaskPrincipalForCredential(ctx, credential)
|
||||
if err != nil || live.ID != t.ID || live.Status != task.StatusRunning || live.OrgOrDefault() != t.OrgOrDefault() {
|
||||
return protocol.SamplingResult{}, errors.New("task grant no longer authorizes sampling")
|
||||
}
|
||||
return sample(ctx, request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package archiegateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/tasktools"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
type taskToolGrants struct {
|
||||
taskToolAuthority
|
||||
task task.Task
|
||||
principal access.Principal
|
||||
accepted *storepkg.Authority
|
||||
revoked bool
|
||||
recorded []usage.Record
|
||||
}
|
||||
|
||||
func (a *taskToolGrants) TaskPrincipalForCredential(context.Context, string) (*task.Task, identity.IdentityID, error) {
|
||||
if a.revoked {
|
||||
return nil, "", errors.New("revoked")
|
||||
}
|
||||
return &a.task, a.principal.IdentityID, nil
|
||||
}
|
||||
|
||||
func (a *taskToolGrants) PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error) {
|
||||
return a.principal, nil
|
||||
}
|
||||
|
||||
func (a *taskToolGrants) RecordUsage(_ context.Context, value usage.Record) error {
|
||||
a.recorded = append(a.recorded, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *taskToolGrants) GetInstalled(context.Context, string) (storepkg.Installed, error) {
|
||||
return storepkg.Installed{AcceptedAuthority: a.accepted}, nil
|
||||
}
|
||||
|
||||
func TestTaskToolAuthorization(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, caller, token, tool string
|
||||
profile []string
|
||||
packaged, revoked bool
|
||||
accepted *storepkg.Authority
|
||||
principalOrg org.OrgID
|
||||
status string
|
||||
want codes.Code
|
||||
}{
|
||||
{name: "allowed", tool: "fetch", want: codes.OK},
|
||||
{name: "profile denial", tool: "fetch", profile: []string{"other"}, want: codes.PermissionDenied},
|
||||
{name: "unaccepted package", tool: "fetch", packaged: true, want: codes.PermissionDenied},
|
||||
{name: "accepted package", tool: "fetch", packaged: true, accepted: &storepkg.Authority{Tools: []string{"fetch"}}},
|
||||
{name: "package intersection", tool: "fetch", packaged: true, accepted: &storepkg.Authority{Tools: []string{"fetch"}}, profile: []string{"other"}, want: codes.PermissionDenied},
|
||||
{name: "workspace never served", tool: "shell", want: codes.PermissionDenied},
|
||||
{name: "chat files never served", tool: "send_file", want: codes.PermissionDenied},
|
||||
{name: "approval unavailable", tool: "danger", want: codes.PermissionDenied},
|
||||
{name: "revoked", tool: "fetch", revoked: true, want: codes.Unauthenticated},
|
||||
{name: "not running", tool: "fetch", status: "completed", want: codes.PermissionDenied},
|
||||
{name: "other org principal", tool: "fetch", principalOrg: "victim", want: codes.PermissionDenied},
|
||||
{name: "non daemon", caller: "archie-ui", tool: "fetch", want: codes.PermissionDenied},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authority := &taskToolGrants{task: task.Task{ID: 7, Org: "acme", Status: "running", WorkflowDefinitionYAML: "id: work\nprofile: kit\nidentity: bot\n"}, principal: access.Principal{IdentityID: "bot", Org: "acme"}, accepted: tt.accepted, revoked: tt.revoked}
|
||||
if tt.packaged {
|
||||
authority.task.WorkflowDefinitionYAML += "package: sample\n"
|
||||
}
|
||||
if tt.status != "" {
|
||||
authority.task.Status = tt.status
|
||||
}
|
||||
if tt.principalOrg != "" {
|
||||
authority.principal.Org = tt.principalOrg
|
||||
}
|
||||
called := 0
|
||||
reg := tools.NewRegistry()
|
||||
for _, entry := range []tools.ToolEntry{
|
||||
{Name: "fetch", Toolset: "web"}, {Name: "shell", Toolset: "workspace"}, {Name: "send_file", Toolset: "media"}, {Name: "danger", Classification: tools.RequiresApproval},
|
||||
} {
|
||||
entry.Schema = tools.JSONSchema{"type": "object"}
|
||||
entry.Handler = func(ctx context.Context, _ map[string]any) (any, error) {
|
||||
called++
|
||||
p, _ := access.PrincipalFromContext(ctx)
|
||||
if p.IdentityID != "bot" || org.OrgFromContext(ctx) != "acme" {
|
||||
t.Fatal("tool executed with caller-selected authority")
|
||||
}
|
||||
return "result", nil
|
||||
}
|
||||
if err := reg.Register(entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cfg := config.Config{Containers: config.ContainerConfig{Profiles: map[string]config.AgentProfile{"kit": {Kit: "image@sha256:pinned", Tools: tt.profile}}}}
|
||||
s := &taskToolsServer{gateway: &server{cfgHolder: config.NewHolder(cfg), toolReg: reg, log: slog.New(slog.DiscardHandler)}, authority: authority, configFor: func(context.Context) (config.Config, error) { return cfg, nil }, sessions: make(map[[32]byte]*taskToolSession)}
|
||||
caller := tt.caller
|
||||
if caller == "" {
|
||||
caller = "archied"
|
||||
}
|
||||
ctx := access.WithSource(t.Context(), caller)
|
||||
result, err := s.ListTaskTools(ctx, &pb.ListTaskToolsRequest{RunCredential: "grant"})
|
||||
if err == nil {
|
||||
var listed []*mcp.Tool
|
||||
if err := json.Unmarshal(result.ToolsJson, &listed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tool := range listed {
|
||||
if slices.Contains([]string{"shell", "send_file", "danger"}, tool.Name) {
|
||||
t.Fatalf("unsafe tool listed: %s", tool.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
_, err = s.CallTaskTool(ctx, &pb.CallTaskToolRequest{RunCredential: "grant", Name: tt.tool, ArgumentsJson: []byte(`{}`)})
|
||||
if status.Code(err) != tt.want {
|
||||
t.Fatalf("error %v, want %v", err, tt.want)
|
||||
}
|
||||
if tt.want == codes.OK && called != 1 {
|
||||
t.Fatalf("calls %d, want 1", called)
|
||||
}
|
||||
if tt.want != codes.OK && called != 0 {
|
||||
t.Fatal("denied request executed")
|
||||
}
|
||||
// Authorization must be checked again after a successful discovery.
|
||||
authority.revoked = true
|
||||
if _, err := s.CallTaskTool(ctx, &pb.CallTaskToolRequest{RunCredential: "grant", Name: "fetch", ArgumentsJson: []byte(`{}`)}); err == nil {
|
||||
t.Fatal("revoked grant remained usable")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskToolGatewayThroughProxy(t *testing.T) {
|
||||
authority := &taskToolGrants{task: task.Task{ID: 7, Org: "acme", Status: "running", WorkflowDefinitionYAML: "id: work\nprofile: kit\nidentity: bot\n"}, principal: access.Principal{IdentityID: "bot", Org: "acme"}}
|
||||
reg := tools.NewRegistry()
|
||||
calls := 0
|
||||
blocked := make(chan struct{})
|
||||
if err := reg.Register(tools.ToolEntry{Name: "echo", Toolset: "web", Schema: tools.JSONSchema{"type": "object", "properties": map[string]any{"value": map[string]any{"type": "string"}}, "required": []string{"value"}}, Handler: func(ctx context.Context, args map[string]any) (any, error) {
|
||||
calls++
|
||||
if org.OrgFromContext(ctx) != "acme" {
|
||||
t.Error("lost task org")
|
||||
}
|
||||
if args["value"] == "block" {
|
||||
close(blocked)
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return args["value"], nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := config.Config{Containers: config.ContainerConfig{Profiles: map[string]config.AgentProfile{"kit": {Kit: "pinned", Tools: []string{"echo"}}}}}
|
||||
service := &taskToolsServer{gateway: &server{cfgHolder: config.NewHolder(cfg), toolReg: reg, log: slog.New(slog.DiscardHandler)}, authority: authority, configFor: func(context.Context) (config.Config, error) { return cfg, nil }, sessions: make(map[[32]byte]*taskToolSession)}
|
||||
defer service.Close(t.Context())
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
rpc := grpc.NewServer(grpc.ChainUnaryInterceptor((rpcidentity.Callers{}).Unary()))
|
||||
pb.RegisterTaskToolsServiceServer(rpc, service)
|
||||
go func() { _ = rpc.Serve(listener) }()
|
||||
defer rpc.Stop()
|
||||
conn, err := grpc.NewClient("passthrough:///gateway", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return listener.Dial() }), grpc.WithUnaryInterceptor(staterpc.UnaryClientCredentialInterceptor("archied", "")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
proxy := egress.NewProxy(nil, egress.ProxyOptions{TaskTools: tasktools.NewClient(conn)})
|
||||
session, err := proxy.Register(egress.SessionOptions{Token: "proxy-password", RunCredential: "grant", Org: "acme"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer proxy.Revoke(t.Context(), session.Token())
|
||||
session.EnterRuntime()
|
||||
httpServer := httptest.NewServer(proxy)
|
||||
defer httpServer.Close()
|
||||
proxyURL, err := url.Parse(httpServer.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxyURL.User = url.UserPassword("archie", session.Token())
|
||||
transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "test-harness", Version: "1"}, nil)
|
||||
clientSession, err := client.Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: tasktools.Endpoint, HTTPClient: &http.Client{Transport: taskSentinelTransport{base: transport}}, DisableStandaloneSSE: true, MaxRetries: -1}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer clientSession.Close()
|
||||
listed, err := clientSession.ListTools(t.Context(), nil)
|
||||
if err != nil || len(listed.Tools) != 1 || listed.Tools[0].Name != "echo" {
|
||||
t.Fatalf("discovery %v %v", listed, err)
|
||||
}
|
||||
result, err := clientSession.CallTool(t.Context(), &mcp.CallToolParams{Name: "echo", Arguments: map[string]any{"value": "hello"}})
|
||||
if err != nil || result.IsError || calls != 1 {
|
||||
t.Fatalf("call %v %v calls %d", result, err, calls)
|
||||
}
|
||||
if _, err := clientSession.CallTool(t.Context(), &mcp.CallToolParams{Name: "forbidden", Arguments: map[string]any{}}); err == nil {
|
||||
t.Fatal("unknown tool accepted")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatal("unknown tool executed")
|
||||
}
|
||||
samples := 0
|
||||
model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
samples++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"sample","object":"chat.completion","model":"task","choices":[{"index":0,"message":{"role":"assistant","content":"sampled"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`))
|
||||
}))
|
||||
defer model.Close()
|
||||
llm := modelloop.NewRuntime(map[string]agentrun.Provider{"fixture": {Class: "openai", BaseURL: model.URL + "/v1"}}, nil)
|
||||
sample := service.taskSampling(llm, config.Config{Models: map[string]string{"default": "fixture/task"}}, &authority.task, "grant")
|
||||
if _, err := sample(t.Context(), protocol.SamplingRequest{MaxTokens: 5, Messages: []protocol.SamplingMessage{{Role: "user", Content: protocol.SamplingContent{Type: "text", Text: "sample"}}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if samples != 1 || len(authority.recorded) != 1 || authority.recorded[0].TaskID != 7 || authority.recorded[0].Source != usage.SourceTask {
|
||||
t.Fatal("sampling lost task attribution")
|
||||
}
|
||||
authority.revoked = true
|
||||
result, err = clientSession.CallTool(t.Context(), &mcp.CallToolParams{Name: "echo", Arguments: map[string]any{"value": "again"}})
|
||||
if err == nil && !result.IsError {
|
||||
t.Fatal("revoked grant executed")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatal("revoked tool executed")
|
||||
}
|
||||
if _, err := sample(t.Context(), protocol.SamplingRequest{}); err == nil || samples != 1 {
|
||||
t.Fatal("revoked grant sampled a model")
|
||||
}
|
||||
authority.revoked = false
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
finished := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := clientSession.CallTool(ctx, &mcp.CallToolParams{Name: "echo", Arguments: map[string]any{"value": "block"}})
|
||||
finished <- err
|
||||
}()
|
||||
select {
|
||||
case <-blocked:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("tool call did not start")
|
||||
}
|
||||
proxy.Revoke(ctx, session.Token())
|
||||
select {
|
||||
case <-finished:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("proxy revocation did not cancel the active call")
|
||||
}
|
||||
}
|
||||
|
||||
type taskSentinelTransport struct{ base http.RoundTripper }
|
||||
|
||||
func (t taskSentinelTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
r = r.Clone(r.Context())
|
||||
r.Header.Set("Authorization", "Bearer "+tasktools.Sentinel)
|
||||
return t.base.RoundTrip(r)
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package archiegateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -12,12 +11,12 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
minimaxtool "github.com/samcharles93/archie-core/internal/tools/minimax"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
builtintoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/builtin"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
"github.com/samcharles93/archie-core/internal/tools/sendfile"
|
||||
"github.com/samcharles93/archie-core/internal/tools/webfetch"
|
||||
)
|
||||
@@ -168,80 +167,12 @@ func isWithin(base, target string) bool {
|
||||
}
|
||||
|
||||
func configuredMCPProvider(server config.MCPServer, workDir string, sampling mcp.SamplingHandler) (toolprovider.Engine, error) {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("MCP server name is required")
|
||||
cacheDir := ""
|
||||
if workDir != "" {
|
||||
cacheDir = filepath.Join(workDir, "mcp-npm-cache")
|
||||
}
|
||||
transportType := strings.ToLower(strings.TrimSpace(server.Transport))
|
||||
if transportType == "" {
|
||||
transportType = "stdio"
|
||||
}
|
||||
|
||||
samplingOption := mcptoolprovider.WithSamplingHandler(sampling)
|
||||
|
||||
switch transportType {
|
||||
case "stdio":
|
||||
command := strings.TrimSpace(server.Command)
|
||||
if command == "" {
|
||||
return nil, fmt.Errorf("MCP stdio server %q requires a command", name)
|
||||
}
|
||||
transport := mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), server.Args...),
|
||||
Dir: server.WorkDir,
|
||||
Env: npmCacheServerEnv(command, workDir),
|
||||
})
|
||||
return mcptoolprovider.New(name, transport, server.ParallelToolCalls, samplingOption), nil
|
||||
|
||||
case "http", "streamablehttp":
|
||||
url := strings.TrimSpace(server.URL)
|
||||
if url == "" {
|
||||
return nil, fmt.Errorf("MCP http server %q requires a url", name)
|
||||
}
|
||||
transport := mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
|
||||
Endpoint: url,
|
||||
Headers: server.Headers,
|
||||
})
|
||||
return mcptoolprovider.New(name, transport, server.ParallelToolCalls, samplingOption), nil
|
||||
|
||||
case "sse":
|
||||
sseEndpoint := strings.TrimSpace(server.SSEEndpoint)
|
||||
if sseEndpoint == "" {
|
||||
return nil, fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
|
||||
}
|
||||
transport := mcp.NewSSETransport(mcp.SSETransportConfig{
|
||||
SSEEndpoint: sseEndpoint,
|
||||
MessageEndpoint: strings.TrimSpace(server.MessageEndpoint),
|
||||
Headers: server.Headers,
|
||||
})
|
||||
return mcptoolprovider.New(name, transport, server.ParallelToolCalls, samplingOption), nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("MCP transport %q is not supported", transportType)
|
||||
}
|
||||
}
|
||||
|
||||
// npmCacheServerEnv returns environment variables that make an
|
||||
// npx-launched MCP server reuse a persistent package cache across Gateway
|
||||
// restarts, instead of npm re-resolving and re-downloading the package
|
||||
// from the registry every time the Gateway starts. Rooted under the
|
||||
// work dir so it persists regardless of whether the Gateway
|
||||
// itself runs in an ephemeral container. See mcp.NpmCacheEnv for the
|
||||
// command-matching and env var details shared with archie-agent's
|
||||
// per-task equivalent (internal/app/agentworker/mcp_providers.go), which
|
||||
// points at a mounted cache volume instead of a work-dir subdirectory.
|
||||
//
|
||||
// workDir is unconditionally defaulted before registerTools runs
|
||||
// (internal/infrastructure/configuration's applyGeneralDefaults), but
|
||||
// filepath.Join silently accepts an empty string and would then put the
|
||||
// cache in the process's current working directory instead of its
|
||||
// persistent data directory -- guard it explicitly rather than trust that
|
||||
// invariant here too.
|
||||
func npmCacheServerEnv(command, workDir string) []string {
|
||||
if workDir == "" {
|
||||
return nil
|
||||
}
|
||||
return mcp.NpmCacheEnv(command, filepath.Join(workDir, "mcp-npm-cache"))
|
||||
provider, _, err := taskmcp.NewProvider(server, sampling, cacheDir)
|
||||
return provider, err
|
||||
}
|
||||
|
||||
func shutdownCapabilityHost(ctx context.Context, capabilityHost *plugin.Host, log *slog.Logger) func() {
|
||||
|
||||
Reference in new issue
Block a user