claude-code-schema-validation
Guide and workflow for Claude Code Schema Validation & Testing. Use when you need Claude Code Schema Validation & Testing.
What this skill does
# Claude Code Schema Validation & Testing
**Purpose**: Comprehensive guide for validating Claude Code settings.json and agent files using official and community tools.
## ๐ฏ Official JSON Schema Support (RESOLVED - Sept 2025)
As of **September 29, 2025**, Anthropic provides official JSON Schema validation for Claude Code settings.
### Official Schema URL
```
https://json.schemastore.org/claude-code-settings.json
```
**Source**: GitHub Issue #2783 - Closed as completed
## โ
Using Official Schema Validation
### Step 1: Add Schema Reference to settings.json
Add the `$schema` field at the top of your settings.json:
```json
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"env": {
"BASH_MAX_OUTPUT_LENGTH": "5000"
},
"permissions": {
"allow": ["Bash(git:*)"]
},
"hooks": {
"PreToolUse": [
{
"matcher": "*",
"hooks": [...]
}
]
}
}
```
### Step 2: Enable IDE Validation
Once the `$schema` field is added, your IDE will automatically:
- โ
Validate settings structure
- โ
Show errors for invalid fields
- โ
Provide autocomplete for available options
- โ
Display documentation on hover
**Supported IDEs**:
- VS Code
- IntelliJ IDEA
- WebStorm
- Any editor with JSON Schema support
## ๐งช Unit Testing Framework
### Option 1: Official Schema Validation (Recommended)
Use the official schema with standard JSON validation tools:
**Using Python (jsonschema)**:
```python
#!/usr/bin/env python3
"""Test Claude Code settings.json validation"""
import json
import requests
from jsonschema import validate, ValidationError
def test_settings_validation():
"""Validate settings.json against official schema"""
# Fetch official schema
schema_url = "https://json.schemastore.org/claude-code-settings.json"
schema = requests.get(schema_url).json()
# Load settings file
with open('.claude/settings.json', 'r') as f:
settings = json.load(f)
# Validate
try:
validate(instance=settings, schema=schema)
print("โ
settings.json is valid")
return True
except ValidationError as e:
print(f"โ Validation error: {e.message}")
print(f" Path: {' -> '.join(str(p) for p in e.path)}")
return False
if __name__ == "__main__":
success = test_settings_validation()
exit(0 if success else 1)
```
**Using Node.js (ajv)**:
```javascript
#!/usr/bin/env node
const Ajv = require('ajv');
const fs = require('fs');
const https = require('https');
async function testSettingsValidation() {
// Fetch official schema
const schemaUrl = 'https://json.schemastore.org/claude-code-settings.json';
const schema = await new Promise((resolve, reject) => {
https.get(schemaUrl, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', reject);
});
// Load settings
const settings = JSON.parse(fs.readFileSync('.claude/settings.json', 'utf8'));
// Validate
const ajv = new Ajv();
const valid = ajv.validate(schema, settings);
if (valid) {
console.log('โ
settings.json is valid');
return true;
} else {
console.error('โ Validation errors:');
ajv.errors.forEach(err => {
console.error(` - ${err.instancePath}: ${err.message}`);
});
return false;
}
}
testSettingsValidation().then(success => process.exit(success ? 0 : 1));
```
### Option 2: Community Tools
**A. claude-code-settings-schema (npm)**
Generates local schema file for offline validation:
```bash
# Generate schema file
npx claude-code-settings-schema
# Your settings.json will reference local schema
{
"$schema": "./claude-code-settings.schema.json",
...
}
```
**Benefits**:
- Offline validation
- IDE autocomplete and IntelliSense
- Based on official Anthropic documentation
**B. claude-json-validator (Python CLI)**
Standalone validator for settings files:
```bash
# Clone repository
git clone https://github.com/trial123Zel/claude-json-validator
cd claude-json-validator
# Setup
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
# Validate
python claude-json-validator.py ~/.claude/settings.json
python claude-json-validator.py .claude/settings.json --verbose
python claude-json-validator.py settings.json --strict
```
**Exit Codes**:
- `0`: Valid (warnings allowed unless `--strict`)
- `1`: Errors found
## ๐ง Pre-Commit Hook Integration
### Method 1: Using Official Schema (Python)
**File**: `.claude/hooks/validate_settings.py`
```python
#!/usr/bin/env python3
"""Pre-commit hook to validate settings.json"""
import json
import sys
from pathlib import Path
try:
import requests
from jsonschema import validate, ValidationError
except ImportError:
print("โ ๏ธ jsonschema not installed, skipping validation")
print(" Install with: pip install jsonschema requests")
sys.exit(0)
def validate_settings():
"""Validate all settings.json files in the project"""
schema_url = "https://json.schemastore.org/claude-code-settings.json"
# Find settings files
settings_files = [
Path.home() / '.claude' / 'settings.json',
Path('.claude') / 'settings.json',
]
errors = []
for settings_file in settings_files:
if not settings_file.exists():
continue
print(f"๐ Validating {settings_file}...")
try:
# Load schema
schema = requests.get(schema_url, timeout=5).json()
# Load settings
with open(settings_file, 'r') as f:
settings = json.load(f)
# Validate
validate(instance=settings, schema=schema)
print(f" โ
Valid")
except ValidationError as e:
print(f" โ Validation error: {e.message}")
print(f" Path: {' -> '.join(str(p) for p in e.path)}")
errors.append((settings_file, e))
except json.JSONDecodeError as e:
print(f" โ Invalid JSON: {e}")
errors.append((settings_file, e))
except Exception as e:
print(f" โ ๏ธ Error validating: {e}")
if errors:
print(f"\nโ Found {len(errors)} validation error(s)")
return False
print(f"\nโ
All settings files valid")
return True
if __name__ == "__main__":
success = validate_settings()
sys.exit(0 if success else 1)
```
**Register in .claude/settings.json**:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'if [[ \"$CLAUDE_TOOL_INPUT\" == *\"settings.json\"* ]]; then python3 .claude/hooks/validate_settings.py; fi'",
"description": "Validate settings.json before writing"
}
]
}
]
}
}
```
### Method 2: Using /doctor Command
The simplest validation method:
```bash
# Run validation
/doctor
```
**Advantages**:
- Built into Claude Code
- No external dependencies
- Validates settings, agents, hooks
- Fast and reliable
**Pre-commit hook**:
```bash
#!/bin/bash
# .claude/hooks/pre_commit_validation.sh
echo "๐ Running Claude Code validation..."
# Run /doctor (requires claude CLI)
if command -v claude >/dev/null 2>&1; then
claude /doctor --quiet || {
echo "โ /doctor validation failed"
exit 1
}
echo "โ
/doctor validation passed"
else
echo "โ ๏ธ claude CLI not found, skipping /doctor validation"
fi
exit 0
```
## ๐งช Agent Frontmatter Validation
### Validation Script for Agent Files
**File**: `.claude/hooks/validate_agents.py`
```python
#!/usr/bin/env python3
"""Validate Claude Code agent frontmatter"""
import re
import sys
from pathlib import Path
def validate_agent_frontmatter(agent_file):
"""Validate agent file frontmatter"""
with open(agent_file, 'r') as f:
content = f.read()
# Check for frontmatter
if Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts โ single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score โฅ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.