Code Intelligence
code_intelAnalyze 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
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes | JavaScript code to execute. Can use top-level await. Available API methods: searchSymbols, getSymbolDetails, getDependencies, getDependents, findCircularDependencies, traceSymbolUsage, getCallGraph, impactAnalysis, findOrphanedCode, getArchitectureOverview | |
| timeout | No | Maximum execution time in milliseconds (default: 30000, max: 60000) | |
| cwd | Yes | 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. |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| logs | No | ||
| time | No | ||
| error | No | ||
| result | No | ||
| success | Yes | ||
| asOfCommit | No | ||
| lastIndexedAt | No | ||
| resultContext | No |
Implementation Reference
- src/tools/query-code-graph-tool.ts:144-412 (registration)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, }; } },