# https://github.com/goldzulu/skill-loader-mcp-server 项目说明书

生成时间：2026-05-18 02:39:22 UTC

## 目录

- [Getting Started](#getting-started)
- [Project Structure](#project-structure)
- [MCP Server Architecture](#mcp-server-architecture)
- [Core Modules](#core-modules)
- [MCP Tools Reference](#mcp-tools-reference)
- [Skill Discovery](#skill-discovery)
- [Security Validation](#security-validation)
- [Format Conversion](#format-conversion)
- [Caching System](#caching-system)
- [Type Definitions](#type-definitions)
- [Deployment and Configuration](#deployment)
- [Error Handling](#error-handling)

<a id='getting-started'></a>

## Getting Started

### 相关页面

相关主题：[Deployment and Configuration](#deployment), [MCP Server Architecture](#mcp-server-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
- [CONTRIBUTING.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CONTRIBUTING.md)
- [CHANGELOG.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CHANGELOG.md)
- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)
</details>

# Getting Started

The **Skill Loader MCP Server** is a Model Context Protocol (MCP) server that enables discovery, fetching, validation, and conversion of Claude Skills from the skills.sh marketplace into formats compatible with the Kiro platform. This guide provides everything you need to install, configure, and begin using the server effectively.

## Overview

The Skill Loader MCP Server acts as a bridge between the skills.sh marketplace and local skill management systems. It provides a unified interface for:

- Discovering available skills through search and browsing
- Fetching skill content directly from GitHub repositories
- Validating skill content for security issues before import
- Converting skills to Kiro steering file format or power format
- Performing complete end-to-end skill imports with a single command

资料来源：[README.md:1-10]()

### Architecture Overview

```mermaid
graph TD
    A[Client] -->|MCP Protocol| B[Skill Loader MCP Server]
    B --> C[Skills.sh API]
    B --> D[GitHub Raw Content]
    
    C -->|Search Results| E[list_skills]
    C -->|Trending Data| F[get_leaderboard]
    D -->|Raw .md| G[fetch_skill]
    
    G --> H[validate_skill]
    H -->|Safe| I[convert_to_steering]
    H -->|Safe| J[convert_to_power]
    
    I --> K[Kiro Steering Files]
    J --> L[Kiro Power Format]
    
    G --> M[import_skill]
    M --> H
    M -->|Validated| I
    M -->|Validated| J
```

## Prerequisites

Before installing the Skill Loader MCP Server, ensure your environment meets the following requirements:

| Requirement | Version/Details |
|-------------|------------------|
| Node.js | v18.0.0 or higher |
| npm or yarn | Latest stable version |
| Git | Installed and configured |
| Skills.sh API Key | Optional (required only for `list_skills` and `get_leerboard`) |

资料来源：[CONTRIBUTING.md:1-5]()

## Installation

### Global Installation

For system-wide access, install the package globally using npm:

```bash
npm install -g @goldzulu/skill-loader-mcp-server
```

资料来源：[README.md:30-32]()

### Local Installation

For project-specific usage, install locally:

```bash
npm install @goldzulu/skill-loader-mcp-server
```

资料来源：[README.md:34-36]()

## Configuration

### Environment Variables

The server uses a single environment variable for authenticated API access:

| Variable | Required | Description |
|----------|----------|-------------|
| `SKILLS_SH_API_KEY` | No | API key for the skills.sh authenticated `/api/v1/skills` endpoint. Required only for `list_skills` and `get_leaderboard` tools. Not required for `search_skills`. |

资料来源：[README.md:43-47]()

### Configuration with Kiro

Add the server to your Kiro configuration file (`mcp.json`):

```json
{
  "mcpServers": {
    "skill-loader": {
      "command": "npx",
      "args": ["-y", "@goldzulu/skill-loader-mcp-server"],
      "env": {
        "SKILLS_SH_API_KEY": "your-api-key-here"
      },
      "description": "Skill Loader MCP Server for managing Claude skills"
    }
  }
}
```

资料来源：[README.md:53-64]()

### Configuration with Claude Desktop

For Claude Desktop integration, add to your configuration:

```json
{
  "mcpServers": {
    "skill-loader": {
      "command": "skill-loader-mcp-server",
      "env": {
        "SKILLS_SH_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

资料来源：[README.md:70-80]()

## Available Tools

The server provides eight MCP tools for skill management. Each tool accepts JSON-formatted arguments and returns structured responses.

资料来源：[README.md:82-100]()

### Tool Overview

| Tool | Authentication | Purpose |
|------|----------------|---------|
| `search_skills` | Not required | Search skills by keyword |
| `list_skills` | Required | List all available skills with pagination |
| `get_leaderboard` | Required | Get trending or top-installed skills |
| `fetch_skill` | Not required | Fetch raw skill content from GitHub |
| `validate_skill` | Not required | Validate skill content for security issues |
| `convert_to_steering` | Not required | Convert skill to Kiro steering file format |
| `convert_to_power` | Not required | Convert skill to Kiro power format |
| `import_skill` | Not required | Complete import workflow (fetch + validate + convert) |

资料来源：[README.md:82-100]()

### 1. search_skills

Search for skills by keyword using the skills.sh public search API. No authentication required.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | - | Search query |
| `limit` | number | No | 20 | Maximum results (max: 50) |

**Example Request:**
```json
{
  "tool": "search_skills",
  "arguments": {
    "query": "pdf",
    "limit": 5
  }
}
```

**Example Response:**
```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400,
      "relevance": 5
    }
  ],
  "query": "pdf",
  "count": 5
}
```

资料来源：[examples/usage-examples.md:1-50]()

### 2. list_skills

List all available skills from skills.sh with pagination. Requires `SKILLS_SH_API_KEY`.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | number | No | 1 | Page number |
| `pageSize` | number | No | 50 | Results per page (max: 100) |

**Example Request:**
```json
{
  "tool": "list_skills",
  "arguments": {
    "page": 1,
    "pageSize": 10
  }
}
```

资料来源：[README.md:102-115]()

### 3. get_leaderboard

Get trending or top-installed skills. Requires `SKILLS_SH_API_KEY`.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `timeframe` | string | No | `'all'` | `'all'` or `'24h'` |
| `limit` | number | No | 20 | Maximum results (max: 50) |

**Example Request:**
```json
{
  "tool": "get_leaderboard",
  "arguments": {
    "timeframe": "24h",
    "limit": 10
  }
}
```

**Example Response:**
```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400,
      "rank": 1,
      "trending": true
    }
  ],
  "timeframe": "24h",
  "count": 10
}
```

资料来源：[examples/usage-examples.md:90-120]()

### 4. fetch_skill

Fetch raw skill content directly from GitHub. Supports both simple skill names and `owner/repo` format.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `identifier` | string | Yes | Skill name or `owner/repo` format |

**Example Request:**
```json
{
  "tool": "fetch_skill",
  "arguments": {
    "identifier": "anthropics/pdf-extractor"
  }
}
```

**Example Response:**
```json
{
  "content": "---\nname: PDF Extractor\ndescription: Extract text from PDF files\n---\n\n# PDF Extractor\n\n...",
  "url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md",
  "metadata": {
    "name": "pdf-extractor",
    "owner": "anthropics",
    "repo": "skills",
    "skillPath": "skills/pdf-extractor",
    "fetchedAt": "2024-01-15T10:30:00.000Z"
  }
}
```

资料来源：[examples/usage-examples.md:130-165]()

### 5. validate_skill

Validate skill content for security issues before importing. This tool scans for dangerous commands, suspicious patterns, and untrusted sources.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to validate |
| `url` | string | No | Source URL for verification |

**Example Request:**
```json
{
  "tool": "validate_skill",
  "arguments": {
    "content": "---\nname: Test\n---\n\n# Test",
    "url": "https://example.com/skill.md"
  }
}
```

**Security Checks Performed:**

| Check Type | Description |
|------------|-------------|
| `dangerous_command` | Commands like `rm -rf`, `sudo`, `eval`, `exec` |
| `suspicious_file_operation` | Access to system directories (`/etc/`, `/usr/`, `/bin/`) |
| `code_injection` | Patterns like `${...}`, `$(...)` |
| `untrusted_source` | Non-GitHub source URLs |

资料来源：[README.md:155-175]()

**Severity Levels:**

| Severity | Conditions |
|----------|------------|
| `safe` | No issues found |
| `warning` | Suspicious patterns detected |
| `unsafe` | Dangerous commands or untrusted sources |

资料来源：[src/core/security-validator.ts:1-30]()

### 6. convert_to_steering

Convert skill content to Kiro steering file format. This format adds metadata headers and preserves the original skill structure.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content |
| `sourceUrl` | string | No | Original source URL |

**Example Request:**
```json
{
  "tool": "convert_to_steering",
  "arguments": {
    "content": "---\nname: PDF Extractor\ndescription: Extract text from PDF files\n---\n\n# PDF Extractor\n\nExtract text content from PDF documents.",
    "sourceUrl": "https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md"
  }
}
```

资料来源：[examples/usage-examples.md:195-220]()

### 7. convert_to_power

Convert skill to Kiro power format. This generates additional configuration files based on skill complexity:

- **mcp.json**: Generated when the skill has dependencies or MCP server references
- **steering/ directory**: Generated when the skill has 3+ complex sections

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content |
| `sourceUrl` | string | No | Original source URL |

**Example Request:**
```json
{
  "tool": "convert_to_power",
  "arguments": {
    "content": "---\nname: Test\ndescription: A test skill\n---\n\n# Test",
    "sourceUrl": "https://example.com/skill.md"
  }
}
```

资料来源：[README.md:190-205]()

### 8. import_skill

Complete import workflow combining fetch, validate, and convert operations in a single command.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `identifier` | string | Yes | Skill identifier (`owner/skill-name` format) |
| `outputFormat` | string | Yes | `'steering'` or `'power'` |
| `skipValidation` | boolean | No | Skip security validation (default: false) |

**Example Request (Steering Format):**
```json
{
  "tool": "import_skill",
  "arguments": {
    "identifier": "anthropics/pdf-extractor",
    "outputFormat": "steering"
  }
}
```

**Example Response:**
```json
{
  "success": true,
  "content": "---\noriginal_skill: PDF Extractor\nsource_url: https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md\nimported_at: '2024-01-15T10:30:00.000Z'\n---\n\n...",
  "filename": "pdf-extractor.md",
  "targetPath": ".kiro/steering/pdf-extractor.md",
  "metadata": {
    "skillName": "PDF Extractor",
    "sourceUrl": "https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md",
    "outputFormat": "steering",
    "validationResult": {
      "isValid": true,
      "issues": [],
      "severity": "safe"
    }
  }
}
```

资料来源：[examples/usage-examples.md:250-280]()

## Common Workflows

### Discovery and Import Workflow

```mermaid
graph LR
    A[Search Skills] --> B[Find Interesting Skill]
    B --> C[Fetch Skill]
    C --> D{Validate}
    D -->|Issues Found| E[Review Security Issues]
    D -->|Safe| F[Choose Format]
    E -->|Override| F
    F --> G[Import as Steering]
    F --> H[Import as Power]
```

### Quick Start: Discover and Import

1. Search for skills by keyword:
```json
{ "tool": "search_skills", "arguments": { "query": "pdf", "limit": 20 } }
```

2. Import a trending skill:
```json
{ "tool": "import_skill", "arguments": { "identifier": "owner/skill-name", "outputFormat": "power" } }
```

### Validate Before Importing

1. Fetch the skill:
```json
{ "tool": "fetch_skill", "arguments": { "identifier": "unknown/skill" } }
```

2. Validate the content:
```json
{ "tool": "validate_skill", "arguments": { "content": "...", "url": "..." } }
```

3. If safe, convert and use:
```json
{ "tool": "convert_to_steering", "arguments": { "content": "...", "sourceUrl": "..." } }
```

资料来源：[examples/usage-examples.md:330-360]()

## Caching

The server implements in-memory caching for skills.sh search results to reduce API calls and improve performance.

| Cache Property | Value |
|----------------|-------|
| Storage | In-memory |
| TTL | 1 hour |
| Refresh | Automatic on expiration |

资料来源：[README.md:180-182]()

## Error Handling

All tools return errors in a consistent format:

```json
{
  "error": "Error message describing what went wrong",
  "tool": "tool_name",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

### Common Error Scenarios

| Error Type | Resolution |
|------------|------------|
| Network errors | Check internet connection, GitHub availability |
| Not found errors | Verify skill name and repository |
| Validation errors | Review security issues before proceeding |
| Parsing errors | Check skill format and YAML syntax |

资料来源：[examples/usage-examples.md:365-375]()

## Development Setup

For local development and contribution:

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test
```

资料来源：[CONTRIBUTING.md:8-14]()

### Project Structure

```
skill-loader-mcp-server/
├── src/
│   ├── core/           # Core functionality
│   │   ├── conversion-engine.ts
│   │   ├── security-validator.ts
│   │   └── errors.ts
│   ├── tools/          # MCP tool implementations
│   ├── utils/          # Utility functions
│   ├── index.ts        # Main entry point
│   └── cli.ts          # CLI entry point
├── examples/           # Usage examples
├── dist/               # Compiled output
└── tests/              # Test files
```

资料来源：[CONTRIBUTING.md:16-28]()

## Supported Versions

| Version | Status | Notes |
|---------|--------|-------|
| 1.1.0 | Latest | Updated to `@modelcontextprotocol/sdk` v1.29 |
| 1.0.0 | Previous | Initial release |

资料来源：[CHANGELOG.md:1-10]()

## Next Steps

- Review the [Usage Examples](examples/usage-examples.md) for detailed tool demonstrations
- Check the [CONTRIBUTING.md](CONTRIBUTING.md) if you wish to contribute to the project
- Explore the [CHANGELOG.md](CHANGELOG.md) for version history and recent changes

---

<a id='project-structure'></a>

## Project Structure

### 相关页面

相关主题：[Getting Started](#getting-started), [Core Modules](#core-modules)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/index.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/index.ts)
- [src/cli.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/cli.ts)
- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
- [CONTRIBUTING.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CONTRIBUTING.md)
</details>

# Project Structure

The skill-loader-mcp-server is a Model Context Protocol (MCP) server that enables discovery, fetching, validation, and conversion of Claude skills from the skills.sh marketplace. The project follows a modular architecture with clear separation between core functionality, MCP tool implementations, and utility modules.

## Architecture Overview

The server is built on the `@modelcontextprotocol/sdk` framework and exposes 9 MCP tools for skill management operations. The architecture follows a layered pattern where the core layer handles business logic, the tools layer exposes MCP-compatible interfaces, and the utils layer provides shared functionality.

```mermaid
graph TD
    A[Client] --> B[MCP Server Entry]
    B --> C[Tool Handlers]
    C --> D[Core Services]
    C --> E[SkillResolver]
    C --> F[ConversionEngine]
    C --> G[SecurityValidator]
    D --> H[skills.sh API]
    D --> I[GitHub API]
    G --> J[Error System]
```

## Directory Structure

```
skill-loader-mcp-server/
├── src/
│   ├── core/           # Core business logic
│   ├── tools/          # MCP tool implementations
│   ├── utils/          # Utility functions
│   ├── index.ts        # Main entry point
│   └── cli.ts          # CLI entry point
├── examples/           # Usage examples
├── dist/               # Compiled output
├── tests/              # Test files
├── package.json
└── tsconfig.json
```

### Source Directory Organization

The `src/` directory contains the primary application code organized into functional layers:

| Directory | Purpose | Key Files |
|-----------|---------|-----------|
| `core/` | Business logic and domain operations | `conversion-engine.ts`, `security-validator.ts`, `errors.ts` |
| `tools/` | MCP tool handler implementations | Tool definitions and handlers |
| `utils/` | Shared utility functions | Parsers, helpers, constants |

## Entry Points

The project provides two entry points for different execution contexts.

### Main Entry Point (index.ts)

The primary entry point initializes the MCP server with stdio transport and registers all available tools. This is the standard entry used when the server runs as an MCP server integration.

```typescript
// Conceptual structure from src/index.ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server(
  { name: 'skill-loader', version: '1.1.0' },
  { capabilities: { tools: {} } }
);

// Register tools and start transport
const transport = new StdioServerTransport();
await server.connect(transport);
```

资料来源：[CONTRIBUTING.md:23-24]()

### CLI Entry Point (cli.ts)

The CLI entry point provides standalone execution capability, allowing the server to run as a command-line utility. This is useful for direct invocation and debugging scenarios.

资料来源：[CONTRIBUTING.md:19]()

## Core Layer Modules

### Conversion Engine

The conversion engine (`src/core/conversion-engine.ts`) handles transformation of skills between different formats. It supports conversion to steering files and power formats with additional generation capabilities.

**Key Responsibilities:**

- Parse YAML frontmatter and markdown body from skill content
- Convert to Kiro steering file format with metadata preservation
- Generate POWER.md content with dependencies section
- Create `mcp.json` for skills with dependencies or tool references
- Generate `steering/` directory for skills with multiple complex sections
- Extract keywords from descriptions for metadata

**Conversion Output Formats:**

| Format | Output File | Generation Triggers |
|--------|-------------|---------------------|
| Steering | `filename.md` | Standard conversion |
| Power | `POWER.md` | Power format conversion |
| MCP Config | `mcp.json` | Skills with dependencies or MCP server references |
| Steering Directory | `steering/*.md` | Skills with 3+ complex sections |

资料来源：[src/core/conversion-engine.ts:1-200]()

### Security Validator

The security validator (`src/core/security-validator.ts`) scans skill content for potential security threats before import. It provides a consistent validation interface across all import operations.

**Security Checks Performed:**

| Check Type | Description | Severity |
|------------|-------------|----------|
| `dangerous_command` | Commands like `rm -rf`, `sudo`, `eval`, `exec` | unsafe |
| `suspicious_path` | Access to system paths (`/etc/`, `/usr/`, `/bin/`) | unsafe |
| `code_injection` | Injection patterns (`${...}`, `$(...)`) | warning |
| `untrusted_source` | Non-GitHub URLs | unsafe |

**Severity Levels:**

- **safe**: No issues detected
- **warning**: Suspicious patterns found, import allowed
- **unsafe**: Dangerous patterns detected, import blocked

资料来源：[src/core/security-validator.ts:1-100]()

### Error Handling System

The error system (`src/core/errors.ts`) provides structured error types with recovery suggestions. All errors extend a base `SkillLoaderError` class with context tracking.

**Error Hierarchy:**

| Error Class | Use Case | Context Fields |
|-------------|----------|----------------|
| `NetworkError` | GitHub/API connectivity failures | `statusCode`, `url` |
| `ValidationError` | Format, security, schema issues | `validationType`, `details` |
| `FileSystemError` | Permission, disk, path issues | `operation`, `filePath` |
| `SkillLoaderError` | Base class for all errors | `operation`, `timestamp` |

资料来源：[src/core/errors.ts:1-150]()

## Tool Layer

The tools layer implements MCP-compatible handlers that expose core functionality to MCP clients. Each tool follows a consistent pattern of parameter validation, execution, and response formatting.

### Available MCP Tools

| Tool | Purpose | Authentication Required |
|------|---------|------------------------|
| `search_skills` | Search skills.sh by keyword | No |
| `list_skills` | Paginated listing of all skills | Yes (API key) |
| `get_leaderboard` | Trending/top-installed skills | Yes (API key) |
| `fetch_skill` | Download skill content from GitHub | No |
| `validate_skill` | Security scan for dangerous patterns | No |
| `convert_to_steering` | Convert to Kiro steering format | No |
| `convert_to_power` | Convert to Kiro power format | No |
| `import_skill` | Complete workflow (fetch + validate + convert) | No |

资料来源：[README.md:40-120]()

## Data Flow

```mermaid
sequenceDiagram
    participant Client
    participant Server
    participant Resolver
    participant Validator
    participant Converter
    participant External

    Client->>Server: import_skill(identifier, format)
    Server->>Resolver: fetchSkill(identifier)
    Resolver->>External: GET GitHub raw content
    External-->>Resolver: SKILL.md content
    Resolver-->>Server: rawContent
    Server->>Validator: validate(content, url)
    Validator-->>Server: ValidationResult
    Server->>Converter: convert(content, format, url)
    Converter-->>Server: ConvertResult
    Server-->>Client: ImportResult

    alt skipValidation = true
        Server->>Converter: Skip validation
    end
```

## Module Dependencies

```mermaid
graph TD
    A[index.ts] --> B[tools/*]
    B --> C[core/ConversionEngine]
    B --> D[core/SkillResolver]
    B --> E[core/SecurityValidator]
    C --> F[core/errors.ts]
    D --> F
    E --> F
    C --> G[utils/*]
    D --> G
```

## Configuration

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `SKILLS_SH_API_KEY` | For `list_skills` and `get_leaderboard` only | API key for authenticated skills.sh API endpoint |

资料来源：[README.md:28-35]()

### TypeScript Configuration

The project uses TypeScript with strict mode enabled. Key configuration in `tsconfig.json`:

- ES2022 target for modern JavaScript features
- ES modules (`module: nodenext`)
- Strict type checking enabled
- Path aliases for clean imports

资料来源：[tsconfig.json](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/tsconfig.json)

## Build and Deployment

### Build Process

```bash
# Install dependencies
npm install

# Build TypeScript
npm run build

# Output to dist/ directory
```

### Deployment Targets

| Target | Entry Point | Transport |
|--------|-------------|-----------|
| Kiro MCP | `index.ts` | stdio |
| Claude Desktop | `index.ts` | stdio |
| Standalone CLI | `cli.ts` | stdio/terminal |

资料来源：[README.md:20-55]()

## Testing Structure

The `tests/` directory follows the project structure with test files mirroring source file organization. Tests use descriptive naming and follow the pattern:

```
tests/
├── core/
│   ├── conversion-engine.test.ts
│   ├── security-validator.test.ts
│   └── errors.test.ts
└── tools/
    └── *.test.ts
```

资料来源：[CONTRIBUTING.md:80-100]()

## Summary

The project architecture emphasizes separation of concerns with a clear hierarchy from entry points through tool handlers to core services. The core layer is framework-agnostic and handles all business logic including skill fetching, validation, and conversion. The tools layer provides MCP-compatible interfaces while delegating to core services. This design allows for easy testing, maintainability, and extension of new features.

---

<a id='mcp-server-architecture'></a>

## MCP Server Architecture

### 相关页面

相关主题：[MCP Tools Reference](#mcp-tools-reference), [Getting Started](#getting-started)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/index.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/index.ts)
- [src/cli.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/cli.ts)
- [package.json](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/package.json)
- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)
- [README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)
- [CHANGELOG.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CHANGELOG.md)
</details>

# MCP Server Architecture

The Skill Loader MCP Server is a Model Context Protocol (MCP) server implementation that enables AI assistants to discover, fetch, validate, and import Claude skills from the skills.sh marketplace. Built on the `@modelcontextprotocol/sdk`, it provides a comprehensive toolset for skill management with enterprise-grade security validation.

## Architecture Overview

The server follows a layered architecture pattern with clear separation between the transport layer, tool handlers, core services, and utilities.

```mermaid
graph TD
    subgraph Transport Layer
        STDIO[Stdio Transport]
        HTTP[HTTP/SSE Transport]
    end

    subgraph MCP SDK
        Server[MCP Server Instance]
        Handlers[Request Handlers]
    end

    subgraph Core Services
        SR[SkillResolver]
        SV[SecurityValidator]
        CE[ConversionEngine]
        Cache[In-Memory Cache]
    end

    subgraph External Services
        SkillsAPI[skills.sh API]
        GitHub[GitHub API]
    end

    STDIO --> Server
    HTTP --> Server
    Server --> Handlers
    Handlers --> SR
    Handlers --> SV
    Handlers --> CE
    SR --> Cache
    SR --> SkillsAPI
    SR --> GitHub
    CE --> SV
```

### Core Components

| Component | Responsibility | Key Files |
|-----------|---------------|-----------|
| **MCP Server** | Protocol handling, request routing | `src/index.ts` |
| **CLI Entry** | Application bootstrap | `src/cli.ts` |
| **SkillResolver** | Fetches skills from GitHub and skills.sh API | Core service |
| **SecurityValidator** | Scans for dangerous patterns | `src/core/security-validator.ts` |
| **ConversionEngine** | Transforms skill formats | `src/core/conversion-engine.ts` |
| **Error System** | Unified error handling | `src/core/errors.ts` |

## Server Initialization

The server is initialized with the `@modelcontextprotocol/sdk` version 1.29 and configured with stdio transport for maximum compatibility.

```typescript
// Simplified initialization pattern
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  { name: "skill-loader", version: "1.x.x" },
  { capabilities: { tools: {} } }
);

const transport = new StdioServerTransport();
await server.connect(transport);
```

资料来源：[README.md:1-50]()

The server supports both stdio transport (for CLI and desktop integrations) and can be configured for HTTP/SSE transport when deployed as a network service.

## Tool System

The server exposes 8 MCP tools that provide complete skill management capabilities:

### Tool Overview

| Tool | Purpose | Authentication Required |
|------|---------|------------------------|
| `search_skills` | Search marketplace by keyword | No |
| `list_skills` | Paginated skill directory | Yes (API Key) |
| `get_leaderboard` | Trending/popular skills | Yes (API Key) |
| `fetch_skill` | Download skill content from GitHub | No |
| `validate_skill` | Security scan skill content | No |
| `convert_to_steering` | Transform to Kiro steering format | No |
| `convert_to_power` | Transform to Kiro power format | No |
| `import_skill` | Complete workflow (fetch + validate + convert) | No |

资料来源：[README.md:50-120]()

### Tool Request Flow

```mermaid
sequence diagram
    participant Client
    participant Server
    participant Resolver
    participant Validator
    participant Converter

    Client->>Server: tool_request
    Server->>Resolver: fetch/resolve skill
    Resolver-->>Server: raw content
    Server->>Validator: scan content
    alt Validation Failed
        Server-->>Client: error with issues
    else Validation Passed
        Server->>Converter: transform content
        Converter-->>Server: formatted output
    end
    Server-->>Client: tool_response
```

## Core Services

### SkillResolver

The `SkillResolver` service handles all interactions with external skill sources. It provides:

- **GitHub Resolution**: Parse `owner/repo` identifiers to fetch raw skill content
- **skills.sh API Integration**: Query marketplace for search, listing, and leaderboard
- **Content Fetching**: Retrieve raw SKILL.md files from GitHub repositories

```typescript
interface ISkillResolver {
  resolveGitHub(identifier: string): Promise<SkillContent>;
  searchSkills(query: string, limit: number): Promise<SearchResult[]>;
  listSkills(page: number, pageSize: number): Promise<PaginatedResult>;
  getLeaderboard(timeframe: string, limit: number): Promise<LeaderboardEntry[]>;
}
```

资料来源：[src/core/conversion-engine.ts:1-50]()

The resolver supports the skills.sh API v1 responses with types including `SkillsShV1Response`, `SkillsShV1Entry`, and extends `SkillShEntry` with additional fields like `id`, `skillId`, and `source`.

### SecurityValidator

The `SecurityValidator` service performs comprehensive security scanning on skill content before import.

```typescript
interface ValidationIssue {
  type: 'dangerous_command' | 'suspicious_pattern' | 'untrusted_source';
  description: string;
  severity: 'critical' | 'warning' | 'info';
  lineNumber?: number;
  location?: string;
}
```

资料来源：[src/core/security-validator.ts:1-80]()

#### Security Checks Performed

| Check Type | Patterns Detected | Severity |
|------------|-------------------|----------|
| **Dangerous Commands** | `rm -rf`, `sudo`, `eval`, `exec` | Critical |
| **Suspicious File Operations** | `/etc/`, `/usr/`, `/bin/` paths | Warning |
| **Code Injection** | `${...}`, `$(...)` patterns | Critical |
| **Untrusted Sources** | Non-GitHub URLs | Critical |

#### Severity Determination

The validator calculates overall severity based on detected issues:

- **Safe**: No issues found
- **Warning**: Only suspicious patterns detected
- **Unsafe**: Dangerous commands or untrusted sources present

资料来源：[src/core/security-validator.ts:80-100]()

### ConversionEngine

The `ConversionEngine` transforms Claude skills into Kiro-compatible formats. It supports two output formats:

#### Steering Format

Converts skills to Kiro steering file format:
- Preserves skill body content
- Adds YAML frontmatter with original skill metadata
- Includes dependencies section if present
- Adds import attribution footer

```typescript
interface SteeringOutput {
  filename: string;        // kebab-case derived from skill name
  content: string;         // Full steering file content
  metadata: {
    originalSkill: string;
    sourceUrl?: string;
    importedAt: string;     // ISO timestamp
  };
}
```

资料来源：[src/core/conversion-engine.ts:50-150]()

#### Power Format

Converts skills to Kiro power format with enhanced capabilities:

- **POWER.md**: Primary power definition file
- **mcp.json** (optional): Generated when skill has dependencies or MCP server references
- **steering/ directory** (optional): Generated for skills with 3+ complex sections

```typescript
interface PowerOutput {
  filename: string;         // "POWER.md"
  content: string;          // Power content with metadata
  files?: Array<{
    path: string;
    content: string;
  }>;
}
```

资料来源：[src/core/conversion-engine.ts:150-250]()

#### Format Selection Logic

| Condition | Output Format |
|-----------|--------------|
| Skill has no dependencies | Single `STEERING.md` file |
| Skill has dependencies/tools | `STEERING.md` + `mcp.json` |
| 3+ complex sections (>200 chars) | Steering directory structure |
| Full power workflow | `POWER.md` + optional `mcp.json` + optional `steering/` |

资料来源：[src/core/conversion-engine.ts:250-300]()

## Error Handling System

The server implements a hierarchical error system with specialized error classes for different failure modes.

```mermaid
graph TD
    SkillLoaderError[SkillLoaderError]
    NetworkError[NetworkError]
    ValidationError[ValidationError]
    FileSystemError[FileSystemError]
    SkillLoaderError --> NetworkError
    SkillLoaderError --> ValidationError
    SkillLoaderError --> FileSystemError
```

### Error Class Hierarchy

| Error Class | HTTP Code Support | Use Case |
|-------------|------------------|----------|
| `SkillLoaderError` | Base class | All errors |
| `NetworkError` | 404, 403, 5xx | GitHub/API failures |
| `ValidationError` | N/A | Format, schema, security issues |
| `FileSystemError` | N/A | Permission, disk, path issues |

资料来源：[src/core/errors.ts:1-100]()

### Error Response Format

```json
{
  "error": "Error message describing what went wrong",
  "tool": "tool_name",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

All errors include recovery suggestions based on error type and context.

## Caching Mechanism

The server implements in-memory caching for the skills.sh directory to reduce API calls and improve performance.

| Cache Property | Value |
|---------------|-------|
| **Storage** | In-memory Map |
| **TTL** | 1 hour |
| **Scope** | Search results |
| **Refresh** | Automatic on expiration |

资料来源：[README.md:180-200]()

Cache invalidation is automatic when the TTL expires. No manual cache clearing is required.

## Configuration and Deployment

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `SKILLS_SH_API_KEY` | For list/leaderboard only | Authentication for authenticated API endpoints |

### Deployment Targets

```mermaid
graph LR
    subgraph Deployment Options
        Kiro[Kiro MCP Config]
        Claude[Claude Desktop]
        CLI[Standalone CLI]
    end

    Kiro --> STDIO
    Claude --> STDIO
    CLI --> STDIO
```

#### Kiro Configuration

```json
{
  "mcpServers": {
    "skill-loader": {
      "command": "npx",
      "args": ["-y", "@goldzulu/skill-loader-mcp-server"],
      "env": {
        "SKILLS_SH_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

#### Claude Desktop Configuration

```json
{
  "mcpServers": {
    "skill-loader": {
      "command": "skill-loader-mcp-server",
      "env": {
        "SKILLS_SH_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

资料来源：[README.md:30-80]()

## Project Structure

```
skill-loader-mcp-server/
├── src/
│   ├── core/               # Core business logic
│   │   ├── conversion-engine.ts
│   │   ├── errors.ts
│   │   └── security-validator.ts
│   ├── tools/              # MCP tool implementations
│   ├── utils/              # Utility functions
│   ├── index.ts            # Server entry point
│   └── cli.ts              # CLI entry point
├── examples/               # Usage examples
├── tests/                  # Test suite
├── dist/                   # Compiled output
├── package.json
└── tsconfig.json
```

资料来源：[CONTRIBUTING.md:1-30]()

## Dependencies

The server relies on the following key dependencies:

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | ^1.29 | MCP protocol implementation |
| `yaml` | Latest | YAML frontmatter parsing |
| `typescript` | Latest | Type safety |

资料来源：[package.json](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/package.json)

## Complete Import Workflow

```mermaid
graph TD
    A[Start: identifier] --> B[Fetch Skill from GitHub]
    B --> C{skipValidation?}
    C -->|No| D[Security Validation]
    C -->|Yes| E[Skip Validation]
    D --> F{isValid?}
    F -->|No| G[Return Error with Issues]
    F -->|Yes| E
    E --> H{outputFormat?}
    H -->|steering| I[Convert to Steering]
    H -->|power| J[Convert to Power]
    I --> K[Add Steering Metadata]
    J --> L[Generate Power Files]
    L --> M{mcp.json needed?}
    L --> N{steering/ needed?}
    M -->|Yes| O[Generate mcp.json]
    M -->|No| P[Skip mcp.json]
    N -->|Yes| Q[Generate steering/]
    N -->|No| R[Skip steering/]
    O --> S[Return Result]
    P --> S
    Q --> S
    R --> S
```

The complete workflow is exposed through the `import_skill` tool, which orchestrates fetch, validation, and conversion in a single operation.

资料来源：[examples/usage-examples.md:100-150]()

## Version History

| Version | Date | Key Changes |
|---------|------|-------------|
| 1.1.0 | 2026-02-XX | Added mcp.json and steering/ generation |
| 1.0.0 | 2026-02-03 | Initial release with 8 core tools |

资料来源：[CHANGELOG.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CHANGELOG.md)

---

<a id='core-modules'></a>

## Core Modules

### 相关页面

相关主题：[Format Conversion](#format-conversion), [Security Validation](#security-validation)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
- [src/core/conversion-engine.test.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.test.ts)
</details>

# Core Modules

The Core Modules of the skill-loader-mcp-server form the foundational layer responsible for skill fetching, parsing, security validation, and format conversion. These modules work together to provide a secure pipeline for importing Claude skills into the Kiro ecosystem.

## Architecture Overview

```mermaid
graph TD
    A[Skill Input] --> B[Skill Fetcher]
    B --> C[Skill Resolver]
    C --> D[Conversion Engine]
    D --> E[Steering Format]
    D --> F[Power Format]
    G[Security Validator] --> D
    G --> C
    H[Error Handler] --> B
    H --> C
    H --> D
    H --> G
```

## Module Components

### 1. Conversion Engine (`conversion-engine.ts`)

The Conversion Engine is responsible for transforming parsed skill content into different output formats suitable for various use cases.

#### Key Methods

| Method | Purpose | Output |
|--------|---------|--------|
| `parseSkill(content)` | Parses YAML frontmatter and markdown body | `ParsedSkill` object |
| `toSteeringFile(skill, sourceUrl?)` | Converts to Kiro steering format | Steering file with metadata |
| `toPower(skill, sourceUrl?)` | Converts to Kiro power format | Power files including `POWER.md` |
| `extractKeywords(description)` | Extracts 3+ char meaningful words | Array of keywords |
| `shouldGenerateMcpJson(skill)` | Determines if MCP config needed | Boolean |
| `shouldGenerateSteeringDir(skill)` | Checks for complex sections | Boolean |

#### Steering File Conversion

The steering file format preserves the original skill structure with kebab-case naming:

```typescript
// Transformation rules:
// 1. Convert to lowercase
// 2. Replace spaces and underscores with hyphens
// 3. Remove special characters (keep only a-z, 0-9, and hyphens)
// 4. Collapse multiple consecutive hyphens into one
// 5. Remove leading and trailing hyphens

"PDF Extractor" → "pdf-extractor"
"React_Best_Practices" → "react-best-practices"
```

资料来源：[src/core/conversion-engine.ts:1-50]()

#### Power Format Generation

The power format generates a more structured output:

```typescript
// Power structure includes:
// 1. POWER.md - Main content with displayName frontmatter
// 2. mcp.json - (optional) MCP server configuration
// 3. steering/ - (optional) Directory with complex sections
```

资料来源：[src/core/conversion-engine.ts:150-200]()

#### Steering Directory Generation Logic

The engine generates a `steering/` directory when the skill has 3+ complex sections (level ≥ 2 with content > 200 characters):

```typescript
if (this.shouldGenerateSteeringDir(skill)) {
  const steeringContent = this.generateSteeringContent(skill);
  // Creates individual files for each complex section
}
```

资料来源：[src/core/conversion-engine.test.ts:1-50]()

---

### 2. Security Validator (`security-validator.ts`)

The Security Validator provides comprehensive threat detection for skill content before processing.

#### Validation Rules

| Check Type | Patterns Detected | Severity |
|------------|-------------------|----------|
| Dangerous Commands | `rm -rf`, `sudo`, `eval`, `exec` | `unsafe` |
| Suspicious File Operations | `/etc/`, `/usr/`, `/bin/` | `warning` |
| Code Injection | `${...}`, `$(...)` | `warning` |
| Untrusted Sources | Non-GitHub URLs | `unsafe` |

#### Severity Levels

```typescript
'safe'    // No issues found
'warning' // Suspicious patterns detected
'unsafe'  // Dangerous commands or untrusted sources
```

资料来源：[src/core/security-validator.ts:1-50]()

#### Validation Flow

```mermaid
graph LR
    A[Skill Content] --> B{Untrusted Source?}
    B -->|Yes| C[Mark unsafe]
    B -->|No| D{Dangerous Command?}
    D -->|Yes| C
    D -->|No| E{Suspicious Patterns?}
    E -->|Yes| F[Mark warning]
    E -->|No| G[Mark safe]
```

资料来源：[src/core/security-validator.ts:50-100]()

#### Line Number Detection

The validator can pinpoint exact locations of issues:

```typescript
private getLineNumber(content: string, index: number): number {
  const lines = content.substring(0, index).split('\n');
  return lines.length;
}
```

---

### 3. Error Handling System (`errors.ts`)

The error system provides structured error handling across all core modules.

#### Error Class Hierarchy

```mermaid
classDiagram
    class SkillLoaderError {
        +string tool
        +string timestamp
        +Record context
        +getUserMessage() string
    }
    class ValidationError {
        +ValidationType validationType
        +ValidationResult result
    }
    class FileSystemError {
        +Operation operation
        +string filePath
        +string systemError?
    }
    class ParsingError {
        +ParsingType parsingType
        +string rawContent
    }
    
    SkillLoaderError <|-- ValidationError
    SkillLoaderError <|-- FileSystemError
    SkillLoaderError <|-- ParsingError
```

#### ValidationError

Handles security and format validation failures:

```typescript
export class ValidationError extends SkillLoaderError {
  public readonly validationType: 'security' | 'format';
  public readonly result: ValidationResult;
}
```

**Recovery suggestions:**
- Security: Review content manually, contact author, use trusted sources
- Format: Verify YAML syntax, check Agent Skills standard compliance

#### FileSystemError

Handles file system operations:

```typescript
export class FileSystemError extends SkillLoaderError {
  public readonly operation: 'read' | 'write' | 'delete' | 'access';
  public readonly filePath: string;
  public readonly systemError?: string;
}
```

**Error codes handled:**

| Code | Cause | Resolution |
|------|-------|------------|
| `EACCES`/`EPERM` | Permission denied | Check file permissions |
| `ENOSPC` | Disk full | Free up space |
| `ENOENT` | Path not found | Verify directory exists |
| `EEXIST` | File exists | Use overwrite flag |

资料来源：[src/core/errors.ts:1-100]()

#### ParsingError

Handles YAML and markdown parsing issues:

```typescript
export class ParsingError extends SkillLoaderError {
  public readonly parsingType: 'yaml' | 'markdown' | 'frontmatter' | 'metadata';
}
```

---

### 4. Skill Fetcher (`skill-fetcher.ts`)

The Skill Fetcher retrieves raw skill content from GitHub repositories.

#### Fetch Resolution Logic

Skills can be referenced by:
- **Simple name**: `pdf-extractor` (resolves to `anthropics/skills`)
- **Full path**: `owner/repo/skill-name`

The resolver determines the correct GitHub URL and path structure.

资料来源：[README.md:1-50]()

---

### 5. Skill Resolver (`skill-resolver.ts`)

The Skill Resolver handles skill identification and API interactions with skills.sh.

#### API Methods

| Method | Description | Auth Required |
|--------|-------------|---------------|
| `listSkills()` | Paginated skill listing | Yes |
| `searchSkills()` | Public keyword search | No |
| `getLeaderboard()` | Trending skills | Yes |

资料来源：[README.md:50-100]()

#### Type Definitions

```typescript
interface SkillsShV1Response {
  skills: SkillsShV1Entry[];
  total: number;
}

interface SkillsShV1Entry {
  id: string;
  skillId: string;
  source: string;
  // ... additional fields
}
```

---

## Data Flow

```mermaid
sequenceDiagram
    participant User
    participant Fetcher
    participant Resolver
    participant Validator
    participant Converter
    participant Output

    User->>Resolver: search_skills(query)
    Resolver-->>User: skill list

    User->>Fetcher: fetch_skill(identifier)
    Fetcher->>Resolver: resolve owner/repo
    Resolver-->>Fetcher: resolved URL
    Fetcher-->>User: raw content

    User->>Validator: validate_skill(content)
    Validator->>Validator: scan patterns
    Validator-->>User: ValidationResult

    User->>Converter: convert_to_power(content)
    Converter->>Validator: re-validate
    Validator-->>Converter: isValid
    alt is valid
        Converter->>Converter: generate POWER.md
        alt has dependencies
            Converter->>Converter: generate mcp.json
        end
        alt has complex sections
            Converter->>Converter: generate steering/
        end
        Converter-->>Output: files array
    else is invalid
        Converter-->>User: ValidationError
    end
```

---

## Configuration

### Environment Variables

| Variable | Required | Module | Description |
|----------|----------|--------|-------------|
| `SKILLS_SH_API_KEY` | For list/leaderboard | SkillResolver | API key for authenticated endpoints |

### Caching

The resolver caches skills.sh search results:
- **TTL**: 1 hour
- **Scope**: In-memory
- **Purpose**: Reduce API calls, improve performance

---

## Testing

The core modules include comprehensive test coverage:

```typescript
describe('ConversionEngine', () => {
  describe('toPower', () => {
    it('converts parsed skill to power format', () => { /* ... */ });
    it('generates mcp.json when skill has dependencies', () => { /* ... */ });
    it('does not generate mcp.json when skill has no dependencies', () => { /* ... */ });
  });
});
```

资料来源：[src/core/conversion-engine.test.ts:1-100]()

---

## Integration Points

The Core Modules expose functionality through MCP tools:

| Tool | Primary Module | Purpose |
|------|---------------|---------|
| `search_skills` | SkillResolver | Discover skills |
| `list_skills` | SkillResolver | Browse marketplace |
| `get_leaderboard` | SkillResolver | Trending skills |
| `fetch_skill` | SkillFetcher | Download content |
| `validate_skill` | SecurityValidator | Security scan |
| `convert_to_steering` | ConversionEngine | Steering format |
| `convert_to_power` | ConversionEngine | Power format |
| `import_skill` | All modules | Complete workflow |

---

<a id='mcp-tools-reference'></a>

## MCP Tools Reference

### 相关页面

相关主题：[MCP Server Architecture](#mcp-server-architecture), [Skill Discovery](#skill-discovery)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/tools/list-skills.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/list-skills.ts)
- [src/tools/search-skills.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/search-skills.ts)
- [src/tools/get-leaderboard.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/get-leaderboard.ts)
- [src/tools/fetch-skill.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/fetch-skill.ts)
- [src/tools/validate-skill.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/validate-skill.ts)
- [src/tools/convert-to-steering.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/convert-to-steering.ts)
- [src/tools/convert-to-power.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/convert-to-power.ts)
- [src/tools/import-skill.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/import-skill.ts)
</details>

# MCP Tools Reference

The Skill Loader MCP Server provides a comprehensive suite of 8 Model Context Protocol (MCP) tools for discovering, fetching, validating, and converting Claude skills from the skills.sh marketplace. These tools enable seamless integration between the skills.sh ecosystem and the Kiro AI platform's steering file and power formats.

## Overview

The MCP Tools form the core interface of the Skill Loader MCP Server, providing programmatic access to the skills.sh API and GitHub-hosted skill repositories. Each tool serves a specific purpose in the skill management lifecycle, from discovery to import.

```mermaid
graph TD
    A[Skills Discovery] --> B[search_skills]
    A --> C[list_skills]
    A --> D[get_leaderboard]
    E[Skill Retrieval] --> F[fetch_skill]
    G[Security] --> H[validate_skill]
    I[Conversion] --> J[convert_to_steering]
    I --> K[convert_to_power]
    L[Workflow] --> M[import_skill]
    
    F --> H
    H --> J
    H --> K
    M --> F
    M --> H
    M --> J
    M --> K
```

### Tool Categories

| Category | Tools | Purpose |
|----------|-------|---------|
| Discovery | `search_skills`, `list_skills`, `get_leaderboard` | Find and browse available skills |
| Retrieval | `fetch_skill` | Download skill content from GitHub |
| Security | `validate_skill` | Scan for dangerous commands and patterns |
| Conversion | `convert_to_steering`, `convert_to_power` | Transform skills to Kiro formats |
| Workflow | `import_skill` | Execute complete import workflow |

资料来源：[README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)

## Discovery Tools

### search_skills

Search for skills by keyword using the skills.sh search API. This tool requires no authentication and provides immediate access to the skill marketplace.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | - | Search query string |
| `limit` | number | No | 20 | Maximum results (max: 50) |

**Response Schema:**

```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400,
      "relevance": 5
    }
  ],
  "query": "pdf",
  "count": 5
}
```

**Example Request:**

```json
{
  "tool": "search_skills",
  "arguments": {
    "query": "pdf",
    "limit": 5
  }
}
```

资料来源：[examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)

### list_skills

List all available skills from skills.sh with pagination support. This tool requires the `SKILLS_SH_API_KEY` environment variable for authenticated access to the paginated directory endpoint.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | number | No | 1 | Page number for pagination |
| `pageSize` | number | No | 50 | Results per page (max: 100) |

**Response Schema:**

```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400
    }
  ],
  "total": 150,
  "page": 1,
  "pageSize": 10
}
```

**Authentication Requirement:**

This tool requires `SKILLS_SH_API_KEY` to access the authenticated `/api/v1/skills` endpoint. Request the API key from Vercel if needed.

资料来源：[README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)

### get_leaderboard

Get trending or top-installed skills to identify the most popular skills in the marketplace.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `timeframe` | string | No | "all" | Time window: `"all"` or `"24h"` |
| `limit` | number | No | 20 | Maximum results (max: 50) |

**Response Schema:**

```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400,
      "rank": 1,
      "trending": true
    }
  ],
  "timeframe": "24h",
  "count": 10
}
```

**Authentication Requirement:**

Similar to `list_skills`, this tool requires `SKILLS_SH_API_KEY` for authenticated access.

资料来源：[examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)

## Retrieval Tools

### fetch_skill

Fetch raw skill content directly from GitHub. This tool supports both short identifiers (skill name) and fully-qualified identifiers (`owner/repo` format).

```mermaid
graph TD
    A[fetch_skill Request] --> B{Identifier Format?}
    B -->|Short name| C[Query skills.sh directory]
    B -->|owner/repo| D[Direct GitHub URL construction]
    C --> E[Resolve to owner/repo]
    E --> F[Construct GitHub URL]
    D --> F
    F --> G[Fetch from GitHub Raw]
    G --> H[Return Skill Content]
    
    H --> I[Extract YAML frontmatter]
    H --> J[Parse markdown body]
    H --> K[Extract sections]
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `identifier` | string | Yes | Skill name or `owner/repo` format |

