mcpField
O
openapi-sync-mcp

openapi-sync-mcp

ローカル
github.com/akintomiwa-fisayo開発ツール16 週間前に更新

openapi-sync-mcp について

openapi-sync-mcp は、OpenAPI 仕様の確認と同期を行う型安全な MCP サーバーです。開発者やエージェントが仕様を検証し、エンドポイントを調べ、生成済みの型を参照できます。

主な機能

  1. 01設定と仕様の検証
  2. 02エンドポイントの閲覧と絞り込み
  3. 03エンドポイントスキーマの確認
  4. 04生成済み TypeScript 型の参照
  5. 05診断チェックの実行

活用シーン

  1. 01コード生成前の API 仕様確認
  2. 02パスによるエンドポイント検索
  3. 03操作スキーマの確認
  4. 04エージェントによる生成型の参照

MCP 対応

OpenAPI Sync の確認、検証、同期機能を MCP クライアントに提供し、エンドポイントや型の検索にも対応します。

設定

ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。

mcp.json · 共通設定
{
"mcpServers": {
"akintomiwa-fisayo-openapi-sync": {
"command": "npx",
"args": [
"-y",
"openapi-sync-mcp"
]
}
}
}
起動コマンドnpx -y openapi-sync-mcp

ローカルサーバーにはマシン上の実行環境(Node.js 18 以上など)が必要です。設定ファイルの場所はクライアントごとに異なります。

パッケージ
npmopenapi-sync-mcp6.4.2

ツール

10

掲載時のツール一覧 · 3 週間前に更新

パラメーター型必須説明
apistringいいえAPI 仕様のソース(<name>=<url>、直接 URL、または絞り込み用の名前)。
apiUrlstringいいえOpenAPI 仕様の直接 URL(JSON または YAML)。
authInenumいいえAPI キーの場所:header または query(authType: apiKey と併用)。header | query
folderstringいいえ生成ファイルの出力ディレクトリ(デフォルト:'' プロジェクトルート)。
presetenumいいえ自動的に適用する名前付きプリセット。react-query-zod | react-query-yup | swr-zod | swr-yup | axios-zod | axios-joi | fetch-zod | rtk-query-zod | next-fetch | python-basic
serverstringいいえデフォルトのサーバーインデックス、またはベース URL の上書き値。
apiFilestringいいえOpenAPI 仕様のローカルファイルへの直接パス。
apiNamestringいいえAPI の名前(デフォルト:'api')。
authNamestringいいえAPI キーの header または query パラメーター名(デフォルト:X-API-Key)。
authTypeenumいいえ仕様の認証タイプ(bearer、basic、apiKey、custom)。bearer | basic | apiKey | custom
languageenumいいえ対象のプログラミング言語。typescript | python
authTokenstringいいえ認証用の Bearer トークンまたはパスワード値/環境変数参照。
authValuestringいいえAPI キーのシークレット値。
authHeaderstringいいえカスタム header('Key: Value' 形式。authType: custom と併用)。
configJsonstringいいえopenapi-sync 設定を定義する生の JSON 文字列。
authPasswordstringいいえbasic 認証用のパスワード。
authUsernamestringいいえbasic 認証用のユーザー名。
outputFolderstringいいえフォルダーの別名です。

詳細

NPM Version License Tests

OpenAPI Sync

OpenAPI Syncは、OpenAPI(旧称 Swagger)仕様を使用して、API ドキュメントとコードベースの同期を自動化する強力な開発者向けツールです。OpenAPI スキーマから TypeScript 型、完全に型付けされた API クライアント(Fetch、Next.js Fetch、Axios、React Query、SWR、RTK Query)、エンドポイント定義、実行時検証スキーマ(Zod、Yup、Joi)、包括的なドキュメントを生成し、API 仕様からクライアント実装、実行時検証まで型安全性を確保します。

📘 ドキュメント全文はこちら

主な機能

  • ⚡ 設定不要のプリセット - すぐにセットアップできる、事前設定済みのフレームワークプリセットを10種類用意(React Query、SWR、Axios、Fetch、RTK Query、Next.js、Python)
  • 🔄 リアルタイム API 同期 - 設定可能な間隔で、リモート URL から OpenAPI 仕様を自動的に同期します
  • 📝 型の自動生成 - ネストを完全にサポートした、すべてのエンドポイント用の TypeScript インターフェースを生成します
  • 🔐 実行時検証 - 制約をすべて保持したまま、OpenAPI 仕様から Zod、Yup、Joi スキーマを生成します
  • 🎯 対話型セットアップウィザード - タグに基づくフォルダー分割が自動で有効になる、簡素化された設定
  • 🛡️ エンタープライズ対応 - エラー処理、検証、状態の永続化、カスタムコードの保持
  • 📦 フォルダー分割 - タグまたはカスタムロジックでコードを整理し、インポートしやすい集約ファイルを生成します
  • 📚 充実したドキュメント - cURL の例とインラインの使用ガイドを含む JSDoc コメント
  • 🤖 エージェント対応エンドポイント - 仕様を再読み込みせずに、ページネーションやパスフィルタリングを使ったエンドポイントの閲覧、詳細なエンドポイント情報の確認、生成された型の参照ができます
  • 🩺 診断ドクター - 設定の有効性、仕様へのアクセス、ピア依存関係、キャッシュ、フォルダーへの書き込み権限を診断します
  • 🧹 古いファイルの削除 - マニフェストに基づいて古いコードを検出・クリーンアップします。孤立したコードを防ぐドライランにも対応しています
  • 🔄 カスタムコードの挿入 - 再生成の際も、保護されたセクション内のカスタムコードを保持します

