> ## Documentation Index
> Fetch the complete documentation index at: https://cognitio-agent.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Give an agent a calculator

> Define an application tool, allow it, and confirm it actually ran.

Let the model call a multiplication function in your Node.js application. The program verifies the function call instead of trusting an answer that merely looks correct. The complete code is below. You can also [browse the project on GitHub](https://github.com/ozgurugurlu/cognitio-agent-sdk/tree/main/examples/03-custom-tool) or [open its JavaScript source](https://github.com/ozgurugurlu/cognitio-agent-sdk/blob/main/examples/03-custom-tool/index.mjs).

## 1. Create the project

Use Node.js 22 or newer, npm, and an OpenAI API key with access to `gpt-4.1-mini`. Model requests use your provider account and can incur charges.

```sh theme={null}
mkdir cognitio-calculator
cd cognitio-calculator
npm init -y
npm install --save-exact cognitio-agent-sdk@2.0.1
```

Keep npm optional dependencies enabled; they include the runtime for your platform. You do not need a separately installed runtime.

## 2. Configure the environment

Create a file named `.env` in this directory:

```dotenv theme={null}
COGNITIO_MODEL=openai/gpt-4.1-mini
OPENAI_API_KEY=replace_with_your_key
```

Replace the placeholder with your key. Add `.env` and `node_modules/` to `.gitignore`. Existing shell environment values take precedence over this file. To use Anthropic instead, set `COGNITIO_MODEL=anthropic/claude-sonnet-4-5` and `ANTHROPIC_API_KEY` to your Anthropic key; the code forwards either provider's credential.

## 3. Create `index.mjs`

```js theme={null}
import { Agent, defineTool } from "cognitio-agent-sdk"

const model = process.env.COGNITIO_MODEL?.trim() || "openai/gpt-4.1-mini"
const credential = { openai: "OPENAI_API_KEY", anthropic: "ANTHROPIC_API_KEY" }[model.split("/")[0]]
if (!model.includes("/")) throw new Error("Set COGNITIO_MODEL to a provider/model identifier.")
if (credential && (!process.env[credential]?.trim() || process.env[credential] === "replace_with_your_key")) {
  throw new Error(`Set ${credential} in .env or your shell before running this example.`)
}
const providerEnv = Object.fromEntries(
  ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"]
    .filter((name) => process.env[name]?.trim())
    .map((name) => [name, process.env[name]]),
)

let requestedCalculationExecuted = false
const multiply = defineTool({
  name: "multiply",
  description: "Multiply two finite numbers and return their product.",
  inputSchema: {
    type: "object",
    properties: { a: { type: "number" }, b: { type: "number" } },
    required: ["a", "b"],
    additionalProperties: false,
  },
  execute({ a, b }) {
    if (!Number.isFinite(a) || !Number.isFinite(b) || !Number.isFinite(a * b)) {
      throw new Error("Both inputs and their product must be finite numbers.")
    }
    const calculation = { a, b, product: a * b }
    if (((a === 6 && b === 7) || (a === 7 && b === 6)) && calculation.product === 42) {
      requestedCalculationExecuted = true
    }
    return calculation
  },
})
const agent = new Agent({
  model,
  instructions: "Use the supplied multiply tool for calculations, then answer briefly with its result.",
  settingSources: [],
  includeEnvironment: false,
  tools: [multiply],
  allowedTools: ["sdk_multiply"],
  maxTurns: 3,
  maxBudgetUsd: 0.03,
  spawn: {
    isolated: true,
    port: 0,
    autoCleanup: true,
    env: { ...providerEnv, COGNITIO_DISABLE_AUTOUPDATE: "1", COGNITIO_DISABLE_LSP_DOWNLOAD: "1" },
    config: { plugin: [], lsp: false, formatter: false, agent: { title: { disable: true } } },
  },
})

try {
  const result = await agent.run("Use multiply to calculate 6 times 7. Do not calculate it yourself.", {
    signal: AbortSignal.timeout(90_000),
  })
  if (result.isError || result.subtype !== "success") throw new Error(`Calculation failed: ${result.subtype}`)
  if (!requestedCalculationExecuted) throw new Error("The model did not execute multiply with the requested inputs.")
  if (typeof result.text !== "string" || !result.text.trim()) throw new Error("The model returned no answer.")
  console.log("Tool result: 6 × 7 = 42")
  console.log(`Assistant: ${result.text.trim()}`)
} finally {
  await agent.close()
}
```

## 4. Run it

```sh theme={null}
node --env-file=.env index.mjs
```

A successful run prints output like:

```text theme={null}
Tool result: 6 × 7 = 42
Assistant: 6 times 7 is 42.
```

The assistant's wording may vary. The program requires a real call with 6 and 7 and a product of 42; it throws if the model answers without calling the tool. Use a model with tool-calling support.

## How it works

The descriptor is named `multiply`; direct Agent tools are exposed to the runtime with the `sdk_` prefix. `allowedTools: ["sdk_multiply"]` makes this the only available tool.

The input schema describes arguments to the model. It does not automatically validate callback input in v2. The callback checks that both values and their product are finite numbers before recording a result. For richer inputs, call a validator inside `execute` before any side effect.

The function runs in your application process. An allowlist grant can settle permission before `canUseTool`; put mandatory checks inside the function or deterministic deny rules. See [tools](https://cognitio-agent.mintlify.site/concepts/tools.md) and [permissions](https://cognitio-agent.mintlify.site/concepts/permissions.md).

This Agent owns its dedicated isolated runtime and closes it in `finally`. It allows three turns, uses a 90-second request deadline, and checks an estimated \$0.03 budget. The budget is not a provider billing cap.

## Use the existing project

If you prefer the [complete GitHub project](https://github.com/ozgurugurlu/cognitio-agent-sdk/tree/main/examples/03-custom-tool), copy that directory, run `npm ci`, copy `.env.example` to `.env`, set your key, and run `npm start`. On PowerShell, use `Copy-Item .env.example .env`; in a Unix shell, use `cp .env.example .env`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.