Skip to main content
Glama

code_generate

Generate Hedera SDK code in multiple languages from natural language descriptions, creating runnable implementations with imports and error handling.

Instructions

Generate context-aware Hedera SDK code from natural language.

CREATES: Complete, runnable code with imports, error handling, best practices LANGUAGES: JavaScript, TypeScript, Java, Python, Go, Solidity STYLES: minimal (core logic), complete (with setup), production (full best practices)

USE FOR: Creating new implementations, generating boilerplate, scaffolding projects.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
descriptionYesWhat code to generate
languageNoTarget language (default: javascript)
styleNoCode style (default: complete)
includeImportsNoInclude imports (default: true)
includeErrorHandlingNoInclude try-catch (default: true)

Implementation Reference

  • Main handler function for the code_generate tool. Searches relevant Hedera documentation using RAG, builds context from code examples, and generates new SDK code using OpenAI GPT-4o-mini based on user description, language, and style preferences.
    export async function codeGenerate(args: { description: string; language?: string; includeImports?: boolean; includeErrorHandling?: boolean; style?: string; }) { try { const services = await initializeRAGServices(); if (!services) { throw new Error('RAG services not initialized. Ensure OPENAI_API_KEY and CHROMA_URL are configured.'); } const language = args.language || 'javascript'; const includeImports = args.includeImports !== false; const includeErrorHandling = args.includeErrorHandling !== false; const style = args.style || 'complete'; logger.info('Generating code from description', { description: args.description.substring(0, 100), language, style, }); // Step 1: Search for relevant documentation and examples const relevantDocs = await services.ragService.search(args.description, { topK: 5, filters: { hasCode: true }, }); // Step 2: Build context from relevant documentation const contextChunks = relevantDocs.map(doc => ({ content: doc.chunk.text, source: doc.chunk.metadata.url, title: doc.chunk.metadata.title, })); // Step 3: Generate code using OpenAI with RAG context const systemPrompt = `You are an expert Hedera Network developer. Generate clean, working ${language} code based on the user's requirements. IMPORTANT GUIDELINES: ${language === 'solidity' ? `- Write Solidity smart contracts optimized for Hedera EVM - Use pragma solidity ^0.8.0 or higher - Follow OpenZeppelin standards when applicable (e.g., ERC-20, ERC-721) - Optimize for gas efficiency on Hedera - Include SPDX license identifier - Add NatSpec documentation comments` : `- Use the official Hedera SDK (@hashgraph/sdk for JavaScript/TypeScript)`} - Follow best practices from the provided documentation context - ${includeImports ? 'Include all necessary import statements' : 'Omit import statements'} - ${includeErrorHandling ? (language === 'solidity' ? 'Include require statements and custom errors for validation' : 'Include proper error handling with try-catch blocks') : 'Focus on core logic without extensive error handling'} - Style: ${style === 'minimal' ? 'Minimal - just the core logic' : style === 'complete' ? 'Complete - include setup and teardown' : 'Production-ready - include validation, logging, and best practices'} - Add clear comments explaining each step - ${language === 'solidity' ? 'Ensure the contract is deployable on Hedera EVM' : 'Ensure the code is immediately runnable (after setting up credentials)'} CONTEXT FROM HEDERA DOCUMENTATION: ${contextChunks.map(c => `--- ${c.title} (${c.source}) ---\n${c.content}`).join('\n\n')}`; const userPrompt = `Generate ${language} code for: ${args.description} Requirements: - Language: ${language} - Include imports: ${includeImports} - Include error handling: ${includeErrorHandling} - Style: ${style} Please provide: 1. Complete working code 2. Brief explanation of what the code does 3. Any prerequisites or setup requirements 4. Example usage if applicable`; const completion = await services.openai.chat.completions.create({ model: 'gpt-4o-mini', messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: userPrompt }, ], temperature: 0.3, max_tokens: 3000, }); const generatedResponse = completion.choices[0]?.message?.content || ''; // Parse the response to extract code and explanation const codeMatch = generatedResponse.match(/```(?:javascript|typescript|java|python|go|solidity)?\n([\s\S]*?)```/); const code = codeMatch ? codeMatch[1].trim() : generatedResponse; const response = { description: args.description, language, style, generatedCode: code, fullResponse: generatedResponse, sources: contextChunks.map(c => ({ title: c.title, url: c.source, })), metadata: { model: 'gpt-4o-mini', includeImports, includeErrorHandling, contextDocuments: contextChunks.length, }, }; // Format sources as a readable list at the bottom const sourcesSection = contextChunks.length > 0 ? '\n\n---\n**Sources Used for Code Generation:**\n' + contextChunks.map((c, i) => `${i + 1}. [${c.title}](${c.source})` ).join('\n') + '\n\n*Generated by HashPilot RAG System*' : '\n\n*Generated by HashPilot RAG System*'; return { content: [ { type: 'text', text: JSON.stringify(response, null, 2) + sourcesSection, }, ], }; } catch (error: any) { logger.error('code_generate failed', { error: error.message }); return { content: [ { type: 'text', text: `Error: ${error.message}`, }, ], isError: true, }; } }
  • Input schema and tool metadata definition for code_generate, including description, parameters (description, language, style, etc.), and validation rules.
    export const codeGenerateTool = { name: 'code_generate', description: 'Generate context-aware Hedera SDK code from natural language descriptions. Synthesizes new, working code based on your requirements using knowledge from official documentation and SDK references. Use this tool when you need to create custom Hedera implementations: account creation workflows, token operations (create, transfer, mint), HCS messaging patterns, smart contract interactions, scheduled transactions, multi-signature setups, and more. Returns complete, runnable code with explanations and best practices.', inputSchema: { type: 'object' as const, properties: { description: { type: 'string', description: 'Natural language description of the code you need. Be specific about the functionality (e.g., "create a fungible token with 1000 initial supply and 2 decimal places", "transfer HBAR from one account to another with memo", "subscribe to HCS topic and process messages")', }, language: { type: 'string', enum: ['javascript', 'typescript', 'java', 'python', 'go', 'solidity'], description: 'Target programming language for the generated code', default: 'javascript', }, includeImports: { type: 'boolean', description: 'Include necessary import statements', default: true, }, includeErrorHandling: { type: 'boolean', description: 'Include try-catch blocks and error handling', default: true, }, style: { type: 'string', enum: ['minimal', 'complete', 'production'], description: 'Code style: minimal (core logic only), complete (with setup), production (with best practices, validation, logging)', default: 'complete', }, }, required: ['description'], }, };
  • src/index.ts:628-630 (registration)
    Registration and dispatch handler in the main MCP server switch statement that routes calls to the codeGenerate function.
    case 'code_generate': result = await codeGenerate(args as any); break;
  • Tool schema definition included in the optimizedToolDefinitions array served by listTools endpoint. This is the schema exposed to MCP clients.
    { name: 'code_generate', description: `Generate context-aware Hedera SDK code from natural language. CREATES: Complete, runnable code with imports, error handling, best practices LANGUAGES: JavaScript, TypeScript, Java, Python, Go, Solidity STYLES: minimal (core logic), complete (with setup), production (full best practices) USE FOR: Creating new implementations, generating boilerplate, scaffolding projects.`, inputSchema: { type: 'object' as const, properties: { description: { type: 'string', description: 'What code to generate' }, language: { type: 'string', enum: ['javascript', 'typescript', 'java', 'python', 'go', 'solidity'], description: 'Target language (default: javascript)', }, style: { type: 'string', enum: ['minimal', 'complete', 'production'], description: 'Code style (default: complete)', }, includeImports: { type: 'boolean', description: 'Include imports (default: true)' }, includeErrorHandling: { type: 'boolean', description: 'Include try-catch (default: true)' }, }, required: ['description'], }, },
  • src/index.ts:51-51 (registration)
    Import statement bringing the codeGenerate handler function into the main MCP server module.
    import { docsSearch, docsAsk, docsGetExample, codeGenerate } from './tools/rag.js';

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/justmert/hashpilot'

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