Skip to main content
Glama
lin2000wl

Serena MCP Server

by lin2000wl

insert_before_symbol

Inserts content before a symbol's definition in code files to add classes, functions, imports, or other elements at specific locations.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
name_pathYesName path of the symbol before which to insert content (definitions in the `find_symbol` tool apply).
relative_pathYesThe relative path to the file containing the symbol.
bodyYesThe body/content to be inserted before the line in which the referenced symbol is defined.

Implementation Reference

  • Main entry point (handler) for the 'insert_before_symbol' tool. Finds the symbol by name and file, then delegates to the low-level insertion method.
    def insert_before_symbol(self, name_path: str, relative_file_path: str, body: str, *, use_same_indentation: bool = True) -> None:
        """
        Inserts content before the symbol with the given name in the given file.
        """
        symbol_candidates = self.find_by_name(name_path, within_relative_path=relative_file_path)
        if len(symbol_candidates) == 0:
            raise ValueError(f"No symbol with name {name_path} found in file {relative_file_path}")
        if len(symbol_candidates) > 1:
            raise ValueError(
                f"Found multiple {len(symbol_candidates)} symbols with name {name_path} in file {relative_file_path}. "
                f"May be an overwritten variable, in which case you can ignore this error. Proceeding with the first one. "
                f"Found symbols at locations: \n" + json.dumps([s.location.to_dict() for s in symbol_candidates], indent=2)
            )
        symbol = symbol_candidates[0]
        self.insert_before_symbol_at_location(symbol.location, body, use_same_indentation=use_same_indentation)
  • Helper function that performs the actual text insertion before the symbol's body start, handling indentation, newlines, and editing context.
    def insert_before_symbol_at_location(self, location: SymbolLocation, body: str, *, use_same_indentation: bool = True) -> None:
        """
        Inserts content before the given symbol
    
        :param location: the location of the symbol before which to add new lines
        :param body: the body of the entity to insert
        """
        with self._edited_symbol_location(location) as symbol:
            symbol_start_pos = symbol.body_start_position
            if symbol_start_pos is None:
                raise ValueError(f"Symbol at {location} does not have a defined start position.")
    
            if use_same_indentation:
                indent = " " * (symbol_start_pos["character"])
                body = "\n".join(indent + line for line in body.splitlines())
    
            # insert position is the start of line where the symbol is defined
            line = symbol_start_pos["line"]
            col = 0
    
            original_trailing_empty_lines = self._count_trailing_newlines(body) - 1
    
            # ensure eol is present at end
            body = body.rstrip() + "\n"
    
            # add suitable number of trailing empty lines after the body (at least 0/1 depending on the symbol type,
            # otherwise as many as the caller wanted to insert)
            min_trailing_empty_lines = 0
            if symbol.is_neighbouring_definition_separated_by_empty_line():
                min_trailing_empty_lines = 1
            num_trailing_newlines = max(min_trailing_empty_lines, original_trailing_empty_lines)
            body += "\n" * num_trailing_newlines
    
            assert location.relative_path is not None
    
            self._lang_server.insert_text_at_position(location.relative_path, line=line, column=col, text_to_be_inserted=body)
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It describes the insertion action but lacks details on permissions needed, error handling (e.g., if the symbol is not found), whether the operation is idempotent, or what happens to existing content. For a mutation tool with zero annotation coverage, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with three sentences that are front-loaded: the first sentence states the core action, and the following sentences provide use cases without redundancy. Every sentence adds value, though it could be slightly more concise by combining the use case examples into one sentence.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (a mutation operation with 3 parameters), no annotations, and no output schema, the description is moderately complete. It covers the purpose and usage but lacks behavioral details like error handling or return values. For a tool with no structured safety or output information, it should do more to compensate, but it meets a minimum viable level.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters (name_path, relative_path, body) with clear descriptions. The description adds minimal value beyond the schema by implying the parameters' roles in the insertion process but does not provide additional syntax, format, or constraints details. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'inserts' and the resource 'body/content' before 'the definition of the given symbol', specifying the action and target. It distinguishes from siblings like 'insert_after_symbol' by specifying 'before' and from 'insert_at_line' by using symbol-based positioning, making the purpose specific and differentiated.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool: 'to insert a new class, function, method, field or variable assignment' or 'to insert a new import statement before the first symbol in the file'. It implies usage based on symbol-based insertion needs but does not explicitly state when not to use it or name alternatives like 'insert_at_line' for line-based insertion, though the context is sufficient for typical cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lin2000wl/Serena-cursor-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server