Skip to main content
Glama

Code Intelligence

code_intel
Read-onlyIdempotent

Analyze code structure to find definitions, dependencies, callers, and impact analysis for TypeScript, JavaScript, and Python projects. Use this tool to understand relationships and assess modification risks before refactoring.

Instructions

DECISION RULE: Structure questions → this tool. Text search → Grep.

Before using Grep, ask: Is this a STRUCTURE question (definitions, callers, impact) or a TEXT question (strings, config)?

QUICK START: return await api.searchSymbols({query: "AuthService"}) — simple queries are one-liners. Run api.listMethods() for full API reference with signatures and descriptions. Run api.help("methodName") for inline TypeScript type definitions — no resource reads needed. Compose: const [impact, deps] = await Promise.all([api.impactAnalysis({symbolId}), api.getDependents({filePath})]);

WHY THIS TOOL: Graph-backed intelligence finds indirect relationships, transitive dependencies, and breaking change risks that text search cannot detect.

"What uses X?" disambiguation: getDependents (file imports) vs getCallGraph (call chain) vs traceSymbolUsage (all usages).

USE IMMEDIATELY WHEN: • BEFORE using Edit on a function/class → run impactAnalysis({symbolId}) first • BEFORE exploring an unfamiliar codebase → run getArchitectureOverview() • BEFORE refactoring → trace getDependencies + getDependents for blast radius • Running 3+ Grep calls for structure? STOP → use code_intel instead

TOP 5 QUESTIONS (query is case-insensitive substring match): • "Where is X defined?" / "Find function Y" → searchSymbols({query}) • "What calls X?" / "What imports this?" → getDependents({filePath}) or getCallGraph({symbolId}) • "What does X depend on?" → getDependencies({filePath}) • "Safe to modify X?" / "Blast radius?" → impactAnalysis({symbolId}) • "Find dead code" / "Unused exports?" → findOrphanedCode()

NOT FOR: literal string search, log messages, config values, or reading source code. Use Grep/Glob/Read for those. Supports TypeScript, JavaScript, Python, and more — run api.getCapabilities() to check your project.

WRONG TOOL SIGNAL: If you've run 3+ Grep calls for structure (callers, dependencies, impact), STOP and use code_intel instead. Typical workflow: code_intel to find → Read to view source → Edit to modify

IMPORTANT: The cwd parameter is required — always set it to the target project directory path.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesJavaScript code to execute. Can use top-level await. Available API methods: searchSymbols, getSymbolDetails, getDependencies, getDependents, findCircularDependencies, traceSymbolUsage, getCallGraph, impactAnalysis, findOrphanedCode, getArchitectureOverview
timeoutNoMaximum execution time in milliseconds (default: 30000, max: 60000)
cwdYesAbsolute path to the project directory being queried. Used to locate the correct constellation.json by finding the git repository root. Set this to the root of the repository or workspace folder you are working in.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
logsNo
timeNo
errorNo
resultNo
successYes
asOfCommitNo
lastIndexedAtNo
resultContextNo

