Skip to main content
Glama
nylas-samples

Nylas API MCP Server

Official

generate-endpoint-code

Generate code for Nylas API endpoints in Node.js, Python, Java, Ruby, or cURL to integrate email, calendar, and contacts functionality into AI applications.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
languageYes
endpointYes
methodNo
paramsNo

Implementation Reference

  • Registration of the 'generate-endpoint-code' tool. Includes inline input schema and the main handler function that normalizes language, formats endpoint/params, selects template, fills with helper-generated code, and returns markdown code block.
      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
              }
            ]
          };
        }
      );
  • Zod input schema defining parameters for the tool: language (programming lang), endpoint (API path), optional method and params.
    {
      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()
    },
  • Handler function: processes inputs, normalizes language, formats endpoint by substituting path params, generates language-specific code templates using helper functions, returns 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
              }
            ]
          };
        }
  • Helper: normalizes input language string to template keys (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: Generates Node.js SDK code snippet for calling the specified Nylas API endpoint/method with params.
    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.";`;
      }
    }

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