Skip to main content
Glama
tofunori

Claude MCP Data Explorer

by tofunori

load-csv

Load CSV files into structured DataFrames for data analysis and exploration within Claude's environment.

Instructions

Load a CSV file into a DataFrame for analysis

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
csv_pathYesPath to the CSV file to load
df_nameNoName for the DataFrame (optional, defaults to df_1, df_2, etc.)

Implementation Reference

  • Primary handler for 'load-csv' tool in Python implementation. Loads CSV using pandas, supports chunking for large files, stores DataFrame globally, and provides summary statistics.
    async def handle_load_csv(arguments):
        """Handle the load-csv tool"""
        global _df_counter
        
        csv_path = arguments.get("csv_path")
        df_name = arguments.get("df_name")
        
        if not csv_path:
            return [TextContent(type="text", text="Error: csv_path is required")]
        
        # Normalize path for Windows
        csv_path = os.path.normpath(csv_path)
        
        # Generate a default name if none provided
        if not df_name:
            df_name = f"df_{_df_counter}"
            _df_counter += 1
        
        try:
            # Get file size
            file_size_mb = os.path.getsize(csv_path) / (1024 * 1024)
            logging.info(f"Loading CSV file: {csv_path} ({file_size_mb:.2f} MB)")
            
            # Use chunking for large files
            if file_size_mb > 100:
                return await _load_large_csv(csv_path, df_name)
            else:
                return await _load_small_csv(csv_path, df_name)
        
        except FileNotFoundError:
            return [TextContent(
                type="text", 
                text=f"Error: File not found: {csv_path}"
            )]
        except Exception as e:
            error_message = f"Error loading CSV: {str(e)}\n{traceback.format_exc()}"
            logging.error(error_message)
            return [TextContent(
                type="text", 
                text=f"Error loading CSV: {str(e)}"
            )]
  • Primary handler for 'load-csv' tool in TypeScript implementation. Parses CSV using PapaParse, stores data globally, generates summary using simple-statistics library.
    export async function loadCsv(args: LoadCsvArgs): Promise<{ type: string, text: string }[]> {
      const { csv_path, df_name } = args;
      
      if (!csv_path) {
        return [{ type: 'text', text: 'Error: csv_path is required' }];
      }
      
      // Normalize path for Windows
      const normalizedPath = path.normalize(csv_path);
      
      // Generate a default name if none provided
      const dataFrameName = df_name || `df_${dfCounter++}`;
      
      try {
        // Check if file exists
        if (!fs.existsSync(normalizedPath)) {
          return [{ type: 'text', text: `Error: File not found: ${normalizedPath}` }];
        }
        
        // Get file size
        const stats = fs.statSync(normalizedPath);
        const fileSizeMb = stats.size / (1024 * 1024);
        
        // Read file content
        const fileContent = fs.readFileSync(normalizedPath, 'utf8');
        
        // Parse CSV
        const parseResult = Papa.parse(fileContent, {
          header: true,
          dynamicTyping: true,
          skipEmptyLines: true
        });
        
        if (parseResult.errors && parseResult.errors.length > 0) {
          return [{ type: 'text', text: `Error parsing CSV: ${parseResult.errors[0].message}` }];
        }
        
        const data = parseResult.data as any[];
        
        // Store in global storage
        dataFrames[dataFrameName] = data;
        
        // Generate summary
        const summary = generateSummary(data, parseResult.meta.fields || []);
        
        return [{ 
          type: 'text', 
          text: `Successfully loaded ${normalizedPath} as ${dataFrameName} (${data.length} rows × ${parseResult.meta.fields?.length || 0} columns)\n\n${summary}` 
        }];
        
      } catch (error: any) {
        return [{ type: 'text', text: `Error loading CSV: ${error.message}` }];
      }
    }
  • Registration of the 'load-csv' tool including schema in the Python MCP server's list_tools handler.
    types.Tool(
        name="load-csv",
        description="Load a CSV file into a DataFrame for analysis",
        inputSchema={
            "type": "object",
            "properties": {
                "csv_path": {
                    "type": "string",
                    "description": "Path to the CSV file to load"
                },
                "df_name": {
                    "type": "string",
                    "description": "Name for the DataFrame (optional, defaults to df_1, df_2, etc.)"
                }
            },
            "required": ["csv_path"]
        }
    ),
  • src/index.ts:56-71 (registration)
    Registration of the 'load-csv' tool including schema in the TypeScript MCP server's listTools handler.
    name: "load-csv",
    description: "Load a CSV file into a DataFrame for analysis",
    inputSchema: {
      type: "object",
      properties: {
        csv_path: {
          type: "string",
          description: "Path to the CSV file to load"
        },
        df_name: {
          type: "string",
          description: "Name for the DataFrame (optional, defaults to df_1, df_2, etc.)"
        }
      },
      required: ["csv_path"]
    }
  • Tool dispatch handler in Python server that routes 'load-csv' calls to the data_loader handler.
    async def handle_call_tool(
        name: str,
        arguments: dict | None
    ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        """Handle tool execution"""
        try:
            if name == "load-csv":
                return await handle_load_csv(arguments)
            elif name == "run-script":
                return await handle_run_script(arguments)
            else:
                raise ValueError(f"Unknown tool: {name}")
        except Exception as e:
            error_message = f"Error executing tool {name}: {str(e)}\n{traceback.format_exc()}"
            logging.error(error_message)
            return [
                types.TextContent(
                    type="text",
                    text=f"Error: {str(e)}"
                )
            ]
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/tofunori/claude-mcp-data-explorer'

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