mcpField
E
example-framework-skill

example-framework-skill

github.com/bobmatnycエージェントワークフロー78318 回インストール15 週間前に更新
リポジトリ

example-framework-skill について

Example Framework のアプリ開発向けに、Claude Code スキルのテンプレートを提供します。セットアップ、データベース、テスト、エラー処理、デプロイのパターンを内包し、他のスキルに依存しません。

主な機能

  1. 01アプリ設定パターンの内包
  2. 02データベース連携の例
  3. 03pytest によるテスト
  4. 04エラー処理と検証
  5. 05デプロイのガイド

活用シーン

  1. 01Example Framework アプリの開始
  2. 02データベースアクセスとリクエスト検証の追加
  3. 03アプリのテスト作成
  4. 04アプリのデプロイ準備

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill example-framework-skill

インストール後、Claude Code で/example-framework-skillを入力して読み込まれたか確認します。

同梱ファイルmetadata.jsonREADME.md

詳細

Example Framework スキル

Claude Code スキルで適切な自己完結型パターンを示す完全な例です。

使用する場面:Example Framework を使ったアプリケーションの構築。セットアップ、パターン、テスト、デプロイを含みます。


概要

このスキルでは、スキルを自己完結型で開発するための正しいアプローチを示します。

✅ 自己完結型:必要なコンテンツがすべてインライン化されており、単独で動作します
✅ 依存関係なし:ほかのスキルへの相対パスはありません
✅ 完全な例:断片ではなく、動作するコードを示します
✅ 段階的な機能低下:任意の拡張機能について説明しますが、必須にはしません
✅ フラットなデプロイに対応:どのようなディレクトリ構成でも動作します


クイックスタート

インストール
# Install framework
pip install example-framework

# Create new project
example-framework init my-project
cd my-project

# Install dependencies
pip install -r requirements.txt

# Run development server
example-framework dev
最小限の例(自己完結型)
"""
Minimal Example Framework application.
Self-contained - no external skill dependencies.
"""
from example_framework import App, route

app = App()

@route("/")
def home():
    """Homepage route."""
    return {"message": "Hello, World!"}

@route("/users/{user_id}")
def get_user(user_id: int):
    """Get user by ID."""
    return {
        "id": user_id,
        "username": f"user_{user_id}"
    }

if __name__ == "__main__":
    # Development server
    app.run(host="0.0.0.0", port=8000, debug=True)

実行方法:

python app.py
# Visit: http://localhost:8000

基本パターン

1. アプリケーションのセットアップ(自己完結型)

完全なセットアップパターン — 外部依存関係はありません。

from example_framework import App, Config
from example_framework.middleware import CORSMiddleware, LoggingMiddleware

# Configuration
config = Config(
    DEBUG=True,
    SECRET_KEY="your-secret-key-here",
    DATABASE_URL="sqlite:///./app.db"
)

# Application instance
app = App(config=config)

# Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"]
)

app.add_middleware(LoggingMiddleware)

# Health check endpoint
@app.route("/health")
def health_check():
    """Health check endpoint."""
    return {"status": "healthy"}
2. データベース統合(自己完結型)

必須のデータベースパターン — 自己完結型にするため、インライン化されています。

from example_framework import Database
from contextlib import contextmanager

# Database configuration
db = Database("sqlite:///./app.db")

@contextmanager
def get_db_session():
    """
    Database session context manager.

    Usage:
        with get_db_session() as session:
            users = session.query(User).all()
    """
    session = db.create_session()
    try:
        yield session
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()

# Model example
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def to_dict(self):
        """Convert to dictionary."""
        return {
            "id": self.id,
            "username": self.username,
            "email": self.email
        }

# CRUD operations
@app.route("/users", methods=["POST"])
def create_user(data):
    """Create new user."""
    with get_db_session() as session:
        user = User(
            username=data["username"],
            email=data["email"]
        )
        session.add(user)
        return user.to_dict(), 201

@app.route("/users/{user_id}")
def get_user(user_id: int):
    """Get user by ID."""
    with get_db_session() as session:
        user = session.query(User).filter_by(id=user_id).first()
        if not user:
            return {"error": "User not found"}, 404
        return user.to_dict()
3. テストパターン(自己完結型)

必須のテストパターン — テストのベストプラクティスをインライン化しています。

"""
Test suite for Example Framework application.
Self-contained testing patterns - no external skill dependencies.
"""
import pytest
from example_framework.testing import TestClient

# Test client fixture
@pytest.fixture
def client():
    """Create test client."""
    return TestClient(app)

# Database fixture
@pytest.fixture
def db_session():
    """Create test database session."""
    db.create_all()
    session = db.create_session()
    yield session
    session.close()
    db.drop_all()

# Test examples
def test_home_route(client):
    """Test homepage returns correct response."""
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, World!"}

def test_create_user(client, db_session):
    """Test user creation."""
    response = client.post("/users", json={
        "username": "testuser",
        "email": "[email protected]"
    })
    assert response.status_code == 201
    data = response.json()
    assert data["username"] == "testuser"
    assert data["email"] == "[email protected]"

def test_get_user(client, db_session):
    """Test get user by ID."""
    # Create user
    user = User(username="testuser", email="[email protected]")
    db_session.add(user)
    db_session.commit()

    # Get user
    response = client.get(f"/users/{user.id}")
    assert response.status_code == 200
    assert response.json()["username"] == "testuser"

def test_user_not_found(client):
    """Test 404 for nonexistent user."""
    response = client.get("/users/999")
    assert response.status_code == 404

テストの実行:

pytest tests/

エラー処理

標準的なエラーハンドラーパターン(自己完結型)
from example_framework import HTTPException

@app.error_handler(404)
def not_found_handler(error):
    """Handle 404 errors."""
    return {
        "error": "Not Found",
        "message": str(error)
    }, 404

@app.error_handler(500)
def server_error_handler(error):
    """Handle 500 errors."""
    return {
        "error": "Internal Server Error",
        "message": "An unexpected error occurred"
    }, 500

@app.error_handler(HTTPException)
def http_exception_handler(error):
    """Handle HTTP exceptions."""
    return {
        "error": error.name,
        "message": error.description
    }, error.status_code

# Custom validation error
class ValidationError(Exception):
    """Validation error."""
    pass

@app.error_handler(ValidationError)
def validation_error_handler(error):
    """Handle validation errors."""
    return {
        "error": "Validation Error",
        "message": str(error)
    }, 400

ベストプラクティス

1. 設定管理
# environment-based configuration
import os
from example_framework import Config

class DevelopmentConfig(Config):
    DEBUG = True
    DATABASE_URL = "sqlite:///./dev.db"

class ProductionConfig(Config):
    DEBUG = False
    DATABASE_URL = os.getenv("DATABASE_URL")
    SECRET_KEY = os.getenv("SECRET_KEY")

# Load config based on environment
env = os.getenv("ENV", "development")
config = DevelopmentConfig() if env == "development" else ProductionConfig()

app = App(config=config)
2. 依存性注入
# Dependency injection pattern
from example_framework import Depends

def get_current_user(token: str = Depends("Authorization")):
    """Get current user from token."""
    # Token validation logic
    user_id = validate_token(token)
    return User.query.get(user_id)

@app.route("/profile")
def get_profile(user: User = Depends(get_current_user)):
    """Get current user profile."""
    return user.to_dict()
3. リクエストの検証
from example_framework import validate_request

# Request schema
user_schema = {
    "username": {"type": "string", "minLength": 3, "maxLength": 80},
    "email": {"type": "string", "format": "email"},
    "age": {"type": "integer", "minimum": 0}
}

