Skip to main content
Glama
Cytrogen

Local Project Sync

by Cytrogen

read_file_section

Extracts specific line ranges from a file in local repositories, enabling targeted code analysis without manual uploads. Supports file path, start and end lines, and optional line number display.

Instructions

读取文件的指定行范围

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
endLineYes结束行号(包含)
filePathYes带前缀的完整文件路径, e.g., '[backend/src]/main.ts'
showLineNumbersNo是否显示行号
startLineYes起始行号(从1开始)

Implementation Reference

  • The handler function reads a file section by line range. It parses the prefixed file path, resolves the full path safely, reads the file, extracts the specified lines, optionally adds line numbers, and returns the content wrapped in MCP response format. Handles errors like invalid paths, missing files, etc.
    async ({ filePath, startLine, endLine, showLineNumbers = true }) => {
      const match = filePath.match(/^(\[.*?\])\/(.*)$/s);
      if (!match) return { content: [{ type: "text", text: "错误:文件路径格式不正确,必须包含如 '[backend/src]/' 的前缀。" }] };
    
      const prefix = match[1];
      const relativePath = match[2];
      const rootPath = pathRegistry.get(prefix);
    
      if (!rootPath) return { content: [{ type: "text", text: `错误:未知的路径前缀 '${prefix}'。` }] };
    
      const resolvedPath = path.resolve(rootPath, relativePath);
      if (!resolvedPath.startsWith(path.resolve(rootPath))) return { content: [{ type: "text", text: "错误:禁止访问项目目录之外的文件。" }] };
    
      try {
        const fileContent = await fs.readFile(resolvedPath, "utf-8");
        const lines = fileContent.split('\n');
    
        // 验证行号范围
        if (startLine < 1) startLine = 1;
        if (endLine > lines.length) endLine = lines.length;
        if (startLine > endLine) {
          return { content: [{ type: "text", text: `错误:起始行号 ${startLine} 大于结束行号 ${endLine}` }] };
        }
    
        // 提取指定行范围(转换为0-based索引)
        const selectedLines = lines.slice(startLine - 1, endLine);
    
        let resultContent: string;
        if (showLineNumbers) {
          resultContent = selectedLines
            .map((line, index) => `${startLine + index}: ${line}`)
            .join('\n');
        } else {
          resultContent = selectedLines.join('\n');
        }
    
        const resultText = `文件 '${filePath}' 第 ${startLine}-${endLine} 行内容:\n---\n${resultContent}`;
        return { content: [{ type: "text", text: resultText }] };
    
      } catch (error: any) {
        let errorMessage = `读取文件 '${filePath}' 时发生错误。`;
        if (error.code === 'ENOENT') errorMessage = `错误:文件 '${filePath}' 未找到。`;
        console.error(errorMessage, error);
        return { content: [{ type: "text", text: errorMessage }] };
      }
    }
  • Zod schema defining input parameters: filePath (prefixed path), startLine, endLine, and optional showLineNumbers.
      filePath: z.string().describe("带前缀的完整文件路径, e.g., '[backend/src]/main.ts'"),
      startLine: z.number().describe("起始行号(从1开始)"),
      endLine: z.number().describe("结束行号(包含)"),
      showLineNumbers: z.boolean().optional().default(true).describe("是否显示行号"),
    },
  • src/index.ts:525-580 (registration)
    Registration of the 'read_file_section' tool using server.tool(), including name, Chinese description, input schema, and inline handler function.
    server.tool(
      "read_file_section",
      "读取文件的指定行范围",
      {
        filePath: z.string().describe("带前缀的完整文件路径, e.g., '[backend/src]/main.ts'"),
        startLine: z.number().describe("起始行号(从1开始)"),
        endLine: z.number().describe("结束行号(包含)"),
        showLineNumbers: z.boolean().optional().default(true).describe("是否显示行号"),
      },
      async ({ filePath, startLine, endLine, showLineNumbers = true }) => {
        const match = filePath.match(/^(\[.*?\])\/(.*)$/s);
        if (!match) return { content: [{ type: "text", text: "错误:文件路径格式不正确,必须包含如 '[backend/src]/' 的前缀。" }] };
    
        const prefix = match[1];
        const relativePath = match[2];
        const rootPath = pathRegistry.get(prefix);
    
        if (!rootPath) return { content: [{ type: "text", text: `错误:未知的路径前缀 '${prefix}'。` }] };
    
        const resolvedPath = path.resolve(rootPath, relativePath);
        if (!resolvedPath.startsWith(path.resolve(rootPath))) return { content: [{ type: "text", text: "错误:禁止访问项目目录之外的文件。" }] };
    
        try {
          const fileContent = await fs.readFile(resolvedPath, "utf-8");
          const lines = fileContent.split('\n');
    
          // 验证行号范围
          if (startLine < 1) startLine = 1;
          if (endLine > lines.length) endLine = lines.length;
          if (startLine > endLine) {
            return { content: [{ type: "text", text: `错误:起始行号 ${startLine} 大于结束行号 ${endLine}` }] };
          }
    
          // 提取指定行范围(转换为0-based索引)
          const selectedLines = lines.slice(startLine - 1, endLine);
    
          let resultContent: string;
          if (showLineNumbers) {
            resultContent = selectedLines
              .map((line, index) => `${startLine + index}: ${line}`)
              .join('\n');
          } else {
            resultContent = selectedLines.join('\n');
          }
    
          const resultText = `文件 '${filePath}' 第 ${startLine}-${endLine} 行内容:\n---\n${resultContent}`;
          return { content: [{ type: "text", text: resultText }] };
    
        } catch (error: any) {
          let errorMessage = `读取文件 '${filePath}' 时发生错误。`;
          if (error.code === 'ENOENT') errorMessage = `错误:文件 '${filePath}' 未找到。`;
          console.error(errorMessage, error);
          return { content: [{ type: "text", text: errorMessage }] };
        }
      }
    );
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the action (read) but doesn't mention permissions needed, error handling (e.g., invalid line numbers), output format, or side effects. This is a significant gap for a tool that interacts with files.

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 in Chinese that directly states the tool's purpose without unnecessary words. It is appropriately sized and front-loaded, with zero wasted content.

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 no annotations, no output schema, and a tool that reads files (potentially involving permissions or errors), the description is incomplete. It lacks details on behavior, output format, or error conditions, making it inadequate for safe and effective use by an 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?

The schema description coverage is 100%, so the schema already documents all parameters (filePath, startLine, endLine, showLineNumbers) with descriptions. The description adds no additional meaning beyond implying line-range usage, matching the baseline for high schema coverage.

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 '读取文件的指定行范围' (Read specified line range of a file) clearly states the verb (read) and resource (file), specifying it operates on a line range. It distinguishes from sibling tools like 'read_file_content' (which likely reads entire files) by focusing on sections, though it doesn't explicitly contrast them.

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 'read_file_content' or 'extract_function_definition'. It lacks context about use cases, prerequisites, or exclusions, leaving the agent to infer usage based on the tool name alone.

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

Related 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/Cytrogen/local-project-sync'

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