ArkType

Use a Type directly with TanStack, tRPC, oRPC, Drizzle, React Hook Form, Hono, Elysia, Fastify, T3 Env, the MCP SDK, the AI SDK and the OpenAI and Anthropic SDKs.

Most libraries on this page accept a Standard Schema, so you pass a Type as-is with no adapter. Where a library also publishes an ArkType-specific adapter, its section shows the Standard Schema route first.

Any other library that accepts a Standard Schema works the same way. standardschema.dev keeps a list.

TanStack

TanStack Form and TanStack Router accept a Type directly with no adapter.

In TanStack Form, pass a Type as a form or field validator:

import { useForm } from "@tanstack/react-form"
import { type } from "arktype"

const 
const User: Type<{
    name: string;
    age: number;
}>
User
= type({
name: type("string > 0").message("Name is required"), age: "number.integer >= 0" }) export const useUserForm = () => useForm({ defaultValues: { name: "", age: 0 }, validators: { onChange:
const User: Type<{
    name: string;
    age: number;
}>
User
}
})

In TanStack Router (and TanStack Start), pass a Type directly to validateSearch:

import { createFileRoute } from "@tanstack/react-router"
import { type } from "arktype"

const 
const Search: Type<{
    page: Default<number, 1>;
    filter?: string;
}>
Search
= type({
page: "number.integer >= 1 = 1", "filter?": "string" }) export const const Route: ...Route = createFileRoute("/users")({ validateSearch:
const Search: Type<{
    page: Default<number, 1>;
    filter?: string;
}>
Search
})

tRPC

tRPC 11 accepts a Type as a procedure's input or output:

import { initTRPC } from "@trpc/server"
import { type } from "arktype"

const 
const t: TRPCRootObject<object, object, RuntimeConfigOptions<object, object>, {
    ctx: object;
    meta: object;
    errorShape: DefaultErrorShape;
    transformer: false;
}>
t
= initTRPC.create()
const
const User: Type<{
    name: string;
    age?: number;
}>
User
= type({
name: "string", "age?": "number.integer >= 0" }) export const
const appRouter: BuiltRouter<{
    ctx: object;
    meta: object;
    errorShape: DefaultErrorShape;
    transformer: false;
}, DecorateCreateRouterOptions<{
    createUser: MutationProcedure<{
        input: {
            name: string;
            age?: number;
        };
        output: {
            name: string;
            age?: number;
        };
        meta: object;
        errorShape: DefaultErrorShape;
    }>;
}>>
appRouter
=
const t: TRPCRootObject<object, object, RuntimeConfigOptions<object, object>, {
    ctx: object;
    meta: object;
    errorShape: DefaultErrorShape;
    transformer: false;
}>
t
.router({
createUser:
const t: TRPCRootObject<object, object, RuntimeConfigOptions<object, object>, {
    ctx: object;
    meta: object;
    errorShape: DefaultErrorShape;
    transformer: false;
}>
t
.procedure.input(
const User: Type<{
    name: string;
    age?: number;
}>
User
).mutation(({ input }) => input)
})

Invalid input is rejected with a BAD_REQUEST error before the resolver runs. Its cause is the TraversalError, so an errorFormatter can send each field's messages to the client:

import { initTRPC } from "@trpc/server"
import { flatMessagesByPath, TraversalError } from "arktype"

