feat: add MCP client capabilities to archied and archie-agent (archie)
Implements #75
This commit is contained in:
1 parent
a7054250ff
commit
5f964030c5
12 files changed
+337
-31
No files matched your search
+146
-1
@@ -16,6 +16,7 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -23,10 +24,15 @@ import (
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
arnats "github.com/samcharles93/archie-core/internal/nats"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -214,6 +220,127 @@ func natsConnectionSettings(flagURL string, getenv func(string) string) (url, to
|
||||
return url, getenv("NATS_TOKEN")
|
||||
}
|
||||
|
||||
// mcpProviderSet holds the resources needed to clean up MCP providers.
|
||||
type mcpProviderSet struct {
|
||||
providers []toolprovider.Engine
|
||||
registry *tools.Registry
|
||||
}
|
||||
|
||||
// startMCPProviders creates MCP transports from config, starts them,
|
||||
// discovers tools, and registers them into a local registry. Returns
|
||||
// nil when there are no servers configured.
|
||||
func startMCPProviders(ctx context.Context, servers []config.MCPServer, log *slog.Logger) (*mcpProviderSet, error) {
|
||||
if len(servers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
reg := tools.NewRegistry()
|
||||
var providers []toolprovider.Engine
|
||||
var firstErr error
|
||||
|
||||
for _, srv := range servers {
|
||||
name := strings.TrimSpace(srv.Name)
|
||||
if name == "" {
|
||||
log.Warn("mcp server skipped: empty name")
|
||||
continue
|
||||
}
|
||||
transportType := strings.ToLower(strings.TrimSpace(srv.Transport))
|
||||
if transportType == "" {
|
||||
transportType = "stdio"
|
||||
}
|
||||
|
||||
var transport mcptoolprovider.LifecycleTransport
|
||||
switch transportType {
|
||||
case "stdio":
|
||||
command := strings.TrimSpace(srv.Command)
|
||||
if command == "" {
|
||||
err := fmt.Errorf("MCP stdio server %q requires a command", name)
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
transport = mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), srv.Args...),
|
||||
})
|
||||
case "http", "streamablehttp":
|
||||
url := strings.TrimSpace(srv.URL)
|
||||
if url == "" {
|
||||
err := fmt.Errorf("MCP http server %q requires a url", name)
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
transport = mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
|
||||
Endpoint: url,
|
||||
Headers: srv.Headers,
|
||||
})
|
||||
case "sse":
|
||||
sseEndpoint := strings.TrimSpace(srv.SSEEndpoint)
|
||||
if sseEndpoint == "" {
|
||||
err := fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
transport = mcp.NewSSETransport(mcp.SSETransportConfig{
|
||||
SSEEndpoint: sseEndpoint,
|
||||
MessageEndpoint: strings.TrimSpace(srv.MessageEndpoint),
|
||||
Headers: srv.Headers,
|
||||
})
|
||||
default:
|
||||
log.Warn("mcp server skipped: unknown transport", "name", name, "transport", transportType)
|
||||
continue
|
||||
}
|
||||
|
||||
provider := mcptoolprovider.New(name, transport)
|
||||
if err := provider.Start(ctx); err != nil {
|
||||
log.Warn("mcp provider start failed", "name", name, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
entries, err := provider.Discover(ctx)
|
||||
if err != nil {
|
||||
log.Warn("mcp tool discovery failed", "name", name, "err", err)
|
||||
// Stop the provider since we can't use it.
|
||||
_ = provider.Stop(ctx)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if err := reg.Register(entry); err != nil {
|
||||
log.Warn("mcp tool registration failed", "tool", entry.Name, "err", err)
|
||||
}
|
||||
}
|
||||
providers = append(providers, provider)
|
||||
log.Info("mcp provider started", "name", name, "transport", transportType, "tools", len(entries))
|
||||
}
|
||||
|
||||
if len(providers) == 0 {
|
||||
return nil, firstErr
|
||||
}
|
||||
return &mcpProviderSet{providers: providers, registry: reg}, nil
|
||||
}
|
||||
|
||||
func (s *mcpProviderSet) cleanup(ctx context.Context) {
|
||||
for _, p := range s.providers {
|
||||
if err := p.Stop(ctx); err != nil {
|
||||
// Logged by caller if desired.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handle(ctx context.Context, msg jetstream.Msg, nc *nats.Conn, log *slog.Logger) error {
|
||||
var req agentexec.AgentRequestMessage
|
||||
if err := json.Unmarshal(msg.Data(), &req); err != nil {
|
||||
@@ -233,7 +360,25 @@ func handle(ctx context.Context, msg jetstream.Msg, nc *nats.Conn, log *slog.Log
|
||||
"reply_to", replyTo,
|
||||
)
|
||||
|
||||
resp, err := agentexec.HandleMessage(ctx, req, log, agentexec.DefaultRunnerFactory)
|
||||
// Start MCP providers and build a local tool registry.
|
||||
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, log)
|
||||
if mcpSet != nil {
|
||||
defer mcpSet.cleanup(ctx)
|
||||
}
|
||||
if mcpErr != nil {
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr)
|
||||
}
|
||||
|
||||
// Build a runner factory that includes MCP-discovered tools.
|
||||
factory := func(providers map[string]agentexec.Provider, log *slog.Logger) agentexec.Runner {
|
||||
var registries []*tools.Registry
|
||||
if mcpSet != nil {
|
||||
registries = append(registries, mcpSet.registry)
|
||||
}
|
||||
return agentexec.NewInProcessRunner(agentexec.NewRuntime(providers), log, registries...)
|
||||
}
|
||||
|
||||
resp, err := agentexec.HandleMessage(ctx, req, log, factory)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle: %w", err)
|
||||
}
|
||||
|
||||
@@ -91,7 +91,22 @@ func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunne
|
||||
localDir: workDir,
|
||||
}
|
||||
|
||||
agent := newRunner(req.Providers, log)
|
||||
// Start MCP providers and build a local tool registry.
|
||||
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, log)
|
||||
if mcpSet != nil {
|
||||
defer mcpSet.cleanup(ctx)
|
||||
}
|
||||
if mcpErr != nil {
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr)
|
||||
}
|
||||
|
||||
// Build a runner with MCP-discovered tools when available.
|
||||
var agent agentexec.Runner
|
||||
if mcpSet != nil && mcpSet.registry != nil {
|
||||
agent = agentexec.NewInProcessRunner(agentexec.NewRuntime(req.Providers), log, mcpSet.registry)
|
||||
} else {
|
||||
agent = newRunner(req.Providers, log)
|
||||
}
|
||||
if agent == nil {
|
||||
return nil, fmt.Errorf("no agent runner configured for task %d", req.Task.ID)
|
||||
}
|
||||
|
||||
+41
-13
@@ -89,18 +89,45 @@ func configuredMCPProvider(server config.MCPServer) (toolprovider.Engine, error)
|
||||
if transportType == "" {
|
||||
transportType = "stdio"
|
||||
}
|
||||
if transportType != "stdio" {
|
||||
|
||||
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...),
|
||||
})
|
||||
return mcptoolprovider.New(name, transport), 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), 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), nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("MCP transport %q is not supported", transportType)
|
||||
}
|
||||
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...),
|
||||
})
|
||||
return mcptoolprovider.New(name, transport), nil
|
||||
}
|
||||
|
||||
func run() int {
|
||||
@@ -502,9 +529,10 @@ func run() int {
|
||||
return 1
|
||||
}
|
||||
agentRunner = &agentexec.NATSRunner{
|
||||
Nats: natsClient,
|
||||
Providers: providers,
|
||||
Log: log,
|
||||
Nats: natsClient,
|
||||
Providers: providers,
|
||||
MCPServers: cfg.Tools.MCPServers,
|
||||
Log: log,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ func TestGatewaysStartOnlyAfterCapabilityHostAndDaemonStartup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredMCPProviderSupportsOnlyExecutableStdioServers(t *testing.T) {
|
||||
func TestConfiguredMCPProviderSupportsAllTransportTypes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
server config.MCPServer
|
||||
@@ -105,9 +105,14 @@ func TestConfiguredMCPProviderSupportsOnlyExecutableStdioServers(t *testing.T) {
|
||||
wantID: "mcp.local",
|
||||
},
|
||||
{
|
||||
name: "http is not advertised without executable transport",
|
||||
server: config.MCPServer{Name: "remote", Transport: "http", URL: "https://example.invalid"},
|
||||
wantErr: true,
|
||||
name: "http transport creates HTTPTransport",
|
||||
server: config.MCPServer{Name: "remote", Transport: "http", URL: "https://example.invalid"},
|
||||
wantID: "mcp.remote",
|
||||
},
|
||||
{
|
||||
name: "sse transport creates SSETransport",
|
||||
server: config.MCPServer{Name: "sse-server", Transport: "sse", SSEEndpoint: "https://example.invalid/sse"},
|
||||
wantID: "mcp.sse-server",
|
||||
},
|
||||
{
|
||||
name: "unknown transport",
|
||||
@@ -120,10 +125,20 @@ func TestConfiguredMCPProviderSupportsOnlyExecutableStdioServers(t *testing.T) {
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing command",
|
||||
name: "missing command for stdio",
|
||||
server: config.MCPServer{Name: "missing", Transport: "stdio"},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing url for http",
|
||||
server: config.MCPServer{Name: "http-missing", Transport: "http"},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing sse_endpoint for sse",
|
||||
server: config.MCPServer{Name: "sse-missing", Transport: "sse"},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
+18
-11
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
arnats "github.com/samcharles93/archie-core/internal/nats"
|
||||
)
|
||||
|
||||
@@ -24,8 +25,12 @@ type AgentRequestMessage struct {
|
||||
Channel string `json:"channel,omitempty"` // "response" (default) or "system"
|
||||
Workspace string `json:"workspace"`
|
||||
Request Request `json:"request"`
|
||||
Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task
|
||||
Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task
|
||||
Providers map[string]Provider `json:"providers,omitempty"`
|
||||
// MCPServers carries MCP server definitions so the agent can construct
|
||||
// transports, discover tools, and register them locally. Absent/empty
|
||||
// means no MCP servers (backward compatible).
|
||||
MCPServers []config.MCPServer `json:"mcp_servers,omitempty"`
|
||||
}
|
||||
|
||||
// AgentResponseEnvelope is the response payload published to the reply inbox.
|
||||
@@ -42,9 +47,10 @@ const defaultAgentTimeout = 30 * time.Minute
|
||||
// NATSRunner sends agent stage execution requests over NATS JetStream and
|
||||
// waits for replies on core NATS inboxes. It implements Runner.
|
||||
type NATSRunner struct {
|
||||
Nats *arnats.Client
|
||||
Providers map[string]Provider
|
||||
Log *slog.Logger
|
||||
Nats *arnats.Client
|
||||
Providers map[string]Provider
|
||||
MCPServers []config.MCPServer
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// Run publishes a stage execution request to JetStream with an X-Archie-Reply
|
||||
@@ -73,13 +79,14 @@ func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request) (Re
|
||||
|
||||
// 3. Publish request with reply header.
|
||||
msg := AgentRequestMessage{
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Workflow: req.Workflow,
|
||||
Workspace: workspace,
|
||||
Request: req,
|
||||
Providers: r.Providers,
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Workflow: req.Workflow,
|
||||
Workspace: workspace,
|
||||
Request: req,
|
||||
Providers: r.Providers,
|
||||
MCPServers: r.MCPServers,
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
|
||||
@@ -268,6 +268,13 @@ type MCPServer struct {
|
||||
Command string `yaml:"command" json:"command,omitempty"`
|
||||
Args []string `yaml:"args" json:"args,omitempty"`
|
||||
URL string `yaml:"url" json:"url,omitempty"`
|
||||
// Headers are additional HTTP headers sent with every request (auth, etc.).
|
||||
Headers map[string]string `yaml:"headers" json:"headers,omitempty"`
|
||||
// SSEEndpoint is the GET URL for the server→client event stream.
|
||||
SSEEndpoint string `yaml:"sse_endpoint" json:"sse_endpoint,omitempty"`
|
||||
// MessageEndpoint is the POST URL for client→server messages. When
|
||||
// empty, the client discovers it from the server's "endpoint" SSE event.
|
||||
MessageEndpoint string `yaml:"message_endpoint" json:"message_endpoint,omitempty"`
|
||||
}
|
||||
|
||||
// ToolPolicy holds tool execution limits.
|
||||
|
||||
@@ -29,6 +29,10 @@ type Request struct {
|
||||
Repo config.Repo `json:"repo"`
|
||||
Cfg config.TaskConfig `json:"cfg"`
|
||||
Providers map[string]agentexec.Provider `json:"providers"`
|
||||
// MCPServers carries MCP server definitions so the agent can construct
|
||||
// transports, discover tools, and register them locally. Absent/empty
|
||||
// means no MCP servers (backward compatible).
|
||||
MCPServers []config.MCPServer `json:"mcp_servers,omitempty"`
|
||||
}
|
||||
|
||||
// Response reports the task's final state after archie-agent runs its
|
||||
|
||||
@@ -102,5 +102,15 @@ func (t *HTTPTransport) do(ctx context.Context, body []byte) (*http.Response, er
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Start is a no-op: HTTP transport is always ready.
|
||||
func (t *HTTPTransport) Start(_ context.Context) error { return nil }
|
||||
|
||||
// Stop is a no-op: HTTP transport has no persistent resources to release.
|
||||
func (t *HTTPTransport) Stop(_ context.Context) error { return nil }
|
||||
|
||||
// State always returns StateRunning: HTTP is stateless, so the transport is
|
||||
// always considered ready.
|
||||
func (t *HTTPTransport) State() TransportState { return StateRunning }
|
||||
|
||||
// Compile-time interface check.
|
||||
var _ Transport = (*HTTPTransport)(nil)
|
||||
@@ -131,3 +131,30 @@ func TestHTTPTransportConfigDefaults(t *testing.T) {
|
||||
t.Errorf("default timeout = %v, want 30s", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportStateAlwaysRunning(t *testing.T) {
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: "http://localhost"})
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State() = %v, want StateRunning", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransportStartStopAreNoops(t *testing.T) {
|
||||
tr := NewHTTPTransport(HTTPTransportConfig{Endpoint: "http://localhost"})
|
||||
ctx := context.Background()
|
||||
// Start and Stop must not error.
|
||||
if err := tr.Start(ctx); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
// State remains Running after Start.
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State after Start = %v, want StateRunning", state)
|
||||
}
|
||||
if err := tr.Stop(ctx); err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
// State remains Running after Stop (stateless transport).
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State after Stop = %v, want StateRunning", state)
|
||||
}
|
||||
}
|
||||
@@ -485,5 +485,12 @@ func readSSEEvent(r *bufio.Reader) (event, data string, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current transport state.
|
||||
func (t *SSETransport) State() TransportState {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.state
|
||||
}
|
||||
|
||||
// Compile-time interface check.
|
||||
var _ Transport = (*SSETransport)(nil)
|
||||
@@ -184,6 +184,39 @@ func TestSSETransportConfigDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportStateReflectsRunning(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
tr := NewSSETransport(SSETransportConfig{
|
||||
SSEEndpoint: fake.URL + "/sse",
|
||||
MessageEndpoint: fake.URL + "/messages",
|
||||
})
|
||||
|
||||
// Before Start, state should be StateStopped.
|
||||
if state := tr.State(); state != StateStopped {
|
||||
t.Errorf("State before Start = %v, want StateStopped", state)
|
||||
}
|
||||
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
|
||||
// After Start, state should be StateRunning.
|
||||
if state := tr.State(); state != StateRunning {
|
||||
t.Errorf("State after Start = %v, want StateRunning", state)
|
||||
}
|
||||
|
||||
if err := tr.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop: %v", err)
|
||||
}
|
||||
|
||||
// After Stop, state should be StateStopped.
|
||||
if state := tr.State(); state != StateStopped {
|
||||
t.Errorf("State after Stop = %v, want StateStopped", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSETransportConcurrentSendsGetCorrectResponses(t *testing.T) {
|
||||
fake := newSSETestServer(t)
|
||||
defer fake.Close()
|
||||
|
||||
@@ -202,6 +202,14 @@ func TestProviderSatisfiesEngine(t *testing.T) {
|
||||
var _ toolprovider.Engine = New("compile", newFakeTransport())
|
||||
}
|
||||
|
||||
// Compile-time checks: HTTP and SSE transports satisfy LifecycleTransport.
|
||||
func TestTransportsSatisfyLifecycleTransport(t *testing.T) {
|
||||
var _ LifecycleTransport = (*protocol.HTTPTransport)(nil)
|
||||
var _ LifecycleTransport = (*protocol.SSETransport)(nil)
|
||||
// Also check StdioTransport, which already satisfied it.
|
||||
var _ LifecycleTransport = (*protocol.StdioTransport)(nil)
|
||||
}
|
||||
|
||||
func TestSanitizeSegmentsAreDeterministicASCII(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
Reference in new issue
Block a user