AI Agents in TypeScript: From Chat Demos to Reliable Business Workflows
Published July 16, 2026 · 12 min read
An AI agent becomes useful when it can do more than compose a reply. Give a model a set of tools, a loop that can execute them, and enough state to continue, and it can investigate a problem, update a system, and check the result. That is also the moment a text-generation feature becomes an execution system.
TypeScript helps make that system legible. Schemas can connect model-generated arguments to typed handlers, and agent SDKs can manage repeated calls. Types do not make a model deterministic, prove that an action is permitted, or turn third-party output into trusted data. The production design still belongs to the application around the model.
What makes an agent different from a chat response
A chat response is one model result. An agent run is a controlled loop: send the current input to a model, inspect its output, execute eligible tool calls, append the results, and continue until the run reaches a stopping condition. It may also hand work to another specialist or pause for approval.
That distinction is visible in the OpenAI Agents SDK architecture. Its runner owns the recurring loop, while the application owns deployment, tool implementations, state, and approval decisions. The documented runner sequence stops on a final answer, switches on a handoff, or continues after tool results. Vercel's AI SDK loop controls make the same boundary explicit with ToolLoopAgent and configurable stop conditions.
The loop is deterministic code wrapped around probabilistic decisions. The model may select a different tool, produce different valid arguments, or decide it has enough information on another run. Product promises should therefore describe permitted actions and measured success rates, not imply a guaranteed sequence of thoughts.
Typed tools are the control surface
A tool is a capability contract: a name and description for model selection, an input schema for runtime validation and type inference, and an implementation that reads data or creates a side effect. Narrow tools are easier to authorize, test, observe, and explain than a generic “run anything” endpoint.
The current OpenAI Agents SDK tool API uses Zod parameters; AI SDK tool calling uses inputSchema; and the production-supported MCP TypeScript SDK v1 can expose Zod-backed tool schemas over a standard protocol. The names differ, but the architectural goal is the same: keep the model-facing contract small and the trusted implementation server-side.
Structured inputs and outputs
This example uses the stable @openai/agents TypeScript API. The authenticated actor arrives through local run context rather than model-visible arguments. Approval pauses the run, while the handler still checks authorization immediately before the write.
import { Agent, RunContext, tool } from "@openai/agents"
import { z } from "zod"
type AppContext = { actorId: string }
// Application-owned services; implementations are intentionally omitted.
declare const authorize: (
actorId: string,
permission: string,
resourceId: string
) => Promise<void>
declare const support: {
closeTicket(input: {
actorId: string
resolution: string
ticketId: string
}): Promise<{ status: "closed" }>
}
const closeTicket = tool({
name: "close_ticket",
description: "Close one support ticket with a recorded resolution.",
parameters: z.object({
ticketId: z.string().min(1),
resolution: z.string().min(10).max(500),
}),
needsApproval: true,
async execute(input, runContext?: RunContext<AppContext>) {
if (!runContext) throw new Error("Missing authenticated context")
await authorize(runContext.context.actorId, "ticket:close", input.ticketId)
return support.closeTicket({
...input,
actorId: runContext.context.actorId,
})
},
})
export const supportAgent = new Agent<AppContext>({
name: "Support operations",
instructions: "Never report success before a tool returns success.",
tools: [closeTicket],
})The schema rejects malformed shape; it does not establish ownership, tenant membership, current ticket state, or business policy. Those checks stay in authorize and the domain service. Validate tool results too, especially when they contain remote content: a successful HTTP response can still be stale, oversized, malicious, or instruction-like text that should remain data.
The agent loop and stopping conditions
A production loop needs more than “continue until the model is finished.” Bound steps, wall-clock time, model tokens, tool retries, concurrent calls, and total cost. Stop on repeated failures and cancellation, and pause instead of executing a tool whose approval is unresolved.
OpenAI exposes a maximum-turn failure path and resumable state for interrupted approvals. AI SDK provides stepCountIs, hasToolCall, and custom stopWhen predicates; its documented default is 20 steps, but a product should choose a smaller task-specific ceiling rather than inherit a framework default accidentally. Tool handlers also need timeouts and idempotency keys because a retry after a network failure may repeat a real side effect.
Why developers should care
Typed tools give developers a seam between fuzzy intent and ordinary application code. A schema can infer handler inputs, a mock can test tool behavior without a model, and a trace can show which call changed the run. Teams can replace prompts or models without rewriting the business capability behind a stable contract.
The tradeoff is distributed debugging. An incorrect result may come from tool selection, arguments, authorization context, stale data, output interpretation, or loop state. Agent frameworks reduce orchestration boilerplate; they do not remove the need for domain services, integration tests, failure design, or a replayable record of what happened.
Why companies should care
Agents can compress workflows that currently require people to search several systems, reconcile results, and perform a bounded action. The business case is strongest when the task has a measurable finish line: resolution time, successful completion rate, handling cost, or time returned to a specialist.
Autonomy also concentrates operational risk. A wrong paragraph is corrected; a wrong refund, permission change, or customer message creates work and liability. Compare value after approval time, exception handling, model and tool cost, audit retention, and incident response are included. If fixed rules can complete the workflow reliably, a conventional service or workflow engine is usually easier to predict and govern.
Production controls that demos omit
The distance from a demo to a product is mostly the control plane around the loop.
| Demo shortcut | Production control | Risk reduced |
|---|---|---|
| Accept schema-valid arguments | Domain validation and fresh server-side authorization | Invalid or cross-tenant access |
| Execute every proposed action | Risk policy plus review of exact normalized arguments | Unwanted side effects |
| Retry the whole run | Idempotency keys and bounded, tool-specific retries | Duplicate writes |
| Let the loop continue | Step, time, token, cost, and concurrency budgets | Runaway latency and spend |
| Print prompts and outputs | Correlated traces, redaction, retention, and audit events | Opaque failures or data leakage |
| Test one happy-path prompt | Versioned datasets, adversarial cases, canaries, and rollback | Silent behavioral regressions |
MCP can standardize the connection between agents and external capabilities, but it does not transfer trust. As of July 16, 2026, the official TypeScript SDK says v2 is beta and v1.x remains the supported production release; stable v2 is expected with the full July 28 specification. Production systems should use the v1 documentation and pin a compatible release rather than copy evolving v2 migration examples. For remote v1 servers, Streamable HTTP is recommended; legacy HTTP with SSE is retained only for backward compatibility.
Authorization, approval, observability, and evaluation
Treat every tool call as untrusted input, even after schema validation and even when it came from your own agent. Resolve the authenticated actor and tenant on the server, authorize the specific resource and operation, recheck mutable preconditions, and give tools the least privilege they need. Never pass a browser-supplied role, tenant ID, or approval flag through as proof.
Approval is a separate control. The OpenAI approval flow pauses a run and resumes from the same state; the MCP tools specification recommends visible tool exposure and a human ability to deny invocations. Bind an approval to the actor, tool, exact normalized arguments, and a short validity window. MCP proxy deployments should also follow the protocol's security guidance, including per-client consent and protections against confused-deputy flows.
Observability should connect one run to its model calls, tool arguments, results, approvals, retries, costs, and domain audit events without recording secrets by default. OpenAI's Agents SDK tracing captures model calls, tools, handoffs, and guardrails; teams still need a privacy-aware retention policy and business-level success events.
Then evaluate behavior, not just prose. A regression set should score correct tool selection, argument validity, authorization denials, abstention, side-effect accuracy, latency, and cost. The agent evaluation guidance recommends moving from individual traces to repeatable datasets and eval runs. Evals estimate risk; canary releases, alerts, and rollback contain failures they did not predict.
Adoption checklist
- Choose one bounded workflow with an observable success measure.
- Define narrow, typed tools and validate both inputs and outputs at runtime.
- Keep credentials, identity, tenant context, and authorization on the server.
- Require approval for irreversible, financial, privileged, or externally visible actions.
- Bind approvals to exact arguments and re-authorize immediately before execution.
- Add step, time, token, cost, retry, and concurrency limits.
- Make write tools idempotent and safe to resume after interruption.
- Trace decisions and side effects with redaction and explicit retention.
- Evaluate happy paths, denials, malformed calls, prompt injection, and outages.
- Pin stable SDK versions; keep MCP TypeScript SDK v2 out of production while it remains beta.
- Roll out behind a canary, monitor business metrics, and keep a non-agent fallback.
The practical decision
Use an agent when the work genuinely needs model-guided choice across several bounded steps and the surrounding system can enforce the consequences. OpenAI's Agents SDK is a strong fit when its managed runner, approvals, state, and tracing match the runtime; AI SDK offers a provider-oriented TypeScript loop with explicit tool and stop controls; MCP is useful when capabilities must be portable across compatible clients.
Do not start with maximum autonomy. Start with read-only tools, explicit ceilings, and a human checkpoint; measure completion, corrections, cost, and incidents; then widen permissions one capability at a time. The durable advantage is not that a model can call a function. It is that the company can prove which functions it may call, for whom, under what limits, and with what evidence afterward.
