Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

readSheetNames

Retrieve all sheet names from an Excel file to identify available worksheets and navigate the workbook structure.

Instructions

Get all sheet names from the Excel file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileAbsolutePathYesThe absolute path of the Excel file

Implementation Reference

  • Core handler function that reads sheet names from an Excel file. First checks cache via workbookCache.ensureWorkbook(); if not cached, calls readAndCacheFile() to read and parse the file, then returns the SheetNames array.
    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}`);
        }
  • Registers the 'readSheetNames' tool on the MCP server with a Zod schema for fileAbsolutePath input. The handler validates the path, checks file existence, then calls readSheetNames() from handlers.
    export const readTools = (server: any) => {
        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 interface for ReadSheetNamesResult, containing success boolean and data object with SheetNames string array and errors string.
    export interface ReadSheetNamesResult {
        success: boolean;
        data: {
            SheetNames: string[];
            errors: string;
        };
    }
  • Helper that reads an Excel file in chunks using fs.createReadStream, parses it with the 'xlsx' library, caches the workbook, and returns ReadSheetNamesResult with SheetNames.
    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, the description must disclose behavioral traits but only states the basic action; no info about error handling, permissions, or edge cases.

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 a single, concise sentence without waste, though it could be slightly more informative.

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?

No output schema and no description of return format; for a data-retrieval tool, this is a significant gap.

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 coverage is 100% and the description adds no extra meaning beyond what the schema provides for the single parameter.

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 verb 'Get' and the resource 'all sheet names from the Excel file', which is specific and distinguishes it from sibling tools like readDataBySheetName.

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?

No guidance on when to use this tool versus alternatives; lacks context like when to use for listing sheets before reading data.

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