Files
archie/internal/agentexec/harness_mcp.go
T

128 lines
4.4 KiB
Go

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"]
}