JSON mapping

View Source

This page is the reference for how a component's types become JSON Schema, and JSON values become native values and back. You need it when you call tools from JSON (an HTTP API, a queue, an agent) or read the schemas MCP clients get. The native API never uses JSON; wasm_tools_json does the conversion when you ask for it.

Types and values

WITJSON SchemaJSON value
boolbooleantrue
s8 to s32, u8 to u32integer with minimum and maximum42
s64, u64an integer in range, or a decimal stringa number up to 2^53-1 in magnitude, a string beyond
f32, f64numberNaN and the infinities have no JSON form and are refused
chara string of one character"a"
stringstring"text"
list<u8>string, contentEncoding: base64"aGk="
list<T>array[1, 2]
recordobject; every field required except an optionevery field written, none as null
tuplearray with prefixItems, fixed length[1, "a"]
variantoneOf objects with a tag, and a val for a case with a payload{"tag": "circle", "val": 2.0}
enumstring with enum"red"
flagsarray of distinct names["read", "write"]
option<T>anyOf [T, null]null for none
result<T, E>oneOf {"ok": T} and {"error": E}{"ok": 1}
  • A 64-bit integer past 2^53-1 is written as a decimal string, because many JSON readers lose its last digits. On the way in, both forms are accepted.
  • option<option<T>> is refused: none and some(none) would both be null.
  • Resources, streams, futures and error contexts have no JSON form.

A function's schemas

Def = #{params => [{<<"a">>, s32}, {<<"b">>, s32}], result => s32},
{ok, #{input := In, output := Out}} = wasm_tools_json:schema(Def),
{maps:get(<<"required">>, In), maps:keys(maps:get(<<"properties">>, Out))}.
%% => {[<<"a">>, <<"b">>], [<<"result">>]}

The output is always an object {"result": V}, because MCP wants structured content to be an object. For a function returning result<T, E>, the output is T, and an err is reported apart.

Convert

Person = {record, [{<<"name">>, string}, {<<"age">>, u8}, {<<"email">>, {option, string}}]},
{ok, Native} = wasm_tools_json:native(Person, #{<<"name">> => <<"Ada">>, <<"age">> => 36}),
Native.
%% => #{<<"name">> := <<"Ada">>, <<"age">> := 36, <<"email">> := none}
wasm_tools_json:value(Person, Native).
%% => {ok, #{<<"email">> := null}}
wasm_tools_json:native(Person, #{<<"name">> => <<"Ada">>, <<"age">> => 300}).
%% => {error, #{class := argument, ctx := #{path := [<<"age">>]}, msg := <<"expected an integer from 0 to 255 at /age">>}}
functiondoes
schema(Def)the input and output schemas of a function
value_schema(Desc)the schema of one type
args(Def, Json)a function's arguments, from a JSON object, as wasm_tools:call/3 takes them
native(Desc, Json)one value, from JSON
value(Desc, Native)one value, as JSON
output(Def, Native)a function's result as its output object, or {guest_error, E}

An error's ctx holds path, the JSON pointer segments to the value, and its message ends with the pointer itself (/age).