api-contract-sync
БесплатноБез исполняемых скриптовНе проверенUse this skill when backend API contracts change and frontend types need synchronization. Triggers on: Pydantic model changes, REST endpoint updates…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
API Contract Sync
Overview
Automatically detect and synchronize API contracts between backend and frontend when data structures, endpoints, or message formats change. Ensures type safety and prevents runtime errors from contract mismatches.
Core Principle: Context-Driven Detection
This skill does not assume Pydantic ↔ TypeScript. It:
- Detects contract type from project context (REST, WebSocket, GraphQL, gRPC)
- Identifies source of truth (backend models, OpenAPI spec, GraphQL schema)
- Determines target (TypeScript types, Zod schemas, client SDKs)
- Syncs appropriately based on detected patterns
When to Use
Invoke this skill when:
- Backend model changes: Pydantic models, SQLAlchemy models, dataclasses modified
- Endpoint modifications: New fields, renamed properties, changed response structure
- Message format updates: WebSocket events, SSE payloads, message queue schemas
- API versioning: New API version with breaking changes
- Type drift detected: Frontend using outdated or incorrect types
DO NOT use when:
- Internal backend types (not exposed via API)
- Frontend-only type definitions (UI state, component props)
- No communication between backend and frontend
- Types already synchronized manually
Contract Detection Workflow
Step 1: Identify Contract Type
Analyze project structure to determine contract mechanism:
Detection heuristics:
# Check project files and structure
if exists("backend/app/models/*.py") and uses("pydantic"):
contract_type = "Pydantic → TypeScript"
source_files = glob("backend/app/models/*.py")
target_files = glob("frontend/types/*.ts") or "frontend/src/types/"
elif exists("backend/schema.graphql"):
contract_type = "GraphQL Schema → TypeScript"
source_files = ["backend/schema.graphql"]
target_files = ["frontend/generated/graphql.ts"]
elif exists("backend/openapi.json") or exists("backend/openapi.yaml"):
contract_type = "OpenAPI → TypeScript"
source_files = ["backend/openapi.json"]
target_files = ["frontend/api/client.ts"]
elif exists("backend/app/websocket.py"):
contract_type = "WebSocket Messages → TypeScript"
source_files = ["backend/app/websocket.py"] # Message definitions
target_files = ["frontend/types/websocket.ts"]
else:
contract_type = "Unknown - manual analysis required"
Output contract type to user for confirmation before proceeding.
Step 2: Extract Backend Contract
Based on detected type, extract API contract:
Type A: Pydantic → TypeScript
Source: Pydantic models used in API responses
# Example: backend/app/models/task.py
from pydantic import BaseModel
class Task(BaseModel):
id: int
title: str
completed: bool
created_at: datetime
Extraction: Parse Pydantic model fields and types
Mapping:
int→numberstr→stringbool→booleandatetime→string(ISO8601)Optional[T]→T | nulllist[T]→T[]
Type B: GraphQL Schema → TypeScript
Source: GraphQL schema file
type Task {
id: ID!
title: String!
completed: Boolean!
createdAt: DateTime!
}
Extraction: Use GraphQL codegen or parse schema directly
Tool: @graphql-codegen/cli (if configured)
Type C: WebSocket Messages → TypeScript
Source: WebSocket message classes/types
# backend/app/websocket.py
class NotificationEvent(BaseModel):
type: Literal["notification"]
message: str
timestamp: datetime
user_id: int
Extraction: Parse message definitions, create discriminated unions
Type D: OpenAPI → TypeScript
Source: OpenAPI spec (usually auto-generated from FastAPI)
components:
schemas:
Task:
type: object
properties:
id: { type: integer }
title: { type: string }
completed: { type: boolean }
Extraction: Use OpenAPI TypeScript generators
Tool: openapi-typescript or swagger-typescript-api
Step 3: Generate Frontend Types
Based on contract type, generate appropriate frontend types:
For Pydantic → TypeScript (Manual)
// frontend/types/task.ts
export interface Task {
id: number;
title: string;
completed: boolean;
created_at: string; // ISO8601 datetime
}
export interface TaskCreate {
title: string;
completed?: boolean;
}
export interface TaskUpdate {
title?: string;
completed?: boolean;
}
For GraphQL (Codegen)
# Use GraphQL Code Generator
npx graphql-codegen --config codegen.yml
Generates frontend/generated/graphql.ts automatically
For WebSocket Messages
// frontend/types/websocket.ts
export type WebSocketMessage =
| { type: "notification"; message: string; timestamp: string; user_id: number }
| { type: "status_update"; status: string }
| { type: "ping" };
export interface NotificationEvent {
type: "notification";
message: string;
Установить api-contract-sync в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл api-contract-sync?
Use this skill when backend API contracts change and frontend types need synchronization. Triggers on: Pydantic model changes, REST endpoint updates, WebSocket message formats, or GraphQL schema modifications. Dynamically detects contract type from context. NOT for unrelated type definitions or internal backend-only changes.
Как установить скилл api-contract-sync?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-contract-sync запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic