Skip to main content
Glama
safurrier

MCP Filesystem Server

get_file_info

Retrieve detailed metadata about files or directories, including path information and output format options for system analysis.

Instructions

Retrieve detailed metadata about a file or directory.

Args:
    path: Path to the file or directory
    format: Output format ('text' or 'json')
    ctx: MCP context

Returns:
    Formatted file information

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
formatNotext

Implementation Reference

  • MCP tool handler function for 'get_file_info'. Decorated with @mcp.tool() which registers it with the FastMCP server. Handles input parameters, delegates to FileOperations.get_file_info, formats output as text or JSON, and returns error messages.
    @mcp.tool()
    async def get_file_info(path: str, ctx: Context, format: str = "text") -> str:
        """Retrieve detailed metadata about a file or directory.
    
        Args:
            path: Path to the file or directory
            format: Output format ('text' or 'json')
            ctx: MCP context
    
        Returns:
            Formatted file information
        """
        try:
            components = get_components()
            info = await components["operations"].get_file_info(path)
    
            if format.lower() == "json":
                return json.dumps(info.to_dict(), indent=2)
            else:
                return str(info)
        except Exception as e:
            return f"Error getting file info: {str(e)}"
  • Core implementation of get_file_info in FileOperations class. Performs path validation using PathValidator, checks existence, and instantiates/returns a FileInfo object.
    async def get_file_info(self, path: Union[str, Path]) -> FileInfo:
        """Get detailed information about a file or directory.
    
        Args:
            path: Path to the file or directory
    
        Returns:
            FileInfo object with detailed information
    
        Raises:
            ValueError: If path is outside allowed directories
            FileNotFoundError: If file does not exist
        """
        abs_path, allowed = await self.validator.validate_path(path)
        if not allowed:
            raise ValueError(f"Path outside allowed directories: {path}")
    
        if not abs_path.exists():
            raise FileNotFoundError(f"File not found: {path}")
    
        return FileInfo(abs_path)
  • FileInfo dataclass defining the output schema for file metadata, including methods for dictionary serialization (to_dict) and string representation (__str__). Used by get_file_info implementations.
    class FileInfo:
        """Information about a file or directory."""
    
        def __init__(self, path: Path):
            """Initialize with a file path.
    
            Args:
                path: Path to the file or directory
    
            Raises:
                FileNotFoundError: If the file or directory does not exist
            """
            self.path = path
            self.stat = path.stat()
            self.is_dir = path.is_dir()
            self.is_file = path.is_file()
            self.is_symlink = path.is_symlink()
            self.size = self.stat.st_size
            self.created = datetime.fromtimestamp(self.stat.st_ctime)
            self.modified = datetime.fromtimestamp(self.stat.st_mtime)
            self.accessed = datetime.fromtimestamp(self.stat.st_atime)
            self.name = path.name
    
            # Format permissions similar to Unix 'ls -l'
            mode = self.stat.st_mode
            self.permissions = "".join(
                [
                    "r" if mode & stat.S_IRUSR else "-",
                    "w" if mode & stat.S_IWUSR else "-",
                    "x" if mode & stat.S_IXUSR else "-",
                    "r" if mode & stat.S_IRGRP else "-",
                    "w" if mode & stat.S_IWGRP else "-",
                    "x" if mode & stat.S_IXGRP else "-",
                    "r" if mode & stat.S_IROTH else "-",
                    "w" if mode & stat.S_IWOTH else "-",
                    "x" if mode & stat.S_IXOTH else "-",
                ]
            )
    
            # Numeric permissions in octal
            self.permissions_octal = oct(mode & 0o777)[2:]
    
        def to_dict(self) -> Dict:
            """Convert to dictionary.
    
            Returns:
                Dictionary with file information
            """
            return {
                "name": self.name,
                "path": str(self.path),
                "size": self.size,
                "created": self.created.isoformat(),
                "modified": self.modified.isoformat(),
                "accessed": self.accessed.isoformat(),
                "is_directory": self.is_dir,
                "is_file": self.is_file,
                "is_symlink": self.is_symlink,
                "permissions": self.permissions,
                "permissions_octal": self.permissions_octal,
            }
    
        def __str__(self) -> str:
            """Get string representation.
    
            Returns:
                Formatted string with file information
            """
            file_type = "Directory" if self.is_dir else "File"
            symlink_info = " (symlink)" if self.is_symlink else ""
            size_str = f"{self.size:,} bytes"
    
            return (
                f"{file_type}{symlink_info}: {self.path}\n"
                f"Size: {size_str}\n"
                f"Created: {self.created.isoformat()}\n"
                f"Modified: {self.modified.isoformat()}\n"
                f"Accessed: {self.accessed.isoformat()}\n"
                f"Permissions: {self.permissions} ({self.permissions_octal})"
            )
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions retrieving metadata but doesn't specify what metadata is included (e.g., size, permissions, timestamps), error handling for non-existent paths, or any rate limits or authentication needs. This leaves significant gaps for a tool that likely interacts with file systems.

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 front-loaded with the core purpose in the first sentence, followed by structured sections for Args and Returns. It's efficient with minimal waste, though the 'ctx' parameter is mentioned without explanation, slightly reducing clarity.

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

Completeness2/5

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

Given the complexity of file operations, no annotations, and no output schema, the description is incomplete. It lacks details on metadata content, error cases, permissions, or return structure, making it inadequate for safe and effective use by an AI agent in this context.

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?

The description lists parameters 'path', 'format', and 'ctx', adding meaning beyond the input schema (which only covers 'path' and 'format' with 0% schema description coverage). It explains 'path' as 'Path to the file or directory' and 'format' as 'Output format ('text' or 'json')', which compensates partially for the low schema coverage, but doesn't detail 'ctx' or provide examples.

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

Purpose4/5

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

The description clearly states the verb 'retrieve' and resource 'detailed metadata about a file or directory', which is specific and unambiguous. It distinguishes from siblings like 'read_file' (content) or 'list_directory' (listing), though it doesn't explicitly mention those distinctions.

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. For example, it doesn't explain when to choose 'get_file_info' over 'list_directory' for metadata or 'read_file' for content, nor does it mention prerequisites like file existence or permissions.

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/safurrier/mcp-filesystem'

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