Blog · · 11 min read
Client-side tool calling AI agent contract: run tools in the user's browser without trusting client results or stranding the run

An embedded copilot often needs something only the page knows: the selected rows, the open record, the half-filled form. So the server-side model calls a tool and the browser runs it. Client-side tool calling in an AI agent breaks in four predictable ways. The chat hangs because no result arrives, a closed tab comes back as an empty answer, a placeholder result lets the model claim a write that never happened, or a missing tool message makes the next provider request fail. All four come from one trust problem. The browser both declares the tool and reports what it did. The contract below keeps browser tools useful without turning the browser into an unauthenticated write path into the agent's reasoning.
Direct answer: a split-execution contract
In AG-UI the client declares its tools with each run; in the AI SDK and ChatKit the server defines them and the browser registers a handler. Either way the model emits a call, the browser executes it, and the result goes back so the run can continue (AG-UI: Tools; Microsoft Learn: Frontend Tool Rendering with AG-UI). Around that round trip, add eight rules:
- Place tools deliberately. Only UI-local reads, page state, and user gestures run in the browser. Product writes stay on server tools.
- Allowlist client-declared tools on the server per user, tenant, page, and agent version. Drop anything else before the model sees it.
- Record a pending call with run ID, tool-call ID, expected output schema, and deadline before you stream the call to the browser.
- Fence the submit so only the session that owns the run can answer, and only once per call.
- Validate the result against a schema and size cap held on the server.
- Turn abandonment, timeout, and cancel into typed errors, never empty strings or placeholders.
- Write exactly one tool message per call into server-held history before resuming the model.
- Test the negative paths: forged tools, forged results, closed tabs, duplicate submits.
Why client-side tool calling breaks in embedded products
The browser is a remote executor with no durability and no authority. Frameworks ship the plumbing and leave the lifecycle to you, and public bug reports show where that bites.
Results that never arrive. The AI SDK requires client tools to call addToolOutput, and it warns not to await that call inside onToolCall because doing so can deadlock (AI SDK UI: Chatbot Tool Usage). Its troubleshooting page says every tool call needs a corresponding result before the conversation can continue (AI SDK: Tool Invocation Missing Result Error). One team followed an older JSDoc that said onToolCall could return the result. The value was dropped, the call stayed in input-available forever, and the chat hung with no error; maintainers reproduced it and corrected the JSDoc in July 2026 (vercel/ai#15268).
Abandonment that reads as an answer. In one CopilotKit report, an agent rendered a form through a frontend tool and the user closed the tab. The step then completed with an empty tool_call_result, and the agent treated it as "user chose nothing" (CopilotKit#5554). A follow-up pull request rejects the pending promise on abort, but in any stack a missing answer must not look like an empty one.
Placeholders that read as success. Another author report shows a backend returning the literal tool result Forwarded to client for a delete_orders frontend tool. The model then told the user the order was deleted, though the browser handler never ran (CopilotKit#3442). Maintainers could not reproduce the exact mechanism, so treat it as one team's report and test for the shape in your own stack.
History that loses the result. A third report describes a second-turn HTTP 400. The replayed history held an assistant tool call with no matching tool message, which OpenAI and Azure OpenAI reject. The root cause sat in an AG-UI adapter, fixed in agent-framework-ag-ui 1.2.0 (CopilotKit#3884). History that depends on every layer forwarding the result breaks when one layer does not.
Trust that nobody checks. Microsoft's AG-UI docs warn that tool declarations and results supplied by an untrusted client are untrusted input, and they tell you to authorize which client tools may influence execution and to validate results before privileged use (Microsoft Learn). CopilotKit's Vue reference says runtime arguments are JSON-parsed but not validated against the declared schema (CopilotKit Vue: useFrontendTool).
Decide which tools belong in the browser
| Tool kind | Run where | Reason |
|---|---|---|
| Read the current selection, scroll position, or form draft | Browser | Only the page has it, and a wrong value affects one answer, not stored data |
| Highlight, navigate, open a panel, show a toast | Browser, as a fire-and-forget effect | No result is needed, so nothing should wait on it |
| Ask the user to confirm or fill a field | Browser for the gesture, server for the effect | The click is human input, and the write still needs authorization |
| Create, update, or delete a product record | Server | The browser can forge any result it returns |
| Read data the user's role may not see in full | Server | Filtering in the browser leaks data to anyone with dev tools |
OpenAI's ChatKit draws the same line between client effects, which trigger UI behavior without pausing the model or entering thread history, and client tool calls, which pause inference until the browser answers (OpenAI ChatKit: Update the client during a response). Use effects whenever you do not need an answer, so there is no pending call to strand.
Client-declared tool schemas and client-side availability flags are not authorization, so the server must allowlist which browser tools each user and page may offer the model and keep product writes on server tools that re-authorize. In AG-UI, client-defined tools travel in RunAgentInput.tools from the frontend (AG-UI: Tools), so a modified client can advertise any name and description it likes. CopilotKit's Vue reference shows an admin-only deleteUser tool whose visibility depends on a client-side isAdmin prop and whose handler calls a delete endpoint (CopilotKit Vue: useFrontendTool). That is UI gating. A user who flips the flag in dev tools gets the tool, and only the delete endpoint is left to stop them. We recommend treating the client's tool list as a request, intersecting it with a server allowlist keyed by role and page, and making every endpoint a browser tool calls enforce its own authorization.
Implement the contract for client-side tool calling
These steps are framework-neutral. Map them onto the hooks you already use.
1. Allowlist client-declared tools on the server
Filter the declared tools before they reach the model, and pin each one to a schema the server owns.
on run_start(request, user, page):
allowed = CLIENT_TOOL_REGISTRY.for(user.role, user.tenant, page.route, agent.version)
offered = []
for decl in request.client_tools:
entry = allowed.get(decl.name)
if entry is None: log("client_tool_rejected", decl.name); continue
offered.append(entry.server_schema) # never decl.parameters from the client
run.tools = server_tools + offered
Use the server copy of the description and parameters. The client's declaration only tells you a handler is mounted. CopilotKit removes a tool when its owning component scope is disposed (CopilotKit Vue: useFrontendTool).
2. Record the pending call before the browser sees it
When the model emits a browser tool call, write a durable record first, then stream the call.
pending_client_call {
run_id, tool_call_id, tool_name, session_id, user_id,
args_hash, output_schema_version,
deadline_at, # e.g. now + 60s for reads, longer for forms
state: "awaiting" | "answered" | "errored" | "expired"
}
Helix Agents shows a production version of this design. It persists pending calls keyed by toolCallId, ends the in-memory loop, and resumes only when an explicit submit and resume arrive. It gives every suspension a deadline, five minutes by default, after which the model receives a client_tool_timeout error (Helix Agents: Client-Executed Tools). You can copy the shape without the framework. Without the record, a restart or a dropped stream leaves you guessing which calls are still owed.
3. Fence and validate every submit
The submit endpoint writes data straight into the model's context. Helix's docs warn that anyone who can reach the endpoint can inject arbitrary data into an agent's reasoning, so it must be authenticated and bound to the session (Helix Agents). Apply four checks in order:
- The caller's session owns
run_id, and the pending record exists in stateawaiting. - The record is still current. A submit for a call that was answered, expired, or belongs to a superseded run becomes a no-op, so a duplicate POST cannot double-apply.
- The payload is under a size cap and matches the server-held output schema. Helix returns a 400 when a result fails the tool's output schema, and it skips that check if you never register the schema (Helix Agents).
- Error strings are sanitized. They go into history and the next model call verbatim, so strip stack traces, tokens, and internal IDs first.
Convert a result that fails validation into an error result so the model can recover.
4. Rebuild history from the server record
When the client resends the full message history each turn, it can rewrite earlier tool outputs, so store browser tool results server-side keyed by tool-call ID and rebuild model history from that record instead of the client copy. The AI SDK documents the approval version of this risk. Because useChat sends the full message history to the server each turn, a modified client could fabricate an approval response, and the SDK offers experimental_toolApprovalSecret so the server can verify it issued the approval (AI SDK UI: Chatbot Tool Usage). The same page documents no equivalent signature for client-side tool outputs. That is our reading of the published docs, and our first-principles recommendation follows from it. Let the client send the new turn, and take tool messages from your pending-call table.
The same rule fixes the history-gap class of bug. If the server inserts exactly one tool message per answered call, an assistant tool call without a result cannot reach the provider, whatever a UI state manager drops (CopilotKit#3884). ChatKit follows this pattern. It stores the client's answer as a ClientToolCallItem and replays it to the model as a function_call plus matching function_call_output (OpenAI ChatKit).
5. Keep consequential writes on server tools
When the user must review a change, use the browser for the review and the server for the change. The browser tool returns a decision such as { "decision": "confirmed", "draft_id": "d_81" }, and a server tool loads the draft, checks permission, and performs the write. A forged decision still meets authorization on the write path. AG-UI lists "sensitive operations are controlled by the application" among the advantages of frontend-defined tools (AG-UI: Tools). Keep the operation itself out of the browser.
Handle abandonment, timeouts, and errors
A closed tab, unmount, or timeout must reach the model as a typed abandoned or timeout error, because an empty or placeholder result reads as a real answer and lets the agent claim work that never ran. AG-UI's tool message carries an error field for this reason. Without it, the docs say, a tool that failed is indistinguishable from one that succeeded (AG-UI: Tools). The AI SDK gives you the same lever with state: 'output-error' and errorText (AI SDK UI: Chatbot Tool Usage).
Define a small vocabulary and use it everywhere:
| Outcome | Who produces it | What the model receives |
|---|---|---|
answered | Browser submit that passes validation | The validated result |
user_cancelled | Browser, when the user dismisses the form | Error text saying the user declined |
abandoned | Browser on unmount or pagehide, or the server when the stream drops | Error text saying no answer was given |
timeout | Server deadline sweep | Error text saying the browser did not answer in time |
invalid_result | Server validation | Error text saying the result was rejected |
Write each error as plain language the model can act on, such as "The user closed the form before answering; ask again or continue without this value." Helix treats a handler that returns undefined as an error rather than an empty success (Helix Agents), and your own handlers should follow the same rule. Never return a placeholder string as a tool result while the real execution is pending. That is the shape behind the false delete confirmation in CopilotKit#3442.
Guard the auto-resubmit. Helix reports that the AI SDK's stock lastAssistantMessageIsCompleteWithToolCalls helper is stateless and caused a runaway chain of 490 POSTs in 58 seconds in one production deployment (Helix Agents). That is a vendor's report, but making resubmission conditional on a call having just moved to answered costs little. Also decide how batches resume. ChatKit allows only one client tool call per turn (OpenAI ChatKit). If your framework allows several, resume only when every call in the batch has an answer or a typed error.
Verify the solution
Automate these against a staging run before shipping any browser tool:
- Forged tool. Declare a tool missing from the allowlist. Assert it never reaches the model request.
- Forged schema. Declare an allowed tool with altered parameters. Assert the model sees the server schema.
- Forged result. Submit a result that fails the output schema. Assert the model receives
invalid_resultand no product write occurs. - Cross-session submit. Submit for another session's
tool_call_id. Assert rejection. - Duplicate submit. Submit twice. Assert one tool message in history and a no-op for the second.
- Closed tab. Start a form tool, close the page, and wait past the deadline. Assert the model receives
abandonedortimeout, never an empty string. - History rewrite. Resend history with an edited earlier tool output. Assert the model gets the server-recorded output.
- History completeness. For every persisted run, assert each assistant tool call has exactly one matching tool message.
- Write isolation. Confirm no browser tool handler calls a write endpoint that skips server-side authorization.
Common mistakes
- Gating a dangerous tool with a client flag. An
availablegetter or role prop hides a button but cannot stop a forged request. - Returning a value from a callback that ignores it. Read your framework's actual contract. The AI SDK needs
addToolOutput, not a return value (vercel/ai#15268). - Trusting the client's transcript. Rebuild tool messages from the server record on every turn.
- Letting the model narrate success from a placeholder. If the browser has not answered, the model gets nothing, or a typed error once the deadline passes.
What to do next
List every tool your embedded agent can call today and put each one in a row of the placement table above. Move any browser tool that writes product data behind a server tool, then add the pending-call record and the closed-tab test before you add another frontend tool. If you embed a Make Your Agent chatbot next to your product UI, apply the same split to client-side tool calling: page-aware helpers in the browser, record changes and CRM routing on the server.