Skip to content

Agent Mesh

fix: restore local SSE/POST ingress for command backends, trim comments

Fernando Marino0f40c806c0bb
diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.go
index 28e559d3..0b71bc2c 100644
--- a/internal/node/mcp_service.go
+++ b/internal/node/mcp_service.go
@@ -77,32 +77,13 @@ func (m *MCPService) Teardown() error {
}
// backendTransport builds a fresh MCP transport to this service's backend.
-//
-// A command backend gets its own subprocess, via mcp.CommandTransport, for
-// every call - the same "one fresh transport per session" shape as the URL
-// case, not a shared one. An earlier version of this multiplexed every
-// session for a command backend over one child process and one stdout
-// stream (StdioBridge/bridgeTransport, since deleted): every line
-// broadcast to every subscriber, relying on each session's own JSON-RPC id
-// to sort out which reply was whose. That doesn't hold - the go-sdk client
-// numbers requests from 1 per connection, so two concurrent sessions on the
-// same bridge could both send id:1 and each read the other's reply, not
-// just their own. Fixing the multiplexer to not do that (id rewriting, a
-// bridge-wide id space) is exactly the kind of protocol-level code this
-// package shouldn't own: stdio MCP is single-session by spec, and no SDK
-// multiplexes it, because a server-initiated request (sampling,
-// elicitation) has no attributable destination on a shared process. One
-// subprocess per session sidesteps all of it by construction, matching
-// what backendTransport already does for URL backends.
-//
-// The cost is a fresh process per Probe/Tools call and per mesh stream
-// instead of one long-lived one; command backends with slow startup pay
-// that repeatedly. Command backends also lose the local SSE/POST HTTP
-// ingress route StdioBridge.ServeHTTP used to provide (baseService.Init
-// no longer builds a handler for them) - the mesh stream path
-// (HandleStreamPassThrough) is what actually matters and is unaffected;
-// restoring a local-ingress equivalent is left for later, not folded into
-// this change.
+// Command backends get their own subprocess per call (mcp.CommandTransport),
+// not a shared one: the go-sdk client numbers requests from 1 per
+// connection, so a shared process risked one session reading another's
+// reply. Stdio MCP is single-session by spec, so this mirrors the URL
+// case's fresh-transport-per-session shape rather than giving the bridge a
+// per-session id space. Cost: a fresh process per call instead of one
+// long-lived one, so slow-starting backends pay startup repeatedly.
func (m *MCPService) backendTransport() (mcp.Transport, error) {
switch x := m.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
diff --git a/internal/node/mcp_service_command_test.go b/internal/node/mcp_service_command_test.go
index 6d6a5028..a5858c4c 100644
--- a/internal/node/mcp_service_command_test.go
+++ b/internal/node/mcp_service_command_test.go
@@ -28,13 +28,10 @@ import (
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
)
-// TestEchoHelperProcess is not a real test: it's a subprocess entry point
-// (exec.Command(os.Args[0], "-test.run=...") self-re-exec, the same pattern
-// TestStartRenewalLoop_ExpiredAndFails in node_test.go uses), standing in
-// for a real command-spawned MCP backend. For every JSON-RPC line with an
-// "id" it reads on stdin, it echoes back a minimal success response on
-// stdout, tagged with its own PID so a test can tell which subprocess
-// answered.
+// TestEchoHelperProcess is a subprocess entry point (self-re-exec, as
+// node_test.go's TestStartRenewalLoop_ExpiredAndFails does), standing in
+// for a command-backed MCP server. It echoes each JSON-RPC call's id back
+// tagged with its own PID, so a test can tell which subprocess answered.
func TestEchoHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_ECHO_HELPER") != "1" {
return
@@ -82,15 +79,9 @@ func newEchoCommandMCPService(t *testing.T) *MCPService {
}
}
-// TestMCPService_BackendTransport_CommandBackendUsesSeparateSubprocess
-// pins the property the StdioBridge/bridgeTransport removal exists for:
-// backendTransport gives every caller of a command backend its own
-// subprocess, so two "sessions" that both happen to number their first
-// request id:1 - exactly what the go-sdk client does per connection -
-// each get their own reply, never the other's. Under the old shared-bridge
-// design this was a real, silent cross-session data leak (see the comment
-// on backendTransport); under the current one it can't happen, because
-// there is no shared process or id space to collide in.
+// Two calls, both sending id:1, must be answered by two different
+// subprocesses - not one shared one, which is how session A used to be
+// able to read session B's reply.
func TestMCPService_BackendTransport_CommandBackendUsesSeparateSubprocess(t *testing.T) {
m := newEchoCommandMCPService(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -141,15 +132,8 @@ func TestMCPService_BackendTransport_CommandBackendUsesSeparateSubprocess(t *tes
}
}
-// TestMCPService_BackendTransport_ConcurrentCallsDoNotCrossTalk drives two
-// concurrent connections through backendTransport at the same time, both
-// sending id:1 first the way independent go-sdk client sessions naturally
-// would, and asserts each connection's Read only ever returns its own
-// subprocess's reply. This is the direct regression test for the bug a
-// shared-process design has and a per-session one cannot: session A
-// silently consuming session B's reply because both used the same
-// JSON-RPC id on a process whose replies were broadcast to every
-// subscriber.
+// Same check under concurrency: two sessions running at once, each always
+// sending id:1, must never see a reply that isn't theirs.
func TestMCPService_BackendTransport_ConcurrentCallsDoNotCrossTalk(t *testing.T) {
m := newEchoCommandMCPService(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
diff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.go
index 4a4b5cb0..1bc33ef2 100644
--- a/internal/node/proxy_test.go
+++ b/internal/node/proxy_test.go
@@ -15,6 +15,8 @@
package node
import (
+ "bufio"
+ "bytes"
"context"
"crypto/ed25519"
"crypto/rand"
@@ -24,6 +26,7 @@ import (
"net/http/httptest"
"net/http/httputil"
"net/url"
+ "strings"
"testing"
"time"
@@ -396,17 +399,196 @@ func TestDatapathIntegration_Unauthenticated(t *testing.T) {
}
}
-// TestStdioDatapathIntegration exercised the local SSE/POST HTTP ingress
-// route for command backends (StdioBridge.ServeHTTP, reached via
-// baseService.Handler()). That route was removed along with
-// StdioBridge/bridgeTransport when command backends moved to a fresh
-// mcp.CommandTransport subprocess per session instead of multiplexing
-// every session over one shared stdio pipe - see the comment on
-// MCPService.backendTransport for why. The mesh stream path this test
-// did not cover (HandleStreamPassThrough, exercised by
-// TestDatapathIntegration above) is unaffected. Restoring a local-ingress
-// equivalent for command backends is left for a follow-up, not folded
-// into that change.
+func TestStdioDatapathIntegration(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ // 1. Setup: Create two in-memory nodes (Node A and Node B)
+ privA, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ privB, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+
+ dirA := t.TempDir()
+ dirB := t.TempDir()
+
+ storeA, err := NewStore(dirA)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = storeA.Close() }()
+
+ storeB, err := NewStore(dirB)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = storeB.Close() }()
+
+ nodeA, err := NewSamNode(Options{
+ PrivKey: privA,
+ RouterAddrs: nil,
+ Store: storeA,
+ MeshID: "test-mesh",
+ DiscoveryInterval: "1s",
+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
+ EnableRelay: false,
+ NodeConfig: &NodeConfigComplete{},
+ KeyGracePeriod: 24 * time.Hour,
+ AllowLoopback: true,
+ MonitorBootstrap: 2 * time.Minute,
+ MonitorInterval: 1 * time.Minute,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodeA.BiscuitTimeout = 500 * time.Millisecond
+ if err := nodeA.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = nodeA.Host.Close() }()
+
+ nodeB, err := NewSamNode(Options{
+ PrivKey: privB,
+ RouterAddrs: nil,
+ Store: storeB,
+ MeshID: "test-mesh",
+ DiscoveryInterval: "1s",
+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
+ EnableRelay: false,
+ NodeConfig: &NodeConfigComplete{},
+ KeyGracePeriod: 24 * time.Hour,
+ AllowLoopback: true,
+ MonitorBootstrap: 2 * time.Minute,
+ MonitorInterval: 1 * time.Minute,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodeB.BiscuitTimeout = 500 * time.Millisecond
+ if err := nodeB.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = nodeB.Host.Close() }()
+
+ // Setup identity for Node B (the caller proxy) and trust it on Node A
+ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("gen root: %v", err)
+ }
+ if err := buildAndSaveBiscuit(nodeB, rootPriv); err != nil {
+ t.Fatalf("buildAndSaveBiscuit: %v", err)
+ }
+ nodeA.keysMu.Lock()
+ nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeA.keysMu.Unlock()
+
+ // Connect Node B to Node A directly
+ err = nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // 2. Target Service: Register a stdio service on Node A using 'cat'
+ serviceName := "stdio-tool"
+ serviceInfo := &api.ServiceInfo{
+ Type: api.ServiceType_SERVICE_TYPE_MCP,
+ Name: serviceName,
+ }
+
+ req := &api.RegisterServiceRequest{
+ Service: serviceInfo,
+ Backend: &api.RegisterServiceRequest_Command{
+ Command: &api.CommandBackend{
+ Command: []string{"cat"},
+ },
+ },
+ }
+
+ // Manually add to services map to ensure it's registered for the test lookup
+ // and avoid double start by not calling RegisterService.
+ handler, cmd, err := createStdioBridgeHandler(req.Backend.(*api.RegisterServiceRequest_Command).Command)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodeA.services.insertService(&testService{
+ info: serviceInfo,
+ handler: handler,
+ })
+
+ defer func() {
+ _ = nodeA.UnregisterService(ctx, serviceName)
+ if cmd != nil && cmd.Process != nil {
+ _ = cmd.Process.Kill()
+ }
+ }()
+
+ // Start the Sidecar server for Node B to get BoundHTTPAddr populated
+ nodeB.BoundHTTPAddr = "127.0.0.1:0" // Dummy
+
+ // 3. Execution: Node B makes requests via its local Egress Proxy
+ proxyHandler := createEgressProxy(nodeB)
+ proxyServer := httptest.NewServer(proxyHandler)
+ defer proxyServer.Close()
+
+ // Construct URLs
+ // http://localhost:<port>/sam/{peer_id}/{service_type}/{service_name}/{upstream_path}
+ sseURL := fmt.Sprintf("%s/sam/%s/mcp/%s/", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
+ postURL := fmt.Sprintf("%s/sam/%s/mcp/%s/", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
+
+ client := &http.Client{}
+
+ // Wait for DHT/routing to settle (retry mechanism)
+ var sseResp *http.Response
+ for i := 0; i < 3; i++ {
+ sseResp, err = client.Get(sseURL)
+ if err == nil && sseResp.StatusCode == http.StatusOK {
+ break
+ }
+ t.Logf("SSE Connect Attempt %d failed: %v, status: %v", i+1, err, sseResp)
+ time.Sleep(1 * time.Second)
+ }
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = sseResp.Body.Close() }()
+
+ if sseResp.StatusCode != http.StatusOK {
+ t.Fatalf("Expected SSE status OK, got %d", sseResp.StatusCode)
+ }
+
+ // Send a message via POST
+ testMessage := `{"jsonrpc":"2.0","method":"ping","id":1}`
+ postResp, err := client.Post(postURL, "application/json", bytes.NewBufferString(testMessage))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = postResp.Body.Close() }()
+
+ if postResp.StatusCode != http.StatusOK {
+ t.Fatalf("Expected POST status OK, got %d", postResp.StatusCode)
+ }
+
+ // Read from SSE stream
+ reader := bufio.NewReader(sseResp.Body)
+ line, err := reader.ReadString('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ expectedPrefix := "data: "
+ if !strings.HasPrefix(line, expectedPrefix) {
+ t.Fatalf("Expected line to start with %q, got %q", expectedPrefix, line)
+ }
+
+ receivedMessage := strings.TrimPrefix(line, expectedPrefix)
+ receivedMessage = strings.TrimSpace(receivedMessage)
+
+ if receivedMessage != testMessage {
+ t.Fatalf("Expected to receive %q, got %q", testMessage, receivedMessage)
+ }
+
+ // Cancel context to close the SSE stream and allow server to close gracefully
+ cancel()
+}
func TestDatapathHeadersAndRoutingTable(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
diff --git a/internal/node/service.go b/internal/node/service.go
index 976b8db3..6315247e 100644
--- a/internal/node/service.go
+++ b/internal/node/service.go
@@ -20,6 +20,7 @@ import (
"net/http"
"net/http/httputil"
"net/url"
+ "os/exec"
"strings"
"github.com/google/sam/api"
@@ -44,6 +45,7 @@ type baseService struct {
info *api.ServiceInfo
backend any
handler http.Handler
+ cmd *exec.Cmd // command backend's ServeHTTP-backing process; nil otherwise
}
// newReverseProxyHandler builds a single-host reverse-proxy handler for a
@@ -84,13 +86,10 @@ func newReverseProxyHandler(targetURL string) (http.Handler, error) {
func (b *baseService) Info() *api.ServiceInfo { return b.info }
func (b *baseService) Handler() http.Handler { return b.handler }
-// Init builds the ingress handler for the backend. URL -> reverse-proxy.
-// A command backend gets no handler here: MCPService.backendTransport
-// gives each session its own subprocess instead of one shared one this
-// type would otherwise have to own and tear down - see the comment there.
-// b.handler stays nil, which Handler()'s callers already treat as "no
-// local HTTP ingress for this service" (a 404), not a crash.
-// MCPService extends this; it does not replace it.
+// Init builds the ingress handler for the backend: URL -> reverse-proxy,
+// Command -> StdioBridge (the local SSE/POST HTTP route only - mesh
+// sessions get their own subprocess via MCPService.backendTransport
+// instead of this one). MCPService extends this; it does not replace it.
func (b *baseService) Init(ctx context.Context) error {
switch x := b.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
@@ -100,18 +99,24 @@ func (b *baseService) Init(ctx context.Context) error {
}
b.handler = h
case *api.RegisterServiceRequest_Command:
- // No handler, no eagerly-spawned process.
+ h, cmd, err := createStdioBridgeHandler(x.Command)
+ if err != nil {
+ return err
+ }
+ b.handler = h
+ b.cmd = cmd
default:
return fmt.Errorf("unsupported backend type %T", b.backend)
}
return nil
}
-// Teardown is a no-op: a URL backend owns nothing here, and a command
-// backend's subprocesses are each spawned and closed by their own session
-// (see MCPService.backendTransport), not held at the service level.
+// Teardown kills the command backend's process, if any.
func (b *baseService) Teardown() error {
- return nil
+ if b.cmd == nil || b.cmd.Process == nil {
+ return nil
+ }
+ return b.cmd.Process.Kill()
}
func NewServiceFromRequest(req *api.RegisterServiceRequest) (Service, error) {
diff --git a/internal/node/service_test.go b/internal/node/service_test.go
index 1beb1486..d45a6134 100644
--- a/internal/node/service_test.go
+++ b/internal/node/service_test.go
@@ -53,6 +53,9 @@ func TestBaseService_InitURLBackend_BuildsReverseProxy(t *testing.T) {
if _, ok := b.handler.(*httputil.ReverseProxy); !ok {
t.Fatalf("handler type: got %T, want *httputil.ReverseProxy", b.handler)
}
+ if b.cmd != nil {
+ t.Errorf("cmd should be nil for URL backend, got %v", b.cmd)
+ }
if err := b.Teardown(); err != nil {
t.Errorf("Teardown: %v", err)
}
@@ -68,13 +71,7 @@ func TestBaseService_InitURLBackend_InvalidURL(t *testing.T) {
}
}
-// TestBaseService_InitCommandBackend_NoLocalHandler pins the deliberate
-// trade-off in Init's Command case: no process is spawned and no handler is
-// built here, because MCPService.backendTransport gives each session (a
-// Probe, a Tools call, a mesh stream) its own subprocess instead - see the
-// comment there. A nil command doesn't even need to be valid, since Init no
-// longer tries to run it.
-func TestBaseService_InitCommandBackend_NoLocalHandler(t *testing.T) {
+func TestBaseService_InitCommandBackend_BuildsBridge(t *testing.T) {
b := &baseService{
info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "demo"},
backend: &api.RegisterServiceRequest_Command{
@@ -85,8 +82,11 @@ func TestBaseService_InitCommandBackend_NoLocalHandler(t *testing.T) {
t.Fatalf("Init: %v", err)
}
defer func() { _ = b.Teardown() }()
- if b.handler != nil {
- t.Fatalf("handler: got %T, want nil", b.handler)
+ if _, ok := b.handler.(*StdioBridge); !ok {
+ t.Fatalf("handler type: got %T, want *StdioBridge", b.handler)
+ }
+ if b.cmd == nil {
+ t.Error("cmd should be non-nil for Command backend")
}
}
diff --git a/internal/node/stdio_bridge.go b/internal/node/stdio_bridge.go
new file mode 100644
index 00000000..be9a17ee
--- /dev/null
+++ b/internal/node/stdio_bridge.go
@@ -0,0 +1,235 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "sync"
+
+ "github.com/google/sam/api"
+)
+
+// StdioBridge backs the local SSE/POST HTTP ingress route for a
+// command-backed service (registered via baseService.Init). It is not used
+// for mesh sessions - see MCPService.backendTransport, which gives those
+// their own subprocess instead of sharing this one.
+type StdioBridge struct {
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ stdout io.ReadCloser
+ mu sync.Mutex
+ clients map[chan string]bool
+ calls map[string]chan string
+}
+
+func (b *StdioBridge) Start() {
+ b.clients = make(map[chan string]bool)
+ b.calls = make(map[string]chan string)
+ go func() {
+ scanner := bufio.NewScanner(b.stdout)
+ for scanner.Scan() {
+ line := scanner.Text()
+
+ b.mu.Lock()
+ if len(line) > 0 && line[0] == '{' {
+ var msg map[string]any
+ if err := json.Unmarshal([]byte(line), &msg); err == nil {
+ if idVal, ok := msg["id"]; ok {
+ reqIDStr := fmt.Sprintf("%v", idVal)
+ if ch, found := b.calls[reqIDStr]; found {
+ select {
+ case ch <- line:
+ default:
+ }
+ }
+ }
+ }
+ }
+
+ for ch := range b.clients {
+ select {
+ case ch <- line:
+ default:
+ }
+ }
+ b.mu.Unlock()
+ }
+
+ b.mu.Lock()
+ for ch := range b.clients {
+ close(ch)
+ delete(b.clients, ch)
+ }
+ for _, ch := range b.calls {
+ close(ch)
+ }
+ b.calls = make(map[string]chan string)
+ b.mu.Unlock()
+ }()
+}
+
+func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
+ return
+ }
+
+ ch := make(chan string, 10)
+ b.mu.Lock()
+ b.clients[ch] = true
+ b.mu.Unlock()
+
+ // Flush headers immediately to establish the stream
+ w.WriteHeader(http.StatusOK)
+ flusher.Flush()
+
+ defer func() {
+ b.mu.Lock()
+ delete(b.clients, ch)
+ b.mu.Unlock()
+ close(ch)
+ }()
+
+ ctx := r.Context()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case line, ok := <-ch:
+ if !ok {
+ return
+ }
+ if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
+ logger.Errorf("Failed to write to SSE client: %v", err)
+ return
+ }
+ flusher.Flush()
+ }
+ }
+ case http.MethodPost:
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ defer func() { _ = r.Body.Close() }()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read body", http.StatusInternalServerError)
+ return
+ }
+
+ var msg map[string]any
+ isCall := false
+ var reqID any
+ if err := json.Unmarshal(body, &msg); err == nil {
+ if id, ok := msg["id"]; ok {
+ isCall = true
+ reqID = id
+ }
+ }
+
+ var ch <-chan string
+ var unsub func()
+ if isCall {
+ reqIDStr := fmt.Sprintf("%v", reqID)
+ callCh := make(chan string, 1)
+ b.mu.Lock()
+ b.calls[reqIDStr] = callCh
+ b.mu.Unlock()
+ ch = callCh
+ unsub = func() {
+ b.mu.Lock()
+ if existing, ok := b.calls[reqIDStr]; ok && existing == callCh {
+ delete(b.calls, reqIDStr)
+ close(callCh)
+ }
+ b.mu.Unlock()
+ }
+ defer unsub()
+ }
+
+ b.mu.Lock()
+ _, err = b.stdin.Write(append(body, '\n'))
+ b.mu.Unlock()
+
+ if err != nil {
+ http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Mcp-Session-Id", "stdio-bridge")
+
+ if !isCall {
+ w.WriteHeader(http.StatusAccepted)
+ return
+ }
+
+ ctx := r.Context()
+ select {
+ case <-ctx.Done():
+ return
+ case line, ok := <-ch:
+ if !ok {
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(line))
+ return
+ }
+ default:
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
+func createStdioBridgeHandler(cmdBackend *api.CommandBackend) (http.Handler, *exec.Cmd, error) {
+ cmd := exec.Command(cmdBackend.Command[0], cmdBackend.Command[1:]...)
+ cmd.Env = os.Environ()
+ for k, v := range cmdBackend.Env {
+ cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
+ }
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, nil, err
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if err := cmd.Start(); err != nil {
+ return nil, nil, err
+ }
+
+ bridge := &StdioBridge{
+ cmd: cmd,
+ stdin: stdin,
+ stdout: stdout,
+ }
+ bridge.Start()
+
+ return bridge, cmd, nil
+}
diff --git a/internal/node/stdio_bridge_test.go b/internal/node/stdio_bridge_test.go
new file mode 100644
index 00000000..e29cbbed
--- /dev/null
+++ b/internal/node/stdio_bridge_test.go
@@ -0,0 +1,122 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// newPipeBridge returns a StdioBridge wired to two in-memory pipes so tests
+// can drive stdin/stdout without a real subprocess.
+func newPipeBridge() (*StdioBridge, *io.PipeWriter, *bytes.Buffer) {
+ stdoutReader, stdoutWriter := io.Pipe()
+ stdinBuf := &bytes.Buffer{}
+ b := &StdioBridge{
+ stdin: nopWriteCloser{stdinBuf},
+ stdout: stdoutReader,
+ }
+ b.Start()
+ return b, stdoutWriter, stdinBuf
+}
+
+type nopWriteCloser struct{ io.Writer }
+
+func (nopWriteCloser) Close() error { return nil }
+
+func TestStdioBridge_ServeHTTP_GETStreamsBroadcastLines(t *testing.T) {
+ b, stdoutWriter, _ := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
+ rec := httptest.NewRecorder()
+ done := make(chan struct{})
+ go func() {
+ b.ServeHTTP(rec, req)
+ close(done)
+ }()
+
+ // Give the handler a moment to register as a client before writing.
+ time.Sleep(50 * time.Millisecond)
+ _, _ = stdoutWriter.Write([]byte("hello\n"))
+ time.Sleep(50 * time.Millisecond)
+ cancel()
+
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("ServeHTTP did not return after ctx was cancelled")
+ }
+
+ if got := rec.Body.String(); !strings.Contains(got, "data: hello\n\n") {
+ t.Fatalf("SSE body = %q, want it to contain %q", got, "data: hello\n\n")
+ }
+}
+
+func TestStdioBridge_ServeHTTP_POSTNotificationReturnsAccepted(t *testing.T) {
+ b, stdoutWriter, stdinBuf := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ body := `{"jsonrpc":"2.0","method":"notify"}`
+ req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
+ rec := httptest.NewRecorder()
+ b.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusAccepted {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusAccepted)
+ }
+ if got := stdinBuf.String(); got != body+"\n" {
+ t.Fatalf("stdin got %q, want %q", got, body+"\n")
+ }
+}
+
+func TestStdioBridge_ServeHTTP_POSTCallWaitsForMatchingReply(t *testing.T) {
+ b, stdoutWriter, _ := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ body := `{"jsonrpc":"2.0","id":1,"method":"ping"}`
+ req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
+ rec := httptest.NewRecorder()
+
+ done := make(chan struct{})
+ go func() {
+ b.ServeHTTP(rec, req)
+ close(done)
+ }()
+
+ time.Sleep(50 * time.Millisecond)
+ reply := `{"jsonrpc":"2.0","id":1,"result":{}}`
+ _, _ = stdoutWriter.Write([]byte(reply + "\n"))
+
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("ServeHTTP did not return after the matching reply arrived")
+ }
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
+ }
+ if got := rec.Body.String(); got != reply {
+ t.Fatalf("body = %q, want %q", got, reply)
+ }
+}