Skip to main content
Glama
gurveeer

MCP Server Gemini

by gurveeer

count_tokens

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

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 primary handler method for the 'count_tokens' tool. It extracts parameters, calls the underlying Gemini SDK's countTokens method, formats the token count result into an MCP response, and handles errors.
    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'
          }
        };
      }
    }
  • Registers the 'count_tokens' tool in the list of available tools, defining its name, description, and input schema for MCP protocol.
      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']
      }
    },
  • Zod schema definition for validating input parameters of the 'count_tokens' tool (text required, model optional).
    countTokens: z.object({
      text: z.string().min(1, 'Text is required'),
      model: CommonSchemas.geminiModel.optional()
    }),
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 the tool counts tokens but doesn't describe what a 'token' means in this context, whether there are rate limits, error handling, or output format. For a tool with no annotation coverage, 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 a single, efficient sentence with zero waste. It's front-loaded with the core purpose and appropriately sized for the tool's complexity, making it easy for an agent to parse quickly.

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 tool's moderate complexity (2 parameters, no output schema, no annotations), the description is incomplete. It lacks details on behavioral traits, usage context, and output expectations. While the schema covers parameters well, the description doesn't compensate for missing annotations or output schema, leaving gaps in overall understanding.

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 fully documents both parameters ('text' and 'model'). The description adds no additional meaning beyond what's in the schema, such as explaining tokenization nuances or model-specific behaviors. Baseline 3 is appropriate when the schema handles all parameter documentation.

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: 'Count tokens for a given text with a specific model'. It specifies the verb ('count'), resource ('tokens'), and scope ('text' and 'model'). However, it doesn't explicitly differentiate from sibling tools like 'embed_text' or 'generate_text', which might also involve token processing, so it doesn't reach the highest score.

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 over other operations like text generation or embedding, nor does it reference sibling tools. This leaves the agent without context for tool selection.

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

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