The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

The mlld SDK provides language bindings for Go, Python, Rust, Ruby, and Elixir. Core capabilities: file-based execution with structured results, string evaluation, runtime tracing, static analysis, in-flight state updates and event streaming via async handles, MCP server injection, signing and verification, and security label helpers.

SDK

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

Two public functions cover all SDK use cases:

processMlld — returns output as a string (simplest API)

const output = await processMlld(script);

execute — returns a structured result object

const result = await execute(filePath, payload);
console.log(result.output);        // text output
console.log(result.stateWrites);   // writes to `state external` slots
console.log(result.sessions);      // final `state session` snapshots
console.log(result.effects);       // output effects
console.log(result.denials);       // guard/policy denials
console.log(result.asks);          // guard/policy review asks
console.log(result.traceEvents);   // runtime trace events
console.log(result.metrics);       // timing (totalMs, parseMs, evaluateMs)

result.sessions holds the final values of each state session attached during the run. Leaf values that still carry labels or other wrapper metadata remain wrapper-bearing values instead of being flattened to plain JSON. The language SDKs return it empty; they report session writes as state:session_write events (see sdk-state).

Streaming — pass stream: true to get real-time events

const stream = await execute(filePath, payload, { stream: true });
stream.on('effect', e => console.log(e));
stream.on('stream:chunk', e => process.stdout.write(e.text));
await stream.done();

The StreamExecution object supports on/off/once event subscriptions and is also an AsyncIterable:

for await (const event of stream) {
  console.log(event.type, event);
}

Runtime tracing — pass trace options to capture execution events

const result = await execute(filePath, payload, {
  trace: 'effects',
  traceMemory: true
});

const memoryEvents = result.traceEvents.filter(event => event.category === 'memory');

traceMemory: true adds memory.* events with RSS, heap, external, and ArrayBuffer samples, plus a final memory.summary event with peak usage and top positive deltas. To correlate memory samples with non-memory runtime events, set trace as well. processMlld() accepts the same trace options, but since it returns only text output, use traceFile to persist trace events:

await processMlld(script, {
  traceMemory: true,
  traceFile: 'tmp/trace.jsonl',
  traceStderr: false
});

Test ambient — pass testMode: true to expose @test in SDK/interpreter tests:

await processMlld(script, { testMode: true });

Execute Function

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

File-based execution with state management.

const result = await execute('./agent.mld', payload, {
  state: { conversationId: '123', messages: [...] },
  payloadLabels: { history: ['.untrusted'] },
  timeout: 30000
});

for (const write of result.stateWrites) {
  await updateState(write.path, write.value);
}

for (const session of result.sessions) {
  console.log(session.name, session.finalState);
}

Features:

  • In-memory AST caching (mtime-based invalidation)
  • Host state passed with state, declared in the program with state external
  • Payload injection via @input.sdk, including per-field labels via payloadLabels
  • Test ambient via testMode: true
  • Writes to state external slots, as state:write events (merged from streamed events + final result)
  • Final state session snapshots via result.sessions
  • Stream handles emit state:session_write events for each write to a state session slot
  • Stream handles support updateState(path, value, labels?), writeFile(path, content), and event consumption via async iteration or next_event
  • mcpServers maps logical names to MCP server commands per-execution
  • Runtime tracing via trace, traceMemory, traceFile, and traceStderr
  • Results include stateWrites, sessions, effects (with security metadata), denials (guard/policy), asks (guard/policy review asks), traceEvents, and metrics (timing)

result.sessions is the final state of each attached state session. Per-write session activity stays in the event stream:

const stream = await execute('./agent.mld', payload, { stream: true });

for await (const event of stream) {
  if (event.type === 'state:session_write') {
    console.log(event.session_write.slot_path, event.session_write.next);
  }
}

These snapshots preserve wrapper-bearing leaves. If a final slot value still carries labels or other .mx metadata, that leaf remains a structured runtime value in result.sessions instead of being flattened away.

MCP server injection lets parallel execute() calls each get independent MCP server instances:

const result = await execute('./agent.mld', payload, {
  mcpServers: { tools: 'uv run python3 server.py --config abc' }
});

The script uses import tools from mcp "tools" as @t — when the SDK supplies mcpServers, "tools" resolves to that command instead of being treated as a shell command.

Memory tracing is request-scoped:

const result = await execute('./agent.mld', payload, {
  traceMemory: true,
  traceFile: 'tmp/trace.jsonl'
});

for (const event of result.traceEvents) {
  if (event.category === 'memory') {
    console.log(event.event, event.data);
  }
}

Use traceMemory to correlate heap/RSS changes with parse, evaluation, LLM calls, tool calls, and parallel batches. Heap size is not an SDK option: the mlld binary has no heap setting.

State Management

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

Host state: state external

The host passes its state when it starts the run:

const result = await execute('./agent.mld', payload, {
  state: { conversationId: '123', count: 0 }
});

The program declares the slots it uses with state external, then reads and writes them like any state:

state external @app = { conversationId: string, count: number, lastResult: string? }
show `Conversation ${@app.conversationId}, count ${@app.count}`
@app.set({ count: 5, lastResult: "report sent" })

On the command line, pass the host state with --state '{"conversationId":"123","count":0}'. A run with no host state cannot read @app: "@app is external state, and this run has no host state to read: the host supplies it when it starts the run."

Every value read from external state carries .src:state:@app.count, which is .src:state matches, and is untrusted by default (@app.count.mx.trust is "untrusted"), because the host, not the program, decides what it holds.

Writes back to the host

Each write to a state external slot is sent to the host as a state:write event naming the slot (path), the value and the operation, and is collected in the execution result:

for (const write of result.stateWrites) {
  await updateState(write.path, write.value);
}

stateWrites merges final-result writes and streamed state:write events emitted during execution.

Which writes reach the host

Two events carry state writes to the host, and they are kept apart so a host never stores one as the other:

Wire event SDK event type Sent for
state:write state_write a write to a state external slot
state:session_write state_session_write a write to a state session slot, including its seed

A write to a plain state @s = { … } sends no event. That state belongs to the run and the host keeps no copy of it; the run's trace records its writes (see Runtime Tracing). See State for the kinds of state.

In-Flight State Updates

SDK clients can change the host state during execution via update_state. The next read of the slot sees the new value. This enables external control of running scripts:

### Python
handle = client.process_async(
    'state external @app = { exit: boolean }\nloop(99999, 50ms) until @app.exit [\n  continue\n]\nshow "done"',
    state={'exit': False},
    timeout=10,
)

