# 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. > [!NOTE] > > The name you register must match the action's **Action name** exactly, and the action must be switched on for the iOS SDK channel. ### 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](/docs/user-guides/chatbot/actions/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. ![The tab bar of the iOS SDK channel with the pointer on the Actions tab, where actions are switched on for the SDK.](annotated/02-ios-actions-tab.webp "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`. | Parameter | Type | Required | Description | | - | - | - | - | | `name` | `String` | Yes | The tool name. Must match the action's **Action name**. | | `handler` | `@Sendable (JSONValue) async throws -> JSONValue` | Yes | An async closure. It receives the tool's input as a [`JSONValue`](/docs/ios-sdk/json-value) 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") ``` > [!WARNING] > > A tool result can be at most **20 KB** of JSON. A bigger one is refused with `400` `VALIDATION_INVALID_BODY`, and that error ends the `send`. Return only the fields the agent needs, never a whole API response. ## 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") } ``` > [!TIP] > > Hitting the limit usually means the agent keeps calling a tool because the result doesn't answer its question. Check that your handler returns what the action's description promises. ### 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": ""}` to the agent instead of failing the whole `send`, so one broken tool doesn't end the answer. > [!WARNING] > > The agent reads these errors and can repeat them in the conversation. Don't throw errors whose description contains tokens, signed URLs, internal IDs or stack traces. Throw or return a message you're happy for a customer to read. ### Tools with no handler If the agent calls a tool you never registered, the SDK sends back `{"error": "No tool named 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? 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) } } } } ``` > [!WARNING] > > Resume the continuation exactly once on every path, including when the user dismisses the sheet. If it's never resumed, the tool waits forever and `send` never returns. ## 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`](/docs/ios-sdk/streaming-events) and [`ToolResult`](/docs/ios-sdk/streaming-events). > [!TIP] > > The finished `Message` keeps each call and result in `parts`, in order, so [`ConversationState`](/docs/ios-sdk/swiftui) can show them in the message list once the answer is complete. ## Reading tool input Input arrives as a [`JSONValue`](/docs/ios-sdk/json-value). 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) // ... } ``` ## Related > [card] Streaming | /docs/ios-sdk/streaming | The send method and its handlers. > [card] JSONValue | /docs/ios-sdk/json-value | Reading and writing tool data. > [card] SwiftUI | /docs/ios-sdk/swiftui | Showing tool parts in a chat screen. > [card] Error Handling | /docs/ios-sdk/error-handling | Handling errors while tools run.