Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
refactor(runtime): extract stdio JSON-RPC line read/write from runStdioMCP (#553)
fx-kurumi10c60b3caf12
diff --git a/internal/runtime/mcp_call.go b/internal/runtime/mcp_call.goindex cd965cd3..61608eff 100644--- a/internal/runtime/mcp_call.go+++ b/internal/runtime/mcp_call.go@@ -6,6 +6,7 @@ import ("context""encoding/json""fmt"+ "io""net/url""os""os/exec"@@ -621,41 +622,46 @@ func runStdioMCP(server mcpCallServer, method string, params any) (json.RawMessa}()scanner := bufio.NewScanner(stdout)scanner.Buffer(make([]byte, 64<<10), 4<<20)- write := func(value any) error {- raw, err := json.Marshal(value)- if err != nil {- return err- }- _, err = fmt.Fprintf(stdin, "%s\n", raw)- return err- }- read := func(id int64) (json.RawMessage, error) {- for scanner.Scan() {- var resp stdioRPCResponse- if json.Unmarshal(scanner.Bytes(), &resp) != nil || resp.ID != id {- continue- }- if resp.Error != nil {- return nil, fmt.Errorf("mcp error [%d]: %s", resp.Error.Code, resp.Error.Message)- }- return resp.Result, nil- }- if ctx.Err() != nil {- return nil, ctx.Err()- }- return nil, fmt.Errorf("stdio MCP exited before response: %s", strings.TrimSpace(stderr.String()))- }- if err := write(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "agentflow-script", "version": "1"}}}); err != nil {+ if err := writeStdioRPC(stdin, map[string]any{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "agentflow-script", "version": "1"}}}); err != nil {return nil, err}- if _, err := read(1); err != nil {+ if _, err := readStdioRPCResult(ctx, scanner, &stderr, 1); err != nil {return nil, fmt.Errorf("mcp init: %w", err)}- if err := write(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized", "params": map[string]any{}}); err != nil {+ if err := writeStdioRPC(stdin, map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized", "params": map[string]any{}}); err != nil {return nil, err}- if err := write(map[string]any{"jsonrpc": "2.0", "id": 2, "method": method, "params": params}); err != nil {+ if err := writeStdioRPC(stdin, map[string]any{"jsonrpc": "2.0", "id": 2, "method": method, "params": params}); err != nil {return nil, err}- return read(2)+ return readStdioRPCResult(ctx, scanner, &stderr, 2)+}++// writeStdioRPC writes one newline-delimited JSON-RPC message.+func writeStdioRPC(w io.Writer, value any) error {+ raw, err := json.Marshal(value)+ if err != nil {+ return err+ }+ _, err = fmt.Fprintf(w, "%s\n", raw)+ return err+}++// readStdioRPCResult scans stdout lines until the response with id arrives,+// skipping notifications, unparsable lines and responses to other requests.+func readStdioRPCResult(ctx context.Context, scanner *bufio.Scanner, stderr *bytes.Buffer, id int64) (json.RawMessage, error) {+ for scanner.Scan() {+ var resp stdioRPCResponse+ if json.Unmarshal(scanner.Bytes(), &resp) != nil || resp.ID != id {+ continue+ }+ if resp.Error != nil {+ return nil, fmt.Errorf("mcp error [%d]: %s", resp.Error.Code, resp.Error.Message)+ }+ return resp.Result, nil+ }+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }+ return nil, fmt.Errorf("stdio MCP exited before response: %s", strings.TrimSpace(stderr.String()))}diff --git a/internal/runtime/mcp_call_stdio_rpc_test.go b/internal/runtime/mcp_call_stdio_rpc_test.gonew file mode 100644index 00000000..30e1bf2c--- /dev/null+++ b/internal/runtime/mcp_call_stdio_rpc_test.go@@ -0,0 +1,64 @@+package runtime++import (+ "bufio"+ "bytes"+ "context"+ "errors"+ "strings"+ "testing"+)++func TestReadStdioRPCResultSkipsUnrelatedLines(t *testing.T) {+ lines := strings.Join([]string{+ "not json",+ `{"jsonrpc":"2.0","method":"notifications/message","params":{}}`,+ `{"jsonrpc":"2.0","id":1,"result":{"stale":true}}`,+ `{"jsonrpc":"2.0","id":2,"result":{"ok":true}}`,+ }, "\n")+ raw, err := readStdioRPCResult(context.Background(), bufio.NewScanner(strings.NewReader(lines)), &bytes.Buffer{}, 2)+ if err != nil {+ t.Fatalf("read: %v", err)+ }+ if string(raw) != `{"ok":true}` {+ t.Fatalf("result = %s", raw)+ }+}++func TestReadStdioRPCResultReturnsRPCError(t *testing.T) {+ line := `{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"method not found"}}`+ _, err := readStdioRPCResult(context.Background(), bufio.NewScanner(strings.NewReader(line)), &bytes.Buffer{}, 1)+ if err == nil || err.Error() != "mcp error [-32601]: method not found" {+ t.Fatalf("err = %v", err)+ }+}++func TestReadStdioRPCResultReportsExitWithStderr(t *testing.T) {+ stderr := bytes.NewBufferString(" boom: missing token \n")+ _, err := readStdioRPCResult(context.Background(), bufio.NewScanner(strings.NewReader("")), stderr, 1)+ if err == nil || err.Error() != "stdio MCP exited before response: boom: missing token" {+ t.Fatalf("err = %v", err)+ }+}++func TestReadStdioRPCResultPrefersContextError(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ _, err := readStdioRPCResult(ctx, bufio.NewScanner(strings.NewReader("")), bytes.NewBufferString("ignored"), 1)+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("err = %v", err)+ }+}++func TestWriteStdioRPCWritesOneLine(t *testing.T) {+ var out bytes.Buffer+ if err := writeStdioRPC(&out, map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}); err != nil {+ t.Fatalf("write: %v", err)+ }+ if got := out.String(); got != `{"id":2,"jsonrpc":"2.0","method":"tools/list"}`+"\n" {+ t.Fatalf("output = %q", got)+ }+ if err := writeStdioRPC(&out, map[string]any{"bad": make(chan int)}); err == nil {+ t.Fatal("expected marshal error")+ }+}