Skip to main content
Glama
RichFerry

Production MCP Template

by RichFerry

workspace_read_text

Read-onlyIdempotent

Read a UTF-8 text file from the workspace root safely, with built-in traversal protection to prevent directory escapes. Specify the relative path and optionally limit bytes.

Instructions

Read a UTF-8 text file under the workspace root with traversal protection.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
relative_pathYes
max_bytesNo

Implementation Reference

  • The MCP tool handler function that receives relative_path and optional max_bytes, calls the workspace service's read_text method, and converts security/file-not-found errors to ValueError.
    @server.tool(
        name="workspace_read_text",
        annotations=ToolAnnotations(readOnlyHint=True, idempotentHint=True, openWorldHint=False),
    )
    async def workspace_read_text(relative_path: str, max_bytes: int | None = None) -> object:
        """Read a UTF-8 text file under the workspace root with traversal protection."""
        with container.metrics.observe_tool("workspace_read_text"):
            try:
                return container.workspace.read_text(
                    relative_path=relative_path,
                    max_bytes=max_bytes or container.settings.max_workspace_read_bytes,
                )
            except (WorkspaceSecurityError, FileNotFoundError) as exc:
                raise ValueError(str(exc)) from exc
  • The output schema for workspace_read_text, containing the path, bytes_read, truncated flag, and text content.
    class WorkspaceDocument(TemplateModel):
        path: str
        bytes_read: int
        truncated: bool
        content: str
  • The @server.tool decorator registers workspace_read_text as an MCP tool. The tool is also listed in the ModuleDescriptor returned by the register() function.
    @server.tool(
        name="workspace_read_text",
        annotations=ToolAnnotations(readOnlyHint=True, idempotentHint=True, openWorldHint=False),
    )
    async def workspace_read_text(relative_path: str, max_bytes: int | None = None) -> object:
        """Read a UTF-8 text file under the workspace root with traversal protection."""
        with container.metrics.observe_tool("workspace_read_text"):
            try:
                return container.workspace.read_text(
                    relative_path=relative_path,
                    max_bytes=max_bytes or container.settings.max_workspace_read_bytes,
                )
            except (WorkspaceSecurityError, FileNotFoundError) as exc:
                raise ValueError(str(exc)) from exc
  • The underlying WorkspaceService.read_text method that resolves the path, reads the file (with byte limit), handles truncation, and decodes UTF-8 content.
    def read_text(self, relative_path: str, max_bytes: int) -> WorkspaceDocument:
        resolved = self.resolve_path(relative_path)
        if not resolved.is_file():
            raise FileNotFoundError(f"{relative_path!r} is not a file under {self.root}")
    
        with resolved.open("rb") as handle:
            payload = handle.read(max_bytes + 1)
    
        truncated = len(payload) > max_bytes
        content = payload[:max_bytes].decode("utf-8", errors="replace")
    
        return WorkspaceDocument(
            path=str(resolved.relative_to(self.root)),
            bytes_read=min(len(payload), max_bytes),
            truncated=truncated,
            content=content,
        )
  • Helper method that resolves a relative path against the workspace root and enforces the path does not escape the root directory (traversal protection).
    def resolve_path(self, relative_path: str) -> Path:
        candidate = Path(relative_path)
        resolved = candidate.resolve() if candidate.is_absolute() else (self.root / candidate).resolve()
    
        if not resolved.is_relative_to(self.root):
            raise WorkspaceSecurityError(f"Path {relative_path!r} escapes workspace root {self.root}")
    
        return resolved
Behavior3/5

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

Annotations already indicate read-only and idempotent behavior. The description adds 'traversal protection' as a safety constraint. However, it does not disclose behavior on file not found, encoding errors, or the effect of the max_bytes parameter. The description adds modest value beyond 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 a single, front-loaded sentence that conveys the essential action and a key safety aspect. Every word earns its place with no redundancy or unnecessary detail.

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?

For a simple tool with two parameters and no output schema, the description is minimally adequate. It states the input location and encoding but omits what is returned (the file content) and does not hint at error conditions or behavior when max_bytes is exceeded.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate. While 'relative_path' is somewhat explained by the tool's purpose (reading under workspace root), 'max_bytes' receives no extra explanation. The description does not add meaning beyond parameter names or clarify defaults and constraints.

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 action (Read) and the resource (UTF-8 text file under workspace root). It adds a specific safety detail ('traversal protection') that further clarifies the purpose and distinguishes it from sibling tools like workspace_inventory.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives. There is no mention of file types, size limits, or comparisons with sibling tools. The description solely states what the tool does without usage context.

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/RichFerry/MCP-Template'

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