惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
F
Full Disclosure
月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tailwind CSS Blog
Microsoft Security Blog
Microsoft Security Blog
N
Netflix TechBlog - Medium
The Register - Security
The Register - Security
aimingoo的专栏
aimingoo的专栏
The GitHub Blog
The GitHub Blog
D
Docker
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
P
Proofpoint News Feed
Cisco Talos Blog
Cisco Talos Blog
NISL@THU
NISL@THU
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
美团技术团队
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Martin Fowler
Martin Fowler
L
Lohrmann on Cybersecurity
Know Your Adversary
Know Your Adversary
Simon Willison's Weblog
Simon Willison's Weblog
S
Securelist
T
Threatpost
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
L
LangChain Blog
Blog — PlanetScale
Blog — PlanetScale
Recorded Future
Recorded Future
C
Cisco Blogs
S
SegmentFault 最新的问题
Cyberwarzone
Cyberwarzone
GbyAI
GbyAI
IT之家
IT之家
S
Schneier on Security
L
LINUX DO - 热门话题
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
MyScale Blog
MyScale Blog
P
Privacy & Cybersecurity Law Blog
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Designing Reliable Tool Schemas with Zod for LLM Agents
Ethan Cole · 2026-05-11 · via DEV Community

LLM agents often fail in surprisingly ordinary places.

Not in the model call. Not in the prompt. Not even in the function that eventually does the work.

They fail at the boundary between "the model produced some arguments" and "my application trusted those arguments enough to run code."

That boundary is where tool schemas matter.

If you are building anything agent-like in TypeScript, such as an internal automation, an MCP server, a CLI helper, or a backend workflow that lets a model call functions, Zod is a practical way to make that boundary explicit.

The goal is simple: treat model output as untrusted input without filling the codebase with scattered defensive checks.

This article walks through the pattern I use for designing reliable tool schemas with Zod.

No framework required. No product pitch. Just TypeScript boundaries.

The problem with "almost valid" tool calls

Imagine we expose a tool like this:

async function searchDocs(input: {
  query: string;
  limit?: number;
  includeDrafts?: boolean;
}) {
  // Search implementation...
}

Enter fullscreen mode Exit fullscreen mode

If a human developer calls this function, TypeScript helps.

If a model calls it, TypeScript does not help at runtime.

The model might produce:

{
  "query": "OAuth callback errors",
  "limit": "10",
  "includeDrafts": "false"
}

Enter fullscreen mode Exit fullscreen mode

That looks close. It is also wrong.

Depending on how the code handles it, "10" might silently work, "false" might behave as truthy, and the tool might return draft documents even though the user did not ask for them.

This is why I like to think of tool inputs as API requests from a slightly chaotic client. The model is not malicious, but it is not type-safe either.

Start with a runtime schema

The first improvement is to define the input shape with Zod:

import { z } from "zod";

const SearchDocsInput = z.object({
  query: z.string().min(1).max(200),
  limit: z.number().int().min(1).max(20).default(5),
  includeDrafts: z.boolean().default(false),
});

type SearchDocsInput = z.infer<typeof SearchDocsInput>;

Enter fullscreen mode Exit fullscreen mode

Now the actual tool accepts a validated type:

async function searchDocs(input: SearchDocsInput) {
  // input.query is a non-empty string
  // input.limit is an integer from 1 to 20
  // input.includeDrafts is a boolean
}

Enter fullscreen mode Exit fullscreen mode

Then the runtime boundary becomes explicit:

async function runSearchDocs(rawInput: unknown) {
  const input = SearchDocsInput.parse(rawInput);
  return searchDocs(input);
}

Enter fullscreen mode Exit fullscreen mode

That is already safer. But for model-facing tools, I usually prefer safeParse.

async function runSearchDocs(rawInput: unknown) {
  const result = SearchDocsInput.safeParse(rawInput);

  if (!result.success) {
    return {
      ok: false,
      error: "Invalid tool input",
      issues: result.error.issues.map((issue) => ({
        path: issue.path.join("."),
        message: issue.message,
      })),
    };
  }

  const data = await searchDocs(result.data);

  return {
    ok: true,
    data,
  };
}

Enter fullscreen mode Exit fullscreen mode

