Skip to main content
Glama
SiroSuzume

MCP ts-morph Refactoring Tools

by SiroSuzume

remove_path_alias_by_tsmorph

Replace path aliases (e.g., '@/') with relative paths in import/export statements within a specified directory or file. Uses ts-morph to analyze tsconfig.json and resolve aliases. Optionally preview changes with a dry run.

Instructions

[Uses ts-morph] Replaces path aliases (e.g., '@/') with relative paths in import/export statements within the specified target path.

Analyzes the project based on tsconfig.json to resolve aliases and calculate relative paths.

Usage

Use this tool to convert alias paths like import Button from '@/components/Button' to relative paths like import Button from '../../components/Button'. This can be useful for improving portability or adhering to specific project conventions.

  1. Specify the absolute path to the projecttsconfig.json.

  2. Specify the absolute path to the target file or directory where path aliases should be removed.

  3. Optionally, run with dryRun: true to preview the changes without modifying files.

Parameters

  • tsconfigPath (string, required): Absolute path to the projecttsconfig.json file. Must be an absolute path.

  • targetPath (string, required): The absolute path to the file or directory to process. Must be an absolute path.

  • dryRun (boolean, optional): If true, only show intended changes without modifying files. Defaults to false.

Result

  • On success: Returns a message containing the list of file paths modified (or scheduled to be modified if dryRun).

  • On failure: Returns a message indicating the error.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dryRunNoIf true, only show intended changes without modifying files.
targetPathYesAbsolute path to the target file or directory.
tsconfigPathYesAbsolute path to the project's tsconfig.json file.

