mcpField
O
openapi-sync-mcp

openapi-sync-mcp

本地服务
github.com/akintomiwa-fisayo开发工具16 周前更新

关于 openapi-sync-mcp

openapi-sync-mcp 是用于检查和同步 OpenAPI 规范的类型安全 MCP 服务,面向开发者和 Agent,支持验证规范、浏览端点及读取生成的类型。

主要功能

  1. 01验证配置和规范
  2. 02浏览并筛选端点
  3. 03检查端点架构
  4. 04读取生成的 TypeScript 类型
  5. 05运行诊断检查

适用场景

  1. 01生成代码前检查 API 规范
  2. 02按路径查找端点
  3. 03检查操作的架构
  4. 04让 Agent 读取生成的类型

MCP 相关

它向 MCP 客户端提供 OpenAPI Sync 的检查、验证和同步能力,包括端点与类型查询。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 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 规范到客户端实现再到运行时验证的全程类型安全。

📘 完整文档请访问 openapi-sync.com

核心功能

  • ⚡ 零配置预设 - 提供 10 种预配置框架预设(React Query、SWR、Axios、Fetch、RTK Query、Next.js、Python),可立即开始设置
  • 🔄 实时 API 同步 - 按可配置的间隔自动从远程 URL 同步 OpenAPI 规范
  • 📝 自动生成类型 - 为所有端点生成 TypeScript 接口,并全面支持嵌套结构
  • 🔐 运行时验证 - 根据 OpenAPI 规范生成 Zod、Yup 或 Joi 架构,并保留所有约束
  • 🎯 交互式设置向导 - 简化配置,并自动启用基于标签的文件夹拆分
  • 🛡️ 满足企业需求 - 提供错误处理、验证、状态持久化和自定义代码保留功能
  • 📦 文件夹拆分 - 按标签或自定义逻辑组织代码,并生成聚合文件,方便导入
  • 📚 丰富的文档 - 提供带有 cURL 示例和内联用法指南的 JSDoc 注释
  • 🤖 适用于 Agent 的端点 - 浏览支持分页和路径筛选的端点、检查深入的端点详情,并在无需重新加载规范的情况下读取生成的类型
  • 🩺 诊断助手 - 诊断配置有效性、规范可访问性、对等依赖项、缓存和文件夹写入权限
  • 🧹 清除过期文件 - 基于清单检测并清理过期代码,支持试运行,避免留下孤立代码
  • 🔄 自定义代码注入 - 在重新生成之间保留自定义代码

查看所有功能 →

安装

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 Agent 搭配使用

所有 CLI 命令和编程接口都适用于 Agent——无需交互式提示,且完全非阻塞。使用 --json 输出机器可读内容,使用 --silent 隐藏日志。

完整的 Agent 参考: llms.txt — 面向大模型、Copilot 和 MCP 工具的结构化发现文件。

Agent 快速入门(无提示)
# 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 对象,因此可以安全地直接传入 jq,或由自动化 Agent 使用。所有面向用户的进度日志都会被隐藏或发送到 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生成 / 文件写入错误
适用于 Agent 与交互式的命令
命令适用于 Agent?说明
npx openapi-sync✅同步规范,生成类型、端点和架构
npx openapi-sync validate✅验证配置和规范;不写入文件
npx openapi-sync doctor✅检查配置、网络、对等依赖和缓存的运行状况
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类型化查询和变更钩子、Zod 模式、保留自定义代码、operationId 命名npm i @tanstack/react-query axios zod
react-query-yupTanStack React Query v5Yup类型化查询和变更钩子、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 QueryZod使用 fetchBaseQuery 的 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 Agent 的重要提示: 在凭据中引用环境变量必须使用 TypeScript(openapi.sync.ts)或 JavaScript(openapi.sync.js)配置文件。 静态 JSON(openapi.sync.json)不支持 process.env 这类 JavaScript 运行时表达式。需要使用动态环境变量时,请务必使用 openapi.sync.ts 或 openapi.sync.js,以确保机密安全并避免无效 JSON 语法错误。

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 Agent 和开发者可以查询特定端点的元数据或读取生成的类型声明,无需加载大型文件或占用过多大模型上下文窗口:

# 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_FOUNDConfigNotFoundError当前工作目录中没有 openapi.sync.{ts,js,json}运行 npx openapi-sync init -y,或提供 --api-url
CONFIG_PARSE_FAILEDConfigParseError配置文件中的语法或求值错误检查配置文件语法;检查 .env 变量导出
CONFIG_INVALIDConfigValidationError缺少必填字段(例如,api 为空)确保 api 映射至少包含一个有效来源
SPEC_FETCH_FAILEDSpecFetchError网络超时、DNS 故障、401/403/404验证 URL;添加 --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 服务(模型上下文协议)

openapi-sync 附带完整的模型上下文协议(MCP)服务。AI Agent(Claude Desktop、Cursor、Windsurf、Zed 以及任何兼容 MCP 的客户端)可以直接通过 stdio 上类型安全的工具调用查询端点、检查架构、读取生成的类型并执行同步,无需将整个 5MB–15MB 的规范粘贴到提示词上下文中。

MCP 服务既作为 openapi-sync 的一部分发布,也作为 npm 上独立的零安装配套包发布:openapi-sync-mcp。

npm 版本 Glama 在 Cursor 中安装

用户和 Agent 访问 OpenAPI Sync 的 4 种方式
方法命令 / 导入最适用场景
1. 独立 MCP 包npx openapi-sync-mcpClaude Desktop、Cursor、Windsurf、Zed 配置(无需在工作区安装)
2. 主 CLI MCP 子命令npx openapi-sync mcp已将 openapi-sync 添加到 devDependencies 或全局 PATH 时
3. 适用于 Agent 的 CLI(--json)npx openapi-sync <cmd> --json可访问 bash/终端的自主 Agent(Cursor Agent、Claude Code、Antigravity)
4. 程序化 Node / ESMrequire("openapi-sync/mcp")自定义编排脚本、内部开发者门户和 CI Bot

启动服务
# 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 或名称返回某个端点的完整存储定义
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 执行的典型 Agent 工作流
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
工具输入/输出类型

所有工具都会返回 JSON 序列化结果,其结构化类型与程序化 API 使用的类型相同:

  • 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 版本需要 macOS 12.0+ 才提供的 API,而 Big Sur 不支持这些 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

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。