@app.route("/users", methods=["POST"])
@validate_request(user_schema)
def create_user(data):
    """Create user with validated data."""
    # Data is already validated
    user = User(**data)
    db.session.add(user)
    db.session.commit()
    return user.to_dict(), 201

デプロイ

本番環境へのデプロイ(自己完結型)
"""
Production deployment configuration.
Self-contained - all necessary patterns included.
"""

# 1. Use production server (e.g., gunicorn)
# requirements.txt:
# gunicorn>=20.1.0

# 2. Production configuration
import os

class ProductionConfig:
    DEBUG = False
    TESTING = False
    SECRET_KEY = os.getenv("SECRET_KEY")
    DATABASE_URL = os.getenv("DATABASE_URL")
    ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "").split(",")

app = App(config=ProductionConfig())

# 3. Run with gunicorn
# gunicorn -w 4 -b 0.0.0.0:8000 app:app

# 4. Environment variables (.env)
# SECRET_KEY=your-production-secret-key
# DATABASE_URL=postgresql://user:pass@localhost/dbname
# ALLOWED_HOSTS=example.com,www.example.com

補完的なスキル

このスキルを使用する際は、関連する以下のスキルも検討してください(デプロイされている場合)。

  • pytest-patterns:高度なテストパターンとフィクスチャ

    • 用途:パラメータ化を用いた包括的なテストスイート
    • 統合:上記の基本的なテストパターンを拡張します
    • ステータス:任意 — 基本的なテストパターンはこのスキルに含まれています
  • database-orm-patterns:高度な ORM パターンと最適化

    • 用途:複雑なクエリ、リレーション、パフォーマンスのチューニング
    • 統合:上記の基本的なデータベースパターンを拡張します
    • ステータス:任意 — 基本的な CRUD パターンはこのスキルに含まれています
  • api-security:認証、認可、セキュリティのベストプラクティス

    • 用途:本番環境に対応したセキュリティの実装
    • 統合:ルートにセキュリティレイヤーを追加します
    • ステータス:本番環境では推奨 — 基本的な例は上記に示しています
  • deployment-patterns:Docker、CI/CD、監視、スケーリング

    • 用途:本番環境へのデプロイと運用
    • 統合:デプロイ戦略とツール
    • ステータス:任意 — 基本的なデプロイ方法は上記に示しています

注:補完的なスキルはすべて個別にデプロイできます。このスキルは、それらがなくても完全に機能します。


よくある落とし穴

❌ 避ける:相対インポート
# DON'T DO THIS
from ..other_skill.patterns import setup
✅ 推奨:自己完結型パターン
# Include pattern directly
def setup():
    """Setup pattern (self-contained)."""
    # Implementation here
    pass
❌ 避ける:外部スキルへの依存
# DON'T DO THIS
# This requires pytest-patterns skill
from skills.pytest_patterns import fixture_factory
✅ 推奨:必須パターンをインライン化
# Include essential pattern
def fixture_factory(name, default=None):
    """Fixture factory pattern (inlined)."""
    @pytest.fixture
    def _fixture():
        return default
    _fixture.__name__ = name
    return _fixture

段階的な情報開示

より高度なトピックについては、references/ ディレクトリを参照してください。

注:メインの SKILL.md だけで必要な情報がそろっています。references には、任意で参照できる詳細情報が含まれています。


リソース

公式ドキュメント:

関連技術:


概要

このスキルでは、自己完結型のスキル開発を紹介します。

✅ 完全:必要なパターンをすべてインラインで記載しています ✅ 独立:他のスキルなしで動作します ✅ テスト済み:単独で動作することを確認済みです ✅ デプロイ可能:フラットなディレクトリ構造で動作します ✅ 柔軟:任意の拡張機能について説明しますが、必須ではありません

新しいスキルを作成する際のテンプレートとしてお使いください。


バージョン:1.0.0 最終更新日:2025-11-30 自己完結性:✅ 完全準拠

コメント