すべての機能を見る →

インストール

npm install openapi-sync
# or
npm install -g openapi-sync
# or use directly
npx openapi-sync

⚠️ macOS Big Sur をお使いの方: esbuild のエラー(Symbol not found: _SecTrustCopyCertificateChain)が発生する場合は、先に [email protected] をインストールしてください。詳しくはトラブルシューティングをご覧ください。


🤖 AI エージェントでの使用

すべての CLI コマンドとプログラム API はエージェントに安全に利用できます。対話型プロンプトはなく、処理をブロックしません。機械可読な出力には --json を、ログを抑制するには --silent を使用してください。

エージェント向けリファレンス全文: llms.txt — LLM、Copilot、MCP ツール向けの構造化されたディスカバリーファイルです。

エージェント向けクイックスタート(プロンプトなし)
# 1. Create config (all settings as flags — no stdin required)
npx openapi-sync init --no-interactive \
  --api-name petstore \
  --api-url https://petstore3.swagger.io/api/v3/openapi.json \
  --output-folder ./src/api \
  --client-type react-query \
  --validation-library zod \
  --config-format typescript \
  --json

# Or for protected specs, configure auth directly on init:
npx openapi-sync init --no-interactive \
  --api-name backend \
  --api-url https://api.example.com/openapi.json \
  --auth-type bearer \
  --auth-token '${env.SPEC_TOKEN}' \
  --preset react-query-zod \
  --json

# 2. Validate config + specs before writing any files
npx openapi-sync validate --json

# 3. Sync — generate types, endpoints, and schemas
npx openapi-sync --json

# 4. Generate a typed API client
npx openapi-sync generate-client --type react-query --json
機械可読な出力(--json)

--json を指定すると、すべてのコマンドは stdout に純粋な JSON オブジェクトを1つ出力するため、jq に直接パイプしたり、自動化されたエージェントで利用したりできます。人間向けの進捗ログはすべて抑制されるか、stderr に出力されます。

$ npx openapi-sync --json
{
  "success": true,
  "apis": ["petstore"],
  "filesWritten": ["src/api/petstore/types.ts", "src/api/petstore/endpoints.ts"],
  "endpointCount": 20,
  "warnings": [],
  "errors": [],
  "phases": {
    "sync": { "filesWritten": ["src/api/petstore/types.ts", "src/api/petstore/endpoints.ts"], "endpointCount": 20 },
    "client": { "filesWritten": [], "endpointCount": 20 }
  }
}
$ npx openapi-sync validate --json
{
  "valid": true,
  "apis": { "petstore": { "valid": true, "endpointCount": 20 } },
  "configErrors": []
}
$ npx openapi-sync list-endpoints --json
{
  "petstore": [
    { "name": "getPetById", "method": "GET", "path": "/pet/{petId}", "tags": ["pet"], "summary": "Find pet by ID" },
    { "name": "addPet", "method": "POST", "path": "/pet", "tags": ["pet"], "summary": "Add a new pet" }
  ]
}
$ npx openapi-sync list-endpoints --api petstore --path-contains pet --limit 2 --offset 0 --json
$ npx openapi-sync get-endpoint --api petstore --operation-id getPetById --json
$ npx openapi-sync read-type --api petstore --type-name Pet --json
ドライラン(ファイルを書き込まずにプレビュー)

計画されたファイルを簡潔かつすばやくプレビューします。

npx openapi-sync --dry-run --json
npx openapi-sync generate-client --type fetch --dry-run --json
レイアウトと出力ディレクトリ
  • フラットモード(デフォルト): folderSplit が省略されているか空({})の場合、ファイルは API フォルダー(endpoints.ts、types/index.ts、types/shared.ts)に直接配置されます。
  • タグ分割モード: folderSplit: { byTags: true } を設定すると、エンドポイントがタグのサブフォルダー(例:{tag}/endpoints.ts、{tag}/types.ts、shared.ts)に整理されます。
  • カスタムクライアントディレクトリ: clientGeneration.outputDir(または CLI の --output)は、フラットレイアウトとフォルダー分割レイアウトの両方で完全にサポートされています。フラットモードでは、クライアントは {outputDir}/clients.ts(または api.ts)に直接配置されます。フォルダー分割モードでは、クライアントは {outputDir}/{tag}/client.ts に配置され、{outputDir}/clients.ts に集約されます。相対インポートは、生成された型とエンドポイントを参照するように解決されます。
