← Academy 日本語で学ぶ(一覧へ戻る)

claude code in action

Anthropic Academy コースの日本語ナレッジ(学習用)/ 全 21 項目

Claude Code in Action 全文ナレッジ(DA式・日本語)

Anthropic Academy 公式コース「Claude Code in Action」の全レッスンを、DA(ダイレクトアカデミー)ナレッジと同格の完全版でナレッジ化したもの。各動画ノートは4層構成:

  1. 日本語ナレッジ(要点整理) — 講義の構造化サマリ
  2. 実務ポイント — 持ち帰り事項
  3. 本文(時系列・日本語逐語+画面差し込み) — 音声の日本語全訳に、画面フレーム372枚から読解したコマンド・コード・UI・スライドを時刻付きで差し込み。hooks 系レッスンは演習プロジェクトの実物コード全文(read_hook.js / tsc.js / query_hook.js / settings 等)も掲載
  4. 英語逐語(ASR全文) — 原文ママ
  • 修了証: https://verify.skilljar.com/c/cw5bokenygwf(NAOKI NAKASHIMA / 2026-07-02 / Anthropic Education)
  • 講師: Steven Grider (Anthropic) / 動画15本 計約63分 + テキストレッスン4本 + クイズ8問(合格済み)
  • 生成: jwplayer 署名付き HLS → ffmpeg(映像+音声)→ mlx_whisper large-v3-turbo(srt・13,117語)+ シーン検出フレーム372枚の画面読解 → Claude 5並列によるDA式統合(2026-07-02)
  • 検証(2パス目・2026-07-03): 画面差し込みが45秒以上空く全13区間を8秒毎の高密度フレーム113枚で再検証→未転記4件を追加・時刻矛盾2件を補正。全19ノートの整合性検収(構成・時系列単調性・要点↔本文矛盾・用語統一)で6件是正済み。講義実装の正確な差分は assets_and_lecture_diffs.md
  • 概要版: ../claude-code-in-action-course-notes.md(コース構成・クイズ全問・講座A設計への学び)
  • 演習素材(実物): assets/uigen/(Module 2 の題材アプリ)・assets/queries/(hooks 演習の開始状態)・assets/queries_COMPLETED/講義完成形:hooks 3本+settings+init スクリプト+pre/post-log.json)

目次

Module 1 — What is Claude Code?(概念)

# ノート 時間 ひとこと
01 Introduction 0:38 コースの4部構成の予告
02 What is a Coding Assistant? 5:53 LM はテキスト入出力のみ→tool use が中核。Claude Code の3つの強み
03 Claude Code in Action 8:25 実演4本:Chalk 3.9倍最適化・Jupyter チャーン分析・Playwright MCP・GitHub Actions で PII 検知

Module 2 — Getting Hands On(実践)

