NEW RELEASEDownload the n8n Starter Pack (5 Workflows + Docker Setup) for free — or save 20% on Pro Kits with DEVHUB20.
DevHubTools Robot Mascot
DevHubTools
Back to Learning Center
AI Agent EngineeringDifficulty: Advanced 12 min read

Building Deterministic Tool-Calling AI Agents in TypeScript (Without Framework Bloat)

How to architect a clean 80-line tool-calling agent loop with strict JSON schema validation, max-iteration budgets, and persistent state.

Prerequisites: TypeScript fundamentals Async/Await & REST APIs
Published: 2026-10-16
Production Implementation Snippet (typescript)
export interface ToolDefinition<TArgs, TResult> {
  name: string;
  description: string;
  parametersSchema: Record<string, unknown>;
  execute: (args: TArgs) => Promise<TResult>;
}

export async function executeToolSafely<TArgs, TResult>(
  tool: ToolDefinition<TArgs, TResult>,
  rawArgs: TArgs,
  timeoutMs = 8000
): Promise<TResult> {
  return await Promise.race([
    tool.execute(rawArgs),
    new Promise<never>((_, reject) =>
      setTimeout(() => reject(new Error(`Tool ${tool.name} timed out after ${timeoutMs}ms`)), timeoutMs)
    ),
  ]);
}
SECTION 01

1. Keep the Control Loop Explicit

When an AI agent fails at 2 AM, you need to see the exact prompt, tool call arguments, and raw HTTP response. Writing a direct while-loop with a strict maxSteps counter makes debugging trivial.

SECTION 02

2. Timeout and Token Guardrails

Wrap every external tool execution in a timeout boundary and track cumulative input/output tokens per run so a runaway prompt can never rack up unexpected API bills.

Companion Starter Kit

AI Agent Starter Kit

Skip manual boilerplate setup. Download the complete production files and configs covered in this guide.

Inspect Kit ($19)
Companion Browser Utility

JSON Formatter, Validator & Minifier

Format, validate, sort keys, and minify JSON payloads with exact syntax error diagnostics.

Open Free Utility
Building Deterministic Tool-Calling AI Agents in TypeScript (Without Framework Bloat) — DevHubTools Engineering Guide | DevHubTools