Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 91 additions & 15 deletions pkgs/mcpx/internal/codegen/roc.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
)

Expand All @@ -28,27 +29,72 @@ 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()
}

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 {
Expand All @@ -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"`
Expand All @@ -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"
Expand All @@ -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 {
Expand Down
22 changes: 12 additions & 10 deletions pkgs/mcpx/internal/codegen/roc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Comment on lines +22 to 25

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add property-based coverage for the wire serialization invariants

The new hand-built argument serializer has explicit invariants—preserve original property names and values, omit absent optional fields, and encode empty arguments as {}—but these checks only inspect generated source substrings. The compiler smoke test and single x: "world" mock-daemon case do not establish those invariants across inputs. This violates the testing doctrine in AGENTS.md, which requires property-based tests for invariant-bearing code, including serializers. Add generated schemas/arguments and use decoded requests observed by the mock daemon as the oracle, covering escaping, sanitization collisions, and optional-field presence.

AGENTS.md reference: AGENTS.md:L36-L39

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added TestRocWireSerializationProperties in runner tests. It builds 16 seeded Roc tool schemas with collision-prone/reserved/quoted wire keys and generated requiredness/argument values, runs one Roc process against a mock daemon, and compares each decoded JSON request to the expected server/tool/args. The fixed cases guarantee all optional fields omitted once and all present once; remaining schemas vary requiredness/presence. Verified with the focused runner tests and go test -race -shuffle=on -count=5 -run Roc ./internal/runner (pass). Commit: 25c4342.

}
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)
}
Expand All @@ -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)
}
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
Expand All @@ -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)
}
}
8 changes: 7 additions & 1 deletion pkgs/mcpx/internal/runner/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 := ""
Expand Down
8 changes: 7 additions & 1 deletion pkgs/mcpx/internal/runner/language.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading