Skip to content
cc-hooks-ts を使用した Claude Code Hooks 作成ガイド logo

cc-hooks-ts を使用した Claude Code Hooks 作成ガイド

TypeScriptで型安全なClaude Code Hooksを作成するためのガイド。cc-hooks-tsライブラリを使用してフックを実装する際に使用する。(1) Claude Code用の新しいhookを作成する時、(2) 既存のhookをTypeScriptで書き直す時、(3) PreToolUse/PostToolUse/SessionStart等のイベントフックを実装する時、(4) plugin.jsonにhooksを設定する時

SKILL.md

Full skill instructions

cc-hooks-ts を使用した Claude Code Hooks 作成ガイド

インストール

bun add cc-hooks-ts

基本的なフック構造

#!/​usr/​bin/​env bun
import { defineHook, runHook } from "cc-hooks-ts";

const hook = defineHook({
  trigger: {
    // トリガーするイベントを指定
    PostToolUse: {
      Write: true,
      Edit: true,
    },
  },
  // オプション: 条件付き実行
  shouldRun: () => {
    return process.platform === "darwin"; // macOSのみ
  },
  run: (context) => {
    // フックのロジック

    // 成功レスポンス(何もしない)
    return context.success({});

    // または、追加コンテキストを返す
    return context.json({
      event: "PostToolUse",
      output: {
        hookSpecificOutput: {
          hookEventName: "PostToolUse",
          additionalContext: "Claude へのメッセージ",
        },
        suppressOutput: true,
      },
    });

    // または、エラーでブロック
    return context.blockingError("操作をブロックしました");
  },
});

if (import.meta.main) {
  await runHook(hook);
}

サポートされているイベント

イベント説明ユースケース
SessionStartセッション開始時環境チェック、初期設定
PreToolUseツール使用前操作のブロック、入力検証
PostToolUseツール使用後ログ記録、追加処理
PostToolUseFailureツール失敗時エラーハンドリング
Notification通知イベントアラート処理

ツール固有のフック

特定のツールに対してのみフックをトリガーする場合:

const hook = defineHook({
  trigger: {
    PreToolUse: {
      Read: true,  // Read ツールのみ
    },
  },
  run: (context) => {
    const filePath = context.input.tool_input.file_path;

    // .env ファイルへのアクセスをブロック
    if (filePath.endsWith(".env")) {
      return context.blockingError("環境ファイルへのアクセスは許可されていません");
    }

    return context.success({});
  },
});

主要 API

context オブジェクト

メソッド説明
context.success({})成功レスポンス(処理を続行)
context.blockingError(message)エラーでブロック
context.json(response)構造化レスポンス(追加コンテキスト付き)

context.input の構造

interface HookInput {
  event: string;           // イベント名
  tool_name?: string;      // ツール名(ToolUse系イベント)
  tool_input?: Record<string, any>;  // ツールの入力パラメータ
  tool_output?: string;    // ツールの出力(PostToolUse)
}

plugin.json での設定

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "bun run -i --silent ${CLAUDE_PLUGIN_ROOT}/​path/​to/​hook.ts"
          }
        ]
      }
    ]
  }
}

重要:

  • bun run -i --silent を使用すること
  • ${CLAUDE_PLUGIN_ROOT} でプラグインルートを参照

実装例

例1: ファイル書き込み時に知見ファイルを提案

#!/​usr/​bin/​env bun
import { existsSync } from "node:fs";
import { basename } from "node:path";
import { defineHook, runHook } from "cc-hooks-ts";

const hook = defineHook({
  trigger: {
    PostToolUse: {
      Write: true,
      Edit: true,
    },
  },
  run: (context) => {
    const filePath = context.input.tool_input.file_path;
    const knowledgePath = `${filePath}.knowledge.md`;

    if (existsSync(knowledgePath)) {
      return context.json({
        event: "PostToolUse",
        output: {
          hookSpecificOutput: {
            hookEventName: "PostToolUse",
            additionalContext: `${knowledgePath} に知見を追記してください`,
          },
          suppressOutput: true,
        },
      });
    }

    return context.success({});
  },
});

if (import.meta.main) {
  await runHook(hook);
}

例2: 特定ディレクトリへの書き込みをブロック

#!/​usr/​bin/​env bun
import { defineHook, runHook } from "cc-hooks-ts";

const PROTECTED_DIRS = ["/​etc", "/​usr", "/​System"];

const hook = defineHook({
  trigger: {
    PreToolUse: {
      Write: true,
    },
  },
  run: (context) => {
    const filePath = context.input.tool_input.file_path;

    for (const dir of PROTECTED_DIRS) {
      if (filePath.startsWith(dir)) {
        return context.blockingError(
          `${dir} への書き込みは許可されていません`
        );
      }
    }

    return context.success({});
  },
});

if (import.meta.main) {
  await runHook(hook);
}

例3: セッション開始時の環境チェック

#!/​usr/​bin/​env bun
import { existsSync } from "node:fs";
import { defineHook, runHook } from "cc-hooks-ts";

const hook = defineHook({
  trigger: {
    SessionStart: true,
  },
  run: (context) => {
    const requiredFiles = [".env", "package.json"];
    const missing = requiredFiles.filter(f => !existsSync(f));

    if (missing.length > 0) {
      console.error(`警告: 以下のファイルが見つかりません: ${missing.join(", ")}`);
    }

    return context.success({});
  },
});

if (import.meta.main) {
  await runHook(hook);
}

カスタムツール型の拡張

MCP で定義されたカスタムツールに型を追加する場合:

import { defineHook } from "cc-hooks-ts";

declare module "cc-hooks-ts" {
  interface ToolSchema {
    my_custom_tool: {
      input: { query: string };
      output: { result: string };
    };
  }
}

const hook = defineHook({
  trigger: {
    PostToolUse: {
      my_custom_tool: true,
    },
  },
  run: (context) => {
    // context.input.tool_input は { query: string } として型付けされる
    return context.success({});
  },
});

ベストプラクティス

  1. エラーハンドリング: try-catch で予期しないエラーをキャッチ
  2. クールダウン: 頻繁なトリガーを避けるためクールダウン機構を実装
  3. ログ出力: console.error() でユーザーに情報を表示(console.log は避ける)
  4. 冪等性: 同じ入力に対して同じ結果を返すように設計
  5. 軽量化: フック処理は高速に完了するよう設計

参考リンク

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View