AI TOOL SCHEMA
ai-tool-schema.ts
Type-safe tool definitions with provider adapters.
StarkWHAT THIS PATTERN TEACHES
How to define tools once and convert to any provider format (Anthropic, OpenAI). Zod schemas validate model output as untrusted input. Registry pattern manages available tools per context.
WHEN TO USE THIS
Any application using function-calling / tool-use with LLM APIs. Define tools once, use everywhere.
AT A GLANCE
const searchTool = defineTool({
name: 'search',
description: 'Search the knowledge base',
parameters: z.object({ query: z.string() }),
execute: async ({ query }) => search(query),
});FRAMEWORK IMPLEMENTATIONS
TypeScript
import { z } from 'zod';
interface ToolDef<T extends z.ZodType> {
name: string;
description: string;
parameters: T;
execute: (params: z.infer<T>) => Promise<string>;
}
function defineTool<T extends z.ZodType>(def: ToolDef<T>) {
return {
...def,
toAnthropic: () => ({
name: def.name,
description: def.description,
input_schema: zodToJsonSchema(def.parameters),
}),
toOpenAI: () => ({
type: 'function' as const,
function: {