Skip to main content
Glama

rename_document

Change a document's name while keeping its content and location intact. Optionally updates references to the renamed document in other files for consistency.

Instructions

Rename a document while preserving its location and content. Optionally updates references to the document in other files.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
newNameYes
updateReferencesNo

Implementation Reference

  • The DocumentHandler.renameDocument method implements the core logic for the rename_document tool. It validates paths, preserves file extension, updates frontmatter title, optionally updates references in other documents, and handles errors.
    async renameDocument(
      docPath: string,
      newName: string,
      updateReferences = true
    ): Promise<ToolResponse> {
      try {
        const validPath = await this.validatePath(docPath);
    
        // Get directory and extension
        const dir = path.dirname(validPath);
        const ext = path.extname(validPath);
    
        // Create new path
        const newPath = path.join(dir, newName + ext);
        const validNewPath = await this.validatePath(newPath);
    
        // Check if source exists
        try {
          await fs.access(validPath);
        } catch {
          throw new Error(`Source file does not exist: ${docPath}`);
        }
    
        // Check if destination already exists
        try {
          await fs.access(validNewPath);
          throw new Error(`Destination file already exists: ${newPath}`);
        } catch (error) {
          // If error is "file doesn't exist", that's good
          if (
            !(
              error instanceof Error &&
              error.message.includes("Destination file already exists")
            )
          ) {
            // Continue with rename
          } else {
            throw error;
          }
        }
    
        // Read the source file
        const content = await fs.readFile(validPath, "utf-8");
    
        // Parse frontmatter
        const { frontmatter, content: docContent } = parseFrontmatter(content);
    
        // Update title in frontmatter if it exists
        if (frontmatter.title) {
          frontmatter.title = newName;
        }
    
        // Reconstruct content with updated frontmatter
        let frontmatterStr = "---\n";
        for (const [key, value] of Object.entries(frontmatter)) {
          if (Array.isArray(value)) {
            frontmatterStr += `${key}:\n`;
            for (const item of value) {
              frontmatterStr += `  - ${item}\n`;
            }
          } else {
            frontmatterStr += `${key}: ${value}\n`;
          }
        }
        frontmatterStr += "---\n\n";
    
        const updatedContent = frontmatterStr + docContent;
    
        // Write to new path
        await fs.writeFile(validNewPath, updatedContent, "utf-8");
    
        // Delete the source file
        await fs.unlink(validPath);
    
        // Update references if requested
        let referencesUpdated = 0;
        if (updateReferences) {
          const relativeSrcPath = path.relative(this.docsDir, validPath);
          const relativeDestPath = path.relative(this.docsDir, validNewPath);
          referencesUpdated = await this.updateReferences(
            relativeSrcPath,
            relativeDestPath
          );
        }
    
        return {
          content: [
            {
              type: "text",
              text:
                `Successfully renamed document from ${docPath} to ${newName}${ext}` +
                (referencesUpdated > 0
                  ? `. Updated ${referencesUpdated} references.`
                  : ""),
            },
          ],
          metadata: {
            originalPath: docPath,
            newPath: path.relative(this.docsDir, validNewPath),
            referencesUpdated,
          },
        };
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        return {
          content: [
            { type: "text", text: `Error renaming document: ${errorMessage}` },
          ],
          isError: true,
        };
      }
    }
  • Zod schema defining the input parameters for the rename_document tool: path (current document path), newName (new filename without extension), updateReferences (whether to update links in other files).
    export const RenameDocumentSchema = ToolInputSchema.extend({
      path: z.string(),
      newName: z.string(),
      updateReferences: z.boolean().default(true),
    });
  • src/index.ts:265-271 (registration)
    Tool registration in the listTools handler, defining the tool name, description, and input schema.
    {
      name: "rename_document",
      description:
        "Rename a document while preserving its location and content. Optionally updates " +
        "references to the document in other files.",
      inputSchema: zodToJsonSchema(RenameDocumentSchema) as any,
    },
  • src/index.ts:428-440 (registration)
    Dispatch handler in the CallToolRequestSchema that parses input using RenameDocumentSchema and calls documentHandler.renameDocument. Note: case label is 'rename_documentation_document' while tool name is 'rename_document'.
    case "rename_documentation_document": {
      const parsed = RenameDocumentSchema.safeParse(args);
      if (!parsed.success) {
        throw new Error(
          `Invalid arguments for rename_document: ${parsed.error}`
        );
      }
      return await documentHandler.renameDocument(
        parsed.data.path,
        parsed.data.newName,
        parsed.data.updateReferences
      );
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It mentions that the tool renames a document while preserving location and content, and optionally updates references, which gives some behavioral context. However, it lacks details on permissions needed, error conditions, whether the rename is atomic or reversible, or what happens if references fail to update, which are important for a mutation tool.

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 appropriately sized and front-loaded, with two clear sentences that efficiently convey the tool's purpose and optional behavior. Every sentence adds value without redundancy, making it easy for an agent to parse quickly.

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?

Given the tool has 3 parameters with 0% schema coverage, no annotations, and no output schema, the description provides basic context but is incomplete. It covers the main action and optional reference updating, but lacks details on return values, error handling, or advanced usage scenarios, which are needed for full agent understanding.

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 description coverage is 0%, so the description must compensate. It adds meaning by explaining that 'path' and 'newName' are used to rename the document, and 'updateReferences' controls whether references in other files are updated. However, it does not specify format for 'path' (e.g., file path syntax) or 'newName' (e.g., naming constraints), leaving gaps in parameter understanding.

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 ('rename', 'preserving', 'updates') and resource ('document'), distinguishing it from siblings like move_document (changes location) and edit_document (changes content). It explicitly mentions what is preserved (location and content) and what can be optionally updated (references).

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 by mentioning 'preserving its location and content', suggesting this tool is for renaming without moving or modifying content, unlike move_document or edit_document. However, it does not explicitly state when to use this tool versus alternatives or provide exclusions, leaving some ambiguity for the agent.

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