@devries-cameron20 / composio-1 / commits / dd05b303c
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(core): expose premium usage charges in usage and logs (#4651)

## Summary Expose the premium usage charge returned by the platform's usage summary and tool log APIs in the TypeScript and Python SDKs. Related platform changes: [usage summary](https://github.com/ComposioHQ/hermes/pull/13195) and [tool logs](https://github.com/ComposioHQ/hermes/pull/13299). ## Changes - Map the exact USD `premium_usage_charge` from the project usage summary to TypeScript `premiumUsageCharge` and Python `premium_usage_charge`. - Type and validate the optional charge in TypeScript tool log metadata; verify Python log search and detail preserve the metadata key. - Document both fields in the production readiness and log streaming guides, and add a core changeset. ## Type of change - [ ] Bug fix - [x] New feature - [ ] Refactor/Chore - [x] Documentation - [ ] Breaking change ## How Has This Been Tested? - `pnpm --filter @composio/core exec vitest run test/models/usage.test.ts test/models/logs.test.ts` — 14 passed. - `pnpm --filter @composio/core typecheck` and `pnpm --filter @composio/core build` — passed. - `uv run --package composio --no-dev --with pytest pytest python/tests/test_experimental_usage.py python/tests/test_logs.py -q` — 10 passed. - Ruff, Oxlint, Prettier, and the repository pre-commit hooks — passed. - `pnpm validate:changesets` — passed. - Docs `bun run test` — 606 passed; `bun run lint`, `bun run lint:links`, `bun run types:check`, and `bun run check:kb-semantic --allow-stale` — passed. The semantic check reported the expected stale artifact warning. - Docs `bun run build` failed while compiling the unrelated `content/docs/tools-direct/executing-tools.mdx`: the Twoslash filesystem cache returned `SyntaxError: Unexpected end of JSON input`. ## Screenshots (if applicable) Not applicable. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the third-party links policy - [x] I ran linters/tests locally and recorded the docs build failure above - [x] I updated documentation as needed - [x] I added focused tests - [x] I added a changeset for the published TypeScript package ## Additional context The pinned generated clients (`@composio/client@2.0.0-rc.8` and `composio-client==2.0.0rc8`) predate these server fields and are the latest published prereleases. Their runtime responses retain the fields, so the SDK exposes them without editing generated code or changing client pins.

Prachi Mandil committed Sep 28, 2026 at 15:35 UTC dd05b303cc283854c393abb228791b7383b3ef3f
17 files changed +151 -18
.changeset/premium-usage-response-contract.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Expose the exact premium usage charge in project usage summaries and tool log metadata.
docs/content/docs/poc-to-prod/stream-logs-to-a-siem.mdx
+2
@@ -40,6 +40,8 @@ Both SDKs expose `composio.logs.search()` for read-only searches with filters, a
40
41 Retrieve the full entry for one execution with `composio.logs.get("log_123")` in Python or `await composio.logs.get('log_123')` in TypeScript.
42
43 +For a charged hosted-account call, both the search result and the full entry include `metadata.premium_usage_charge` as an exact USD string. The field is absent when the call has no premium charge.
44 +
45 ## Schedule collection without losing your place
46
47 Run a collector for each project, with its own API key and durable checkpoint. A scheduled job or your platform's HTTP poller can perform these steps. If you use a poller, verify that it supports POST bodies, cursor pagination, and saved state.
docs/content/docs/production-readiness.mdx
+2
@@ -86,6 +86,8 @@ In Python, pass a standard `logging.Logger` as `logger` and a `composio.utils.lo
86
87 Use `composio.experimental.usage.summary()` for totals by entity type and `composio.experimental.usage.breakdown()` for grouped usage of one entity type, such as `tool_calls` or `sessions`. Both SDKs scope these queries to the project associated with your API key.
88
89 +The summary also returns the total premium usage charge for the window as an exact USD string: `premiumUsageCharge` in TypeScript and `premium_usage_charge` in Python. It returns `"0"` when no usage was charged. Breakdowns contain usage quantities and event counts, not charges.
90 +
91 <Callout>
92 Usage metering is experimental, and its response shape may change.
93 </Callout>
python/composio/core/models/__init__.py
+2
@@ -13,6 +13,7 @@ from .experimental import (
13 ExperimentalAPI,
14 ExperimentalCustomToolkits,
15 ExperimentalUsage,
16 + UsageSummaryResponse,
17 )
18 from .keyring import Keyring
19 from .logs import Logs
@@ -54,6 +55,7 @@ __all__ = [
55 "ExperimentalCustomToolkits",
56 "ExperimentalToolkit",
57 "ExperimentalUsage",
58 + "UsageSummaryResponse",
59 "Keyring",
60 "Logs",
61 "MCP",
python/composio/core/models/experimental.py
+14 -3
@@ -49,6 +49,14 @@ from .custom_tool import (
49 ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT = "acl_config_for_shared is only valid on SHARED"
50
51
52 +class UsageSummaryResponse(
53 + usage_retrieve_summary_response.UsageRetrieveSummaryResponse
54 +):
55 + """Project usage summary with the exact USD premium charge for the window."""
56 +
57 + premium_usage_charge: str
58 +
59 +
60 class ExperimentalUsage:
61 """Project usage metering, accessed via ``composio.experimental.usage``.
62
@@ -72,7 +80,7 @@ class ExperimentalUsage:
80 def summary(
81 self,
82 **params: te.Unpack[usage_retrieve_summary_params.UsageRetrieveSummaryParams],
75 - ) -> usage_retrieve_summary_response.UsageRetrieveSummaryResponse:
83 + ) -> UsageSummaryResponse:
84 """
85 Fetch a usage summary for the project. Experimental — shape may change.
86
@@ -80,14 +88,17 @@ class ExperimentalUsage:
88 :param to: End of the window (Unix epoch milliseconds).
89 :param entity_types: Restrict the summary to these entity types.
90 :param filters: Additional server-side filters.
83 - :return: Usage totals keyed by entity type under ``.entities``.
91 + :return: Usage totals under ``.entities`` and the exact USD amount in
92 + ``.premium_usage_charge`` (``"0"`` when nothing was charged).
93
94 Example:
95 summary = composio.experimental.usage.summary(
96 entity_types=["tool_calls"],
97 )
98 """
90 - return self._require_client().project.usage.retrieve_summary(**params)
99 + response = self._require_client().project.usage.retrieve_summary(**params)
100 + # The pinned generated client retains new response fields as Pydantic extras.
101 + return UsageSummaryResponse.model_validate(response.model_dump())
102
103 def breakdown(
104 self,
python/composio/core/models/logs.py
+5 -2
@@ -34,7 +34,9 @@ class Logs(Resource):
34 :param cursor: Pagination cursor from a previous response.
35 :param filters: Filter clauses to narrow the search.
36 :param time_range: Time window to search within.
37 - :return: Matching logs plus a ``next_cursor`` for pagination.
37 + :return: Matching logs plus a ``next_cursor`` for pagination. A charged
38 + tool log has an exact USD string at
39 + ``log.metadata["premium_usage_charge"]``.
40
41 Example:
42 page = composio.logs.search(
@@ -55,7 +57,8 @@ class Logs(Resource):
57 Retrieve a single tool execution log by id.
58
59 :param id: The log id.
58 - :return: The full log entry.
60 + :return: The full log entry. For charged calls,
61 + ``log.metadata["premium_usage_charge"]`` is the exact USD amount.
62
63 Example:
64 log = composio.logs.get("log_123")
python/composio/types.py
+2
@@ -1,5 +1,6 @@
1 from composio.client.types import Tool
2 from composio.core.models.connected_accounts import auth_scheme
3 +from composio.core.models.experimental import UsageSummaryResponse
4 from composio.core.models.tools import (
5 Modifiers,
6 PremiumCharge,
@@ -23,6 +24,7 @@ __all__ = [
24 "PremiumCharge",
25 "ToolExecuteParams",
26 "ToolExecutionResponse",
27 + "UsageSummaryResponse",
28 "TriggerEvent",
29 "Modifiers",
30 "auth_scheme",
python/tests/test_experimental_usage.py
+16 -3
@@ -5,6 +5,7 @@ from unittest.mock import Mock
5 import pytest
6
7 from composio import exceptions
8 +from composio.client.types import usage_retrieve_summary_response
9 from composio.core.models.experimental import ExperimentalAPI, ExperimentalUsage
10
11
@@ -29,7 +30,11 @@ class TestExperimentalUsage:
30 assert experimental.usage._client is mock_client
31
32 def test_summary_passes_params_through(self, usage, mock_client):
32 - mock_client.project.usage.retrieve_summary.return_value = "summary"
33 + mock_client.project.usage.retrieve_summary.return_value = (
34 + usage_retrieve_summary_response.UsageRetrieveSummaryResponse.model_validate(
35 + {"entities": {}, "premium_usage_charge": "0.025"}
36 + )
37 + )
38
39 result = usage.summary(
40 from_=1.0,
@@ -38,7 +43,8 @@ class TestExperimentalUsage:
43 filters={"toolkit_slug": "github"},
44 )
45
41 - assert result == "summary"
46 + assert result.entities == {}
47 + assert result.premium_usage_charge == "0.025"
48 mock_client.project.usage.retrieve_summary.assert_called_once_with(
49 from_=1.0,
50 to=2.0,
@@ -47,9 +53,16 @@ class TestExperimentalUsage:
53 )
54
55 def test_summary_without_params(self, usage, mock_client):
50 - usage.summary()
56 + mock_client.project.usage.retrieve_summary.return_value = (
57 + usage_retrieve_summary_response.UsageRetrieveSummaryResponse.model_validate(
58 + {"entities": {}, "premium_usage_charge": "0"}
59 + )
60 + )
61 +
62 + result = usage.summary()
63
64 mock_client.project.usage.retrieve_summary.assert_called_once_with()
65 + assert result.premium_usage_charge == "0"
66
67 def test_breakdown_passes_entity_type_and_params(self, usage, mock_client):
68 mock_client.project.usage.retrieve.return_value = "breakdown"
python/tests/test_logs.py
+48
@@ -4,6 +4,10 @@ from unittest.mock import Mock
4
5 import pytest
6
7 +from composio.client.types import (
8 + log_create_tool_execution_response,
9 + log_retrieve_tool_execution_response,
10 +)
11 from composio.core.models.logs import Logs
12 from tests.conftest import mock_http_client
13
@@ -21,6 +25,29 @@ def logs(mock_client: Mock) -> Logs:
25
26
27 class TestLogs:
28 + def test_search_preserves_premium_usage_charge(self, logs, mock_client):
29 + mock_client.logs.create_tool_execution.return_value = log_create_tool_execution_response.LogCreateToolExecutionResponse.model_validate(
30 + {
31 + "logs": [
32 + {
33 + "id": "log_1",
34 + "timestamp": "2026-01-01T00:00:00Z",
35 + "type": "tool.execution",
36 + "status": "success",
37 + "level": "info",
38 + "metadata": {"premium_usage_charge": "0.012"},
39 + "metrics": {},
40 + "parent": None,
41 + }
42 + ],
43 + "next_cursor": None,
44 + }
45 + )
46 +
47 + result = logs.search()
48 +
49 + assert result.logs[0].metadata["premium_usage_charge"] == "0.012"
50 +
51 def test_search_passes_params_through(self, logs, mock_client):
52 mock_client.logs.create_tool_execution.return_value = "page"
53
@@ -49,3 +76,24 @@ class TestLogs:
76
77 assert logs.get("log_123") == "log"
78 mock_client.logs.retrieve_tool_execution.assert_called_once_with("log_123")
79 +
80 + def test_get_preserves_premium_usage_charge(self, logs, mock_client):
81 + mock_client.logs.retrieve_tool_execution.return_value = log_retrieve_tool_execution_response.LogRetrieveToolExecutionResponse.model_validate(
82 + {
83 + "id": "log_1",
84 + "timestamp": "2026-01-01T00:00:00Z",
85 + "type": "tool.execution",
86 + "status": "success",
87 + "level": "info",
88 + "metadata": {"premium_usage_charge": "0.012"},
89 + "metrics": {},
90 + "parent": None,
91 + "context": {},
92 + "source": {},
93 + "data": {},
94 + }
95 + )
96 +
97 + result = logs.get("log_1")
98 +
99 + assert result.metadata["premium_usage_charge"] == "0.012"
ts/packages/core/src/models/Logs.ts
+2 -2
@@ -46,7 +46,7 @@ export class Logs {
46 * pagination.
47 *
48 * @param {LogSearchParams} [params] - Filters, `timeRange`, `limit` and `cursor`
49 - * @returns {Promise<LogSearchResponse>} Matching logs and the next cursor
49 + * @returns {Promise<LogSearchResponse>} Matching logs and the next cursor. Charged calls include `metadata.premium_usage_charge` as an exact USD string.
50 * @throws {ValidationError} If the params fail validation
51 *
52 * @example
@@ -83,7 +83,7 @@ export class Logs {
83 * source and raw `data`).
84 *
85 * @param {string} id - The log id
86 - * @returns {Promise<ToolExecutionLogDetail>} The log detail
86 + * @returns {Promise<ToolExecutionLogDetail>} The log detail, with an optional exact USD charge in `metadata.premium_usage_charge`
87 *
88 * @example
89 * ```typescript
ts/packages/core/src/models/Usage.ts
+2 -1
@@ -32,6 +32,7 @@ import {
32 * ```typescript
33 * const summary = await composio.experimental.usage.summary();
34 * console.log(summary.entities.tool_calls?.totalQuantity);
35 + * console.log(summary.premiumUsageCharge); // exact USD string
36 *
37 * const byTool = await composio.experimental.usage.breakdown('tool_calls', {
38 * groupBy: 'tool_slug',
@@ -52,7 +53,7 @@ export class Usage {
53 * **Experimental — shape may change in future releases.**
54 *
55 * @param {UsageSummaryParams} [params] - Optional range, `entityTypes` and filters
55 - * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type
56 + * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type and the exact USD premium usage charge
57 * @throws {ValidationError} If the params fail validation
58 *
59 * @example
ts/packages/core/src/types/logs.types.ts
+9 -1
@@ -56,6 +56,14 @@ export const ToolExecutionLogParentSchema = z
56 })
57 .nullable();
58
59 +/** Tool log metadata, including the optional exact USD premium charge. */
60 +export const ToolExecutionLogMetadataSchema = z
61 + .object({
62 + premium_usage_charge: z.string().optional(),
63 + })
64 + .catchall(z.unknown());
65 +export type ToolExecutionLogMetadata = z.infer<typeof ToolExecutionLogMetadataSchema>;
66 +
67 /**
68 * A tool-execution log entry as returned by `composio.logs.search()`.
69 */
@@ -68,7 +76,7 @@ export const ToolExecutionLogSchema = z.object({
76 status: ToolExecutionLogStatusSchema,
77 level: ToolExecutionLogLevelSchema,
78 message: z.string().optional(),
71 - metadata: z.record(z.string(), z.unknown()),
79 + metadata: ToolExecutionLogMetadataSchema,
80 metrics: z.record(z.string(), z.unknown()),
81 parent: ToolExecutionLogParentSchema,
82 });
ts/packages/core/src/types/usage.types.ts
+2
@@ -61,6 +61,8 @@ export type UsageEntitySummary = z.infer<typeof UsageEntitySummarySchema>;
61 export const UsageSummaryResponseSchema = z.object({
62 /** Aggregates keyed by metering entity type (e.g. `tool_calls`, `sessions`). */
63 entities: z.record(z.string(), UsageEntitySummarySchema),
64 + /** Total premium usage charge for the window, in USD as an exact decimal string. */
65 + premiumUsageCharge: z.string(),
66 });
67 export type UsageSummaryResponse = z.infer<typeof UsageSummaryResponseSchema>;
68
ts/packages/core/src/utils/transformers/logs.ts
+3 -2
@@ -10,6 +10,7 @@ import {
10 ToolExecutionLog,
11 ToolExecutionLogDetail,
12 ToolExecutionLogDetailSchema,
13 + ToolExecutionLogMetadataSchema,
14 ToolExecutionLogSchema,
15 } from '../../types/logs.types';
16 import { transform } from '../transform';
@@ -33,7 +34,7 @@ export const transformToolExecutionLog = (
34 status: response.status,
35 level: response.level,
36 message: response.message,
36 - metadata: response.metadata,
37 + metadata: ToolExecutionLogMetadataSchema.parse(response.metadata),
38 metrics: response.metrics,
39 parent: response.parent
40 ? { logId: response.parent.log_id, toolSlug: response.parent.tool_slug }
@@ -62,7 +63,7 @@ export const transformToolExecutionLogDetail = (
63 status: response.status,
64 level: response.level,
65 message: response.message,
65 - metadata: response.metadata,
66 + metadata: ToolExecutionLogMetadataSchema.parse(response.metadata),
67 metrics: response.metrics,
68 parent: response.parent
69 ? { logId: response.parent.log_id, toolSlug: response.parent.tool_slug }
ts/packages/core/src/utils/transformers/usage.ts
+4
@@ -4,6 +4,7 @@ import type {
4 UsageRetrieveSummaryParams as RawUsageSummaryParams,
5 UsageRetrieveSummaryResponse as RawUsageSummaryResponse,
6 } from '@composio/client/resources/project/usage';
7 +import { z } from 'zod/v3';
8 import {
9 UsageBreakdownParams,
10 UsageBreakdownResponse,
@@ -42,6 +43,8 @@ export const transformUsageBreakdownParams = (
43 export const transformUsageSummaryResponse = (
44 response: RawUsageSummaryResponse
45 ): UsageSummaryResponse => {
46 + // The pinned generated client predates this response field but preserves the raw JSON.
47 + const { premium_usage_charge } = z.object({ premium_usage_charge: z.string() }).parse(response);
48 return transform(response)
49 .with(UsageSummaryResponseSchema)
50 .using(response => ({
@@ -55,6 +58,7 @@ export const transformUsageSummaryResponse = (
58 },
59 ])
60 ),
61 + premiumUsageCharge: premium_usage_charge,
62 }));
63 };
64
ts/packages/core/test/models/logs.test.ts
+26 -2
@@ -26,7 +26,7 @@ const rawLog = {
26 status: 'success',
27 level: 'info',
28 message: 'ok',
29 - metadata: { tool_slug: 'GITHUB_GET_REPO' },
29 + metadata: { tool_slug: 'GITHUB_GET_REPO', premium_usage_charge: '0.012' },
30 metrics: { duration_ms: 12 },
31 parent: { log_id: 'log_0', tool_slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' },
32 };
@@ -37,7 +37,7 @@ const transformedLog = {
37 status: 'success',
38 level: 'info',
39 message: 'ok',
40 - metadata: { tool_slug: 'GITHUB_GET_REPO' },
40 + metadata: { tool_slug: 'GITHUB_GET_REPO', premium_usage_charge: '0.012' },
41 metrics: { duration_ms: 12 },
42 parent: { logId: 'log_0', toolSlug: 'COMPOSIO_MULTI_EXECUTE_TOOL' },
43 };
@@ -102,6 +102,7 @@ describe('Logs', () => {
102 ],
103 nextCursor: 'cursor_2',
104 });
105 + expect(result.logs[0]?.metadata.premium_usage_charge).toBe('0.012');
106 });
107
108 it('throws a ValidationError for an unknown filter field', async () => {
@@ -112,6 +113,15 @@ describe('Logs', () => {
113 ).rejects.toThrow(ValidationError);
114 expect(mockClient.logs.createToolExecution).not.toHaveBeenCalled();
115 });
116 +
117 + it('rejects a non-string premium charge in log metadata', async () => {
118 + mockClient.logs.createToolExecution.mockResolvedValue({
119 + logs: [{ ...rawLog, metadata: { premium_usage_charge: 0.012 } }],
120 + next_cursor: null,
121 + });
122 +
123 + await expect(logs.search()).rejects.toThrow();
124 + });
125 });
126
127 describe('get', () => {
@@ -149,5 +159,19 @@ describe('Logs', () => {
159 expect(result.timings).toBeUndefined();
160 expect(result.context).toEqual({});
161 });
162 +
163 + it('leaves the premium charge absent for an uncharged call', async () => {
164 + mockClient.logs.retrieveToolExecution.mockResolvedValue({
165 + ...rawLog,
166 + metadata: { tool_slug: 'GITHUB_GET_REPO' },
167 + context: {},
168 + source: {},
169 + data: {},
170 + });
171 +
172 + const result = await logs.get('log_1');
173 +
174 + expect(result.metadata.premium_usage_charge).toBeUndefined();
175 + });
176 });
177 });
ts/packages/core/test/models/usage.test.ts
+7 -2
@@ -43,7 +43,10 @@ describe('Experimental.usage', () => {
43
44 describe('summary', () => {
45 it('sends an empty body when called without params', async () => {
46 - mockClient.project.usage.retrieveSummary.mockResolvedValue({ entities: {} });
46 + mockClient.project.usage.retrieveSummary.mockResolvedValue({
47 + entities: {},
48 + premium_usage_charge: '0',
49 + });
50
51 const result = await experimental.usage.summary();
52
@@ -51,7 +54,7 @@ describe('Experimental.usage', () => {
54 { from: undefined, to: undefined, entity_types: undefined, filters: undefined },
55 undefined
56 );
54 - expect(result).toEqual({ entities: {} });
57 + expect(result).toEqual({ entities: {}, premiumUsageCharge: '0' });
58 });
59
60 it('maps params to the wire and transforms the response', async () => {
@@ -60,6 +63,7 @@ describe('Experimental.usage', () => {
63 tool_calls: { unit: 'call', total_quantity: '42', event_count: 42 },
64 sessions: { unit: 'session', total_quantity: '3', event_count: 3 },
65 },
66 + premium_usage_charge: '0.025',
67 });
68 const signal = new AbortController().signal;
69
@@ -87,6 +91,7 @@ describe('Experimental.usage', () => {
91 tool_calls: { unit: 'call', totalQuantity: '42', eventCount: 42 },
92 sessions: { unit: 'session', totalQuantity: '3', eventCount: 3 },
93 },
94 + premiumUsageCharge: '0.025',
95 });
96 });
97