**Supported Identifier Formats:**

| Format | Example | Resolution |
|--------|---------|------------|
| Short name | `pdf-extractor` | Resolved via skills.sh directory |
| Fully qualified | `anthropics/pdf-extractor` | Direct GitHub URL |

**Response Schema:**

```json
{
  "content": "---\nname: PDF Extractor\ndescription: Extract text from PDF files\n---\n\n# PDF Extractor\n\n...",
  "url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md",
  "metadata": {
    "name": "pdf-extractor",
    "owner": "anthropics",
    "repo": "skills",
    "skillPath": "skills/pdf-extractor",
    "fetchedAt": "2024-01-15T10:30:00.000Z"
  }
}
```

**URL Resolution Pattern:**

The `SkillResolver` class constructs URLs using the pattern:
```
https://raw.githubusercontent.com/{owner}/{repo}/main/skills/{name}/SKILL.md
```

资料来源：[src/core/skill-resolver.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/skill-resolver.ts)

## Security Tools

### validate_skill

Validate skill content for security issues before importing. This is a critical security measure that scans for dangerous commands, suspicious patterns, and code injection vulnerabilities.

```mermaid
graph TD
    A[Skill Content] --> B[SecurityValidator]
    B --> C{Dangerous Commands?}
    B --> D{Suspicious Patterns?}
    B --> E{Untrusted Sources?}
    
    C -->|rm -rf, sudo, eval| F[dangerous_command]
    D -->|Code injection, special chars| G[suspicious_pattern]
    E -->|Non-GitHub URLs| H[untrusted_source]
    
    F --> I{Severity Assessment}
    G --> I
    H --> I
    I --> J[Validation Result]
    
    J --> K{Result}
    K -->|No issues| L["severity: safe"]
    K -->|Untrusted/Dangerous| M["severity: unsafe"]
    K -->|Suspicious only| N["severity: warning"]
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to validate |
| `url` | string | No | Source URL for verification |

**Detected Security Issues:**

| Issue Type | Description | Severity |
|------------|-------------|----------|
| `dangerous_command` | Commands like `rm -rf`, `sudo`, `eval`, `exec` | unsafe |
| `suspicious_pattern` | Code injection patterns `${...}`, `$(...)` | warning |
| `untrusted_source` | Non-GitHub URLs in skill content | unsafe |

**Dangerous Patterns Scanned:**

- Recursive delete commands (`rm -rf`)
- Privilege escalation (`sudo`)
- Dynamic code execution (`eval`, `exec`)
- Path traversal attempts (`/etc/`, `/usr/`, `/bin/`)
- Shell interpolation patterns (`${`, `$(`)

**Response Schema:**

```json
{
  "isValid": false,
  "issues": [
    {
      "type": "dangerous_command",
      "description": "Dangerous recursive delete command (rm -rf)",
      "location": "Line 7: rm -rf /"
    }
  ],
  "severity": "unsafe"
}
```

**Severity Determination Logic:**

| Condition | Result |
|-----------|--------|
| No issues found | `safe` |
| `untrusted_source` or `dangerous_command` present | `unsafe` |
| Only `suspicious_pattern` issues | `warning` |

资料来源：[src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)

## Conversion Tools

### convert_to_steering

Convert skill content to Kiro steering file format. This format is designed for guiding AI behavior through structured markdown with YAML frontmatter.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to convert |
| `sourceUrl` | string | No | Original source URL for metadata |

**Output Format Structure:**

```yaml
---
original_skill: PDF Extractor
source_url: https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md
imported_at: '2024-01-15T10:30:00.000Z'
---

# PDF Extractor

Extract text from PDF files

[Skill body content...]

---

*Imported from Claude Skills via Skill Loader Power*
```

**Conversion Process:**

1. Parse YAML frontmatter from skill content
2. Build new frontmatter with original skill metadata
3. Add skill name as H1 heading
4. Include description if present
5. Preserve skill body content
6. Add dependencies section if applicable
7. Append import attribution footer

**Naming Convention:**

The filename is generated using `toKebabCase()` transformation:
- `"PDF Extractor"` → `"pdf-extractor"`
- `"React Best Practices"` → `"react-best-practices"`

资料来源：[src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)

### convert_to_power

Convert skill content to Kiro power format. This is a more comprehensive format that may generate additional files beyond the main `POWER.md`.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to convert |
| `sourceUrl` | string | No | Original source URL for metadata |

**Generated Files:**

| Condition | File | Purpose |
|-----------|------|---------|
| Always | `POWER.md` | Main power definition |
| Skill has dependencies or tool references | `mcp.json` | MCP server configuration |
| Skill has 3+ complex sections | `steering/` directory | Structured guidance files |

**mcp.json Generation:**

When a skill contains dependencies or MCP server references, the conversion engine generates an `mcp.json` configuration file:

```json
{
  "mcpServers": {
    "skill-name": {
      "command": "npx",
      "args": ["-y", "@some/package"],
      "env": {}
    }
  }
}
```

**steering/ Directory:**

For skills with multiple complex sections (3+ sections with content > 200 characters at level 2+), a structured steering directory is generated to provide granular guidance.

**Response Schema:**

```json
{
  "success": true,
  "content": "---\nname: pdf-extractor\ndisplayName: PDF Extractor\n...",
  "filename": "POWER.md",
  "targetPath": "~/.kiro/powers/pdf-extractor/POWER.md",
  "metadata": {
    "skillName": "pdf-extractor",
    "sourceUrl": "https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md",
    "outputFormat": "power",
    "validationResult": {
      "isValid": true,
      "issues": [],
      "severity": "safe"
    }
  }
}
```

**Dependencies Section:**

When present in the original skill, dependencies are converted to a markdown list:

```markdown
## Dependencies

- dependency-1
- dependency-2
```

资料来源：[src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)

## Workflow Tools

### import_skill

Complete end-to-end import workflow that combines fetch, validate, and convert operations into a single atomic action.

```mermaid
graph TD
    A[import_skill Request] --> B[Fetch Skill from GitHub]
    B --> C{skipValidation?}
    C -->|No| D[Validate Security]
    C -->|Yes| E[Skip Validation]
    D --> F{isValid?}
    F -->|Yes| G[Convert to Target Format]
    F -->|No| H[Block Import]
    E --> G
    G --> I[Return Converted Content]
    H --> J[Return Validation Error]
    
    I --> K[Optional: Write to Target Path]
```

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `identifier` | string | Yes | - | Skill name or `owner/repo` format |
| `outputFormat` | string | Yes | - | Target format: `"steering"` or `"power"` |
| `skipValidation` | boolean | No | false | Bypass security validation |

**Workflow Steps:**

1. **Fetch**: Retrieve skill content from GitHub using `fetch_skill`
2. **Validate**: Run security checks via `validate_skill` (unless skipped)
3. **Convert**: Transform to requested format (`convert_to_steering` or `convert_to_power`)

**Recommended Workflow Pattern:**

```json
{
  "tool": "import_skill",
  "arguments": {
    "identifier": "anthropics/pdf-extractor",
    "outputFormat": "power",
    "skipValidation": false
  }
}
```

**Security Considerations:**

- Always validate skills from untrusted sources
- Use `skipValidation: true` only for locally-verified content
- Review validation issues before proceeding with imports

**Response Schema:**

```json
{
  "success": true,
  "content": "---\nname: pdf-extractor\ndisplayName: PDF Extractor\n...",
  "filename": "POWER.md",
  "targetPath": "~/.kiro/powers/pdf-extractor/POWER.md",
  "metadata": {
    "skillName": "pdf-extractor",
    "sourceUrl": "https://raw.githubusercontent.com/anthropics/skills/main/skills/pdf-extractor/SKILL.md",
    "outputFormat": "power",
    "validationResult": {
      "isValid": true,
      "issues": [],
      "severity": "safe"
    }
  }
}
```

**Error Response:**

```json
{
  "error": "Error message describing what went wrong",
  "tool": "import_skill",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

资料来源：[examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)

## Error Handling

All MCP tools return errors in a consistent format to enable reliable error handling in clients:

**Error Response Schema:**

| Field | Type | Description |
|-------|------|-------------|
| `error` | string | Human-readable error message |
| `tool` | string | Name of the tool that failed |
| `timestamp` | string | ISO 8601 timestamp of the error |

**Common Error Scenarios:**

| Scenario | Cause | Resolution |
|----------|-------|------------|
| Network errors | Internet connectivity, GitHub availability | Check connection, retry later |
| Not found | Invalid skill name or repository | Verify identifier format |
| Validation errors | Security issues detected | Review and address issues |
| Parsing errors | Invalid YAML or markdown format | Check skill syntax |

**Error Types:**

| Error Class | Trigger | Context |
|-------------|---------|---------|
| `NetworkError` | HTTP request failures | Retry with backoff |
| `SkillResolutionError` | Skill not found or ambiguous | Provide alternatives |
| `ValidationError` | Security validation failures | Review skill content |
| `FileSystemError` | File operations | Check permissions |

资料来源：[src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)

## Configuration

### Environment Variables

| Variable | Required | Tools | Description |
|----------|----------|-------|-------------|
| `SKILLS_SH_API_KEY` | Conditional | `list_skills`, `get_leaderboard` | API key for authenticated endpoints |

**Note:** `search_skills` and `fetch_skill` do not require authentication as they use public APIs.

### Caching Behavior

The server implements in-memory caching for skills.sh search results:

| Cache | TTL | Scope |
|-------|-----|-------|
| Skills.sh directory | 1 hour | All authenticated list operations |

Caching reduces API calls and improves response times for repeated queries.

## Quick Reference

### Tool Summary Table

| Tool | Auth Required | Input | Output |
|------|---------------|-------|--------|
| `search_skills` | No | `query`, `limit` | Array of matching skills |
| `list_skills` | Yes (API Key) | `page`, `pageSize` | Paginated skill directory |
| `get_leaderboard` | Yes (API Key) | `timeframe`, `limit` | Trending/top skills |
| `fetch_skill` | No | `identifier` | Raw skill content |
| `validate_skill` | No | `content`, `url` | Validation result |
| `convert_to_steering` | No | `content`, `sourceUrl` | Steering file |
| `convert_to_power` | No | `content`, `sourceUrl` | Power format + extras |
| `import_skill` | No* | `identifier`, `outputFormat` | Complete import result |

*Security validation can be optionally skipped

### Recommended Workflows

**Discover and Import Trending Skill:**

```json
[
  { "tool": "get_leaderboard", "arguments": { "timeframe": "24h", "limit": 10 } },
  { "tool": "fetch_skill", "arguments": { "identifier": "owner/skill-name" } },
  { "tool": "validate_skill", "arguments": { "content": "..." } },
  { "tool": "convert_to_steering", "arguments": { "content": "...", "sourceUrl": "..." } }
]
```

**Single-Command Import:**

```json
{ "tool": "import_skill", "arguments": { "identifier": "owner/skill-name", "outputFormat": "power" } }

---

<a id='skill-discovery'></a>

## Skill Discovery

### 相关页面

相关主题：[MCP Tools Reference](#mcp-tools-reference), [Caching System](#caching-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/core/skill-resolver.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/skill-resolver.ts)
- [src/tools/search-skills.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/list-skills.ts)
- [src/tools/list-skills.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/list-skills.ts)
- [src/tools/get-leaderboard.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/get-leaderboard.ts)
- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
</details>

# Skill Discovery

Skill Discovery is a core subsystem of the Skill Loader MCP Server that enables users to find, browse, and explore available Claude skills from the skills.sh ecosystem. It provides multiple discovery mechanisms including keyword search, paginated listing, and trending leaderboards.

## Overview

The Skill Discovery system acts as the front-end interface for exploring the skills.sh marketplace. It abstracts away the complexity of fetching and filtering skills from external APIs, providing a unified interface for skill exploration.

### Key Capabilities

- **Keyword Search**: Find skills by name or description keywords
- **Paginated Listing**: Browse all available skills with pagination support
- **Trending Leaderboard**: Discover popular or recently trending skills
- **Source Resolution**: Resolve skill identifiers to GitHub URLs
- **Install Statistics**: View install counts for skill popularity metrics

### Architecture Overview

```mermaid
graph TD
    A[User Request] --> B[MCP Tools Layer]
    B --> C[search_skills]
    B --> D[list_skills]
    B --> E[get_leaderboard]
    C --> F[SkillResolver]
    D --> F
    E --> F
    F --> G[Skills.sh API]
    F --> H[GitHub Raw Content]
    G --> I[SkillShEntry Parser]
    I --> J[ResolvedSkill Output]
    H --> J
```

## Core Components

### SkillResolver

The `SkillResolver` class is the central orchestrator for skill discovery operations. Located at `src/core/skill-resolver.ts`, it handles all interactions with the skills.sh API and provides unified resolution of skill identifiers.

**Primary Methods:**

| Method | Purpose |
|--------|---------|
| `resolveSkill()` | Resolve a skill identifier to a full URL |
| `searchSkills()` | Search skills by keyword |
| `listSkills()` | List skills with pagination (authenticated) |
| `getLeaderboard()` | Get trending or top-installed skills |

资料来源：[src/core/skill-resolver.ts:1-50]()

### Data Models

#### SkillShEntry

Represents a skill entry from the skills.sh API:

```typescript
interface SkillShEntry {
  name: string;
  owner: string;
  repo: string;
  installs: number;
  description: string;
  id?: string;
  skillId?: string;
  source?: string;
  metadata?: {
    trending: boolean;
  };
}
```

#### ResolvedSkill

Internal representation after resolution:

```typescript
interface ResolvedSkill {
  name: string;
  description: string;
  owner: string;
  repo: string;
  skillPath: string;
  url: string;
  installs: number;
}
```

资料来源：[src/core/skill-resolver.ts:60-100]()

## Discovery Tools

### 1. search_skills

Performs keyword-based search across skill names and descriptions. This tool uses the public search API endpoint and does not require authentication.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | - | Search query string |
| `limit` | number | No | 5 | Maximum results (max: 50) |

**Workflow:**

```mermaid
graph LR
    A[query: string] --> B[Call skills.sh Search API]
    B --> C[Parse Response]
    C --> D[Filter by Relevance]
    D --> E[Return Top N Results]
    E --> F[Skills with relevance scores]
```

**Response Structure:**

```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400,
      "relevance": 5
    }
  ],
  "query": "pdf",
  "count": 5
}
```

资料来源：[examples/usage-examples.md:30-60]()

### 2. list_skills

Retrieves a paginated list of all available skills from the skills.sh directory. Requires `SKILLS_SH_API_KEY` for authenticated access to the v1 API endpoint.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | number | No | 1 | Page number |
| `pageSize` | number | No | 50 | Results per page (max: 100) |

**API Integration:**

```typescript
const url = `https://skills.sh/api/v1/skills?page=${page}&pageSize=${pageSize}`;
const headers = {
  'Authorization': `Bearer ${apiKey}`,
  'Content-Type': 'application/json'
};
```

**Response Structure:**

```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400
    }
  ],
  "total": 150,
  "page": 1,
  "pageSize": 10
}
```

资料来源：[examples/usage-examples.md:20-40]()

### 3. get_leaderboard

Retrieves trending or top-installed skills ranked by popularity metrics.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `timeframe` | string | No | "all" | Time period: `'all'` or `'24h'` |
| `limit` | number | No | 20 | Maximum results (max: 50) |

**Timeframe Behavior:**

| Timeframe | Source | Use Case |
|-----------|--------|----------|
| `all` | Historical install counts | All-time popular skills |
| `24h` | Recent activity metrics | Currently trending skills |

**Response Structure:**

```json
{
  "skills": [
    {
      "name": "pdf-extractor",
      "description": "Extract text from PDF files",
      "owner": "anthropics",
      "repo": "skills",
      "installs": 30400,
      "rank": 1,
      "trending": true
    }
  ],
  "timeframe": "24h",
  "count": 10
}
```

资料来源：[examples/usage-examples.md:55-80]()

## Skill Resolution Flow

The resolution process transforms various identifier formats into canonical GitHub URLs:

```mermaid
graph TD
    A[Identifier Input] --> B{Normalize Identifier}
    B --> C["owner/repo format?"]
    C -->|Yes| D[Build URL: owner/repo]
    C -->|No| E[Search skills.sh Directory]
    E --> F{Match Found?}
    F -->|Single| G[Use Match]
    F -->|Multiple| H[Raise Error: Multiple Matches]
    F -->|None| I[Raise Error: Not Found]
    D --> J[Build Full GitHub URL]
    G --> J
    J --> K[Return ResolvedSkill]