Implementation Reference

  • Core implementation of the path alias removal logic using ts-morph. Processes target files or directories, identifies import/export declarations with path aliases, resolves them, and replaces with relative paths.
    export async function removePathAlias({
    	project,
    	targetPath,
    	dryRun = false,
    	baseUrl,
    	paths,
    }: {
    	project: Project; // Project インスタンスは呼び出し元で作成・管理
    	targetPath: string;
    	dryRun?: boolean;
    	baseUrl: string;
    	paths: Record<string, string[]>;
    }): Promise<{ changedFiles: string[] }> {
    	let filesToProcess: SourceFile[] = [];
    	const directory = project.getDirectory(targetPath);
    
    	if (directory) {
    		filesToProcess = directory.getSourceFiles("**/*.{ts,tsx,js,jsx}");
    	} else {
    		const sourceFile = project.getSourceFile(targetPath);
    		if (!sourceFile) {
    			throw new Error(
    				`指定されたパスはプロジェクト内でディレクトリまたはソースファイルとして見つかりません: ${targetPath}`,
    			);
    		}
    		filesToProcess.push(sourceFile);
    	}
    
    	const changedFilePaths: string[] = [];
    
    	for (const sourceFile of filesToProcess) {
    		const modified = processSourceFile(sourceFile, baseUrl, paths, dryRun);
    		if (!modified) {
    			continue;
    		}
    		changedFilePaths.push(sourceFile.getFilePath());
    	}
    
    	return { changedFiles: changedFilePaths };
    }
  • Registers the 'remove_path_alias_by_tsmorph' MCP tool with schema and handler that wraps the core removePathAlias function.
    	server.tool(
    		"remove_path_alias_by_tsmorph",
    		`[Uses ts-morph] Replaces path aliases (e.g., '@/') with relative paths in import/export statements within the specified target path.
    
    Analyzes the project based on \`tsconfig.json\` to resolve aliases and calculate relative paths.
    
    ## Usage
    
    Use this tool to convert alias paths like \`import Button from '@/components/Button'\` to relative paths like \`import Button from '../../components/Button'\`. This can be useful for improving portability or adhering to specific project conventions.
    
    1.  Specify the **absolute path** to the project\`tsconfig.json\`.
    2.  Specify the **absolute path** to the target file or directory where path aliases should be removed.
    3.  Optionally, run with \`dryRun: true\` to preview the changes without modifying files.
    
    ## Parameters
    
    - tsconfigPath (string, required): Absolute path to the project\`tsconfig.json\` file. **Must be an absolute path.**
    - targetPath (string, required): The absolute path to the file or directory to process. **Must be an absolute path.**
    - dryRun (boolean, optional): If true, only show intended changes without modifying files. Defaults to false.
    
    ## Result
    
    - On success: Returns a message containing the list of file paths modified (or scheduled to be modified if dryRun).
    - On failure: Returns a message indicating the error.`,
    		{
    			tsconfigPath: z
    				.string()
    				.describe("Absolute path to the project's tsconfig.json file."),
    			targetPath: z
    				.string()
    				.describe("Absolute path to the target file or directory."),
    			dryRun: z
    				.boolean()
    				.optional()
    				.default(false)
    				.describe(
    					"If true, only show intended changes without modifying files.",
    				),
    		},
    		async (args) => {
    			const startTime = performance.now();
    			let message = "";
    			let isError = false;
    			let duration = "0.00";
    			const project = new Project({
    				tsConfigFilePath: args.tsconfigPath,
    			});
    
    			try {
    				const { tsconfigPath, targetPath, dryRun } = args;
    				const compilerOptions = project.compilerOptions.get();
    				const tsconfigDir = path.dirname(tsconfigPath);
    				const baseUrl = path.resolve(
    					tsconfigDir,
    					compilerOptions.baseUrl ?? ".",
    				);
    				const pathsOption = compilerOptions.paths ?? {};
    
    				const result = await removePathAlias({
    					project,
    					targetPath,
    					dryRun,
    					baseUrl,
    					paths: pathsOption,
    				});
    
    				if (!dryRun) {
    					await project.save();
    				}
    
    				const changedFilesList =
    					result.changedFiles.length > 0
    						? result.changedFiles.join("\n - ")
    						: "(No changes)";
    				const actionVerb = dryRun ? "scheduled for modification" : "modified";
    				message = `Path alias removal (${
    					dryRun ? "Dry run" : "Execute"
    				}): Within the specified path '${targetPath}', the following files were ${actionVerb}:\n - ${changedFilesList}`;
    			} catch (error) {
    				const errorMessage =
    					error instanceof Error ? error.message : String(error);
    				message = `Error during path alias removal process: ${errorMessage}`;
    				isError = true;
    			} finally {
    				const endTime = performance.now();
    				duration = ((endTime - startTime) / 1000).toFixed(2);
    			}
    
    			const finalMessage = `${message}\nStatus: ${
    				isError ? "Failure" : "Success"
    			}\nProcessing time: ${duration} seconds`;
    
    			return {
    				content: [{ type: "text", text: finalMessage }],
    				isError: isError,
    			};
    		},
    	);
  • Zod schema defining input parameters: tsconfigPath, targetPath, dryRun.
    {
    	tsconfigPath: z
    		.string()
    		.describe("Absolute path to the project's tsconfig.json file."),
    	targetPath: z
    		.string()
    		.describe("Absolute path to the target file or directory."),
    	dryRun: z
    		.boolean()
    		.optional()
    		.default(false)
    		.describe(
    			"If true, only show intended changes without modifying files.",
    		),
    },
  • Helper function that processes a single source file: scans import/export declarations, replaces path aliases with relative paths if applicable.
    function processSourceFile(
    	sourceFile: SourceFile,
    	baseUrl: string,
    	paths: Record<string, string[]>,
    	dryRun: boolean,
    ): boolean {
    	let changed = false;
    	const sourceFilePath = sourceFile.getFilePath();
    	const alias = Object.keys(paths);
    	const declarations: (ImportDeclaration | ExportDeclaration)[] = [
    		...sourceFile.getImportDeclarations(),
    		...sourceFile.getExportDeclarations(),
    	];
    
    	for (const declaration of declarations) {
    		const moduleSpecifierNode = declaration.getModuleSpecifier();
    		if (!moduleSpecifierNode) continue;
    
    		const moduleSpecifier = moduleSpecifierNode.getLiteralText();
    
    		if (!isPathAlias(moduleSpecifier, alias)) {
    			continue;
    		}
    
    		// TypeScript/ts-morph の解決結果を使用
    		const resolvedSourceFile = declaration.getModuleSpecifierSourceFile();
    
    		if (!resolvedSourceFile) {
    			// console.warn(`[remove-path-alias] Could not resolve module specifier: ${moduleSpecifier} in ${sourceFilePath}`);
    			continue; // 解決できないエイリアスはスキップ
    		}
    		const targetAbsolutePath = resolvedSourceFile.getFilePath();
    
    		const relativePath = calculateRelativePath(
    			sourceFilePath,
    			targetAbsolutePath,
    			{
    				simplifyIndex: false,
    				removeExtensions: true,
    			},
    		);
    
    		if (!dryRun) {
    			declaration.setModuleSpecifier(relativePath);
    		}
    		changed = true;
    	}
    	return changed;
    }
  • Helper function to check if a module specifier matches any path alias from tsconfig paths.
    function isPathAlias(moduleSpecifier: string, alias: string[]): boolean {
    	// paths のキー(例: "@/*", "@components/*", "exact-alias")に基づいて判定
    	return alias.some((alias) => {
    		if (moduleSpecifier === alias) {
    			return true; // 完全一致
    		}
    		if (!alias.endsWith("/*")) {
    			return false; // ワイルドカードエイリアスでない場合は false
    		}
    		const prefix = alias.substring(0, alias.length - 1); // 末尾の '*' を除く (例: "@/", "@components/")
    		return moduleSpecifier.startsWith(prefix);
    	});
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key behaviors: it modifies files (implied by 'replaces'), offers a dry-run mode for previewing changes, analyzes tsconfig.json for alias resolution, and specifies that paths must be absolute. It also mentions the result format (list of modified files or error message). However, it doesn't explicitly state whether changes are reversible or discuss error-handling details beyond generic failure messages.

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 well-structured and appropriately sized. It front-loads the core purpose in the first sentence, uses clear sections (Usage, Parameters, Result), and every sentence adds value—no redundant or vague statements. The bullet points in the Parameters and Result sections are efficient and easy to scan.

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?

Given the tool's moderate complexity (file modification with ts-morph analysis), no annotations, and no output schema, the description does a strong job. It covers purpose, usage, parameters, and results adequately. However, it lacks details on potential side effects (e.g., whether it modifies files in place or creates backups) and doesn't fully explain the output format beyond a high-level message. For a mutation tool with no annotations, this leaves minor gaps in behavioral context.

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 description coverage is 100%, so the schema already documents all parameters. The description adds meaningful context beyond the schema: it explains why tsconfigPath is needed ('to resolve aliases'), clarifies that targetPath can be a file or directory, and provides a concrete example of the dryRun behavior ('preview the changes without modifying files'). This enhances understanding but doesn't add new parameter-specific details beyond what's in the schema descriptions.

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: 'Replaces path aliases (e.g., '@/') with relative paths in import/export statements within the specified target path.' It specifies the exact action (replaces), the resource (path aliases in import/export statements), and distinguishes from siblings like 'rename_symbol_by_tsmorph' or 'move_symbol_to_file_by_tsmorph' by focusing on path alias conversion rather than symbol manipulation.

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

Usage Guidelines5/5

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

The description provides explicit usage guidance: 'Use this tool to convert alias paths... This can be useful for improving portability or adhering to specific project conventions.' It includes a specific example and distinguishes when to use this tool (for path alias conversion) versus not using it (for other refactoring tasks handled by sibling tools). The 'Usage' section further clarifies the context with step-by-step instructions.

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

Related 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/SiroSuzume/mcp-ts-morph'

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