codeFileRead
Read and display code file content with line numbers to verify and edit file structure accurately, ensuring clarity without unnecessary formatting changes.
Instructions
讀取程式碼檔案並顯示行號,用於確認檔案實際行數以便編輯操作。(如果不影響編譯器的話,不需要針對縮排等小問題修改。提醒User就好了)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes |
Implementation Reference
- tools/csFileReader.ts:14-39 (handler)Core handler function that reads the file content, splits into lines, adds formatted line numbers, and handles errors.static async readFileWithLineNumbers(filePath: string): Promise<string> { try { // 檢查檔案是否存在 if (!existsSync(filePath)) { return `錯誤: 檔案 ${filePath} 不存在`; } // 讀取檔案內容 const content = await fs.readFile(filePath, 'utf8'); const lines = content.split(/\r?\n/); // 計算行號寬度 (最大行號的位數) const lineNumberWidth = lines.length.toString().length; // 為每行添加行號 const numberedLines = lines.map((line, index) => { const lineNumber = (index + 1).toString().padStart(lineNumberWidth, '0'); return `${lineNumber}: ${line}`; }); return numberedLines.join('\n'); } catch (error) { console.error(`讀取檔案時發生錯誤: ${error}`); return `讀取檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } }
- main.ts:70-85 (registration)Registers the 'codeFileRead' tool with MCP server, including schema, description, and a thin wrapper handler that calls the core implementation.server.tool("codeFileRead", "讀取程式碼檔案並顯示行號,用於確認檔案實際行數以便編輯操作。(如果不影響編譯器的話,不需要針對縮排等小問題修改。提醒User就好了)", { filePath: z.string() }, async ({ filePath }) => { try { const result = await myFileReader.readFileWithLineNumbers(filePath); return { content: [{ type: "text", text: result }] }; } catch (error) { return { content: [{ type: "text", text: `讀取檔案失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }] }; } } );
- main.ts:72-72 (schema)Zod schema defining the input parameter 'filePath' as a string.{ filePath: z.string() },
- tools/csFileReader.ts:8-40 (helper)The myFileReader class containing the static method used by the tool.export class myFileReader { /** * 讀取程式碼文件並添加行號 * @param filePath 檔案路徑 * @returns 帶行號的檔案內容 */ static async readFileWithLineNumbers(filePath: string): Promise<string> { try { // 檢查檔案是否存在 if (!existsSync(filePath)) { return `錯誤: 檔案 ${filePath} 不存在`; } // 讀取檔案內容 const content = await fs.readFile(filePath, 'utf8'); const lines = content.split(/\r?\n/); // 計算行號寬度 (最大行號的位數) const lineNumberWidth = lines.length.toString().length; // 為每行添加行號 const numberedLines = lines.map((line, index) => { const lineNumber = (index + 1).toString().padStart(lineNumberWidth, '0'); return `${lineNumber}: ${line}`; }); return numberedLines.join('\n'); } catch (error) { console.error(`讀取檔案時發生錯誤: ${error}`); return `讀取檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } } }