A tool() with a Zod input schema, handed to a ToolLoopAgent, checks a company in its official register. Written against ai 7.0.183 and zod 4.6.7, 26 November 2026.
In the AI SDK a tool is a tool() call with a description, an inputSchema and an execute function, and the agent is a ToolLoopAgent that keeps calling the model until it stops asking for tools or a step limit is reached. This page builds one tool around GET /companies/search. It was written against ai 7.0.183 and zod 4.6.7 (installed from npm on 26 November 2026, Node 22). The tool's execute function was run against the live API; the model loop needs a model your account can call and was not run.
npm init -y && npm pkg set type=module npm i ai zod export PROMETIAM_API_KEY=rk_live_demo_publichn # or your own rk_live_ key
The tool is a separate module so the function can be tested without the SDK. companyCheck does the work; companyCheckTool wraps it. The Zod schema allows name and company_number as optional fields and a refine rejects a call that gives both or neither:
import { tool } from 'ai'
import { z } from 'zod'
const BASE = process.env.PROMETIAM_BASE_URL ?? 'https://api.prometiam.com/functions/v1/risk-api'
const input = z
.object({
country: z.string().length(2).describe('Two-letter country code, for example ES, FR or GB'),
name: z.string().min(2).optional().describe('Company name. Give this or company_number.'),
company_number: z.string().min(2).optional().describe('National register number (exact). Give this or name.'),
})
.refine((v) => Boolean(v.name) !== Boolean(v.company_number), { message: 'Give exactly one of name or company_number.' })
export async function companyCheck({ country, name, company_number }) {
const key = process.env.PROMETIAM_API_KEY
if (!key) return { ok: false, error: 'missing_key', message: 'PROMETIAM_API_KEY is not set.' }
const params = new URLSearchParams({ country: country.toUpperCase(), limit: '3' })
if (company_number) params.set('company_number', company_number)
else params.set('name', name)
let res
try {
for (let attempt = 0; attempt < 2; attempt++) {
res = await fetch(`${BASE}/companies/search?${params}`, {
headers: { Authorization: `Bearer ${key}` },
signal: AbortSignal.timeout(15_000),
})
if (res.status !== 429 || attempt === 1) break
await new Promise((r) => setTimeout(r, Math.min(Number(res.headers.get('retry-after')) || 5, 30) * 1000))
}
} catch (err) {
return { ok: false, error: 'network', message: err.name }
}
if (res.status === 401) return { ok: false, error: 'unauthorized', message: 'The API key is missing, wrong or expired.' }
if (res.status === 429) return { ok: false, error: 'rate_limited', retry_after_seconds: Number(res.headers.get('retry-after')) || null }
if (!res.ok) {
// includes 403 upgrade_required
const body = await res.json().catch(() => ({}))
return { ok: false, error: body?.error?.code ?? `http_${res.status}`, message: body?.error?.message ?? 'The API returned an error.' }
}
const { data } = await res.json()
if (!data.length) return { ok: true, found: false, message: 'No company matched in this country. Do not guess; ask for the register number.' }
const top = data[0].match_score
return {
ok: true,
found: true,
ambiguous: data.filter((c) => c.match_score === top).length > 1,
companies: data.map((c) => ({
legal_name: c.company_name,
register_number: c.company_number,
status: c.status,
legal_form: c.legal_form,
founding_date: c.founding_date,
vat_number: c.vat_number,
vat_number_source: c.vat_number_source,
match_score: c.match_score,
})),
}
}
export const companyCheckTool = tool({
description:
'Look up a company in the official register of one country. Give a two-letter country code and either the company name or the register number. Returns legal name, register number, status, legal form, founding date and VAT number. Fields are null where the register publishes none.',
inputSchema: input,
execute: companyCheck,
})
The function sends limit=3 so the model sees the other close candidates, and it reports ambiguous when more than one candidate has the top score. fetch has no retry of its own, so the function tries a second time after a 429, once, waiting the Retry-After seconds (at most 30). The API base can be overridden with PROMETIAM_BASE_URL, which is how the error rows below were tested without asking the live API to fail.
The SDK turns the Zod schema into the JSON schema the model sees. Printed with asSchema(companyCheckTool.inputSchema).jsonSchema, it is:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"country": {
"type": "string",
"minLength": 2,
"maxLength": 2,
"description": "Two-letter country code, for example ES, FR or GB"
},
"name": {
"description": "Company name. Give this or company_number.",
"type": "string",
"minLength": 2
},
"company_number": {
"description": "National register number (exact). Give this or name.",
"type": "string",
"minLength": 2
}
},
"required": [
"country"
],
"additionalProperties": false
}
The refine rule is checked when the SDK validates the model's arguments; it is not part of the JSON schema, so the descriptions say "give this or company_number" for the model's benefit.
On 26 November 2026 companyCheckTool.execute({ country: 'GB', company_number: '00445790' }, ...) ran against the live API with the demo key and printed:
{
"ok": true,
"found": true,
"ambiguous": false,
"companies": [
{
"legal_name": "TESCO PLC",
"register_number": "00445790",
"status": "active",
"legal_form": "PLC",
"founding_date": "1947-11-27",
"vat_number": null,
"vat_number_source": null,
"match_score": null
}
]
}
A register number is an exact match, so match_score is null. The company has no VAT number in the answer: for Great Britain the API serves none, and the tool passes the null on. An agent that reads a null VAT number as "not VAT registered" would be wrong, and the instructions tell it to report fields as given.
The same day, a nonsense name returned data and not an error:
{
"ok": true,
"found": false,
"message": "No company matched in this country. Do not guess; ask for the register number."
}
And a wrong key, sent to the live API, returned the 401 as data:
{
"ok": false,
"error": "unauthorized",
"message": "The API key is missing, wrong or expired."
}
The tool goes in the agent's tools object, keyed by the name the model will use. stopWhen: isStepCount(6) bounds the loop (the SDK's default is 20 steps, and it logs a warning when the default is what stops a loop). The model is yours: this page does not name one, so set MODEL_ID to a model your account can call, as a gateway string or after installing a provider package:
import { ToolLoopAgent, isStepCount } from 'ai'
import { companyCheckTool } from './company-check.mjs'
export const agent = new ToolLoopAgent({
model: process.env.MODEL_ID ?? 'provider/model-id', // replace with a model your account can call
instructions:
'You check companies against official registers with the companyCheck tool. Report only what the tool returns. ' +
'Fields can be null where a register publishes none. If several companies match equally, list them and ask which one is meant. ' +
'Never state that a company is safe or approved; a person decides.',
tools: { companyCheck: companyCheckTool },
stopWhen: isStepCount(6),
})
Importing this module constructs the agent without a key. On 26 November 2026 the object printed as a ToolLoopAgent whose tools were [ 'companyCheck' ]. To run the loop, call generate with your own model credentials in place:
import { agent } from './agent.mjs'
const result = await agent.generate({ prompt: 'Is the UK company 00445790 still active?' })
console.log(result.text)
The agent.generate snippet was not run. It calls a model, and this page's author did not use a model key. The tool it calls was run, as shown above.
The 401 above was live. The 403, 429 and retry rows were checked against a local test server that answers as the API does.
| Answer from the API | What the tool returns to the model |
|---|---|
401 unauthorized | { ok: false, error: "unauthorized", ... }. The model should tell the user, not retry. |
403 upgrade_required | { ok: false, error: "upgrade_required", message } with the API's own message: the key's plan does not include what was asked. |
429 with Retry-After | One automatic retry after the wait. If still limited: { ok: false, error: "rate_limited", retry_after_seconds }. A run where the second attempt succeeds returns the normal result. |
200 with an empty data | { ok: true, found: false, message }: the model is told not to guess. |
| Timeout or network error | { ok: false, error: "network" } after 15 seconds. |
x-credits-cost response header is available inside execute if you want to return or log it.rk_live_demo_publichn works without signup for company search, records, VAT, LEI, insolvency and coverage, at 30 calls a minute and 1,000 a day across all its users.upgrade_required for sanctions screening, people and company events, none of which this tool calls.process.env inside execute. It is not in inputSchema, so the model cannot fill it in, and it is not in instructions.instructions in the sample say never to call a company safe or approved.GET /account lists them).vat_number_source is register where the register publishes the number and rule where the number is built from the register identifier by the country's rule: the format is right, the registration is not confirmed. For an EU number, check it with GET /vat/{number}.entity_class that this tool does not forward, so add it if the agent must tell kinds of registrant apart. Several companies can share a name: ambiguous tells the agent to ask.If you would rather not maintain the tool, the prometiam-risk-mcp server exposes company search, records, events, insolvency, VAT, LEI and sanctions screening (beta) as ready-made tools, and the AI SDK can load tools from an MCP server. See the MCP server and the use case for AI agents. The same tool for other stacks: OpenAI Agents SDK and LangChain.
The free trial lasts 14 days and includes 500 credits. A card is required and nothing is charged during the trial; it then continues as Starter (EUR 9.99/month) unless you cancel.