count_tokens
Calculate token counts for text using specified Gemini AI models to manage input length and optimize API usage.
Instructions
Count tokens for a given text with a specific model
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| model | No | Model to use for token counting | gemini-2.5-flash |
| text | Yes | Text to count tokens for |
Implementation Reference
- src/enhanced-stdio-server.ts:740-784 (handler)Main handler implementation for the 'count_tokens' tool. Calls Google Gemini SDK's countTokens method with the provided text and model, then formats and returns the MCP response with token count.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' } }; } }
- src/enhanced-stdio-server.ts:318-337 (registration)Registration of the 'count_tokens' tool in the getAvailableTools() method, defining name, description, and input schema for MCP tools/list.{ 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'] } },
- src/utils/validation.ts:93-96 (schema)Zod schema for validating 'count_tokens' tool input parameters (text and optional model). Part of ToolSchemas export.countTokens: z.object({ text: z.string().min(1, 'Text is required'), model: CommonSchemas.geminiModel.optional() }),
- src/enhanced-stdio-server.ts:493-494 (handler)Dispatch case in handleToolCall() that routes 'count_tokens' tool calls to the countTokens handler method.case 'count_tokens': return await this.countTokens(request.id, args);