tutorials
One Zod tool manifest for MCP, chat, and CLI
November 13, 2026

You wire a tool into your chat agent, then again into your MCP server, then again into your CLI. Three copies of the same schema, three descriptions that say almost the same thing, and three execute bodies that were identical until someone fixed a bug in only one of them.
If you expose the same capabilities to an in-app AI chat, to an external MCP client like Claude, and to a CLI, the naive path defines each tool three times. That triplication is where drift lives: a parameter gets renamed in the chat tool but not the MCP one, the CLI validates differently from the agent, and the descriptions slowly diverge until the model and the human are working from different mental models of the same action.
This article shows the hard way first (three hand-maintained definitions), names exactly where they rot, and then builds the single-manifest pattern that collapses them into one declaration with thin per-surface adapters. The code is the pattern the Tinbox MCP server and chat agent actually use.
How can I define an AI tool once and reuse it across MCP, chat, and a CLI?
Put each tool's name, description, Zod input schema, and execute function in one manifest entry that imports only Zod and your own result types. Then write one thin adapter per surface that reads that entry: chat wraps it in the AI SDK, MCP emits a JSON-RPC descriptor, the CLI generates flags. The schema and the execute live in exactly one place, so the surfaces translate the same declaration instead of restating it.
The rule that makes this hold: the manifest is SDK-free. It never imports the AI SDK, the MCP SDK, a provider SDK, or your runtime's bindings. Every surface-specific dependency lives in the adapter for that surface. Break this rule and your CLI starts dragging in the AI SDK, and a non-edge consumer pulls in worker bindings it has no use for.
The hard way: three definitions, three sources of drift
Here is a single search_emails tool defined separately for each surface, the way most projects start. It looks reasonable. It is a trap.
The chat version, using the Vercel AI SDK:
// chat/tools.ts
import { tool } from "ai";
import { z } from "zod";
export const searchEmailsChat = tool({
description: "Full-text search the user's mail by subject, sender, or body.",
inputSchema: z.object({
query: z.string(),
inboxId: z.string().optional(),
}),
execute: async ({ query, inboxId }) => {
const out = await db.searchEmails(query, inboxId);
return out.results.map((r) => `${r.subject} from ${r.from}`).join("\n");
},
});
The MCP version, hand-written as a JSON-RPC descriptor with JSON Schema (MCP does not speak Zod):
// mcp/tools.ts
export const searchEmailsMcp = {
name: "search_emails",
description: "Search emails by subject or sender.", // already diverging
inputSchema: {
type: "object",
properties: {
query: { type: "string" },
inbox: { type: "string" }, // oops: "inbox", not "inboxId"
},
required: ["query"],
},
async call(args: { query: string; inbox?: string }) {
const out = await db.searchEmails(args.query, args.inbox);
return { content: [{ type: "text", text: JSON.stringify(out.results) }] };
},
};
And the CLI version:
// cli/search.ts
program
.command("search-emails <query>")
.option("--inbox-id <id>")
.action(async (query, opts) => {
const out = await db.searchEmails(query, opts.inboxId);
console.table(out.results); // different output shape again
});
Three files, one capability. Count the drift already present in this small example:
- The descriptions differ. The model behind chat and the model behind the MCP client are reading different instructions for the same tool.
- The MCP schema named the field
inbox; the others useinboxId. An MCP client that passesinboxIdgets silently ignored. - The CLI prints a table, chat returns a joined string, MCP returns stringified JSON. Three result shapes nobody reconciled.
- Validation is inconsistent: chat and MCP enforce a Zod or JSON Schema, the CLI trusts commander.
None of this is hypothetical. The moment you add a field, fix a description, or change a result shape, you have to find and edit three places, and the day you forget one is the day a client breaks in a way your type-checker cannot see, because each surface validates its own copy.
You can mitigate by hand: keep a shared searchEmails(query, inboxId) function so at least the data access is shared. That helps, but the interface (schema, description, validation, result shape) is still triplicated, and the interface is what the model and the human actually consume.
The fix: one Zod manifest, thin per-surface adapters
Define the tool once. A manifest entry holds the name, the description, a single Zod input schema, MCP-style annotations, an execute that returns a structured result, and a function that trims that result down to what the model should see.
First, the dependency-free contracts. A discriminated union for results and a context for execution. These import nothing but types:
// tools/result.ts (zero deps, imported by tools AND the UI card switch)
export type ToolResult =
| { kind: "email_list"; query?: string; emails: ToolEmail[]; truncated?: boolean }
| { kind: "error"; message: string };
export interface ToolEmail {
messageId: string;
threadId: string;
inboxId: string;
subject: string;
from: string;
preview: string;
date: number;
}
export function toolError(message: string): ToolResult {
return { kind: "error", message };
}
// tools/manifest.ts (imports ONLY zod + your own result/context types)
import type { z } from "zod";
import type { ToolResult } from "./result.js";
export interface ToolAnnotations {
readOnlyHint: boolean;
destructiveHint: boolean;
idempotentHint: boolean;
}
export type ToolSurface = "chat" | "mcp" | "cli";
/** The execution context: an authorized caller + capture sinks. */
export interface ToolContext {
caller: AppCaller; // your authorized data layer
fullResults: Map<string, string>;
errored: Set<string>;
}
export interface ToolManifestEntry<
TInput extends z.ZodTypeAny = z.ZodTypeAny,
TOutput extends ToolResult = ToolResult,
> {
name: string;
title: string;
description: string;
inputSchema: TInput;
annotations: ToolAnnotations;
/** Omit ⇒ every surface; pass a subset to opt out. */
surfaces?: ToolSurface[];
execute: (input: z.infer<TInput>, ctx: ToolContext, callId: string) => Promise<TOutput>;
toModelText: (result: TOutput) => string;
}
/** Fixes generic inference so `input` in execute is z.infer<inputSchema>. */
export function defineManifestTool<TInput extends z.ZodTypeAny, TOutput extends ToolResult>(
entry: ToolManifestEntry<TInput, TOutput>,
): AnyToolManifestEntry {
return entry as unknown as AnyToolManifestEntry;
}
The trick in defineManifestTool is worth pausing on. Because it captures the per-tool generic at the call site, z.infer<typeof inputSchema> flows straight into your execute parameter type. You declare the schema once and the input type is derived, not restated. It returns an input-erased AnyToolManifestEntry so you can hold a heterogeneous array of tools (each with its own schema) in one TOOL_MANIFEST[], while the runtime Zod schema still validates each call.
Now the actual tool, declared exactly once:
// tools/email-tools.ts
import { z } from "zod";
import { defineManifestTool } from "./manifest.js";
import { type ToolResult, type ToolEmail } from "./result.js";
export const searchEmails = defineManifestTool({
name: "search_emails",
title: "Search email",
description:
"Full-text search the user's mail by subject, sender, or body. Call this " +
"to find relevant emails BEFORE answering. Returns matching messages with " +
"threadId, inboxId, subject, sender, and a body preview.",
inputSchema: z.object({
query: z.string().describe("Search terms (e.g. 'refund', 'invoice March')."),
inboxId: z
.string()
.optional()
.describe("Optional: restrict to one inbox id. Omit to search all."),
}),
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
execute: async ({ query, inboxId }, ctx): Promise<ToolResult> => {
const out = (await ctx.caller.emails.search({ query, inboxId })) as {
results?: Record<string, unknown>[];
total?: number;
};
const results = out.results ?? [];
return {
kind: "email_list",
query,
emails: results.map(toEmail),
truncated: (out.total ?? results.length) > results.length,
};
},
toModelText: (r) =>
r.kind === "email_list"
? `Found ${r.emails.length} email(s) for "${r.query}":\n` +
r.emails.map((e) => `- [${e.threadId}] ${e.subject} (${e.from}): ${e.preview}`).join("\n")
: "",
});
function toEmail(m: Record<string, unknown>): ToolEmail {
const body = String(m.bodyText ?? m.preview ?? "");
return {
messageId: String(m.messageId ?? m.id ?? ""),
threadId: String(m.threadId ?? ""),
inboxId: String(m.inboxId ?? ""),
subject: String(m.subject ?? "(no subject)"),
from: String(m.from ?? ""),
preview: body.slice(0, 200),
date: typeof m.date === "number" ? m.date : 0,
};
}
export const TOOL_MANIFEST = [searchEmails /* , ...the rest */];
Notice the result is structured ({ kind: "email_list", emails: [...] }), not a string. The chat UI can render a card by switching on kind, MCP returns it as structuredContent, and the CLI can format it for a terminal. The model, meanwhile, never sees the full object: toModelText gives it a trimmed text view so a 200-result search does not blow the token budget. One object, three presentations.
How do I adapt one manifest entry into a Vercel AI SDK tool?
Map the entry's Zod schema and execute straight into the SDK's tool() call, and use toModelOutput to feed the model the trimmed text while the structured result is persisted for the UI. This is the only place the manifest meets the AI SDK.
// adapters/ai-sdk.ts
import { tool, zodSchema } from "ai";
import type { Tool } from "ai";
import type { AnyToolManifestEntry, ToolContext } from "../tools/manifest.js";
import { toolError } from "../tools/result.js";
export function toAiSdkTool(entry: AnyToolManifestEntry, ctx: ToolContext): Tool {
return tool<any, any>({
description: entry.description,
inputSchema: zodSchema(entry.inputSchema),
needsApproval: entry.annotations.destructiveHint,
execute: async (input: unknown, { toolCallId }: { toolCallId: string }) => {
let result;
try {
result = await entry.execute(input as never, ctx, toolCallId);
} catch (err) {
result = toolError(err instanceof Error ? err.message : String(err));
}
if (result.kind === "error") ctx.errored.add(toolCallId);
ctx.fullResults.set(toolCallId, JSON.stringify(result)); // audit sink
return result; // structured → the chat card reads this
},
// The model sees the trimmed text; the card reads the full structured output.
toModelOutput: ({ output }) => ({
type: "text",
value: entry.toModelText(output as never),
}),
});
}
The AI SDK consumes the Zod schema directly through zodSchema(), so there is no second schema to maintain. needsApproval is wired from the manifest's destructiveHint, which means a tool that sends mail (send_email) asks for human confirmation in chat without a special case. If you are building the chat loop itself, see tool-calling over an inbox with the Vercel AI SDK for the streaming side.
How do I expose the same manifest over an MCP server?
Answer MCP's tools/list by converting each Zod schema to JSON Schema (the AI SDK's zodSchema() ships a .jsonSchema for exactly this), and answer tools/call by validating arguments against the same Zod schema before running the same execute. On Cloudflare Workers this is a stateless JSON-RPC handler, no heavy SDK required.
// adapters/mcp.ts (a stateless JSON-RPC 2.0 handler)
import { zodSchema } from "ai";
import { MANIFEST_BY_NAME, toolNamesForSurface } from "../tools/index.js";
export async function handleMcp(body: JsonRpcRequest, ctx: ToolContext): Promise<unknown> {
const allowed = new Set(toolNamesForSurface("mcp"));
switch (body.method) {
case "initialize":
return rpcResult(body.id, {
protocolVersion: "2025-06-18",
capabilities: { tools: {} },
serverInfo: { name: "tinbox", version: "1" },
});
case "tools/list": {
const tools = [];
for (const name of allowed) {
const entry = MANIFEST_BY_NAME[name];
if (!entry) continue;
// Zod → JSON Schema, the format MCP clients expect.
const inputSchema = await Promise.resolve(zodSchema(entry.inputSchema as any).jsonSchema);
tools.push({
name: entry.name,
title: entry.title,
description: entry.description, // SAME description as chat
inputSchema,
annotations: entry.annotations,
});
}
return rpcResult(body.id, { tools });
}
case "tools/call": {
const name = String(body.params?.name ?? "");
const entry = MANIFEST_BY_NAME[name];
if (!entry || !allowed.has(name)) {
return rpcError(body.id, -32601, `Unknown tool "${name}".`);
}
// Validate with the SAME Zod schema the chat path uses.
const parsed = entry.inputSchema.safeParse(body.params?.arguments ?? {});
if (!parsed.success) {
return rpcError(body.id, -32602, `Invalid arguments: ${parsed.error.message}`);
}
const result = await entry.execute(parsed.data, ctx, crypto.randomUUID());
return rpcResult(body.id, {
content: [{ type: "text", text: entry.toModelText(result) }],
structuredContent: result,
isError: result.kind === "error",
});
}
}
}
The MCP description is now literally entry.description, the same string the chat model reads. There is no second place to forget. The surfaces field gives you a clean opt-out axis: a tool that should not appear over MCP just omits "mcp" from its surfaces, and toolNamesForSurface("mcp") filters it out. For the auth layer that fronts this (tbx_ bearer tokens, or OAuth 2.1 with PKCE for the Claude app), see adding OAuth 2.1 and PKCE to your MCP server. Before you ship an inbox over MCP, the things to know before you run an email MCP server covers the operational gotchas this pattern does not.
A note on the Workers runtime: a Cloudflare Worker has no long-lived process, so the MCP transport here is stateless. Each POST resolves the bearer token, builds the context, dispatches, and returns. That is a feature, not a limitation, for the edge.
How do I generate a CLI command from the same manifest?
Introspect the Zod object shape: turn each field into a --flag (or a positional, by hint), coerce and validate the parsed values against the same schema, then run the same execute. The CLI adds no new data path; it bridges its tRPC client to the caller shape the execute expects with a Proxy.
// adapters/cli.ts
import { Command } from "commander";
import { z } from "zod";
import type { AnyToolManifestEntry } from "../tools/manifest.js";
export function manifestToCommand(entry: AnyToolManifestEntry, makeCtx: () => ToolContext): Command {
const shape = (entry.inputSchema as z.ZodObject<z.ZodRawShape>).shape;
const positional = entry.cli?.positional ?? [];
const cmd = new Command(entry.name.replace(/_/g, "-")).description(entry.description);
for (const field of positional) {
cmd.argument(`<${field}>`, describe(shape[field]));
}
for (const field of Object.keys(shape).filter((k) => !positional.includes(k))) {
cmd.option(`--${field.replace(/_/g, "-")} <value>`, describe(shape[field]));
}
// Destructive tools mirror chat's confirmation with a --yes gate.
if (entry.annotations.destructiveHint) cmd.option("--yes", "confirm destructive action");
cmd.action(async function (this: Command, ...args) {
const raw = assembleInput(shape, positional, args, this.opts());
// Validate against the SAME Zod schema the chat + MCP paths use.
const parsed = entry.inputSchema.safeParse(raw);
if (!parsed.success) throw new Error(`Invalid arguments: ${parsed.error.message}`);
const result = await entry.execute(parsed.data, makeCtx(), `cli:${entry.name}`);
if (result.kind === "error") throw new Error(result.message);
console.log(renderForHuman(result)); // format the SAME structured result
});
return cmd;
}
Now tinbox search-emails "refund" --inbox-id inb_123 runs the exact execute the chat agent runs and the MCP client runs. The .describe() you put on each Zod field becomes the flag's help text, so the CLI documentation is also derived from the one declaration. Destructive tools get a --yes gate that mirrors chat's confirmation prompt, so a script cannot silently send.
Here is the failure mode that proves the validation is shared. Run the command with a missing required argument and you get the Zod error, not a stack trace, before any network call:
$ tinbox search-emails
error: missing required argument 'query'
$ tinbox search-emails "" --inbox-id 42
Invalid arguments: query: String must contain at least 1 character(s)
That second message is Zod talking. The same message would come back from the MCP tools/call and from the chat tool, because all three validate against the identical schema.
How do I keep the three surfaces from drifting over time?
Write a test that introspects the live manifest and asserts which tools appear on which surface against a checked-in snapshot. Adding a tool, or flipping a tool's surfaces, fails the test until you update the snapshot on purpose. Drift becomes a red build instead of a silent production bug.
// surface-compat.test.ts
import { describe, it, expect } from "vitest";
import { TOOL_MANIFEST, toolEnabledOn } from "./tools/index.js";
describe("surface compatibility matrix", () => {
it("each tool's surface exposure matches the snapshot", () => {
const matrix = TOOL_MANIFEST.map((t) => ({
name: t.name,
chat: toolEnabledOn(t, "chat"),
mcp: toolEnabledOn(t, "mcp"),
cli: toolEnabledOn(t, "cli"),
}));
expect(matrix).toMatchSnapshot();
});
});
Pair it with an integrity check that confirms every backend procedure a tool dispatches still exists. The casts inside a tool's execute defeat the type-checker, so a renamed data-layer method would otherwise slip through; a runtime introspection of the router catches it. Together, these two tests are the safety net that lets one manifest feed many surfaces without anyone hand-maintaining a compatibility list.
What you actually gain
Adding a capability becomes a one-file change. You write a new defineManifestTool entry, add it to TOOL_MANIFEST, and it appears in the chat agent, on the MCP endpoint, and as a CLI command, with one description, one schema, and one execute. For ideas on which capabilities are worth defining first, the agent tools to build for your inbox first is a good starting menu. The result type drives the chat card, the MCP structuredContent, and the CLI's human output from the same union. This is how the inbox you own becomes uniformly reachable, whether you are connecting Claude over MCP or scripting against it from a terminal.
The discipline that makes it work is one rule: the manifest imports nothing but Zod and your own types. Every SDK lives behind an adapter. Keep that boundary and the surfaces multiply for free; break it and they fuse back into a tangle.
In Tinbox, this manifest is the source of truth for the in-app AI chat, the /mcp route external assistants connect to, and the generated tinbox CLI, all reading the same TOOL_MANIFEST. The tools run the same authorized tRPC procedures your app already uses, so the agent layer adds zero new data paths and inherits your existing authorization for free.
Deploy this yourself: npx tinbox init <domain> scaffolds the manifest, the chat agent, the MCP route, and the CLI wired to a single tool registry on your own Cloudflare account. The full tool reference is generated from the same manifest in the docs.
Frequently asked questions
How can I define an AI tool once and reuse it for MCP, a chat agent, and a CLI?
Put the tool's name, description, Zod input schema, and execute function in a single manifest entry that imports only Zod (no AI SDK, no MCP SDK, no CLI framework). Then write one small adapter per surface that reads that entry: the chat adapter wraps it in the Vercel AI SDK tool() call, the MCP adapter emits a JSON-RPC tool descriptor and converts the Zod schema to JSON Schema, and the CLI adapter turns each schema field into a flag. All three call the same execute, so behavior stays identical.
Why does Zod work as the single source of truth for tool schemas?
Zod gives you a runtime validator and a static TypeScript type from one declaration. z.infer<typeof schema> drives the input type for the execute function, the AI SDK consumes the Zod schema directly, MCP needs JSON Schema which the AI SDK can derive from Zod, and a CLI can introspect the Zod object shape to generate flags. One schema satisfies every consumer's needs.
Should the shared manifest import the AI SDK or the MCP SDK?
No. Keep the manifest dependency-free except for Zod and your own result types. If the manifest imports the AI SDK or worker bindings, the CLI and any non-edge consumer drag those deps in too. Put every SDK-specific concern (the AI SDK tool() call, the MCP JSON-RPC envelope, commander flags) in the per-surface adapter, not the manifest.
How do I keep the three surfaces from silently drifting?
Add a test that introspects the live manifest and asserts the per-surface exposure matrix against a snapshot. When you add a tool or flip which surfaces it appears on, the snapshot fails until you update it consciously. Pair that with a test that checks every procedure a tool dispatches still exists, so a renamed backend call cannot slip through the type casts.
Does the same tool need a different execute function per surface?
No, and that is the point. The execute function takes a context object (an authorized caller plus a few sinks) and returns a structured result. Chat, MCP, and CLI each build that context their own way but pass it to the same execute, so the actual work runs once and the surfaces only differ in how they present the result.