time.sleep(0.12)
handle.update_state('exit', True)
print(handle.result())
// Go
handle, _ := client.ProcessAsync(script, &mlld.ProcessOptions{
    State: map[string]any{"exit": false},
    Timeout: 10 * time.Second,
})
time.Sleep(120 * time.Millisecond)
handle.UpdateState("exit", true)
output, _ := handle.Result()

All language SDKs support update_state with retry semantics on REQUEST_NOT_FOUND.

Labeled State Updates

Boundary values injected through update_state can carry security labels, just like labeled values declared in mlld source.

handle.update_state("tool_result", result_text, labels=[".untrusted"])
handle.UpdateState("tool_result", resultText, ".untrusted")
handle.update_state_with_labels("tool_result", result_text, [".untrusted"])?;

Labels applied through SDK state updates:

  • are visible on the value: data labels such as .pii in @app.some_path.mx.labels, trust in .mx.taint (test it with @app.some_path is .untrusted)
  • propagate through normal mlld label flow
  • are optional; omitting labels preserves unlabeled behavior for that updated path
  • may not include a label mlld writes only from what it observed itself (.src:envelope, .src:tape, .src:selector, .src:host, .src:state, .src:fyi, and anything under them): the update is refused with sig.envelope.origin_label, and seed labels naming one refuse the run. A previous run's .src:state labels sent back are dropped rather than refused; mlld adds its own on every read. Report where the host got a value with a channel label such as .src:file or .src:web instead.

Event Streaming

Handles emit events during execution. Use next_event to consume them:

handle = client.execute_async("./agent.mld", payload)

while True:
    event = handle.next_event(timeout=5)
    if event is None or event.type == "complete":
        break
    if event.type == "state_write":
        print(f"State: {event.state_write.path} = {event.state_write.value}")
    elif event.type == "state_session_write":
        print(f"Session: {event.session_write.slot_path} = {event.session_write.next}")
    elif event.type == "guard_denial":
        print(f"Denied: {event.guard_denial.operation}")

result = handle.result()

State writes and guard denials from events are merged into the final ExecuteResult regardless of whether next_event was called. Session writes are reported only as events; result.sessions comes back empty. result() can be called at any time — it blocks until execution completes.

Handle Lifecycle

Handles follow a three-state lifecycle: PENDING → STREAMING → COMPLETE. After COMPLETE, next_event returns null, result() returns the cached result (idempotent), and update_state errors. The terminal semantics are enforced in each wrapper client (e.g. sdk/python/mlld.py); the runtime side is crates/mlld-cli/src/live.rs.

Passing Runtime Context

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

Injecting modules at run time (dynamic_modules) is not available in mlld 2.2.0. Pass runtime context in the payload instead; it needs no files.

execute('./script.mld', { text: 'user input', userId: '123' });
>> @input.sdk is available directly — no import required
show @input.sdk.text
const @name = @input.sdk.userId ? @input.sdk.userId : "anonymous"

CLI usage with mlld run (the script lives in the script directory, llm/run/ by default; to run a file anywhere, use mlld myscript.mld --topic foo --count 5):

mlld run myscript --topic foo --count 5
>> In myscript.mld
show `Topic: ${@input.cli.topic}, Count: ${@input.cli.count}`

Payload values carry the .src:sdk (or .src:cli) label.

Analyze Module

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

Static analysis without execution.

const analysis = await analyzeModule('./tools.mld');

if (!analysis.valid) {
  console.error('Errors:', analysis.errors);
}

const tools = analysis.executables
  .filter(e => analysis.exports.includes(e.name));

AnalyzeResult contains:

Field Description
filepath Absolute path to analyzed file
valid Whether the module is valid
errors Parse/analysis errors (message, line, column)
executables Executable definitions (name, params, labels)
policies Policy declarations (rules, operations, refs)
policyCalls Static analysis of legacy @policy.build(...) / @policy.validate(...) callsites (retired builtins; entries flag callsites to migrate to grants)
records Record declarations and key/read metadata
exports Exported names
imports Import statements (source, names)
guards Guard definitions (name, timing, trigger)
needs Capability requirements (cmd, node, py)

policyCalls entries are conservative by design: analyzable callsites return status: "analyzed" plus diagnostics, while dynamic callsites return status: "skipped" plus a skip reason. The SDK keeps skipped callsites visible so callers can decide whether to surface or ignore them.

Use cases: MCP proxy, module validation, IDE/LSP, policy auditing, security auditing.

In the language wrappers the method is validate(filepath) (the validate method of mlld serve live --stdio). It returns filepath, valid, errors (each with a code and message), warnings, executables, exports, imports, guards, variables and stats. It checks parsing and module metadata; for the full set of checks, run mlld validate (see validate-features).

Input Channels (CLI / SDK Payload)

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

Passed-in input lives under the channel-keyed @input namespace, one channel per source:

Channel What it holds
@input.cli CLI flags / arguments (mlld run, direct invocation, -e)
@input.sdk SDK execute() payload
@input.stdin data piped to stdin
@input.env environment variables

Each channel mirrors its provenance label: .src:cli, .src:sdk, .src:stdin, .src:env.

show `Topic: ${@input.cli.topic}, Count: ${@input.cli.count}`
const @env = @input.cli.env ? @input.cli.env : "dev"

SDK usage lands at @input.sdk:

execute('./script.mld', { topic: 'foo', count: 5 });
show `Topic: ${@input.sdk.topic}, Count: ${@input.sdk.count}`

@input is position-defined

@input means one thing by where it appears:

  • Inside an execution context — an exe body, a pipeline stage, a transform, a hook/guard body — bare @input is the implicit value (the input to that operation).
  • Channel-qualified @input.<channel>[.field] — passed-in input, carrying that channel's .src:* labels. Valid anywhere.
  • Bare @input at the top level, or @input.<non-channel-field> at the top level, is a validation error — channel-qualify it. Templates (backtick, :::, .mtt) count as top level, so a template at the top level must channel-qualify (@input.cli.name).

mlld validate reports each top-level violation with the exact fix.

Importing from @input

import { value } from @input is a convenience form: it resolves value across the channels (cli, stdin, sdk, env) and imports the match.

import { topic } from @input
show `Topic: ${@topic}`

A channel name imports that whole channel:

import { cli } from @input
show `Topic: ${@cli.topic}`

If the same field name exists in more than one channel, the import fails when the script runs (Ambiguous @input import 'topic': present in channels stdin, cli) — the channels carry different trust, so you must qualify it (@input.cli.value) and choose deliberately. An imported value keeps its source channel's .src:* provenance and its gate-honored trust, so a self-attested-but-not-allowlisted field stays untrusted through the import (no laundering).