```

### Resolution Rules

1. **Explicit Format** (`owner/repo`): Directly constructs GitHub URL
2. **Name Only**: Searches skills.sh directory for matching name
3. **Fuzzy Match**: Case-insensitive partial matching on skill names
4. **Multiple Matches**: Throws `SkillResolutionError` with list of matches

资料来源：[src/core/skill-resolver.ts:100-150]()

## API Integration

### Skills.sh API Endpoints

| Endpoint | Auth Required | Purpose |
|----------|---------------|---------|
| `GET /api/v1/skills` | Yes (API Key) | Paginated skill listing |
| `GET /search?q={query}` | No | Public keyword search |

### Authentication

```typescript
const response = await fetch(url, {
  headers: {
    'Authorization': `Bearer ${process.env.SKILLS_SH_API_KEY}`,
    'Content-Type': 'application/json'
  }
});
```

### Error Handling

| Error Type | HTTP Code | Handling |
|------------|-----------|----------|
| `NetworkError` | 4xx/5xx | Retry with exponential backoff |
| `SkillResolutionError` | N/A | Return helpful suggestions |

资料来源：[src/core/skill-resolver.ts:150-200]()

## Caching Strategy

The Skill Discovery system implements in-memory caching for the skills.sh directory to reduce API calls and improve performance.

```mermaid
graph LR
    A[Request] --> B{Cache Valid?}
    B -->|Yes| C[Return Cached Data]
    B -->|No| D[Fetch from API]
    D --> E[Update Cache]
    E --> F[Return Fresh Data]
    C --> G[Response]
    F --> G
```

**Cache Configuration:**

| Setting | Value | Description |
|---------|-------|-------------|
| TTL | 1 hour | Time-to-live for cached entries |
| Scope | In-memory | Process-level caching |
| Invalidation | TTL-based | Automatic refresh on expiry |

资料来源：[examples/usage-examples.md:150-160]()

## Usage Examples

### Discover Skills by Keyword

```json
{
  "tool": "search_skills",
  "arguments": {
    "query": "pdf",
    "limit": 5
  }
}
```

### Browse Available Skills

```json
{
  "tool": "list_skills",
  "arguments": {
    "page": 1,
    "pageSize": 10
  }
}
```

### Find Trending Skills

```json
{
  "tool": "get_leaderboard",
  "arguments": {
    "timeframe": "24h",
    "limit": 20
  }
}
```

### Complete Discovery Workflow

```mermaid
graph TD
    A[Search for Skills] --> B[Found Interesting Skill?]
    B -->|Yes| C[Fetch Skill Details]
    B -->|No| A
    C --> D[Validate Skill Content]
    D --> E{Valid?}
    E -->|Yes| F[Convert to Target Format]
    E -->|No| G[Review Security Issues]
    G --> H[Skip or Find Alternative]
    F --> I[Import Skill]
    I --> J[Complete]