プログラム API(TypeScript)
import {
  ValidateConfig,
  Init,
  GenerateClient,
  ListEndpoints,
  GetEndpointDetails,
  ReadGeneratedType,
  Doctor,
  Purge,
} from "openapi-sync";

// Pre-flight check — no files written
const validation = await ValidateConfig({ silent: true });
if (!validation.valid) throw new Error(JSON.stringify(validation));

// Diagnostic health check on config, specs, peer dependencies, and directories
const health = await Doctor({ silent: true });
console.log("Health check:", health.healthy ? "All checks passed" : "Issues detected");

// Inspect API surface with pagination and filtering
const endpoints = await ListEndpoints({
  apiName: "petstore",
  pathContains: "pet",
  limit: 5,
  offset: 0,
  silent: true,
});
console.log(endpoints.petstore.length, "endpoints found");

// Inspect a single endpoint in full detail (4-tier fuzzy matching)
const detail = await GetEndpointDetails({ apiName: "petstore", operationId: "getPetById", silent: true });
console.log(detail.endpoint.path);

// Read an exact generated type declaration (with optional line pagination)
const typeDecl = await ReadGeneratedType({ apiName: "petstore", typeName: "Pet", silent: true });
console.log(typeDecl);

// Sync and get structured result
const syncResult = await Init({ silent: true });
if (!syncResult.success) throw new Error(JSON.stringify(syncResult));
console.log("Files written:", syncResult.filesWritten);

// Generate client
const clientResult = await GenerateClient({ type: "react-query", silent: true });
console.log(JSON.stringify(clientResult));

// Detect and purge stale files from disk
const purgeResult = await Purge({ yes: true, silent: true });
console.log("Purged files:", purgeResult.purged);
終了コード
コード意味
0成功
1設定エラーまたは検証失敗
2ネットワーク/仕様ファイルの取得エラー
3生成/ファイル書き込みエラー
エージェントセーフなコマンドと対話型コマンド
コマンドエージェントセーフ?説明
npx openapi-sync✅仕様を同期し、型、エンドポイント、スキーマを生成
npx openapi-sync validate✅設定と仕様を検証。ファイルは書き込まれません
npx openapi-sync doctor✅設定、ネットワーク、peer deps、キャッシュの診断ヘルスチェック
npx openapi-sync list-endpoints✅フィルタリングとページネーションを使ってエンドポイントを一覧表示。ファイルは書き込まれません
npx openapi-sync get-endpoint✅operationId または名前で指定したエンドポイントの詳細なスキーマを確認
npx openapi-sync read-type✅生成された TypeScript 宣言ブロックを読み込み
npx openapi-sync generate-client✅型付き API クライアントを生成(fetch、next-fetch、axios、react-query、swr、rtk-query)
npx openapi-sync purge --yes✅確認なしで古い生成ファイルを削除
npx openapi-sync init --no-interactive✅プロンプトなしで設定ファイルを作成
npx openapi-sync init(フラグなし)❌対話型ウィザード(stdin が必要)

クイックスタート

オプション 1:対話型セットアップ(おすすめ)🎯

最も簡単に始めるには、対話型セットアップウィザードを利用します。

npx openapi-sync init

ウィザードでは、次の項目を設定できます。

  • 📝 設定ファイル形式の選択(TypeScript、JSON、JavaScript)
  • 🌐 API 仕様のソース(URL またはローカルファイル)
  • 📁 フォルダー構成のオプション(タグ別またはカスタムロジックで分割)
  • 🚀 クライアント生成のオプション(React Query、SWR、Fetch、Axios、RTK Query)
  • ✅ バリデーションライブラリのセットアップ(Zod、Yup、Joi)
  • 🔧 カスタムコードの保持設定
  • 🏷️ 型の命名設定(operationId の使用、プレフィックス)
  • 🚫 エンドポイントのフィルタリング(タグで除外)
  • 📚 ドキュメントのオプション(cURL の例)
オプション 2:手動セットアップ

1. プロジェクトのルートに openapi.sync.json を作成します。

{
	"refetchInterval": 5000,
	"folder": "./src/api",
	"api": {
		"petstore": "https://petstore3.swagger.io/api/v3/openapi.json"
	}
}

2. 同期コマンドを実行します。

npx openapi-sync

3. 生成された型とエンドポイントを使用します。

import { getPetById } from "./src/api/petstore/endpoints";
import { IPet } from "./src/api/petstore/types";

const petUrl = getPetById("123"); // Returns: "/pet/123"

詳しいクイックスタートガイドを見る →

⚡ プリセット(フレームワークをゼロコンフィグでセットアップ)

プリセットには、フレームワーク、クライアントライブラリ、バリデーションスタック向けの独自のデフォルト設定が、単一の名前にまとめられています。多数の設定を手動で構成する代わりに、npx openapi-sync init の実行時にプリセットを選択するか、設定ファイルに "preset": "<name>" を設定してください。明示的に定義した設定値は、常にプリセットのデフォルト設定より優先されます。