Per-Field Labels

SDK payload fields can carry security labels at the boundary.

await execute('./agent.mld', {
  history: 'external tool output',
  query: 'user request'
}, {
  payloadLabels: {
    history: ['.untrusted']
  }
});
result = client.execute(
    "./agent.mld",
    {"history": "external tool output"},
    payload_labels={"history": [".untrusted"]},
)

A script that declares args ( … ) (see cli-file) binds those names from the SDK payload the same way it binds them from flags: each value is checked against its type with no conversion ("5" is not a number), an unknown key refuses, and each value carries .src:sdk plus its payload labels. A refusal is an error with code ARGS_USAGE. @input.sdk still holds the payload as sent.

All wrapper SDKs support inline label helpers — labeled, trusted, and untrusted:

from mlld import trusted, untrusted, labeled

result = client.execute(
    "./agent.mld",
    {
        "query": trusted("approved request"),
        "history": untrusted("external tool output"),
        "data": labeled(value, ".pii", ".sensitive"),
    },
)
payload := map[string]any{
    "query":   mlld.Trusted("approved request"),
    "history": mlld.Untrusted("external tool output"),
}

These wrap values so the SDK extracts raw values for the payload and collects labels into payload_labels automatically.

Per-field labels are preserved on direct @input.sdk.field access. Data labels such as .pii show in @input.sdk.<field>.mx.labels; trust shows in .mx.trust, so test it with is (@input.sdk.history is .untrusted).

CLI usage — mlld run, direct invocation, and -e all feed @input.cli:

mlld run myscript --topic foo --count 5
mlld script.mld --topic foo --count 5
mlld -e 'show @input.cli.topic' --topic foo

Unknown flags become @input.cli fields automatically. Kebab-case flags are converted to camelCase (e.g., --dry-run becomes @input.cli.dryRun).

@input.cli is always {} when no flags are passed — safe to reference fields without checking.

CLI sidecar flags — labels and trust

Two reserved suffix flags attach security metadata to a CLI field without becoming payload data:

mlld script.mld --report data.json --report.labels .src:reviewed,.secret
mlld script.mld --report data.json --report.trusted
  • --<field>.labels .a,.b adds the labels .a,.b to @input.cli.<field> (visible at @input.cli.<field>.mx.labels).
  • --<field>.trusted requests trust for @input.cli.<field>.

Both are sidecar — they never appear in the payload data itself.

A trust request is honored only when a policy's self_attestation table gives the field's source channel a row granting trust (in the * block; absent by default, so requests are ignored unless the operator grants it — e.g. * { self_attestation: { sdk: { claims: ["trust"] } } }). The sdk row may be written only in a policy that mlld-config.json's policy.import loads; a script's own policy that writes it is refused when it loads (see security-policies). This is a single per-source gate: requesting trust via --<field>.trusted, via a .trusted label (--<field>.labels .trusted), or via SDK payload_labels with .trusted (and the trusted() helper) all go through the same check, keyed on the field's source. An ungranted request is dropped without a warning: the field stays untrusted. Labeling a field .untrusted is always allowed (it only tightens).

In the wrappers, a host requests trust with payload_labels={'report': ['.trusted']} or the trusted() helper, honored once a config policy sets * { self_attestation: { sdk: { claims: ["trust"] } } }. The JavaScript SDK spells the same request payloadFieldTrust:

await execute('script.mld', { report: data }, {
  payloadFieldTrust: { report: true }
});

mlld validate reports @payload.X, @stdin.X and top-level @input.X as errors and names the @input.<channel> form to use instead.

Language SDKs

Thin wrappers around the mlld CLI for Go, Python, Rust, Ruby, and Elixir. Each keeps a persistent mlld serve live --stdio subprocess for repeated calls via NDJSON RPC.

The mlld serve live --stdio NDJSON protocol is implemented in crates/mlld-cli/src/live.rs; see docs/dev/SDK.md for the SDK architecture.

Core API (all languages)

All SDKs provide:

  • process(script, options) — execute inline mlld, return text
  • execute(filepath, payload, options) — file-based execution, return structured result
  • validate(filepath) — static analysis without execution (see sdk-analyze-module for the fields)
  • process_async / execute_async — return a handle for in-flight control
ExecuteResult

Every execute call returns a structured result:

Field Description
output Text output
state_writes All writes to state external slots (merged: streamed + final)
exports Exported values
effects Output effects with security metadata
denials Guard/policy label-flow denials observed during execution
asks Guard/policy asks sent to the host (with host_asks or ask_handler)
trace_events Runtime trace events (when trace or memory tracing is enabled)
metrics Timing statistics: total_ms (parse_ms and evaluate_ms are reported as 0)
Options

Common options for process and execute:

Option Description
payload_labels Per-field security labels for payload
state The host state, read in the program through state external
mcp_servers Logical name to MCP server command
mode Parsing mode: "strict"
allow_absolute_paths Allow absolute path access
timeout Override client default
trace Runtime trace level: "off", "effects", "handle" / "handles", or "verbose"
trace_memory Include memory.* events; set trace to include non-memory events
trace_file Write trace events as JSONL to a file path
trace_stderr Accepted; has no effect

The dynamic_modules and dynamic_module_source options are refused with METHOD_UNAVAILABLE; pass data through the payload and read it as @input.sdk.<field>.

Naming follows each language's conventions. Go uses TraceMemory; Python, Rust, Ruby, and Elixir use trace_memory. File and stderr options follow the same convention (TraceFile / trace_file, TraceStderr / trace_stderr).

Runtime Tracing

Memory tracing is request-scoped. It emits memory.sample, memory.delta, and a final memory.summary trace event with RSS, peak, and top-delta measurements:

result = client.execute(
    "./agent.mld",
    payload,
    trace_memory=True,
    trace_file="tmp/trace.jsonl",
)

for event in result.trace_events:
    if event.category == "memory":
        print(event.event, event.data)

The heap and heap_snapshot_near_limit client options are accepted and ignored: the mlld binary has no heap setting, so the SDKs pass no heap flag. The options are removed in a later release.

Handle API

Handles follow a three-state lifecycle: PENDING → STREAMING → COMPLETE.

All handle types provide:

Method Description
request_id Unique request identifier
cancel() Request graceful cancellation
update_state(path, value, labels?) Change the host state while the run is in flight
next_event(timeout?) Block until next event; returns null on timeout
wait() / result() Block until complete, return final result

ExecuteHandle also provides:

