npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

structured-coding-agent-output

v1.0.0

Published

Structured output wrapper for Claude Code with JSON Schema validation

Readme

structured-coding-agent-output

Claude Code の出力を JSON Schema で検証し、構造化されたデータを取得するためのラッパーツールです。

特徴

  • Zod スキーマ定義: TypeScript で型安全なスキーマを定義
  • JSON Schema 自動生成: Zod から JSON Schema を自動生成
  • 出力検証: Ajv による厳密な JSON Schema 検証
  • リトライ機能: 検証失敗時の自動リトライ
  • CLI サポート: コマンドラインから直接実行可能

インストール

npm レジストリから(公開後)

npm install structured-coding-agent-output

GitHub から直接

# HTTPS
npm install git+https://github.com/YOUR_USERNAME/structured-coding-agent-output.git

# SSH
npm install git+ssh://[email protected]:YOUR_USERNAME/structured-coding-agent-output.git

# 特定のブランチやタグを指定
npm install git+https://github.com/YOUR_USERNAME/structured-coding-agent-output.git#main
npm install git+https://github.com/YOUR_USERNAME/structured-coding-agent-output.git#v1.0.0

ローカルパスから

# 相対パス
npm install ../structured-coding-agent-output

# 絶対パス
npm install /path/to/structured-coding-agent-output

# npm link を使用(開発時)
cd /path/to/structured-coding-agent-output
npm link

cd /path/to/your-project
npm link structured-coding-agent-output

ローカル開発用セットアップ

git clone https://github.com/YOUR_USERNAME/structured-coding-agent-output.git
cd structured-coding-agent-output
npm install

ビルド

# TypeScript をコンパイル
npm run build

# Zod スキーマから JSON Schema を生成
npm run generate:schemas

使い方

CLI から使用

# ビルトインスキーマを使用
npx structured-claude -s opinion-review -p "このコードをレビューしてください: ..."

# カスタム JSON Schema ファイルを使用
npx structured-claude -f ./my-schema.json -p "データを分析してください"

# リトライ回数とタイムアウトを指定
npx structured-claude -s opinion-review -p "レビュー" -r 5 -t 60000

# 利用可能なスキーマ一覧を表示
npx structured-claude --list-schemas

CLI オプション

| オプション | 短縮形 | 説明 | デフォルト | |-----------|--------|------|-----------| | --schema <name> | -s | 使用するビルトインスキーマ名 | - | | --schema-file <path> | -f | JSON Schema ファイルのパス | - | | --prompt <text> | -p | Claude Code に送信するプロンプト | (必須) | | --retries <number> | -r | 最大リトライ回数 | 3 | | --timeout <ms> | -t | タイムアウト (ミリ秒) | 300000 | | --list-schemas | - | 利用可能なスキーマ一覧を表示 | - |

プログラムから使用

import { createExecutor, createValidator } from 'structured-coding-agent-output';

// Executor を作成
const executor = createExecutor({
  maxRetries: 3,
  timeout: 300000,
});

// スキーマ名を指定して実行
const result = await executor.execute('このコードをレビューしてください', {
  schema: 'opinion-review',
});

if (result.success) {
  console.log('検証済みデータ:', result.data);
} else {
  console.error('エラー:', result.error);
}

// カスタムスキーマファイルを使用
const result2 = await executor.execute('データを分析してください', {
  schemaFile: './custom-schema.json',
});

Validator を直接使用

import { createValidator } from 'structured-coding-agent-output';

const validator = createValidator('./schemas');

// スキーマ名で検証
const result = validator.validate('opinion-review', {
  verdict: 'approve',
  confidence: 85,
  summary: 'コードは良好です',
});

if (result.valid) {
  console.log('有効なデータ:', result.data);
} else {
  console.log('検証エラー:', validator.formatErrors(result.errors));
}

// ファイルパスで検証
const result2 = validator.validateWithSchemaFile('./my-schema.json', data);

スキーマ定義

ビルトインスキーマ: opinion-review

コードレビューの結果を構造化するためのスキーマです。

