Skip to main content
Glama

Read File

read_file
Read-only

Retrieve file contents or specific line ranges from codebases to analyze source code, review implementations, or extract data for development tasks.

Instructions

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. Returns the full text of the file at the given relative path.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
relative_pathYesThe relative path to the file to read.
start_lineNoThe 0-based index of the first line to be retrieved.
end_lineNoThe 0-based index of the last line to be retrieved (inclusive). If None, read until the end of the file.
max_answer_charsNoIf the file (chunk) is longer than this number of characters, no content will be returned. Don't adjust unless there is really no other way to get the content required for the task.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Handler implementation for the 'read_file' tool: the apply method of ReadFileTool reads the file content using project.read_file, extracts line range, and limits length if specified.
    class ReadFileTool(Tool):
        """
        Reads a file within the project directory.
        """
    
        def apply(self, relative_path: str, start_line: int = 0, end_line: int | None = None, max_answer_chars: int = -1) -> str:
            """
            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.
    
            :param relative_path: the relative path to the file to read
            :param start_line: the 0-based index of the first line to be retrieved.
            :param end_line: the 0-based index of the last line to be retrieved (inclusive). If None, read until the end of the file.
            :param max_answer_chars: if the file (chunk) is longer than this number of characters,
                no content will be returned. Don't adjust unless there is really no other way to get the content
                required for the task.
            :return: the full text of the file at the given relative path
            """
            self.project.validate_relative_path(relative_path, require_not_ignored=True)
    
            result = self.project.read_file(relative_path)
            result_lines = result.splitlines()
            if end_line is None:
                result_lines = result_lines[start_line:]
            else:
                result_lines = result_lines[start_line : end_line + 1]
            result = "\n".join(result_lines)
    
            return self._limit_length(result, max_answer_chars)
  • Tool.get_name_from_cls derives the tool name 'read_file' from the ReadFileTool class name.
    @classmethod
    def get_name_from_cls(cls) -> str:
        name = cls.__name__
        if name.endswith("Tool"):
            name = name[:-4]
        # convert to snake_case
        name = "".join(["_" + c.lower() if c.isupper() else c for c in name]).lstrip("_")
        return name
  • ToolRegistry automatically discovers Tool subclasses like ReadFileTool in serena.tools packages and registers them with names derived from class names.
    @singleton
    class ToolRegistry:
        def __init__(self) -> None:
            self._tool_dict: dict[str, RegisteredTool] = {}
            for cls in iter_subclasses(Tool):
                if not any(cls.__module__.startswith(pkg) for pkg in tool_packages):
                    continue
                is_optional = issubclass(cls, ToolMarkerOptional)
                name = cls.get_name_from_cls()
                if name in self._tool_dict:
                    raise ValueError(f"Duplicate tool name found: {name}. Tool classes must have unique names.")
                self._tool_dict[name] = RegisteredTool(tool_class=cls, is_optional=is_optional, tool_name=name)
  • Derives schema metadata from the apply method signature and docstring using func_metadata for MCP tool definition.
    def get_apply_fn_metadata_from_cls(cls) -> FuncMetadata:
        """Get the metadata for the apply method from the class (static metadata).
        Needed for creating MCP tools in a separate process without running into serialization issues.
        """
        # First try to get from __dict__ to handle dynamic docstring changes
        if "apply" in cls.__dict__:
            apply_fn = cls.__dict__["apply"]
        else:
            # Fall back to getattr for inherited methods
            apply_fn = getattr(cls, "apply", None)
            if apply_fn is None:
                raise AttributeError(f"apply method not defined in {cls}. Did you forget to implement it?")
    
        return func_metadata(apply_fn, skip_names=["self", "cls"])
  • Project.read_file helper method called by the tool handler to safely read file contents using FileUtils.
    def read_file(self, relative_path: str) -> str:
        """
        Reads a file relative to the project root.
    
        :param relative_path: the path to the file relative to the project root
        :return: the content of the file
        """
        abs_path = Path(self.project_root) / relative_path
        return FileUtils.read_file(str(abs_path), self.project_config.encoding)
Behavior4/5

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

Annotations already declare readOnlyHint=true and destructiveHint=false, indicating a safe read operation. The description adds valuable context beyond this: it explains that it can read 'a chunk' of a file (via start_line/end_line parameters) and warns about the max_answer_chars constraint ('no content will be returned' if exceeded). This enhances behavioral understanding without contradicting annotations.

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

Conciseness5/5

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

The description is efficiently structured in two sentences: the first states the core functionality and preferred alternatives, the second clarifies the return value. Every sentence serves a clear purpose with zero wasted words, making it easy to parse and understand quickly.

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

Completeness5/5

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

Given the tool's moderate complexity (4 parameters, 1 required), 100% schema coverage, annotations covering safety, and an output schema (implied by 'Returns...'), the description is complete. It covers purpose, guidelines, and key behavioral aspects without needing to repeat schema details or explain return values extensively.

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 fully documents all four parameters. The description mentions 'chunk' reading and the max_answer_chars behavior, but these details are already covered in the schema descriptions for start_line, end_line, and max_answer_chars. It adds minimal semantic value beyond what the structured schema provides.

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 specific action ('Reads') and resource ('the given file or a chunk of it'), distinguishing it from sibling tools like find_symbol or find_referencing_symbols. It explicitly mentions what it returns ('full text of the file at the given relative path'), making the purpose unambiguous and well-defined.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use alternatives: 'Generally, symbolic operations like find_symbol or find_referencing_symbols should be preferred if you know which symbols you are looking for.' This clearly indicates when not to use this tool and names specific sibling alternatives, offering strong contextual direction.

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/oraios/serena'

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