# ノート 時間 ひとこと
t1 Claude Code setup text インストール4通り+初回起動
t2 Project setup text 演習プロジェクト uigen のセットアップ
04 Adding Context 5:14 「理想のコンテキスト量」・/init・CLAUDE.md 3レベル・#メモリ・@メンション
05 Making Changes 4:04 スクショは Ctrl+V・Plan Mode(広さ)× Thinking(深さ)
06 Controlling Context 3:37 Esc 割り込み・Esc×2 巻き戻し・/compact・/clear の使い分け
07 Custom Commands 1:44 .claude/commands/*.md と $ARGUMENTS
08 MCP Servers 2:53 claude mcp add・Playwright でプロンプト自己改善ループ
09 Github Integration 3:40 /install-github-app・@claude メンション・CI では MCP ツール個別許可

Module 3 — Hooks and the SDK(拡張・自動化)

# ノート 時間 ひとこと
10 Introducing Hooks 3:37 PreToolUse=検査・ブロック/PostToolUse=後続処理・フィードバック
11 Defining Hooks 3:44 フック設計4ステップ(イベント→matcher→stdin JSON→exit 0/2)
12 Implementing a Hook 4:14 .env 読取禁止フックの実装(exit(2)・再起動必須)
13 Useful Hooks! 11:33 実用2本:編集毎 tsc 型チェック・SDK で別 Claude Code を起動するレビューフック
t3 Gotchas around hooks text 絶対パス推奨と共有性の両立($PWD+init スクリプト)
t4 Another useful hook text 全7フックイベント・stdin 構造の違い・jq デバッグフック
14 The Claude Code SDK 2:46 CLI/TS/Python からのプログラム利用・デフォルト read-only

Module 4 — Wrapping Up

# ノート 時間 ひとこと
15 Wrap Up 0:53 総括3アドバイス:最新を追う・実験する・GitHub 連携で自動化

逐語データ

  • transcripts/ — ASR 原文 txt(15本)+テキストレッスン原文(text_lessons.md)
  • 注意: 逐語内の「Cloud Code」「clod.md」等は ASR の誤認識で原文ママ。日本語ナレッジ側は正しい表記に正規化済み
↑ 目次へ戻る

Claude Code in Action | Lesson 01「Introduction」(全文ナレッジ)

動画 0分38秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

講師と趣旨

  • 講師は Anthropic の technical staff メンバー、Steven Grider。
  • 本コースの目的は、受講者を Claude Code を使いこなせる状態に引き上げること("get you up to speed with Claude Code")。

コースの4部構成

講義全体は以下の4セクションで進む。

  1. コーディングアシスタントとは何か — まず「コーディングアシスタント」が正確に何なのかを理解する時間を取る。
  2. Claude Code そのもの — 市場にある数多くのコーディングアシスタントの中で、Claude Code を際立たせているものは何かを理解する。
  3. 典型的なプロジェクトでの実践 — 実際のプロジェクトで Claude Code を使うウォークスルーを行い、ハンズオン経験を積む。
  4. 自分のプロジェクトで最大限活用する方法 — 締めくくりとして、受講者自身のプロジェクトで Claude Code から最大の成果を引き出す方法を見る。

実務ポイント(このレッスンから持ち帰るもの)

  • コースは「概念理解 → Claude Code の差別化要因 → ハンズオン → 自分のプロジェクトへの適用」の4段階で設計されている。この順で学ぶのが前提。
  • 技術的な話に入る前に「コーディングアシスタントとは何か」の理解を挟む構成=道具の内部動作を理解してから使う、という学習方針。
  • 最終ゴールは「自分のプロジェクトで最大限活用できる」状態。デモの再現ではなく応用が着地点。

本文(時系列・日本語逐語+画面差し込み)

[0:00] こんにちは、ようこそ。私の名前は Steven Grider(スティーブン・グライダー)、Anthropic の technical staff(技術スタッフ)の一員です。このコースでは、皆さんを Claude Code を使いこなせる状態まで引き上げていきます。技術的な話に深く入る前に、これから学ぶ内容のクイックな概要をお見せしたいと思います。

🖥 [0:13] 画面: スライド「Course goals」(Anthropic ロゴ入り・クリーム色背景)。右側に4つの角丸カードが縦に並ぶ: 1. What's a coding assistant? 2. Why Claude Code? 3. Working with Claude Code as a partner 4. Getting the most out of Claude Code

[0:13] このコースは4つのセクションで構成されています。まず最初に、コーディングアシスタントとは正確に何なのかを理解する時間を取ります。次に Claude Code そのものを見て、市場にある数多くのコーディングアシスタントの中で Claude Code を際立たせているものは何かを理解します。

[0:27] それを押さえたら、典型的なプロジェクトで Claude Code を使うウォークスルーを行い、ハンズオンの経験を積みます。最後に締めくくりとして、皆さん自身のプロジェクトで Claude Code から最大限の成果を引き出す方法を見ていきます。

英語逐語(ASR全文)

Hello and welcome. My name is Steven Greider and I'm a member of technical staff at Anthropic. In this course, we're going to get you up to speed with Claude Code. And before we get into anything too technical, I want to give you a quick overview on what we'll be learning.

This course is organized into four sections. We're going to first spend some time to understand exactly what a coding assistant is. We'll then take a look at Claude Code itself and understand what makes it stand out among all the different coding assistants on the market. Once we've established that, we'll walk through the use of Claude Code on a typical project and get some hands-on experience. Finally, we'll wrap things up by seeing how you can get the most out of Claude Code on your own projects.

↑ 目次へ戻る

Claude Code in Action | Lesson 02「What is a Coding Assistant?」(全文ナレッジ)

動画 5分53秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

コーディングアシスタントの内部動作モデル

  • コーディングアシスタントは「コードを書くツール」だが、裏側で何が起きているかを理解すると「本当に優れたアシスタント」の条件が見えてくる。
  • 動作イメージ(例:エラーメッセージに基づくバグ修正タスク): 1. タスクを受け取る — アシスタントにタスクが与えられる 2. 言語モデルに渡す — 内部で言語モデル(LM)が解決方法を考える 3. コンテキスト収集 — エラーが何を指すか、コードベースのどこでエラーが出ているか、どのファイルが関連しそうかを把握(人間の働き方とよく似ている) 4. 計画の策定 — コードを変更し、テストを実行または作成して修正を検証する、といった計画を立てる 5. アクション実行 — ファイルを更新し、テストを実行する
  • 重要な観察:最初のステップ(コンテキスト収集)と最後のステップ(アクション)は、外の世界から情報を得る/外の世界に影響を与える「実際の行為」を必要とする。例:ファイルを読む、オンラインのドキュメントを取得する、コマンドを実行する、ファイルを編集する。

言語モデル単体には「行為」ができない

  • コーディングアシスタントの外で言語モデルと直接やり取りする場面を想像する:main.go ファイルの中身を尋ねても、素の言語モデルにはファイルを読む能力が本来的に無い。
  • 言語モデルはテキストを受け取り、テキストを返す。それが能力の全て。これは全ての言語モデルに共通の事実。
  • 素の言語モデルにファイルを読むよう頼むと、「ファイルを読む能力はありません」と答えるのがオチ。

tool use(ツール使用)の仕組み

言語モデルに「ファイルを読ませる」ために、コーディングアシスタント(や他の多くのツール)がやっていること:

  1. ユーザーがリクエストを送ると、アシスタントが裏で大量のテキストを自動的に追記する。例:「(言語モデルである)あなたがファイルを読みたい場合は、この厳密にフォーマットされたメッセージで応答せよ」——例えば ReadFile: <ファイル名> のような形式。
  2. 言語モデルは質問に答えるにはファイルを読む必要があると気づき、ReadFile: main.go のような応答を返す。
  3. アシスタント側がこの厳密フォーマットのメッセージを受け取り、「モデルがファイル読み取りというアクションを取りたがっている」と解釈して、実際にファイルを読み、その内容を言語モデルに送り返す。
  4. ファイルの実際の中身を受け取った言語モデルが、最終的な応答(「このファイルを読んだところ、中身は~」)をユーザーに返す。
  • この「モデルに追加の指示を与え、厳密にフォーマットされた形で応答させる」仕組み全体を tool use と呼ぶ。
  • 役割分担:モデル=特定の形式で応答する責任アシスタント=約束された行為(ファイルの読み書き等)を実際に実行する責任
  • 世の中の全ての言語モデルがこの tool use の考え方で動いている。

Claude の tool use が Claude Code の中核的強み

  • Claude 系モデル(Opus・Sonnet・Haiku)は、ツールが呼ばれたとき何をするかの理解、タスク完了への効果的な利用、さらに高度・複雑なタスクのための面白い組み合わせ方が特に強い
  • Claude の強力な tool use は、コーディングアシスタントとしての Claude Code の「絶対的な中核の強み」。理由は3つ: 1. より複雑なタスクを扱える — tool use が優れているほど複雑なタスクに対応できる 2. 拡張性 — Claude Code 自体が拡張可能で、新しいツールの追加が非常に簡単。Claude はそれらを喜んで使いこなす。開発の世界の速い変化を踏まえると「継続的な relevance(今後も使い続けられること)」に特に重要=Claude Code は今後何年もあなたと共に変化していくアシスタント 3. セキュリティ向上 — tool use が優れていると、インデックス化に頼らずにコードベースを効果的に検索して関連コードを見つけられる。インデックス化はコードベース全体を外部サーバーへ送ることに依存しがちなので、それを避けられる

このレッスンのまとめ(講師による復習)

  • コーディングアシスタントは内部で言語モデルを使ってタスクを完了する。
  • 言語モデルは、与えられるタスクの大半をこなすために tool use を知っている必要がある。
  • ツールはファイルの読み取り・書き込み・コマンド実行など、「テキスト生成以外のほぼ全て」に使われる。
  • 全ての言語モデルが同じレベルでツールを使えるわけではなく、その差がコーディングアシスタント全体の効率に大きく影響する

実務ポイント(このレッスンから持ち帰るもの)

  • LMは「テキストin・テキストout」しかできない。ファイル読み書き・コマンド実行はすべて tool use(モデルが形式化された応答→アシスタントが実行)で実現されている、という基本構造を押さえる。
  • コーディングアシスタントの品質差=ほぼ「モデルの tool use の巧さ」の差。ツール選択・組み合わせの質がアシスタントの効率を決める。
  • Claude Code の中核強みは Claude(Opus/Sonnet/Haiku)の tool use 能力。①複雑タスク対応 ②ツール追加が容易な拡張性 ③インデックス不要(コード外部送信を避ける)のセキュリティ、の3点で効く。
  • 新しいツールを足せば Claude はそれを使いこなす=環境変化への追従はツール追加で対応できる、という設計思想を活用する。

本文(時系列・日本語逐語+画面差し込み)

[0:00] この動画では、コーディングアシスタントとは何かをより深く理解していきます。ええ、コーディングアシスタントはコードを書くツールです。ただ、その舞台裏で何が起きているのか、より深い理解を皆さんに持ってもらいたいのです。というのも、コーディングアシスタントが本当は何をしていて、どう動いているのかを理解すると、あなたのチームを補完する「本当に素晴らしいアシスタント」を成り立たせているものが、より深く味わえるようになるからです。

🖥 [0:00] 画面: タイトルスライド「What is a coding assistant?」(ANTHROP\C ロゴ・ベージュ背景)

[0:25] コーディングアシスタントが何をしているかをイメージする一つの方法がこちらです。アシスタントはまずタスクを与えられます。この例では、何らかのエラーメッセージに基づいてバグを修正する必要があるとしましょう。このタスクは内部で言語モデルに渡され、言語モデルが問題の解決方法を考える必要があります。さて、言語モデルによって問題の解き方のスタイルは異なりますし、タスクの複雑さにも依存します。しかし多くの場合、人間の働き方と非常によく似た動きをします。まず、エラーが何を指しているのか、コードベースのどの領域でエラーが投げられているのか、どのファイルが関連していそうかを理解して、コンテキストを収集する必要があるでしょう。

🖥 [0:21] 画面: 図解スライド「Assistant」。左に Task ボックス: Got an error. Find and fix the issue. Here's the error: Cannot read property 'records' of undefined 矢印 → Assistant 枠内に「Language Model」⇄「Set of tools」、そこから右へ「Gather context」→「Formulate a plan」→「Take an action」の3段フロー+「Iterate」の戻り矢印。下部の箇条書き: - Most coding assistants use remotely hosted language models - Claude Code uses the Claude series of models hosted at Anthropic, AWS, or Google Cloud (configurable)

[0:53] その情報を集め終えたら、次に、どうやって実際にタスクを達成するかの計画を策定する必要があります。この例では、コードをいくらか変更し、それから問題が実際に修正されたことを検証するテストを実行するか書くか、と決めるかもしれません。最後に、アクションを実行します。この例では、ファイルを更新してテストを実行する、といったことになるでしょう。

[1:10] さて、この一連のプロセスについてもう少し情報を補足したいと思います。特に注目してほしいのは、ここの最初と最後のステップでは、コーディングアシスタントが実際に「何かを行う」必要があるという点です。言い換えると、外の世界から実際に情報を収集したり、外の世界に何らかの形で影響を与えたりする必要があるのです。例えば、コンテキストを収集するには、アシスタントはファイルを読んだり、オンラインでドキュメントを取得したりする必要があるかもしれません。そしてアクションを取るには、アシスタントは実際にコマンドを実行したり、ファイルを編集したりする必要があるかもしれません。

[1:38] ところが、言語モデルに実際にこれらのことをやらせるのは、聞こえよりも少しトリッキーです。なぜそうなのか、理解を助けましょう。私たちが言語モデルと直接やり取りしている場面を想像してください。つまり、コーディングアシスタントの類の中で動いているのではない、ということです。そして、この言語モデルに直接「main.go ファイルの中にはどんなコードが書かれていますか」と尋ねたとしましょう。

🖥 [1:48] 画面: シーケンス図。左「You」、右「Language Model」(注記 Running outside of any coding assistant)。You → Language Model への矢印: What code is written in the main.go file?

[1:59] コーディングアシスタントや類似ツールのコンテキストの外で動いている言語モデルは、ファイルを読むとか、コマンドを書く(実行する)とかいった能力を本来的に持っていません。言語モデルはテキストのようなコンテンツを受け取り、テキストを返す。それだけです。それが彼らの能力の全範囲です。そしてこれは全ての言語モデルに当てはまります。ですから、素の言語モデルにテキストを送ってファイルを読むよう頼んだら、おそらく「ファイルを読む能力はありません」という趣旨の応答が返ってくるでしょう。

🖥 [2:00] 画面: 同じシーケンス図に Language Model → You の応答矢印が追加される: I'm sorry, but I don't have the ability to read any files

[2:32] では、言語モデルに「引用符付きの意味で」ファイルを読ませるために、コーディングアシスタントや世の中の非常に多くのツールが実際に何をしているのかをお見せしましょう。こういうことが起きます。あなたがコーディングアシスタントにリクエストを送ると、コーディングアシスタントは舞台裏で、あなたのリクエストに大量のテキストを自動的に追記します。この例では、コーディングアシスタントが「言語モデルであるあなたがファイルを読みたい場合は、この非常に注意深くフォーマットされたメッセージで応答せよ」というようなテキストを追加すると想像できます。例えば「ReadFile:(コロン)読みたいファイル名」のような形式です。

[3:06] するとこの場合、言語モデルは、私たちの質問に答えるためにはそのファイルを読む応答をする必要がある、と気づいてくれるはずです。そこで「ReadFile: main.go」と応答するかもしれません。

🖥 [3:00] 画面: 3者のシーケンス図「You/Coding Assistant/Language Model」。 - You → Coding Assistant: What code is written in the main.go file? - Coding Assistant → Language Model: What code is written in the main.go file? If you want to read a file, respond with "ReadFile: name of file"(←アシスタントが裏で追記した指示) - Language Model → Coding Assistant: ReadFile: main.go

[3:17] さて、この非常に注意深くフォーマットされたメッセージを受け取り、「言語モデルがファイル読み取りという何らかのアクションを取りたがっている」と理解するのはコーディングアシスタントの役目です。そこでコーディングアシスタントが、実際にそのファイルを読み、そのファイルの中身を言語モデルに送り返す責任を持ちます。ファイルの実際の中身を受け取った言語モデルは、私たちに送り返される最終応答を書けるようになります。そこでは「このファイルを読みました。中身はこれこれのコードです」など、そのファイルの中にあるものが何であれ、それを述べるでしょう。

🖥 [3:30] 画面: 同じ3者シーケンス図の続き: - Coding Assistant → Language Model: <Contents of main.go file>(ファイルの実際の中身) - Language Model → You: The main.go file contains code to initialize the application and...(最終応答)

[3:46] 言語モデルにこうした追加の小さな指示を与え、非常に整った・注意深くフォーマットされた形で応答するよう頼む、このシステム全体を tool use(ツール使用) と呼びます。つまり、ツールはモデルに追加の能力を与えるために使われるのです。モデルは非常に特定の形式で応答する責任を持ち、そしてコーディングアシスタントのようなものが、約束された内容——実際にファイルを読む、ファイルを書く、その他何であれ——を実際に実行する責任を持ちます。繰り返しますが、これは世の中の全ての言語モデルの動き方です。全てがこの tool use の考え方で動いています。

🖥 [3:47] 画面: スライド「Tool Use」。左の箇条書き: - Models are given plain text directions on how to respond a certain way to use a 'tool' - When the model responds with a request to use a tool, the coding assistant does whatever the tool is supposed to do (read a file, write a file, make a request, etc) - The Claude series of models (Opus, Sonnet, Haiku) are particularly strong at understanding what tools do and using them to complete tasks

右に Coding Assistant ⇄ Language Model のシーケンス図(ReadFile 例の要約再掲)

[4:20] さて、ここが理解すべき決定的な部分です。Claude 系のモデル——つまり Opus、Sonnet、Haiku——は、ツールが呼ばれたときに何をするのかを理解すること、タスクを効果的に完了するために実際にツールを使うこと、そしてより高度で複雑なタスクを完了するためにツールを本当に面白い組み合わせで使うことに、特に強いのです。Claude の強力な tool use は、コーディングアシスタントとしての Claude Code の絶対的な中核の強みです。理由はこうです。

[4:44] 第一に、今申し上げたとおり、より優れた tool use があれば、Claude はより複雑なタスクを扱えます。第二に、Claude Code 自体が拡張可能(extensible)です。Claude Code に新しいツールを追加するのは本当に簡単で、Claude はそれらのツールを喜んで使いこなします。これは、開発の世界で私たちが目にしている速い変化を考えると、「継続的なレレバンス(今後も価値を持ち続けること)」のために特に重要です。言い換えれば、Claude Code はこの先何年もあなたと共に変化していくアシスタントだということです。そして最後に、tool use が向上すると、多くの場合セキュリティも向上します。Claude はインデックス化に頼らずにコードベースを効果的に検索して関連コードを見つけられるからです。インデックス化はしばしば、コードベース全体を外部サーバーに送信することに依存しています。

🖥 [4:38] 画面: スライド「Strong tool use is everything — Tool use strength allows for unique (and unexpected) benefits」。3枚のカード: 1. Claude Code can tackle harder tasks — Claude will eagerly combine together different tools to handle more complex work / Claude will adeptly use tools it hasn't seen before 2. Claude Code is extensible — You can easily add additional tools (capabilities) to Claude Code / Adding tools allows customization for your particular workflow / Adding tools allow Claude Code to keep up with rapid changes in AI-enable development 3. Improved security — Thanks to Claude's strong tool use, Claude Code has can easily navigate codebases / Claude Code doesn't rely upon indexing your codebase, which often requires sending your entire codebase to outside servers

[5:25] この動画で学んだ「コーディングアシスタントとは本当は何か」を素早く復習しましょう。覚えておいてください。コーディングアシスタントは、さまざまなタスクを完了するために内部で言語モデルを使います。これらの言語モデルは、与えられるタスクの大半に取り組むために、ツールの使い方を知っている必要があります。ツールはファイルの読み取り、ファイルの書き込み、コマンドの実行、そして本質的に「単なるテキスト生成ではない」ほぼ全てのことに使われます。全ての言語モデルが同じレベルでツールを使いこなすわけではなく、この差はコーディングアシスタント全体の効率に大きな影響を与えます。

🖥 [5:23] 画面: まとめスライド「What is a coding assistant?」。4つのカード: - Coding assistants use language models to complete different tasks - Language models need to use tools to work a vast majority of tasks - Not all language models use tools with the same finesse - Claude's strong tool use with Claude Code allows for better security, customization, and longevity

英語逐語(ASR全文)

※ ASR原文ママ("CloudCode"=Claude Code、"refile"=read file 等の誤認識を含む)

In this video, we're going to get a better understanding of what a coding assistant is. Yes, a coding assistant is a tool that writes code, but I want to give you a deeper understanding of what's going on behind the scenes. You see, by understanding what a coding assistant really does and how it works, you'll have a greater appreciation of what makes a truly amazing assistant to complement your team.

Here's one way that you can picture what a coding assistant is doing. An assistant is first given a task. In this case, maybe the assistant needs to fix a bug based upon some kind of error message. This task is passed off internally to a language model, which needs to figure out how to solve the issue. Now, different language models solve problems in different styles, depending upon the complexity of the task. But in many cases, they work very much like how a human would work. It first might need to gather context by understanding what the error is referring to, what area in the code base is thrown in the error, and what files seem to be relevant. Once it has gathered that information, it then needs to formulate a plan on how it will actually accomplish the task. In this case, it might decide to change some code and then run or write a test to verify that the issue is actually fixed. Finally, it will take an action. In this case, that might be updating a file and running the tests.

Now, I want to give you some more information on this entire process. In particular, I'd like you to notice that the first and last steps here require the coding assistant to actually do something. In other words to actually gather information from the outside world or affect the outside world in some way. For example, to gather context, the assistant needs to maybe read a file or fetch some documentation online. And for taking an action, the assistant might need to actually run a command or edit a file. Now having a language model actually do these things is a little bit trickier than it actually sounds. Let me help you understand why that is.

Let's imagine that we are interacting with a language model directly. So it's not running inside of any coding assistant or anything like that. Let's then imagine that we asked this language model directly what code is written inside the main.go file. Language models running outside the context of any coding assistant or similar tool do not inherently have the ability to say, read a file or write a command or anything like that. Language models take in content like text and they return text. That's it. That's the entire extent of their capabilities. And this is true of all language models. So if you were to send some text into a plain language model, asking it to read a file, it would most likely respond by saying that it doesn't have the ability to read any files.

So let me show you what coding assistants and many, many other tools out there do to actually allow a language model to quote unquote, read a file. So here's what happens. Whenever you send a request off to your coding assistant, the coding assistant behind the scenes is going to automatically append a lot of text into your request. In this particular case, we can imagine that the coding assistant is going to add on some text that says something like, if you language model want to read a file, respond with this very carefully formatted message. For example, maybe something like read file colon, and then the name of a file to read. So in this case, the language model would hopefully realize that in order to answer our question, it needs to respond by reading that file. So it might respond with refile colon main.go.

Now the coding assistant would be in charge of receiving this very carefully formatted message and realizing that the language model wants to take some kind of action by reading a file. So the coding assistant would then be responsible for actually reading the file and sending the contents of that file back into the language model. Now that the language model has received the actual contents of that file, it can write a final response that gets sent back to us, in which it might say, well, I read this file and it contains some amount of code or whatever else, whatever's inside that file.

This entire system of giving a language model these extra little instructions, asking it to respond in a very well formatted or carefully formatted way, is referred to as tool use. So tools are used to give models extra capabilities. The model is responsible for responding in a very particular way, and then something like our coding assistant would be responsible for actually doing whatever was promised. So actually reading a file or writing a file or whatever else. Again, this is how every single language model out there works. They all work with this idea of tool use.

Now here's the critical part to understand. The Claude series of models, so Opus, Sonnet, and Haiku, are particularly strong at understanding what tools do when they're called and actually using them to effectively complete tasks and using them in really interesting combinations to complete more advanced or complex tasks. Claude strong tool use is the absolute core strength of CloudCode as a coding assistant. Here's why. First, as I just mentioned, with better tool use, Cloud can handle more complex tasks. Second, CloudCode itself is extensible, so it's really easy to add in new tools to CloudCode. And Cloud will happily make use of those tools. This is especially important for continued relevance, given the fast changes that we're seeing in the world of development. In other words, Claude code is an assistant that will change with you in the years to come. And finally, with improved tool use, you often get better security because Claude can effectively search your code base to find relevant code without relying upon indexing, which often relies upon sending your entire code base to outside servers.

Let's do a quick review on what we learned inside this video around what a coding assistant really is. So remember, coding assistants use language models internally to complete different tasks. These language models, they need to know how to use tools to work on the vast majority of tasks that they are given. Tools are used to read files, write files, run commands, and essentially everything else that doesn't just involve generating some text. Not all language models make use of tools at the same level, and this has a big impact on the overall efficiency of a coding assistant.

↑ 目次へ戻る

Claude Code in Action | Lesson 03「Claude Code in Action」(全文ナレッジ)

動画 8分25秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

このレッスンの位置づけ

  • 前レッスンの「Claude はツール使用の達人」「Claude Code は簡単に拡張できる」という主張を、デモで実証する回。
  • Claude Code にはデフォルトツール一式がある:ファイル読み取り・ファイル書き込み・コマンド実行など、期待される能力は一通り揃っている。
  • デモは複数のタスクで構成され、いずれもこのツール群を知的に使う。少なくとも1つのタスクでは追加の新しいツール一式を Claude に与える=素の能力と拡張の容易さの両方を見せる。

デモ1:Chalk ライブラリのパフォーマンス最適化

  • Chalk は JavaScript パッケージ。テキストを色付き(色・背景・書式)で出力するだけの非常に小さなライブラリ。
  • しかし JavaScript エコシステム全体で5番目にダウンロードの多いパッケージ(直近1週間で 4億2,900万ダウンロード)。最適化できれば効果は絶大。
  • 依頼内容:ベンチマークを実行 → 最悪パフォーマンスのケースを特定 → プロファイリングツールで遅い原因を究明 → 修正。
  • Claude が使ったツールの流れ:
  • to-do リストを作って進捗管理
  • コマンド実行でベンチマークを走らせる
  • 特定ケースにズームインするためのファイルを書く
  • CPU プロファイラでそのケースが遅い理由を理解
  • 改善を実装
  • 結果:ある操作でスループット 3.9 倍の改善。

デモ2:CSV データ分析(Jupyter ノートブック)

  • 動画ストリーミングプラットフォームのユーザー情報が入った CSV データセットを渡し、全般的な分析+チャーン(解約)の原因特定を Jupyter ノートブック内で行うよう依頼。
  • ここが効果的なツール使用の要点:ノートブックにコードを書くだけでは不十分で、Claude は各セルのコードを実行し、実行結果を見ることができる。
  • つまり、まずデータを概観 → その結果を踏まえて後続セルを逐次カスタマイズし、特定の詳細に絞り込んでいける。

デモ3:Playwright MCP server でツールを拡張(UI スタイリング改善)

  • 題材:左側の説明入力から UI コンポーネントを生成し右側に表示する自作アプリ。コンポーネント生成は良好だが、左のチャットインターフェースと上部ヘッダーのスタイリングが良くない。
  • スタイリング修正だけなら普通に頼んでも十分こなせるが、機能追加の容易さを見せるため、Playwright MCP server が提供する新しいツール一式を Claude Code に与える(MCP の詳細は後の講義で説明)。
  • このツールで Claude はブラウザを直接開いて操作できる。実際の流れ: 1. アプリのスタイリング改善を「ブラウザを使って」行うよう依頼 2. Claude がブラウザを開き、アプリへ移動 3. スクリーンショットを撮って現状のスタイリングを確認 4. スタイリングを更新 5. 完了後に再度スクリーンショット → デザインを数回反復(iterate)して「映える」デザインに仕上げる

デモ4:GitHub 統合による自動 PR レビュー(PII 漏えい検知)

  • Claude Code は GitHub と密接に統合できる。GitHub Action の中で Claude Code を実行するよう設定でき、PR 作成時や issue 内での直接メンションなどのイベントで自動起動する。
  • GitHub 上で動く Claude Code は、コードの閲覧・実行に加えて GitHub 操作用の新しいツール一式(コメント作成・コミット作成・PR 作成など)にアクセスできる。これで PR の自動レビューが可能。
  • シナリオ設定:
  • AWS 上のインフラを Terraform ファイル一式で定義し、GitHub にコミット済み。インフラが Terraform で定義されているため、Claude Code はインフラ内の情報の流れを正確に把握できる
  • DynamoDB テーブルにユーザー情報(閲覧プラン plans viewed・登録日 registration date など)を保存
  • この2項目だけを社内マーケチームと社外のマーケチーム(別会社)に共有したい → 毎晩 Lambda 関数がテーブルから全ユーザーを取り出し、2項目だけ抽出して S3 バケットに保存。両チームがそこへアクセス
  • 数ヶ月後、社内チームから「メールアドレスも S3 に入れて」と依頼 → Lambda に1行だけコード追加。このバケットが外部パートナーと共有されていることを忘れている → 個人識別情報(PII)が別会社からアクセス可能な場所に置かれる重大ミス
  • この種のミスは実際に起こるうえ、バケットの共有状況を正確に把握していないと捕捉が難しい
  • 実演:Lambda にユーザーのメールをバケットへ追加する1行だけ変更した PR を作成 → Claude Code は自動レビューの中で、変更内容を確認し、インフラの仕組みを把握し、PII をパートナーに露出させていることを特定。データフローを段階的に列挙し、バケットが外部パートナーと共有されている経緯を詳細に説明した。
  • 価値:この種の問題をデプロイ後ではなく開発中に捕まえられる。このフローの具体的なセットアップ方法は後の講義で詳述される。

締めの原則

  • Claude Code は、優れたツール使用能力のおかげでこれだけのことができる。
  • Claude Code は「カスタマイズでき、チームのニーズに合わせて成長・変化していく柔軟なアシスタント」として捉えるべき

実務ポイント(このレッスンから持ち帰るもの)

  • デフォルトツール(read/write/コマンド実行等)だけでも「ベンチマーク→プロファイル→修正」の実測ドリブン最適化が回る。to-do リストで進捗管理させるのが型。
  • Jupyter 分析では「コードを書く」だけでなく「セルを実行して結果を見て次のセルを変える」ループが Claude Code の強み。分析タスクは実行結果を見せる設計にする。
  • UI 作業は Playwright MCP server を足して「スクリーンショット→修正→再スクリーンショット」の反復をさせると品質が上がる。
  • GitHub Actions 統合で PR 自動レビューが組める。インフラを Terraform などコードで定義しておくほど、Claude はデータフローを追跡でき、PII 露出のような設計レベルの事故を開発中に検知できる。
  • Claude Code は固定機能の道具ではなく、MCP 等でツールを足して育てる前提で運用する。

本文(時系列・日本語逐語+画面差し込み)

[0:00] つい先ほど、私はかなり大きな主張をしました。Claude はツールの使用に関して達人であり、Claude Code は簡単に拡張できる、と言ったのです。当然、皆さんは少し懐疑的かもしれません。そこで、いくつかの短いデモをお見せしたいと思います。この表にあるのは、Claude Code で利用できるデフォルトのツール群です。ファイルの読み取り、ファイルの書き込み、コマンドの実行など、期待されるであろう能力は全て揃っています。

🖥 [0:00] 画面: スライド「Tools with Claude Code」。Name/Purpose の2列表(2段組・Continued... 付き): | Name | Purpose | |---|---| | Agent | Launch a subagent to handle a task | | Bash | Run a shell command | | Edit | Edit a file | | Glob | Find files based upon a pattern | | Grep | Search the contents of a file | | LS | List files and directories | | MultiEdit | Make several edits at the same time | | NotebookEdit | Write to a cell in a Jupyter notebook | | NotebookRead | Read a cell | | Read | Read a file | | TodoRead | Read one of the created to-do's | | TodoWrite | Update the list of to-do's | | WebFetch | Fetch from a URL | | WebSearch | Search the web | | Write | Write to a file |

[0:21] これから Claude Code を使って完了させたいくつかのタスクをお見せします。それぞれのケースで、Claude はこのツール群をかなり知的な方法で使います。そして少なくとも1つのタスクでは、Claude に追加の新しいツール一式を与えて使わせます。このプロセスを通じて、Claude Code が「箱から出してすぐ」の状態で何ができるかがよく分かるだけでなく、Claude Code をさらなる機能でいかに簡単に拡張できるかも見えてくるはずです。

[0:46] これが Claude Code への最初のタスクです。Chalk ライブラリのパフォーマンス問題を見つけて最適化するよう頼みます。ご存じない方のために言うと、Chalk は JavaScript のパッケージです。これがそのドキュメントです。これは非常に小さなライブラリで、目的はただ一つ、とてもシンプルです。テキストをきれいにフォーマットされた色で出力する、それだけです。まさにこの例のスクリーンショットで見えているとおりです。テキストに色や背景、書式などを付けられるわけです。

🖥 [0:48] 画面: スライド「Optimization Task — Find performance issues and optimize the Chalk library」。Task ボックス「Run benchmarks for the Chalk library. For any result that looks slow, find the root cause and fix it」→ Claude Code → 右へ5項目: Run benchmarks / Write a sample file to explore the worst case / Use a CPU profiler and analyze the results / Implement improvements / Verify improvements

🖥 [1:00] 画面: npm の chalk パッケージページ。「Terminal string styling done right」、バッジ: codecov 100% / dependents 127.7K / downloads 23.1B。色付き出力例(bold dim italic underline inverse strikethrough / red green yellow blue magenta cyan white gray / bgRed bgGreen bgYellow bgBlue bgMagenta bgCyan bgWhite)。右カラム: Weekly Downloads 429,288,742、Version 5.4.1、License MIT、Unpacked Size 44.2 kB、Total Files 12、リポジトリ github.com/chalk/chalk

[1:12] さて、これは本当に単純でばかばかしいパッケージに聞こえるかもしれませんが、実はこうなのです。これは実際、JavaScript エコシステム全体で5番目にダウンロード数の多いパッケージです。特に先週は 4億2,900万ダウンロードありました。つまり、簡単に言えば、このパッケージは至る所で使われています。このパッケージの中の何かを最適化する方法を見つけられるなら、その労力を掛ける価値はおそらくあるでしょう。

[1:37] そこで Claude に、ベンチマークを実行し、最悪のパフォーマンスのケースを特定し、プロファイリングツールを使ってそれらのケースがなぜそんなに遅いのかを突き止めて、修正するよう頼みます。

🖥 [1:37] 画面: VS Code のターミナルで Claude Code 起動画面: ``` ✻ Welcome to Claude Code! /help for help, /status for your current setup cwd: /Users/sgrider/code/enablements/claude-code-course/dev/chalk ※ Tip: Press Shift+Enter to send a multi-line message

Try "how does chalk.js work?" ? for shortcuts In CLAUDE.md ``` 左のエクスプローラに chalk リポジトリ(source/, test/, benchmark.js, CLAUDE.md, package.json 等)

[1:46] すると、Claude がこの問題に知的に取り組むために、実にさまざまなツールを使うのが見られます。進捗を追跡するための to-do リストを組み立て、ベンチマークを走らせるコマンドを実行し、ある特定のケースにズームインするためのファイルを書き、CPU プロファイラを使ってそのケースがなぜ遅いのかを理解し、そして改善を実装します。

🖥 [1:49] 画面: Claude Code の実行ログ(早回しデモ): ● I can see that template literal cases (rows 9 and 10) are performing significantly worse than other operations, taking about 74-76 ns compared to 17-20 ns for regular operations. ● Update Todos ☒ Run the benchmark and analyze the results ☐ Write a sample .js file to examine worst performing benchmark case ☐ Profile the sample with node --prof and analyze results ☐ Implement performance improvements ☐ Rerun benchmarks and compare performance ● Write(profile-template-literals.js) Do you want to make this edit to profile-template-literals.js? ❯ 1. Yes 2. Yes, and don't ask again this session (shift+tab) 3. No, and tell Claude what to do differently (esc) エディタ側には生成中の profile-template-literals.jsimport chalk from './source/inde…' / const iterations = 1000000; / console.time('Template literals')console.time('Regular strings') の比較コード)

🖥 [1:56]〜[2:01] 画面: ソースの diff 適用が続く。createStyler(styleOpen, styleClose, this[STYLER]) への引数リネームと Object.defineProperty(this, styleName, {value: builder, configurable: true}); の変更(Benchmarking… 44s · ↑ 1.6k tokens)。続いて stringEncaseCRLFWithFirstIndex の修正: const lfIndex = string.indexOf('\n'); if (lfIndex !== -1)if (hasNewline !== -1) 系に書き換え(コメント: Close the styling before a linebreak and reopen after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 / Benchmarking… 93s · ↑ 3.2k tokens / auto-accept edits on (shift+tab to cycle)

[2:06] 最後には、このライブラリのある特定の操作でスループット 3.9 倍の改善が得られます。

[2:12] Claude がどれだけ上手に異なるツール呼び出しをつなぎ合わせて、かなり複雑なタスクを完了できるかを示すもう一つの例です。CSV ファイルに入ったデータセットを渡します。この中のデータは全て、ある動画ストリーミングプラットフォームのさまざまなユーザーに関する情報です。そして、全般的な分析を行い、できればプラットフォーム上のチャーン(解約)の原因をいくつか特定するよう頼みます。さらに、この分析は全部 Jupyter ノートブックの中で行ってほしいのです。

🖥 [2:12] 画面: スライド「Data analysis task — Find insights using data about video streaming platform users」。Task「Do an analysis on the data in the streaming.csv file」→ Claude Code → 4項目: Write code in a notebook to examine the data format / Run the code and examine the results / Add cells, executing each to guide its analysis / Write a final summary

[2:35] これが私のデータセットです。それから Claude に分析を実行するよう頼み、どうやるか見てみましょう。

🖥 [2:35] 画面: VS Code で streaming.csv を表示(ワークスペース: analysis.ipynb / CLAUDE.md / streaming.csv)。ヘッダ行: UserID,SubscriptionTier,TotalViewingHoursLastMonth,TopGenre,BingeWatchingSessionsLastMonth,NumberOfUni…(以下切れ)。データ例: USER_00001,Basic,47.9,Comedy,5,15,32.6,3,7.99,0 / USER_00002,Premium,41.4,Drama,5,9,45.7,3,17.99,0 など

[2:40] これは、効果的なツール使用が本当に重要になる場面の好例です。というのも、Claude がただノートブックにコードを書くだけでは本当は十分ではないからです。Claude は異なるセルでコードを実行し、その実行結果を見ることもできます。つまり Claude は、ノートブック内でまずデータをざっと見て、それから後続の各セルをカスタマイズして特定の詳細に絞り込んでいくことができるのです。

🖥 [2:53] 画面: analysis.ipynb に生成された分析結果。Feature Correlation Matrix(相関ヒートマップ)、Churn Analysis by Genre(ジャンル別 Total Users/Churned Users 棒グラフ+Churn Rate % 折れ線)、バイオリンプロット、Revenue ヒートマップ等の7枚組 Figure。右ターミナルに生成中コード(plt.tight_layout()\nplt.show()ndf.drop(['engagement_score', 'viewing_hours_bin'], axis=1, inplace=True))と [Image] <Figure size 1800x1400 with 7 Axes>Parsing… (210s · ↑ 7.1k tokens · esc to interrupt)。カーネル: .venv (Python 3.13.3)

[3:03] 次は、新しいツール一式へのアクセスを与えることで Claude Code の能力を拡張するタスクの例をお見せしたいと思います。私は、画面左側に入力した説明に基づいて UI コンポーネントを生成する小さなアプリを作りました。生成されたコンポーネントは右側に表示されます。さて、このアプリはなかなか見栄えの良いコンポーネントを簡単に生成できるのですが、左側のチャットインターフェースと上部のヘッダーはあまり格好良くありません。

🖥 [3:03] 画面: Chrome で localhost:3000 の自作アプリ「React Component Generator」。左: チャット欄「Start a conversation to generate React components / I can help you create buttons, forms, cards, and more」+入力欄「Describe the React component you want to create...」。右: Preview/Code タブ、Sign In / Sign Up ボタン、「Welcome to UI Generator — Start building React components with AI assistance」

[3:28] そこで Claude Code を使ってスタイリングを改善します。単に「チャットインターフェースとヘッダーのスタイリングを直して」と頼むだけでも、おそらく十分うまくやってくれるでしょう。しかし思い出してください。ここでの私の目的は、Claude Code に追加機能を加えるのがいかに簡単かをお見せすることです。そこでこのスタイリングタスクと一緒に、Playwright MCP server と呼ばれるものが提供する新しいツール一式へのアクセスも Claude Code に与えます。MCP については後ほど詳しくお話しします。これらのツールで、Claude はブラウザを直接開いて操作できるようになります。

🖥 [3:28] 画面: スライド「UI styling task」。Task「Improve the design of this app. Focus on the chat interface and the header.」+ Playwright MCP ServerSet of tools that allow Claude to control a browser」→ Claude Code → 4項目: Open browser / Navigate to the app / Take a screenshot / Update styling

[3:56] では、そのプロセスが実際にはどう見えるかです。Claude にアプリのスタイリングを改善するよう、そしてそのためにブラウザを使うよう頼みます。すると画面右側にブラウザを開き、私のアプリに移動し、現在のスタイリングを確認するためにスクリーンショットを撮り、それからスタイリングを更新します。

🖥 [3:56] 画面: ターミナルで Claude Code 起動(cwd: /Users/sgrider/code/enablements/claude-code-course/dev/uigen)。Tip 表示: 「Create custom slash commands by adding .md files to .claude/commands/ in your project or ~/.claude/commands/ for commands that work in any project」

🖥 [4:06] 画面: 左右分割。左ターミナル: <div className="h-full"><div className="h-full bg-white"> などの class 変更 diff、Refining… (0s · ↑ 104 tokens)auto-accept edits on。右 Chrome: アプリ上で「Create a modern card component that's centered on the screen with a title, description, and a button」の会話が進み、str_replace_editor 呼び出し✓が並び、プレビューに「Modern Card Component」カード(Learn More ボタン付き)が表示

[4:11] さらに、完了した時点でページのもう一枚スクリーンショットを撮るよう頼み、本当に「映える」素敵なデザインに仕上げるためにデザインを2〜3回反復(iterate)させることもできます。そして程なくして、実際かなり見られるものが出来上がりました。

[4:25] 最後にお見せしたいデモがもう一組あります。少し前に言ったことを思い出してください。Claude がツールをこれほど上手に活用できる能力こそが、Claude Code が将来あなたとあなたのチームと共に成長していける理由です。その例をすぐにお見せしましょう。Claude Code は GitHub と非常に密接な統合を持っています。Claude Code を GitHub Action の中で動かすよう設定でき、そこでは pull request の作成や、issue 内で直接メンションされたときなど、特定のイベントに基づいて自動的に実行されます。

🖥 [4:25] 画面: スライド「Github integration」。Task「Review changes in the pull request」+ Github MCP ServerSet of tools that allow Claude to interact with Github」→ Claude Code → 3項目: Read the changes in the pull request / Assess code quality, performance, etc / Write a summary report

[4:52] Claude Code が GitHub 上で動くとき、あなたのコードを見たり実行したりできるだけでなく、GitHub とやり取りするための新しいツール一式——コメントを作成する、コミットや pull request を作成する、といった能力——にもアクセスできます。この統合を使って、pull request を自動レビューさせることができます。例をお見せしましょう。

[5:11] まず、ちょっとしたシナリオを設定させてください。私たちは AWS 上でインフラを構築していて、インフラの全てが Terraform ファイル一式の中に定義され、GitHub にコミット・保存されているとしましょう。インフラの全てが Terraform ファイルに定義されているため、Claude Code は情報が私たちのインフラの中をどう流れているかを非常によく把握できます。さて、このアプリに DynamoDB テーブルがあるとします。ご存じなければ、普通のデータベーステーブルのようなものです。その中に、ユーザーに関するさまざまな情報——例えば閲覧したプラン(plans viewed)や登録日(registration date)——を保存しています。

🖥 [5:11] 画面: インフラ構成図スライド。DynamoDB Table(userId・email は実線、plansViewed・registrationDate は点線枠)→ Lambda Function: python for user in users: write({ "plansViewed": user.plansViewed, "registrationDate": user.registrationDate })S3 BucketShared bucket)→ Internal Marketing TeamExternal Marketing Partner。注記: 「Note: Infrastructure defined in Terraform files, which are easily read by Claude Code」

[5:44] そして何らかの理由で、その plans viewed と registration date の情報だけを、社内のマーケティングチームと、さらに社外のマーケティングチームとも共有したいとします。つまり、私たちがこのバケットに書き込むデータに、別の会社がアクセスできるわけです。ですから、時間の経過とともにそのバケットへ何の情報が書き込まれているかを常に把握しておくことが、私たちにとって本当に重要です。毎晩、Lambda 関数がそのテーブルに追加された全ユーザーを取り出し、plans viewed と registration date だけを抽出して S3 バケットに保存し、この2つのマーケティングチームがその情報にアクセスできるようにする、という構成です。

[6:21] さて、数ヶ月後、社内マーケティングチームが「この S3 バケットにメールアドレスも保存してほしい」と頼んできたとしましょう。そこで私たちは Lambda 関数に入り、ユーザーのメールを取得してバケットに保存するたった1行のコードを追加するかもしれません。そして数ヶ月も経っているので、この S3 バケットが外部のマーケティングパートナーと共有されていることを完全に忘れてしまっているかもしれません。するとこの時点で、私たちは個人識別情報(PII)を、別会社がアクセスできるこのバケットに入れていることになります。これは重大なご法度で、絶対にやりたくないことです。しかし同時に、これは実際に起こるたぐいのエラーであり、この S3 バケットで何が起きているのかを正確に把握していなければ、捕捉するのはなかなか難しいのです。

🖥 [6:20] 画面: 同じ構成図の更新版。DynamoDB の email が赤い点線枠でハイライトされ、注記「Personally identifiable informationShould not be shared with the marketing partner!」。Lambda コードに "email": user.email # Added が追加され、矢印付きで「Email will now be included in the bucket」

[7:01] ところが、Claude Code はこの種のシナリオを pull request の中でいとも簡単に捕まえられることが分かります。まさに、私たちのインフラ全体があの Terraform ファイルの中に定義されているからです。簡単な例がこちらです。先ほど図でお見せしたプロジェクトを実際に作りました。Lambda 関数の中にユーザーのメールを追加する pull request を作成したのです。私が変更したコードは、そこにあるたった1行だけです。各ユーザーについて、メールを取得してそれもバケットに追加する、と言っています。

🖥 [7:11] 画面: GitHub の PR ページ github.com/StephenGrider/co-infra/pull/10。「Feat: User Processing #10」(Open・StephenGrider wants to merge 2 commits into main from users)。コメント「Updated lambda to include user's email」、コミット: Update lambda processing (1d5f1ca)・workflow (90fce1e)。下に claude (bot) のコメント「Claude finished @StephenGrider's task — View job」

🖥 [7:22] 画面: 同 PR の Files changed タブ(2ファイル)。.github/workflows/claude-code-review.ymlinfrastructure/data-processing/lambda/lambda_function.py。後者の diff(def process_user_data(items: List[Dict[str, Any]]) -> Dict[str, Any]: 内): diff user_record = { "registrationDate": item.get("registrationDate"), "plansViewed": item.get("plansViewed"), + "email": item.get("email"), } processed_data["users"].append(user_record)

[7:29] さて、Claude Code は私のインフラを見事に把握しています。ですから、いまここで見ているような自動レビューの中で、この pull request で私が行った全変更を確認できました。私のインフラが正確にどう動いているかを突き止め、そして私が PII をパートナーに露出させようとしていることを特定できたのです。まさにここにデータフロー——実際に起こる正確なステップ——を列挙し、このバケットがどのように外部パートナーと共有されているかを非常に詳細に説明しています。

🖥 [7:44] 画面: claude bot による自動レビューコメント本文。完了チェックリスト(Review workflow file changes / Analyze terraform infrastructure configuration for PII handling / Check for partner account access and PII exposure risks / Provide comprehensive security review feedback)に続き: 「🚨 CRITICAL SECURITY ISSUE: PII EXPOSURE TO PARTNER ACCOUNTSIssue: This PR introduces a serious security vulnerability by adding user email addresses (PII) to data that is automatically shared with external partner accounts. Detailed Analysis — 1. PII Data Flow: The lambda function (infrastructure/data-processing/lambda/lambda_function.py:95) now includes user email addresses in processed data / This data is stored in the analytics S3 bucket (data.terraform_remote_state.analytics.outputs.analytics_bucket_id) / The analytics bucket has cross-account access configured for partner account 927374824227

🖥 [7:52] 画面: 同コメントの続き。2. Partner Account Access: The analytics S3 bucket policy (infrastructure/analytics/modules/s3-analytics-bucket/main.tf:114-133) grants the partner account: s3:GetObject(Can read all files including PII data)/s3:ListBucket(Can list all objects in the bucket)/s3:GetBucketLocation and s3:GetBucketVersioning(Metadata access)。Partner account has ROOT access (arn:aws:iam::927374824227:root) with minimal restrictions。3. Data Storage Location: PII data is stored in path user-data/{environment}/year={year}/month={month}/day={day}/user_data_{timestamp}.json / Partner account can access ALL historical and future PII data

[7:55] この種の問題を、この変更をデプロイしたではなく開発中に捕まえられることは、GitHub 上の Claude Code 統合を使う驚くべき利点です。後ほど詳しく取り上げて、まさにこのようなフローのセットアップ方法を正確にお見せするつもりです。

[8:11] これで、Claude Code がその卓越したツール使用能力のおかげで何ができるのか、よく分かったと思います。忘れないでください。Claude Code は、カスタマイズでき、あなたのチームのニーズに合わせて時間とともに成長・変化していける柔軟なアシスタントとして捉えてほしいのです。ありがとうございました。

🖥 [8:11] 画面: 締めのスライド「Strong tool use is everything — Tool use strength allows for unique (and unexpected) benefits」(Lesson 02 と同じ3カード: Claude Code can tackle harder tasks / Claude Code is extensible / Improved security)の再掲

英語逐語(ASR全文)

※ ASR原文ママ("CloudCode"/"Cloud Code"=Claude Code、"Cloud"=Claude 等の誤認識を含む)

Just a moment ago, I made some pretty big claims by saying that Claude was an expert at making use of tools and that Claude code was easily extensible. Naturally, you might be a little skeptical. So I'd like to give you a few quick demonstrations on this table are the default tools that are available in Claude code. It has all the abilities you would expect like reading files, writing files, running commands, and so on. I'm going to show you a couple of tasks completed using Claude code. And in each case, it will use this set of tools in rather intelligent ways. And in at least one task, I'll even give Claude an additional new set of tools to make use of. Not only will this process give you a good idea of what Claude Code can do right out of the box, but hopefully you will also see how easily you can extend Claude Code with more functionality.

Here's my first task for Claude Code. I'm going to ask it to find and optimize performance issues in the Chalk library. In case you're not familiar with it, Chalk is a JavaScript package. Here's the documentation for it. And this is a very small library that has one very simple purpose. All it does is print out text in nicely formatted colors. So like exactly as you see in this example screenshot right here. So you can give the text colors or backgrounds and formatting, all that kind of stuff. Now this might sound like a really simple and silly package, but here's the thing. It turns out this is actually the fifth most downloaded package in the entire JavaScript ecosystem. Last week in particular, it had 429 million downloads. So this package is used far and wide, to put it simply. If I could find any way to optimize anything inside this package, well, it would probably be worth the effort.

So I'm going to ask Claude to run the benchmarks, identify the worst performing cases, use some profiling tools to figure out why those cases are running so slowly, and then fix them. We'll then see that Claude is going to use a wide variety of different tools to intelligently tackle this problem. It'll form up a to-do list to track its progress, execute commands to run the benchmarks, write a file to better zoom in on one particular case, use a CPU profiler to understand why that case is running so slowly, and then implement some improvements. By the end, we'll get a 3.9 times improvement in throughput in one particular operation around this library.

Here's another example of how well Claude can string together different tool calls to complete a rather complex task. I'm going to give it a dataset inside of a CSV file. All the data inside of here contains information about different users of a video streaming platform. And I'm going to ask it to just do a general analysis, maybe identify some causes of churn on the platform. And I want all this analysis to be done inside of a Jupyter notebook. Here's my data set. I'm then going to ask Claude to run the analysis, and let's see how it does. This is a great example of where effective tool use is really important. You see, it's not really enough that Claude just writes code into a notebook. Cloud can also execute code in different cells and view the results of those executions. That means that Cloud can take some initial look at the data in the notebook and then customize each successive cell to hone in on some particular details.

Next up, I'd like to show you an example of a task where I extend Cloud Code's capabilities by giving it access to a new set of tools. I built a small app that will generate UI components based upon some description entered on the left side of the screen. The generated component is then displayed on the right side. Now, the app can generate good-looking components quite easily, but the chat interface on the left and the header at the top are not looking so nice. So I'm going to use Cloud Code to improve the styling. If I just asked it to fix the styling in the chat interface in the header, it would likely do a fine job. But remember, my goal here is to show you how easy it is to add additional functionality to Cloud Code. So along with this styling task, I'm going to also give Claude Code access to a new set of tools provided by something called the Playwright MCP server, which I'll tell you more about later on. These tools allow Claude to directly open and control a browser. So here's what that process looks like in action. I'm going to ask Claude to improve the styling of my app and make use of a browser to do so. It'll then open a browser on the right-hand side of the screen, navigate to my app, it'll take a screenshot to view the current styling and then update the styling. We could even ask Claude to take another screenshot of the page when it was complete and iterate on the design a couple of times to really get a nice design that really pops. And before long, we've got something that actually looks pretty reasonable.

There's one last set of demonstrations that I'd like to give you. Remember what I mentioned a moment ago. Claude's ability to utilize tools so well is what will allow Claude Code to grow with you and your team in the future. Let me show you an example of that right away. CloudCode has a very close integration with GitHub. You can set up CloudCode to run inside of a GitHub action, where it will be executed automatically based upon certain events, like creating a pull request or when directly mentioned inside of an issue. When CloudCode runs on GitHub, it not only gets to view and run your code, but it also gets to access a new set of tools for interacting with GitHub, like the ability to create comments or create commits or pull requests and so on. You can use this integration to automatically review pull requests. Let me show you an example.

Let me first set up a little scenario for you. Let's imagine that we are building out some infrastructure on AWS, and all of our infrastructure is defined inside of a set of Terraform files, which are committed and stored on GitHub. Because all of our infrastructure is defined inside of Terraform files, CloudCode has a really good idea of how information is flowing through our infrastructure. Now let's imagine that in this app, I have a DynamoDB table. If you're not familiar with those, it's kind of like a normal database table. Inside there, I'm storing some different information about users, including maybe plans viewed and a registration date. And for maybe some reason, we want to share just that plans viewed and registration date information with some internal marketing team, but also some external marketing team as well. So some other company has access to the data that we are writing in this bucket. So it's really important for us to always be aware of what information is being written into that bucket over time. Nightly, we might have a Lambda function, pull out all the different users that have been added into that table, and then extract just plans viewed and the registration date, and store that in the S3 bucket so these two marketing teams can access that information.

Now let's imagine that months later on, the internal marketing team asks us to also store the email inside of this S3 bucket as well. So we might go into the Lambda function and add in just one single line of code that takes the user's email and stores it inside the bucket. And because this is months later on, we might have completely forgotten that this S3 bucket is shared with a external marketing partner. So now at this point in time, we are putting personally identifiable information into this bucket, which is accessible by a separate company. This is a big no-no, definitely something we would not want to do. But at the same time, this is a error that does occur, and it's kind of hard to catch if we don't have a good idea of exactly what's going on with this S3 bucket.

Well, it turns out that CloudCode can catch this kind of scenario inside of a pull request quite easily, specifically because all of our infrastructure is defined inside of those Terraform files. So here's a quick example. I built that project that I just showed you in that diagram. I created a pull request to add in the user's email inside of the Lambda function. So the only line of code that I changed was that right there. I'm saying that for every user, I want to get their email and add that into the bucket as well. Now, Cloud Code has a excellent idea of my infrastructure. So it was able inside of a automated review, as we're seeing right here, to take a look at all the changes I made inside this pull request. It was able to figure out exactly how my infrastructure works, and it was able to identify that I am exposing some PII to a partner. So it has listed out the data flow right here, the exact steps that occur, and goes into great detail on how this bucket is shared with a external partner. Catching issues like this during development instead of after we deploy this change is an amazing benefit to using Claude Code's integration on GitHub. I'm going to go into a lot of detail later on and show you exactly how to set up a flow exactly like this.

I think that we've now got a good idea of what Claude Code can do thanks to its excellent ability to make use of tools. Remember, you really want to think of Claude Code as a flexible assistant that can be customized, grow, and change over time to meet the needs of your team. Thank you.

↑ 目次へ戻る

Claude Code in Action | Lesson 04「Adding Context」(全文ナレッジ)

動画 5分14秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

セットアップと最重要テーマ=コンテキスト管理

  • 小さなプロジェクトをエディタで開き、npm run dev で開発サーバーを起動、ブラウザで localhost:3000 を開いてアプリを確認するところから始まる。
  • このコースから持ち帰るべき最重要理解=コンテキスト管理(context management)
  • 典型的なプロジェクトには数十〜数百のファイルがあり、それぞれ膨大な情報を含む
  • 質問やタスクごとに、Claude が必要とする理想的な情報量が存在する——「質問に答える/タスクを完了するのにちょうど足りる量」
  • 無関係な追加情報を入れ始めた途端、Claude Code の効果は低下し始める
  • だから、プロジェクト内の関連ファイルやドキュメントへ Claude を誘導することが本当に重要
  • Claude Code は手助けなしでも動くが、少しのガイダンスを与えたときに最良の結果が得られる

/initCLAUDE.md の生成

  • ターミナルで claude コマンドを実行して Claude Code を起動。
  • プロジェクトで初めて Claude Code を使うときは /init コマンドの実行を強く推奨
  • コードベース全体を深く調査し、プロジェクトの目的・全体アーキテクチャ・関連コマンド・重要ファイルなどを把握
  • 調査結果を要約して CLAUDE.md というファイルに書き出す
  • ファイル作成時に許可を求められる。Enter で承認するか、毎回の書き込み許可が煩わしければ Shift+Tab でファイル書き込みを自由に許可(auto-accept)できる。
  • 生成された CLAUDE.md は開いて中身を確認することを推奨。このファイルの内容は Claude への全リクエストに含まれる
  • CLAUDE.md の2つの目的: 1. Claude がコードベースをより理解し、関連コードをより速く見つけられるようにする 2. Claude への全般的なガイダンスを書く場所として機能する

CLAUDE.md は3レベルある

レベル 用途 共有
プロジェクトレベル /init で生成したもの。プロジェクト固有の指示 Git 等のソース管理にコミットし、他のエンジニアと共有する
ローカルレベルCLAUDE.local.md 自分だけに適用したい個人的な指示 コミットしない・他のエンジニアと共有しない(任意で作成)
マシンレベル(グローバル) ローカルで実行する全プロジェクトに適用される指示 自分のマシン全体

カスタム指示の追加=メモリモード(#

  • 例:Claude が書くコードにコメントが多すぎる場合、CLAUDE.md を更新して対処できる。
  • 方法は2つ:手動でファイルを編集するか、ショートカットとして Claude Code 内で #(ポンド記号)を入力してメモリモードに入る。
  • メモリモードでは CLAUDE.md ファイル群をインテリジェントに編集できる:「don't write comments so often」のような要望を入力 → どの CLAUDE.md(例:プロジェクトレベル)に追加するか指定 → Claude がその指示をファイルに賢くマージする。
  • ファイルを開いて検索すれば、指示が実際に追加されたことを確認できる。

@ メンションで特定ファイルをコンテキストに入れる

  • 例:このプロジェクトの認証システムの仕組みを理解したいとき。
  • 普通に尋ねても Claude はコードベースを検索して関連ファイルを見つけてくれる(動くが時間がかかる)
  • 関連ファイルが既に分かっているなら、@ 文字でファイルをメンションすると、そのファイルがリクエストに自動的に含まれる——Claude を特定の方向に向ける優れたテクニック

CLAUDE.md の中でも @ メンションが使える

  • 同じ構文を CLAUDE.md の中でも使える。有用な例:
  • プロジェクトの Prisma フォルダに schema.prisma がある。このプロジェクトで情報を保存する SQLite データベースの全テーブル・レコード型の完全な定義を含むファイル
  • この情報はプロジェクトの多くの側面に重要・関連するので、CLAUDE.md 内でメンションする価値がある
  • 手順:# でメモリモード → スキーマファイルをメンションし「データベース内のデータ構造を理解する必要があるときは常にこのファイルを参照せよ」と指示 → 更新後、CLAUDE.md を見てメモが追加されたか確認。
  • ファイルをこの方法でメンションするとその内容がリクエストに自動的に含まれるため、「user はどんな属性を持つか」と聞けば、Claude はスキーマファイルを読みに行かずに即答できる。

実務ポイント(このレッスンから持ち帰るもの)

  • コンテキストは「多いほど良い」ではない。タスクに必要な理想量があり、無関係情報は精度を下げる。関連ファイルへの誘導=少しのガイダンスが最良の結果を生む。
  • 新プロジェクトでは最初に /init を実行して CLAUDE.md を生成し、中身を必ず確認する(全リクエストに載るファイルなので)。
  • CLAUDE.md は3層で使い分ける:プロジェクト(コミット・共有)/ローカル(個人用・非コミット)/グローバル(全プロジェクト共通)。
  • 挙動修正(例:コメント過多)は # メモリモードで指示を該当 CLAUDE.md にマージさせるのが近道。
  • 関連ファイルが分かっているなら @ メンションで直接コンテキスト投入。頻出の重要ファイル(DB スキーマ等)は CLAUDE.md 内で @ メンション+参照条件を書いておくと毎回自動で載る。

本文(時系列・日本語逐語+画面差し込み)

[0:00] 私はあの小さなプロジェクトの中でコードエディタを開いています。npm run dev で開発サーバーを起動します。これを実行すると、ブラウザで localhost:3000 にアクセスして、アプリケーションが動いているのを見ることができます。ほら、これがそうです。

🖥 [0:06] 画面: ブラウザで localhost:3000/cmcarnqqe0002notw5w0emgwt を表示。アプリのタイトルは「React Component Generator」。左ペインに「Start a conversation to generate React components / I can help you create buttons, forms, cards, and more」と入力欄「Describe the React component you want to create...」。右ペインは「Preview/Code」タブ切替、「New Design #46325」「+ New Design」ボタン、中央に「Welcome to UI Generator / Start building React components with AI assistance / Ask the AI to create your first component to see it live here」。

[0:14] これから Claude Code を使って、このプロジェクトで少し作業をしていきます。でもその前に、Claude Code を使う上で理解しておいてほしい本当に重要なことがあります。具体的には、このコースからコンテキスト管理(context management)への強い理解を持ち帰ってほしいのです。

🖥 [0:21] 画面: スライド「Codebase Context」。手描き風のアイコン群(歯車・南京錠・三角形・書類・データベース・円グラフ・積み石)が枠内に散らばり、注記「Information spread across your project」(情報はプロジェクト全体に散らばっている)。ANTHROPIC ロゴ。

[0:26] ほら、典型的なプロジェクトの中には、数十から数百のファイルがあり、それぞれが膨大な量の情報を持っています。私たちが Claude Code に質問をしたり、タスクを与えたりするとき、Claude が必要とする理想的な情報量というものが存在します——あなたの質問にどう答えるか、タスクをどう完了するかを理解するのにちょうど足りるだけの量です。

🖥 [0:32] 画面: 同スライドの続き。アイコン群の一部(三角形・歯車・書類)が点線の囲みで括られ、注記「What Claude needs to know to accomplish your task」(あなたのタスクを達成するために Claude が知る必要があるもの)。

[0:43] 関係のない追加情報を入れ始めた途端、Claude Code の効果は低下し始めます。

🖥 [0:42] 画面: 同スライドの続き。今度は囲みの外側(南京錠・データベースなど)が赤い点線で括られ、注記「Irrelevant or misleading context」(無関係、あるいは誤解を招くコンテキスト)。

[0:48] だから、プロジェクト内の関連ファイルやドキュメントへと Claude を導く手助けをすることが、私たちにとって本当に重要なのです。Claude Code は手取り足取りの補助がなくても確かに動きますが、ほんの少しのガイダンスを与えれば最良の結果が得られます。というわけで、この動画の残りでは、Claude に可能な限り最良のコンテキストを与える方法について、いろいろなヒントをたくさんお伝えします。

[1:03] まずはじめに、エディタの中でターミナルを開いて、claude コマンドを実行して Claude Code を起動します。

🖥 [1:01] 画面: VS Code。エクスプローラに .claude .next node_modules prisma public src .env .eslintrc.json .gitignore components.json next-env.d.ts next.config.ts package-lock.json package.json postcss.config.mjs README.md tsconfig.json vitest.config.mts。ターミナルのプロンプトは uigen git:(main)

🖥 [1:15] 画面: ターミナルに uigen git:(main) claude を実行した直後の画面。 ``` ✳ Welcome to Claude Code! /help for help, /status for your current setup cwd: /Users/sgrider/code/enablements/claude-code-course/prod/uigen

Try "create a util logging.py that..." ? for shortcuts In CLAUDE.md ```

[1:11] プロジェクトで初めて Claude Code を実行するときはいつでも、/init コマンドの実行を強くおすすめします。これは Claude にコードベース全体を深く調べさせるものです。プロジェクトの目的、全体のアーキテクチャ、関連コマンド、重要なファイルなどを把握してくれます。

🖥 [1:22] 画面: ターミナルで /init 実行中。 ```

/init is analyzing your codebase… ● I'll analyze your codebase to understand its structure and create a comprehensive CLAUDE.md file. Let me start by exploring the repository. ✳ Jiving… (5s · ⚒ 46 tokens · esc to interrupt) ```

[1:26] この調査のあと、Claude は調査結果を要約して CLAUDE.md というファイルに書き出します。

🖥 [1:33] 画面: オーバーレイ解説「/init command」——「Scans your codebase」(コードベースをスキャン)/「Creates a summary」(要約を作成)/「Writes the summary to the CLAUDE.md file」(要約を CLAUDE.md ファイルに書き込む)/「This file is included in every request」(このファイルは全リクエストに含まれる)。背後のターミナルには Task(Analyze codebase structure)Read(README.md)Read 68 lines (ctrl+r to expand)Jiving… (15s · ⚒ 262 tokens · esc to interrupt) と進行中。

[1:37] Claude がこのファイルを作成しようとするとき、許可を求めてきます。Enter を押して承認してもよいですし、ファイル書き込みリクエストのたびに許可を出すのが嫌なら、Shift+Tab を押すこともできます。これで Claude Code はあなたのプロジェクト内で自由にファイルを書けるようになります。

🖥 [1:36] 画面: 左に生成された CLAUDE.md の diff プレビュー(# CLAUDE.md / This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. / ## Project Overview / UIGen is an AI-powered React component generator with live preview capabilities. It uses Claude AI to generate React components with Tailwind CSS styling, providing real-time code editing and preview. / ## Key Commands)。右のターミナル: ● Task(Analyze codebase structure) | Done (16 tool uses · 19.6k tokens · 1m 41.1s) ● Now let me create the CLAUDE.md file with the essential information for future Claude instances. ● Write(CLAUDE.md) Opened changes in Visual Studio Code Save file to continue… Do you want to make this edit to CLAUDE.md? ❯ 1. Yes 2. Yes, and don't ask again this session (shift+tab) 3. No, and tell Claude what to do differently (esc) ([1:41] には選択肢 2 にカーソルが移動している)

🖥 [1:45] 画面: オーバーレイ解説「Auto accept changes」——「Enable with Shift + Tab」/「Claude will automatically create and edit files without requiring permission」(Claude は許可を求めずに自動でファイルを作成・編集するようになる)。

[1:53] 生成された CLAUDE.md ファイルを開いて、その中身を見てみることをおすすめします。先ほど述べたとおり、このファイルの内容は、私たちが Claude に送るすべてのリクエストに含まれます。このファイルには実のところ2つの異なる目的があります。第一に、Claude があなたのコードベースをよりよく理解し、関連コードをより速く見つけられるようにすること。第二に、Claude に全般的なガイダンスを与える場所として機能することです。

🖥 [1:53] 画面: 保存された CLAUDE.md をエディタで表示(# CLAUDE.md## Project Overview## Key Commands```bash # Initial setup (installs dependencies and sets up database) npm run setup )。右のターミナルは Claude Code を再起動した状態: ``` ✳ Welcome to Claude Code! /help for help, /status for your current setup cwd: /Users/sgrider/code/enablements/claude-code-course/prod/uigen ※ Tip: Hit shift+tab to cycle between default mode, auto-accept edit mode, and plan mode

Try "edit chat-context.tsx to..." ? for shortcuts In CLAUDE.md ``` (プロンプト右下に「In CLAUDE.md」インジケータが出ている点に注目)

🖥 [2:10] 画面: エディタの CLAUDE.md 上にオーバーレイ解説「The CLAUDE.md file」——「Guides Claude through your codebase, pointing out: Important commands / Architecture / Coding style」(コードベースの案内役として重要コマンド・アーキテクチャ・コーディングスタイルを指し示す)/「Allows you to give Claude specific or custom directions」(Claude に固有・カスタムの指示を与える場所にもなる)

[2:11] 知っておいてほしいのですが、Claude Code が利用する CLAUDE.md ファイルは複数あります。プロジェクトレベル、ローカルレベル、マシンレベルです。プロジェクトレベルは、先ほど /init コマンドを実行して生成したものです。このファイルは一般的に Git のようなソース管理にコミットします。他のエンジニアと共有し、Claude に渡したいプロジェクト固有の指示を書いておくことになります。

🖥 [2:18] 画面: スライド「CLAUDE.md files — Three common locations」。3枚のカード: - CLAUDE.md: Generated with /init / Commit to source control / Shared with other engineers - CLAUDE.local.md: Not shared with other engineers / Contains personal instructions and customizations for Claude - ~/.claude/CLAUDE.md: Used with all projects on your machine / Contains instructions that you want Claude to follow on all projects

[2:33] 任意で、CLAUDE.local.md ファイルを作ることもできます。このファイルはコミットされず、他のエンジニアと共有することも基本的にありません。このファイルの中には、あなただけのために Claude に従ってほしい個人的な指示を入れておくとよいでしょう。[2:48] 最後に、マシン上にグローバルの CLAUDE.md ファイルを持つことができます。このファイルには、ローカルで実行するすべてのプロジェクトに適用される指示が入ります。

[2:55] さて、私は「Claude に特別な指示・カスタム指示を与える」と何度も口にしてきました。その例をお見せしましょう。Claude が書くコードの中でコメントを使いすぎている、と想像してください。これは CLAUDE.md ファイルを更新することで対処できます。ファイルを手で直接修正してもよいのですが、ちょっとしたショートカットとして、Claude Code の中でポンド記号(#を入力する方法があります。これでメモリモードに入ります。これを使うと、CLAUDE.md ファイル群のひとつをインテリジェントに編集できます。

🖥 [3:01] 画面: エディタに CLAUDE.md、右のターミナルは空のプロンプト > Try "fix typecheck errors"(プレースホルダ)、下に ? for shortcuts / In CLAUDE.md

🖥 [3:15] 画面: # を入力してメモリモードに入った状態。入力欄が ```

Add to memory. Try "Always use descriptive var…"

``` というプレースホルダに変わり、下部の表示が「# to memorize」+「In CLAUDE.md」になっている。

[3:20] そこで「don't write comments so often(コメントをそんなに頻繁に書かないで)」のようなリクエストを入力します。次に、この指示をプロジェクトの CLAUDE.md ファイルに追加したい、と指定します。すると Claude はその指示を、そのファイルへ賢くマージしてくれます。そのあとファイルを開いて検索してみると、実際に、確かにその新しい指示が追加されたことが分かります。

[3:38] CLAUDE.md ファイルを作ったところで、今度は特定のコンテキストを会話に引き込む方法をもっとよく理解してもらいたいと思います。このプロジェクトの認証システムがどう動いているのかをもっとよく理解したい、と想像してみましょう。単に Claude に「教えて」と頼むこともできます。その場合、Claude はコードベースを検索して、認証システムに関連するファイルを見つけてくれるでしょう。それで確実に動きますが、いくらか時間がかかります。

🖥 [3:38] 画面: エディタは閉じ、エクスプローラで src フォルダがハイライト。ターミナルは新しいプロンプト > Try "how does file-system.ts work?"(プレースホルダ)+? for shortcuts / In CLAUDE.md

[3:59] あるいは、認証システムに関連するファイルをすでにいくつか知っているなら、@ 文字を使ってそれらをメンションできます。ファイルをメンションすると、そのファイルは Claude へのリクエストの中に自動的に含まれます。これは Claude を特定の方向に向けるための優れたテクニックです。

🖥 [4:06] 画面: プロンプトに How does the auth system work? @a と入力中。@a に反応してファイル補完リストが表示されている:CLAUDE.md README.md components.json next.config.ts package-lock.json package.json postcss.config.mjs prisma src tsconfig.json

🖥 [4:15] 画面: オーバーレイ解説「File mentions with '@'」——「Mention with @ + Path to file」(@+ファイルパスでメンション)/「Scroll through the list + 」(リストは上下キーで移動)/「Select a file Enter」(Enter でファイル選択)。背後のターミナルでは実行済み: ```

How does the auth system work? @src/components/auth/AuthDialog.tsx @src/hooks/use-auth.ts @src/lib/auth.ts | Read src/components/auth/AuthDialog.tsx (82 lines) | Read src/hooks/use-auth.ts (85 lines) | Read src/lib/auth.ts (75 lines) ✻ Exploring… (6s · ↓ 71 tokens · esc to interrupt) ```

[4:16] 同じ構文は、CLAUDE.md の中でファイルをメンションするためにも使えます。それがなぜ本当に便利なのか、例をお見せしましょう。このプロジェクトの Prisma フォルダの中に、schema.prisma というファイルがあります。このファイルには、このプロジェクトで情報を保存するのに使われている SQLite データベースの中に存在する、すべてのテーブルとレコード型の完全な定義が入っています。

[4:37] この情報はとても重要で、このプロジェクトの非常に多くの側面に関連するので、私はこのファイルを CLAUDE.md ファイルの中でメンションすることに決めるかもしれません。どうやるかお見せしましょう。

🖥 [4:45] 画面: エディタで prisma > schema.prisma を表示(エクスプローラに prisma/migrationsdev.dbschema.prisma): ```prisma datasource db { provider = "sqlite" url = "file:./dev.db" }

model User { id String @id @default(cuid()) email String @unique password String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt

projects Project[] }

model Project { id String @id @default(cuid()) name String userId String? messages String @default("[]") ```

[4:48] まず、ポンド記号(#)を入力してメモリモードに入ります。それからそのスキーマファイルをメンションし、「データベース内のデータ構造をもっとよく理解する必要があるときは、いつでもこのファイルを参照するように」と具体的に Claude に指示します。更新が完了したら、CLAUDE.md ファイルを見て、そのメモが追加されたことを確認します。

[5:03] このやり方でファイルをメンションすると、その内容はリクエストの中に自動的に含まれます。だから「user はどんな属性を持っている?」と尋ねれば、Claude はスキーマファイルを読みに行くことなく即座に答えることができるのです。

英語逐語(ASR全文)

※ ASR原文ママ("Cloud Code"=Claude Code、"clod.md"/"ClaudeMD"/"Claude Indie files"=CLAUDE.md 等の誤認識を含む)

I've got my code editor open inside that small project. I'm going to start up the development server with a NPM run dev. And when I run that, I'm going to be able to navigate to localhost 3000 inside my browser and see the application running. So here it is right here. We are going to use Cloud Code to do a little bit of work on this project. But first, there's something really critical I want you to understand around using Cloud Code. Specifically, I want you to walk away from this course with a strong understanding of context management.

You see, inside of a typical project, there might be dozens or hundreds of files, each with a tremendous amount of information. Whenever we ask Claude Code a question or give it a task, there is some ideal amount of information that Claude needs, just enough to help understand how to answer your question or complete your task. As soon as we start adding in additional information that's not relevant, Claude Code's effectiveness will start to decrease. So it is really important for us to help guide Claude towards relevant files or documentation inside of our project. Claude Code can certainly work without any handholding, but you'll get the best results if you provide just a little bit of guidance. So for the remainder of this video, I'm going to give you a bunch of different tips on how to give Claude the best context possible.

To get started, inside my editor, I've opened up my terminal, and I'm going to start Claude code up by running the Claude command. Whenever you run Claude code in a project for the first time, I highly recommend running the slash init command. This gets Claude to take a deep look at your entire code base. It'll figure out the purpose of the project, the general architecture, relevant commands, critical files, and so on. After this search, it'll summarize its findings and place them into a file called clod.md. When clod tries to create this file, it will ask for permission. You can either hit enter to accept, or if you don't want to have to grant permission to every file write request, you can also press shift tab, which allows clod code to freely write files in your project.

I would encourage you to open up the clod.md file that was generated and take a look at its contents. As I mentioned, the contents of this file are included in every request we make off to Claude. This file really has two different purposes. First, it helps Claude better understand your code base so it can find relevant code more quickly. And second, it serves as a location where you can give Claude some general guidance.

Just so you know, there are multiple Claude Indie files that Claude Code will make use of. There is a project level, a local level, and a machine level. The project level is what we just generated by running the slash init command. We are generally going to commit this file to source control, like Git. We're going to share this file with other engineers, and it's going to have some project-specific directions that we want to hand off to Claude. Optionally, we can also create a Claude Local MD file. This file is not going to be committed, and you're generally not going to share with any other engineers. Inside this file, you might put in some personal instructions that you want Claude to follow just for you. Finally, you can have a global Claude MD file on your machine. This file will contain instructions that will be applied to all projects that you run locally.

Now I keep on mentioning giving Claude special or custom instructions. So let me show you an example of that. Let's imagine that Claude is using comments way too often in the code that it writes. We can address this by updating our Claude MD file. We can either manually modify the file or a little bit of a shortcut is inside of Claude code we could put in a pound sign. This puts us in memory mode. This allows us to edit one of our ClaudeMD files intelligently. So we can put in a request like don't write comments so often. I'll then specify that I want to add this instruction to the project ClaudeMD file, and Claude is then going to merge this instruction into that file intelligently. If I then open the file up and do a search, I'll see that in fact, yes, it did add in that new instruction.

Now that we've created our ClaudeMD file, I want to give you a better understanding of how to pull in specific context into a conversation. Let's imagine that we want to better understand how the authentication system in this project works. We could just ask Claude to tell us about it, in which case it would search over our code base and find files relevant to the authentication system. That would definitely work, but it would just take some amount of time. Alternatively, if we already know some files that are relevant for the authentication system, we could mention them using the at character. When we mention a file, it will be automatically included inside of our request off to Claude. This is an excellent technique for pointing Claude in a specific direction.

You can use the same syntax to also mention files inside of ClaudeMD. Let me show you an example of why that is really useful. Inside of the Prisma folder of this project, there's a file called schema.prisma. This file contains a complete definition of all the different tables and types of records that exist inside the SQLite database that is used to store information inside this project. Because this information is so important and relevant to so many aspects of this project, I might decide to mention this file inside of my clod.md file. Let me show you how I'd do that. First, I'll enter a pound to enter memory mode. I'll then mention that schema file, and specifically tell clod to reference that file any time it needs to better understand the structure of data inside the database. Once the update is complete, I'm going to take a look at the clod.md file and just verify that the note was added. When you mention a file like this, its contents are automatically included inside of your request. So if I ask what attributes the user has, Claude can immediately answer without reading the schema file.

↑ 目次へ戻る

Claude Code in Action | Lesson 05「Making Changes」(全文ナレッジ)

動画 4分04秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

変更1:スクリーンショット貼り付けでレイアウト修正

  • タスク:左側にあるプレースホルダーテキストをパネル中央へ移動したい。
  • どのコンテンツを動かしたいかを Claude に正確に理解させるため、該当箇所のスクリーンショットを撮って Claude Code に貼り付ける
  • 貼り付けは Ctrl+V。macOS で慣れている Cmd+V ではない点に注意——スクリーンショットの貼り付けには Ctrl+V を使う
  • その上で「そのプレースホルダーを中央に」と依頼 → 少し検索した後、Claude がスタイリングを更新 → ブラウザで確認して完了。

変更2:ツール名の表示をユーザーフレンドリーに(難しめのタスク)

  • タスク:カードコンポーネント(タイトル+説明を表示)を生成させたところ、チャットインターフェース側に「string replace editor」という表示が出る。これは「ファイルが作成中」であることを示すパネルだが、裏側で使われているツールの技術用語がそのまま出ている。
  • やりたいこと:「ファイルを作成しています+ファイル名」のようなフレンドリーな文言にする。ファイル編集・削除などの他ケースも扱う。
  • ここでもスクリーンショットを撮って貼り付け、その文言をユーザーフレンドリーなメッセージに置き換えるよう依頼。
  • このタスクはプロジェクト内をかなり調査する必要がある「少し難しいタスク」——そこで Claude の知能をブーストする2つの方法が登場する。

ブースト手段1:プランモード(plan mode)

  • 有効化:Shift+Tab を2回押す(ファイル編集の auto-accept を既に有効にしている場合は1回)。
  • プランモードでは Claude は:
  • プロジェクト内容の調査を大幅に増やし、より多くのファイルを読む
  • タスク完了のための詳細な計画を立てる
  • 計画完成後、何をしたいかを正確に提示する
  • ユーザーの選択肢:計画を承認して実装させる/軌道修正する(見落としたファイルや考慮漏れのシナリオを指摘する等)。

ブースト手段2:シンキング(extended thinking)

  • Claude の extended thinking 機能を有効にし、タスクについてより深く推論させる。
  • 有効化はいくつかのトリガーフレーズで行い、フレーズごとに思考用トークン予算が段階的に大きくなる
  • 今回は難しめのタスクなので、最大級の「ultra think」で最良の実装方法を考えるよう依頼。

プラン×シンキングの併用と使い分け

  • プランとシンキングは併用できる。今回は ultra think+プランモードの両方を有効にして実行。
  • 使い分けの考え方=「広さ(breadth)vs 深さ(depth)」
  • プランモード=広さ:コードベースの広い理解が必要で複数エリアを見るタスク、複数ステップかかるタスクに有効
  • シンキング=深さ:特定の厄介なロジックに集中するときや、難しいバグのトラブルシューティングに有効
  • 「常時オンにすべきか?」→ 可能だが、プランもシンキングも追加トークンを消費する=コストがかかる点に留意。

結果確認と Git コミット

  • 数分の作業で機能が完成。エディタに戻ってテスト:
  • ファイル作成時に以前よりも良いステータス情報(「ファイルを作成しています」)が表示される
  • フォローアップ(タイトルの変更依頼)を送ると、app.jsx ファイルを編集中という表示に変わる——編集ケースも正しく扱えている
  • 変更が済んだらコミット。Claude Code は優秀な Git アシスタント:ステージとコミットを頼めば、説明的なコミットメッセージも書いてくれる

実務ポイント(このレッスンから持ち帰るもの)

  • UI 上の「ここを直したい」はスクリーンショットを撮って Ctrl+V(Cmd+V ではない)で貼り付けてから指示すると、対象の誤解がなくなる。
  • 難しいタスクは2つのブーストを使う:プランモード(Shift+Tab×2、auto-accept 中は×1)=広さthinking トリガーフレーズ(最大 "ultra think")=深さ
  • 使い分け基準:複数エリア・複数ステップ→プランモード/厄介なロジック1点・難バグ→thinking。両方必要なら併用可。
  • プラン・thinking は追加トークンを消費する。常時オンにはコストが伴うため、タスク難度で使い分ける。
  • 実装後は挙動をアプリ上で確認し、コミットは Claude に「stage して commit」と頼めば説明的なメッセージ付きでやってくれる。

本文(時系列・日本語逐語+画面差し込み)

[0:00] このプロジェクトにいくつか変更を加えてみましょう。その過程で、Claude Code まわりの便利な機能をいくつか紹介します。

🖥 [0:07] 画面: VS Code(プロジェクト名 uigen)。右側ターミナルに Claude Code が起動しており、空のプロンプト欄にヒントが表示されている。 ```

Try "write a test for file-system.ts" ? for shortcuts ⧉ In CLAUDE.md `` 左のエクスプローラーには.claude/.next/node_modules/prisma/public/src/.env/CLAUDE.md/package.json/vitest.config.mts` などが見える。

[0:06] 最初にやりたいのは、左側にあるこのプレースホルダーテキストを、このパネルの中央まで移動することです。どのコンテンツを動かしたいのかを Claude に正確に理解させるため、ちょうどその領域のスクリーンショットを撮り、それを Ctrl+V で Claude Code に貼り付けます。macOS で慣れているであろう Cmd+V ではなく、Ctrl+V である点に注意してください——スクリーンショットの貼り付けには、特に Ctrl+V を使います。それから Claude に、そのプレースホルダーを中央寄せするよう頼めます。少し検索した後、Claude はスタイリングの更新をやってのけます。そしてブラウザに戻ると——ええ、いい感じですね。

🖥 [0:15] 画面: Chrome で localhost:3000 の開発中アプリ「React Component Generator」を表示。左パネル上部(=移動対象のプレースホルダー)に「Start a conversation to generate React components / I can help you create buttons, forms, cards, and more」、右パネルに「Welcome to UI Generator / Start building React components with AI assistance / Ask the AI to create your first component to see it live here」。下部に入力欄「Describe the React component you want to create...」。ヘッダーに「Preview / Code」タブ、「Design #70176」「+ New Design」ボタン。

🖥 [0:31] 画面: 解説スライド「Screenshots」——Paste = Ctrl + V/Screenshot on MacOS = Cmd + Shift + 4/Screenshot on Windows = Win + Shift + S。注記「On MacOS and the screenshot isn't working? Try Cmd-Shift-5, select Options, then select 'Clipboard'」。右のターミナルでは画像を貼り付けて指示を入力済み: ```

[Image #1] center this content ```

🖥 [0:36] 画面: Claude が調査の末に編集を提案。エディタ中央に MessageList.tsx の diff(16行目の <div className=... が赤→緑で置換)。ターミナル: ``` Read(src/components/chat/ChatInterface.tsx) Read 43 lines (ctrl+r to expand)

The issue is that the MessageList component needs its parent container to provide proper height. The ScrollArea wrapper doesn't pass the full height to its children. Let me update the MessageList component to ensure the empty state is properly centered:

Update(src/components/chat/MessageList.tsx)

Opened changes in Visual Studio Code ⧉ Save file to continue…

Do you want to make this edit to MessageList.tsx? ❯ 1. Yes 2. Yes, and don't ask again this session (shift+tab) 3. No, and tell Claude what to do differently (esc) ```

[0:39] 次にこのアプリで変更したいことをお見せしましょう。タイトルと説明文を表示するカードコンポーネントを頼んでみます。カードは何の問題もなく生成されますが、1つ不格好なところがあります。左側のチャットインターフェースに「string replace editor」という表示があるのです。あの小さなパネルは、ファイルが作成中であることをユーザーに示すためのものです。ところが今は、裏側で使われているツールを指す非常に技術的な用語「string replace editor」をそのまま出してしまっています。

🖥 [0:45] 画面: ブラウザでカード生成のデモ。チャット左側:ユーザー「Create a card with a title and a description」→ アシスタント「I'll create a simple React component for a card with a title and description using Tailwind CSS.」の直下に、問題のツール名バッジ: ● str_replace_editor 続けて「I've created a React application with a Card component that displays a title and description. The card has a clean design with a white background, subtle shadow, and rounded corners. / The App component renders the Card in the center of the screen against a light gray background. You can easily customize the title and description by changing the props passed to the Card component.」。右プレビューに「Card Title / This is a simple card component with a title and description. You can customize this text as needed.」のカードが表示されている([1:15] 時点でもこの画面のまま、カーソルが str_replace_editor バッジを指している)。

[1:00] ここではユーザーにもう少し親切なテキストを見せて、ファイルが作成中であることと、そのファイル名だけを伝えたいのです。そしてもちろん、このチャットボットがファイルを編集している、あるいはファイルを削除している、といった他のケースも扱うべきでしょう。Claude の注意を導くために、もう一度これのスクリーンショットを撮って、私が何の話をしているのかを正確に理解させます。それからこちら(Claude Code)に戻って、その画像を貼り付け、あの特定のテキストをもっとユーザーフレンドリーなメッセージに置き換えるよう Claude に頼みます。

🖥 [1:21] 画面: ターミナル。変更1(中央寄せ)の完了報告が出て、空のプロンプトが次の指示を待っている: ● Done! Changed h-full to min-h-[calc(100vh-200px)] to ensure the empty state content is vertically centered in the viewport, accounting for the header and input areas. 下部ステータス: ⏵⏵ auto-accept edits on (shift+tab to cycle) / 右下 ⧉ In MessageList.tsx

🖥 [1:43] 画面: スクリーンショットを貼り付けて指示を入力済み: ```

[Image #3] Replace the 'str_replace_editor' text with a more user friendly message of what this tool call is doing. For example, maybe state that a file is being created or edited, along with the name of the file being modified. Also, put this into a new component and write tests for it. ```

[1:29] さて、これは少しトリッキーなタスクで、完了するには Claude がこのプロジェクト内でかなりの量のリサーチをする必要があります。Claude に難しめのタスクを与えるときはいつでも、Claude の知能を簡単にブーストできる方法が2つあります。1つ目の方法は、プランモードを有効にすることです。プランモードは Shift+Tab を2回押すと有効になります——すでにファイル編集を自動承認(auto-accept)している場合は1回だけです。プランモードでは、Claude はプロジェクトの内容に対してはるかに多くのリサーチを行い、より多くのファイルを読み、あなたのタスクを完了する方法について詳細な計画を立てます。

🖥 [1:45] 画面: 解説スライド「Planning mode」——「Enable with Shift + TabShift + Tab」「Claude will do some thorough exploration and planning before writing any code」。この時点の右側ターミナルのステータスはまだ ⏵⏵ auto-accept edits on (shift+tab to cycle)

🖥 [1:54] 画面: Shift+Tab でモードを切り替え、ステータス表示が ⏸ plan mode on (shift+tab to cycle) に変わった。

[1:59] 計画が完成すると、Claude はあなたのタスクを完了するために何をしたいのかを正確に伝えてきます。その時点で、この計画を承認して Claude に実装させることもできますし、何らかの形で Claude を軌道修正することもできます——もしかすると何かのファイルを見落としていたり、何かのシナリオを考慮していなかったりするかもしれませんから。

🖥 [2:01] 画面: プランモードの成果物として詳細計画が出力され、末尾で承認を求められる(約2秒の間に計画全文が高速スクロール表示される): ``` Implementation steps:

  1. Create new component /src/components/chat/ ToolInvocationDisplay.tsx
    • Parse tool arguments to determine the action
    • Return user-friendly messages like "Creating file App.jsx", "Editing file Button.tsx", etc.
  2. Write comprehensive tests /src/components/ chat/tests/ToolInvocationDisplay.test.tsx
    • Test all command types (create, str_replace, view, insert, rename, delete)
    • Test loading and completed states
    • Test edge cases
  3. Update MessageList.tsx to use the new component instead of displaying raw tool names
  4. Update existing MessageList tests to work with the new component

The component will transform technical tool names into readable messages like: - "str_replace_editor" with create command → "Creating file [filename]" - "str_replace_editor" with str_replace command → "Editing file [filename]" - "file_manager" with rename command → "Renaming file [oldname] to [newname]" - "file_manager" with delete command → "Deleting file [filename]"

Would you like to proceed? ❯ 1. Yes 2. No, keep planning ``` 計画の途中には「3. Show appropriate status indicators (loading spinner or success checkmark) / 4. Handle both tools: str_replace_editor and file_manager」という項も見える。

[2:13] Claude の知能をブーストできる2つ目の方法は、シンキング(thinking)を有効にすることです。これは Claude の拡張思考(extended thinking)機能をオンにして、特定のタスクについてより多く推論できるようにします。シンキングを有効にするには、いくつかの異なるトリガーフレーズがあります。それぞれのフレーズが、Claude に段階的に大きくなる思考用トークン予算を与えます。これはトリッキーめのタスクですから、実装の最良の方法について「ultra think」するよう Claude に頼むことにしましょう。

🖥 [2:15] 画面: 解説スライド「Thinking modes」——「Allows Claude to reason about more challenging problems」。トリガーフレーズの階段表(上から下へ思考量が増える): Less thinking ↑ "Think" "Think more" "Think a lot" "Think longer" More thinking ↓ "Ultrathink" 右のターミナルには(別テイクの)プロンプト「[Image #1] Replace the 'str_replace_editor' text with a more use friendly message of what this tool call is doing. For example, maybe state that a file is being created or edited, along with the name of the file being modified. Also, put this in a new component and write tests for it.」が入力済み。

[2:36] 最後に理解しておくべきことは、プランニングとシンキングは併用できるということです。そこで、この ultra think に加えて、プランモードもオンにします。では実行して、Claude がこの機能をどれだけうまく実装できるか見てみましょう。

🖥 [2:45] 画面: プロンプト末尾に ultrathink の指示文を追記し、プランモードもオンにして実行する直前: ```

[Image #1] Replace the 'str_replace_editor' text with a more use friendly message of what this tool call is doing. (中略) Also, put this in a new component and write tests for it. This is a tough task, so ultrathink about the best way to implement it. `` ステータス:⏸ plan mode on (shift+tab to cycle)`

[2:48] さて、いつプランニングを使い、いつシンキングを使うべきか疑問に思っているかもしれません。この2つは「広さ(breadth)対 深さ(depth)」を扱うものだと考えてください。プランモードが有効なのは、コードベースの幅広い理解を必要とし、異なる複数のエリアを見ることが求められるタスクがあるときです。完了までに複数のステップを要するタスクに取り組むときにも有効です。一方シンキングが有効なのは、特定の厄介なロジックの一点に集中しているときや、難しいバグをトラブルシューティングしているときです。

[3:13] 2つ目に浮かぶ疑問は、シンキングとプランニングを常に有効にしておけばいいのではないか、というものでしょう。ええ、確かにそうすることはできます。ただ、プランニングとシンキングは追加のトークンを消費するということを覚えておいてください。つまり、使用にはコストが伴うのです。

🖥 [3:15] 画面: 実装が進行中。エディタに追加行の diff(緑)、ターミナルには思考と TODO 進行の表示: ``` ✻ Thinking…

Perfect! I've successfully updated the MessageList component to use the new ToolInvocation component. Now let me mark this task as complete and move on to creating comprehensive tests for the ToolInvocation component.

● Update Todos

· Enhancing… (71s · 6.0k tokens · esc to interrupt) `` ステータス:⏵⏵ auto-accept edits on (shift+tab to cycle)`

[3:25] 数分の作業の後、機能が完成したようです。そこでエディタの方へ戻って、これをテストしてみます。すぐに、以前あったものより良いステータス情報がここに表示されているのが分かります。ユーザーはいま「ファイルが作成中である」と伝えられるようになりました。そしてフォローアップのリクエスト——たとえばタイトルの変更——を送れば、今度はそのフォローアップで、そのファイルを編集中であることについての何かが表示されるはずです。ほら、できました。今度は app.jsx ファイルを編集中となっています。Claude は間違いなく、この機能の実装に成功したと言ってよいでしょう。

🖥 [3:29] 画面: ブラウザで再テスト。「Create a card with a title and a description」を送ると、以前 str_replace_editor と表示されていた場所が次のバッジに変わっている: ● Creating App.jsx

🖥 [3:46] 画面: フォローアップ「Change the title」を送信。アシスタント「I'll update the title in the App.jsx file:」の直下に(直後は「⟳ Generating...」表示を経て): ● Editing App.jsx

[3:52] さて、このプロジェクトに変更を加えたので、変更をコミットしておくべきでしょう。Claude Code は堅実な Git アシスタントです。変更のステージとコミットを頼むことができ、説明的なコミットメッセージも書いてくれます。

🖥 [3:53] 画面: VS Code のターミナルに戻る。Claude Code の空プロンプト(ヒント「Try "how do I log an error?"」、右下 ⧉ In MessageList.tsx)。

🖥 [4:02] 画面: ステージ&コミットを頼むと、Claude が Bash コマンドの実行許可を求める: ``` Bash command

git commit -m "Add ToolInvocation component for displaying AI tool usage

  • Created ToolInvocation component to show tool calls in chat
  • Added unit tests for ToolInvocation component
  • Updated MessageList to use ToolInvocation for tool messages
  • Updated MessageList tests to cover new functionality

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com" Create commit with descriptive message

Do you want to proceed? ❯ 1. Yes 2. Yes, and don't ask again for git commit commands in /Users/sgrider/code/enablements/claude-code-course/prod/uigen 3. No, and tell Claude what to do differently (esc) ```

英語逐語(ASR全文)

※ ASR原文ママ("cloud code"/"cloud"=Claude Code/Claude 等の誤認識を含む)

Let's try making a couple of changes to this project. Along the way, I'll show you some useful features around cloud code. The first thing I'd like to do is move this placeholder text over here on the left-hand side, down to the center of this panel to help cloud understand exactly what content I want moved. I'm going to take a screenshot of that area right there, and then I'm going to paste it into cloud code using control V note that it's control V and not command V that you might be used to on Mac OS control V is used specifically to paste in a screenshot. I can then ask Claude to center that placeholder. After a little bit of searching, Claude is able to make the styling update. And then back inside the browser, yeah, looks great.

Let me show you the next thing I would like to change in this app. I'm going to ask for a card component that displays a title and some description. The card is generated without any issue, but there is one awkward thing. On the left-hand side in the chat interface, there's string replace editor. That little panel right there is meant to indicate to the user that a file is being created. But right now it's using a very technical term, string replace editor for the tool that is being used behind the scenes. I would like to show a user a little more friendly text here and just tell the user that a file is being created and the name of the file. And of course we should also handle cases where maybe this chatbot is editing a file or deleting a file and other stuff like that. To help guide Claude's attention I'm going to once again take a screenshot of this so it understands exactly what I'm talking about. Then back over here I'm going to paste that image in and ask Claude to replace that particular text with some more user-friendly message.

Now, this is a little bit of a tricky task that will require Claude to do a decent amount of research in this project to complete. Whenever you give Claude a harder task, there are two ways that you can easily boost Claude's intelligence. The first way is to enable plan mode. Plan mode is enabled by pressing shift tab twice or just once if you are already auto accepting file edits. In plan mode, Claude will do much more research over the contents of your project, reading more files, and coming up with a detailed plan on how to complete your task. After completing the plan, Claude will tell you exactly what it wants to do to complete your task. At that point, you can either accept this plan, and Claude will implement it, or you can redirect Claude in some way, maybe it missed some file or didn't consider some scenario.

The second way in which we can boost Claude's intelligence is by enabling thinking. This turns on Claude's extended thinking feature, allowing it to reason more about a particular task. To enable thinking, there are a handful of different trigger phrases. Each one gives Claude a progressively larger token budget to think with. Given that this is a trickier task, I might ask Claude to ultra think about the best way to implement it. The last thing to understand is that planning and thinking can be used together. So in addition to this ultra think, I'm going to also turn on plan mode as well. And now I'm going to run this and we'll see how well Claude can implement this feature.

Now you might be wondering when you should use planning and when you should use thinking. Think of these two as handling breadth versus depth. Planning mode is useful when you have a task that requires a wide understanding of your code base and requires looking at different areas. It's also useful when working on a task that requires several steps to complete. Thinking, on the other hand, is useful when you are focusing on a particular tricky bit of logic or troubleshooting a difficult bug. The second question you might have is whether you should just enable thinking and planning all the time. Well, you certainly can. Just keep in mind that planning and thinking consume additional tokens. So there is a cost associated with using them.

After a couple of minutes of work, it looks like the feature is complete. So I'm going to go back over to my editor and test this out. So right away, we can see that we get some better status information here than what we had before. Users are now being told that a file is being created. And if I send in a follow-up request, maybe to change the title, hopefully now on the follow-up, we'll see something about editing that file. So there we go. So now we're editing the app.jsx file. Well, I would say Claude definitely succeeded in implementing this feature. Now that we have made some changes to this project, we should probably commit our changes. Claude code is a solid Git assistant. We can ask it to stage and commit our changes, and it will write a descriptive commit message for us.

↑ 目次へ戻る

Claude Code in Action | Lesson 06「Controlling Context」(全文ナレッジ)

動画 3分37秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

このレッスンのテーマ

会話(コンテキスト)の流れをコントロールし、Claude をタスクに集中させ続けるためのテクニック集。

Esc — 実行中の Claude への割り込み

  • 例: 認証ファイル(auth.ts)内の関数群へのテスト作成を依頼すると、Claude は複数テストを一気に書く計画を立てる。しかしこのファイルのテストは難しいので「一度に1つだけ」テストさせたい。
  • Esc を押すと Claude をその場で停止でき、別の進め方を提案(指示)し直せる。

Esc + メモリ(# ショートカット)— 「繰り返すエラー」の恒久対策

  • 同じファイルへのテスト作成を再依頼すると、Claude が実在しないテスト設定ファイルを読みに行く。これはこのプロジェクトで以前にも見たエラー。
  • 再発を止めるには、素早く Esc で停止 → #(pound ショートカット)でテスト設定ファイルの正しい名前をメモリに追加。以後このエラーはほぼ見なくなる。
  • これらの会話コントロールショートカットは単なる便利機能に見えるが、正しく使えば Claude の作業効率とタスク集中力を大きく改善する。

Esc 2回 — 会話履歴の巻き戻し(不要コンテキストの切り捨て)

  • 実例: auth.ts の4関数を1つずつテスト。最初の create session のテスト中に、未インストールのパッケージが原因のエラーが出て、デバッグの往復が発生。
  • テスト完成後、会話履歴には「壊れたパッケージ」をめぐる大量のやり取りが残る。これは次のテスト作成には全く関係のないコンテキスト=気を散らすノイズ。
  • 理想は「過去の自分のメッセージ時点に戻って、そこから『get session のテストを書いて』に書き換える」こと。こうすれば Claude が auth.ts の中身をすでに読んだというコンテキストは保持したまま、デバッグの雑音だけを捨てられる。
  • 方法: Esc を2回押す → 自分が送ったメッセージの一覧が表示され、過去の時点に巻き戻して中間の会話をスキップできる。

/compact — 会話を要約して「学び」を次タスクへ持ち越す

  • 現在の会話の全メッセージを要約するコマンド。
  • Claude が数分間の自律作業で「このファイルのテストの書き方」を深く学習した後など、その知識を維持したまま次のタスクに進みたい時に有効。

/clear — 会話履歴を全部捨ててゼロから

  • 会話履歴を丸ごと破棄し、まっさらな状態から開始できる。
  • 現在のタスクと無関係な、完全に別のタスクを始める時に最も有効。

使いどころ

タスクの切り替え時、および長時間に及ぶ会話では、これらのショートカットを頻繁に使うことを推奨。本コースの残りでも Claude をタスクに集中させるために何度も使用する。

実務ポイント(このレッスンから持ち帰るもの)

  • 実行中でも Esc で即座に割り込める。間違った方向に走り出したら止めて軌道修正する。
  • 同じエラーを繰り返すなら Esc# でメモリに正しい情報を追加し、恒久対策にする。
  • Esc 2回で会話を巻き戻し、デバッグの往復など「次のタスクに無関係な雑音コンテキスト」を捨てる。必要な文脈(ファイルを読んだ事実など)は残る。
  • /compact=要約して知識を持ち越す(関連タスクの続き用)、/clear=全部捨てる(無関係な新タスク用)、と明確に使い分ける。
  • コンテキスト管理はタスク切替時と長時間セッションで特に効く。「便利機能」ではなく Claude の集中力を保つ中核テクニック。

本文(時系列・日本語逐語+画面差し込み)

画面はデモプロジェクト「uigen」(Next.js + Prisma + vitest 構成)を開いた VS Code。右側ターミナルで Claude Code が動作。🖥 のタイムスタンプはフレーム抽出位置からの近似値。

[0:00] この動画では、会話の流れをコントロールし、方向づけるためのいくつかのテクニックをお見せしたいと思います。さっそく基本的な例です。認証ファイルに書かれたいくつかの関数について、Claude にテストを書くよう頼みます。Claude はすぐに、複数の異なるテストを作成する計画を立てます。

🖥 [0:05] 画面: VS Code(プロジェクト名 uigen)。左エクスプローラーに .claude .next node_modules prisma public src.env .eslintrc.json .gitignore CLAUDE.md components.json next-env.d.ts next.config.ts package-lock.json package.json postcss.config.mjs README.md tsconfig.json vitest.config.mts。右の TERMINAL タブで Claude Code が実行中: ```

Write tests for the @src/lib/auth.ts file ⎿ Read src/lib/auth.ts (75 lines)

● I'll write comprehensive tests for the auth.ts file. Let me first check the existing test setup and then create the tests.

● Update Todos

✳ Scribing… (8s · ⚒ 237 tokens · esc to interrupt) `` 入力欄下に? for shortcuts`。

🖥 [0:14] 画面: Claude が Todo 計画を提示(複数テストを一気に書く計画): ``` ● Update Todos ⎿ ☐ Check existing test setup and patterns ☐ Create test file for auth.ts ☐ Write tests for createSession function ☐ Write tests for getSession function ☐ Write tests for deleteSession function ☐ Write tests for verifySession function ☐ Run tests to verify they work

· Scribing… (12s · ↑ 254 tokens · esc to interrupt) ```

[0:16] しかし、このファイルのテストは少し難しいことが分かっているので、Claude には一度に1つのことだけをテストしてほしいのです。Claude に割り込むには、Esc(エスケープ)を押せばよいのです。これで Claude をその場で止めることができ、別の進め方を提案できます。

🖥 [0:25] 画面: 左側にスライドカード「Interrupting — Stop Claude with Esc」、下部の説明文「Interrupt Claude, allowing you to redirect it or give alternative instructions」。右ターミナルでは Todo リスト(createSession / getSession / deleteSession / verifySession / Run tests…)の直後に: ``` ⎿ Interrupted by user

Actually only write tests for the createSession function for now.

● I'll update my todo list and write tests specifically for the createSession function.

● Update Todos ⎿ ☐ Check existing test setup and patterns ☐ Create test file for auth.ts ☐ Write tests for createSession function

✻ Writing… (6s · ↑ 103 tokens · esc to interrupt) ```

[0:30] Esc とメモリ(memories)を組み合わせるのは、Claude が繰り返し犯すエラーを直すための非常に強力な方法です。例をお見せします。同じファイルに対して、もう一度テストを書くよう Claude に頼みます。今回は、実際には存在しないテスト設定ファイルを読み込もうとします。

🖥 [0:40] 画面: ターミナル上部に auth.ts の説明の末尾「…expiration time. It uses the jose library for JWT operations and Next.js cookies API.」。続いて: ```

Write tests for the createSession function

● I'll write tests for the createSession function. Let me first check the existing test setup and then create appropriate tests.

● Search(pattern: "*/.test.ts") ⎿ Found 11 files (ctrl+r to expand)

