mcpField
B
bad-example-skill

bad-example-skill

github.com/bobmatnycAgent 工作流78324 次安装15 周前更新
代码仓库

关于 bad-example-skill

用于教学的反模式技能,展示技能如何依赖目录结构或其他技能。面向检查技能自包含性的作者,并以修正方法对照说明常见违规问题。

主要功能

  1. 01说明相对路径依赖风险
  2. 02解释内容缺失问题
  3. 03指出技能硬依赖
  4. 04介绍跨技能导入问题
  5. 05提供自包含性检查

适用场景

  1. 01检查技能是否存在部署耦合
  2. 02查找相对路径假设
  3. 03评估示例是否自包含

安装

复制下面的命令,在终端中运行。

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

安装后在 Claude Code 中输入/bad-example-skill确认已加载。

附带文件metadata.jsonREADME.md

详细介绍

⚠️ 错误示例 - 相互依赖的技能(反面模式)

警告:这是一个展示错误做法的反面模式示例。

请勿复制此结构。正确做法请参阅 good-self-contained-skill。


❌ 违规 #1:相对路径依赖

## Related Documentation

For setup instructions, see [../setup-skill/SKILL.md](../setup-skill/SKILL.md)

For testing patterns, see:
- [../../testing/pytest-patterns/](../../testing/pytest-patterns/)
- [../../testing/test-utils/](../../testing/test-utils/)

Database integration: [../../data/database-skill/](../../data/database-skill/)

错误原因:

  • ❌ 使用相对路径(../、../../)
  • ❌ 假设目录结构是分层的
  • ❌ 在扁平化部署(~/.claude/skills/)中失效
  • ❌ 技能独立部署时链接会失效

正确做法:

## Complementary Skills

Consider these related skills (if deployed):

- **setup-skill**: Installation and configuration patterns
- **pytest-patterns**: Testing framework and fixtures
- **database-skill**: Database integration patterns

*Note: All skills are independently deployable.*

❌ 违规 #2:缺少必要内容

## Testing

This skill uses pytest for testing.

**See pytest-patterns skill for all testing code.**

To write tests for this framework, install pytest-patterns skill
and refer to its documentation.

错误原因:

  • ❌ 未包含实际的测试模式
  • ❌ 要求用户拥有另一个技能
  • ❌ 缺少其他技能时,该技能并不完整
  • ❌ 用“参见其他技能”代替内联内容

正确做法:

## Testing (Self-Contained)

**Essential pytest pattern** (inlined):

```python
import pytest
from example_framework.testing import TestClient

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

def test_home_route(client):
    """Test homepage."""
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello"}

高级 fixture(如果已部署 pytest-patterns 技能):

  • 参数化 fixture
  • 数据库会话 fixture
  • Mock fixture

全面的模式请参阅 pytest-patterns 技能。


---

## ❌ VIOLATION #3: Hard Skill Dependencies

```markdown
## Prerequisites

**Required Skills**:
1. **setup-skill** - Must be installed first
2. **database-skill** - Required for database operations
3. **pytest-patterns** - Required for testing

Install all required skills before using this skill:
```bash
claude-code skills add setup-skill database-skill pytest-patterns

没有这些依赖项,该技能将无法运行。


**Why This is Wrong**:
- ❌ Lists other skills as "Required"
- ❌ Skill doesn't work standalone
- ❌ Creates deployment coupling
- ❌ Violates self-containment principle

**Correct Approach**:
```markdown
## Prerequisites

**External Dependencies**:
```bash
pip install example-framework pytest sqlalchemy

互补技能

使用此技能时,可考虑使用(如果已部署):

  • setup-skill:高级配置模式(可选)
  • database-skill:ORM 模式和优化(可选)
  • pytest-patterns:测试增强功能(可选)

此技能可独立完整运行。


---

## ❌ VIOLATION #4: Cross-Skill Imports

```python
"""
Bad example - importing from other skills.
"""

# ❌ DON'T DO THIS
from skills.database_skill import get_db_session
from skills.pytest_patterns import fixture_factory
from ..shared.utils import validate_input

