Skip to main content
Glama

rename_document

Rename a document within the MCP Documentation Service without altering its content or location. Optionally updates references to the document in related 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
newNameYes
pathYes
updateReferencesNo

Implementation Reference

  • Core handler implementation for renaming a document. Validates paths, preserves extension, updates frontmatter title, copies content to new file, deletes old file, optionally updates references in other documents.
    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 for validating inputs to the rename_document tool: requires path and newName, optional updateReferences flag.
    export const RenameDocumentSchema = ToolInputSchema.extend({ path: z.string(), newName: z.string(), updateReferences: z.boolean().default(true), });
  • src/index.ts:265-271 (registration)
    MCP tool registration defining the 'rename_document' tool name, description, and references the RenameDocumentSchema for input validation.
    { 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 main switch that routes 'rename_documentation_document' calls to the documentHandler.renameDocument method after schema validation. Note: case name may mismatch tool name.
    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 ); }
  • Private helper method used by renameDocument (and moveDocument) to update references to the renamed/moved path across all markdown files.
    private async updateReferences( oldPath: string, newPath: string ): Promise<number> { // Normalize paths for comparison const normalizedOldPath = oldPath.replace(/\\/g, "/"); const normalizedNewPath = newPath.replace(/\\/g, "/"); // Find all markdown files const files = await glob("**/*.md", { cwd: this.docsDir }); let updatedCount = 0; for (const file of files) { const filePath = path.join(this.docsDir, file); const content = await fs.readFile(filePath, "utf-8"); // Look for references to the old path // Match markdown links: [text](path) const linkRegex = new RegExp( `\\[([^\\]]+)\\]\\(${normalizedOldPath.replace( /[.*+?^${}()|[\]\\]/g, "\\$&" )}\\)`, "g" ); // Match direct path references const pathRegex = new RegExp( normalizedOldPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g" ); // Replace references let updatedContent = content.replace( linkRegex, `[$1](${normalizedNewPath})` ); updatedContent = updatedContent.replace(pathRegex, normalizedNewPath); // If content changed, write the updated file if (updatedContent !== content) { await fs.writeFile(filePath, updatedContent, "utf-8"); updatedCount++; } } return updatedCount; }

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