Instead of crashing the whole run, the tool can return a structured validation error that the agent or application can handle.

Coerce deliberately, not accidentally

Coercion can be useful. Models often produce numbers as strings, especially when values came from natural language.

Zod supports this:

const SearchDocsInput = z.object({
  query: z.string().min(1).max(200),
  limit: z.coerce.number().int().min(1).max(20).default(5),
  includeDrafts: z.coerce.boolean().default(false),
});

Enter fullscreen mode Exit fullscreen mode

But be careful with booleans.

JavaScript boolean coercion is not the same thing as parsing user intent:

Boolean("false"); // true

Enter fullscreen mode Exit fullscreen mode

For model-facing schemas, I usually avoid broad boolean coercion and define a stricter helper:

const BooleanFromModel = z.union([
  z.boolean(),
  z.literal("true").transform(() => true),
  z.literal("false").transform(() => false),
]);

const SearchDocsInput = z.object({
  query: z.string().min(1).max(200),
  limit: z.coerce.number().int().min(1).max(20).default(5),
  includeDrafts: BooleanFromModel.default(false),
});

Enter fullscreen mode Exit fullscreen mode

The point is not "never coerce." The point is to make every coercion a design choice.

Keep schemas boring

Tool schemas should be boring.

That sounds small, but it matters. If a schema is too clever, the model has a harder time producing valid input, and humans have a harder time debugging failures.

Prefer this:

const CreateIssueInput = z.object({
  title: z.string().min(1).max(120),
  body: z.string().max(4000).optional(),
  priority: z.enum(["low", "medium", "high"]).default("medium"),
});

Enter fullscreen mode Exit fullscreen mode

Over this:

const CreateIssueInput = z.object({
  payload: z.object({
    meta: z.object({
      attributes: z.record(z.unknown()),
    }),
  }),
});

Enter fullscreen mode Exit fullscreen mode

Nested shapes are sometimes necessary, but for model-called tools, flat and literal usually wins.

A good tool schema answers three questions quickly:

  1. What fields are allowed?
  2. What values are valid?
  3. What defaults will be applied?

If a future maintainer has to read several transforms to understand the shape, the schema is probably doing too much.

Use enums instead of open strings

Open strings give the model too much room to improvise.

For example:

const ExportReportInput = z.object({
  format: z.string(),
});

Enter fullscreen mode Exit fullscreen mode

The model might send:

{ "format": "spreadsheet" }

Enter fullscreen mode Exit fullscreen mode

But your code expected "csv" or "xlsx".

Use an enum:

const ExportReportInput = z.object({
  format: z.enum(["csv", "xlsx", "json"]),
});

Enter fullscreen mode Exit fullscreen mode

This helps in two ways.

First, runtime validation becomes safer.

Second, if you convert the Zod schema into JSON Schema for a tool definition, the model can see the allowed values directly.

Separate public input from internal options

One mistake I see in tool design is exposing internal options too early.

Suppose your search system supports these options:

type InternalSearchOptions = {
  query: string;
  limit: number;
  indexName: string;
  rankingProfile: "fast" | "balanced" | "deep";
  debugTraceId?: string;
};

Enter fullscreen mode Exit fullscreen mode

That does not mean the model-facing tool should expose all of them.

Create a smaller public schema:

const SearchInput = z.object({
  query: z.string().min(1).max(200),
  limit: z.number().int().min(1).max(10).default(5),
});

Enter fullscreen mode Exit fullscreen mode

Then map it into internal options:

function toInternalSearchOptions(input: SearchInput): InternalSearchOptions {
  return {
    query: input.query,
    limit: input.limit,
    indexName: "docs",
    rankingProfile: "balanced",
  };
}

Enter fullscreen mode Exit fullscreen mode

This is one of the simplest ways to make tools safer.

The model should control intent, not infrastructure.

Return structured errors

When validation fails, do not return a giant stack trace to the model. Also do not return a vague "bad input".

Return compact, structured feedback:

function formatZodError(error: z.ZodError) {
  return error.issues.map((issue) => ({
    field: issue.path.join(".") || "(root)",
    problem: issue.message,
  }));
}

Enter fullscreen mode Exit fullscreen mode

Example response:

