diff --git a/internal/platform/pg/migrations/00005_mcp_servers.sql b/internal/platform/pg/migrations/00005_mcp_servers.sql new file mode 100644 index 000000000..e9081737e --- /dev/null +++ b/internal/platform/pg/migrations/00005_mcp_servers.sql @@ -0,0 +1,29 @@ +-- +goose Up +-- An accepted MCP server runs as published: a stdio binary with its arguments, +-- or an HTTP endpoint. Tools are what its acceptance declares it may offer. +ALTER TABLE connectors.accepted + ADD COLUMN args jsonb NOT NULL DEFAULT '[]', + ADD COLUMN url text NOT NULL DEFAULT '', + ADD COLUMN tools jsonb NOT NULL DEFAULT '[]'; + +ALTER TABLE connectors.accepted DROP CONSTRAINT accepted_contract_check; +ALTER TABLE connectors.accepted + ADD CONSTRAINT accepted_contract_check + CHECK (contract IN ('connector', 'secretengine', 'mcp')); + +-- An MCP server's credential slot is an HTTP auth scheme: basic or bearer. +ALTER TABLE connectors.credentials DROP CONSTRAINT credentials_kind_check; +ALTER TABLE connectors.credentials + ADD CONSTRAINT credentials_kind_check + CHECK (kind IN ('machine', 'age', 'basic', 'bearer')); + +-- +goose Down +ALTER TABLE connectors.credentials DROP CONSTRAINT credentials_kind_check; +ALTER TABLE connectors.credentials + ADD CONSTRAINT credentials_kind_check CHECK (kind IN ('machine', 'age')); + +ALTER TABLE connectors.accepted DROP CONSTRAINT accepted_contract_check; +ALTER TABLE connectors.accepted + ADD CONSTRAINT accepted_contract_check CHECK (contract IN ('connector', 'secretengine')); + +ALTER TABLE connectors.accepted DROP COLUMN tools, DROP COLUMN url, DROP COLUMN args; diff --git a/internal/platform/prompts/investigate.md b/internal/platform/prompts/investigate.md index 3fd3bd80b..be54a05e4 100644 --- a/internal/platform/prompts/investigate.md +++ b/internal/platform/prompts/investigate.md @@ -13,6 +13,13 @@ The event is a claim, not a fact. Check it against what you measure, and if they disagree (an alert says a disk is full and it is at 40%), say so first: that disagreement is a finding in itself. +A trend is a query, not an estimate. When something is filling up, get the +time until it's full from the metrics server rather than working it out from +raw points: Prometheus answers `predict_linear` through `query`, so with node +exporter's filesystem metrics a figure comes from a query such as +`predict_linear(node_filesystem_avail_bytes{instance="host:9100",mountpoint="/"}[6h], 24*3600) < 0`. +Report that figure and the query it came from. + When you're done, reply with your findings in plain text: - What happened, in one or two sentences. diff --git a/modules/connectors/connector.go b/modules/connectors/connector.go index c48208141..b2aae47f6 100644 --- a/modules/connectors/connector.go +++ b/modules/connectors/connector.go @@ -111,6 +111,17 @@ const ( KindAction = "action" ) +// Tool runs one declaration by name: a connector's lookup or action, or a tool +// an accepted MCP server declares. Output is the text the agent is given, +// verbatim. +type Tool interface { + // Lookup answers a read-only question. found is false when there was + // nothing to find, which callers report as a finding. + Lookup(ctx context.Context, name string, input jsontext.Value) (output string, found bool, err error) + // Invoke runs one judged action. + Invoke(ctx context.Context, inv Invocation) (output string, err error) +} + // Connector is a running connector and what it declared. type Connector struct { name string @@ -230,53 +241,48 @@ func (c *Connector) Resolve(ctx context.Context, name string, input jsontext.Val }, nil } -// Invoke runs one judged action and decodes its output into T. The connector -// must report the digest of what it ran; a different digest is refused. -func (c *Connector) Invoke[T any](ctx context.Context, inv Invocation) (T, error) { - var zero T +// Invoke runs one judged action and returns its output verbatim. The +// connector must report the digest of what it ran; a different digest is +// refused. +func (c *Connector) Invoke(ctx context.Context, inv Invocation) (string, error) { a, err := c.action(inv.Action, inv.Input) if err != nil { - return zero, err + return "", err } if !a.effect.ReadOnly && !a.idempotent { - return zero, fmt.Errorf("connector %q: action %q: %w", c.name, inv.Action, ErrNotIdempotent) + return "", fmt.Errorf("connector %q: action %q: %w", c.name, inv.Action, ErrNotIdempotent) } digest := Digest(inv.Action, inv.Input) resp, err := c.client.Invoke(ctx, &pb.InvokeRequest{ Action: inv.Action, Input: inv.Input, IdempotencyKey: inv.IdempotencyKey, Digest: digest, }) if err != nil { - return zero, fmt.Errorf("connector %q: invoke %q: %w", c.name, inv.Action, err) + return "", fmt.Errorf("connector %q: invoke %q: %w", c.name, inv.Action, err) } if resp.GetExecutedDigest() != digest { - return zero, fmt.Errorf("connector %q: action %q: %w", c.name, inv.Action, ErrDigestMismatch) + return "", fmt.Errorf("connector %q: action %q: %w", c.name, inv.Action, ErrDigestMismatch) } if resp.GetOutcomeUnknown() { - return zero, fmt.Errorf("connector %q: action %q: %w", c.name, inv.Action, ErrOutcomeUnknown) + return "", fmt.Errorf("connector %q: action %q: %w", c.name, inv.Action, ErrOutcomeUnknown) } - return decode[T](resp.GetOutput()) + return string(resp.GetOutput()), nil } -// Lookup answers a read-only question and decodes the answer into T. found is -// false when the connector found nothing, which callers report as a finding. -func (c *Connector) Lookup[T any](ctx context.Context, name string, input jsontext.Value) (T, bool, error) { - var zero T +// Lookup answers a read-only question and returns the answer verbatim. found +// is false when the connector found nothing, which callers report as a finding. +func (c *Connector) Lookup(ctx context.Context, name string, input jsontext.Value) (string, bool, error) { l, ok := c.lookups[name] if !ok { - return zero, false, fmt.Errorf("connector %q: lookup %q: %w", c.name, name, ErrUnknownName) + return "", false, fmt.Errorf("connector %q: lookup %q: %w", c.name, name, ErrUnknownName) } if err := validate(l.input, input); err != nil { - return zero, false, fmt.Errorf("connector %q: lookup %q: %w", c.name, name, err) + return "", false, fmt.Errorf("connector %q: lookup %q: %w", c.name, name, err) } resp, err := c.client.Lookup(ctx, &pb.LookupRequest{Lookup: name, Input: input}) if err != nil { - return zero, false, fmt.Errorf("connector %q: lookup %q: %w", c.name, name, err) + return "", false, fmt.Errorf("connector %q: lookup %q: %w", c.name, name, err) } - if !resp.GetFound() { - return zero, false, nil - } - out, err := decode[T](resp.GetOutput()) - return out, err == nil, err + return string(resp.GetOutput()), resp.GetFound(), nil } func (c *Connector) action(name string, input jsontext.Value) (action, error) { @@ -339,14 +345,3 @@ func validate(schema *jsonschema.Resolved, raw jsontext.Value) error { } return nil } - -func decode[T any](raw []byte) (T, error) { - var out T - if len(raw) == 0 { - return out, nil - } - if err := json.Unmarshal(raw, &out); err != nil { - return out, fmt.Errorf("decode connector output: %w", err) - } - return out, nil -} diff --git a/modules/connectors/connector_test.go b/modules/connectors/connector_test.go index 62d2ed7e6..c9da43dbd 100644 --- a/modules/connectors/connector_test.go +++ b/modules/connectors/connector_test.go @@ -75,7 +75,7 @@ func TestInvokeRunsOnlyTheJudgedAction(t *testing.T) { if err != nil { t.Fatalf("open: %v", err) } - out, err := c.Invoke[map[string]int](t.Context(), Invocation{Action: "delete", Input: tt.input, IdempotencyKey: "run:1"}) + out, err := c.Invoke(t.Context(), Invocation{Action: "delete", Input: tt.input, IdempotencyKey: "run:1"}) wantOK := tt.wantErr == nil && !tt.wantAnyErr switch { case wantOK && err != nil: @@ -85,8 +85,8 @@ func TestInvokeRunsOnlyTheJudgedAction(t *testing.T) { case tt.wantErr != nil && !errors.Is(err, tt.wantErr): t.Fatalf("Invoke error = %v, want %v", err, tt.wantErr) } - if wantOK && out["deleted"] != 3 { - t.Fatalf("output = %v, want deleted:3", out) + if wantOK && out != `{"deleted":3}` { + t.Fatalf("output = %q, want the connector's own %q", out, `{"deleted":3}`) } if tt.client.invoked != tt.wantInvoked { t.Fatalf("connector invoked %d times, want %d", tt.client.invoked, tt.wantInvoked) diff --git a/modules/connectors/connectors.go b/modules/connectors/connectors.go index d9e5ae7a5..824699942 100644 --- a/modules/connectors/connectors.go +++ b/modules/connectors/connectors.go @@ -41,11 +41,12 @@ type Spec struct { // Host owns the running connectors. type Host struct { procs *host.Host + log *slog.Logger } // NewHost returns a host that logs plugin lifecycle to log. func NewHost(log *slog.Logger) *Host { - return &Host{procs: host.NewHost(log)} + return &Host{procs: host.NewHost(log), log: log} } // Start launches spec, configures it and reads its declaration. A connector diff --git a/modules/connectors/credentials.go b/modules/connectors/credentials.go index c392ba93f..62d4bcc14 100644 --- a/modules/connectors/credentials.go +++ b/modules/connectors/credentials.go @@ -30,6 +30,10 @@ func kindFields(kind string) (required, optional []string, ok bool) { return []string{"username", "private_key"}, []string{"private_key_passphrase"}, true case "age": return []string{"identity"}, nil, true + case "basic": + return []string{"username", "password"}, nil, true + case "bearer": + return []string{"token"}, nil, true } return nil, nil, false } diff --git a/modules/connectors/internal/egress/dialer.go b/modules/connectors/internal/egress/dialer.go new file mode 100644 index 000000000..0709e9dd8 --- /dev/null +++ b/modules/connectors/internal/egress/dialer.go @@ -0,0 +1,28 @@ +package egress + +import ( + "context" + "fmt" + "net" + "strconv" +) + +// Dialer returns a DialContext that reaches only the hosts allow names, for a +// client in this process that dials out itself rather than through the tunnel. +// The same rules hold as for the tunnel: a host named exactly may resolve to a +// private address, a wildcard match may not, and loopback is always refused. +func Dialer(allow []string) func(ctx context.Context, network, addr string) (net.Conn, error) { + r := rules{allow: compilePatterns(allow)} + t := &Tunnel{rules: r} + t.dial = t.dialGuarded + return func(ctx context.Context, network, addr string) (net.Conn, error) { + host, port, err := splitTarget(addr, 443) + if err != nil { + return nil, err + } + if !r.allows(host, port) { + return nil, fmt.Errorf("egress to %s:%d is not allowed", host, port) + } + return t.dialGuarded(ctx, network, net.JoinHostPort(host, strconv.Itoa(port))) + } +} diff --git a/modules/connectors/internal/host/confine_linux.go b/modules/connectors/internal/host/confine_linux.go index ec0bb5696..4c1970938 100644 --- a/modules/connectors/internal/host/confine_linux.go +++ b/modules/connectors/internal/host/confine_linux.go @@ -24,22 +24,27 @@ const proxyAddr = "127.0.0.1:3128" func init() { if len(os.Args) > 2 && os.Args[1] == launcherArg { - os.Exit(launch(os.Args[2])) + os.Exit(launch(os.Args[2], os.Args[3:])) } } // confinedCommand re-execs this binary as the launcher in a fresh user and -// network namespace. The namespace holds only loopback, so the extension -// cannot reach anything except through the launcher's relay to socket. Where -// the kernel refuses the namespaces, the start fails: there is no unconfined -// fallback. -func confinedCommand(ctx context.Context, binary *os.File, socket string) (*exec.Cmd, error) { +// network namespace. The namespace holds only loopback, so the child cannot +// reach anything except through the launcher's relay to socket. Where the +// kernel refuses the namespaces, the start fails: there is no unconfined +// fallback. args reach the child as they were given to it. +// +// The process lives until ctx ends, which is the session's lifetime rather +// than any one call's deadline; Pdeathsig ends it if this process dies. +func confinedCommand(ctx context.Context, binary *os.File, args []string, socket string) (*exec.Cmd, error) { self, err := os.Executable() if err != nil { return nil, err } uid, gid := os.Getuid(), os.Getgid() - cmd := exec.CommandContext(ctx, self, launcherArg, socket) + launchArgs := append([]string{launcherArg, socket}, args...) + //nolint:gosec // the binary is this one, named by path; the arguments are the accepted package's own. + cmd := exec.CommandContext(ctx, self, launchArgs...) cmd.ExtraFiles = []*os.File{binary} cmd.SysProcAttr = &syscall.SysProcAttr{ Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNET, @@ -63,8 +68,8 @@ func openCommand(ctx context.Context, binary *os.File) *exec.Cmd { } // launch runs inside the namespace: loopback up, relay listening, then the -// extension from descriptor 3 with every capability gone. -func launch(socket string) int { +// child from descriptor 3 with every capability gone. +func launch(socket string, args []string) int { ctx := context.Background() if err := loopbackUp(); err != nil { fmt.Fprintln(os.Stderr, "extension egress: loopback:", err) @@ -85,16 +90,16 @@ func launch(socket string) int { return 1 } syscall.CloseOnExec(3) - return runExtension(ctx, fmt.Sprintf("/proc/%d/fd/3", os.Getpid())) + return runExtension(ctx, fmt.Sprintf("/proc/%d/fd/3", os.Getpid()), args) } -// runExtension starts the extension as the launcher's child and mirrors its -// exit. Pdeathsig ties the child to this thread, so killing the launcher -// kills the extension. -func runExtension(ctx context.Context, path string) int { +// runExtension starts the child from path and mirrors its exit. Pdeathsig ties +// the child to this thread, so killing the launcher kills it. +func runExtension(ctx context.Context, path string, args []string) int { runtime.LockOSThread() proxy := "http://" + proxyAddr - cmd := exec.CommandContext(ctx, path) // the host-verified binary, by descriptor + //nolint:gosec // the binary is named by its verified descriptor; the arguments are the accepted package's own. + cmd := exec.CommandContext(ctx, path, args...) // the host-verified binary, by descriptor cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr cmd.Env = append(os.Environ(), "HTTP_PROXY="+proxy, "HTTPS_PROXY="+proxy, "ALL_PROXY="+proxy, diff --git a/modules/connectors/internal/host/confine_other.go b/modules/connectors/internal/host/confine_other.go index 79ee43376..e780cbd49 100644 --- a/modules/connectors/internal/host/confine_other.go +++ b/modules/connectors/internal/host/confine_other.go @@ -11,7 +11,7 @@ import ( // confinedCommand refuses: extensions run only where their egress can be // confined to the hosts the operator accepted. -func confinedCommand(context.Context, *os.File, string) (*exec.Cmd, error) { +func confinedCommand(context.Context, *os.File, []string, string) (*exec.Cmd, error) { return nil, errors.New("extensions need Linux network namespaces to confine their egress") } diff --git a/modules/connectors/internal/host/host.go b/modules/connectors/internal/host/host.go index dba23d347..42dcb9f2d 100644 --- a/modules/connectors/internal/host/host.go +++ b/modules/connectors/internal/host/host.go @@ -46,7 +46,9 @@ type Spec struct { // Host owns the running extension processes, keyed by Spec.Name. type Host struct { - log hclog.Logger + // log is the service's logger; plugin lifecycle goes through hclog. + log *slog.Logger + hclog hclog.Logger mu sync.Mutex procs map[string]*proc @@ -76,7 +78,7 @@ func command(ctx context.Context, binary *os.File, egress []string) (*exec.Cmd, if err != nil { return nil, nil, fmt.Errorf("egress: %w", err) } - cmd, err := confinedCommand(ctx, binary, g.socket) + cmd, err := confinedCommand(ctx, binary, nil, g.socket) if err != nil { g.close() return nil, nil, err @@ -86,7 +88,7 @@ func command(ctx context.Context, binary *os.File, egress []string) (*exec.Cmd, // NewHost returns a Host that reports plugin lifecycle problems to log. func NewHost(log *slog.Logger) *Host { - return &Host{log: newSlogger(log), procs: make(map[string]*proc)} + return &Host{log: log, hclog: newSlogger(log), procs: make(map[string]*proc)} } // Start launches spec serving surface and returns the dispensed client. An @@ -116,7 +118,7 @@ func (h *Host) Start(ctx context.Context, spec Spec, surface string, impl goplug AllowedProtocols: []goplugin.Protocol{goplugin.ProtocolGRPC}, SkipHostEnv: true, AutoMTLS: true, - Logger: h.log.Named(spec.Name), + Logger: h.hclog.Named(spec.Name), })} rpc, err := p.client.Client() if err != nil { diff --git a/modules/connectors/internal/host/stdio.go b/modules/connectors/internal/host/stdio.go new file mode 100644 index 000000000..cb0317f99 --- /dev/null +++ b/modules/connectors/internal/host/stdio.go @@ -0,0 +1,49 @@ +package host + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "os/exec" +) + +// Command returns the command that runs a verified stdio MCP server with args, +// in its own user and network namespace. +// +// An extension is confined only when its package names egress hosts; a stdio +// MCP server always is, because there is no contract behind it to hold it: the +// namespace and the allow-list are what limit it, and an acceptance that names +// no host leaves it able to reach nothing. +// +// env is added to the server's environment as given, for the settings and +// credentials its acceptance resolves. The returned release ends the server's +// egress gate and closes the verified binary. +func (h *Host) Command(ctx context.Context, spec Spec, args, env []string) (*exec.Cmd, func(), error) { + sum, err := hex.DecodeString(spec.SHA256) + if err != nil || len(sum) != sha256.Size { + return nil, nil, fmt.Errorf("mcp server %q: sha256 must be a hex digest", spec.Name) + } + binary, err := openVerified(spec.Path, sum) + if err != nil { + return nil, nil, fmt.Errorf("mcp server %q: %w", spec.Name, err) + } + release := func() { _ = binary.Close() } + g, err := openGate(ctx, spec.Egress) + if err != nil { + release() + return nil, nil, fmt.Errorf("mcp server %q: egress: %w", spec.Name, err) + } + // The server's lifetime is its session's, not the caller's deadline: the + // accept path and the supervisor both connect under a timeout. + lifetime, stop := context.WithCancel(context.WithoutCancel(ctx)) + cmd, err := confinedCommand(lifetime, binary, args, g.socket) + if err != nil { + stop() + g.close() + release() + return nil, nil, fmt.Errorf("mcp server %q: %w", spec.Name, err) + } + cmd.Env = append(passEnv(spec.Env), env...) + return cmd, func() { stop(); g.close(); release() }, nil +} diff --git a/modules/connectors/internal/store/store.go b/modules/connectors/internal/store/store.go index 6b091cb9a..99d04e7a2 100644 --- a/modules/connectors/internal/store/store.go +++ b/modules/connectors/internal/store/store.go @@ -14,7 +14,7 @@ import ( "github.com/jmoiron/sqlx" ) -// Accepted is one connector an operator accepted, with the authority it +// Accepted is one package an operator accepted, with the authority it // declared. type Accepted struct { OrgID string `db:"org_id"` @@ -24,16 +24,24 @@ type Accepted struct { Egress Strings `db:"egress"` Env Strings `db:"env"` Settings jsontext.Value `db:"settings"` - // Contract is ContractConnector or ContractSecretEngine. + // Contract is ContractConnector, ContractSecretEngine or ContractMCP. Contract string `db:"contract"` // Credentials maps a slot to a credential name, as a JSON object. Credentials jsontext.Value `db:"credentials"` + // Args are a stdio MCP server's arguments; URL is an HTTP server's + // endpoint. Which one the acceptance set is what picks the transport. + Args Strings `db:"args"` + URL string `db:"url"` + // Tools are the lookups and actions an MCP server's acceptance declares, + // as a JSON array. + Tools jsontext.Value `db:"tools"` } // Contracts an accepted package can serve. const ( ContractConnector = "connector" ContractSecretEngine = "secretengine" + ContractMCP = "mcp" ) // Credential is a credential's sealed fields. @@ -56,7 +64,7 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} } func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) { var out []Accepted if err := s.db.SelectContext(ctx, &out, ` - SELECT org_id, name, path, sha256, egress, env, settings, contract, credentials + SELECT org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil { return nil, fmt.Errorf("list connectors: %w", err) } @@ -66,12 +74,13 @@ func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) { // Upsert records an accepted connector, replacing an earlier acceptance. func (s *Store) Upsert(ctx context.Context, a Accepted) error { if _, err := s.db.NamedExecContext(ctx, ` - INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings, contract, credentials) - VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings, :contract, :credentials) + INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools) + VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings, :contract, :credentials, :args, :url, :tools) ON CONFLICT (org_id, name) DO UPDATE SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress, env = EXCLUDED.env, settings = EXCLUDED.settings, contract = EXCLUDED.contract, - credentials = EXCLUDED.credentials, updated_at = now()`, a); err != nil { + credentials = EXCLUDED.credentials, args = EXCLUDED.args, url = EXCLUDED.url, + tools = EXCLUDED.tools, updated_at = now()`, a); err != nil { return fmt.Errorf("accept connector: %w", err) } return nil diff --git a/modules/connectors/mcp.go b/modules/connectors/mcp.go new file mode 100644 index 000000000..4ce2059fd --- /dev/null +++ b/modules/connectors/mcp.go @@ -0,0 +1,512 @@ +package connectors + +import ( + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "maps" + "net/http" + "slices" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/google/jsonschema-go/jsonschema" + sdk "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/samcharles93/archie-core/modules/connectors/internal/egress" + "github.com/samcharles93/archie-core/modules/connectors/internal/host" +) + +// Bounds on one MCP server. A server is a tool source like a connector, so the +// same rules hold: a call has a deadline, a result has a size, and a tool the +// acceptance doesn't name is never offered. +const ( + // mcpConnectTimeout bounds the handshake and the tool listing. + mcpConnectTimeout = 30 * time.Second + // mcpCallTimeout bounds one tool call. + mcpCallTimeout = 60 * time.Second + // mcpPingInterval is how often a live session is checked, so a server that + // stopped answering is reported by readiness. + mcpPingInterval = 30 * time.Second + // mcpResultLimit caps the text one tool result hands back to the agent. + mcpResultLimit = 32 << 10 + // mcpToolLimit caps how many tools one server may list. + mcpToolLimit = 200 + // mcpBackoffMin and mcpBackoffMax bound the restart delay. + mcpBackoffMin = time.Second + mcpBackoffMax = time.Minute +) + +// ServerSpec is one accepted MCP server: how it is reached, the environment or +// headers its credentials resolve into, and the tools its acceptance permits. +type ServerSpec struct { + Name string + // Path and SHA256 identify a stdio server's binary; URL is an HTTP server's + // endpoint. Which one the acceptance set picks the transport. + Path string + SHA256 string + URL string + Args []string + // Env names host environment variables the server may see. + Env []string + // Settings are handed to a stdio server as its environment, since MCP has + // no configuration channel of its own. + Settings []string + // Egress is the accepted host list. A stdio server reaches only these. + Egress []string + // SecretEnv is a stdio server's credential-derived environment, and + // SecretHeaders an HTTP server's credential-derived headers. + SecretEnv []string + SecretHeaders map[string]string + // Tools are the tools the acceptance permits. + Tools []ToolDecl +} + +// ToolDecl is one tool an acceptance permits: a lookup, or an action with the +// effect it declares. +type ToolDecl struct { + Name string `json:"name"` + // Kind is KindLookup or KindAction. + Kind string `json:"kind"` + // ReadOnly, Reversibility and Summary are an action's effect. + ReadOnly bool `json:"read_only,omitzero"` + Reversibility string `json:"reversibility,omitzero"` + Summary string `json:"summary,omitzero"` +} + +// effect is what the declaration says the tool does. Its reversibility and +// summary are kept for judgement, which is what runs an action. +func (d ToolDecl) effect() Effect { + r, _ := reversibility(d.Reversibility) + return Effect{ReadOnly: d.Kind == KindLookup || d.ReadOnly, Reversibility: r, Summary: d.Summary} +} + +// mcpTool is one declared tool as the server lists it. +type mcpTool struct { + kind string + effect Effect + description string + input *jsonschema.Resolved + schema jsontext.Value +} + +// Server is one accepted MCP server: the process or endpoint its acceptance +// names, and the declared subset of the tools that server offers. +type Server struct { + name string + spec ServerSpec + log *slog.Logger + procs *host.Host + // dial connects, initialises a session and returns the release that ends + // it. It is a field so a test can speak to an in-memory server. + dial func(context.Context) (*sdk.ClientSession, func(), error) + + mu sync.Mutex + session *sdk.ClientSession + release func() + tools map[string]mcpTool + lastErr error +} + +// NewServer returns an MCP server that connects when it is first used and +// reconnects when its process or endpoint fails. +func (h *Host) NewServer(spec ServerSpec) *Server { + s := &Server{ + name: spec.Name, spec: spec, log: h.log, procs: h.procs, + tools: map[string]mcpTool{}, + } + s.dial = s.connect + return s +} + +// Declarations lists the tools the acceptance permits, in name order. +func (s *Server) Declarations() []Declaration { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]Declaration, 0, len(s.tools)) + for _, name := range slices.Sorted(maps.Keys(s.tools)) { + t := s.tools[name] + out = append(out, Declaration{ + Connector: s.name, Kind: t.kind, Name: name, + Description: t.description, Schema: t.schema, ReadOnly: t.effect.ReadOnly, + }) + } + return out +} + +// Lookup calls one declared lookup and returns the result verbatim. found is +// false when the server answered with nothing. +func (s *Server) Lookup(ctx context.Context, name string, input jsontext.Value) (string, bool, error) { + return s.call(ctx, name, KindLookup, input) +} + +// Invoke calls one declared action and returns the result verbatim. Nothing +// judges an action yet, so a declared one is never offered. +func (s *Server) Invoke(ctx context.Context, inv Invocation) (string, error) { + out, _, err := s.call(ctx, inv.Action, KindAction, inv.Input) + return out, err +} + +func (s *Server) call(ctx context.Context, name, kind string, input jsontext.Value) (string, bool, error) { + t, err := s.tool(name, kind) + if err != nil { + return "", false, err + } + if err := validate(t.input, input); err != nil { + return "", false, fmt.Errorf("mcp server %q: tool %q: %w", s.name, name, err) + } + args, err := arguments(input) + if err != nil { + return "", false, fmt.Errorf("mcp server %q: tool %q: %w", s.name, name, err) + } + cs, err := s.live(ctx) + if err != nil { + return "", false, fmt.Errorf("mcp server %q: %w", s.name, err) + } + ctx, cancel := context.WithTimeout(ctx, mcpCallTimeout) + defer cancel() + res, err := cs.CallTool(ctx, &sdk.CallToolParams{Name: name, Arguments: args}) + if err != nil { + s.drop(cs, fmt.Errorf("tool %q: %w", name, err)) + return "", false, fmt.Errorf("mcp server %q: tool %q: %w", s.name, name, err) + } + // A tool that answered with an error fails this call, not the run: the + // message is the server's own, so a bad query reads as a bad query. + out := capResult(render(res)) + if res.IsError { + return "", false, fmt.Errorf("mcp server %q: tool %q: %s", s.name, name, out) + } + if out == "" { + return "", false, nil + } + return out, true, nil +} + +// tool returns one declared tool, refusing a name the acceptance doesn't +// declare and a tool called through the wrong side of the contract. +func (s *Server) tool(name, kind string) (mcpTool, error) { + s.mu.Lock() + defer s.mu.Unlock() + t, ok := s.tools[name] + if !ok { + return mcpTool{}, fmt.Errorf("mcp server %q: tool %q: %w", s.name, name, ErrUnknownName) + } + if t.kind != kind { + return mcpTool{}, fmt.Errorf("mcp server %q: tool %q is a %s: %w", s.name, name, t.kind, ErrUnknownName) + } + return t, nil +} + +// live returns the current session, connecting once when there is none. +func (s *Server) live(ctx context.Context) (*sdk.ClientSession, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.session != nil { + return s.session, nil + } + cs, release, tools, err := s.open(ctx) + if err != nil { + s.lastErr = err + return nil, err + } + s.session, s.release, s.tools, s.lastErr = cs, release, tools, nil + return cs, nil +} + +// open connects and matches the server's tool list to the acceptance. +func (s *Server) open(ctx context.Context) (*sdk.ClientSession, func(), map[string]mcpTool, error) { + ctx, cancel := context.WithTimeout(ctx, mcpConnectTimeout) + defer cancel() + cs, release, err := s.dial(ctx) + if err != nil { + return nil, nil, nil, err + } + tools, err := s.declared(ctx, cs) + if err != nil { + release() + _ = cs.Close() + return nil, nil, nil, err + } + return cs, release, tools, nil +} + +// Connect opens the first session, so an acceptance that can't work is +// reported to the operator when it is made. +func (s *Server) Connect(ctx context.Context) error { + _, err := s.live(ctx) + return err +} + +// declared matches the server's tool list to the acceptance: a permitted tool +// takes the server's description and input schema, and a permitted tool the +// server doesn't list is an error rather than a silently missing one. +func (s *Server) declared(ctx context.Context, cs *sdk.ClientSession) (map[string]mcpTool, error) { + listed, err := listTools(ctx, cs) + if err != nil { + return nil, fmt.Errorf("mcp server %q: %w", s.name, err) + } + out := make(map[string]mcpTool, len(s.spec.Tools)) + var missing []string + for _, d := range s.spec.Tools { + t, ok := listed[d.Name] + if !ok { + missing = append(missing, d.Name) + continue + } + schema, resolved, err := compileTool(t) + if err != nil { + return nil, fmt.Errorf("mcp server %q: tool %q: %w", s.name, d.Name, err) + } + out[d.Name] = mcpTool{ + kind: d.Kind, effect: d.effect(), description: t.Description, + input: resolved, schema: schema, + } + } + if len(missing) > 0 { + return nil, fmt.Errorf("mcp server %q doesn't list the declared tool %s", s.name, strings.Join(missing, ", ")) + } + return out, nil +} + +// Supervise keeps the server answering, restarting it with backoff when it +// fails to start, exits or stops answering, until ctx ends. +func (s *Server) Supervise(ctx context.Context) { + log := s.log.With("server", s.name) + backoff := mcpBackoffMin + for { + cs, err := s.live(ctx) + if err != nil { + log.ErrorContext(ctx, "mcp server down", "error", err, "retry_in", backoff) + if !sleep(ctx, backoff) { + return + } + backoff = min(2*backoff, mcpBackoffMax) + continue + } + backoff = mcpBackoffMin + if !s.watch(ctx, cs) { + return + } + } +} + +// watch pings the session until it fails or ctx ends, and reports whether the +// server should be reconnected. +func (s *Server) watch(ctx context.Context, cs *sdk.ClientSession) bool { + ticker := time.NewTicker(mcpPingInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return false + case <-ticker.C: + pingCtx, cancel := context.WithTimeout(ctx, mcpCallTimeout) + err := cs.Ping(pingCtx, nil) + cancel() + if err != nil { + s.drop(cs, fmt.Errorf("ping: %w", err)) + return true + } + } + } +} + +// drop ends a session the server has left behind, so the next call reconnects. +func (s *Server) drop(cs *sdk.ClientSession, reason error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.session != cs { + return + } + s.session, s.lastErr = nil, reason + if s.release != nil { + s.release() + s.release = nil + } + _ = cs.Close() +} + +// Ready reports why the server isn't answering, or nil. +func (s *Server) Ready() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.session != nil { + return nil + } + if s.lastErr == nil { + return errors.New("mcp server not connected") + } + return s.lastErr +} + +// Close ends the server's session. +func (s *Server) Close() { + s.mu.Lock() + cs, release := s.session, s.release + s.session, s.release = nil, nil + s.mu.Unlock() + if release != nil { + release() + } + if cs != nil { + _ = cs.Close() + } +} + +// connect opens the transport the acceptance names and initialises a session. +func (s *Server) connect(ctx context.Context) (*sdk.ClientSession, func(), error) { + client := sdk.NewClient(&sdk.Implementation{Name: "archie-core", Version: "1.0.0"}, nil) + if s.spec.URL != "" { + transport := &sdk.StreamableClientTransport{ + Endpoint: s.spec.URL, HTTPClient: s.httpClient(), DisableStandaloneSSE: true, + } + cs, err := client.Connect(ctx, transport, nil) + if err != nil { + return nil, nil, err + } + return cs, func() { _ = cs.Close() }, nil + } + cmd, release, err := s.procs.Command(ctx, host.Spec{ + Name: s.spec.Name, Path: s.spec.Path, SHA256: s.spec.SHA256, Env: s.spec.Env, Egress: s.spec.Egress, + }, s.spec.Args, append(slices.Clone(s.spec.Settings), s.spec.SecretEnv...)) + if err != nil { + return nil, nil, err + } + cs, err := client.Connect(ctx, &sdk.CommandTransport{Command: cmd}, nil) + if err != nil { + release() + return nil, nil, err + } + return cs, release, nil +} + +// httpClient dials only the hosts the acceptance names, and sends that +// server's own credentials and no other's. +func (s *Server) httpClient() *http.Client { + transport := &http.Transport{ + DialContext: egress.Dialer(s.spec.Egress), + TLSHandshakeTimeout: 10 * time.Second, + MaxIdleConnsPerHost: 2, + } + return &http.Client{Transport: &headerTransport{base: transport, headers: s.spec.SecretHeaders}} +} + +// headerTransport sets the credentials an HTTP server is called with. +type headerTransport struct { + base http.RoundTripper + headers map[string]string +} + +func (h *headerTransport) RoundTrip(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + for name, value := range h.headers { + r.Header.Set(name, value) + } + return h.base.RoundTrip(r) +} + +// listTools reads every page of a server's tool list. +func listTools(ctx context.Context, cs *sdk.ClientSession) (map[string]*sdk.Tool, error) { + out := map[string]*sdk.Tool{} + params := &sdk.ListToolsParams{} + for { + res, err := cs.ListTools(ctx, params) + if err != nil { + return nil, fmt.Errorf("list tools: %w", err) + } + for _, t := range res.Tools { + if len(out) >= mcpToolLimit { + return nil, fmt.Errorf("the server lists more than %d tools", mcpToolLimit) + } + out[t.Name] = t + } + if res.NextCursor == "" { + return out, nil + } + params.Cursor = res.NextCursor + } +} + +// compileTool compiles a listed tool's input schema, and keeps the schema as +// the agent is shown it. +func compileTool(t *sdk.Tool) (jsontext.Value, *jsonschema.Resolved, error) { + raw, err := json.Marshal(t.InputSchema) + if err != nil { + return nil, nil, fmt.Errorf("input schema: %w", err) + } + if len(raw) == 0 || string(raw) == "null" { + // A tool that takes no arguments still has to carry a schema a model + // API accepts. + raw = []byte(`{"type":"object"}`) + } + resolved, err := compile(raw) + if err != nil { + return nil, nil, err + } + return jsontext.Value(raw), resolved, nil +} + +// arguments turns a call's input into the arguments a tool call carries. +func arguments(input jsontext.Value) (map[string]any, error) { + if len(input) == 0 { + return map[string]any{}, nil + } + var args map[string]any + if err := json.Unmarshal(input, &args); err != nil { + return nil, fmt.Errorf("arguments: %w", err) + } + return args, nil +} + +// render turns a tool result into the text the agent is given: text blocks +// verbatim, and any other block as the JSON the server sent. +func render(res *sdk.CallToolResult) string { + var b strings.Builder + for _, c := range res.Content { + if text, ok := c.(*sdk.TextContent); ok { + b.WriteString(text.Text) + continue + } + raw, err := c.MarshalJSON() + if err != nil { + continue + } + b.Write(raw) + } + if b.Len() == 0 && res.StructuredContent != nil { + if raw, err := json.Marshal(res.StructuredContent); err == nil { + b.Write(raw) + } + } + return b.String() +} + +// capResult holds a result to mcpResultLimit bytes, on a character boundary, +// and says what it dropped. +func capResult(out string) string { + if len(out) <= mcpResultLimit { + return out + } + kept := mcpResultLimit + for kept > 0 && !utf8.RuneStart(out[kept]) { + kept-- + } + return out[:kept] + fmt.Sprintf("\n[truncated: %d bytes dropped, a result is capped at %d]", len(out)-kept, mcpResultLimit) +} + +// sleep waits out a backoff, reporting false when ctx ended first. +func sleep(ctx context.Context, d time.Duration) bool { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} diff --git a/modules/connectors/mcp_test.go b/modules/connectors/mcp_test.go new file mode 100644 index 000000000..2ca54cdd8 --- /dev/null +++ b/modules/connectors/mcp_test.go @@ -0,0 +1,177 @@ +package connectors + +import ( + "context" + "encoding/json/jsontext" + "errors" + "log/slog" + "strings" + "testing" + + sdk "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// fakeTools is a server offering one lookup, one action and one tool that +// answers with an error, the last of them only when ask names it. +func fakeTools(t *testing.T, list ...string) *sdk.Server { + t.Helper() + srv := sdk.NewServer(&sdk.Implementation{Name: "fake", Version: "1.0.0"}, nil) + for _, name := range list { + schema := map[string]any{ + "type": "object", + "properties": map[string]any{"query": map[string]any{"type": "string"}}, + } + srv.AddTool(&sdk.Tool{Name: name, Description: name + " looks something up", InputSchema: schema}, + func(_ context.Context, req *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + text := `{"status":"success","tool":"` + req.Params.Name + `"}` + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: text}}}, nil + }) + } + return srv +} + +// inMemory wires a Server to srv over an in-memory transport, so the client +// side is exercised without a process. +func inMemory(t *testing.T, spec ServerSpec, srv *sdk.Server) *Server { + t.Helper() + s := &Server{name: spec.Name, spec: spec, log: slog.New(slog.DiscardHandler), tools: map[string]mcpTool{}} + s.dial = func(ctx context.Context) (*sdk.ClientSession, func(), error) { + serverTransport, clientTransport := sdk.NewInMemoryTransports() + if _, err := srv.Connect(ctx, serverTransport, nil); err != nil { + return nil, nil, err + } + client := sdk.NewClient(&sdk.Implementation{Name: "archie-core", Version: "1.0.0"}, nil) + cs, err := client.Connect(ctx, clientTransport, nil) + if err != nil { + return nil, nil, err + } + return cs, func() { _ = cs.Close() }, nil + } + return s +} + +// TestOnlyDeclaredToolsAreOffered guards 2.5's allow-list: a tool the server +// lists but the acceptance doesn't name is never offered to an agent and +// can't be called by name, while a permitted tool keeps the server's own +// description and schema. A declared tool the server doesn't list fails the +// start, so an operator sees it rather than a silently missing tool. +func TestOnlyDeclaredToolsAreOffered(t *testing.T) { + spec := ServerSpec{Name: "metrics", Tools: []ToolDecl{{Name: "query", Kind: KindLookup}}} + s := inMemory(t, spec, fakeTools(t, "query", "reload")) + if err := s.Connect(t.Context()); err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(s.Close) + + decls := s.Declarations() + if len(decls) != 1 || decls[0].Name != "query" { + t.Fatalf("declarations = %+v, want only query", decls) + } + if !decls[0].ReadOnly || decls[0].Description != "query looks something up" { + t.Fatalf("declaration = %+v, want the server's read-only description", decls[0]) + } + if !strings.Contains(string(decls[0].Schema), "query") { + t.Fatalf("schema = %s, want the server's own", decls[0].Schema) + } + if _, _, err := s.Lookup(t.Context(), "reload", nil); !errors.Is(err, ErrUnknownName) { + t.Fatalf("calling the undeclared tool: %v, want %v", err, ErrUnknownName) + } +} + +// TestUndeclaredListedToolFailsTheStart covers the other direction: the server +// doesn't list a tool the acceptance declares. +func TestUndeclaredListedToolFailsTheStart(t *testing.T) { + spec := ServerSpec{Name: "metrics", Tools: []ToolDecl{{Name: "query", Kind: KindLookup}, {Name: "series", Kind: KindLookup}}} + s := inMemory(t, spec, fakeTools(t, "query")) + err := s.Connect(t.Context()) + if err == nil || !strings.Contains(err.Error(), "series") { + t.Fatalf("connect: %v, want an error naming the missing tool", err) + } + if rerr := s.Ready(); rerr == nil { + t.Fatal("readiness is clean after a failed start") + } +} + +// TestErrorResultFailsOnlyItsCall guards the contract an agent depends on: the +// server's own error text comes back verbatim, marked as an ordinary failure +// rather than an unknown outcome, and input that breaks the tool's schema never +// reaches the server. +func TestErrorResultFailsOnlyItsCall(t *testing.T) { + var called int + srv := sdk.NewServer(&sdk.Implementation{Name: "fake", Version: "1.0.0"}, nil) + schema := map[string]any{"type": "object", "required": []string{"query"}, "properties": map[string]any{"query": map[string]any{"type": "string"}}} + srv.AddTool(&sdk.Tool{Name: "query", Description: "runs promql", InputSchema: schema}, + func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + called++ + return &sdk.CallToolResult{ + IsError: true, + Content: []sdk.Content{&sdk.TextContent{Text: "parse error: unexpected end of input"}}, + }, nil + }) + s := inMemory(t, ServerSpec{Name: "metrics", Tools: []ToolDecl{{Name: "query", Kind: KindLookup}}}, srv) + if err := s.Connect(t.Context()); err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(s.Close) + + out, found, err := s.Lookup(t.Context(), "query", jsontext.Value(`{"query":"rate("}`)) + if err == nil || found || out != "" { + t.Fatalf("lookup = %q, %v, %v; want the server's error", out, found, err) + } + if !strings.Contains(err.Error(), "parse error: unexpected end of input") { + t.Fatalf("error = %v, want the server's text verbatim", err) + } + if errors.Is(err, ErrOutcomeUnknown) { + t.Fatalf("error = %v, want a failure that ends the call and not the run", err) + } + + // A call that breaks the schema is refused before it reaches the server. + if _, _, err := s.Lookup(t.Context(), "query", jsontext.Value(`{"query":7}`)); err == nil { + t.Fatal("a payload breaking the tool's schema was accepted") + } + if called != 1 { + t.Fatalf("the server was called %d times, want 1", called) + } + + // An empty answer reads as nothing found, not as an error. + empty := sdk.NewServer(&sdk.Implementation{Name: "fake", Version: "1.0.0"}, nil) + empty.AddTool(&sdk.Tool{Name: "query", InputSchema: map[string]any{"type": "object"}}, + func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{}, nil + }) + nothing := inMemory(t, ServerSpec{Name: "quiet", Tools: []ToolDecl{{Name: "query", Kind: KindLookup}}}, empty) + if err := nothing.Connect(t.Context()); err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(nothing.Close) + out, found, err = nothing.Lookup(t.Context(), "query", nil) + if err != nil || found || out != "" { + t.Fatalf("lookup = %q, %v, %v; want found=false and no error", out, found, err) + } +} + +// TestResultIsCapped guards the size bound: a result larger than the cap is cut +// at a character boundary and says how much it dropped, so a series explosion +// can't spend the run's context. +func TestResultIsCapped(t *testing.T) { + srv := sdk.NewServer(&sdk.Implementation{Name: "fake", Version: "1.0.0"}, nil) + srv.AddTool(&sdk.Tool{Name: "range_query", InputSchema: map[string]any{"type": "object"}}, + func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: strings.Repeat("ée", mcpResultLimit)}}}, nil + }) + s := inMemory(t, ServerSpec{Name: "metrics", Tools: []ToolDecl{{Name: "range_query", Kind: KindLookup}}}, srv) + if err := s.Connect(t.Context()); err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(s.Close) + out, _, err := s.Lookup(t.Context(), "range_query", nil) + if err != nil { + t.Fatalf("lookup: %v", err) + } + if len(out) > mcpResultLimit+128 { + t.Fatalf("result is %d bytes, want it capped near %d", len(out), mcpResultLimit) + } + if !strings.Contains(out, "truncated") || !strings.Contains(out, "capped at") { + t.Fatalf("result doesn't say it was truncated: %q", out[max(0, len(out)-120):]) + } +} diff --git a/modules/connectors/mcpaccept.go b/modules/connectors/mcpaccept.go new file mode 100644 index 000000000..f300d18c1 --- /dev/null +++ b/modules/connectors/mcpaccept.go @@ -0,0 +1,234 @@ +package connectors + +import ( + "context" + json "encoding/json/v2" + "errors" + "fmt" + "maps" + "net/http" + "net/url" + "regexp" + "slices" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/connectors/internal/store" +) + +// envSettingName is the shape of a setting's name: a stdio server's settings +// are its environment. +var envSettingName = regexp.MustCompile(`^[A-Z_][A-Z0-9_]*$`) + +// mcpRequest is one acceptance of an MCP server. +type mcpRequest struct { + // URL reaches an HTTP server; Path and SHA256 name a stdio server's binary. + // Setting one of the two picks the transport. + URL string `json:"url"` + Path string `json:"path"` + SHA256 string `json:"sha256"` + // Args are a stdio server's arguments. + Args []string `json:"args"` + // Env names host environment variables the server may see. + Env []string `json:"env"` + // Settings are handed to a stdio server as its environment. + Settings map[string]string `json:"settings"` + // Egress is the accepted host list: everything the server may reach. + Egress []string `json:"egress"` + // Credentials maps each slot the server's credentials are read from to a + // credential by name. + Credentials map[string]string `json:"credentials"` + // Tools are the tools the server may offer, and nothing else is offered. + Tools []ToolDecl `json:"tools"` +} + +// check refuses an acceptance that couldn't work, before anything is stored. +func (r mcpRequest) check() error { + if err := r.checkTransport(); err != nil { + return err + } + for _, name := range slices.Sorted(maps.Keys(r.Settings)) { + if !envSettingName.MatchString(name) { + return fmt.Errorf("setting %q isn't an environment variable name", name) + } + } + return r.checkTools() +} + +// checkTransport refuses an acceptance that names no transport, both of them, +// or a field the transport it named has no use for. +func (r mcpRequest) checkTransport() error { + stdio, exchange := r.Path != "" || r.SHA256 != "", r.URL != "" + switch { + case stdio && exchange: + return errors.New("an MCP server is reached over stdio or HTTP, not both") + case !stdio && !exchange: + return errors.New("an MCP server needs a path and its sha256 (stdio), or a url (HTTP)") + } + if stdio { + if r.Path == "" || r.SHA256 == "" { + return errors.New("a stdio MCP server needs its binary's path and sha256") + } + return nil + } + if len(r.Args) > 0 || len(r.Settings) > 0 { + return errors.New("an HTTP MCP server takes no arguments or settings: both belong to a stdio server") + } + u, err := url.Parse(r.URL) + if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { + return fmt.Errorf("url %q needs an http or https scheme and a host", r.URL) + } + return nil +} + +// checkTools refuses an acceptance that declares nothing to offer, or a +// declaration that can't be judged: an action without the effect it claims. +func (r mcpRequest) checkTools() error { + if len(r.Tools) == 0 { + return errors.New("an MCP server offers only the tools its acceptance declares, and this one declares none") + } + seen := make(map[string]bool, len(r.Tools)) + for _, t := range r.Tools { + if t.Name == "" { + return errors.New("a declared tool needs a name") + } + if seen[t.Name] { + return fmt.Errorf("tool %q is declared twice", t.Name) + } + seen[t.Name] = true + switch t.Kind { + case KindLookup: + case KindAction: + if t.Summary == "" { + return fmt.Errorf("action %q needs a summary of its effect", t.Name) + } + if _, ok := reversibility(t.Reversibility); !ok { + return fmt.Errorf("action %q: reversibility %q isn't one of auto, recoverable, irreversible", t.Name, t.Reversibility) + } + default: + return fmt.Errorf("tool %q is a %q, want %q or %q", t.Name, t.Kind, KindLookup, KindAction) + } + } + return nil +} + +// reversibility reads an action declaration's reversibility. Judgement reads +// it; nothing runs an action until judgement exists. +func reversibility(name string) (Reversibility, bool) { + switch name { + case "": + return ReversibilityUnspecified, true + case "auto": + return UndoneAutomatically, true + case "recoverable": + return Recoverable, true + case "irreversible": + return Irreversible, true + } + return ReversibilityUnspecified, false +} + +// acceptServer stores an MCP server's acceptance and starts it. A server that +// doesn't come up is still accepted: it is reported by readiness and retried +// with backoff, so a restart fixes it without another acceptance. +func (m *Module) acceptServer(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + var req mcpRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if !validName.MatchString(name) { + httpjson.Error(w, http.StatusBadRequest, "an MCP server needs a lowercase name") + return + } + if err := req.check(); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + a, err := req.accepted(m.orgID, name) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if err := m.store.Upsert(r.Context(), a); err != nil { + httpjson.Error(w, http.StatusInternalServerError, err.Error()) + return + } + if err := m.launch(context.WithoutCancel(r.Context()), a); err != nil { + httpjson.Error(w, http.StatusUnprocessableEntity, err.Error()) + return + } + httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"}) +} + +// accepted is the row an acceptance stores. +func (r mcpRequest) accepted(orgID, name string) (store.Accepted, error) { + settings, err := json.Marshal(r.Settings, json.FormatNilMapAsNull(false)) + if err != nil { + return store.Accepted{}, err + } + slots, err := json.Marshal(r.Credentials, json.FormatNilMapAsNull(false)) + if err != nil { + return store.Accepted{}, err + } + tools, err := json.Marshal(r.Tools) + if err != nil { + return store.Accepted{}, err + } + return store.Accepted{ + OrgID: orgID, Name: name, Contract: store.ContractMCP, + Path: r.Path, SHA256: r.SHA256, URL: r.URL, Args: r.Args, + Env: r.Env, Egress: r.Egress, Settings: settings, Credentials: slots, Tools: tools, + }, nil +} + +// startServer runs one accepted MCP server. Its supervisor keeps it answering, +// reconnecting with backoff, until the module closes or the server is accepted +// again. +func (m *Module) startServer(ctx context.Context, a store.Accepted) error { + spec, err := m.serverSpec(ctx, a) + if err != nil { + return m.fail(ctx, a.Name, err) + } + base, stop := context.WithCancel(context.WithoutCancel(ctx)) + s := m.host.NewServer(spec) + m.mu.Lock() + m.servers[a.Name], m.stops[a.Name] = s, stop + delete(m.failed, a.Name) + m.mu.Unlock() + go s.Supervise(base) + if err := s.Connect(ctx); err != nil { + m.log.ErrorContext(ctx, "mcp server failed to start", "server", a.Name, "error", err) + return err + } + m.log.InfoContext(ctx, "mcp server started", "server", a.Name) + return nil +} + +// serverSpec is what a stored acceptance says a running server must be. +func (m *Module) serverSpec(ctx context.Context, a store.Accepted) (ServerSpec, error) { + spec := ServerSpec{ + Name: a.Name, Path: a.Path, SHA256: a.SHA256, URL: a.URL, + Args: a.Args, Egress: a.Egress, + } + if len(a.Settings) > 0 { + var settings map[string]string + if err := json.Unmarshal(a.Settings, &settings); err != nil { + return ServerSpec{}, fmt.Errorf("settings: %w", err) + } + for _, name := range slices.Sorted(maps.Keys(settings)) { + spec.Settings = append(spec.Settings, name+"="+settings[name]) + } + } + if len(a.Tools) > 0 { + if err := json.Unmarshal(a.Tools, &spec.Tools); err != nil { + return ServerSpec{}, fmt.Errorf("tools: %w", err) + } + } + env, headers, err := m.mcpCredentials(ctx, a, spec.URL != "") + if err != nil { + return ServerSpec{}, err + } + spec.SecretEnv, spec.SecretHeaders = env, headers + return spec, nil +} diff --git a/modules/connectors/mcpauth.go b/modules/connectors/mcpauth.go new file mode 100644 index 000000000..e5c4fdf76 --- /dev/null +++ b/modules/connectors/mcpauth.go @@ -0,0 +1,117 @@ +package connectors + +import ( + "context" + "encoding/base64" + "fmt" + "maps" + "slices" + "strings" + + "github.com/samcharles93/archie-core/modules/connectors/internal/store" +) + +// Credential kinds an MCP server's slot can hold: one HTTP auth scheme each. +const ( + kindBasic = "basic" + kindBearer = "bearer" +) + +// mcpEnv turns one slot's fields into the environment a stdio server is +// launched with, named _ in upper case. +func mcpEnv(slot, kind string, fields map[string]string) ([]string, error) { + var names []string + switch kind { + case kindBearer: + names = []string{"token"} + case kindBasic: + names = []string{"username", "password"} + default: + return nil, fmt.Errorf("a credential slot for an MCP server needs a basic or bearer credential, not %s", kind) + } + out := make([]string, 0, len(names)) + for _, name := range names { + value, ok := fields[name] + if !ok { + return nil, fmt.Errorf("a %s credential has no %s", kind, name) + } + out = append(out, envName(slot, name)+"="+value) + } + return out, nil +} + +// mcpAuthorization is the header an HTTP server is called with, from the same +// fields. +func mcpAuthorization(kind string, fields map[string]string) (string, error) { + switch kind { + case kindBearer: + token, ok := fields["token"] + if !ok { + return "", fmt.Errorf("a %s credential has no token", kind) + } + return "Bearer " + token, nil + case kindBasic: + username, ok := fields["username"] + if !ok { + return "", fmt.Errorf("a %s credential has no username", kind) + } + return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+fields["password"])), nil + } + return "", fmt.Errorf("a credential slot for an MCP server needs a basic or bearer credential, not %s", kind) +} + +// envName is the environment variable one slot's field is handed to a stdio +// server in. +func envName(slot, field string) string { + name := strings.NewReplacer("-", "_", ".", "_").Replace(slot) + return strings.ToUpper(name + "_" + field) +} + +// mcpCredentials resolves an MCP server's credential slots into the environment +// a stdio server is launched with, or the headers an HTTP one is called with. +// Only the slots this acceptance names are read, so one server's credentials +// never reach another. +func (m *Module) mcpCredentials(ctx context.Context, a store.Accepted, httpTransport bool) ([]string, map[string]string, error) { + slots, err := decodeSlots(a.Credentials) + if err != nil { + return nil, nil, err + } + var env []string + headers := map[string]string{} + for _, slot := range slices.Sorted(maps.Keys(slots)) { + name := slots[slot] + c, ok, err := m.store.Credential(ctx, m.orgID, name) + if err != nil { + return nil, nil, err + } + if !ok { + return nil, nil, fmt.Errorf("credential %q for slot %q doesn't exist", name, slot) + } + fields, err := m.openCredential(c) + if err != nil { + return nil, nil, err + } + values := make(map[string]string, len(fields)) + for field, f := range fields { + value, err := m.resolveField(ctx, a, f) + if err != nil { + return nil, nil, fmt.Errorf("credential %q field %s: %w", name, field, err) + } + values[field] = value + } + if httpTransport { + auth, err := mcpAuthorization(c.Kind, values) + if err != nil { + return nil, nil, fmt.Errorf("credential %q for slot %q: %w", name, slot, err) + } + headers["Authorization"] = auth + continue + } + lines, err := mcpEnv(slot, c.Kind, values) + if err != nil { + return nil, nil, fmt.Errorf("credential %q for slot %q: %w", name, slot, err) + } + env = append(env, lines...) + } + return env, headers, nil +} diff --git a/modules/connectors/mcpauth_test.go b/modules/connectors/mcpauth_test.go new file mode 100644 index 000000000..67fb9ade5 --- /dev/null +++ b/modules/connectors/mcpauth_test.go @@ -0,0 +1,89 @@ +package connectors + +import ( + "encoding/base64" + "slices" + "strings" + "testing" +) + +// TestCredentialSlotsReachOnlyTheirOwnServer guards 2.5's boundary at the MCP +// server: a slot resolves into that server's environment or its Authorization +// header and nothing else, a kind that isn't an HTTP auth scheme is refused +// rather than handed over unshaped, and a second server's slot never appears in +// the first one's. +func TestCredentialSlotsReachOnlyTheirOwnServer(t *testing.T) { + bearer := map[string]string{"token": "s3cret"} + basic := map[string]string{"username": "archie", "password": "hunter2"} + tests := []struct { + name string + slot string + kind string + fields map[string]string + http bool + want []string + header string + refused bool + }{ + { + name: "a bearer token in a stdio server's environment", slot: "metrics", kind: kindBearer, + fields: bearer, want: []string{"METRICS_TOKEN=s3cret"}, + }, + { + name: "a basic credential in a stdio server's environment", slot: "metrics", kind: kindBasic, + fields: basic, want: []string{"METRICS_USERNAME=archie", "METRICS_PASSWORD=hunter2"}, + }, + { + name: "a bearer token as a header", slot: "metrics", kind: kindBearer, fields: bearer, http: true, + header: "Bearer s3cret", + }, + { + name: "a basic credential as a header", slot: "metrics", kind: kindBasic, fields: basic, http: true, + header: "Basic " + base64.StdEncoding.EncodeToString([]byte("archie:hunter2")), + }, + { + name: "a slot named with a dot still makes a usable variable", slot: "prom.mcp", kind: kindBearer, + fields: bearer, want: []string{"PROM_MCP_TOKEN=s3cret"}, + }, + { + name: "a machine credential is refused rather than handed over unshaped", slot: "metrics", kind: "machine", + fields: map[string]string{"username": "archie", "private_key": "key"}, refused: true, + }, + { + name: "an age identity is refused too", slot: "metrics", kind: "age", + fields: map[string]string{"identity": "AGE-SECRET-KEY-1"}, refused: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.http { + header, err := mcpAuthorization(tt.kind, tt.fields) + if refused := err != nil; refused != tt.refused { + t.Fatalf("refused = %v, want %v (%v)", refused, tt.refused, err) + } + if tt.refused { + return + } + if header != tt.header { + t.Fatalf("authorization = %q, want %q", header, tt.header) + } + return + } + env, err := mcpEnv(tt.slot, tt.kind, tt.fields) + if refused := err != nil; refused != tt.refused { + t.Fatalf("refused = %v, want %v (%v)", refused, tt.refused, err) + } + if tt.refused { + return + } + if !slices.Equal(env, tt.want) { + t.Fatalf("environment = %v, want %v", env, tt.want) + } + for _, line := range env { + if strings.Contains(line, "AGE-SECRET-KEY") || strings.Contains(line, "private_key") { + t.Fatalf("credential %q leaked into the server's environment", line) + } + } + }) + } +} diff --git a/modules/connectors/module.go b/modules/connectors/module.go index ffefa235f..f157bf863 100644 --- a/modules/connectors/module.go +++ b/modules/connectors/module.go @@ -38,6 +38,10 @@ type Module struct { mu sync.RWMutex running map[string]*Connector engines map[string]*Engine + // servers are the accepted MCP servers, and stops ends each one's + // supervisor. + servers map[string]*Server + stops map[string]context.CancelFunc failed map[string]string } @@ -57,6 +61,7 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealing Sealing) (*M return &Module{ orgID: orgID, host: NewHost(log), store: store.New(db), sealer: sealer, log: log, running: map[string]*Connector{}, engines: map[string]*Engine{}, failed: map[string]string{}, + servers: map[string]*Server{}, stops: map[string]context.CancelFunc{}, }, nil } @@ -75,7 +80,8 @@ func (m *Module) Start(ctx context.Context) error { return nil } -// ordered puts secret engines ahead of connectors. +// ordered starts secret engines first, then connectors, then MCP servers: a +// credential may be resolved through an engine. func ordered(accepted []store.Accepted) []store.Accepted { out := slices.Clone(accepted) slices.SortStableFunc(out, func(a, b store.Accepted) int { @@ -85,13 +91,17 @@ func ordered(accepted []store.Accepted) []store.Accepted { } func rank(a store.Accepted) int { - if a.Contract == store.ContractSecretEngine { + switch a.Contract { + case store.ContractSecretEngine: return 0 + case store.ContractMCP: + return 2 } return 1 } -// Get returns the running connector named name. +// Get returns the running connector named name. An MCP server is reached +// through Tool, since it answers lookups and actions rather than events. func (m *Module) Get(name string) (*Connector, bool) { m.mu.RLock() defer m.mu.RUnlock() @@ -99,8 +109,19 @@ func (m *Module) Get(name string) (*Connector, bool) { return c, ok } -// Declarations lists every running connector's lookups and actions, ordered -// by connector and then by name. +// Tool returns the connector or MCP server that declared name. +func (m *Module) Tool(name string) (Tool, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + if c, ok := m.running[name]; ok { + return c, true + } + s, ok := m.servers[name] + return s, ok +} + +// Declarations lists every running connector's lookups and actions and every +// MCP server's declared tools, ordered by name and then by tool name. func (m *Module) Declarations() []Declaration { m.mu.RLock() defer m.mu.RUnlock() @@ -108,13 +129,16 @@ func (m *Module) Declarations() []Declaration { for _, name := range slices.Sorted(maps.Keys(m.running)) { out = append(out, m.running[name].Declarations()...) } + for _, name := range slices.Sorted(maps.Keys(m.servers)) { + out = append(out, m.servers[name].Declarations()...) + } return out } -// Ready reports connectors that failed to start or whose process has exited. +// Ready reports an extension that failed to start or whose process has exited, +// and an MCP server that doesn't answer. func (m *Module) Ready(context.Context) error { m.mu.RLock() - defer m.mu.RUnlock() var problems []string for name, reason := range m.failed { problems = append(problems, name+": "+reason) @@ -129,6 +153,13 @@ func (m *Module) Ready(context.Context) error { problems = append(problems, name+": process exited") } } + servers := maps.Clone(m.servers) + m.mu.RUnlock() + for _, name := range slices.Sorted(maps.Keys(servers)) { + if err := servers[name].Ready(); err != nil { + problems = append(problems, name+": "+err.Error()) + } + } if len(problems) == 0 { return nil } @@ -136,13 +167,26 @@ func (m *Module) Ready(context.Context) error { return errors.New(strings.Join(problems, "; ")) } -// Close stops every connector and secret engine. -func (m *Module) Close() { m.host.Close() } +// Close stops every connector, secret engine and MCP server. +func (m *Module) Close() { + m.mu.Lock() + stops, servers := m.stops, m.servers + m.stops, m.servers = map[string]context.CancelFunc{}, map[string]*Server{} + m.mu.Unlock() + for _, stop := range stops { + stop() + } + for _, s := range servers { + s.Close() + } + m.host.Close() +} // Routes adds the admin routes, each wrapped in guard. func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { mux.Handle("PUT /api/connectors/{name}", guard(m.accept(store.ContractConnector))) mux.Handle("PUT /api/secret-engines/{name}", guard(m.accept(store.ContractSecretEngine))) + mux.Handle("PUT /api/mcp-servers/{name}", guard(http.HandlerFunc(m.acceptServer))) mux.Handle("PUT /api/credentials/{name}", guard(http.HandlerFunc(m.putCredential))) mux.Handle("GET /api/credentials", guard(http.HandlerFunc(m.listCredentials))) } @@ -198,8 +242,14 @@ func (m *Module) acceptAs(w http.ResponseWriter, r *http.Request, contract strin httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"}) } -// launch starts or restarts one accepted extension and records the outcome. +// launch starts or restarts one accepted package and records the outcome. A +// name runs one package: whatever ran under it before is stopped first, so a +// connector, a secret engine and an MCP server never share a name. func (m *Module) launch(ctx context.Context, a store.Accepted) error { + m.release(a.Name) + if a.Contract == store.ContractMCP { + return m.startServer(ctx, a) + } var settings map[string]string if len(a.Settings) > 0 { if err := json.Unmarshal(a.Settings, &settings); err != nil { @@ -238,6 +288,29 @@ func (m *Module) launch(ctx context.Context, a store.Accepted) error { return nil } +// release stops whatever ran under name, so one accepted package is what a +// name runs. +func (m *Module) release(name string) { + m.mu.Lock() + _, running := m.running[name] + _, engine := m.engines[name] + s, stop := m.servers[name], m.stops[name] + delete(m.running, name) + delete(m.engines, name) + delete(m.servers, name) + delete(m.stops, name) + m.mu.Unlock() + if running || engine { + m.host.Stop(name) + } + if stop != nil { + stop() + } + if s != nil { + s.Close() + } +} + func (m *Module) fail(ctx context.Context, name string, err error) error { m.mu.Lock() delete(m.running, name) diff --git a/modules/runs/investigate.go b/modules/runs/investigate.go index 88b6d1a8a..8aa1ca8d8 100644 --- a/modules/runs/investigate.go +++ b/modules/runs/investigate.go @@ -24,11 +24,11 @@ type AgentModels interface { AgentModel(ctx context.Context) (governance.Model, error) } -// Toolbox is where a workflow finds the connector lookups and actions it may -// offer an agent, and the connectors that run them. +// Toolbox is where a workflow finds the connector lookups and actions and the +// MCP server tools it may offer an agent, and the tools that run them. type Toolbox interface { Declarations() []connectors.Declaration - Get(name string) (*connectors.Connector, bool) + Tool(name string) (connectors.Tool, bool) } // Notifier tells people what a run found. @@ -117,8 +117,8 @@ func offered(all []connectors.Declaration) []connectors.Declaration { var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`) // toolSet turns pinned declarations into the agent's tools. Each tool calls -// its connector by name when the model asks, so a connector that has since -// stopped fails that call rather than the run. +// its connector or MCP server by name when the model asks, so one that has +// since stopped fails that call rather than the run. func toolSet(box Toolbox, decls []connectors.Declaration) core.ToolSet { set := core.ToolSet{} for _, d := range decls { @@ -136,21 +136,21 @@ func toolSet(box Toolbox, decls []connectors.Declaration) core.ToolSet { } func call(ctx context.Context, box Toolbox, d connectors.Declaration, input jsontext.Value) (string, error) { - conn, ok := box.Get(d.Connector) + tool, ok := box.Tool(d.Connector) if !ok { - return "", fmt.Errorf("connector %q isn't running", d.Connector) + return "", fmt.Errorf("%q isn't running", d.Connector) } if d.Kind == connectors.KindLookup { - out, found, err := conn.Lookup[jsontext.Value](ctx, d.Name, input) + out, found, err := tool.Lookup(ctx, d.Name, input) switch { case err != nil: return "", err case !found: return "not found", nil } - return string(out), nil + return out, nil } - out, err := conn.Invoke[jsontext.Value](ctx, connectors.Invocation{ + out, err := tool.Invoke(ctx, connectors.Invocation{ Action: d.Name, Input: input, IdempotencyKey: core.IdempotencyKey(ctx), }) if errors.Is(err, connectors.ErrOutcomeUnknown) { @@ -159,5 +159,5 @@ func call(ctx context.Context, box Toolbox, d connectors.Declaration, input json if err != nil { return "", err } - return string(out), nil + return out, nil }