Skip to main content
Glama

move_file

Move or rename a file to a new absolute path within the same project. Rejects cross-project moves.

Instructions

Move/rename a file. Destination 'new_path' must be absolute and resolve INSIDE the file's owning project or global knowledge directory. Cross-project moves are rejected. Operates locally with no auth or limits. Parameters: 'file_id' is a valid file ID. 'new_path' is an absolute path.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_idYesFile ID
new_pathYesAbsolute destination path

Implementation Reference

  • Core business-logic function that moves a file on disk and updates the SQLite database. It renames the file via renameSync, then updates the 'path' column in the DB. If the DB UPDATE fails, it rolls back the disk rename. Returns the updated FileRecord.
    export function moveFile(id: number, newPath: string): FileRecord {
      const db = getDatabase();
    
      const fileRecord = db.prepare("SELECT * FROM files WHERE id = ?").get(id) as FileRecord | undefined;
      if (!fileRecord) {
        throw new Error(`File not found: ${id}`);
      }
    
      mkdirSync(dirname(newPath), { recursive: true });
      const oldPath = fileRecord.path;
      renameSync(oldPath, newPath);
    
      // If the DB UPDATE fails (UNIQUE conflict, etc.) we'd be left with the
      // file at newPath but the row pointing at oldPath — in the web app the
      // watcher would then unlink the row (losing tags/favorites). Roll the
      // disk rename back so the system stays consistent.
      const updateStmt = db.prepare("UPDATE files SET path = ?, updated_at = datetime('now') WHERE id = ?");
      try {
        updateStmt.run(newPath, id);
      } catch (e) {
        try { renameSync(newPath, oldPath); } catch (rollbackErr) {
          throw new Error(
            `moveFile failed and rollback also failed; disk and DB are out of sync. ` +
            `update error: ${(e as any)?.message ?? e}; rollback error: ${(rollbackErr as any)?.message ?? rollbackErr}`
          );
        }
        throw e;
      }
    
      const updatedRecord = db.prepare("SELECT * FROM files WHERE id = ?").get(id) as FileRecord;
      return updatedRecord;
    }
  • MCP tool handler registration for 'move_file'. Defines the Zod schema (file_id: number, new_path: string), validates that new_path is absolute and within the file's owning project or knowledge directory, then delegates to the core moveFile function.
    server.tool(
      "move_file",
      "Move/rename a file. Destination 'new_path' must be absolute and resolve INSIDE the file's owning project or global knowledge directory. Cross-project moves are rejected. Operates locally with no auth or limits. Parameters: 'file_id' is a valid file ID. 'new_path' is an absolute path.",
      {
        file_id: z.number().describe("File ID"),
        new_path: z.string().describe("Absolute destination path"),
      },
      async ({ file_id, new_path }) => {
        try {
          if (typeof new_path !== "string" || new_path.length === 0) {
            throw new Error("new_path is required");
          }
          if (new_path.includes("\0")) throw new Error("new_path contains null byte");
          if (!isAbsolute(new_path)) throw new Error("new_path must be absolute");
    
          const file = readFile(file_id);
          let base: string;
          if (file.storage_type === "reference" && file.project_id) {
            const project = getDatabase()
              .prepare("SELECT path FROM projects WHERE id = ?")
              .get(file.project_id) as { path: string | null } | undefined;
            if (!project?.path) throw new Error(`Project not found for file ${file_id}`);
            base = project.path;
          } else {
            base = join(dataDir, "knowledge");
          }
          const baseResolved = resolve(base);
          const destResolved = resolve(new_path);
          if (destResolved !== baseResolved && !destResolved.startsWith(baseResolved + sep)) {
            throw new Error(`new_path must be inside ${base}`);
          }
          // Defense-in-depth: also confirm the SOURCE lives under the same base.
          // If a project was re-registered to a new path after this file was
          // ingested, fileRecord.path can point outside the current base — and
          // without this check moveFile would relocate that orphan into the
          // project root.
          const srcResolved = resolve(file.path);
          if (srcResolved !== baseResolved && !srcResolved.startsWith(baseResolved + sep)) {
            throw new Error(`source path ${file.path} is no longer inside ${base}; refusing to move`);
          }
    
          const updated = moveFile(file_id, new_path);
          return {
            content: [{ type: "text", text: JSON.stringify(annotateTokens(updated as any), null, 2) }],
          };
        } catch (e: any) {
          return {
            isError: true,
            content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
          };
        }
      }
    );
  • The 'move_file' tool is registered via server.tool() in the MCP server index file. It imports moveFile from ctxnest-core and wires it as an MCP tool with validation and error handling.
    server.tool(
      "move_file",
      "Move/rename a file. Destination 'new_path' must be absolute and resolve INSIDE the file's owning project or global knowledge directory. Cross-project moves are rejected. Operates locally with no auth or limits. Parameters: 'file_id' is a valid file ID. 'new_path' is an absolute path.",
      {
        file_id: z.number().describe("File ID"),
        new_path: z.string().describe("Absolute destination path"),
      },
      async ({ file_id, new_path }) => {
        try {
          if (typeof new_path !== "string" || new_path.length === 0) {
            throw new Error("new_path is required");
          }
          if (new_path.includes("\0")) throw new Error("new_path contains null byte");
          if (!isAbsolute(new_path)) throw new Error("new_path must be absolute");
    
          const file = readFile(file_id);
          let base: string;
          if (file.storage_type === "reference" && file.project_id) {
            const project = getDatabase()
              .prepare("SELECT path FROM projects WHERE id = ?")
              .get(file.project_id) as { path: string | null } | undefined;
            if (!project?.path) throw new Error(`Project not found for file ${file_id}`);
            base = project.path;
          } else {
            base = join(dataDir, "knowledge");
          }
          const baseResolved = resolve(base);
          const destResolved = resolve(new_path);
          if (destResolved !== baseResolved && !destResolved.startsWith(baseResolved + sep)) {
            throw new Error(`new_path must be inside ${base}`);
          }
          // Defense-in-depth: also confirm the SOURCE lives under the same base.
          // If a project was re-registered to a new path after this file was
          // ingested, fileRecord.path can point outside the current base — and
          // without this check moveFile would relocate that orphan into the
          // project root.
          const srcResolved = resolve(file.path);
          if (srcResolved !== baseResolved && !srcResolved.startsWith(baseResolved + sep)) {
            throw new Error(`source path ${file.path} is no longer inside ${base}; refusing to move`);
          }
    
          const updated = moveFile(file_id, new_path);
          return {
            content: [{ type: "text", text: JSON.stringify(annotateTokens(updated as any), null, 2) }],
          };
        } catch (e: any) {
          return {
            isError: true,
            content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
          };
        }
      }
    );
  • Re-exports the moveFile function from the files module as part of the ctxnest-core package's public API.
    import { createFile, readFile, updateFile, deleteFile, listFiles, moveFile, createFolder, deleteFolder, listProjectFolders, slugify } from "./files/index.js";
    export { createFile, readFile, updateFile, deleteFile, listFiles, moveFile, createFolder, deleteFolder, listProjectFolders, slugify };
  • Categorizes 'move_file' under the 'Write' category in the web UI's tool category mapping.
    move_file: "Write",
Behavior3/5

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

With no annotations, the description discloses local operation, no auth/limits, and rejection of cross-project moves. But it does not detail error behavior or whether overwrites occur, leaving some behavioral ambiguity.

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?

Three sentences: purpose, constraints, parameter guidance. No wasted words; very efficient and well-structured.

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

Completeness4/5

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

Covers purpose, constraints, and parameter guidance adequately for a simple file move tool. However, it does not mention return values or error handling, which might be needed for full completeness.

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?

Schema coverage is 100% but descriptions are basic. The tool description adds clarifying constraints (valid file ID, absolute path) and usage context, adding value beyond the 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 moves or renames a file, and specifies constraints like absolute path and no cross-project moves, distinguishing it from other file operations.

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

Usage Guidelines4/5

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

Provides explicit constraints (destination must be absolute, inside allowed directories, no cross-project) and states it requires no auth. However, it does not explicitly when not to use or compare to alternatives like update_file.

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/safiyu/ctxnest'

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