Skip to main content
Glama
ishayoyo

Excel MCP Server

by ishayoyo

read_file_chunked

Process large Excel or CSV files in sections to manage data within token constraints, enabling analysis of extensive datasets without exceeding processing limits.

Instructions

Read large files in manageable chunks to avoid token limits

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesPath to the CSV or Excel file
sheetNoSheet name for Excel files (optional)
chunkIndexNoChunk index to read (0-based, defaults to 0)
chunkSizeNoNumber of rows per chunk (optional, auto-calculated if not provided)

Implementation Reference

  • Main execution logic for the read_file_chunked tool. Handles chunked reading of large files by calculating optimal chunk sizes, validating boundaries, slicing data, managing headers for context, and providing comprehensive chunk metadata including navigation info.
    async readFileChunked(args: ToolArgs): Promise<ToolResponse> {
      try {
        if (!args.filePath) {
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  success: false,
                  error: 'Missing required parameter: filePath',
                }, null, 2),
              },
            ],
          };
        }
    
        const { filePath, sheet, chunkIndex = 0, chunkSize } = args;
        const result = await readFileContentWithWarnings(filePath, sheet);
    
        const totalRows = result.data.length;
        const totalColumns = result.data[0]?.length || 0;
    
        // Calculate optimal chunk size if not provided
        const optimalChunkSize = chunkSize || calculateOptimalChunkSize(totalRows, totalColumns);
    
        // Calculate offset for requested chunk
        const offset = chunkIndex * optimalChunkSize;
    
        if (offset >= totalRows) {
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  success: false,
                  error: `Chunk index ${chunkIndex} is out of range. File has ${Math.ceil(totalRows / optimalChunkSize)} chunks.`,
                }, null, 2),
              },
            ],
          };
        }
    
        // Validate and apply chunking
        const { validOffset, validLimit } = validateChunkBoundaries(result.data, offset, optimalChunkSize);
        const endRow = validOffset + validLimit;
        const chunkedData = result.data.slice(validOffset, endRow);
    
        // Include headers if this is the first chunk or if specifically requested
        let finalData = chunkedData;
        if (chunkIndex === 0 && totalRows > 0) {
          // First chunk already includes headers naturally
        } else if (chunkIndex > 0 && totalRows > 0) {
          // For subsequent chunks, optionally include headers as context
          finalData = [result.data[0], ...chunkedData.slice(validOffset === 0 ? 1 : 0)];
        }
    
        const totalChunks = Math.ceil(totalRows / optimalChunkSize);
    
        const response: any = {
          success: true,
          data: finalData,
          chunkInfo: {
            chunkIndex,
            chunkSize: optimalChunkSize,
            totalChunks,
            totalRows,
            totalColumns,
            currentChunkRows: chunkedData.length,
            hasNext: chunkIndex < totalChunks - 1,
            hasPrevious: chunkIndex > 0,
            nextChunkIndex: chunkIndex < totalChunks - 1 ? chunkIndex + 1 : null,
            previousChunkIndex: chunkIndex > 0 ? chunkIndex - 1 : null,
          },
          headers: totalRows > 0 ? result.data[0] : [],
        };
    
        // Include warnings if they exist
        if (result.warnings) {
          response.warnings = result.warnings;
        }
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error occurred',
              }, null, 2),
            },
          ],
        };
      }
    }
  • JSON Schema defining the input parameters for the read_file_chunked tool: filePath (required), sheet, chunkIndex (default 0), chunkSize (optional).
      name: 'read_file_chunked',
      description: 'Read large files in manageable chunks to avoid token limits',
      inputSchema: {
        type: 'object',
        properties: {
          filePath: {
            type: 'string',
            description: 'Path to the CSV or Excel file',
          },
          sheet: {
            type: 'string',
            description: 'Sheet name for Excel files (optional)',
          },
          chunkIndex: {
            type: 'number',
            description: 'Chunk index to read (0-based, defaults to 0)',
            default: 0,
          },
          chunkSize: {
            type: 'number',
            description: 'Number of rows per chunk (optional, auto-calculated if not provided)',
          },
        },
        required: ['filePath'],
      },
    },
  • src/index.ts:1215-1218 (registration)
    Registration of the read_file_chunked tool in the MCP CallToolRequestSchema handler switch statement, dispatching calls to DataOperationsHandler.readFileChunked method.
    case 'read_file_chunked':
      return await this.dataOpsHandler.readFileChunked(toolArgs);
    case 'get_file_info':
      return await this.dataOpsHandler.getFileInfo(toolArgs);
  • Utility function to compute optimal chunk size based on file dimensions and target token limit to prevent exceeding LLM context windows.
    export function calculateOptimalChunkSize(totalRows: number, totalColumns: number, targetTokens: number = 8000): number {
      const avgCellLength = 10;
      const tokensPerRow = Math.ceil((totalColumns * avgCellLength) / 4);
      const optimalRows = Math.floor(targetTokens / tokensPerRow);
    
      return Math.max(100, Math.min(optimalRows, 5000)); // Between 100 and 5000 rows
    }
  • Helper to validate and adjust chunk offset and limit to stay within file data bounds.
    export function validateChunkBoundaries(data: any[][], offset: number, limit: number): { validOffset: number; validLimit: number } {
      const totalRows = data.length;
    
      // Ensure offset is within bounds
      const validOffset = Math.max(0, Math.min(offset, totalRows - 1));
    
      // Ensure limit doesn't exceed remaining data
      const remainingRows = totalRows - validOffset;
      const validLimit = Math.min(limit, remainingRows);
    
      return { validOffset, validLimit };
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It mentions chunking to avoid token limits, which is useful behavioral context, but lacks details on file formats (only implied via parameters), error handling, performance traits, or output structure. For a tool with 4 parameters and no annotations, this is insufficient.

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, efficient sentence that front-loads the core purpose. Every word earns its place, with no redundancy or unnecessary elaboration, making it highly concise and well-structured.

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 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't cover behavioral aspects like file format support (beyond CSV/Excel implied in schema), chunking mechanics, or return values. For a tool with moderate complexity, this leaves significant gaps for an AI agent.

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?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no parameter-specific information beyond what's in the schema (e.g., it doesn't explain chunkIndex or chunkSize behavior further). Baseline 3 is appropriate as the schema does the heavy lifting.

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: 'Read large files in manageable chunks to avoid token limits.' It specifies the verb ('read'), resource ('large files'), and key constraint ('chunked'). However, it doesn't explicitly differentiate from sibling 'read_file' (which likely reads entire files), though the chunking aspect implies a distinction.

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

Usage Guidelines3/5

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

The description implies usage context ('large files... to avoid token limits'), suggesting this tool is for handling files too large for standard processing. It doesn't explicitly state when to use it versus alternatives like 'read_file' or provide exclusions (e.g., for small files). The guidance is present but not comprehensive.

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/ishayoyo/excel-mcp'

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