Implementation Reference

  • Registration and implementation of the 'code_intel' MCP tool.
    server.registerTool(
    	'code_intel',
    	{
    		title: 'Code Intelligence',
    		description:
    			'DECISION RULE: Structure questions → this tool. Text search → Grep.\n\n' +
    			'Before using Grep, ask: Is this a STRUCTURE question (definitions, callers, impact) or a TEXT question (strings, config)?\n\n' +
    			'QUICK START: `return await api.searchSymbols({query: "AuthService"})` — simple queries are one-liners.\n' +
    			'Run `api.listMethods()` for full API reference with signatures and descriptions.\n' +
    			'Run `api.help("methodName")` for inline TypeScript type definitions — no resource reads needed.\n' +
    			'Compose: `const [impact, deps] = await Promise.all([api.impactAnalysis({symbolId}), api.getDependents({filePath})]);`\n\n' +
    			'WHY THIS TOOL: Graph-backed intelligence finds indirect relationships, transitive dependencies, and breaking change risks that text search cannot detect.\n\n' +
    			'"What uses X?" disambiguation: getDependents (file imports) vs getCallGraph (call chain) vs traceSymbolUsage (all usages).\n\n' +
    			'USE IMMEDIATELY WHEN:\n' +
    			'• BEFORE using Edit on a function/class → run impactAnalysis({symbolId}) first\n' +
    			'• BEFORE exploring an unfamiliar codebase → run getArchitectureOverview()\n' +
    			'• BEFORE refactoring → trace getDependencies + getDependents for blast radius\n' +
    			'• Running 3+ Grep calls for structure? STOP → use code_intel instead\n\n' +
    			'TOP 5 QUESTIONS (query is case-insensitive substring match):\n' +
    			'• "Where is X defined?" / "Find function Y" → searchSymbols({query})\n' +
    			'• "What calls X?" / "What imports this?" → getDependents({filePath}) or getCallGraph({symbolId})\n' +
    			'• "What does X depend on?" → getDependencies({filePath})\n' +
    			'• "Safe to modify X?" / "Blast radius?" → impactAnalysis({symbolId})\n' +
    			'• "Find dead code" / "Unused exports?" → findOrphanedCode()\n\n' +
    			'NOT FOR: literal string search, log messages, config values, or reading source code. Use Grep/Glob/Read for those.\n' +
    			'Supports TypeScript, JavaScript, Python, and more — run api.getCapabilities() to check your project.\n\n' +
    			"WRONG TOOL SIGNAL: If you've run 3+ Grep calls for structure (callers, dependencies, impact), STOP and use code_intel instead.\n" +
    			'Typical workflow: code_intel to find → Read to view source → Edit to modify\n\n' +
    			'IMPORTANT: The `cwd` parameter is required — always set it to the target project directory path.',
    		inputSchema: {
    			code: z
    				.string()
    				.min(1)
    				.describe(
    					'JavaScript code to execute. Can use top-level await. ' +
    						'Available API methods: searchSymbols, getSymbolDetails, getDependencies, ' +
    						'getDependents, findCircularDependencies, traceSymbolUsage, getCallGraph, ' +
    						'impactAnalysis, findOrphanedCode, getArchitectureOverview',
    				),
    			timeout: z
    				.number()
    				.min(MIN_EXECUTION_TIMEOUT_MS)
    				.max(MAX_EXECUTION_TIMEOUT_MS)
    				.optional()
    				.default(DEFAULT_EXECUTION_TIMEOUT_MS)
    				.describe(
    					`Maximum execution time in milliseconds (default: ${DEFAULT_EXECUTION_TIMEOUT_MS}, max: ${MAX_EXECUTION_TIMEOUT_MS})`,
    				),
    			cwd: z
    				.string()
    				.min(1)
    				.describe(
    					'Absolute path to the project directory being queried. ' +
    						'Used to locate the correct constellation.json by finding the git repository root. ' +
    						'Set this to the root of the repository or workspace folder you are working in.',
    				),
    		},
    		outputSchema: {
    			success: z.boolean(),
    			result: z.any().optional(),
    			logs: z.array(z.string()).optional(),
    			time: z.number().optional(),
    			asOfCommit: z.string().optional(),
    			lastIndexedAt: z.string().optional(),
    			resultContext: z
    				.object({
    					reason: z.string(),
    					branchIndexed: z.boolean(),
    					indexedFileCount: z.number(),
    				})
    				.optional(),
    			error: z.string().optional(),
    		},
    		annotations: {
    			readOnlyHint: true,
    			destructiveHint: false,
    			idempotentHint: true,
    			openWorldHint: false,
    		},
    	},
    	async ({ code, timeout, cwd }) => {
    		console.error('[code_intel] Executing code mode script');
    		if (cwd) {
    			console.error(`[code_intel] Using cwd: ${cwd}`);
    		}
    
    		// Resolve configuration context
    		let configContext: ConfigContext;
    		try {
    			configContext = await resolveConfigContext(cwd);
    		} catch (error) {
    			console.error('[code_intel] Config resolution failed:', error);
    
    			// Create structured error for config resolution failures
    			const structuredError = createStructuredError(error, 'code_intel');
    
    			return {
    				content: [
    					{
    						type: 'text',
    						text: JSON.stringify(structuredError, null, 2),
    					},
    				],
    				structuredContent: toErrorStructuredContent(structuredError),
    				isError: true,
    			};
    		}
    
    		try {
    			// Check for configuration errors (e.g., missing constellation.json)
    			if (configContext.initializationError) {
    				console.error(
    					'[code_intel] Configuration error detected, returning setup instructions',
    				);
    
    				// Create structured error for configuration issues
    				const structuredError = createStructuredError(
    					new ConfigurationError(configContext.initializationError),
    					'code_intel',
    					configContext,
    				);
    
    				return {
    					content: [
    						{
    							type: 'text',
    							text: JSON.stringify(structuredError, null, 2),
    						},
    					],
    					structuredContent: toErrorStructuredContent(structuredError),
    					isError: true,
    				};
    			}
    
    			// FIX SB-87: Validate code size to prevent DoS attacks
    			if (code.length > MAX_CODE_SIZE) {
    				console.error(
    					`[code_intel] Code too large: ${code.length} bytes (max ${MAX_CODE_SIZE})`,
    				);
    				const error = new ValidationError(
    					`Code size (${code.length} bytes) exceeds maximum allowed (${MAX_CODE_SIZE} bytes / 100KB)`,
    					{
    						actualSize: code.length,
    						maxSize: MAX_CODE_SIZE,
    						guidance: [
    							'Reduce code size by removing unnecessary code',
    							'Break large operations into smaller steps',
    							'Move data to API calls instead of embedding in code',
    						],
    					},
    				);
    				const structuredError = createStructuredError(
    					error,
    					'code_intel',
    					configContext,
    				);
    				return {
    					content: [
    						{
    							type: 'text',
    							text: JSON.stringify(structuredError, null, 2),
    						},
    					],
    					structuredContent: toErrorStructuredContent(structuredError),
    					isError: true,
    				};
    			}
    
    			// FIX SB-87: Check for binary/control characters
    			if (BINARY_CHAR_PATTERN.test(code)) {
    				console.error('[code_intel] Code contains invalid binary characters');
    				const error = new ValidationError(
    					'Code contains invalid binary or control characters',
    					{
    						reason: 'binary_chars_detected',
    						guidance: [
    							'Ensure code is valid UTF-8 text',
    							'Remove any binary data or control characters',
    							'Check for encoding issues in your code editor',
    						],
    					},
    				);
    				const structuredError = createStructuredError(
    					error,
    					'code_intel',
    					configContext,
    				);
    				return {
    					content: [
    						{
    							type: 'text',
    							text: JSON.stringify(structuredError, null, 2),
    						},
    					],
    					structuredContent: toErrorStructuredContent(structuredError),
    					isError: true,
    				};
    			}
    
    			// Create runtime with configuration
    			const runtime = new CodeModeRuntime({
    				timeout: timeout || DEFAULT_EXECUTION_TIMEOUT_MS,
    				allowConsole: true,
    				allowTimers: false,
    				configContext,
    			});
    
    			// Execute the code
    			const response = await runtime.execute({
    				code,
    				timeout,
    			});
    
    			// Check if response contains a structured error (from API/sandbox)
    			if (response.structuredError) {
    				console.error('[code_intel] Execution returned structured error');
    
    				return {
    					content: [
    						{
    							type: 'text',
    							text: JSON.stringify(response.structuredError, null, 2),
    						},
    					],
    					structuredContent: toErrorStructuredContent(
    						response.structuredError,
    					),
    					isError: true,
    				};
    			}
    
    			// Format the result for successful execution
    			const formatted = runtime.formatResult(response);
    
    			console.error('[code_intel] Execution successful');
    
    			// Return both text and structured content (schema-compliant)
    			return {
    				content: [
    					{
    						type: 'text',
    						text: formatted,
    					},
    				],
    				structuredContent: toSchemaCompliantOutput(response),
    			};
    		} catch (error) {
    			console.error('[code_intel] Execution error:', error);
    
    			// Create structured error for unexpected errors
    			const structuredError = createStructuredError(
    				error,
    				'code_intel',
    				configContext,
    			);
    
    			return {
    				content: [
    					{
    						type: 'text',
    						text: JSON.stringify(structuredError, null, 2),
    					},
    				],
    				structuredContent: toErrorStructuredContent(structuredError),
    				isError: true,
    			};
    		}
    	},
    );
  • The handler function for 'code_intel' which executes code mode scripts.
    async ({ code, timeout, cwd }) => {
    	console.error('[code_intel] Executing code mode script');
    	if (cwd) {
    		console.error(`[code_intel] Using cwd: ${cwd}`);
    	}
    
    	// Resolve configuration context
    	let configContext: ConfigContext;
    	try {
    		configContext = await resolveConfigContext(cwd);
    	} catch (error) {
    		console.error('[code_intel] Config resolution failed:', error);
    
    		// Create structured error for config resolution failures
    		const structuredError = createStructuredError(error, 'code_intel');
    
    		return {
    			content: [
    				{
    					type: 'text',
    					text: JSON.stringify(structuredError, null, 2),
    				},
    			],
    			structuredContent: toErrorStructuredContent(structuredError),
    			isError: true,
    		};
    	}
    
    	try {
    		// Check for configuration errors (e.g., missing constellation.json)
    		if (configContext.initializationError) {
    			console.error(
    				'[code_intel] Configuration error detected, returning setup instructions',
    			);
    
    			// Create structured error for configuration issues
    			const structuredError = createStructuredError(
    				new ConfigurationError(configContext.initializationError),
    				'code_intel',
    				configContext,
    			);
    
    			return {
    				content: [
    					{
    						type: 'text',
    						text: JSON.stringify(structuredError, null, 2),
    					},
    				],
    				structuredContent: toErrorStructuredContent(structuredError),
    				isError: true,
    			};
    		}
    
    		// FIX SB-87: Validate code size to prevent DoS attacks
    		if (code.length > MAX_CODE_SIZE) {
    			console.error(
    				`[code_intel] Code too large: ${code.length} bytes (max ${MAX_CODE_SIZE})`,
    			);
    			const error = new ValidationError(
    				`Code size (${code.length} bytes) exceeds maximum allowed (${MAX_CODE_SIZE} bytes / 100KB)`,
    				{
    					actualSize: code.length,
    					maxSize: MAX_CODE_SIZE,
    					guidance: [
    						'Reduce code size by removing unnecessary code',
    						'Break large operations into smaller steps',
    						'Move data to API calls instead of embedding in code',
    					],
    				},
    			);
    			const structuredError = createStructuredError(
    				error,
    				'code_intel',
    				configContext,
    			);
    			return {
    				content: [
    					{
    						type: 'text',
    						text: JSON.stringify(structuredError, null, 2),
    					},
    				],
    				structuredContent: toErrorStructuredContent(structuredError),
    				isError: true,
    			};
    		}
    
    		// FIX SB-87: Check for binary/control characters
    		if (BINARY_CHAR_PATTERN.test(code)) {
    			console.error('[code_intel] Code contains invalid binary characters');
    			const error = new ValidationError(
    				'Code contains invalid binary or control characters',
    				{
    					reason: 'binary_chars_detected',
    					guidance: [
    						'Ensure code is valid UTF-8 text',
    						'Remove any binary data or control characters',
    						'Check for encoding issues in your code editor',
    					],
    				},
    			);
    			const structuredError = createStructuredError(
    				error,
    				'code_intel',
    				configContext,
    			);
    			return {
    				content: [
    					{
    						type: 'text',
    						text: JSON.stringify(structuredError, null, 2),
    					},
    				],
    				structuredContent: toErrorStructuredContent(structuredError),
    				isError: true,
    			};
    		}
    
    		// Create runtime with configuration
    		const runtime = new CodeModeRuntime({
    			timeout: timeout || DEFAULT_EXECUTION_TIMEOUT_MS,
    			allowConsole: true,
    			allowTimers: false,
    			configContext,
    		});
    
    		// Execute the code
    		const response = await runtime.execute({
    			code,
    			timeout,
    		});
    
    		// Check if response contains a structured error (from API/sandbox)
    		if (response.structuredError) {
    			console.error('[code_intel] Execution returned structured error');
    
    			return {
    				content: [
    					{
    						type: 'text',
    						text: JSON.stringify(response.structuredError, null, 2),
    					},
    				],
    				structuredContent: toErrorStructuredContent(
    					response.structuredError,
    				),
    				isError: true,
    			};
    		}
    
    		// Format the result for successful execution
    		const formatted = runtime.formatResult(response);
    
    		console.error('[code_intel] Execution successful');
    
    		// Return both text and structured content (schema-compliant)
    		return {
    			content: [
    				{
    					type: 'text',
    					text: formatted,
    				},
    			],
    			structuredContent: toSchemaCompliantOutput(response),
    		};
    	} catch (error) {
    		console.error('[code_intel] Execution error:', error);
    
    		// Create structured error for unexpected errors
    		const structuredError = createStructuredError(
    			error,
    			'code_intel',
    			configContext,
    		);
    
    		return {
    			content: [
    				{
    					type: 'text',
    					text: JSON.stringify(structuredError, null, 2),
    				},
    			],
    			structuredContent: toErrorStructuredContent(structuredError),
    			isError: true,
    		};
    	}
    },
