JSONValue in the iOS SDK

Use the JSONValue enum to read tool arguments and build tool results in Swift, with literal syntax, accessors and decoding into your own types.

Working draft. These docs are illustrative: names, endpoints and examples describe the intended behaviour and can change before launch.

Swift has no built-in type for arbitrary JSON, so the SDK ships JSONValue. It carries the arguments the agent sends to a client tool and the result your handler returns. Android uses JsonObject from kotlinx.serialization for the same job.

The type

public enum JSONValue: Sendable, Codable, Hashable {
    case string(String)
    case number(Double)
    case bool(Bool)
    case object([String: JSONValue])
    case array([JSONValue])
    case null
}

JSONValue conforms to Codable, so it encodes and decodes with JSONEncoder and JSONDecoder.

Build values with literals

JSONValue adopts the expressible-by-literal protocols for strings, integers, floating point numbers, booleans, arrays, dictionaries and nil. You can write JSON almost as you would in a JSON file.

let result: JSONValue = [
    "opened": true,
    "orderId": "ord_42",
    "items": [1, 2, 3],
    "note": nil,
]

The dictionary literal becomes .object, the array literal becomes .array and nil becomes .null.

Read values with accessors

Accessor Returns Notes
stringValue String? nil unless the value is a string.
doubleValue Double? Works for any number.
intValue Int? nil if the number has a fraction.
boolValue Bool? nil unless the value is a boolean.
objectValue [String: JSONValue]? The dictionary of an object.
arrayValue [JSONValue]? The elements of an array.
isNull Bool true for .null.

Each accessor returns nil instead of crashing when the type is different, so you can chain them with guard let.

guard let id = args["orderId"]?.stringValue,
      let quantity = args["quantity"]?.intValue else {
    return ["error": "orderId and quantity are required"]
}

Decode into your own type

When a tool has many arguments, decode them once into a Decodable struct.

struct OrderArgs: Decodable {
    let orderId: String
    let quantity: Int
}

let data = try JSONEncoder().encode(JSONValue.object(args))
let order = try JSONDecoder().decode(OrderArgs.self, from: data)

Catch the decoding error and return a small ["error": ...] result so the agent can ask the customer for the missing detail.

Tip: Keep results small and flat. The agent reads them as text, so short keys with plain values work best.

Something unclear or missing? Tell us and we will fix the page.