プリセット名対象フレームワーク/HTTP クライアントバリデーションライブラリ設定される機能推奨される依存関係
react-query-zod (デフォルト/推奨)TanStack React Query v5Zod型付き Query・Mutation フック、Zod スキーマ、カスタムコードの保持、operationId に基づく命名npm i @tanstack/react-query axios zod
react-query-yupTanStack React Query v5Yup型付き Query・Mutation フック、Yup バリデーションスキーマ、カスタムコードの保持npm i @tanstack/react-query axios yup
swr-zodVercel SWRZodミューテーションをサポートする SWR フック(useSWRMutation)、Zod スキーマ、カスタムコードの保持npm i swr axios zod
swr-yupVercel SWRYupミューテーションをサポートする SWR フック、Yup バリデーションスキーマ、カスタムコードの保持npm i swr axios yup
axios-zodAxios クライアントZod単独で使える型付き Axios クライアントインスタンス、Zod スキーマ、カスタムコードの保持npm i axios zod
axios-joiAxios クライアントJoi単独で使える型付き Axios クライアント、Joi バリデーションスキーマ(Node.js バックエンドに最適)npm i axios joi
fetch-zodネイティブ Fetch APIZod依存関係のないネイティブ fetch クライアント、Zod による実行時バリデーションnpm i zod
rtk-query-zodRedux Toolkit QueryZodfetchBaseQuery を使用する RTK Query API スライス定義、Zod スキーマnpm i @reduxjs/toolkit react-redux zod
next-fetchNext.js(App/Pages ルーター)無効キャッシュヘッダーを使用する Server Components 対応の fetch 呼び出し、バンドルサイズの増加を防ぐためバリデーションは無効(Next.js に組み込み済み)
python-basicPython該当なしPython dataclass/TypedDict 型を生成。TypeScript の実行時バリデーションはありませんpip install requests
プリセットの使用

CLI セットアップウィザードの場合:

npx openapi-sync init
# Select your preset from the interactive menu with rich descriptions

非対話型/CI の場合:

npx openapi-sync init --preset react-query-zod --api-name petstore --api-url https://petstore3.swagger.io/api/v3/openapi.json

JSON(openapi.sync.json)の場合:

{
  "$schema": "./node_modules/openapi-sync/openapi.sync.schema.json",
  "preset": "react-query-zod",
  "api": {
    "petstore": "https://petstore3.swagger.io/api/v3/openapi.json"
  }
}

TypeScript(openapi.sync.ts)の場合:

import { defineConfig } from "openapi-sync";

export default defineConfig({
  preset: "react-query-zod",
  api: {
    petstore: "https://petstore3.swagger.io/api/v3/openapi.json",
  },
  // User values cleanly override preset defaults:
  folder: "./src/api",
});

ウェブサイトでプリセットガイドを見る →

API クライアントの生成

人気のライブラリ向けに、フックを備えた完全な型付き API クライアントを生成します。

Fetch クライアントを生成
npx openapi-sync generate-client --type fetch
Axios クライアントを生成
npx openapi-sync generate-client --type axios
React Query フックを生成
npx openapi-sync generate-client --type react-query --api petstore
SWR フックを生成
npx openapi-sync generate-client --type swr
RTK Query API を生成
npx openapi-sync generate-client --type rtk-query
Next.js Fetch クライアントを生成(App Router と Server Components)
npx openapi-sync generate-client --type next-fetch
# Or use --preset next-fetch during init / sync

Next.js App Router(Server Components)での使用:

// app/pets/[id]/page.tsx (Server Component — no React hooks needed)
import { getPetById, setApiConfig } from "@/api/petstore/clients";

// Set baseURL at runtime or via environment variables
setApiConfig({ baseURL: process.env.API_BASE_URL || "https://api.example.com" });

export default async function PetPage({ params }: { params: { id: string } }) {
  // Built-in Next.js App Router cache and tag-based revalidation
  const pet = await getPetById(
    { url: { petId: params.id } },
    {
      cache: "force-cache",
      next: { revalidate: 3600, tags: ["pets"] },
    }
  );

  return <div><h1>{pet.name}</h1></div>;
}
タグまたはエンドポイントで絞り込む
# Filter by tags
npx openapi-sync generate-client --type fetch --tags pets,users

# Filter by specific endpoints
npx openapi-sync generate-client --type axios --endpoints getPetById,createPet
使用例(React Query)

1. クライアントを生成する:

npx openapi-sync generate-client --type react-query

2. React コンポーネントで使用する:

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useGetPetById, useCreatePet } from "./api/petstore/client/hooks";
import apiClient from "./api/petstore/client/client";

// Configure API client
apiClient.updateConfig({
  baseURL: "https://api.example.com",
  headers: {
    Authorization: "Bearer your-auth-token",
  },
});

function PetDetails({ petId }: { petId: string }) {
  // Query hook for GET requests with structured params
  const { data, isLoading, error } = useGetPetById({
    url: { petId }, // Path parameters
    query: { includeOwner: true }, // Query parameters (if any)
  });

  // Mutation hook for POST/PUT/PATCH/DELETE requests
  const createPet = useCreatePet({
    onSuccess: () => {
      console.log("Pet created!");
    },
  });

  const handleCreate = () => {
    createPet.mutate({
      data: {
        // Request body
        name: "Fluffy",
        species: "cat",
      },
    });
  };

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>{data?.name}</h1>
      <button onClick={handleCreate}>Create New Pet</button>
    </div>
  );
}
クライアント生成オプション
オプション説明例
--type, -t生成するクライアントの種類fetch, next-fetch, axios, react-query, swr, rtk-query
--api, -a設定から特定の API を指定--api petstore
--tagsエンドポイントのタグで絞り込む--tags pets,users
--endpoints, -eエンドポイント名で絞り込む--endpoints getPetById,createPet
--output, -o出力ディレクトリ--output ./src/clients
--base-url, -bリクエストのベース URL--base-url https://api.example.com
カスタムコードの保持

生成されたクライアントは、再生成時にも保持されるカスタムコードセクションに対応しています。

// client.ts (Generated)

// ============================================================
// 🔒 CUSTOM CODE START
// Add your custom code below this line
// This section will be preserved during regeneration
// ============================================================

// Your custom helper functions, middleware, etc.

// 🔒 CUSTOM CODE END
// ============================================================

クライアント生成ガイドの全文を見る →

設定

複数の設定形式に対応しています:openapi.sync.json、openapi.sync.ts、または openapi.sync.js

基本的な例:

{
	"refetchInterval": 5000,
	"folder": "./src/api",
	"api": {
		"petstore": "https://petstore3.swagger.io/api/v3/openapi.json"
	}
}

TypeScript の応用例:

import { IConfig } from "openapi-sync";

const config: IConfig = {
	refetchInterval: 10000,
	folder: "./src/api",
	api: {
		"main-api": "https://api.example.com/openapi.json",
	},
	folderSplit: { byTags: true },
	types: { name: { prefix: "I", useOperationId: true } },
	endpoints: {
		exclude: { tags: ["deprecated"] },
		doc: { showCurl: true },
	},
	validations: { library: "zod" },
};

export default config;
🔐 保護された仕様と認証情報の保存(auth)

Bearer トークン、Basic 認証、API キー、またはカスタムヘッダーで保護された OpenAPI 仕様を取得します。

⚠️ 人間および AI エージェントへの重要なお知らせ: 認証情報に環境変数を指定するには、TypeScript(openapi.sync.ts)または JavaScript(openapi.sync.js)の設定ファイルを使用する必要があります。 静的 JSON(openapi.sync.json)は、process.env のような JavaScript ランタイム式に対応していません。シークレットを安全に保ち、無効な JSON 構文エラーを防ぐため、動的な環境変数が必要な場合は必ず openapi.sync.ts または openapi.sync.js を使用してください。

TypeScript の例(openapi.sync.ts):

import { defineConfig } from "openapi-sync";

export default defineConfig({
  folder: "./src/api",
  api: {
    // 1. Protected with Bearer token
    billingApi: {
      url: "https://api.example.com/billing/openapi.json",
      auth: {
        type: "bearer",
        token: process.env.BILLING_API_TOKEN!,
      },
    },

    // 2. Protected with Basic auth
    internalApi: {
      url: "https://internal.example.com/spec.json",
      auth: {
        type: "basic",
        username: process.env.INTERNAL_USER!,
        password: process.env.INTERNAL_PASSWORD!,
      },
    },

    // 3. Protected with API Key (header or query)
    analyticsApi: {
      url: "https://analytics.example.com/openapi.json",
      auth: {
        type: "apiKey",
        in: "header",
        name: "X-API-Key",
        value: process.env.ANALYTICS_KEY!,
      },
    },
  },
});

JavaScript の例(openapi.sync.js):

/** @type {import('openapi-sync').IConfig} */
module.exports = {
  folder: "./src/api",
  api: {
    protectedApi: {
      url: "https://api.example.com/openapi.json",
      auth: {
        type: "bearer",
        token: process.env.MY_SPEC_TOKEN,
      },
    },
  },
};

設定オプションの全文を見る →

CLI コマンド

対話型セットアップ
npx openapi-sync init

設定ファイルの作成を案内する対話型ウィザードを起動します。初回のセットアップや、利用可能なオプションの確認に最適です。

API 型の同期
# Sync with default config
npx openapi-sync

# Sync with custom refetch interval
npx openapi-sync --refreshinterval 10000

OpenAPI 仕様を同期し、TypeScript の型、エンドポイント、検証スキーマを生成します。

CLI のゼロ設定実行と設定の上書き

設定ファイルをディスク上に作成せずに、ターミナルスクリプトや CI/CD パイプラインから openapi-sync を直接実行できます。設定ファイルでサポートされている任意のプロパティを CLI フラグで渡します。

# Zero-config sync with preset
npx openapi-sync --api-url https://petstore3.swagger.io/api/v3/openapi.json --preset react-query-zod --folder ./src/api

