Skip to content
QwryAI
Documentation
Pages

iOS SDK

Client-Side Tools

Let your QwryAI agent run Swift code on the device in the middle of an answer

Some questions can only be answered on the phone: what's in the user's cart, which screen they're on, what they picked in a sheet. A client-side tool is a Swift closure you register on QwryClient. When the agent calls it, the SDK runs it, sends the result back and the agent carries on answering, all inside one send.

What are client-side tools?

A client-side tool is the app half of a custom action whose type is Run client-side code. The action in the dashboard tells your agent the tool exists and when to use it. Your handler in the app does the work.

Set up the action in the dashboard

  1. Create a custom action that runs on the client

    Go to Actions and create a custom action. Give it an Action name such as get_cart and describe when the agent should use it. Under the action type, choose Run client-side code ("This action will run custom code on the client"). See Custom action for the editor itself.

  2. Switch it on for the iOS SDK

    Open Channels → iOS SDK → Actions, switch the action on and select Save changes. Only actions that can run in an app are listed there.

    Actions lists what the agent may use inside the SDK.

tool

Swift
public func tool(_ name: String, handler: @escaping @Sendable (JSONValue) async throws -> JSONValue)

Registers a handler. Registering the same name again replaces the old handler. QwryClient is an actor, so call it with await.

ParameterTypeRequiredDescription
nameStringYesThe tool name. Must match the action's Action name.
handler@Sendable (JSONValue) async throws -> JSONValueYesAn async closure. It receives the tool's input as a JSONValue and returns the result as a JSONValue.
Swift
await client.tool("get_cart") { _ in
    let items = await CartStore.shared.items
    return [
        "count": .number(Double(items.count)),
        "items": .array(items.map { .string($0.name) }),
        "total": .string(CartStore.shared.formattedTotal)
    ]
}

Register your tools right after you create the client, before the first send:

Swift
let client = QwryClient(agentId: "YOUR_AGENT_ID")
await client.tool("get_cart") { ... }
await client.tool("lookup_order") { ... }

To stop handling a tool, remove it:

Swift
await client.removeTool("get_cart")

How the tool loop works

One send can go back and forth with the server several times:

  1. You send a message

    client.send("What's in my cart?") opens the answer stream.

  2. The agent calls a tool

    The SDK calls your onToolCall handler and looks up the tool you registered.

  3. Your handler runs

    The SDK waits for it, calls onToolResult and sends the result to the server.

  4. The answer continues

    The SDK asks the agent to carry on in the same conversation. The agent now sees the result and either answers or calls another tool.

  5. Repeat until finished

    This goes on until the agent finishes without calling a tool. send then returns the ChatResponse.

    All of this happens inside the one await. Your onTextDelta handler receives the text of every round; the returned response.message is the message from the final round.

Tool loop limit

A limit stops an agent that keeps calling tools. The default is 10 rounds per send or retry, and you can change it when you create the client:

Swift
let client = QwryClient(agentId: "YOUR_AGENT_ID", maxToolLoopSteps: 20)

Going over the limit throws QwryError.toolLoopLimitExceeded:

Swift
do {
    try await client.send("Check every order I've ever placed")
} catch QwryError.toolLoopLimitExceeded {
    print("The agent called tools too many times in a row, so the SDK stopped")
}

Automatic retries

If sending a tool result fails with a network error, the SDK tries again up to 3 times, waiting 300 ms, then 600 ms, then 1.2 s. You don't need to retry it yourself.

When a tool fails

Return an object with an error key to tell the agent the tool failed, so it can try something else or explain the problem:

Swift
await client.tool("lookup_order") { input in
    guard let number = input["order_number"]?.stringValue else {
        return ["error": "Missing order_number"]
    }
    guard let order = try await OrderService.fetch(number: number) else {
        return ["error": .string("No order found with number \(number)")]
    }
    return ["status": .string(order.status)]
}

Thrown errors become the same thing. If your handler throws, the SDK sends {"error": "<the error's localizedDescription>"} to the agent instead of failing the whole send, so one broken tool doesn't end the answer.

Tools with no handler

If the agent calls a tool you never registered, the SDK sends back {"error": "No tool named <name> is registered in the app"}. The agent can then apologize or try something else instead of waiting.

Tools that ask the user

Handlers are async, so they can wait for the user and return their answer as the tool result. This is how you build confirmations, pickers and in-chat forms.

Swift
@MainActor
@Observable
final class SizePickerCoordinator {
    var isPresented = false
    private var pending: CheckedContinuation<String?, Never>?

    func request() async -> String? {
        await withCheckedContinuation { continuation in
            pending = continuation
            isPresented = true
        }
    }

    func choose(_ size: String?) {
        isPresented = false
        pending?.resume(returning: size)
        pending = nil
    }
}
Swift
await client.tool("pick_size") { _ in
    guard let size = await coordinator.request() else {
        return ["error": "The customer closed the size picker"]
    }
    return ["size": .string(size)]
}
Swift
struct ChatView: View {
    @State var coordinator: SizePickerCoordinator

    var body: some View {
        MessageList()
            .sheet(isPresented: $coordinator.isPresented, onDismiss: { coordinator.choose(nil) }) {
                SizeGrid { size in coordinator.choose(size) }
            }
    }
}

Watching tools run

Use onToolCall and onToolResult to show progress:

Swift
let response = try await client.send("What's in my cart?") { handlers in
    handlers.onToolCall = { call in
        print("Calling \(call.name) with \(call.input)")
    }
    handlers.onToolResult = { result in
        print("\(result.name) returned \(result.output)")
    }
    handlers.onTextDelta = { print($0, terminator: "") }
}

Both handlers also run for tools the server runs, such as API actions and integrations, not only your own. One piece of UI can show every tool the agent uses. See ToolCall and ToolResult.

Reading tool input

Input arrives as a JSONValue. Read it with the subscript and the typed properties:

Swift
await client.tool("book_table") { input in
    let party = Int(input["party_size"]?.numberValue ?? 2)
    let name  = input["name"]?.stringValue
    let vip   = input["vip"]?.boolValue ?? false
    // ...
}

For bigger inputs, decode into your own type. JSONValue is Codable:

Swift
struct BookingInput: Decodable {
    let partySize: Int
    let name: String
    enum CodingKeys: String, CodingKey { case partySize = "party_size", name }
}

await client.tool("book_table") { input in
    let data = try JSONEncoder().encode(input)
    let booking = try JSONDecoder().decode(BookingInput.self, from: data)
    // ...
}

Explore the documentation