interface OpinionReview {
  verdict: 'approve' | 'reject' | 'needs_revision';  // 判定結果
  confidence: number;      // 確信度 (0-100)
  summary: string;         // 概要
  strengths?: string[];    // 強み (オプション)
  weaknesses?: string[];   // 弱み (オプション)
  suggestions?: string[];  // 提案 (オプション)
  reasoning?: string;      // 理由 (オプション)
}

カスタムスキーマの追加

  1. src/schemas/ に Zod スキーマを定義:
// src/schemas/my-schema.ts
import { z } from 'zod';

export const MySchema = z.object({
  title: z.string(),
  score: z.number().min(0).max(100),
  tags: z.array(z.string()).optional(),
});

export type MyData = z.infer<typeof MySchema>;
  1. src/schemas/index.ts にエクスポートを追加:
import { MySchema } from './my-schema';

export const schemas = {
  'opinion-review': OpinionReviewSchema,
  'my-schema': MySchema,  // 追加
} as const;
  1. JSON Schema を生成:
npm run generate:schemas

出力フォーマット

Claude Code からの出力は以下の形式で構造化データを含める必要があります:

```structured_output
{
  "verdict": "approve",
  "confidence": 85,
  "summary": "コードは良好です"
}

または JSON コードブロック:

```markdown
```json
{
  "verdict": "approve",
  "confidence": 85,
  "summary": "コードは良好です"
}

生の JSON も認識されます:

```json
{"verdict": "approve", "confidence": 85, "summary": "コードは良好です"}

API リファレンス

ClaudeExecutor

class ClaudeExecutor {
  constructor(options?: ExecutorOptions);
  execute(prompt: string, options?: ExecutorOptions): Promise<ExecutionResult>;
  extractStructuredOutput(output: string): unknown | null;
}

interface ExecutorOptions {
  schema?: string;           // スキーマ名
  schemaFile?: string;       // スキーマファイルパス
  maxRetries?: number;       // 最大リトライ回数
  timeout?: number;          // タイムアウト (ms)
  validator?: SchemaValidator;
}

interface ExecutionResult {
  success: boolean;
  data?: unknown;            // 検証済みデータ
  rawOutput?: string;        // Claude の生出力
  error?: string;            // エラーメッセージ
  attempts: number;          // 試行回数
}

SchemaValidator

class SchemaValidator {
  constructor(schemasDir?: string);
  loadSchema(schemaName: string): ValidateFunction;
  loadSchemaFromFile(schemaFilePath: string): ValidateFunction;
  validate(schemaName: string, data: unknown): ValidationResult;
  validateWithSchemaFile(schemaFilePath: string, data: unknown): ValidationResult;
  formatErrors(errors: ErrorObject[]): string;
}

interface ValidationResult {
  valid: boolean;
  data?: unknown;
  errors?: ErrorObject[];
}

ファクトリ関数

// Executor を作成
function createExecutor(options?: ExecutorOptions): ClaudeExecutor;

// Validator を作成
function createValidator(schemasDir?: string): SchemaValidator;

ディレクトリ構成

structured-coding-agent-output/
├── src/
│   ├── schemas/
│   │   ├── index.ts           # スキーマエクスポート
│   │   └── opinion-review.ts  # サンプルスキーマ
│   ├── wrapper/
│   │   ├── index.ts           # wrapper エクスポート
│   │   ├── executor.ts        # Claude Code 実行
│   │   └── validator.ts       # Ajv 検証
│   └── index.ts               # CLI エントリーポイント
├── scripts/
│   └── generate-schemas.ts    # Zod → JSON Schema 生成
├── schemas/                   # 生成された JSON Schema
│   └── opinion-review.json
├── __tests__/                 # 単体テスト
├── package.json
├── tsconfig.json
└── jest.config.js

テスト

# テスト実行
npm test

# カバレッジ付きテスト
npm run test:coverage

依存関係

  • zod: スキーマ定義
  • zod-to-json-schema: Zod → JSON Schema 変換
  • ajv: JSON Schema 検証
  • commander: CLI パーサー

ライセンス

MIT