● Read(src/lib/tests/file-system.test.ts) ⎿ Read 678 lines (ctrl+r to expand)

● Read(vitest.config.ts) ⎿ Error: File does not exist. Did you mean vitest.config.mts?

✳ Exploring… (15s · ↑ 91 tokens · esc to interrupt) `` ※ 存在しないvitest.config.tsを読もうとして赤字エラー(正しくはvitest.config.mts`)。

[0:44] さて、これは私がこのプロジェクトで Claude が以前にも犯すのを見たことのあるエラーです。そこで、この間違いが繰り返されるのを止めるために、すぐさま Esc を押します。次に #(ポンド)ショートカットを使って、このテスト設定ファイルの正しい名前についてのメモリを追加します。これで、おそらくこのエラーを二度と見なくて済むでしょう。

🖥 [0:52] 画面: 左側にスライドカード「Repetitive error? — Stop Claude with Esc / Add a memory with #」、説明文「Add a memory to the CLAUDE.md file, helping Claude avoid this error in the future」。右ターミナル: ``` ● Read(vitest.config.ts) ⎿ Error: File does not exist. Did you mean vitest.config.mts? ⎿ Interrupted by user

vitest config is in vitest.config.mts

⎿ Good to know.

continue▌ ``` 下部ステータスに「Saving project memory…」(# で入れたメモリが CLAUDE.md に保存されている)。

[1:01] こうした会話コントロールのショートカットのいくつかは、単なる便利機能のように見えます。しかし正しく使えば、Claude が効果的に作業し、タスクに集中し続ける能力を本当に向上させることができます。そこで、もっと実践的な例をお見せしましょう。

🖥 [1:10] 画面: ターミナルに auth.ts の要約が表示されている: ``` Key exports: - createSession(userId, email) — Creates JWT token and sets httpOnly cookie - getSession() — Retrieves and verifies session from cookies - deleteSession() — Removes auth cookie - verifySession(request) — Verifies session from NextRequest

Implementation details: - Uses jose library for JWT operations - 7-day token expiration - Stores token in httpOnly cookie named "auth-token" - JWT secret from JWT_SECRET env var (defaults to "development-secret-key") - Server-only module (can't be imported client-side) `` 入力欄にはユーザーが> Write tests for the c▌` と入力中(createSession のテスト依頼を打ちかけている)。

[1:12] auth.ts ファイルの中には4つの異なる関数があり、Claude にはそれぞれのテストを一度に1つずつ書いてもらいたいのです。まずは createSession という関数から始めます。Claude は間違いなくテストを書こうとしますが、それを実行する中でエラーに遭遇し、少しの時間をデバッグに費やします。実は、私がインストールし忘れていたパッケージがあったのです。最終的にテストは完成して動くようになり、次のテスト群に取りかかる時が来ます。

🖥 [1:30] 画面: デバッグ後の様子。差分(30行目に + tokenCounter = 0;、31〜33行目に mockCookies = { set: vi.fn(), };)に続き: ``` ● Now let's run the tests again:

● Bash(npm test src/lib/tests/auth.test.ts) ⎿ > uigen@0.1.0 test > vitest src/lib/tests/auth.test.ts … +13 lines (ctrl+r to expand)

● Great! All tests are passing. Let's also run lint to ensure code quality:

● Bash(npm run lint src/lib/tests/auth.test.ts) ⎿ No (tell Claude what to do differently) ``` 下部に「▶▶ auto-accept edits on (shift+tab to cycle)」。

[1:38] でも、ここがポイントです。私の会話履歴には今、あの壊れたパッケージをめぐる大量のやり取りが残っています。これは、次のテスト群を実行するにはまったく関係のないコンテキストの塊です。

🖥 [1:40] 画面: スライド「Conversation around tests for createSession()」。チャット吹き出しが縦に並ぶ: 「Whats in the @auth.ts file?」→「The file contains several functions」→「Write tests for 'createSession'」→「Sure! I'll write tests for that.」→「Research and test writing」→「Error related to missing package」→「Investigating the error」→「Fixing the error」→「Running the tests」。エラー関連の3つの吹き出しが赤枠で囲まれ、赤字ラベル「Messages not related to the next set of tests」が指している。

[1:50] 理想を言えば、時間を遡って、以前に送ったメッセージまで戻り、それを「getSession のテストを書いて」と書き換えるだけ、ということができればよいのです。ここでの利点は、Claude がすでに auth.ts ファイルの中身を確認したというコンテキストを維持できること、そして私たちが getSession と言えば何の話をしているのか Claude がすでに分かっている、ということです。さらに、デバッグの話でしかなかった余計なメッセージを全部捨てたので、注意をそらすものもそれほど多くなくなります。つまり、ここでも Claude は本当に集中してタスクに取り組み続けられるのです。

🖥 [2:05] 画面: 同じスライドだが、吹き出しが3つだけに減っている: 「Whats in the @auth.ts file?」→「The file contains several functions」→「Write tests for 'getSession'」(getSession が太字)。エラー関連のやり取りが会話から消えた状態を図示。

[2:18] 会話履歴の中を戻るには、Esc を2回押します。すると、自分が送ったすべてのメッセージが表示されるので、過去の時点まで巻き戻して、途中の会話をスキップすることができます。

🖥 [2:20] 画面: 左側にスライドカード「Rewind a Conversation — Revert to a previous message Escape + Escape」、説明文「Removes context not relevant to the current task」。右ターミナルには auth.ts の Key exports 要約が残ったまま、入力欄では過去メッセージを編集中: > Write tests for the getS▌ function。下に「▶▶ auto-accept edits on (shift+tab to cycle)」。

[2:29] Claude はこれから次のテスト群に取りかかります。今回、Claude は非常に集中を保ちますが、残念ながらいくつもの問題に遭遇します。最終的にはそれらを解決し、テストを通します。さてこの時点で、Claude は数分間ひとりで作業を続けており、このファイルのテストの書き方について非常によく理解しています。同時に、またしても、この会話履歴には大量のコンテキストが溜まっています。

🖥 [2:30] 画面: getSession テストの作業開始。Todo「☐ Add getSession tests to auth.test.ts」に続き: ``` ● Update(src/lib/tests/auth.test.ts) ⎿ Updated src/lib/tests/auth.test.ts with 1 addition and 1 removal 1 import { test, expect, vi, beforeEach, afterEach, describe } from "vitest"; 2 - import { createSession } from "@/lib/auth"; 2 + import { createSession, getSession } from "@/lib/auth"; 3 import { cookies } from "next/headers"; 5 vi.mock("next/headers", () => ({

✳ Scribing… (0s · ↑ 200 tokens · esc to interrupt) ```

🖥 [2:36] 画面: 問題への対処が続く。import の差し替え差分(createSession, getSessioncreateSession, getSession, deleteSession を含む書き換え、import { cookies } from "next/headers"; import { jwtVerify } from "jose";)の後、「…if the cookies mock itself might be the issue:」として: ● Update(src/lib/__tests__/auth.test.ts) ⎿ Updated src/lib/__tests__/auth.test.ts with 3 additions and 6 removals 455 - test("propagates error if cookies operation fails", async () => { 456 - const errorCookies = { 457 - delete: vi.fn().mockRejectedValue( new Error("Cookie deletion failed")), 458 - }; 459 - (cookies as any).mockResolvedValue (errorCookies); 455 + test("propagates error if cookies function fails", async () => { 456 + (cookies as any).mockRejectedValue(new Error("Failed to acces… ステータスは「✻ Typing… (28s · ✻ 900 tokens · esc to interrupt)」(数分間の自律作業でトークンが積み上がっている)。

🖥 [2:42] 画面: テスト完了の要約。番号付きリストの後半(5. Expired and malformed tokens — tests error handling for various JWT issues / 6. Different payload structures / 7. JWT secret consistency — confirms the same secret is used as in createSession / 8. Async operations — tests promise-based cookie operations / 9. Error handling / 10. Cookie identification — ensures the correct cookie name is used / 11. Type preservation — verifies session payload types are maintained)に続き: All 23 tests are now passing successfully.

🖥 [2:50] 画面: (この前後で)会話/セッション履歴の一覧らしき画面が挟まる。列は「Modified / Created / # Messages / Summary」で、各行に相対時刻とメッセージ数・要約(例: 「1. 9s ago / 1m ago / 29 / This session is…」「2. 2m ago / 8m ago / 108 / Whats in the…」「9 / Write tests for…」「24 / run tests fix…」)、最下部に「↓ and 27 more…」。会話に大量の履歴が溜まっていることを示す文脈で表示。

[2:51] 次の関数のテストを書く時になったら、私は compact というコマンドを使います。/compact コマンドは、現在の会話にあるすべてのメッセージを取り込み、それらを要約します。/compact が本当に役立つのは、Claude が現在のタスクについて多くのことを学んでいて、次のタスクに進む際にその知識を維持したい、という時です。

[3:09] 最後に知っておくべきコンテキスト関連のコマンドは、clear コマンドです。/clear は会話履歴を丸ごと捨て去り、ゼロから始められるようにします。/clear が最も役立つのは、現在のタスクとは無関係な、完全に別のタスクを始めようとしている時ならいつでもです。

🖥 [3:10] 画面: 背景にはテストカバレッジの要約(2. Valid JWT token verification and session retrieval / 3. Error handling for invalid, expired, or malformed tokens / 4. Support for different session payload structures / 5. Consistent JWT secret usage / 6. Correct cookie identification by name / 7. Type preservation of session payload / 8. Handling multiple cookies / 9. Edge cases like undefined cookie values、そして「The test file now has complete coverage for all four authentication functions: createSession, getSession, deleteSession, and verifySession.」)。入力欄に > /clear▌ と入力中で、オートコンプリートが表示: /clear Clear conversation history and free up context /compact Clear conversation history but keep a summary in context. Optional: /compact [instructions for summarization]

[3:25] これらのショートカットは、かなり頻繁に使うことをおすすめします。特に、タスクを切り替える時や、Claude と長時間にわたる会話をしている時にはいつでも、です。このコースの残りの部分でも、Claude がタスクに集中し続けられるようにするために、これらを何度も使っていきます。

🖥 [3:20] 画面: まとめスライド「Controlling Context」。4行の対応表: - Escape — Interrupt Claude, allowing you to redirect or correct it. / Also useful to fix issues with # memories. - Double-tap Escape — Rewind the conversation to an earlier point in time. / Allows you to maintain valuable context. - /compact — Summarize the conversation and continue / Helps Claude stay focused but remember what it has learned in the current session. - /clear — Dumps current conversation history. / Useful when switching between different tasks.

英語逐語(ASR全文)

In this video, I'd like to show you a couple of different techniques for controlling and directing the flow of conversation. Here's a basic example right away. I'm going to ask Claude to write tests for some functions written into an authentication file. Claude quickly comes up with a plan for authoring several different tests. However, I know that testing this file is a little tough, and I'd like Claude to only test one thing at a time. To interrupt Claude, I can press escape. This will stop Claude in its tracks, allowing me to suggest a different path.

Combining escape along with memories is a really powerful way to fix errors that Claude makes repeatedly. Here's an example. I'm going to ask Claude to write tests for the same file again. This time around, it will attempt to read a test configuration file that doesn't actually exist. Now, this is an error that I've seen Claude make before on this project. So to stop this mistake from being repeated, I'll very quickly hit escape. I'll then use the pound shortcut to add in a memory about the correct name of this test config file, and now I probably won't have to see this error again.

Some of these conversation control shortcuts seem like they're just for convenience, but used correctly, they can really improve Claude's ability to work effectively and stay on task. So let me show you a more practical example. Inside the auth.ts file, there are four different functions, and I would like to get Claude to write tests for each of them one at a time, first starting on a function called create session. Cloud will definitely attempt to write the tests, but as it is running them, it runs into an error and spends a little bit of time debugging it. It turns out there was a package that I forgot to install. Eventually the tests are completed and working and it's time to start working on the next set of tests.

But here's the thing. In my conversation history, there is now a lot of back and forth around that broken package. Now this is a bunch of context that is not at all relevant to running the next set of tests. Ideally, we would be able to jump back in time and go back to the previous message we sent and just update it to say, write test for git session. Now the benefit here is that we maintain the context where Claude already took a look at the contents of the auth.ts file, and it already knows what we're talking about when we refer to git session. And because we dumped all those extra messages that were just about debugging, we're not going to have as much distraction going on here. So again, Claude can really just stay focused and on task.

To go back in the conversation history, hit escape twice. This will show you all the different messages that you have sent, so you can rewind back to a previous point in time and skip over some intermediate conversation. Claude is now going to start working on the next set of tests. This time around, Claude stays super focused, but unfortunately it runs into a number of issues. It eventually resolves them and gets the test to pass. Now at this point, Claude has been working by itself for several minutes and has a really good idea of how to write tests for this file. At the same time, once again, we have a bunch of context in this conversation history.

When it is time to write tests for the next function, I'm going to use a command called compact. The compact command will take all the messages in the current conversation and summarize them. Compact is really useful when Claude has learned a lot about the current task and you want to maintain that knowledge as it goes into the next task.

The last context-related command to be aware of is the clear command. Clear will dump the entire conversation history. allowing you to start off from scratch. Clear is most useful anytime you are about to start on a completely different task unrelated to the current one. I recommend using these shortcuts quite a bit, particularly when you are changing between tasks or anytime you are having a long-running conversation with Claude. In the remainder of this course, we'll use them several times to make sure that Claude stays on task and focused.

↑ 目次へ戻る

Claude Code in Action | Lesson 07「Custom Commands」(全文ナレッジ)

動画 1分44秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

組み込みコマンドとカスタムコマンド

  • Claude Code で /(スラッシュ)を入力すると、デフォルトで組み込まれたコマンド一覧が表示される。
  • これに加えて自分専用のカスタムコマンドを簡単に追加できる。頻繁に繰り返す作業の自動化に有効。

カスタムコマンドの作り方(例: /audit

  1. プロジェクトディレクトリ内の .claude フォルダを開く
  2. その中に commands ディレクトリを作成
  3. さらにその中に audit.md というファイルを作成 - ファイル名(この場合 audit)がそのままコマンド名になる。 - このコマンドの目的: プロジェクトにインストール済みの全依存パッケージを監査し、脆弱性があれば更新し、その後テストを実行して何も壊れていないことを確認する。
  4. コマンドファイル作成後は Claude Code を再起動する(忘れずに)
  5. 再起動後に /audit と入力すると、作成したコマンドが表示され、実行できる。この例では「コマンド実行 → 脆弱なパッケージの有無を確認 → 必要なら修正 → テスト実行」がそのまま行われる。

引数を受け取るコマンド($ARGUMENTS

  • 例: write_tests コマンド(.claude/commands/write_tests.md)を作成。実行のたびにプロジェクト内の特定ファイルへのテストを作らせたい。
  • コマンド本文の中に $ARGUMENTS というプレースホルダを書いておく。
  • コマンド実行時にファイルパスを渡すと、そのパスが $ARGUMENTS の位置に挿入される。
  • 再起動後に write_tests コマンドを実行できる。
  • 引数はファイルパスに限らず、渡したい任意の文字列でよい。「あるフォルダ内のファイルのテストを」というようなラフな依頼でも、Claude に探す場所のちょっとした方向づけとして機能する。

実務ポイント(このレッスンから持ち帰るもの)

  • 繰り返しタスクは .claude/commands/<名前>.md に落とし込む。ファイル名がそのままスラッシュコマンド名になる。
  • コマンドファイルを作成したら Claude Code の再起動が必要(忘れがちなので注意)。
  • $ARGUMENTS プレースホルダでコマンドを汎用化できる。実行時に渡した文字列がその位置に挿入される。
  • 引数はパス以外の任意文字列でもよい。厳密な形式は不要で「方向づけ」として渡せる。
  • 「監査 → 脆弱性修正 → テストで検証」のような定型フロー丸ごとの1コマンド化が典型的なユースケース。

本文(時系列・日本語逐語+画面差し込み)

[0:00] Claude Code を起動してスラッシュ(/)を入力すると、Claude Code にデフォルトで組み込まれているたくさんのコマンドが表示されます。これらのデフォルトコマンドに加えて、自分専用のカスタムコマンドも簡単に追加できます。カスタムコマンドは、自分が頻繁に実行していると気づいた繰り返し作業を自動化するのに便利です。作り方の例をお見せしましょう。

🖥 [0:15] 画面: VS Code 内ターミナルの Claude Code で / を入力した状態。組み込みコマンドの一覧が表示されている: ```

/ /add-dir Add a new working directory /bug Submit feedback about Claude Code /clear Clear conversation history and free up context /compact Clear conversation history but keep a summary in context. Optional: /compact [instructions for summarization] /config (theme) Open config panel /cost Show the total cost and duration of the current session /doctor Checks the health of your Claude Code installation /exit (quit) Exit the REPL /help Show help and available commands /ide Manage IDE integrations and show status `` プロジェクトはuigen。左のファイルツリーに.claude/.next/node_modules/prisma/public/src/CLAUDE.md` などが見える。

[0:17] プロジェクトディレクトリの中で、.claude フォルダを見つけます。その中に commands という新しいディレクトリを作ります。そしてさらにその中に、audit.md という新しいファイルを作ります。ここで作るファイルの名前——この場合は audit——が、最終的に実行するコマンドの名前になります。

[0:33] このコマンドのゴールは、このプロジェクトにインストールされているさまざまな依存パッケージをすべて監査(audit)し、脆弱性があれば更新し、その後テストを実行して実際に何も壊れていないことを確認する、というものにします。

🖥 [0:45] 画面: .claude > commands > audit.md の中身(8行・全文): ``` Your goal is to update any vulnerable dependencies.

Do the following:

  1. Run npm audit to find vulnerable installed packages in this project
  2. Run npm audit fix to apply updates
  3. Run tests and verify the updates didn't break anything ```

[0:44] コマンドファイルを作成したら、Claude Code を再起動します。再起動を忘れないでください。Claude Code を開き直したら、/audit と入力します。すると、いま作ったばかりのコマンドが表示されます。あとはこれを実行すればよく、この例ではまさに私たちが Claude に頼んだとおりのことをやってくれます。コマンドを実行し、脆弱なパッケージがないか確認し、必要なら修正し、それからテストを実行します。

🖥 [1:04] 画面: エディタのタブは閉じられ、ファイルツリーの .claude > commands の下に audit.md(新規追加マーク U 付き)が確認できる。エディタ中央は VS Code のショートカット一覧(Show All Commands ⇧⌘P など)のみ。

[1:04] コマンドは引数(arguments)を受け取ることもできます。例をお見せしましょう。write-tests というもう一つのコマンドを作ります。このコマンドを実行するたびに、プロジェクト内のある特定のファイルに対するテストを作成してもらいたいのです。コマンド本文の中に、$ARGUMENTS というプレースホルダを入れておきます。コマンドを実行するときにファイルパスを渡すと、そのパスがこの $ARGUMENTS の位置に挿入されます。

🖥 [1:15] 画面: .claude > commands > write_tests.md の中身(5行・全文): ``` Write comprehensive tests for: $ARGUMENTS

Testing conventions: - Use Vitests with React Testing Library - Place test files in a tests directory in the same folder as the source fil ``` (最終行は画面右端で見切れており「…the source fil」まで表示。文脈上は file と続く)

[1:26] それでは Claude Code をもう一度再起動して、writeTest コマンドを実行できます。

🖥 [1:27] 画面: 再起動直後の Claude Code。左ペインには write_tests.md が開いたまま: ``` ✳ Welcome to Claude Code!

/help for help, /status for your current setup

cwd: /Users/sgrider/code/enablements/claude-code-course/prod/uigen

※ Tip: Run /terminal-setup to enable Shift+Enter for new lines

Try "refactor MessageList.tsx" ? for shortcuts In write_tests.md ```

[1:31] ここではっきりさせておくと、渡す引数はファイルパスでなくても構いません。渡したい任意の文字列で大丈夫です。ですから、「どこか特定のフォルダの中にあるファイルのテストを」というようにカジュアルに頼み、Claude にどこを見ればよいかのちょっとした方向づけだけを与える、というやり方もできます。

英語逐語(ASR全文)

When you run Cloud Code, you can enter in a forward slash and see a bunch of commands that are built into Cloud Code by default. In addition to these default commands, you can easily add your own custom commands as well. Custom commands are useful for automating repetitive tasks that you find yourself running frequently. Let me show you an example of how to make one.

Inside of my project directory, I'm going to find the .cloud folder. Inside there, I'll make a new directory called commands. And then inside that, I'll make a new file called audit.md. The name of the file that we create, in this case audit, is going to be the name of the command we eventually run. The goal of this command is going to be to audit all the different dependencies that have been installed into this project, update them if there are any vulnerabilities, and then run tests to make sure that nothing actually broke. Once you have created the command file, you'll then restart Cloud Code. Don't forget to restart it. When you reopen Cloud Code, put in slash audit. This will then display the command that you just created. You can then run this, and in this case it will do exactly what we asked Claude to do. It'll run a command, see if there are any vulnerable packages, fix them if necessary, and then run tests.

Commands can also receive arguments. Let me show you an example. I'm going to make another command called write tests. Whenever I run this command, I want to have some tests created for a very particular file inside my project. Inside of the command text, I'm going to put in a placeholder of $arguments. Whenever I run the command, if I pass in a path to a file, that path will be inserted at dollar sign arguments. So now I can restart Claude code again, and then execute the writeTest command. Now, to be clear, the arguments we pass in don't have to be a file path. It can be any string we want to pass in. So I might casually ask for tests for a file in some particular folder, giving Claude just a little bit of direction on where to look.

↑ 目次へ戻る

Claude Code in Action | Lesson 08「Extending Claude Code with MCP Servers」(全文ナレッジ)

動画 2分53秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

MCP サーバーとは

  • MCP サーバーを使うと Claude Code に新しいツール・能力を追加できる。
  • MCP サーバーはリモートで動くものと、自分のマシン上でローカルに動くものがある。
  • 非常に人気の高い例が Playwright MCP サーバー。Claude Code にブラウザを操作する能力を与える。

インストール手順

  • Claude Code の中ではなく、ターミナルで実行する: claude mcp add + この MCP サーバーの名前(ここでは playwright)+ その後ろにローカルでサーバーを起動するコマンド。
  • その後 Claude Code を起動し、「ブラウザを開いて localhost:3000 のアプリに移動して」と依頼できる。

許可プロンプトの省略設定

  • ブラウザが開く前に、そのツールの実行許可を求められる。
  • 毎回の許可ポップアップが煩わしい場合は、.claude ディレクトリ内の settings.local.json を開き、allow 配列に mcp__playwright という文字列を追加する(アンダースコアは2つであることに注意)。
  • これで Claude Code はこの MCP サーバーと配下のツールを、毎回の許可なしに自由に使えるようになる。Claude Code を再起動して再度ブラウザを開くよう頼むと、許可なしで開く。

実践例: 生成プロンプトの自己改善ループ

  • エディタで src/lib/prompts/generation.tsx を開く。これはこのアプリ内で(ユーザーが依頼した)コンポーネントを実際に生成するために使われるプロンプト。
  • やらせたいこと: Claude Code にブラウザを使わせ、自分でコンポーネントを生成させ、その生成結果に基づいてプロンプト自体を Claude 自身に調整させる → 最終的により見栄えのよいコンポーネントが生成されるようにする。
  • Claude Code への依頼内容: 「localhost:3000 に移動 → コンポーネントの生成を試みる → 生成されたソースコードを見てスタイリングを評価 → generation.tsx 内のプロンプトを更新」。
  • 実行結果: Claude はまずブラウザを開いてコンポーネント生成を試み、コメントを見ると出来にあまり満足していない。この種のアプリで非常によく使われる「紫から青へのグラデーション」スタイルに不満を述べる。その後プロンプトを更新して新しいコンポーネントを再生成。
  • 講師の率直な感想: 期待をはるかに超える良い結果。生成されたテスティモニアルカードは本当に見栄えがよい。

まとめ

  • この結果だけでも、MCP サーバーが多くの興味深いユースケースへの扉を開くことが実感できる。
  • 自分が取り組んでいるプロジェクトの開発を助けてくれる MCP サーバーを探してみることを強く推奨。

実務ポイント(このレッスンから持ち帰るもの)

  • MCP サーバー追加は Claude Code 内ではなくターミナルから claude mcp add <名前> <起動コマンド>
  • 許可ポップアップは .claude/settings.local.jsonallow 配列に mcp__<サーバー名>(アンダースコア2つ)を追加して一括許可できる。設定変更後は再起動。
  • Playwright MCP でブラウザ操作を与えると、「生成 → 実物を目で評価 → プロンプト改善 → 再生成」という自己改善ループを Claude 単独で回せる。
  • 「Claude に成果物を見せて自分で直させる」パターンは、生成系アプリのプロンプトチューニングに特に効く。
  • 自分のプロジェクトに合う MCP サーバーを能動的に探すこと自体が推奨アクション。

本文(時系列・日本語逐語+画面差し込み)

[0:00] MCP サーバーを使うことで、Claude Code に新しいツールと能力を追加できます。これらの MCP サーバーは、リモートで動くものもあれば、自分のマシン上でローカルに動くものもあります。とても人気のある MCP サーバーに Playwright というものがあり、これは Claude Code にブラウザを操作する能力を与えます。これを Claude Code に追加する方法をお見せして、そのあと実際に使って私たちのアプリをもう少し開発してみましょう。

🖥 [0:15] 画面: Anthropic のスライド図解。左に「Claude Code」の枠(中に「...Default set of tools」と点線枠の「Tools provided by MCP servers」)、右に「Playwright MCP Server」の枠。右枠の中の4つのツールが左の点線枠へ矢印で接続されている: Tool to open the browser Tool to run code in the browser Tool to navigate to an address Tool to click on the screen

[0:20] このサーバーをインストールするには、Claude Code の中ではなくターミナルで、claude mcp add を実行し、その後にこの MCP サーバーの名前——ここでは playwright と名付けます——を続け、名前の後ろに、この サーバーをあなたのマシン上でローカルに起動するコマンドを追加します。

🖥 [0:20] 画面: VS Code の TERMINAL タブ(zsh)。プロンプトは uigen git:(main) の状態(ここからインストールコマンドを打つ)。

[0:33] それから Claude Code を起動して、「ブラウザを開いて、localhost:3000 にある私たちのアプリケーションに移動して」と頼めます。ブラウザが開く前に、そのツールの実行許可を求められることに気づくでしょう。

🖥 [0:39] 画面: 画面右側に Chrome ウィンドウ(タブ名 Untitled・アドレスは about:blank)が開いた瞬間。背後の Claude Code には「> Open the br…」「⏺ I'll open t…」「playwright:…」「✳ Browsing…」の途中経過が見える。

🖥 [0:45] 画面: ブラウザが localhost:3000 に到達し、アプリ「React Component Generator」が表示された。左ペインに「Start a conversation to generate React components / I can help you create buttons, forms, cards, and more」、右ペインに「Welcome to UI Generator / Start building React components with AI assistance」、上部に Preview / Code タブと Sign In / Sign Up ボタン、下部に「Describe the React component you want to create...」入力欄。

🖥 [0:47] 画面: ターミナル全景。1回目の実行ログ: ```

Open the browser and navigate to localhost:3000

⏺ I'll open the browser and navigate to localhost:3000.

⏺ playwright:browser_navigate (MCP)(url: "http://localhost:3000") ⎿ - Ran Playwright code: ```js // Navigate to http://localhost:3000 … +41 lines (ctrl+r to expand)

⏺ The page loaded successfully. I can see the React Component Generator interface with: - A chat interface on the left for describing components - A preview/code tab view on the right - Sign In/Sign Up buttons - The preview area showing a welcome message ```

[0:48] ああいう許可ポップアップにうんざりしてきたら、.claude ディレクトリの中の settings.local.json を開いて、その中の allow 配列に mcp__playwright という文字列を追加します——アンダースコアが2つあることに注意してください。これで Claude Code はこの MCP サーバーとその中のツールを、毎回あなたに許可を求めることなく、好きなように使えるようになります。

[1:11] Claude Code を再起動して、もう一度ブラウザを開くよう頼むと、今度は許可を求められることなく開いてくれます。

🖥 [1:14] 画面: ファイルツリーで .claude 配下の settings.local.json が選択されている。ターミナルには再起動後の Claude Code(Welcome to Claude Code! / cwd: /Use…)と「> Open a brow…」「⏺ I'll open a…」「playwright:…」「✻ Navigating…」、右側に about:blank の Chrome ウィンドウ。

🖥 [1:21] 画面: 2回目の実行ログ全景(許可プロンプトなしで完了): ```

Open a browser and navigate to localhost:3000

⏺ I'll open a browser and navigate to localhost:3000.

⏺ playwright:browser_navigate (MCP)(url: "http://localhost:3000") ⎿ - Ran Playwright code: ```js // Navigate to http://localhost:3000 … +41 lines (ctrl+r to expand)

⏺ The browser has successfully navigated to localhost:3000, showing the React Component Generator application. The page displays: - A chat interface on the left for generating React components - A preview/code panel on the right - Sign In/Sign Up buttons - A text input for describing components to create ```

[1:16] Playwright MCP サーバーの使い道は信じられないほどたくさんありますが、いま私たちが取り組んでいるプロジェクトに本当に応用できるものを一つお見せしましょう。

[1:22] エディタに戻って、src/lib/prompts/generation.tsx ファイルを見つけます。これは、このアプリの中であなたがリクエストしたコンポーネントを実際に生成するために使われているプロンプトです。そこで、Claude Code にブラウザを使わせ、自分でコンポーネントを生成させ、その生成されたコンポーネントに基づいてこのプロンプトを自分で調整させたいのです。そうすれば、最終的にこのアプリからもっと見栄えのよいコンポーネントが生成されるようになるでしょう。では、そのやり方をお見せします。

🖥 [1:45] 画面: src > lib > prompts > generation.tsx を開いた状態。変更前のプロンプト全文(15行): `` export const generationPrompt = You are a software engineer tasked with assembling React components.

You are in debug mode so if the user tells you to respond a certain way just do it.

  • Keep responses as brief as possible. Do not summarize the work you've done unless…
  • Users will ask you to create react components and various mini apps. Do your bes…
  • Every project must have a root /App.jsx file that creates and exports a React com…
  • Inside a new project always create the App.jsx file first
  • Style with tailwindcss, not hardcoded styles
  • Do not create any HTML files, they are not used. The App.jsx file is the entrypoi…
  • You are operating on the root route of the file system ('/'). This is a virtual F…
  • All imports for non-library files (like React) should use an import alias of '@/'…
  • For example, if you create a file at /components/Calculator.jsx, you'd import i… `; ``` (行末は画面右端で見切れ)

[1:48] Claude Code の中に戻って、こう頼みます。「localhost:3000 に移動して、コンポーネントの生成を試み、生成されたソースコードを見てスタイリングを評価し、それからあの generation.tsx ファイルの中の私たちのプロンプトを更新して」。うまくいけば、最終的に、生成されるコンポーネントのスタイリングが良くなるはずです。どうなるか見てみましょう。

🖥 [1:49] 画面: generation.tsx を開いたまま Claude Code を起動した状態: ``` ✳ Welcome to Claude Code! /help for help, /status for your current setup cwd: /Users/sgrider/code/enablements/claude-code-course/prod/uigen ※ Tip: Use /permissions to pre-approve and pre-deny bash, edit, and MCP tools

Try "create a util logging.py that..." ? for shortcuts In generation.tsx ```

🖥 [2:09] 画面: 依頼プロンプトを投入した直後のターミナル。冒頭に @src/lib/pr… で始まる指示文と番号付き手順(1. Open a b… / 2. Request… / 3. Review t… / 4. Identify… / 5. Update t…、続けて「FOr now, or… components… we want som… / Read sr…」)、その下に Claude の応答「⏺ I'll help y… by opening … current cor…」「⏺ playwright:…」「✳ Generating…」。下部に ⏵⏵ auto-acc[ept edits on] 表示(テキストは左右見切れ)。

[2:09] Claude はまずブラウザを開きます。そしてコンポーネントの生成を試みます。ここで Claude のコメントをいくつか見てみると、どうやらあまり満足していないようです。この種のアプリケーションでとてもよく使われるスタイル——紫から青へのグラデーションのようなもの——について文句を言っているのに気づくかもしれません。

🖥 [2:15] 画面: ブラウザ内のアプリで Claude 自身が「Create a modern pricing card component with a gradient background, rounded corners, and a call-to-action button」と入力してテスト生成中。チャット応答: 「I'll create a modern pricing card component with a gradient background, rounded corners, and a call-to-action button using React and Tailwind CSS. Let's start by creating the App.jsx file: ⏺ Creating App.jsx / Now, let's create the PricingCard component: ⏺ Creating PricingCard.jsx / I've created a modern pricing card component with: 1. A beautiful gradient background (purple to blue) 2. Rounded corners (rounded-2xl) 3. A call-to-action button with hover effects 4. Additional features: Hover animation (slight scale up) / Checkmark icons for features / Clean typography with proper spacing / Shadow effects for depth」。Code タブには components/PricingCard.jsxApp.jsx、App.jsx のコード(<PricingCard title="Premium Plan" price="$29" period="per month" features={[ "Unlimited access to all features", "Priority customer support", "Advanced analytics dashboard", "Custom integrations", "Team collaboration tools" ]} ctaText="Get Started" />)が表示。

🖥 [2:15] 画面: Preview タブ。生成されたプライシングカード=紫〜青グラデーション背景の「Premium Plan / $29 per month / ✓ Unlimited access to all features / ✓ Priority customer support / ✓ Advanced analytics dashboard / ✓ Custom integrations / ✓ Team collaboration tools / Get Started」。

🖥 [2:16] 画面: ターミナルに Claude の分析結果: ``` ⏺ Update Todos ⎿ ☒ Analyze the current generated component's visual styling ☐ Identify areas where the styling looks too typical/generic ☐ Update the generation prompt to encourage more original designs ☐ Test the updated prompt with a new component request

⏺ Based on my analysis of the generated pricing card component, I've identified several areas where the styling is too typical of standard Tailwind CSS components:

  1. Predictable gradient colors - Purple to blue gradients are very common
  2. Standard rounded corners - Using rounded-2xl is the typical Tailwind approach
  3. Basic shadow effects - shadow-xl is a standard utility
  4. Common hover effects - Scale transform on hover is overused
  5. Generic button styling - The gradient button is a typical pattern
  6. Standard spacing - Using p-8, mt-4, space-y-4 are default choices

✳ Generating… (67s · ⚒ 522 tokens · esc to interrupt) ```

[2:26] そこで Claude は私たちのプロンプトを更新し、それから新しいコンポーネントを生成しようとします。

🖥 [2:24] 画面: ターミナル続き: ``` ⏺ Update Todos ⎿ ☒ Analyze the current generated component's visual styling ☒ Identify areas where the styling looks too typical/generic ☐ Update the generation prompt to encourage more original designs ☐ Test the updated prompt with a new component request

⏺ Now I'll update the generation prompt to encourage more original and creative designs.

⏺ Update(src/lib/prompts/generation.tsx)

✳ Generating… (102s · 1.6k tokens · esc to interrupt) ```

🖥 [2:27] 画面: 更新後の generation.tsx(M マーク付き)。16行目以降に追記されたガイドライン: IMPORTANT STYLING GUIDELINES: * Avoid typical, generic Tailwind pat… * Don't use predictable gradients lik… - Warm sunset gradients (orange-to-… - Ocean depths (teal-to-emerald-to-… - Neon combinations (pink-to-yellow… - Monochromatic with subtle shifts * Experiment with unconventional shap… - Asymmetric designs - Overlapping elements - Rotated or skewed components - Custom clip-paths using Tailwind'… * Use creative spacing and sizing: - Avoid standard p-4, p-8 patterns - Mix different spacing scales for … - Use negative margins for overlapp… * Apply unique effects and animations - Custom transitions beyond simple … - Gradient animations (行末は画面右端で見切れ)

[2:33] 正直に言うと、これは私が期待していたよりもずっと良い結果を出しました。このテスティモニアル(お客様の声)カードは、実際、本当に本当に見栄えがいいです。

🖥 [2:45] 画面: 更新後プロンプトでの再テスト。チャットに「Create a testimonial card component with a modern design」と依頼し、応答は「I'll create a modern testimonial card component for you. Let me start by creating the App.jsx file with a testimonial card that has a unique design. ⏺ Creating App.jsx / I've created a modern testimonial card component with several unique design elements: 1. A layered design with gradient backgrounds and blur effects 2. Subtle colored orbs that create a soft, modern atmosphere 3. A shadow effect for the profile image 4. Custom quote styling with a decorative quotation mark 5. A clean, readable testimonial text section 6. A 5-star rating display at the bottom / The card uses a warm sunset gradient (amber to rose) combined with teal accents for visual interest. The design includes overlapping elements and depth through blur effects and subtle shadows. The card is responsive and will look good on various screen sizes.」。プレビューには Sophia Chen(Product Designer)のテスティモニアルカード=暖色グラデーション背景・引用符付き本文・★5.0 表示。

[2:38] この結果だけからでも、MCP サーバーが多くの興味深いユースケースへの扉を開いてくれることがすぐに実感できるはずです。あなたが個人的に取り組んでいるのがどんな種類のプロジェクトであれ、Claude がその開発を進める助けになりそうな MCP サーバーをいくつか調べてみることを強くおすすめします。

英語逐語(ASR全文)

You can add new tools and capabilities to CloudCode through the use of MCP servers. These MCP servers either run remotely or locally on your machine. A very popular MCP server named Playwright gives CloudCode the ability to control a browser. Let me show you how to add it to CloudCode, and then we'll use it to develop our app a little bit more.

To install this server at your terminal, not inside of CloudCode, we'll execute CloudMCPAdd, and then a name for this MCP server, I'm going to name it Playwright, and then after the name we'll add in a command that will start up the server locally on your machine. We can then start Cloud Code and ask it to open a browser and navigate to our application at localhost 3000. Before the browser opens you might notice that you are required to give permission for that tool to run. If you get tired of all those permission pop-ups you can open up the Cloud directory inside their settings.local.json and then inside of the allow array you can add in a string of mcp underscore underscore notice there are two underscores there playwright this allows cloud code to make use of this mcp server and the tools inside of it in any way it wants without requiring you to provide permission every time if i restart cloud code and then ask it to open a browser again it will do so without requiring you to give permission there are incredible number of ways that you can use the playwright mcp server let me show you one that would be really applicable to the project we are working on right now.

Back inside my editor, I'm going to find the src lib prompts generation.tsx file. This is the prompt that is used to actually generate the components that you ask for inside of our app. So I want to allow Cloud Code to make use of the browser, generate a component on its own, and then tweak this prompt on its own based upon the generated component. And hopefully we'll end up with some better looking components being generated out of our app. So let me show you how we would do that. Back inside of Claude code, I'm going to ask it to navigate to localhost 3000, attempt to generate a component, take a look at the generated source code and evaluate the styling, and then update our prompt inside that generation.tsx file. And hopefully we'll end up with some, at the end of the day, better styling on our generated components. So let's see how it does.

Claude is going to first open up the browser. It's going to attempt to generate a component. And looking at some of the commentary from Claude here, it looks like it's not quite so happy you might actually notice that it complains about a very common style that's used in applications like this, a purple to blue kind of gradient. Cloud is then going to update our prompt and then try to generate a new component. And I'll be honest with you, this actually gave a much better result than I ever expected. This testimonial card actually looks really, really great. Based on these results alone, you can immediately get a sense that MCP servers really open the door to a lot of interesting use cases. And I highly recommend you look into some MCP servers that might aid Claude in developing whatever kind of project you personally are working on.

↑ 目次へ戻る

Claude Code in Action | Lesson 09「Github Integration」(全文ナレッジ)

動画 3分40秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

公式 GitHub 統合のセットアップ

  • Claude Code には公式の GitHub 統合があり、GitHub Action の中で Claude Code を実行できる。
  • セットアップは /install-github-app を実行。以下のステップを案内される: 1. GitHub に Claude Code アプリをインストール 2. API キーを追加 3. その後、プルリクエストが自動生成される
  • この PR は 2つの GitHub Actions を追加する: 1. メンション対応 — issue や PR から @claude で Claude にメンションし、タスクを依頼できる 2. PR レビュー — PR を作成するたびに Claude Code が自動で実行され、変更内容をレビューする
  • どちらのアクションもカスタマイズ可能で、他の種類のイベントをトリガーにする追加アクションも作れる。

メンション機能のカスタマイズ例

  • 前提: 2つの action 設定ファイルを GitHub 上のリポジトリにマージ済みなので、まずローカルに pull する。新しくできた GitHub workflows ディレクトリに2つの action 設定ファイル(PR レビュー用/メンション処理用)がある。
  • カスタマイズの狙い: issue や PR で Claude をメンションしたら、GitHub Action の中でプロジェクトを起動し、Playwright MCP サーバーでブラウザからアプリにアクセスできるようにする。
  • 手順: 1. このワークフロー内で Claude Code が実行される前のステップを追加 — setup コマンドを実行し、開発サーバーを起動する 2. Claude Code の設定を更新し、custom instructions を追加 — これは Claude に直接渡され、追加の指示やコンテキストを与えられる。ここでは「開発サーバーは既に起動済み。必要ならば Playwright MCP サーバーでブラウザからアプリにアクセスできる」と伝える 3. Playwright MCP サーバー自体をセットアップする設定を追加
  • 重要な注意点: Action 内で Claude Code を実行する場合、許可する permission をすべて明示的に列挙しなければならない。しかも MCP サーバーを使う場合、各 MCP サーバーの各ツールを個別に列挙する必要がある(ローカルで見たようなショートカットは存在しない)。Playwright MCP サーバーはツール数が多いので、全部を列挙することになる。
  • 設定更新が終わったら commit して push する。

動作テスト

  • アプリ内の2つのボタン(preview パネルと code パネルの切替)は実際には正常に動くが、「意図通り動いていない」という体で試す。
  • スクリーンショットを撮影 → issue を作成 → スクリーンショットを貼り付け、@claude でメンションして「2つのボタンが意図通り動くか検証して」と依頼 → issue を作成して待つ。
  • Action が起動して Claude が応答するまで1〜2分かかる。Claude Code が動き出す前に、アプリ全体のセットアップと起動が先に走るため。
  • やがて Claude が応答する。多くの場合、与えられたタスクを達成するためのチェックリストを作成する。今回は「アプリにアクセス → ボタンを手動でテスト → 見つかった問題を修正」を試みる。
  • Claude はボタンが実際には正常に動作していることに気づき、所見を文書化したメッセージを残して早期終了する。

まとめ

  • これは GitHub 統合の使い方のごく小さな一例。自分のプロジェクトに合わせてどうカスタムテイラーできるか、時間を取って考えることを推奨。

実務ポイント(このレッスンから持ち帰るもの)

  • /install-github-app 一発で「@claude メンション対応」と「PR 自動レビュー」の2つの GitHub Actions が PR として届く。
  • Action 内で Claude を動かす前に必要な環境(setup・dev サーバー起動)はワークフローの前段ステップとして自分で用意する。
  • custom instructions で「サーバー起動済み」「Playwright MCP が使える」といった前提コンテキストを Claude に直接渡せる。
  • CI 上では permission の全列挙が必須。MCP サーバーはツール単位で個別列挙が必要(mcp__<name> のような一括ショートカットは使えない)。
  • issue にスクリーンショット+@claude メンションで「実ブラウザでの動作検証」まで CI 内で完結できる。問題がなければ Claude は所見を残して正しく早期終了する。

本文(時系列・日本語逐語+画面差し込み)

[0:00] Claude Code には公式の GitHub 統合があり、Claude Code を GitHub Action の中で実行できるようになります。この統合は /install-github-app を実行することでセットアップできます。これがいくつかのステップを順に案内してくれます。まず、GitHub に Claude Code アプリをインストールする必要があります。次に、API キーを追加する必要があります。そしてその後、プルリクエストが自動的に生成されます。

🖥 [0:12] 画面: ブラウザで github.com/apps/claude を表示。GitHub App「Claude」のページ。説明文: 「Run Claude Code from your GitHub Pull Requests and Issues to respond to reviewer feedback, fix CI errors, or modify code, turning it into a virtual teammate that works alongside your development pipelines. / This is built on the publicly available Claude Code SDK.」右側に「Configure」ボタン、Developer: anthropics。

🖥 [0:14] 画面: ターミナルの /install-github-app ウィザード: ``` Install the Claude GitHub App

Opening browser to install the Claude GitHub App…

Please install the app for repository: StephenGrider/uigen-project

Important: Make sure to grant access to this specific repository

Press Enter once you've installed the app… ```

[0:20] このプルリクエストは、2つの異なる GitHub Actions を追加します。

🖥 [0:20] 画面: GitHub の「Open a pull request」画面。「The change you just made was written to a new branch named add-claude-github-actions-1750958584251. Create a pull request below to propose these changes.」base: main ← compare: add-claude-github-actions-1…。タイトル「Add Claude Code GitHub Workflow」、説明「## 🤖 Installing Claude Code GitHub App / This PR adds a GitHub Actions workflow that enables Claude Code integration in our repository. / ### What is Claude Code?」

🖥 [0:21] 画面: 作成された PR「Add Claude Code GitHub Workflow #1」(Open)。「StephenGrider wants to merge 2 commits into main from add-claude-github-actions-1750958584251」。本文に「What is Claude Code? / Claude Code is an AI coding agent that can help with: Bug fixes and improvements / Documentation updates / Implementing new features…」。タブは Conversation 0 / Commits 2 / Checks 0 / Files changed 2(+134 −0)。

🖥 [0:23] 画面: 同 PR をスクロール。「There's more information in the Claude Code documentation. / After merging this PR, let's try mentioning @claude in a comment on any PR to get started!」。追加された2コミット: 「Claude PR Assistant workflow c3a4943」「Claude Code Review workflow 51044af」。下に「No conflicts with base branch / Merging can be performed automatically」と Merge pull request ボタン。

🖥 [0:24] 画面: 同 PR のチェック欄: 「Some checks haven't completed yet — 1 queued check / ⏺ Claude Code Review / claude-review (pull_request) — Queued — Waitin…」(PR 作成をトリガーに Claude のレビュー action が既にキュー投入されている)。

[0:26] 1つ目の action はメンション対応を追加します。つまり issue やプルリクエストから、@claude で Claude にメンションして、Claude に何らかのタスクを実行させることができます。2つ目の action はプルリクエストのレビュー対応を追加します。つまりプルリクエストを作成するたびに、Claude Code が自動的に実行され、提案された変更をレビューします。これらの action は両方ともカスタマイズ可能で、他の種類のイベントをトリガーとする追加の action を足すこともできます。

🖥 [0:25] 画面: スライド「Default Github actions」。左列 Mention Action: 「Claude Code mentioned with '@claude'(Can be mentioned from an issue or a PR)→ Claude Code runs(Claude has access to your codebase)→ Claude completes the task it was given with the mention → Claude Code responds(Response added to the issue or PR)」。右列 Pull Request Action: 「Create a pull request(This triggers an action)→ Claude Code runs(Claude has access to your codebase)→ Claude Code reviews changes → Claude Code posts a full report on the impact of the pull request」。

[0:49] メンション機能をどうカスタマイズできるかお見せしましょう。まず、さきほどあの2つの action 設定ファイルを GitHub 上の私たちのリポジトリにマージしたところです。なので、その変更をローカルマシンに pull する必要があります。

🖥 [0:52] 画面: VS Code のターミナル(zsh)。プロンプト uigen git:(main)(ここから pull を実行)。

[1:00] すると、新しく作られた GitHub workflows ディレクトリの中に、この2つの action 設定ファイルが見えます。片方がプルリクエストレビューの対応を追加するもので、もう片方がメンション処理の対応を追加するものです。

🖥 [1:00] 画面: pull 後のファイルツリー。.claude の下に新しく .github フォルダが現れている。

🖥 [1:15] 画面: .github > workflowsclaude-code-review.y…claude.yml の2ファイル。claude.yml(メンション対応側)のデフォルト内容(29〜48行目): ```yaml with: fetch-depth: 1

  • name: Run Claude Code id: claude uses: anthropics/claude-code-action@beta with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

    Optional: Specify model (defaults to Claude Sonnet 4, uncomment fo…

    model: "claude-opus-4-20250514"

    Optional: Customize the trigger phrase (default: @claude)

    trigger_phrase: "/claude"

    Optional: Trigger when specific user is assigned to an issue

    assignee_trigger: "claude-bot"

    Optional: Allow Claude to run specific commands

    allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run …

    ```

[1:11] さて、メンション機能をこうカスタマイズしたいと思います。issue やプルリクエストの中で Claude をメンションしたら、プロジェクトを起動して、Playwright MCP サーバーを使ってウェブブラウザの中でアプリにアクセスできるようにしたい——すべて GitHub Action の中で、です。

[1:26] これを実現するために、まずこのワークフローの中で Claude Code が実行される前にステップを1つ追加します。setup コマンドを実行し、それから開発サーバーを起動します。次に、Claude Code の設定を更新します。カスタム指示(custom instructions)を追加します。これは Claude に直接渡されるもので、追加の指示やコンテキストを与えることができます。今回は、開発サーバーはすでに起動していること、必要ならば Playwright MCP サーバーを使ってブラウザでアプリにアクセスできることを Claude に伝えます。

🖥 [1:35] 画面: claude.yml のデフォルトのオプション節(46〜63行目)を選択した状態。custom instructions と環境変数のコメント例が見える: ```yaml

Optional: Add custom instructions for Claude to customize its behav…

custom_instructions: |

Follow our coding standards

Ensure all new code has tests

Use TypeScript for new files

Optional: Custom environment variables for Claude

claude_env: |

NODE_ENV: test

```

🖥 [1:45] 画面: 編集後の claude.yml(M マーク)。34〜48行目: ```yaml npm run setup npm run dev:daemon

  • name: Run Claude Code id: claude uses: anthropics/claude-code-action@beta with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

    custom_instructions: | The project is already set up with all dependencies installed. The server is already running at localhost:3000. Logs from it are beign written to logs.txt. If needed, you can query the db with the 'sqlite3' cli. If needed, use the mcp__playwright set of tools to launch a ``` (custom_instructions は入力途中。「beign」は画面上の原文ママ=being の打ち間違い)

[1:51] それから、Playwright MCP サーバー自体をセットアップするための設定を追加します。ここでもう一つ注意すべきことがあります。Claude Code を Action の中で実行するときは、Claude Code に与えたい許可(permission)をすべて明示的に列挙しなければなりません。そしてこれには一つ厄介な側面があります。MCP サーバーを使う場合、許可したい各 MCP サーバーの各ツールを個別に列挙しなければならないのです。以前見たような許可のショートカットは存在しません。残念ながら Playwright MCP サーバーにはたくさんの異なるツールがあるので、それぞれを列挙する必要があります。

🖥 [2:15] 画面: claude.yml の allowed_tools 行(64行目・横に長い1行)。Playwright MCP の各ツールが個別列挙されている(一部のみ視認可能): (sqlite3:*),mcp__playwright__browser_snapshot,mcp__playwright__browser_click,mc… (上方 58 行目には …ilwindcss.com;esm.sh" という文字列の断片も見える)

[2:27] この設定更新が終わったら、忘れずにこれらの変更をコミットして push します。

🖥 [2:29] 画面: ターミナルの git 操作: ``` modified: .github/workflows/claude.yml

no changes added to commit (use "git add" and/or "git commit -a") ➜ uigen git:(main) ✗ git add . ➜ uigen git:(main) ✗ git commit -m "update workflow action"

[main 1a3431b] update workflow action 1 file changed, 1 insertion(+), 1 deletion(-) ➜ uigen git:(main) git push origin main … To github.com:StephenGrider/uigen-project.git b8a0bf9..1a3431b main -> main ```

[2:32] さあ、この更新したワークフローを試すときが来ました。Claude にちょっとしたタスクを与えます。実際のアプリの中で、上にあるこの2つのボタンが見えますか? 今のところ、これらは問題なく動いています。preview パネルと code パネルの間を問題なく切り替えられます。でも、これらが意図したとおりに動いていないふりをすることにします。

🖥 [2:30] 画面: localhost:3000/cmcdm289t001inoauo7x60y5m で稼働中のアプリ。上部中央に Preview / Code の切替ボタン、右上に「Design #17505」「+ New Design」。左はチャット欄、右は「Welcome to UI Generator」。

🖥 [2:38] 画面: Code タブに切り替えた状態。ファイルツリー側は「No files yet / Files will appear here」、エディタ側は「Select a file to edit / Choose a file from the file tree」(トグルが正常動作している実演)。

[2:44] あそこにあるボタンでスクリーンショットを撮ります。それから issue を作ります。スクリーンショットを貼り付けて、@claude で Claude にメンションし、この2つのボタンが意図どおりに動くか検証するよう頼みます。そして issue を作成して、待ちます。

🖥 [2:45] 画面: アプリ画面上でスクリーンショット撮影用の十字カーソルを操作中(座標「987 203」の表示)。

🖥 [2:48] 画面: GitHub リポジトリ StephenGrider/uigen-project(Private)のトップ。最新コミット「issues workflow b8a0bf9 · now」、.github/workflows が「issues workflow — now」、19 Commits。

🖥 [3:00] 画面: 作成された issue「Toggle Buttons #2」(Open)。本文: ``` Sometimes it feels like the toggle buttons aren't working.

Here are the ones I'm talking about:

[スクリーンショット添付]

@claude can you take a look at this? Just test them out and verify that clicking them toggles between the code and preview tabs. ```

[2:58] さて、action が実際に起動して Claude が応答するまでには1〜2分かかります。思い出してください。さきほど action の中で見たとおり、Claude Code が動き出す前に、アプリ全体をセットアップして起動まで済ませる構成になっているのです。しかし、やがて Claude は応答します。

🖥 [3:03] 画面: issue に claude(bot)の最初のコメントが付いた: ``` Claude Code is working… ✳

I'll analyze this and get back to you.

View job run View branch ```

[3:13] Claude は多くの場合、与えられたタスクを達成するためのステップのチェックリストを作ります。今回のケースでは、アプリにアクセスし、ボタンを手動でテストし、見つかった問題があれば修正しようとします。

🖥 [3:13] 画面: claude(bot)のコメントが更新され、チェックリストが表示された: ``` Testing Toggle Buttons ✳

I'll test the toggle buttons and verify they work correctly for switching between code and preview tabs.

Todo List: ☐ Navigate to the application at localhost:3000 ☐ Test toggle button functionality ☐ Identify any issues with the toggle behavior ☐ Examine code if problems are found ☐ Fix any issues discovered ☐ Commit changes if needed

View job run ```

[3:23] Claude は、ボタンが実際にはまったく正常に動いていることに気づきます。そこで、発見した所見を文書化したメッセージを残して、早期に終了します。

🖥 [3:27] 画面: 最終レポート(同コメントの完成形・抜粋): ``` ・Performed extensive testing with both empty state and generated content ・Tab selection changes properly every time: Preview [selected] ↔ Code [selected] ・Content area switches correctly between preview iframe and code editor view ・Tested rapid sequential clicking - no stuck states or failures observed ・Works consistently across multiple scenarios

⚠ Minor Unrelated Issue Found ・Monaco code editor shows "Loading..." persistently in Code tab ・This doesn't affect toggle functionality but may impact code editing experience ・File tree loads correctly and files can be selected

Conclusion The toggle buttons are working perfectly. I was unable to reproduce the intermittent issues you reported. The core functionality of switching between Code and Preview tabs is reliable and responsive.

The buttons correctly toggle the view state and content display as expected. No fixes are needed for the toggle functionality itself.

View job run ```

[3:30] さて、これは Claude Code の GitHub 統合の使い方のほんの小さな一例にすぎません。あなた自身のプロジェクトに合わせてこれをどうカスタムテイラーできるか、少し時間を取って考えてみることをおすすめします。

英語逐語(ASR全文)

CloudCode has an official GitHub integration that allows CloudCode to run inside of a GitHub action. You can set up this integration by running slash install GitHub app. This will walk you through a couple of steps. First, you'll need to install the CloudCode app on GitHub. Next, you'll need to add in an API key. And then after this, a pull request will be automatically generated. This pull request adds in two different GitHub actions. The first action adds in mentioning support. So from an issue or a pull request, you can mention Claude with at Claude and give Claude some kind of task to run. The second action adds in support for reviewing pull requests. So whenever you create a pull request, Claude code will automatically run and review the proposed changes. Both of these actions can be customized and you can also add in additional actions to trigger based on other types of events.

Let me show you how you can customize the mentioning feature. First, we just merged in those two action config files to our repository on GitHub. So I need to pull those changes down to my local machine. Then inside of the newly created GitHub workflows directory, I'll see these two action config files. One adds in support for the pull request review and the other adds in support for handling mentions. Now here's how I want to customize the mention functionality. Whenever I mention Claude inside of an issue or a pull request, I wanted to be able to run the project and use the Playwright MCP server to access the app inside of a web browser, all inside of a GitHub action. To make this work, I'll first add in a step before Claude code runs in this workflow. I'll run the setup command, and then start the development server up. Then I'm going to update the Claude code configuration. I'll add in some custom instructions. These are passed directly to Claude, and they allow us to provide some additional directions or context. In this case, I'll tell Claude that the development server is already running and that I can use the Playwright MCP server to access the app in the browser if needed. Then I will add in some configuration to set up the Playwright MCP server itself. There is one other thing to be aware of here. When you're running Cloud Code inside of an action, we have to specifically list out all the permissions that we want to grant Cloud Code. And there's one tricky aspect to this. If you're using an MCP server, you have to individually list out each tool from each MCP server that you want to allow. There is no shortcut for permissions like we saw previously. Unfortunately, the Playwright MCP server has many different tools, so they each need to be listed out. Once I've finished with this configuration update, I'll be sure to commit these changes and push them.

Now it's time to test out this updated workflow. I'm going to give Claude a little task. In our actual app, see these two buttons up here? Right now they work fine. I can toggle between the preview and the code panels without issue, but I'm going to pretend as though they weren't working as intended. I'm going to take a screenshot with that button right there. I'm then going to make an issue. I'm going to paste in the screenshots and I'm going to mention Claude with at Claude and ask it to verify that the two buttons are working as intended. I'll then create the issue and wait.

Now it is going to take a minute or two for the action to actually start up and for Claude to respond. Remember, as we just saw in the action, we are now setting up the entire app and starting it running before Claude code even starts to run at all. But eventually, Claude will respond. It will very often create a checklist of steps to accomplish the given task. In this case, it is going to attempt to visit the app, manually test out the button, and fix any issues that it finds. Claude will notice that the buttons actually are working just fine, and so it's going to terminate early with a message documenting its findings. Now this is just a small example of how you can use CloudCode's GitHub integration. I recommend you spend some time to think about how you can custom tailor it for your own particular project.

↑ 目次へ戻る

Claude Code in Action | Lesson 10「Introducing Hooks」(全文ナレッジ)

動画 3分37秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

フックとは

  • フック(hooks)は、Claude がツールを実行しようとする前後にコマンドを走らせる仕組み。
  • 実装できる機能の例:
  • Claude がファイルを書いた後に、そのファイルへ自動でコードフォーマッタを実行
  • ファイル編集後にテストを実行
  • Claude が特定ファイルを読むのをブロック
  • 可能性は事実上無限。

フックの動作原理(ツール実行フローのどこに挟まるか)

  • おさらい: Claude Code に何かを依頼すると、クエリはツール定義とともに Claude モデルへ送られる。モデルは、注意深くフォーマットされた応答を返すことで「ツールを実行する」と決めることがある。その時点で、要求されたツール(例: ファイル読み取り)を実行し、その結果を返すのは Claude Code の役割。
  • フックは、このツール実行の直前・直後にコードを実行する能力を与える。
  • ツールの前に走るフック = PreToolUse(pre-tool use)フック
  • ツールの後に走るフック = PostToolUse(post-tool use)フック

設定方法

  • フックは settings ファイルに設定を追加して定義する。
  • settings ファイルは複数種類あることを思い出す: 1. マシン上の全プロジェクトで使うグローバル用 2. プロジェクト用(他のエンジニアと共有される) 3. 特定プロジェクトでの自分専用
  • 追加方法は、このファイルに手書きするか、Claude Code 内の組み込み /hooks コマンドを使うかの2通り。

設定ファイルの構造(例の読み解き)

  • ファイル内には2つの独立したセクションがある:
  • ツール使用のに実行するコマンド一覧(PreToolUse フック)
  • ツール使用のに実行するコマンド一覧(PostToolUse フック)
  • 各セクションには matcher を書く。これは「どのツール使用の種類を対象にするか」を示す。
  • 例(Pre 側): Read ツールが対象。Claude Code がファイルを読もうとするたびに、そこに書かれたコマンドを実行
  • 例(Post 側): WriteEditMultiEdit ツールの使用後に、別のコマンドを実行

フックが本当に意図していること(ここが重要)

  • フックで実行されるコマンドには、Claude が実行しようとしているツールコールの詳細情報が渡される。
  • PreToolUse フック: Claude がやろうとしていることを検査でき、何らかの理由で許可したくなければ、ツール使用をブロックして Claude にエラーメッセージを返せる
  • PostToolUse フック: ツールコールは既に発生済みなのでブロックには手遅れ。だが、ツールコールに基づく後続処理ができる:
  • 例: 編集されたばかりのファイルをフォーマットする
  • さらに、そのツール使用について Claude にメッセージを返すこともできる。例えば、編集のコード品質をチェックする別プログラムや型チェックを走らせ、そのフィードバックを Claude に返す → Claude はそのフィードバックを受けて、書いたばかりのファイルを更新するかもしれない。

むすび

  • フックの概念がまだ腑に落ちなくても全く問題ない。フックを理解するのは本当に難しい。この後、フックを使うサンプルプロジェクトに取り組む。

実務ポイント(このレッスンから持ち帰るもの)

  • フック=ツール実行の直前(PreToolUse)/直後(PostToolUse)に任意コマンドを差し込む仕組み。
  • PreToolUse はツールコールの中身を検査してブロック+エラー返却ができる(ガードレール用途)。
  • PostToolUse はブロック不可だが、後続処理(フォーマット等)+Claude へのフィードバック返却ができ、Claude がそれを受けて自己修正するループを作れる。
  • 設定場所は3種の settings ファイル(グローバル/プロジェクト共有/プロジェクト個人)。手書きでも /hooks コマンドでも定義できる。
  • matcher で対象ツール(ReadWriteEditMultiEdit など)を指定する構造を覚えておく。

本文(時系列・日本語逐語+画面差し込み)

[0:00] このビデオではフック(hooks)を見ていきます。フックを使うと、Claude がツールを実行しようとする前または後にコマンドを実行できます。フックは、実に興味深く、非常に有用な機能を実装するのに使えます。例えば、Claude がファイルを書くと決めた後に、作成されたファイルへ自動的にコードフォーマッタを実行できます。あるいは、ファイルが編集された後にテストを実行したり、Claude が特定のファイルを読むのをブロックしたりできます。可能性は本当に無限です。あなたのプロジェクトでフックをどう使えそうか、アイデアを掴んでもらうための良い例をいくつか用意してあります。

🖥 [0:00] 画面: スライド「Hooks」— サブタイトル「Run a command before or after Claud Code does something. Optionally, block Claude's action.」(スライド原文ママ。"Claud Code" は誤記)。下に用途例の6ボックス: - Run a code formatter after Claude edits a file(Claude のファイル編集後にコードフォーマッタを実行) - Stop Claude from editing or reading a particular file(特定ファイルの編集・読み取りを止める) - Check for TODO comments in code that Claude writes and add them to a log file(Claude が書くコード内の TODO コメントを検出しログファイルへ追加) - Run tests automatically after a file is changed(ファイル変更後に自動でテストを実行) - Block file edits that add variables that don't follow naming conventions(命名規約に従わない変数を追加するファイル編集をブロック) - Block deprecated function usage(非推奨関数の使用をブロック)

[0:32] ですがまず、フックが正確にどう動くのかを理解する手助けをさせてください。おさらいですが、Claude Code に何かを尋ねると、あなたのクエリはいくつかのツール定義とともに Claude モデルへ送られます。Claude モデルは、注意深くフォーマットされた応答を返すことで、ツールを実行すると決めることがあります。そしてその時点で、要求されたツールを実行するのは Claude Code の役目です。この例で言えば、ファイルを読み、そのツールコールの結果を返す、といった具合です。

🖥 [0:38] 画面: シーケンス図(登場者3列: You / Claude Code / Claude)。 - You → Claude Code: 「What code is written in the main.go file?」 - Claude Code → Claude: 「What code is written in the main.go file? If you want to read a file, respond with "ReadFile: name of file"」— この追記部分に注釈「Added (indirectly) by the coding assistant(コーディングアシスタントによって(間接的に)追加される)」 - Claude → Claude Code: 「ReadFile: main.go

[0:59] さて、フックは、ツール実行の直前または直後にコードを実行する能力を与えてくれます。ツールの前に実行されるフックは、ツールの前に走ることから pre-tool use(PreToolUse)フックと呼ばれ、ツールの後に実行されるフックは、同じ理由で post-tool use(PostToolUse)フックと呼ばれます。

🖥 [1:02] 画面: 同じシーケンス図の Claude Code のライフライン上に、上から順に3ボックスが挿入される: - 「PreToolUse hook runs」(赤茶色) - 「Claude Code reads the file」(ベージュ) - 「PostToolUse hook runs」(赤茶色)

最後に Claude Code → Claude へ「\<Contents of main.go file>」の矢印。

[1:19] フックを定義するには、Claude の settings ファイルに設定を追加します。settings ファイルには数種類あることを思い出してください。1つはマシン上の全プロジェクトで使うグローバル用、1つは他のエンジニアと共有される、あなたの特定のプロジェクト用、そして1つは特定のプロジェクトにおけるあなた専用のものです。フックは、このファイルの中に手で書き出すか、Claude Code 自体に組み込まれている /hooks コマンドを使うかのどちらかで追加できます。設定そのものは、画面の右側に見えているようなものです。

🖥 [1:19] 画面: スライド「Hook Definitions」。左に定義場所の表と補足:

Defined in...
Global ~/.claude/settings.json
Project .claude/settings.json
Project (not committed) .claude/settings.local.json

「Write by hand or by using the /hooks command」

右に設定例の JSON:

json { "hooks": { "PreToolUse": [ { "matcher": "Read", "hooks": [ { "type": "command", "command": "node /home/hooks/read_hook.ts" } ] } ], "PostToolUse": [ { "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "node /home/hooks/edit_hook.ts" } ] } ] } }

[1:45] このサンプルファイルを一通り見ていって、何が起きているのかをもう少し分かりやすくしましょう。まず、このファイルの中に2つの異なるセクションがあることに注目してください。一方のセクションは、ツール使用のに実行されるべきコマンドをすべて列挙しています。思い出してください、それらは pre-tool use フックと呼ばれます。もう一方のセクションは、ツール使用のに実行されるべき様々なコマンドをすべて列挙しています。そして繰り返しますが、それらは post-tool use フックです。

🖥 [1:50] 画面: 同じ JSON の "PreToolUse" キーと "PostToolUse" キーが赤枠でハイライトされ、左から注釈: - 「Hooks that run before a tool is called」→ "PreToolUse" - 「Hooks that after before a tool is called」→ "PostToolUse"(スライド原文ママ。"that run after" の誤記)

[2:10] これらの各セクションでは、matcher を指定します。これは、どのツール使用タイプを探しているのかを示すものです。この場合、私は Read ツールの使用を見つけたい。Claude Code がファイルを読もうとするたびに、そこに列挙されているコマンドを実行したいのです。同様に、post-tool use セクションの中では、Write・Edit・MultiEdit ツールの使用後に実行したい別のコマンドがあります。

🖥 [2:10] 画面: PreToolUse 側の "matcher": "Read","command": "node /home/hooks/read_hook.ts" が赤枠でハイライトされ、左から注釈: - 「Before the 'Read' tool is executed...('Read' ツールが実行される前に…)」→ matcher 行 - 「...run this command(…このコマンドを実行する)」→ command 行

🖥 [2:35] 画面: 同じ JSON のハイライトが PostToolUse 側に切り替わる。"matcher": "Write|Edit|MultiEdit" の行と "command": "node /home/hooks/edit_hook.ts" の行が赤枠でハイライトされ、左から注釈: - 「After the 'Write', 'Edit', or 'MultiEdit' tools are executed...('Write'・'Edit'・'MultiEdit' ツールが実行された後に…)」→ matcher 行 - 「...run this command(…このコマンドを実行する)」→ command 行

[2:35] さて、ここが重要な部分です。フックが本当に意図していることはこうです。先ほど見たコマンドには、Claude が実行しようとしているツールコールについての詳細情報が渡されます。pre-tool use フックの場合、Claude がやろうとしていることを検査でき、何らかの理由でそれを許可したくなければ、ツール使用の操作をブロックして、Claude にエラーメッセージを送り返すことができます。post-tool use フックの場合、ツールコールはすでに発生してしまっているので、ブロックするには手遅れです。しかし、そのツールコールに基づいた何らかのフォローアップ操作を行うことはできます。例えば、たった今編集されたファイルをフォーマットするといったことです。また、そのツール使用について Claude に何らかのメッセージを返すこともできます。例えば、その編集のコード品質をチェックする別のプログラムを走らせたり、型チェックを行ったりして、そのフィードバックを Claude に返すと決めてもよいでしょう。Claude はそのフィードバックを受け取って、たった今書き込んだファイルに更新を加えるかもしれません。

🖥 [2:35] 画面: PreToolUse/PostToolUse の縦フロー図に、それぞれの能力の注釈ボックス: - 「PreToolUse hook runs」← - 「Runs a command you provide(あなたが提供したコマンドを実行する)」 - 「Your command can block the tool call, sending an error message back to Claude(あなたのコマンドはツールコールをブロックでき、Claude にエラーメッセージを送り返せる)」 - 「Claude Code reads the file」 - 「PostToolUse hook runs」← - 「Runs a command you provide」 - 「Too late to block the call! But you can provide additional feedback to Claude(ブロックするには手遅れ! だが Claude に追加のフィードバックを提供できる)」

[3:25] もしまだフックについて、あるいはフックが何を意図しているのかについて混乱していても、まったく問題ありません。フックを理解するのは本当に難しいことがあります。では、少ししたら戻ってきて、フックを使うサンプルプロジェクトに取り組みましょう。

[3:36] ありがとうございました。(※ 動画はここで終了(全長 3:37)。ASR の srt は末尾に "Thank you." のセグメントを 4:06 まで引き延ばして出力しているが、動画長を超えた whisper の末尾無音アーチファクト)

英語逐語(ASR全文)

in this video we're going to take a look at hooks these allow you to run commands before or after claude attempts to run a tool hooks can use to implement really interesting and very useful functionality for example after claude decides to write a file you can automatically run a code formatter on the created file or you can run tests after a file is edited or you can block claude from reading particular files the possibilities are really endless and i've got a a couple of good examples lined up to show you to give you some ideas of how you might use hooks on your particular project.

First, however, let me help you understand exactly how hooks work. As a reminder, when you ask Claude Code something, your query is sent off to the Claude model along with some tool definitions. The Claude model might then decide to run a tool by providing a carefully formatted response. And at that point, it is up to Claude Code to run the requested tool, maybe in this case to read a file and then respond with the result of that tool call. Now hooks give us the ability to execute code just before or just after the tool execution. Hooks that run before a tool are referred to as pre-tool use hooks because they run before the tool and hooks that run after the tool are referred to as post-tool use for the same reason. To define hooks we add configuration to the clod settings file. Remember that there are several different settings files, one for global use across all projects on your machine, one for your particular project that gets shared with other engineers, and one for just you on a particular project. You can add hooks either by writing them out by hand inside this file or by using the built-in slash hooks command inside of clod code itself. The configuration itself looks like what you see on the right-hand side of the screen.

Let me walk you through this example file just to give you a better idea of what's going on. So first, notice that there are two distinct sections inside this file. One section lists out all the commands that should be executed before a tool use. Remember, those are referred to as pre-tool use hooks. The other section lists out all the different commands that should be executed after a tool use. And again, those are post-tool use hooks. In each of these sections, we provide a matcher. This indicates which tool use types we are looking for. So in this case, I want to find uses of the read tool. Whenever Cloud Code attempts to read a file, I want to run the command you see listed there. Likewise, inside the post-tool use section, after use of the write, edit, or multi-edit tools, there's a different command that I want to run.

Now here's the important part. Here's what hooks are really intended to do. Those commands you saw will be given details about the tool call that Claude wants to run. In the case of a pre-tool use hook, you can inspect what Claude wants to do, and if for any reason you don't want to allow it, you can block the tool use operation and send an error message back to Claude. In the case of a post-tool use hook, the tool call has already occurred, so it's too late to block it. But you can do some follow-up operation based upon the tool call, like maybe format a file that was just edited. You can also provide some message back to Claude about that tool use. For example, you might decide to run a separate program to check the code quality of the edit, or maybe do a type check, and then provide that feedback back to Claude. Claude might then take that feedback and make an update to the file that it just wrote to.

If you're still confused about hooks or what they are intended to do, that is absolutely okay. Wrapping your head around hooks can be really challenging. So let's come back in a moment and work on a sample project with hooks. Thank you.

↑ 目次へ戻る

Claude Code in Action | Lesson 11「Defining Hooks」(全文ナレッジ)

動画 3分44秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

サンプルプロジェクト「queries」

  • このレッスンから新しいサンプルプロジェクト queries.zip(レクチャー添付)を使う。ダウンロードしてエディタで開き、npm run setup を実行すると、依存パッケージのインストールと、いくつかのフックの準備が行われる。
  • Hooks を深く理解するため、このプロジェクト内で自作フックを作る

作るフックのゴール

  • プロジェクトのルートにある .env ファイルには機微情報が入っている。念のため、Claude がこのファイルを直接読むことを完全に防止したい。

フック設計の4ステップ

Step 1: PreToolUse か PostToolUse かを決める - 今回は「特定ファイルの読み取りを防ぐ」のが目的。PostToolUse にすると、フック(コマンド)が実行されるのは Claude がすでにファイルを読んだ後になってしまう。 - したがって読み取り操作の発生自体を防げる PreToolUse フックが必須。

Step 2: 監視対象のツール呼び出しを決める - Claude Code に含まれる全ツール名を暗記するのは大変(MCP サーバー経由でカスタムツールも追加できるためなおさら)。 - 小技: Claude Code を開いて「今アクセスできる全ツール名を箇条書きで出して」と直接 Claude に聞けばよい。 - ファイル内容を簡単に読めるツールは2つ: - Read ツール - 見落としがちだが Grep ツール(ファイルの中身を検索できる=内容を読める) - よって Read と Grep の両方のツール呼び出しを監視する。

Step 3: ツール呼び出し情報を受け取るコマンドを書く - 流れ: 自分でコマンドを書く → Claude が自動実行する → そのプロセスの標準入力(stdin)に、Claude がツール呼び出しデータを JSON で流し込む。 - JSON はツール名やツールへの入力などの情報を持つ大きなオブジェクト。例:ツール名が Read で、.env を指す file_path を読もうとしている、など。 - コマンド側では stdin からこの情報を受け取り、JSON をパースして、ツール名・ツール入力引数などを読み、このツール呼び出しをどう扱うかを決める。

Step 4: 終了コード(exit code)で Claude Code にシグナルを返す - 提案されたツール呼び出しデータを受け取った後、コマンドは exit し、その終了コードが Claude Code へのシグナルになる。 - exit code 0 = 問題なし。このツール呼び出しを許可する。 - exit code 2 = このツール呼び出しをブロックする。ただしブロックできるのは PreToolUse フックのみ(ツール呼び出しを止められるのは PreToolUse だけ)。 - exit code 2 で終了した場合、コマンド実行中に標準エラー(stderr)に出力したログが Claude へのフィードバックとして送られる。つまり「拒否」と「理由の提示」を同時にできる。

実務ポイント(このレッスンから持ち帰るもの)

  • ブロック系フックは必ず PreToolUse。PostToolUse では実行後なので手遅れ。
  • ファイル読み取りの防止は Read だけでなく Grep も塞ぐ(Grep でも中身が読める)。
  • ツール名の一覧が欲しければ、Claude 自身に「使えるツール名を箇条書きして」と聞くのが早い(MCP 追加ツールも含めて出る)。
  • フックコマンドは stdin で JSON(tool_name / tool_input 等)を受け取る設計にする。
  • シグナル規約: exit 0 = 許可、exit 2 = ブロック(PreToolUse のみ)、exit 2 時の stderr が Claude へのフィードバックになる。

本文(時系列・日本語逐語+画面差し込み)

[0:00] フックの仕組みをもっとよく理解するために、新しいサンプルプロジェクトを見ていきます。このレクチャーには queries.zip というファイルが添付されています。ぜひこのプロジェクトをダウンロードして、その中でコードエディタを開いてください。エディタを開いてターミナルに立ったら、npm run setup を実行してください。これは、いくつかの依存パッケージをインストールし、いくつかのフックを使える状態に準備します。

🖥 [0:14] 画面: VS Code のターミナル(プロジェクト名 queries、タブ: PROBLEMS / OUTPUT / DEBUG CONSOLE / TERMINAL / PORTS)。プロンプトに入力中:

➜ queries git:(dev) ✗ npm ru▌

(このあと npm run setup を実行)

📄 実物コード(queries_COMPLETED/.claude/settings.example.json): npm run setup が準備する「いくつかのフック」の元テンプレート。setup は scripts/init-claude.js を実行し、このファイル内の $PWD を実際のプロジェクト絶対パスに置換して .claude/settings.local.json として書き出す。1つ目の PreToolUse エントリ("matcher": """command": "true")が、次レッスンで Read|Grep ブロック用に埋めるプレースホルダー。

json { "hooks": { "PreToolUse": [ { "matcher": "", "hooks": [ { "type": "command", "command": "true" } ] }, { "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "node $PWD/hooks/query_hook.js", "timeout": 300 } ] }, { "matcher": "*", "hooks": [ { "type": "command", "command": "jq . > pre-log.json" } ] } ], "PostToolUse": [ { "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "jq -r '.tool_response.filePath // .tool_input.file_path // empty' | xargs -I {} npx --yes prettier --write {} 2>/dev/null || true" }, { "type": "command", "command": "node $PWD/hooks/tsc.js" } ] }, { "matcher": "*", "hooks": [ { "type": "command", "command": "jq . > post-log.json" } ] } ] } }

[0:21] フックをよりよく理解するため、このプロジェクトの中で自分たち自身のフックを作ります。私たちのフックにやってほしいことはこうです。プロジェクトのルートディレクトリの中に .env というファイルがあります。このファイルには機微な情報が含まれており、用心に用心を重ねて、Claude がこのファイルを直接読むことを完全に防ぎたいのです。このフックをどう組み立てていくのかを理解してもらうために、いくつか図をお見せしましょう。

[0:44] ステップ1は、pre-tool use フックと post-tool use フックのどちらが必要かを決めることです。このシナリオでは、Claude が特定のファイルを読むことを絶対に防ぎたい。もし post-tool use のブロックを作ってしまうと、Claude がすでにファイルを読んだに、フックを実行した(コマンドを走らせた)ことになってしまいます。というわけでこの場合は、読み取り操作の発生を確実に防げるよう、間違いなく pre-tool use フックが必要です。

🖥 [0:44] 画面: スライド「Building a Hook」— 4ステップのリスト(Step 1 が太字強調): 1. Decide on a PreToolUse or PostToolUse hook(PreToolUse か PostToolUse かを決める) 2. Determine which type of tool calls you want to watch for(どの種類のツールコールを監視するか決める) 3. Write a command that will receive the tool call(ツールコールを受け取るコマンドを書く) 4. If needed, command should provide feedback to Claude(必要なら、コマンドは Claude にフィードバックを返す)

右側にシーケンス図(Claude Code / Claude): Claude → Claude Code「Read: .env」、Claude Code のライフライン上に「PreToolUse hook runs」→「Claude Code reads the file」→「PostToolUse hook runs」。

[1:07] 次にやるべきことは、どの種類のツールコールを監視したいのかを正確に決めることです。この図の右側に、現在の様々なツール名の一覧を載せています。さて、Claude Code に含まれる様々なツール名をすべて暗記するのは本当に大変です。MCP サーバーを使って独自のカスタムツールを追加できることを考えるとなおさらです。そこで、ここで使える小技をお見せしましょう。戻って Claude Code を開けば、Claude に直接、「今アクセスできる全ツール名の箇条書きリスト」を求めることができます。これらの様々なツールのうち、ファイルの内容をとても簡単に読むのに使えるものが2つあります。まず Read ツールがあります。そして、見落としやすいのですが、こちらも実はファイルの内容を読むことができます——Grep ツールです。Grep はファイルの内容を検索できます。ですから、私たちは Read ツールと Grep ツールのツールコールを監視したいのです。

🖥 [1:07] 画面: 同スライド(Step 2 が太字強調)。右側に表「Tool Names」:

Tool Name Purpose
Read Read a file
Edit, MultiEdit Edit an existing file
Write Create a file and write to it
Bash Execute a command
Glob Find files/folders based upon a pattern
Grep Search for content
Task Create a sub-agent to complete a particular task
WebFetch, WebSearch Search or fetch a particular page

🖥 [1:31] 画面: VS Code。左エディタに .env ファイル(1行目 # Normally this file wou…、2行目 SECRET_API_KEY="SUPER SE…=いずれも画面右端で見切れ)。右のターミナルで Claude Code が回答中:

``` ● Here are the tools I have access to:

• Task • Bash • Glob • Grep • LS • exit_plan_mode • Read ← カーソルで選択(ハイライト)中 • Edit • MultiEdit • Write • NotebookRead • NotebookEdit • WebFetch • TodoWrite • WebSearch • mcp__ide__getDiagnostics • mcp__ide__executeCode

▌ ? for shortcuts ```

[1:57] 次に、Claude が行おうとしているツールコールについての情報を受け取ることになるコマンドを書き出す必要があります。この部分はこう動きます。私たちはコマンドを書き出します。Claude はそれを自動的に実行します。そしてそのプロセスの標準入力(standard in)に、Claude はツールコールデータを JSON として流し込みます。右上にツールコールデータの例を載せています。ツール名と、そのツールへの入力についての情報を持つ、大きな JSON オブジェクトになります。この場合、ツール名は read です。つまり Claude は read ツールを呼ぼうとしていて、具体的には、あの .env ファイルを指すファイルパスを読もうとしているのかもしれません。繰り返しますが、それが読み取り操作を防ぎたいファイルです。そこで、私たちのプログラム(コマンド)の中では、この情報を標準入力経由で受け取り、その JSON をパースし、ツール名やツールの入力引数などを読んで、このツールコールをどう扱いたいかを決める必要があります。

🖥 [1:57] 画面: 同スライド(Step 3 が太字強調)。右側に「Tool Call Data」の JSON と、それが「Standard In」経由で「Your command」へ流れる図:

json { "session_id": "2d6a1e4d-6…", "transcript_path": "/Users/sg/…", "hook_event_name": "PreToolUse", "tool_name": "Read", "tool_input": { "file_path": "/code/queries/.env" } }

Tool Call Data →(矢印)→ Standard In → Your command

[2:46] そしてステップ4へ。ステップ4では、コマンドが提案されたツールコールデータを受け取った後、exit します。そしてその終了コードが、Claude Code へ返すシグナルになります。終了コード 0 は「すべて問題なし。このツールコールの発生を許可したい」という意味です。一方、終了コード 2 は、Claude Code に対する「このツールコールをブロックしたい」というサインです。そしてこれは pre-tool use フックにだけ当てはまります。なぜなら、思い出してください、実際にツールコールをブロックできるのは pre-tool use フックの中だけだからです。終了コード 2 で exit した場合、その間にコマンドの中で生成した標準エラー(standard error)のログも、フィードバックとして Claude に送られます。つまり、ツールコールを拒否すると同時に、Claude に理由を伝えることもできるのです。

🖥 [2:49] 画面: 同スライド(Step 4 が太字強調)。右側に分岐図:

Your command」→ 「Exit Code 0」= All is well!(すべて良し!) 「Your command」→ 「Exit Code 2」= Tool blocked! (PreToolUse only)(ツールブロック! PreToolUse のみ)→「Stderr logs sent to Claude as feedback(stderr のログがフィードバックとして Claude に送られる)」

[3:29] 以上がプロセス全体です。もう一度言いますが、ここでは多くのことが起きています。ですから、このフックに必要なもの一式をプロジェクトの中で配線していくこのプロセス全体を通しでやって、これらのステップがどう組み合わさるのかを理解しましょう。

英語逐語(ASR全文)

To get a better idea of how hooks work, we're going to take a look at a new sample project. Attached to this lecture is a file called queries.zip. I'd encourage you to download this project and open your code editor inside of it. Once you've got your editor open at your terminal, run npm run setup. This is going to install a couple of dependencies and get a couple of hooks ready for use. To better understand hooks, we're going to make our own inside of this project. So here's what I want our hook to do. Inside the root directory of our project is a file called .env. This file contains some sensitive information and out of an abundance of caution, I want to completely prevent Claude from ever reading this file directly. Let me show you a couple of diagrams to help you understand how we're going to put this hook together.

Step one is to decide on whether we need a pre-tool use or a post-tool use hook. In this scenario, we want to prevent Claude from ever reading a particular file. If we make a post tool use block, then we will have executed our hook or ran our command after Claude already read the file. So in this case, we definitely need a pre-tool use hook to make sure that we can prevent the read operation from occurring.

The next thing we need to do is decide exactly which kind of tool calls we want to watch for. I've got a list of all the different current tool names on the right-hand side of this diagram. Now, memorizing all the different tool names that are included inside of Claude code can me really challenging, especially since you can add your own custom tools through the use of MCP servers. So let me show you a little trick you can use here. If I go back over and open up Claude code, I can directly ask Claude for a bullet point list of all the different tool names that it has access to right now. Out of all these different tools, there are two that can be used to very easily read the contents of a file. First, there's the read tool, and then it's easy to miss, but this one can actually read the contents of a file as well, the grep tool. Grep can search the contents of a file. So we really want to watch for tool calls for the read tool and the grep tool.

Next up, we need to write out a command that is going to receive some information about the tool call that Claude wants to make. Here's how that part works. We're going to write out a command. Claude is going to automatically execute it. And then on standard in to that process, Claude is going to feed in some tool call data as JSON. I've got an example of some tool call data on the top right hand side. So it's going to be a big JSON object that has some information about the tool name and the input to that tool. In this case, the tool name is read. So Claude is trying to call the read tool and it might be trying to read specifically a file path pointing to that .env file. And again, that's the file that we want to prevent a read operation for. So then inside of our program or our command, we need to receive this information through standard in, parse that JSON, and then read the tool name, the tool input arguments, and so on, and decide what we want to do with this tool call.

Then on to step four. In step four, after our command receives that proposed tool call data, we're then going to exit, and our exit code is going to provide a signal back to Claude code. An exit code of zero means everything is okay, and we want to allow this tool call to occur. An exit code of two, however, is a sign to Claude code that we want to block this tool call, and that specifically only applies for the pre-tool use hooks because remember only in a pre-tool use hook can we actually block a tool call. If we exit with a code of two, then any standard error logs that we generated inside of our command during that time will also be sent as feedback to Claude. So we can both deny the tool call and give Claude a reason at the same time as well. So that's the entire process. And I know once again, there's a lot of stuff going on here. So let's go through this entire process of wiring everything up needed for this hook inside of our project to understand how all these steps come together.

↑ 目次へ戻る

Claude Code in Action | Lesson 12「Implementing a Hook」(全文ナレッジ)

動画 4分14秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

ゴールの再確認

  • 前レッスンで設計した「Claude に .env の中身を絶対読ませない」フックを、今回は実装する(設定オプションの議論は前回済み、今回は実装が中心)。

設定ファイル側(.claude/settings.local.json

  • .claude ディレクトリの settings.local.json を開く。この中に PreToolUse フックと PostToolUse フックのリストがある。
  • ブロックしたいので PreToolUse 側に設定する。講師が設定セクションの雛形を用意済みで、埋めるのは matchercommand の2つ。
  • matcher = 監視したいツール。今回は Read と Grep の2つをパイプ記号 | で区切って指定する(L や大文字 I ではなく、キーボードの Return キーの上にある記号)。
  • command = それらのツールを Claude が呼ぼうとした時に実行するコマンド。何でもよい(CLI でも、シェルスクリプト呼び出しでも)。このプロジェクトの流儀に合わせ、hooks ディレクトリに事前配置した Node.js スクリプトを呼ぶ:プレースホルダーの truenode ./hooks/read_hook.js に置き換えて保存。
"PreToolUse": [
  {
    "matcher": "Read|Grep",
    "hooks": [
      { "type": "command", "command": "node ./hooks/read_hook.js" }
    ]
  }
]

フック本体(hooks/read_hook.js

  • ファイル冒頭には、標準入力から読み取り JSON としてパースするコードが用意済み。パース結果の toolArgs オブジェクトが、前レッスンの図で見た大きな JSON(session_idtool_nametool_input などのプロパティを持つ)。
  • やることは、ツール入力の file path を見て .env を読もうとしているか判定するだけ。読み取りパスの取得には tool_input.path を見るフォールバックも入れてある(理由は後のレッスンで説明)。
  • 判定ロジック(TODO 部分の実装):
// readPath が ".env" を含む= Claude が .env を読もうとしている
if (readPath.includes(".env")) {
  console.error("You cannot read the .env file"); // stderr へ=Claude へのフィードバック
  process.exit(2);                                 // exit code 2 =ブロック
}
  • console.error を使うのがポイント(標準エラーに出すことで Claude にフィードバックが渡る)。その後 process.exit(2) でブロック。

テストと重要な注意

  • フックの変更を反映させるには Claude Code の再起動が必須。すでに開いている場合は必ず再起動する。
  • Claude に「.env を読んで」と頼むと、読もうとした瞬間にエラー「you cannot read the .env file」が返り、Claude は読めないことを認識する。しかも「read hook に阻止された」ことまで認識できる。
  • Grep 経由でも同様にブロックされることを確認(matcher に Grep も入れたため)。
  • このフック自体は実用性が高いわけではなく、次のレッスンでもっと有用なフックを紹介する。

実務ポイント(このレッスンから持ち帰るもの)

  • matcher で複数ツールを監視するときは Read|Grep のようにパイプ区切り
  • フックの command は任意のコマンドでよい(Node スクリプト、シェルスクリプト、CLI 何でも)。
  • フック実装の型:stdin → JSON パース → tool_input のパス判定 → console.errorprocess.exit(2)
  • パス取得は file_path だけでなく tool_input.path のフォールバックも見る。
  • フック設定を変えたら Claude Code を再起動しないと反映されない(ハマりどころ)。

本文(時系列・日本語逐語+画面差し込み)

[0:00] それでは、カスタムフックを組み立てましょう。思い出してください、ここでの目標全体は、Claude が .env ファイルの内容を絶対に読めないようにすることです。前回のビデオでは、設定が必要になる様々な設定オプションについて多く議論しました。ですのでこのビデオでは、主に実装に集中していきます。

🖥 [0:00] 画面: VS Code(タイトル: queries)。エクスプローラーにプロジェクト構成: .claude / hooks / node_modules / scripts / src / .env / .gitignore / CLAUDE.md / package-lock.json / package.json / task.md / tsconfig.json。エディタは未オープン(Show All Commands ⇧⌘P などのショートカット一覧が見える初期画面)。

[0:15] まずは .claude ディレクトリの中で、settings.local.json ファイルを開きます。思い出してください、この中には pre-tool use フックと post-tool use フックのリストがあります。少し前に議論したとおり、Claude があの特定のファイルの内容を絶対に読めないようにするため、pre-tool use フックを作りたいのです。タイピングの手間を少し省くために、ここに小さな設定セクションをあらかじめ追加しておきました。私たちがやるべきことは、matcher と command を埋めることだけです。

🖥 [0:30] 画面: .claude/settings.local.json を開いた状態(パンくず: .claude > settings.local.json > hooks > PreToolUse > 0 > matcher):

json { "hooks": { "PreToolUse": [ { "matcher": "", "hooks": [ { "type": "command", "command": "true" } ] }, { "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "node /Users/sgrider/code/enablements/claude-code-course/pro…", "timeout": 300 } ] }

(command のパスは画面右端で見切れ。npm run setup が settings.example.json の $PWD を実パスに置換して生成したもの。1つ目のエントリ "matcher": "" / "command": "true" が今回埋めるプレースホルダー)

[0:42] まずは matcher です。matcher は、監視したいツールになります。私たちのケースでは、議論したとおり、read ツールと grep ツールの呼び出しを監視したい。この2つのツール名をパイプ記号で区切ります。これは L でも大文字の I でもなく、キーボードの Return キーのすぐ上にある記号です。

🖥 [1:02] 画面: 5行目が "matcher": "Read|Grep", に書き換わり、9行目のプレースホルダー "true" を選択(ハイライト)した状態。

[1:03] 次に、Claude がこの2つのツールを呼ぼうとしたときに必ず実行するコマンドを指定する必要があります。ここには好きなコマンドを何でも入れられます。CLI でも、シェルスクリプトの呼び出しでも、本当に何でも構いません。このファイルの他の部分ですでに確立してあるパターンに従うため、このプロジェクトの hooks ディレクトリにあらかじめ置いておいた Node.js スクリプトを呼ぶことにします。hooks ディレクトリの中に、read_hook.js というファイルを用意しておきました。Claude がこの2つのツールのどちらかを呼ぼうとしたときに実行したいのが、このファイルです。それを呼ぶために、今はただのプレースホルダーである、ここの true を node ./hooks/read_hook.js に置き換えます。それからこのファイルを保存します。このファイルの中でやることは、これで全部です。

🖥 [1:35] 画面: エクスプローラーで hooks ディレクトリが展開され query_hook.js / read_hook.js / tsc.js が見える(ルートには post-log.json / pre-log.json も生成済み)。9行目を "command": "node ./hooks/read_hook.│" まで入力中(タイピング途中)。

[1:52] 次に、Claude が read や grep ツールを呼ぼうとするたびに実行される、そのコマンド自体を実際に実装する必要があります。それが read_hook.js ファイルです。このファイルの先頭には、標準入力から読み取って、そのデータを JSON としてパースするコードを用意してあります。ここにあるこの toolArgs オブジェクトが、あちらの図でお見せした、あの大きな JSON オブジェクトになります。session ID、ツール名、ツール入力(tool input)などのプロパティを持つことになります。私たちが本当にやるべきことは、あそこにあるファイルパスを見て、それが .env ファイルを読もうとしているのかどうかを判定することだけです。もしそうなら、このプログラム(コマンド)から終了コード 2 で確実に exit し、できれば「申し訳ないけれど、そのファイルは読めません」という情報も Claude へログ出力したい。それで、こちらに戻ってもらうと、そのファイルパスを読み取るコードがすでにあることに気づくでしょう。さらに、ここに tool_input.path を見るフォールバックがあることにも気づくはずです。これがなぜ追加されているのかは、すぐ後でお話しします。

🖥 [2:04] 画面: スライドに切り替え——「Building a Hook」(Step 3 太字)+「Tool Call Data」の JSON(session_id / transcript_path / hook_event_name: "PreToolUse" / tool_name: "Read" / tool_input.file_path: "/code/queries/.env")→ Standard In → Your command(前レッスンと同じ図)。[2:34] 頃にエディタへ戻る。

🖥 [2:35] 画面: hooks/read_hook.js を開いた状態(パンくず: hooks > read_hook.js > main > readPath)。10行目の toolArgs.tool_input?.path がハイライト(フォールバックの説明箇所):

```js async function main() { const chunks = []; for await (const chunk of process.stdin) { chunks.push(chunk); } const toolArgs = JSON.parse(Buffer.concat(chunks).toString());

// readPath is the path to the file that Claude is trying to read const readPath = toolArgs.tool_input?.file_path || toolArgs.tool_input?.path || "";

// TODO: ensure Claude isn't trying to read the .env file }

main(); ```

[2:45] では、TODO 文を実装しましょう。if (readPath.includes(".env")) と書きます。これは、Claude が .env ファイルを読もうとしているに違いない、という意味です。もしそうであれば、その操作を確実にブロックし、Claude に何らかのログのフィードバックを提供したい。そこで、まず console.error を追加します。console.error であることが肝心です。標準エラー(standard error)にログを出したいからです。思い出してください、それが Claude にフィードバックを提供する方法です。そして「you cannot read the .env file(.env ファイルは読めません)」のような文言にして、それから process.exit(2) を実行します。

🖥 [3:00] 画面: TODO 直下に実装をタイピング中(13〜15行目):

js if(readPath.includes('.env')) { console.error("You cannot read the│") }

📄 実物コード(queries_COMPLETED/hooks/read_hook.js・完成形全文):

```js async function main() { const chunks = []; for await (const chunk of process.stdin) { chunks.push(chunk); } const toolArgs = JSON.parse(Buffer.concat(chunks).toString());

// readPath is the path to the file that Claude is trying to read const readPath = toolArgs.tool_input?.file_path || toolArgs.tool_input?.path || "";

// TODO: ensure Claude isn't trying to read the .env file if (readPath.includes(".env")) { console.error("You cannot read the .env file"); process.exit(2); } }

main(); ```

[3:21] さあ、これをテストするために、ファイルを保存します。Claude Code を開きます。もしすでに開いている場合は、必ず Claude Code を再起動してください。フックへの変更を反映させるには、再起動しなければならないのです。Claude に .env ファイルを読むよう頼んでみます。おそらく読もうとするはずですが、読もうとしたまさにその時に、こちらから「you cannot read the .env file」というエラーを送り返します。そして Claude は、「申し訳ないが、実際にはこれは読めない」と気づくはずです。実際のところ、read hook によって阻止されたことまで認識できています。

🖥 [3:30] 画面: VS Code 分割ビュー。左に read_hook.js(15行目 process.exit(2); まで実装完了)、右のターミナルで Claude Code を再起動してテスト:

``` cwd: /Users/sgrider/code/enablements/claude-code-course/prod/queries

※ Tip: Run claude --continue or claude --resume to resume a conversation

Read the .env file

● I'll read the .env file for you.

● Read(.env) └ Error: Read operation blocked by hook: - [node ./hooks/read_hook.js]: You cannot read the .env file

✳ Discombobulating… (8s · ↑ 29 tokens · esc to interrupt) ```

[3:52] さて、私たちのフックは grep 操作でも同様に機能するはずです。ですから、Claude に grep ツールを試すよう頼めば、これも同じく禁止されるはずです。どうなるか見てみましょう。……はい、同じ結果です。今度も禁止されました。というわけで、これが私たちが組み立てた、動作するフックです。さて、このフック自体はそれほど有用ではありません。すぐ後で、もっとずっと有用なフックをお見せします。

英語逐語(ASR全文)

Let's put together our custom hook. Remember, the entire goal here is to prevent Claude from ever reading the contents of the .env file. In the last video, we discussed many of the different configuration options we'll need to set. So in this video, we're going to be mostly focused on the implementation.

To get started inside the .claud directory, I'm going to open up the settings.local.json file. Remember, inside of here, we have a list of pre-tool use hooks and post-tool use hooks. As we discussed a moment ago, we want to make a pre-tool use hook so that we can prevent Claude from ever reading the contents of that particular file. I already added in a little configuration section right here for us, just to save us a little bit of typing. All we need to do is fill in the matcher and the command. First is the matcher. So the matcher is going to be the tools that we want to watch for. In our case, as we discussed, we want to watch for calls to the read and the grep tools. I'm going to separate those two tool names with a pipe symbol, so that's not an L or a capital I, it is the symbol right above the return key on your keyboard.

Then, next up, we need to provide a command to run whenever Claude attempts to call those two tools. We could put in here any command you want, so it can be a CLI, it can be a call to a shell script, absolutely anything. To follow the pattern that I've already established inside the rest of this file, I'm going to call a Node.js script that I placed ahead of time inside the hooks directory of this project. So inside the hooks directory, I put together for us a read underscore hook.js file. This is the file that I want to run whenever Claude attempts to call one of those two tools. So to call that, I'm going to replace the true right here, which is just a placeholder for right now with node dot slash hooks read underscore hook.js. I'm then going to save this file, and that's all we have to do inside of here.

Next up, we need to actually implement the command that's going to run anytime Claude tries to call the read or the grep tools. So that's going to be the readhook.js file. At the top of this file, I've got some code that's going to read from standard in and parse that data as JSON. So this tool args object right here, that's going to be the big JSON object I showed you in this diagram back over here. So it's going to have properties like session ID, the tool name, the tool input, and so on. So all we really need to do is take a look at that file path right there and decide whether or not it is trying to read the .env file. If it is, then we want to make sure that we exit from our program or our command here with an exit code of two, and hopefully also log some information out to claw that says, sorry, but you can't read that file. So you'll notice that back over here, I've already got some code that's going to read that file path. You'll also notice that there's a fallback of looking at tool input.path right here, I'll tell you why that's added in in just a moment.

So now let's implement the to-do statement. We'll say if readPathIncludes.env. That means that Claude must be trying to read the .env file. And if that's the case, then I want to make sure that we block that operation and provide some logging feedback to Claude. So I'm going to first add in a console.air, specifically a console.air, because we want to log to standard air. Remember, that's how we provide some feedback to Claude. and I'll say something like you cannot read the .emd file and then I'll do a process .exit2.

So now to test this out I'm going to save the file. I'm going to open up Claude code. If you already have it open make sure you restart Claude code. You have to restart it to have any changes to your hooks take effect. I'm going to ask Claude to read the .emd file and it's probably going to attempt to, but as it attempts to read it, we're going to send back an error that says you cannot read the .emd file, and then Claude's hopefully going to realize that sorry, you can't actually read this. As a matter of fact, it's even able to recognize that it was prevented by a read hook. Now, our hook should also be working on grep operations as well. So if I ask Claude to try the grep tool, this should also hopefully be forbidden as well. So let's see how it does. and yep same thing it is now forbidden so that is a working hook that we have put together now this hook is not terribly useful and I'm going to show you a much more useful hook in just a moment

↑ 目次へ戻る

Claude Code in Action | Lesson 13「Useful Hooks!」(全文ナレッジ)

動画 11分33秒(最長レッスン)/ 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

このレッスンは、実プロジェクトで使いたくなる実用フック2本の紹介。どちらも Claude Code の「よくある弱点」を補うためのもの。

弱点デモ①: 編集の波及先(呼び出し元)を直さない

  • src/schema.ts には createSchema という関数が1つあり、main.ts から呼ばれている。
  • 手動で関数定義に「呼び出し時に verbose: boolean 引数を必須で渡す」変更を入れると、main.ts 側で即座に型エラー(argument for verbose was not provided)になる。
  • 同じ変更を Claude Code に頼むと、編集自体は問題なくやる(verbose: true を追加)が、プロジェクト内の呼び出し箇所(call site)を探して直しには行かないmain.ts を開くとエラーが残っている。

実用フック①: 編集のたびに TypeScript 型チェックを回す(PostToolUse)

  • tsc --noEmit でプロジェクト全体の型チェックができ、main.tscreateSchema 呼び出しのエラーがはっきり出る。
  • フックの発想:TypeScript ファイルを編集するたびに型チェッカーを走らせ、エラーがあれば PostToolUse フックで即座に Claude にフィードバックする。「いま自分が入れた変更で、プロジェクトの別の場所に型エラーが出た。直しに行く必要がある」というシグナルを与える。
  • 実装は hooks/tsc.js に用意済み(型チェッカーを実行し、見つかったエラーを Claude に返すロジック一式)。デモ用に冒頭へ process.exit(0) を入れて無効化してあったので、その行を削除すると有効化される。
  • 有効化して再テスト:schema.ts を元に戻す → Claude Code を再起動 → 同じ変更を依頼 → 編集直後にフックから「別ファイルにエラーを入れた」というフィードバックが届き、Claude は「main.tscreateSchema 呼び出しを直す必要がある」と理解して、欠けている引数を追加しに行く。
  • 応用:TypeScript 専用ではなく、型チェッカーを簡単に回せる型付き言語なら何でも同じ発想が使える。型なし言語でも、編集のたびにテストを実行する形で同じ機能を実装できる。

弱点デモ②: 大きなタスクの中で既存コードの再利用を忘れる

  • 背景:src/queries ディレクトリに多数のファイルがあり、各ファイルに SQL クエリを含む関数が多数ある。orderQueries.ts には e コマース DB から pending 状態の注文を取る getPendingOrders 関数が既にある。
  • 焦点の絞られたタスク(「main.ts で pending の注文を出力して」)なら、Claude はクエリファイル群を見て getPendingOrders を見つけ、新規クエリを書かずに既存関数を再利用する。これは期待どおり。
  • カーブボール/clear でコンテキストを消した後、task.md の大きめのタスク(「一定時間 pending のままの注文を、1日1回特定チャンネルに Slack 通知する統合を書け」)として同じ要求を包んで渡すと、今度は集中を失って getOrdersPendingTooLong という新規重複クエリを書き、しかも新規ファイルまで作ってしまう(本来は orderQueries ファイルに置くべき)。

実用フック②: クエリ変更を別の Claude Code にレビューさせる(PreToolUse + SDK)

  • 発動条件:Claude が Write / Edit / MultiEdit ツールで src/queries ディレクトリ内を変更しようとした時だけ。
  • 動作:フック内で 別の Claude Code インスタンスをプログラム起動(Claude Code の TypeScript SDK を使用。ターミナルで Claude Code を使うのと本質的に同じ)し、「直近の変更と queries ディレクトリの既存コードを見て、似たクエリが既にないかレビューせよ」という長いプロンプトを渡す。
  • レビュー結果で重複と判定されたら exit code 2 で早期終了し、そのフィードバックを元の Claude に返す→「追加したクエリを消して既存のものを使え」と促す。これで queries フォルダから重複コードを排除できる。
  • デモ:新規作成された order_alerts_queries.tsslack.ts を削除 → hooks/query_hook の冒頭の process.exit(0) を消して有効化 → Claude Code 再起動 → 同じタスクを再実行。Claude はまた新規クエリファイルを作ろうとするが、フックが別コピーの Claude Code を起動してリサーチし、「再利用できる既存クエリがある。既存クエリを目的に合わせて更新すればよい」と助言。主インスタンスは「既存クエリを修正しよう」と方針転換する。
  • トレードオフ:queries ディレクトリを編集するたびに追加の時間とコストがかかる。その代わり重複コードが大幅に減る。導入するなら、本当に重要な少数のディレクトリだけを監視対象にして余計な処理を最小化することを推奨。

実務ポイント(このレッスンから持ち帰るもの)

  • Claude は「編集そのもの」は正確でも、波及先(呼び出し元)の修正を漏らすことがある → PostToolUse で型チェックを自動実行してエラーを即フィードバックするのが特効薬。
  • 型チェックフックの考え方は言語非依存:型付き言語=型チェッカー、型なし言語=テスト実行で同じ効果。
  • 大きなタスクに包まれると Claude は既存コードの再利用を忘れて重複を作る(コンテキストが薄い時ほど顕著)。
  • 対策としてフック内から SDK で別の Claude Code を起動し、変更をレビューさせて exit 2 で差し戻す「レビュー用フック」が組める。
  • レビュー系フックは時間・コスト増と引き換え → 重要ディレクトリ数個だけに限定して適用する。
  • フックの無効化/有効化は、スクリプト冒頭の process.exit(0) の挿入/削除で簡単に切り替えられる。

本文(時系列・日本語逐語+画面差し込み)

[0:00] このビデオでは、皆さん自身のプロジェクトでぜひ使いたくなるような、本当に便利なフックをいくつかお見せしたいと思います。これらのフックは、Claude Code のよくある弱点への対処を意図したものです。1つ目のフックがどう機能するかを理解してもらうために、Claude Code が時々ぶつかる問題——特に大きめのプロジェクトで——を手短にデモしましょう。

🖥 [0:00] 画面: VS Code。ウィンドウタイトル「queries」。エクスプローラーに .claude / hooks / node_modules / scripts / srcqueriesmain.tsschema.ts)/ .env / .gitignore / CLAUDE.md / package-lock.json / package.json / post-log.json / pre-log.json / task.md / tsconfig.json

[0:18] src ディレクトリの中の schema.ts を開きます。この中には createSchema という関数が1つだけあります。この関数は main.ts ファイルから——具体的にはまさにこの箇所から——呼ばれています。ではまた schema.ts に戻って、関数定義を更新します。この関数を呼び出したいなら、必ず verbose 引数も渡さなければならず、型は Boolean でなければならない、とします。

🖥 [0:30] 画面: schema.ts を手動編集。シグネチャが次の形に: ts export async function createSchema(db: Database, verbose: boolean) { 下には // 1. Customers table / await db.exec( / CREATE TABLE IF NOT EXISTS customers ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT UNIQUE NOT NULL, username TEXT UNIQUE, first_name TEXT NOT NULL, last_name TEXT NOT NULL, phone TEXT, status TEXT CHECK(status IN ('active', 'inactive', 'suspended')), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP などのスキーマ定義

[0:43] この変更を入れた途端、main.ts の側に戻ると型エラーが出ます。この関数の定義を更新したのに、verbose の値を実際には追加していないからです。エラーはまさに「argument for verbose was not provided(verbose への引数が渡されていません)」と言っています。

[0:59] ではこの変更をすぐに取り消します。main.ts ファイルを閉じます。それから Claude Code を開いて、まったく同じ変更をするように頼みます。

🖥 [1:00] 画面: 右側ターミナルに Claude Code。 ```

In the @src/schema.ts file update createSchema to take in a 'verbose' arg, boolean, no defaults └ Read src/schema.ts (199 lines) ⏺ I'll update the createSchema function to accept a verbose boolean parameter. ✳ Creating… (5s · 20 tokens · esc to interrupt) ▶▶ auto-accept edits on (shift+tab to cycle) ```

[1:10] 実行すると、Claude Code はこの編集をまったく問題なくこなします。このファイルを更新します。そして残念ながら、その変更を加えた後——ほら、そこに新しい verbose: true があります——残念ながら Claude は、プロジェクトを回ってその関数が実際に呼ばれている場所を探し、各呼び出し箇所(call site)を更新しには行きません。ここで main.ts を開くと、実際にこちらにエラーが残っているのが分かります。そして Claude はこれを捕捉できませんでした、残念ながら。

🖥 [1:30] 画面: main.ts(12行目 await createSchema(db); に赤の波線=エラー)。ターミナルには tsc と入力中。main.ts の中身: ```ts import { open } from "sqlite"; import sqlite3 from "sqlite3";

import { createSchema } from "./sche…

async function main() { const db = await open({ filename: "ecommerce.db", driver: sqlite3.Database, });

await createSchema(db); }

main(); ```

[1:35] そこで、最初にお見せするフックはこの問題を超簡単に解決してくれます。TypeScript に馴染みがない場合でも、まったく問題ありません。Claude Code を終了して tsc --noEmit コマンドを実行すると、プロジェクト全体の型チェックが走ります。そしてこの型チェックで、エラーがまさにここにはっきり見えます。あの main.ts ファイルからの createSchema 呼び出しについて文句を言っているわけです。

🖥 [2:00] 画面: ターミナルの tsc --noEmit 出力: ``` src/main.ts:12:9 - error TS2554: Expected 2 arguments, but got 1.

12 await createSchema(db);

src/schema.ts:3:50 3 export async function createSchema(db: Database, verbose: boolean) { An argument for 'verbose' was not provided.

Found 1 error in src/main.ts:12 ```

[1:59] 私のフックのアイデアはとてもシンプルです。TypeScript ファイルを編集するたびに TypeScript の型チェッカーを走らせ、明確なエラーがないか確認する。もしあれば、そのエラーを post-tool use フックの中で即座に Claude にフィードバックする。うまくいけば、これが Claude へのシグナルになり、「いま自分が持ち込んだ型エラーがあり、プロジェクト内の別のどこかを直しに行く必要がありそうだ」と伝えられます。

[2:25] さて、時間を少し節約するために、幸いこのフックはすでに hooks/tsc.js ファイルの中に組んであります。このファイルの中には、TypeScript 型チェッカーを実行し、見つかったエラーを取り出して Claude に返すロジック一式が入っています。現時点では、さっき見せたデモをするために私がこのフックを無効化してあります。まさにそこに process exit zero を足して無効化したわけです。それを削除します。これでこのフックは問題なく(a-okay)動くはずです。

🖥 [2:30] 画面: hooks/tsc.js の main() 冒頭(73行目)に無効化用の process.exit(0); が入っている: ```js async function main() { process.exit(0); // ← デモ用の無効化行。これを削除して有効化 const input = await readInput(); const file = input.tool_response?.filePath || input.tool_input?.file_path;

// Only check TypeScript files if (!file || !/.(ts|tsx)$/.test(file)) { process.exit(0); }

const typeChecks = runTypeCheck("./tsconfig.json"); if (typeChecks) { console.error(typeChecks); process.exit(2); } } ```

📄 実物コード(queries_COMPLETED/hooks/tsc.js・全文=講義の完成状態。process.exit(0) 無効化行なし): ```js import * as ts from "typescript"; import * as path from "path";

// Read stdin async function readInput() { const chunks = []; for await (const chunk of process.stdin) { chunks.push(chunk); } return JSON.parse(Buffer.concat(chunks).toString()); }

function runTypeCheck(configPath) { // Parse the tsconfig.json file const configFile = ts.readConfigFile(configPath, ts.sys.readFile); if (configFile.error) { console.error( ts.formatDiagnostic(configFile.error, { getCanonicalFileName: (x) => x, getCurrentDirectory: ts.sys.getCurrentDirectory, getNewLine: () => ts.sys.newLine, }) ); return; }

// Parse the configuration const parseConfigHost = { fileExists: ts.sys.fileExists, readFile: ts.sys.readFile, readDirectory: ts.sys.readDirectory, getCurrentDirectory: ts.sys.getCurrentDirectory, onUnRecoverableConfigFileDiagnostic: () => {}, };

const parsed = ts.parseJsonConfigFileContent( configFile.config, parseConfigHost, path.dirname(configPath) );

// Override to ensure no emit const compilerOptions = { ...parsed.options, noEmit: true, };

// Create the program const program = ts.createProgram(parsed.fileNames, compilerOptions);

// Get all diagnostics const allDiagnostics = ts.getPreEmitDiagnostics(program);

// Format and display diagnostics if (allDiagnostics.length > 0) { const formatHost = { getCanonicalFileName: (path) => path, getCurrentDirectory: ts.sys.getCurrentDirectory, getNewLine: () => ts.sys.newLine, };

const formattedDiagnostics = ts.formatDiagnostics(
  allDiagnostics,
  formatHost
);
return formattedDiagnostics; // Type check failed

}

return null; // Type check passed }

async function main() { const input = await readInput(); const file = input.tool_response?.filePath || input.tool_input?.file_path;

// Only check TypeScript files if (!file || !/.(ts|tsx)$/.test(file)) { process.exit(0); }

const typeChecks = runTypeCheck("./tsconfig.json"); if (typeChecks) { console.error(typeChecks); process.exit(2); } }

main(); ```

📄 実物コード(queries_COMPLETED/.claude/settings.example.json より・このフックの配線部分。tsc.js は PostToolUse の Write|Edit|MultiEdit に接続): json "PostToolUse": [ { "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "jq -r '.tool_response.filePath // .tool_input.file_path // empty' | xargs -I {} npx --yes prettier --write {} 2>/dev/null || true" }, { "type": "command", "command": "node $PWD/hooks/tsc.js" } ] } ]

[2:52] それでは schema.ts ファイルに戻って、あの verbose フラグを外し、Claude Code を再起動して、もう一度同じ変更をするよう頼みます。Claude は変更を行います。そして今度は、直後に TypeScript 型チェッカーからのフィードバック——「おい、プロジェクトの別の場所に、いま自分が持ち込んだエラーがあるぞ」——を即座に受け取るはずです。そして Claude が直しに行ってくれるはずです。

[3:16] ここを見てください。行われた編集がそこにあります。そして、われわれが組んだフックからの「edit operation feedback(編集操作フィードバック)」を受け取りました。つまり別のファイルの中に問題を見つけたのです。Claude はいま「わかった、自分がエラーを持ち込んだと理解した。main.ts の中の createSchema 呼び出しを直す必要がある」と言っています。そして次に行う更新で、そのファイルに入って関数呼び出しを更新し、欠けている引数を追加しようとします。

🖥 [3:00] 画面: 左=schema.ts、右=Claude Code。編集 diff とフックのフィードバックが見える: `` 3 - export async function createSchema(db: Database) { 3 + export async function createSchema(db: Database, verbose: boolean) { 4 // 1. Customers table 5 await db.exec( 6 CREATE TABLE IF NOT EXISTS customers (

Edit operation feedback: - [node /Users/sgrider/code/enablements/claude-code-course/prod/queries/hooks/tsc.js]: src/main.ts(12,9): error TS2554: Expected 2 arguments, but got 1. └ Found 1 new diagnostic issue in 1 file (ctrl-r to expand)

✳ Elucidating… (10s · ↑ 82 tokens · esc to interrupt) ```

🖥 [3:30] 画面: Claude が波及先を自走修正: ⏺ I need to fix the call to createSchema in main.ts and also use the verbose parameter in the createSchema function. ⏺ Read(src/main.ts) └ Read 16 lines (ctrl+r to expand) ⏺ Now I'll update the call in main.ts to include the verbose argument: ⏺ Update(src/main.ts) └ Updated src/main.ts with 1 addition and 1 removal 12 - await createSchema(db); 12 + await createSchema(db, false); ⏺ Now I need to implement the verbose functionality in the createSchema function. I'll add console logs when verbose is true: ⏺ Update(src/schema.ts) (この後 schema.ts 側には if (verbose) console.log("Creating customers table..."); のような verbose 実装も追加される=[4:06] 頃の画面で確認できる)

[3:42] これは、皆さん自身の個人プロジェクトで実装を試してみるとよいフックです。このフックは TypeScript 専用に実装しましたが、型チェッカーを簡単に走らせられる型付き言語なら、他のどんな言語でも同じように機能します。型なし言語を使っている場合でも、型チェッカーを走らせる代わりにテストを使って、同じ発想の機能を実装できます。つまり編集が行われるたびにテストを走らせ、その編集が問題ないことを確かめればよいのです。

[4:05] さて、次にお見せしたいフックは説明が少し難しいのですが、いったん背後のアイデアを掴めば、特に大きなプロジェクトでは間違いなく本当に役立つと感じてもらえるはずです。このもう1つのフックを理解してもらうために、このプロジェクトの背景を少し説明したいと思います。src/queries ディレクトリの中には、たくさんの異なるファイルがあります。これらのファイルにはそれぞれ、いろいろな関数の中に書かれた多数の SQL クエリが入っています。

[4:29] 特に order_queries.ts ファイルの中に、getPendingOrders という関数があることを指摘しておきたいと思います。このクエリは、e コマース関連のデータが入ったデータベースを見に行きます。そして理屈の上では、作成済みで pending 状態にある注文をすべて見つけます。この関数をしばらく頭に置いておいてください。

🖥 [4:30] 画面: src/queries/order_queries.ts(110行目付近)。queries フォルダには analytics_queries.ts / customer_queries.ts / inventory_queries.ts / order_queries.ts / product_queries.ts / promotion_queries.ts / review_queries.ts / shipping_queries.ts: ``ts export async function getPendingOrders(db: Database): Promise<any[]> { const query = SELECT o.order_id, o.order_date, o.total_amount, c.first_name || ' ' || c.last_name as customer_name, c.phone, julianday('now') - julianday(o.order_date) as days_since_create… FROM orders o JOIN customers c ON o.customer_id = c.customer_id WHERE o.status = 'pending' ORDER BY o.order_date `;

const rows = await db.all(query, []); return rows; } ```

[4:49] それでは、大きなプロジェクトの中で起こり始めるよくある問題を理解してもらうために、図をいくつか手短にお見せします。この図では、左側にクエリファイルの一覧があります。見てきたとおり、それぞれのクエリファイルには多くの異なるクエリが入っています。特にあの order_queries ファイルの中には getPendingOrders 関数があります。つまり、pending の注文を見つけようとするクエリは、すでに用意されているわけです。

🖥 [5:00] 画面: 図解スライド(ANTHROPIC)。左に ./queries ボックス(analytics_queries.tsreview_queries.ts の一覧。order_queries.ts / getPendingOrders() がハイライト)。右の吹き出し: Hi Claude! Can you update main.ts to print out orders that have been pending longer than 3 days? 吹き出しから order_queries.ts へ矢印。

🖥 [5:04] 画面: 同じ図の変形。右側の黒いパネルに getPendingOrders の実装コード(上記 SQL と同じもの)が表示され、order_queries.ts ボックスと矢印で結ばれる=「既存クエリを見つけて使ってほしい」の視覚化

[5:12] ここで Claude のところへ行って「main.ts を更新して、3日より長く pending 状態のままになっている注文をすべて出力して」と頼んだら、完璧な世界では、Claude は order_queries.ts ファイルを見つけ、あの既存のクエリを見つけて、まったく新しいクエリを書き出すのではなく、それを利用するはずです。それがわれわれの望みです。

[5:34] そして、実際にいま Claude を使ってまさにそれをやるよう頼めば、まさに望みどおりの結果が得られます。Claude に「main.ts で、pending になっている注文を出力して」と頼みます。

🖥 [5:30] 画面: Claude Code のプロンプト入力(右下に「In order_queries.ts」バッジ): ```

In main.ts print out orders that have been pending longer than 3 days ```

[5:46] Claude の名誉のために言うと、Claude は存在するいろいろなクエリファイルを見に行きます。order_queries ファイルを見つけます。そしてその中に、getPendingOrders というクエリがすでにあることを認識します。そして新しいクエリを作るのではなく、その関数を使おうとします。われわれは新しいクエリが欲しかったのではなく、Claude に既存の関数を使ってほしかったのです。つまり、非常にフォーカスが利いた指示の明確なタスクを与えたとき、Claude は「うん、新しいクエリを書くべきではなさそうだ。少なくともすでに存在するものをいくつか見てみるべきだ」と理解できたわけです。それは間違いなく良いことでした。

🖥 [6:00] 画面: Claude の実行ログ: what query functions are available for orders. ⏺ Read(src/main.ts) └ Read 16 lines (ctrl+r to expand) ⏺ Now let me check what order query functions are available in the order_queries.ts file. ⏺ Read(src/queries/order_queries.ts) └ Read 251 lines (ctrl+r to expand) ⏺ Perfect! I can see there's already a getPendingOrders function in order_queries.ts that includes a calculated field days_since_created. I'll now modify main.ts to use this function and filter for orders pending longer than 3 days. · Philosophising… (23s · ⚒ 261 tokens · esc to interrupt)

[6:17] ここで Claude にちょっとしたカーブボールを投げます。わざとこのタスクを少し難しくするのです。まず slash clear(/clear)を実行して、これまでに得たコンテキストをすべて消します。それから task.md ファイルを見てほしいのです。このファイルの中に、やはり「しばらく pending のままになっている注文を見つけて」と Claude に頼むプロンプトを用意したのですが、それをより大きなプロジェクトで包んであります。Slack 統合を書き、pending が長すぎる注文をすべて、1日1回、特定のチャンネルへメッセージする、というものを Claude に頼んでいます。

🖥 [6:30] 画面: task.md の中身(「orders that have been pending too long」の部分が選択ハイライト)

📄 実物(queries_COMPLETED/task.md・全文): @main.ts is executed automatically once per day as a cron job. Add in a new slack integration in a separate file. Then whenever this thing runs, check for orders that have been pending too long (more than 3 days) and send an alert to the #order-alerts channel with the customer name and phone number so someone can follow up. @schema.ts contains the current db structure. Remember, all queries should be placed in the ./queries dir. Start with the slack integration.

[6:51] このシナリオでも、pending が長すぎる注文を見つけたいことに変わりはありませんが、今回はそれをこの大きなタスクの中に包みました。そしてこのタスクを、あの slash clear 操作をやった後で Claude に食わせると、今度は残念ながら、さっきほどフォーカスを保ってくれず、結局まったく新しい get pending orders クエリを書き出そうとすることになります。繰り返しますが、これは望んでいないことです。プロジェクト中にコードを重複させることになるからです。

[7:15] しばらく実行させておくと、やがて、実際に getOrdersPendingTooLong という真新しいクエリを作るのが確認できます。これは、Claude がいわばフォーカスを失い、既存のクエリを再利用するのではなく真新しいクエリを書くと決めてしまった例です。改めて、ここには重複コードができています。おそらく望むところではありません。加えて、新しいクエリを作っただけでなく、真新しいファイルまで作りました。これもおそらく望んでいないことです。この注文関連のクエリは order_queries ファイルに追加されてほしいはずです。

🖥 [7:00] 画面: 大タスク実行中の Claude: ⏺ Update Todos └ ☐ Create Slack integration module (slack.ts) ☐ Create query to find orders pending for more than 3 days ☐ Integrate Slack alerts into main.ts cron job ⏺ Let me first check the schema to understand the orders structure: ⏺ Read(src/schema.ts) └ Read 100 lines (ctrl+r to expand) ⏺ Read(src/schema.ts) └ Read 100 lines (ctrl+r to expand) ⏺ Now I'll create the Slack integration module: ✳ Envisioning… (54s · ⚒ 710 tokens · esc to interrupt)

🖥 [7:30] 画面: エクスプローラーに新規ファイル src/queries/order_alerts_queries.ts(U)と src/slack.ts(U)が出現。ターミナルに書かれた重複クエリ: ts import { Database } from "sqlite"; export function getOrdersPendingTooLong(db: Database, days: number = 3): Promise<any[]> { const query = ` SELECT o.order_number, o.created_at, c.first_name || ' ' || c.last_name as customer_name, c.phone as customer_phone, CAST((julianday('now') - julianday(o.created_at)) AS INTEGER) as days_pending … +14 lines (ctrl+r to expand) └ Interrupted by user

[7:45] さて、問題を理解したところで、フックを利用してこれをどう直せる可能性があるかをお見せしましょう。いいですか、Claude が Write、Edit、あるいは MultiEdit ツールを使って、特に queries ディレクトリの中の何かを修正しようとしたときは必ず、次のフックを実行します。まず、このフックの中で、真新しい別コピーの Claude Code を起動します。この新しいコピーに、いま行われた変更を見て、queries ディレクトリ内の既存コードもいくつか見て、似たクエリがすでにその中にないか確認するよう頼みます。それで既存のクエリがあったなら、そのフィードバックを取って元のコピーの Claude に送り返し、Claude に状況の修正を判断してもらうよう頼みます。つまり、追加したクエリを取り除いて、すでに存在するものを使う、ということです。こうすることで、queries フォルダが総じてクリーンに保たれ、中が重複コードだらけにならないようにできるわけです。

🖥 [8:00] 画面: 図解スライド(ANTHROPIC): Claude uses Write, Edit, or MultiEdit to modify a file in the ./queries dir ↓ ┌─────────── PreToolUse Hook ───────────┐ │ Programmatically launch a separate copy of │ │ Claude Code │ │ Ask it to research the queries dir and see │ │ if a similar query already exists │ │ If so, provide this feedback to Claude, │ │ giving it the opportunity to fix the │ │ situation │ └────────────────────────────────────────┘ ※ナレーションは「write/edit/multi-edit しようとした時」=図・実配線とも PreToolUse(settings.example.json でも query_hook.js は PreToolUse の Write|Edit|MultiEdit に接続。ツール実行に割り込んで書き込みを exit 2 でブロックする設計)

[8:35] では、これが実際に動くところをお見せしましょう。まずこちらに戻ります。さっき作られた真新しい order_alerts_queries.ts ファイルと、同じく作られた slack.ts ファイルを削除します。

🖥 [8:30] 画面: VS Code の削除確認ダイアログ: Are you sure you want to delete 'order_alerts_queries.ts'? You can restore this file from the Trash. [Move to Trash] [Cancel] ☐ Do not ask me again

[8:53] 次に hooks ディレクトリの中の query hook ファイルを見つけます。このフックもすでに用意しておきました。いまは先頭に process.exit があるので無効化された状態です。このフックを手短に見ていきましょう。まず、src/queries ディレクトリへの変更だけをレビューするように指定します。それから少し下で、いま行われた変更が queries ディレクトリに対するものだったかをチェックします。その後に長いプロンプトがあり、いま行われた変更についてレビューを行うよう Claude に頼んでいます。そしてその後が、Claude Code をプログラムから起動している箇所——具体的にはまさにこの数行です。これは Claude Code の TypeScript SDK を利用しています。これについてはもう少し後でたっぷり説明しますが、今のところは、これがターミナルで Claude Code を使うのと本質的に同じものだと理解しておいてください。

🖥 [9:00] 画面: hooks/query_hook.js(23〜39行目、パス正規化〜レビュープロンプト冒頭): ```js // Normalize paths for comparison const normalizedFilePath = path.resolve(filePath); const queriesDir = path.resolve(process.cwd(), REVIEW_DIR);

// Check if file is within queries directory (handles subdirectories too) if (!normalizedFilePath.startsWith(queriesDir + path.sep)) { process.exit(0); }

// Prepare prompt for analysis const newContent = toolInput.content || toolInput.contents; const prompt = `You are reviewing a proposed change to a database query fi… Your task is to analyze if the new or modified query functions could be accomplished by reusing or slightly modifying existing query functions.

Within reason, we want to prevent duplicate queries from being added into th… so you are seeing if the proposed change will duplicate any existing functio… `` ※動画内のファイル冒頭はimport { query } from "@anthropic-ai/claude-code";(旧パッケージ名)。現行 assets は改名後の@anthropic-ai/claude-agent-sdk` を import している

[9:41] Claude Code が実行されて応答が返ってきたら、Claude が「うん、変更は問題なさそうだ」と判断したのか、それとも重複クエリがあるのかをチェックします。そして重複がある場合は、exit code 2 で早期終了します。これによってこのフィードバックが Claude に返され、うまくいけば「変更が必要だ」と伝わるはずです。

🖥 [9:30] 画面: hooks/query_hook.js(66〜84行目): ```js const resultMessage = messages.find((m) => m.type === "result"); if (!resultMessage || resultMessage.subtype !== "success") { process.exit(0); }

// If changes are appropriate, allow them if (resultMessage.result.includes("Changes look appropriate")) { process.exit(0); }

// Otherwise, block with feedback console.error(Query duplication detected:\n\n${resultMessage.result}); process.exit(2);

main().catch((err) => { console.error(Hook error: ${err.message}); process.exit(1); }); ```

📄 実物コード(queries_COMPLETED/hooks/query_hook.js・全文。※assets 版は配布時の安全のため main() 冒頭に process.exit(0); の無効化行が残った状態=講義でいう「削除前」。有効化するにはこの1行を消す): ```js import { query } from "@anthropic-ai/claude-agent-sdk"; import path from "path";

const REVIEW_DIR = "src/queries";

async function main() { process.exit(0); // Read JSON input from stdin const input = await new Promise((resolve) => { let data = ""; process.stdin.on("data", (chunk) => (data += chunk)); process.stdin.on("end", () => resolve(data)); });

const hookData = JSON.parse(input); const toolInput = hookData.tool_input;

// Check if this is a file modification in ./queries const filePath = toolInput.file_path || toolInput.path; if (!filePath) { process.exit(0); }

// Normalize paths for comparison const normalizedFilePath = path.resolve(filePath); const queriesDir = path.resolve(process.cwd(), REVIEW_DIR);

// Check if file is within queries directory (handles subdirectories too) if (!normalizedFilePath.startsWith(queriesDir + path.sep)) { process.exit(0); }

// Prepare prompt for analysis const newContent = toolInput.content || toolInput.contents || toolInput.new_string; const prompt = `You are reviewing a proposed change to a database query file. Your task is to analyze if the new or modified query functions could be accomplished by reusing or slightly modifying existing query functions.

Within reason, we want to prevent duplicate queries from being added into this project, so you are seeing if the proposed change will duplicate any existing functionality.

File: ${filePath} New content: ${newContent}

Please research and analyze the existing queries in the ./queries directory and: 1. Identify any new query functions being added in this change 2. For each new query function, determine if it could be accomplished by: - Using an existing query function as-is - Slightly modifying an existing query function, perhaps by adding additional arguments or expanding a select statement

If yes, provide specific feedback on which existing functions could be used instead. Be concise and specific. If no, just say "Changes look appropriate."`;

const messages = []; for await (const message of query({ prompt, abortController: new AbortController(), })) { messages.push(message); }

// Extract the analysis result const resultMessage = messages.find((m) => m.type === "result"); if (!resultMessage || resultMessage.subtype !== "success") { process.exit(0); }

// If changes are appropriate, allow them if (resultMessage.result.includes("Changes look appropriate")) { process.exit(0); }

// Otherwise, block with feedback console.error(Query duplication detected:\n\n${resultMessage.result}); process.exit(2); }

main().catch((err) => { console.error(Hook error: ${err.message}); process.exit(1); }); ```

📄 実物コード(queries_COMPLETED/.claude/settings.example.json・query_hook の配線部分=PreToolUse): json "PreToolUse": [ { "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "node $PWD/hooks/query_hook.js", "timeout": 300 } ] } ] (timeout 300 秒=別 Claude Code の起動・リサーチに時間がかかるため長めに確保)

[9:56] さて、この追加フックを組み上げて、先頭のあの process exit zero を取り除いて有効化したので、もう一度 Claude Code を再起動し、それから同じクエリ(タスク)をもう一度実行します。今度は、最初はあの重複クエリを入れようとするかもしれませんが、そこでまさにこのフックが走って、うまくいけばこう伝えてくれるはずです。「おい、その重複コードは要らない。この機能を実装するには、すでに存在するどれかのクエリを使うべきだ」と。

🖥 [10:00] 画面: Claude Code を再起動して同じタスクを投入(右下に「In query_hook.js」バッジ): ``` /help for help, /status for your current setup cwd: /Users/sgrider/code/enablements/claude-code-course/prod/queries ※ Tip: Send messages to Claude while it works to steer Claude in real-time

@main.ts is executed automatically once per day as a cron job. Add in a new slack integration in a separate file. Then whenever this thing runs, check for orders that have been pending too long (more than 3 days) and send an alert to the #order-alerts channel with the customer name and phone number so someone can follow up. @schema.ts contains the current db structure. Remember, all queries should be placed in the ./queries dir. Start with the slack integration. ```

[10:24] Claude Code はまたしても、すでに存在していた古いクエリを利用せずに、真新しい、完全に別個のクエリファイルを作ろうとします。しかし、そのファイルを作ろうとしたとき、われわれのフックが実行されます。これがあの別コピーの Claude Code を起動し、そのコピーがいくらかリサーチを行って、実際に再利用できる既存のクエリがあることを見つけます。そしてアドバイスを返してくれます。「なあ、この別の既存クエリを更新しに行けば、君の目的にぴったり合うはずだよ」と。そして、われわれが対話している主インスタンスの Claude からのフィードバックが見えます。「ああ、そうだ、この既存クエリがある。真新しいものを書き出そうとするのではなく、その既存クエリを修正することにしよう」と。

🖥 [10:30] 画面: 2回目の実行でフックが発動する瞬間。Slack 統合(1件目の Todo)が完了し、重複クエリファイルを Write しようとしたところで PreToolUse フックが実行中: ``` export class SlackIntegration { … +53 lines (ctrl+r to expand)

⏺ Now let me mark the first task as completed and move to creating the query for pending orders. ⏺ Update Todos └ ☒ ~~Create Slack integration module~~(完了・取り消し線) ☐ Create query to find orders pending more than 3 days ☐ Integrate Slack alerts into main.ts cron job ☐ Test the integration ⏺ Write(src/queries/order_alert_queries.ts) └ Running hook PreToolUse:Write... ✳ Creating… (145s · ⚒ 1.3k tokens · esc to interrupt) `` (「**Running hook PreToolUse:Write...**」の表示=query_hook が別コピーの Claude Code を起動してレビュー中。経過 145 秒はそのリサーチに要している時間。エクスプローラーにはsrc/slack.ts(U)が既に新規作成済み。なお2回目の Write 先ファイル名はorder_alert_queries.tsで、1回目に作られたorder_alerts_queries.ts` とは微妙に異なる)

🖥 [10:38] 画面: フックに差し戻されて方針転換する主インスタンス(エクスプローラーには slack.ts(U)のみ新規=queries 外なのでフック対象外。order_alerts_queries.ts は再作成されていない): `` - Calculates days since creation usingjulianday('now') - julianday(o.order_date)` … +1 line (ctrl+r to see all)

⏺ Let me check the existing order queries to see the getPendingOrders function. ⏺ Read(src/queries/order_queries.ts) └ Read 251 lines (ctrl+r to expand) ⏺ I see the existing getPendingOrders function. Let me modify it to accept an optional parameter for filtering by days as the hook suggested. ⏺ Update(src/queries/order_queries.ts) └ Interrupted by user ``` (=新規重複ファイルではなく order_queries.ts の既存 getPendingOrders に日数パラメータを足す方向へ転換。最後の Interrupted by user は講師が収録上ここで打ち切ったもの)

[11:02] さて、このフックの欠点は、queries ディレクトリの中の何かを編集したいときに毎回、追加の時間と費用がかかって実行される、という点です。一方の利点は、最終的に queries ディレクトリ内の重複コードがずっと少なくなることです。つまり結局のところ、自分のプロジェクトでこういうものを実装したいかどうかは、皆さんが判断すべきトレードオフの組み合わせに帰着します。もし導入するなら、少なくとも query hook の中でお見せしたこと——つまりまさにこれです——をやることをお勧めします。監視するのはプロジェクト内の本当に重要なフォルダのような、せいぜい一握りのディレクトリだけにして、行われる余計な仕事の量を最小化するのです。

🖥 [11:24] 画面: hooks/query_hook.js 冒頭(監視対象を絞る要の1行 const REVIEW_DIR = "src/queries"; を含む): ```js import { query } from "@anthropic-ai/claude-code"; import path from "path";

const REVIEW_DIR = "src/queries";

async function main() { // Read JSON input from stdin const input = await new Promise((resolve) => { let data = ""; process.stdin.on("data", (chunk) => (data += chunk)); process.stdin.on("end", () => resolve(data)); });

const hookData = JSON.parse(input); const toolInput = hookData.tool_input;

// Check if this is a file modification in ./queries const filePath = toolInput.file_path || toolInput.path; if (!filePath) { process.exit(0); ```

英語逐語(ASR全文)

In this video, I'd like to show you some really useful hooks that you might want to use on your own projects. These hooks are intended to address some common weak points in CloudCode. To help you understand how the first one works, let me give you a quick demonstration of a problem that CloudCode sometimes runs into, especially on larger projects. So inside the src directory, I'm going to find schema.ts. Inside of here, there's just one single function called create schema. This function is called from the main dot TS file specifically right here. Now I'm going to go back to the schema dot TS file, and I'm going to update the function definition. I'm going to say that if you ever want to call this function, you must also pass in a verbose argument that must be of type Boolean. Now, as soon as I add in this change, if I go backwards, the main dot TS file, I'm going to get a type error because I just updated the definition of this function, but I have not actually added in a value for verbose. So the error right here says specifically argument for verbose was not provided.

Now I'm going to undo that change very quickly. I'm going to close the main.ts file. I'm then going to open up Claude code and ask it to make the exact same change. Now, if I run this, Claude code is going to have absolutely no issue making this edit whatsoever. But it's going to update this file. And then unfortunately, after making that change, so there's the new verbose true right there. Unfortunately, Claude won't go around the project and try to find where that function is actually called and try to update any of the different call sites. So if I now open up main.ts, we'll see that we do in fact have an error over here. And Claude didn't really catch this, unfortunately.

So the first hook that I want to show you will fix this solution super easily. In case you're not familiar with TypeScript, if you're not, that's totally fine. If I close out a Claude code and run the command tsc-noemit, that's going to run a type check on my entire project. And in this type check, we can see that the error is very evident right here. So it's complaining about our call to create schema from that main.ts file. So my idea for a hook is really simple. I think that any time that we edit a TypeScript file, we should run the TypeScript type checker and see if there are any distinct errors. If there are, we should attempt to feed these errors back into Claude immediately inside of a post-tool use hook. And hopefully this will give Claude a signal and tell it that there is a type error that it just introduced that it probably needs to go and fix somewhere else inside of our project.

Now, I already put this hook together for us, fortunately, just to save us a little bit of time inside the hooks tsc.js file. So inside this file, I've got a bunch of logic put together to run TypeScript type checker, take any errors that it found, and pass them back into clod. At present, I disabled this hook just so I can give you that demonstration you just saw. So I disabled it by adding the process exit zero right there. I'm going to delete that, and now this hook should be working a-okay. So if I now go back to the schema.ts file, remove that verbose flag, restart Claude code, and ask it to make the same change once again, it will make the change. And then hopefully this time it will immediately get that feedback from the TypeScript type checker saying, Hey, you've got an error somewhere else in the project that you've just introduced. And hopefully Claude will go and fix it. So we can see right here, there's the edit that was made. We got some edit operation feedback from the hook that we put together. So it found an issue inside of one of our different files. And Claude is now saying, okay, I understand I introduced an error. I need to fix the call to create schema inside of main.ts. And then the next update it makes is going to attempt to go into that file and update that function call to add in that missing argument. So this is a hook that you might want to try implementing on your own personal projects. Now, even though this hook was implemented specifically for TypeScript, it still works for any other kind of typed language where you can run a type checker very easily. Even if you're using an untyped language, you might even implement the same idea of functionality using tests instead of running a type checker. So every time an edit is made, you could run your tests to make sure that the edit is okay.

Now, the next hook that I would like to show you is a little bit more challenging to explain, but once you get the idea behind it, I think that you will definitely find this next one really helpful, particularly in larger projects. To help you understand this other hook, I want to give you a little bit of background on this project. Inside of the SRC queries directory, there are many different files. Each of these different files contains many different SQL queries written inside of different functions. Inside of the order queries.ts file in particular, I want to point out that there is a function inside of here called get pending orders. This query goes through a database that contains some e-commerce related data. And in theory, it's going to find all the different orders that have been created that are in a pending state. So just keep that function in mind for a moment.

Okay, so I'm going to show you a couple of diagrams really quickly to help you understand a common problem that starts to arise inside of larger projects. So in this diagram, I've got my list of different query files on the left hand side. And as we saw, each of those different query files contains many different queries. Inside of that order queries file in particular is the get pending orders function. So we've already got a query put together that will attempt to find some different pending orders. Now, if I go to Claude and ask it to update the main.ts file to print out all the different orders that have been in a pending state for longer than three days, in a perfect world, Claude would find the order queries.ts file, it would find that existing query, and it would make use of it, as opposed to writing out a brand new query. So that's what we want. And we'll see that if we make use of Claude right now and ask it to do exactly that, we're going to get exactly the result we want. So I'm going to ask Claude in the main.ts file, print out orders that have been pending. Now to Claude's credit, it is going to take a look at the different query files that exist. It's going to find the order queries file. And then inside there, it's going to recognize that there is already a query called get pending orders. And it's going to attempt to use that function as opposed to creating a new query. We didn't want a new query. we wanted Claude to use the existing function. So when we gave Claude a very focused and directed task, it was able to understand that, yeah, it probably shouldn't write a new query. It should at least take a look at some of the ones that already exist. And that was definitely good.

Now I'm going to give Claude a little bit of a curveball. I'm going to purposefully make this task a little bit more difficult. First, I'm going to run slash clear to clear out all the context that we've gained. Then I'd like you to take a look at the task.md file. Inside this file, I put together a prompt that is still going to ask Claude to find orders that have been pending for a while, but I've also wrapped it up in some larger project. I'm asking Claude to write out a Slack integration that's going to message a specific channel once a day with all the different orders that have been pending for too long. So in this scenario, we still want to find orders have been pending for too long, but now I've wrapped it inside this larger task. And if I take this task and then feed it into Claude, again, after doing that slash clear operation, we're going to see that this time around, unfortunately, it's not going to stay quite as focused, and it's going to end up trying to write out a brand new get pending orders query, which is, again, not what we want, because that would be duplicating code throughout our project. If I let this run for a bit, I will eventually see that, yes, it does in fact make a brand new query called get orders pending too long. So this is an example of where Claude kind of lost focus and decided to write a brand new query as opposed to reusing an existing one. Again, we've got some duplicate code here, which is probably not what we want. In addition, it didn't only create the new query, it also created a brand new file, which is also probably something we don't want. We'd probably want this order-related query to be added to the order queries file.

So now that we understand the issue here, let me show you how we could fix this potentially by making use of a hook. All right, so whenever Claude attempts to write, edit, or use the multi-edit tool to modify something inside the queries directory specifically, I'm going to run the following hook. First, inside this hook, I'm going to launch a brand new separate copy of Claude code. I'm going to ask this new copy to take a look at the change that was just made and take a look at some of the existing code inside the queries directory and see if a similar query is already inside there. Then if there is an existing query, then I'm going to take that feedback and send it back to the original copy of Claude, and I'm going to ask Claude to maybe decide to fix the situation. So remove the added query and make use of the one that already exists. So this is going to allow us to make sure that the queries folder generally stays clean and doesn't have a bunch of duplicate code inside of it.

So let me show you how this would work in action. First, I'm going to flip back over here. I'm going to delete the brand new order alerts queries.ts file that was made and the slack.ts file that was made as well. Then I'm going to find inside the hooks directory, the query hook file. So I already put this hook together for us. Right now it is currently disabled because I got a process.exit at the very top. So let's walk through this hook really quickly. First, I'm going to tell this thing that it's only going to review changes to the src queries directory. Then a little bit lower, I'm going to check and see if the change that was just made was made to the queries directory. After that, I've then got a long prompt here, that is asking Claude to do a review on the change that was just made. And then after that is where I'm launching Claude code programmatically, specifically these lines right here. This is making use of the Claude code TypeScript SDK. I can give you a lot more information on it in just a little bit. For right now, just understand that this right here is essentially the same as us making use of Claude code at the terminal. Once Claude code runs and I get a response back out of it, I check and see if Claude decides that, yeah, the changes look okay, or maybe we've got a duplicate query. And if we do, then we're going to exit early with an exit code of two, which is going to give this feedback back to Claude and hopefully tell it that it needs to make a change.

So now that I've got this additional hook put together and enabled by removing that process exit zero at the top, I'm going to again restart Claude code and then run the same query again. And hopefully this time it might initially put in that duplicate query, but then our hook right here is going to run and hopefully tell it, Hey, we don't want that duplicate code. You should make use of some already existing query to implement this functionality. Now, CloudCode is once again going to attempt to create a brand new, completely separate query file, not making use of the old query that already existed. When it tries to create that file, however, our hook is going to run. This is going to launch that separate copy of CloudCode, which is going to do some research and find that there is in fact an existing query that can be reused. It's going to provide some advice and say, hey, you could probably go and update this other existing query to suit your purposes perfectly. And we'll see some feedback from Claude, our primary instance that we are interacting with saying, ah, yes, there is this existing query. Let's just modify that existing query rather than attempting to write out a brand new one.

Now, the downside to this hook is that it's going to take some additional time and expense to run every single time that I want to edit something inside the queries directory. But the upside is that I'm going to end up with a lot less duplicate code inside my queries directory. So it really comes down to a set of trade-offs for you deciding whether or not you want to implement something like this in your own project. If you do, I would at least recommend doing what I showed you inside of the query hook. So this one right here and only watching maybe a handful of directories like really important folders inside your project just to minimize the amount of extra work that is being done.

↑ 目次へ戻る

Claude Code in Action | Lesson 14「The Claude Code SDK」(全文ナレッジ)

動画 2分46秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

Claude Code SDK とは

  • 前レッスンのクエリレビュー用フックで一瞬登場した Claude Code SDK の解説。SDK を使うと Claude Code をプログラムから利用できる。
  • 利用形態は3つ:CLI 経由/TypeScript ライブラリ/Python ライブラリ
  • 中身はターミナルで普段使っているのとまったく同じ Claude Code。同じツール一式を持ち、それらを使ってタスクを完了する。
  • SDK が最も活きるのは、より大きなパイプラインやツールの一部として組み込む使い方(前レッスンのフックがまさにそれ)。ワークフローに「知能」を簡単に配線できる。

TypeScript SDK のデモ

  • プロジェクトルートの sdk.ts に最小限のスターターコードが用意されている。
  • 冒頭の prompt を「src/queries ディレクトリ内の重複クエリを探して」に書き換え、保存して npm run sdk で実行。
  • npm run sdk は組み込みコマンドではなく、この TypeScript ファイルを普通に実行するために講師が作ったショートカット。
  • 実行すると、ローカルの Claude Code と Claude 言語モデルの生の会話がメッセージ単位で流れ、最後にコマンドラインへ戻る。最後に出力されるメッセージに Claude の最終回答が入っている。

ハマりどころ: デフォルトは読み取り専用

  • SDK はデフォルトでは read 系の能力しか持たない(ファイル読み取り・ディレクトリ閲覧・grep など)。write / edit / ファイル作成などは不可
  • 書き込み権限を与える方法は2つ: 1. query 呼び出しに手動で書き込み許可を追加する 2. .claude ディレクトリの settings ファイルに permission 設定を追加する
  • デモ(方法1):prompt 引数の直後に options を追加して Edit ツールを許可する。
// prompt 引数の直後に options を追加
{
  prompt,
  options: {
    allowedTools: ["Edit"]   // 講義音声では「allow tools に配列で edit を入れる」
  }
}
  • prompt を「package.json に description を追加して」に変えて npm run sdk を再実行 → package.json に description が実際に追加され、編集能力が確認できた。

使いどころ

  • Claude Code SDK は他のツールの部品として最も有用。自分のプロジェクトのヘルパーコマンド・スクリプト・そして特にフックの中で使う機会を考えてみるとよい。

実務ポイント(このレッスンから持ち帰るもの)

  • Claude Code は CLI / TypeScript / Python の SDK でプログラム呼び出しでき、ターミナル版と同一のツール・能力を持つ。
  • 単体で使うよりパイプライン・スクリプト・フックの部品として組み込むのが本命の用途。
  • デフォルトは read-only。書き込みが要るなら options の許可ツール指定(例: allowedTools: ["Edit"])か settings の permission 設定で明示的に付与する。
  • SDK 実行ではモデルとの生のメッセージ列が観察でき、最終メッセージが最終回答。

本文(時系列・日本語逐語+画面差し込み)

[0:00] さっきクエリレビュー用フックを見ていたとき、Claude Code SDK をちらっと目にしました。SDK を使うと、Claude Code をプログラムから利用できます。SDK は CLI、TypeScript ライブラリ、あるいは Python ライブラリ経由で使えます。これは、皆さんがすでにターミナルで使っているのとまったく同じ Claude Code です。同じツールをすべて持っていて、与えられたタスクを完了するためにそれらを使います。SDK が最も役立つのは、さっきあのフックで見たように、より大きなパイプラインやツールの一部として、です。Claude Code をより大きなプロセスの一部として簡単に配線して、あるワークフローに大量の知能を追加できます。

🖥 [0:00] 画面: スライド「Claude Code SDK」(ANTHROPIC): - Available for Typescript, Python, and via the CLI - Runs Claude Code programatically - Same Claude Code! - Inherits all the settings of an instance of Claude Code launched in the same directory - Has read-only permissions by default - Useful as part of a larger pipeline or tool

右側のコード例3種: CLI: claude -p "Look for duplicate queries" ```ts // Typescript import { query, SDKMessage } from "@anthropic-ai/claude-code";

const prompt = "Look for duplicate queries";

for await (const message of query({prompt})) { console.log(message); } python

Python

import anyio from claude_code_sdk import query

async def main(): prompt = "Look for duplicate queries" async for message in query(prompt=prompt): print(message)

anyio.run(main) `` ※スライド当時のパッケージ名は@anthropic-ai/claude-code。現在は@anthropic-ai/claude-agent-sdk` に改名済み(assets の sdk.ts 冒頭コメント参照)

[0:34] それでは、特に TypeScript SDK を、われわれの既存プロジェクトに追加する形で手早くデモしたいと思います。エディタに戻って、プロジェクトのルートディレクトリの中にある sdk.ts ファイルを見つけます。この中に、SDK を使い始めるためのほんの少しのコードを用意しておきました。

🖥 [0:30] 画面: sdk.ts(スターター状態): ```ts import { query } from "@anthropic-ai/claude-code";

const prompt = "";

for await (const message of query({ prompt, })) { console.log(JSON.stringify(message, null, 2)); } ```

[0:51] 先頭の prompt を更新して、src/queries ディレクトリの中の重複クエリを探すよう Claude に頼みます(差し替え後の3行目は const prompt = "Look for duplicate queries in the ./src/queries dir";。エディタ画面は [1:30] のフレーム参照)。それからこのファイルを保存して、実行するためにターミナルを開き、npm run sdk を実行します。ちなみに、これは組み込みコマンドか何かではありません。念のため言っておくと、裏側ではこのファイルを普通の TypeScript ファイルとして実行しているだけです。TypeScript ファイルの実行を少し楽にするために、私がこの小さなショートカットを用意しただけです。

[1:14] これを実行すると、ローカルコピーの Claude Code と Claude 言語モデルの間の生の会話が、メッセージ単位で見えます。

🖥 [1:00] 画面: npm run sdk 実行直後、最初に流れる init メッセージ(生 JSON): json "cwd": "/Users/sgrider/code/enablements/claude-code-course/prod/queries", "session_id": "7f07632d-5e2d-4287-aae0-3e2ce18afd81", "tools": [ "Task", "Bash", "Glob", "Grep", "LS", "exit_plan_mode", "Read", "Edit", "MultiEdit", "Write", "NotebookRead", "NotebookEdit", "WebFetch", "TodoWrite", "WebSearch" ], "mcp_servers": [], "model": "claude-sonnet-4-20250514", "permissionMode": "default", "apiKeySource": "ANTHROPIC_API_KEY"

🖥 [1:17] 画面: 続いて assistant のツール呼び出しメッセージが流れる。プロンプトを展開した長い指示(「For each file in ./src/queries, read the content and extract all the function names and their SQL queries. Then compare across files to find duplicates.\n\nReturn a detailed report of:\n- All query files found\n- Any duplicate functions identified\n- Similar functions that could potentially be consolidated\n- Specific line numbers and function names where duplicates exist」)と、"stop_reason": "tool_use""usage": { "input_tokens": 7, "cache_creation_input_tokens": 193, "cache_read_input_tokens": 14921, "output_tokens": 201, "service_tier": "standard" } などが見える

[1:21] やがてコマンドラインに戻されます。一番最後に表示されるメッセージに、Claude からの最終応答が入っています。

🖥 [1:24] 画面: 最後の result メッセージ(分析結果の結び): "…While there are no exact duplicates, there are significant opportunities to consolidate similar functionality, particularly around customer segmentation, order filtering, inventory status checking, and date range queries. The consolidation would reduce code duplication, improve maintainability, and provide more consistent interfaces across the query modules." "parent_tool_use_id": null, "session_id": "7f07632d-5e2d-4287-aae0-3e2ce18afd81"

[1:27] さて、SDK にはちょっとしたハマりどころ(gotcha)があります。それは、デフォルトでは読み取り能力しか持たない、という点です。つまり、ファイルやディレクトリの読み取り、grep 操作などしかできません。ファイルの write や edit、create などをする能力はありません。書き込み権限を与えるには、まさにここの query 呼び出しに手動で書き込み権限を追加するか、あるいは代わりに、.claude ディレクトリの中の settings ファイルに permission 設定を追加することもできます。

🖥 [1:30] 画面: エディタに戻り sdk.ts を表示(プロンプト差し替え後の状態。3行目): ts const prompt = "Look for duplicate queries in the ./src/queries dir";

[1:55] このプロジェクトの中で SDK に Edit ツールの使用を許可する方法をお見せしましょう。まさにここの prompt 引数を見つけます。そのすぐ後に options を追加し、オブジェクトを入れて、allow tools(allowedTools)。これは配列にして、edit を入れます。先頭の prompt も更新して、package.json ファイルに description を追加するよう頼みます。

🖥 [2:00] 画面: options を追記し、prompt を打ち替え中("Add a descrip|"): ```ts import { query } from "@anthropic-ai/claude-code";

const prompt = "Add a descrip"; // ← 入力途中

for await (const message of query({ prompt, options: { allowedTools: ["Edit"] } })) { console.log(JSON.stringify(message, null, 2)); } ```

📄 実物コード(queries_COMPLETED/sdk.ts・全文=講義の完成状態。パッケージ改名の注記コメント付き): ```ts // Note: the "@anthropic-ai/claude-code" package has been renamed // to "@anthropic-ai/claude-agent-sdk" import { query } from "@anthropic-ai/claude-agent-sdk";

const prompt = "Add a description to the package.json file";

for await (const message of query({ prompt, options: { allowedTools: ["Edit"], }, })) { console.log(JSON.stringify(message, null, 2)); } ```

[2:18] これを保存して、もう一度 npm run sdk を実行します。そして完了したら、package.json ファイルを開くと、実際に description が追加されているのが確認できます。これで、間違いなくファイルを編集する能力を持ったわけです。

🖥 [2:19] 画面: 実行完了時の result メッセージ(生 JSON の末尾)。"total_cost_usd": 0.21965474999999998"usage": { "input_tokens": 30, "cache_creation_input_tokens": 2425, "cache_read_input_tokens": 75769, "output_tokens": 1072, "server_tool_use": { "web_search_requests": 0 }, "service_tier": "standard" } が見え、zsh プロンプトに戻る

🖥 [2:26] 画面: エクスプローラーで package.json に M(変更済み)マーク=description が実際に書き込まれた

[2:33] 先ほど述べたように、Claude Code SDK は他のツールの一部として最も役立ちます。ですから、皆さん自身のプロジェクトの中で、ヘルパーコマンドやスクリプト、そしておそらく最も特筆すべきはフックの中でこれを使う機会を、ぜひ考えてみてください。

英語逐語(ASR全文)

As we were looking at the query review hook a moment ago, we got a brief look at the CloudCode SDK. The SDK allows you to use CloudCode programmatically. You can use the SDK via the CLI, TypeScript library, or Python library. This is the exact same CloudCode that you already use at the terminal. It has all the same tools and will use them to complete a given task. The SDK is most useful as part of a larger pipeline or tool, as we saw in that hook a moment ago. You can easily wire in Claude code as part of a larger process to add in a bunch of intelligence to some given workflow.

Now I'd like to give you a quick demonstration of the TypeScript SDK in particular by adding it into our existing project. Back inside of my editor, I'm going to find the sdk.ts file inside of the root project directory. Inside of here, I put together just a little bit of code to get us started with the SDK. I'm going to update the prompt at the top and ask Claude to look for duplicate queries inside the SRC queries directory. Then I'm going to save this file and to run it, I'll open up my terminal and execute npm run SDK. Now this is not a built-in command or anything like that. Just so you know, behind the scenes, it just executes this file as a normal TypeScript file. I just put together this little shortcut for us to make running a TypeScript file a little bit easier. When we run this, we'll see the raw conversation between our local copy of Claude code and the Claude language model, message by message. Eventually, we'll get kicked back to the command line. The very last message printed out will contain the final response from Claude.

Now there is a little bit of a gotcha around the SDK, and that is that by default it only has read abilities. So in other words, it can only read files, directories, do grep operations, and so on. It does not have the ability to write or edit or create and so on files. To give it write permissions, you can either manually add in write permissions to the query call right here, or alternatively, you can add in some permission settings to your settings file inside of your .cloud directory. Let me show you how we can allow the SDK to use the edit tool within this project. I'm going to find the prompt argument right here. Right after it, I'll add in options, put in an object, allow tools. That'll be an array and I'll put in edit. I'm going to update the prompt at the top and I'll ask it to add a description to the package.json file. Now I'm going to save this and run npm run SDK once again. and then once it is complete, I can open up the package.json file and I will see that it did in fact add in a description. So now it definitely has the ability to edit files. As I mentioned earlier, the Cloud Code SDK is most useful as part of other tools. So I would encourage you to think of opportunities to use it in helper commands, scripts, or probably most notably hooks inside of your own projects.

↑ 目次へ戻る

Claude Code in Action | Lesson 15「Wrap Up」(全文ナレッジ)

動画 0分53秒 / 講師: Steven Grider (Anthropic) / 文字起こし: mlx_whisper large-v3-turbo / 2026-07-02

日本語ナレッジ(要点整理)

コース総括:ここから先の3つのアドバイス

  1. 最新情報を追う — Claude Code は絶えず変化しており、活発に開発が続いている。Claude Code のホームページをウォッチして、新機能・新テクニックの登場を見逃さないこと。
  2. 実験する — Claude Code のカスタマイズ方法は多彩で、自分のユースケースに合わせて仕立てられる。 - カスタムコマンド(custom commands)を自作してみる - CLAUDE.md ファイルに追加の指示を書いてみる - このコースで扱った以外の MCP サーバーもいくつか試してみる
  3. 自動化するGitHub 連携(GitHub integration)を見て、日常的に繰り返しているタスクを洗い出し、GitHub リポジトリ内で発生するイベントをトリガーに Claude へ自動で委任する方法を考える。

実務ポイント(このレッスンから持ち帰るもの)

  • Claude Code は活発に進化中 → 公式ホームページを定期チェックして新機能を取り込む。
  • 学びを定着させる次の一歩は「実験」:カスタムコマンド作成・CLAUDE.md への指示追加・未体験の MCP サーバー導入。
  • 最終形は「自動化」:GitHub イベント駆動で反復タスクを Claude に委任する。

本文(時系列・日本語逐語+画面差し込み)

[0:00] この Claude Code の概観を楽しんでもらえていたら嬉しいです。締めくくる前に、ここからどこへ進むかについて、いくつかアドバイスをお伝えしたいと思います。

🖥 [0:00] 画面: スライド「Wrap up and next steps」(ANTHROPIC)。全編このスライド1枚: ``` Watch for changes and updates Keep an eye on anthropic.com/claude-code

Experiment! Customize with commands, CLAUDE.md, and MCP servers

Automate! Use the Github integration to delegate common tasks to Claude ```

[0:06] まず、Claude Code は絶えず変化していて、活発に開発が続いていることを覚えておいてください。ですから Claude Code のホームページ——アドレスをちょうどそこに出しています(anthropic.com/claude-code)——から目を離さず、新しい機能やテクニックが出てくるのをウォッチしてください。

[0:17] 次に、実験することを強くお勧めします。Claude Code をカスタマイズして、皆さんの特定のユースケースに合わせて本当に仕立て上げる方法は、たくさんあります。カスタムコマンドをいくつか自作してみたり、CLAUDE.md ファイルに追加の指示を入れてみたりしてください。それから、このコースの中で見たもの以外の MCP サーバーも、2〜3個試してみてください。

[0:34] 最後に、自動化しましょう。GitHub 連携(GitHub integration)を見て、皆さんがいつも繰り返しているよくあるタスクをいくつか思い浮かべ、GitHub リポジトリの中で発生するイベントに基づいて、それらを Claude に自動的に委任する方法を考えてみてください。

[0:48] それでは改めて、このコースを楽しんでもらえたことを願っています。Claude Code と過ごす時間を楽しんでください。

英語逐語(ASR全文)

I hope you've enjoyed this overview of Cloud Code. Before we finish up, I want to give you some advice on where to go from here. First, keep in mind that Cloud Code is constantly changing and in active development. So keep an eye on the homepage of Cloud Code, I've got the address to it right there, and watch for new features and techniques to come out. Secondly, I really recommend you experiment. There's a lot of different ways to customize Cloud Code and really tailor it to your particular use case. Try to author some custom commands or put extra instructions in your Cloud MD file. and also try out a couple of different MCP servers beyond the ones we looked at inside this course. Finally, automate. Take a look at the GitHub integration and think of some different common tasks that you go through all the time and think of some ways you can delegate those to Claude automatically based upon events that occur inside of your GitHub repository. Well, again, I hope you enjoyed this course and enjoy your time working with Claude Code.

↑ 目次へ戻る

演習素材と「講義で書かれたコード」の正確な差分

2026-07-03 / assets/queries(スターター)と assets/queries_COMPLETED(講義完成形)の diff から確定

演習素材の内訳

素材 内容 使用レッスン
assets/uigen/ UI 生成 Next.js アプリ(Lesson 03 デモ・Module 2 の題材)。配布時点で .claude / CLAUDE.md は非同梱=講義中に /init で CLAUDE.md を生成し、.claude/commands/audit.mdwrite_tests.md を作成(実物は各ノートの画面転記に収録) 02〜09
assets/queries/ EC データユーティリティ(SQLite・クエリ関数群)。hooks 演習の開始状態 10〜14
assets/queries_COMPLETED/ 講義完成形。hooks 3本+settings+init-claude.js+pre/post-log.json(デバッグフックの実出力) 10〜14

講義で実際に書かれたコード=スターターとの差分(全量)

1) hooks/read_hook.js — Lesson 12 で実装した4行(.env 読取ブロック)

  if (readPath.includes(".env")) {
    console.error("You cannot read the .env file");
    process.exit(2);
  }

(それ以外の stdin 読取・JSON parse・tool_input.file_path 抽出はスターターに用意済み)

2) sdk.ts — Lesson 14 で書いた部分(プロンプト+許可ツール)

- const prompt = "";
+ const prompt = "Add a description to the package.json file";
+   options: {
+     allowedTools: ["Edit"],
+   },

3) package.json — Lesson 14 の SDK デモで Claude 自身が書いた成果物

- "description": "",
+ "description": "E-commerce data utilities project that provides query functions for a SQLite database",

4) hooks/query_hook.js — ほぼ完成品がスターターに同梱(Lesson 13 は読解中心)

差分は2点のみ: パッケージ改名注記コメントの有無(@anthropic-ai/claude-code@anthropic-ai/claude-agent-sdk)と abortController: new AbortController() の追加。

5) hooks/tsc.js.claude/settings.example.jsonscripts/init-claude.js

スターターと完成形で同一(配布時点から完成済み)。全文は Lesson 11〜13 ノートに収録。

pre-log.json / post-log.json(jq . > pre-log.json デバッグフックの実出力)

Lesson 13/t4 で解説された「stdin の中身を知るための helper hook」が実際に吐いたログ。hook 入力スキーマの一次資料として assets/queries_COMPLETED/ に現物あり。

↑ 目次へ戻る

Claude Code in Action | Text Lesson「Claude Code setup」(全文ナレッジ)

テキストレッスン(Skilljar 本文)/ 2026-07-02 取得

日本語ナレッジ

Claude Code をローカルにセットアップする回(Module 2・レッスン ID 301614)。完全なセットアップ手順は公式クイックスタートを参照: https://code.claude.com/docs/en/quickstart

インストール(プラットフォーム別)

macOS / Linux / WSL:

curl -fsSL https://claude.ai/install.sh | bash

Windows PowerShell:

irm https://claude.ai/install.ps1 | iex

Windows cmd.exe:

curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

Homebrew:

brew install --cask claude-code

初回起動

  • インストール後、claude を実行する。
  • 初回起動時に次の2つが求められる: 1. カラーテーマの選択 2. claude.ai の資格情報での認証

トラブルシューティング

  • エラーが出る場合(コマンドが見つからない/ネットワークエラー/permission エラー)→ 公式 docs の「Troubleshoot installation」を参照。
  • Amazon Bedrock / Vertex AI / Foundry 経由で使うユーザー → サードパーティプロバイダのセットアップ docs を参照。

英語原文

## 301614 — Claude Code setup(Module 2)
Time to get Claude Code set up locally!
Full setup instructions: https://code.claude.com/docs/en/quickstart
- Install: macOS/Linux/WSL `curl -fsSL https://claude.ai/install.sh | bash` / Windows PowerShell `irm https://claude.ai/install.ps1 | iex` / cmd.exe `curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd` / Homebrew `brew install --cask claude-code`
- After install, run `claude`; first run prompts for color theme + authenticate with claude.ai credentials
- Errors (not found / network / permissions) → Troubleshoot installation in docs
- Bedrock / Vertex AI / Foundry users → third-party provider setup docs
↑ 目次へ戻る

Claude Code in Action | Text Lesson「Project setup」(全文ナレッジ)

テキストレッスン(Skilljar 本文)/ 2026-07-02 取得

日本語ナレッジ

コース演習用プロジェクトのセットアップ回(Module 2・レッスン ID 301615)。

  • Claude Code の学習は実プロジェクトがあった方が面白い。講師が小さなプロジェクト uigen.zip(前の動画で見せた UI 生成アプリ)を提供する。
  • 自分のコードベースで進めても構わない(uigen は必須ではない)。

セットアップ手順

  1. Node JS をインストールしておく
  2. レクチャーに添付された uigen.zip をダウンロードして展開する
  3. セットアップを実行する:
npm run setup

(依存パッケージのインストール+ローカル SQLite DB の作成が行われる)

  1. 任意: 本物のコンポーネント生成を動かしたい場合は Anthropic API キーを設定する - console.anthropic.com でキーを取得 - .env 内の your-api-key-here を自分のキーに置き換える - キーなしでも動く: その場合アプリは静的なフェイクコードを生成する
  2. 開発サーバーを起動する:
npm run dev

英語原文

## 301615 — Project setup(Module 2)
Working with Claude Code is more interesting with a project. Instructor provides a small project (uigen.zip — the UI generation app shown in a previous video). You can follow along with your own codebase instead.
Setup:
1. Node JS installed
2. Download uigen.zip attached to the lecture, extract
3. `npm run setup` (installs deps + local SQLite DB)
4. Optional: Anthropic API key for real generation (console.anthropic.com → put key in .env replacing your-api-key-here). Without key, app generates static fake code
5. `npm run dev`
↑ 目次へ戻る

Claude Code in Action | Text Lesson「Gotchas around hooks」(全文ナレッジ)

テキストレッスン(Skilljar 本文)/ 2026-07-02 取得

日本語ナレッジ

なぜ .claude に settings ファイルが2つあるのか

サンプルプロジェクト(queries)で npm run setup を実行すると、.claude ディレクトリに settings 系の JSON ファイルが2つ存在する状態になる。これは次のジレンマを解決するための仕掛け。

  • 公式ドキュメントの推奨:フックスクリプトのパスは絶対パスで書くこと。相対パスだとパス乗っ取り(path interception)/バイナリ植え付け(binary planting)攻撃のリスクがあり、絶対パスはその緩和策になる。
  • 絶対パスの問題:マシンごとにパスが異なるため、絶対パスを書いた settings.jsonチームで共有しづらい

このプロジェクトの解決策

  1. 共有用のテンプレートとして settings.example.json を用意し、パス部分に $PWD プレースホルダーを書いておく。
  2. npm run setup 時に scripts/init-claude.js が走り、$PWDそのマシンの絶対パスに置換して settings.local.json としてコピーする。
settings.example.json($PWD プレースホルダー・共有用)
        │  npm run setup → scripts/init-claude.js が $PWD を絶対パスに置換
        ▼
settings.local.json(マシン固有の絶対パス・実際に使われる)

結果

  • 共有可能な設定settings.example.json)と、推奨どおりの絶対パスsettings.local.json)を両立できる。

実務ポイント

  • フックの command は絶対パス推奨(セキュリティ緩和策)と覚える。
  • チーム共有したい場合は「プレースホルダー入り example + setup スクリプトで置換生成」のパターンをそのまま流用できる。

英語原文

## 312423 — Gotchas around hooks(Module 3)
After `npm run setup` there are TWO settings.json files in .claude — here's why:
- Docs recommend ABSOLUTE paths for hook scripts (mitigates path interception / binary planting attacks)
- But absolute paths make settings.json hard to share (paths differ per machine)
- Solution in project: `settings.example.json` contains `$PWD` placeholders; `npm run setup` runs `scripts/init-claude.js` which replaces `$PWD` with the machine's absolute path, copies to `settings.local.json`
- Result: shareable settings + recommended absolute paths
↑ 目次へ戻る

Claude Code in Action | Text Lesson「Another useful hook」(全文ナレッジ)

テキストレッスン(Skilljar 本文)/ 2026-07-02 取得

日本語ナレッジ

PreToolUse / PostToolUse 以外のフックイベント一覧

フックは PreToolUse / PostToolUse だけではない。以下のイベントでも発火できる:

イベント 発火タイミング
Notification Claude Code が通知を送る時(許可が必要な時、または 60 秒アイドル時)
Stop Claude Code が応答を終えた時
SubagentStop サブエージェント(画面上は "Task" と表示される)が終了した時
PreCompact compact(手動・自動どちらも)の実行前
UserPromptSubmit ユーザーがプロンプトを送信した時(Claude が処理する前)
SessionStart セッションの開始・再開時
SessionEnd セッションの終了時

紛らわしいポイント:stdin の中身はフック種別で変わる

  • コマンドに渡される標準入力(stdin)の JSON はフックイベントの種類によって形が変わる。さらに tool_input の中身はツールごとに異なる

PostToolUse(TodoWrite ツール)の stdin 例:

{"session_id":"...","transcript_path":"<path>","hook_event_name":"PostToolUse","tool_name":"TodoWrite","tool_input":{"todos":[{"content":"write a readme","status":"pending","id":"1"}]},"tool_response":{"oldTodos":[],"newTodos":["..."]}}

Stop の stdin 例(tool 系フィールドは無く、stop_hook_active を持つ):

{"session_id":"...","transcript_path":"<path>","hook_event_name":"Stop","stop_hook_active":false}

デバッグ用の便利フック:stdin をそのままファイルに記録する

どんな JSON が来るのか正確に知りたい時は、stdin を jq でファイルに書き出すだけのフックを仕込むのが手っ取り早い:

"PostToolUse": [{"matcher":"*","hooks":[{"type":"command","command":"jq . > post-log.json"}]}]

これで post-log.json に、実際にフックへ渡された stdin の JSON がそのまま記録される。

実務ポイント

  • フックを設計する前に、対象イベントの stdin ペイロードを実測する(jq . > log.json フック)のが最短。
  • イベントごと・ツールごとにペイロード構造が違う前提でパーサーを書く(Stop には tool_name が無い等)。

英語原文

## 312427 — Another useful hook(Module 3)
Hooks beyond PreToolUse/PostToolUse:
- Notification — when Claude Code sends a notification (needs permission, or idle 60s)
- Stop — when Claude Code finishes responding
- SubagentStop — when a subagent (shown as "Task") finishes
- PreCompact — before compact (manual or auto)
- UserPromptSubmit — when user submits a prompt, before Claude processes it
- SessionStart — starting/resuming a session
- SessionEnd — session ends

Confusing part: stdin input to your command changes by hook type; tool_input differs by tool.
Example PostToolUse (TodoWrite) stdin:
{"session_id":"...","transcript_path":"<path>","hook_event_name":"PostToolUse","tool_name":"TodoWrite","tool_input":{"todos":[{"content":"write a readme","status":"pending","id":"1"}]},"tool_response":{"oldTodos":[],"newTodos":[...]}}
Example Stop stdin:
{"session_id":"...","transcript_path":"<path>","hook_event_name":"Stop","stop_hook_active":false}
Debug helper hook — log exact stdin to a file:
"PostToolUse": [{"matcher":"*","hooks":[{"type":"command","command":"jq . > post-log.json"}]}]
↑ 目次へ戻る