Skip to main content
Glama

generate-endpoint-code

Generate code snippets in Node, Python, Java, Ruby, or cURL for Nylas API endpoints. Simplify integration of email, calendar, and contacts functionality into AI applications by specifying the endpoint and HTTP method.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
endpointYes
languageYes
methodNo
paramsNo

Implementation Reference

  • Main handler function for 'generate-endpoint-code' tool. Normalizes language, formats the endpoint, replaces path parameters, defines language-specific code templates that invoke helper functions to generate SDK code, and returns the generated code as text content.
    async ({ language, endpoint, method = "GET", params = {} }) => { const normalizedLanguage = normalizeLanguage(language); const endpointPath = endpoint.startsWith("/") ? endpoint : `/${endpoint}`; // Construct the endpoint with path parameters let formattedEndpoint = endpointPath; // Replace path parameters with values from params Object.keys(params).forEach(key => { if (formattedEndpoint.includes(`{${key}}`)) { formattedEndpoint = formattedEndpoint.replace(`{${key}}`, params[key]); delete params[key]; // Remove used path parameters } }); // Map of languages to their API code templates const templates: Record<string, string> = { "Node": ` // ${method} ${endpointPath} using Nylas Node.js SDK import 'dotenv/config'; import Nylas from '@nylas/nylas-js'; // Initialize the Nylas client const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY }); async function callNylasApi() { try { ${generateNodeCode(method, formattedEndpoint, params)} console.log(response); return response; } catch (error) { console.error('Error calling Nylas API:', error); } } callNylasApi(); `, "Python": ` # ${method} ${endpointPath} using Nylas Python SDK from dotenv import load_dotenv load_dotenv() import os from nylas import Client # Initialize the Nylas client nylas = Client( api_key=os.environ.get('NYLAS_API_KEY') ) ${generatePythonCode(method, formattedEndpoint, params)} print(response) `, "Java": ` // ${method} ${endpointPath} using Nylas Java SDK import com.nylas.NylasClient; import com.nylas.models.*; public class NylasApiExample { public static void main(String[] args) { try { // Initialize the Nylas client NylasClient nylas = new NylasClient.Builder(System.getenv("NYLAS_API_KEY")).build(); ${generateJavaCode(method, formattedEndpoint, params)} System.out.println(response); } catch (Exception e) { System.err.println("Error calling Nylas API: " + e.getMessage()); } } } `, "Ruby": ` # ${method} ${endpointPath} using Nylas Ruby SDK require 'nylas' require 'dotenv/load' # Initialize the Nylas client nylas = Nylas::Client.new( api_key: ENV['NYLAS_API_KEY'] ) ${generateRubyCode(method, formattedEndpoint, params)} puts response `, "curl": ` # ${method} ${endpointPath} using curl ${generateCurlCode(method, formattedEndpoint, params)} ` }; // Get the template for the requested language, or provide an error message const template = templates[normalizedLanguage] || `Code generation is not available for ${language}. Available languages are: Node.js, Python, Java, Ruby, and curl.`; return { content: [ { type: "text", text: template } ] }; }
  • Zod schema defining the input parameters for the tool: language (required, enum), endpoint (required string), method (optional enum), params (optional record).
    { language: z.enum(["node", "python", "java", "ruby", "curl"]), endpoint: z.string(), method: z.enum(["GET", "POST", "PUT", "DELETE"]).optional(), params: z.record(z.any()).optional() },
  • MCP server tool registration for 'generate-endpoint-code' including schema and inline handler function.
    server.tool( "generate-endpoint-code", { language: z.enum(["node", "python", "java", "ruby", "curl"]), endpoint: z.string(), method: z.enum(["GET", "POST", "PUT", "DELETE"]).optional(), params: z.record(z.any()).optional() }, async ({ language, endpoint, method = "GET", params = {} }) => { const normalizedLanguage = normalizeLanguage(language); const endpointPath = endpoint.startsWith("/") ? endpoint : `/${endpoint}`; // Construct the endpoint with path parameters let formattedEndpoint = endpointPath; // Replace path parameters with values from params Object.keys(params).forEach(key => { if (formattedEndpoint.includes(`{${key}}`)) { formattedEndpoint = formattedEndpoint.replace(`{${key}}`, params[key]); delete params[key]; // Remove used path parameters } }); // Map of languages to their API code templates const templates: Record<string, string> = { "Node": ` // ${method} ${endpointPath} using Nylas Node.js SDK import 'dotenv/config'; import Nylas from '@nylas/nylas-js'; // Initialize the Nylas client const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY }); async function callNylasApi() { try { ${generateNodeCode(method, formattedEndpoint, params)} console.log(response); return response; } catch (error) { console.error('Error calling Nylas API:', error); } } callNylasApi(); `, "Python": ` # ${method} ${endpointPath} using Nylas Python SDK from dotenv import load_dotenv load_dotenv() import os from nylas import Client # Initialize the Nylas client nylas = Client( api_key=os.environ.get('NYLAS_API_KEY') ) ${generatePythonCode(method, formattedEndpoint, params)} print(response) `, "Java": ` // ${method} ${endpointPath} using Nylas Java SDK import com.nylas.NylasClient; import com.nylas.models.*; public class NylasApiExample { public static void main(String[] args) { try { // Initialize the Nylas client NylasClient nylas = new NylasClient.Builder(System.getenv("NYLAS_API_KEY")).build(); ${generateJavaCode(method, formattedEndpoint, params)} System.out.println(response); } catch (Exception e) { System.err.println("Error calling Nylas API: " + e.getMessage()); } } } `, "Ruby": ` # ${method} ${endpointPath} using Nylas Ruby SDK require 'nylas' require 'dotenv/load' # Initialize the Nylas client nylas = Nylas::Client.new( api_key: ENV['NYLAS_API_KEY'] ) ${generateRubyCode(method, formattedEndpoint, params)} puts response `, "curl": ` # ${method} ${endpointPath} using curl ${generateCurlCode(method, formattedEndpoint, params)} ` }; // Get the template for the requested language, or provide an error message const template = templates[normalizedLanguage] || `Code generation is not available for ${language}. Available languages are: Node.js, Python, Java, Ruby, and curl.`; return { content: [ { type: "text", text: template } ] }; } );
  • Helper function to normalize input language strings to match the template keys used in the handler (e.g., 'node' -> 'Node').
    function normalizeLanguage(language: string): string { const langMap: Record<string, string> = { 'node': 'Node', 'nodejs': 'Node', 'javascript': 'Node', 'js': 'Node', 'python': 'Python', 'py': 'Python', 'java': 'Java', 'ruby': 'Ruby', 'rb': 'Ruby', 'curl': 'curl', 'api': 'curl', 'rest': 'curl' }; return langMap[language.toLowerCase()] || language; }
  • Helper function that generates Node.js specific code snippet for calling the Nylas API endpoint using the SDK, handling different methods (GET, POST, etc.) and parsing the endpoint path.
    function generateNodeCode(method: string, endpoint: string, params: Record<string, any>): string { const parts = endpoint.split('/'); let resourceType = ''; let functionName = ''; let grantId = 'process.env.NYLAS_GRANT_ID'; let resourceId = ''; // Try to determine the resource type and function name if (parts.length >= 3) { if (parts[1] === 'v3' && parts[2] === 'grants') { if (parts.length >= 5) { resourceType = parts[4]; // like 'messages', 'events', etc. if (parts.length >= 6) { resourceId = parts[5]; if (parts.length >= 7 && parts[6] === 'send') { functionName = 'send'; } } } } } // Handle different HTTP methods switch (method) { case 'GET': if (resourceId) { // Get a specific resource return `const response = await nylas.${resourceType}.find({ identifier: ${grantId}, ${resourceType.slice(0, -1)}Id: "${resourceId}", ${Object.entries(params).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(',\n ')} });`; } else { // List resources return `const response = await nylas.${resourceType}.list({ identifier: ${grantId}, ${Object.keys(params).length > 0 ? `queryParams: { ${Object.entries(params).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(',\n ')} }` : ''} });`; } case 'POST': if (functionName === 'send') { // Send a draft return `const response = await nylas.${resourceType}.send({ identifier: ${grantId}, ${resourceType.slice(0, -1)}Id: "${resourceId}" });`; } else { // Create a resource return `const response = await nylas.${resourceType}.create({ identifier: ${grantId}, ${Object.entries(params).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(',\n ')} });`; } case 'PUT': // Update a resource return `const response = await nylas.${resourceType}.update({ identifier: ${grantId}, ${resourceType.slice(0, -1)}Id: "${resourceId}", ${Object.entries(params).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(',\n ')} });`; case 'DELETE': // Delete a resource return `const response = await nylas.${resourceType}.destroy({ identifier: ${grantId}, ${resourceType.slice(0, -1)}Id: "${resourceId}" });`; default: return `// No code generation available for this endpoint const response = "Please refer to the Nylas API documentation for this endpoint.";`; } }

Other Tools

Related 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/nylas-samples/nylas-api-mcp'

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