MCP HubMCP Hub
스킬 목록으로 돌아가기

build-cli-plugin

pjt222
업데이트됨 2 days ago
6 조회
17
2
17
GitHub에서 보기
메타design

정보

이 스킬은 추상 기본 클래스 패턴을 사용하여 CLI 플러그인이나 어댑터를 구축하는 방법을 개발자에게 안내합니다. 플러그인 계약 정의, 멱등성 설치/제거 작업 구현, 심볼릭 링크 또는 복사와 같은 설치 전략 선택을 다룹니다. CLI 도구에 새로운 프레임워크 지원을 추가하거나 기존 플러그인 아키텍처를 확장할 때 활용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/build-cli-plugin

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Build a CLI Plugin

Add new plugin or adapter to CLI tool's pluggable architecture using abstract base class pattern.

When Use

  • Adding support for new target framework to CLI installer
  • Building plugin system for multi-target command-line tool
  • Extending existing adapter architecture with new strategy variant
  • Porting content delivery to framework using different file layout

Inputs

  • Required: Framework or target plugin supports (name, config paths, conventions)
  • Required: Path to base class or plugin contract
  • Required: Installation strategy: symlink, copy, file-per-item, or append-to-file
  • Optional: Content types plugin handles (e.g., skills only, skills + agents, full support)
  • Optional: Scope support (project-level, global, both)

Steps

Step 1: Define the Contract

Base class establishes interface all plugins must implement:

export class FrameworkAdapter {
  static id = 'base';            // Unique identifier
  static displayName = 'Base';   // Human-readable name
  static strategy = 'symlink';   // Installation strategy
  static contentTypes = ['skill']; // What this adapter handles

  async detect(projectDir) { return false; }
  getTargetPath(projectDir, scope) { throw new Error('Not implemented'); }
  async install(item, projectDir, scope, options) { throw new Error('Not implemented'); }
  async uninstall(item, projectDir, scope, options) { throw new Error('Not implemented'); }
  async listInstalled(projectDir, scope) { return []; }
  async audit(projectDir, scope) { return { framework: this.constructor.displayName, ok: [], warnings: [], errors: [] }; }
  supports(contentType) { return this.constructor.contentTypes.includes(contentType); }
}

Static fields define plugin's identity and capabilities:

  • id: Used in --framework <id> option and result reporting
  • displayName: Shown in human-readable output
  • strategy: Determines how content reaches target
  • contentTypes: Filters which items this adapter receives

Base class doesn't exist yet? Create it first. Pattern scales to any number of plugins.

Got: Base class with static identity fields and abstract methods.

If fail: Base class has methods that don't apply to all plugins (e.g., not all frameworks support audit)? Provide default implementations returning sensible no-ops.

Step 2: Choose the Installation Strategy

StrategyWhen to useExample
symlinkTarget reads source files directly. Cheapest, stays in sync.Claude Code reads .claude/skills/<name>/ symlinks
copyTarget needs files in its own directory. Modifications don't propagate.Some IDEs index only their own dirs
file-per-itemTarget expects one file per item with specific format.Cursor .mdc rules files
append-to-fileTarget reads a single instructions file.Aider CONVENTIONS.md, Codex AGENTS.md

Strategy determines implementation shape:

  • Symlink: symlinkSync(source, target) — handle relative vs absolute paths
  • Copy: cpSync(source, target, { recursive: true }) — handle overwrites
  • File-per-item: writeFileSync(target, transform(content)) — may need format conversion
  • Append-to-file: Wrap content in markers for idempotent insert/replace/remove

Got: Strategy selected with clear rationale based on how target framework discovers content.

If fail: Unsure? Check framework's documentation for how it discovers configuration or instruction files. Default to symlink if framework reads arbitrary directories.

Step 3: Implement Detection

Detection tells CLI which frameworks present in project:

// In detector.js — each rule checks for a filesystem marker
const RULES = [
  {
    id: 'my-framework',
    displayName: 'My Framework',
    check: (dir) => existsSync(resolve(dir, '.myframework/')),
    marker: '.myframework/',
    scope: 'project',
  },
];

Detection strategies:

  • Directory presence: .claude/, .cursor/, .gemini/
  • Config file: opencode.json, .aider.conf.yml
  • Instruction file: AGENTS.md, CONVENTIONS.md
  • Global markers: ~/.openclaw/, ~/.hermes/

Always return marker in detection result so users can understand why framework was detected.

Got: Detection rule reliably identifies framework without false positives.

If fail: Framework has no unique marker (generic directory name)? Use combination of markers or require explicit --framework specification.

Step 4: Implement Install with Idempotency

async install(item, projectDir, scope, options) {
  const targetDir = this.getTargetPath(projectDir, scope);
  const targetPath = resolve(targetDir, item.id);

  // Idempotency: skip if already installed (unless force)
  if (existsSync(targetPath) && !options.force) {
    return { action: 'skipped', path: targetPath };
  }

  if (options.dryRun) {
    return { action: 'created', path: targetPath, details: 'dry-run' };
  }

  // Ensure parent directory exists
  mkdirSync(targetDir, { recursive: true });

  // Strategy-specific installation
  if (this.constructor.strategy === 'symlink') {
    const relPath = relative(targetDir, item.sourceDir);
    symlinkSync(relPath, targetPath);
  } else if (this.constructor.strategy === 'copy') {
    cpSync(item.sourceDir, targetPath, { recursive: true });
  }

  return { action: 'created', path: targetPath };
}

Idempotency rules:

  • Skip if target exists and --force not set
  • Overwrite if --force set (remove first, then install)
  • Dry-run always succeeds with action: 'created'
  • Return value must always be { action, path, details? }

Got: Install creates content at target path, skips if already present, respects --force and --dry-run.

If fail: Symlink creation fails on Windows/NTFS? Fall back to directory junction or copy. Log the fallback.

Step 5: Implement Uninstall with Cleanup

async uninstall(item, projectDir, scope, options) {
  const targetDir = this.getTargetPath(projectDir, scope);
  const targetPath = resolve(targetDir, item.id);

  if (!existsSync(targetPath)) {
    return { action: 'skipped', path: targetPath };
  }

  if (options.dryRun) {
    return { action: 'removed', path: targetPath };
  }

  // Remove the installed content
  rmSync(targetPath, { recursive: true });

  return { action: 'removed', path: targetPath };
}

Cleanup considerations:

  • Remove only what plugin installed — never delete user-created files
  • For append-to-file: remove marked section, not entire file
  • Leave parent directories intact (other plugins may use them)

Got: Uninstall removes only plugin's content and nothing else.

If fail: Removal fails (permissions, locked file)? Return error result instead of throwing.

Step 6: Implement Listing and Audit

async listInstalled(projectDir, scope) {
  const targetDir = this.getTargetPath(projectDir, scope);
  if (!existsSync(targetDir)) return [];

  const entries = readdirSync(targetDir);
  return entries.map(name => {
    const fullPath = resolve(targetDir, name);
    const broken = lstatSync(fullPath).isSymbolicLink()
      && !existsSync(fullPath);
    return { id: name, type: 'skill', broken };
  });
}

async audit(projectDir, scope) {
  const items = await this.listInstalled(projectDir, scope);
  const ok = items.filter(i => !i.broken);
  const broken = items.filter(i => i.broken);
  return {
    framework: this.constructor.displayName,
    ok: [`${ok.length} skills installed`],
    warnings: [],
    errors: broken.map(i => `Broken: ${i.id}`),
  };
}

Got: Listing returns all installed items with broken-link detection. Audit summarizes health.

If fail: Target directory doesn't exist? Return empty results (not error — framework just has nothing installed).

Step 7: Register the Plugin

// In adapters/index.js
import { MyFrameworkAdapter } from './my-framework.js';
register(MyFrameworkAdapter);

Registration makes adapter available to:

  • Auto-detection (detectFrameworks()getAdaptersForDetections())
  • Explicit selection (--framework my-framework)
  • Listing (listAdapters())

Got: Adapter appears in tool detect output, can be targeted with --framework.

If fail: Adapter doesn't appear? Verify static id matches detection rule's id and that register() was called.

Step 8: Write Tests

describe('adapter: my-framework (dry-run)', () => {
  it('targets the correct path', () => {
    const out = run('install create-skill --framework my-framework --dry-run');
    assert.match(out, /\.myframework/i);
  });
});

Test at minimum: dry-run path, detection presence, content type support.

Got: Adapter-specific tests confirm installation path and behavior.

If fail: Framework isn't detected in CI (no marker directory)? Use --framework explicitly in tests.

Checks

  • Plugin extends base class correctly
  • Static fields (id, displayName, strategy, contentTypes) set
  • Detection rule identifies framework without false positives
  • install() idempotent (skip if exists, respect --force)
  • uninstall() removes only plugin-created content
  • listInstalled() detects broken symlinks
  • audit() reports health accurately
  • Plugin registered, appears in tool detect
  • Dry-run tests pass

Pitfalls

  • Forgetting relative vs absolute symlinks: Project-scope symlinks should be relative (portable). Global-scope symlinks should be absolute (not dependent on cwd).
  • Not handling missing parent directories: Always mkdirSync(dir, { recursive: true }) before creating content.
  • Append-to-file without markers: Without idempotent markers (<!-- start:id --> / <!-- end:id -->), repeated installs duplicate content. Always wrap appended content.
  • Detection false positives: Generic directory name (e.g., .config/) may match multiple frameworks. Use specific file markers inside directory.
  • Forgetting supports() check: Installer calls supports(item.type) before dispatching. Wrong contentTypes? Adapter silently skips items.

See Also

  • scaffold-cli-command — build CLI commands using this plugin
  • test-cli-application — testing patterns for CLI tools including adapter tests
  • design-cli-output — terminal output for install/uninstall results

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman/skills/build-cli-plugin
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기