openapi-sync-mcp について
openapi-sync-mcp は、OpenAPI 仕様の確認と同期を行う型安全な MCP サーバーです。開発者やエージェントが仕様を検証し、エンドポイントを調べ、生成済みの型を参照できます。
主な機能
- 01設定と仕様の検証
- 02エンドポイントの閲覧と絞り込み
- 03エンドポイントスキーマの確認
- 04生成済み TypeScript 型の参照
- 05診断チェックの実行
活用シーン
- 01コード生成前の API 仕様確認
- 02パスによるエンドポイント検索
- 03操作スキーマの確認
- 04エージェントによる生成型の参照
MCP 対応
OpenAPI Sync の確認、検証、同期機能を MCP クライアントに提供し、エンドポイントや型の検索にも対応します。
設定
ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。
ツール
10掲載時のツール一覧 · 3 週間前に更新
| パラメーター | 型 | 必須 | 説明 |
|---|---|---|---|
| api | string | いいえ | API 仕様のソース(<name>=<url>、直接 URL、または絞り込み用の名前)。 |
| apiUrl | string | いいえ | OpenAPI 仕様の直接 URL(JSON または YAML)。 |
| authIn | enum | いいえ | API キーの場所:header または query(authType: apiKey と併用)。header | query |
| folder | string | いいえ | 生成ファイルの出力ディレクトリ(デフォルト:'' プロジェクトルート)。 |
| preset | enum | いいえ | 自動的に適用する名前付きプリセット。react-query-zod | react-query-yup | swr-zod | swr-yup | axios-zod | axios-joi | fetch-zod | rtk-query-zod | next-fetch | python-basic |
| server | string | いいえ | デフォルトのサーバーインデックス、またはベース URL の上書き値。 |
| apiFile | string | いいえ | OpenAPI 仕様のローカルファイルへの直接パス。 |
| apiName | string | いいえ | API の名前(デフォルト:'api')。 |
| authName | string | いいえ | API キーの header または query パラメーター名(デフォルト:X-API-Key)。 |
| authType | enum | いいえ | 仕様の認証タイプ(bearer、basic、apiKey、custom)。bearer | basic | apiKey | custom |
| language | enum | いいえ | 対象のプログラミング言語。typescript | python |
| authToken | string | いいえ | 認証用の Bearer トークンまたはパスワード値/環境変数参照。 |
| authValue | string | いいえ | API キーのシークレット値。 |
| authHeader | string | いいえ | カスタム header('Key: Value' 形式。authType: custom と併用)。 |
| configJson | string | いいえ | openapi-sync 設定を定義する生の JSON 文字列。 |
| authPassword | string | いいえ | basic 認証用のパスワード。 |
| authUsername | string | いいえ | basic 認証用のユーザー名。 |
| outputFolder | string | いいえ | フォルダーの別名です。 |
詳細
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 v5 | Zod | 型付き Query・Mutation フック、Zod スキーマ、カスタムコードの保持、operationId に基づく命名 | npm i @tanstack/react-query axios zod |
react-query-yup | TanStack React Query v5 | Yup | 型付き Query・Mutation フック、Yup バリデーションスキーマ、カスタムコードの保持 | npm i @tanstack/react-query axios yup |
swr-zod | Vercel SWR | Zod | ミューテーションをサポートする SWR フック(useSWRMutation)、Zod スキーマ、カスタムコードの保持 | npm i swr axios zod |
swr-yup | Vercel SWR | Yup | ミューテーションをサポートする SWR フック、Yup バリデーションスキーマ、カスタムコードの保持 | npm i swr axios yup |
axios-zod | Axios クライアント | Zod | 単独で使える型付き Axios クライアントインスタンス、Zod スキーマ、カスタムコードの保持 | npm i axios zod |
axios-joi | Axios クライアント | Joi | 単独で使える型付き Axios クライアント、Joi バリデーションスキーマ(Node.js バックエンドに最適) | npm i axios joi |
fetch-zod | ネイティブ Fetch API | Zod | 依存関係のないネイティブ fetch クライアント、Zod による実行時バリデーション | npm i zod |
rtk-query-zod | Redux Toolkit Query | Zod | fetchBaseQuery を使用する RTK Query API スライス定義、Zod スキーマ | npm i @reduxjs/toolkit react-redux zod |
next-fetch | Next.js(App/Pages ルーター) | 無効 | キャッシュヘッダーを使用する Server Components 対応の fetch 呼び出し、バンドルサイズの増加を防ぐためバリデーションは無効 | (Next.js に組み込み済み) |
python-basic | Python | 該当なし | 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_FOUND | ConfigNotFoundError | cwd に openapi.sync.{ts,js,json} がない | npx openapi-sync init -y を実行するか、--api-url を指定してください |
CONFIG_PARSE_FAILED | ConfigParseError | 設定ファイルの構文エラーまたは評価エラー | 設定ファイルの構文を確認し、.env 変数がエクスポートされているか確認してください |
CONFIG_INVALID | ConfigValidationError | 必須フィールドがない(例:api が空) | api マッピングに有効なソースが少なくとも1つ含まれていることを確認してください |
SPEC_FETCH_FAILED | SpecFetchError | ネットワークタイムアウト、DNS エラー、401/403/404 | URL を確認し、--auth-type を追加するか、auth ブロックを設定してください |
SPEC_READ_FAILED | SpecReadError | ローカルファイルが存在しない、または読み取れない | api 設定の相対ファイルパスを確認してください |
SPEC_PARSE_FAILED | SpecParseError | OpenAPI の JSON または YAML 仕様の形式が不正 | Swagger Editor または openapi-sync validate で仕様を検証してください |
GENERATION_FAILED | GenerationError | ファイルシステムへの書き込み権限エラー | 出力先ディレクトリに書き込み権限があることを確認してください |
UNKNOWN_API | UnknownApiError | --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。
4 つの方法でユーザーとエージェントが OpenAPI Sync にアクセスできます
| 方法 | コマンド/インポート | 最適な用途 |
|---|---|---|
| 1. スタンドアロン MCP パッケージ | npx openapi-sync-mcp | Claude Desktop、Cursor、Windsurf、Zed の設定(ワークスペースへのインストールは不要) |
| 2. メイン CLI の MCP サブコマンド | npx openapi-sync mcp | openapi-sync がすでに devDependencies またはグローバル PATH にある場合 |
3. エージェント対応 CLI(--json) | npx openapi-sync <cmd> --json | bash/ターミナルにアクセスできる自律型エージェント(Cursor Agent、Claude Code、Antigravity) |
| 4. プログラムからの Node/ESM | require("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_details | operationId または名前を指定して、エンドポイント 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_init | openapi.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→SyncResultopenapi_sync_generate_client→SyncResultopenapi_sync_validate→ValidationResultopenapi_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→stringopenapi_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 リポジトリにプルリクエストを送信してください。
コントリビューター
このプロジェクトに貴重な貢献をしてくださった以下のコントリビューターに、心より感謝いたします。
サポート/寄付
OpenAPI Sync が役に立ち、開発を支援していただける場合は、ありがとうございます。ご支援はホスティング、CI、継続的なメンテナンスの費用に役立ちます。
以下のいずれかの方法でプロジェクトを支援できます。
- GitHub でメンテナーをスポンサーする:https://github.com/sponsors/akintomiwa-fisayo
- Open Collective でプロジェクトを支援する(プレースホルダー):https://opencollective.com/fisayo-akintomiwa
プロジェクトへのご支援をご検討いただき、ありがとうございます。どんな支援も助けになります。
📘 ドキュメント全文 | GitHub | npm
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。