Skip to main content
Glama

oauth2_auth

Authenticate and authorize OAuth2 flows for secure API access, supporting client credentials, password, authorization code, and refresh token grant types within CyberMCP.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
authorization_urlNoOAuth2 authorization endpoint URL (for authorization code flow)
client_idYesOAuth2 client ID
client_secretNoOAuth2 client secret
grant_typeNoOAuth2 grant typeclient_credentials
passwordNoPassword (for password grant type)
redirect_uriNoRedirect URI (for authorization code flow)
scopeNoOAuth2 scope
token_urlYesOAuth2 token endpoint URL
usernameNoUsername (for password grant type)

Implementation Reference

  • The handler function for the 'oauth2_auth' tool. Validates input parameters based on grant type, constructs OAuth2Config, calls AuthManager.authenticateWithOAuth2, and returns success or error message.
    async ({ client_id, client_secret, token_url, authorization_url, grant_type, username, password, scope, redirect_uri }) => {
      try {
        const authManager = AuthManager.getInstance();
        
        // Validate required parameters for specific grant types
        if (grant_type === 'password' && (!username || !password)) {
          throw new Error("Username and password are required for password grant type");
        }
        
        if (grant_type === 'authorization_code' && !redirect_uri) {
          throw new Error("Redirect URI is required for authorization code grant type");
        }
        
        // Configure OAuth2
        const config: OAuth2Config = {
          clientId: client_id,
          clientSecret: client_secret,
          tokenUrl: token_url,
          authorizationUrl: authorization_url || "",
          grantType: grant_type as any,
          username,
          password,
          scope,
          redirectUri: redirect_uri
        };
        
        const authState = await authManager.authenticateWithOAuth2(config);
        
        return {
          content: [
            {
              type: "text",
              text: `Successfully authenticated with OAuth2\nGrant type: ${grant_type}\nToken type: ${authState.token ? 'Bearer' : 'Unknown'}\n${authState.tokenExpiry ? `Token expires: ${authState.tokenExpiry.toISOString()}` : ''}`,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error authenticating with OAuth2: ${(error as Error).message}`,
            },
          ],
        };
      }
    }
  • Zod input schema for the 'oauth2_auth' tool defining all required and optional parameters for different OAuth2 grant types.
    {
      client_id: z.string().describe("OAuth2 client ID"),
      client_secret: z.string().optional().describe("OAuth2 client secret"),
      token_url: z.string().url().describe("OAuth2 token endpoint URL"),
      authorization_url: z.string().url().optional().describe("OAuth2 authorization endpoint URL (for authorization code flow)"),
      grant_type: z.enum(['client_credentials', 'password', 'authorization_code', 'refresh_token']).default('client_credentials').describe("OAuth2 grant type"),
      username: z.string().optional().describe("Username (for password grant type)"),
      password: z.string().optional().describe("Password (for password grant type)"),
      scope: z.string().optional().describe("OAuth2 scope"),
      redirect_uri: z.string().optional().describe("Redirect URI (for authorization code flow)"),
    },
  • Registration of the 'oauth2_auth' tool using server.tool(), including schema and handler within the registerAuthenticationTools function.
    server.tool(
      "oauth2_auth",
      {
        client_id: z.string().describe("OAuth2 client ID"),
        client_secret: z.string().optional().describe("OAuth2 client secret"),
        token_url: z.string().url().describe("OAuth2 token endpoint URL"),
        authorization_url: z.string().url().optional().describe("OAuth2 authorization endpoint URL (for authorization code flow)"),
        grant_type: z.enum(['client_credentials', 'password', 'authorization_code', 'refresh_token']).default('client_credentials').describe("OAuth2 grant type"),
        username: z.string().optional().describe("Username (for password grant type)"),
        password: z.string().optional().describe("Password (for password grant type)"),
        scope: z.string().optional().describe("OAuth2 scope"),
        redirect_uri: z.string().optional().describe("Redirect URI (for authorization code flow)"),
      },
      async ({ client_id, client_secret, token_url, authorization_url, grant_type, username, password, scope, redirect_uri }) => {
        try {
          const authManager = AuthManager.getInstance();
          
          // Validate required parameters for specific grant types
          if (grant_type === 'password' && (!username || !password)) {
            throw new Error("Username and password are required for password grant type");
          }
          
          if (grant_type === 'authorization_code' && !redirect_uri) {
            throw new Error("Redirect URI is required for authorization code grant type");
          }
          
          // Configure OAuth2
          const config: OAuth2Config = {
            clientId: client_id,
            clientSecret: client_secret,
            tokenUrl: token_url,
            authorizationUrl: authorization_url || "",
            grantType: grant_type as any,
            username,
            password,
            scope,
            redirectUri: redirect_uri
          };
          
          const authState = await authManager.authenticateWithOAuth2(config);
          
          return {
            content: [
              {
                type: "text",
                text: `Successfully authenticated with OAuth2\nGrant type: ${grant_type}\nToken type: ${authState.token ? 'Bearer' : 'Unknown'}\n${authState.tokenExpiry ? `Token expires: ${authState.tokenExpiry.toISOString()}` : ''}`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error authenticating with OAuth2: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
    );
  • Supporting utility in AuthManager class that performs the actual OAuth2 token request via axios.post to the tokenUrl, handles different grant types, parses response, calculates expiry, and updates the authentication state.
    public async authenticateWithOAuth2(config: OAuth2Config): Promise<AuthState> {
      const { 
        clientId, 
        clientSecret, 
        tokenUrl, 
        grantType = 'client_credentials',
        username,
        password,
        scope,
        redirectUri
      } = config;
      
      try {
        let data: Record<string, string> = {
          client_id: clientId,
          grant_type: grantType
        };
        
        // Add optional parameters based on grant type
        if (clientSecret) {
          data.client_secret = clientSecret;
        }
        
        if (scope) {
          data.scope = scope;
        }
        
        if (redirectUri) {
          data.redirect_uri = redirectUri;
        }
        
        // Add credentials for password grant
        if (grantType === 'password' && username && password) {
          data.username = username;
          data.password = password;
        }
        
        // Execute the token request
        const response = await axios.post(tokenUrl, new URLSearchParams(data), {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
        
        const { 
          access_token, 
          refresh_token, 
          expires_in, 
          token_type = 'Bearer'
        } = response.data;
        
        // Calculate token expiry
        let tokenExpiry: Date | undefined;
        if (expires_in) {
          tokenExpiry = new Date();
          tokenExpiry.setSeconds(tokenExpiry.getSeconds() + expires_in);
        }
        
        // Update auth state
        this.authState = {
          type: 'oauth2',
          token: access_token,
          refreshToken: refresh_token,
          tokenExpiry,
          oauthTokens: response.data,
          headers: {
            'Authorization': `${token_type} ${access_token}`
          }
        };
        
        return this.getAuthState();
      } catch (error) {
        throw new Error(`OAuth2 authentication failed: ${(error as Error).message}`);
      }
    }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

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/ricauts/CyberMCP'

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