# Using imported patterns
@app.route("/users")
def create_user(data):
    # Requires database-skill to be installed
    with get_db_session() as session:
        user = User(**data)
        session.add(user)
        return user.to_dict()

错误原因:

  • ❌ 从其他技能导入内容
  • ❌ 没有其他技能时,代码无法运行
  • ❌ 造成运行时依赖
  • ❌ 违反 Python 模块边界

正确做法:

"""
Good example - self-contained implementation.
"""
from contextlib import contextmanager

# ✅ Include pattern directly in this skill
@contextmanager
def get_db_session():
    """Database session context manager (self-contained)."""
    db = SessionLocal()
    try:
        yield db
        db.commit()
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()

@app.route("/users")
def create_user(data):
    # Works independently
    with get_db_session() as session:
        user = User(**data)
        session.add(user)
        return user.to_dict()

❌ 违规 #5:对分层目录结构的假设

## Project Structure

This skill is located in:

toolchains/python/frameworks/bad-example-skill/


**Navigate to parent directories for related skills**:
- `../` - Other framework skills
- `../../testing/` - Testing skills
- `../../data/` - Database skills

**All skills in `toolchains/python/frameworks/` are related to this skill.**

错误原因:

  • ❌ 假设存在特定的目录结构
  • ❌ 使用相对路径提供导航说明
  • ❌ 无法在扁平化部署中运行
  • ❌ 混淆部署位置与技能之间的关系

正确做法:

## Related Skills

**Complementary Python Framework Skills** (informational):

- **fastapi-patterns**: Web framework patterns
- **django-patterns**: Full-stack framework patterns
- **flask-patterns**: Micro-framework patterns

**Testing Skills**:
- **pytest-patterns**: Testing framework
- **test-driven-development**: TDD workflow

*Note: Skills are independently deployable. Directory structure may vary.*

❌ 违规 #6:示例不完整

# Database setup
# (See database-skill for complete implementation)

class User(db.Model):
    # ... see database-skill for model definition ...
    pass

# Testing
# (See pytest-patterns for test examples)

def test_user():
    # ... see pytest-patterns for fixtures ...
    pass

# Deployment
# (See deployment-skill for production setup)

错误原因:

  • ❌ 示例只是代码片段,并非完整代码
  • ❌ 用“参见其他技能”代替展示代码
  • ❌ 用户无法复制粘贴并运行
  • ❌ 技能没有提供实际的实现指导

正确做法:

# Complete database model (self-contained)
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    """User model - complete implementation."""
    __tablename__ = "users"

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

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

# Complete test example (self-contained)
import pytest
from example_framework.testing import TestClient

@pytest.fixture
def client():
    return TestClient(app)

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

# Complete deployment example (self-contained)
import os

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

app = App(config=ProductionConfig())

# Run with: gunicorn -w 4 app:app

❌ 违规 #7:引用目录包含跨技能路径

bad-example-skill/
├── SKILL.md
├── metadata.json
└── references/
    ├── testing.md          # Contains: ../../pytest-patterns/
    ├── database.md         # Contains: ../../database-skill/
    └── deployment.md       # Contains: ../../../universal/deployment/

references/testing.md 的内容:

# Testing Patterns

For complete testing patterns, see:
- [Pytest Patterns](../../pytest-patterns/SKILL.md)
- [TDD Workflow](../../../universal/testing/test-driven-development/)

Refer to those skills for all testing code.

错误原因:

  • ❌ 引用目录中包含跨技能路径
  • ❌ 渐进式披露会引导到技能之外
  • ❌ 在扁平化部署中失效
  • ❌ 引用内容并非自包含

正确做法:

good-example-skill/
├── SKILL.md
├── metadata.json
└── references/
    ├── advanced-patterns.md    # All about THIS skill
    ├── api-reference.md        # THIS skill's API
    └── examples.md             # THIS skill's examples

references/advanced-patterns.md 应包含:

# Advanced Testing Patterns

**Advanced pytest fixtures** (this skill):