```

资料来源：[examples/usage-examples.md:170-210]()

## Related Systems

### Conversion Engine Integration

After discovery, skills can be converted to target formats:

| Format | Output | Use Case |
|--------|--------|----------|
| Steering | `.kiro/steering/` | Kiro steering files |
| Power | `~/.kiro/powers/` | Kiro power modules |

### Security Validation

All discovered skills should be validated before import using the `validate_skill` tool to scan for:

- Dangerous commands (`rm -rf`, `sudo`, `eval`)
- Suspicious file operations (`/etc/`, `/usr/`)
- Code injection patterns (`${...}`, `$(...)`)

资料来源：[src/core/security-validator.ts:1-50]()

## Summary

Skill Discovery provides the foundational capability to explore and find Claude skills from the skills.sh ecosystem. Through a combination of search, listing, and trending endpoints, users can efficiently discover relevant skills for their needs. The system emphasizes:

- **Performance**: In-memory caching with 1-hour TTL
- **Reliability**: Retry logic with exponential backoff
- **Security**: Integration with validation pipeline
- **Developer Experience**: Clear error messages with actionable suggestions

For implementation details, refer to the source files listed at the beginning of this page.

---

<a id='security-validation'></a>

## Security Validation

### 相关页面

相关主题：[Error Handling](#error-handling), [Format Conversion](#format-conversion)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)
- [src/core/security-validator.test.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.test.ts)
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
- [src/tools/validate-skill.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/validate-skill.ts)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
</details>

# Security Validation

The Security Validation system is a critical component of the Skill Loader MCP Server that protects users from potentially malicious or unsafe skill content. It performs comprehensive static analysis on skill markdown files before they are imported, converted, or executed.

## Overview

The security validation module (`SecurityValidator`) scans skill content for multiple categories of security threats, including dangerous system commands, file system access patterns, code injection vulnerabilities, and untrusted content sources. Skills that fail security validation are blocked from import unless validation is explicitly skipped.

**Purpose:**
- Prevent execution of harmful system commands
- Block imports from non-verified sources
- Detect potential code injection patterns
- Protect the host system from malicious skills

**Scope:** All skill content passing through the server's import, validation, and conversion workflows.

资料来源：[src/core/security-validator.ts:1-50]()

## Architecture

```mermaid
graph TD
    A[Skill Content Input] --> B[SecurityValidator.validate]
    B --> C{Dangerous Commands?}
    C -->|Yes| D[Issue: dangerous_command]
    B --> E{Suspicious File Ops?}
    E -->|Yes| F[Issue: suspicious_file_operation]
    B --> G{Code Injection?}
    G -->|Yes| H[Issue: code_injection]
    B --> I{Untrusted Source?}
    I -->|Yes| J[Issue: untrusted_source]
    B --> K{Suspicious Patterns?}
    K -->|Yes| L[Issue: suspicious_pattern]
    
    D --> M[ValidationResult.issues]
    F --> M
    H --> M
    J --> M
    L --> M
    
    M --> N[getSeverity]
    N --> O{hasDangerousCommand<br/>or untrustedSource?}
    O -->|Yes| P[Severity: unsafe]
    N --> Q{hasIssues?}
    Q -->|Yes| R[Severity: warning]
    N --> S{noIssues?}
    S -->|Yes| T[Severity: safe]
```

## Validation Checks

The security validator performs five distinct categories of checks:

### 1. Dangerous Commands

Detects execution of potentially harmful shell commands that could damage the system.

| Pattern | Description | Severity |
|---------|-------------|----------|
| `rm -rf` | Recursive force delete | unsafe |
| `sudo` | Privilege escalation | unsafe |
| `eval` | Dynamic code execution | unsafe |
| `exec` | Command execution | unsafe |

资料来源：[src/core/security-validator.ts:60-80]()

**Example detected content:**
```bash
rm -rf /
sudo rm -rf /usr
eval $user_input
exec sh
```

### 2. Suspicious File Operations

Identifies attempts to access or modify sensitive system directories.

| Pattern | Target Directory | Severity |
|---------|------------------|----------|
| `/etc/` | System configuration | unsafe |
| `/usr/` | System binaries | unsafe |
| `/bin/` | Essential binaries | unsafe |
| `~/.` | Hidden files | warning |

资料来源：[src/core/security-validator.ts:81-100]()

### 3. Code Injection Patterns

Detects template injection and command substitution vulnerabilities.

| Pattern | Type | Severity |
|---------|------|----------|
| `${...}` | Variable expansion | unsafe |
| `$(...)` | Command substitution | unsafe |

资料来源：[src/core/security-validator.ts:101-120]()

**Example detected content:**
```bash
echo ${MALICIOUS_VAR}
Result: $(whoami)
```

### 4. Untrusted Sources

Blocks content from non-GitHub sources that cannot be verified.

| Source Type | Status | Severity |
|-------------|--------|----------|
| GitHub URLs | Trusted | safe |
| Other URLs | Blocked | unsafe |

资料来源：[src/core/security-validator.ts:121-140]()

### 5. Suspicious Patterns

Flags potentially concerning patterns that warrant review.

| Pattern | Description | Severity |
|---------|-------------|----------|
| Hidden file access (`~/.`) | File hiding | warning |
| Base64 encoded content | Obfuscation | warning |

资料来源：[src/core/security-validator.ts:141-160]()

## Data Models

### ValidationIssue

```typescript
interface ValidationIssue {
  type: 'dangerous_command' | 'suspicious_file_operation' | 
        'code_injection' | 'untrusted_source' | 'suspicious_pattern';
  description: string;
  line: number;
  content: string;
}
```

资料来源：[src/core/security-validator.ts:20-30]()

### ValidationResult

```typescript
interface ValidationResult {
  isValid: boolean;
  issues: ValidationIssue[];
  severity: 'safe' | 'warning' | 'unsafe';
}
```

| Field | Type | Description |
|-------|------|-------------|
| `isValid` | boolean | True if no blocking issues (dangerous commands or untrusted sources) |
| `issues` | ValidationIssue[] | Array of detected issues |
| `severity` | 'safe' \| 'warning' \| 'unsafe' | Overall risk assessment |

资料来源：[src/core/security-validator.ts:31-45]()

## Severity Calculation

The severity determination follows a hierarchical logic:

```mermaid
graph LR
    A[Issues Array] --> B{Contains<br/>dangerous_command<br/>or untrusted_source?}
    B -->|Yes| C[unsafe]
    B -->|No| D{Has any<br/>issues?}
    D -->|Yes| E[warning]
    D -->|No| F[safe]
```

| Condition | Severity |
|-----------|----------|
| Contains `dangerous_command` OR `untrusted_source` | `unsafe` |
| Contains any other issue type | `warning` |
| No issues detected | `safe` |

资料来源：[src/core/security-validator.ts:170-190]()

## Integration Points

The security validator is integrated into the skill import workflow at multiple stages:

```mermaid
graph TD
    A[import_skill Tool] --> B[fetch_skill]
    B --> C{validate_skill}
    C --> D{skipValidation?}
    D -->|No| E[SecurityValidator.validate]
    D -->|Yes| F[Skip validation]
    E --> G{unsafe?}
    G -->|Yes| H[Block import<br/>Return error]
    G -->|No| I[Proceed]
    F --> I
    I --> J[convert_to_steering<br/>or convert_to_power]
    J --> K[Import complete]
```

### validate_skill Tool

The `validate_skill` MCP tool provides standalone security validation:

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to validate |
| `url` | string | No | Source URL for verification |

**Example Request:**
```json
{
  "tool": "validate_skill",
  "arguments": {
    "content": "---\nname: Test\n---\n\n# Test",
    "url": "https://github.com/example/repo/main/skill.md"
  }
}
```

**Example Response:**
```json
{
  "isValid": false,
  "issues": [
    {
      "type": "dangerous_command",
      "description": "Dangerous recursive delete command (rm -rf)",
      "location": "Line 7: rm -rf /"
    }
  ],
  "severity": "unsafe"
}
```

资料来源：[src/tools/validate-skill.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/tools/validate-skill.ts)

## Error Handling

Validation errors are wrapped in the `ValidationError` class for consistent error handling:

```typescript
export class ValidationError extends SkillLoaderError {
  public readonly validationType: 'format' | 'security' | 'schema' | 'content';
  public readonly lineNumber?: number;
  public readonly details: string[];
}
```

| Field | Type | Description |
|-------|------|-------------|
| `validationType` | 'format' \| 'security' \| 'schema' \| 'content' | Category of validation failure |
| `lineNumber` | number (optional) | Line where validation failed |
| `details` | string[] | List of specific validation issues |

资料来源：[src/core/errors.ts:100-130]()

## Testing

The security validator includes comprehensive test coverage:

| Test Case | Expected Behavior |
|-----------|-------------------|
| Content with `rm -rf` | Detects as `dangerous_command`, severity: unsafe |
| Content with `${VAR}` | Detects as `code_injection`, severity: unsafe |
| Content with `$(cmd)` | Detects as `code_injection`, severity: unsafe |
| Content with `~/.` only | Detects as `suspicious_pattern`, severity: warning |
| Clean content | Severity: safe |

资料来源：[src/core/security-validator.test.ts:1-50]()

**Test Implementation:**
```typescript
it('detects dangerous commands', () => {
  const content = makeContent('Run rm -rf /');
  const result = validator.validate(content);
  expect(result.issues.some(i => i.type === 'dangerous_command')).toBe(true);
  expect(result.severity).toBe('unsafe');
});

