Defines and validates JSON schemas in TypeScript with static type inference and built-in MCP server and client support.
Also known as dswbx/jsonv-ts
- Stars
- 24
- Tools
- —
- Downloads, 30 days
- —
- Latest version
- —
- Last commit
- Sep 28, 2026
- License
- MIT
What is jsonv-ts MCP?
jsonv-ts defines and validates JSON schemas in TypeScript with static type inference and built-in MCP server and client support.
Summary generated from the project's README
About jsonv-ts MCP server
Developers building type-safe APIs can use jsonv-ts to define and validate JSON schemas using a TypeScript-first approach. The library provides a lightweight way to create schemas for strings, numbers, integers, booleans, arrays, and objects while automatically inferring TypeScript types through a Static helper. This ensures that your code remains synchronized with your validation logic without manual type definitions.
This tool is designed for those who require strict adherence to the JSON schema 2020-12 specification. It includes built-in support for Model Context Protocol, allowing you to implement MCP servers and clients directly. For web developers, it integrates with Hono to provide middleware for request validation and automatic OpenAPI generation. Because it is dependency-free and focuses on predictable validation, it serves as a high-performance alternative to heavier libraries that might impact IDE responsiveness.
What you can do with it
- 1Automate TypeScript type generationA developer can automatically derive TypeScript interfaces from their JSON schema definitions to ensure type safety.
- 2Build MCP compliant toolsYou can implement an MCP server and client to facilitate communication between AI models and your local tools.
- 3Validate Hono API requestsIntegrate schema validation into a Hono web server to automatically check incoming request data.
- 4Enforce strict object structuresCreate schemas that reject any properties not explicitly defined in the object specification.
Written from the project's README. Every use case is checked against a quote from it.
How to install jsonv-ts MCP
Formats verified 10 Nov 2026Add to CursorAdd to GooseInstall jsonv-ts MCP in Claude Code
$ claude mcp add jsonv-ts -- npx -y jsonv-tsInstall jsonv-ts MCP in Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"jsonv-ts": {
"command": "npx",
"args": [
"-y",
"jsonv-ts"
]
}
}
}Install jsonv-ts MCP in VS Code
.vscode/mcp.json
{
"servers": {
"jsonv-ts": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"jsonv-ts"
]
}
}
}Install jsonv-ts MCP in VS Code CLI
$ code --add-mcp '{"name":"jsonv-ts","type":"stdio","command":"npx","args":["-y","jsonv-ts"]}'Install jsonv-ts MCP in Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"jsonv-ts": {
"command": "npx",
"args": [
"-y",
"jsonv-ts"
]
}
}
}Install jsonv-ts MCP in Codex
$ codex mcp add jsonv-ts -- npx -y jsonv-tsInstall jsonv-ts MCP in Codex config.toml
~/.codex/config.toml
[mcp_servers.jsonv-ts] command = "npx" args = ["-y", "jsonv-ts"]
Install jsonv-ts MCP in Gemini CLI
$ gemini mcp add -s user jsonv-ts npx -- -y jsonv-tsInstall jsonv-ts MCP in Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"jsonv-ts": {
"command": "npx",
"args": [
"-y",
"jsonv-ts"
]
}
}
}Automated checks
Ran Nov 14, 2026Full report →Passed our automated checks. That is not a security audit: read the code and give the server the narrowest access it needs. How checks work
- Source repository linked and reachabledswbx/jsonv-ts is public and reachablegithub.com/dswbx/jsonv-ts ↗Pass
- Package names this repository as its sourcejsonv-ts names dswbx/jsonv-ts as sourcenpmjs.com/package/jsonv-ts ↗Pass
- Build provenance (Sigstore attestation)Sigstore attestation for jsonv-tsnpmjs.com/package/jsonv-ts/v/0.11.1#provenance ↗Pass
- Open source license (OSI)MITspdx.org/licenses/MIT.html ↗Pass
- Commit or release in the last yearLast commit or release 2026-09-28github.com/dswbx/jsonv-ts ↗Pass
- OpenSSF ScorecardNot checked
- Package name not close to a popular packageNo popular package one edit away from jsonv-tsPass
- No critical advisory in the package or its dependenciesNot checked
- No hidden instructions to the model0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersPass
- Destructive tools are labelledNot checked
- Remote endpoint answers the MCP handshakeNot checked
README
View on GitHubjsonv-ts: JSON Schema Builder and Validator for TypeScript
- Installation
- Example
- Motivation
- Schema Types
- Utilities
- Hono Integration
- MCP
- Validation
- Development
- License
- Acknowledgements
A simple, lightweight and dependency-free TypeScript library for defining and validating JSON schemas with static type inference.
- Type-safe JSON schema definition in TypeScript.
- Static type inference from schemas using the
Statichelper. - Built-in spec-compliant validation for the latest JSON schema draft (2020-12).
- Hono integration for OpenAPI generation and request validation.
- MCP server and client implementation.
- Support for standard JSON schema types, references, and validation keywords.
The schemas composed can be used with any JSON schema validator, it strips all metadata when being JSON stringified.
jsonv-ts allows you to define JSON schemas using a TypeScript API. It provides functions for all standard JSON schema types (object, string, number, array, boolean) as well as common patterns like optional fields, union types (anyOf, oneOf, and allOf), and constants/enums. The Static type helper infers the corresponding TypeScript type directly from your schema definition.
Installation
npm install jsonv-ts
Example
import { s, type Static } from "jsonv-ts";
const schema = s.object({
id: s.number(),
username: s.string({ minLength: 3 }),
email: s.string({ format: "email" }).optional(),
});
// {
// "type": "object",
// "properties": {
// "id": { "type": "number" },
// "username": { "type": "string", "minLength": 3 },
// "email": { "type": "string", "format": "email" }
// },
// "required": ["id", "username"]
// }
// Infer the TypeScript type from the schema
type User = Static<typeof schema>;
// { id: number; username: string; email?: string | undefined }
// Example usage:
const user: User = {
id: 123,
username: "john_doe",
// email is optional
};
// Type checking works as expected:
// const invalidUser: User = { id: "abc", username: "jd" }; // Type error
// Use the integrated validation
const result = schema.validate(user);
// { valid: true, errors: [] }
const result2 = schema.validate({ id: 1 });
// {
// "valid": false,
// "errors": [
// {
// "keywordLocation": "/required",
// "instanceLocation": "/",
// "error": "Expected object with required properties id, username",
// "data": {
// "id": 1
// }
// }
// ]
// }
Motivation
If you validate schemas only within the same code base and need comprehensive functionality, you might be better off choosing another library such as zod, TypeBox, etc.
But if you need controllable and predictable schema validation, this library is for you. I was frustrated about the lack of adherence to the JSON schema specification in other libraries, so I decided to create this library. Furthermore, most of the other libraries may reduce your IDE performance due to the sheer number of features they provide.
JSON Schema is simple, elegant and well-defined, so why not use it directly?
Schema Types
Below are the primary functions for building schemas:
Strings
Defines a string type. Optional schema can include standard JSON schema string constraints like minLength, maxLength, pattern, format, etc.
const schema = s.string({ format: "email" });
// { type: "string", format: "email" }
type Email = Static<typeof schema>; // string
To define an Enum, you can add the enum property to the schema. It'll be inferred correctly.
const schema = s.string({ enum: ["red", "green", "blue"] });
// { type: "string", enum: [ "red", "green", "blue" ] }
type Color = Static<typeof schema>; // "red" | "green" | "blue"
The same applies to Constants:
const schema = s.string({ const: "active" });
// { type: "string", const: "active" }
type Status = Static<typeof schema>; // "active"
Numbers
Defines a number type. Optional schema can include minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf.
const schema = s.number({ minimum: 0 });
// { type: "number", minimum: 0 }
type PositiveNumber = Static<typeof schema>; // number
Just like with Strings, you can use Enums and Constants with Numbers:
const enumSchema = s.number({ enum: [18, 21, 25] });
// { type: "number", enum: [ 18, 21, 25 ] }
type Age = Static<typeof enumSchema>; // 18 | 21 | 25
const constSchema = s.number({ const: 200 });
// { type: "number", const: 200 }
type Status = Static<typeof constSchema>; // 200
Integers
Defines an integer type. This is a shorthand for s.number({ type: "integer", ...props }).
Booleans
Defines a boolean type.
const schema = s.boolean();
// { type: "boolean" }
type Active = Static<typeof schema>; // boolean
Literals
The literal schema type defines a schema that only accepts a specific value. It's useful for defining constants or enums with a single value.
const schema = s.literal(1);
// { const: 1 }
type One = Static<typeof schema>; // 1
It can be used with all primitive types, arrays and objects:
// String literal
const strSchema = s.literal("hello");
type Hello = Static<typeof strSchema>; // "hello"
// Number literal
const numSchema = s.literal(42);
type FortyTwo = Static<typeof numSchema>; // 42
// Boolean literal
const boolSchema = s.literal(true);
type True = Static<typeof boolSchema>; // true
// Null literal
const nullSchema = s.literal(null);
type Null = Static<typeof nullSchema>; // null
// Undefined literal
const undefSchema = s.literal(undefined);
type Undefined = Static<typeof undefSchema>; // undefined
// Object literal
const objSchema = s.literal({ name: "hello" });
type Obj = Static<typeof objSchema>; // { name: "hello" }
// Array literal
const arrSchema = s.literal([1, "2", true]);
type Arr = Static<typeof arrSchema>; // [1, "2", true]
You can also add additional schema properties:
const schema = s.literal(1, { title: "number" });
// { const: 1, title: "number" }
Arrays
Defines an array type where all items must match the items schema.
const schema = s.array(s.string({ minLength: 1 }), { minItems: 1 });
// { type: "array", items: { type: "string", minLength: 1 }, minItems: 1 }
type Tags = Static<typeof schema>; // string[]
Objects
Defines an object type with named properties. By default, all properties defined are required. Use optional() to mark properties as optional.
const schema = s.object({
productId: s.integer(),
name: s.string(),
price: s.number({ minimum: 0 }),
description: s.string().optional(), // Optional property
});
// {
// type: "object",
// properties: {
// productId: { type: "integer" },
// name: { type: "string" },
// price: { type: "number", minimum: 0 },
// description: { type: "string" }
// },
// required: [ "productId", "name", "price" ]
// }
type Product = Static<typeof schema>;
// {
// productId: number;
// name: string;
// price: number;
// description?: string | undefined;
// [key: string]: unknown;
// }
Strict Object
You may also use the s.strictObject() function to create a strict object schema which sets additionalProperties to false.
const schema = s.strictObject({
id: s.integer(),
username: s.string().optional(),
});
// {
// type: "object",
// properties: {
// id: { type: "integer" },
// username: { type: "string" }
// },
// required: ["id"],
// additionalProperties: false,
// }
type StrictProduct = Static<typeof schema>;
// {
// productId: number;
// name: string;
// price: number;
// description?: string | undefined;
// }
//
// note that `[key: string]: unknown` is not added to the type now
// it's equivalent to:
const schema = s.object(
{
id: s.integer(),
username: s.string().optional(),
},
{
additionalProperties: false,
}
);
Partial Object
The partialObject function creates an object schema where all properties are optional. This is useful when you want to make all properties of an object optional without having to call .optional() on each property individually.
const schema = s.partialObject({
name: s.string(),
age: s.number(),
});
// {
// type: "object",
// properties: {
// name: { type: "string" },
// age: { type: "number" }
// }
// }
type User = Static<typeof schema>;
// { name?: string; age?: number; [key: string]: unknown }
You can also combine it with additionalProperties: false to create a strict partial object:
const schema = s.partialObject(
{
name: s.string(),
age: s.number(),
},
{ additionalProperties: false }
);
// {
// type: "object",
// properties: {
// name: { type: "string" },
// age: { type: "number" }
// },
// additionalProperties: false
// }
type User = Static<typeof schema>;
// { name?: string; age?: number }
Record
Or for records, use s.record().
const schema = s.record(s.string());
// {
// type: "object",
// additionalProperties: {
// type: "string"
// }
// }
type User = Static<typeof schema>;
// { [key: string]: string; [key: string]: unknown }
Unions
Combine multiple schemas using union keywords:
anyOf(schemas: TSchema[]): Must match at least one of the provided schemas.oneOf(schemas: TSchema[]): Must match exactly one of the provided schemas.allOf(schemas: TSchema[]): Must match all of the provided schemas.
import { s, type Static } from "jsonv-ts";
const schema = s.anyOf([s.string(), s.number()]);
// { anyOf: [ { type: "string" }, { type: "number" } ] }
type StringOrNumber = Static<typeof schema>; // string | number
Any
The any schema type allows any value to pass validation. It's useful when you need to accept any type of value in your schema.
const schema = s.any(); // {}
type AnyValue = Static<typeof schema>; // any
It can be used in objects to allow any type for a property:
const schema = s.object({
name: s.any().optional(),
});
// {
// type: "object",
// properties: {
// name: {}
// }
// }
type User = Static<typeof schema>;
// { name?: any }
From Schema
In case you need schema functionality such as validation of coercion, but only have raw JSON schema definitions, you may use s.fromSchema():
import { fromSchema } from "jsonv-ts";
const schema = fromSchema({
type: "string",
maxLength: 10,
});
There is no type inference, but it tries to read the schema added and maps it to the corresponding schema function. In this case, s.string() will be used. The benefit of using this function over s.schema() (described below) is that coercion logic is applied.
This function is mainly added to perform the tests against the JSON Schema Test Suite.
References
Use s.ref(schema) when the referenced schema object is available. The referenced schema must have an $id, and Static / StaticCoerced are inferred from that schema:
import { s, type Static } from "jsonv-ts";
const user = s.object({
id: s.string(),
}, { $id: "User" });
const schema = s.object({
owner: s.ref(user),
});
type Resource = Static<typeof schema>;
// { owner: { id: string; [key: string]: unknown }; [key: string]: unknown }
Use s.refId<T>() when only the reference string is available. TypeScript cannot infer the target type from a JSON Pointer string, so provide it explicitly:
const schema = s.object({
owner: s.refId<{ id: string }>("#/$defs/User"),
});
type Resource = Static<typeof schema>;
// { owner: { id: string }; [key: string]: unknown }
Custom Schemas
In case you need to define a custom schema, e.g. without type to be added, you may simply use s.schema():
import { schema } from "jsonv-ts";
const schema = schema({
// any valid JSON schema object
maxLength: 10,
});
It can also be used to define boolean schemas:
const alwaysTrue = schema(true);
const alwaysFalse = schema(false);
Utilities
TypeScript Type Generation
The toTypes utility function allows you to generate TypeScript type definitions from your schemas. This is useful for generating type files, documentation, or when you need to convert schemas to TypeScript interfaces.
import { toTypes, schemaToTypes, s } from "jsonv-ts";
// Generate a type declaration
const userSchema = s.object({
id: s.number(),
name: s.string(),
tags: s.array(s.string()).optional(),
status: s.string({ enum: ["active", "inactive"] }),
});
const typeDeclaration = toTypes(userSchema, "User");
console.log(typeDeclaration);
// type User = {
// id: number,
// name: string,
// tags?: string[]
// status: "active" | "inactive"
// }
// Generate an interface declaration
const interfaceDeclaration = toTypes(userSchema, "User", { type: "interface" });
console.log(interfaceDeclaration);
// interface User {
// id: number,
// name: string,
// tags?: string[]
// status: "active" | "inactive"
// }
You can also use schemaToTypes directly to get just the type definition without the declaration:
const typeDefinition = schemaToTypes(userSchema);
console.log(typeDefinition);
// {
// id: number,
// name: string,
// tags?: string[]
// status: "active" | "inactive"
// }
The function supports various options for customization:
const customType = toTypes(userSchema, "User", {
indent: " ", // Use 4 spaces for indentation
fallback: "any", // Use 'any' instead of 'unknown' for unknown types
type: "interface", // Generate interface instead of type
});
Hono Integration
Validator Middleware
If you're using Hono and want to validate the request targets (query, body, etc.), you can use the validator middleware.
import { Hono } from "hono";
import { validator } from "jsonv-ts/hono";
import { s } from "jsonv-ts";
const app = new Hono().post(
"/json",
validator("json", s.object({ name: s.string() })),
(c) => {
const json = c.req.valid("json");
// ^? { name: string }
return c.json(json);
}
);
It also automatically coerces e.g. query parameters to the corresponding type.
import { Hono } from "hono";
import { validator } from "jsonv-ts/hono";
import { s } from "jsonv-ts";
const app = new Hono().get(
"/query",
validator("query", s.object({ count: s.number() })),
(c) => {
const query = c.req.valid("query");
// ^? { count: number }
return c.json(query);
}
);
OpenAPI generation
Every route that uses the validator middleware will be automatically added to the OpenAPI specification. Additionally, you can use the describeRoute function to add additional information to the route, or add routes that don't use any validations:
import { Hono } from "hono";
import { describeRoute } from "jsonv-ts/hono";
const app = new Hono().get(
"/",
describeRoute({ summary: "Hello, world!" }),
(c) => c.json({ foo: "bar" })
);
To then generate the OpenAPI specification, you can use the openAPISpecs function at a desired path:
import { openAPISpecs } from "jsonv-ts/hono";
const app = /* ... your hono app */;
app.get("/openapi.json", openAPISpecs(app, { info: { title: "My API" } }));
You may then use Swagger UI to view the API documentation:
import { swaggerUI } from "@hono/swagger-ui";
const app = /* ... your hono app */;
app.get("/swagger", swaggerUI({ url: "/openapi.json" }));
MCP
This package also includes a Web-spec compliant MCP server and client implementation. Not all features are supported yet, see STATUS.md for the current status.
Here is a simple MCP server example:
import { McpServer } from "jsonv-ts/mcp";
import { s } from "jsonv-ts";
const server = new McpServer({
name: "demo-server",
version: "1.0.0",
});
server.tool(
"add",
{
name: "add",
description: "Add two numbers",
inputSchema: s.object({
a: s.number(),
b: s.number(),
}),
},
({ a, b }, c) => c.text(String(a + b))
);
server.resource("greeting", "greeting://{name}", async (c, { name }) => {
return c.text(`Hello, ${name}!`, {
title: "Greeting Resource",
description: "Dynamic greeting resource",
});
});
// send a message to the server
const response = await server.handle({
jsonrpc: "2.0",
method: "resources/read",
params: {
uri: "greeting://John",
},
});
console.log(response);
// {
// jsonrpc: "2.0",
// result: {
// contents: [
// {
// name: "greeting",
// title: "Greeting Resource",
// description: "Dynamic greeting resource",
// mimeType: "text/plain",
// uri: "greeting://John",
// text: "Hello, John!",
// }
// ],
// },
// }
Hono MCP Middleware
You can use the MCP server with any Web-spec compliant web framework. If you choose to use it with Hono, there is a built-in middleware that can be used to handle MCP requests.
import { Hono } from "hono";
import { mcp } from "jsonv-ts/mcp/hono";
// use the `server` from the example above
const app = new Hono().use(mcp({ server }));
Alternatively, you can use the middleware to specify MCP server options:
import { Hono } from "hono";
import { mcp, Tool, Resource } from "jsonv-ts/mcp";
const add = new Tool(
"add",
{
inputSchema: s.object({ a: s.number(), b: s.number() }),
},
({ a, b }, c) => c.text(String(a + b))
);
const greeting = new Resource("greeting", "greeting://{name}", (c, { name }) =>
c.text(`Hello, ${name}!`)
);
const app = new Hono().use(
mcp({
// optionally specify the server info
serverInfo: { name: "my-server", version: "1.0.0" },
// register tools and resources
tools: [add],
resources: [greeting],
// optionally enable sessions
sessionsEnabled: true,
// optionally specify the path to the MCP endpoint
endpoint: {
path: "/mcp",
},
})
);
Hono Routes as MCP Tools
You can expose selected Hono routes as MCP tools by adding the mcpTool middleware to each route. Input schemas come from the route's validator middleware. Use withMcp to create the MCP server and attach its endpoint to the app:
import { Hono } from "hono";
import { s } from "jsonv-ts";
import { validator } from "jsonv-ts/hono";
import { mcpTool, withMcp } from "jsonv-ts/mcp";
const app = new Hono().get(
"/lookup",
mcpTool("lookup"),
validator("query", s.object({ name: s.string() })),
(c) => c.json({ greeting: `Hello, ${c.req.valid("query").name}!` })
);
const appWithMcp = withMcp(app, {
endpoint: { path: "/mcp" },
});
Only routes marked with mcpTool are exposed. When an MCP client calls lookup, the server validates its arguments using the route schema and invokes the Hono route handler. The /mcp path keeps the MCP endpoint separate from the app's regular routes.
To override the schema inferred from a route's validators, pass target schemas in the mcpTool config. For example, this sets the MCP tool's query input schema explicitly; keep it aligned with the route's own validation:
mcpTool("lookup", {
inputSchema: {
query: s.object({ name: s.string() }),
},
});
MCP Client
You can use the MCP client to interact with MCP servers.
import { McpClient } from "jsonv-ts/mcp";
const client = new McpClient({ url: "http://localhost/sse" });
// list resources
const resources = await client.listResources();
// read a resource
const resource = await client.readResource({
uri: "file:///example.txt",
});
// call a tool
const result = await client.callTool({
name: "add",
arguments: { a: 1, b: 2 },
});
Validation
The schemas created with jsonv-ts are standard JSON Schema objects and can be used with any compliant validator. The library ensures that when the schema object is converted to JSON (e.g., using JSON.stringify), only standard JSON Schema properties are included, stripping any internal metadata. For the examples, this is going to be the base schema object.
import { s } from "jsonv-ts";
const schema = s.object({
id: s.integer({ minimum: 1 }),
username: s.string({ minLength: 3 }),
email: s.string({ format: "email" }).optional(),
});
// { id: number, username: string, email?: string }
Integrated Validator
The library includes an integrated validator that can be used to validate instances against the schema.
const result = schema.validate({ id: 1, username: "valid_user" });
// { valid: true, errors: [] }
Validation Status
- Total tests: 2098
- Passed: 2098 (100.00%)
- Skipped: 0 (0.00%)
- Failed: 0 (0.00%)
- Optional failed: 0 (0.00%)
Advanced validation features supported in the tested draft 2020-12 suite:
$ref,$defs,$id,$anchor,$dynamicRef, and$dynamicAnchor- Local, recursive, dynamic, and registered remote references
unevaluatedItemsandunevaluatedPropertiesdependencies,dependentRequired, anddependentSchemas- Vocabulary gating and draft-aware keyword handling
- Built-in and custom formats, including optional IDN, IRI, and RFC3339 cases covered by the suite
Content keywords such as contentMediaType, contentSchema, and contentEncoding are JSON Schema annotations. jsonv-ts preserves them in schemas, but does not decode or validate encoded content.
Using Standard Schema
The integrated validator of jsonv-ts supports Standard Schema. To use it, refer to the list of tools and frameworks that accept spec-compliant schemas.
jsonv-ts MCP questions
How do I add jsonv-ts MCP to Claude Code?
Run claude mcp add jsonv-ts -- npx -y jsonv-ts in your terminal. Add --scope user to make it available in every project.
How do I add jsonv-ts MCP to Cursor?
Open ~/.cursor/mcp.json and add the server under mcpServers, using the Cursor config shown in the install section above.
What makes jsonv-ts different from Zod or TypeBox?
It focuses on strict adherence to the JSON schema specification and is designed to be lightweight and predictable without impacting IDE performance.
Can I infer TypeScript types from my schemas?
Yes, you can use the Static helper to infer the corresponding TypeScript type directly from your schema definition.
Does it support OpenAPI generation?
Yes, it includes Hono integration for OpenAPI generation and request validation.