Method Description
write_file(path, content) Write a file within the execution context; pass an absolute path
Event types from next_event
Type Payload Description
"state_write" StateWrite A state external slot was written (wire event state:write)
"state_session_write" SessionWrite A state session slot was written (wire event state:session_write)
"guard_denial" GuardDenial A guard/policy denied an operation
"guard_ask" GuardAsk A question is waiting for the host to put to a person: a guard/policy ask, or the script's or an agent's own question (only with host_asks)
"effect" Effect Output as it is produced (show, log)
"trace_event" TraceEvent A runtime trace event (when tracing is on)
"complete" none Execution finished

Events are buffered in FIFO order. State writes and guard denials from events are merged into the final ExecuteResult regardless of whether next_event was called — ignoring events does not lose data. For what happens to a guard ask, see Host asks, denials and sealed envelopes.

Terminal semantics
  • result() is idempotent — multiple calls return the same value
  • After cancel(), the handle transitions to COMPLETE with an error
  • After result() returns, next_event returns null
  • update_state and write_file error after COMPLETE

Host asks, denials and sealed envelopes

The SDKs wrap three parts of the live protocol. The wire format and the full rules are in Live STDIO Transport; each SDK's README has per-language examples.

  • Answering asks. By default, a guard or policy ask that the script does not handle ends the request with the error code GUARD_ASK_UNHANDLED, raised as a typed ask error (Python MlldAskError, Go *AskError, Ruby Mlld::AskError, Elixir Mlld.AskError, Rust Error::Ask). To answer asks from the host instead, set ask_handler to a callback that returns the answer, or set host_asks and answer each guard_ask event on a handle with answer_ask. Every ask is a menu: the answer names the chosen option's id ("1" approves a guard or policy ask, "2" denies it), or gives text where the ask allows it, and carries the principal who answered, a stable account id such as gh:12345678 that only the host writes. A script's own match ask question, and an agent's, arrive the same way; show the pieces an agent wrote as the agent's. ask_timeout bounds how long one ask may wait. No answer, a failing handler, or a closed connection all count as no.
  • Migrating from decision. An answer used to be decision: "approve" or "deny"; it is now chosen: "1" or "2", plus the principal. The server refuses the old field by name, and each SDK's answer type changed with it (see each SDK's README).
  • Denials. A guard, policy or law refusal that ends a request fails it with the error code DENIED, raised as a typed denial error (Python MlldDenialError, Go *DenialError, Ruby Mlld::DenialError, Elixir Mlld.DenialError, Rust Error::Denied) that carries the reason, the guard or policy rule, and the refused operation. Code that matched RUNTIME_ERROR to detect a refusal must match DENIED. A refusal the script catches with a denied => arm does not end the request and is listed in the result's denials.
  • Sealing envelopes. seal_envelope (Go SealEnvelope) signs a value with your own ssh key so that mlld admits it, with its labels, as a payload field. It needs ssh-keygen on PATH, and the project's config policy must name your key as an issuer.
  • Checking envelopes. verify_envelope (Go VerifyEnvelope) asks whether a project would admit a sealed envelope, without running anything, and returns the issuer, the claims, and the labels it carries (which can only restrict). A refusal is a result with ok false and a sig.envelope.* code, not an error; an error means the request itself was malformed, and carries the server's code (INVALID_REQUEST). The issuers are the project's own, from its config policy; no SDK takes any. Checking does not use the envelope up, so you can send it into a run afterwards.

Go spells the options HostAsks, AskTimeout and AskHandler, and the method AnswerAsk.

Checking an envelope before sending it, in each SDK (sealed is an envelope from seal_envelope, /abs/project the project whose config policy names the issuers):

Python:

check = client.verify_envelope(sealed, base_path="/abs/project")
if check.ok:
    print(check.issuer, check.claims.source, check.carried_labels.labels)
else:
    print(check.code, check.message)  # e.g. sig.envelope.bad_signature

Go:

check, err := client.VerifyEnvelope(sealed, &mlld.VerifyEnvelopeOptions{BasePath: "/abs/project"})
if err == nil && !check.OK {
    log.Printf("%s: %s", check.Code, check.Message)
}

Rust:

let check = client.verify_envelope(
    sealed,
    Some(VerifyEnvelopeOptions { base_path: Some("/abs/project".into()), ..Default::default() }),
)?;
if !check.ok {
    eprintln!("{:?}: {:?}", check.code, check.message);
}

Ruby:

check = client.verify_envelope(sealed, base_path: "/abs/project")
puts(check.ok ? check.issuer : "#{check.code}: #{check.message}")

Elixir:

case Mlld.Client.verify_envelope(client, sealed, base_path: "/abs/project") do
  {:ok, %Mlld.EnvelopeVerification{ok: true, issuer: issuer}} -> {:admitted, issuer}
  {:ok, %Mlld.EnvelopeVerification{code: code}} -> {:refused, code}
  {:error, error} -> {:error, error}
end

Elixir refuses an :issuers option, or any option but :base_path and :timeout, with INVALID_REQUEST before anything is sent; in the other SDKs there is no such parameter to pass.

Label Helpers

All SDKs provide helpers for attaching security labels to payload values:

Python:

from mlld import execute, trusted, untrusted, labeled

result = execute("script.mld", {
    "config": trusted({"mode": "safe"}),
    "user_input": untrusted(raw_input),
    "data": labeled(value, ".pii", ".sensitive"),
})

Go:

payload := map[string]any{
    "config":     mlld.Trusted(config),
    "user_input": mlld.Untrusted(rawInput),
    "data":       mlld.Labeled(value, ".pii", ".sensitive"),
}

Rust:

payload.insert("config", trusted(config));
payload.insert("user_input", untrusted(raw_input));
payload.insert("data", labeled(value, &[".pii", ".sensitive"]));

Ruby:

payload = {
  "config" => Mlld.trusted(config),
  "user_input" => Mlld.untrusted(raw_input),
  "data" => Mlld.labeled(value, ".pii", ".sensitive"),
}

Elixir:

payload = %{
  "config" => Mlld.trusted(config),
  "user_input" => Mlld.untrusted(raw_input),
  "data" => Mlld.labeled(value, [".pii", ".sensitive"]),
}

Data labels such as .pii show in @input.sdk.<field>.mx.labels; trust shows in .mx.trust. Test either with is (@input.sdk.user_input is .untrusted). Both propagate through mlld policy/guard flow. trusted() takes effect only when a policy that mlld-config.json's policy.import loads sets * { self_attestation: { sdk: { claims: ["trust"] } } }; otherwise the request is ignored. Write labels dotted when you call labeled() yourself.

MCP Server Injection

All SDKs support per-execution MCP server commands:

