# Client tools

> Declare application tools, submit per-call results and own side effects safely across reconnects and crashes.

Source: https://docs.corfedo.ai/connect/api/ai/client-tools/

Client tools run in your application while Corfedo AI investigates. Declare them on a message with a name, description and parameter JSON schema. They stay the same for the whole run.

```ts
const run = client.ai.stream({
  clientMessageId: crypto.randomUUID(),
  text: 'Compare the indexed code with my local build status',
  clientTools: [{
    name: 'build_status',
    description: 'Read the status of the local build',
    parameters: { type: 'object', properties: {}, additionalProperties: false },
  }],
});
for await (const event of run) {
  if (event.type === 'text.delta') process.stdout.write(event.text);
}

// This logical message call owns requiredCalls. The application supplies readBuildStatus.
if (run.requiredCalls.length > 0) {
  const results = [];
  for (const call of run.requiredCalls) {
    if (call.name !== 'build_status') throw new Error('Unexpected client tool');
    results.push({ callId: call.callId, output: await readBuildStatus(call.callId) });
  }
  const continuation = client.ai.streamToolResults(run.conversationId!, { results });
  for await (const event of continuation) {
    if (event.type === 'run.completed') console.log(event.answer);
  }
}
```

A continuation can request more client tools. Repeat that turn's processing until the run ends. Chat-model integrations let their framework's invocation loop return tool results. The CLI declares no client tools.

## Requests and results

The stream emits informational `tool.requested` events, then ends at `run.requires_action` with the calls open now. Each call has a `callId`, tool name, arguments and deadline. The application handles any required approval before executing it. Corfedo's own read tools have no approval waits.

Post results to the conversation's [tool-results endpoint](https://docs.corfedo.ai/reference/api/ai/submitAiToolResults/). Each result has exactly one of `output` or `error`. For example:

```json
{
  "results": [
    { "callId": "11111111-1111-4111-8111-111111111111", "output": { "status": "passed" } }
  ],
  "after": "42",
  "stream": true
}
```

`after` is optional. Without it, the continuation begins with a snapshot. A request can submit some of the pending calls. It then pauses again with the calls still open.

Sending the same results again is safe, even after the run ended or a newer one started. All calls in one request must belong to one run of the conversation, started through the same connection (the same API key or client sign-in). Otherwise the request fails with `invalid_argument` (400) and nothing is submitted.

## Per-call outcomes

A streaming result submission starts with `tool_results.outcomes`. Non-streaming results expose the same outcomes. Inspect each call independently.

| Outcome | Meaning |
| --- | --- |
| `accepted` | The result resolved the call |
| `alreadyResolved` | An identical result already resolved it |
| `conflict` | A different result already resolved it |
| `expired` | Its wait expired |
| `cancelled` | Its wait was cancelled |
| `notFound` | The call was not found |
| `invalid` | The result was invalid |

A result is JSON of at most 64 KiB. Results are not checked against a schema. Corfedo AI treats them as data from your application, not as evidence from the code.

## Who runs a call

Only that connection can submit results. The SDK call that sent the message or the results owns that turn's calls, and returns each one at most once in `requiredCalls`, also when it reconnects.

Reattaching, another subscriber and reading the run only show pending calls. They do not put them in `requiredCalls`. Do not run a call from a replayed `tool.requested`.

Corfedo does not guarantee exactly-once side effects. The application owns execution, approvals, deduplication and concurrency. Use `callId` as the external action's idempotency key when the tool supports one.

## Recover after a crash

A crash can happen after an action succeeds but before the result reaches Corfedo. After restarting, read pending calls and consult your own durable records by `callId`:

1. Submit a stored result if the action completed and its result is known.
2. Execute the tool if your records establish that it did not run.
3. Submit an error saying the outcome is unknown if execution cannot be established safely.

If a call's deadline passes, Corfedo AI continues without the result, and a late result gets `expired`. A disconnect leaves the run going and does not extend the deadline. Cancelling the run is a separate action.