{
  "ok": false,
  "error": "Invalid tool input",
  "issues": [
    {
      "field": "limit",
      "problem": "Number must be less than or equal to 20"
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

This is useful for three audiences:

  • The model can retry with better arguments.
  • The developer can see what went wrong.
  • The application can log validation failures without leaking sensitive internals.

Add descriptions where your tool runtime supports them

Zod itself is not an LLM tool spec. But many stacks let you turn Zod schemas into JSON Schema, OpenAPI-like definitions, or tool descriptors.

Descriptions help the model choose fields correctly:

const SearchDocsInput = z.object({
  query: z
    .string()
    .min(1)
    .max(200)
    .describe("The plain-language search query."),
  limit: z
    .number()
    .int()
    .min(1)
    .max(20)
    .default(5)
    .describe("Maximum number of results to return."),
  includeDrafts: z
    .boolean()
    .default(false)
    .describe("Whether unpublished draft documents may be included."),
});

Enter fullscreen mode Exit fullscreen mode

Keep descriptions short and literal.

Bad description:

.describe("Use this when the user really wants to go deep and find all the things.")

Enter fullscreen mode Exit fullscreen mode

Better description:

.describe("Maximum number of results to return.")

Enter fullscreen mode Exit fullscreen mode

The model does not need vibes. It needs constraints.

Put authorization outside the schema

Zod can validate shape. It cannot decide whether the caller is allowed to do something.

Keep those separate:

const DeleteDocumentInput = z.object({
  documentId: z.string().uuid(),
});

async function runDeleteDocument(rawInput: unknown, user: User) {
  const result = DeleteDocumentInput.safeParse(rawInput);

  if (!result.success) {
    return {
      ok: false,
      error: "Invalid tool input",
      issues: formatZodError(result.error),
    };
  }

  const canDelete = await permissions.canDeleteDocument(
    user.id,
    result.data.documentId,
  );

  if (!canDelete) {
    return {
      ok: false,
      error: "Not authorized to delete this document",
    };
  }

  await documents.delete(result.data.documentId);

  return {
    ok: true,
  };
}

Enter fullscreen mode Exit fullscreen mode

The schema proves the input is shaped correctly.

The permission check proves the action is allowed.

You need both.

A small wrapper pattern

After writing a few tools, the validation wrapper starts to repeat. I usually extract a tiny helper:

import { z } from "zod";

type ToolResult<T> =
  | { ok: true; data: T }
  | {
      ok: false;
      error: string;
      issues?: Array<{ field: string; problem: string }>;
    };

function defineTool<InputSchema extends z.ZodTypeAny, Output>(
  schema: InputSchema,
  handler: (input: z.infer<InputSchema>) => Promise<Output>,
) {
  return async function run(rawInput: unknown): Promise<ToolResult<Output>> {
    const result = schema.safeParse(rawInput);

    if (!result.success) {
      return {
        ok: false,
        error: "Invalid tool input",
        issues: formatZodError(result.error),
      };
    }

    const data = await handler(result.data);

    return {
      ok: true,
      data,
    };
  };
}

Enter fullscreen mode Exit fullscreen mode

Now tools stay small:

const searchDocsTool = defineTool(SearchDocsInput, async (input) => {
  return searchDocs(input);
});

Enter fullscreen mode Exit fullscreen mode

This is not a full agent framework. It is just a clean runtime boundary.

That is often enough.

Checklist for model-facing Zod schemas

Before I ship a tool schema, I like to check:

  • Are all fields explicitly listed?
  • Are strings bounded with min and max?
  • Are numbers bounded with min, max, and int where appropriate?
  • Are open strings replaced with enums when possible?
  • Are defaults safe?
  • Are coercions deliberate?
  • Are internal options hidden?
  • Are validation errors structured?
  • Are authorization checks separate from validation?

Most tool bugs come from skipping one of those.

Final thought

The best tool schemas are not fancy.

They are narrow, readable, and a little suspicious of everything crossing the model-to-code boundary.

That suspicion is healthy. It lets you build agents that can recover from bad inputs, explain what went wrong, and call real application code without pretending a language model is a type checker.

Zod is not the only way to do this.

But if your agent code is already in TypeScript, it is one of the fastest ways to make the boundary concrete.