result = client.execute("./agent.mld", payload,
    mcp_servers={"tools": "uv run python3 mcp_server.py"})

In the mlld script, import tools from mcp "tools" as @t resolves to the SDK-provided command; run from the CLI without mcp_servers, the same line treats tools as a shell command. Each execute() call gets an independent server lifecycle.

Signing

All SDKs expose signing and verification:

signed = client.sign("docs/note.txt", identity=".user.alice")
verified = client.verify("docs/note.txt")
content_sig = client.sign_content("runtime payload", ".user.alice")

### Write a file within an active execution
handle = client.execute_async("./agent.mld")
file_result = handle.write_file("/abs/path/out.txt", "hello from sdk")

fs_status is refused (METHOD_UNAVAILABLE); use mlld sig drift or mlld sig unsigned from the command line.

Host sessions and tapes in each SDK

Every SDK supports every host-session and tape feature below. The table gives each one's spelling; the sections after it explain the features, and each SDK's README has the full signatures.

Feature Go Python Ruby Elixir Rust
Open, record, close OpenHostSession, Record*, Close open_host_session, record_*, close same as Python Client.open_host_session/5, the HostSession.record_* functions, HostSession.close/1 same as Python
Helper start and stop RecordHelperStart, RecordHelperStop record_helper_start, record_helper_stop same as Python HostSession.record_helper_start/2, record_helper_stop/2 same as Python, taking a Helper
Batches RecordBatch with a HostBatch record_batch with a HostBatch same as Python HostSession.record_batch/3 same as Python
Stored bodies and body keys HostSessionOptions.Bodies bodies= bodies: bodies: HostSessionOptions.bodies
Host storage HostSessionOptions.Store store= store: store: (each result carries stored) HostSessionOptions.store
Lock wait on open (SESSION_BUSY past it) HostSessionOptions.LockWait (a time.Duration) lock_wait= (seconds) lock_wait: (seconds) lock_wait: (milliseconds) HostSessionOptions.lock_wait (a Duration)
Trusted signers HostSessionOptions.TrustedSigners, SetTrustedSigners, SignersFrom trusted_signers=, set_trusted_signers, signers_from trusted_signers:, set_trusted_signers, signers_from trusted_signers:, HostSession.set_trusted_signers/2, signers_from HostSessionOptions.trusted_signers, set_trusted_signers, signers_from
Making verified heads MakeHeads make_heads make_heads HostSession.make_heads/2 make_heads
Opening with heads HostSessionOptions.Heads, HostSummary, Admissions heads=, host_summary=, admissions heads:, host_summary:, admissions heads:, host_summary:, admissions HostSessionOptions.heads, host_summary, admissions
Checking a whole session VerifySession verify_session verify_session Client.verify_session/5 verify_session with VerifySessionOptions
Checking a tool call Check check check HostSession.check/2 check
Calling an exported function Call with CallOptions call call Client.call/5 call with CallOptions
Call options DeadlineMs, NoEffects, HelperHistory, Readable, Tapes, TrustedSigners, BodyKeys deadline_ms, no_effects, helper_history, readable, tapes, trusted_signers, body_keys same as Python same as Python same as Python
Module digest ModuleDigest module_digest module_digest Client.module_digest/3 module_digest
Checking an envelope VerifyEnvelope verify_envelope verify_envelope Client.verify_envelope/3 verify_envelope

Recording a host session