```python
# Parametrized test fixture
@pytest.fixture(params=["value1", "value2"])
def data_variants(request):
    return request.param

def test_with_variants(data_variants):
    # Test with multiple data variants
    assert process(data_variants) is not None

进一步增强(如果已部署 pytest-patterns):

  • Fixture 工厂
  • 自定义标记
  • 插件集成

全面的高级模式请参阅 pytest-patterns 技能。


---

## ❌ VIOLATION #8: metadata.json with Skill Dependencies

```json
{
  "name": "bad-example-skill",
  "version": "1.0.0",
  "requires": [
    "setup-skill",
    "database-skill",
    "pytest-patterns"
  ],
  "self_contained": false,
  "dependencies": ["example-framework"],
  "notes": [
    "This skill requires setup-skill to be installed first",
    "Must deploy with database-skill for database operations",
    "Won't work without pytest-patterns for testing"
  ]
}

错误原因:

  • ❌ 在“requires”字段中列出其他技能
  • ❌ "self_contained": false
  • ❌ 说明中指出该技能缺少其他技能便无法运行
  • ❌ 造成部署耦合

正确做法:

{
  "name": "good-example-skill",
  "version": "1.0.0",
  "requires": [],
  "self_contained": true,
  "dependencies": ["example-framework", "pytest", "sqlalchemy"],
  "complementary_skills": [
    "setup-skill",
    "database-skill",
    "pytest-patterns"
  ],
  "notes": [
    "This skill is fully self-contained and works independently",
    "All essential patterns are inlined",
    "Complementary skills provide optional enhancements"
  ]
}

违规摘要

违规项示例影响
相对路径../../other-skill/在扁平化部署中失效
缺少内容“参见其他技能了解 X”内容不完整,无法独立运行
硬依赖“需要 other-skill”无法独立部署
跨技能导入from skills.other import运行时依赖
分层结构假设“导航到上级目录”依赖位置
不完整示例只有代码片段无法使用
引用跨技能references/ 中包含 ../渐进式披露失效
元数据依赖"requires": ["skill"]部署耦合

如何修正这些违规

第 1 步:移除所有相对路径
# Find violations
grep -r "\.\\./" bad-example-skill/

# Remove them - use skill names instead
# ❌ [skill](../../skill/SKILL.md)
# ✅ skill (if deployed)
第 2 步:内联必要内容
# Before (wrong):
## Testing
See pytest-patterns skill for all testing code.

# After (correct):
## Testing (Self-Contained)

**Essential pattern** (inlined):
[20-50 lines of actual testing code]

**Advanced patterns** (if pytest-patterns deployed):
- Feature list

*See pytest-patterns for comprehensive guide.*
第 3 步:移除硬依赖
# Before (wrong):
**Required Skills**: pytest-patterns, database-skill

# After (correct):
**Complementary Skills** (optional):
- pytest-patterns: Testing enhancements
- database-skill: ORM optimization
第 4 步:使导入内容自包含
# Before (wrong):
from skills.database import get_db_session

# After (correct):
@contextmanager
def get_db_session():
    """Inlined pattern."""
    # Implementation here
第 5 步:更新 metadata.json
// Before (wrong):
{
  "requires": ["other-skill"],
  "self_contained": false
}

// After (correct):
{
  "requires": [],
  "self_contained": true,
  "complementary_skills": ["other-skill"]
}

验证

修复后,验证内容是否自包含:

# Should return empty (no violations)
grep -r "\.\\./" skill-name/
grep -r "from skills\." skill-name/
grep -i "requires.*skill" skill-name/SKILL.md

# Isolation test
cp -r skill-name /tmp/skill-test/
cd /tmp/skill-test/skill-name
cat SKILL.md  # Should be complete and useful

# Metadata check
cat metadata.json | jq '.requires'  # Should be [] or external packages only

请参阅正确示例

请勿将此示例用作模板

请改为参阅:


请记住:此示例展示的是错误做法。请始终确保你的技能是自包含的!

评论

支持 Markdown