it('detects code injection patterns', () => {
  const content = makeContent('Use ${VARIABLE} in template');
  const result = validator.validate(content);
  expect(result.issues.some(i => i.description.includes('Variable expansion'))).toBe(true);
});
```

## Configuration

Security validation behavior can be configured through the import workflow:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `skipValidation` | boolean | false | Skip security checks entirely |

**Warning:** Setting `skipValidation: true` bypasses all security checks and should only be used for trusted, locally-verified content.

资料来源：[examples/usage-examples.md:80-100]()

## Line Number Tracking

The validator tracks the line number for each detected issue:

```typescript
private getLineNumber(content: string, index: number): number {
  const lines = content.substring(0, index).split('\n');
  return lines.length;
}
```

This enables precise error reporting showing exactly where issues were found in the skill content.

资料来源：[src/core/security-validator.ts:200-210]()

## Security Recommendations

When working with skills from external sources:

1. **Always validate first** - Use `validate_skill` before importing unknown skills
2. **Review issue descriptions** - Understand what triggered each warning
3. **Prefer GitHub sources** - Skills from GitHub are automatically verified
4. **Use warning-level skills with caution** - Review content before proceeding
5. **Never skip validation for untrusted sources** - The unsafe designation exists for protection

---

<a id='format-conversion'></a>

## Format Conversion

### 相关页面

相关主题：[Core Modules](#core-modules)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation page:

- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
- [src/core/conversion-engine.test.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.test.ts)
- [src/core/types.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/types.ts) (referenced)
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
- [README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)
</details>

# Format Conversion

The Format Conversion system is a core component of the Skill Loader MCP Server that transforms Claude Skills (represented in markdown with YAML frontmatter) into Kiro-compatible formats for use in AI agent contexts. This system provides bidirectional conversion capabilities through the `ConversionEngine` class and exposes conversion functionality via MCP tools.

## Overview

The conversion system serves as a bridge between two ecosystems:

| Source Format | Target Formats |
|--------------|----------------|
| Claude Skills (markdown + YAML) | Kiro Steering Files |
| | Kiro Powers |

Claude Skills follow a specific structure with YAML frontmatter containing metadata (name, description, dependencies) and a markdown body with instructions and sections. Kiro, by contrast, supports two distinct consumption patterns: lightweight steering files for simple guidance and comprehensive power packages for complex, multi-file skills.

## Architecture

### Core Components

```mermaid
graph TD
    A[Claude Skill Markdown] --> B[ConversionEngine]
    B --> C[parseSkill]
    C --> D[ParsedSkill]
    D --> E{Output Format}
    E --> F[toSteeringFile]
    E --> G[toPower]
    F --> H[SteeringFile]
    G --> I[PowerStructure]
    
    H --> J[.kiro/steering/*.md]
    G --> K[POWER.md]
    G --> L[mcp.json]
    G --> M[steering/ directory]
```

The `ConversionEngine` class located in `src/core/conversion-engine.ts` is the central orchestrator for all conversion operations. It provides three primary public methods:

| Method | Purpose | Returns |
|--------|---------|---------|
| `parseSkill(content)` | Parse raw markdown into structured data | `ParsedSkill` |
| `toSteeringFile(skill, sourceUrl?)` | Convert to Kiro steering format | `SteeringFile` |
| `toPower(skill, sourceUrl?)` | Convert to Kiro power format | `PowerStructure` |

资料来源：[src/core/conversion-engine.ts:38-200]()

### Data Models

The conversion engine works with several interconnected TypeScript interfaces:

```typescript
interface SkillFrontmatter {
  name: string;
  description: string;
  dependencies?: string[];
  // ... additional fields
}

interface SkillSection {
  heading: string;
  level: number;
  content: string;
}

interface ParsedSkill {
  frontmatter: SkillFrontmatter;
  body: string;
  sections: SkillSection[];
}

interface SteeringFile {
  filename: string;
  content: string;
  metadata: {
    originalSkill: string;
    sourceUrl?: string;
    importedAt: string;
  };
}

interface PowerStructure {
  powerName: string;
  files: Array<{ path: string; content: string }>;
}
```

资料来源：[src/core/conversion-engine.ts:1-50]()

## Skill Parsing

### Frontmatter Extraction

The `parseSkill` method extracts YAML frontmatter using a regex pattern:

```typescript
const frontmatterRegex = /^---\n([\s\S]*?)\n---/;
```

This pattern matches content between `---` delimiters at the document start. The extracted YAML is then parsed using the `js-yaml` library into a JavaScript object.

资料来源：[src/core/conversion-engine.ts:55-90]()

### Validation Rules

The parser enforces the following validation rules:

| Field | Requirement | Error Type |
|-------|-------------|------------|
| `name` | Required, non-empty string | `ValidationError` |
| `description` | Required, non-empty string | `ValidationError` |
| Content | Must not be empty after trimming | `ValidationError` |

```typescript
if (!content || content.trim().length === 0) {
  const error = new ValidationError(
    'Skill content is empty',
    'content',
    { details: ['The skill file contains no content'] }
  );
  ErrorLogger.log(error);
  throw error;
}
```

资料来源：[src/core/conversion-engine.ts:55-65]()

### Section Extraction

The parser splits the markdown body into hierarchical sections based on heading levels (H1-H6). Each section captures:

- `heading`: The text following the `#` symbols
- `level`: The heading depth (1-6)
- `content`: The markdown content following the heading

```typescript
const sectionRegex = /^(#{1,6})\s+(.+)\n([\s\S]*?)(?=\n#{1,6}\s|\n*$)/gm;
```

This regex preserves code blocks with language annotations, allowing syntax-highlighted examples to pass through unchanged.

资料来源：[src/core/conversion-engine.ts:70-150]()

### Keyword Extraction

The private `extractKeywords` method generates up to 5 relevant keywords from the skill description:

1. Converts text to lowercase
2. Removes special characters
3. Filters out common stop words
4. Keeps words with 3+ characters
5. Returns the first 5 matches

```typescript
private extractKeywords(description: string): string[] {
  const stopWords = new Set([
    'the', 'and', 'for', 'with', 'this', 'that', 'from', 'into',
    'when', 'what', 'where', 'how', 'why', 'can', 'will', 'should',
    // ... additional stop words
  ]);
  
  const words = description
    .toLowerCase()
    .replace(/[^a-z0-9\s]/g, ' ')
    .split(/\s+/)
    .filter(word => word.length >= 3 && !stopWords.has(word))
    .slice(0, 5);
  
  return words;
}
```

资料来源：[src/core/conversion-engine.ts:180-220]()

## Steering File Conversion

### Output Format

Steering files are designed for simple, single-file skill guidance. They are saved with a kebab-case filename derived from the skill name and placed in `.kiro/steering/` directories.

### Conversion Process

```mermaid
graph LR
    A[ParsedSkill] --> B[Generate Filename]
    B --> C[kebab-case + .md]
    A --> D[Build Content]
    D --> E[Title from name]
    D --> F[Description section]
    D --> G[Complex sections]
    D --> H[Dependencies list]
    A --> I[Create Metadata]
    I --> J[originalSkill]
    I --> K[sourceUrl]
    I --> L[importedAt]
    E --> M[SteeringFile]
    F --> M
    G --> M
    H --> M
    I --> M
```

### Content Structure

A steering file contains these sections in order:

1. **Title**: `# {skill.name} Guidelines`
2. **Description**: From frontmatter if present
3. **Complex Sections**: Sections with level ≥ 2 and content length > 200 characters
4. **Dependencies**: Bulleted list if dependencies exist
5. **Footer**: Attribution message

### Filename Generation

The `toSteeringFile` method uses `toKebabCase` to transform skill names:

```typescript
private toKebabCase(str: string): string {
  return str
    .toLowerCase()
    .replace(/[\s_]+/g, '-')
    .replace(/[^a-z0-9-]/g, '')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '');
}
```

Transformation examples:

| Input | Output |
|-------|--------|
| `PDF Extractor` | `pdf-extractor` |
| `React_Best_Practices` | `react-best-practices` |
| `My Skill!!` | `my-skill` |

资料来源：[src/core/conversion-engine.ts:120-160]()

### Steering File Output

```typescript
return {
  filename,
  content,
  metadata: {
    originalSkill: skill.frontmatter.name,
    sourceUrl,
    importedAt: now
  }
};
```

资料来源：[src/core/conversion-engine.ts:190-200]()

## Power Conversion

### Output Format

Power format is more comprehensive, supporting multi-file outputs for complex skills. The `toPower` method can generate up to three files:

| File | Condition | Purpose |
|------|-----------|---------|
| `POWER.md` | Always | Main power manifest and content |
| `mcp.json` | Has dependencies or MCP tool references | MCP server configuration |
| `steering/` directory | Has 3+ complex sections | Additional guidance files |

资料来源：[src/core/conversion-engine.ts:200-280]()

### Power Manifest Structure

The `POWER.md` file follows Kiro's power specification:

```markdown
---
name: {kebab-case-name}
displayName: {original-name}
description: {description}
keywords: [{extracted-keywords}]
---

# {skill.frontmatter.name}

{skill.body}

## Dependencies
{dependency-list}

## Import Metadata
- **Original Skill**: {name}
- **Source URL**: {url}
- **Imported At**: {ISO-timestamp}
- **Imported Via**: Skill Loader Power
```

资料来源：[src/core/conversion-engine.ts:220-260]()

### MCP.json Generation

The method `shouldGenerateMcpJson` determines when to create the MCP configuration:

```typescript
private shouldGenerateMcpJson(skill: ParsedSkill): boolean {
  const hasDependencies = skill.frontmatter.dependencies?.length > 0;
  const hasTools = skill.sections.some(s => s.content.includes('mcp__'));
  return hasDependencies || hasTools;
}
```

资料来源：[src/core/conversion-engine.ts:280-300]()

### Steering Directory Generation

Complex skills with multiple substantial sections generate additional files in a `steering/` subdirectory:

```typescript
private shouldGenerateSteeringDir(skill: ParsedSkill): boolean {
  const complexSections = skill.sections.filter(
    s => s.level >= 2 && s.content.length > 200
  );
  return complexSections.length >= 3;
}
```

资料来源：[src/core/conversion-engine.ts:300-320]()

### Power Output Structure

```typescript
const files: Array<{ path: string; content: string }> = [
  { path: 'POWER.md', content: powerContent }
];

if (this.shouldGenerateMcpJson(skill)) {
  const mcpJson = this.generateMcpJson(skill);
  files.push({
    path: 'mcp.json',
    content: JSON.stringify(mcpJson, null, 2)
  });
}

if (this.shouldGenerateSteeringDir(skill)) {
  const steeringContent = this.generateSteeringContent(skill);
  // Add steering files...
}
```

资料来源：[src/core/conversion-engine.ts:260-290]()

## MCP Tools Integration

### Available Tools

The conversion functionality is exposed through two MCP tools:

#### convert_to_steering

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Raw skill markdown content |
| `sourceUrl` | string | No | Original source URL for metadata |

```json
{
  "tool": "convert_to_steering",
  "arguments": {
    "content": "---\nname: PDF Extractor\ndescription: Extract text from PDF files\n---\n\n# PDF Extractor",
    "sourceUrl": "https://example.com/skill.md"
  }
}
```

资料来源：[README.md:80-100]()

#### convert_to_power

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Raw skill markdown content |
| `sourceUrl` | string | No | Original source URL for metadata |

```json
{
  "tool": "convert_to_power",
  "arguments": {
    "content": "---\nname: PDF Extractor\ndescription: Extract text from PDF files\n---\n\n# PDF Extractor",
    "sourceUrl": "https://example.com/skill.md"
  }
}
```

资料来源：[README.md:105-125]()

### Complete Import Workflow

The `import_skill` tool provides a unified workflow combining fetch, validation, and conversion:

```json
{
  "tool": "import_skill",
  "arguments": {
    "identifier": "anthropics/pdf-extractor",
    "outputFormat": "power",
    "skipValidation": false
  }
}
```

This workflow:
1. Fetches skill content from GitHub
2. Validates for security issues (unless skipped)
3. Converts to the specified format
4. Returns the converted content with metadata

资料来源：[README.md:130-150]()

## Error Handling

### Error Types

The conversion engine uses specialized error classes for different failure scenarios:

| Error Class | Usage | Context Fields |
|-------------|-------|----------------|
| `ParsingError` | YAML/frontmatter parsing failures | `field`, `value` |
| `ValidationError` | Content validation failures | `field`, `details` |

```typescript
if (!parsed || typeof parsed !== 'object') {
  const error = new ParsingError(
    'YAML frontmatter is not a valid object',
    'frontmatter',
    { yamlContent: yamlContent.substring(0, 100) }
  );
  ErrorLogger.log(error);
  throw error;
}
```

资料来源：[src/core/conversion-engine.ts:70-85]()

### Error Logging

All errors are logged through `ErrorLogger` before being thrown, enabling debugging and audit trails:

```typescript
ErrorLogger.log(error);
throw error;
```

资料来源：[src/core/errors.ts:50-100]()

## Testing

The conversion engine has comprehensive test coverage in `src/core/conversion-engine.test.ts`:

### parseSkill Tests

| Test Case | Input | Expected |
|-----------|-------|----------|
| Valid skill with frontmatter | Complete YAML + body | Parsed frontmatter and sections |
| Empty content | `""` | Throws ValidationError |
| Missing name | YAML without `name` | Throws ValidationError |
| Missing description | YAML without `description` | Throws ValidationError |
| No frontmatter | Plain markdown | Uses "Untitled Skill" |
| Code block preservation | Markdown with code fences | Code blocks intact |

资料来源：[src/core/conversion-engine.test.ts:1-80]()

### Steering Conversion Tests

| Test Case | Description |
|-----------|-------------|
| Basic conversion | Validates output structure |
| Empty dependencies | No dependencies section generated |
| With dependencies | Dependencies section populated |

### Power Conversion Tests

| Test Case | Expected Behavior |
|-----------|-------------------|
| Basic conversion | POWER.md generated with manifest |
| With dependencies | `mcp.json` added to files array |
| Without dependencies | No `mcp.json` generated |
| Complex sections (3+) | `steering/` directory created |

资料来源：[src/core/conversion-engine.test.ts:80-150]()

## Usage Examples

### Convert to Steering File

```typescript
const content = `---
name: PDF Extractor
description: Extract text from PDF files
---

# PDF Extractor

Extract text content from PDF documents.`;

const result = engine.toSteeringFile(
  engine.parseSkill(content),
  'https://example.com/skill.md'
);

// Result structure:
// {
//   filename: "pdf-extractor.md",
//   content: "# PDF Extractor Guidelines\n\n...",
//   metadata: { originalSkill: "PDF Extractor", ... }
// }
```

### Convert to Power

```typescript
const content = `---
name: React Best Practices
description: Guide for React development
dependencies:
  - react
  - react-dom
---

# React Best Practices

Content with multiple sections...`;

const result = engine.toPower(
  engine.parseSkill(content),
  'https://example.com/skill.md'
);

// Result structure:
// {
//   powerName: "react-best-practices",
//   files: [
//     { path: "POWER.md", content: "..." },
//     { path: "mcp.json", content: "..." }
//   ]
// }
```

资料来源：[examples/usage-examples.md:50-120]()

## Summary

The Format Conversion system provides a robust bridge between Claude Skills and Kiro formats:

- **Single Entry Point**: `ConversionEngine` class handles all conversions
- **Two Output Formats**: Steering files (simple) and Powers (complex)
- **Automatic Structure Detection**: Determines output complexity based on content
- **Security Integration**: Works with the validation system for safe imports
- **Comprehensive Error Handling**: Typed errors with context for debugging
- **Full Test Coverage**: Unit tests for all major code paths

---

<a id='caching-system'></a>

## Caching System

### 相关页面

相关主题：[Skill Discovery](#skill-discovery), [Type Definitions](#type-definitions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/utils/cache.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/utils/cache.ts)
- [src/utils/cache.test.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/utils/cache.test.ts)
- [README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)
</details>

# Caching System

## Overview

The Caching System in the Skill Loader MCP Server provides an in-memory caching layer with TTL (Time To Live) support. It is designed to reduce redundant API calls to external services like skills.sh, improving response times and reducing network overhead.

The cache implementation is generic and reusable, supporting any data type through TypeScript generics. It automatically expires entries after a configurable TTL and provides basic cache management operations.

**Key Characteristics:**
- In-memory storage using `Map` data structure
- Configurable TTL per cache instance
- Automatic expiration checking on access
- Zero external dependencies

资料来源：[src/utils/cache.ts:1-60]()

---

## Architecture

### Component Diagram

```mermaid
graph TB
    subgraph "Caching System Components"
        Cache["Cache<T> Class"]
        CacheEntry["CacheEntry<T> Interface"]
    end
    
    subgraph "Data Structure"
        Map["Map<string, CacheEntry<T>>"]
        Data["data: T"]
        Timestamp["timestamp: number"]
    end
    
    subgraph "Operations"
        Get["get(key)"]
        Set["set(key, data)"]
        Has["has(key)"]
        Delete["delete(key)"]
        Clear["clear()"]
    end
    
    Cache --> CacheEntry
    CacheEntry --> Data
    CacheEntry --> Timestamp
    Cache --> Map
    Cache -.-> Get
    Cache -.-> Set
    Cache -.-> Has
    Cache -.-> Delete
    Cache -.-> Clear
```

### Data Model

```typescript
interface CacheEntry<T> {
  data: T;           // The cached value
  timestamp: number; // Unix timestamp when entry was created
}
```

资料来源：[src/utils/cache.ts:9-13]()

---

## API Reference

### Cache Class

```typescript
class Cache<T> {
  constructor(ttl: number)
  get(key: string): T | undefined
  set(key: string, data: T): void
  has(key: string): boolean
  delete(key: string): void
  clear(): void
}
```

### Constructor

| Parameter | Type | Description |
|-----------|------|-------------|
| `ttl` | `number` | Time to live in milliseconds |

```typescript
constructor(ttl: number) {
  this.ttl = ttl;
}
```

资料来源：[src/utils/cache.ts:22-28]()

### get()

Retrieves a cached value by key. Returns `undefined` if the key does not exist or the entry has expired.

| Parameter | Type | Description |
|-----------|------|-------------|
| `key` | `string` | Cache key |

| Return Type | Description |
|-------------|-------------|
| `T \| undefined` | Cached value or undefined if not found/expired |

```typescript
get(key: string): T | undefined {
  const entry = this.cache.get(key);
  
  if (!entry) {
    return undefined;
  }
  
  // Check if entry has expired
  if (Date.now() - entry.timestamp > this.ttl) {
    this.cache.delete(key);
    return undefined;
  }
  
  return entry.data;
}
```

资料来源：[src/utils/cache.ts:37-53]()

### set()

Stores a value in the cache with the current timestamp.

| Parameter | Type | Description |
|-----------|------|-------------|
| `key` | `string` | Cache key |
| `data` | `T` | Data to cache |

```typescript
set(key: string, data: T): void {
  this.cache.set(key, {
    data,
    timestamp: Date.now(),
  });
}
```

资料来源：[src/utils/cache.ts:60-67]()

### has()

Checks if a key exists in the cache and has not expired.

| Parameter | Type | Description |
|-----------|------|-------------|
| `key` | `string` | Cache key |

| Return Type | Description |
|-------------|-------------|
| `boolean` | True if key exists and is not expired |

```typescript
has(key: string): boolean {
  return this.get(key) !== undefined;
}
```

资料来源：[src/utils/cache.ts:69-72]()

### delete()

Removes a specific entry from the cache.

| Parameter | Type | Description |
|-----------|------|-------------|
| `key` | `string` | Cache key to delete |

```typescript
delete(key: string): void {
  this.cache.delete(key);
}
```

资料来源：[src/utils/cache.ts:74-76]()

### clear()

Removes all entries from the cache.

```typescript
clear(): void {
  this.cache.clear();
}
```

资料来源：[src/utils/cache.ts:78-80]()

---

## Cache Lifecycle

### Entry Lifecycle Diagram

```mermaid
graph LR
    A["set(key, data)"] --> B["Entry Created<br/>timestamp = Date.now()"]
    B --> C{"get(key) called?"}
    C -->|Yes| D{"Date.now() - timestamp<br/> > TTL?"}
    D -->|No| E["Return cached data"]
    D -->|Yes| F["Delete expired entry"]
    F --> G["Return undefined"]
    C -->|No| H["Entry remains in cache"]
    E --> H
    G --> I["Next get() call"]
    I --> C
```

### Expiration Check Flow

```mermaid
flowchart TD
    A["get(key)"] --> B{"Entry exists?"}
    B -->|No| C["Return undefined"]
    B -->|Yes| D{"Date.now() - timestamp<br/> > TTL?"}
    D -->|Yes| E["Delete entry<br/>from cache"]
    E --> F["Return undefined"]
    D -->|No| G["Return cached data"]
```

资料来源：[src/utils/cache.ts:37-53]()

---

## Configuration

### TTL Configuration

The TTL (Time to Live) determines how long cached entries remain valid.

| TTL Value | Duration | Use Case |
|-----------|----------|----------|
| 60,000 ms | 1 minute | Short-lived data, frequent updates |
| 3,600,000 ms | 1 hour | Skills.sh directory listings |
| 86,400,000 ms | 24 hours | Stable, rarely changing data |

**Implementation Note:** The skills.sh integration uses a 1-hour TTL to cache search results and directory listings, reducing API calls while ensuring relatively fresh data.

资料来源：[README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)

---

## Usage Examples

### Basic Cache Usage

```typescript
import { Cache } from './utils/cache.js';

// Create a cache with 60 second TTL
const cache = new Cache<string>(60_000);

// Set a value
cache.set('user:123', JSON.stringify({ name: 'Alice', role: 'admin' }));

// Get the value
const userData = cache.get('user:123');
if (userData) {
  console.log(JSON.parse(userData));
}

// Check existence
if (cache.has('user:123')) {
  console.log('User exists in cache');
}

// Delete specific entry
cache.delete('user:123');

// Clear all entries
cache.clear();
```

资料来源：[src/utils/cache.test.ts:1-22]()

### Type-Safe Caching

```typescript
// Generic cache works with any type
interface Skill {
  name: string;
  description: string;
  owner: string;
}

const skillCache = new Cache<Skill>(3_600_000); // 1 hour TTL

skillCache.set('pdf-extractor', {
  name: 'pdf-extractor',
  description: 'Extract text from PDF files',
  owner: 'anthropics'
});

const skill = skillCache.get('pdf-extractor');
// skill is typed as Skill | undefined
```

---

## Test Coverage

The cache implementation includes comprehensive unit tests covering:

| Test Case | Description |
|-----------|-------------|
| Stores and retrieves values | Basic set/get operations |
| Returns undefined for missing keys | Cache miss behavior |
| Expires entries after TTL | Automatic expiration |
| `has()` returns true for valid keys | Existence check |
| `delete()` removes entries | Manual removal |
| `clear()` removes all entries | Bulk removal |

资料来源：[src/utils/cache.test.ts:1-32]()

### Test Implementation

```typescript
it('expires entries after TTL', () => {
  const cache = new Cache<string>(1); // 1ms TTL
  cache.set('key1', 'value1');
  // Force expiry by waiting
  const start = Date.now();
  while (Date.now() - start < 5) { /* busy wait */ }
  expect(cache.get('key1')).toBeUndefined();
});
```

资料来源：[src/utils/cache.test.ts:16-24]()

---

## Design Decisions

### Why In-Memory Cache?

1. **Simplicity**: No external dependencies required
2. **Performance**: Direct memory access is extremely fast
3. **Suitable for Server Use Case**: The MCP server runs as a single process where in-memory caching is appropriate

### Why TTL-Based Expiration?

- Ensures data freshness without manual invalidation
- Automatic cleanup prevents memory leaks
- Simple and predictable behavior

### Why Check Expiration on Get?

- Lazy expiration keeps the cache simple
- No background timer overhead
- Expired entries are cleaned on next access

---

## Limitations

| Limitation | Impact |
|------------|--------|
| Single-process only | Cache not shared between server instances |
| No persistence | Cache lost on server restart |
| Memory bound | Large caches consume RAM |
| No distributed invalidation | Cannot invalidate across processes |

资料来源：[src/utils/cache.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/utils/cache.ts)

---

## Related Components

```mermaid
graph LR
    Cache["Caching System"] --> SkillResolver["SkillResolver"]
    SkillResolver["SkillResolver"] -->|Caches directory listings| Cache
    
    Cache --> Usage["MCP Tools<br/>list_skills<br/>search_skills"]
    
    subgraph "Storage"
        Cache
    end
    
    subgraph "Consumers"
        SkillResolver
        Usage
    end
