Skip to main content
Glama
aliargun

Gemini MCP Server

by aliargun

count_tokens

Calculate token counts for text using Gemini models to manage API usage and optimize input length.

Instructions

Count tokens for a given text with a specific model

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYesText to count tokens for
modelNoModel to use for token countinggemini-2.5-flash

Implementation Reference

  • The handler function that executes the count_tokens tool. It takes text and optional model, calls the Gemini API's countTokens method, and returns the token count in MCP response format.
    private async countTokens(id: any, args: any): Promise<MCPResponse> {
      try {
        const model = args.model || 'gemini-2.5-flash';
        
        const result = await this.genAI.models.countTokens({
          model,
          contents: [{
            parts: [{
              text: args.text
            }],
            role: 'user'
          }]
        });
    
        return {
          jsonrpc: '2.0',
          id,
          result: {
            content: [{
              type: 'text',
              text: `Token count: ${result.totalTokens}`
            }],
            metadata: {
              tokenCount: result.totalTokens,
              model
            }
          }
        };
      } catch (error) {
        return {
          jsonrpc: '2.0',
          id,
          error: {
            code: -32603,
            message: error instanceof Error ? error.message : 'Internal error'
          }
        };
      }
    }
  • Input schema definition for the count_tokens tool, specifying required 'text' parameter and optional 'model'.
    inputSchema: {
      type: 'object',
      properties: {
        text: {
          type: 'string',
          description: 'Text to count tokens for'
        },
        model: {
          type: 'string',
          description: 'Model to use for token counting',
          enum: Object.keys(GEMINI_MODELS),
          default: 'gemini-2.5-flash'
        }
      },
      required: ['text']
    }
  • Tool registration in the available tools list, including name, description, and input schema.
    {
      name: 'count_tokens',
      description: 'Count tokens for a given text with a specific model',
      inputSchema: {
        type: 'object',
        properties: {
          text: {
            type: 'string',
            description: 'Text to count tokens for'
          },
          model: {
            type: 'string',
            description: 'Model to use for token counting',
            enum: Object.keys(GEMINI_MODELS),
            default: 'gemini-2.5-flash'
          }
        },
        required: ['text']
      }
    },
  • Dispatch case in handleToolCall method that routes count_tokens calls to the handler function.
    case 'count_tokens':
      return await this.countTokens(request.id, args);
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states what the tool does ('count tokens') but doesn't describe behavioral traits such as whether it's a read-only operation, if it has rate limits, what the output format looks like (e.g., integer count or structured response), or any error conditions (e.g., handling of empty text). For a tool with no annotations, this is a significant gap in transparency.

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 appropriately sized and front-loaded in a single, efficient sentence. It conveys the core functionality without unnecessary words, making it easy for an agent to parse quickly. Every part of the sentence ('count tokens', 'for a given text', 'with a specific model') contributes essential information, earning its place.

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

Completeness2/5

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

Given the complexity (a computational tool with model dependencies) and lack of annotations and output schema, the description is incomplete. It doesn't explain the output (e.g., token count as an integer), error handling, or practical use cases. While the schema covers parameters well, the description fails to provide sufficient context for an agent to understand the tool's behavior and results fully, especially without structured output information.

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?

The description adds minimal meaning beyond the input schema. It mentions 'text' and 'model' as parameters, but the schema already provides 100% coverage with clear descriptions and an enum for 'model'. The description doesn't explain why token counting might vary by model or provide additional context (e.g., token definitions, implications for different models). With high schema coverage, the baseline is 3, and the description doesn't significantly enhance parameter understanding.

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

Purpose4/5

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

The description clearly states the tool's purpose with a specific verb ('count') and resource ('tokens'), and specifies the input ('text') and method ('with a specific model'). It distinguishes from siblings like 'embed_text' or 'generate_text' by focusing on token counting rather than text generation or embedding. However, it doesn't explicitly differentiate from all siblings (e.g., 'analyze_image' is clearly different, but the distinction could be more explicit).

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention scenarios where token counting is needed (e.g., for cost estimation, input validation), nor does it reference sibling tools like 'embed_text' or 'generate_text' as alternatives for different tasks. The lack of context leaves the agent to infer usage based on the tool name alone.

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/aliargun/mcp-server-gemini'

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