diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 8a6f2beb6c..b603b3776a 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -1060,7 +1060,7 @@ skipped launcher phases). | `script.importsOnDynamic` | enum | `warn` | client | no | `--script-imports-on-dynamic` | `MCPX_SCRIPT_IMPORTS_ON_DYNAMIC` | what to do about an import() whose specifier is computed | | `script.importsOnMissing` | enum | `fail` | client | no | `--script-imports-on-missing` | `MCPX_SCRIPT_IMPORTS_ON_MISSING` | how to handle a package absent from the dependency set | | `script.interpreter` | string | *(empty)* | client | no | `--script-interpreter`, `--interpreter`, `--shell` | `MCPX_SCRIPT_INTERPRETER` | command line that runs scripts instead of a JavaScript runtime | -| `script.language` | enum | `auto` | client | no | `--script-language`, `--language` | `MCPX_SCRIPT_LANGUAGE` | language a script is written in: auto, typescript, javascript or python | +| `script.language` | enum | `auto` | client | no | `--script-language`, `--language` | `MCPX_SCRIPT_LANGUAGE` | language a script is written in: auto, typescript, javascript, python or roc | | `script.launcher` | source | *(empty)* | client | no | `--script-launcher` | `MCPX_SCRIPT_LAUNCHER` | replace the generated launcher entirely | | `script.onError` | source | *(empty)* | client | no | `--script-on-error` | `MCPX_SCRIPT_ON_ERROR` | runs when the script throws; the error still propagates | | `script.onSuccess` | source | *(empty)* | client | no | `--script-on-success` | `MCPX_SCRIPT_ON_SUCCESS` | runs when the script returns without throwing | diff --git a/pkgs/mcpx/docs/runtimes.md b/pkgs/mcpx/docs/runtimes.md index b1cd428f8f..c0a2f563bc 100644 --- a/pkgs/mcpx/docs/runtimes.md +++ b/pkgs/mcpx/docs/runtimes.md @@ -81,7 +81,8 @@ be updated in the same change. | Bare package resolution from `node_modules` | yes | yes | yes | | Static type checking before run | yes (`deno check`) | no — types are stripped unchecked | no — types are stripped unchecked | | Permission enforcement (profiles below) | full model | none (`all` only) | partial (`--permission`) | -| Python runtime ([#1917](https://github.com/developing-today/code/issues/1917)) | pending | pending | pending | +| Python scripts ([#1917](https://github.com/developing-today/code/issues/1917)) | independent Python interpreter; does not use this runtime | independent Python interpreter; does not use this runtime | independent Python interpreter; does not use this runtime | +| Roc scripts ([#1964](https://github.com/developing-today/code/issues/1964)) | independent `roc run`; basic-cli platform required | independent `roc run`; basic-cli platform required | independent `roc run`; basic-cli platform required | | Flake environments ([#1921](https://github.com/developing-today/code/issues/1921)) | pending | pending | pending | | Dependency management ([#1913](https://github.com/developing-today/code/issues/1913)) | pending | pending | pending | diff --git a/pkgs/mcpx/internal/api/ops_exec.go b/pkgs/mcpx/internal/api/ops_exec.go index 7589a52072..567266cfcc 100644 --- a/pkgs/mcpx/internal/api/ops_exec.go +++ b/pkgs/mcpx/internal/api/ops_exec.go @@ -102,7 +102,7 @@ func execOps() []Op { // and a generated schema would carry field names and no reasons. const execOptionsSchema = `{"type":"object","properties":{ "runtime":{"type":"string","enum":["auto","deno","bun","node"]}, -"language":{"type":"string","enum":["auto","typescript","javascript","python"],"description":"script language; auto detects from shebang then extension (#1917)"}, +"language":{"type":"string","enum":["auto","typescript","javascript","python","roc"],"description":"script language; auto detects from shebang then extension (#1917, #1964)"}, "timeout":{"type":"string","description":"a duration such as 30s; default from settings"}, "permissions":{"type":"string","description":"sandbox profile: all, net, read, read-net, strict, or raw runtime flags"}, "placeholders":{"type":"object","additionalProperties":true,"description":"values for @names a launcher template refers to"}, diff --git a/pkgs/mcpx/internal/api/ops_exec_schema_test.go b/pkgs/mcpx/internal/api/ops_exec_schema_test.go index 31a40ad831..a1dd6dbb82 100644 --- a/pkgs/mcpx/internal/api/ops_exec_schema_test.go +++ b/pkgs/mcpx/internal/api/ops_exec_schema_test.go @@ -38,3 +38,25 @@ func TestExecOptionsSchemaDeclaresDeps(t *testing.T) { } } } + +func TestExecOptionsSchemaDeclaresRocLanguage(t *testing.T) { + o, ok := api.ByName("exec") + if !ok { + t.Fatal("no exec operation") + } + var doc map[string]any + if err := json.Unmarshal(o.InputSchema(), &doc); err != nil { + t.Fatal(err) + } + props, _ := doc["properties"].(map[string]any) + options, _ := props["options"].(map[string]any) + optProps, _ := options["properties"].(map[string]any) + language, _ := optProps["language"].(map[string]any) + enum, _ := language["enum"].([]any) + for _, value := range enum { + if value == "roc" { + return + } + } + t.Fatalf("published exec options schema language enum does not include roc: %v", enum) +} diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index aeb1477b00..a1affea03a 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -636,7 +636,7 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { rt := fs.String("runtime", "", "javascript runtime: auto, deno, bun, node, a name from script.runtimes, or a path") lang := fs.String("language", "", - "script language: auto, typescript, javascript, or python (default: script.language)") + "script language: auto, typescript, javascript, python, or roc (default: script.language)") timeout := fs.Duration("timeout", 0, "kill the script after this long (default: exec.timeout; 0 = no limit)") keep := fs.Bool("keep", false, "keep the generated client and script for inspection") session := fs.String("session", "", "session key (default: a fresh one per run)") @@ -929,6 +929,9 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { // and never fails the run -- a daemon without the route leaves clients // empty and the run as it was. clients := map[string]runner.Client{} + if roc, rocErr := c.ClientModuleLanguage(ctx, codegen.Roc.Name, ns, "", a.Profile); rocErr == nil && roc != clientSrc { + clients[codegen.Roc.Name] = runner.Client{Module: roc} + } if py, pyerr := c.ClientModuleLanguage(ctx, codegen.Python.Name, ns, "", a.Profile); pyerr == nil && py != clientSrc { // A daemon from before #1917 Phase 2 ignores ?language and answers // with the TypeScript module; installing that as mcpx_client.py diff --git a/pkgs/mcpx/internal/cli/flagindex_generated.go b/pkgs/mcpx/internal/cli/flagindex_generated.go index dabfc23cc4..6bfb8fe2a7 100644 --- a/pkgs/mcpx/internal/cli/flagindex_generated.go +++ b/pkgs/mcpx/internal/cli/flagindex_generated.go @@ -92,7 +92,7 @@ var handFlagIndex = map[string][]HandFlag{ "exec": { {Name: "ns", Usage: "restrict the client to these namespaces (comma separated)"}, {Name: "runtime", Usage: "javascript runtime: auto, deno, bun, node, a name from script.runtimes, or a path"}, - {Name: "language", Usage: "script language: auto, typescript, javascript, or python (default: script.language)"}, + {Name: "language", Usage: "script language: auto, typescript, javascript, python, or roc (default: script.language)"}, {Name: "timeout", Usage: "kill the script after this long (default: exec.timeout; 0 = no limit)"}, {Name: "keep", Usage: "keep the generated client and script for inspection"}, {Name: "session", Usage: "session key (default: a fresh one per run)"}, @@ -221,7 +221,7 @@ var handFlagIndex = map[string][]HandFlag{ "run": { {Name: "ns", Usage: "restrict the client to these namespaces (comma separated)"}, {Name: "runtime", Usage: "javascript runtime: auto, deno, bun, node, a name from script.runtimes, or a path"}, - {Name: "language", Usage: "script language: auto, typescript, javascript, or python (default: script.language)"}, + {Name: "language", Usage: "script language: auto, typescript, javascript, python, or roc (default: script.language)"}, {Name: "timeout", Usage: "kill the script after this long (default: exec.timeout; 0 = no limit)"}, {Name: "keep", Usage: "keep the generated client and script for inspection"}, {Name: "session", Usage: "session key (default: a fresh one per run)"}, diff --git a/pkgs/mcpx/internal/cli/scripts.go b/pkgs/mcpx/internal/cli/scripts.go index e077d97b0e..f65f3dbc57 100644 --- a/pkgs/mcpx/internal/cli/scripts.go +++ b/pkgs/mcpx/internal/cli/scripts.go @@ -308,6 +308,7 @@ func scriptExtension(name string) string { var generatedClientNames = map[string]bool{ runner.ClientFileName: true, codegen.Python.ClientFile: true, + codegen.Roc.ClientFile: true, } // ScriptEntry is one discoverable script. diff --git a/pkgs/mcpx/internal/codegen/language.go b/pkgs/mcpx/internal/codegen/language.go index f6443702b6..4ac1dc0925 100644 --- a/pkgs/mcpx/internal/codegen/language.go +++ b/pkgs/mcpx/internal/codegen/language.go @@ -11,7 +11,7 @@ package codegen // ".ts" or "mcpx-client.ts" named it on its own — so adding a language was // an audit, not an entry. Now the existing package-level emitters are the // TypeScript entry's emitters, reached through the table; a new language -// (Python is the queued follow-on, #1917 Phase 1 remainder) is one more +// (Python and Roc are additional targets) is one more // entry with its own emitters, and callers that ask the Language for file // names never spell a foreign target's. // @@ -19,7 +19,7 @@ package codegen // data plus three renderings, and a table literal states both at the // place a reader looks for them. type Language struct { - // Name is the registry key: "typescript", and in time "python". + // Name is the registry key, such as "typescript", "python" or "roc". Name string // ClientFile is the generated client module's name on disk. For // TypeScript it must stay runner.ClientFileName — the runner writes @@ -62,10 +62,10 @@ var TypeScript = Language{ } // Languages is the registry of codegen targets, in preference order. -var Languages = []Language{TypeScript, Python} +var Languages = []Language{TypeScript, Python, Roc} // Default is the target every surface that does not name one means: the -// only target there has ever been. +// original target unless a script selects another language. func Default() Language { return TypeScript } // Lookup finds a target by name. diff --git a/pkgs/mcpx/internal/codegen/language_test.go b/pkgs/mcpx/internal/codegen/language_test.go index c40c333d6a..f1385d2679 100644 --- a/pkgs/mcpx/internal/codegen/language_test.go +++ b/pkgs/mcpx/internal/codegen/language_test.go @@ -31,6 +31,9 @@ func TestTypeScriptIsTheDefaultLanguage(t *testing.T) { } else if l, _ := Lookup("python"); l.ClientFile != "mcpx_client.py" || l.ScriptExt != ".py" { t.Fatalf("python entry = %+v, want mcpx_client.py / .py", l) } + if roc, ok := Lookup("roc"); !ok || roc.ClientFile != "Mcpx.roc" || roc.ScriptExt != ".roc" { + t.Fatalf("Roc entry = %+v, found=%v", roc, ok) + } } func TestTypeScriptFileNamesMatchTheRunnerContract(t *testing.T) { diff --git a/pkgs/mcpx/internal/codegen/roc.go b/pkgs/mcpx/internal/codegen/roc.go new file mode 100644 index 0000000000..955d6d342f --- /dev/null +++ b/pkgs/mcpx/internal/codegen/roc.go @@ -0,0 +1,186 @@ +package codegen + +import ( + "encoding/json" + "fmt" + "sort" + "strings" +) + +// Roc is the Roc basic-cli target. Generated clients use the HTTP API exposed +// by the selected basic-cli platform and the shared roc-lang/http types. +var Roc = Language{ + Name: "roc", ClientFile: "Mcpx.roc", ScriptExt: ".roc", + ContentType: "text/x-roc", module: RocModule, + globals: func([]Namespace) string { return "" }, + declarations: RocDeclarations, +} + +// RocModule emits a client module for Roc's basic-cli platform. The host +// supplies basic-cli as the app platform; roc-lang/http is also listed as a +// direct app package because generated modules import its shared HTTP types. +// Tool argument records are concrete per-tool types so Roc can statically +// select its JSON encoder for each request. +func RocModule(nss []Namespace, endpoint, session string) string { + var b strings.Builder + functions := rocFunctions(nss) + // Roc's current module format is a headerless type module. The file is + // 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") + 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") + 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") + } + return b.String() +} + +type rocFunction struct { + name, server, tool string + fields []string +} + +func rocFunctions(nss []Namespace) []rocFunction { + sorted := append([]Namespace(nil), nss...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name }) + var out []rocFunction + usedNames := map[string]struct{}{"call": {}, "default_endpoint": {}, "default_session": {}} + for _, ns := range sorted { + for _, tool := range sortedTools(ns) { + name := uniqueRocIdent(rocIdent(ns.Name+"_"+tool.Name, false), usedNames) + fields := rocInputFields(tool.InputSchema) + out = append(out, rocFunction{ + name: name, server: ns.Server, + tool: tool.Name, fields: fields, + }) + } + } + return out +} + +func rocInputFields(raw json.RawMessage) []string { + var schema struct { + Properties map[string]struct { + Type string `json:"type"` + } `json:"properties"` + } + _ = json.Unmarshal(raw, &schema) + keys := make([]string, 0, len(schema.Properties)) + for k := range schema.Properties { + keys = append(keys, k) + } + sort.Strings(keys) + fields := make([]string, 0, len(keys)) + usedNames := make(map[string]struct{}, len(keys)) + for _, k := range keys { + typ := "Json.Value" + switch schema.Properties[k].Type { + case "string": + typ = "Str" + case "integer": + typ = "I64" + case "number": + typ = "F64" + case "boolean": + typ = "Bool" + } + fields = append(fields, uniqueRocIdent(rocIdent(k, false), usedNames)+" : "+typ) + } + if len(fields) == 0 { + return []string{"_unit : {}"} + } + return fields +} + +func uniqueRocIdent(name string, used map[string]struct{}) string { + candidate := name + for suffix := 2; ; suffix++ { + if _, exists := used[candidate]; !exists { + used[candidate] = struct{}{} + return candidate + } + candidate = fmt.Sprintf("%s_%d", name, suffix) + } +} + +func RocDeclarations(nss []Namespace) string { + var b strings.Builder + b.WriteString("Roc client (basic-cli platform)\n\n") + for _, fn := range rocFunctions(nss) { + fmt.Fprintf(&b, "%s : generated typed arguments -> Try(Response.Response, ToolError)\n", fn.name) + } + return b.String() +} + +func rocString(s string) string { + var b strings.Builder + b.WriteByte('"') + for _, r := range s { + switch r { + case '\\': + b.WriteString("\\\\") + case '"': + b.WriteString("\\\"") + case '\n': + b.WriteString("\\n") + case '\r': + b.WriteString("\\r") + case '\t': + b.WriteString("\\t") + default: + if r < 0x20 { + fmt.Fprintf(&b, "\\u(%04x)", r) + } else { + b.WriteRune(r) + } + } + } + b.WriteByte('"') + return b.String() +} + +var rocReserved = map[string]struct{}{ + "and": {}, "app": {}, "as": {}, "crash": {}, "dbg": {}, "else": {}, "expect": {}, + "exposes": {}, "for": {}, "if": {}, "implements": {}, "import": {}, "in": {}, "is": {}, + "match": {}, "module": {}, "not": {}, "or": {}, "packages": {}, "platform": {}, + "provides": {}, "requires": {}, "return": {}, "test": {}, "then": {}, "try": {}, + "when": {}, "where": {}, "with": {}, +} + +func rocIdent(s string, upper bool) string { + var b strings.Builder + for i, r := range s { + if r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' { + if i == 0 && r >= '0' && r <= '9' { + b.WriteByte('_') + } + b.WriteRune(r) + } else { + b.WriteByte('_') + } + } + name := strings.Trim(b.String(), "_") + if name == "" { + name = "field" + } + if upper { + name = strings.ToUpper(name[:1]) + name[1:] + } else { + name = strings.ToLower(name[:1]) + name[1:] + } + if _, reserved := rocReserved[name]; reserved { + name += "_" + } + return name +} diff --git a/pkgs/mcpx/internal/codegen/roc_test.go b/pkgs/mcpx/internal/codegen/roc_test.go new file mode 100644 index 0000000000..f81896ccd7 --- /dev/null +++ b/pkgs/mcpx/internal/codegen/roc_test.go @@ -0,0 +1,111 @@ +package codegen_test + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/codegen" +) + +func TestRocLanguageEntryAndClient(t *testing.T) { + l, ok := codegen.Lookup("roc") + if !ok || l.ClientFile != "Mcpx.roc" || l.ScriptExt != ".roc" || l.ContentType != "text/x-roc" { + 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"}}}`), + }}}} + 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|"} { + if !strings.Contains(out, want) { + t.Errorf("Roc client missing %q:\n%s", want, out) + } + } + if got := l.EmitGlobals(nss); got != "" { + t.Errorf("Roc has no ambient globals, got %q", got) + } +} + +func TestRocNamesAvoidReservedWordsAndSanitizationCollisions(t *testing.T) { + nss := []codegen.Namespace{{Name: "demo", Server: "demo", Tools: []codegen.Tool{ + {Name: "say-hi", InputSchema: []byte(`{"type":"object","properties":{"if":{"type":"string"},"a-b":{"type":"string"},"a_b":{"type":"string"}}}`)}, + {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"} { + if !strings.Contains(out, want) { + t.Errorf("generated Roc names missing %q:\n%s", want, out) + } + } + if got := strings.Count(out, "demo_say_hi!"); got != 2 { + t.Errorf("first tool declaration/reference count = %d, want 2", got) + } +} + +func TestRocStringUsesRocEscapes(t *testing.T) { + out := codegen.RocModule(nil, "quote\" slash\\ line\n", "") + if !strings.Contains(out, `default_endpoint = "quote\" slash\\ line\n"`) { + t.Errorf("Roc endpoint did not use Roc string escapes:\n%s", out) + } +} + +func TestRocNamesAndStringEscapingAreStable(t *testing.T) { + nss := []codegen.Namespace{ + {Name: "demo", Server: "one", Tools: []codegen.Tool{{Name: "say-hi"}}}, + {Name: "demo_say", Server: "two", Tools: []codegen.Tool{{Name: "hi"}}}, + {Name: "schema", Server: "three", Tools: []codegen.Tool{{ + Name: "fields", InputSchema: []byte(`{"type":"object","properties":{"if":{"type":"string"},"if_":{"type":"string"}}}`), + }}}, + } + out := codegen.RocModule(nss, "https://example.test/\"path\n", "session\tvalue") + 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 }`, + } { + if !strings.Contains(out, want) { + t.Errorf("Roc output missing %q:\n%s", want, out) + } + } +} + +// The installed nightly is the syntax oracle for the generated Roc module. +// The application platform provides the Http API; Approach C (a custom mcpx +// platform) is intentionally not part of this test or implementation. +func TestRocModulePassesCompiler(t *testing.T) { + roc, err := exec.LookPath("roc") + if err != nil { + t.Skip("roc compiler is not installed") + } + dir := t.TempDir() + 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"}}}`), + }}}} + 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" + if err := os.WriteFile(filepath.Join(dir, "Mcpx.roc"), []byte(client), 0o600); err != nil { + t.Fatal(err) + } + app := filepath.Join(dir, "main.roc") + if err := os.WriteFile(app, []byte(main), 0o600); err != nil { + t.Fatal(err) + } + platformURL := "https://github.com/roc-lang/basic-cli/releases/download/0.28.1/7brgwR8YUqfeGrkdfF1V4GPPN7DnP7ftqub9KcrTEZtr.tar.zst" + cmd := exec.Command(roc, "check", app) + cache, _ := os.UserCacheDir() + localPlatform := filepath.Join(cache, "roc", "packages", "github.com", "roc-lang", "basic-cli", "releases", "download", "0.28.1", "7brgwR8YUqfeGrkdfF1V4GPPN7DnP7ftqub9KcrTEZtr", "main.roc") + if _, err := os.Stat(localPlatform); err == nil { + 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/daemon/consumer.go b/pkgs/mcpx/internal/daemon/consumer.go index 2a92531d67..fe03e3bd6a 100644 --- a/pkgs/mcpx/internal/daemon/consumer.go +++ b/pkgs/mcpx/internal/daemon/consumer.go @@ -1026,6 +1026,9 @@ func (s *Server) execScript(ctx context.Context, source, session string) (*ExecR // source chose it (#1917 Phase 2); the same options the runner // itself would derive reach one from daemon callers. Clients: map[string]runner.Client{ + codegen.Roc.Name: { + Module: codegen.RocModule(nss, s.endpoint, session), + }, codegen.Python.Name: { Module: codegen.PythonModule(nss, s.endpoint, session), Globals: codegen.PythonGlobals(nss), diff --git a/pkgs/mcpx/internal/execsvc/execsvc.go b/pkgs/mcpx/internal/execsvc/execsvc.go index de2fbd9540..9c539b16f9 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc.go +++ b/pkgs/mcpx/internal/execsvc/execsvc.go @@ -969,7 +969,13 @@ func (s *Service) Run(ctx context.Context, req Request, sink Sink) (*Result, err // Python client. clients := map[string]runner.Client{} effectiveLanguage := firstNonEmpty(opts.Language, s.Limits.Language) - if runner.ClientScriptLanguage(firstNonEmpty(req.File, req.SourceName), req.Source, effectiveLanguage) == codegen.Python.Name { + clientLanguage := runner.ClientScriptLanguage(firstNonEmpty(req.File, req.SourceName), req.Source, effectiveLanguage) + if clientLanguage == codegen.Roc.Name { + if module, rocGlobals, cerr := s.Src.ClientModuleFor(ctx, codegen.Roc.Name, opts.NS); cerr == nil { + clients[codegen.Roc.Name] = runner.Client{Module: module, Globals: rocGlobals} + } + } + if clientLanguage == codegen.Python.Name { if module, pyGlobals, cerr := s.Src.ClientModuleFor(ctx, codegen.Python.Name, opts.NS); cerr == nil { clients[codegen.Python.Name] = runner.Client{Module: module, Globals: pyGlobals} } diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index fa6779e895..211c013618 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -877,8 +877,8 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err // interpreter, tools and tracebacks see the file it is, while a // raw dispatch keeps the interpreter, not the name, deciding. suffix := "" - if d.language == codegen.Python.Name { - suffix = codegen.Python.ScriptExt + if lang, ok := codegen.Lookup(d.language); ok { + suffix = lang.ScriptExt } if workDir == "" { wd, err := os.MkdirTemp("", "mcpx-run-") diff --git a/pkgs/mcpx/internal/runner/language.go b/pkgs/mcpx/internal/runner/language.go index 3b33cf8bc6..661995e506 100644 --- a/pkgs/mcpx/internal/runner/language.go +++ b/pkgs/mcpx/internal/runner/language.go @@ -38,6 +38,8 @@ func ScriptLanguage(file, source string) string { switch strings.ToLower(filepath.Ext(file)) { case codegen.Python.ScriptExt: return codegen.Python.Name + case codegen.Roc.ScriptExt: + return codegen.Roc.Name case ".ts", ".mts", ".js", ".mjs": return codegen.TypeScript.Name } @@ -61,6 +63,9 @@ func shebangLanguage(file, source string) string { if isPythonInterpreter(sp.tokens[0]) { return codegen.Python.Name } + if isRocInterpreter(sp.tokens[0]) { + return codegen.Roc.Name + } if isJSRuntimeName(Setup{}, sp.tokens[0]) { return codegen.TypeScript.Name } @@ -94,10 +99,12 @@ func NormalizeLanguage(v string) (string, error) { return "", nil case "python": return codegen.Python.Name, nil + case "roc": + return codegen.Roc.Name, nil case "typescript", "javascript": return codegen.TypeScript.Name, nil default: - return "", fmt.Errorf("runner: script language %q is not one of auto, typescript, javascript, python", v) + return "", fmt.Errorf("runner: script language %q is not one of auto, typescript, javascript, python, roc", v) } } @@ -126,6 +133,8 @@ func isPythonInterpreter(token string) bool { return strings.HasPrefix(strings.TrimSuffix(base, filepath.Ext(base)), "python") } +func isRocInterpreter(token string) bool { return filepath.Base(token) == "roc" } + // resolvePython finds the interpreter a Python script runs under: python3, // then the bare python some machines provide instead, then uv. uv is the // fallback because it is the tool a Python author already has when python3 is @@ -169,12 +178,39 @@ func pythonDispatch(opts Options) (*dispatch, error) { }, nil } +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") + } + c, ok := opts.Clients[codegen.Roc.Name] + var client *Client + if ok { + client = &c + } + return &dispatch{bin: bin, args: []string{"run"}, name: "roc", source: "language", language: codegen.Roc.Name, client: client}, nil +} + // harnessClient attaches the generated client for a dispatch's language, if // this run has one. It is what turns a raw interpreter run into a harnessed // one: the client is installed beside the script, the run is told where it // is (MCPX_CLIENT), and the "no generated client" notice no longer applies. func harnessClient(opts Options, d *dispatch) { - if d == nil || !isPythonInterpreter(firstNonEmpty(d.lookupBin, d.bin)) { + if d == nil { + return + } + interpreter := firstNonEmpty(d.lookupBin, d.bin) + if isRocInterpreter(interpreter) { + d.language = codegen.Roc.Name + if len(d.args) == 0 || d.args[0] != "run" { + d.args = append([]string{"run"}, d.args...) + } + if c, ok := opts.Clients[d.language]; ok { + d.client = &c + } + return + } + if !isPythonInterpreter(interpreter) { return } lang := codegen.Python.Name diff --git a/pkgs/mcpx/internal/runner/roc_test.go b/pkgs/mcpx/internal/runner/roc_test.go new file mode 100644 index 0000000000..637a26aaf4 --- /dev/null +++ b/pkgs/mcpx/internal/runner/roc_test.go @@ -0,0 +1,93 @@ +package runner + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/codegen" +) + +func TestRocLanguageDetectionAndSelection(t *testing.T) { + cases := []struct{ file, source, explicit, want string }{ + {"report.roc", "", "", codegen.Roc.Name}, + {"", "#!/usr/bin/env roc\napp [main] {}\n", "", codegen.Roc.Name}, + {"report.ts", "", "roc", codegen.Roc.Name}, + {"report.roc", "", "typescript", codegen.TypeScript.Name}, + } + for _, tc := range cases { + if got := EffectiveScriptLanguage(tc.file, tc.source, tc.explicit); got != tc.want { + t.Errorf("EffectiveScriptLanguage(%q, %q, %q) = %q, want %q", tc.file, tc.source, tc.explicit, got, tc.want) + } + } + if got := ClientScriptLanguage("", "#!/usr/bin/env roc\n", "typescript"); got != codegen.Roc.Name { + t.Errorf("Roc shebang client language = %q, want roc", got) + } + if got, err := NormalizeLanguage(" Roc "); err != nil || got != codegen.Roc.Name { + t.Errorf("NormalizeLanguage(roc) = %q, %v", got, err) + } +} + +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) + 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 call: %v", err) + } + seen <- body + w.Header().Set("content-type", "application/json") + _, _ = w.Write([]byte(`{"result":{"structuredContent":{"ok":true}}}`)) + })) + defer srv.Close() + + nss := []codegen.Namespace{{Name: "demo", Server: "demo-server", Tools: []codegen.Tool{{ + Name: "fancy-name", InputSchema: []byte(`{"type":"object","properties":{"x":{"type":"string"}},"required":["x"]}`), + }}}} + dir := t.TempDir() + script := filepath.Join(dir, "report.roc") + 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_fancy_name!({ x: \"world\" })\n Ok({})\n}\n" + if err := os.WriteFile(script, []byte(main), 0o600); err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + 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"}, + Stdout: &stdout, + Stderr: &stderr, + }) + if err != nil { + t.Fatalf("roc run failed: %v\nstderr:\n%s", err, stderr.String()) + } + if !strings.Contains(res.Runtime, "roc") { + t.Errorf("Result.Runtime = %q, want Roc interpreter", res.Runtime) + } + select { + case got := <-seen: + if got["server"] != "demo-server" || got["tool"] != "fancy-name" { + t.Errorf("daemon call = %#v, want demo-server/fancy-name", got) + } + args, _ := got["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") + } +} diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index 24458b39fd..b169fd9857 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -78,7 +78,7 @@ type Options struct { Runtime string // Language is the explicit script-language selection for this run // (script.language / --language / ExecOptions.language): auto, - // typescript, javascript or python. Empty means auto. It decides the + // typescript, javascript, python or roc. Empty means auto. It decides the // language -- and so which generated client is installed -- when no // shebang or configured interpreter dispatch decides first (#1917). Language string @@ -489,13 +489,19 @@ func Run(ctx context.Context, opts Options) (*Result, error) { // harness path honours what the raw path preserves. opts.Runtime = js.runtime jsEnv = js - } else if EffectiveScriptLanguage(opts.evidenceFile(), opts.Source, opts.Language) == codegen.Python.Name { + } else if lang := EffectiveScriptLanguage(opts.evidenceFile(), opts.Source, opts.Language); lang == codegen.Python.Name || lang == codegen.Roc.Name { // Rank 3: nothing named an interpreter and the script is Python // by extension, so the run is a Python harness run rather than a // TypeScript one. Installing the client is the difference from a // raw dispatch: `import mcpx_client` works, and the script's own // top-level code is the program. - d, derr := pythonDispatch(opts) + var d *dispatch + var derr error + if lang == codegen.Roc.Name { + d, derr = rocDispatch(opts) + } else { + d, derr = pythonDispatch(opts) + } if derr != nil { return nil, derr } diff --git a/pkgs/mcpx/internal/scriptresolve/scriptresolve.go b/pkgs/mcpx/internal/scriptresolve/scriptresolve.go index dd6216fca0..31bb7dfda7 100644 --- a/pkgs/mcpx/internal/scriptresolve/scriptresolve.go +++ b/pkgs/mcpx/internal/scriptresolve/scriptresolve.go @@ -41,7 +41,7 @@ const Ext = ".ts" // TypeScript's by default, the way every run without a language is. (The // #2168 branch originally dropped ".py" here; restored on revival — the // CLI's list has always ended with it.) -var Extensions = []string{".ts", ".mts", ".js", ".mjs", ".py"} +var Extensions = []string{".ts", ".mts", ".js", ".mjs", ".py", ".roc"} // SplitPathList accepts either a JSON array, as a configuration file holds // it, or a separator-joined string, as an environment variable must. "-" and diff --git a/pkgs/mcpx/internal/settings/registry.go b/pkgs/mcpx/internal/settings/registry.go index f40f7d580d..8f59651091 100644 --- a/pkgs/mcpx/internal/settings/registry.go +++ b/pkgs/mcpx/internal/settings/registry.go @@ -238,9 +238,9 @@ func scriptSettings() []Setting { { Path: "script.language", Commands: runCommands, Kind: KindEnum, Default: "auto", Scope: ScopeClient, - Enum: []string{"auto", "typescript", "javascript", "python"}, + Enum: []string{"auto", "typescript", "javascript", "python", "roc"}, FlagAliases: []string{"language"}, - Name: "Script language", Short: "language a script is written in: auto, typescript, javascript or python", + Name: "Script language", Short: "language a script is written in: auto, typescript, javascript, python or roc", Long: "auto detects from the shebang, then the file extension, as before. " + "python runs the script under the machine's Python with the generated " + "Python client installed; typescript and javascript run under " + diff --git a/pkgs/mcpx/plugin/core/ops.gen.ts b/pkgs/mcpx/plugin/core/ops.gen.ts index ce75bd2cc2..f0371e5e5e 100644 --- a/pkgs/mcpx/plugin/core/ops.gen.ts +++ b/pkgs/mcpx/plugin/core/ops.gen.ts @@ -20,7 +20,7 @@ type OpSpec = { response: "json" | "response" } -export const OPERATION_FINGERPRINT = "dfe97845b14e07ac3974e1beb9aa85d32219b0d99ce4493f9dad624ffd83d2a0" +export const OPERATION_FINGERPRINT = "da584569030ee496cfdaba3e7bb83a68741d79c2278e7e137e0db3e622e7d008" /** Every /v1 operation, by name. */ export const OPS: Record = {