Skip to main content
Glama
SiroSuzume

MCP ts-morph Refactoring Tools

by SiroSuzume

find_references_by_tsmorph

Locate symbol definitions and all references across a TypeScript project using tsconfig.json. Specify file path and symbol position to analyze where a function, variable, or class is used for informed refactoring.

Instructions

[Uses ts-morph] Finds the definition and all references to a symbol at a given position throughout the project.

Analyzes the project based on tsconfig.json to locate the definition and all usages of the symbol (function, variable, class, etc.) specified by its position.

Usage

Use this tool before refactoring to understand the impact of changing a specific symbol. It helps identify where a function is called, where a variable is used, etc.

  1. Specify the absolute path to the project's tsconfig.json.

  2. Specify the absolute path to the file containing the symbol you want to investigate.

  3. Specify the exact position (line and column) of the symbol within the file.

Parameters

  • tsconfigPath (string, required): Absolute path to the project's root tsconfig.json file. Essential for ts-morph to parse the project. Must be an absolute path.

  • targetFilePath (string, required): The absolute path to the file containing the symbol to find references for. Must be an absolute path.

  • position (object, required): The exact position of the symbol to find references for.

    • line (number, required): 1-based line number.

    • column (number, required): 1-based column number.

Result

  • On success: Returns a message containing the definition location (if found) and a list of reference locations (file path, line number, column number, and line text).

  • On failure: Returns a message indicating the error.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
positionYesThe exact position of the symbol.
targetFilePathYesAbsolute path to the file containing the symbol.
tsconfigPathYesAbsolute path to the project's tsconfig.json file.

