diff --git a/packages/core/src/tools/mcp-tool.test.ts b/packages/core/src/tools/mcp-tool.test.ts index 005623afee..1826ff1977 100644 --- a/packages/core/src/tools/mcp-tool.test.ts +++ b/packages/core/src/tools/mcp-tool.test.ts @@ -18,6 +18,8 @@ import { ToolConfirmationOutcome } from './tools.js'; import type { CallableTool, Part } from '@google/genai'; import { ToolErrorType } from './tool-error.js'; +vi.mock('node:fs/promises'); + // Mock @google/genai mcpToTool and CallableTool // We only need to mock the parts of CallableTool that DiscoveredMCPTool uses. const mockCallTool = vi.fn(); @@ -147,7 +149,7 @@ describe('DiscoveredMCPTool', () => { expect(toolResult.returnDisplay).toBe(stringifiedResponseContent); }); - it('should handle empty result from getStringifiedResultForDisplay', async () => { + it('should handle empty result from getDisplayFromParts', async () => { const params = { param: 'testValue' }; const mockMcpToolResponsePartsEmpty: Part[] = []; mockCallTool.mockResolvedValue(mockMcpToolResponsePartsEmpty); @@ -155,7 +157,9 @@ describe('DiscoveredMCPTool', () => { const toolResult: ToolResult = await invocation.execute( new AbortController().signal, ); - expect(toolResult.returnDisplay).toBe('```json\n[]\n```'); + expect(toolResult.returnDisplay).toBe( + '[Error: Could not parse tool response]', + ); expect(toolResult.llmContent).toEqual([ { text: '[Error: Could not parse tool response]' }, ]); @@ -339,7 +343,9 @@ describe('DiscoveredMCPTool', () => { }, }, ]); - expect(toolResult.returnDisplay).toBe('[Audio: audio/mp3]'); + expect(toolResult.returnDisplay).toBe( + `[Tool '${serverToolName}' provided the following audio data with mime-type: audio/mp3]\n[audio/mp3]`, + ); }); it('should handle a ResourceLinkBlock response', async () => { @@ -372,7 +378,7 @@ describe('DiscoveredMCPTool', () => { }, ]); expect(toolResult.returnDisplay).toBe( - '[Link to My Resource: file:///path/to/thing]', + 'Resource Link: My Resource at file:///path/to/thing', ); }); @@ -446,7 +452,7 @@ describe('DiscoveredMCPTool', () => { }, ]); expect(toolResult.returnDisplay).toBe( - '[Embedded Resource: application/octet-stream]', + `[Tool '${serverToolName}' provided the following embedded resource with mime-type: application/octet-stream]\n[application/octet-stream]`, ); }); @@ -489,7 +495,7 @@ describe('DiscoveredMCPTool', () => { { text: 'Second part.' }, ]); expect(toolResult.returnDisplay).toBe( - 'First part.\n[Image: image/jpeg]\nSecond part.', + `First part.\n[Tool '${serverToolName}' provided the following image data with mime-type: image/jpeg]\n[image/jpeg]\nSecond part.`, ); }); @@ -514,9 +520,7 @@ describe('DiscoveredMCPTool', () => { const toolResult = await invocation.execute(new AbortController().signal); expect(toolResult.llmContent).toEqual([{ text: 'Valid part.' }]); - expect(toolResult.returnDisplay).toBe( - 'Valid part.\n[Unknown content type: future_block]', - ); + expect(toolResult.returnDisplay).toBe('Valid part.'); }); it('should handle a complex mix of content block types', async () => { @@ -574,7 +578,7 @@ describe('DiscoveredMCPTool', () => { }, ]); expect(toolResult.returnDisplay).toBe( - 'Here is a resource.\n[Link to My Resource: file:///path/to/resource]\nEmbedded text content.\n[Image: image/jpeg]', + `Here is a resource.\nResource Link: My Resource at file:///path/to/resource\nEmbedded text content.\n[Tool '${serverToolName}' provided the following image data with mime-type: image/jpeg]\n[image/jpeg]`, ); }); @@ -964,6 +968,223 @@ describe('DiscoveredMCPTool', () => { }); }); + describe('output truncation for large MCP results', () => { + const THRESHOLD = 1000; + const TRUNCATE_LINES = 50; + + const mockConfigWithTruncation = { + getTruncateToolOutputThreshold: () => THRESHOLD, + getTruncateToolOutputLines: () => TRUNCATE_LINES, + getUsageStatisticsEnabled: () => false, + storage: { + getProjectTempDir: () => '/tmp/test-project', + }, + isTrustedFolder: () => true, + } as any; + + it('should truncate large text results from direct client execution', async () => { + const largeText = 'Line of text content\n'.repeat(200); // ~4200 chars, well over THRESHOLD + const mockMcpClient: McpDirectClient = { + callTool: vi.fn(async () => ({ + content: [{ type: 'text', text: largeText }], + })), + }; + + const truncTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, // trust + undefined, + mockConfigWithTruncation, + mockMcpClient, + ); + + const invocation = truncTool.build({ param: 'test' }); + const result = await invocation.execute(new AbortController().signal); + + // The text part in llmContent should be truncated + const textParts = (result.llmContent as Part[]).filter( + (p: Part) => p.text, + ); + const combinedText = textParts.map((p: Part) => p.text).join(''); + expect(combinedText.length).toBeLessThan(largeText.length); + expect(combinedText).toContain('CONTENT TRUNCATED'); + expect(result.returnDisplay).toContain('CONTENT TRUNCATED'); + }); + + it('should truncate large text results from callable tool execution', async () => { + const largeText = 'Line of text content\n'.repeat(200); + const mockMcpToolResponseParts: Part[] = [ + { + functionResponse: { + name: serverToolName, + response: { + content: [{ type: 'text', text: largeText }], + }, + }, + }, + ]; + mockCallTool.mockResolvedValue(mockMcpToolResponseParts); + + const truncTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfigWithTruncation, + ); + + const invocation = truncTool.build({ param: 'test' }); + const result = await invocation.execute(new AbortController().signal); + + const textParts = (result.llmContent as Part[]).filter( + (p: Part) => p.text, + ); + const combinedText = textParts.map((p: Part) => p.text).join(''); + expect(combinedText.length).toBeLessThan(largeText.length); + expect(combinedText).toContain('CONTENT TRUNCATED'); + expect(result.returnDisplay).toContain('CONTENT TRUNCATED'); + }); + + it('should not truncate small text results', async () => { + const smallText = 'Small response'; + const mockMcpClient: McpDirectClient = { + callTool: vi.fn(async () => ({ + content: [{ type: 'text', text: smallText }], + })), + }; + + const truncTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfigWithTruncation, + mockMcpClient, + ); + + const invocation = truncTool.build({ param: 'test' }); + const result = await invocation.execute(new AbortController().signal); + + expect(result.llmContent).toEqual([{ text: smallText }]); + expect(result.returnDisplay).not.toContain('Output too long'); + }); + + it('should not truncate non-text content (images, audio)', async () => { + const mockMcpClient: McpDirectClient = { + callTool: vi.fn(async () => ({ + content: [ + { + type: 'image', + data: 'x'.repeat(5000), // large base64 data + mimeType: 'image/png', + }, + ], + })), + }; + + const truncTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfigWithTruncation, + mockMcpClient, + ); + + const invocation = truncTool.build({ param: 'test' }); + const result = await invocation.execute(new AbortController().signal); + + // Image data should not be truncated + const inlineDataParts = (result.llmContent as Part[]).filter( + (p: Part) => p.inlineData, + ); + expect(inlineDataParts[0].inlineData!.data).toBe('x'.repeat(5000)); + }); + + it('should truncate only text parts in mixed content', async () => { + const largeText = 'Line of text content\n'.repeat(200); + const mockMcpClient: McpDirectClient = { + callTool: vi.fn(async () => ({ + content: [ + { type: 'text', text: largeText }, + { + type: 'image', + data: 'IMAGE_DATA', + mimeType: 'image/png', + }, + ], + })), + }; + + const truncTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfigWithTruncation, + mockMcpClient, + ); + + const invocation = truncTool.build({ param: 'test' }); + const result = await invocation.execute(new AbortController().signal); + + const parts = result.llmContent as Part[]; + // Text should be truncated + const textPart = parts.find( + (p: Part) => p.text && !p.text.startsWith('[Tool'), + ); + expect(textPart!.text!.length).toBeLessThan(largeText.length); + expect(textPart!.text).toContain('CONTENT TRUNCATED'); + // Image should be preserved + const imagePart = parts.find((p: Part) => p.inlineData); + expect(imagePart!.inlineData!.data).toBe('IMAGE_DATA'); + }); + + it('should not truncate when config is not provided', async () => { + const largeText = 'Line of text content\n'.repeat(200); + const mockMcpClient: McpDirectClient = { + callTool: vi.fn(async () => ({ + content: [{ type: 'text', text: largeText }], + })), + }; + + // No cliConfig provided + const truncTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + undefined, + undefined, + undefined, // no config + mockMcpClient, + ); + + const invocation = truncTool.build({ param: 'test' }); + const result = await invocation.execute(new AbortController().signal); + + // Without config, should return untouched + expect(result.llmContent).toEqual([{ text: largeText }]); + }); + }); + describe('streaming progress for long-running MCP tools', () => { it('should have canUpdateOutput set to true so the scheduler creates liveOutputCallback', () => { // For long-running MCP tools (e.g., browseruse), the scheduler needs diff --git a/packages/core/src/tools/mcp-tool.ts b/packages/core/src/tools/mcp-tool.ts index 5d48b68c79..73ba1ece4c 100644 --- a/packages/core/src/tools/mcp-tool.ts +++ b/packages/core/src/tools/mcp-tool.ts @@ -23,6 +23,7 @@ import { import type { CallableTool, FunctionCall, Part } from '@google/genai'; import { ToolErrorType } from './tool-error.js'; import type { Config } from '../config/config.js'; +import { truncateToolOutput } from '../utils/truncation.js'; type ToolParams = Record; @@ -263,10 +264,11 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< } const transformedParts = transformMcpContentToParts(rawResponseParts); + const truncatedParts = await this.truncateTextParts(transformedParts); return { - llmContent: transformedParts, - returnDisplay: getStringifiedResultForDisplay(rawResponseParts), + llmContent: truncatedParts, + returnDisplay: getDisplayFromParts(truncatedParts), }; } @@ -333,13 +335,39 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< } const transformedParts = transformMcpContentToParts(rawResponseParts); + const truncatedParts = await this.truncateTextParts(transformedParts); return { - llmContent: transformedParts, - returnDisplay: getStringifiedResultForDisplay(rawResponseParts), + llmContent: truncatedParts, + returnDisplay: getDisplayFromParts(truncatedParts), }; } + /** + * Truncates text parts in the transformed result if they exceed the + * configured threshold. Non-text parts (images, audio, etc.) are preserved. + */ + private async truncateTextParts(parts: Part[]): Promise { + if (!this.cliConfig) { + return parts; + } + + const result: Part[] = []; + for (const part of parts) { + if (part.text && !part.inlineData) { + const truncated = await truncateToolOutput( + this.cliConfig, + `mcp__${this.serverName}__${this.serverToolName}`, + part.text, + ); + result.push({ text: truncated.content }); + } else { + result.push(part); + } + } + return result; + } + getDescription(): string { return safeJsonStringify(this.params); } @@ -524,43 +552,22 @@ function transformMcpContentToParts(sdkResponse: Part[]): Part[] { } /** - * Processes the raw response from the MCP tool to generate a clean, - * human-readable string for display in the CLI. It summarizes non-text - * content and presents text directly. - * - * @param rawResponse The raw Part[] array from the GenAI SDK. - * @returns A formatted string representing the tool's output. + * Builds a human-readable display string from transformed Part[]. + * Text parts are shown directly; inline data is summarized by mime type. */ -function getStringifiedResultForDisplay(rawResponse: Part[]): string { - const mcpContent = rawResponse?.[0]?.functionResponse?.response?.[ - 'content' - ] as McpContentBlock[]; - - if (!Array.isArray(mcpContent)) { - return '```json\n' + JSON.stringify(rawResponse, null, 2) + '\n```'; +function getDisplayFromParts(parts: Part[]): string { + if (parts.length === 0) { + return ''; } - const displayParts = mcpContent.map((block: McpContentBlock): string => { - switch (block.type) { - case 'text': - return block.text; - case 'image': - return `[Image: ${block.mimeType}]`; - case 'audio': - return `[Audio: ${block.mimeType}]`; - case 'resource_link': - return `[Link to ${block.title || block.name}: ${block.uri}]`; - case 'resource': - if (block.resource?.text) { - return block.resource.text; - } - return `[Embedded Resource: ${ - block.resource?.mimeType || 'unknown type' - }]`; - default: - return `[Unknown content type: ${(block as { type: string }).type}]`; + const displayParts: string[] = []; + for (const part of parts) { + if (part.text !== undefined) { + displayParts.push(part.text); + } else if (part.inlineData) { + displayParts.push(`[${part.inlineData.mimeType}]`); } - }); + } return displayParts.join('\n'); } diff --git a/packages/core/src/tools/shell.ts b/packages/core/src/tools/shell.ts index 1de48b599a..54ecf30f8a 100644 --- a/packages/core/src/tools/shell.ts +++ b/packages/core/src/tools/shell.ts @@ -26,9 +26,7 @@ import { Kind, } from './tools.js'; import { getErrorMessage } from '../utils/errors.js'; -import { truncateAndSaveToFile } from '../utils/truncation.js'; -import { logToolOutputTruncated } from '../telemetry/loggers.js'; -import { ToolOutputTruncatedEvent } from '../telemetry/types.js'; +import { truncateToolOutput } from '../utils/truncation.js'; import type { ShellExecutionConfig, ShellOutputEvent, @@ -381,21 +379,11 @@ export class ShellToolInvocation extends BaseToolInvocation< } // Truncate large output and save full content to a temp file. - const truncateThreshold = this.config.getTruncateToolOutputThreshold(); - const truncateLines = this.config.getTruncateToolOutputLines(); - if ( - typeof llmContent === 'string' && - truncateThreshold > 0 && - truncateLines > 0 - ) { - const originalContentLength = llmContent.length; - const fileName = `shell_${crypto.randomBytes(6).toString('hex')}`; - const truncatedResult = await truncateAndSaveToFile( + if (typeof llmContent === 'string') { + const truncatedResult = await truncateToolOutput( + this.config, + ShellTool.Name, llmContent, - fileName, - this.config.storage.getProjectTempDir(), - truncateThreshold, - truncateLines, ); if (truncatedResult.outputFile) { @@ -403,17 +391,6 @@ export class ShellToolInvocation extends BaseToolInvocation< returnDisplayMessage += (returnDisplayMessage ? '\n' : '') + `Output too long and was saved to: ${truncatedResult.outputFile}`; - - logToolOutputTruncated( - this.config, - new ToolOutputTruncatedEvent('', { - toolName: ShellTool.Name, - originalContentLength, - truncatedContentLength: truncatedResult.content.length, - threshold: truncateThreshold, - lines: truncateLines, - }), - ); } } diff --git a/packages/core/src/utils/truncation.ts b/packages/core/src/utils/truncation.ts index 47a21ef601..6672a1f83d 100644 --- a/packages/core/src/utils/truncation.ts +++ b/packages/core/src/utils/truncation.ts @@ -6,7 +6,11 @@ import * as fs from 'node:fs/promises'; import * as path from 'node:path'; +import * as crypto from 'node:crypto'; import { ReadFileTool } from '../tools/read-file.js'; +import type { Config } from '../config/config.js'; +import { logToolOutputTruncated } from '../telemetry/loggers.js'; +import { ToolOutputTruncatedEvent } from '../telemetry/types.js'; /** * Truncates large tool output and saves the full content to a temp file. @@ -100,3 +104,50 @@ ${truncatedContent}`, }; } } + +/** + * High-level truncation helper that reads thresholds from Config, + * truncates if needed, saves full output to a temp file, and logs + * telemetry. Returns the (possibly truncated) content and an optional + * output file path. + * + * Callers no longer need to duplicate config extraction, file naming, + * or telemetry logging. + */ +export async function truncateToolOutput( + config: Config, + toolName: string, + content: string, +): Promise<{ content: string; outputFile?: string }> { + const threshold = config.getTruncateToolOutputThreshold(); + const lines = config.getTruncateToolOutputLines(); + + if (threshold <= 0 || lines <= 0) { + return { content }; + } + + const originalLength = content.length; + const fileName = `${toolName}_${crypto.randomBytes(6).toString('hex')}`; + const result = await truncateAndSaveToFile( + content, + fileName, + config.storage.getProjectTempDir(), + threshold, + lines, + ); + + if (result.outputFile) { + logToolOutputTruncated( + config, + new ToolOutputTruncatedEvent('', { + toolName, + originalContentLength: originalLength, + truncatedContentLength: result.content.length, + threshold, + lines, + }), + ); + } + + return result; +}