A host can record a session of its own (an agent harness's conversation, say) on a tape through mlld, with no script running: mlld writes, chains and seals every record, and the host does no cryptography (see live-stdio, Host session tapes). Recording grants nothing by itself. The Go SDK:

session, err := client.OpenHostSession("harness", "fray", "s-42", &mlld.HostSessionOptions{BasePath: "/path/to/project"})
if err != nil { return err }

session.RecordUserTurn(mlld.UserTurn{Conversation: "main", Text: "push it", Labels: []string{".src:user:intent:literal"}})
session.RecordToolCall(mlld.ToolCall{Tool: "harness:claude/Bash", ToolUseID: "toolu_1", Args: map[string]any{"command": "git push"}})
session.RecordToolResult(mlld.ToolResult{Tool: "harness:claude/Bash", ToolUseID: "toolu_1", Value: map[string]any{"stdout": "pushed"}})
event, err := session.RecordNote(mlld.Note{Kind: "phase", Text: "after push"})
// event.Event is "<tape>/<event id>"; event.Sealed says whether a seal covers it.

closed, err := session.Close()

Each record returns once its event and the seal over it are on disk. session.Sealed (and each record's Sealed) is false, with SealReason, when the project's config lists no signers or the ssh-agent is unavailable and no host-bound signer can sign instead (see policy-signers, "Host-bound signers"). A host-bound seal covers only the session's own host events. A session belongs to the client's connection: client.Close() closes and seals every session still open, waiting up to 15 seconds for the server to finish before it stops it and returns an error. Errors are *mlld.Error with the server's code: TAPE_NOT_FOUND for a closed session, INVALID_REQUEST for a missing field, RUNTIME_ERROR for a refused record (a tool call with no args, a turn labelled secret).

A host that keeps the session's bytes in its own storage (a database row, an encrypted object) instead of files passes Store: &mlld.TapeBytes{}, or what it kept from earlier calls, in HostSessionOptions. mlld checks the bytes it is handed as it checks files, and every call adds what it wrote to that TapeBytes, which the host saves after each call (see live-stdio, "Keeping the session's bytes yourself"). The other SDKs take the same on open_host_session: Python store=TapeBytes(), Ruby store: Mlld::TapeBytes.new, Rust HostSessionOptions { store: Some(Arc::new(Mutex::new(TapeBytes::default()))), .. }, each filled by every answer as Go's is, and Elixir store: %Mlld.TapeBytes{}, where Elixir values do not change, so each result (the session, each record, batch, check and close) carries stored and Mlld.TapeBytes.add/2 adds it to what you keep.

Stored bodies. A host that wants to delete what was said later, and keep a tape that still verifies, asks for every event body to be stored apart from its line, and can name stored bodies by a keyed hash so that nobody holding the tape can test a guess at a deleted one (see cli-tape, "Stored bodies"). Every SDK takes this when it opens a session: Go HostSessionOptions.Bodies: &mlld.BodyStorage{StoreAll: true, Keys: []mlld.BodyKey{{ID: "k1", Key: secret}}}, Python bodies=BodyStorage(store_all=True, keys=[BodyKey("k1", secret)]), Ruby bodies: Mlld::BodyStorage.new(store_all: true, keys: [Mlld::BodyKey.new(id: 'k1', key: secret)]), Elixir bodies: %Mlld.BodyStorage{store_all: true, keys: [%Mlld.BodyKey{id: "k1", key: secret}]}, Rust HostSessionOptions { bodies: Some(BodyStorage { store_all: true, keys: vec![BodyKey { id: "k1".into(), key: secret }] }), .. }. A stored body is the RFC 8785 canonical JSON of the event's body fields (for an event of your own type, {"data": <data>}), and its file is named by the SHA-256 of those bytes, or by the HMAC-SHA256 under your key, so you can compute the name before you hand the event over (see tape-methods, "Stored and pruned bodies", for the test vectors). The key is raw bytes, at least 16, and the SDK sends it base64-encoded on tape:open's bodies. The first key names new bodies; later ones check bodies written under earlier keys. The session keeps the keys for its checks, heads and close. Keys are secrets: the SDK types print the id only, and mlld never writes a key to the tape or echoes it in an answer or error. A key lets mlld check a body, never trust it, and a body checked under a different key with the same id counts as changed. A no-effects call that lists tapes takes body keys too (Go CallOptions.BodyKeys, body_keys elsewhere), so the module reads keyed bodies on those tapes back instead of finding them uncheckable (see live-stdio, bodyKeys, and "Calling an exported function" below).

The Python SDK uses the same names in snake case, and a session works as a context manager:

with client.open_host_session("harness", "fray", "s-42", base_path="/path/to/project") as session:
    session.record_user_turn("main", "push it", labels=[".src:user:intent:literal"])
    session.record_tool_call("harness:claude/Bash", "toolu_1", {"command": "git push"})
    session.record_tool_result("harness:claude/Bash", "toolu_1", {"stdout": "pushed"})
    event = session.record_note("phase", "after push")
    # event.event is "<tape>/<event id>"; event.sealed says whether a seal covers it.

Leaving the with block calls session.close(). client.close() closes and seals every session still open, waiting up to 15 seconds for the server to finish before it stops it. Errors are MlldError with the server's code in .code.

The Rust SDK takes one struct per kind, as Go does:

use mlld_sdk::{HostSessionOptions, Note, ToolCall, ToolResult, UserTurn};
use serde_json::json;

let session = client.open_host_session("harness", "fray", "s-42", Some(HostSessionOptions {
    base_path: Some("/path/to/project".into()),
    ..Default::default()
}))?;

session.record_user_turn(UserTurn {
    conversation: "main".into(),
    text: "push it".into(),
    labels: vec![".src:user:intent:literal".into()],
    ..Default::default()
})?;
session.record_tool_call(ToolCall {
    tool: "harness:claude/Bash".into(),
    tool_use_id: "toolu_1".into(),
    args: Some(json!({"command": "git push"})),
    ..Default::default()
})?;
session.record_tool_result(ToolResult {
    tool: "harness:claude/Bash".into(),
    tool_use_id: "toolu_1".into(),
    value: json!({"stdout": "pushed"}),
    ..Default::default()
})?;
let event = session.record_note(Note {
    kind: "phase".into(),
    text: "after push".into(),
    ..Default::default()
})?;
// event.event is "<tape>/<event id>"; event.sealed says whether a seal covers it.

let closed = session.close()?;

client.close(), or dropping the last clone of the client, closes and seals every session still open, waiting up to 15 seconds for the server to finish before it kills it. Errors are Error::Mlld with the server's code in code.

Ruby:

session = client.open_host_session('harness', 'fray', 's-42', base_path: '/path/to/project')

session.record_user_turn(conversation: 'main', text: 'push it', labels: ['.src:user:intent:literal'])
session.record_tool_call(tool: 'harness:claude/Bash', tool_use_id: 'toolu_1', args: { 'command' => 'git push' })
session.record_tool_result(tool: 'harness:claude/Bash', tool_use_id: 'toolu_1', value: { 'stdout' => 'pushed' })
event = session.record_note(kind: 'phase', text: 'after push') # event.event, event.seq, event.sealed

closed = session.close # closed.events, closed.sealed

Errors raise Mlld::Error with the server's code in error.code. client.close lets the server close and seal any session still open before it returns.

Elixir:

alias Mlld.HostSession

{:ok, session} = Mlld.Client.open_host_session(client, "harness", "fray", "s-42", base_path: "/path/to/project")

{:ok, _} = HostSession.record_user_turn(session, conversation: "main", text: "push it", labels: [".src:user:intent:literal"])
{:ok, _} = HostSession.record_tool_call(session, tool: "harness:claude/Bash", tool_use_id: "toolu_1", args: %{"command" => "git push"})
{:ok, _} = HostSession.record_tool_result(session, tool: "harness:claude/Bash", tool_use_id: "toolu_1", value: %{"stdout" => "pushed"})
{:ok, event} = HostSession.record_note(session, kind: "phase", text: "after push")
### event.event, event.seq, event.sealed

{:ok, closed} = HostSession.close(session)

Errors come back as {:error, %Mlld.Error{code: code}} with the server's code. Mlld.Client.stop/1 lets the server close and seal any session still open before it returns.

What else a session records

Besides user turns, tool calls, tool results and notes, the SDKs record the kinds below. Each SDK README's "Recording a Host Session" section gives its spelling; the fields are the live tape:record kinds (see config-live-stdio, Host session tapes).

  • Delivered messages: a message handed to the agent as its prompt is recorded as a user turn with the labels the message carried and who sent it, its sender kind: agent for another agent, person for a person (record_user_turn with labels and sender_kind, Go RecordUserTurn with Labels and SenderKind; each SDK has constants for the two values, Python, Ruby and Rust SENDER_KIND_AGENT and SENDER_KIND_PERSON, Go SenderKindAgent and SenderKindPerson; Elixir takes the strings). Any other value is refused with INVALID_REQUEST. A message from another agent counts toward the session's influence whether or not it carries labels, so no second event is needed beside it; mlld marks it .src:agent, which a config can list in clear.sources so a person can clear it (see policy-basics). Without a sender kind, only untrusted labels on it count, as an untrusted tool result's do. A person's message is recorded with sender kind person, their principal, or both: it counts as trusted only when it is the words of the person the run works for, labelled .src:user:intent:* under the config's host intent grant, and is untrusted otherwise (see builtins-ambient-mx, influence).
  • Outcome: a tool result with outcome failed (and an error) or denied (and who denied it and why) records a call that ended without a value. It never counts as a value or a fact, though its labels still count toward the session's influence.
  • Host fields: tool calls and results take hostFields (host_fields), an object of the host's own fields such as paths, intent, model or turn id, at most 64 KiB as JSON; a larger one is refused with HOST_FIELDS_TOO_LARGE. Notes take data and facts, a list of {kind, value} pairs that can hold several facts of one kind (Go []mlld.Fact, Rust Vec<Fact>; Python, Ruby and Elixir also take an object of kind to value as shorthand for one fact per kind), and every kind takes source, the hook or component that wrote it, author, the host's permanent id for whose words these are (never a principal), and occurredAt (occurred_at), an RFC 3339 time the host says it happened; the line keeps mlld's own time. These are the host's claims: none becomes a label, a fact, proof or a principal.
  • Helpers: a helper's start and stop (a subagent the agent ran), paired by the host's helper id and linked to the tool call that started it. Every SDK records them (Go RecordHelperStart and RecordHelperStop, record_helper_start and record_helper_stop elsewhere), and a HostBatch takes them with its add_helper_start and add_helper_stop (Go AddHelperStart, AddHelperStop). Nothing checks that a stop has a start, and neither counts as a label, a fact or proof.
  • Host-defined events: an event of a type the host defines, <namespace>.<name> such as opgate.checkpoint, with data, facts and host fields and no labels (Go RecordEvent, Python record_event, Ruby record_event, Elixir record_event/2, Rust record_event; live kind event). A namespace mlld uses is refused. A signature or key id the host carries goes in its host fields, which stay in the event when a stored body (data) is deleted. It is a claim, as a note is: .select finds it by type or fact.
  • Assistant turns: a model's reply, the provider's message stored byte for byte.
  • Clear: a person setting influence causes aside. It counts only under the project config's host clear row and a verified seal, and never for a never: law or a locked rule.
  • Batches: many records in one request, written in order, sealed once and put on disk once, for a host importing a history or a transcript. All or nothing: one refused record refuses the batch, the error names its index, and nothing is written. Every SDK sends them with a HostBatch whose add_* methods take what the matching record method takes: Go RecordBatch (a refusal is a BatchError), Python record_batch (MlldBatchError), Ruby record_batch (Mlld::BatchError), Elixir HostSession.record_batch/3 ({:error, %Mlld.Error{index: i}}) and Rust record_batch (Error::Batch); each refusal carries the index. On the wire it is tape:record with records (see config-live-stdio, Batches).
Trusted signers

A host can say which signer keys it trusts for the session's files, for a project whose config names no signers (see live-stdio, trustedSigners). The keys are given by principal, in the shape of an entry in the config's signers: a public key line, with optional validity times and a host-bound key. They check the files' seals and never sign. A config that names any signers is the whole trust set, and the host's keys are then ignored. The session's signers_from (Go SignersFrom), and each check result's, says which set was used: "config", "host" or "none". set_trusted_signers (Go SetTrustedSigners) replaces the keys from the next check or make_heads on; passing none drops them. A verified head made under one set of keys is not admitted under another.

from mlld import TrustedSigner

keys = {"fray": TrustedSigner(key="ssh-ed25519 AAAA...")}
session = client.open_host_session("harness", "fray", "s-42", trusted_signers=keys)
print(session.signers_from)  # "host" when the config names no signers
Verified heads

A verified head is a signed statement that one file of the session checked out through its last line, with what the next check needs to go on from there (see cli-tape, "Checking the whole session, and verified heads"). make_heads (Go MakeHeads) makes one for each file that verifies and ends in a seal. It signs through the user's ssh-agent with a key the project's config lists under tape.checkers, and binds the host's own record of the session (host_summary) when one is given; mlld only hashes that record. Keep each head's three fields (statement, signature, fold) unchanged, with the record it binds. Handed to a later open with heads and host_summary, the heads spare that open from checking the seal signatures again up to each head. The session's admissions say which heads counted; one that does not count (its code says why, such as HEAD_EXPIRED) leaves its file checked in full.

made = session.make_heads(host_summary=my_record)
### Later, perhaps from another process:
session = client.open_host_session("harness", "fray", "s-42", heads=made.heads, host_summary=my_record)
for admission in session.admissions:
    print(admission.run_id, admission.admitted, admission.code)
Checking a whole session

verify_session (Go VerifySession) checks every file of a session without opening it: no handle, no lock, and nothing written. It reports whether the session verifies, each file's result, and the session's influence ("untouched", "influenced" or "cleared"). A host that keeps a session in pieces passes only the lines added since the last head as that file's bytes (store), with that head and the record it binds, and only the new lines are read. Asking for new heads (make_heads, with next_host_summary) returns the heads to keep for the next piece. A head that does not count refuses its file, and the session then reads as influenced, since the earlier lines are not there to check. Trust in those earlier lines rests on the checker key that signed the head: a change made to them after it was signed is found only by a full check of the whole session.

verdict = client.verify_session(
    "harness", "fray", "s-42",
    store=TapeBytes(files={run_id: new_lines}), heads=made.heads, host_summary=my_record,
    make_heads=True, next_host_summary=my_next_record,
)
print(verdict.verified, verdict.influence)
next_heads = verdict.heads
Checking a tool call before the harness runs it

On an open host session, check (Go Check) asks whether a harness tool call would be allowed, asked or denied, by the project's policy, guards and grants and the session's history. Nothing runs, nobody is asked, and no approval is used up (see live-stdio, Checking a harness tool call).

answer, err := session.Check(mlld.ToolCheck{
    Tool: "harness:claude/Bash", ToolUseID: "toolu_2",
    Args: map[string]any{"command": "git push"}, Labels: []string{".op:tool:w"},
})
// answer.Verdict is "allow", "ask" or "deny"; answer.Reason says why.
answer = session.check("harness:claude/Bash", {"command": "git push"}, labels=[".op:tool:w"])
let answer = session.check(ToolCheck {
    tool: "harness:claude/Bash".into(),
    args: json!({"command": "git push"}),
    labels: vec![".op:tool:w".into()],
    ..Default::default()
})?;
answer = session.check(tool: 'harness:claude/Bash', args: { 'command' => 'git push' }, labels: ['.op:tool:w'])
{:ok, answer} = HostSession.check(session, tool: "harness:claude/Bash", args: %{"command" => "git push"}, labels: [".op:tool:w"])
  • The tool's operation labels (labels) count in full only when the project's config lets the host name that tool (the host row's tool claim and tool.tools list; see policy-basics). Otherwise the call is judged as an unnamed tool and named is false; its labels can then only refuse the call (a deny, ask or guard on them applies) and never let it through (an allow! exception, an only or allow list, or a guard's allow on them has no effect).
  • arg_labels (Go ArgLabels) puts restricting labels, such as untrusted, on every argument.
  • The result also carries the ask or denial object when there is one, and check, the tape position mlld why reads the check by.
  • No SDK takes a policy or a mapping module: the project's mlld-config.json chooses them.
  • Errors carry the server's code: CHECK_UNAVAILABLE when the answer depends on code a check would have to run, TAPE_NOT_FOUND for a closed session, INVALID_REQUEST for a malformed or refused field.

Calling an exported function

call (Go Call) runs one function a module exports and returns its value as JSON, with its labels and taint. The server keeps the module loaded between calls, so later calls are fast. Every argument carries .src:sdk. Call options set a deadline (RUN_TIMEOUT when it passes) and can refuse every effect the call tries (DENIED). See config-live-stdio, Calling an exported function, for the rules, and each SDK README's "Calling an Exported Function" for its signature.

Every SDK takes the same call options (Go spells them as CallOptions fields):

  • deadline_ms (Go DeadlineMs) stops the call after that many milliseconds with RUN_TIMEOUT. A hard limit needs no_effects too.
  • no_effects (Go NoEffects) refuses every effect the call tries (commands, network, file writes, llm calls, state writes and the like); a refusal is a DENIED error.
  • With no_effects, the module's @mx.history keeps each call the function makes as its name, id, order and outcome only, without its arguments. helper_history (Go HelperHistory) changes that: full keeps them in full, for a module that reads its helper calls' arguments back; slim is the default; none keeps no entry for them at all, so @mx.history and @mx.tools.calls do not see them, for a judge that reads neither and wants the least memory. Go spells the values HelperHistoryFull, HelperHistorySlim and HelperHistoryNone, Rust HelperHistory::Full and so on, Elixir :full, :slim and :none; Python and Ruby take the strings.
  • With no_effects, readable lists the files and folders the call may read (inside the project, never .llm/), and tapes the named tapes; with neither it reads no file and no tape.
  • trusted_signers gives the keys a listed tape's seals verify against when the project's config names no signers, as on a host session.
  • body_keys gives the body keys for the listed tapes, so the module reads their keyed bodies back instead of finding them uncheckable.

A judge reading a host session without being able to change anything:

result = client.call(
    "./judge.mld", "review", {"session": "s-42"},
    no_effects=True, deadline_ms=5000,
    tapes=["harness"], trusted_signers=keys, body_keys=[BodyKey("k1", secret)],
)
print(result.value, result.labels)
Module digest

module_digest (Go ModuleDigest) returns the digest of a module and every module its imports reach (mlld-module-v1:sha256:…), with the mlld version that computed it. It is the value a script reads with @mx.moduleDigest, and the same for the same files on any machine, so two parties can compare digests to show they ran the same code. It is computed from the files as they are now, not from what call has loaded. From the command line, mlld module digest <path> prints the same digest without a server.

d = client.module_digest("./judge.mld")
print(d.digest, d.mlld_version)

Installation

### Go
go get github.com/mlld-lang/mlld/sdk/go

### Python
pip install mlld-sdk

### Rust
### Add to Cargo.toml: mlld-sdk = "2.0"

### Ruby
cd sdk/ruby && gem build mlld.gemspec && gem install ./mlld-*.gem

### Elixir
cd sdk/elixir && mix deps.get

Quick Start Examples

Python:

from mlld import Client

client = Client()
output = client.process('show "Hello World"')

result = client.execute('./agent.mld', {'text': 'hello'},
    state={'count': 0},
    timeout=10)
print(result.output)
client.close()

Go:

client := mlld.New()
output, _ := client.Process(`show "Hello World"`, nil)

result, _ := client.Execute("./agent.mld",
    map[string]any{"text": "hello"},
    &mlld.ExecuteOptions{
        State: map[string]any{"count": 0},
        Timeout: 10 * time.Second,
    })
fmt.Println(result.Output)
client.Close()

Rust:

let client = Client::new();
let output = client.process(r#"show "Hello World""#, None)?;

let result = client.execute("./agent.mld",
    Some(json!({"text": "hello"})),
    Some(ExecuteOptions {
        state: Some(json!({"count": 0})),
        timeout: Some(Duration::from_secs(10)),
        ..Default::default()
    }))?;
println!("{}", result.output);

Elixir:

{:ok, client} = Mlld.Client.start_link(command: "mlld", timeout: 30_000)

{:ok, result} = Mlld.Client.execute(client, "./agent.mld", %{"text" => "hello"},
    state: %{"count" => 0},
    timeout: 10_000)
IO.puts(result.output)

Elixir-Specific Features

The Elixir SDK adds BEAM-native features beyond the core spec:

  • Supervision — Mlld.Client is a GenServer with child spec support
  • Connection pool — Mlld.Pool with checkout/checkin and overflow
  • Telemetry — :telemetry events with [:mlld, ...] prefix
  • Event subscriptions — subscribe/unsubscribe for OTP-style message passing
  • Task integration — process_task/execute_task for Task.await/yield
  • Phoenix bridge — Mlld.Phoenix.stream_execute for channel integration

Requirements

All SDKs require the mlld binary on PATH, or its path passed as the client's command option. The binary is self-contained; no Node.js runtime is needed.

Result details

  • exports values are null. ExecuteResult.exports reports accurate names with null values.
  • sessions is empty. The final session snapshot list comes back as [].
  • Host state labels. Every value read from the host state carries a .src:state:@app.<slot> label, which is .src:state matches; labels you pass with the seed or with update_state are added to it.

Errors are the same MlldError shape in every language; METHOD_UNAVAILABLE refusals arrive as ordinary request errors you can catch and branch on.

VirtualFS Overlay

The JavaScript/TypeScript SDK is not available in mlld 2.2.0. The Python, Go, Rust, Ruby and Elixir wrappers over mlld serve live --stdio are (see sdk-language-sdks).

VirtualFS provides a copy-on-write filesystem overlay for SDK runs.

import { VirtualFS, NodeFileSystem } from 'mlld';

const vfs = VirtualFS.over(new NodeFileSystem());

Inspection and lifecycle APIs:

const changes = await vfs.changes(); // canonical
const alias = await vfs.diff();      // compatibility alias
const unified = await vfs.fileDiff('/path/file.ts');

Selective apply/discard:

for (const change of await vfs.changes()) {
  if (await approve(change)) {
    await vfs.flush(change.path);
  } else {
    vfs.discard(change.path);
  }
}

Patch export/replay:

const patch = vfs.export();

const replay = VirtualFS.over(new NodeFileSystem());
replay.apply(patch);
await replay.flush();