```

The caching system is utilized by the `SkillResolver` for caching skills.sh directory listings to improve performance of listing and searching operations.

---

## Summary

The Caching System provides a lightweight, generic in-memory cache with TTL support. It serves as the foundational caching layer for the Skill Loader MCP Server, enabling efficient storage of frequently accessed data like skills.sh API responses. The system prioritizes simplicity and reliability over feature complexity, making it suitable for server-side caching in a single-process environment.

---

<a id='type-definitions'></a>

## Type Definitions

### 相关页面

相关主题：[Core Modules](#core-modules), [Caching System](#caching-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/core/types.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/types.ts) - 主类型定义文件
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts) - 错误类定义
- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts) - 转换引擎类型
- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts) - 安全验证器
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md) - 使用示例
- [CHANGELOG.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CHANGELOG.md) - 变更日志
</details>

# Type Definitions

This page documents the type system for the Skill Loader MCP Server, covering core data models, error classes, and validation types used throughout the application.

## Overview

The Skill Loader MCP Server uses TypeScript for type-safe development. The type system is organized around several key domains:

- **Skill Data Models**: Structures for representing Claude Skills and their components
- **Error Handling**: Hierarchical error classes with context and recovery suggestions
- **Security Validation**: Types for security issue detection and severity levels
- **API Responses**: Standardized response formats for MCP tools

资料来源：[src/core/types.ts]()，[src/core/errors.ts]()

## Core Data Models

### Skill Structure

The skill data model represents Claude Skills with their metadata and content sections.

```mermaid
classDiagram
    class SkillFrontmatter {
        +string name
        +string description
        +string[] dependencies
    }
    class SkillSection {
        +number level
        +string heading
        +string content
    }
    class ParsedSkill {
        +SkillFrontmatter frontmatter
        +string body
        +SkillSection[] sections
    }
    class ConversionResult {
        +string filename
        +string content
        +Record metadata
    }
    
    ParsedSkill *-- SkillFrontmatter
    ParsedSkill *-- SkillSection
    ConversionResult ..> ParsedSkill
```

### SkillFrontmatter

The frontmatter contains skill metadata defined in YAML format at the top of skill files.

| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | The skill name |
| `description` | `string` | Brief description of the skill |
| `dependencies` | `string[]` | Optional list of required dependencies |

资料来源：[src/core/conversion-engine.ts]() (示例展示结构)

### ParsedSkill

A fully parsed skill document containing all extracted components.

| Field | Type | Description |
|-------|------|-------------|
| `frontmatter` | `SkillFrontmatter` | YAML metadata block |
| `body` | `string` | Raw skill content body |
| `sections` | `SkillSection[]` | Extracted markdown sections |

资料来源：[src/core/conversion-engine.ts]()

### SkillSection

Represents a heading section within a skill document.

| Field | Type | Description |
|-------|------|-------------|
| `level` | `number` | Heading level (1-6) |
| `heading` | `string` | Section title text |
| `content` | `string` | Section body content |

## Error Class Hierarchy

The error system uses a hierarchical class structure for granular error handling.

```mermaid
classDiagram
    class Error {
        +string message
        +string name
        +Date timestamp
        +string stack
    }
    
    class SkillLoaderError {
        +Date timestamp
        +Record context
        +getDetailedMessage()
    }
    
    class NetworkError {
        +string url
        +number? statusCode
        +number retryCount
        +getUserMessage()
    }
    
    class ValidationError {
        +string validationType
        +number? lineNumber
        +string[] details
    }
    
    class FileSystemError {
        +string operation
        +string filePath
        +string? systemError
    }
    
    class ParsingError {
        +string parseType
        +string? invalidContent
        +getUserMessage()
    }
    
    Error <|-- SkillLoaderError
    SkillLoaderError <|-- NetworkError
    SkillLoaderError <|-- ValidationError
    SkillLoaderError <|-- FileSystemError
    SkillLoaderError <|-- ParsingError
```

### Base Class: SkillLoaderError

All application errors extend the base `SkillLoaderError` class.

```typescript
class SkillLoaderError extends Error {
  public readonly timestamp: Date;
  public readonly context: Record<string, any>;
}
```

| Property | Type | Description |
|----------|------|-------------|
| `timestamp` | `Date` | When the error occurred |
| `context` | `Record<string, any>` | Additional error context data |

资料来源：[src/core/errors.ts]()

### NetworkError

Handles network-related failures including connection issues, timeouts, and HTTP errors.

```typescript
class NetworkError extends SkillLoaderError {
  public readonly url: string;
  public readonly statusCode?: number;
  public readonly retryCount: number;
}
```

资料来源：[src/core/errors.ts]()

**Recovery suggestions by status code:**

| Status Code | Suggestion |
|-------------|------------|
| `404` | Verify skill name is correct; check repository exists |
| `403` | Rate limit hit; wait a few minutes |
| `>= 500` | Server issues; try again later |

### ValidationError

Represents validation failures for format, security, schema, or content issues.

```typescript
class ValidationError extends SkillLoaderError {
  public readonly validationType: 'format' | 'security' | 'schema' | 'content';
  public readonly lineNumber?: number;
  public readonly details: string[];
}
```

| Property | Type | Description |
|----------|------|-------------|
| `validationType` | `ValidationType` | Category of validation failure |
| `lineNumber` | `number?` | Line where error occurred (if applicable) |
| `details` | `string[]` | List of specific validation issues |

资料来源：[src/core/errors.ts]()

### FileSystemError

Handles file system operations including read, write, delete, and access errors.

```typescript
class FileSystemError extends SkillLoaderError {
  public readonly operation: 'read' | 'write' | 'delete' | 'access';
  public readonly filePath: string;
  public readonly systemError?: string;
}
```

| Property | Type | Description |
|----------|------|-------------|
| `operation` | `FileOperation` | Type of file operation that failed |
| `filePath` | `string` | Path involved in the error |
| `systemError` | `string?` | Raw system error message |

**System error code mappings:**

| Error Code | Issue | Recovery |
|------------|-------|----------|
| `EACCES` / `EPERM` | Permission denied | Check file permissions |
| `ENOSPC` | Disk full | Free up disk space |
| `ENOENT` | Path not found | Verify directory exists |
| `EEXIST` | File exists | Use --overwrite flag |

资料来源：[src/core/errors.ts]()

## Security Validation Types

### ValidationIssue

Represents a detected security or content issue.

```typescript
interface ValidationIssue {
  type: 'dangerous_command' | 'suspicious_pattern' | 'untrusted_source' | 'suspicious_file_op';
  description: string;
  location: string;
}
```

| Type | Severity | Description |
|------|----------|-------------|
| `dangerous_command` | unsafe | Commands like `rm -rf`, `sudo`, `eval`, `exec` |
| `suspicious_pattern` | warning | Code injection patterns like `${...}`, `$(...)` |
| `untrusted_source` | unsafe | Non-GitHub source URLs |
| `suspicious_file_op` | warning | Access to system directories (`/etc/`, `/usr/`, `/bin/`) |

资料来源：[src/core/security-validator.ts]()

### ValidationResult

Complete validation outcome with severity classification.

```typescript
interface ValidationResult {
  isValid: boolean;
  issues: ValidationIssue[];
  severity: 'safe' | 'warning' | 'unsafe';
}
```

**Severity determination rules:**

```mermaid
graph TD
    A[ValidationResult] --> B{issues.length === 0?}
    B -->|Yes| C[Return safe]
    B -->|No| D{Has untrusted_source?}
    D -->|Yes| E[Return unsafe]
    D -->|No| F{Has dangerous_command?}
    F -->|Yes| E
    F -->|No| G[Return warning]
```

资料来源：[src/core/security-validator.ts]()

## API Response Types

### SkillsShEntry

Represents a skill entry from skills.sh directory.

```typescript
interface SkillsShEntry {
  name: string;
  description: string;
  owner: string;
  repo: string;
  installs: number;
  relevance?: number;
  rank?: number;
  trending?: boolean;
}
```

### SkillsShV1Response

API response wrapper for skills.sh v1 endpoints.

```typescript
interface SkillsShV1Response {
  skills: SkillsShEntry[];
  total?: number;
  page?: number;
  pageSize?: number;
}
```

### ConversionResponse

Response format for skill conversion operations.

```typescript
interface ConversionResponse {
  success: boolean;
  content: string;
  filename: string;
  targetPath: string;
  metadata: {
    skillName: string;
    sourceUrl?: string;
    outputFormat: 'steering' | 'power';
    validationResult: ValidationResult;
  };
}
```

资料来源：[examples/usage-examples.md]()

## MCP Tool Parameters

### Tool Input Schemas

| Tool | Required Parameters | Optional Parameters |
|------|---------------------|---------------------|
| `list_skills` | - | `page`, `pageSize` |
| `search_skills` | `query` | `limit` |
| `get_leaderboard` | - | `timeframe`, `limit` |
| `fetch_skill` | `identifier` | - |
| `validate_skill` | `content` | `url` |
| `convert_to_steering` | `content` | `sourceUrl` |
| `convert_to_power` | `content` | `sourceUrl` |
| `import_skill` | `identifier`, `outputFormat` | `skipValidation` |

## Configuration Types

### Server Configuration

```typescript
interface ServerConfig {
  SKILLS_SH_API_KEY?: string;
  cache?: {
    skillsTTL: number;  // Default: 3600000 (1 hour)
  };
  retry?: {
    maxRetries: number;
    baseDelay: number;
  };
}
```

## Type Naming Conventions

Per project coding standards:

| Category | Convention | Example |
|----------|------------|---------|
| Files | kebab-case | `skill-fetcher.ts` |
| Classes | PascalCase | `SkillFetcher` |
| Functions | camelCase | `fetchSkill` |
| Constants | UPPER_SNAKE_CASE | `MAX_RETRIES` |
| Interfaces | PascalCase | `ISkillData` |

资料来源：[CONTRIBUTING.md]()

## Summary

The type system provides:

1. **Type-safe data models** for skills, sections, and metadata
2. **Hierarchical error handling** with context and recovery suggestions
3. **Security validation** with issue categorization and severity levels
4. **Standardized API responses** for all MCP tools

All types are defined in TypeScript with proper JSDoc documentation for IDE support and generated documentation.

资料来源：[CHANGELOG.md]()

---

<a id='deployment'></a>

## Deployment and Configuration

### 相关页面

相关主题：[Getting Started](#getting-started), [Error Handling](#error-handling)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
- [CONTRIBUTING.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CONTRIBUTING.md)
- [CHANGELOG.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CHANGELOG.md)
- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
</details>

# Deployment and Configuration

## Overview

The Skill Loader MCP Server provides a comprehensive deployment model for integrating Claude skill management capabilities into various AI development environments. The deployment architecture supports multiple integration patterns, including integration with Kiro, Claude Desktop, and standalone operation modes. Configuration is primarily driven through environment variables and MCP server configuration files, enabling flexible deployment scenarios ranging from simple local installations to enterprise-scale distributed setups.

The server operates as a Model Context Protocol (MCP) server that exposes eight distinct tools for skill management operations. These tools interact with external services including the skills.sh marketplace API and GitHub repositories containing skill definitions. The deployment model emphasizes security through content validation, caching strategies for performance optimization, and comprehensive error handling mechanisms that provide actionable feedback for administrators and users alike.

## Installation Methods

### Global Installation

Global installation provides system-wide access to the Skill Loader MCP Server, making it immediately available to all projects and users on a given system. This approach is recommended for scenarios where multiple projects require access to skill management capabilities without individual per-project configuration.

The global installation is performed using npm with the `-g` flag, which installs the package in the global npm registry location. For systems with multiple Node.js versions or requiring specific version management, npx can be used to execute the package directly without permanent installation.

```bash
npm install -g @goldzulu/skill-loader-mcp-server
```

资料来源：[README.md:49](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L49)

### Local Installation

Local installation is appropriate for project-specific deployments where the skill loader should be tracked as a project dependency. This approach ensures version consistency across team members and facilitates reproducible builds through package.json dependency management.

```bash
npm install @goldzulu/skill-loader-mcp-server
```

资料来源：[README.md:53](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L53)

### Development Installation

For contributors setting up the development environment, the installation process includes additional steps for building the TypeScript source and running tests. The development setup requires Node.js, npm or yarn, and Git for version control.

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test
```