Behavior4/5

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

Annotations cover the safety profile (readOnly, idempotent, non-destructive). The description adds valuable behavioral context: it explains the graph-backed analysis capability, notes that queries are case-insensitive substring matches, warns about breaking change risks, and documents the available API methods (searchSymbols, impactAnalysis, etc.) that can be called within the code parameter.

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?

While lengthy, the description is well-structured with clear section headers (DECISION RULE, QUICK START, WHY THIS TOOL, USE IMMEDIATELY WHEN) that allow scanning. The content is front-loaded with the critical decision rule and quick start. Every section serves a distinct purpose for this complex meta-tool that executes arbitrary JavaScript code.

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

Completeness5/5

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

Given the tool's complexity (arbitrary code execution against a code intelligence API) and the presence of an output schema, the description is remarkably complete. It documents all available API methods, provides usage patterns for the five most common questions, explains project capability detection, and outlines typical workflows. No significant gaps remain.

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%, establishing a baseline of 3. The description adds significant value by providing concrete usage examples for the 'code' parameter (e.g., 'return await api.searchSymbols({query: "AuthService"})'), explaining that 'cwd' locates constellation.json via git root, and emphasizing the cwd requirement. This compensates for the abstract nature of the 'code' parameter.

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 explicitly distinguishes structure questions (definitions, callers, impact) from text search, using specific verbs like 'Graph-backed intelligence finds indirect relationships, transitive dependencies.' It clearly identifies the resource (code structure/symbols) and scope, differentiating from text-based alternatives.

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?

Provides explicit decision rules ('Structure questions → this tool. Text search → Grep'), lists specific scenarios for immediate use ('BEFORE using Edit,' 'BEFORE refactoring'), names alternatives explicitly (Grep, Glob, Read), and includes a 'WRONG TOOL SIGNAL' to prevent misuse. This is exemplary guidance.

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/ShiftinBits/constellation-mcp'

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