serena MCP をGemini-Cliに設定する
.gemini
フォルダを見つける
lsで即見つかったので、
code .gemini/
でsettings.json
を開く
{
"theme": "GitHub",
"selectedAuthType": "oauth-personal",
"preferredEditor": "vscode"
}
serena
これ
brew install uv
local installationで行ってみる
準備
ghq get https://github.com/oraios/serena.git
ghq-pecoで移動
❯ uv run serena config edit
Using CPython 3.11.11 interpreter at: /opt/homebrew/opt/python@3.11/bin/python3.11
Creating virtual environment at: .venv
Built serena-agent @ file:///Users/watanabetsubasa/src/github.com/oraios/seren
Installed 55 packages in 99ms
参考
~/src/github.com/oraios/serena main 9s
❯ . .venv/bin/activate
~/src/github.com/oraios/serena main
.venv ❯ python --version
Python 3.11.11
~/src/github.com/oraios/serena main
.venv ❯
uv run serena start-mcp-server
サーバー起動したので次へ
Gemini-Cli settings.jsonの設定
{
"mcpServers": {
"serena": {
"command": "/abs/path/to/uv",
"args": ["run", "--directory", "/abs/path/to/serena", "serena", "start-mcp-server"]
}
}
}
これを自分の環境に直していく
❯ which uv
/opt/homebrew/bin/uv
これでuvのabs path調べて、
ghq-pecoでserenaのabs path調べて書き換え
動作確認
その辺に、RemixをCloudflareにデプロイする用のテンプレが転がっていたので試してみる
███ █████████ ██████████ ██████ ██████ █████ ██████ █████ █████
░░░███ ███░░░░░███░░███░░░░░█░░██████ ██████ ░░███ ░░██████ ░░███ ░░███
░░░███ ███ ░░░ ░███ █ ░ ░███░█████░███ ░███ ░███░███ ░███ ░███
░░░███ ░███ ░██████ ░███░░███ ░███ ░███ ░███░░███░███ ░███
███░ ░███ █████ ░███░░█ ░███ ░░░ ░███ ░███ ░███ ░░██████ ░███
███░ ░░███ ░░███ ░███ ░ █ ░███ ░███ ░███ ░███ ░░█████ ░███
███░ ░░█████████ ██████████ █████ █████ █████ █████ ░░█████ █████
░░░ ░░░░░░░░░ ░░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░ ░░░░░ ░░░░░ ░░░░░
Tips for getting started:
1. Ask questions, edit files, or run commands.
2. Be specific for the best results.
3. Create GEMINI.md files to customize your interactions with Gemini.
4. /help for more information.
╭────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ > serenaを使って、現在のディレクトリ内のファイルを解析して、どのようなプロジェクトかを分析して下さい │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ はい、承知いたしました。現在のディレクトリ内のファイルを分析し、プロジェクトの概要を説明します。
まず、プロジェクトの基本的な設定が記述されているpackage.jsonを読み込みます。
╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✔ ReadFile package.json │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ package.jsonの情報を分析しました。
このプロジェクトは、Remixフレームワークを使用したWebアプリケーションです。UIの構築にはReactとTailwind
CSSが利用されており、TypeScriptで開発されています。
また、Cloudflare Workersへのデプロイが想定されており、wranglerコマンドが用意されています。
要約すると、これはRemix on Cloudflare Workersの構成のプロジェクトです。
次に、アプリケーションのエントリーポイントであるapp/routes/_index.tsxの内容を確認し、どのような初期ページが設定
されているかを把握します。
╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✔ ReadFile app/routes/_index.tsx │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ app/routes/_index.tsx の内容を確認しました。
このファイルは、Remixのデフォルトのトップページです。Remixのロゴと、ドキュメントやコミュニティへのリンクが表示
されるようになっています。
分析結果のまとめ
以上の分析から、このプロジェクトはRemixフレームワークを利用して新規に作成されたWebアプリケーションであり、Cloud
flare Workers上での動作を前提としていることが分かりました。UIはReactとTailwind
CSSで構築され、開発言語はTypeScriptです。
現時点では、Remixの初期テンプレートの状態から大きな変更は加えられていないようです。
何か他に知りたいことはありますか?
╭───────────────╮
│ > /mcp desc │
╰───────────────╯
ℹ Configured MCP servers:
🟢 serena - Ready (32 tools)
Tools:
- activate_project:
Activates the project with the given name.
- check_onboarding_performed:
Checks whether project onboarding was already performed.
You should always call this tool before beginning to actually work on the project/after activating a
project,
but after calling the initial instructions tool.
- create_text_file:
Write a new file (or overwrite an existing file). For existing files, it is strongly recommended
to use symbolic operations like replace_symbol_body or insert_after_symbol/insert_before_symbol, if
possible.
You can also use insert_at_line to insert content at a specific line for existing files if the symbolic
operations
are not the right choice for what you want to do.
If ever used on an existing file, the content has to be the complete content of that file (so it
may never end with something like "The remaining content of the file is left unchanged.").
For operations that just replace a part of a file, use the replace_lines or the symbolic editing tools
instead. Returns a message indicating success or failure.
- delete_lines:
Deletes the given lines in the file.
Requires that the same range of lines was previously read using the `read_file` tool to verify
correctness
of the operation.
- delete_memory:
Delete a memory file. Should only happen if a user asks for it explicitly,
for example by saying that the information retrieved from a memory file is no longer correct
or no longer relevant for the project.
- execute_shell_command:
Execute a shell command and return its output.
IMPORTANT: you should always consider the memory about suggested shell commands before using this tool.
If this memory was not loaded in the current conversation, you should load it using the `read_memory`
tool
before using this tool.
You should have at least once looked at the suggested shell commands from the corresponding memory
created during the onboarding process before using this tool.
Never execute unsafe shell commands like `rm -rf /` or similar! Generally be very careful with deletions.
Returns a JSON object containing the command's stdout and optionally stderr output.
- find_file:
Finds non-gitignored files matching the given file mask within the given relative path. Returns a JSON
object with the list of matching files.
- find_referencing_symbols:
Finds symbols that reference the symbol at the given `name_path`. The result will contain metadata about
the referencing symbols
as well as a short code snippet around the reference (unless `include_body` is True, then the short
snippet will be omitted).
Note that among other kinds of references, this function can be used to find (direct) subclasses of a
class,
as subclasses are referencing symbols that have the kind class. Returns a list of JSON objects with the
symbols referencing the requested symbol.
- find_symbol:
Retrieves information on all symbols/code entities (classes, methods, etc.) based on the given
`name_path`,
which represents a pattern for the symbol's path within the symbol tree of a single file.
The returned symbol location can be used for edits or further queries.
Specify `depth > 0` to retrieve children (e.g., methods of a class).
The matching behavior is determined by the structure of `name_path`, which can
either be a simple name (e.g. "method") or a name path like "class/method" (relative name path)
or "/class/method" (absolute name path). Note that the name path is not a path in the file system
but rather a path in the symbol tree **within a single file**. Thus, file or directory names should never
be included in the `name_path`. For restricting the search to a single file or directory,
the `within_relative_path` parameter should be used instead. The retrieved symbols' `name_path` attribute
will always be composed of symbol names, never file or directory names.
Key aspects of the name path matching behavior:
- Trailing slashes in `name_path` play no role and are ignored.
- The name of the retrieved symbols will match (either exactly or as a substring)
the last segment of `name_path`, while other segments will restrict the search to symbols that
have a desired sequence of ancestors.
- If there is no starting or intermediate slash in `name_path`, there is no
restriction on the ancestor symbols. For example, passing `method` will match
against symbols with name paths like `method`, `class/method`, `class/nested_class/method`, etc.
- If `name_path` contains a `/` but doesn't start with a `/`, the matching is restricted to symbols
with the same ancestors as the last segment of `name_path`. For example, passing `class/method` will
match against
`class/method` as well as `nested_class/class/method` but not `method`.
- If `name_path` starts with a `/`, it will be treated as an absolute name path pattern, meaning
that the first segment of it must match the first segment of the symbol's name path.
For example, passing `/class` will match only against top-level symbols like `class` but not against
`nested_class/class`.
Passing `/class/method` will match against `class/method` but not `nested_class/class/method` or
`method`. Returns JSON string: a list of symbols (with locations) matching the name.
- get_current_config:
Print the current configuration of the agent, including the active and available projects, tools,
contexts, and modes.
- get_symbols_overview:
Gets an overview of the given file or directory.
For each analyzed file, we list the top-level symbols in the file (name_path, kind).
Use this tool to get a high-level understanding of the code symbols.
Calling this is often a good idea before more targeted reading, searching or editing operations on the
code symbols.
Before requesting a symbol overview, it is usually a good idea to narrow down the scope of the overview
by first understanding the basic directory structure of the repository that you can get from memories
or by using the `list_dir` and `find_file` tools (or similar). Returns a JSON object mapping relative
paths of all contained files to info about top-level symbols in the file (name_path, kind).
- insert_after_symbol:
Inserts the given body/content after the end of the definition of the given symbol (via the symbol's
location).
A typical use case is to insert a new class, function, method, field or variable assignment.
- insert_at_line:
Inserts the given content at the given line in the file, pushing existing content of the line down.
In general, symbolic insert operations like insert_after_symbol or insert_before_symbol should be
preferred if you know which
symbol you are looking for.
However, this can also be useful for small targeted edits of the body of a longer symbol (without
replacing the entire body).
- insert_before_symbol:
Inserts the given body/content before the beginning of the definition of the given symbol (via the
symbol's location).
A typical use case is to insert a new class, function, method, field or variable assignment.
It also can be used to insert a new import statement before the first symbol in the file.
- list_dir:
Lists all non-gitignored files and directories in the given directory (optionally with recursion).
Returns a JSON object with the names of directories and files within the given directory.
- list_memories:
List available memories. Any memory can be read using the `read_memory` tool.
- onboarding:
Call this tool if onboarding was not performed yet.
You will call this tool at most once per conversation. Returns instructions on how to create the
onboarding information.
- prepare_for_new_conversation:
Instructions for preparing for a new conversation. This tool should only be called on explicit user
request.
- serena__read_file:
Reads the given file or a chunk of it. Generally, symbolic operations
like find_symbol or find_referencing_symbols should be preferred if you know which symbols you are
looking for.
Reading the entire file is only recommended if there is no other way to get the content required for the
task. Returns the full text of the file at the given relative path.
- read_memory:
Read the content of a memory file. This tool should only be used if the information
is relevant to the current task. You can infer whether the information
is relevant from the memory file name.
You should not read the same memory file multiple times in the same conversation.
- remove_project:
Removes a project from the Serena configuration.
- replace_lines:
Replaces the given range of lines in the given file.
Requires that the same range of lines was previously read using the `read_file` tool to verify
correctness
of the operation.
- replace_regex:
Replaces one or more occurrences of the given regular expression.
This is the preferred way to replace content in a file whenever the symbol-level
tools are not appropriate.
Even large sections of code can be replaced by providing a concise regular expression of
the form "beginning.*?end-of-text-to-be-replaced".
Always try to use wildcards to avoid specifying the exact content of the code to be replaced,
especially if it spans several lines.
IMPORTANT: REMEMBER TO USE WILDCARDS WHEN APPROPRIATE! I WILL BE VERY UNHAPPY IF YOU WRITE LONG REGEXES
WITHOUT USING WILDCARDS INSTEAD!.
- replace_symbol_body:
Replaces the body of the symbol with the given `name_path`.
- restart_language_server:
Use this tool only on explicit user request or after confirmation.
It may be necessary to restart the language server if the user performs edits
not through Serena, so the language server state becomes outdated and further editing attempts lead to
errors.
If such editing errors happen, you should suggest using this tool.
- search_for_pattern:
Offers a flexible search for arbitrary patterns in the codebase, including the
possibility to search in non-code files.
Generally, symbolic operations like find_symbol or find_referencing_symbols
should be preferred if you know which symbols you are looking for.
Pattern Matching Logic:
For each match, the returned result will contain the full lines where the
substring pattern is found, as well as optionally some lines before and after it. The pattern will be
compiled with
DOTALL, meaning that the dot will match all characters including newlines.
This also means that it never makes sense to have .* at the beginning or end of the pattern,
but it may make sense to have it in the middle for complex patterns.
If a pattern matches multiple lines, all those lines will be part of the match.
Be careful to not use greedy quantifiers unnecessarily, it is usually better to use non-greedy
quantifiers like .*? to avoid
matching too much content.
File Selection Logic:
The files in which the search is performed can be restricted very flexibly.
Using `restrict_search_to_code_files` is useful if you are only interested in code symbols (i.e.,
those
symbols that can be manipulated with symbolic tools like find_symbol).
You can also restrict the search to a specific file or directory,
and provide glob patterns to include or exclude certain files on top of that.
The globs are matched against relative file paths from the project root (not to the `relative_path`
parameter that
is used to further restrict the search).
Smartly combining the various restrictions allows you to perform very targeted searches. Returns A
JSON object mapping file paths to lists of matched consecutive lines (with context, if requested).
- summarize_changes:
Summarize the changes you have made to the codebase.
This tool should always be called after you have fully completed any non-trivial coding task,
but only after the think_about_whether_you_are_done call.
- switch_modes:
Activates the desired modes, like ["editing", "interactive"] or ["planning", "one-shot"].
- think_about_collected_information:
Think about the collected information and whether it is sufficient and relevant.
This tool should ALWAYS be called after you have completed a non-trivial sequence of searching steps like
find_symbol, find_referencing_symbols, search_files_for_pattern, read_file, etc.
- think_about_task_adherence:
Think about the task at hand and whether you are still on track.
Especially important if the conversation has been going on for a while and there
has been a lot of back and forth.
This tool should ALWAYS be called before you insert, replace, or delete code.
- think_about_whether_you_are_done:
Whenever you feel that you are done with what the user has asked for, it is important to call this tool.
- write_memory:
Write some information about this project that can be useful for future tasks to a memory.
Use markdown formatting for the content.
The information should be short and to the point.
The memory name should be meaningful, such that from the name you can infer what the information is
about.
It is better to have multiple small memories than to have a single large one because
memories will be read one by one and we only ever want to read relevant memories.
This tool is either called during the onboarding process or when you have identified
something worth remembering about the project from the past conversation.
Using: 1 MCP server (ctrl+t to toggle)
GPTの助言を信じて公開
このbash出力(ログ)には、以下の点から「公開すると問題のある情報」は基本的に含まれていないと考えられます。
含まれている内容
プロジェクトの概要(Remix、React、Tailwind CSS、TypeScriptを使っていること)
ディレクトリ内のファイル読み込みや解析の状況
コマンドの実行ログやツールの説明
含まれていない情報
APIキー、パスワード、シークレット情報
個人情報(名前、メールアドレスなど)
内部ネットワークやIPアドレス
特定のユーザー情報や機密データ
ただし注意したほうがよい点
将来的にpackage.jsonやソースコードの内容に秘密情報(環境変数、APIキーなど)が含まれている場合は注意が必要。
実際のファイル中にトークンやパスワードが書かれていないかは別途確認推奨。
結論
今回提示されたbashの出力ログ自体には公開リスクのある機密情報は含まれていません。
公開して問題ない内容と言えます。
もし別に具体的なファイルの中身を共有する場合は、その内容に機密情報が含まれていないかを必ず確認してください。
╭────────────────────────────────────────╮
│ > read Serena's initial instructions │
╰────────────────────────────────────────╯
これをgeminiで実行したところ、.serenaディレクトリが作られて、その中に色々とmdファイルが作られたのできっとうまく行っているのだろう
custom slash command
claude codeはmdなので、tomlに変換。普通のtomlではgemini側からうまく認識されなかったので、gemini cliのcustom slash commandのドキュメントをそのまま突っ込んだ。
依頼したプロンプト
次のドキュメントが、目的のtomlを作成するためのドキュメントなのですが、それに基づいて、tomlファイルを修正できますか?
Today, we're announcing support for custom slash commands in Gemini CLI! This highly requested feature lets you define reusable prompts for streamlining interactions with Gemini CLI and helps improve efficiency across workflows. Slash commands can be defined in local .toml files or through Model Context Protocol (MCP) prompts. Get ready to transform how you leverage Gemini CLI with the new power of slash commands!
To use slash commands, make sure that you update to the latest version of Gemini CLI.
Update npx:
npx @google/gemini-cli
Update npm:
npm install -g @google/gemini-cli@latest
Powerful and extensible foundation with .toml files
The foundation of custom slash commands is rooted in .toml files.
The .toml file provides a powerful and structured base on which to build extensive support for complex commands. To help support a wide range of users, we made the required keys minimal (just prompt). And we support easy-to-use args with {{args}} and shell command execution !{...} directly into the prompt.
Here is an example .toml file that is invoked using /review <issue_number> from Gemini CLI to review a GitHub PR. Notice that the file name defines the command name and it's case sensitive. For more information about custom slash commands, see the Custom Commands section of the Gemini CLI documentation.
description="Reviews a pull request based on issue number."
prompt = """
Please provide a detailed pull request review on GitHub issue: {{args}}.
Follow these steps:
- Use
gh pr view {{args}}
to pull the information of the PR. - Use
gh pr diff {{args}}
to view the diff of the PR. - Understand the intent of the PR using the PR description.
- If PR description is not detailed enough to understand the intent of the PR,
make sure to note it in your review. - Make sure the PR title follows Conventional Commits, here are the last five
commits to the repo as examples: !{git log --pretty=format:"%s" -n 5} - Search the codebase if required.
- Write a concise review of the PR, keeping in mind to encourage strong code
quality and best practices. - Use
gh pr comment {{args}} --body {{review}}
to post the review to the PR.
Remember to use the GitHub CLI (gh
) with the Shell tool for all
GitHub-related tasks.
"""
Namespacing
The name of a command is determined by its file path relative to the commands directory. Sub-directories are used to create namespaced commands, with the path separator (/ or ) being converted to a colon (:).
A file at <project>/.gemini/commands/test.toml becomes the command /test.
A file at <project>/.gemini/commands/git/commit.toml becomes the namespaced command /git:commit.
This allows grouping related commands under a single namespace.
Building a slash command
The next few sections show you how to build a slash command for Gemini CLI.
1 - Create the command file
First, create a file named plan.toml inside the ~/.gemini/commands/ directory. Doing so will let you create a /plan command to tell Gemini CLI to only plan the changes by providing a step-by-step plan and to not start on implementation. This approach will let you provide feedback and iterate on the plan before implementation.
Custom slash commands can be scoped to an individual user or project by defining the .toml files in designated directories.
User-scoped commands are available across all Gemini CLI projects for a user and are stored in ~/.gemini/commands/ (note the ~).
Project-scoped commands are only available from sessions within a given project and are stored in .gemini/commands/.
Hint: To streamline project workflows, check these into Git repositories!
mkdir -p ~/.gemini/commands
touch ~/.gemini/commands/plan.toml
2 - Add the command definition
Open plan.toml and add the following content:
~/.gemini/commands/plan.toml
description="Investigates and creates a strategic plan to accomplish a task."
prompt = """
Your primary role is that of a strategist, not an implementer.
Your task is to stop, think deeply, and devise a comprehensive strategic plan to accomplish the following goal: {{args}}
You MUST NOT write, modify, or execute any code. Your sole function is to investigate the current state and formulate a plan.
Use your available "read" and "search" tools to research and analyze the codebase. Gather all necessary context before presenting your strategy.
Present your strategic plan in markdown. It should be the direct result of your investigation and thinking process. Structure your response with the following sections:
- Understanding the Goal: Re-state the objective to confirm your understanding.
- Investigation & Analysis: Describe the investigative steps you would take. What files would you need to read? What would you search for? What critical questions need to be answered before any work begins?
- Proposed Strategic Approach: Outline the high-level strategy. Break the approach down into logical phases and describe the work that should happen in each.
- Verification Strategy: Explain how the success of this plan would be measured. What should be tested to ensure the goal is met without introducing regressions?
-
Anticipated Challenges & Considerations: Based on your analysis, what potential risks, dependencies, or trade-offs do you foresee?
Your final output should be ONLY this strategic plan.
"""
3 - Use the command
Now you can use this command within Gemini CLI:
/plan How can I make the project more performant?
Gemini will plan out the changes and output a detailed step-by-step execution plan!
Enriched integration with MCP Prompts
Gemini CLI now offers a more integrated experience with MCP by supporting MCP Prompts as slash commands! MCP provides a standardized way for servers to expose prompt templates to clients. Gemini CLI utilizes this to expose available prompts for configured MCP servers and make the prompts available as slash commands.
The name and description of the MCP prompt is used as the slash command name and description. MCP prompt arguments are also supported and leveraged in slash commands by using /mycommand --<argument_name>="<argument_value>" or positionally /mycommand <argument1> <argument2>.
The following is an example /research command that uses FastMCP Python server:
So what are you waiting for? Upgrade your terminal experience with Gemini CLI today and try out custom slash commands to streamline your workflows. To learn more, check out the Custom Commands documentation for the Gemini CLI.
出来上がったtoml
serena.toml
description = "Token-efficient Serena MCP command for structured app development and problem-solving."
prompt = """
You are an expert app developer and problem solver using Serena MCP.
You will receive a command describing a problem or task: {{args}}
Based on the command, choose the appropriate approach automatically (Debug, Design, Implement, Optimize, Review) by keywords.
Use Serena MCP tools to:
- perform analysis, debugging, design, or implementation planning
- research relevant documentation using Context7 MCP if needed
- synthesize actionable solutions with clear next steps
- create implementation todos if requested
You can apply these command options in your process:
- -q for quick mode (3-5 steps)
- -d for deep mode (10-15 steps)
- -c for code-focused analysis
- -s for step-by-step implementation with todos
- -v for verbose output showing thought process
- -r to include research phase
- -t to create implementation todos
Here are typical usage patterns:
- Debug: error, bug, issue, broken, failing → 5-8 thought steps
- Design: architecture, system, plan → 8-12 thought steps
- Implement: build, create, add feature → 6-10 thought steps
- Optimize: performance, slow, improve, refactor → 4-7 thought steps
- Review: analyze, check, evaluate → 4-7 thought steps
Structure your response clearly and concisely. Consider security, performance, and maintainability.
Respond ONLY with the solution or plan as instructed.
"""
serena initを追加してみた
これでいけるっぽい
init.toml
description = "Initializes the Serena project by reading initial instructions and creating .serena/project.yml."
prompt = """
You are a project assistant specialized in Serena MCP.
When invoked, perform the following steps:
1. Read the initial instructions for the project thoroughly.
2. Based on the instructions, generate or initialize the configuration file at .serena/project.yml.
3. Confirm the successful creation of the project configuration.
4. Provide a brief summary of the initialization results.
Do not proceed to other tasks until the initialization is confirmed complete.
Your output should be clear and concise, focusing only on the initialization process.
"""
serena/init.tomlの変更
挙動が安定しないので次のように変更
description = "Initializes the Serena project by reading initial instructions and creating .serena/"
prompt = """
You are a project assistant specialized in Serena MCP.
When invoked, perform the following steps:
1. activate: activate the root directory
2. onboarding: read Serena's initial instructions
Do not proceed to other tasks until the initialization is confirmed complete.
Your output should be clear and concise, focusing only on the initialization process.
"""
activateとonboardingを直接指示すれば良いと言えばそうなのだが、コマンドラインに出てくると忘れにくくなるのでひとまずこんな感じで。挙動は安定していたが、activateの時点で止まるので、2回実行が必要だった