Skip to main content
Glama

generate-auth-code

Generate authentication codes for integrating email, calendar, and contacts functionality into applications using the Nylas API MCP Server. Supports multiple programming languages and configurable scopes for secure API access.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
clientIdNo
clientSecretNo
languageYes
redirectUriNo
scopesNo

Implementation Reference

  • The inline anonymous async function that implements the core logic of the 'generate-auth-code' tool. It normalizes the language input, prepares placeholder values for client credentials and scopes, selects from hardcoded template strings for each language (Node.js, Python, Java, Ruby, curl), interpolates the placeholders into the template, and returns a structured content response with the generated code.
    async ({ language, clientId, clientSecret, redirectUri, scopes }) => { const normalizedLanguage = normalizeLanguage(language); const placeholderClientId = clientId || "YOUR_CLIENT_ID"; const placeholderClientSecret = clientSecret || "YOUR_CLIENT_SECRET"; const placeholderRedirectUri = redirectUri || "YOUR_REDIRECT_URI"; const placeholderScopes = scopes || ["email", "calendar", "contacts"]; // Map of languages to their authentication code templates const templates: Record<string, string> = { "Node": ` // Authentication with Nylas API using Node.js import { Nylas } from '@nylas/nylas-js'; // Initialize Nylas client Nylas.config({ clientId: "${placeholderClientId}", clientSecret: "${placeholderClientSecret}", }); // Generate OAuth URL to redirect the user to const authUrl = Nylas.urlForAuthentication({ redirectURI: "${placeholderRedirectUri}", scopes: ${JSON.stringify(placeholderScopes)}, }); console.log("Redirect the user to:", authUrl); // After the user is redirected back to your redirect URI: // Exchange the authorization code for an access token async function exchangeCodeForToken(code) { try { const tokenData = await Nylas.exchangeCodeForToken(code); console.log("Access token:", tokenData.accessToken); console.log("Grant ID:", tokenData.grantId); // Now you can use this token to make API calls return tokenData; } catch (error) { console.error("Error exchanging code for token:", error); } } // Call this function with the code from the URL parameter // exchangeCodeForToken(codeFromUrl); `, "Python": ` # Authentication with Nylas API using Python from nylas import Client import os # Initialize Nylas client nylas = Client( client_id="${placeholderClientId}", client_secret="${placeholderClientSecret}" ) # Generate OAuth URL to redirect the user to auth_url = nylas.authentication_url( redirect_uri="${placeholderRedirectUri}", scopes=${placeholderScopes} ) print("Redirect the user to:", auth_url) # After the user is redirected back to your redirect URI: # Exchange the authorization code for an access token def exchange_code_for_token(code): try: token_data = nylas.exchange_code_for_token(code) print("Access token:", token_data['access_token']) print("Grant ID:", token_data['grant_id']) # Now you can use this token to make API calls return token_data except Exception as e: print("Error exchanging code for token:", e) # Call this function with the code from the URL parameter # exchange_code_for_token(code_from_url) `, "Java": ` // Authentication with Nylas API using Java import com.nylas.NylasClient; import com.nylas.models.*; public class NylasAuth { public static void main(String[] args) { // Initialize Nylas client NylasClient nylas = new NylasClient.Builder("${placeholderClientId}") .clientSecret("${placeholderClientSecret}") .build(); // Generate OAuth URL to redirect the user to String authUrl = nylas.auth().urlForAuthentication( "${placeholderRedirectUri}", ${placeholderScopes.map(scope => '"' + scope + '"').join(", ")} ); System.out.println("Redirect the user to: " + authUrl); // After the user is redirected back to your redirect URI: // Exchange the authorization code for an access token String code = "CODE_FROM_URL_PARAMETER"; try { TokenResponse tokenData = nylas.auth().exchangeCodeForToken(code); System.out.println("Access token: " + tokenData.getAccessToken()); System.out.println("Grant ID: " + tokenData.getGrantId()); // Now you can use this token to make API calls } catch (Exception e) { System.err.println("Error exchanging code for token: " + e.getMessage()); } } } `, "Ruby": ` # Authentication with Nylas API using Ruby require 'nylas' # Initialize Nylas client nylas = Nylas::Client.new( client_id: "${placeholderClientId}", client_secret: "${placeholderClientSecret}" ) # Generate OAuth URL to redirect the user to auth_url = nylas.auth.authorize_url( redirect_uri: "${placeholderRedirectUri}", scopes: ${JSON.stringify(placeholderScopes)} ) puts "Redirect the user to: #{auth_url}" # After the user is redirected back to your redirect URI: # Exchange the authorization code for an access token def exchange_code_for_token(code) begin token_data = nylas.auth.exchange_code_for_token(code) puts "Access token: #{token_data.access_token}" puts "Grant ID: #{token_data.grant_id}" # Now you can use this token to make API calls return token_data rescue => e puts "Error exchanging code for token: #{e.message}" end end # Call this function with the code from the URL parameter # exchange_code_for_token(code_from_url) `, "curl": ` # Authentication with Nylas API using curl # Step 1: Generate an authorization URL (typically done in your backend) # Users will be redirected to this URL to authorize your application # Step 2: After authorization, the user is redirected to your redirect URI with a code # For example: ${placeholderRedirectUri}?code=AUTHORIZATION_CODE # Step 3: Exchange the authorization code for an access token curl --request POST \\ --url "https://api.us.nylas.com/v3/connect/oauth/token" \\ --header "Content-Type: application/json" \\ --data '{ "client_id": "${placeholderClientId}", "client_secret": "${placeholderClientSecret}", "grant_type": "authorization_code", "code": "AUTHORIZATION_CODE_FROM_REDIRECT", "redirect_uri": "${placeholderRedirectUri}" }' # Response will contain access_token, refresh_token, grant_id, etc. # Step 4: Use the access token to make API calls curl --request GET \\ --url "https://api.us.nylas.com/v3/grants/GRANT_ID/messages?limit=10" \\ --header "Content-Type: application/json" \\ --header "Authorization: Bearer ACCESS_TOKEN" ` }; // 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 'generate-auth-code' tool: required language (one of node, python, java, ruby, curl) and optional OAuth-related fields.
    { language: z.enum(["node", "python", "java", "ruby", "curl"]), clientId: z.string().optional(), clientSecret: z.string().optional(), redirectUri: z.string().optional(), scopes: z.array(z.string()).optional() },
  • The MCP server.tool() call that registers the 'generate-auth-code' tool, providing the name, input schema, and handler function.
    server.tool( "generate-auth-code", { language: z.enum(["node", "python", "java", "ruby", "curl"]), clientId: z.string().optional(), clientSecret: z.string().optional(), redirectUri: z.string().optional(), scopes: z.array(z.string()).optional() }, async ({ language, clientId, clientSecret, redirectUri, scopes }) => { const normalizedLanguage = normalizeLanguage(language); const placeholderClientId = clientId || "YOUR_CLIENT_ID"; const placeholderClientSecret = clientSecret || "YOUR_CLIENT_SECRET"; const placeholderRedirectUri = redirectUri || "YOUR_REDIRECT_URI"; const placeholderScopes = scopes || ["email", "calendar", "contacts"]; // Map of languages to their authentication code templates const templates: Record<string, string> = { "Node": ` // Authentication with Nylas API using Node.js import { Nylas } from '@nylas/nylas-js'; // Initialize Nylas client Nylas.config({ clientId: "${placeholderClientId}", clientSecret: "${placeholderClientSecret}", }); // Generate OAuth URL to redirect the user to const authUrl = Nylas.urlForAuthentication({ redirectURI: "${placeholderRedirectUri}", scopes: ${JSON.stringify(placeholderScopes)}, }); console.log("Redirect the user to:", authUrl); // After the user is redirected back to your redirect URI: // Exchange the authorization code for an access token async function exchangeCodeForToken(code) { try { const tokenData = await Nylas.exchangeCodeForToken(code); console.log("Access token:", tokenData.accessToken); console.log("Grant ID:", tokenData.grantId); // Now you can use this token to make API calls return tokenData; } catch (error) { console.error("Error exchanging code for token:", error); } } // Call this function with the code from the URL parameter // exchangeCodeForToken(codeFromUrl); `, "Python": ` # Authentication with Nylas API using Python from nylas import Client import os # Initialize Nylas client nylas = Client( client_id="${placeholderClientId}", client_secret="${placeholderClientSecret}" ) # Generate OAuth URL to redirect the user to auth_url = nylas.authentication_url( redirect_uri="${placeholderRedirectUri}", scopes=${placeholderScopes} ) print("Redirect the user to:", auth_url) # After the user is redirected back to your redirect URI: # Exchange the authorization code for an access token def exchange_code_for_token(code): try: token_data = nylas.exchange_code_for_token(code) print("Access token:", token_data['access_token']) print("Grant ID:", token_data['grant_id']) # Now you can use this token to make API calls return token_data except Exception as e: print("Error exchanging code for token:", e) # Call this function with the code from the URL parameter # exchange_code_for_token(code_from_url) `, "Java": ` // Authentication with Nylas API using Java import com.nylas.NylasClient; import com.nylas.models.*; public class NylasAuth { public static void main(String[] args) { // Initialize Nylas client NylasClient nylas = new NylasClient.Builder("${placeholderClientId}") .clientSecret("${placeholderClientSecret}") .build(); // Generate OAuth URL to redirect the user to String authUrl = nylas.auth().urlForAuthentication( "${placeholderRedirectUri}", ${placeholderScopes.map(scope => '"' + scope + '"').join(", ")} ); System.out.println("Redirect the user to: " + authUrl); // After the user is redirected back to your redirect URI: // Exchange the authorization code for an access token String code = "CODE_FROM_URL_PARAMETER"; try { TokenResponse tokenData = nylas.auth().exchangeCodeForToken(code); System.out.println("Access token: " + tokenData.getAccessToken()); System.out.println("Grant ID: " + tokenData.getGrantId()); // Now you can use this token to make API calls } catch (Exception e) { System.err.println("Error exchanging code for token: " + e.getMessage()); } } } `, "Ruby": ` # Authentication with Nylas API using Ruby require 'nylas' # Initialize Nylas client nylas = Nylas::Client.new( client_id: "${placeholderClientId}", client_secret: "${placeholderClientSecret}" ) # Generate OAuth URL to redirect the user to auth_url = nylas.auth.authorize_url( redirect_uri: "${placeholderRedirectUri}", scopes: ${JSON.stringify(placeholderScopes)} ) puts "Redirect the user to: #{auth_url}" # After the user is redirected back to your redirect URI: # Exchange the authorization code for an access token def exchange_code_for_token(code) begin token_data = nylas.auth.exchange_code_for_token(code) puts "Access token: #{token_data.access_token}" puts "Grant ID: #{token_data.grant_id}" # Now you can use this token to make API calls return token_data rescue => e puts "Error exchanging code for token: #{e.message}" end end # Call this function with the code from the URL parameter # exchange_code_for_token(code_from_url) `, "curl": ` # Authentication with Nylas API using curl # Step 1: Generate an authorization URL (typically done in your backend) # Users will be redirected to this URL to authorize your application # Step 2: After authorization, the user is redirected to your redirect URI with a code # For example: ${placeholderRedirectUri}?code=AUTHORIZATION_CODE # Step 3: Exchange the authorization code for an access token curl --request POST \\ --url "https://api.us.nylas.com/v3/connect/oauth/token" \\ --header "Content-Type: application/json" \\ --data '{ "client_id": "${placeholderClientId}", "client_secret": "${placeholderClientSecret}", "grant_type": "authorization_code", "code": "AUTHORIZATION_CODE_FROM_REDIRECT", "redirect_uri": "${placeholderRedirectUri}" }' # Response will contain access_token, refresh_token, grant_id, etc. # Step 4: Use the access token to make API calls curl --request GET \\ --url "https://api.us.nylas.com/v3/grants/GRANT_ID/messages?limit=10" \\ --header "Content-Type: application/json" \\ --header "Authorization: Bearer ACCESS_TOKEN" ` }; // 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 } ] }; } );
  • Utility function to normalize input language strings to match template keys (e.g., 'node' -> 'Node'), used in the generate-auth-code handler.
    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; }

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