# Build a custom tool loop

Use the complete dependency-free Node example to exchange calls and results, read allow-listed project files, and stop within six model turns.

## Keep execution in your application.

Blaschke validates and relays messages. Your application owns tool validation, authorization, file access, and conversation history.

## The actual source file.

This is the complete source from `examples/tool-loop.mjs`. It uses only Node built-ins and lets you pass an `AbortSignal` to each request.

### examples/tool-loop.mjs

```javascript
import { readFile, realpath, stat } from "node:fs/promises";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";

const MAX_TURNS = 6;
const OUTPUT_TOKENS = 1024;
const FILE_LIMIT = 20_000;
const ALLOWED_FILES = new Set(["README.md", "package.json", "AGENTS.md"]);
const TOOL = {
  type: "function",
  function: {
    name: "read_project_file",
    description: "Read one allow-listed public project file.",
    parameters: {
      type: "object",
      properties: { file: { type: "string" } },
      required: ["file"],
      additionalProperties: false,
    },
  },
};

export async function executeProjectTool(name, rawArguments, root = process.cwd()) {
  if (name !== "read_project_file") throw new Error("This agent only permits read_project_file.");
  const args = JSON.parse(rawArguments);
  if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).length !== 1 || typeof args.file !== "string" || !ALLOWED_FILES.has(args.file)) {
    throw new Error("Choose README.md, package.json, or AGENTS.md. Other paths are not permitted.");
  }
  const projectRoot = await realpath(root);
  const target = await realpath(resolve(projectRoot, args.file));
  if (target !== resolve(projectRoot, args.file) || !(await stat(target)).isFile()) {
    throw new Error("Only regular project files from the allow-list are permitted.");
  }
  return (await readFile(target, "utf8")).slice(0, FILE_LIMIT);
}

export async function runToolLoop({
  baseUrl,
  apiKey,
  model,
  prompt = "Read README.md through the tool, then summarize the setup in two bullets.",
  root = process.cwd(),
  fetchImpl = fetch,
  signal,
}) {
  const endpoint = new URL("chat/completions", new URL(baseUrl.replace(/\/?$/, "/")));
  if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") {
    throw new Error("The gateway must use HTTP or HTTPS.");
  }
  const messages = [
    { role: "system", content: "Use the provided tool to inspect files before answering." },
    { role: "user", content: prompt },
  ];

  for (let turn = 0; turn < MAX_TURNS; turn++) {
    const response = await fetchImpl(endpoint, {
      method: "POST",
      headers: {
        authorization: "Bearer " + apiKey,
        "content-type": "application/json",
      },
      body: JSON.stringify({
        model,
        messages,
        tools: [TOOL],
        tool_choice: "auto",
        max_tokens: OUTPUT_TOKENS,
        stream: false,
      }),
      signal,
    });
    if (!response.ok) {
      throw new Error("Gateway HTTP " + response.status + ": " + (await response.text()).slice(0, 2000));
    }
    const payload = await response.json();
    const message = payload?.choices?.[0]?.message;
    if (!message || message.role !== "assistant") throw new Error("The gateway returned no assistant message.");
    const calls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
    if (calls.length === 0) return message.content || "The model returned no text.";
    messages.push(message);

    for (const call of calls) {
      if (call.type !== "function" || typeof call.id !== "string") {
        throw new Error("The gateway returned an invalid tool call.");
      }
      let result;
      try {
        result = await executeProjectTool(call.function?.name, call.function?.arguments ?? "", root);
      } catch (error) {
        result = JSON.stringify({ error: error instanceof Error ? error.message : String(error) });
      }
      messages.push({ role: "tool", tool_call_id: call.id, content: result });
    }
  }
  throw new Error("Stopped after six model turns. No further calls were made.");
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  const apiKey = process.env.BLASCHKE_API_KEY;
  const model = process.env.BLASCHKE_MODEL;
  if (!apiKey || !model) throw new Error("Set BLASCHKE_API_KEY and BLASCHKE_MODEL first.");
  const answer = await runToolLoop({
    baseUrl: process.env.BLASCHKE_BASE_URL || "https://blaschkelabs.com/v1",
    apiKey,
    model,
  });
  console.log(answer);
}
```

## Run against Blaschke.

Select an exact model ID from model discovery. Missing credentials or an unavailable model produce an error rather than fake model output.

### Run the example

```shell
export BLASCHKE_API_KEY="blsk_..."
export BLASCHKE_BASE_URL=https://beta.blaschkelabs.com/v1
export BLASCHKE_MODEL="<exact-model-id>"
node examples/tool-loop.mjs
```

## Test without inference.

The tests use a local mock server instead of sending inference. They verify tool authorization, API-error handling, and the six-turn limit.

### Run the example tests

```shell
node --test examples/tool-loop.test.mjs
```

- The default task reads README.md and asks for two summary bullets.
- Only README.md, package.json and AGENTS.md are permitted.
- Supply AbortSignal.timeout(...) or an AbortController when a pending request must be bounded.

## Related guides

- [Tool protocol](https://beta.blaschkelabs.com/docs/tools): Review tool schemas and result IDs.

Source: https://beta.blaschkelabs.com/docs/agents/build

Markdown: https://beta.blaschkelabs.com/docs/md/agents/build.md
