Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

readSheetNames

Retrieve all worksheet names from an Excel file to understand its structure and navigate between sheets.

Instructions

Get all sheet names from the Excel file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileAbsolutePathYesThe absolute path of the Excel file

Implementation Reference

  • The handler function executing the readSheetNames tool logic, checks cache or reads and caches the Excel workbook to return sheet names.
    export async function readSheetNames(filePathWithName: string): Promise<string[]> {
    
    
        try {
            //从缓存中获取workbook
            const workbookResult: EnsureWorkbookResult = workbookCache.ensureWorkbook(filePathWithName);
    
            if (!workbookResult.success) {
                // 缓存中没有workbook,尝试读取并缓存文件
                const readResult: ReadSheetNamesResult = await readAndCacheFile(filePathWithName);
                if (!readResult.success) {
                    // 读取文件失败,返回错误信息
                    throw new Error(`read file failure: ${readResult.data.errors}`);
                } else {
                    return readResult.data.SheetNames;
                }
    
            } else {
                const workbook = workbookResult.data as XLSX.WorkBook;
                return workbook.SheetNames
            }
    
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            throw new Error(`read file failure: ${errorMessage}`);
        }
    }
  • Tool registration for 'readSheetNames' including input schema with Zod and the wrapper async function that normalizes path, checks existence, and calls the handler.
    server.tool("readSheetNames", 'Get all sheet names from the Excel file',
        {
            fileAbsolutePath: z.string().describe("The absolute path of the Excel file")
        },
        async (params: { fileAbsolutePath: string }) => {
            try {
                const normalizedPath = await normalizePath(params.fileAbsolutePath);
                if (normalizedPath === 'error') {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `path is not valid: ${params.fileAbsolutePath}`,
                                suggestion: "please check the path and filename"
                            })
                        }]
                    };
                }
                if (!(await fileExists(normalizedPath))) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `file is not exist: ${params.fileAbsolutePath}`,
                                suggestion: "please check the path and filename"
                            })
                        }]
                    };
    
                }
                const result = await readSheetNames(normalizedPath);
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(result)
                    }]
                };
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            error: `read sheet names failure: ${error}`,
                            suggestion: "please check the path and filename"
                        })
                    }]
                };
            }
    
        }
    );
  • Type definition for the result structure returned by readSheetNames and readAndCacheFile.
    export interface ReadSheetNamesResult {
        success: boolean;
        data: {
            SheetNames: string[];
            errors: string;
        };
    }
  • Supporting utility that reads the Excel file in chunks with timeout, parses with XLSX.read, caches the workbook, and returns SheetNames or error.
    export async function readAndCacheFile(filePathWithName: string): Promise<ReadSheetNamesResult> {
        try {
            const timeout = new Promise((_, reject) => {
                setTimeout(() => reject(new Error('File reading timeout')), READ_TIMEOUT);
            });
    
            const readOperation = new Promise<ReadSheetNamesResult>(async (resolve, reject) => {
                try {
                    // Read file in chunks
                    const fileStream = fs.createReadStream(filePathWithName, {
                        highWaterMark: 1024 * 1024 // 1MB chunks
                    });
    
                    const chunks: Buffer[] = [];
    
                    fileStream.on('data', (chunk: string | Buffer) => {
                        if (Buffer.isBuffer(chunk)) {
                            chunks.push(chunk);
                        } else {
                            chunks.push(Buffer.from(chunk));
                        }
                    });
    
                    fileStream.on('end', () => {
                        const buffer = Buffer.concat(chunks);
                        const workbook = XLSX.read(buffer, {
                            type: 'buffer',
                            cellDates: true,
                            cellNF: false,
                            cellText: false,
                        });
                        workbookCache.set(filePathWithName, workbook);
                        resolve({
                            success: true,
                            data: {
                                SheetNames: workbook.SheetNames,
                                errors: ''
                            }
                        });
                    });
    
                    fileStream.on('error', (error) => {
                        reject(error);
                    });
                } catch (error) {
                    reject(error);
                }
            });
    
            const result = await Promise.race([readOperation, timeout]);
            return result as ReadSheetNamesResult;
    
        } catch (bufferError) {
            await logToFile(`[read-and-cache-file] Buffer read failure: ${bufferError}`);
            return {
                success: false,
                data: {
                    SheetNames: [],
                    errors: JSON.stringify(bufferError)
                }
            };
        }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Get' implies a read operation, it doesn't specify whether this requires file access permissions, whether it caches results, what happens with invalid paths, or the format of returned data. For a file I/O tool with zero annotation coverage, this leaves significant behavioral questions unanswered.

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 with zero wasted words. It's front-loaded with the core functionality and uses clear, direct language. Every word earns its place in conveying the tool's purpose.

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?

For a file I/O tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the return value looks like (array of strings? object with metadata?), error conditions, performance characteristics, or how it interacts with sibling tools. The agent would need to guess about important behavioral aspects.

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 input schema already fully documents the single parameter. The description doesn't add any additional context about the parameter beyond what's in the schema (e.g., file format requirements, path validation rules, or examples). Baseline 3 is appropriate when 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 verb ('Get') and resource ('all sheet names from the Excel file'), making the purpose immediately understandable. It doesn't explicitly distinguish from siblings like 'readSheetData' or 'analyzeExcelStructure', but the focus on sheet names specifically provides some implicit differentiation.

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 like 'readSheetData' (which reads actual data) or 'analyzeExcelStructure' (which might provide more comprehensive metadata). There's no mention of prerequisites, error conditions, or typical use cases.

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

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