Tools
Tools are created with defineTool and come in two kinds:
- Investigation tools (
investigationTools): the AI calls them while investigating and reads their output, which never reaches your caller. Keep them read-only. - Result tools (
resultTools): the AI picks one as its outcome, with its input, and trypatch calls it once the investigation is done. Its return value is what the decorated method returns, so this is where recovery actions belong: retries, fallbacks, cache reads.
ts
import { setTimeout as sleep } from 'node:timers/promises'
import { z } from 'zod/v4'
import { defineTool, trypatch } from '@ssandir/trypatch'
// Investigation tool: lets the AI see what the upstream actually sent
const fetchRawQuote = defineTool({
name: 'fetchRawQuote',
description: 'Fetch the raw, unparsed pricing API response for a product',
parameters: z.object({ productId: z.string() }),
execute: async ({ productId }) => {
const response = await fetch(`https://pricing.example.com/products/${productId}/quote`)
return `${response.status}\n${await response.text()}`
},
})
// Result tool: its return value becomes getQuote's return value
const retryWithBackoff = defineTool({
name: 'retryWithBackoff',
description: 'Fetch the quote again with exponential backoff. Use for transient failures (timeouts, 5xx).',
parameters: z.object({ productId: z.string(), delayMs: z.number(), maxAttempts: z.number() }),
execute: async ({ productId, delayMs, maxAttempts }, _context, { signal }): Promise<Quote> => {
for (let attempt = 0; ; attempt++) {
try {
return await pricingClient.fetchQuote(productId)
} catch (error) {
if (attempt >= maxAttempts - 1) throw error
await sleep(delayMs * 2 ** attempt, undefined, { signal })
}
}
},
})
export class PricingService {
@trypatch({
aiInvestigation: {
resultSchema: QuoteSchema,
investigationProvider: {
provider: 'claude',
apiKey: process.env.ANTHROPIC_API_KEY!,
},
investigationTools: [fetchRawQuote],
resultTools: [retryWithBackoff],
},
})
async getQuote (productId: string): Promise<Quote> {
return await pricingClient.fetchQuote(productId)
}
}The tool loop
- The AI can call investigation tools over several turns before it picks an outcome.
maxToolIterationson the provider config caps the turns, andtimeoutMsbounds the whole loop. - If an investigation tool throws, the error goes back to the AI so it can try something else; the investigation doesn't fail.
- With redaction on, a tool's input has placeholders restored before it runs, and its output is redacted before the AI sees it. See Redaction.
cursordoesn't run investigation tools, since its cloud agent runs its own; give it tools through MCP servers.
Calling execute
- Its input is validated against
parametersfirst. A tool withoutparameterstakes no input, andexecutereceivesundefined. - Its second argument is
toolContext, and its third is{ signal }. See Cancellation. - A tool still running at a deadline is abandoned; listen to
signalto actually stop it.
Result tools
- A result tool runs inside the investigation's
timeoutMs, and its owntimeoutMsstill applies. - If it throws, the investigation fails, and the method rethrows its original error.
- Its return type is checked against
resultSchemaat compile time. Its value isn't validated at runtime, since it's your code.
Built-in safe toolbox
Unless allowSafeToolbox is false, the AI also gets tools named trypatch_builtin_* to:
wait, e.g. for a rate limit to resetread_call_context: read parts of the error or arguments the prompt cut short, aftersanitizeArgsdecodeandencodebase64, hex and JWTs (JWTs are decoded only, never verified)
They're never result tools.