# Zero-config sync with protected spec
npx openapi-sync --api-url https://api.example.com/openapi.json --auth-type bearer --auth-token "$MY_TOKEN" --preset next-fetch

# Multiple APIs via CLI
npx openapi-sync --api users=https://api.example.com/users.json --api billing=https://api.example.com/billing.json --preset axios-zod

# Override existing disk config properties on-the-fly
npx openapi-sync --folder ./dist/api --validation-lib yup --no-docs

# Raw JSON configuration via CLI
npx openapi-sync --config-json '{"api":{"main":"https://api.example.com/spec.json"},"preset":"react-query-zod"}'

メモ

ディスク上に設定ファイルがなく、必要な CLI フラグ(例:--api-url、--api <name>=<url>、または --config-json)も指定せずに実行した場合、openapi-sync は標準の ConfigNotFoundError を表示し、npx openapi-sync init の実行を促します。

API クライアントの生成
# Generate React Query hooks
npx openapi-sync generate-client --type react-query

# Generate for specific API
npx openapi-sync generate-client --type axios --api petstore

# Generate with filters
npx openapi-sync generate-client --type fetch --tags pets,users

# Generate for specific endpoints
npx openapi-sync generate-client --type swr --endpoints getPetById,createPet

さまざまなフレームワークやライブラリ向けに、型付けされた API クライアントを生成します。

利用可能なコマンドとオプション
コマンド説明
init対話型セットアップウィザード(または -y / --no-interactive による非対話型セットアップ)
sync(デフォルト)OpenAPI 仕様を同期し、型、エンドポイント、検証スキーマを生成します
generate-client型付き API クライアントコード(fetch、axios、react-query、swr、rtk-query)を生成します
validateファイルを書き込まずに、設定とリモート/ローカル仕様を検証します
doctor設定、仕様、ピア依存関係、キャッシュの診断ヘルスチェックを実行します
purge仕様に存在しなくなった古い生成ファイルを検出して削除します
list-endpointsフィルタリング、タグ、ページネーションを使用して、検出されたすべてのエンドポイントを一覧表示します
get-endpoint特定のエンドポイントの詳細、パラメーター、生成コードを確認します
read-type任意のスキーマについて、生成された TypeScript 型定義を抽出して表示します
--help, -hヘルプ情報を表示します
--version, -vバージョン番号を表示します
CLI フラグのエイリアス

init、sync、validate、generate-client では、フラグを相互に置き換えて使用できます:

  • 出力フォルダー:--output-folder または --folder(-f)(デフォルトはプロジェクトのルート "")
  • 検証ライブラリ:--validation-library または --validation-lib(--validations-library)
  • タグフォルダーの分割:--folder-split または --split-by-tags
  • 型のプレフィックス:--types-prefix または --type-prefix
診断ヘルスチェック(doctor)

環境を自動監査して、設定の構文、仕様へのアクセス可否、オプションのピア依存関係(zod、yup、joi)、キャッシュの状態、ディレクトリへの書き込み権限を診断します。

# Run human-readable diagnostic report
npx openapi-sync doctor

# Run machine-readable health check for agents and CI
npx openapi-sync doctor --json

出力例:

{
  "healthy": true,
  "checks": [
    { "name": "Configuration", "status": "ok", "message": "Valid openapi.sync.ts found" },
    { "name": "Spec Reachability: petstore", "status": "ok", "message": "HTTP 200 OK (20 endpoints)" },
    { "name": "Peer Dependency: zod", "status": "ok", "message": "zod v3.23.8 installed" },
    { "name": "Output Directory", "status": "ok", "message": "./src/api is writable" }
  ],
  "recommendations": []
}
古いファイルの検出とクリーンアップ(purge)

OpenAPI 仕様からエンドポイントやスキーマを削除すると、以前に生成されたファイルがコードベース内に孤立することがあります。openapi-sync は .openapi-sync/manifest.json を通じて生成済みアーティファクトを追跡し、古いファイルを自動的に検出します。

# Preview what stale files would be deleted without making changes
npx openapi-sync purge --dry-run

# Preview stale files as JSON (for CI / AI agents)
npx openapi-sync purge --dry-run --json

# Delete stale files without an interactive prompt
npx openapi-sync purge --yes

# Limit purge to a single configured API
npx openapi-sync purge --api petstore --yes
エンドポイントと型の確認(get-endpoint、read-type)

AI エージェントや開発者は、巨大なファイルを読み込んだり、LLM のコンテキストウィンドウを圧迫したりせずに、特定のエンドポイントのメタデータを照会したり、生成された型宣言を読み取ったりできます。

# Inspect full endpoint definition by operationId
npx openapi-sync get-endpoint --operation-id getPetById --json

# Inspect endpoint using 4-tier fuzzy matching by name or path
npx openapi-sync get-endpoint --name pet_update --json

# Read exact generated TypeScript type definition
npx openapi-sync read-type --api petstore --type-name Pet --json
型付きエラーコードと復旧

