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
2 changes: 1 addition & 1 deletion pkgs/mcpx/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
3 changes: 2 additions & 1 deletion pkgs/mcpx/docs/runtimes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/api/ops_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
22 changes: 22 additions & 0 deletions pkgs/mcpx/internal/api/ops_exec_schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
5 changes: 4 additions & 1 deletion pkgs/mcpx/internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pkgs/mcpx/internal/cli/flagindex_generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkgs/mcpx/internal/cli/scripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 4 additions & 4 deletions pkgs/mcpx/internal/codegen/language.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ 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.
//
// The emitters are fields rather than an interface because a target is
// 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
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions pkgs/mcpx/internal/codegen/language_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
186 changes: 186 additions & 0 deletions pkgs/mcpx/internal/codegen/roc.go
Original file line number Diff line number Diff line change
@@ -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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Authenticate requests with the supplied daemon bearer token

When transport.bearerToken is configured, every generated Roc tool call receives HTTP 401 because the request never includes an Authorization header. The exec service already supplies MCPX_TRANSPORT_BEARER_TOKEN in scriptEnv, and daemon/bearer.go's requireBearer enforces it on every HTTP route, including /v1/call. Read that environment variable and conditionally send Authorization: Bearer <token> so Roc scripts can use authenticated daemons.

Useful? React with 👍 / 👎.

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 Forward the run ID to preserve dry-run interception

For a Roc execution requested with dryRun:true, these requests omit X-Mcpx-Run even though the exec service supplies MCPX_RUN. In daemon/server.go, handleCall obtains the run identity exclusively from that header, and dryRunResult declines interception when the identity is empty. Consequently, Roc tool calls execute against real servers during a purported dry run, including calls with destructive side effects. Forward the run ID on every generated request so the daemon can recognize the dry-run registration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Authenticate requests with the supplied daemon bearer token

When transport.bearerToken is configured, every generated Roc tool call receives HTTP 401 because the request never includes an Authorization header. The exec service already supplies MCPX_TRANSPORT_BEARER_TOKEN in scriptEnv, and daemon/bearer.go's requireBearer enforces it on every HTTP route. Read that environment variable and attach the bearer token to generated requests.

Useful? React with 👍 / 👎.

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 Forward the run ID so dry-run calls remain intercepted

When a Roc execution is requested with dryRun:true, the generated requests omit X-Mcpx-Run even though the exec service supplies MCPX_RUN. In daemon/server.go, handleCall obtains the run identity exclusively from that header, and dryRunResult declines interception when the identity is empty. Consequently, Roc tool calls execute against real servers during a purported dry run, including calls with destructive side effects. Forward the run ID on every generated request so the daemon can recognize the dry-run registration.

Useful? React with 👍 / 👎.

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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Return an error for tool-level failure responses

When an MCP tool returns isError:true, the daemon preserves that envelope and responds with HTTP 200 (daemon/server.go:1282), so this status-only check returns Ok(response) for a failed tool invocation. Roc callers using the generated Try result for error handling will therefore continue down the success path after a tool failure. Decode the response envelope and convert tool-level failures into Err(ToolError) rather than treating every 2xx response as success; this also preserves the result-error contract in pkgs/mcpx/AGENTS.md.

AGENTS.md reference: pkgs/mcpx/AGENTS.md:L80-L80

Useful? React with 👍 / 👎.

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")
Comment on lines +43 to +44

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore original argument keys before JSON encoding

For schemas containing properties such as a-b, if, or colliding names like a-b and a_b, rocInputFields renames the fields, but this payload serializes the renamed record directly. The daemon consequently receives keys such as a_b, if_, and a_b_2 instead of the schema's original keys, causing required arguments to be missing or values to reach the wrong property. Preserve the original-to-generated field mapping and use the original keys when constructing the JSON request.

Useful? React with 👍 / 👎.

}
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve omission semantics for optional arguments

When a tool schema has optional properties, every property is nevertheless emitted as a mandatory record field, and the complete record is serialized into the request. A caller therefore cannot omit an optional argument to use the server's default or leave a setting unchanged; supplying an empty string, zero, or false is not equivalent to omission. Read the schema's required set and provide an argument representation and encoder that can leave optional keys out of the payload.

Useful? React with 👍 / 👎.

}
if len(fields) == 0 {
return []string{"_unit : {}"}
Comment on lines +100 to +101

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Encode an empty object for tools without arguments

For a tool whose input schema has no properties, the generated signature requires an artificial _unit field. Because the wrapper serializes args unchanged, the request contains {"_unit":{}} rather than {}. A no-argument tool with additionalProperties:false will reject that request. Keep any unit value needed by the Roc call interface separate from the wire arguments and encode an empty object for this case.

Useful? React with 👍 / 👎.

}
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
}
Loading