どうも、佐々木と申します。今回は「Claude Code × serenaでKiro風仕様書駆動開発をやるためのカスタムコンテキスト」という事で、久々に記事を書こうかなと思います!
(AIに読み込まれる前提なので、必要な情報としっかりしたソースを情報過多なレベルで書いてます。NotebookLMだのに入れ込んで煮るなり焼くなり好きにしてください)
もうすでにserenaの導入方法に関しては色々な記事がありますね、私も使い方勉強中です。
なかなか激熱なMCPサーバーなので、Kiro的な感じで盛り上がるのかな~とか思ってます。
久々に記事を書くのと、時間もなく下調べも結構いい加減なので、備忘録的な感じだと思ってみてください。間違いもガンガン指摘してくれると嬉しいです。
今回別の方のserenaの記事を見て使ってみましたが、initial_instructionsが出ないだの色々問題おきて、ちょっと中身のソースや公式README見ながら使ってみました。
この記事を読んで、serenaの事が少しでも分かると嬉しいです。
もう一度言いますが、備忘録的な感じなので注意してください。
今回の環境はClaude Codeでの実行になります。
というかClaude Codeに最適化したカスタムコンテキスト(実はツール許可しただけ)の紹介です。
これを参考に色々発展してくと私の開発も楽になるので嬉しいですね。
今回Claude Codeでserenaのide-assistantコンテキストを使うときに、switch_modesツールが使えなかったり、get_current_configツールが使えなかったり、てかinitial_instructionsも出ないやん、どういうことなん?って疑問がわきました。
自分のイメージではinitial_instructionsツールを使ってプロジェクト初期化していくと思ったんですけど、なんか違うかったんですよね。
記事構成として、Claude Codeでserena使うときの制約から、技術的な理由を説明して、それに対しての解決策としてカスタムコンテキストを作成して、Kiro風の仕様書駆動開発を実現する方法を紹介します。
そのあとはserenaのモード、serenaのコンテキストを紹介、ちょっと最後の方になりますけど、initial_instructionsツールが出ない理由とそもそもなんぞやって話、最後に補足として.serenaいつ作られるか問題を紹介します。
書きたいこと取っ散らかってますが、最後まで読んでいただけると嬉しいです。(結局AIに読ませるから構成どうでもいいんですけどね…とか思いながら書いてます)
とりあえず公式のGithubリポジトリです。
制約:
- 複数
--mode
パラメータは指定不可 (これで何が困るのかは後で説明します) -
switch_modes
ツールが使えない(ide-assistant
コンテキストでは無効化されてる) - 動的なモード切り替えができない (2が原因、これができないとmode変えたいときに毎回MCPサーバーを削除して再起動する必要がある)
技術的な理由:switch_modes
はToolMarkerOptional
でマークされており、デフォルトでは全てのコンテキストで無効。included_optional_tools
で明示的に有効化する必要があるらしい。
ToolMarkerOptionalでマークされている全ツール一覧
serenaのコードベースを調査したところ、以下のツールがToolMarkerOptional
でマークされており、デフォルトで無効化されています:
設定・プロジェクト管理系:
-
remove_project
– プロジェクト削除 -
switch_modes
– モード切り替え(今回の主要問題) -
get_current_config
– 現在の設定確認
ファイル編集系(行単位):
-
delete_lines
– 行削除 -
replace_lines
– 行置換 -
insert_at_line
– 行挿入
JetBrains統合系:
-
jetbrains_find_symbol
– JetBrainsでのシンボル検索 -
jetbrains_find_referencing_symbols
– JetBrainsでの参照検索 -
jetbrains_get_symbols_overview
– JetBrainsでのシンボル概要取得
ワークフロー系:
-
summarize_changes
– 変更内容の要約 -
initial_instructions
– 初期指示取得
これらのツールは、各コンテキストのincluded_optional_tools
で明示的に有効化する必要があります。
重要なポイント:ide-assistant
コンテキストでは、switch_modes
ツールが有効化されていないわけですね。
switch_modes
が使えるコンテキスト:
-
desktop-app
(Claude Desktop用) –included_optional_tools
で有効化済み -
chatgpt
(ChatGPT用) –included_optional_tools
で有効化済み
対策(面倒):
-
セッション分割方式:仕様書駆動開発のフェーズごとに
claude mcp remove/add
でセッション切り替えというのはできます。
流石に面倒なので、カスタムコンテキストを作成して対応
毎回claude mcp remove serena
してclaude mcp add
し直すのは手間。
理想的には、onboarding → planning → editing → interactive というワークフローを一つのセッション内で動的に切り替えたい。(こいつらが何かってのは後述)
解決策:カスタムコンテキストの作成
そこで、Claude Code専用にswitch_modes
ツールを有効化したカスタムコンテキストを作成することで、この問題を解決。
上記の制約を解決し、Kiroのような「分析→仕様書作成→実装→デバッグ」のワークフローを実現するため、Claude Code専用のカスタムコンテキストを作成・共有します。
ステップ1:カスタムコンテキスト「ide-assistant-enhanced」の作成コマンド
以下のコマンドでswitch_modes
機能付きのカスタムコンテキストを作成:
uvx --from git+https://github.com/oraios/serena serena context create --from-internal ide-assistant --name ide-assistant-enhanced
作成されたファイル(~/.serena/contexts/ide-assistant-enhanced.yml
)を以下のように編集:
※ide-assistantベースのカスタムコンテキストを作成したタイミングで.serenaディレクトリが作成されているはずです。
description: Claude Code optimized context with mode switching capabilities
prompt: |
You are running in enhanced IDE assistant context for Claude Code.
This context is optimized for Claude Code users who want to seamlessly switch between
different workflow modes (onboarding → planning → editing → interactive) without
restarting MCP sessions.
You have access to mode switching capabilities that allow dynamic workflow transitions:
- Use switch_modes to change between onboarding, planning, editing, and interactive modes
- Use get_current_config to check your current mode and tool configuration
File operations, basic (line-based) edits and reads, and shell commands are handled by Claude Code's
internal tools. Use Serena's symbolic tools for efficient code analysis and modification.
Recommended workflow:
1. Start with onboarding mode for project understanding
2. Switch to planning mode for analysis and specification creation
3. Switch to editing mode for implementation
4. Use interactive mode when user collaboration is needed
excluded_tools:
- create_text_file
- read_file
- execute_shell_command
- prepare_for_new_conversation
included_optional_tools:
- switch_modes
- get_current_config
tool_description_overrides: {}
ステップ2:カスタムコンテキストでMCPサーバー起動
注意:既存のserena MCPサーバーがある場合は先に削除
カスタムコンテキストでMCPサーバーを起動:
claude mcp add serena -- uvx --from git+https://github.com/oraios/serena serena-mcp-server --context ide-assistant-enhanced --mode onboarding --project $(pwd)
ステップ3:Kiro風仕様書駆動開発の実践ワークフロー
基本的な4フェーズワークフロー
フェーズ1:プロジェクト理解(onboardingモード)
初回起動時は自動的にonboardingモードで開始されます
推奨プロンプト例:
onboardingツールを利用して、このプロジェクトの全体構造を理解してください。
このフェーズの特徴:
- 読み取り専用でプロジェクト全体を把握
- 重要な情報をメモリシステムに蓄積
- 後のフェーズで参照できる基盤作り
フェーズ2:詳細仕様書作成(planningモード)
モード切替プロンプト:
switch_modesツールを使って、planning one-shotモードに切り替えてください。
次の命令用プロンプト:
JWT認証システムとパスワードリセット機能の詳細仕様書を作成してください。
Specification.mdファイルを作成し、以下を含めてください:
## 1. 機能概要
- JWT認証フローの説明
- パスワードリセットフローの説明
## 2. API設計
- 認証関連エンドポイント(/auth/login, /auth/refresh, etc.)
- パスワード関連エンドポイント(/auth/password-reset, etc.)
- リクエスト・レスポンス形式
## 3. データベース設計
- 新規テーブル設計
- 既存テーブルの変更内容
- インデックス設計
## 4. セキュリティ要件
- JWT有効期限・暗号化方式
- パスワードハッシュ化方式
- レート制限設計
## 5. エラーハンドリング
- エラーコード一覧
- エラーレスポンス形式
このフェーズの特徴:
- 実装前の詳細設計
- 包括的な仕様書作成
- 実装方針の明確化
フェーズ3:実装(editingモード)
モード切替プロンプト:
switch_modesツールを使って、editing no-onboardingモードに切り替えてください。
次の命令用プロンプト:
Specification.mdに基づいてJWT認証システムを実装してください。
実装順序:
1. データベースマイグレーション作成
2. JWT認証ミドルウェア実装
3. 認証API エンドポイント実装
4. パスワードリセット機能実装
5. フロントエンド認証状態管理
6. テストケース作成
各ステップごとに進捗を報告してください。
このフェーズの特徴:
- シンボリック編集による精密な実装
- 既存メモリを活用した効率的開発
- 仕様書に沿った段階的実装
フェーズ4:レビュー・最適化(interactiveモード)
モード切替プロンプト:
switch_modesツールを使って、editing interactiveモードに切り替えてください。
次の命令用プロンプト:
実装したJWT認証システムを包括的にレビューしてください。
以下の観点で確認し、改善提案をお願いします:
1. セキュリティホール・脆弱性
2. パフォーマンス最適化
3. コード品質・保守性
4. エラーハンドリングの妥当性
5. テストカバレッジ
問題を発見した場合は、修正案も提示してください。
このフェーズの特徴:
- 対話的な品質向上
- 段階的な問題解決
- 最適化・リファクタリング
補足:モード確認コマンド
現在のモードとツール構成を確認:
get_current_configツールを使って現在のモードと有効なツールを確認してください。
このワークフローにより、Kiroのような高品質な「仕様書→実装→最適化」の開発サイクルを実現
参考:フェーズ別モード組み合わせパターン一覧
フェーズ | 推奨モード組み合わせ | 目的 |
---|---|---|
初回分析 |
onboarding のみ |
プロジェクト理解とメモリ構築 |
仕様書作成 |
planning + one-shot
|
包括的な計画・仕様書作成 |
対話的分析 |
planning + interactive
|
ユーザーとの対話で段階的分析 |
実装開始 |
editing + no-onboarding
|
既存知識を活用した効率的開発 |
デバッグ |
editing + interactive
|
対話的な問題解決 |
Planningモード
目的: コード分析と計画策定に特化
planningモードでできること:
- コードの解析・分析
- プロジェクト構造の理解
- 仕様書・設計書の作成計画
- シンボル検索、参照関係の調査(※シンボル = クラス、関数、メソッド等のコード要素)
- メモリの読み書き(プロジェクト知識の蓄積)
planningモードでできないこと:
- 実際のコード編集(
replace_symbol_body
,insert_after_symbol
,insert_before_symbol
等) - ファイル作成(
create_text_file
) - 正規表現による編集(
replace_regex
) - 行単位の編集(
delete_lines
,replace_lines
,insert_at_line
) - シェルコマンド実行(
execute_shell_command
)
planning.yml の内容:
description: Only read-only tools, focused on analysis and planning
prompt: |
You are operating in planning mode. Your task is to analyze code but not write any code.
The user may ask you to assist in creating a comprehensive plan, or to learn something about the codebase -
either a small aspect of it or about the whole project.
excluded_tools:
- create_text_file
- replace_symbol_body
- insert_after_symbol
- insert_before_symbol
- delete_lines
- replace_lines
- insert_at_line
- execute_shell_command
- replace_regex
実際の利用シーン:
- 「このプロジェクトのAPI設計について教えて」→ コードベース全体を分析して設計思想を理解
- 「Userクラスがどこで使われているか調べて」→ シンボル参照関係を調査
- 「データベース周りの仕様書を作りたい」→ 関連コードを分析して仕様書作成
- 「新機能の実装計画を立てたい」→ 既存構造を理解して実装方針を策定
Editingモード
目的: 実際のコード編集と実装
editingモードでできること:
- シンボル単位での精密な編集(
replace_symbol_body
,insert_after_symbol
等) - 正規表現による部分的な編集(
replace_regex
) - ファイル作成・削除(
create_text_file
) - シェルコマンド実行(
execute_shell_command
) - すべての分析ツール(planningモードの機能も含む)
editingモードでできないこと:
- 行単位の編集(
replace_lines
,insert_at_line
,delete_lines
) – シンボリック編集を優先
editing.yml の内容:
description: All tools, with detailed instructions for code editing
prompt: |
You are operating in editing mode. You can edit files with the provided tools
to implement the requested changes to the code base while adhering to the project's code style and patterns.
Use symbolic editing tools whenever possible for precise code modifications.
If no editing task has yet been provided, wait for the user to provide one.
When writing new code, think about where it belongs best. Don't generate new files if you don't plan on actually
integrating them into the codebase, instead use the editing tools to insert the code directly into the existing files in that case.
You have two main approaches for editing code - editing by regex and editing by symbol.
The symbol-based approach is appropriate if you need to adjust an entire symbol, e.g. a method, a class, a function, etc.
But it is not appropriate if you need to adjust just a few lines of code within a symbol, for that you should
use the regex-based approach that is described below.
excluded_tools:
- replace_lines
- insert_at_line
- delete_lines
実際の利用シーン:
- 「バグ修正:ログイン機能が動かない」→ シンボル単位で該当メソッドを精密修正
- 「新しいAPIエンドポイントを追加」→ 既存パターンに従って実装
- 「リファクタリング:共通処理を関数化」→ 正規表現で部分的な置換を実行
- 「テストケース追加とコード修正」→ テスト実行も含めた一連の開発作業
Interactiveモード
目的: ユーザーとの対話的な作業進行
interactiveモードでできること:
- 不明点の積極的な質問
- 複雑なタスクの段階的な分解
- 中間結果の詳細な説明
- ユーザーからのフィードバック受け取り
- すべてのツール(excluded_toolsが空のため)
interactiveモードでできないこと:
- 特に制限なし(他のモードとの組み合わせ次第)
interactive.yml の内容:
description: Interactive mode for clarification and step-by-step work
prompt: |
You are operating in interactive mode. You should engage with the user throughout the task, asking for clarification
whenever anything is unclear, insufficiently specified, or ambiguous.
Break down complex tasks into smaller steps and explain your thinking at each stage. When you're uncertain about
a decision, present options to the user and ask for guidance rather than making assumptions.
Focus on providing informative results for intermediate steps so the user can follow along with your progress and
provide feedback as needed.
excluded_tools: []
実際の利用シーン:
- 「この実装方針で良いか相談したい」→ 段階的に方針を確認しながら進行
- 「複雑な機能の実装手順を教えて」→ ステップバイステップで詳細説明
- 「エラーの原因が分からない」→ 対話的にデバッグ手順を案内
- 「要件が曖昧なので詳細を決めたい」→ 質問を通じて要件を明確化
Onboardingモード
目的: プロジェクト初回理解とメモリ構築
onboardingモードでできること:
- プロジェクト構造の初回分析
- メモリファイルの作成・保存
- オンボーディング専用ツールの利用
- 既存ファイルの読み取り・解析
onboardingモードでできないこと:
- 実際のコード編集(
replace_symbol_body
,insert_after_symbol
等) - ファイル作成(
create_text_file
) - 行単位の編集(
delete_lines
,replace_lines
,insert_at_line
) - シェルコマンド実行(
execute_shell_command
)
onboarding.yml の内容:
description: Only read-only tools, focused on analysis and planning
prompt: |
You are operating in onboarding mode. This is the first time you are seeing the project.
Your task is to collect relevant information about it and to save memories using the tools provided.
Call relevant onboarding tools for more instructions on how to do this.
In this mode, you should not be modifying any existing files.
If you are also in interactive mode and something about the project is unclear, ask the user for clarification.
excluded_tools:
- create_text_file
- replace_symbol_body
- insert_after_symbol
- insert_before_symbol
- delete_lines
- replace_lines
- insert_at_line
- execute_shell_command
実際の利用シーン:
- 「初回:このプロジェクトについて教えて」→ 全体構造を分析してメモリに保存
- 「初回:主要なクラスと機能を把握したい」→ 重要なシンボルを特定・記録
- 「初回:開発環境の設定方法を理解したい」→ 設定ファイル等を分析
- 「プロジェクト参加初日の理解促進」→ 段階的にコードベースを学習
No-Onboardingモード
目的: 既存メモリを活用した効率的な作業開始
no-onboardingモードでできること:
- 既存メモリの活用
- 即座のタスク着手
- オンボーディング処理のスキップ
- 通常の開発作業(他のモードとの組み合わせ次第)
no-onboardingモードでできないこと:
- オンボーディング関連ツール(
onboarding
,check_onboarding_performed
)
no-onboarding.yml の内容:
description: Onboarding was already performed, exclude all onboarding tools
prompt: |
You have already performed onboarding, meaning that memories have already been created.
Read a list of available memories using the `list_memories` tool before proceeding with the task.
You don't need to read the actual memories, just remember that they exist and that you can read them later if they are relevant for your task.
excluded_tools:
- onboarding
- check_onboarding_performed
実際の利用シーン:
- 「2回目以降:前回の続きから作業したい」→ 既存メモリを参照して効率的に作業再開
- 「メモリがある状態で新機能実装」→ プロジェクト理解済みとして即座に実装着手
- 「複数セッション跨ぎの開発」→ オンボーディングをスキップして継続作業
- 「チームメンバーが作成したメモリを活用」→ 他者の理解を引き継いで作業開始
serenaのコンテキストは、異なる開発環境や用途に応じて最適化されたツールセットと動作を提供します。各コンテキストの特徴を理解することで、効果的にserenaを活用できます。
IDE-Assistantコンテキスト
目的: IDE統合環境(Claude Code等)での使用に最適化
ide-assistantコンテキストでできること:
- シンボリック編集ツールによる精密なコード操作
- セマンティックな検索・分析機能
- メモリシステムによる知識蓄積
- プロジェクト管理機能
ide-assistantコンテキストでできないこと:
- ファイル作成(
create_text_file
) – IDEの内部ツールを使用 - ファイル読み取り(
read_file
) – IDEの内部ツールを使用 - シェルコマンド実行(
execute_shell_command
) – IDEの内部ツールを使用 - モード切り替え(
switch_modes
) – デフォルトでは無効化
ide-assistant.yml の内容:
description: Non-symbolic editing tools and general shell tool are excluded
prompt: |
You are running in IDE assistant context where file operations, basic (line-based) edits and reads,
and shell commands are handled by your own, internal tools.
The initial instructions and the current config inform you on which tools are available to you,
and how to use them.
Don't attempt to use any excluded tools, instead rely on your own internal tools
for achieving the basic file or shell operations.
If serena's tools can be used for achieving your task,
you should prioritize them. In particular, it is important that you avoid reading entire source code files,
unless it is strictly necessary! Instead, for exploring and reading code in a token-efficient manner,
you should use serena's overview and symbolic search tools. The call of the read_file tool on an entire source code
file should only happen in exceptional cases, usually you should first explore the file (by itself or as part of exploring
the directory containing it) using the symbol_overview tool, and then make targeted reads using find_symbol and other symbolic tools.
For non-code files or for reads where you don't know the symbol's name path you can use the patterns searching tool,
using the read_file as a last resort.
excluded_tools:
- create_text_file
- read_file
- execute_shell_command
- prepare_for_new_conversation
tool_description_overrides: {}
実際の利用シーン:
- 「Claude Codeでserenaを使いたい」→ IDEとの重複機能を避けた効率的な開発
- 「シンボリック編集を中心とした開発」→ 精密なコード操作に特化
- 「トークン効率を重視した開発」→ ファイル全体読み込みを避けて効率化
Desktop-Appコンテキスト
目的: デスクトップアプリ(Claude Desktop等)での使用に最適化
desktop-appコンテキストでできること:
- 全ツールへのアクセス(excluded_toolsが空)
- 動的なモード切り替え(
switch_modes
が有効) - ファイルシステムへの完全アクセス
- 高レベルな思考と計画立案
- 図表作成(Mermaid対応)
desktop-appコンテキストでできないこと:
- 特に制限なし(最も包括的なコンテキスト)
desktop-app.yml の内容:
description: All tools included for desktop app context
prompt: |
You are running in desktop app context where the tools give you access to the code base as well as some
access to the file system, if configured. You interact with the user through a chat interface that is separated
from the code base. As a consequence, if you are in interactive mode, your communication with the user should
involve high-level thinking and planning as well as some summarization of any code edits that you make.
For viewing the code edits the user will view them in a separate code editor window, and the back-and-forth
between the chat and the code editor should be minimized as well as facilitated by you.
If complex changes have been made, advise the user on how to review them in the code editor.
If complex relationships that the user asked for should be visualized or explained, consider creating
a diagram in addition to your text-based communication. Note that in the chat interface you have various rendering
options for text, html, and mermaid diagrams, as has been explained to you in your initial instructions.
excluded_tools: []
included_optional_tools:
- switch_modes
tool_description_overrides: {}
実際の利用シーン:
- 「Claude Desktopでserenaを使いたい」→ 完全な機能セットで包括的開発
- 「複雑なプロジェクト分析と図表作成」→ Mermaid図表で関係性を可視化
- 「フレキシブルなワークフロー」→ switch_modesで動的な作業切り替え
ChatGPTコンテキスト
目的: ChatGPT環境での使用(30ツール制限対応)
chatgptコンテキストでできること:
- ChatGPTの制約に最適化されたツールセット
- 短縮されたツール説明で効率化
- 動的なモード切り替え(
switch_modes
が有効) - デスクトップアプリと同様の高レベル思考
chatgptコンテキストでできないこと:
- 特に制限なし(ChatGPTの制約内で最大限の機能)
chatgpt.yml の内容(重要部分):
description: A configuration specific for chatgpt, which has a limit of 30 tools and requires short descriptions.
prompt: |
You are running in desktop app context where the tools give you access to the code base as well as some
access to the file system, if configured. You interact with the user through a chat interface that is separated
from the code base. As a consequence, if you are in interactive mode, your communication with the user should
involve high-level thinking and planning as well as some summarization of any code edits that you make.
excluded_tools: []
included_optional_tools:
- switch_modes
tool_description_overrides:
find_symbol: |
Retrieves symbols matching `name_path` in a file.
Use `depth > 0` to include children. `name_path` can be: "foo": any symbol named "foo"; "foo/bar": "bar" within "foo"; "/foo/bar": only top-level "foo/bar"
replace_regex: |
Replaces text using regular expressions. Preferred for smaller edits where symbol-level tools aren't appropriate.
Use wildcards (.*?) to match large sections efficiently: "beginning.*?end" instead of specifying exact content.
Essential for multi-line replacements.
実際の利用シーン:
- 「ChatGPTでserenaを使いたい」→ 30ツール制限内での最適化
- 「ツール説明を短縮したい」→ トークン効率を重視した開発
- 「ChatGPT特有の制約下での開発」→ 環境制約に対応した設計
Agentコンテキスト
目的: より自律的なエージェント動作に最適化
agentコンテキストでできること:
- シンボリックツールによる自律的なコード理解・修正
- 外部システムプロンプトとの連携
- 最小限の設定での動作
agentコンテキストでできないこと:
- 初期指示取得(
initial_instructions
) – 外部でシステムプロンプト提供 - モード切り替え(
switch_modes
) – デフォルトでは無効化
agent.yml の内容:
description: All tools except InitialInstructionsTool for agent context
prompt: |
You are running in agent context where the system prompt is provided externally. You should use symbolic
tools when possible for code understanding and modification.
excluded_tools:
- initial_instructions
tool_description_overrides: {}
実際の利用シーン:
- 「外部システムとの連携」→ システムプロンプトが外部から提供される環境
- 「自律的なエージェント開発」→ 最小限の設定で自動化されたワークフロー
- 「API経由での利用」→ プログラムから制御される開発タスク
前述したように、initial_instructions
もswitch_modes
と同様にToolMarkerOptional
でマークされており、デフォルトで無効化されています。しかしinitial_instructions
の場合は、Claude Codeでは技術的に不要なツールでもあります。
改めて、なぜinitial_instructions
が使えないのかをコードレベルで詳しく解説します。
前のセクションで確認した通り、公式ドキュメント通りに--context ide-assistant
で起動すると、switch_modes
、get_current_config
、initial_instructions
が使えない状態でスタートします。これは意図された正しい動作です。
Claude Codeではinitial_instructions
を実行する必要がないのは、このツールがシステムプロンプトを手動取得するためのものだからです。Claude Codeのようにシステムプロンプト自動設定ができる環境では本質的に不要なツールです。
src/serena/tools/workflow_tools.py
の125行目から:
class InitialInstructionsTool(Tool, ToolMarkerDoesNotRequireActiveProject, ToolMarkerOptional):
"""
Gets the initial instructions for the current project.
Should only be used in settings where the system prompt cannot be set,
e.g. in clients you have no control over, like Claude Desktop.
"""
def apply(self) -> str:
"""
Get the initial instructions for the current coding project.
If you haven't received instructions on how to use Serena's tools in the system prompt,
you should always call this tool before starting to work (including using any other tool) on any programming task,
the only exception being when you are asked to call `activate_project`, which you should then call before.
"""
return self.agent.create_system_prompt()
重要なポイント:
-
ToolMarkerOptional
の仕組み- 前述した通り、デフォルトで無効になっているオプショナルツール
-
included_optional_tools
で明示的に有効化しない限り使用不可
-
docstringの重要な記述
- 「Should only be used in settings where the system prompt cannot be set」
- 翻訳:「システムプロンプトを設定できない環境でのみ使用すべき」
- つまり、Claude Desktop等の制約がある環境でのみ必要
-
実装の本質
- 単に
self.agent.create_system_prompt()
を呼ぶだけ - これは、本来システムプロンプトとして自動設定される内容を手動で取得するツール
- Claude Codeのようにシステムプロンプト自動設定ができる環境では不要
- 単に
システムプロンプト自動設定の仕組み:create_system_prompt()の内部処理
src/serena/agent.py
の367行目:
def create_system_prompt(self) -> str:
available_markers = self._exposed_tools.tool_marker_names
log.info("Generating system prompt with available_tools=(see exposed tools), available_markers=%s", available_markers)
system_prompt = self.prompt_factory.create_system_prompt(
context_system_prompt=self._format_prompt(self._context.prompt),
mode_system_prompts=[self._format_prompt(mode.prompt) for mode in self._modes],
available_tools=self._exposed_tools.tool_names,
available_markers=available_markers,
)
log.info("System prompt:\n%s", system_prompt)
return system_prompt
各パラメータの詳細解説
このメソッドは以下の4つの要素を組み合わせて最終的なシステムプロンプトを生成します:
-
context_system_prompt
– コンテキストのプロンプト-
ide-assistant
の場合:「あなたはIDE統合環境で動作し、基本的なファイル操作はClaude Codeの内部ツールが処理します」 -
agent
の場合:「システムプロンプトは外部で提供されます」
-
-
mode_system_prompts
– モードのプロンプト-
planning
の場合:「あなたは計画モードで動作し、コードを分析するがコードは書きません」 -
editing
の場合:「編集モードで動作し、シンボリック編集ツールを使って精密なコード編集を行います」
-
-
available_tools
– 利用可能なツール一覧- コンテキストとモードによって利用可能なツールが決定される
- 例:
planning
では編集系ツールは除外
-
available_markers
– 利用可能なツールマーカー-
ToolMarkerSymbolicRead
、ToolMarkerSymbolicEdit
等のマーカー一覧 - AIがどの種類のツールが使えるかを理解するための情報
-
実際の生成例
--context ide-assistant --mode planning
で生成されるシステムプロンプトの重要部分:
英語(原文):
You are a professional coding agent concerned with one particular codebase. You have
access to semantic coding tools on which you rely heavily for all your work...
Context description:
You are running in IDE assistant context where file operations, basic (line-based) edits and reads,
and shell commands are handled by your own, internal tools.
The initial instructions and the current config inform you on which tools are available to you,
and how to use them.
Don't attempt to use any excluded tools, instead rely on your own internal tools
for achieving the basic file or shell operations.
Modes descriptions:
- You are operating in planning mode. Your task is to analyze code but not write any code.
The user may ask you to assist in creating a comprehensive plan, or to learn something about the codebase -
either a small aspect of it or about the whole project.
日本語訳:
あなたは特定のコードベースに特化したプロフェッショナルなコーディングエージェントです。
セマンティックなコーディングツールにアクセスでき、すべての作業でこれらを重用します...
Context description:
IDE統合環境で動作し、基本的なファイル操作、行単位の編集、シェルコマンドは
あなた自身の内部ツールが処理します。除外されたツールは使用せず、
基本的なファイルやシェル操作には内部ツールに依存してください。
Modes descriptions:
- あなたは計画モードで動作しています。コードを分析することが任務ですが、
コードを書くことはありません。ユーザーは包括的な計画の作成や、
コードベースについて学ぶことを求めるかもしれません。
これにより、AIは自分がどのような役割で、どのような制約の下で動作するかを正確に理解できます。
Claude Codeでは自動処理:MCPサーバー側のシステムプロンプト設定
src/serena/mcp.py
の221行目:
def _get_initial_instructions(self) -> str:
assert self.agent is not None
return self.agent.create_system_prompt()
コメントにもある通り、MCPサーバー側ではInitialInstructionsTool
を使わず、直接create_system_prompt()
を呼んでいます。
実際はどう?各コンテキストでのinitial_instructionsツールの利用可能性
前のセクションで確認したYAMLファイルの内容を踏まえると:
なぜinitial_instructionsが使えないのか
実際の理由:
-
initial_instructions
はToolMarkerOptional
– 前述した通りデフォルトで無効 - どのコンテキストも
included_optional_tools
で有効化していない - 結果的に全てのコンテキストで使用不可
つまり、「ide-assistantで無効化されている」のではなく、「全コンテキストで明示的に有効化していないため使えない」が正確な理由です。
各コンテキストの除外ツール比較(再掲)
前のセクションで確認した通り:
コンテキスト | excluded_tools | included_optional_tools | initial_instructions可否 |
---|---|---|---|
ide-assistant |
基本ファイル操作系 | なし | 使用不可 |
agent |
initial_instructions |
なし | 使用不可(明示的除外) |
desktop-app |
なし |
switch_modes のみ |
使用不可 |
chatgpt |
なし |
switch_modes のみ |
使用不可 |
initial_instructionsツールの結論
これまでの調査で分かった重要なポイント:
実用的な結論
-
Claude Code: システムプロンプト自動設定のため、
initial_instructions
は技術的に不要 -
Claude Desktop: システムプロンプト設定不可のため、
initial_instructions
が本来必要だが、実際には全コンテキストで使用不可 -
根本的な問題:
ToolMarkerOptional
により無効化されているが、どのコンテキストもincluded_optional_tools
で有効化していない -
設計思想: 各環境の制約に応じて適切なツールセットを提供するが、現状は
initial_instructions
が使えない状態
ユーザーから「.serena
がいつ作られるか」について質問があったので、コードを調査した結果を記載します。
パターン1:ホームディレクトリの.serena(~/.serena)作成タイミング
作成タイミング: serena初回起動時(MCPサーバー開始時)
作成処理:
-
SerenaAgent
初期化時にSerenaConfig.from_config_file()
が呼ばれる(src/serena/agent.py:136
) - 設定ファイルが存在しない場合、
generate_config_file()
で自動生成(src/serena/config/serena_config.py:403
) - この際、
os.makedirs(os.path.dirname(config_path), exist_ok=True)
で~/.serena
ディレクトリが作成される(src/serena/config/serena_config.py:386
)
保存される内容:
-
serena_config.yml
– serena全体の設定 -
contexts/
– カスタムコンテキストファイル -
modes/
– カスタムモードファイル -
language_servers/
– 言語サーバーのバイナリキャッシュ
パターン2:プロジェクトディレクトリの.serena作成タイミング
作成タイミング: --project
パラメータでプロジェクトが指定された時点
作成処理の流れ:
- プロジェクトが指定される(
--project $(pwd)
) -
ProjectConfig.rel_path_to_project_yml()
で.serena/project.yml
のパスが決定 - プロジェクト設定ファイルが必要になった時点で
.serena
ディレクトリが作成される - その後、プロジェクト設定ファイルが自動生成される
保存される内容:
-
project.yml
– プロジェクト固有の設定 -
memories/
– プロジェクト固有のメモリファイル(onboarding後)
まとめ .serenaディレクトリ作成の重要ポイントと推奨ワークフロー
既存の設定への影響:
- 一度serenaを起動すると
~/.serena
ディレクトリが作成される - カスタムコンテキスト作成は、serena起動前でも実行可能
-
claude mcp add
で既存のサーバー名を使うとエラーになるため、claude mcp remove
が必要
推奨ワークフロー:
uvx --from git+https://github.com/oraios/serena serena context create --from-internal ide-assistant --name ide-assistant-enhanced
修正内容(~/.serena/contexts/ide-assistant-enhanced.yml
):
description: Claude Code optimized context with mode switching capabilities
prompt: |
You are running in enhanced IDE assistant context for Claude Code.
This context is optimized for Claude Code users who want to seamlessly switch between
different workflow modes (onboarding → planning → editing → interactive) without
restarting MCP sessions.
You have access to mode switching capabilities that allow dynamic workflow transitions:
- Use switch_modes to change between onboarding, planning, editing, and interactive modes
- Use get_current_config to check your current mode and tool configuration
File operations, basic (line-based) edits and reads, and shell commands are handled by Claude Code's
internal tools. Use Serena's symbolic tools for efficient code analysis and modification.
Recommended workflow:
1. Start with onboarding mode for project understanding
2. Switch to planning mode for analysis and specification creation
3. Switch to editing mode for implementation
4. Use interactive mode when user collaboration is needed
excluded_tools:
- create_text_file
- read_file
- execute_shell_command
- prepare_for_new_conversation
included_optional_tools:
- switch_modes
- get_current_config
tool_description_overrides: {}
claude mcp add serena -- uvx --from git+https://github.com/oraios/serena serena-mcp-server --context ide-assistant-enhanced --mode onboarding --project $(pwd)
このタイミングで両方の.serena
ディレクトリが作成され、以降のセッションでメモリやカスタム設定が活用されます。
どうも、佐々木です。ここまで長い記事を読んでいただき、ありがとうございました。
今回Claude Code × serenaの組み合わせを色々試してみて、かなり色々な発見がありました。備忘録的に書くつもりが、結構がっつり調査してますね(Claude Codeさまさまですが…)
各セクションを振り返って
Claude Codeの制約について
最初に直面した「switch_modesツールが使えない」問題から始まったんですが、調べてみるとToolMarkerOptional
ってな仕組みがあって、デフォルトで無効化されてるツールがめっちゃあるんですよね。ここらも色々変わると思いますが、serenaの設計思想を多少は理解できた気がしますね。
これ、最初知らんかったので「なんで使えんねん」って思ってたんですが、これさえ分かっておけば、今後も大丈夫かなと。
カスタムコンテキストの威力
カスタムコンテキスト作るのも、思ったより簡単でした。included_optional_tools
にswitch_modes
とget_current_config
追加するだけで、かなり使い勝手が変わります。カスタムモードも同じ感じで作れるので、なかなか柔軟性が高いですね。
てかClaude Codeでモード切り替えできないのは不便じゃないのかな?邪道なのかもしれませんが、カスタムコンテキストで色々できるのは伝わったかなと思います。
Kiro風ワークフローの実現
onboarding → planning → editing → interactiveの4フェーズワークフロー、これがなかなか良い感じでしたね。そもそもmodeとしてあるってことはそういうことなんでしょう。
特にplanningモードでSpecification.md作って、それをベースにeditingモードで実装、最後にinteractiveモードでレビューって流れは、Kiro的な「仕様書駆動開発」って感じになりますね。世の中的にも、仕様書駆動が浸透してきているということでしょうね。
serenaのモードとコンテキストの奥深さ
前述したように、5つのモード(onboarding, planning, editing, interactive, no-onboarding)それぞれにちゃんと役割があって、4つのコンテキスト(ide-assistant, desktop-app, chatgpt, agent)もそれぞれ異なる環境の制約に対応してる。
特にide-assistant
コンテキストがClaude Codeの内部ツールとの重複を避けるために、基本的なファイル操作系ツールを除外してるのとかは、「なるほどなー」って感じでしたね。
initial_instructionsの謎が解けた
これが一番スッキリしましたね。最初「なんでinitial_instructionsが出ないんや」って思ってたんですが、実はClaude Codeではシステムプロンプトが自動設定されるから、このツール自体が不要だったという。これで初期化するもんだと思ってたので、スッキリしました。
InitialInstructionsTool
の実装見たら、単にagent.create_system_prompt()
呼んでるだけで、MCPサーバー側で自動的にやってくれてるから、手動で呼ぶ必要がないんですよね。
しかも調べてみると、実際には全コンテキストでToolMarkerOptional
のせいで使えないっていう。まぁ実は公式READMEにもちらっと書いてますけど、コード読んだ方が分かりやすいですね。
.serenaディレクトリの仕組み
これもコード読んで初めて分かったんですが、~/.serena
は初回起動時、プロジェクトの.serena
は--project
指定時に作られます。
SerenaConfig.from_config_file()
のあたりのコード見てて、「あー、ここで作ってるんか」と。
最後に
てか、実は今回ってswitch_modes
を有効化しただけでしたね。カスタムなんとか作れば皆読んでくれるかなと思って、ちょっと大げさに書いちゃいましたね。
今回は備忘録的に書くつもりが、気づいたら結構がっつりした技術記事になってしまいました。
でも、Claude Code × serenaの組み合わせで開発する人の参考になれば嬉しいです。特に「switch_modesが使えない」「initial_instructionsが出ない」で困ってる人には、解決策を提供できたかなと思います。
serenaはまだまだ奥が深そうなので、引き続き色々試してみたいと思います。何か面白い発見があったら、また記事にするかもしれません。
間違いや改善点があったら、ガンガン指摘してください。みんなでserenaをもっと便利に使えるようになっていけば良いなと思います。
それでは、最後まで読んでいただき、ありがとうございました!
この戦略で、Kiroのような「分析→仕様書作成→実装」のワークフローがserenaで快適に実現できます。という感じで、お疲れ様でした!
Views: 0