api-integration-patterns
サブプロセスの安全性、GitHub CLI統合、リトライロジック、認証、レート制限、タイムアウト処理に対応しています。外部APIやCLIツールの統合時に使用します。トリガー条件:サブプロセス、gh cli、APIコール、リトライロジック、レート制限、認証。トリガーしない条件:内部関数呼び出し、純粋なPythonロジック、設定ファイル編集。
description の原文を見る
Subprocess safety, GitHub CLI integration, retry logic, authentication, rate limiting, and timeout handling. Use when integrating external APIs or CLI tools. TRIGGER when: subprocess, gh cli, API call, retry logic, rate limiting, authentication. DO NOT TRIGGER when: internal function calls, pure Python logic, config file edits.
SKILL.md 本文
API統合パターンスキル
autonomous-dev プラグインエコシステムにおける外部API と CLI ツール統合の標準化されたパターン。外部サービスの呼び出し時の安全性、信頼性、セキュリティに焦点を当てています。
このスキルがアクティブになる場合
- 外部API(GitHub等)の統合
- サブプロセスコマンドの安全な実行
- リトライロジックの実装
- 認証の処理
- レート制限の管理
- キーワード: 「api」「subprocess」「github」「gh cli」「retry」「authentication」
コアパターン
1. サブプロセスセーフティ(CWE-78対策)
定義: コマンドインジェクション脆弱性のない安全な外部コマンド実行。
重要ルール:
- ✅ 常に引数配列を使用:
["gh", "issue", "create"] - ❌ ユーザー入力付きで shell=True を使用しない
- ✅ 常に許可されたコマンドをホワイトリストする
- ✅ 常にタイムアウトを設定する
パターン:
import subprocess
from typing import List
def safe_subprocess(
command: List[str],
*,
allowed_commands: List[str],
timeout: int = 30
) -> subprocess.CompletedProcess:
"""CWE-78対策付きサブプロセスを実行します。
Args:
command: コマンドと引数をリストで指定(文字列ではない!)
allowed_commands: 許可されたコマンドのホワイトリスト
timeout: 最大実行時間(秒)
Returns:
完了したサブプロセスの結果
Raises:
SecurityError: コマンドがホワイトリストにない場合
subprocess.TimeoutExpired: タイムアウトを超過した場合
Security:
- CWE-78対策: 引数配列(シェルインジェクションなし)
- コマンドホワイトリスト: 承認されたコマンドのみ
- タイムアウト: DoS対策
Example:
>>> result = safe_subprocess(
... ["gh", "issue", "create", "--title", user_title],
... allowed_commands=["gh", "git"]
... )
"""
# ホワイトリスト検証
if command[0] not in allowed_commands:
raise SecurityError(f"Command not allowed: {command[0]}")
# 引数配列で実行(決して shell=True を使わない!)
return subprocess.run(
command,
capture_output=True,
text=True,
timeout=timeout,
check=True,
shell=False # CRITICAL
)
参照: docs/subprocess-safety.md, examples/safe-subprocess-example.py
2. GitHub CLI(gh)統合
定義: gh CLIを経由したGitHub操作の標準化されたパターン。
パターン:
def create_github_issue(
title: str,
body: str,
*,
labels: Optional[List[str]] = None,
timeout: int = 30
) -> str:
"""gh CLIを使用してGitHub Issueを作成します。
Args:
title: Issue タイトル
body: Issue 本文(Markdown形式)
labels: Issue ラベル(デフォルト: なし)
timeout: コマンドタイムアウト(秒)
Returns:
Issue URL
Raises:
subprocess.CalledProcessError: gh コマンドが失敗した場合
RuntimeError: gh CLIがインストールされていない場合
Example:
>>> url = create_github_issue(
... "Bug: Login fails",
... "Login button doesn't work",
... labels=["bug", "p1"]
... )
"""
# gh コマンドを構築(引数配列)
cmd = ["gh", "issue", "create", "--title", title, "--body", body]
if labels:
for label in labels:
cmd.extend(["--label", label])
# 安全に実行
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=True,
shell=False
)
# 出力からURLを抽出
return result.stdout.strip()
参照: docs/github-cli-integration.md, examples/github-issue-example.py
3. 指数バックオフ付きリトライロジック
定義: 失敗したAPI呼び出しを指数バックオフで自動的に再試行します。
パターン:
import time
from typing import Callable, TypeVar, Any
T = TypeVar('T')
def retry_with_backoff(
func: Callable[..., T],
*,
max_attempts: int = 3,
base_delay: float = 1.0,
max_delay: float = 60.0
) -> T:
"""指数バックオフ付きで関数を再試行します。
Args:
func: 再試行する関数
max_attempts: 最大再試行回数
base_delay: 初期遅延(秒)
max_delay: 最大遅延(秒)
Returns:
関数の結果
Raises:
Exception: すべての再試行が失敗した場合の最後の例外
Example:
>>> result = retry_with_backoff(
... lambda: api_call(),
... max_attempts=5,
... base_delay=2.0
... )
"""
last_exception = None
for attempt in range(max_attempts):
try:
return func()
except Exception as e:
last_exception = e
if attempt < max_attempts - 1:
# 指数バックオフ: 1s, 2s, 4s, 8s, ...
delay = min(base_delay * (2 ** attempt), max_delay)
time.sleep(delay)
raise last_exception
参照: docs/retry-logic.md, templates/retry-decorator-template.py
4. 認証パターン
定義: API認証情報とトークンの安全な処理。
原則:
- 環境変数を認証情報に使用する
- APIキーをハードコードしない
- 認証情報をログに出力しない
- 使用前に認証情報を検証する
パターン:
import os
from typing import Optional
def get_github_token() -> str:
"""環境からGitHubトークンを取得します。
Returns:
GitHub個人アクセストークン
Raises:
RuntimeError: トークンが見つからない場合
Security:
- 環境変数: トークンをハードコードしない
- 検証: トークン形式をチェック
- ログ出力なし: 認証情報をログに出力しない
"""
token = os.getenv("GITHUB_TOKEN")
if not token:
raise RuntimeError(
"GITHUB_TOKEN not found in environment\n"
"Set with: export GITHUB_TOKEN=your_token\n"
"Or add to .env file"
)
# トークン形式を検証(基本チェック)
if not token.startswith("ghp_") and not token.startswith("github_pat_"):
raise ValueError("Invalid GitHub token format")
return token
参照: docs/authentication-patterns.md, templates/github-api-template.py
5. レート制限とクォータ管理
定義: API レート制限を適切に処理します。
パターン:
import time
from datetime import datetime, timedelta
class RateLimiter:
"""API呼び出し用の簡易レート制限機。
Attributes:
max_calls: ウィンドウ内の最大呼び出し数
window_seconds: 時間ウィンドウ(秒)
"""
def __init__(self, max_calls: int, window_seconds: int):
self.max_calls = max_calls
self.window_seconds = window_seconds
self.calls = []
def wait_if_needed(self) -> None:
"""レート制限に達する場合は待機します。"""
now = datetime.now()
cutoff = now - timedelta(seconds=self.window_seconds)
# ウィンドウ外の古い呼び出しを削除
self.calls = [c for c in self.calls if c > cutoff]
# 制限に達している場合は待機
if len(self.calls) >= self.max_calls:
oldest = self.calls[0]
wait_until = oldest + timedelta(seconds=self.window_seconds)
wait_seconds = (wait_until - now).total_seconds()
if wait_seconds > 0:
time.sleep(wait_seconds)
# 待機後に削除を再試行
self.calls = [c for c in self.calls if c > cutoff]
# この呼び出しを記録
self.calls.append(now)
参照: docs/rate-limiting.md, examples/github-api-example.py
使用ガイドライン
ライブラリ作成者向け
外部APIを統合する場合:
- サブプロセスを安全に使用: 引数配列を使用する
- コマンドをホワイトリスト: インジェクション対策
- リトライロジックを追加: 一時的な障害への対応
- 認証を安全に処理: 環境経由で
- レート制限を尊重: クォータ枯渇を回避
Claude向け
API統合を作成する場合:
- キーワードが一致したときにこのスキルを読み込む
- サブプロセスセーフティパターンに従う
- 信頼性のためにリトライを実装する
- 一般的なパターンのテンプレートを参照する
トークン節約
API統合パターンを集約することで:
- 従来: ライブラリあたり約45トークン(サブプロセスセーフティドキュメント用)
- 改善後: スキル参照で約10トークン
- 節約: ライブラリあたり約35トークン
- 合計: 8ライブラリで約280トークン(3~4%削減)
段階的な情報提供
このスキルはClaude Code 2.0+ の段階的情報提供アーキテクチャを使用:
- メタデータ(frontmatter): 常に読み込まれる(約170トークン)
- 完全なコンテンツ: キーワードが一致した場合のみ読み込まれる
- 結果: 効率的なコンテキスト使用
テンプレートと例
テンプレート
templates/subprocess-executor-template.py: 安全なサブプロセス実行templates/retry-decorator-template.py: リトライロジックデコレータtemplates/github-api-template.py: GitHub API統合
例
examples/github-issue-example.py: gh CLI経由のIssue作成examples/github-pr-example.py: PR作成パターンexamples/safe-subprocess-example.py: コマンド実行セーフティ
ドキュメント
docs/subprocess-safety.md: CWE-78対策docs/github-cli-integration.md: gh CLIパターンdocs/retry-logic.md: リトライ戦略docs/authentication-patterns.md: 認証情報処理
クロスリファレンス
このスキルは他のautonomous-dev スキルと統合:
- library-design-patterns: セキュリティファーストな設計
- security-patterns: CWE-78対策
- error-handling-patterns: リトライと復旧
メンテナンス
更新時期:
- 新しいAPI統合パターンが現れた場合
- セキュリティベストプラクティスが進化した場合
- gh CLIに新機能が追加された場合
最終更新: 2025-11-16(フェーズ8.8 - 初期作成) バージョン: 1.0.0
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- jj1985
- ライセンス
- MIT
- 最終更新
- 2026/4/29
Source: https://github.com/jj1985/claude-config-template / ライセンス: MIT