すべての CLI コマンドとプログラムから呼び出すメソッドは、OpenApiSyncError を拡張した構造化エラーオブジェクトをスローします。各エラーは、安定した code 文字列を公開します。

エラーコードエラークラスよくある原因推奨される復旧方法
CONFIG_NOT_FOUNDConfigNotFoundErrorcwd に openapi.sync.{ts,js,json} がないnpx openapi-sync init -y を実行するか、--api-url を指定してください
CONFIG_PARSE_FAILEDConfigParseError設定ファイルの構文エラーまたは評価エラー設定ファイルの構文を確認し、.env 変数がエクスポートされているか確認してください
CONFIG_INVALIDConfigValidationError必須フィールドがない(例:api が空)api マッピングに有効なソースが少なくとも1つ含まれていることを確認してください
SPEC_FETCH_FAILEDSpecFetchErrorネットワークタイムアウト、DNS エラー、401/403/404URL を確認し、--auth-type を追加するか、auth ブロックを設定してください
SPEC_READ_FAILEDSpecReadErrorローカルファイルが存在しない、または読み取れないapi 設定の相対ファイルパスを確認してください
SPEC_PARSE_FAILEDSpecParseErrorOpenAPI の JSON または YAML 仕様の形式が不正Swagger Editor または openapi-sync validate で仕様を検証してください
GENERATION_FAILEDGenerationErrorファイルシステムへの書き込み権限エラー出力先ディレクトリに書き込み権限があることを確認してください
UNKNOWN_APIUnknownApiError--api <name> が設定キーのいずれにも一致しないlist-endpoints --json で設定済みの API 名を確認してください

ドキュメント

以下を含む完全なドキュメントについては、次をご覧ください。

  • 設定オプション - 利用可能なすべての設定とカスタマイズ
  • 生成される出力 - 生成ファイルと構成について
  • カスタムコードの挿入 - 再生成の間もコードを保持
  • 検証スキーマ - Zod、Yup、Joi によるランタイム検証
  • 高度な例 - 複雑な設定とユースケース
  • API リファレンス - プログラムからの利用方法と型定義
  • トラブルシューティング - よくある問題と解決方法

openapi-sync.com をご覧ください


🔌 MCP サーバー(Model Context Protocol)

openapi-sync には、完全な Model Context Protocol(MCP)サーバーが付属しています。AI エージェント(Claude Desktop、Cursor、Windsurf、Zed、および MCP 対応クライアント)は、仕様全体をプロンプトのコンテキストに貼り付けることなく、stdio 経由の型安全なツール呼び出しによって、エンドポイントの照会、スキーマの確認、生成された型の読み取り、同期の実行を直接行えます。

MCP サーバーは openapi-sync の一部として、また npm の専用のゼロインストール用コンパニオンパッケージとして公開されています:openapi-sync-mcp。

npm version Glama Install in Cursor

4 つの方法でユーザーとエージェントが OpenAPI Sync にアクセスできます
方法コマンド/インポート最適な用途
1. スタンドアロン MCP パッケージnpx openapi-sync-mcpClaude Desktop、Cursor、Windsurf、Zed の設定(ワークスペースへのインストールは不要)
2. メイン CLI の MCP サブコマンドnpx openapi-sync mcpopenapi-sync がすでに devDependencies またはグローバル PATH にある場合
3. エージェント対応 CLI(--json)npx openapi-sync <cmd> --jsonbash/ターミナルにアクセスできる自律型エージェント(Cursor Agent、Claude Code、Antigravity)
4. プログラムからの Node/ESMrequire("openapi-sync/mcp")カスタムオーケストレーションスクリプト、社内開発者ポータル、CI ボット

サーバーの起動
# Option A: Via standalone companion package (recommended for agent configs)
npx openapi-sync-mcp

# Option B: Via main CLI (if openapi-sync is installed)
npx openapi-sync mcp

# Option C: If installed globally
openapi-sync-mcp

トランスポート: サーバーは stdio トランスポート を使用します。stdin から JSON-RPC を読み取り、stdout にレスポンスを書き込みます。プロセスの作業ディレクトリ(cwd)が、ファイルの読み書きに使用するプロジェクトルートになります。


ホストの設定ガイド
1. Cursor の設定

プロジェクトルートに .cursor/mcp.json を作成または更新します。

{
  "mcpServers": {
    "openapi-sync": {
      "command": "npx",
      "args": ["-y", "openapi-sync-mcp"],
      "cwd": "${workspaceFolder}"
    }
  }
}

または、Cursor Settings → Features → MCP → + Add New MCP Server からグローバルに追加します。

2. Claude Desktop の設定

設定ファイルを編集します。

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "openapi-sync": {
      "command": "npx",
      "args": ["-y", "openapi-sync-mcp"],
      "cwd": "/path/to/your/project"
    }
  }
}
3. Windsurf(Codeium)の設定

~/.codeium/windsurf/mcp_config.json に追加します。

{
  "mcpServers": {
    "openapi-sync": {
      "command": "npx",
      "args": ["-y", "openapi-sync-mcp"]
    }
  }
}
4. Zed の設定

Zed の settings.json の context_servers の下に追加します。

{
  "context_servers": [
    {
      "name": "openapi-sync",
      "command": {
        "path": "npx",
        "args": ["-y", "openapi-sync-mcp"]
      }
    }
  ]
}
5. Google Antigravity の設定

グローバル設定(~/.gemini/config/mcp_config.json)またはプロジェクトルート(.agents/mcp_config.json)に追加します。

{
  "mcpServers": {
    "openapi-sync": {
      "command": "npx",
      "args": ["-y", "openapi-sync-mcp"]
    }
  }
}
利用可能な MCP ツール
ツール説明
openapi_sync_read_config現在の設定ファイルを読み取ります。設定内容を確認するには、まずこれを実行してください
openapi_sync_validateファイルを書き込まずに、設定と仕様を検証します(認証と設定のオーバーライドに対応)
openapi_sync_doctor設定、仕様、ピア依存関係、キャッシュの完全な診断ヘルスチェックを実行します
openapi_sync_list_endpointsタグによる絞り込み、ページネーション、パスの照合、オプションのキャッシュ再利用を指定してエンドポイントを一覧表示します
openapi_sync_get_endpoint_detailsoperationId または名前を指定して、エンドポイント 1 件の保存済み定義全体を返します
openapi_sync_read_generated_type生成された型ファイルから、生成済みの TypeScript インターフェース/型宣言をそのまま読み取ります
openapi_sync_sync型、エンドポイント、検証スキーマを生成します
openapi_sync_generate_client型付き API クライアント(fetch、next-fetch、axios、react-query、swr、rtk-query)を生成します
openapi_sync_purge古くなった生成ファイルを検出して削除します(dryRun と yes に対応)
openapi_sync_initopenapi.sync の設定ファイルを作成します(非対話型で、認証と runSync を標準でサポート)
MCP を介した一般的なエージェントのワークフロー
1. openapi_sync_read_config               → check if config exists
2. openapi_sync_init                      → create config if needed (non-interactive, default folder "")
3. openapi_sync_doctor                    → verify environment, spec reachability, and peer dependencies
4. openapi_sync_validate                  → confirm specs are reachable and valid
5. openapi_sync_list_endpoints            → inspect a paged subset of endpoints or search by path
6. openapi_sync_get_endpoint_details      → inspect the full schema for one endpoint
7. openapi_sync_read_generated_type       → read a specific generated TypeScript declaration
8. openapi_sync_sync                      → generate types + schemas
9. openapi_sync_generate_client           → generate a typed client with optional cache reuse
10. openapi_sync_purge                    → clean up stale files when specs evolve
ツールの入出力型

すべてのツールは、プログラム API で使用されるものと同じ構造化型を JSON にシリアライズした形式で返します。

  • openapi_sync_sync → SyncResult
  • openapi_sync_generate_client → SyncResult
  • openapi_sync_validate → ValidationResult
  • openapi_sync_doctor → DoctorResult({ healthy, checks, recommendations })
  • openapi_sync_list_endpoints → Record<string, EndpointSummary[]>
  • openapi_sync_get_endpoint_details → { apiName, endpoint }
  • openapi_sync_read_generated_type → string
  • openapi_sync_init → { success, configFile, message, errors }
  • openapi_sync_read_config → { found, file, path, content }

トラブルシューティング

macOS Big Sur(11.x)- esbuild のインストールエラー

エラー: openapi-sync のインストール時に発生する dyld: Symbol not found: _SecTrustCopyCertificateChain

原因: デフォルトの esbuild バージョンは、Big Sur では利用できない macOS 12.0 以降の API を必要とします。

解決方法: openapi-sync のインストール前に、互換性のある esbuild バージョンをインストールします。

# Install compatible esbuild first
npm install [email protected]

# Then install openapi-sync
npm install openapi-sync

または、package.json にオーバーライドを追加します。

{
	"overrides": {
		"esbuild": "0.17.19"
	}
}

注: この問題は macOS Big Sur(darwin 20.x)のみで発生します。macOS 12 以降のユーザーには影響しません。


ライセンス

ISC ライセンスの詳細については、LICENSE ファイルを参照してください。

貢献

貢献を歓迎します!GitHub リポジトリにプルリクエストを送信してください。

コントリビューター

このプロジェクトに貴重な貢献をしてくださった以下のコントリビューターに、心より感謝いたします。

Fisayo Akintomiwa Opemipo Akintomiwa Ayotunde Obasa

サポート/寄付

OpenAPI Sync が役に立ち、開発を支援していただける場合は、ありがとうございます。ご支援はホスティング、CI、継続的なメンテナンスの費用に役立ちます。

以下のいずれかの方法でプロジェクトを支援できます。

プロジェクトへのご支援をご検討いただき、ありがとうございます。どんな支援も助けになります。

📘 ドキュメント全文 | GitHub | npm

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。