チームのスキルを、手元のフォルダではなく MCP サーバーから配りたい、という場面はありませんか?
同じ SKILL.md を「.claude/skills/ に置く」と「公式 SDK で書いた MCP サーバーから配る」の2通りで用意し、Claude Code 2.1.332 の対話セッション32回で確かめました(Max サブスクの範囲内で、従量課金の API は使っていません)。
結論、ローカルでは11項目すべて効いた機能のうち、MCP 経由では7つが効きませんでした(各2回とも)。うち1つは、ドキュメントの「効かない」一覧に載っていない ${CLAUDE_SKILL_DIR} です。検証サーバー(86行)と計測スクリプトは末尾に全文あります。
見るのは右の列です。+ が MCP でも効いた4項目、- が効かなかった7項目です。数字は各2回の結果で、2/2 は両方とも効いた、0/2 は両方とも効かなかった、という意味です。
この記事の黒い画像3枚は、計測ログから必要な行を抜き出して画像にしたものです(ターミナルのスクショそのものではありません。数字はログのままです)。
こんにちは、八兵衛です。
ドキュメントには「MCP 経由だと効かない機能」の一覧があります。じゃあ、実際に配るとどう見えるのか。一覧に書かれていない機能はどうなるのか。そこを見たかったんです。
先に結論と持ち帰り
-
同じ SKILL.md でも、MCP 経由だと次の7つは効きませんでした(各2回とも 0/2)。
!`コマンド`の差し込み、${CLAUDE_SESSION_ID}/${CLAUDE_SKILL_DIR}/${CLAUDE_PROJECT_DIR}の置き換え、@ファイル参照の添付、frontmatter のmodelとallowed-toolsです。 -
効いたのは4つです。スキル本文が届く、
$ARGUMENTSの置き換え、disable-model-invocation(一覧に出さない、手入力なら実行できる)。いずれも 2/2 でした。 -
ドキュメントの「効かない」一覧に無いのに効かなかったものが、1つありました。
${CLAUDE_SKILL_DIR}です。同じページの置き換え変数の表には載っています。残りの6つは一覧どおりでした。 - スキルを選んで課題を解くところは、今回の課題では変わりませんでした。スキル21個(正解1個+無関係20個)から Claude が自分で選ぶ課題は、ローカルも MCP も5回とも正解です。入力トークン合計の中央値は 127,918 対 129,230 で、比は 1.01(約1%の差)でした。
- スキル20個を置いただけの、最初のリクエストの入力トークン増分は、ローカル +1,031、MCP +1,232 でした。増分の差は 201 で、ローカルの増分の約19.5%、最初のリクエスト全体(ローカルの中央値 42,300.5)から見ると約0.5%です。MCP 側の増分には、サーバーを1つつないだ分も入っています。
- セッションの途中でサーバー側の SKILL.md を1行書き換えると、次の1回は読み込まれず、その次で新しい版が入りました(2回くり返して同じ)。コマンドは手入力で、承認ダイアログは0回です。
- 一覧のチェックサムと合わない本文は、サーバーは返していましたが、4回とも Claude には届きませんでした。
- 確認が出る手動モードでは、初回に「Allow this version」を選ぶと、同じ版の次のセッションでは確認が出ず、書き換え後はまた出ました(2回くり返して同じ)。
配る前に見るなら、この3つです。
- SKILL.md に
!`、${CLAUDE_SESSION_ID}、${CLAUDE_SKILL_DIR}、${CLAUDE_PROJECT_DIR}、@参照、model:、allowed-tools:が無いかを見る。1行で探す grep を後ろに置きました(検証用のスキル23個で確かめたもので、自分の~/.claude/skillsには流していません)。 - サーバー側を書き換えた直後の1回は、「読み込まれなかった」というメッセージが出ます。もう一度呼ぶと新しい版が入りました。
- bypassPermissions(確認を全部スキップする設定)では、Claude が自分で MCP スキルを読み込んだ5回とも、承認ダイアログは出ませんでした。毎回確認させる設定(ask ルール)はドキュメントにありますが、今回は試していません。
Skills over MCP ってなに?
MCP サーバーが、ツールと一緒にスキル(SKILL.md と補助ファイル)も配れるようになった機能です。Claude Code では、配られたスキルに サーバー名:スキル名 という名前が付きます(今回なら /handbook:release-check)。
告知(MCP servers can now ship skills, run tasks, and more with Claude、ページ表記 November 24, 2026。2026-11-30 に開いて確認)には、「Skills over MCP is in public beta in Claude and Claude Code, on by default for Pro, Max, and Ultra plans」とあります。続きによると、Team プランは管理者が有効にしてから、Enterprise は「Coming soon」です。
Claude Code では、v2.1.332 のリリースノート(2026-11-25 01:32 UTC = 11/25 10:32 JST)に「Added skills from MCP servers (beta)」と入っています。
ドキュメント(Use skills from MCP servers、2026-11-30 に開いて確認)では、public beta で Claude Code v2.1.331 以降が必要、とあります。今回試したのは 2.1.332 だけです。対象外として claude -p と Agent SDK などが挙げられているので、今回は tmux の中で対話画面を動かしています。
同じドキュメントの Skills from MCP servers には、「効かない」機能の一覧もあります。あとで、試した範囲との照合を書きます。
やったこと
同じ SKILL.md を、次の2通りに置いて比べました。
- ローカル: 作業フォルダの
.claude/skills/に置く - MCP: 公式 TypeScript SDK
@modelcontextprotocol/server2.4.0 で書いた stdio サーバー(サーバー名handbook)から配る
見たのは次の6つです。
| 何を見るか | 回数 |
|---|---|
| 機能11項目が効くか(確認用の probe スキル) | ローカル2回、MCP 2回 |
| スキル21個から Claude が自分で選ぶ課題(リリースノート案の点検) | ローカル5回、MCP 5回 |
| スキル20個を置いただけの、最初のリクエストの入力トークン | 置かない2回、ローカル2回、MCP 2回 |
| セッションの途中でサーバー側の SKILL.md を1行書き換える | 2回 |
| 一覧のチェックサムと違う本文を返す | 4回 |
| 手動モードの承認(Allow this version → 同じ版 → 書き換え後) | 3セッション1組を2回 |
合計は対話セッション32回です。置き場所どうしを比べたのが20回(表の上3行)、MCP 側だけの確認が12回(下3行)です。ログの単位(run)では28本になります(承認だけ、1本に3セッション入るためです)。
1コマンドで全部回すスクリプトは、末尾に全文あります。
条件
- 日付: 2026-11-30(JST)。開始 10:17:26、終了 10:30:27(所要 13分01秒。記事では約13分)
- Claude Code 2.1.332(
.deps/に入れた固定版。セッションバナーも32セッションすべて 2.1.332。box のグローバル 2.1.330 は未使用) - モデル指定:
--model sonnet。課題の10回はすべてclaude-sonnet-5-5 - 認証: Max サブスク(OAuth トークンをファイルから読む。値は出していません)。
ANTHROPIC_API_KEYは unset。費用 0円(従量課金の API は使っていない) - OS: Linux(box)、tmux 3.5a の対話 UI。
claude -pの呼び出しは 0回 - サーバー:
verify/server/server.mjs(86行)、SDK 2.4.0、node v24.22.1、npm 11.21.1 - 権限: 機能の確認・課題・一覧・書き換え・改ざんは bypassPermissions(確認を全部スキップする設定)。承認だけ手動モード(default)
- 目安: 「課題の入力トークンの差は ±10% 以内」「置いただけの増分の差は 10% 以内」。本番前の動作確認(各1回)を見たあとで置いたものです
機能を1つずつ確かめる: 11項目中7つが MCP で効かなかった
使ったのは、11項目を一度に見るための短い probe/SKILL.md です。手入力で /probe hello-world(MCP なら /handbook:probe hello-world)を送り、Claude に渡った本文とログを見ました。
| 項目 | ローカル | MCP |
|---|---|---|
| スキル本文が Claude に届く | 2/2 | 2/2 |
$ARGUMENTS の置き換え |
2/2 | 2/2 |
!`コマンド` の実行結果の差し込み |
2/2 | 0/2 |
${CLAUDE_SESSION_ID} の置き換え |
2/2 | 0/2 |
${CLAUDE_SKILL_DIR} の置き換え |
2/2 | 0/2 |
${CLAUDE_PROJECT_DIR} の置き換え |
2/2 | 0/2 |
@ ファイル参照の添付 |
2/2 | 0/2 |
frontmatter の model: haiku
|
2/2 | 0/2 |
frontmatter の allowed-tools
|
2/2 | 0/2 |
disable-model-invocation(一覧に出さない) |
2/2 | 2/2 |
disable-model-invocation のスキルを手入力で実行 |
2/2 | 2/2 |
ローカルは11項目すべて 2/2 で効きました。MCP 経由でも全回効いたのは4項目、効かなかったのは7項目です(11 − 4 = 7)。
Claude に渡った本文を見ると、違いがそのまま出ていました。ローカルでは、次のように置き換わった値が届いています。
- args: hello-world
- shell: 42
- session: 486ac0d5-6873-40a1-8dc4-29690b5f5e2a
- skilldir: /tmp/som-verify/20261130-101726/probe_local_r1/work/.claude/skills/probe
- projectdir: /tmp/som-verify/20261130-101726/probe_local_r1/work
(2回目は session が 31c56755-db58-4d38-a398-cc3ba2b32948、パスが probe_local_r2 になる以外は同じです。)
MCP では、置き換え前のまま届いていました(probe_mcp_r1 と r2 は同じ文面です)。
- args: hello-world
- shell: !`expr 40 + 2`
- session: ${CLAUDE_SESSION_ID}
- skilldir: ${CLAUDE_SKILL_DIR}
- projectdir: ${CLAUDE_PROJECT_DIR}
model: haiku も同じで、ローカルの1ターン目は 2回とも claude-haiku-5-5、MCP は 2回とも claude-sonnet-5-5(起動時の --model sonnet)でした。allowed-tools は、ローカルではログに Bash(expr *) が載り、MCP では空でした。ただし今回は bypassPermissions なので、確認ダイアログが実際に省かれるかどうかまでは見ていません。ドキュメントにも、MCP サーバーのスキルでは「Claude gets no allowed-tools grant.」とあります。
! コマンドで試したのは、行の中に書く形(!`コマンド`)だけです。! で始めるコードブロックの形は試していません。
disable-model-invocation を付けた probe-hidden は、ローカルでも MCP でもスキル一覧に出ず、手入力(/probe-hidden または /handbook:probe-hidden)すると 4回とも hidden-probe-ran と答えました。
ドキュメントの「効かない」一覧との照合
Skills のドキュメント(2026-11-30 に取得して確認)の「Skill features that don't apply」には、次のようにあります。
- Frontmatter の
allowed-tools、disallowed-tools、hooks、model、effort、context、agent、background、shell、paths、metadataは無視される -
!`コマンド`は実行されない -
@参照のファイルは添付されない -
${CLAUDE_PROJECT_DIR}と${CLAUDE_SESSION_ID}は置き換わらない
試した範囲との照合は、こうなりました。
- 一覧にあり、実測でも効かなかった: 6項目(
!`コマンド`、${CLAUDE_SESSION_ID}、${CLAUDE_PROJECT_DIR}、@参照、model、allowed-tools) - 一覧に無いが、実測では効かなかった: 1項目(
${CLAUDE_SKILL_DIR})。同じページの置き換え変数の表には${CLAUDE_SKILL_DIR}がありますが、「don't apply」の一覧には書かれていません - 一覧に無く、実測でも効いた:
$ARGUMENTSとdisable-model-invocation - 一覧にあるが試していない frontmatter: 残り9フィールド(11フィールドのうち、試したのは
allowed-toolsとmodelの2つ)
ドキュメントの一覧に無い「効かない」が1つあった、というところまでです。書き漏れなのか、今の版だけの動きなのかは分かりません。
補助ファイルの読み方は、課題のログでついでに見ました。ローカルでは Read で references/rules.md を読み、MCP では ReadMcpResourceTool(skill://release-check/references/rules.md)で読んでいました。MCP の5回とも rules.md は読めています。
なお、MCP 経由で読み込まれた release-check の本文は、セッションログの上では <rule id> が <rule id> になっていました(本文が届いた MCP の17回すべて。ローカルの5回は <rule id> のまま)。どこで置き換わっているか、答えに影響するか、モデルに届く時点の文字列がログと同じかは確かめていません。MCP の課題5回は、判定4件とも正解でした。
課題: 選ぶ・正答・入力トークンはほぼ同じ
課題は、英語のプロンプト Please check the release note draft in draft.md.(リリースノート案を点検して)の1種類です。スキルは release-check(正解)と、説明文だけの無関係なスキル20個の、合計21個です。正解は、4つのルール(R1〜R4)について R1 OK/R2 NG/R3 OK/R4 NG です。スキルの本文には「答えの最後に ZEBRA-4417 入りの1行を付ける」と書いてあるので、この合言葉が答えにあれば、スキルを読んだと分かります。Claude が自分でスキルを選ぶかどうかを見るために、スキル名はプロンプトに書いていません。
画像の上半分(B)がこの課題、下半分(C)が次の節の「置いただけのときの増分」です。
| 置き場所 | 回数 | スキル読み込み | rules.md を読んだ | 合言葉あり | 判定4件とも正解 | API往復(中央値) | 入力トークン合計(中央値) | 出力トークン(中央値) | 所要秒(中央値) |
|---|---|---|---|---|---|---|---|---|---|
| ローカル | 5 | 5/5 | 5/5 | 5/5 | 5/5 | 3 | 127,918 | 323 | 3.1 |
| MCP | 5 | 5/5 | 5/5 | 5/5 | 5/5 | 3 | 129,230 | 330 | 3.3 |
入力トークン合計の中央値の比は、129,230 ÷ 127,918 = 1.0103 → 1.01 です。差は 1,312 トークン(+1.03%、約1%)で、本番前に置いた目安(±10% 以内)には収まっています。
各回の入力トークン合計は、ローカルが 127,915/127,921/127,918/127,927/127,903、MCP が 129,027/129,230/129,027/129,236/129,233 でした。API 往復は10回すべて3回です。
「入力トークン合計」は、3往復ぶんの input + cache_creation + cache_read の合計です。例として、task_local_r1 は 8 + 8,682 + 119,225 = 127,915、task_mcp_r1 は 8 + 9,162 + 119,857 = 129,027 で、大半はキャッシュの読み取りでした。
この合計の大半は、スキルと関係なく毎回渡る分です(スキルを置かないときの最初のリクエストだけで、中央値 41,269.5 トークンありました)。「約1%」は、その大きな分母に対する比です。なお、この値は課題の1ターンぶんで、セッション全体の消費量ではありません。
bypassPermissions で Claude が自分で MCP スキルを読み込んだ5回では、承認ダイアログは0回でした。
スキル20個を置いただけのときの増分
スキルを置いて、プロンプトは OK の一言だけ送ったときの、最初のリクエストの入力トークンです。回数は各2回です。
| 置き場所 | 各回の値 | 中央値(2回の平均) | 集計スクリプトの表示(整数に丸め) | なしとの差 | 一覧の文字数 | うち20個分 | 一覧に出た数 |
|---|---|---|---|---|---|---|---|
| なし | 41,271/41,268 | 41,269.5 | 41,270 | - | 8,179 | 0 | 0 |
| ローカル | 42,300/42,301 | 42,300.5 | 42,300 | 1,031 | 11,272 | 3,093 | 20 |
| MCP | 42,500/42,503 | 42,501.5 | 42,502 | 1,232 | 11,667 | 3,273 | 20 |
増分の差は 1,232 − 1,031 = 201 トークンで、201 ÷ 1,031 = 0.19496 → 約19.5% でした。本番前に置いた目安(差は10%以内)は外れました。
ただし 201 トークンは、最初のリクエスト(ローカルの中央値 42,300.5)の 0.475% で、約0.5% です。単純に20で割ると、1,031 ÷ 20 = 51.55(画像の表示は 51.5)、1,232 ÷ 20 = 61.6 でした。
ここで1つ注意があります。MCP 側の +1,232 は、「スキル20個の一覧」だけの値ではありません。「なし」の回は MCP サーバーをつないでいないので、サーバーを1つつないだ分も入っています。ログを見ると、MCP の2回だけ、あとから読み込めるツールの一覧が19個から22個に増えていました(増えた3個は ListMcpResourcesTool・ReadMcpResourceDirTool・ReadMcpResourceTool)。この3個が何トークンに当たるかは確かめていません。「サーバーをつないだだけ・スキル0個」の回も取っていないので、201 のうちスキル一覧の分がいくつかは分けられません。
スキル一覧の文字数で見ると、20個分の差 180字は、接頭辞 handbook:(9字)× 20個です。MCP の一覧には、このほか末尾に3行(215字)が付いていました。一覧の文字数の差は、合計 180 + 215 = 395字です(リクエスト全体の差の内訳ではありません)。
回数が各2回なので、傾向として見るだけにしておきます。
書き換え・改ざん・承認
画像は上から、途中の書き換え(D1)、一覧と違う本文(D2)、手動モードの承認(D3)の順です。
途中でサーバー側の1行を書き換える
bypassPermissions で、手入力の /handbook:release-check draft.md を送ったあと、サーバーが配る SKILL.md の合言葉を ZEBRA-4417 から ZEBRA-8802 に書き換え、5秒待って同じコマンドを2回送りました。これを2回くり返して、結果は同じでした。
- 1回目: 答えに
ZEBRA-4417 - 2回目: 読み込まれない
- 3回目: 答えに
ZEBRA-8802 - 承認ダイアログ: 0回
2回目に出たメッセージは、次の原文どおりです。
The skill "release-check" from MCP server "handbook" was not loaded, because the server has changed it since it was listed. Its entry has been refreshed; invoke it again to load the current version.
ドキュメントには「Typing a skill's command at the prompt doesn't need approval.」(スキルのコマンドを手入力するときは承認が要らない)とあります。今回の書き換えは手入力なので、承認0回は記載と合います。「Claude が自分で読み込む+途中で書き換え」の組み合わせは、bypassPermissions では試していません。
一方、この「読み込まれなかった」メッセージに当たる説明は、Claude Code のドキュメント2ページ(mcp と skills)を検索した範囲では見つけられませんでした。MCP の仕様のエラー処理の表には、不一致のとき「Host rejects content and refreshes the entry.」とあります。
一覧と違う本文を返す
サーバーは、起動時のファイルから一覧(マニフェスト)を作り、フラグが立ったあとだけ SKILL.md の読み取りを ZEBRA-4417 → TAMPR-9999 に差し替えます。どちらも10文字で、サイズは同じです。文字数が変わる改ざんだと、動作確認のときに「does not match the size」で止まったためです。
- 最初から改ざん(2回): 読み込まれず
- 1回読んだあとに改ざん(2回): 答えに
ZEBRA-4417→ 読み込まれず - 4回すべて、改ざん文は Claude に届いていません。サーバーが改ざん版を返したのは、4回それぞれで1回ずつです
出たメッセージは、次の原文どおりです。
The skill "release-check" from MCP server "handbook" was not loaded, because the content of its SKILL.md file does not match the checksum that the server listed for it. This is a problem with the server; retrying will not help until the server's owner fixes it.
MCP の仕様(Skills 拡張の概要、2026-11-30 に開いて確認)にも、「Hosts MUST NOT use content that fails verification.」とあります。試した範囲では、そのとおり動いていました。
手動モードの承認
Claude に課題と同じプロンプトを送り、自分で handbook:release-check を読み込むところを見ました。3セッションを1組にして2回くり返し、同じ結果でした。
- 初回: 承認ダイアログが出た。表示は
Version sha256:992a607e…。「Allow this version」を選ぶと、答えにZEBRA-4417 - 同じ版・新しいセッション: ダイアログは出ない。答えに
ZEBRA-4417 - サーバー側で1行書き換えたあとの新しいセッション: ダイアログが出た。表示は
Version sha256:194ab06d…(1と違う)。「Allow once」を選ぶと、答えにZEBRA-8802
書き換え後のダイアログの先頭は Skill changed. になっていました。保存された allow ルールは Skill(handbook:release-check@sha256:992a607e0edc…) で、3回目は Allow once なのでルールは増えていません。
表示された sha256:992a607e… は、SKILL.md 単体の sha256(74dc8238…)とは別の値です。何を対象にしたハッシュかは確かめていません。
ドキュメントの「Manual または acceptEdits では確認が出る。Allow this version を選ぶと、サーバーがスキルのファイルを変えるまで、確認と分類器の判定を省く」という説明と、手動モードの実測は一致しました。書き換え後の版で「Allow this version」を選んだ場合や、auto モードは試していません。
ドキュメントには、ask ルール(例は Skill(mcp__docs__*)。docs はサーバー名)を置くと、auto や bypassPermissions でも毎回承認が要る、ともあります。こちらも今回は試していません。
つまずき
-
box に入っていた Claude Code 2.1.330 では、MCP スキルが出ませんでした。
/handbookは「No commands match」でした。本番は.deps/に入れた 2.1.332 を使っています(グローバルは触っていません)。ドキュメントは v2.1.331 以降が必要、と書いています。 -
動作確認では、起動直後にスキルが出ない回が1度ありました。 約100秒たっても
/handbook:probeが「Unknown command」のままでした。同じ条件で3回起動し直すと、3回とも約2秒で出ました。本番は起動し直し0回で、スキルを待った30セッションはすべて、1回目の確認でメニューに出ていました(記録上の 2.0秒は、確認1回にかかる時間です)。ドキュメントのトラブルシュートは、Unknown commandに対して「もう一度送る」です。 -
claude -pでは使えません。 ドキュメントの対象外です。今回は tmux で対話画面を動かし、親の環境変数はenv -iで切っています。 -
改ざんテストは、サイズをそろえる必要がありました。 文字数が変わる改ざんだと「does not match the size」で止まりました。本番は
ZEBRA-4417→TAMPR-9999(どちらも10文字)にして、チェックサムの照合を見ています。
動作確認では、プロンプトを送った対話セッションが計31回ありました。この数字は判定には使っていません。
限界
- 回数が少ないです。機能の確認・一覧・書き換え・改ざん・承認は各2回(改ざんは条件ごとに2回)、課題だけ各5回です。傾向として書くだけで、統計的な差は主張しません。
- Claude Code は 2.1.332 だけ、モデルは
--model sonnet(Sonnet 5.5)だけです。 - サーバーは自作の stdio サーバー1種類(公式 TypeScript SDK 2.4.0)だけです。HTTP のサーバー、claude.ai のコネクタ、プラグイン同梱のサーバーは試していません。
- Linux の box で tmux の対話 UI を動かしました。VS Code 拡張と Desktop アプリは試していません。
- 権限モードは bypassPermissions と手動(default)だけです。auto モードは試していません。
- 書き換えから次の呼び出しまでは、5秒(書き換え)と2秒(改ざんの途中)です。1時間を超える放置は未確認です。
- 課題は英語のリリースノート点検が1種類、スキルは最大21個です。ドキュメントにある上限の100個付近は試していません。
- 自分の
~/.claude/skillsを、このサーバーで配る実験はしていません。 - frontmatter の残り9フィールドは未確認です。
-
!コマンドは、行の中に書く形だけを試しました。コードブロックの形は未確認です。 - 置いただけの増分は、MCP 側に「サーバーを1つつないだ分」が混ざっています。スキル一覧だけの増分は分けていません。
- 費用の 0円は、起動のしかた(サブスクの OAuth トークン、
ANTHROPIC_API_KEYは unset)からの判断です。請求画面では確かめていません。
配る前に見る grep
2026-11-30 10:44 JST に、検証用のスキルへ流して確かめました。当たったのは probe/SKILL.md の7行だけで、効かなかった7項目に1行ずつ対応しています。probe-hidden と release-check は0行でした。無関係な20個は、ログに残したコピーに同じ正規表現を流して0行でした。
grep -rnE '!`|\$\{CLAUDE_(SESSION_ID|SKILL_DIR|PROJECT_DIR)\}|^(model|allowed-tools):|(^|[[:space:]])@[A-Za-z0-9_./-]+' verify/skills_src --include=SKILL.md
試したのは検証用の23個(3 + 20)だけです。自分の ~/.claude/skills には流していません。
この正規表現には、当たりすぎと取りこぼしがあります(短い文字列を流して確かめました)。@ は「行頭か空白の直後の @名前」に当たるので、@types/node や @dataclass のような、ファイル参照ではない書き方も拾います。メールアドレスの途中の @ には当たりません。逆に、コードブロックの形で書いた ! コマンドは拾いません。当たった行は、目で見て判断してください。
計測スクリプトと、公式 SDK で書いたサーバー(86行)は、このあと全文あります。
課題を差し替えれば自分の作業でも測れるはずです(差し替えての実行は、僕もまだ試していません)。
おまけ: 今週ほかに出た発表
一次情報のページを開いて確認できたものだけです。Skills over MCP 自体は上に書いたので、ここには入れていません。
- 2026-11-24 Anthropic が Claude Ship を発表。Code Review(GA)に、PR Steward と Claude Approvals(どちらも beta)が加わった。Team/Enterprise プランの GitHub リポジトリ向け https://claude.com/resources/articles/introducing-claude-ship
- 2026-11-24 ZDR(データを保持しない契約)のまま不正利用の検知を受けられる Enterprise Frontier Safeguards が public beta に。入出力は顧客側のストレージ(Amazon S3/Google Cloud Storage)に置く https://claude.com/resources/articles/zero-data-retention-with-enterprise-frontier-safeguards
- 2026-11-24 OpenAI と Cisco が Shirudo を公開。パッチや再起動を待たずに、稼働中の Linux を eBPF で守るための OSS ランタイム(BSD 2-Clause) https://openai.com/index/introducing-shirudo/
- 2026-11-24 Codex CLI 0.172.0。スラッシュコマンド引数の Tab 補完、stdio MCP サーバーを最初のツール呼び出し時に起動、Code Mode のホスト接続を gRPC に一本化 https://github.com/openai/codex/releases/tag/rust-v0.172.0
- 2026-11-24 Cloudflare の Email Sending が Workers Free プランでも使えるように(検証済みの宛先アドレスのみ。任意の宛先は Workers Paid) https://developers.cloudflare.com/changelog/post/2026-11-24-email-sending-workers-free/
- 2026-11-25 Claude のアーティファクトを Mac/Windows のアプリとして入れられる「Install as app」が beta で提供開始。全プラン対象、権限は版ごとに確認される https://claude.com/resources/articles/install-as-app
- 2026-11-25 Anthropic がサンドボックス脱出の評価 Siren を公開。26環境・1,700超のシナリオで、Claude 5.5 系と Mythos 5.2 は 21〜32% のシナリオで外に手を伸ばした。サンドボックスの説明を与えると 68〜96% 減った https://safeguards.anthropic.com/2026/siren/
- 2026-11-25 Claude Code v2.1.332 に
PreSkillShellCommandフックが追加。スキルやコマンドの読み込み時に走るインラインのシェルコマンドを止められる https://github.com/anthropics/claude-code/releases/tag/v2.1.332 - 2026-11-25 Cloudflare が Search for Agents を追加。ダッシュボードで有効にすると、サイトに
/.well-known/search(GET と HTTP QUERY)ができ、結果を Markdown で返す。全プラン対象 https://developers.cloudflare.com/changelog/post/2026-11-25-search-for-agents/ - 2026-11-26 Anthropic が Messages API を Python から Rust に移した経緯を公開。リクエストあたり CPU 約70%減・メモリ 80%超減・最初のトークンまでの中央値 約20%短縮。本番のトラフィックで Python 版との違いを見つけ、その修正をエージェントに任せた https://www.anthropic.com/research/migrating-api-to-rust
日付は日本時間です。Claude Ship、Enterprise Frontier Safeguards、Shirudo、Install as app、Siren、Rust 移行の6件は、公式アカウントの投稿時刻から決めた日付で、ページの表記は前日の日付になっています。その投稿時刻は、僕は確かめ直していません。ページ表記と要点は、2026-11-30 に各ページを開いて確認しました。URL は同日 10:33–10:34 JST に HTTP 200 でした。
チームのスキルを MCP サーバーから配りたくなったら、まずは上の grep を1回どうぞ。当たった行が、今回の7項目に関わりそうなところです!
最後まで読んでいただきありがとうございました!
付録: 検証サーバーと計測スクリプト全文
./verify/run_all.sh の1コマンドで、32セッションと集計(summary.md / summary.csv)まで回ります。
動かすのに要るのは、tmux・node・npm・python3(ほかに timeout と sha256sum)と、~/.config/claude/oauth_token に置いたサブスクのトークンです。Claude Code 2.1.332 は、無ければスクリプトが .deps/ に入れます。動かしたのは Linux だけです。
OAuth トークンはファイルから読むだけで、記事にもスクリプトにも値は入っていません。ANTHROPIC_API_KEY は使いません。
このスクリプトは、機能の確認・課題・一覧・書き換え・改ざんを Claude Code の bypassPermissions(確認を全部スキップする設定)で起動します。 作業は /tmp に作った使い捨てフォルダの中で行う作りですが、自分の作業に差し替えるときは、壊れても困らないコピーで試してください。承認のシナリオだけは手動モードです。初回に出る「このフォルダを信頼するか」と bypassPermissions の同意には、スクリプトが自動で答えます。
スクリプト冒頭のコメントには「about 30-40 min」とありますが、今回の実測は13分01秒でした。
以下は、実行したときのファイルそのままで、省略していません。
verify/server/server.mjs(公式 SDK で書いた stdio サーバー(86行))
// Minimal stdio MCP server that serves a folder of Agent Skills over MCP
// (Skills extension, io.modelcontextprotocol/skills, SEP-2640).
//
// node server.mjs <skills_dir> serve every <skills_dir>/<name>/SKILL.md
// node server.mjs <skills_dir> --tamper publish the real manifest, but return an
// altered SKILL.md once <skills_dir>/../TAMPER exists
//
// In the normal mode the folder is re-scanned every second, so an edited skill is
// republished with a new digest (the SDK sends resources/list_changed when needed).
import { readFile, readdir, stat } from 'node:fs/promises';
import { existsSync, appendFileSync } from 'node:fs';
import path from 'node:path';
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { SkillsExtension, skillEntry } from '@modelcontextprotocol/server/ext/skills';
import { loadSkills } from '@modelcontextprotocol/server/ext/skills/node';
const root = path.resolve(process.argv[2] ?? './skills');
const tamper = process.argv.includes('--tamper');
const logFile = process.env.SKILLS_SERVER_LOG; // optional: one JSON line per event
const log = (event, extra = {}) => {
if (logFile) appendFileSync(logFile, JSON.stringify({ t: new Date().toISOString(), event, ...extra }) + '\n');
};
async function filesOf(dir, base = '') {
const out = {};
for (const e of await readdir(dir, { withFileTypes: true })) {
const rel = base ? `${base}/${e.name}` : e.name;
if (e.isDirectory()) Object.assign(out, await filesOf(path.join(dir, e.name), rel));
else if (e.isFile()) out[rel] = await readFile(path.join(dir, e.name));
}
return out;
}
let skills;
if (!tamper) {
skills = await loadSkills(root);
log('loaded', { skills: skills.entries.length });
setInterval(async () => {
try {
const c = await skills.reload();
if (c.added.length || c.removed.length || c.changed.length) log('reloaded', c);
} catch (e) {
log('reload-error', { message: String(e?.message ?? e) });
}
}, 1000).unref();
} else {
// A server that lies: the manifest (digests, sizes) is computed from the files on disk
// at start-up, but SKILL.md reads return different bytes once the TAMPER flag file exists.
const flag = path.join(root, '..', 'TAMPER');
const entries = new Map(); // SKILL.md uri -> entry
const bytes = new Map(); // file uri -> Buffer
for (const name of (await readdir(root)).sort()) {
const dir = path.join(root, name);
if (!(await stat(dir)).isDirectory() || !existsSync(path.join(dir, 'SKILL.md'))) continue;
const files = await filesOf(dir);
const entry = await skillEntry(name, files);
entries.set(entry.uri, entry);
for (const [rel, buf] of Object.entries(files)) bytes.set(`skill://${name}/${rel}`, buf);
}
log('loaded-tamper', { skills: entries.size });
skills = new SkillsExtension({
source: {
list: async () => ({ skills: [...entries.values()] }),
get: async (uri) => entries.get(uri),
read: async (uri) => {
const buf = bytes.get(uri);
if (!buf) return undefined;
let text = buf.toString('utf8');
const lying = uri.endsWith('/SKILL.md') && existsSync(flag);
if (lying) text = text.replace(/ZEBRA-4417/g, 'TAMPR-9999'); // same byte length: only the digest differs
log('read', { uri, tampered: lying });
return { text, mimeType: 'text/markdown' };
},
},
});
}
serveStdio(
() => {
const server = new McpServer({ name: 'handbook', version: '1.0.0' }, { capabilities: { resources: {} } });
skills.attach(server);
return server;
},
{ onerror: (e) => log('error', { message: String(e?.message ?? e) }) },
);
verify/server/package.json(サーバーの依存(@modelcontextprotocol/server 2.4.0))
{
"name": "skills-over-mcp-verify-server",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Minimal stdio MCP server that serves a folder of Agent Skills (Skills extension, SEP-2640)",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/server": "2.4.0"
}
}
verify/server/package-lock.json(`npm ci` が使う lock ファイル(50行))
{
"name": "skills-over-mcp-verify-server",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "skills-over-mcp-verify-server",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/server": "2.4.0"
}
},
"node_modules/@modelcontextprotocol/core": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
"integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
"license": "Apache-2.0",
"dependencies": {
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@modelcontextprotocol/server": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz",
"integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==",
"license": "Apache-2.0",
"dependencies": {
"@modelcontextprotocol/core": "2.4.0",
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
verify/skills_src/probe/SKILL.md(機能確認(probe)用 SKILL.md(19行))
---
name: probe
description: Prints probe markers. Use only when the user types the probe command.
argument-hint: "[word]"
allowed-tools: Bash(expr *)
model: haiku
---
# Probe
Repeat the five marker lines below exactly as you see them, then stop. Do not run any tool.
- args: $ARGUMENTS
- shell: !`expr 40 + 2`
- session: ${CLAUDE_SESSION_ID}
- skilldir: ${CLAUDE_SKILL_DIR}
- projectdir: ${CLAUDE_PROJECT_DIR}
Reference file: @probe-facts.md
verify/skills_src/probe-hidden/SKILL.md(disable-model-invocation 用 SKILL.md(9行))
---
name: probe-hidden
description: Hidden probe skill with the marker HIDDEN-PROBE-5150. Only a typed command may run it.
disable-model-invocation: true
---
# Hidden probe
Reply with the single line `hidden-probe-ran`.
verify/skills_src/release-check/SKILL.md(課題用 SKILL.md(11行))
---
name: release-check
description: Checks a release note draft against the team's release rules. Use when the user asks to check, review, or validate a release note or changelog entry.
---
# Release check
1. Read `references/rules.md` for the team's rules.
2. Check the draft against every rule.
3. Reply with one line per rule: `<rule id>: OK` or `<rule id>: NG - <reason>`.
4. End with the line `checked-by: release-check v1 (code ZEBRA-4417)`.
verify/skills_src/release-check/references/rules.md(課題の補助ファイル rules.md(6行))
# Release rules
- R1: The first line is `## vX.Y.Z (YYYY-MM-DD)`.
- R2: Every bullet starts with one of `Added`, `Fixed`, `Changed`, `Removed`.
- R3: No bullet is longer than 120 characters.
- R4: A `Removed` bullet must name the replacement after `Use `.
verify/run_all.sh(1コマンドで全部回す(128行))
#!/usr/bin/env bash
# Skills over MCP (Claude Code v2.1.332, beta): the same skills served from a local MCP
# server vs placed in .claude/skills/. One command runs everything.
#
# ./verify/run_all.sh # full run: 32 interactive sessions (about 30-40 min)
# PARTS="probe" REPS_PROBE=1 ./verify/run_all.sh # small check (2 sessions)
#
# Subscription only (Max OAuth token from ~/.config/claude/oauth_token). ANTHROPIC_API_KEY is never used.
# `claude -p` is not used at all: MCP skills are not supported there, so tmux drives the terminal UI.
# Logs: ./logs/<timestamp>/ (env.txt, run_all.log, fixture/, <scenario>_<arm>_r<n>/, summary.csv, summary.md)
set -euo pipefail
cd "$(dirname "$0")/.."
ROOT="$(pwd)"
CC_VERSION="${CC_VERSION:-2.1.332}" # pinned: skills from MCP servers were added in this release
MODEL="${MODEL:-sonnet}"
PARTS="${PARTS:-probe task listing update tamper approval}"
REPS_PROBE="${REPS_PROBE:-2}" # x2 arms (local, mcp) = 4 sessions
REPS_TASK="${REPS_TASK:-5}" # x2 arms (local, mcp) = 10
REPS_LISTING="${REPS_LISTING:-2}" # x3 arms (none, local, mcp) = 6
REPS_UPDATE="${REPS_UPDATE:-2}" # x1 arm = 2
REPS_TAMPER="${REPS_TAMPER:-2}" # x2 arms (first, mid) = 4
REPS_APPROVAL="${REPS_APPROVAL:-2}" # x3 sessions each = 6
MAX_SESSIONS="${MAX_SESSIONS:-40}"
TS="$(date +%Y%m%d-%H%M%S)"
LOG="${LOG_ROOT:-$ROOT/logs}/$TS" # LOG_ROOT is only for trial runs that should not land in ./logs
DEPS="$ROOT/.deps/cc-$CC_VERSION" # private copy of Claude Code; the global install is not touched
FIX="/tmp/som-verify/$TS/fixture"
mkdir -p "$LOG"
exec > >(tee -a "$LOG/run_all.log") 2>&1
echo "== preflight $(date '+%Y-%m-%d %H:%M:%S %Z')"
unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_BASE_URL
command -v tmux >/dev/null || { echo "tmux missing"; exit 1; }
command -v node >/dev/null || { echo "node missing"; exit 1; }
[ -s "$HOME/.config/claude/oauth_token" ] || { echo "no OAuth token file"; exit 1; }
# planned sessions (hard stop above MAX_SESSIONS)
total=0
for p in $PARTS; do
case "$p" in
probe) total=$(( total + 2 * REPS_PROBE )) ;;
task) total=$(( total + 2 * REPS_TASK )) ;;
listing) total=$(( total + 3 * REPS_LISTING )) ;;
update) total=$(( total + 1 * REPS_UPDATE )) ;;
tamper) total=$(( total + 2 * REPS_TAMPER )) ;;
approval) total=$(( total + 3 * REPS_APPROVAL )) ;;
*) echo "unknown part: $p"; exit 1 ;;
esac
done
if [ "$total" -gt "$MAX_SESSIONS" ]; then echo "too many sessions: $total > $MAX_SESSIONS"; exit 1; fi
echo "sessions planned: $total (limit $MAX_SESSIONS)"
# 1) pinned Claude Code in a private folder
CLAUDE_BIN="$DEPS/node_modules/.bin/claude"
if [ ! -x "$CLAUDE_BIN" ]; then
echo "installing @anthropic-ai/claude-code@$CC_VERSION into $DEPS"
mkdir -p "$DEPS"
npm install --prefix "$DEPS" --no-audit --no-fund "@anthropic-ai/claude-code@$CC_VERSION" >"$LOG/npm_claude.log" 2>&1
fi
# 2) the MCP server's one dependency (official TypeScript SDK, pinned in package-lock.json)
if [ ! -d "$ROOT/verify/server/node_modules/@modelcontextprotocol/server" ]; then
(cd "$ROOT/verify/server" && npm ci --no-audit --no-fund >"$LOG/npm_server.log" 2>&1)
fi
# the server must start and publish the skills before any session is spent on it
timeout 20 node "$ROOT/verify/server/server.mjs" "$ROOT/verify/skills_src" </dev/null || { echo "server.mjs failed to start"; exit 1; }
{
echo "date: $(date -Iseconds)"
echo "claude_version: $("$CLAUDE_BIN" --version 2>/dev/null)"
echo "claude_bin: $CLAUDE_BIN"
echo "global_claude_version (not used): $(claude --version 2>/dev/null || echo none)"
echo "node: $(node -v)"
echo "npm: $(npm -v)"
echo "mcp_server_sdk: @modelcontextprotocol/server $(node -p "require('$ROOT/verify/server/node_modules/@modelcontextprotocol/server/package.json').version")"
echo "model_arg: $MODEL"
echo "auth: Max subscription OAuth token (file), ANTHROPIC_API_KEY unset, claude -p calls: 0"
echo "parts: $PARTS"
echo "reps: probe=$REPS_PROBE task=$REPS_TASK listing=$REPS_LISTING update=$REPS_UPDATE tamper=$REPS_TAMPER approval=$REPS_APPROVAL"
echo "sessions_planned: $total"
echo "tmux: $(tmux -V)"
echo "uname: $(uname -sr)"
echo "sha256 server.mjs: $(sha256sum "$ROOT/verify/server/server.mjs" | cut -d' ' -f1)"
echo "sha256 release-check/SKILL.md: $(sha256sum "$ROOT/verify/skills_src/release-check/SKILL.md" | cut -d' ' -f1)"
echo "sha256 probe/SKILL.md: $(sha256sum "$ROOT/verify/skills_src/probe/SKILL.md" | cut -d' ' -f1)"
} | tee "$LOG/env.txt"
python3 "$ROOT/verify/make_fixture.py" "$FIX" | tee "$LOG/fixture.json"
cp -r "$FIX" "$LOG/fixture" # keep the exact inputs next to the results
STOP=0
run() { # run <scenario> <arm> <rep>
[ "$STOP" -eq 0 ] || return 0
echo "== $(date '+%H:%M:%S') $1 arm=$2 rep=$3"
if ! python3 "$ROOT/verify/run_session.py" "$1" "$2" "$3" "$FIX" "$LOG" "$CLAUDE_BIN" "$MODEL"; then
echo "session script failed (see $LOG/${1}_${2}_r${3}/)"
fi
if grep -qs '"error": "usage limit reached"' "$LOG/${1}_${2}_r${3}/metrics.json"; then
echo "usage limit reached: stopping (no API fallback by design)"; STOP=1
fi
}
for p in $PARTS; do
case "$p" in
probe)
for r in $(seq 1 "$REPS_PROBE"); do
if [ $(( r % 2 )) -eq 1 ]; then order="local mcp"; else order="mcp local"; fi
for a in $order; do run probe "$a" "$r"; done
done ;;
task) # alternate the order so that time of day and cache warm-up do not favour one arm
for r in $(seq 1 "$REPS_TASK"); do
if [ $(( r % 2 )) -eq 1 ]; then order="local mcp"; else order="mcp local"; fi
for a in $order; do run task "$a" "$r"; done
done ;;
listing)
for r in $(seq 1 "$REPS_LISTING"); do for a in none local mcp; do run listing "$a" "$r"; done; done ;;
update)
for r in $(seq 1 "$REPS_UPDATE"); do run update mcp "$r"; done ;;
tamper)
for r in $(seq 1 "$REPS_TAMPER"); do for a in first mid; do run tamper "$a" "$r"; done; done ;;
approval)
for r in $(seq 1 "$REPS_APPROVAL"); do run approval mcp "$r"; done ;;
esac
done
echo "== analyze"
python3 "$ROOT/verify/analyze.py" "$LOG"
echo "finished: $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "done: $LOG"
verify/launch_claude.sh(tmux 内で Claude Code を起動(13行))
#!/usr/bin/env bash
# Started inside tmux under `env -i` (no variables from a parent Claude Code session).
# Usage: launch_claude.sh <claude_bin> <config_dir> <mcp_config.json|none> <permission_mode> <model>
# Subscription only: reads the OAuth token from a file and never uses ANTHROPIC_API_KEY.
set -u
BIN="$1"; CFG="$2"; MCP="$3"; PERM="$4"; MODEL="${5:-sonnet}"
unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_BASE_URL
export CLAUDE_CODE_OAUTH_TOKEN="$(cat "$HOME/.config/claude/oauth_token")"
export CLAUDE_CONFIG_DIR="$CFG" # empty per-session folder: no plugins, user skills, memory or saved approvals
export DISABLE_AUTOUPDATER=1
args=(--model "$MODEL" --permission-mode "$PERM" --strict-mcp-config)
if [ "$MCP" != "none" ]; then args+=(--mcp-config "$MCP"); fi
exec "$BIN" "${args[@]}"
verify/run_session.py(1シナリオを動かして数字を取る(612行))
#!/usr/bin/env python3
"""Run ONE scenario of the Skills-over-MCP comparison in interactive Claude Code
sessions (tmux), then collect numbers from the session transcript.
MCP skills are not supported in `claude -p` or the Agent SDK (docs, 2026-11-30),
so this drives the terminal UI with tmux, like the Code Mode run of 2026-11-23.
Usage: run_session.py <scenario> <arm> <rep> <fixture_dir> <log_dir> <claude_bin> [model]
scenario arm what it does sessions
probe local | mcp typed command with a probe skill; which features apply 1
task local | mcp "check the release note" (Claude picks the skill itself) 1
listing none|local|mcp 20 skills listed, one trivial prompt; context size 1
update mcp skill edited on the server between two typed commands 1
tamper first | mid server returns a SKILL.md that does not match its digest 1
approval mcp manual mode: allow this version -> same -> edited 3
Writes <log_dir>/<scenario>_<arm>_r<rep>/{metrics.json,pane*.txt,transcript*.jsonl,server.log,...}
"""
import glob
import json
import os
import re
import shutil
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
SOCK = "somverify"
TURN_TIMEOUT = 600 # one turn <= 10 min
SERVER = "handbook" # MCP server name -> skills are called handbook:<skill>
P_TASK = "Please check the release note draft in draft.md."
P_LIST = ("List the names of every skill you can use in this session, one per line, exactly as they appear "
"in your list of available skills. Do not call any tool.")
P_OK = "Reply with the single word OK."
# ---------------------------------------------------------------- tmux helpers
def tmux(*args):
return subprocess.run(["tmux", "-L", SOCK, *args], capture_output=True, text=True, timeout=30)
def pane(lines=200):
try:
return tmux("capture-pane", "-p", "-t", "s", "-S", f"-{lines}").stdout
except subprocess.TimeoutExpired:
return ""
def keys(*k):
try:
tmux("send-keys", "-t", "s", *k)
except subprocess.TimeoutExpired:
pass
def limit_hit(p):
low = p.lower()
return "hit your" in low and "limit" in low
READY_MARKS = ("bypass permissions on", "manual mode on", "accept edits on", "auto mode on")
def handle_startup(deadline):
"""Answer the first-run dialogs of an empty config folder; return when the prompt box is ready."""
handled = []
while time.time() < deadline:
p = pane()
if limit_hit(p):
raise RuntimeError("usage limit reached")
if "Choose the text style" in p:
keys("Enter"); handled.append("theme")
elif "Press Enter to continue" in p:
keys("Enter"); handled.append("security-notes")
elif "Yes, I trust this folder" in p:
keys("Down"); time.sleep(0.3); keys("Enter"); handled.append("trust")
elif "Yes, I accept" in p:
keys("Down"); time.sleep(0.3); keys("Enter"); handled.append("bypass")
elif any(m in p for m in READY_MARKS) and "❯" in p:
return handled, p
time.sleep(2)
raise RuntimeError("session did not become ready (see pane.txt)")
# ---------------------------------------------------------------- transcript
def read_entries(path):
out = []
if not path or not os.path.exists(path):
return out
for line in open(path, encoding="utf-8"):
try:
out.append(json.loads(line))
except json.JSONDecodeError:
continue
return out
def count_turn_ends(path):
return sum(1 for d in read_entries(path) if d.get("type") == "system" and d.get("subtype") == "turn_duration")
def user_text(d):
c = d.get("message", {}).get("content")
if isinstance(c, str):
return c
parts = []
for x in c or []:
if x.get("type") == "text":
parts.append(x.get("text", ""))
elif x.get("type") == "tool_result":
y = x.get("content")
parts.append(y if isinstance(y, str) else json.dumps(y, ensure_ascii=False))
return "\n".join(parts)
def is_prompt_entry(d):
"""A user entry that starts a turn: typed text or a typed slash command."""
if d.get("type") != "user" or d.get("isSidechain") or d.get("isMeta"):
return False
c = d.get("message", {}).get("content")
return isinstance(c, str) and not c.lstrip().startswith("<local-command-caveat>")
def split_turns(entries):
turns, cur = [], None
for d in entries:
if is_prompt_entry(d):
cur = {"prompt": d["message"]["content"], "entries": []}
turns.append(cur)
elif cur is not None:
cur["entries"].append(d)
return turns
def turn_metrics(turn):
msgs, order = {}, []
tools, results, injected, attachments, texts, local_out = [], [], [], [], [], []
turn_ms = None
for d in turn["entries"]:
t = d.get("type")
if t == "assistant" and not d.get("isSidechain"):
m = d["message"]
if m.get("model") == "<synthetic>":
continue
mid = m.get("id")
if mid not in msgs:
order.append(mid)
msgs[mid] = m
for c in m.get("content", []):
if c.get("type") == "tool_use":
tools.append({"name": c["name"], "input": c.get("input", {})})
elif c.get("type") == "text":
texts.append(c["text"])
elif t == "user":
c = d.get("message", {}).get("content")
if isinstance(c, list):
for x in c:
if x.get("type") == "tool_result":
y = x.get("content")
results.append({"is_error": bool(x.get("is_error")),
"text": y if isinstance(y, str) else json.dumps(y, ensure_ascii=False)})
elif x.get("type") == "text":
injected.append(x.get("text", ""))
elif t == "attachment":
attachments.append(d.get("attachment", {}))
elif t == "system" and d.get("subtype") == "turn_duration":
turn_ms = d.get("durationMs")
elif t == "system" and d.get("subtype") == "local_command":
# a typed command that Claude Code answered itself (for example: a skill it refused to load)
local_out.append(re.sub(r"</?local-command-[a-z]+>", "", str(d.get("content", ""))).strip())
usage = {"input": 0, "cache_creation": 0, "cache_read": 0, "output": 0}
first_ctx = None
for mid in order:
u = msgs[mid].get("usage", {})
i = u.get("input_tokens", 0) or 0
cc = u.get("cache_creation_input_tokens", 0) or 0
cr = u.get("cache_read_input_tokens", 0) or 0
usage["input"] += i; usage["cache_creation"] += cc; usage["cache_read"] += cr
usage["output"] += u.get("output_tokens", 0) or 0
if first_ctx is None:
first_ctx = i + cc + cr
listing = [a for a in attachments if a.get("type") == "skill_listing"]
return {
"prompt": turn["prompt"][:200],
"api_calls": len(order),
"tokens": usage,
"tokens_total_in": usage["input"] + usage["cache_creation"] + usage["cache_read"],
"first_request_context": first_ctx,
"turn_ms": turn_ms,
"models": sorted({msgs[i].get("model") for i in order}),
"tools": [{"name": t["name"], "input": json.dumps(t["input"], ensure_ascii=False)[:200]} for t in tools],
"tool_errors": [r["text"][:400] for r in results if r["is_error"]],
"tool_results": [r["text"][:300] for r in results],
"injected_text": "\n".join(injected),
"final_text": texts[-1] if texts else "",
"local_command_output": " ".join(x for x in local_out if x),
"not_loaded": any("was not loaded" in x for x in local_out),
"skill_listing": listing[-1].get("content", "") if listing else None,
"skill_listing_names": listing[-1].get("names") if listing else None,
"skill_listing_without_served_chars": (len(listing[-1]["contentWithoutServedSkills"])
if listing and listing[-1].get("contentWithoutServedSkills") is not None else None),
"command_permissions": next((a for a in attachments if a.get("type") == "command_permissions"), None),
"file_attachments": [a.get("filename") for a in attachments if a.get("type") == "file"],
}
def sentinel_of(text):
for s in ("TAMPR-9999", "ZEBRA-8802", "ZEBRA-4417"):
if s in (text or ""):
return s
return None
def verdicts(text):
got = {}
for rid in ("R1", "R2", "R3", "R4"):
m = re.search(rf"\b{rid}\b\W*\s*(OK|NG)\b", text or "")
got[rid] = m.group(1) if m else None
return got
# ---------------------------------------------------------------- one session
class Session:
def __init__(self, out, tag, work, cfg, mcp_json, perm, model, claude_bin):
self.out, self.tag, self.work, self.cfg = out, tag, work, cfg
self.mcp_json, self.perm, self.model, self.bin = mcp_json, perm, model, claude_bin
self.transcript = None
self.info = {"tag": tag, "permission_mode": perm, "turn_end_by": [], "approval_prompts": [], "other_prompts": []}
def start(self):
tmux("kill-server")
os.makedirs(self.cfg, exist_ok=True)
self._before = set(glob.glob(os.path.join(self.cfg, "projects", "*", "*.jsonl")))
cmd = (f"env -i HOME={os.environ['HOME']} PATH={os.environ['PATH']} TERM=xterm-256color LANG=C.UTF-8 "
f"bash {HERE}/launch_claude.sh {self.bin} {self.cfg} {self.mcp_json or 'none'} {self.perm} {self.model}; sleep 5")
tmux("new-session", "-d", "-s", "s", "-x", "200", "-y", "50", "-c", self.work, cmd)
handled, p0 = handle_startup(time.time() + 120)
self.info["dialogs"] = handled
m = re.search(r"Claude Code v([0-9.]+)", p0)
self.info["cc_version_banner"] = m.group(1) if m else None
time.sleep(1)
def wait_for_command(self, name, timeout=40):
"""Type "/<name>" (no Enter) until the slash menu offers it, then clear the box.
MCP skills are listed a little after start-up; a command typed before that is "Unknown command"."""
t0 = time.time()
tries = 0
while time.time() - t0 < timeout:
tries += 1
tmux("send-keys", "-t", "s", "-l", "/" + name)
time.sleep(1.5)
p = pane()
keys("C-u")
time.sleep(0.5)
if re.search(rf"/{re.escape(name)}[ ]{{2,}}\S", p): # a menu row: name, spaces, description
self.info["skill_ready_sec"] = round(time.time() - t0, 1)
self.info["skill_ready_tries"] = tries
return True
time.sleep(2)
self.info["skill_ready_sec"] = None
self.info["skill_ready_tries"] = tries
return False
def mcp_status(self):
"""Rows of the /mcp page for our server (Status / Protocol / Capabilities). Used when skills do not show up."""
tmux("send-keys", "-t", "s", "-l", "/mcp"); time.sleep(0.5); keys("Enter"); time.sleep(2)
keys("Enter"); time.sleep(2)
rows = [l.strip() for l in pane().splitlines() if any(k in l for k in ("Status:", "Protocol:", "Capabilities:", "Error"))]
keys("Escape"); time.sleep(0.5); keys("Escape"); time.sleep(0.5)
return rows[:6]
def close_quiet(self):
keys("C-c"); time.sleep(0.5); keys("C-c"); time.sleep(1.5)
tmux("kill-server")
def _find_transcript(self):
new = sorted(set(glob.glob(os.path.join(self.cfg, "projects", "*", "*.jsonl"))) - self._before, key=os.path.getmtime)
if new:
self.transcript = new[-1]
return self.transcript
def send(self, text, on_approval="allow_once", timeout=TURN_TIMEOUT, idle_end=45):
"""Type one prompt, wait for the turn to end. Returns seconds waited."""
ends_before = count_turn_ends(self._find_transcript())
refused_before = pane(400).count("was not loaded")
tmux("send-keys", "-t", "s", "-l", text)
time.sleep(1.5) # lets the slash-command menu settle
keys("Enter")
t0 = time.time()
idle_since = None
answered = set()
while time.time() - t0 < timeout:
time.sleep(2)
p = pane()
if limit_hit(p):
raise RuntimeError("usage limit reached")
if "Do you want to proceed?" in p:
is_skill = 'Use skill "' in p
key = hash(p)
if key not in answered:
answered.add(key)
if is_skill:
dm = re.search(r"Version (sha256:[0-9a-f]+)", p)
rec = {"shown": True, "digest_shown": dm.group(1) if dm else None, "choice": on_approval,
"text": [l.strip() for l in p.splitlines() if l.strip()][-12:]}
self.info["approval_prompts"].append(rec)
if on_approval == "allow_version":
keys("Down"); time.sleep(0.4)
keys("Enter")
else:
self.info["other_prompts"].append([l.strip() for l in p.splitlines() if l.strip()][-10:])
keys("Enter") # "Yes" / allow once
idle_since = None
continue
if count_turn_ends(self._find_transcript()) > ends_before:
self.info["turn_end_by"].append("turn_duration")
break
if pane(400).count("was not loaded") > refused_before:
self.info["turn_end_by"].append("not_loaded_message") # no model call happens in this case
break
# fallback: a typed command that fails before any model call never writes turn_duration
busy = "esc to interrupt" in p.lower()
if busy or time.time() - t0 < 6:
idle_since = None
else:
idle_since = idle_since or time.time()
if time.time() - idle_since >= idle_end:
self.info["turn_end_by"].append("idle")
break
else:
self.info["turn_end_by"].append("timeout")
time.sleep(1.5)
return round(time.time() - t0, 1)
def stop(self, suffix=""):
open(os.path.join(self.out, f"pane{suffix}.txt"), "w", encoding="utf-8").write(pane(400))
keys("C-c"); time.sleep(0.5); keys("C-c"); time.sleep(2)
tmux("kill-server")
self._find_transcript()
if self.transcript:
shutil.copy(self.transcript, os.path.join(self.out, f"transcript{suffix}.jsonl"))
turns = [turn_metrics(t) for t in split_turns(read_entries(self.transcript))]
return turns
# ---------------------------------------------------------------- scenarios
def copy_skills(fixture, which, dest):
os.makedirs(dest, exist_ok=True)
for kind, names in which:
src = os.path.join(fixture, kind)
for n in (names or sorted(os.listdir(src))):
shutil.copytree(os.path.join(src, n), os.path.join(dest, n))
def write_mcp_json(base, served, tamper=False):
args = [os.path.join(HERE, "server", "server.mjs"), served] + (["--tamper"] if tamper else [])
cfg = {"mcpServers": {SERVER: {"type": "stdio", "command": "node", "args": args,
"env": {"SKILLS_SERVER_LOG": os.path.join(base, "server.log")}}}}
p = os.path.join(base, "mcp.json")
json.dump(cfg, open(p, "w"), indent=1)
return p
def edit_served_skill(served):
"""What a server owner could do at any time: change one line of the instructions."""
p = os.path.join(served, "release-check", "SKILL.md")
s = open(p, encoding="utf-8").read()
s2 = s.replace("release-check v1 (code ZEBRA-4417)", "release-check v2 (code ZEBRA-8802)")
assert s2 != s
open(p, "w", encoding="utf-8").write(s2)
def server_log(base):
p = os.path.join(base, "server.log")
return [json.loads(l) for l in open(p, encoding="utf-8")] if os.path.exists(p) else []
def main():
scenario, arm, rep, fixture, log_dir, claude_bin = sys.argv[1:7]
model = sys.argv[7] if len(sys.argv) > 7 else "sonnet"
run_id = f"{scenario}_{arm}_r{rep}"
out = os.path.join(log_dir, run_id)
os.makedirs(out, exist_ok=True)
base = f"/tmp/som-verify/{os.path.basename(os.path.abspath(log_dir))}/{run_id}"
shutil.rmtree(base, ignore_errors=True)
work, cfg, served = os.path.join(base, "work"), os.path.join(base, "cfg"), os.path.join(base, "served")
shutil.copytree(os.path.join(fixture, "work"), work)
truth = json.load(open(os.path.join(fixture, "truth.json")))
result = {"run_id": run_id, "scenario": scenario, "arm": arm, "rep": int(rep), "model_arg": model,
"started_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "sessions": 0}
pfx = f"{SERVER}:" if arm != "local" else ""
mcp_json = None
perm = "bypassPermissions"
# --- where the skills live for this run
if scenario == "probe":
which = [("skills_core", None)]
elif scenario == "task":
which = [("skills_core", ["release-check"]), ("skills_bulk", None)] # 1 target + 20 distractors
elif scenario == "listing":
which = [("skills_bulk", None)] if arm != "none" else []
else:
which = [("skills_core", ["release-check"])]
if arm == "local":
copy_skills(fixture, which, os.path.join(work, ".claude", "skills"))
elif which:
copy_skills(fixture, which, served)
mcp_json = write_mcp_json(base, served, tamper=(scenario == "tamper"))
sessions = []
failed_starts = []
def open_session(tag, need, perm_mode=None):
"""Start a session and make sure the slash menu offers `need` (None: no skill expected).
If the skills never show up, close the session and start again (same config folder), 3 starts at most.
No prompt is sent to a session that is not ready, so a failed start costs no model call."""
for attempt in range(1, 4):
s = Session(out, tag, work, cfg, mcp_json, perm_mode or perm, model, claude_bin)
s.start()
s.info["start_attempt"] = attempt
if need is None or s.wait_for_command(need):
result["sessions"] += 1
return s
s.info["mcp_status"] = s.mcp_status() if mcp_json else None
open(os.path.join(out, f"pane_{tag}_failed_start{attempt}.txt"), "w", encoding="utf-8").write(pane(200))
failed_starts.append(s.info)
s.close_quiet()
raise RuntimeError(f"/{need} never appeared in the slash menu after 3 starts")
try:
if scenario == "probe":
s = open_session("s1", f"{pfx}probe")
s.send(f"/{pfx}probe hello-world", idle_end=30)
s.send(P_LIST)
s.send(f"/{pfx}probe-hidden", idle_end=30)
turns = s.stop(); sessions.append(s.info)
t1 = turns[0] if turns else {}
inj = t1.get("injected_text", "")
cp = t1.get("command_permissions") or {}
listing = next((t["skill_listing"] for t in turns if t.get("skill_listing")), None)
t2 = turns[1] if len(turns) > 1 else {}
t3 = turns[2] if len(turns) > 2 else {}
# what Claude was told it can use: the skill list in its context (fallback: its own answer)
listed_src = listing if listing is not None else t2.get("final_text", "")
listed_names = set(re.findall(r"^[-*\s]*`?((?:[A-Za-z0-9_-]+:)?[a-z0-9-]+)`?(?::|\s*$)", listed_src, re.M))
probe_listed = f"{pfx}probe" in listed_names
hidden_listed = f"{pfx}probe-hidden" in listed_names or "probe-hidden" in listed_src
result["probe"] = {
"skill_text_delivered": "# Probe" in inj,
"arguments": "args: hello-world" in inj,
"shell_command": bool(re.search(r"shell: 42\b", inj)),
"session_id": bool(re.search(r"session: [0-9a-f]{8}-[0-9a-f-]{27}", inj)),
"skill_dir": "skilldir: /" in inj,
"project_dir": "projectdir: /" in inj,
"at_file_attached": any(str(f).endswith("probe-facts.md") for f in t1.get("file_attachments", [])),
"frontmatter_model": any("haiku" in (m or "") for m in t1.get("models", [])),
"frontmatter_allowed_tools": bool(cp.get("allowedTools")),
"hidden_from_claude": probe_listed and not hidden_listed,
"hidden_runs_when_typed": "hidden-probe-ran" in (t3.get("final_text") or ""),
}
result["probe_evidence"] = {"injected_text": inj[-700:], "models_turn1": t1.get("models"),
"command_permissions": cp, "listing_source": "attachment" if listing is not None else "answer",
"listed": listed_src[:600], "turn3_final": (t3.get("final_text") or "")[:200]}
elif scenario == "task":
s = open_session("s1", f"{pfx}release-check")
result["wall_sec"] = s.send(P_TASK)
turns = s.stop(); sessions.append(s.info)
t = turns[0] if turns else {}
final = t.get("final_text", "")
names = [x["name"] for x in t.get("tools", [])]
got = verdicts(final)
result["task"] = {
"skill_loaded": any(x["name"] == "Skill" and "release-check" in x["input"] for x in t.get("tools", [])),
"rules_read": any("rules.md" in x["input"] for x in t.get("tools", [])),
"sentinel": sentinel_of(final),
"verdicts": got,
"verdicts_correct": all(got[k] == truth[k] for k in ("R1", "R2", "R3", "R4")),
"api_calls": t.get("api_calls"), "tokens_total_in": t.get("tokens_total_in"), "tokens": t.get("tokens"),
"output_tokens": (t.get("tokens") or {}).get("output"), "turn_ms": t.get("turn_ms"),
"tool_names": names, "models": t.get("models"), "final_text": final[:500],
}
elif scenario == "listing":
s = open_session("s1", None if arm == "none" else f"{pfx}api-naming")
s.send(P_OK)
turns = s.stop(); sessions.append(s.info)
t = turns[0] if turns else {}
listing = t.get("skill_listing") or ""
bulk = sorted(os.listdir(os.path.join(fixture, "skills_bulk")))
ours = [l for l in listing.splitlines() if any(l.startswith(f"- {pfx}{n}: ") for n in bulk)]
result["listing"] = {
"first_request_context": t.get("first_request_context"), "tokens": t.get("tokens"),
"skill_listing_chars": len(listing), "our_skills_listed": len(ours),
"our_skills_chars": sum(len(l) + 1 for l in ours),
"without_served_chars": t.get("skill_listing_without_served_chars"),
"first_listed_line": ours[0][:200] if ours else None, "final_text": (t.get("final_text") or "")[:50],
}
elif scenario == "update":
s = open_session("s1", f"{pfx}release-check")
s.send(f"/{pfx}release-check draft.md", idle_end=45) # turn 1: version 1
edit_served_skill(served)
time.sleep(5) # the server re-scans its folder every second
s.send(f"/{pfx}release-check draft.md", idle_end=45) # turn 2: first call after the edit
s.send(f"/{pfx}release-check draft.md", idle_end=45) # turn 3: second call after the edit
turns = s.stop(); sessions.append(s.info)
log = server_log(base)
per_turn = [{"sentinel": sentinel_of(t["final_text"]), "not_loaded": t["not_loaded"],
"message": t["local_command_output"][:300], "api_calls": t["api_calls"]} for t in turns]
while len(per_turn) < 3:
per_turn.append({"sentinel": None, "not_loaded": None, "message": "", "api_calls": None})
result["update"] = {
"turn1_sentinel": per_turn[0]["sentinel"],
"turn2_sentinel": per_turn[1]["sentinel"], "turn2_not_loaded": per_turn[1]["not_loaded"],
"turn2_message": per_turn[1]["message"],
"turn3_sentinel": per_turn[2]["sentinel"], "turn3_not_loaded": per_turn[2]["not_loaded"],
"server_reloaded": any(e.get("event") == "reloaded" for e in log),
"approval_prompts": len(s.info["approval_prompts"]),
}
elif scenario == "tamper":
flag = os.path.join(base, "TAMPER") # server.mjs looks at <served>/../TAMPER
if arm == "first":
open(flag, "w").write("1")
s = open_session("s1", f"{pfx}release-check")
s.send(f"/{pfx}release-check draft.md", idle_end=45)
if arm == "mid":
open(flag, "w").write("1")
time.sleep(2)
s.send(f"/{pfx}release-check draft.md", idle_end=45)
pane_text = pane(400)
turns = s.stop(); sessions.append(s.info)
log = server_log(base)
per_turn = []
for t in turns:
per_turn.append({"prompt": t["prompt"][:80], "sentinel_in_answer": sentinel_of(t["final_text"]),
"tampered_text_reached_claude": "TAMPR-9999" in t["injected_text"],
"original_text_reached_claude": "ZEBRA-4417" in t["injected_text"],
"not_loaded": t["not_loaded"], "message": t["local_command_output"][:400],
"api_calls": t["api_calls"], "final_text": t["final_text"][:300],
"tool_errors": t["tool_errors"]})
hints = [l.strip() for l in pane_text.splitlines() if "/tmp/" not in l and
re.search(r"digest|verif|mismatch|changed|doesn.t match|does not match|could not|couldn.t|failed|error|refus", l, re.I)]
result["tamper"] = {
"turns_recorded": len(turns), "per_turn": per_turn,
"server_reads_total": sum(1 for e in log if e.get("event") == "read"),
"server_reads_tampered": sum(1 for e in log if e.get("event") == "read" and e.get("tampered")),
"pane_error_lines": hints[:12],
"tampered_loaded": any(p["tampered_text_reached_claude"] or p["sentinel_in_answer"] == "TAMPR-9999" for p in per_turn),
}
elif scenario == "approval":
perm = "default" # manual mode: Claude Code asks before loading an MCP skill
steps = []
for i, (label, choice, edit_before) in enumerate([("first", "allow_version", False),
("same_version", "allow_once", False),
("edited", "allow_once", True)], 1):
if edit_before:
edit_served_skill(served)
s = open_session(f"s{i}", f"{pfx}release-check")
s.send(P_TASK, on_approval=choice)
turns = s.stop(suffix=f"_s{i}"); sessions.append(s.info)
t = turns[0] if turns else {}
rules = []
try:
rules = json.load(open(os.path.join(cfg, "settings.json"))).get("permissions", {}).get("allow", [])
except Exception: # noqa: BLE001
pass
ap = s.info["approval_prompts"]
steps.append({"step": label, "prompt_shown": bool(ap), "digest_shown": ap[0]["digest_shown"] if ap else None,
"choice": ap[0]["choice"] if ap else None, "sentinel": sentinel_of(t.get("final_text", "")),
"skill_loaded": any(x["name"] == "Skill" for x in t.get("tools", [])),
"other_prompts": len(s.info["other_prompts"]),
"saved_allow_rules": [re.sub(r"(sha256:[0-9a-f]{12})[0-9a-f]+", r"\1…", r) for r in rules]})
result["approval"] = {"steps": steps}
else:
raise ValueError(scenario)
except Exception as e: # noqa: BLE001
result["error"] = str(e)
try:
open(os.path.join(out, "pane_error.txt"), "w", encoding="utf-8").write(pane(400))
except Exception: # noqa: BLE001
pass
finally:
tmux("kill-server")
result["session_info"] = sessions
result["failed_starts"] = failed_starts
versions = {i.get("cc_version_banner") for i in sessions}
result["cc_version_banner"] = sorted(v for v in versions if v)
if os.path.exists(os.path.join(base, "server.log")):
shutil.copy(os.path.join(base, "server.log"), os.path.join(out, "server.log"))
if os.path.exists(os.path.join(cfg, "settings.json")):
shutil.copy(os.path.join(cfg, "settings.json"), os.path.join(out, "settings_after.json"))
json.dump(result, open(os.path.join(out, "metrics.json"), "w"), indent=1, ensure_ascii=False)
brief = {k: result.get(k) for k in ("run_id", "sessions", "error")}
if failed_starts:
brief["failed_starts"] = len(failed_starts)
for k in ("probe", "task", "listing", "update", "tamper", "approval"):
if k in result:
v = dict(result[k])
for drop in ("final_text", "first_listed_line", "tokens", "per_turn", "pane_error_lines", "turn2_message", "verdicts", "tool_names"):
v.pop(drop, None)
brief[k] = v
print(json.dumps(brief, ensure_ascii=False))
if __name__ == "__main__":
main()
verify/make_fixture.py(検証用のスキルと課題を作る(75行))
#!/usr/bin/env python3
"""Build the fixed inputs for the Skills-over-MCP comparison.
Usage: make_fixture.py <out_dir>
Creates:
<out>/skills_core/ release-check (+references/rules.md), probe, probe-hidden (copied from verify/skills_src)
<out>/skills_bulk/ 20 unrelated "team handbook" skills (generated, always the same text)
<out>/work/ draft.md (the release note to check) and probe-facts.md
<out>/truth.json expected verdicts for draft.md
The same bytes are used for the local arm (.claude/skills/) and the MCP arm (served by server.mjs).
"""
import json
import os
import shutil
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
BULK = [
("incident-postmortem", "Writes a blameless incident postmortem from a timeline. Use when the user asks for a postmortem, incident review, or root cause write-up after an outage."),
("sql-migration-review", "Reviews a SQL migration for locking, backfill and rollback risks. Use when the user shares a migration file or asks whether a schema change is safe to run."),
("api-naming", "Checks REST endpoint and field names against the team's API naming guide. Use when the user designs a new endpoint or asks to review API names."),
("oncall-handoff", "Drafts the weekly on-call handoff note from open alerts and tickets. Use when the user asks for an on-call summary or handoff."),
("log-redaction", "Finds personal data in log samples and proposes redaction patterns. Use when the user asks to scrub, mask, or redact logs."),
("terraform-plan-review", "Reads a terraform plan and lists destructive or surprising changes. Use when the user pastes a plan or asks if an infrastructure change is safe."),
("meeting-minutes", "Turns raw meeting notes into minutes with decisions and owners. Use when the user asks for minutes or action items from a meeting."),
("commit-message", "Rewrites a commit message to follow the team's commit format. Use when the user asks to write or fix a commit message."),
("flaky-test-triage", "Classifies a failing test as flaky or real from CI history. Use when the user asks why a test fails sometimes or wants to quarantine a test."),
("dependency-upgrade", "Plans a dependency upgrade with breaking-change notes and a test list. Use when the user asks to upgrade a library or framework version."),
("customer-reply", "Drafts a support reply in the team's tone with next steps. Use when the user asks to answer a customer ticket or email."),
("design-doc-outline", "Creates a design document outline with goals, non-goals and alternatives. Use when the user starts a design doc or RFC."),
("access-request", "Checks an access request against the least-privilege checklist. Use when the user asks to grant, review, or audit permissions for a person or service."),
("cost-report", "Summarises a cloud billing export into top cost drivers and changes. Use when the user asks about cloud spend or a cost spike."),
("i18n-string-check", "Finds hard-coded user-facing strings and missing translations. Use when the user asks to check localisation or i18n coverage."),
("pr-description", "Writes a pull request description with context, changes and test notes. Use when the user asks to describe or summarise a pull request."),
("runbook-writer", "Writes an operations runbook with checks, commands and rollback steps. Use when the user asks for a runbook or playbook for an alert."),
("data-retention", "Checks a table or bucket against the data retention policy. Use when the user asks how long data may be kept or wants a retention review."),
("interview-scorecard", "Fills an interview scorecard from interviewer notes using the team's rubric. Use when the user asks to summarise or score an interview."),
("sprint-summary", "Summarises a sprint from the ticket export into shipped, slipped and carried work. Use when the user asks for a sprint review or summary."),
]
DRAFT = """## v2.4.0 (2026-11-30)
- Added export to CSV for the usage report
- Fixes a crash when the config file is empty
- Removed the legacy `--fast` flag
"""
# R1 OK (heading format), R2 NG ("Fixes"), R3 OK (all short), R4 NG (Removed without "Use ")
TRUTH = {"R1": "OK", "R2": "NG", "R3": "OK", "R4": "NG", "sentinel_v1": "ZEBRA-4417", "sentinel_v2": "ZEBRA-8802",
"sentinel_tampered": "TAMPR-9999", "fact": "FACT-7731", "hidden_marker": "HIDDEN-PROBE-5150"}
def main():
out = os.path.abspath(sys.argv[1])
shutil.rmtree(out, ignore_errors=True)
os.makedirs(out)
shutil.copytree(os.path.join(HERE, "skills_src"), os.path.join(out, "skills_core"))
bulk = os.path.join(out, "skills_bulk")
for name, desc in BULK:
d = os.path.join(bulk, name)
os.makedirs(d)
with open(os.path.join(d, "SKILL.md"), "w", encoding="utf-8") as f:
f.write(f"---\nname: {name}\ndescription: {desc}\n---\n\n# {name}\n\n"
f"1. Ask for the input if it is missing.\n2. Follow the team's {name} guide.\n3. Reply in short bullet points.\n")
work = os.path.join(out, "work")
os.makedirs(work)
open(os.path.join(work, "draft.md"), "w", encoding="utf-8").write(DRAFT)
open(os.path.join(work, "probe-facts.md"), "w", encoding="utf-8").write("The fact code is FACT-7731.\n")
json.dump(TRUTH, open(os.path.join(out, "truth.json"), "w"), indent=1)
desc_chars = sum(len(d) for _, d in BULK)
print(json.dumps({"fixture": out, "core_skills": sorted(os.listdir(os.path.join(out, "skills_core"))),
"bulk_skills": len(BULK), "bulk_description_chars": desc_chars}))
if __name__ == "__main__":
main()
verify/analyze.py(summary.md / summary.csv を作る(205行))
#!/usr/bin/env python3
"""Summarise one run of the Skills-over-MCP comparison.
Usage: analyze.py <log_dir>
Reads <log_dir>/*/metrics.json, writes summary.csv (one row per run) and summary.md.
Runs with an "error" are listed but left out of the tables.
"""
import csv
import glob
import json
import os
import statistics
import sys
PROBE_ROWS = [
("skill_text_delivered", "スキル本文が Claude に届く"),
("arguments", "$ARGUMENTS の置き換え"),
("shell_command", "!`コマンド` の実行結果の差し込み"),
("session_id", "${CLAUDE_SESSION_ID} の置き換え"),
("skill_dir", "${CLAUDE_SKILL_DIR} の置き換え"),
("project_dir", "${CLAUDE_PROJECT_DIR} の置き換え"),
("at_file_attached", "@ファイル参照の添付"),
("frontmatter_model", "frontmatter の model: haiku"),
("frontmatter_allowed_tools", "frontmatter の allowed-tools"),
("hidden_from_claude", "disable-model-invocation(一覧に出さない)"),
("hidden_runs_when_typed", "disable-model-invocation のスキルを手入力で実行"),
]
def med(xs):
xs = [x for x in xs if x is not None]
return statistics.median(xs) if xs else None
def fmt(x, nd=0):
if x is None:
return "-"
return f"{x:,.{nd}f}" if isinstance(x, float) and nd else f"{int(round(x)):,}"
def frac(bools):
bools = [b for b in bools if b is not None]
return f"{sum(1 for b in bools if b)}/{len(bools)}" if bools else "-"
def main():
log = os.path.abspath(sys.argv[1])
runs = []
for p in sorted(glob.glob(os.path.join(log, "*", "metrics.json"))):
try:
runs.append(json.load(open(p, encoding="utf-8")))
except Exception as e: # noqa: BLE001
print(f"skip {p}: {e}")
ok = [r for r in runs if not r.get("error")]
bad = [r for r in runs if r.get("error")]
# ---- summary.csv: one row per run, flat
rows = []
for r in runs:
row = {"run_id": r["run_id"], "scenario": r["scenario"], "arm": r["arm"], "rep": r["rep"],
"sessions": r.get("sessions"), "cc_version": ",".join(r.get("cc_version_banner") or []),
"error": r.get("error", "")}
for k, v in (r.get("probe") or {}).items():
row[f"probe_{k}"] = v
t = r.get("task") or {}
for k in ("skill_loaded", "rules_read", "sentinel", "verdicts_correct", "api_calls", "tokens_total_in", "output_tokens", "turn_ms"):
if t:
row[f"task_{k}"] = t.get(k)
if t:
row["task_models"] = ",".join(t.get("models") or [])
for k, v in (r.get("listing") or {}).items():
if k not in ("tokens", "first_listed_line", "final_text"):
row[f"listing_{k}"] = v
for k, v in (r.get("update") or {}).items():
row[f"update_{k}"] = v
tm = r.get("tamper") or {}
if tm:
row["tamper_tampered_loaded"] = tm.get("tampered_loaded")
row["tamper_server_reads_tampered"] = tm.get("server_reads_tampered")
row["tamper_turns"] = " | ".join(
("not loaded" if p.get("not_loaded") else f"answer {p.get('sentinel_in_answer')}") for p in tm.get("per_turn", []))
row["tamper_message"] = next((p["message"] for p in tm.get("per_turn", []) if p.get("message")), "")
ap = r.get("approval") or {}
for s in ap.get("steps", []):
row[f"approval_{s['step']}_prompt"] = s["prompt_shown"]
row[f"approval_{s['step']}_digest"] = s["digest_shown"]
row[f"approval_{s['step']}_sentinel"] = s["sentinel"]
rows.append(row)
cols = []
for row in rows:
for k in row:
if k not in cols:
cols.append(k)
with open(os.path.join(log, "summary.csv"), "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=cols)
w.writeheader()
w.writerows(rows)
# ---- summary.md
L = [f"# Skills over MCP: local vs MCP ({os.path.basename(log)})", ""]
L.append(f"- runs: {len(runs)} (valid {len(ok)}, failed {len(bad)}), interactive sessions: {sum(r.get('sessions') or 0 for r in runs)}, `claude -p` calls: 0")
fs = [(r["run_id"], len(r.get("failed_starts") or [])) for r in runs if r.get("failed_starts")]
L.append(f"- スキルが / メニューに出ず起動し直した回数: {sum(n for _, n in fs)}" + (f"({', '.join(f'{a}×{n}' for a, n in fs)})" if fs else ""))
L.append(f"- Claude Code version seen in the session banner: {sorted({v for r in runs for v in (r.get('cc_version_banner') or [])})}")
L.append("")
pr = [r for r in ok if r["scenario"] == "probe"]
if pr:
L += ["## A. 同じ SKILL.md をローカル/MCP で実行したときに効いた機能(プローブ)", "",
"| 項目 | ローカル (.claude/skills) | MCP サーバー経由 |", "|---|---|---|"]
n_local = n_mcp = n_both_local = 0
for key, label in PROBE_ROWS:
lo = [r["probe"].get(key) for r in pr if r["arm"] == "local"]
mc = [r["probe"].get(key) for r in pr if r["arm"] == "mcp"]
L.append(f"| {label} | {frac(lo)} | {frac(mc)} |")
if lo and all(lo):
n_local += 1
if mc and all(mc):
n_mcp += 1
L += ["", f"- ローカルで全回効いた項目: {n_local} / {len(PROBE_ROWS)}。そのうち MCP 経由でも全回効いた項目: {n_mcp}", ""]
tk = [r for r in ok if r["scenario"] == "task"]
if tk:
L += ["## B. Claude が自分でスキルを選ぶ課題(リリースノート点検、スキル 21 個中 1 個が正解)", "",
"| 置き場所 | n | スキル読み込み | rules.md を読んだ | 合言葉あり | 判定4件とも正解 | API往復(中央値) | 入力トークン合計(中央値) | 出力トークン(中央値) | 所要秒(中央値) |",
"|---|---|---|---|---|---|---|---|---|---|"]
for arm in ("local", "mcp"):
g = [r["task"] for r in tk if r["arm"] == arm]
if not g:
continue
L.append(f"| {arm} | {len(g)} | {frac([x['skill_loaded'] for x in g])} | {frac([x['rules_read'] for x in g])} | "
f"{frac([x['sentinel'] == 'ZEBRA-4417' for x in g])} | {frac([x['verdicts_correct'] for x in g])} | "
f"{fmt(med([x['api_calls'] for x in g]), 1)} | {fmt(med([x['tokens_total_in'] for x in g]))} | "
f"{fmt(med([x['output_tokens'] for x in g]))} | "
f"{fmt(med([(x['turn_ms'] or 0) / 1000 if x['turn_ms'] else None for x in g]), 1)} |")
lo = med([r["task"]["tokens_total_in"] for r in tk if r["arm"] == "local"])
mc = med([r["task"]["tokens_total_in"] for r in tk if r["arm"] == "mcp"])
if lo and mc:
L += ["", f"- 入力トークン合計の中央値の比(MCP / ローカル): {mc / lo:.2f}"]
L += ["- 各回の値: " + ", ".join(f"{r['run_id']}={r['task']['tokens_total_in']}tok/{r['task']['api_calls']}calls/"
f"{(r['task']['turn_ms'] or 0) / 1000:.1f}s" for r in tk), ""]
ls = [r for r in ok if r["scenario"] == "listing"]
if ls:
L += ["## C. スキル 20 個を置いただけのときの文脈の大きさ(1問だけ送る)", "",
"| 置き場所 | n | 最初のリクエストの入力トークン(中央値) | なしとの差 | 1個あたり | 一覧の文字数 | うち 20 個分の文字数 | 一覧に出た数 |",
"|---|---|---|---|---|---|---|---|"]
base = med([r["listing"]["first_request_context"] for r in ls if r["arm"] == "none"])
for arm in ("none", "local", "mcp"):
g = [r["listing"] for r in ls if r["arm"] == arm]
if not g:
continue
ctx = med([x["first_request_context"] for x in g])
diff = (ctx - base) if (ctx is not None and base is not None) else None
L.append(f"| {arm} | {len(g)} | {fmt(ctx)} | {fmt(diff) if arm != 'none' else '-'} | "
f"{fmt(diff / 20, 1) if (diff is not None and arm != 'none') else '-'} | {fmt(med([x['skill_listing_chars'] for x in g]))} | "
f"{fmt(med([x['our_skills_chars'] for x in g]))} | {fmt(med([x['our_skills_listed'] for x in g]))} |")
L.append("")
up = [r for r in ok if r["scenario"] == "update"]
if up:
L += ["## D1. セッションの途中でサーバー側の SKILL.md を1行書き換える(bypassPermissions)", "",
"| run | 1回目 | 書き換え直後の2回目 | 3回目 | サーバーの再読込 | 承認ダイアログ |", "|---|---|---|---|---|---|"]
for r in up:
u = r["update"]
t2 = "読み込まれず" if u.get("turn2_not_loaded") else f"答えに {u.get('turn2_sentinel')}"
t3 = "読み込まれず" if u.get("turn3_not_loaded") else f"答えに {u.get('turn3_sentinel')}"
L.append(f"| {r['run_id']} | 答えに {u.get('turn1_sentinel')} | {t2} | {t3} | {u.get('server_reloaded')} | {u.get('approval_prompts')} 回 |")
msg = next((r["update"].get("turn2_message") for r in up if r["update"].get("turn2_message")), None)
if msg:
L += ["", f"- 2回目に出たメッセージ: `{msg}`"]
L.append("")
tm = [r for r in ok if r["scenario"] == "tamper"]
if tm:
L += ["## D2. 一覧のチェックサムと違う SKILL.md を返すサーバー(サイズは同じ)", "",
"| run | いつ改ざん | 各回の結果 | 改ざん文が Claude に届いた | サーバーが改ざん版を返した回数 |", "|---|---|---|---|---|"]
for r in tm:
t = r["tamper"]
res = " → ".join(("読み込まれず" if p.get("not_loaded") else f"答えに {p.get('sentinel_in_answer')}") for p in t.get("per_turn", []))
L.append(f"| {r['run_id']} | {'最初から' if r['arm'] == 'first' else '1回読み込んだ後'} | {res} | {t.get('tampered_loaded')} | {t.get('server_reads_tampered')} |")
msg = next((p["message"] for r in tm for p in r["tamper"].get("per_turn", []) if p.get("message")), None)
if msg:
L += ["", f"- 出たメッセージ: `{msg}`"]
L.append("")
ap = [r for r in ok if r["scenario"] == "approval"]
if ap:
L += ["## D3. 手動モードの承認(Allow this version)と、書き換え後の再確認", "",
"| run | 手順 | 承認ダイアログ | 表示されたバージョン | 選んだもの | 答えの合言葉 | 保存された allow ルール |", "|---|---|---|---|---|---|---|"]
label = {"first": "1. 初回", "same_version": "2. 同じ版・新しいセッション", "edited": "3. サーバー側で1行書き換え後"}
for r in ap:
for s in r["approval"]["steps"]:
L.append(f"| {r['run_id']} | {label.get(s['step'], s['step'])} | {'出た' if s['prompt_shown'] else '出ない'} | "
f"{s.get('digest_shown') or '-'} | {s.get('choice') or '-'} | {s.get('sentinel')} | {'; '.join(s.get('saved_allow_rules') or []) or '-'} |")
L.append("")
if bad:
L += ["## 失敗した run(表から除外)", ""] + [f"- {r['run_id']}: {r['error']}" for r in bad] + [""]
open(os.path.join(log, "summary.md"), "w", encoding="utf-8").write("\n".join(L))
print("\n".join(L))
if __name__ == "__main__":
main()


