feat(kit): central tools for harnesses through the egress proxy and gateway task-tool RPCs

This commit is contained in:
sam committed 2026-10-17 23:42:37 +11:00
1 parent f975dccec0
commit 3f553bb6f2
41 files changed
+2187 -189

No files matched your search

+26 -3
View File
@@ -46,6 +46,17 @@ func AcceptCapture(spec agentrun.CaptureTool, accepted int, value json.RawMessag
// its rejection, so the agent can correct it, and is not recorded.
func ServeCaptureMCP(ctx context.Context, specs []agentrun.CaptureTool, sink io.Writer, t mcp.Transport) error {
server := mcp.NewServer(&mcp.Implementation{Name: "archie", Version: "1"}, nil)
return serveHarnessMCP(ctx, specs, sink, t, server, false)
}
func serveHarnessMCP(ctx context.Context, specs []agentrun.CaptureTool, sink io.Writer, t mcp.Transport, server *mcp.Server, central bool) error {
if central {
cleanup, err := addCentralTools(ctx, server, specs)
if err != nil {
return err
}
defer cleanup()
}
var mu sync.Mutex
accepted := map[string]int{}
for _, spec := range specs {
@@ -121,8 +132,8 @@ func ServeCaptureFiles(ctx context.Context, specPath, capturesPath string, t mcp
if err != nil {
return err
}
var specs []agentrun.CaptureTool
if err := json.Unmarshal(raw, &specs); err != nil {
var spec harnessMCPSpec
if err := json.Unmarshal(raw, &spec); err != nil {
return fmt.Errorf("capture tool spec: %w", err)
}
sink, err := os.OpenFile(capturesPath, os.O_WRONLY|os.O_APPEND, 0)
@@ -130,5 +141,17 @@ func ServeCaptureFiles(ctx context.Context, specPath, capturesPath string, t mcp
return err
}
defer sink.Close()
return ServeCaptureMCP(ctx, specs, sink, t)
server := mcp.NewServer(&mcp.Implementation{Name: "archie", Version: "1"}, nil)
server.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
result, err := next(ctx, method, req)
if err == nil && (method == "tools/list" || method == "tools/call") {
if err := os.WriteFile(capturesPath+".ready", nil, 0o600); err != nil {
return nil, fmt.Errorf("record MCP initialization: %w", err)
}
}
return result, err
}
})
return serveHarnessMCP(ctx, spec.Captures, sink, t, server, spec.CentralTools)
}
+3 -6
View File
@@ -29,12 +29,9 @@ var harnessAdapters = map[string]HarnessAdapter{
NewOutput: func() HarnessOutput { return newClaudeCodeHarnessOutput() },
MCPConfig: []string{"--mcp-config", mcpConfigPlaceholder},
},
// Codex takes MCP servers only as inline -c overrides, and Pi and OMP
// read no MCP config file of this shape, so their stages serve no
// capture tools.
AdapterCodex: {NewOutput: func() HarnessOutput { return &codexHarnessOutput{} }},
AdapterPi: {NewOutput: func() HarnessOutput { return &piHarnessOutput{} }},
AdapterOMP: {NewOutput: func() HarnessOutput { return &piHarnessOutput{} }},
AdapterCodex: {NewOutput: func() HarnessOutput { return &codexHarnessOutput{} }, MCPConfig: []string{"-c", mcpConfigPlaceholder}},
AdapterPi: {NewOutput: func() HarnessOutput { return &piHarnessOutput{} }, MCPConfig: []string{"--extension", mcpConfigPlaceholder}},
AdapterOMP: {NewOutput: func() HarnessOutput { return &piHarnessOutput{} }, MCPConfig: []string{"--extension", mcpConfigPlaceholder}},
AdapterCopilot: {
NewOutput: func() HarnessOutput { return newCopilotHarnessOutput() },
MCPConfig: []string{"--additional-mcp-config", "@" + mcpConfigPlaceholder},
+127
View File
@@ -0,0 +1,127 @@
package agentexec
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/infrastructure/tasktools"
)
type harnessMCPSpec struct {
Captures []agentrun.CaptureTool `json:"captures"`
CentralTools bool `json:"central_tools"`
}
// Each adapter registers one stdio bridge; it holds only proxy credentials
// and sentinels, and never writes invocation configuration into the worktree.
func harnessMCPRegistration(adapter, dir, configPath string, server map[string]any) (string, error) {
switch adapter {
case AdapterCodex:
args, err := json.Marshal(server["args"])
if err != nil {
return "", err
}
command, ok := server["command"].(string)
if !ok {
return "", fmt.Errorf("MCP command is missing")
}
return "mcp_servers.archie={command=" + strconv.Quote(command) + ",args=" + string(args) + ",env={HTTP_PROXY=" + strconv.Quote(harnessMCPEnvironmentValue(server)) + "},required=true}", nil
case AdapterPi:
server["exposure"] = "direct"
definition, err := json.Marshal(server)
if err != nil {
return "", err
}
path := filepath.Join(dir, "archie-mcp.ts")
script := "export default function(pi) { if (typeof pi.registerMcpServer !== 'function') throw new Error('This Pi version does not support native MCP registration'); pi.registerMcpServer('archie', " + string(definition) + "); }\n"
if err := os.WriteFile(path, []byte(script), 0o644); err != nil {
return "", err
}
return path, nil
case AdapterOMP:
// OMP discovers .mcp.json in an explicitly loaded extension package.
path := filepath.Join(dir, "index.ts")
if err := os.WriteFile(path, []byte("export default function() {}\n"), 0o644); err != nil {
return "", err
}
data, err := os.ReadFile(configPath)
if err != nil {
return "", err
}
if err := os.WriteFile(filepath.Join(dir, ".mcp.json"), data, 0o644); err != nil {
return "", err
}
return dir, nil
default:
return configPath, nil
}
}
type centralTransport struct{ base http.RoundTripper }
func (t centralTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.String() != tasktools.Endpoint {
return nil, fmt.Errorf("central tool request names an unexpected endpoint")
}
r = r.Clone(r.Context())
r.Header.Set("Authorization", "Bearer "+tasktools.Sentinel)
return t.base.RoundTrip(r)
}
func addCentralTools(ctx context.Context, server *mcp.Server, captures []agentrun.CaptureTool) (func(), error) {
proxy, err := url.Parse(os.Getenv("HTTP_PROXY"))
if err != nil || proxy.Host == "" {
return nil, fmt.Errorf("central tools require the task egress proxy")
}
transport := &http.Transport{Proxy: http.ProxyURL(proxy)}
client := mcp.NewClient(&mcp.Implementation{Name: "archie-harness", Version: "1"}, nil)
session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: tasktools.Endpoint, HTTPClient: &http.Client{Transport: centralTransport{base: transport}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, DisableStandaloneSSE: true, MaxRetries: -1, MaxEventSize: -1}, nil)
if err != nil {
transport.CloseIdleConnections()
return nil, fmt.Errorf("connect central tools: %w", err)
}
closeSession := func() { _ = session.Close(); transport.CloseIdleConnections() }
names := map[string]bool{}
for _, spec := range captures {
names[spec.Name] = true
}
for tool, err := range session.Tools(ctx, nil) {
if err != nil {
closeSession()
return nil, fmt.Errorf("list central tools: %w", err)
}
if names[tool.Name] {
closeSession()
return nil, fmt.Errorf("central tool %q collides with a capture tool", tool.Name)
}
server.AddTool(tool, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return session.CallTool(ctx, &mcp.CallToolParams{Name: req.Params.Name, Arguments: req.Params.Arguments})
})
}
return closeSession, nil
}
func harnessMCPEnvironment(env []string) map[string]string {
out := map[string]string{}
for _, entry := range env {
if value, ok := strings.CutPrefix(entry, "HTTP_PROXY="); ok {
out["HTTP_PROXY"] = value
}
}
return out
}
func harnessMCPEnvironmentValue(server map[string]any) string {
env, _ := server["env"].(map[string]string)
return env["HTTP_PROXY"]
}
+46
View File
@@ -0,0 +1,46 @@
//go:build unix
package agentexec
import (
"encoding/json"
"os"
"os/exec"
"testing"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
)
// Some CLIs log an unsupported MCP configuration but still exit successfully.
func TestHarnessRequiresMCPInitialization(t *testing.T) {
for _, central := range []bool{false, true} {
t.Run(map[bool]string{false: "captures", true: "central tools"}[central], func(t *testing.T) {
workspace, err := os.MkdirTemp("", "archie-mcp-regression-") //nolint:usetesting // The harness user cannot traverse testing's private parent directory.
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(workspace)
for _, args := range [][]string{{"init", "-q"}, {"-c", "user.name=fixture", "-c", "user.email=fixture@example.invalid", "commit", "--allow-empty", "-q", "-m", "fixture"}} {
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", workspace}, args...)...)
if raw, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git fixture %v: %s", err, raw)
}
}
h := &agentrun.HarnessSpec{Launch: []string{"sh", "-c", "exit 0", "harness"}, Prompt: []string{"{{.Prompt}}"}, MCPConfig: []string{"{{.MCPConfig}}"}, Env: []string{"PATH=/usr/bin:/bin"}, CentralTools: central}
if os.Geteuid() == 0 {
h.User = "65534"
}
req := agentrun.Request{Version: agentrun.ProtocolVersion, TaskID: 7, Attempt: 1, Stage: "test", Mission: "return a result", Model: "fixture/model", Harness: h}
if !central {
req.CaptureTools = []agentrun.CaptureTool{{Name: "capture_result", Parameters: json.RawMessage(`{"type":"object"}`)}}
}
result, err := NewHarnessRunner(nil).Run(t.Context(), workspace, req, nil)
if err != nil {
t.Fatal(err)
}
if result.Status == agentrun.StatusPassed || result.StopReason != StopExited {
t.Fatalf("unsupported MCP silently passed: %+v", result)
}
})
}
}
+15 -5
View File
@@ -81,6 +81,11 @@ func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.
defer cleanup()
res, err := r.run(ctx, workspace, req, mcpConfig, report)
if capturesPath != "" {
if res.Status == agentrun.StatusPassed {
if _, readyErr := os.Stat(capturesPath + ".ready"); readyErr != nil {
return park(res, StopExited, "harness did not initialize Archie MCP; check CLI MCP support and startup errors"), err
}
}
captures, readErr := readCaptures(capturesPath, req.CaptureTools)
if readErr != nil {
return res, errors.Join(err, fmt.Errorf("read captures: %w", readErr))
@@ -195,8 +200,8 @@ func validateHarness(req agentrun.Request) error {
if len(h.Resume) > 0 && !slices.ContainsFunc(h.Resume, func(s string) bool { return strings.Contains(s, sessionPlaceholder) }) {
return fmt.Errorf("harness resume verb must carry %s", sessionPlaceholder)
}
if len(req.CaptureTools) > 0 && !slices.ContainsFunc(h.MCPConfig, func(s string) bool { return strings.Contains(s, mcpConfigPlaceholder) }) {
return errors.New("stage has capture tools but the harness registers no MCP server; its results would be lost")
if (len(req.CaptureTools) > 0 || h.CentralTools) && !slices.ContainsFunc(h.MCPConfig, func(s string) bool { return strings.Contains(s, mcpConfigPlaceholder) }) {
return errors.New("stage needs Archie tools but the harness registers no MCP server; its results would be lost")
}
return nil
}
@@ -485,7 +490,7 @@ func (t *tailBuffer) String() string { return t.buf.String() }
// writes into it.
func (r *HarnessRunner) prepareCaptures(req agentrun.Request) (config, captures string, cleanup func(), err error) {
cleanup = func() {}
if len(req.CaptureTools) == 0 {
if len(req.CaptureTools) == 0 && !req.Harness.CentralTools {
return "", "", cleanup, nil
}
dir, err := os.MkdirTemp("", "archie-captures-")
@@ -497,7 +502,7 @@ func (r *HarnessRunner) prepareCaptures(req agentrun.Request) (config, captures
cleanup()
return "", "", func() {}, err
}
spec, err := json.Marshal(req.CaptureTools)
spec, err := json.Marshal(harnessMCPSpec{Captures: req.CaptureTools, CentralTools: req.Harness.CentralTools})
if err != nil {
return fail(err)
}
@@ -511,6 +516,7 @@ func (r *HarnessRunner) prepareCaptures(req agentrun.Request) (config, captures
command = []string{self}
}
server := map[string]any{
"env": harnessMCPEnvironment(req.Harness.Env),
"command": command[0],
"args": slices.Concat(command[1:], []string{"mcp", "-spec", specPath, "-captures", capturesPath}),
}
@@ -526,5 +532,9 @@ func (r *HarnessRunner) prepareCaptures(req agentrun.Request) (config, captures
if err := ownForHarness(req.Harness.User, dir, specPath, configPath, capturesPath); err != nil {
return fail(err)
}
return configPath, capturesPath, cleanup, nil
registration, err := harnessMCPRegistration(req.Harness.Adapter, dir, configPath, server)
if err != nil {
return fail(err)
}
return registration, capturesPath, cleanup, nil
}
+9 -1
View File
@@ -14,6 +14,12 @@ import (
// "provider/model"; its Reasoning flag tells the runtime which models need
// max_completion_tokens instead of max_tokens.
func NewRuntime(providers map[string]agentrun.Provider, limits map[string]config.ModelLimits) *runtime.Runtime {
return NewRuntimeWithKeys(providers, limits, nil)
}
// NewRuntimeWithKeys binds host-resolved credentials to one runtime without
// exporting them into the process environment or the task protocol.
func NewRuntimeWithKeys(providers map[string]agentrun.Provider, limits map[string]config.ModelLimits, keys map[string]string) *runtime.Runtime {
if len(providers) == 0 {
return nil
}
@@ -21,7 +27,9 @@ func NewRuntime(providers map[string]agentrun.Provider, limits map[string]config
catalog := make(map[string]runtime.ProviderConfig, len(providers))
for name, provider := range providers {
cfg := runtime.ProviderConfig{ID: name, Class: provider.Class, BaseURL: provider.BaseURL, Models: reasoningModels(name, limits)}
if provider.APIKeyEnv == "" {
if key, ok := keys[name]; ok {
cfg.Auth = runtime.AuthConfig{APIKey: key}
} else if provider.APIKeyEnv == "" {
cfg.Auth = runtime.AuthConfig{Type: runtime.AuthTypeNone}
} else {
cfg.Auth = runtime.AuthConfig{APIKeyEnv: provider.APIKeyEnv}