PHPackages                             code-wheel/mcp-schema-builder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. code-wheel/mcp-schema-builder

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

code-wheel/mcp-schema-builder
=============================

JSON Schema builder and validator for MCP tool definitions

v1.1.3(3mo ago)1525↓68%MITPHPPHP &gt;=8.1CI passing

Since Jan 9Pushed 3mo agoCompare

[ Source](https://github.com/code-wheel/mcp-schema-builder-php)[ Packagist](https://packagist.org/packages/code-wheel/mcp-schema-builder)[ RSS](/packages/code-wheel-mcp-schema-builder/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (6)Used By (0)

MCP Schema Builder
==================

[](#mcp-schema-builder)

[![CI](https://github.com/code-wheel/mcp-schema-builder/actions/workflows/ci.yml/badge.svg)](https://github.com/code-wheel/mcp-schema-builder/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/4e3a80e3c703f96d58a8c3bd66d0cbd12e4f9eb5ed6026aa1c7d7f7a7c4f65e7/68747470733a2f2f636f6465636f762e696f2f67682f636f64652d776865656c2f6d63702d736368656d612d6275696c6465722f67726170682f62616467652e737667)](https://codecov.io/gh/code-wheel/mcp-schema-builder)[![Latest Stable Version](https://camo.githubusercontent.com/4e5afad93d88d991531fbf8ad1415028e644ec0bff7b818bbee6c8b7eb88268d/68747470733a2f2f706f7365722e707567782e6f72672f636f64652d776865656c2f6d63702d736368656d612d6275696c6465722f76)](https://packagist.org/packages/code-wheel/mcp-schema-builder)[![License](https://camo.githubusercontent.com/4e0f3c534e141d32e7aecd7bdb7393d1e96b2547240e0a2498d44d64f08d7d28/68747470733a2f2f706f7365722e707567782e6f72672f636f64652d776865656c2f6d63702d736368656d612d6275696c6465722f6c6963656e7365)](https://packagist.org/packages/code-wheel/mcp-schema-builder)

A fluent JSON Schema builder with validation for MCP (Model Context Protocol) tool definitions. Build type-safe schemas, validate LLM-generated inputs, and use pre-built patterns for common MCP tools.

Installation
------------

[](#installation)

```
composer require code-wheel/mcp-schema-builder
```

Quick Start
-----------

[](#quick-start)

### Building Schemas

[](#building-schemas)

```
use CodeWheel\McpSchemaBuilder\SchemaBuilder;

$schema = SchemaBuilder::object()
    ->property('name', SchemaBuilder::string()->minLength(1)->required())
    ->property('email', SchemaBuilder::string()->format('email')->required())
    ->property('age', SchemaBuilder::integer()->minimum(0)->maximum(150))
    ->property('role', SchemaBuilder::string()->enum(['admin', 'user', 'guest'])->default('user'))
    ->build();
```

### Validating Input

[](#validating-input)

```
use CodeWheel\McpSchemaBuilder\SchemaValidator;

$validator = new SchemaValidator();
$result = $validator->validate($input, $schema);

if (!$result->isValid()) {
    foreach ($result->getErrors() as $error) {
        echo "{$error->path}: {$error->message}\n";
        // "email: Invalid email format"
        // "age: Value must be >= 0"
    }

    // Or convert to ErrorBag for tool responses
    return $result->toErrorBag()->toToolResult();
}
```

### MCP Presets

[](#mcp-presets)

```
use CodeWheel\McpSchemaBuilder\McpSchema;

// Common patterns for MCP tools
$schema = SchemaBuilder::object()
    ->property('node_id', McpSchema::entityId('node'))       // Entity ID with description
    ->property('bundle', McpSchema::machineName())           // Machine name pattern
    ->property('query', McpSchema::searchQuery(2))           // Search with min length
    ->merge(McpSchema::pagination(50, 100))                  // limit + offset
    ->merge(McpSchema::sorting(['created', 'title']))        // sort_by + sort_order
    ->build();

// Complete tool schemas
$listSchema = McpSchema::listToolSchema(
    filterFields: ['status', 'author'],
    sortFields: ['created', 'updated', 'title']
);

$getSchema = McpSchema::getToolSchema('node_id', 'node');

$createSchema = McpSchema::createToolSchema(
    requiredFields: ['title' => SchemaBuilder::string(), 'body' => SchemaBuilder::string()],
    optionalFields: ['status' => SchemaBuilder::string()->enum(['draft', 'published'])]
);

$deleteSchema = McpSchema::deleteToolSchema('node_id', includeForce: true);
```

### Schema Composition

[](#schema-composition)

```
// Reusable schema fragments
$timestamps = SchemaBuilder::object()
    ->property('created', SchemaBuilder::string()->format('date-time'))
    ->property('updated', SchemaBuilder::string()->format('date-time'));

$author = SchemaBuilder::object()
    ->property('author_id', SchemaBuilder::string()->required())
    ->property('author_name', SchemaBuilder::string());

// Compose into larger schema
$contentSchema = SchemaBuilder::object()
    ->property('id', SchemaBuilder::string()->required())
    ->property('title', SchemaBuilder::string()->required())
    ->merge($timestamps)
    ->merge($author)
    ->build();

// Extend without modifying original
$extendedSchema = $timestamps->extend()
    ->property('deleted', SchemaBuilder::string()->format('date-time'))
    ->build();
```

Schema Builder API
------------------

[](#schema-builder-api)

### String

[](#string)

```
SchemaBuilder::string()
    ->description('Field description')
    ->minLength(1)
    ->maxLength(255)
    ->pattern('^[a-z]+$')
    ->format('email')  // email, uri, uuid, date, date-time
    ->enum(['a', 'b', 'c'])
    ->default('a')
    ->nullable()
    ->required();
```

### Integer / Number

[](#integer--number)

```
SchemaBuilder::integer()
    ->minimum(0)
    ->maximum(100)
    ->exclusiveMinimum(0)
    ->exclusiveMaximum(100);

SchemaBuilder::number()
    ->minimum(0.0)
    ->maximum(1.0);
```

### Boolean

[](#boolean)

```
SchemaBuilder::boolean()
    ->default(false);
```

### Array

[](#array)

```
SchemaBuilder::array(SchemaBuilder::string())
    ->minItems(1)
    ->maxItems(10)
    ->uniqueItems();
```

### Object

[](#object)

```
SchemaBuilder::object()
    ->property('name', SchemaBuilder::string()->required())
    ->property('age', SchemaBuilder::integer())
    ->additionalProperties(false)
    ->minProperties(1)
    ->maxProperties(10);
```

MCP Presets Reference
---------------------

[](#mcp-presets-reference)

### Identifiers

[](#identifiers)

MethodDescription`McpSchema::entityId($type)`Entity ID (numeric or UUID)`McpSchema::machineName($desc)`Machine name pattern `[a-z][a-z0-9_]*``McpSchema::uuid()`UUID format`McpSchema::slug()`URL-safe slug### Pagination &amp; Filtering

[](#pagination--filtering)

MethodDescription`McpSchema::pagination($default, $max)`limit + offset properties`McpSchema::cursorPagination($default)`limit + cursor properties`McpSchema::sorting($fields)`sort\_by + sort\_order properties`McpSchema::searchQuery($minLen)`Search query string`McpSchema::statusFilter($statuses)`Status enum filter`McpSchema::dateRange()`from + to date properties### Content

[](#content)

MethodDescription`McpSchema::title($maxLen)`Title string with length limits`McpSchema::body($allowHtml)`Body/content field`McpSchema::tags()`Array of tag strings`McpSchema::metadata()`Key-value object### Complete Tool Schemas

[](#complete-tool-schemas)

MethodDescription`McpSchema::listToolSchema($filters, $sorts)`List entities with pagination`McpSchema::getToolSchema($idField, $type)`Get single entity by ID`McpSchema::createToolSchema($required, $optional)`Create entity`McpSchema::updateToolSchema($idField, $fields)`Update entity`McpSchema::deleteToolSchema($idField, $force)`Delete entity`McpSchema::confirmation()`Destructive operation confirmationValidation
----------

[](#validation)

The `SchemaValidator` validates:

- **Type checking**: string, integer, number, boolean, array, object
- **String constraints**: minLength, maxLength, pattern, format
- **Number constraints**: minimum, maximum, exclusiveMinimum, exclusiveMaximum
- **Array constraints**: minItems, maxItems, uniqueItems, items schema
- **Object constraints**: required properties, additionalProperties
- **Enum validation**: Value must be in allowed list
- **Format validation**: email, uri, uuid, date, date-time, ipv4, ipv6

```
$validator = new SchemaValidator();
$result = $validator->validate($input, $schema);

$result->isValid();           // bool
$result->getErrors();         // ValidationError[]
$result->toErrorBag();        // ErrorBag (from mcp-error-codes)
```

Integration with mcp-error-codes
--------------------------------

[](#integration-with-mcp-error-codes)

```
use CodeWheel\McpSchemaBuilder\SchemaValidator;
use CodeWheel\McpErrorCodes\ErrorBag;

$validator = new SchemaValidator();
$result = $validator->validate($input, $schema);

if (!$result->isValid()) {
    // Convert validation errors to ErrorBag
    $errorBag = $result->toErrorBag();

    // Return as MCP tool result
    return $errorBag->toToolResult();
}
```

Integration with mcp-tool-gateway
---------------------------------

[](#integration-with-mcp-tool-gateway)

```
use CodeWheel\McpToolGateway\Middleware\ValidatingMiddleware;
use CodeWheel\McpToolGateway\Middleware\MiddlewarePipeline;
use CodeWheel\McpSchemaBuilder\SchemaValidator;

// Automatic validation before tool execution
$validator = new SchemaValidator();
$middleware = new ValidatingMiddleware($provider, $validator);

$pipeline = new MiddlewarePipeline($provider);
$pipeline->add($middleware);

// Invalid inputs are rejected before reaching tools
$result = $pipeline->execute('create_user', $input);
```

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) file.

###  Health Score

41

—

FairBetter than 88% of packages

Maintenance83

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

5

Last Release

119d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4cb6eebdce9234e8ad086e2786111257d1f959a3f7323c9fdae46c600082f646?d=identicon)[mowens3](/maintainers/mowens3)

---

Top Contributors

[![mowens3](https://avatars.githubusercontent.com/u/1635473?v=4)](https://github.com/mowens3 "mowens3 (17 commits)")

---

Tags

schemavalidationjson-schemamcptoolsModel Context Protocol

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/code-wheel-mcp-schema-builder/health.svg)

```
[![Health](https://phpackages.com/badges/code-wheel-mcp-schema-builder/health.svg)](https://phpackages.com/packages/code-wheel-mcp-schema-builder)
```

###  Alternatives

[opis/json-schema

Json Schema Validator for PHP

64236.9M185](/packages/opis-json-schema)[geraintluff/jsv4

A (coercive) JSON Schema v4 Validator for PHP

115455.2k3](/packages/geraintluff-jsv4)[romaricdrigon/metayaml

Using \[Yaml|Xml|json\] schemas files to validate \[Yaml|Xml|json\]

103306.5k8](/packages/romaricdrigon-metayaml)[freshwork/chilean-bundle

A PHP composer package with Chilean validations, common variables, etc. (RUT, IVA, ETC). Ready for Laravel 5. Grande chile ctm :)

97195.6k3](/packages/freshwork-chilean-bundle)[evaisse/php-json-schema-generator

A JSON Schema Generator.

20298.5k1](/packages/evaisse-php-json-schema-generator)[romegasoftware/laravel-schema-generator

Generate TypeScript Zod validation schemas from Laravel validation rules

288.2k](/packages/romegasoftware-laravel-schema-generator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
