Skip to main content
Glama
harshitdynamite

DhanHQ MCP Server

complete_authentication

Exchange the tokenId from browser login redirect for an access token to finalize authentication with DhanHQ trading APIs.

Instructions

Completes the authentication flow (Step 3). Takes the tokenId from the redirect URL after browser login and exchanges it for an access token.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tokenIdYesThe tokenId received in the redirect URL after browser login (Step 2).

Implementation Reference

  • MCP CallTool handler case for 'complete_authentication': validates input, calls consumeConsent helper, and returns formatted success response with auth token.
    case 'complete_authentication': {
      console.error('[Tool] Executing: complete_authentication');
      const { tokenId } = args as Record<string, unknown>;
    
      if (!tokenId) {
        throw new Error('tokenId is required');
      }
    
      const authToken = await consumeConsent(tokenId as string);
      return {
        content: [
          {
            type: 'text' as const,
            text: JSON.stringify(
              {
                success: true,
                message: 'Authentication completed successfully',
                authToken,
              },
              null,
              2
            ),
          },
        ],
      };
    }
  • Tool schema definition including name, description, and inputSchema requiring 'tokenId' string.
    {
      name: 'complete_authentication',
      description:
        'Completes the authentication flow (Step 3). Takes the tokenId from the redirect URL after browser login and exchanges it for an access token.',
      inputSchema: {
        type: 'object' as const,
        properties: {
          tokenId: {
            type: 'string' as const,
            description:
              'The tokenId received in the redirect URL after browser login (Step 2).',
          },
        },
        required: ['tokenId'],
      },
    },
  • Core helper function implementing the API call to Dhan auth endpoint to exchange tokenId for access token, store auth state, and return DhanAuthToken.
    export async function consumeConsent(
      tokenId: string
    ): Promise<DhanAuthToken> {
      try {
        log('Consuming consent with tokenId...');
    
        const response = await axios.get<AuthStep3Response>(
          `${AUTH_BASE_URL}/app/consumeApp-consent?tokenId=${tokenId}`,
          {
            headers: {
              app_id: dhanConfig.apiKey,
              app_secret: dhanConfig.apiSecret,
            },
          }
        );
    
        const authToken: DhanAuthToken = {
          accessToken: response.data.accessToken,
          dhanClientId: response.data.dhanClientId,
          dhanClientName: response.data.dhanClientName,
          dhanClientUcc: response.data.dhanClientUcc,
          expiryTime: response.data.expiryTime,
          givenPowerOfAttorney: response.data.givenPowerOfAttorney,
          generatedAt: new Date().toISOString(),
        };
    
        authState.authToken = authToken;
        authState.tokenId = tokenId;
    
        log('✓ Access token generated successfully');
        log(`Client Name: ${authToken.dhanClientName}`);
        log(`Client ID: ${authToken.dhanClientId}`);
        log(`Token Expiry: ${authToken.expiryTime}`);
    
        return authToken;
      } catch (error) {
        const errorMessage =
          error instanceof axios.AxiosError
            ? `API Error: ${error.response?.status} - ${error.response?.data}`
            : error instanceof Error
              ? error.message
              : 'Unknown error';
    
        log(`✗ Failed: ${errorMessage}`);
        throw new Error(`Step 3 Failed: ${errorMessage}`);
      }
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses the tool's purpose (completing authentication) and input requirement (tokenId exchange), but lacks details on behavioral traits like error handling, rate limits, security implications, or what happens on success/failure. It adequately describes the core operation but misses advanced context.

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

Conciseness5/5

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

The description is perfectly concise with two sentences: the first states the purpose and step context, the second explains the parameter and outcome. Every word earns its place, and it's front-loaded with the essential action. No wasted verbiage.

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

Completeness4/5

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

For a single-parameter tool with 100% schema coverage but no annotations or output schema, the description is reasonably complete. It explains the tool's role in the authentication flow, when to use it, and the parameter's purpose. However, it could better address behavioral aspects like error cases or token lifecycle, given the security-sensitive context.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already fully documents the single parameter 'tokenId'. The description adds minimal value by reiterating the parameter's source ('from the redirect URL after browser login') but doesn't provide additional syntax, format, or validation details beyond what the schema states. Baseline 3 is appropriate.

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

Purpose5/5

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

The description clearly states the specific action ('Completes the authentication flow') and resource ('exchanges it for an access token'), with explicit reference to 'Step 3' distinguishing it from sibling tools like 'start_authentication' and 'reset_authentication'. It precisely defines the tool's role in a multi-step process.

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

Usage Guidelines5/5

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

The description explicitly states when to use this tool ('Step 3', 'after browser login') and references prerequisites ('tokenId from the redirect URL after browser login'), clearly differentiating it from alternatives like 'start_authentication' (Step 1) and 'check_auth_status'. It provides complete contextual guidance.

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

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/harshitdynamite/DhanMCP'

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