const 
const t: TRPCRootObject<object, object, {
    errorFormatter: ({ shape, error }: ErrorFormatterOptions<object | undefined>) => {
        data: {
            fieldErrors: Record<string, string[]> | null;
            code: TRPC_ERROR_CODE_KEY;
            httpStatus: number;
            path?: string;
            stack?: string;
        };
        message: string;
        code: TRPC_ERROR_CODE_NUMBER;
    };
}, {
    ctx: object;
    meta: object;
    errorShape: {
        data: {
            fieldErrors: Record<string, string[]> | null;
            code: TRPC_ERROR_CODE_KEY;
            httpStatus: number;
            path?: string;
            stack?: string;
        };
        message: string;
        code: TRPC_ERROR_CODE_NUMBER;
    };
    transformer: false;
}>
t
= initTRPC.create({
errorFormatter: ({ shape, error }) => ({ ...shape, data: { ...shape.data, // { name: ["must be a string"] } fieldErrors: error.cause instanceof TraversalError ? flatMessagesByPath(error.cause.arkErrors) : null } }) })

oRPC

oRPC accepts a Type the same way:

import { os } from "@orpc/server"
import { type } from "arktype"

const 
const User: Type<{
    name: string;
    age?: number;
}>
User
= type({
name: "string", "age?": "number.integer >= 0" }) export const
const createUser: DecoratedProcedure<Record<never, never>, Record<never, never>, Type<{
    name: string;
    age?: number;
}, {}>, Schema<{
    name: string;
    age?: number;
}, {
    name: string;
    age?: number;
}>, Record<never, never>, Record<never, never>>
createUser
= os.input(
const User: Type<{
    name: string;
    age?: number;
}>
User
).handler(({ input }) => input)

To generate an OpenAPI document, give oRPC's OpenAPIGenerator the converter from @orpc/arktype:

import { experimental_ArkTypeToJsonSchemaConverter } from "@orpc/arktype"
import { OpenAPIGenerator } from "@orpc/openapi"

const const generator: OpenAPIGeneratorgenerator = new OpenAPIGenerator({
	schemaConverters: [new experimental_ArkTypeToJsonSchemaConverter()]
})

const const spec: OpenAPIV3_1.Document<{}>spec = await const generator: OpenAPIGeneratorgenerator.generate({ createUser })

Drizzle

Drizzle maintains drizzle-arktype, which creates Types from your tables:

import { createInsertSchema, createSelectSchema } from "drizzle-arktype"
import { integer, pgTable, serial, text } from "drizzle-orm/pg-core"

const 
const users: PgTableWithColumns<{
    name: "users";
    schema: undefined;
    columns: {
        id: PgColumn<{
            name: "id";
            tableName: "users";
            dataType: "number";
            columnType: "PgSerial";
            data: number;
            driverParam: number;
            notNull: true;
            hasDefault: true;
            isPrimaryKey: true;
            isAutoincrement: false;
            hasRuntimeDefault: false;
            enumValues: undefined;
            baseColumn: never;
            identity: undefined;
            generated: undefined;
        }, {}, {}>;
        name: PgColumn<{
            name: "name";
            tableName: "users";
            dataType: "string";
            columnType: "PgText";
            data: string;
            driverParam: string;
            notNull: true;
            hasDefault: false;
            isPrimaryKey: false;
            isAutoincrement: false;
            hasRuntimeDefault: false;
            enumValues: [...];
            baseColumn: never;
            identity: undefined;
            generated: undefined;
        }, {}, {}>;
        age: PgColumn<...>;
    };
    dialect: "pg";
}>
users
= pgTable("users", {
id: serial().primaryKey(), name: text().notNull(), age: integer() }) const
const User: Type<{
    id: number;
    name: string;
    age: number | null;
}>
User
= createSelectSchema(
const users: PgTableWithColumns<{
    name: "users";
    schema: undefined;
    columns: {
        id: PgColumn<{
            name: "id";
            tableName: "users";
            dataType: "number";
            columnType: "PgSerial";
            data: number;
            driverParam: number;
            notNull: true;
            hasDefault: true;
            isPrimaryKey: true;
            isAutoincrement: false;
            hasRuntimeDefault: false;
            enumValues: undefined;
            baseColumn: never;
            identity: undefined;
            generated: undefined;
        }, {}, {}>;
        name: PgColumn<{
            name: "name";
            tableName: "users";
            dataType: "string";
            columnType: "PgText";
            data: string;
            driverParam: string;
            notNull: true;
            hasDefault: false;
            isPrimaryKey: false;
            isAutoincrement: false;
            hasRuntimeDefault: false;
            enumValues: [...];
            baseColumn: never;
            identity: undefined;
            generated: undefined;
        }, {}, {}>;
        age: PgColumn<...>;
    };
    dialect: "pg";
}>
users
)
// Type<{ id: number; name: string; age: number | null }> const
const NewUser: Type<{
    name: string;
    id?: number;
    age?: number | null;
}>
NewUser
= createInsertSchema(
const users: PgTableWithColumns<{
    name: "users";
    schema: undefined;
    columns: {
        id: PgColumn<{
            name: "id";
            tableName: "users";
            dataType: "number";
            columnType: "PgSerial";
            data: number;
            driverParam: number;
            notNull: true;
            hasDefault: true;
            isPrimaryKey: true;
            isAutoincrement: false;
            hasRuntimeDefault: false;
            enumValues: undefined;
            baseColumn: never;
            identity: undefined;
            generated: undefined;
        }, {}, {}>;
        name: PgColumn<{
            name: "name";
            tableName: "users";
            dataType: "string";
            columnType: "PgText";
            data: string;
            driverParam: string;
            notNull: true;
            hasDefault: false;
            isPrimaryKey: false;
            isAutoincrement: false;
            hasRuntimeDefault: false;
            enumValues: [...];
            baseColumn: never;
            identity: undefined;
            generated: undefined;
        }, {}, {}>;
        age: PgColumn<...>;
    };
    dialect: "pg";
}>
users
)
// Type<{ name: string; id?: number; age?: number | null }>

createUpdateSchema is like createInsertSchema with every column optional. Integer columns also get their range, so age above must be a 32-bit integer.

React Hook Form

@hookform/resolvers includes standardSchemaResolver:

import { standardSchemaResolver } from "@hookform/resolvers/standard-schema"
import { type } from "arktype"
import { useForm } from "react-hook-form"

const 
const User: Type<{
    name: string;
    age: number;
}>
User
= type({
name: type("string > 0").message("Name is required"), age: "number.integer >= 0" }) export const useUserForm = () => useForm({ resolver: standardSchemaResolver(
const User: Type<{
    name: string;
    age: number;
}>
User
) })

Each field's error holds its issue's message: errors.name.message is the message configured above, and errors.age.message is ArkType's own, like must be an integer.

The form's field values are typed from the Type's input, and handleSubmit receives its output. If you pass type arguments to useForm yourself, pass all three: useForm<typeof User.inferIn, unknown, typeof User.infer>.

The same package exports arktypeResolver from @hookform/resolvers/arktype, which behaves the same from version 5. In versions 3 and 4 it throws on invalid values beside ArkType 3. @hookform/resolvers lists arktype@^2 as an optional peer dependency, so npm refuses to install it beside a later major version of ArkType, whichever resolver you import, until you override the peer. pnpm warns, and bun installs it as is.

Hono

@hono/standard-validator validates a request's json, form, query, param, header or cookie:

import { sValidator } from "@hono/standard-validator"
import { type } from "arktype"
import { Hono } from "hono"

const 
const User: Type<{
    name: string;
    age: number;
}>
User
= type({
name: "string", age: "number.integer >= 0" }) const const app: Hono<BlankEnv, BlankSchema, "/">app = new Hono() const app: Hono<BlankEnv, BlankSchema, "/">app.post("/users", sValidator("json",
const User: Type<{
    name: string;
    age: number;
}>
User
), c => {
const
const user: {
    name: string;
    age: number;
}
user
= c.req.valid("json")
return c.json({ message: `${
const user: {
    name: string;
    age: number;
}
user
.name} is ${
const user: {
    name: string;
    age: number;
}
user
.age}` })
})

Invalid requests get a 400 response with the request's data and its issues as JSON, and each issue holds the value it rejected as data. To choose what the response says, return it from a hook:

const app: Hono<BlankEnv, BlankSchema, "/">app.post(
	"/users",
	sValidator("json", 
const User: Type<{
    name: string;
    age: number;
}>
User
, (result, c) => {
if (!result.success) return c.json( result.error.map(({ path, message }) => ({ path, message })), 400 ) }), c => c.json(c.req.valid("json")) )

@hono/arktype-validator has an arktypeValidator written for ArkType 2. Beside ArkType 3, version 2.0.1 answers an invalid header with a 500 where sValidator answers 400, and its required peer dependency on arktype@^2 needs an override to install with npm, so use sValidator until it's updated.

To generate an OpenAPI document from your routes, hono-openapi has a validator that accepts a Type, and a resolver for describing responses with one.

Elysia

Elysia accepts a Type directly for a route's body, query, params, headers, cookie or response:

import { type } from "arktype"
import { Elysia } from "elysia"

const 
const User: Type<{
    name: string;
    age: number;
}>
User
= type({
name: "string", age: "number.integer >= 0" }) const const app: ...app = new Elysia().post("/users", ({ body }) => body, { body:
const User: Type<{
    name: string;
    age: number;
}>
User
})

With @elysiajs/openapi, Elysia reads the Type's JSON Schema from ~standard.jsonSchema automatically.

Fastify

Fastify validates with any function it's given, so two compilers and a type provider make a route's schema take Types:

import { type } from "arktype"
import Fastify, {
	type FastifySchemaCompiler,
	type FastifySerializerCompiler,
	type FastifyTypeProvider
} from "fastify"

interface ArkTypeProvider extends FastifyTypeProvider {
	validator: this["schema"] extends type.Any ? this["schema"]["infer"] : unknown
	serializer: this["schema"] extends type.Any ? this["schema"]["inferIn"]
	:	unknown
}

const const validatorCompiler: FastifySchemaCompiler<type.Any<any, ...>>validatorCompiler: FastifySchemaCompiler<type.Any> =
	({ schema }) =>
	data => {
		const const out: ...out = schema(data)
		return const out: ...out instanceof type.errors ?
				{ error: new Error(const out: ArkErrorsout.summary) }
			:	{ value: const out: ...out }
	}

const const serializerCompiler: FastifySerializerCompiler<type.Any<any, ...>>serializerCompiler: FastifySerializerCompiler<type.Any> =
	({ schema }) =>
	data =>
		JSON.stringify(schema.assert(data))

const const app: ...app = Fastify()
	.setValidatorCompiler(const validatorCompiler: FastifySchemaCompiler<type.Any<any, ...>>validatorCompiler)
	.setSerializerCompiler(const serializerCompiler: FastifySerializerCompiler<type.Any<any, ...>>serializerCompiler)
	.withTypeProvider<ArkTypeProvider>()

const 
const User: Type<{
    name: string;
    age: number;
}>
User
= type({ name: "string", age: "number.integer >= 0" })
const app: ...app.post( "/users", { schema: { body:
const User: Type<{
    name: string;
    age: number;
}>
User
, response: { 201:
const User: Type<{
    name: string;
    age: number;
}>
User
} } },
async (request, reply) => reply.code(201).send(request.body) )

An invalid body, querystring, params or headers gets Fastify's 400, with the errors' summary as its message, like age must be non-negative. A response is validated before it's sent, and one that fails is a 500. Where Fastify's own serializer leaves out keys the schema doesn't list, a Type sends them unless it deletes undeclared keys.

T3 Env

T3 Env accepts a Type for each environment variable:

import { createEnv } from "@t3-oss/env-core"
import { type } from "arktype"

export const const env: ...env = createEnv({
	server: {
		PORT: type("string.integer.parse"),
		DATABASE_URL: type("string.url")
	},
	runtimeEnv: process.env
})

Each variable is validated alone and gets undefined when unset. @t3-oss/env-core lists arktype@^2 as an optional peer dependency, so npm needs a peer override beside ArkType 3.

MCP SDK

The MCP TypeScript SDK accepts a Type as a tool's inputSchema or outputSchema:

import { McpServer } from "@modelcontextprotocol/server"
import { type } from "arktype"

const const server: McpServerserver = new McpServer({ name: "greeter", version: "1.0.0" })

const server: McpServerserver.registerTool(
	"greet",
	{
		description: "Greet someone by name",
		inputSchema: type({
			name: "string",
			"times?": "1 <= number.integer <= 5"
		})
	},
	async ({ name, times = 1 }) => ({
		content: [{ type: "text", text: `Hello, ${name}! `.repeat(times) }]
	})
)

The SDK sends clients the JSON Schema from ~standard.jsonSchema and validates arguments with the Type before your handler runs. A call with times: 9 returns an error result, and the handler doesn't run.

This needs @modelcontextprotocol/server, the SDK's second major version. The first, @modelcontextprotocol/sdk, accepts only Zod schemas.

To serve it over stdio, connect a transport from @modelcontextprotocol/server/stdio:

import { McpServer } from "@modelcontextprotocol/server"
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"

const const server: McpServerserver = new McpServer({ name: "greeter", version: "1.0.0" })
// server.registerTool(...)

await const server: McpServerserver.connect(new StdioServerTransport())

To serve it from a route handler, like a Next.js App Router route, createMcpHandler builds a server for each request, and its fetch answers it:

app/api/mcp/route.ts
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"

const const handler: McpHttpHandlerhandler = createMcpHandler(() => {
	const const server: McpServerserver = new McpServer({ name: "greeter", version: "1.0.0" })
	// server.registerTool(...)
	return const server: McpServerserver
})

const serve = (request: Request) => const handler: McpHttpHandlerhandler.fetch(request)

export { serve as GET, serve as POST, serve as DELETE }

AI SDK

The AI SDK accepts a Type wherever it takes a schema. For structured output:

import { generateText, Output } from "ai"
import { type } from "arktype"

const 
const Ingredient: Type<{
    name: string;
    amount: string;
}>
Ingredient
= type({ name: "string", amount: "string" })
const
const Recipe: Type<{
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    steps: string[];
}>
Recipe
= type({
name: "string", ingredients:
const Ingredient: Type<{
    name: string;
    amount: string;
}>
Ingredient
.array(),
steps: "string[]" }) const {
const output: {
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    steps: string[];
}

The generated output according to the output specification.

output
} = await generateText({
model: "anthropic/claude-sonnet-5.5", output: Output.object({ schema:
const Recipe: Type<{
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    steps: string[];
}>
Recipe
}),
prompt: "Write a recipe for toast." })

For a tool's input:

import { tool } from "ai"
import { type } from "arktype"

const weather = tool({
	description: "Get the weather in a city",
	inputSchema: type({
		city: type("string").describe("the name of a city")
	}),
	execute: async ({ city }) => ({ city, celsius: 21 })
})

The model sees the JSON Schema from ~standard.jsonSchema, and the AI SDK validates its response with the Type. Parts of a Type with no JSON Schema equivalent, like a narrow, aren't described to the model, but its response is still checked against them. Structured output arrives as JSON, so use string.date.iso.parse rather than Date for a date.

.describe() writes a field's description in that JSON Schema, which tells the model what the field means. The same text is what the field's errors say it must be, like city must be the name of a city. On a Type with checks, like "1 <= number.integer <= 7", .describe(text, "self") leaves each check its own error.

OpenAI SDK

The OpenAI SDK has helpers that take a Type in openai/helpers/standard-schema, from version 6.49. For structured output:

import { type } from "arktype"
import OpenAI from "openai"
import { standardResponseFormat } from "openai/helpers/standard-schema"

const 
const Ingredient: Type<{
    name: string;
    amount: string;
}>
Ingredient
= type({ name: "string", amount: "string" })
const
const Recipe: Type<{
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    notes: string | null;
}>
Recipe
= type({
name: "string", ingredients:
const Ingredient: Type<{
    name: string;
    amount: string;
}>
Ingredient
.array(),
notes: "string | null" }) const const openai: ...openai = new OpenAI() const const completion: ...completion = await const openai: ...openai.chat.completions.parse({ model: "gpt-6.1-sol", messages: [{ role: "user", content: "Write a recipe for toast." }], response_format: standardResponseFormat(
const Recipe: Type<{
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    notes: string | null;
}>
Recipe
, "recipe")
}) // typed as Recipe's output, or null const const recipe: ...recipe = const completion: ...completion.choices[0]?.message.parsed

standardTextFormat does the same for responses.parse, and standardFunction and standardResponsesFunction take a Type as a tool's parameters. Each sends the Type's JSON Schema with strict: true and validates what the model returns with the Type, so an invalid response throws an OpenAIError listing its errors, like Standard Schema validation failed: servings: must be at most 12.

Strict mode needs every key required. A Type with an optional key or a default throws when a helper is given it, with a message about .optional(): write the key as required and allow null, like notes above.

Anthropic SDK

The Anthropic SDK has helpers that take a Type in @anthropic-ai/sdk/helpers/beta/standard-schema, from version 0.121. For structured output and for a tool the SDK runs:

import Anthropic from "@anthropic-ai/sdk"
import {
	betaStandardSchemaOutputFormat,
	betaStandardSchemaTool
} from "@anthropic-ai/sdk/helpers/beta/standard-schema"
import { type } from "arktype"

const const client: ...client = new Anthropic()

const 
const Ingredient: Type<{
    name: string;
    amount: string;
}>
Ingredient
= type({ name: "string", amount: "string" })
const
const Recipe: Type<{
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    notes: string | null;
}>
Recipe
= type({
name: "string", ingredients:
const Ingredient: Type<{
    name: string;
    amount: string;
}>
Ingredient
.array(),
notes: "string | null" }) const const message: ...message = await const client: ...client.beta.messages.parse({ model: "claude-opus-5-5", max_tokens: 16000, messages: [{ role: "user", content: "Write a recipe for toast." }], output_config: { format: betaStandardSchemaOutputFormat(
const Recipe: Type<{
    name: string;
    ingredients: {
        name: string;
        amount: string;
    }[];
    notes: string | null;
}>
Recipe
) }
}) // typed as Recipe's output, or null const const recipe: ...recipe = const message: ...message.parsed_output const const search: ...search = betaStandardSchemaTool({ name: "search", description: "Search recipes by keyword", inputSchema: type({ query: type("string > 0").describe("what to search for", "self"), "limit?": "1 <= number.integer <= 50" }), run: async ({ query, limit = 10 }) => `${limit} recipes matching ${query}` }) const const final: ...final = await const client: ...client.beta.messages.toolRunner({ model: "claude-opus-5-5", max_tokens: 16000, messages: [{ role: "user", content: "Find me a toast recipe." }], tools: [const search: ...search] })

Both send the Type's JSON Schema and validate with the Type. A response that fails throws an AnthropicError listing its errors. A tool call that fails isn't run: the runner returns the errors to the model as the tool's result, like query: must be non-empty, so it can call again.

Precompiled validators

A precompiled validator validates through Standard Schema as a Type does, so tRPC, oRPC, Hono's validators, React Hook Form, TanStack Form and Router, Elysia, t3-env and Next.js server actions take one with nothing to set. The build bakes a JSON Schema into each validator it sees a library convert, so the MCP SDK, the AI SDK, the OpenAI and Anthropic SDKs' helpers, Elysia's @elysiajs/openapi, hono-openapi and oRPC's OpenAPIGenerator with @orpc/arktype need nothing set either, as members describes. A library that defines Types itself needs dependencies set:

LibrarySet in ark.json (or package.json's "ark" key)
drizzle-arktype, which creates Types from tables as it runs"precompile": { "dependencies": { "drizzle-arktype": "arktype" } }
t3-env's presets-arktype, which defines static Types"precompile": { "dependencies": { "@t3-oss/env-core": "aot" } }

Without it, a build importing drizzle-arktype or presets-arktype fails, naming the setting. A package that imports arktype itself, like @hookform/resolvers/arktype, has to be bundled with your validators, so a server build with Vite fails until ssr.noExternal names it. Troubleshooting has each message.

A production build keeps ~standard in a validator a library like Hono's sValidator validates with, and leaves out what nothing reads.