Skip to main content
Glama
cablate

Simple Document Processing MCP Server

text_splitter

Split text files by line count or delimiter into multiple output files. Specify input path, output directory, and split method for efficient document segmentation.

Instructions

Split text file by specified delimiter or line count

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
inputPathYesPath to the input text file
outputDirYesDirectory where split files should be saved
splitByYesSplit method: by line count or delimiter
valueYesLine count (number) or delimiter string

Implementation Reference

  • The main handler function for the text_splitter tool. Reads a text file and splits it either by line count (chunking every N lines) or by a delimiter string. Each part is written to a separate file (part_{id}_{n}.txt).
    // 文字分割實作
    export async function splitText(
      inputPath: string,
      outputDir: string,
      splitBy: "lines" | "delimiter",
      value: string
    ) {
      try {
        console.error(`Starting text splitting...`);
        console.error(`Input file: ${inputPath}`);
        console.error(`Output directory: ${outputDir}`);
        console.error(`Split by: ${splitBy}`);
        console.error(`Value: ${value}`);
    
        // 確保輸出目錄存在
        try {
          await fs.access(outputDir);
          console.error(`Output directory exists: ${outputDir}`);
        } catch {
          console.error(`Creating output directory: ${outputDir}`);
          await fs.mkdir(outputDir, { recursive: true });
          console.error(`Created output directory: ${outputDir}`);
        }
    
        const uniqueId = generateUniqueId();
        const content = await fs.readFile(inputPath, "utf-8");
        const parts: string[] = [];
    
        if (splitBy === "lines") {
          const lineCount = parseInt(value, 10);
          if (isNaN(lineCount) || lineCount <= 0) {
            throw new Error("Invalid line count");
          }
    
          const lines = content.split("\n");
          for (let i = 0; i < lines.length; i += lineCount) {
            parts.push(lines.slice(i, i + lineCount).join("\n"));
          }
        } else {
          parts.push(...content.split(value));
        }
    
        const results: string[] = [];
        for (let i = 0; i < parts.length; i++) {
          const outputPath = path.join(outputDir, `part_${uniqueId}_${i + 1}.txt`);
          await fs.writeFile(outputPath, parts[i]);
          results.push(outputPath);
          console.error(`Written part ${i + 1} to ${outputPath}`);
        }
    
        return {
          success: true,
          data: `Successfully split text into ${parts.length} parts: ${results.join(
            ", "
          )}`,
        };
      } catch (error) {
        console.error(`Error in splitText:`, error);
        return {
          success: false,
          error: error instanceof Error ? error.message : "Unknown error",
        };
      }
    }
  • The input schema definition for the text_splitter tool. Defines required parameters: inputPath (string), outputDir (string), splitBy ('lines'|'delimiter'), and value (string - either line count or delimiter).
    // 文字分割工具
    export const TEXT_SPLIT_TOOL: Tool = {
      name: "text_splitter",
      description: "Split text file by specified delimiter or line count",
      inputSchema: {
        type: "object",
        properties: {
          inputPath: {
            type: "string",
            description: "Path to the input text file",
          },
          outputDir: {
            type: "string",
            description: "Directory where split files should be saved",
          },
          splitBy: {
            type: "string",
            enum: ["lines", "delimiter"],
            description: "Split method: by line count or delimiter",
          },
          value: {
            type: "string",
            description: "Line count (number) or delimiter string",
          },
        },
        required: ["inputPath", "outputDir", "splitBy", "value"],
      },
    };
  • src/index.ts:302-320 (registration)
    The tool call handler in the MCP server that dispatches to the splitText function when name is 'text_splitter'. It destructures args (inputPath, outputDir, splitBy, value) and calls splitText(...).
    if (name === "text_splitter") {
      const { inputPath, outputDir, splitBy, value } = args as {
        inputPath: string;
        outputDir: string;
        splitBy: "lines" | "delimiter";
        value: string;
      };
      const result = await splitText(inputPath, outputDir, splitBy, value);
      if (!result.success) {
        return {
          content: [{ type: "text", text: `Error: ${result.error}` }],
          isError: true,
        };
      }
      return {
        content: [{ type: "text", text: fileOperationResponse(result.data) }],
        isError: false,
      };
    }
  • Re-exports TEXT_SPLIT_TOOL from txtTools.ts and includes it in the tools array used by the MCP server's ListToolsRequestSchema handler.
    import { TEXT_DIFF_TOOL, TEXT_ENCODING_CONVERT_TOOL, TEXT_FORMAT_TOOL, TEXT_SPLIT_TOOL } from "./txtTools.js";
    
    export const tools = [DOCUMENT_READER_TOOL, PDF_MERGE_TOOL, PDF_SPLIT_TOOL, DOCX_TO_PDF_TOOL, DOCX_TO_HTML_TOOL, HTML_CLEAN_TOOL, HTML_TO_TEXT_TOOL, HTML_TO_MARKDOWN_TOOL, HTML_EXTRACT_RESOURCES_TOOL, HTML_FORMAT_TOOL, TEXT_DIFF_TOOL, TEXT_SPLIT_TOOL, TEXT_FORMAT_TOOL, TEXT_ENCODING_CONVERT_TOOL, EXCEL_READ_TOOL, FORMAT_CONVERTER_TOOL];
    
    export * from "./documentReader.js";
    export * from "./docxTools.js";
    export * from "./excelTools.js";
    export * from "./formatConverterPlus.js";
    export * from "./htmlTools.js";
    export * from "./pdfTools.js";
    export * from "./txtTools.js";
Behavior2/5

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

No annotations provided, so description must disclose behavioral traits. It only states the split method, missing details like file overwrite behavior, error handling, or output naming conventions.

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?

Single sentence, no wasted words. Could be improved by front-loading actionable info, but still concise.

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 tool with 4 required parameters and no output schema, the description is too minimal. It lacks context on file format requirements, output naming, or how the split method works in practice.

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%, so baseline is 3. Description adds no extra meaning beyond what the schema already provides (e.g., line count or delimiter string).

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?

Description clearly states the tool splits a text file by delimiter or line count, which is specific and distinguishes it from siblings like pdf_splitter and text_formatter.

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 (e.g., for numeric splitting vs. delimiter patterns), nor any prerequisites like file existence or directory creation.

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/cablate/mcp-doc-forge'

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