Skip to main content
Glama

Token Counter

count_tokens

Count tokens in text across multiple LLM models to check context window usage and compare costs before sending to an LLM.

Instructions

Count tokens for any text across multiple LLM models and get per-model cost estimates. Use before sending text to an LLM to check context window usage or compare costs across models. Supports GPT-4o, GPT-4, GPT-3.5-turbo, Claude 3.5 Sonnet, Claude 3 Opus, and 10+ more.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYesThe text to count tokens for
modelsNoModels to count tokens for

Implementation Reference

  • The "count_tokens" tool is registered here. It uses the helper function `callToolApi` to forward the request to the `token-counter` endpoint of the Agent Toolbelt API.
    // ----- Tool: Token Counter -----
    server.registerTool(
      "count_tokens",
      {
        title: "Token Counter",
        description:
          "Count tokens for any text across multiple LLM models and get per-model cost estimates. " +
          "Use before sending text to an LLM to check context window usage or compare costs across models. " +
          "Supports GPT-4o, GPT-4, GPT-3.5-turbo, Claude 3.5 Sonnet, Claude 3 Opus, and 10+ more.",
        inputSchema: {
          text: z.string().describe("The text to count tokens for"),
          models: z
            .array(z.string())
            .default(["gpt-4o", "claude-3-5-sonnet"])
            .describe("Models to count tokens for"),
        },
      },
      async ({ text, models }) => {
        const result = await callToolApi("token-counter", { text, models });
        const data = result as any;
        const r = data.result;
    
        const lines = [
          `**Characters:** ${r.characterCount.toLocaleString()}`,
          `**Words:** ${r.wordCount.toLocaleString()}`,
          "",
          "**Token counts:**",
        ];
    
        for (const [model, info] of Object.entries(r.results) as any) {
          const approx = info.approximate ? " (approx)" : "";
          const cost = info.estimatedCost
            ? ` | input ~$${info.estimatedCost.input} / output ~$${info.estimatedCost.output}`
            : "";
          lines.push(`  ${model}: **${info.tokens.toLocaleString()} tokens**${approx}${cost}`);
        }
    
        return { content: [{ type: "text" as const, text: lines.join("\n") }] };
      }
    );
Behavior3/5

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

With no annotations provided, the description carries full disclosure burden. It successfully indicates dual outputs (token counts and cost estimates) and lists supported model families. However, it omits critical behavioral traits like whether external API calls are made for pricing data, rate limits, or caching behavior.

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?

Three tightly constructed sentences with zero redundancy: sentence 1 declares core functionality, sentence 2 specifies usage timing, sentence 3 enumerates supported models. Information is front-loaded and every clause earns its place.

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 2-parameter utility tool with no output schema, the description adequately compensates by explaining the return value nature ('cost estimates', 'context window usage'). The 100% schema coverage means parameter documentation needs are minimal, making this sufficiently complete despite lacking annotations.

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

Parameters4/5

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

While the schema has 100% description coverage (baseline 3), the description adds significant value by enumerating supported model examples ('GPT-4o, GPT-4, GPT-3.5-turbo, Claude 3.5 Sonnet...') which compensates for the lack of enum constraints in the schema and guides valid string inputs for the models parameter.

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 uses specific verbs ('Count', 'get') with clear resources ('tokens', 'cost estimates') and explicitly scopes the operation to 'any text across multiple LLM models'. It effectively distinguishes from siblings like pack_context_window or optimize_prompt by focusing purely on measurement and estimation rather than modification.

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

Usage Guidelines4/5

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

Provides explicit temporal context for invocation ('Use before sending text to an LLM') and clear use cases ('check context window usage or compare costs'). Lacks explicit 'when not to use' guidance or named alternatives, though the specific function has no direct sibling equivalent.

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/marras0914/agent-toolbelt'

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