资料来源：[CONTRIBUTING.md:14-19](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CONTRIBUTING.md#L14-L19)

## Environment Variables

The Skill Loader MCP Server uses environment variables to configure runtime behavior and authentication. Understanding the distinction between required and optional environment variables is critical for successful deployment.

### SKILLS_SH_API_KEY

The `SKILLS_SH_API_KEY` environment variable provides authentication for the skills.sh marketplace API. This key is required only for tools that access authenticated endpoints of the skills.sh service.

| Tool | SKILLS_SH_API_KEY Required |
|------|---------------------------|
| `search_skills` | No (uses public API) |
| `list_skills` | Yes |
| `get_leaderboard` | Yes |
| `fetch_skill` | No |
| `validate_skill` | No |
| `convert_to_steering` | No |
| `convert_to_power` | No |
| `import_skill` | No |

资料来源：[README.md:57-58](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L57-L58)

The API key must be requested from Vercel, the platform hosting the skills.sh service. Organizations planning to use the authenticated listing and leaderboard features should coordinate with the skills.sh team to obtain appropriate credentials.

## MCP Server Configuration

The Skill Loader MCP Server implements the Model Context Protocol specification version 1.29, utilizing the official `@modelcontextprotocol/sdk` for protocol compliance. Configuration varies depending on the target platform and deployment scenario.

### Kiro Configuration

Integration with Kiro requires modification of the `mcp.json` configuration file. The server can be launched using npx for immediate execution or configured as a persistent server service.

```json
{
  "mcpServers": {
    "skill-loader": {
      "command": "npx",
      "args": ["-y", "@goldzulu/skill-loader-mcp-server"],
      "env": {
        "SKILLS_SH_API_KEY": "your-api-key-here"
      },
      "description": "Skill Loader MCP Server for managing Claude skills"
    }
  }
}
```

资料来源：[README.md:65-76](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L65-L76)

The configuration specifies the npx command with the `-y` flag to automatically confirm package installation. The `args` array passes the package name as an argument to npx. The `env` block configures the skills.sh API key, which is optional and only required when accessing authenticated endpoints.

### Claude Desktop Configuration

Claude Desktop users can integrate the Skill Loader MCP Server by adding the server configuration to their Claude Desktop configuration file. The configuration structure differs slightly from Kiro, using the `skill-loader-mcp-server` command directly rather than npx invocation.

```json
{
  "mcpServers": {
    "skill-loader": {
      "command": "skill-loader-mcp-server",
      "env": {
        "SKILLS_SH_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

资料来源：[README.md:87-97](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L87-L97)

The Claude Desktop configuration omits the `description` field and uses the globally installed command directly. This approach assumes the package has been installed globally via npm.

### Standalone Operation

For scenarios requiring direct execution without MCP integration, the server can be launched in standalone mode. This mode is useful for testing, debugging, or batch processing operations where the full MCP protocol overhead is unnecessary.

```bash
skill-loader-mcp-server
```

资料来源：[README.md:99-101](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L99-L101)

## Deployment Architecture

The deployment architecture follows a layered design that separates concerns between protocol handling, core business logic, and external service integration.

```mermaid
graph TD
    A[Client Application] -->|MCP Protocol| B[MCP Server Layer]
    B -->|Request Dispatch| C[Tool Handlers]
    C --> D1[list_skills]
    C --> D2[search_skills]
    C --> D3[get_leaderboard]
    C --> D4[fetch_skill]
    C --> D5[validate_skill]
    C --> D6[convert_to_steering]
    C --> D7[convert_to_power]
    C --> D8[import_skill]
    D1 --> E[Skills.sh API Client]
    D2 --> E
    D3 --> E
    D4 --> F[GitHub Fetcher]
    E --> G[(Skills.sh API)]
    F --> H[(GitHub)]
    D5 --> I[Security Validator]
    D6 --> J[Conversion Engine]
    D7 --> J
    D8 --> K[Complete Workflow]
    K --> D4
    K --> D5
    K --> D7
    J --> L[(Output Files)]
    I --> M[Error Handler]
    M --> N[User Feedback]
```

## Tool Configuration Parameters

Each MCP tool exposed by the server accepts specific parameters that control its behavior. Understanding these parameters is essential for effective configuration and usage.

### search_skills

The `search_skills` tool searches the skills.sh marketplace using the public search API. No authentication is required for this endpoint.

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | - | Search query string |
| `limit` | number | No | 20 | Maximum results (max: 50) |

资料来源：[README.md:109-118](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L109-L118)

### list_skills

The `list_skills` tool retrieves paginated results from the authenticated skills.sh directory endpoint. This tool requires the `SKILLS_SH_API_KEY` environment variable.

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | number | No | 1 | Page number for pagination |
| `pageSize` | number | No | 50 | Results per page (max: 100) |

资料来源：[README.md:122-131](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L122-L131)

### get_leaderboard

The `get_leaderboard` tool retrieves trending or top-installed skills, sorted by installation count or trending score.

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `timeframe` | string | No | 'all' | Time window: 'all' or '24h' |
| `limit` | number | No | 20 | Maximum results (max: 50) |

资料来源：[README.md:135-144](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L135-L144)

### fetch_skill

The `fetch_skill` tool retrieves raw skill content directly from GitHub repositories. The tool supports both shorthand skill names and fully-qualified owner/repo identifiers.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `identifier` | string | Yes | Skill name or 'owner/repo' format |

资料来源：[README.md:148-156](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L148-L156)

### validate_skill

The `validate_skill` tool performs security analysis on skill content, scanning for dangerous patterns and potential security risks.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to validate |
| `url` | string | No | Source URL for verification |

资料来源：[README.md:160-168](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L160-L168)

### convert_to_steering

The `convert_to_steering` tool transforms skill content into the Kiro steering file format, which is used for providing behavioral guidelines to AI models.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to convert |
| `sourceUrl` | string | No | Original source URL for metadata |

资料来源：[README.md:173-181](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L173-L181)

### convert_to_power

The `convert_to_power` tool generates the Kiro power format, which includes additional components for complex skills. When a skill has dependencies or MCP server references, the tool automatically generates an `mcp.json` configuration file. For skills containing three or more complex sections, the tool creates a `steering/` subdirectory with structured content.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Skill content to convert |
| `sourceUrl` | string | No | Original source URL for metadata |

资料来源：[README.md:185-193](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L185-L193)

### import_skill

The `import_skill` tool orchestrates the complete import workflow, combining fetch, validation, and conversion operations in a single atomic transaction.

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `identifier` | string | Yes | - | Skill name or 'owner/repo' format |
| `outputFormat` | string | Yes | - | 'steering' or 'power' |
| `skipValidation` | boolean | No | false | Bypass security validation |

资料来源：[README.md:198-207](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L198-L207)

## Security Configuration

The security validation system is a critical component of the deployment configuration, providing defense-in-depth against potentially malicious skill content.

### Validation Checks

The security validator scans skill content for multiple categories of risk:

| Category | Patterns Detected |
|----------|------------------|
| Dangerous Commands | `rm -rf`, `sudo`, `eval`, `exec` |
| Suspicious Paths | `/etc/`, `/usr/`, `/bin/` |
| Code Injection | `${...}`, `$(...)` |
| Untrusted Sources | Non-GitHub URLs |

资料来源：[README.md:212-220](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L212-L220)

### Validation Bypass

The `skipValidation` parameter on the `import_skill` tool allows administrators to bypass security checks when importing trusted skills. This parameter should be used cautiously and only for skills from verified sources.

```json
{
  "tool": "import_skill",
  "arguments": {
    "identifier": "trusted/author/skill-name",
    "outputFormat": "power",
    "skipValidation": false
  }
}
```

资料来源：[examples/usage-examples.md:175-183](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md#L175-L183)

## Error Handling Configuration

The error handling system provides structured error responses that enable programmatic error recovery and user-friendly error messages.

### Error Response Format

All tools return errors in a consistent JSON format that includes the error message, affected tool name, and timestamp:

```json
{
  "error": "Error message describing what went wrong",
  "tool": "tool_name",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

资料来源：[examples/usage-examples.md:220-226](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md#L220-L226)

### Error Categories

The error handling system classifies errors into distinct categories, each with specific recovery suggestions:

| Error Type | Description | Recovery Actions |
|------------|-------------|------------------|
| Network Errors | Connection failures, timeouts | Check internet connection, verify GitHub availability |
| Not Found Errors | Invalid skill identifiers | Verify skill name and repository |
| Validation Errors | Security issues detected | Review security issues before proceeding |
| Parsing Errors | Invalid YAML or markdown syntax | Check skill format and YAML syntax |

资料来源：[examples/usage-examples.md:228-236](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md#L228-L236)

### Custom Error Classes

The error handling infrastructure includes specialized error classes that provide contextual information for different failure scenarios. The `FileSystemError` class captures operation type, file path, and system-level error details for file-related failures.

资料来源：[src/core/errors.ts:1-50](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts#L1-L50)

The `ParsingError` class tracks parser type, line numbers, column positions, and code snippets for format-related failures, enabling precise identification of parsing issues in skill content.

## Caching Configuration

The server implements in-memory caching for skills.sh directory results to optimize performance and reduce API load.

### Cache Behavior

| Setting | Value | Description |
|---------|-------|-------------|
| Cache Type | In-memory | Stored in process memory |
| TTL | 1 hour | Time before automatic refresh |
| Cache Target | search_skills results | Cached API responses |
| Refresh | Automatic on expiry | Proactive cache refresh |

资料来源：[README.md:224-228](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md#L224-L228)

The caching strategy balances performance optimization with data freshness, automatically refreshing cached data when the TTL expires. This approach reduces API calls for frequently accessed data while ensuring users receive current information.

## Typical Workflow Configuration

The repository documentation provides recommended workflow patterns for common deployment scenarios.

### Discovery and Import Workflow

```mermaid
graph LR
    A[Search Skills] --> B[Evaluate Results]
    B --> C{Find Skill?}
    C -->|Yes| D[List with Pagination]
    C -->|No| E[Refine Search]
    D --> F[Fetch Skill]
    F --> G[Validate Content]
    G --> H{Valid?}
    H -->|Yes| I[Convert Format]
    H -->|No| J[Report Issues]
    I --> K[Import Complete]
```

For discovering skills, users should first search using the `search_skills` tool to find relevant skills by keyword. When multiple results exist, the `list_skills` tool provides paginated browsing of the full directory.

资料来源：[examples/usage-examples.md:200-212](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md#L200-L212)

### Validation Workflow

When importing skills from unknown sources, a two-step validation approach is recommended:

1. **Fetch the skill**: Retrieve the raw content using `fetch_skill`
2. **Validate the content**: Use `validate_skill` to scan for security issues
3. **Convert if safe**: Apply `convert_to_steering` or `convert_to_power` if validation passes

```json
{ "tool": "fetch_skill", "arguments": { "identifier": "unknown/skill" } }
```

```json
{ "tool": "validate_skill", "arguments": { "content": "...", "url": "..." } }
```

资料来源：[examples/usage-examples.md:215-228](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md#L215-L228)

### Complete Import Workflow

For streamlined operations, the `import_skill` tool combines all steps into a single atomic operation:

1. **Search for trending skills**:
   ```json
   { "tool": "get_leaderboard", "arguments": { "timeframe": "24h", "limit": 20 } }
   ```

2. **Import a trending skill**:
   ```json
   { "tool": "import_skill", "arguments": { "identifier": "owner/skill-name", "outputFormat": "power" } }
   ```

资料来源：[examples/usage-examples.md:195-200](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md#L195-L200)

## Project Structure Reference

The deployment configuration is organized within a structured project layout that separates core functionality, tool implementations, and utilities:

```
skill-loader-mcp-server/
├── src/
│   ├── core/           # Core functionality
│   │   ├── conversion-engine.ts
│   │   └── errors.ts
│   ├── tools/          # MCP tool implementations
│   ├── utils/          # Utility functions
│   ├── index.ts        # Main entry point
│   └── cli.ts          # CLI entry point
├── examples/           # Usage examples
├── dist/               # Compiled output
└── tests/              # Test files
```

资料来源：[CONTRIBUTING.md:26-35](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CONTRIBUTING.md#L26-L35)

The `dist/` directory contains the compiled JavaScript output from the TypeScript source, which is the code actually executed during deployment. The `examples/` directory provides configuration examples and usage documentation that inform deployment procedures.

## Version History

The deployment and configuration capabilities have evolved through the following version milestones:

| Version | Date | Key Configuration Changes |
|---------|------|---------------------------|
| 1.1.0 | 2026-02-03 | Updated to `@modelcontextprotocol/sdk` v1.29, improved skills.sh API integration |
| 1.0.0 | 2026-02-03 | Initial release with 9 MCP tools and comprehensive error handling |

资料来源：[CHANGELOG.md:1-40](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/CHANGELOG.md#L1-L40)

---

<a id='error-handling'></a>

## Error Handling

### 相关页面

相关主题：[Security Validation](#security-validation), [Deployment and Configuration](#deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/core/errors.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/errors.ts)
- [src/core/security-validator.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/security-validator.ts)
- [README.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/README.md)
- [examples/usage-examples.md](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/examples/usage-examples.md)
- [src/core/conversion-engine.ts](https://github.com/goldzulu/skill-loader-mcp-server/blob/main/src/core/conversion-engine.ts)
</details>

# Error Handling

The Skill Loader MCP Server implements a comprehensive error handling system designed to provide consistent, informative, and actionable error feedback across all MCP tools. The system follows a hierarchical class structure that categorizes errors by their domain (validation, file system, network) and provides context-rich error messages with recovery suggestions.

## Architecture Overview

The error handling system is built on a base `SkillLoaderError` class that extends the native `Error` class, adding structured metadata and context tracking. This design enables consistent error formatting across all tools while maintaining type safety and enabling programmatic error handling.

```mermaid
graph TD
    A[Error Occurs] --> B{SkillLoaderError}
    B --> C[ValidationError]
    B --> D[FileSystemError]
    B --> E[NetworkError]
    C --> C1[security validation]
    C --> C2[format validation]
    D --> D1[read/write/delete/access]
    E --> E1[connection timeout]
    E --> E2[rate limiting]
    
    style A fill:#ff6b6b
    style B fill:#4ecdc4
    style C fill:#45b7d1
    style D fill:#96ceb4
    style E fill:#ffeaa7
```

## Error Class Hierarchy

### Base Class: SkillLoaderError

The base error class provides common functionality for all error types:

| Property | Type | Description |
|----------|------|-------------|
| `message` | `string` | Human-readable error message |
| `code` | `string` | Machine-readable error code |
| `timestamp` | `Date` | When the error occurred |
| `context` | `Record<string, any>` | Additional error context |

资料来源：[src/core/errors.ts:1-50]()

### ValidationError

Thrown when skill content fails security or format validation checks:

```typescript
export class ValidationError extends SkillLoaderError {
  public readonly validationType: 'security' | 'format';
  public readonly details?: string[];
}
```

**Validation Types:**

1. **Security Validation** - Triggered when dangerous patterns are detected:
   - Dangerous commands (`rm -rf`, `sudo`, `eval`, `exec`)
   - Suspicious file operations (`/etc/`, `/usr/`, `/bin/`)
   - Code injection patterns (`${...}`, `$(...)`)
   - Untrusted sources (non-GitHub URLs)

2. **Format Validation** - Triggered when skill structure is invalid:
   - Malformed YAML frontmatter
   - Missing required fields
   - Invalid markdown structure

资料来源：[src/core/errors.ts:60-120]()

### FileSystemError

Handles errors during file operations:

| Property | Type | Description |
|----------|------|-------------|
| `operation` | `'read' \| 'write' \| 'delete' \| 'access'` | Type of file operation |
| `filePath` | `string` | Target file path |
| `systemError` | `string \| undefined` | Raw system error message |

**System Error Codes:**

| Code | Meaning | Recovery Action |
|------|---------|-----------------|
| `EACCES` / `EPERM` | Permission denied | Check file permissions |
| `ENOSPC` | Disk full | Free up disk space |
| `ENOENT` | Path not found | Verify directory exists |
| `EEXIST` | File exists | Use `--overwrite` flag |

资料来源：[src/core/errors.ts:130-200]()

### NetworkError

Handles connectivity and API-related failures:

```typescript
export class NetworkError extends SkillLoaderError {
  public readonly url: string;
  public readonly statusCode?: number;
  public readonly retryable: boolean;
}
```

**Retry Behavior:**

- `retryable: true` - Transient errors (timeout, 503, rate limit)
- `retryable: false` - Permanent failures (404, 401, 403)

资料来源：[src/core/errors.ts:200-280]()

## Security Validation

The security validator analyzes skill content before import to prevent malicious code execution.

### Security Issue Types

```mermaid
graph LR
    A[Skill Content] --> B{Security Validator}
    B --> C[Dangerous Commands]
    B --> D[Suspicious Patterns]
    B --> E[Untrusted Sources]
    
    C --> C1[rm -rf, sudo, eval]
    D --> D1[Code injection, path traversal]
    E --> E1[Non-GitHub URLs]
```

### Severity Levels

| Severity | Condition | Import Behavior |
|----------|-----------|------------------|
| `safe` | No issues found | Allowed |
| `warning` | Suspicious patterns only | Allowed with notice |
| `unsafe` | Dangerous commands OR untrusted sources | Blocked by default |

资料来源：[src/core/security-validator.ts:1-50]()

### Validation Response Format

```json
{
  "isValid": false,
  "issues": [
    {
      "type": "dangerous_command",
      "description": "Dangerous recursive delete command (rm -rf)",
      "location": "Line 7: rm -rf /"
    }
  ],
  "severity": "unsafe"
}
```

资料来源：[examples/usage-examples.md:30-40]()

## Error Response Format

All MCP tools return errors in a standardized JSON format:

```json
{
  "error": "Error message describing what went wrong",
  "tool": "tool_name",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

### Common Error Scenarios

| Scenario | Tool | Error Message Pattern |
|----------|------|----------------------|
| Network failure | `fetch_skill`, `list_skills` | "Failed to connect to GitHub/skills.sh" |
| Not found | `fetch_skill` | "Skill not found: {identifier}" |
| Validation failure | `validate_skill`, `import_skill` | "Security validation failed" |
| Parsing error | `convert_to_*` | "Failed to parse skill content" |

资料来源：[README.md:150-170]()

## Error Recovery Suggestions

The error system provides actionable recovery guidance based on error type.

### Validation Errors

```
Suggestions:
- Review the skill content manually
- Contact the skill author about security concerns
- Use a different skill from a trusted source
```

### File System Errors

```
Suggestions:
- Check file permissions (EACCES/EPERM)
- Free up disk space (ENOSPC)
- Verify the directory exists (ENOENT)
- Use the --overwrite flag to replace existing files (EEXIST)
```

### Network Errors

```
Suggestions:
- Check internet connection
- Verify GitHub availability
- Retry the request after a short delay
- Use cached results if available
```

资料来源：[src/core/errors.ts:180-220]()

## Error Flow Diagram

```mermaid
sequenceDiagram
    participant Tool as MCP Tool
    participant Engine as Conversion Engine
    participant Validator as Security Validator
    participant FS as File System
    
    Tool->>Engine: process(content)
    Engine->>Validator: validate(content)
    
    alt Validation Failed
        Validator-->>Tool: ValidationError
        Tool->>Tool: Return error with suggestions
    end
    
    Engine->>FS: write(output)
    
    alt File System Error
        FS-->>Tool: FileSystemError
        Tool->>Tool: Return error with path info
    end
    
    alt Success
        Validator-->>Engine: isValid: true
        Engine-->>Tool: Success result
    end
```

## Best Practices

1. **Always validate before import** - Use `validate_skill` to check content safety
2. **Handle errors gracefully** - Check for error responses before processing results
3. **Use try-catch blocks** - Wrap tool calls to handle unexpected errors
4. **Check severity levels** - Distinguish between warnings and blocking errors
5. **Preserve error context** - Log error timestamps and tool names for debugging

资料来源：[examples/usage-examples.md:180-200]()

## Configuration

Error handling behavior can be influenced through these configuration options:

| Option | Description | Default |
|--------|-------------|---------|
| `skipValidation` | Bypass security checks during import | `false` |
| `timeout` | Request timeout in milliseconds | Platform-specific |
| `maxRetries` | Maximum retry attempts for network errors | Configurable |

资料来源：[README.md:140-150]()

---

---

## Doramagic Pitfall Log

Project: goldzulu/skill-loader-mcp-server

Summary: Found 9 potential pitfall items; 0 are high/blocking. Highest priority: configuration - 可能修改宿主 AI 配置.

## 1. configuration · 可能修改宿主 AI 配置

- Severity: medium
- Evidence strength: source_linked
- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。
- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- Evidence: capability.host_targets | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | host_targets=mcp_host, claude

## 2. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | README/documentation is current enough for a first validation pass.

## 3. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | last_activity_observed missing

## 4. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | no_demo; severity=medium

## 5. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | no_demo; severity=medium

## 6. security_permissions · 来源证据：v1.0.0 - Initial Release

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v1.0.0 - Initial Release
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_fb2ea148b03e4fb5993d3b2db08b43f6 | https://github.com/goldzulu/skill-loader-mcp-server/releases/tag/v1.0.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 7. security_permissions · 来源证据：v1.1.0 — skills.sh API migration & Power format update

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v1.1.0 — skills.sh API migration & Power format update
- User impact: 可能影响升级、迁移或版本选择。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_78c48e3f6caa41a9bf94d3dba01baf0c | https://github.com/goldzulu/skill-loader-mcp-server/releases/tag/v1.1.0 | 来源类型 github_release 暴露的待验证使用条件。

## 8. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | issue_or_pr_quality=unknown

## 9. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:1148400928 | https://github.com/goldzulu/skill-loader-mcp-server | release_recency=unknown

<!-- canonical_name: goldzulu/skill-loader-mcp-server; human_manual_source: deepwiki_human_wiki -->
