Skip to main content
Glama
Supermaxman
by Supermaxman

get_costs

Retrieve OpenAI API usage costs for a specified time period. Filter by project IDs or group costs by project and line items to analyze spending.

Instructions

Fetches OpenAI costs for the specified period.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
start_timeYesThe start time as a UTC timestamp.
end_timeNoThe end time as a UTC timestamp (defaults to now).
group_byNoThe fields to group by (optional). Group the costs by the specified fields. Support fields include project_id, line_item and any combination of them.
project_idsNoThe project IDs to filter by (optional).

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for the 'get_costs' tool. It fetches OpenAI organization costs using the Admin API, handles pagination, parameter construction for filtering and grouping, and converts timestamps to datetime objects.
    @mcp.tool(description="Fetches OpenAI costs for the specified period.")
    async def get_costs(
        start_time: Annotated[datetime, "The start time as a UTC timestamp."],
        end_time: Annotated[
            Optional[datetime], "The end time as a UTC timestamp (defaults to now)."
        ] = None,
        group_by: Annotated[
            Optional[list[Literal["project_id", "line_item"]]],
            "The fields to group by (optional). Group the costs by the specified fields. Support fields include project_id, line_item and any combination of them.",
        ] = None,
        project_ids: Annotated[
            Optional[list[str]], "The project IDs to filter by (optional)."
        ] = None,
    ) -> list[dict]:
        """Fetches the costs for the current month."""
    
        base_url = "https://api.openai.com/v1/organization/costs"
        params: list[tuple[str, str]] = [
            ("start_time", int(start_time.timestamp())),
            ("limit", 180),
        ]
        if end_time:
            params.append(("end_time", int(end_time.timestamp())))
    
        if group_by:
            for field in group_by:
                params.append(("group_by", field))
        if project_ids:
            for project_id in project_ids:
                params.append(("project_ids", project_id))
        base_params = params.copy()
        url = f"{base_url}?{urlencode(base_params)}"
        results: list[dict] = []
        async with httpx.AsyncClient(
            timeout=60,
            headers={"Authorization": f"Bearer {OPENAI_ADMIN_API_KEY}"},
        ) as client:
            while url:
                response = await client.get(url)
                response.raise_for_status()
                data = response.json()
                items = data["data"]
                for item in items:
                    item["start_time"] = datetime.fromtimestamp(item["start_time"])
                    item["end_time"] = datetime.fromtimestamp(item["end_time"])
                    results.append(item)
                next_page = data.get("next_page")
                has_more = data.get("has_more")
                url = None
                if next_page and has_more:
                    params = base_params.copy()
                    params.append(("page", next_page))
                    url = f"{base_url}?{urlencode(params)}"
                    # sleep to avoid rate limiting
                    await asyncio.sleep(1.0)
        return results
  • Registers the 'get_costs' tool with the FastMCP server using the @mcp.tool decorator.
    @mcp.tool(description="Fetches OpenAI costs for the specified period.")
  • Input schema defined via Annotated type hints and descriptions for the tool parameters.
        start_time: Annotated[datetime, "The start time as a UTC timestamp."],
        end_time: Annotated[
            Optional[datetime], "The end time as a UTC timestamp (defaults to now)."
        ] = None,
        group_by: Annotated[
            Optional[list[Literal["project_id", "line_item"]]],
            "The fields to group by (optional). Group the costs by the specified fields. Support fields include project_id, line_item and any combination of them.",
        ] = None,
        project_ids: Annotated[
            Optional[list[str]], "The project IDs to filter by (optional)."
        ] = None,
    ) -> list[dict]:
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states 'fetches' which implies a read operation, but doesn't mention authentication needs, rate limits, error conditions, or what the output contains (though an output schema exists). For a tool with no annotation coverage, this leaves significant behavioral gaps.

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 that immediately conveys the core functionality without any wasted words. It's appropriately sized for a straightforward data retrieval tool and is perfectly front-loaded.

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?

Given the tool's moderate complexity (4 parameters, 1 required), 100% schema coverage, and the presence of an output schema, the description is reasonably complete. It states what the tool does, though it could better address behavioral aspects given the lack of annotations. The output schema reduces the need to describe return values.

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 all parameters. The description adds no parameter-specific information beyond implying temporal filtering ('for the specified period'), which is already covered in the schema. This meets the baseline for high schema coverage without adding extra value.

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 verb ('fetches') and resource ('OpenAI costs') with temporal scope ('for the specified period'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from the sibling tool 'get_projects', which appears to be a different resource type, so it misses 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 or in what context. It mentions 'for the specified period' but doesn't clarify prerequisites, constraints, or comparison with 'get_projects', leaving the agent with no usage direction beyond the basic purpose.

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/Supermaxman/mcp-server-openai'

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