Serena Tools System
Overview
Serena's tool system is defined by src/…/tools_base.py and exposed as concrete tool classes under src/serena/tools/. A tool is a Tool subclass with an apply(...) -> str method; the class docstring becomes the high-level tool description, and the apply docstring plus type annotations are converted to MCP function metadata by Tool.get_apply_fn_metadata_from_cls() via mcp.server.mcpserver.utilities.func_metadata.func_metadata. Tool names are derived from class names in Tool.get_name_from_cls() by stripping a trailing Tool and converting to snake case, so ExecuteShellCommandTool is registered as execute_shell_command.
All tool classes inherit Component, which gives them access to the active SerenaAgent, active Project, prompt factory, memory manager, language backend, symbol retriever, and code editor through src/…/tools_base.py. The common execution path is Tool.apply_ex(): it records MCP client information when a Context is provided, checks whether the tool is active, enforces active-project requirements unless the class implements ToolMarkerDoesNotRequireActiveProject, calls the concrete apply, retries once if a SolidLSPException indicates that a language server terminated, records usage on the agent, saves language-server caches if due, and runs the whole call through the agent task executor with serena_config.tool_timeout. Errors are normalized to ToolCallError; with catch_exceptions=True they are returned as strings instead of being raised. Tools that accept user text paths or patterns can call _sanitize_input_param() to undo clients that HTML-escape < and >.
Tool behavior and availability are declared with marker base classes in src/…/tools_base.py. ToolMarkerCanEdit marks edit-capable tools; ToolMarkerSymbolicEdit inherits it for refactoring/symbol edits, and ToolMarkerSymbolicRead identifies symbol-read tools. ToolMarkerOptional means disabled by default, ToolMarkerBeta flags beta tools, and ToolMarkerDoesNotRequireActiveProject bypasses the active-project guard. EditingToolWithDiagnostics is the shared base for file-editing tools that may wrap edits in a DiagnosticsContext, though its global ENABLE_DIAGNOSTICS flag is currently false.
ToolRegistry in src/…/tools_base.py is a singleton that discovers concrete tool classes by iterating subclasses of Tool and including only classes whose module starts with serena.tools and whose class dictionary defines apply. Registration is assembled through src/…/__init__.py, which imports every tool-family module so subclass discovery can see them. The registry stores RegisteredTool records containing the class, generated tool name, optional flag, and beta flag; it rejects duplicate names, separates default-enabled from optional tools, validates tool names, and tracks deleted legacy names such as switch_modes and check_onboarding_performed so callers can distinguish invalid names from removed ones. scripts/print_tool_overview.py is a small CLI that instantiates ToolRegistry and prints default-enabled tool names and class descriptions.
Most concrete tool families are thin adapters over REPL facade APIs. They import those APIs lazily inside mixins because the API modules refer back to the tools they correspond to:
- src/…/cmd_tools.py exposes
execute_shell_commandthroughShellApi.execute_shell_command(...). It is edit-capable because shell commands can modify the project; its docstring explicitly warns against unsafe, long-running, or interactive commands. - src/…/config_tools.py exposes configuration/session tools.
activate_projectandget_current_configare default tools, whileopen_dashboardandremove_projectare optional.activate_projectandopen_dashboarddo not require an active project;activate_projectaccepts asessionparameter rather thansession_iddue to a Claude Desktop client bug and returns the agent's project activation message. - src/…/file_tools.py provides file-system reads (
read_file,list_dir,find_file,search_for_pattern), file creation (create_text_file), content-level replacement (replace_content,replace_in_files), and optional line-editing tools (delete_lines,replace_lines,insert_at_line). Read/list/search tools delegate toFsApi; editing tools delegate toEditApiand wrap changes indiagnostics_context(...)where appropriate.replace_in_filessupports a dry-run flow with occurrence IDs and anexpected_countguard so broad multi-file replacements can fail safely without changing files. - src/…/symbol_tools.py provides LSP-backed symbolic tools through
LspApi. Read tools include overviews, symbol search, references, implementations, declaration lookup, and diagnostics. Edit tools includereplace_symbol_body,insert_after_symbol,insert_before_symbol,rename_symbol, andsafe_delete_symbol.find_symbolsupports a parameter alias fromname_pathtoname_path_pattern, and declaration lookup sanitizes escaped input before sending regexes and paths to the backend. - src/…/memory_tools.py exposes project memory operations through
MemoryApi: write, read, list, delete, rename, and regex/literal edit. Write/delete/rename/edit are edit-capable. Memory names can use/topics,global/is reserved for explicit requests, and rename updatesmem:references except in read-only memories. - src/…/workflow_tools.py exposes workflow helpers.
onboardingis edit-capable because it writes memories and only proceeds ifWriteMemoryToolis available.initial_instructionsreturns the full Serena system prompt and does not require a project. Optionalserena_infocurrently handles thejet_brains_debug_repltopic by returning a prompt-factory help page. - src/…/query_project_tools.py provides optional cross-project read-only querying.
list_queryable_projectslists registered projects, narrowing to JetBrains clients with symbol access when the active backend is JetBrains.query_projectrejects non-read-only tools, usesProjectServerClientfor LSP symbolic read tools, and otherwise runs the requested tool under a temporaryactive_project_contextafter decoding JSON parameters. - src/…/jetbrains_tools.py provides optional JetBrains-backed symbol and refactoring tools through
JetBrainsApi. These mirror many LSP symbolic operations but add IDE-specific capabilities: dependency search injet_brains_find_symbol, file/directory/symbol move, safe delete with propagation, inline symbol, type hierarchy, IDE inspections, inspection listing, rename of symbols/files/directories, and a persistent debug REPL. Several methods sanitize paths/patterns before handing them to the IDE backend, and wildcard-onlyjet_brains_find_symbolcalls restricted to a file are redirected tojet_brains_get_symbols_overviewwith a wrapped response. - src/…/repl_tools.py exposes optional beta
serena_repl, an edit-capable Python notebook-like interface to Serena facades. Its dynamicget_apply_docstring()appends available facade documentation when the agent is in a single-project state; top-level definitions persist within the provided Serena session, and results are returned from the last expression rather than fromprint.
Edit-capability metadata for hook processes is generated rather than maintained by hand. scripts/gen_tool_capabilities.py creates a ToolRegistry, filters all registered classes by tool_class.can_edit(), sorts their generated names, and writes src/…/tool_capabilities.py deterministically. The generated module currently exports EDIT_CAPABLE_TOOL_NAMES as a frozenset[str] containing file edits, memory edits, shell execution, onboarding, LSP/JetBrains symbolic edits, and serena_repl.
Coupling
- If a concrete tool is added, renamed, or moved under
src/serena/tools/, verify src/…/__init__.py still imports its module; otherwiseToolRegistryin src/…/tools_base.py may not discover it during subclass iteration. - If a tool can mutate files, memories, shell state, or project contents, it must inherit
ToolMarkerCanEditdirectly or throughToolMarkerSymbolicEdit/EditingToolWithDiagnostics; otherwise scripts/gen_tool_capabilities.py will omit it from src/…/tool_capabilities.py and read-only enforcement such asQueryProjectTool.apply()in src/…/query_project_tools.py may classify it incorrectly. - If marker classes or
Tool.can_edit()change in src/…/tools_base.py, regenerate src/…/tool_capabilities.py with scripts/gen_tool_capabilities.py; the generated file is consumed as lightweight static metadata and is not updated automatically at runtime. - If an
applysignature or docstring changes in any src/…/*_tools.py file, check MCP clients that rely onTool.get_apply_fn_metadata_from_cls()in src/…/tools_base.py; parameters namedsessioninactivate_projectandserena_replare intentional workarounds for a Claude Desktopsession_idbug. - If a tool delegates to a REPL API via a mixin, preserve the local import pattern in files such as src/…/file_tools.py, src/…/symbol_tools.py, and src/…/jetbrains_tools.py; the comments state that API modules refer back to tools, so eager top-level imports can introduce circular imports.
- If the semantics of
Tool.is_readonly()orTool.is_symbolic()change in src/…/tools_base.py, verify src/…/query_project_tools.py; it relies on read-only checks to block mutating cross-project calls and on symbolic-read detection to decide when an LSP project-server query is required.
Risks
- src/…/tools_base.py discovers only classes whose own
__dict__containsapply. If a future tool inherits anapplyimplementation instead of defining one directly, it will not be registered, so it will be absent from MCP/REPL exposure and from generated capability metadata. - src/…/tool_capabilities.py is a checked-in generated file. If a developer changes edit markers in
src/serena/tools/*but forgets to run scripts/gen_tool_capabilities.py, hook processes can use staleEDIT_CAPABLE_TOOL_NAMES, causing mutating tools to be missed or read-only tools to be over-restricted. - src/…/tools_base.py runs every tool through
agent.issue_task(..., timeout=serena_config.tool_timeout). Tools that start long-running or interactive work, especiallyexecute_shell_commandin src/…/cmd_tools.py or arbitrary code inserena_replfrom src/…/repl_tools.py, can hit the timeout path and return only a timeout error while any unmanaged subprocess behavior depends on the delegated API.