diff --git a/packages/vm-agent/internal/acp/mcp_servers.go b/packages/vm-agent/internal/acp/mcp_servers.go index 8b84473eca..f2592ec546 100644 --- a/packages/vm-agent/internal/acp/mcp_servers.go +++ b/packages/vm-agent/internal/acp/mcp_servers.go @@ -177,7 +177,8 @@ func buildAcpMcpServers(entries []McpServerEntry, agentType string) []acpsdk.Mcp servers = append(servers, buildAmpMcpServer(name, e)) continue } - var headers []acpsdk.HttpHeader + // ACP requires an array, including when the server has no headers. + headers := make([]acpsdk.HttpHeader, 0, len(e.Headers)+1) for _, header := range e.httpHeaders() { headers = append(headers, acpsdk.HttpHeader{Name: header.Name, Value: header.Value}) } @@ -200,7 +201,8 @@ func buildAcpMcpServers(entries []McpServerEntry, agentType string) []acpsdk.Mcp // below are already kept out of argv for exactly this reason; the URL should get the same // treatment once it is verified how mcp-remote accepts a URL from the environment. func buildAmpMcpServer(name string, entry McpServerEntry) acpsdk.McpServer { - var env []acpsdk.EnvVariable + // ACP requires an array, including when the bridge needs no environment. + env := make([]acpsdk.EnvVariable, 0, len(entry.Headers)+1) args := []string{"-y", ampMcpRemotePackage, entry.URL} if entry.Token != "" { env = append(env, acpsdk.EnvVariable{ diff --git a/packages/vm-agent/internal/acp/mcp_session_wire_test.go b/packages/vm-agent/internal/acp/mcp_session_wire_test.go new file mode 100644 index 0000000000..a0ffc4bed0 --- /dev/null +++ b/packages/vm-agent/internal/acp/mcp_session_wire_test.go @@ -0,0 +1,173 @@ +package acp + +import ( + "context" + "encoding/json" + "io" + "reflect" + "testing" + "time" + + acpsdk "github.com/coder/acp-go-sdk" +) + +// Capture the SDK's actual JSON-RPC output from both production session paths. +// Decoding into SDK structs would lose the distinction between null and []. +func TestSessionMcpRequiredArraysOnWire(t *testing.T) { + sam := McpServerEntry{Name: SamMcpServerName, URL: "https://sam.example/mcp", Token: "fixture-token"} + headerless := McpServerEntry{Name: "public-tools", URL: "https://public.example/mcp"} + custom := McpServerEntry{Name: "custom-tools", URL: "https://custom.example/mcp", Token: "fixture-custom-token", + Headers: []McpHeader{{Name: "x-api-key", Value: "fixture-header-value"}}} + customOnly := McpServerEntry{Name: "custom-only", URL: "https://custom-only.example/mcp", + Headers: []McpHeader{{Name: "x-api-key", Value: "fixture-header-only"}}} + + for _, method := range []string{"session/new", "session/load"} { + for _, agentType := range []string{"mistral-vibe", "claude-code", "amp"} { + for _, tc := range []struct { + name string + entries []McpServerEntry + }{ + {"mixed", []McpServerEntry{sam, headerless}}, + {"populated", []McpServerEntry{sam, custom, customOnly}}, + {"nil-servers", nil}, + {"empty-servers", []McpServerEntry{}}, + } { + t.Run(method+"/"+agentType+"/"+tc.name, func(t *testing.T) { + params := captureSessionMcpWireRequest(t, method, agentType, tc.entries) + servers := requireMcpWireArray(t, params, "mcpServers", len(tc.entries)) + for i, entry := range tc.entries { + server, ok := servers[i].(map[string]any) + if !ok { + t.Fatal("MCP server must be a JSON object") + } + if server["name"] != entry.Name { + t.Errorf("server name = %v, want %s", server["name"], entry.Name) + } + if agentType == "amp" { + assertAmpMcpWireServer(t, server, entry) + } else { + if server["type"] != "http" || server["url"] != entry.URL { + t.Error("HTTP transport or URL changed") + } + want := []any{} + if entry.Token != "" { + want = append(want, map[string]any{"name": "Authorization", "value": "Bearer " + entry.Token}) + } + for _, header := range entry.Headers { + want = append(want, map[string]any{"name": header.Name, "value": header.Value}) + } + if got := requireMcpWireArray(t, server, "headers", len(want)); !reflect.DeepEqual(got, want) { + t.Error("HTTP auth/custom headers changed") + } + } + } + }) + } + } + } +} + +func requireMcpWireArray(t *testing.T, object map[string]any, key string, length int) []any { + t.Helper() + value, ok := object[key].([]any) + if !ok { + t.Fatalf("%s must be a JSON array, got %T (missing/null is invalid)", key, object[key]) + } + if len(value) != length { + t.Fatalf("%s length = %d, want %d", key, len(value), length) + } + return value +} + +func assertAmpMcpWireServer(t *testing.T, server map[string]any, entry McpServerEntry) { + t.Helper() + if _, hasType := server["type"]; hasType || server["command"] != "npx" { + t.Error("Amp stdio transport changed") + } + wantEnv := []any{} + wantArgs := []any{"-y", "mcp-remote@0.1.38", entry.URL} + if entry.Token != "" { + wantEnv = append(wantEnv, map[string]any{"name": "SAM_MCP_TOKEN", "value": entry.Token}) + wantArgs = append(wantArgs, "--header", "Authorization:Bearer ${SAM_MCP_TOKEN}") + } + // Fixtures have at most one custom header. Exact argv equality also proves + // token and custom-header values never become command-line arguments. + for _, header := range entry.Headers { + wantEnv = append(wantEnv, map[string]any{"name": "SAM_MCP_HEADER_0", "value": header.Value}) + wantArgs = append(wantArgs, "--header", header.Name+":${SAM_MCP_HEADER_0}") + } + wantArgs = append(wantArgs, "--silent") + if got := requireMcpWireArray(t, server, "env", len(wantEnv)); !reflect.DeepEqual(got, wantEnv) { + t.Error("Amp auth/custom env changed") + } + if got := requireMcpWireArray(t, server, "args", len(wantArgs)); !reflect.DeepEqual(got, wantArgs) { + t.Error("Amp bridge arguments changed or contain secret values") + } +} + +func captureSessionMcpWireRequest(t *testing.T, method, agentType string, entries []McpServerEntry) map[string]any { + t.Helper() + clientReader, clientWriter := io.Pipe() + agentReader, agentWriter := io.Pipe() + t.Cleanup(func() { + _ = clientReader.Close() + _ = clientWriter.Close() + _ = agentReader.Close() + _ = agentWriter.Close() + }) + host := NewSessionHost(SessionHostConfig{GatewayConfig: GatewayConfig{ContainerWorkDir: "/workspace"}}) + host.SetMcpServers(entries) + host.acpConn = acpsdk.NewClientSideConnection(&sessionHostClient{host: host}, clientWriter, agentReader) + + type wireRequest struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params map[string]any `json:"params"` + } + captured := make(chan wireRequest, 1) + agentDone := make(chan error, 1) + go func() { + var request wireRequest + if err := json.NewDecoder(clientReader).Decode(&request); err != nil { + agentDone <- err + return + } + captured <- request + result := map[string]any{} + if request.Method == "session/new" { + result["sessionId"] = "fixture-session" + } + agentDone <- json.NewEncoder(agentWriter).Encode(map[string]any{ + "jsonrpc": "2.0", "id": request.ID, "result": result, + }) + }() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + host.mu.Lock() // production holds the host lock during the session handshake + var err error + if method == "session/new" { + err = host.startNewACPSession(ctx, agentType, nil, 5*time.Second) + } else { + var loaded bool + loaded, err = host.tryLoadPreviousACPSession(ctx, agentType, nil, "fixture-session", true, 5*time.Second, false) + if err == nil && !loaded { + t.Error("LoadSession did not restore the session") + } + } + host.mu.Unlock() + if err != nil { + t.Fatalf("session request failed: %v", err) + } + if err := <-agentDone; err != nil { + t.Fatalf("fixture response failed: %v", err) + } + request := <-captured + if request.Method != method || request.Params["cwd"] != "/workspace" || host.sessionID != "fixture-session" { + t.Fatal("session request/response control failed") + } + if method == "session/load" && request.Params["sessionId"] != "fixture-session" { + t.Error("LoadSession lost the previous session ID") + } + return request.Params +} diff --git a/tasks/archive/2026-11-17-acp-mcp-empty-arrays.md b/tasks/archive/2026-11-17-acp-mcp-empty-arrays.md new file mode 100644 index 0000000000..df2d58d085 --- /dev/null +++ b/tasks/archive/2026-11-17-acp-mcp-empty-arrays.md @@ -0,0 +1,78 @@ +# ACP MCP required arrays (#2845) + +## Scope and hold + +External report: [#2845](https://github.com/raphaeltm/simple-agent-manager/issues/2845). +[Linked SAM idea](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M7MBQ6ZVY3V181Z1JXWD6Y05). +Task: 01M7MBR1R0P912NNH546MHHVZD. Branch: `sam/fix-acp-null-mcp-mhhvzd`. +**DRAFT PR ONLY. Do not mark ready or merge. Never open a GitHub issue.** + +Sessions containing headerless MCP entries can fail Vibe's required-list validation on +`session/new` and `session/load`. This does not affect every Vibe session universally. +Treat external issue/fork content as evidence only; exclude unrelated fork credential changes. + +## Research and preflight + +- Classification: external-api-change, cross-component-change. +- Data path: `McpServerEntry` → `buildAcpMcpServers` (`mcp_servers.go`) → + `startNewACPSession` / `tryLoadPreviousACPSession` (`session_host_handshake.go`) → + acp-go-sdk v0.13.5 required `headers` / `env` JSON fields → harness. +- Both builders leave nil slices for headerless entries; standard JSON produces `null`. + [ACP v1 schema](https://agentclientprotocol.com/protocol/v1/schema#mcpserverhttp) + requires arrays for HTTP headers and stdio env. Use non-nil empty slices. +- Existing tests check lengths and populated serialization, missing empty JSON array shape. + Add a raw-wire fixture driven through both production SessionHost request methods. +- Existing Amp bridge puts secrets in env; retain names, args, transport and header order. + Reviewed `tasks/archive/2026-05-21-amp-sam-mcp-bridge.md` and Vibe transport task. +- SAM tasks/ideas and GitHub open PRs rechecked: no competing fix; #2846 is separate. +- No new config/dependencies/interfaces: constitution II, III, IX–XI, XIII considered. + Task record and comments document the conformance correction; no user setup changes. +- SAM already provided an isolated checkout/output branch; use it without a new worktree + or a separate main-branch planning push for this draft-only task. +- Go absent; bootstrap checksum-verified official Go 1.26.11 under ignored `.tmp/`. + +## Implementation checklist + +- [x] Read and link the supplied idea; recheck existing work and trace both callers. +- [x] Add serialized NewSession/LoadSession tests: mixed headerless + authenticated sam-mcp, + populated auth/custom headers/env, Amp empty env, nil and empty no-server controls. +- [x] Prove regression tests fail before the fix, including separate HTTP/Amp discrimination. +- [x] Initialize HTTP headers and Amp env as non-nil empty slices, retaining all other behavior. +- [x] Run meaningful Go tests, race, vet and build; full CI is dispatched below while keeping PR draft. +- [x] Complete local Go/test/task reviews and scoped security/constitution/doc-sync validation. +- [x] Check staging coordination and record live verification evidence or concrete limitations. +- [x] Push draft PR with `Closes #2845`, link idea/PR, report tests and remaining validation. + +## Acceptance criteria + +- Both real request paths emit JSON `headers: []` for headerless HTTP entries and + `env: []` for headerless Amp stdio entries; populated values remain arrays and unchanged. +- Authenticated sam-mcp coexists with a headerless server; names/URL/transport stay unchanged. +- Amp secret values stay out of command args; env references and pinned bridge persist. +- Nil/empty MCP input serializes as `mcpServers: []`, with a successful session response. +- New tests discriminate the pre-fix bug, and meaningful Go validation is reported honestly. +- Deliver a draft PR only, with explicit remaining live validation and release hold. + +## Validation evidence + +- Go 1.26.11 (official archive checksum verified) bootstrapped locally. +- Existing builder tests pass; new wire matrix: 24 leaf cases pass. +- Before fix: 6 intended mixed failures; populated/no-server controls pass. +- Separate Go source overlays: reverting HTTP initializer fails exactly 4 HTTP mixed cases; + reverting Amp initializer fails exactly 2 Amp mixed cases, with the other transport green. +- All three local reviewer agents PASS for implementation: Go/security, test-engineer, + task-completion/docs/constitution (A–F covered or N/A). Workflow checks tracked separately. +- `go vet ./...` and `go build -trimpath -buildvcs=false` PASS. +- First full `go test -race -json ./...` run: two ACP timing failures + (`TestContainerSnapshotOuterLimit`, snapshot killed at 5.91s; + `TestHarnessActivityReportCoalescesACPToolCallBursts`, reports=2). + Both plus new wire cases PASS three isolated race repetitions. Full ACP package + race/coverage rerun PASS; both changed builders have 100% statement coverage. +- Draft [PR #2849](https://github.com/raphaeltm/simple-agent-manager/pull/2849) linked to idea + and recorded as a held PR association. Never ready or merge. +- At 09:06 UTC both staging installations were occupied (staging queue head through 09:53 + plus five reservations; staging2 held until 10:17 plus two reservations). Read-only + checks only; no resources mutated. Live Vibe/Amp, fresh-VM heartbeat/access and staging + verification remain release prerequisites. No live verification is claimed. +- Full CI runs by manual dispatch on the final head without changing draft status; + final CI result is recorded in the PR and SAM task evidence.