Skip to main content
Glama
knishioka

Treasure Data MCP Server

by knishioka

td_list_project_files

Extract and list all files and directories from a Treasure Data project archive to view project contents.

Instructions

List all files contained in a project archive.

This tool extracts and lists the content of a previously downloaded
project archive, showing all files and directories within the project.

Args:
    archive_path: The path to the downloaded project archive (.tar.gz file)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
archive_pathYes

Implementation Reference

  • The primary handler function for the 'td_list_project_files' tool. It validates the archive path, opens the tar.gz file, iterates through members with security checks, categorizes files by extension, and returns a structured list of files.
    @mcp.tool()
    async def td_list_project_files(archive_path: str) -> dict[str, Any]:
        """List all files contained in a project archive.
    
        This tool extracts and lists the content of a previously downloaded
        project archive, showing all files and directories within the project.
    
        Args:
            archive_path: The path to the downloaded project archive (.tar.gz file)
        """
        # Input validation - prevent path traversal
        if not _validate_archive_path(archive_path):
            return _format_error_response("Invalid archive path")
    
        try:
            if not os.path.exists(archive_path):
                return _format_error_response("Archive file not found")
    
            file_list = []
    
            with tarfile.open(archive_path, "r:gz") as tar:
                for member in tar.getmembers():
                    # Security check for each member
                    if not _safe_extract_member(member, "/tmp/validation"):
                        continue  # Skip unsafe members
    
                    file_info = {
                        "name": member.name,
                        "type": "directory" if member.isdir() else "file",
                        "size": member.size,
                    }
    
                    # Add extension information for files
                    if not member.isdir():
                        ext = Path(member.name).suffix.lower()
                        file_info["extension"] = ext
    
                        # Identify file types based on extension
                        if ext == ".dig":
                            file_info["file_type"] = "Digdag workflow"
                        elif ext == ".sql":
                            file_info["file_type"] = "SQL query"
                        elif ext == ".py":
                            file_info["file_type"] = "Python script"
                        elif ext in [".yml", ".yaml"]:
                            file_info["file_type"] = "YAML configuration"
                        else:
                            file_info["file_type"] = "Other"
    
                    file_list.append(file_info)
    
            # Sort files: directories first, then by name
            file_list.sort(key=lambda x: (0 if x["type"] == "directory" else 1, x["name"]))
    
            return {
                "success": True,
                "archive_path": archive_path,
                "file_count": len(file_list),
                "files": file_list,
            }
        except (OSError, tarfile.ReadError) as e:
            return _format_error_response(f"Failed to list project files: {str(e)}")
        except Exception as e:
            return _format_error_response(
                f"Unexpected error while listing project files: {str(e)}"
            )
  • Helper function to validate the archive_path input parameter, ensuring it points to a safe temporary .tar.gz file and prevents path traversal attacks.
    def _validate_archive_path(archive_path: str) -> bool:
        """Validate archive path to ensure it's in allowed temporary directories."""
        if not archive_path:
            return False
    
        # Normalize the path to prevent tricks
        normalized_path = os.path.normpath(archive_path)
    
        # Allow paths in temp directories or test paths
        temp_prefix = tempfile.gettempdir()
        allowed_prefixes = [temp_prefix, "/tmp"]
    
        if not any(normalized_path.startswith(prefix) for prefix in allowed_prefixes):
            return False
    
        # Prevent path traversal
        if ".." in normalized_path:
            return False
    
        if not archive_path.endswith(".tar.gz"):
            return False
        return True
  • Helper function to safely validate each tarfile member, preventing path traversal, absolute paths, and oversized files (zip bombs).
    def _safe_extract_member(member, extract_path: str) -> bool:
        """Safely extract a tar member, preventing path traversal and other attacks."""
        # Normalize the member name
        member_path = os.path.normpath(member.name)
    
        # Prevent absolute paths
        if member_path.startswith("/") or member_path.startswith("\\"):
            return False
    
        # Prevent path traversal
        if ".." in member_path:
            return False
    
        # Check final extracted path
        final_path = os.path.join(extract_path, member_path)
        if not final_path.startswith(extract_path):
            return False
    
        # Check file size (prevent zip bombs)
        if hasattr(member, "size") and member.size > MAX_FILE_SIZE:
            return False
    
        return True
  • Helper function used to format consistent error responses across tools.
    def _format_error_response(error_msg: str) -> dict[str, str]:
        """Format error response without exposing sensitive information."""
        return {"error": error_msg}
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses that the tool 'extracts and lists' content, implying read-only behavior, but doesn't mention performance characteristics, error conditions, or output format details. It adds some behavioral context but leaves gaps about what 'lists' actually returns.

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: purpose statement, elaboration, and parameter explanation. The structure is front-loaded with the core purpose first. Minor improvement possible by integrating parameter info more seamlessly, but overall efficient.

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 no annotations and no output schema, the description adequately covers the basic operation and parameter, but doesn't explain what the listing output looks like (structure, format, limitations). For a tool with 1 parameter and simple operation, it's minimally complete but could better address output expectations.

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

Parameters5/5

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

With 0% schema description coverage (schema has no parameter descriptions), the description fully compensates by explaining the single parameter: 'archive_path: The path to the downloaded project archive (.tar.gz file)'. This adds crucial semantic meaning beyond the bare schema, specifying file type and context.

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 ('List all files contained in a project archive') and distinguishes it from siblings like td_download_project_archive (which downloads) and td_read_project_file (which reads content). It specifies the resource (project archive files/directories) with precise scope.

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 that this tool operates on 'a previously downloaded project archive', implying it should be used after td_download_project_archive. However, it doesn't explicitly state when NOT to use it or name alternatives for similar operations, missing full sibling differentiation.

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/knishioka/td-mcp-server'

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