Skip to main content
Glama

edit_document

Make line-based edits to markdown documents by replacing specific text sequences, generating git-style diffs to track changes.

Instructions

Make line-based edits to a markdown document. Each edit replaces exact line sequences with new content. Returns a git-style diff showing the changes made.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
editsYes
dryRunNo

Implementation Reference

  • The core handler function in DocumentHandler class that reads a document, applies sequential text replacements (with fuzzy line matching), generates a unified diff, and optionally writes changes back. Supports dry-run mode.
    async editDocument(
      docPath: string,
      edits: Array<{ oldText: string; newText: string }>,
      dryRun = false
    ): Promise<ToolResponse> {
      try {
        const validPath = await this.validatePath(docPath);
    
        // Read file content and normalize line endings
        const content = normalizeLineEndings(
          await fs.readFile(validPath, "utf-8")
        );
    
        // Apply edits sequentially
        let modifiedContent = content;
        for (const edit of edits) {
          const normalizedOld = normalizeLineEndings(edit.oldText);
          const normalizedNew = normalizeLineEndings(edit.newText);
    
          // If exact match exists, use it
          if (modifiedContent.includes(normalizedOld)) {
            modifiedContent = modifiedContent.replace(
              normalizedOld,
              normalizedNew
            );
            continue;
          }
    
          // Otherwise, try line-by-line matching with flexibility for whitespace
          const oldLines = normalizedOld.split("\n");
          const contentLines = modifiedContent.split("\n");
          let matchFound = false;
    
          for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
            const potentialMatch = contentLines.slice(i, i + oldLines.length);
    
            // Compare lines with normalized whitespace
            const isMatch = oldLines.every((oldLine, j) => {
              const contentLine = potentialMatch[j];
              return oldLine.trim() === contentLine.trim();
            });
    
            if (isMatch) {
              // Preserve original indentation of first line
              const originalIndent = contentLines[i].match(/^\s*/)?.[0] || "";
              const newLines = normalizedNew.split("\n").map((line, j) => {
                if (j === 0) return originalIndent + line.trimStart();
                // For subsequent lines, try to preserve relative indentation
                const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || "";
                const newIndent = line.match(/^\s*/)?.[0] || "";
                if (oldIndent && newIndent) {
                  const relativeIndent = newIndent.length - oldIndent.length;
                  return (
                    originalIndent +
                    " ".repeat(Math.max(0, relativeIndent)) +
                    line.trimStart()
                  );
                }
                return line;
              });
    
              contentLines.splice(i, oldLines.length, ...newLines);
              modifiedContent = contentLines.join("\n");
              matchFound = true;
              break;
            }
          }
    
          if (!matchFound) {
            throw new Error(
              `Could not find exact match for edit:\n${edit.oldText}`
            );
          }
        }
    
        // Create unified diff
        const diff = createUnifiedDiff(content, modifiedContent, docPath);
    
        // Format diff with appropriate number of backticks
        let numBackticks = 3;
        while (diff.includes("`".repeat(numBackticks))) {
          numBackticks++;
        }
        const formattedDiff = `${"`".repeat(
          numBackticks
        )}diff\n${diff}${"`".repeat(numBackticks)}\n\n`;
    
        if (!dryRun) {
          await fs.writeFile(validPath, modifiedContent, "utf-8");
        }
    
        return {
          content: [{ type: "text", text: formattedDiff }],
        };
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        return {
          content: [
            { type: "text", text: `Error editing document: ${errorMessage}` },
          ],
          isError: true,
        };
      }
    }
  • Zod schema defining the input for edit_document tool: path to document, array of edits (oldText/newText pairs), optional dryRun flag.
    export const EditDocumentSchema = ToolInputSchema.extend({
      path: z.string(),
      edits: z.array(
        z.object({
          oldText: z.string(),
          newText: z.string(),
        })
      ),
      dryRun: z.boolean().default(false),
    });
  • src/index.ts:216-222 (registration)
    Tool registration in the MCP server's listTools response, defining name, description, and input schema.
      description:
        "Make line-based edits to a markdown document. Each edit replaces exact line sequences " +
        "with new content. Returns a git-style diff showing the changes made.",
      inputSchema: zodToJsonSchema(EditDocumentSchema) as any,
    },
    {
      name: "list_documents",
  • src/index.ts:335-347 (registration)
    Dispatch logic in the main CallToolRequest handler that parses input with EditDocumentSchema and delegates to documentHandler.editDocument.
    case "edit_document": {
      const parsed = EditDocumentSchema.safeParse(args);
      if (!parsed.success) {
        throw new Error(
          `Invalid arguments for edit_document: ${parsed.error}`
        );
      }
      return await documentHandler.editDocument(
        parsed.data.path,
        parsed.data.edits,
        parsed.data.dryRun
      );
    }
  • Helper function to generate unified diff patch used in editDocument response.
    function createUnifiedDiff(
      originalContent: string,
      newContent: string,
      filepath: string = "file"
    ): string {
      // Ensure consistent line endings for diff
      const normalizedOriginal = normalizeLineEndings(originalContent);
      const normalizedNew = normalizeLineEndings(newContent);
    
      return createTwoFilesPatch(
        filepath,
        filepath,
        normalizedOriginal,
        normalizedNew,
        "original",
        "modified"
      );
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the edit mechanism (line-based replacements), the return format (git-style diff), and the dry-run capability (implied through the parameter). However, it doesn't mention permissions needed, whether edits are reversible, rate limits, or error handling for invalid edits.

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 perfectly concise with two sentences that each earn their place: the first explains the core functionality, the second explains the return value. No wasted words, and the most important information (what the tool does) is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool with 3 parameters, 0% schema coverage, and no output schema, the description is adequate but has gaps. It explains the edit mechanism and return format well, but doesn't cover error conditions, authentication needs, or provide examples. Given the complexity, it should ideally mention more about the edit constraints or validation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description compensates well by explaining the edit mechanism ('replaces exact line sequences') and the return format. It doesn't detail individual parameters like 'path' or 'dryRun', but the context about line-based edits and git-style diff provides meaningful semantic understanding beyond the bare schema.

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 tool's purpose with specific verbs ('make line-based edits', 'replaces exact line sequences') and identifies the resource ('markdown document'). It distinguishes from siblings like 'write_document' or 'update_navigation_order' by specifying the exact edit mechanism (line-based replacements).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for line-based markdown editing but doesn't explicitly state when to use this tool versus alternatives like 'write_document' or 'update_navigation_order'. It mentions the return format (git-style diff) which provides some context, but lacks explicit guidance on prerequisites or exclusions.

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/alekspetrov/mcp-docs-service'

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