Skip to main content
Glama
temurkhan13

openclaw-cost-tracker-mcp

by temurkhan13

costs_by_agent

Break down token costs by agent, showing total spend, request count, average cost per request, primary provider and model, and share of total spend, sorted by cost descending.

Instructions

Per-agent cost breakdown — total spend + request count + avg cost-per-request + primary provider/model + share of total spend, sorted by cost descending.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
window_hoursNo

Implementation Reference

  • The call_tool handler for 'costs_by_agent': fetches entries in the window, aggregates via _by_agent(), wraps in AgentCostBreakdown, and serializes.
    if name == "costs_by_agent":
        from openclaw_cost_tracker_mcp.analysis import _by_agent
    
        window_hours = max(1, min(int(arguments.get("window_hours", 168)), 720))
        entries = await _entries_in_window(window_hours)
        agents = _by_agent(entries)
        return _serialize(
            AgentCostBreakdown(
                window_hours=window_hours,
                total_cost_usd=sum(e.cost_usd for e in entries),
                agents=agents,
            )
        )
  • AgentCostBreakdown model — the response schema for the costs_by_agent tool.
    class AgentCostBreakdown(BaseModel):
        """Response for `costs_by_agent`."""
    
        window_hours: int
        total_cost_usd: float
        agents: list[AgentCost]
  • AgentCost model — per-agent cost roll-up with total spend, request count, total tokens, avg cost/request, primary provider/model, and share of total.
    class AgentCost(BaseModel):
        """Cost roll-up for a single agent/channel/skill over a window."""
    
        model_config = ConfigDict(frozen=True)
    
        agent_id: str
        total_cost_usd: float
        request_count: int
        total_tokens: int
        avg_cost_per_request_usd: float
        primary_provider: Provider | None = None
        primary_model: str | None = None
        share_of_total_pct: float
  • _by_agent() — the pure aggregation function that groups CostEntry records by agent_id, computes total cost, request count, tokens, avg cost/request, primary provider/model, and share of total, sorted by cost descending.
    def _by_agent(entries: list[CostEntry], top_n: int | None = None) -> list[AgentCost]:
        if not entries:
            return []
        total = sum(e.cost_usd for e in entries) or 1.0
        grouped: dict[str, list[CostEntry]] = defaultdict(list)
        for e in entries:
            agent = e.agent_id or "<unattributed>"
            grouped[agent].append(e)
        out: list[AgentCost] = []
        for agent, group in grouped.items():
            cost = sum(e.cost_usd for e in group)
            # Most-common provider/model in the group
            provider_counts = Counter(e.provider for e in group)
            model_counts = Counter((e.provider, e.model) for e in group)
            primary_provider = provider_counts.most_common(1)[0][0] if provider_counts else None
            primary_model = model_counts.most_common(1)[0][0][1] if model_counts else None
            out.append(
                AgentCost(
                    agent_id=agent,
                    total_cost_usd=cost,
                    request_count=len(group),
                    total_tokens=sum(e.total_tokens for e in group),
                    avg_cost_per_request_usd=cost / len(group),
                    primary_provider=primary_provider,
                    primary_model=primary_model,
                    share_of_total_pct=100.0 * cost / total,
                )
            )
        out.sort(key=lambda a: a.total_cost_usd, reverse=True)
        if top_n is not None:
            out = out[:top_n]
        return out
  • Tool registration: defines the 'costs_by_agent' tool with name, description, and inputSchema (window_hours integer).
    Tool(
        name="costs_by_agent",
        description=(
            "Per-agent cost breakdown — total spend + request count + avg cost-per-request "
            "+ primary provider/model + share of total spend, sorted by cost descending."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "window_hours": {"type": "integer", "default": 168},
            },
            "required": [],
        },
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. It does not disclose whether the tool is read-only, destructive, or has auth/rate limits. Since it likely just queries data, a note about idempotency would be beneficial.

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 sentence that efficiently lists all output fields and the sort order. No unnecessary words.

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

Completeness3/5

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

The description explains the output well but omits the single input parameter entirely. Given no output schema, this is a notable gap for input comprehension.

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

Parameters1/5

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

The input schema has one optional parameter (window_hours) with 0% schema description coverage. The description does not mention this parameter at all, failing to explain its meaning or effect on results. The description adds no value beyond the schema.

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 it provides a per-agent cost breakdown with specific metrics (total spend, request count, avg cost-per-request, primary provider/model, share of total spend, sorted by cost descending). This distinguishes it from sibling tools like cost_overview (likely overall) or costs_by_provider.

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

Usage Guidelines3/5

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

The usage is implied from the purpose (use when you need per-agent costs), but there is no explicit guidance on when to use this tool versus alternatives, no prerequisites, and no mention of when not to use it.

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/temurkhan13/openclaw-cost-tracker-mcp'

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