Implementation Reference

  • The tool handler function that extracts arguments, calls the findSymbolReferences helper, formats definition and references into a markdown-like text response, handles errors, and includes performance metrics.
    async (args) => {
    	const startTime = performance.now();
    	let message = "";
    	let isError = false;
    	let duration = "0.00"; // duration を外で宣言・初期化
    
    	try {
    		const { tsconfigPath, targetFilePath, position } = args;
    		const { references, definition } = await findSymbolReferences({
    			tsconfigPath: tsconfigPath,
    			targetFilePath: targetFilePath,
    			position,
    		});
    
    		let resultText = "";
    
    		if (definition) {
    			resultText += "Definition:\n";
    			resultText += `- ${definition.filePath}:${definition.line}:${definition.column}\n`;
    			resultText += `  \`\`\`typescript\n  ${definition.text}\n  \`\`\`\n\n`;
    		} else {
    			resultText += "Definition not found.\n\n";
    		}
    
    		if (references.length > 0) {
    			resultText += `References (${references.length} found):\n`;
    			const formattedReferences = references
    				.map(
    					(ref) =>
    						`- ${ref.filePath}:${ref.line}:${ref.column}\n  \`\`\`typescript\n  ${ref.text}\n  \`\`\`\``,
    				)
    				.join("\n\n");
    			resultText += formattedReferences;
    		} else {
    			resultText += "References not found.";
    		}
    		message = resultText.trim();
    	} catch (error) {
    		const errorMessage =
    			error instanceof Error ? error.message : String(error);
    		message = `Error during reference search: ${errorMessage}`;
    		isError = true;
    	} finally {
    		const endTime = performance.now();
    		duration = ((endTime - startTime) / 1000).toFixed(2); // duration を更新
    	}
    
    	// finally の外で return する
    	const finalMessage = `${message}\nStatus: ${
    		isError ? "Failure" : "Success"
    	}\nProcessing time: ${duration} seconds`;
    
    	return {
    		content: [{ type: "text", text: finalMessage }],
    		isError: isError,
    	};
    },
  • Main helper function that uses ts-morph to find the identifier at the given position, retrieve its references and definition, extract locations and line texts, deduplicate definition from references, and sort references.
    export async function findSymbolReferences({
    	tsconfigPath,
    	targetFilePath,
    	position,
    }: {
    	tsconfigPath: string;
    	targetFilePath: string;
    	position: { line: number; column: number };
    }): Promise<{
    	references: ReferenceLocation[];
    	definition: ReferenceLocation | null;
    }> {
    	const project = initializeProject(tsconfigPath);
    
    	// targetFilePath は絶対パスである想定
    	const identifierNode = findIdentifierNode(project, targetFilePath, position);
    
    	// findReferencesAsNodes() は定義箇所を含まない場合がある
    	const referenceNodes: Node[] = identifierNode.findReferencesAsNodes();
    
    	let definitionLocation: ReferenceLocation | null = null;
    	const definitions = identifierNode.getDefinitionNodes();
    	if (definitions.length > 0) {
    		const defNode = definitions[0];
    		const defSourceFile = defNode.getSourceFile();
    		const defStartPos = defNode.getStart();
    		const { line: defLine, column: defColumn } =
    			defSourceFile.getLineAndColumnAtPos(defStartPos);
    		const lineText = getLineText(defSourceFile, defLine);
    		definitionLocation = {
    			filePath: defSourceFile.getFilePath(),
    			line: defLine,
    			column: defColumn,
    			text: lineText.trim(),
    		};
    	}
    
    	const references: ReferenceLocation[] = [];
    	for (const refNode of referenceNodes) {
    		const refSourceFile = refNode.getSourceFile();
    		const refStartPos = refNode.getStart();
    		const { line: refLine, column: refColumn } =
    			refSourceFile.getLineAndColumnAtPos(refStartPos);
    
    		if (
    			definitionLocation &&
    			refLine !== undefined &&
    			refColumn !== undefined &&
    			refSourceFile.getFilePath() === definitionLocation.filePath &&
    			refLine === definitionLocation.line &&
    			refColumn === definitionLocation.column
    		) {
    			continue; // 定義箇所と同じであればスキップ
    		}
    
    		if (refLine === undefined || refColumn === undefined) continue;
    
    		const filePath = refSourceFile.getFilePath();
    		const lineText = getLineText(refSourceFile, refLine);
    
    		references.push({
    			filePath,
    			line: refLine,
    			column: refColumn,
    			text: lineText.trim(),
    		});
    	}
    
    	references.sort((a, b) => {
    		if (a.filePath !== b.filePath) {
    			return a.filePath.localeCompare(b.filePath);
    		}
    		return a.line - b.line;
    	});
    
    	return { references, definition: definitionLocation };
    }
  • Input schema for the tool parameters using Zod: tsconfigPath, targetFilePath, and position object with line and column.
    {
    	tsconfigPath: z
    		.string()
    		.describe("Absolute path to the project's tsconfig.json file."),
    	targetFilePath: z
    		.string()
    		.describe("Absolute path to the file containing the symbol."),
    	position: z
    		.object({
    			line: z.number().describe("1-based line number."),
    			column: z.number().describe("1-based column number."),
    		})
    		.describe("The exact position of the symbol."),
    },
  • Registration function that calls server.tool to register 'find_references_by_tsmorph' with its description, input schema, and handler function.
    export function registerFindReferencesTool(server: McpServer): void {
    	server.tool(
    		"find_references_by_tsmorph",
    		`[Uses ts-morph] Finds the definition and all references to a symbol at a given position throughout the project.
    
    Analyzes the project based on \`tsconfig.json\` to locate the definition and all usages of the symbol (function, variable, class, etc.) specified by its position.
    
    ## Usage
    
    Use this tool before refactoring to understand the impact of changing a specific symbol. It helps identify where a function is called, where a variable is used, etc.
    
    1.  Specify the **absolute path** to the project's \`tsconfig.json\`.
    2.  Specify the **absolute path** to the file containing the symbol you want to investigate.
    3.  Specify the exact **position** (line and column) of the symbol within the file.
    
    ## Parameters
    
    - tsconfigPath (string, required): Absolute path to the project's root \`tsconfig.json\` file. Essential for ts-morph to parse the project. **Must be an absolute path.**
    - targetFilePath (string, required): The absolute path to the file containing the symbol to find references for. **Must be an absolute path.**
    - position (object, required): The exact position of the symbol to find references for.
      - line (number, required): 1-based line number.
      - column (number, required): 1-based column number.
    
    ## Result
    
    - On success: Returns a message containing the definition location (if found) and a list of reference locations (file path, line number, column number, and line text).
    - On failure: Returns a message indicating the error.`,
    		{
    			tsconfigPath: z
    				.string()
    				.describe("Absolute path to the project's tsconfig.json file."),
    			targetFilePath: z
    				.string()
    				.describe("Absolute path to the file containing the symbol."),
    			position: z
    				.object({
    					line: z.number().describe("1-based line number."),
    					column: z.number().describe("1-based column number."),
    				})
    				.describe("The exact position of the symbol."),
    		},
    		async (args) => {
    			const startTime = performance.now();
    			let message = "";
    			let isError = false;
    			let duration = "0.00"; // duration を外で宣言・初期化
    
    			try {
    				const { tsconfigPath, targetFilePath, position } = args;
    				const { references, definition } = await findSymbolReferences({
    					tsconfigPath: tsconfigPath,
    					targetFilePath: targetFilePath,
    					position,
    				});
    
    				let resultText = "";
    
    				if (definition) {
    					resultText += "Definition:\n";
    					resultText += `- ${definition.filePath}:${definition.line}:${definition.column}\n`;
    					resultText += `  \`\`\`typescript\n  ${definition.text}\n  \`\`\`\n\n`;
    				} else {
    					resultText += "Definition not found.\n\n";
    				}
    
    				if (references.length > 0) {
    					resultText += `References (${references.length} found):\n`;
    					const formattedReferences = references
    						.map(
    							(ref) =>
    								`- ${ref.filePath}:${ref.line}:${ref.column}\n  \`\`\`typescript\n  ${ref.text}\n  \`\`\`\``,
    						)
    						.join("\n\n");
    					resultText += formattedReferences;
    				} else {
    					resultText += "References not found.";
    				}
    				message = resultText.trim();
    			} catch (error) {
    				const errorMessage =
    					error instanceof Error ? error.message : String(error);
    				message = `Error during reference search: ${errorMessage}`;
    				isError = true;
    			} finally {
    				const endTime = performance.now();
    				duration = ((endTime - startTime) / 1000).toFixed(2); // duration を更新
    			}
    
    			// finally の外で return する
    			const finalMessage = `${message}\nStatus: ${
    				isError ? "Failure" : "Success"
    			}\nProcessing time: ${duration} seconds`;
    
    			return {
    				content: [{ type: "text", text: finalMessage }],
    				isError: isError,
    			};
    		},
    	);
    }
  • TypeScript interface defining the structure of reference and definition locations returned by findSymbolReferences.
    export interface ReferenceLocation {
    	filePath: string;
    	line: number;
    	column: number;
    	text: string;
    }
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 uses ts-morph for analysis, requires tsconfig.json for project parsing, returns definition and reference locations on success, and provides error messages on failure. It covers the tool's scope and outcomes well, though it doesn't mention performance aspects like execution time or memory usage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (purpose, usage, parameters, result) and front-loads the core functionality. It's appropriately sized for a 3-parameter tool with no annotations, though the 'Parameters' section slightly repeats schema information. Every sentence adds value, making it efficient but not minimal.

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 (3 parameters, nested object, no output schema), the description provides good completeness. It covers purpose, usage context, parameter requirements, and result behavior. The lack of output schema is compensated by describing success/failure outcomes. It could be slightly more complete by detailing output format specifics, but it's largely adequate.

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?

The schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds some context in the 'Usage' section about why each parameter is needed (e.g., tsconfigPath is 'essential for ts-morph to parse the project'), but doesn't provide significant additional semantic value beyond what's in the schema. This meets the baseline for high schema coverage.

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: 'Finds the definition and all references to a symbol at a given position throughout the project.' It specifies the verb ('finds'), resource ('definition and all references to a symbol'), and scope ('throughout the project'), distinguishing it from siblings like rename_symbol_by_tsmorph or move_symbol_to_file_by_tsmorph, which are for modification rather than analysis.

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 guidance on when to use this tool: 'Use this tool before refactoring to understand the impact of changing a specific symbol.' It distinguishes this analysis tool from modification-oriented siblings by emphasizing its preparatory role, helping the agent select it appropriately over alternatives for refactoring tasks.

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