mcp_translate_code
Translate code between programming languages while preserving structure and comments. This tool converts source code from one language to another, maintaining the original logic and formatting for local development workflows.
Instructions
Translate code between languages with structure preservation.
Tool call template
Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {
"code": "<code>",
"sourceLanguage": "<sourceLanguage>",
"targetLanguage": "<targetLanguage>"
},
"name": "mcp_translate_code"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes | Source code to translate | |
| sourceLanguage | Yes | Source programming language | |
| targetLanguage | Yes | Target programming language | |
| preserveComments | No | Keep comments in output (default: true) |
Implementation Reference
- src/tools/code-assistance.ts:724-785 (handler)The `translateCode` method within `CodeAssistanceTools` class acts as the handler for the `mcp_translate_code` tool, coordinating the LLM call for translating code between programming languages.
async translateCode( code: string, targetLanguage: string, options?: { sourceLanguage?: string; preserveComments?: boolean; } ): Promise<TranslateCodeResult> { const sourceLanguage = options?.sourceLanguage ?? 'auto-detect'; const prompt = `You are an expert polyglot programmer. Translate this code from ${sourceLanguage} to ${targetLanguage}. Guidelines: - Use idiomatic patterns in the target language - Include equivalent library imports where needed - ${options?.preserveComments ? 'Preserve and translate comments' : 'Add comments explaining key differences'} Provide your response as JSON: { "sourceLanguage": "Detected or specified source language", "targetLanguage": "${targetLanguage}", "translatedCode": "The translated code", "notes": ["Important translation notes"], "warnings": ["Any caveats or things that couldn't be directly translated"] }`; try { const responseText = await this.llmWrapper.callToolLlm( 'mcp_translate_code', [ { role: 'system', content: prompt }, { role: 'user', content: `\`\`\`${sourceLanguage}\n${code}\n\`\`\`` }, ], { type: 'translate_code', sourceLanguage, targetLanguage } ); const parsed = this.parseJsonResponse(responseText, { sourceLanguage: sourceLanguage, targetLanguage: targetLanguage, translatedCode: '', notes: [], }); return { success: true, sourceLanguage: parsed.sourceLanguage || sourceLanguage, targetLanguage: parsed.targetLanguage || targetLanguage, translatedCode: parsed.translatedCode || '', notes: parsed.notes || [], warnings: parsed.warnings, }; } catch (error) { return { success: false, sourceLanguage: sourceLanguage, targetLanguage: targetLanguage, translatedCode: '', notes: [], error: error instanceof Error ? error.message : 'Unknown error', }; } }