Skip to main content
Glama
aigo666

MCP Development Framework

parse_csv

Parse CSV files with support for multiple encoding formats to extract structured data for analysis and processing.

Instructions

解析CSV文件内容,支持各种编码格式

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesCSV文件的本地路径,例如'/path/to/data.csv'
encodingNo文件编码格式,例如'utf-8'、'gbk'等,默认自动检测

Implementation Reference

  • The main handler function that executes the parse_csv tool. It reads the CSV file using pandas, detects encoding if needed, provides file info, data preview, and descriptive statistics.
    async def execute(self, arguments: Dict[str, Any]) -> List[types.TextContent]:
        """
        解析CSV文件内容
        
        Args:
            arguments: 参数字典,必须包含'file_path'键,可选'encoding'键
        
        Returns:
            解析结果列表
        """
        if "file_path" not in arguments:
            return [types.TextContent(
                type="text",
                text="错误: 缺少必要参数 'file_path'"
            )]
        
        file_path = arguments["file_path"]
        # 处理文件路径,支持挂载目录的转换
        file_path = self.process_file_path(file_path)
        
        if not os.path.exists(file_path):
            return [types.TextContent(
                type="text",
                text=f"错误: 文件不存在: {file_path}"
            )]
        
        try:
            # 尝试自动检测编码
            encoding = arguments.get("encoding", None)
            if encoding is None:
                try:
                    import chardet
                    with open(file_path, 'rb') as f:
                        raw_data = f.read()
                        encoding = chardet.detect(raw_data)['encoding']
                except ImportError:
                    encoding = 'utf-8'  # 如果没有chardet,默认使用utf-8
            
            # 读取CSV文件
            df = pd.read_csv(file_path, encoding=encoding)
            
            # 获取基本信息
            info = {
                "文件名": os.path.basename(file_path),
                "行数": len(df),
                "列数": len(df.columns),
                "列名": list(df.columns),
                "数据预览": df.head().to_string()
            }
            
            # 生成描述性统计
            stats = df.describe().to_string()
            
            # 组合结果
            result = (
                f"CSV文件解析结果:\n\n"
                f"基本信息:\n"
                f"- 文件名: {info['文件名']}\n"
                f"- 行数: {info['行数']}\n"
                f"- 列数: {info['列数']}\n"
                f"- 列名: {', '.join(info['列名'])}\n\n"
                f"数据预览:\n{info['数据预览']}\n\n"
                f"描述性统计:\n{stats}"
            )
            
            return [types.TextContent(
                type="text",
                text=result
            )]
            
        except Exception as e:
            error_details = traceback.format_exc()
            return [types.TextContent(
                type="text",
                text=f"错误: 处理CSV文件时发生错误: {str(e)}\n{error_details}"
            )] 
  • Input schema defining the parameters for the parse_csv tool: required file_path and optional encoding.
    input_schema = {
        "type": "object",
        "required": ["file_path"],
        "properties": {
            "file_path": {
                "type": "string",
                "description": "CSV文件的本地路径,例如'/path/to/data.csv'",
            },
            "encoding": {
                "type": "string",
                "description": "文件编码格式,例如'utf-8'、'gbk'等,默认自动检测",
            }
        },
    }
  • Tool registration via @ToolRegistry.register decorator, class name CsvTool, and tool name 'parse_csv' assignment.
    @ToolRegistry.register
    class CsvTool(BaseTool):
        """
        CSV文件处理工具,用于解析CSV文件内容
        """
        
        name = "parse_csv"
        description = "解析CSV文件内容,支持各种编码格式"
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 support for various encoding formats, which adds some context about input handling. However, it doesn't describe what the tool returns (structure of parsed data), error conditions, performance characteristics, or any limitations. For a parsing tool with zero annotation coverage, this leaves significant behavioral gaps.

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 extremely concise - just one sentence that directly states the core function and a key capability. Every word earns its place with no redundancy or fluff. The structure is front-loaded with the primary purpose followed by an important feature.

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 tool has no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (parsed data structure), doesn't mention error handling for malformed CSV files, and provides minimal behavioral context. For a parsing tool that transforms file data, this leaves too many unknowns for effective agent usage.

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 schema description coverage is 100%, with both parameters well-documented in the schema itself. The description doesn't add any meaningful parameter semantics beyond what's already in the schema - it mentions encoding support generally but doesn't provide additional details about the encoding parameter. This meets the baseline score when schema coverage is complete.

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 tool's purpose as '解析CSV文件内容' (parse CSV file content), which is a specific verb+resource combination. However, it doesn't explicitly distinguish this CSV parsing tool from its sibling tools like parse_excel, parse_pdf, etc., which all parse different file formats. The mention of '支持各种编码格式' (supports various encoding formats) adds useful context but doesn't differentiate from siblings.

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?

The description provides no guidance on when to use this tool versus alternatives. There's no mention of when this CSV parser should be used instead of other parsing tools like parse_excel or parse_file, nor any context about prerequisites or limitations. The agent receives no usage direction beyond the basic function.

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/aigo666/mcp-framework'

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