From 92c6b57394cc921ca3fcdd52cced0b8ef80a024e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 02:08:02 -0600 Subject: [PATCH 1/2] Fix Roc client wire semantics Roc now emits original JSON wire keys and values, omits absent optional arguments, encodes empty arguments as {}, and propagates daemon and tool errors. Include MCPX_RUN and bearer auth in requests. The dry-run regression caught that omitting x-mcpx-run lets a dispatched Roc call lack the run identity needed for safe interception. Resolve Roc through a flake devshell when it is unavailable on the host PATH. Closes #12466 --- pkgs/mcpx/internal/codegen/roc.go | 106 +++++++++++++++++++++---- pkgs/mcpx/internal/codegen/roc_test.go | 22 ++--- pkgs/mcpx/internal/runner/dispatch.go | 8 +- pkgs/mcpx/internal/runner/language.go | 8 +- pkgs/mcpx/internal/runner/roc_test.go | 70 ++++++++++++++-- 5 files changed, 179 insertions(+), 35 deletions(-) diff --git a/pkgs/mcpx/internal/codegen/roc.go b/pkgs/mcpx/internal/codegen/roc.go index 955d6d342f..69f5fd1cec 100644 --- a/pkgs/mcpx/internal/codegen/roc.go +++ b/pkgs/mcpx/internal/codegen/roc.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "sort" + "strconv" "strings" ) @@ -28,20 +29,58 @@ func RocModule(nss []Namespace, endpoint, session string) string { // written as Mcpx.roc, so define the matching top-level type. b.WriteString("Mcpx := {}\n\n") b.WriteString("import pf.Http\nimport pf.Env\nimport http.Method\nimport http.Request\nimport http.Response\n\n") - b.WriteString("ToolError := [TransportError(Str), StatusError(U16)]\n\n") + b.WriteString("ToolError := [TransportError(Str), StatusError(U16), DaemonError(Str), ToolResultError(Str), EncodingError(Str)]\n\n") fmt.Fprintf(&b, "default_endpoint = %s\ndefault_session = %s\n\n", rocString(endpoint), rocString(session)) b.WriteString("call! : Str => Try(Response.Response, ToolError)\n") b.WriteString("call! = |body| {\n") b.WriteString(" endpoint = match Env.var_str!(\"MCPX_ENDPOINT\") {\n Ok(value) => value\n Err(_) => default_endpoint\n }\n") b.WriteString(" session = match Env.var_str!(\"MCPX_SESSION\") {\n Ok(value) => value\n Err(_) => default_session\n }\n") - b.WriteString(" request = Request.from_method(Method.POST)\n .with_uri(Str.concat(endpoint, \"/v1/call\"))\n .with_body(Str.to_utf8(body))\n .add_header(\"Content-Type\", \"application/json\")\n .add_header(\"x-mcpx-session\", session)\n .add_header(\"x-mcpx-call\", session)\n") - b.WriteString(" response = Http.send!(request, {}) ? |_err| TransportError(\"mcpx daemon request failed\")\n") - b.WriteString(" if Response.status(response) < 200 or Response.status(response) >= 300 {\n return Err(StatusError(Response.status(response)))\n }\n Ok(response)\n}\n\n") + b.WriteString(" token = match Env.var_str!(\"MCPX_TRANSPORT_BEARER_TOKEN\") {\n Ok(value) => value\n Err(_) => \"\"\n }\n") + b.WriteString(" run = match Env.var_str!(\"MCPX_RUN\") {\n Ok(value) => value\n Err(_) => \"\"\n }\n") + b.WriteString(" request = Request.from_method(Method.POST)\n .with_uri(Str.concat(endpoint, \"/v1/call\"))\n .with_body(Str.to_utf8(body))\n .add_header(\"Content-Type\", \"application/json\")\n .add_header(\"x-mcpx-session\", session)\n .add_header(\"x-mcpx-call\", session)\n .add_header(\"x-mcpx-run\", run)\n") + b.WriteString(" authenticated_request = if token == \"\" { request } else { request.add_header(\"Authorization\", Str.concat(\"Bearer \", token)) }\n") + b.WriteString(" response = Http.send!(authenticated_request, {}) ? |_err| TransportError(\"mcpx daemon request failed\")\n") + b.WriteString(" if Response.status(response) < 200 or Response.status(response) >= 300 {\n return Err(StatusError(Response.status(response)))\n }\n") + b.WriteString(" response_text = Str.from_utf8(Response.body(response)) ? |_err| TransportError(\"mcpx daemon returned invalid UTF-8\")\n") + b.WriteString(" envelope : Try({ error ?: Str, result ?: { isError ?: Bool, content ?: List({ type : Str, text ?: Str }) } }, _)\n") + b.WriteString(" envelope = Json.parse(response_text)\n") + b.WriteString(" match envelope {\n Err(_) => Err(DaemonError(\"mcpx daemon returned invalid JSON\"))\n Ok(value) => match value.?error {\n Ok(message) => Err(DaemonError(message))\n Err(_) => match value.?result {\n Ok(result) => match result.?isError {\n Ok(is_error) => if is_error {\n blocks = match result.?content {\n Ok(content) => List.keep_oks(content, |block| block.?text)\n Err(_) => []\n }\n message = if List.is_empty(blocks) { \"tool returned isError\" } else { Str.join_with(blocks, \"\\n\") }\n Err(ToolResultError(message))\n } else { Ok(response) }\n Err(_) => Ok(response)\n }\n Err(_) => Ok(response)\n }\n }\n }\n}\n\n") for _, fn := range functions { - fmt.Fprintf(&b, "%s! : { %s } => Try(Response.Response, ToolError)\n", fn.name, strings.Join(fn.fields, ", ")) - fmt.Fprintf(&b, "%s! = |args| {\n", fn.name) - fmt.Fprintf(&b, " payload = { server: %s, tool: %s, args }\n", rocString(fn.server), rocString(fn.tool)) - b.WriteString(" body = Json.to_str_try(payload) ? |_err| TransportError(\"mcpx request encoding failed\")\n call!(body)\n}\n\n") + argType := "{ " + strings.Join(fn.fields, ", ") + " }" + argName := "args" + if len(fn.args) == 0 { + argType = "{}" + argName = "_args" + } + where := "" + if len(fn.genericTypes) > 0 { + constraints := make([]string, len(fn.genericTypes)) + for i, generic := range fn.genericTypes { + constraints[i] = generic + ".Json.Encodable(_)" + } + where = " where [" + strings.Join(constraints, ", ") + "]" + } + fmt.Fprintf(&b, "%s! : %s => Try(Response.Response, ToolError)%s\n", fn.name, argType, where) + fmt.Fprintf(&b, "%s! = |%s| {\n", fn.name, argName) + if len(fn.args) == 0 { + b.WriteString(" args_json = \"{}\"\n") + } else { + b.WriteString(" arg_fields = [\n") + } + for _, field := range fn.args { + key, _ := json.Marshal(field.wireName) + if field.optional { + fmt.Fprintf(&b, " match args.?%s {\n Ok(value) => {\n encoded = Json.to_str_try(value) ? |_err| EncodingError(\"mcpx argument encoding failed\")\n Ok(Str.concat(%s, Str.concat(\":\", encoded)))\n }\n Err(_) => Ok(\"\")\n },\n", field.name, strconv.Quote(string(key))) + } else { + fmt.Fprintf(&b, " {\n encoded = Json.to_str_try(args.%s) ? |_err| EncodingError(\"mcpx argument encoding failed\")\n Ok(Str.concat(%s, Str.concat(\":\", encoded)))\n },\n", field.name, strconv.Quote(string(key))) + } + } + if len(fn.args) > 0 { + b.WriteString(" ]\n encoded_fields = List.map_try(arg_fields, |entry| entry) ? |_err| EncodingError(\"mcpx argument encoding failed\")\n present_fields = List.keep_if(encoded_fields, |entry| entry != \"\")\n args_json = Str.concat(\"{\", Str.concat(Str.join_with(present_fields, \",\"), \"}\"))\n") + } + fmt.Fprintf(&b, " server_json = Json.to_str_try(%s) ? |_err| EncodingError(\"mcpx request encoding failed\")\n", rocString(fn.server)) + fmt.Fprintf(&b, " tool_json = Json.to_str_try(%s) ? |_err| EncodingError(\"mcpx request encoding failed\")\n", rocString(fn.tool)) + b.WriteString(" body = Str.concat(\"{\\\"server\\\":\", Str.concat(server_json, Str.concat(\",\\\"tool\\\":\", Str.concat(tool_json, Str.concat(\",\\\"args\\\":\", Str.concat(args_json, \"}\"))))))\n call!(body)\n}\n\n") } return b.String() } @@ -49,6 +88,13 @@ func RocModule(nss []Namespace, endpoint, session string) string { type rocFunction struct { name, server, tool string fields []string + args []rocArgument + genericTypes []string +} + +type rocArgument struct { + name, wireName, rocType string + optional bool } func rocFunctions(nss []Namespace) []rocFunction { @@ -59,18 +105,29 @@ func rocFunctions(nss []Namespace) []rocFunction { for _, ns := range sorted { for _, tool := range sortedTools(ns) { name := uniqueRocIdent(rocIdent(ns.Name+"_"+tool.Name, false), usedNames) - fields := rocInputFields(tool.InputSchema) + fields, args := rocInputFields(tool.InputSchema) + var generics []string + for i := range args { + if args[i].rocType == "" { + args[i].rocType = string(rune('a' + len(generics))) + generics = append(generics, args[i].rocType) + for j := range fields { + fields[j] = strings.Replace(fields[j], "__GENERIC_"+args[i].name+"__", args[i].rocType, 1) + } + } + } out = append(out, rocFunction{ name: name, server: ns.Server, - tool: tool.Name, fields: fields, + tool: tool.Name, fields: fields, args: args, genericTypes: generics, }) } } return out } -func rocInputFields(raw json.RawMessage) []string { +func rocInputFields(raw json.RawMessage) ([]string, []rocArgument) { var schema struct { + Required []string `json:"required"` Properties map[string]struct { Type string `json:"type"` } `json:"properties"` @@ -82,9 +139,14 @@ func rocInputFields(raw json.RawMessage) []string { } sort.Strings(keys) fields := make([]string, 0, len(keys)) + args := make([]rocArgument, 0, len(keys)) usedNames := make(map[string]struct{}, len(keys)) + required := make(map[string]struct{}, len(schema.Required)) + for _, k := range schema.Required { + required[k] = struct{}{} + } for _, k := range keys { - typ := "Json.Value" + typ := "" switch schema.Properties[k].Type { case "string": typ = "Str" @@ -95,12 +157,26 @@ func rocInputFields(raw json.RawMessage) []string { case "boolean": typ = "Bool" } - fields = append(fields, uniqueRocIdent(rocIdent(k, false), usedNames)+" : "+typ) + name := uniqueRocIdent(rocIdent(k, false), usedNames) + if typ == "" { + typ = "__GENERIC_" + name + "__" + } + _, isRequired := required[k] + if !isRequired { + fields = append(fields, name+" ?: "+typ) + } else { + fields = append(fields, name+" : "+typ) + } + rocType := typ + if strings.HasPrefix(typ, "__GENERIC_") { + rocType = "" + } + args = append(args, rocArgument{name: name, wireName: k, rocType: rocType, optional: !isRequired}) } if len(fields) == 0 { - return []string{"_unit : {}"} + return nil, nil } - return fields + return fields, args } func uniqueRocIdent(name string, used map[string]struct{}) string { diff --git a/pkgs/mcpx/internal/codegen/roc_test.go b/pkgs/mcpx/internal/codegen/roc_test.go index f81896ccd7..2f51e0068f 100644 --- a/pkgs/mcpx/internal/codegen/roc_test.go +++ b/pkgs/mcpx/internal/codegen/roc_test.go @@ -16,14 +16,17 @@ func TestRocLanguageEntryAndClient(t *testing.T) { t.Fatalf("Roc language entry = %+v, found=%v", l, ok) } nss := []codegen.Namespace{{Name: "demo", Server: "demo-server", Tools: []codegen.Tool{{ - Name: "say-hi", InputSchema: []byte(`{"type":"object","properties":{"name":{"type":"string"},"count":{"type":"integer"}}}`), + Name: "say-hi", InputSchema: []byte(`{"type":"object","required":["name","count"],"properties":{"name":{"type":"string"},"count":{"type":"integer"},"next-page":{"type":"string"},"raw":{"description":"any JSON encodable value"}}}`), }}}} out := l.EmitModule(nss, "http://127.0.0.1:1", "test-session") - for _, want := range []string{"import pf.Http", "import pf.Env", "import http.Request", "TransportError(Str)", "StatusError(U16)", "Try(Response.Response, ToolError)", "name : Str", "count : I64", "Http.send!(request, {})", "x-mcpx-session", "demo_say_hi! = |args|"} { + for _, want := range []string{"import pf.Http", "import pf.Env", "import http.Request", "TransportError(Str)", "StatusError(U16)", "DaemonError(Str)", "ToolResultError(Str)", "Try(Response.Response, ToolError)", "name : Str", "count : I64", "Http.send!(authenticated_request, {})", "x-mcpx-session", "x-mcpx-run", "MCPX_RUN", "Authorization", "Bearer", "demo_say_hi! = |args|", `Json.to_str_try("say-hi")`, `Json.to_str_try("demo-server")`, "isError ?: Bool", "List.keep_oks(content, |block| block.?text)", "Response.body", "Json.parse", "MCPX_TRANSPORT_BEARER_TOKEN", `\"next-page\"`, `raw ?: a`, "a.Json.Encodable(_)"} { if !strings.Contains(out, want) { t.Errorf("Roc client missing %q:\n%s", want, out) } } + if strings.Contains(out, "server: \"demo-server\"") || strings.Contains(out, "tool: \"say-hi\"") { + t.Errorf("Roc wire keys/values must be serialized with their original spellings:\n%s", out) + } if got := l.EmitGlobals(nss); got != "" { t.Errorf("Roc has no ambient globals, got %q", got) } @@ -35,7 +38,7 @@ func TestRocNamesAvoidReservedWordsAndSanitizationCollisions(t *testing.T) { {Name: "say_hi", InputSchema: []byte(`{"type":"object"}`)}, }}} out := codegen.RocModule(nss, "", "") - for _, want := range []string{"demo_say_hi! :", "demo_say_hi_2! :", "if_ : Str", "a_b : Str", "a_b_2 : Str"} { + for _, want := range []string{"demo_say_hi! :", "demo_say_hi_2! :", `demo_say_hi_2! : {}`, `args_json = "{}"`, "present_fields = List.keep_if(encoded_fields, |entry| entry != \"\")", "if_ ?: Str", "a_b ?: Str", "a_b_2 ?: Str", `\"a-b\"`, `\"a_b\"`} { if !strings.Contains(out, want) { t.Errorf("generated Roc names missing %q:\n%s", want, out) } @@ -64,9 +67,9 @@ func TestRocNamesAndStringEscapingAreStable(t *testing.T) { for _, want := range []string{ `default_endpoint = "https://example.test/\"path\n"`, `default_session = "session\tvalue"`, - `demo_say_hi! : { _unit : {} }`, - `demo_say_hi_2! : { _unit : {} }`, - `schema_fields! : { if_ : Str, if__2 : Str }`, + `demo_say_hi! : {}`, + `demo_say_hi_2! : {}`, + `schema_fields! : { if_ ?: Str, if__2 ?: Str }`, } { if !strings.Contains(out, want) { t.Errorf("Roc output missing %q:\n%s", want, out) @@ -87,7 +90,9 @@ func TestRocModulePassesCompiler(t *testing.T) { Name: "say-hi", InputSchema: []byte(`{"type":"object","properties":{"name":{"type":"string"},"count":{"type":"integer"}}}`), }}}} client := codegen.RocModule(nss, "http://127.0.0.1:1", "test-session") - main := "app [main!] { pf: platform \"https://github.com/roc-lang/basic-cli/releases/download/0.28.1/7brgwR8YUqfeGrkdfF1V4GPPN7DnP7ftqub9KcrTEZtr.tar.zst\", http: \"https://github.com/roc-lang/http/releases/download/1.0.0/6ZUwqYhCS8PU9Mo6MF7oV82ET2o7KYb57CLKDq4cq4sS.tar.zst\" }\n\nimport Mcpx\n\nmain! = |_args| {\n _ = Mcpx.demo_say_hi!({ name: \"hello\", count: 1 })\n Ok({})\n}\n" + main := "app [main!] { pf: platform \"https://github.com/roc-lang/basic-cli/releases/download/0.28.1/7brgwR8YUqfeGrkdfF1V4GPPN7DnP7ftqub9KcrTEZtr.tar.zst\", http: \"https://github.com/roc-lang/http/releases/download/1.0.0/6ZUwqYhCS8PU9Mo6MF7oV82ET2o7KYb57CLKDq4cq4sS.tar.zst\" }\n\nimport Mcpx\n\nmain! = |_args| {\n _ = Mcpx.demo_say_hi!({ name: \"hello\", count: 1 })\n _ = Mcpx.demo_empty!({})\n _ = Mcpx.demo_raw!({ payload: { nested: { flag: True, count: 1, text: \"x\" } } })\n Ok({})\n}\n" + nss[0].Tools = append(nss[0].Tools, codegen.Tool{Name: "empty", InputSchema: []byte(`{"type":"object"}`)}, codegen.Tool{Name: "raw", InputSchema: []byte(`{"type":"object","required":["payload"],"properties":{"payload":{"description":"any JSON value"}}}`)}) + client = codegen.RocModule(nss, "http://127.0.0.1:1", "test-session") if err := os.WriteFile(filepath.Join(dir, "Mcpx.roc"), []byte(client), 0o600); err != nil { t.Fatal(err) } @@ -103,9 +108,6 @@ func TestRocModulePassesCompiler(t *testing.T) { cmd = exec.Command(roc, "check", "--replace-dep", platformURL, localPlatform, app) } if out, err := cmd.CombinedOutput(); err != nil { - if strings.Contains(string(out), "package download failed") || strings.Contains(string(out), "invalid package dependency") { - t.Skipf("Roc basic-cli platform is unavailable/incompatible with this compiler: %s", out) - } t.Fatalf("roc check rejected generated client: %v\n%s\n--- client ---\n%s", err, out, client) } } diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 211c013618..1b9938d355 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -929,7 +929,7 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err return nil, err } dir = applyChdir(dir, d.chdir) - if d.lookupBin != "" { + if d.lookupBin != "" && !(devshellIsFlake(opts.Devshell) && isRocInterpreter(d.lookupBin)) { // The interpreter a shebang names is resolved here, against // the directory the run actually moves to: deciding earlier // would check relative PATH entries against mcpx's own @@ -940,6 +940,12 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", d.source, d.lookupBin, err) } d.bin = abs + } else if d.lookupBin != "" { + // A Roc shebang under a flake devshell is resolved by that shell, + // just like a .roc file dispatched by language. Looking it up on + // the host here would reject a compiler that exists only in the + // selected devshell. + d.bin = d.lookupBin } notice := "" diff --git a/pkgs/mcpx/internal/runner/language.go b/pkgs/mcpx/internal/runner/language.go index 661995e506..3047d46eac 100644 --- a/pkgs/mcpx/internal/runner/language.go +++ b/pkgs/mcpx/internal/runner/language.go @@ -181,7 +181,13 @@ func pythonDispatch(opts Options) (*dispatch, error) { func rocDispatch(opts Options) (*dispatch, error) { bin, err := exec.LookPath("roc") if err != nil { - return nil, errors.New("runner: roc binary not found on PATH for a Roc script") + if !devshellIsFlake(opts.Devshell) { + return nil, errors.New("runner: roc binary not found on PATH for a Roc script") + } + // As for an explicitly selected JavaScript runtime, a flake devshell + // may provide the compiler even when the host cannot find it. Keep + // the invocation name so nix develop resolves the pinned compiler. + bin = "roc" } c, ok := opts.Clients[codegen.Roc.Name] var client *Client diff --git a/pkgs/mcpx/internal/runner/roc_test.go b/pkgs/mcpx/internal/runner/roc_test.go index 637a26aaf4..7e34184118 100644 --- a/pkgs/mcpx/internal/runner/roc_test.go +++ b/pkgs/mcpx/internal/runner/roc_test.go @@ -35,11 +35,56 @@ func TestRocLanguageDetectionAndSelection(t *testing.T) { } } +func TestRocCompilerCanComeFromFlakeDevshell(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "nix"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + + want := []string{"develop", "./tools", "-c", "roc", "run"} + for _, tc := range []struct { + name, filename, source, interpreter string + }{ + {name: "language", filename: "report.roc", source: "app [main!] {}\n\nmain! = |_args| Ok({})\n"}, + {name: "shebang", filename: "report.sh", source: "#!/usr/bin/env roc\napp [main!] {}\n\nmain! = |_args| Ok({})\n"}, + {name: "configured interpreter", filename: "report.sh", source: "app [main!] {}\n\nmain! = |_args| Ok({})\n", interpreter: "roc"}, + } { + t.Run(tc.name, func(t *testing.T) { + script := filepath.Join(t.TempDir(), tc.filename) + if err := os.WriteFile(script, []byte(tc.source), 0o600); err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + _, err := Run(context.Background(), Options{ + File: script, Interpreter: tc.interpreter, Devshell: "flake:./tools", + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Roc run through flake devshell: %v\nstderr:\n%s", err, stderr.String()) + } + got := strings.Fields(stdout.String()) + if len(got) < len(want) { + t.Fatalf("nix argv = %q, want prefix %q", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("nix argv = %q, want prefix %q", got, want) + } + } + }) + } +} + func TestRocFileRunCallsMockDaemon(t *testing.T) { if _, err := exec.LookPath("roc"); err != nil { t.Skip("roc compiler is not installed") } - seen := make(chan map[string]any, 1) + type observedCall struct { + body map[string]any + run string + } + seen := make(chan observedCall, 1) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/v1/call" { http.NotFound(w, r) @@ -49,9 +94,15 @@ func TestRocFileRunCallsMockDaemon(t *testing.T) { if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Errorf("mock daemon: decode call: %v", err) } - seen <- body + seen <- observedCall{body: body, run: r.Header.Get("X-Mcpx-Run")} + // The mock daemon only returns its dry-run synthetic when the run + // identity arrives. Without it, fail closed instead of reaching a live tool. + if r.Header.Get("X-Mcpx-Run") != "run-roc-dry" { + http.Error(w, `{"error":"missing dry-run run identity"}`, http.StatusForbidden) + return + } w.Header().Set("content-type", "application/json") - _, _ = w.Write([]byte(`{"result":{"structuredContent":{"ok":true}}}`)) + _, _ = w.Write([]byte(`{"result":{"structuredContent":{"dryRun":true,"ok":true}}}`)) })) defer srv.Close() @@ -68,7 +119,7 @@ func TestRocFileRunCallsMockDaemon(t *testing.T) { res, err := Run(context.Background(), Options{ File: script, Clients: map[string]Client{codegen.Roc.Name: {Module: codegen.RocModule(nss, srv.URL, "sess-roc")}}, - Env: map[string]string{"MCPX_ENDPOINT": srv.URL, "MCPX_SESSION": "sess-roc"}, + Env: map[string]string{"MCPX_ENDPOINT": srv.URL, "MCPX_SESSION": "sess-roc", "MCPX_RUN": "run-roc-dry"}, Stdout: &stdout, Stderr: &stderr, }) @@ -80,14 +131,17 @@ func TestRocFileRunCallsMockDaemon(t *testing.T) { } select { case got := <-seen: - if got["server"] != "demo-server" || got["tool"] != "fancy-name" { - t.Errorf("daemon call = %#v, want demo-server/fancy-name", got) + if got.run != "run-roc-dry" { + t.Errorf("daemon run identity = %q, want run-roc-dry", got.run) + } + if got.body["server"] != "demo-server" || got.body["tool"] != "fancy-name" { + t.Errorf("daemon call = %#v, want demo-server/fancy-name", got.body) } - args, _ := got["args"].(map[string]any) + args, _ := got.body["args"].(map[string]any) if args["x"] != "world" { t.Errorf("daemon args = %#v, want x=world", args) } default: - t.Fatal("Roc tool call did not reach mock daemon") + t.Fatalf("Roc tool call did not reach mock daemon (result: %+v)\nstdout:\n%s\nstderr:\n%s", res, stdout.String(), stderr.String()) } } From 25c4342bd563249c1c2ac1e49cae93b08291b224 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 02:34:23 -0600 Subject: [PATCH 2/2] test(mcpx): property-test Roc wire serialization --- pkgs/mcpx/internal/runner/roc_test.go | 184 ++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) diff --git a/pkgs/mcpx/internal/runner/roc_test.go b/pkgs/mcpx/internal/runner/roc_test.go index 7e34184118..157a145c99 100644 --- a/pkgs/mcpx/internal/runner/roc_test.go +++ b/pkgs/mcpx/internal/runner/roc_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -13,6 +14,8 @@ import ( "testing" "github.com/developing-today/code/pkgs/mcpx/internal/codegen" + "github.com/developing-today/code/pkgs/mcpx/internal/testsupport/gen" + "github.com/developing-today/code/pkgs/mcpx/internal/testsupport/seed" ) func TestRocLanguageDetectionAndSelection(t *testing.T) { @@ -145,3 +148,184 @@ func TestRocFileRunCallsMockDaemon(t *testing.T) { t.Fatalf("Roc tool call did not reach mock daemon (result: %+v)\nstdout:\n%s\nstderr:\n%s", res, stdout.String(), stderr.String()) } } + +// TestRocWireSerializationProperties compiles and runs one generated client +// against a mock daemon for a seeded set of argument values. The daemon's +// decoded JSON request is the oracle: original wire keys and values must be +// preserved, sanitized Roc identifiers must not collide, and absent optional +// fields must stay absent. A single Roc process keeps this property test +// bounded while exercising many generated requests. +func TestRocWireSerializationProperties(t *testing.T) { + if _, err := exec.LookPath("roc"); err != nil { + t.Skip("roc compiler is not installed") + } + + const ( + calls = 16 + serverName = "server\"\\\n雪" + ) + type propertyCall struct { + args map[string]any + fields string + } + properties := map[string]any{ + "required-key": map[string]any{"type": "string"}, + "a-b": map[string]any{"type": "string"}, + "a_b": map[string]any{"type": "string"}, + "if": map[string]any{"type": "string"}, + "quoted\"key": map[string]any{"type": "string"}, + } + src := seed.Source(t, "roc-wire-serialization", 1) + const alphabet = "abcXYZ012_-\"\\\n\r\t雪🙂" + characters := []rune(alphabet) + makeValue := func() string { + n := 1 + gen.Intn(src, 18) + var b strings.Builder + for j := 0; j < n; j++ { + b.WriteRune(characters[gen.Intn(src, len(characters))]) + } + return b.String() + } + // The wire keys intentionally include two names that sanitize to a_b, + // a reserved Roc word, and a key containing a quote. Values include Roc + // escapes and arbitrary Unicode; the mock daemon observes decoded JSON. + const optionalKeys = "a-b\x00a_b\x00if\x00quoted\"key" + keys := strings.Split(optionalKeys, "\x00") + identifiers := []string{"a_b", "a_b_2", "if_", "quoted_key"} + propertyCalls := make([]propertyCall, calls) + tools := make([]codegen.Tool, calls) + var main strings.Builder + main.WriteString("app [main!] { pf: platform \"https://github.com/roc-lang/basic-cli/releases/download/0.28.1/7brgwR8YUqfeGrkdfF1V4GPPN7DnP7ftqub9KcrTEZtr.tar.zst\", http: \"https://github.com/roc-lang/http/releases/download/1.0.0/6ZUwqYhCS8PU9Mo6MF7oV82ET2o7KYb57CLKDq4cq4sS.tar.zst\" }\n\nimport Mcpx\n\nmain! = |_args| {\n") + for i := range propertyCalls { + toolName := fmt.Sprintf("case-%02d", i) + required := []string{"required-key"} + call := propertyCall{args: map[string]any{}} + requiredValue := makeValue() + call.fields = "required_key: " + rocSourceString(requiredValue) + call.args["required-key"] = requiredValue + presentFields := make([]bool, len(keys)) + for j, key := range keys { + switch { + case i == 0: + // First schema/call proves all optional fields may be absent. + case i == 1: + required = append(required, key) + presentFields[j] = true + default: + // Vary schema requiredness and argument presence independently. + if gen.Intn(src, 2) == 1 { + required = append(required, key) + presentFields[j] = true + } else { + presentFields[j] = gen.Intn(src, 2) == 1 + } + } + } + for j, key := range keys { + if !presentFields[j] { + continue + } + value := makeValue() + call.fields += ", " + identifiers[j] + ": " + rocSourceString(value) + call.args[key] = value + } + schema, err := json.Marshal(map[string]any{ + "type": "object", "required": required, "properties": properties, + }) + if err != nil { + t.Fatal(err) + } + tools[i] = codegen.Tool{Name: toolName, InputSchema: schema} + propertyCalls[i] = call + fmt.Fprintf(&main, " _ = Mcpx.demo_case_%02d!({ %s })\n", i, call.fields) + } + main.WriteString(" Ok({})\n}\n") + nss := []codegen.Namespace{{Name: "demo", Server: serverName, Tools: tools}} + + seen := make(chan map[string]any, calls) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/call" { + http.NotFound(w, r) + return + } + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("mock daemon: decode request: %v", err) + http.Error(w, `{"error":"bad JSON"}`, http.StatusBadRequest) + return + } + if r.Header.Get("X-Mcpx-Run") != "run-roc-property" { + t.Errorf("run identity = %q, want run-roc-property", r.Header.Get("X-Mcpx-Run")) + } + seen <- body + w.Header().Set("content-type", "application/json") + _, _ = w.Write([]byte(`{"result":{"structuredContent":{"ok":true}}}`)) + })) + defer srv.Close() + + dir := t.TempDir() + script := filepath.Join(dir, "property.roc") + if err := os.WriteFile(script, []byte(main.String()), 0o600); err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + _, err := Run(context.Background(), Options{ + File: script, + Clients: map[string]Client{codegen.Roc.Name: {Module: codegen.RocModule(nss, srv.URL, "sess-roc-property")}}, + Env: map[string]string{"MCPX_ENDPOINT": srv.URL, "MCPX_SESSION": "sess-roc-property", "MCPX_RUN": "run-roc-property"}, + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("property Roc run failed: %v\nstderr:\n%s", err, stderr.String()) + } + for i, want := range propertyCalls { + select { + case got := <-seen: + wantTool := fmt.Sprintf("case-%02d", i) + if got["server"] != serverName || got["tool"] != wantTool { + t.Errorf("call %d server/tool = %q/%q, want %q/%q", i, got["server"], got["tool"], serverName, wantTool) + } + args, ok := got["args"].(map[string]any) + if !ok { + t.Errorf("call %d args = %#v, want object", i, got["args"]) + continue + } + if !jsonEqual(args, want.args) { + t.Errorf("call %d args = %#v, want %#v", i, args, want.args) + } + default: + t.Fatalf("only %d of %d generated requests reached mock daemon\nstdout:\n%s\nstderr:\n%s", i, calls, stdout.String(), stderr.String()) + } + } +} + +func rocSourceString(s string) string { + var b strings.Builder + b.WriteByte('"') + for _, r := range s { + switch r { + case '\\', '"': + b.WriteByte('\\') + b.WriteRune(r) + case '\n': + b.WriteString("\\n") + case '\r': + b.WriteString("\\r") + case '\t': + b.WriteString("\\t") + default: + b.WriteRune(r) + } + } + b.WriteByte('"') + return b.String() +} + +func jsonEqual(a, b any) bool { + left, err := json.Marshal(a) + if err != nil { + return false + } + right, err := json.Marshal(b) + return err == nil && string(left) == string(right) +}