Packages

Load WebAssembly components and call them as tools from Erlang, Elixir and MCP

Current section

Files

Jump to
erlang_wasm_tools docs elixir.md
Raw

docs/elixir.md

# Elixir

This page shows wasm_tools from Elixir. Everything else in these docs applies:
the functions are the same, called as `:wasm_tools`. `examples/elixir/` is a Mix
project that runs every line below.

## Add the dependency

```elixir
defp deps do
  [{:wasm_tools, "~> 0.1", hex: :erlang_wasm_tools}]
end
```

## Load and call

Names and map keys are binaries, which in Elixir are strings:

```elixir
{:ok, calc} = :wasm_tools.load({:file, "calculator.component.wasm"})
{:ok, 42} = :wasm_tools.call(calc, "add", %{"a" => 20, "b" => 22})
:ok = :wasm_tools.unload(calc)
```

Values follow the table of [Call a component](call-a-component.md): a record is a
map with string keys, a variant `{"case", payload}`, an option `:none` or
`{:some, value}`, a result `{:ok, value}` or `{:error, value}`.

```elixir
{:ok, data} = :wasm_tools.load({:file, "data_transform.component.wasm"})

{:ok, {:ok, person}} =
  :wasm_tools.call(data, "normalize", %{
    "p" => %{"name" => " Ada ", "age" => 36, "email" => :none, "tags" => ["b", "a"]}
  })

"Ada" = person["name"]
```

## Errors

Errors are maps with atom keys:

```elixir
case :wasm_tools.call(calc, "add", %{"a" => 1}) do
  {:ok, value} -> value
  {:error, %{class: :argument, ctx: %{path: path}}} -> {:bad_argument, path}
end
```

## Put a registry in your supervision tree

```elixir
children = [
  :wasm_tools.child_spec(%{name: :tools, max_concurrency: 64})
]

Supervisor.start_link(children, strategy: :one_for_one)

{:ok, ["calc_add", "calc_multiply"]} = :wasm_tools.add(:tools, calc, %{namespace: "calc"})
{:ok, 42} = :wasm_tools.call(:tools, "calc_add", %{"a" => 20, "b" => 22})
```

## Host interfaces

A handler is a function of three arguments, or a module with `handle/3`:

```elixir
kv = fn
  "get", [key], _ctx -> {:some, "value of " <> key}
  "put", [_key, _value], _ctx -> :undefined
end

{:ok, app} =
  :wasm_tools.load({:file, "custom_host.component.wasm"},
    %{host: %{"example:app/kv" => kv}})
```