Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

feat(usage): meter web searches and Composio-backed tool calls (#3779)

Q1hangL9f25ab65152b
diff --git a/src/xagent/core/model/chat/token_context.py b/src/xagent/core/model/chat/token_context.py
index efc2d2db5..408bd9328 100644
--- a/src/xagent/core/model/chat/token_context.py
+++ b/src/xagent/core/model/chat/token_context.py
@@ -5,11 +5,12 @@ contextvars let statistics be collected automatically during task execution.
Two dimensions live here. LLM tokens use ``add_token_usage`` and aggregate via
``aggregate_token_usage_by_model``. Non-LLM media calls — image, video, TTS,
-ASR, music, sound effect, embedding, rerank — use the ``MediaUnit`` /
-``MediaCallType`` vocabulary, record through ``add_media_usage``, and aggregate
-via ``aggregate_media_usage_by_model``. Both write into the same
-``TokenUsage.details`` list, discriminated by each row's ``type``, so existing
-persistence and quota paths carry media rows with no schema change.
+ASR, music, sound effect, embedding, rerank, web search, Composio connector
+calls — use the ``MediaUnit`` / ``MediaCallType`` vocabulary, record through
+``add_media_usage``, and aggregate via ``aggregate_media_usage_by_model``.
+Both write into the same ``TokenUsage.details`` list, discriminated by each
+row's ``type``, so existing persistence and quota paths carry media rows with
+no schema change.
"""
import contextvars
@@ -86,6 +87,13 @@ class MediaCallType(str, Enum):
SOUND_EFFECT = ("sound_effect", MediaUnit.SECONDS)
EMBEDDING = ("embedding", MediaUnit.TEXTS)
RERANK = ("rerank", MediaUnit.REQUESTS)
+ # Platform-metered requests with nothing finer to bill than the call
+ # itself: one successful search against a search provider's key, and one
+ # request Composio accepted on the platform's grant. A connector tool call
+ # can make several such requests, so a ``composio`` call is metered per
+ # request and the connector reports its count in the MCP result ``_meta``.
+ WEB_SEARCH = ("web_search", MediaUnit.REQUESTS)
+ COMPOSIO = ("composio", MediaUnit.REQUESTS)
_MEDIA_CALL_TYPE_VALUES = frozenset(member.value for member in MediaCallType)
diff --git a/src/xagent/core/tools/adapters/vibe/mcp_adapter.py b/src/xagent/core/tools/adapters/vibe/mcp_adapter.py
index ee35d00c5..e87860505 100644
--- a/src/xagent/core/tools/adapters/vibe/mcp_adapter.py
+++ b/src/xagent/core/tools/adapters/vibe/mcp_adapter.py
@@ -56,6 +56,7 @@ from ....utils.public_http_transport import (
UnsafePublicHttpTarget,
)
from ....utils.security import PrivateNetworkHostError, redact_sensitive_text
+from ...core.mcp.composio_requests import COMPOSIO_REQUESTS_META_KEY
from ...core.mcp.sessions import (
Connection,
SSEConnection,
@@ -2247,6 +2248,28 @@ def _normalized_mcp_call_result(
}
+# The private member ``_execute_mcp_call`` hands the subprocess-reported
+# Composio count back under. ``run_json_async`` records the rows and removes
+# it, so it never reaches the model.
+_COMPOSIO_REQUESTS_KEY = "_composio_requests"
+
+
+def _reported_composio_requests(meta: Any) -> int:
+ """How many Composio requests a connector reported for one tool call.
+
+ ``meta`` is the MCP result's ``_meta``, written by the connector
+ subprocess. Only a non-negative int is a count; a missing or malformed
+ value means no request was accepted (or the subprocess does not report
+ them), so nothing is recorded.
+ """
+ if not isinstance(meta, Mapping):
+ return 0
+ count = meta.get(COMPOSIO_REQUESTS_META_KEY)
+ if type(count) is not int or count < 0:
+ return 0
+ return count
+
+
def _excel_failure_code(result: Mapping[str, Any]) -> str | None:
"""Carry the Excel connector's allowlisted failure code to the runtime."""
from ....agent.result import EXCEL_FAILURE_CODES, normalize_tool_failure_code
@@ -2409,6 +2432,12 @@ class MCPToolAdapter(AbstractBaseTool):
runtime_config = connection if isinstance(connection, Mapping) else {}
self._runtime_bindings = runtime_bindings_from_config(runtime_config)
self._connector_runtime = connector_runtime_from_config(runtime_config)
+ # Set by the server config only for a connector whose subprocess runs on
+ # a Composio grant. That subprocess reports how many Proxy Execute
+ # requests Composio accepted for each call, and the adapter records
+ # that many rows. Absent for every native connector and every other
+ # server, which are not billed to Composio.
+ self._composio_backed = runtime_config.get("composio") is True
self._signed_upload = self._usable_signed_upload(signed_upload)
from .base import ToolCategory
@@ -3716,6 +3745,18 @@ class MCPToolAdapter(AbstractBaseTool):
if retry_result is None:
raise
result = retry_result
+ if self._composio_backed:
+ # Composio bills every Proxy Execute request it accepted,
+ # so a call that listed once and read ten messages is
+ # eleven rows. The connector subprocess counted them and
+ # reported the count on the result's ``_meta``; a retry
+ # above ran in a new subprocess, so only the retry's
+ # accepted requests are counted here.
+ # Local import: media_usage loads the model layer, and
+ # the MCP loader is used without it.
+ from ...core.media_usage import record_composio_usage
+
+ record_composio_usage(result.pop(_COMPOSIO_REQUESTS_KEY, 0))
if (
self._workspace is not None
and self._workspace_download_field is not None
@@ -3870,6 +3911,10 @@ class MCPToolAdapter(AbstractBaseTool):
normalized["failure_code"] = failure_code
normalized["success"] = False
normalized["is_error"] = True
+ if self._composio_backed:
+ normalized[_COMPOSIO_REQUESTS_KEY] = _reported_composio_requests(
+ getattr(result, "meta", None)
+ )
return normalized
async def _retry_after_authorization_failure(
diff --git a/src/xagent/core/tools/adapters/vibe/web_search.py b/src/xagent/core/tools/adapters/vibe/web_search.py
index 1916f6f0b..d0b091873 100644
--- a/src/xagent/core/tools/adapters/vibe/web_search.py
+++ b/src/xagent/core/tools/adapters/vibe/web_search.py
@@ -80,5 +80,4 @@ class WebSearchTool(AbstractBaseTool):
num_results=search_args.num_results,
include_content=search_args.include_content,
)
-
return WebSearchResult(results=results).model_dump()
diff --git a/src/xagent/core/tools/core/exa_web_search.py b/src/xagent/core/tools/core/exa_web_search.py
index 467d617d2..edb3ceef1 100644
--- a/src/xagent/core/tools/core/exa_web_search.py
+++ b/src/xagent/core/tools/core/exa_web_search.py
@@ -8,6 +8,7 @@ import logging
import os
from typing import Any, Dict, List, Optional
+from .media_usage import record_web_search_usage
from .web_search_guard import run_guarded_search
logger = logging.getLogger(__name__)
@@ -150,6 +151,9 @@ class ExaWebSearchCore:
raise ValueError(f"Error during Exa search: {str(e)}") from e
logger.info("✅ Exa API request successful")
+ # The SDK returned, so Exa billed this request; record it before the
+ # response is read into results.
+ record_web_search_usage("exa")
return self._normalize_results(response, content_mode)
@staticmethod
diff --git a/src/xagent/core/tools/core/mcp/composio_requests.py b/src/xagent/core/tools/core/mcp/composio_requests.py
new file mode 100644
index 000000000..a8c3b0263
--- /dev/null
+++ b/src/xagent/core/tools/core/mcp/composio_requests.py
@@ -0,0 +1,13 @@
+"""The MCP result member a Composio-backed connector reports its count on.
+
+Composio bills each Proxy Execute request, and one connector tool call can make
+several. The connector subprocess counts the requests Composio accepted and
+puts the count in the MCP tool result's ``_meta`` under this key; the agent
+process reads it in ``MCPToolAdapter`` and records one usage row per request.
+
+The key lives here, outside ``media_usage`` (which loads the model layer), so a
+connector subprocess can import it cheaply, and under ``core`` so the adapter
+can read it without importing the web package.
+"""
+
+COMPOSIO_REQUESTS_META_KEY = "xagent/composio_requests"
diff --git a/src/xagent/core/tools/core/media_usage.py b/src/xagent/core/tools/core/media_usage.py
index 761f33b6d..26ef1287b 100644
--- a/src/xagent/core/tools/core/media_usage.py
+++ b/src/xagent/core/tools/core/media_usage.py
@@ -1,10 +1,11 @@
-"""Best-effort media-usage recording for media generation tools.
+"""Best-effort usage recording for media generation and other metered calls.
TTS/ASR/video/music/sound-effect models don't return a normalised usage
payload the way image/chat models do, and their adapters are factory-only, so
the natural metering point is the tool call site where the request params and
result are both in scope. This helper wraps ``add_media_usage`` so a failure in
-accounting can never break the underlying media call.
+accounting can never break the underlying media call. Search providers and
+Composio-backed connectors use the same rule through the helpers below.
Metering invariants
-------------------
@@ -247,3 +248,46 @@ def record_media_seconds(
model=model,
model_id=model_id,
)
+
+
+# One platform identity per built-in search provider, keyed by the provider
+# name that ``XAGENT_WEB_SEARCH_PROVIDER`` accepts. Search keys belong to the
+# deployment, so every id is in the platform namespace and a deployment can
+# price each provider separately. A new provider adds one line here; nothing
+# else names a search id.
+WEB_SEARCH_MODEL_IDS: dict[str, str] = {
+ "zhipu": "platform/web-search-zhipu",
+ "tavily": "platform/web-search-tavily",
+ "exa": "platform/web-search-exa",
+ "google": "platform/web-search-google",
+}
+
+
+def record_web_search_usage(provider: str) -> None:
+ """Record one search the provider accepted with a 2xx answer.
+
+ Call it as soon as the provider's answer is known to be successful, before
+ the body is parsed and before any result page is fetched: the provider
+ bills the request whether or not the body turns out usable. A search that
+ raised -- a missing key, a timeout, an HTTP error -- never reached the
+ provider's bill, so it records nothing. ``provider`` is the name in
+ ``XAGENT_WEB_SEARCH_PROVIDER``; the platform's own search key pays, so the
+ row carries that provider's platform id rather than a user's model.
+ """
+ model_id = WEB_SEARCH_MODEL_IDS.get(provider)
+ if model_id is None:
+ logger.error("Unknown web search provider %r; dropping the usage row", provider)
+ return
+ record_media_usage(MediaCallType.WEB_SEARCH, 1, model_id=model_id)
+
+
+def record_composio_usage(requests: int) -> None:
+ """Record one ``composio`` row per request Composio accepted in a call.
+
+ Composio bills each Proxy Execute request, and one connector tool call can
+ make several: a Gmail search reads one message per request, and a batch
+ sends one request per item. A ``requests`` row bills quantity 1, so N
+ accepted requests are N rows.
+ """
+ for _ in range(requests):
+ record_media_usage(MediaCallType.COMPOSIO, 1, model_id="platform/composio")
diff --git a/src/xagent/core/tools/core/tavily_web_search.py b/src/xagent/core/tools/core/tavily_web_search.py
index f05e66057..b7b1b6217 100644
--- a/src/xagent/core/tools/core/tavily_web_search.py
+++ b/src/xagent/core/tools/core/tavily_web_search.py
@@ -9,6 +9,7 @@ from typing import Any, Dict, List, Optional
import httpx
+from .media_usage import record_web_search_usage
from .web_search_guard import run_guarded_search
logger = logging.getLogger(__name__)
@@ -103,6 +104,9 @@ class TavilyWebSearchCore:
)
response.raise_for_status()
+ # Tavily billed this request as soon as it answered 2xx, so
+ # record it before reading the body.
+ record_web_search_usage("tavily")
data = response.json()
logger.info("✅ Tavily API request successful")
diff --git a/src/xagent/core/tools/core/web_search.py b/src/xagent/core/tools/core/web_search.py
index b1518194a..0d727e978 100644
--- a/src/xagent/core/tools/core/web_search.py
+++ b/src/xagent/core/tools/core/web_search.py
@@ -9,6 +9,7 @@ from typing import Any, Dict, List, Optional
import httpx
+from .media_usage import record_web_search_usage
from .web_content import WebContentFetcher, get_proxy_url
from .web_search_guard import run_guarded_search
@@ -108,6 +109,9 @@ class WebSearchCore:
self._handle_403_error(response)
response.raise_for_status()
+ # Google billed this request as soon as it answered 2xx, so
+ # record it before reading the body or fetching any result page.
+ record_web_search_usage("google")
data = response.json()
logger.info("✅ Google API request successful")
diff --git a/src/xagent/core/tools/core/zhipu_web_search.py b/src/xagent/core/tools/core/zhipu_web_search.py
index 8ad88d48e..736b86a61 100644
--- a/src/xagent/core/tools/core/zhipu_web_search.py
+++ b/src/xagent/core/tools/core/zhipu_web_search.py
@@ -10,6 +10,7 @@ from typing import Any, Dict, List, Optional, cast
import httpx
from ...utils.public_http_transport import create_public_async_client
+from .media_usage import record_web_search_usage
from .web_content import get_trusted_proxy_url
from .web_search_guard import run_guarded_search
@@ -141,6 +142,9 @@ class ZhipuWebSearchCore:
)
response.raise_for_status()
+ # Zhipu billed this request as soon as it answered 2xx, so
+ # record it before reading the body.
+ record_web_search_usage("zhipu")
return cast(Dict[str, Any], response.json())
except httpx.RequestError as e:
diff --git a/src/xagent/web/tools/config.py b/src/xagent/web/tools/config.py
index 199e64dc0..e46ba34a3 100644
--- a/src/xagent/web/tools/config.py
+++ b/src/xagent/web/tools/config.py
@@ -4226,6 +4226,12 @@ class WebToolConfig(BaseToolConfig):
composio_user_id=instance_url,
)
)
+ # The subprocess runs on Composio's grant, so its tool calls are
+ # billed to Composio rather than to the provider directly. The
+ # MCP adapter reads this to trust the accepted-request count on
+ # the tool result's ``_meta``; no env var carries it because
+ # nothing in the subprocess acts on it.
+ transport_config["composio"] = True
else:
for env_key, token_type in env_mapping.items():
if token_type == "access_token":
diff --git a/src/xagent/web/tools/mcp/composio_metering.py b/src/xagent/web/tools/mcp/composio_metering.py
new file mode 100644
index 000000000..30f1a3297
--- /dev/null
+++ b/src/xagent/web/tools/mcp/composio_metering.py
@@ -0,0 +1,72 @@
+"""Report the Composio requests a connector tool call made.
+
+Composio bills each Proxy Execute request, and one connector tool call can make
+several: a Gmail search lists once and then reads one message per request, and
+a batch sends one request per item. The connector subprocess has no usage
+tracker bound, so it counts the requests Composio accepted during the call and
+puts that count on the MCP tool result's ``_meta``. The agent process reads it
+in ``MCPToolAdapter`` and records one row per accepted request.
+
+A batch returns at its deadline without waiting for the requests it has
+already sent, and each of those can still be accepted by Composio afterwards.
+The count therefore waits for those requests to settle before it is taken, so
+a late acceptance is still reported. That wait is bounded: a request a batch
+sent has an end-to-end deadline of its own (its transport's ``timeout``, 30
+seconds by default, the same length as a batch's), covering however its
+answer's body is delivered and a binary download, so a request still running
+when its batch hits the deadline settles within one more deadline. One that
+runs out of time fails like a timeout and is not counted.
+
+Only the connector servers that can run on a Composio grant use this class; a
+native grant runs on the same module and makes no proxy call, so its count is
+zero.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from mcp.server.fastmcp import FastMCP
+from mcp.types import CallToolResult
+
+from ....core.tools.core.mcp.composio_requests import COMPOSIO_REQUESTS_META_KEY
+from .composio_proxy import (
+ begin_request_count,
+ end_request_count,
+ pending_batch_requests,
+)
+
+
+class ComposioMeteringFastMCP(FastMCP):
+ """A FastMCP server that reports how many Composio requests a call made."""
+
+ async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any:
+ token = begin_request_count()
+ try:
+ result = await super().call_tool(name, arguments)
+ # A batch that hit its deadline has already-sent requests still
+ # running. Each of those has an end-to-end deadline of its own and
+ # can still be accepted before it runs out, so waiting for them
+ # settles every request before the count is taken. One that fails
+ # or runs out of time is neither this tool call's failure nor a
+ # counted request.
+ await asyncio.gather(
+ *(asyncio.wrap_future(future) for future in pending_batch_requests()),
+ return_exceptions=True,
+ )
+ finally:
+ accepted = end_request_count(token)
+ meta = {COMPOSIO_REQUESTS_META_KEY: accepted}
+ if isinstance(result, CallToolResult):
+ result.meta = {**(result.meta or {}), **meta}
+ return result
+ if isinstance(result, tuple):
+ content, structured = result
+ tool_result = CallToolResult(
+ content=list(content), structuredContent=structured
+ )
+ else:
+ tool_result = CallToolResult(content=list(result))
+ tool_result.meta = meta
+ return tool_result
diff --git a/src/xagent/web/tools/mcp/composio_proxy.py b/src/xagent/web/tools/mcp/composio_proxy.py
index c588231a0..188a034d3 100644
--- a/src/xagent/web/tools/mcp/composio_proxy.py
+++ b/src/xagent/web/tools/mcp/composio_proxy.py
@@ -18,7 +18,13 @@ and sends absolute URLs.
Two kinds of failure stay apart:
- Composio itself refusing or failing (bad key, unknown account, rate limit,
- an answer that is not a proxy result) raises ``ComposioProxyError``.
+ an answer that is not a proxy result) raises ``ComposioProxyError``. So does
+ a request a batch sent that outlives its end-to-end deadline: ``requests``'
+ ``timeout`` bounds one connect attempt and each socket read, not the whole
+ exchange, so a body that keeps arriving inside the read timeout would never
+ end. Only a batch's request has that deadline, because a metered tool call
+ waits for it after the batch returned; a request sent outside a batch keeps
+ just the ``timeout``.
- The provider's own answer, error or not, is returned as a ``ProxyResponse``
with the provider's status, so each connector maps its own API's errors.
@@ -35,8 +41,12 @@ import json
import logging
import os
import re
-from collections.abc import Collection, Iterable, Mapping
-from dataclasses import dataclass
+import threading
+import time
+from collections.abc import Callable, Collection, Iterable, Mapping
+from concurrent.futures import Future, wait
+from contextvars import ContextVar, Token
+from dataclasses import dataclass, field
from typing import Any
from urllib.parse import quote, urlsplit
@@ -54,6 +64,11 @@ _LAUNCH_SECRET_ENVS = (
COMPOSIO_CONNECTED_ACCOUNT_ID_ENV,
COMPOSIO_USER_ID_ENV,
)
+# The per-socket timeout given to ``requests``, which bounds one connect attempt
+# and each read, not the whole exchange. A proxied request a batch sent also has
+# it as an end-to-end budget, from the send to the last byte of the answer (a
+# binary answer's download included), because a metered tool call waits for such
+# a request after its batch returned.
DEFAULT_TIMEOUT_SECONDS = 30
# The largest JSON body one Proxy Execute call may carry. Composio's API is
# served by Vercel functions (its answers can carry ``x-vercel-id``), whose
@@ -164,6 +179,64 @@ def serves_composio_grant() -> bool:
return bool(os.environ.get(COMPOSIO_CONNECTED_ACCOUNT_ID_ENV))
+@dataclass
+class _RequestCount:
+ """What one metered tool call has counted, and what can still count.
+
+ ``accepted`` is the per-request count: a batch's worker threads reach the
+ same object through a copy of the caller's context. ``pending`` holds the
+ batch futures that were still running when their batch returned, because
+ each of those can still be accepted after the batch's deadline.
+ """
+
+ accepted: list[int] = field(default_factory=list)
+ pending: list[Future[Any]] = field(default_factory=list)
+
+
+# The requests the MCP tool call being handled made to Composio. FastMCP
+# handles calls concurrently in one process, so the count is a context
+# variable; outside a metered call (a host-issued call, a direct client use)
+# nothing is counted.
+_request_count: ContextVar[_RequestCount | None] = ContextVar(
+ "composio_request_count", default=None
+)
+
+
+def begin_request_count() -> Token[_RequestCount | None]:
+ """Start counting the requests Composio accepts for one tool call."""
+ return _request_count.set(_RequestCount())
+
+
+def end_request_count(token: Token[_RequestCount | None]) -> int:
+ """Stop counting and return how many requests were accepted."""
+ count = _request_count.get()
+ _request_count.reset(token)
+ return len(count.accepted) if count is not None else 0
+
+
+def record_accepted_request() -> None:
+ """Count one request Composio accepted; a no-op outside a metered call."""
+ count = _request_count.get()
+ if count is not None:
+ # ``list.append`` is atomic under the GIL, so a batch can count from
+ # its worker threads without a lock.
+ count.accepted.append(1)
+
+
+def register_pending_batch_requests(futures: Iterable[Future[Any]]) -> None:
+ """Have the metered call wait for the batch requests in ``futures`` that
+ outlived their batch's deadline; a no-op outside a metered call."""
+ count = _request_count.get()
+ if count is not None:
+ count.pending.extend(futures)
+
+
+def pending_batch_requests() -> tuple[Future[Any], ...]:
+ """The batch requests a metered call still has to wait for."""
+ count = _request_count.get()
+ return tuple(count.pending) if count is not None else ()
+
+
def redact(value: Any) -> Any:
"""``value`` with every launch secret and provider token replaced, in
nested values too."""
@@ -944,6 +1017,44 @@ def check_json_body_size(
)
+class _DeadlinePassed(Exception):
+ """One proxied send did not finish by the deadline it was given."""
+
+
+def send_within_deadline(deadline: float | None, send: Callable[[], Any]) -> Any:
+ """``send()``, given up on at ``deadline`` (a ``time.monotonic()`` value).
+
+ ``send`` performs one ``requests`` call, whose own ``timeout`` bounds one
+ connect attempt and each socket read, not the whole exchange: a body that
+ keeps arriving inside the read timeout never trips it. Given a deadline,
+ the call runs on a thread of its own and the caller waits only until then,
+ so one deadline can cover several steps of one proxied request (the proxy
+ call and the download of a binary answer); a call that outlives it is
+ abandoned and raises, and nothing this client counts or returns comes from
+ the abandoned call, because the caller counts and reads the answer itself,
+ after this returns. Without a deadline, ``send()`` runs on this thread, as
+ one sent outside a batch does.
+ """
+ if deadline is None:
+ return send()
+ sent: Future[Any] = Future()
+
+ def run() -> None:
+ try:
+ sent.set_result(send())
+ except BaseException as exc: # handed to the waiting caller
+ sent.set_exception(exc)
+
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise _DeadlinePassed
+ threading.Thread(target=run, name="composio-proxy-send", daemon=True).start()
+ _, unfinished = wait([sent], timeout=remaining)
+ if unfinished:
+ raise _DeadlinePassed
+ return sent.result()
+
+
def proxy_request(
method: str,
endpoint: str,
@@ -954,17 +1065,27 @@ def proxy_request(
body: Any = None,
timeout: float = DEFAULT_TIMEOUT_SECONDS,
max_body_bytes: int | None = None,
+ deadline: float | None = None,
) -> ProxyResponse:
"""Send ``method endpoint`` through Composio as the launched grant.
``allowed_hosts`` are the hostnames an absolute ``endpoint`` may name.
``query`` is a mapping or a sequence of pairs, and each name may appear
only once; ``body`` is sent as JSON. Raises ``ComposioProxyError`` when
- Composio does not relay the call, and ``ValueError`` before sending
- anything when the endpoint, a launch variable or a parameter is unusable,
- when a query name appears more than once, or when the JSON body would
- exceed ``MAX_JSON_BODY_BYTES``. ``max_body_bytes`` overrides that shared
- default, for a connector whose real limit differs.
+ Composio does not relay the call, or does not finish a call that has a
+ ``deadline`` inside it, and ``ValueError`` before sending anything when the
+ endpoint, a launch variable or a parameter is unusable, when a query name
+ appears more than once, or when the JSON body would exceed
+ ``MAX_JSON_BODY_BYTES``. ``max_body_bytes`` overrides that shared default,
+ for a connector whose real limit differs.
+
+ ``timeout`` is the per-socket timeout given to ``requests``. ``deadline``
+ is an end-to-end cutoff for the call, as a ``time.monotonic()`` value, for
+ a caller that runs further steps of the same request under it (reading a
+ binary answer): ``GoogleApiProxyHttp`` gives one to each request a batch
+ sends, because a metered tool call waits for those. A call that outlives it
+ is abandoned and raises. Without a deadline the call has no end-to-end
+ cutoff and is bounded only by ``timeout``.
"""
if isinstance(allowed_hosts, str):
raise TypeError("allowed_hosts must be a collection of hostnames, not a str")
@@ -974,17 +1095,25 @@ def proxy_request(
_checked_payload_size(payload, max_body_bytes)
try:
- response = requests.request(
- method="POST",
- url=COMPOSIO_PROXY_URL,
- headers={
- "x-api-key": api_key,
- "Accept": "application/json",
- "Content-Type": "application/json",
- },
- json=payload,
- timeout=timeout,
+ response = send_within_deadline(
+ deadline,
+ lambda: requests.request(
+ method="POST",
+ url=COMPOSIO_PROXY_URL,
+ headers={
+ "x-api-key": api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ },
+ json=payload,
+ timeout=timeout,
+ ),
)
+ except _DeadlinePassed:
+ logger.warning("Composio proxy request did not finish within %gs", timeout)
+ raise ComposioProxyError(
+ f"Composio proxy did not finish the answer within {timeout:g}s"
+ ) from None
except Exception as exc:
# Type only: a connection error's text can name the request.
logger.warning(
@@ -1023,6 +1152,9 @@ def proxy_request(
"Composio proxy returned a binary answer in an unexpected shape",
status=status,
)
+ # Composio accepted this call (the provider's own status, success or not,
+ # is in ``provider_status``), so it is a billed request.
+ record_accepted_request()
return ProxyResponse(
status=provider_status,
data=answer.get("data"),
diff --git a/src/xagent/web/tools/mcp/composio_tools.py b/src/xagent/web/tools/mcp/composio_tools.py
index 9d95b1030..ac9cb6ca1 100644
--- a/src/xagent/web/tools/mcp/composio_tools.py
+++ b/src/xagent/web/tools/mcp/composio_tools.py
@@ -42,6 +42,7 @@ from .composio_proxy import (
DEFAULT_TIMEOUT_SECONDS,
_required_env,
_truncated,
+ record_accepted_request,
redact,
)
@@ -185,6 +186,7 @@ def execute_tool(
if not isinstance(successful, bool):
raise ComposioToolError("Composio returned a tool answer without a result")
error = answer.get("error")
+ record_accepted_request()
return ToolResult(
successful=successful,
data=answer.get("data"),
diff --git a/src/xagent/web/tools/mcp/facebook.py b/src/xagent/web/tools/mcp/facebook.py
index 78d6d4564..dbf8158f0 100644
--- a/src/xagent/web/tools/mcp/facebook.py
+++ b/src/xagent/web/tools/mcp/facebook.py
@@ -5,9 +5,8 @@ from pathlib import Path
from typing import Any
from urllib.parse import quote
-from mcp.server.fastmcp import FastMCP
-
from . import meta_graph
+from .composio_metering import ComposioMeteringFastMCP
from .meta_graph import (
GraphAPIError,
)
@@ -24,7 +23,7 @@ logger = logging.getLogger("facebook-mcp")
setup_proxy_env()
-mcp = FastMCP("facebook-mcp")
+mcp = ComposioMeteringFastMCP("facebook-mcp")
requests = meta_graph.requests # exposed for test monkeypatching
_UPLOAD_ALLOWED_DIRS_ENV_VAR = "XAGENT_FACEBOOK_IMAGE_ALLOWED_DIRS"
_MAX_IMAGE_BYTES = 10 * 1024 * 1024
diff --git a/src/xagent/web/tools/mcp/gmail.py b/src/xagent/web/tools/mcp/gmail.py
index a251c9d9f..5cc78be2c 100644
--- a/src/xagent/web/tools/mcp/gmail.py
+++ b/src/xagent/web/tools/mcp/gmail.py
@@ -9,9 +9,9 @@ from typing import Any
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build # type: ignore[import-not-found]
-from mcp.server.fastmcp import FastMCP
from . import composio_proxy, google_api_proxy
+from .composio_metering import ComposioMeteringFastMCP
from .utils import allowed_dirs_from_env, setup_proxy_env
logging.basicConfig(level=logging.INFO)
@@ -20,7 +20,7 @@ logger = logging.getLogger("gmail-mcp")
# Ensure standard proxy environment variables are set to prevent hanging requests
setup_proxy_env()
-mcp = FastMCP("gmail-mcp")
+mcp = ComposioMeteringFastMCP("gmail-mcp")
# Gmail's real limit is 25MB on the base64-encoded message. base64 inflates
# raw bytes by 4/3, so this caps the raw (pre-encoding) total at 3/4 of that
diff --git a/src/xagent/web/tools/mcp/google_api_proxy.py b/src/xagent/web/tools/mcp/google_api_proxy.py
index e2e50307b..ca25e45ae 100644
--- a/src/xagent/web/tools/mcp/google_api_proxy.py
+++ b/src/xagent/web/tools/mcp/google_api_proxy.py
@@ -28,8 +28,10 @@ from __future__ import annotations
import http.client
import json
+import time
from collections.abc import Collection, Mapping
from concurrent.futures import ThreadPoolExecutor, wait
+from contextvars import ContextVar, copy_context
from dataclasses import dataclass
from typing import Any
from urllib.parse import parse_qsl, urlsplit
@@ -43,6 +45,8 @@ from .composio_proxy import (
ProxyResponse,
check_json_body_size,
proxy_request,
+ register_pending_batch_requests,
+ send_within_deadline,
)
# How many batch requests may be in flight at once. A Gmail message search
@@ -60,6 +64,14 @@ DEFAULT_BATCH_DEADLINE_SECONDS = float(DEFAULT_TIMEOUT_SECONDS)
# the same scale as the native batch it replaces.
MAX_BATCH_REQUESTS = 100
+# Whether the request being sent right now is one a batch sent. Only those get
+# an end-to-end deadline: a metered Composio tool call waits, after its batch
+# returned, for a request still running, so that request's answer must not keep
+# arriving for longer than one ``timeout``. ``execute_batch`` sets this inside
+# the context it copies for the worker that sends one request, so it cannot
+# reach a request sent outside a batch (a Drive read, a single Gmail call).
+_batch_request: ContextVar[bool] = ContextVar("google_api_batch_request", default=False)
+
# The only request headers forwarded to the API. Both change what Google
# returns or how it reads the body. Content-Length and User-Agent describe
# the request we no longer make, Accept-Encoding would ask Google to compress
@@ -111,7 +123,7 @@ def _declared_size(value: Any) -> int | None:
def _binary_content(
- binary_data: Mapping[str, Any], *, timeout: float
+ binary_data: Mapping[str, Any], *, timeout: float, deadline: float | None
) -> tuple[bytes, str]:
"""The bytes behind a binary answer's signed URL, and their content type.
@@ -119,7 +131,10 @@ def _binary_content(
that signed URL in ``binary_data``; the URL expires, so it must not be
kept, and it must not appear in an error either (it is a bearer-like
credential for the file). ``public_requests`` keeps the download off a
- non-public destination.
+ non-public destination. When the request was one a batch sent, the download
+ runs under the same end-to-end deadline as the proxy call it belongs to:
+ the count was settled when that call returned, so a download that never
+ ends must not hold the caller of the request either.
The bytes must be the whole body: a 206, or a body shorter or longer than
the size Composio declared (or, unless the answer is compressed, the
@@ -138,8 +153,11 @@ def _binary_content(
# it the client would ask for gzip/deflate, decode the body, and
# compare the decoded length with the encoded one -- refusing a
# perfectly good download as truncated.
- response = requests.get(
- url, timeout=timeout, headers={"Accept-Encoding": "identity"}
+ response = send_within_deadline(
+ deadline,
+ lambda: requests.get(
+ url, timeout=timeout, headers={"Accept-Encoding": "identity"}
+ ),
)
except Exception:
# Type only: the exception's text can name the signed URL.
@@ -178,7 +196,9 @@ def _binary_content(
return content, content_type
-def _body_and_type(answer: ProxyResponse, *, timeout: float) -> tuple[bytes, str]:
+def _body_and_type(
+ answer: ProxyResponse, *, timeout: float, deadline: float | None
+) -> tuple[bytes, str]:
"""The body and content type of one provider answer.
Gmail answers an empty success with 204, so a 2xx other than 204 that
@@ -187,9 +207,13 @@ def _body_and_type(answer: ProxyResponse, *, timeout: float) -> tuple[bytes, str
to a caller that reads it as a JSON document. The shared client leaves
that judgment to each API: Salesforce, for one, reads an empty answer as
an empty object.
+
+ ``deadline`` is the end-to-end deadline of the proxied request this answer
+ belongs to, when it is one a batch sent, so a binary body is downloaded
+ inside it.
"""
if answer.binary_data is not None:
- return _binary_content(answer.binary_data, timeout=timeout)
+ return _binary_content(answer.binary_data, timeout=timeout, deadline=deadline)
if answer.ok and answer.status != 204 and answer.data is None:
raise ComposioProxyError(
"Composio proxy returned an answer without the provider's data"
@@ -318,7 +342,14 @@ class GoogleApiProxyHttp:
httplib2's callers pass them; neither applies here. This transport
does not follow a redirect: the status and the provider's headers
(including ``location``) are returned, so the caller can follow it.
+
+ A request a batch sent gets an end-to-end deadline, because a metered
+ tool call waits for it after the batch returned: the whole call, a
+ binary answer's download included, runs inside one ``timeout`` from
+ here. A request sent outside a batch has no such deadline and keeps
+ only the ``timeout`` given to ``requests``.
"""
+ deadline = time.monotonic() + self._timeout if _batch_request.get() else None
prepared = self._prepare(uri, method, body, headers)
answer = proxy_request(
prepared.method,
@@ -329,10 +360,13 @@ class GoogleApiProxyHttp:
body=prepared.body,
timeout=self._timeout,
max_body_bytes=self._max_body_bytes,
+ deadline=deadline,
)
if answer.ok and answer.binary_data is None and _is_media_request(prepared):
_refuse_relayed_media_object(answer.data)
- content, content_type = _body_and_type(answer, timeout=self._timeout)
+ content, content_type = _body_and_type(
+ answer, timeout=self._timeout, deadline=deadline
+ )
response_headers = {
str(name).lower(): str(value)
for name, value in (answer.headers or {}).items()
@@ -434,7 +468,13 @@ def execute_batch(
A request still unanswered at ``deadline`` reaches its callback as a
``TimeoutError``; the batch's own threads are abandoned rather than
- awaited, so the caller returns inside its budget.
+ awaited, so the caller returns inside its budget. A request that was
+ already sent keeps running, but only until the end-to-end deadline of the
+ transport that sent it (``GoogleApiProxyHttp`` gives it ``timeout`` from
+ its start, the answer's body and a binary download included), so it
+ settles inside one such deadline. It can still be accepted before then,
+ and a metered Composio tool call registers it and waits for that, so the
+ count it reports includes every request Composio accepted.
"""
# BatchHttpRequest keeps its requests, their order and its callbacks in
# these attributes and googleapiclient has no public accessor for them. A
@@ -466,6 +506,9 @@ def execute_batch(
http = request.http
if http is None:
return ValueError("Missing a valid http object.")
+ # This runs in a context copied for this one request, so the mark
+ # reaches this request's transport and no other.
+ _batch_request.set(True)
try:
answer: tuple[Any, bytes] = http.request(
request.uri,
@@ -486,10 +529,25 @@ def execute_batch(
thread_name_prefix="google-api-proxy",
)
try:
- futures = {request_id: executor.submit(run, request_id) for request_id in order}
+ # Each worker runs under the caller's context, so a Composio request
+ # count started for this tool call also sees the batch's requests.
+ futures = {
+ request_id: executor.submit(copy_context().run, run, request_id)
+ for request_id in order
+ }
_, pending = wait(futures.values(), timeout=deadline)
for future in pending:
future.cancel()
+ # A request that is neither cancelled nor finished has started and is
+ # still running past the deadline, so it can still be accepted: a
+ # metered tool call waits for it before it reports its count. A
+ # cancelled request was never sent and can never be accepted, so it is
+ # not registered.
+ register_pending_batch_requests(
+ future
+ for future in futures.values()
+ if not future.cancelled() and not future.done()
+ )
for request_id, future in futures.items():
# ``pending`` is a snapshot taken when ``wait`` returned: a
# request can finish between that snapshot and this loop, and
diff --git a/src/xagent/web/tools/mcp/google_drive.py b/src/xagent/web/tools/mcp/google_drive.py
index e88143e2b..9d030cc75 100644
--- a/src/xagent/web/tools/mcp/google_drive.py
+++ b/src/xagent/web/tools/mcp/google_drive.py
@@ -19,11 +19,11 @@ from googleapiclient.http import ( # type: ignore[import-not-found]
MediaIoBaseDownload,
MediaIoBaseUpload,
)
-from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations
from ....config import get_tool_max_output_length
from . import composio_proxy, google_api_proxy
+from .composio_metering import ComposioMeteringFastMCP
from .utils import (
allowed_dirs_from_env,
clamp_limit,
@@ -41,7 +41,7 @@ logger = logging.getLogger("google-drive-mcp")
# Ensure standard proxy environment variables are set to prevent hanging requests
setup_proxy_env()
-mcp = FastMCP("google-drive-mcp")
+mcp = ComposioMeteringFastMCP("google-drive-mcp")
# google_drive_composio -- the Composio write path for the three byte-writing
# tools below -- is imported inside each Composio branch, not here: that
diff --git a/src/xagent/web/tools/mcp/instagram.py b/src/xagent/web/tools/mcp/instagram.py
index 7d0b5ca67..84f8e0297 100644
--- a/src/xagent/web/tools/mcp/instagram.py
+++ b/src/xagent/web/tools/mcp/instagram.py
@@ -3,9 +3,8 @@ import time
from typing import Any
from urllib.parse import quote
-from mcp.server.fastmcp import FastMCP
-
from . import meta_graph
+from .composio_metering import ComposioMeteringFastMCP
from .meta_graph import (
GraphAPIError,
)
@@ -23,7 +22,7 @@ logger = logging.getLogger("instagram-mcp")
setup_proxy_env()
-mcp = FastMCP("instagram-mcp")
+mcp = ComposioMeteringFastMCP("instagram-mcp")
requests = meta_graph.requests # exposed for test monkeypatching
LINKED_ACCOUNT_FIELDS = (
diff --git a/src/xagent/web/tools/mcp/meta_graph.py b/src/xagent/web/tools/mcp/meta_graph.py
index 50156e37c..6b7ad06e9 100644
--- a/src/xagent/web/tools/mcp/meta_graph.py
+++ b/src/xagent/web/tools/mcp/meta_graph.py
@@ -373,12 +373,22 @@ def _composio_proxy_request(
"Composio proxy returned a response that is not a JSON object",
sensitive_values=sensitive_values,
)
+ upstream_status = body.get("status")
+ # Same rule as ``composio_proxy.proxy_request``: exactly an int, so a bool
+ # or a numeric string is not read as Graph's status.
+ if type(upstream_status) is not int:
+ raise ComposioProxyError(
+ "Composio proxy returned an answer without the provider's status",
+ sensitive_values=sensitive_values,
+ )
+ # Composio accepted this call; a Graph error in the body is the provider's
+ # answer, not a refusal, so the request is billed either way.
+ composio_proxy.record_accepted_request()
upstream_data = body.get("data")
_remember_proxy_response_secrets(upstream_data)
_strip_tokens_from_paging_links(upstream_data)
- upstream_status = body.get("status")
- if isinstance(upstream_status, int) and upstream_status >= 400:
+ if upstream_status >= 400:
message = f"Graph API returned HTTP {upstream_status} through Composio"
if upstream_data is not None:
message = f"{message} - {json.dumps(upstream_data)}"
diff --git a/src/xagent/web/tools/mcp/salesforce.py b/src/xagent/web/tools/mcp/salesforce.py
index 6179b7c97..5899c14ec 100644
--- a/src/xagent/web/tools/mcp/salesforce.py
+++ b/src/xagent/web/tools/mcp/salesforce.py
@@ -5,11 +5,10 @@ import re
from typing import Any, NoReturn
from urllib.parse import urlparse, urlsplit
-from mcp.server.fastmcp import FastMCP
-
from ....config import get_tool_max_output_length
from ....core.utils import public_requests as requests
from . import composio_proxy
+from .composio_metering import ComposioMeteringFastMCP
from .utils import (
clamp_limit,
clamp_offset,
@@ -21,7 +20,7 @@ logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("salesforce-mcp")
-mcp = FastMCP("salesforce-mcp")
+mcp = ComposioMeteringFastMCP("salesforce-mcp")
# The OIDC userinfo endpoint is documented as this fixed host, not the
# per-org instance_url used by every other endpoint here -- Salesforce
diff --git a/tests/core/model/chat/test_media_usage.py b/tests/core/model/chat/test_media_usage.py
index fe2ca58da..4e7d7b837 100644
--- a/tests/core/model/chat/test_media_usage.py
+++ b/tests/core/model/chat/test_media_usage.py
@@ -347,6 +347,38 @@ def test_enum_members_are_accepted() -> None:
assert isinstance(entry["unit"], str)
+def test_web_search_and_composio_bill_in_requests() -> None:
+ # Both are hosted calls paid for by the platform's own keys and grants, and
+ # neither has a finer billable dimension, so a call is one request.
+ for call_type in (MediaCallType.WEB_SEARCH, MediaCallType.COMPOSIO):
+ assert call_type.unit is MediaUnit.REQUESTS
+
+
+ ("call_type", "model_id"),
+ [
+ # The plain string the search tools pass, and the member itself.
+ ("web_search", "platform/web-search-tavily"),
+ (MediaCallType.COMPOSIO, "platform/composio"),
+ ],
+)
+def test_platform_request_rows_carry_the_provider_identity(call_type, model_id) -> None:
+ usage = TokenUsage()
+ usage.record_media_call(call_type, 1, model_id=model_id)
+
+ assert usage.media_calls == 1
+ entry = usage.details[0]
+ assert entry["type"] == "media"
+ assert entry["call_type"] == call_type
+ assert entry["unit"] == "requests"
+ assert entry["quantity"] == 1.0
+ # The identity is the platform provider id, not a user-configured model
+ # name, so `model` stays empty and rows group on `model_id` alone.
+ assert entry["model"] == ""
+ assert entry["model_id"] == model_id
+ assert entry["provider_tokens"] == 0
+
+
def test_legacy_positional_construction_still_binds_the_same_fields() -> None:
# media_calls must NOT be inserted into the historical positional sequence.
# An existing TokenUsage(input, output, llm_calls, tool_calls, details) call
diff --git a/tests/core/tools/adapters/vibe/test_mcp_adapter.py b/tests/core/tools/adapters/vibe/test_mcp_adapter.py
index d9c5b6316..65c3bb41a 100644
--- a/tests/core/tools/adapters/vibe/test_mcp_adapter.py
+++ b/tests/core/tools/adapters/vibe/test_mcp_adapter.py
@@ -25,6 +25,7 @@ from xagent.core.model.chat.basic.gemini import (
_flatten_json_schema,
_sanitize_schema_for_gemini,
)
+from xagent.core.model.chat.token_context import TokenContextManager
from xagent.core.tools.adapters.vibe import mcp_adapter as mcp_adapter_module
from xagent.core.tools.adapters.vibe.config import (
MCPFailurePolicy,
@@ -64,6 +65,7 @@ from xagent.core.tools.adapters.vibe.tool_naming_limits import (
MAX_AGENT_TOOL_NAME_LENGTH,
)
from xagent.core.tools.core.mcp import tools as mcp_tools_module
+from xagent.core.tools.core.mcp.composio_requests import COMPOSIO_REQUESTS_META_KEY
from xagent.core.tools.core.mcp.tools import _tools_with_raw_annotations
@@ -8271,3 +8273,233 @@ def test_google_slides_thumbnail_download_registration(server_name, expected):
)
assert adapter._workspace_download_field == expected
assert ("durable file_ref" in adapter.description) == (expected is not None)
+
+
+# --- Composio metering -------------------------------------------------------
+
+_COMPOSIO_CONNECTION = {
+ "transport": "stdio",
+ "command": "python",
+ "args": [],
+ # Set by the server config for a connector whose subprocess runs on a
+ # Composio grant; every other server's config omits it.
+ "composio": True,
+}
+
+
+def _composio_adapter(connection: Optional[dict[str, Any]] = None) -> MCPToolAdapter:
+ return MCPToolAdapter(
+ mcp_tool=_mcp_tool(),
+ connection=dict(connection or _COMPOSIO_CONNECTION),
+ name_prefix="mcp_Gmail_",
+ source_server="gmail",
+ )
+
+
+def _session_returning(text: str = "ok", *, meta: Any = None, is_error: bool = False):
+ class _FakeSession:
+ async def initialize(self):
+ return None
+
+ async def call_tool(self, name, arguments, **kwargs):
+ return CallToolResult(
+ content=[TextContent(type="text", text=text)],
+ isError=is_error,
+ _meta=meta,
+ )
+
+ @asynccontextmanager
+ async def _fake_create_session(_connection):
+ yield _FakeSession()
+
+ return _fake_create_session
+
+
+def _assert_composio_rows(details: list[dict[str, Any]], count: int) -> None:
+ assert len(details) == count
+ for row in details:
+ assert row["call_type"] == "composio"
+ assert row["unit"] == "requests"
+ assert row["quantity"] == 1.0
+ assert row["model_id"] == "platform/composio"
+
+
+async def test_a_composio_call_records_one_row_per_accepted_request(monkeypatch):
+ # A Gmail search on a Composio grant lists once and reads one message per
+ # request; the subprocess reports all eleven, and each is one row.
+ monkeypatch.setattr(
+ mcp_adapter_module,
+ "create_session",
+ _session_returning(meta={COMPOSIO_REQUESTS_META_KEY: 11}),
+ )
+ adapter = _composio_adapter()
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is False
+ # The private count the adapter read is not part of the model's result.
+ assert "_composio_requests" not in result
+ _assert_composio_rows(details, 11)
+
+
+async def test_a_composio_call_without_a_reported_count_records_nothing(monkeypatch):
+ monkeypatch.setattr(mcp_adapter_module, "create_session", _session_returning())
+ adapter = _composio_adapter()
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is False
+ assert details == []
+
+
+async def test_a_native_connector_call_ignores_a_reported_count(monkeypatch):
+ # A connector holding its own provider token runs natively: it reaches the
+ # provider directly and is not billed to Composio. A `_meta` count on its
+ # result is not trusted.
+ monkeypatch.setattr(
+ mcp_adapter_module,
+ "create_session",
+ _session_returning(meta={COMPOSIO_REQUESTS_META_KEY: 11}),
+ )
+ native_connection = {
+ key: value for key, value in _COMPOSIO_CONNECTION.items() if key != "composio"
+ }
+ adapter = _composio_adapter(native_connection)
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is False
+ assert details == []
+
+
+async def test_a_composio_call_that_raises_records_nothing(monkeypatch):
+ class _FailingSession:
+ async def initialize(self):
+ return None
+
+ async def call_tool(self, name, arguments, **kwargs):
+ raise RuntimeError("connector failed")
+
+ @asynccontextmanager
+ async def _fake_create_session(_connection):
+ yield _FailingSession()
+
+ monkeypatch.setattr(mcp_adapter_module, "create_session", _fake_create_session)
+ adapter = _composio_adapter()
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is True
+ assert details == []
+
+
+async def test_a_composio_error_result_still_records_the_accepted_requests(monkeypatch):
+ # A call that failed after Composio had accepted requests brings its count
+ # back on the error result; those requests were billed and are recorded.
+ monkeypatch.setattr(
+ mcp_adapter_module,
+ "create_session",
+ _session_returning(
+ "connector failed", meta={COMPOSIO_REQUESTS_META_KEY: 2}, is_error=True
+ ),
+ )
+ adapter = _composio_adapter()
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is True
+ _assert_composio_rows(details, 2)
+
+
+async def test_a_retried_composio_call_counts_only_the_retrys_requests(monkeypatch):
+ """A retry runs in a new subprocess, so its count is the whole bill.
+
+ The failed attempt's accepted requests were not brought back with the
+ exception, and the retry's requests must not be counted twice either.
+ """
+ calls: list[int] = []
+
+ async def _failing_then_retried(_self, connection, tool_args, tool_meta):
+ calls.append(1)
+ raise RuntimeError("first attempt failed")
+
+ monkeypatch.setattr(MCPToolAdapter, "_execute_mcp_call", _failing_then_retried)
+ monkeypatch.setattr(
+ MCPToolAdapter,
+ "_retry_after_authorization_failure",
+ AsyncMock(
+ return_value={
+ "content": [{"text": "ok"}],
+ "is_error": False,
+ "_composio_requests": 3,
+ }
+ ),
+ )
+ adapter = _composio_adapter()
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is False
+ assert len(calls) == 1
+ _assert_composio_rows(details, 3)
+
+
+ "meta",
+ [
+ None,
+ {},
+ {COMPOSIO_REQUESTS_META_KEY: None},
+ {COMPOSIO_REQUESTS_META_KEY: "3"},
+ {COMPOSIO_REQUESTS_META_KEY: 3.0},
+ {COMPOSIO_REQUESTS_META_KEY: -1},
+ {COMPOSIO_REQUESTS_META_KEY: True},
+ {COMPOSIO_REQUESTS_META_KEY: [3]},
+ ],
+ ids=["none", "empty", "null", "str", "float", "negative", "bool", "list"],
+)
+async def test_a_malformed_reported_count_records_nothing(monkeypatch, meta):
+ monkeypatch.setattr(
+ mcp_adapter_module, "create_session", _session_returning(meta=meta)
+ )
+ adapter = _composio_adapter()
+
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async({})
+ details = manager.get_usage().details
+
+ assert result["is_error"] is False
+ assert details == []
+
+
+async def test_composio_metering_without_a_run_context_does_not_raise(monkeypatch):
+ monkeypatch.setattr(
+ mcp_adapter_module,
+ "create_session",
+ _session_returning(meta={COMPOSIO_REQUESTS_META_KEY: 2}),
+ )
+ adapter = _composio_adapter()
+
+ result = await adapter.run_json_async({})
+
+ assert result["is_error"] is False
diff --git a/tests/core/tools/adapters/vibe/test_mcp_error_envelope.py b/tests/core/tools/adapters/vibe/test_mcp_error_envelope.py
index d968015df..ef4235882 100644
--- a/tests/core/tools/adapters/vibe/test_mcp_error_envelope.py
+++ b/tests/core/tools/adapters/vibe/test_mcp_error_envelope.py
@@ -138,11 +138,14 @@ def test_other_connections_do_not_speak_the_envelope(connection):
def _fastmcp_server_modules() -> set[str]:
+ # A module is a server when it constructs ``FastMCP`` or a subclass of it
+ # (``ComposioMeteringFastMCP``). The line that defines such a subclass
+ # constructs nothing, so it does not count.
package_dir = Path(in_repo_servers.__file__).parent
return {
path.stem
for path in package_dir.glob("*.py")
- if re.search(r"\bFastMCP\(", path.read_text(encoding="utf-8"))
+ if re.search(r"(?<!class )\b\w*FastMCP\(", path.read_text(encoding="utf-8"))
}
diff --git a/tests/core/tools/core/test_media_usage_helpers.py b/tests/core/tools/core/test_media_usage_helpers.py
index ab1a377ad..f21dc4119 100644
--- a/tests/core/tools/core/test_media_usage_helpers.py
+++ b/tests/core/tools/core/test_media_usage_helpers.py
@@ -6,20 +6,34 @@ unusable if the same model sometimes reports "seconds" and sometimes
"requests".
"""
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
import pytest
+from xagent.core.model.chat import token_context
from xagent.core.model.chat.token_context import (
MediaCallType,
MediaUnit,
TokenContextManager,
aggregate_media_usage_by_model,
+ get_token_usage,
)
+from xagent.core.tools.core import zhipu_web_search as zhipu_web_search_module
+from xagent.core.tools.core.exa_web_search import ExaWebSearchCore
from xagent.core.tools.core.media_usage import (
+ WEB_SEARCH_MODEL_IDS,
coerce_duration,
record_media_seconds,
record_media_usage,
+ record_web_search_usage,
resolve_billing_model,
)
+from xagent.core.tools.core.tavily_web_search import TavilyWebSearchCore
+from xagent.core.tools.core.web_search import WebSearchCore
+from xagent.core.tools.core.zhipu_web_search import ZhipuWebSearchCore
@pytest.mark.parametrize(
@@ -286,3 +300,260 @@ def test_record_media_seconds_leaves_empty_call_types_to_the_primitive(empty) ->
# Swallowed, not raised, and no half-written row left behind.
assert manager.get_usage().details == []
+
+
+# --- Web search: one row per search the provider accepted ---------------------
+
+# Every provider's id lives in one map; the cores name the provider, never the
+# id. The platform's own search key pays the provider, so the identity is the
+# provider's platform id rather than a user-configured model.
+WEB_SEARCH_PROVIDERS = ["zhipu", "tavily", "exa", "google"]
+
+
+class _ProviderAnswer:
+ """The ``httpx`` response shape the three HTTP cores read."""
+
+ def __init__(
+ self,
+ status_code: int = 200,
+ payload: Any = None,
+ json_error: Exception | None = None,
+ ) -> None:
+ self.status_code = status_code
+ self._payload = payload
+ self._json_error = json_error
+
+ def raise_for_status(self) -> None:
+ if self.status_code < 400:
+ return
+ request = httpx.Request("GET", "https://provider.example.test")
+ raise httpx.HTTPStatusError(
+ "provider error",
+ request=request,
+ response=httpx.Response(self.status_code, request=request),
+ )
+
+ def json(self) -> Any:
+ if self._json_error is not None:
+ raise self._json_error
+ return self._payload
+
+
+class _FakeAsyncClient:
+ """What ``create_public_async_client`` yields, with one fake ``post``."""
+
+ def __init__(self, answer: Any) -> None:
+ self._answer = answer
+
+ async def __aenter__(self) -> "_FakeAsyncClient":
+ return self
+
+ async def __aexit__(self, *exc: Any) -> bool:
+ return False
+
+ async def post(self, *args: Any, **kwargs: Any) -> Any:
+ if isinstance(self._answer, BaseException):
+ raise self._answer
+ return self._answer
+
+
+def _answered(provider: str) -> Any:
+ """A 2xx answer in the shape that provider's core really reads."""
+ if provider == "zhipu":
+ return _ProviderAnswer(
+ 200,
+ {"search_result": [{"title": "t", "link": "https://example.com"}]},
+ )
+ if provider == "exa":
+ return SimpleNamespace(
+ results=[
+ SimpleNamespace(
+ title="t",
+ url="https://example.com",
+ highlights=None,
+ text="",
+ summary="",
+ )
+ ]
+ )
+ if provider == "google":
+ return _ProviderAnswer(
+ 200,
+ {"items": [{"title": "t", "link": "https://example.com", "snippet": "s"}]},
+ )
+ return _ProviderAnswer(
+ 200, {"results": [{"title": "t", "url": "https://example.com", "content": "s"}]}
+ )
+
+
+def _http_mock(answer: Any) -> AsyncMock:
+ if isinstance(answer, BaseException):
+ return AsyncMock(side_effect=answer)
+ return AsyncMock(return_value=answer)
+
+
+async def _search_once(
+ provider: str, answer: Any, *, include_content: bool = False
+) -> None:
+ """Run one real core search with the provider's transport faked.
+
+ ``answer`` is a response object, or an exception the transport raises.
+ """
+ if provider == "google":
+ with patch("httpx.AsyncClient.get", new=_http_mock(answer)):
+ await WebSearchCore(api_key="k", cse_id="c").search(
+ "q", include_content=include_content
+ )
+ return
+ if provider == "tavily":
+ with patch("httpx.AsyncClient.post", new=_http_mock(answer)):
+ await TavilyWebSearchCore(api_key="k").search("q")
+ return
+ if provider == "zhipu":
+ client = _FakeAsyncClient(answer)
+ with patch.object(
+ zhipu_web_search_module,
+ "create_public_async_client",
+ lambda **kwargs: client,
+ ):
+ await ZhipuWebSearchCore(api_key="k").search("q")
+ return
+ client = MagicMock()
+ client.headers = {}
+ if isinstance(answer, BaseException):
+ client.search.side_effect = answer
+ client.search_and_contents.side_effect = answer
+ else:
+ client.search.return_value = answer
+ client.search_and_contents.return_value = answer
+ with patch("exa_py.Exa", return_value=client):
+ await ExaWebSearchCore(api_key="k").search("q")
+
+
[email protected](("provider", "model_id"), sorted(WEB_SEARCH_MODEL_IDS.items()))
+def test_each_provider_has_one_platform_id(provider: str, model_id: str) -> None:
+ assert model_id == f"platform/web-search-{provider}"
+
+
[email protected](("provider", "model_id"), sorted(WEB_SEARCH_MODEL_IDS.items()))
+def test_record_web_search_usage_records_the_provider_id(
+ provider: str, model_id: str
+) -> None:
+ with TokenContextManager() as manager:
+ record_web_search_usage(provider)
+ details = manager.get_usage().details
+
+ assert len(details) == 1
+ assert details[0]["call_type"] == MediaCallType.WEB_SEARCH
+ assert details[0]["unit"] == "requests"
+ assert details[0]["quantity"] == 1.0
+ assert details[0]["model_id"] == model_id
+
+
+def test_an_unknown_web_search_provider_records_nothing() -> None:
+ with TokenContextManager() as manager:
+ record_web_search_usage("not-a-provider")
+ details = manager.get_usage().details
+
+ assert details == []
+
+
[email protected]("provider", WEB_SEARCH_PROVIDERS)
+async def test_a_provider_answer_records_exactly_one_row(provider: str) -> None:
+ with TokenContextManager() as manager:
+ await _search_once(provider, _answered(provider))
+ details = manager.get_usage().details
+
+ assert len(details) == 1
+ assert details[0]["call_type"] == "web_search"
+ assert details[0]["unit"] == "requests"
+ assert details[0]["quantity"] == 1.0
+ assert details[0]["model_id"] == WEB_SEARCH_MODEL_IDS[provider]
+
+
+def _provider_failures() -> list[Any]:
+ """One case per auth/rate/network failure, in each provider's terms."""
+ cases: list[Any] = []
+ for provider in WEB_SEARCH_PROVIDERS:
+ for status in (401, 403, 429):
+ answer: Any
+ if provider == "exa":
+ # The SDK reports these as its own exception, not a response.
+ answer = RuntimeError(f"Exa answered {status}")
+ else:
+ answer = _ProviderAnswer(status)
+ cases.append(pytest.param(provider, answer, id=f"{provider}-{status}"))
+ cases.append(
+ pytest.param(
+ provider, httpx.ConnectError("network down"), id=f"{provider}-network"
+ )
+ )
+ return cases
+
+
[email protected](("provider", "answer"), _provider_failures())
+async def test_a_failed_search_records_nothing(provider: str, answer: Any) -> None:
+ # A missing key, a timeout, an auth failure or an HTTP error means the
+ # provider never billed the request, so there is no call to record. The
+ # search still reports the failure to the model exactly as before.
+ with TokenContextManager() as manager:
+ with pytest.raises(ValueError):
+ await _search_once(provider, answer)
+ details = manager.get_usage().details
+
+ assert details == []
+
+
+def _unreadable_answer(provider: str) -> Any:
+ """A 2xx whose body cannot be turned into results."""
+ if provider == "exa":
+ return SimpleNamespace(results=None)
+ return _ProviderAnswer(200, json_error=ValueError("unusable body"))
+
+
[email protected]("provider", WEB_SEARCH_PROVIDERS)
+async def test_a_2xx_with_an_unreadable_body_is_still_recorded(provider: str) -> None:
+ # The provider billed the request when it answered 2xx, so the row is
+ # written before the body is parsed. A parse failure must not lose it.
+ with TokenContextManager() as manager:
+ with pytest.raises((TypeError, ValueError)):
+ await _search_once(provider, _unreadable_answer(provider))
+ details = manager.get_usage().details
+
+ assert len(details) == 1
+ assert details[0]["model_id"] == WEB_SEARCH_MODEL_IDS[provider]
+
+
+async def test_google_records_before_fetching_page_content() -> None:
+ # include_content fetches a page per result after Google answered. A page
+ # fetch that fails cannot un-bill the search.
+ answer = _answered("google")
+ with patch(
+ "xagent.core.tools.core.web_search.WebContentFetcher.fetch_text",
+ new=AsyncMock(side_effect=RuntimeError("page fetch failed")),
+ ):
+ with TokenContextManager() as manager:
+ with pytest.raises(ValueError):
+ await _search_once("google", answer, include_content=True)
+ details = manager.get_usage().details
+
+ assert len(details) == 1
+ assert details[0]["model_id"] == "platform/web-search-google"
+
+
+def test_search_metering_without_a_run_context_does_not_raise() -> None:
+ # A search can run with nothing bound to report its usage. The row then goes
+ # to the unbound usage, which is what every other media producer does, and
+ # the search itself is unaffected.
+ token_context.token_context.set(None)
+ try:
+ record_web_search_usage("tavily")
+ usage = get_token_usage()
+ finally:
+ token_context.token_context.set(None)
+
+ assert usage.media_calls == 1
diff --git a/tests/web/test_blocking_call_inventory.py b/tests/web/test_blocking_call_inventory.py
index 128437404..1c80d7021 100644
--- a/tests/web/test_blocking_call_inventory.py
+++ b/tests/web/test_blocking_call_inventory.py
@@ -108,6 +108,7 @@ ALLOWED: dict[str, tuple[int, str]] = {
"running execution (load); writes nothing.",
),
"web/tools/config.py": (1, NETWORK),
+ "web/tools/mcp/composio_proxy.py": (1, NETWORK),
"web/tools/mcp/google_api_proxy.py": (1, NETWORK),
"web/tools/mcp/google_slides.py": (3, NETWORK),
"web/tracking/standalone_usage.py": (
diff --git a/tests/web/tools/test_composio_metering.py b/tests/web/tools/test_composio_metering.py
new file mode 100644
index 000000000..f89e38ce1
--- /dev/null
+++ b/tests/web/tools/test_composio_metering.py
@@ -0,0 +1,359 @@
+"""The ``_meta`` count a Composio-backed connector reports on a tool result.
+
+Composio bills each Proxy Execute request, and one tool call can make several.
+The connector subprocess reports how many were accepted so the agent process
+can record that many rows; these tests pin what the server puts on the result,
+including what a call that raises cannot report, that a batch request accepted
+after the batch's deadline still reaches the count, and that a request a batch
+sent whose answer never stops arriving is cut off by its own deadline instead
+of holding the call open, a binary download included.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any
+
+import pytest
+from googleapiclient.discovery import build
+from mcp.shared.memory import create_connected_server_and_client_session
+
+from tests.web.tools.conftest import GMAIL_HOSTS, _Response
+from xagent.core.tools.core.mcp.composio_requests import COMPOSIO_REQUESTS_META_KEY
+from xagent.web.tools.mcp import composio_proxy, google_api_proxy
+from xagent.web.tools.mcp.composio_metering import ComposioMeteringFastMCP
+
+
+def _server() -> ComposioMeteringFastMCP:
+ mcp = ComposioMeteringFastMCP("metering-test")
+
+ @mcp.tool()
+ def accepted_twice() -> str:
+ composio_proxy.record_accepted_request()
+ composio_proxy.record_accepted_request()
+ return "ok"
+
+ @mcp.tool()
+ def accepted_then_raises() -> str:
+ composio_proxy.record_accepted_request()
+ raise RuntimeError("failed after Composio accepted the request")
+
+ @mcp.tool()
+ def accepted_nothing() -> str:
+ return "ok"
+
+ @mcp.tool(structured_output=False)
+ def accepted_without_an_output_schema() -> str:
+ composio_proxy.record_accepted_request()
+ return "ok"
+
+ return mcp
+
+
+async def test_the_result_reports_every_accepted_request() -> None:
+ async with create_connected_server_and_client_session(
+ _server()._mcp_server
+ ) as session:
+ result = await session.call_tool("accepted_twice", {})
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 2}
+
+
+async def test_a_call_that_accepts_nothing_reports_zero() -> None:
+ async with create_connected_server_and_client_session(
+ _server()._mcp_server
+ ) as session:
+ result = await session.call_tool("accepted_nothing", {})
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 0}
+
+
+async def test_a_tool_without_an_output_schema_still_reports_its_count() -> None:
+ """A tool that declares no output schema gets only a content list back.
+
+ FastMCP returns ``(content, structured)`` only when the tool declares an
+ output schema and returns the bare content list otherwise, so both shapes
+ have to come back as a result carrying the count.
+ """
+ async with create_connected_server_and_client_session(
+ _server()._mcp_server
+ ) as session:
+ result = await session.call_tool("accepted_without_an_output_schema", {})
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 1}
+
+
+async def test_a_call_that_raises_loses_its_count() -> None:
+ """A raised tool error becomes an ``isError`` result without the count.
+
+ FastMCP builds that result itself, so the accepted requests before the
+ failure cannot be reported and are under-counted. The tool contract keeps
+ errors as returned payloads where that matters (every Composio connector
+ catches its own errors and returns them).
+ """
+ async with create_connected_server_and_client_session(
+ _server()._mcp_server
+ ) as session:
+ result = await session.call_tool("accepted_then_raises", {})
+
+ assert result.isError is True
+ assert result.meta is None
+
+
+_FILE_BYTES = b"%PDF-1.4 real bytes"
+# Composio's answer for a binary body: the file is not relayed in ``data`` but
+# stored, and its signed URL comes back in ``binary_data``.
+_FILE_ANSWER = {
+ "status": 200,
+ "data": None,
+ "binary_data": {
+ "url": "https://files.composio.dev/signed",
+ "content_type": "application/pdf",
+ "size": len(_FILE_BYTES),
+ },
+}
+
+
+class _DownloadedFile:
+ """The ``public_requests`` response shape a binary download returns."""
+
+ def __init__(self, status_code: int, content: bytes) -> None:
+ self.status_code = status_code
+ self.content = content
+ self.headers: dict[str, str] = {}
+
+
+class _TimedProxy:
+ """The proxy answering each message read after its own delay.
+
+ A message that trickles keeps its answer's body arriving in small pieces
+ for that long: ``requests`` reads the whole body before it returns, and a
+ read timeout does not trip while the pieces keep coming. A message that
+ answers with a file gets Composio's binary envelope instead of data, so the
+ transport downloads it from the signed URL.
+ """
+
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+ self._delays: dict[str, float] = {}
+ self._trickles: dict[str, float] = {}
+ self._files: set[str] = set()
+ self._refusals: set[str] = set()
+ self._lock = threading.Lock()
+
+ def answers_after(self, message_id: str, delay: float) -> None:
+ self._delays[message_id] = delay
+
+ def trickles_for(self, message_id: str, seconds: float) -> None:
+ self._trickles[message_id] = seconds
+
+ def answers_a_file(self, message_id: str) -> None:
+ self._files.add(message_id)
+
+ def refuses_after(self, message_id: str, delay: float) -> None:
+ self._delays[message_id] = delay
+ self._refusals.add(message_id)
+
+ def request(self, **kwargs: Any) -> _Response:
+ message_id = kwargs["json"]["endpoint"].rsplit("/", 1)[-1]
+ with self._lock:
+ self.calls.append(message_id)
+ time.sleep(self._delays.get(message_id, 0.0))
+ trickling_until = time.monotonic() + self._trickles.get(message_id, 0.0)
+ while time.monotonic() < trickling_until:
+ time.sleep(0.02)
+ if message_id in self._refusals:
+ return _Response(500, {"error": {"message": "refused"}})
+ if message_id in self._files:
+ return _Response(200, _FILE_ANSWER)
+ return _Response(200, {"status": 200, "data": {"id": message_id}})
+
+
+def timed_proxy(monkeypatch, composio_env) -> _TimedProxy:
+ """A proxy whose per-message answer delay the test controls."""
+ fake = _TimedProxy()
+ monkeypatch.setattr(composio_proxy.requests, "request", fake.request)
+ return fake
+
+
+def _batch_server(
+ *,
+ deadline: float,
+ max_workers: int = 8,
+ timeout: float = composio_proxy.DEFAULT_TIMEOUT_SECONDS,
+) -> tuple[ComposioMeteringFastMCP, list[tuple[str, Any, Any]]]:
+ """A metered server whose only tool reads the given messages as one batch."""
+ mcp = ComposioMeteringFastMCP("batch-metering-test")
+ seen: list[tuple[str, Any, Any]] = []
+
+ @mcp.tool()
+ def read_messages(messages: list[str]) -> str:
+ """Read the named messages with one proxied batch."""
+ service = build(
+ "gmail",
+ "v1",
+ http=google_api_proxy.GoogleApiProxyHttp(
+ allowed_hosts=GMAIL_HOSTS, timeout=timeout
+ ),
+ static_discovery=True,
+ )
+ batch = service.new_batch_http_request(
+ callback=lambda request_id, response, exception: seen.append(
+ (request_id, response, exception)
+ )
+ )
+ for message_id in messages:
+ batch.add(
+ service.users()
+ .messages()
+ .get(userId="me", id=message_id, format="metadata")
+ )
+ google_api_proxy.execute_batch(
+ batch, max_workers=max_workers, deadline=deadline
+ )
+ return "ok"
+
+ return mcp, seen
+
+
+async def test_a_request_accepted_after_the_deadline_is_counted(timed_proxy):
+ """The batch returns at its deadline, but a request it already sent can
+ still be accepted: that late acceptance must reach the reported count."""
+ timed_proxy.answers_after("m1", 0.0)
+ timed_proxy.answers_after("m2", 0.6)
+ mcp, seen = _batch_server(deadline=0.2)
+
+ async with create_connected_server_and_client_session(mcp._mcp_server) as session:
+ result = await session.call_tool("read_messages", {"messages": ["m1", "m2"]})
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 2}
+ # The tool's own answer is unchanged: the unanswered request timed out.
+ assert [item[0] for item in seen] == ["1", "2"]
+ assert seen[1][1] is None
+ assert isinstance(seen[1][2], TimeoutError)
+
+
+async def test_a_request_refused_after_the_deadline_is_not_counted(timed_proxy):
+ """A late answer that is a Composio refusal is not an accepted request."""
+ timed_proxy.answers_after("m1", 0.0)
+ timed_proxy.refuses_after("m2", 0.6)
+ mcp, seen = _batch_server(deadline=0.2)
+
+ async with create_connected_server_and_client_session(mcp._mcp_server) as session:
+ result = await session.call_tool("read_messages", {"messages": ["m1", "m2"]})
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 1}
+ assert isinstance(seen[1][2], TimeoutError)
+
+
+async def test_a_request_that_never_started_is_not_waited_for(timed_proxy):
+ """Behind one running request the rest of the batch is cancelled and never
+ sent: those requests cannot be accepted, so the call neither waits for
+ them nor counts them."""
+ timed_proxy.answers_after("m1", 0.5)
+ timed_proxy.answers_after("m2", 1.0)
+ timed_proxy.answers_after("m3", 1.0)
+ mcp, _ = _batch_server(deadline=0.2, max_workers=1)
+
+ started = time.monotonic()
+ async with create_connected_server_and_client_session(mcp._mcp_server) as session:
+ result = await session.call_tool(
+ "read_messages", {"messages": ["m1", "m2", "m3"]}
+ )
+ elapsed = time.monotonic() - started
+
+ assert timed_proxy.calls == ["m1"]
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 1}
+ assert elapsed < 1.5, "the cancelled requests must not be waited for"
+
+
+async def test_a_request_that_keeps_trickling_is_cut_off_at_its_deadline(timed_proxy):
+ """A body that keeps arriving in small pieces never trips ``requests``'
+ read timeout, so the request needs an end-to-end deadline of its own: the
+ metered call returns one deadline after its batch, and a request that ran
+ out of time is not counted."""
+ timed_proxy.answers_after("m1", 0.0)
+ timed_proxy.trickles_for("m2", 1.5)
+ mcp, seen = _batch_server(deadline=0.2, timeout=0.3)
+
+ started = time.monotonic()
+ async with create_connected_server_and_client_session(mcp._mcp_server) as session:
+ result = await session.call_tool("read_messages", {"messages": ["m1", "m2"]})
+ elapsed = time.monotonic() - started
+
+ assert sorted(timed_proxy.calls) == ["m1", "m2"]
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 1}
+ # The tool's own answer is unchanged: the trickling request timed out.
+ assert [item[0] for item in seen] == ["1", "2"]
+ assert isinstance(seen[1][2], TimeoutError)
+ assert elapsed < 2 * (0.2 + 0.3), (
+ "the wait must end one proxy deadline after the batch's"
+ )
+
+
+async def test_a_slow_request_inside_its_deadline_still_counts(timed_proxy):
+ """An answer that takes a while but arrives inside the request's deadline
+ is an ordinary accepted request: the tool call succeeds and counts it."""
+ timed_proxy.answers_after("m1", 0.15)
+ mcp, seen = _batch_server(deadline=1.0, timeout=1.0)
+
+ async with create_connected_server_and_client_session(mcp._mcp_server) as session:
+ result = await session.call_tool("read_messages", {"messages": ["m1"]})
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 1}
+ assert seen[0][1] is not None
+ assert seen[0][2] is None
+
+
+async def test_a_binary_download_inside_a_batch_runs_under_its_deadline(
+ timed_proxy, monkeypatch
+):
+ """A Gmail batch has no binary answer of its own, so this drives the
+ transport with one: a batch request's deadline covers a binary answer's
+ download too, so a download that keeps arriving cannot hold the metered
+ call past it. Composio accepted the call before the download, so it is
+ counted."""
+ timed_proxy.answers_a_file("m1")
+
+ def trickling(url: str, timeout: float, **kwargs: Any) -> _DownloadedFile:
+ trickling_until = time.monotonic() + 1.5
+ while time.monotonic() < trickling_until:
+ time.sleep(0.02)
+ return _DownloadedFile(200, _FILE_BYTES)
+
+ monkeypatch.setattr(google_api_proxy.requests, "get", trickling)
+ mcp, seen = _batch_server(deadline=0.2, timeout=0.3)
+
+ started = time.monotonic()
+ async with create_connected_server_and_client_session(mcp._mcp_server) as session:
+ result = await session.call_tool("read_messages", {"messages": ["m1"]})
+ elapsed = time.monotonic() - started
+
+ assert result.isError is False
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 1}
+ # The tool's own answer is unchanged: the request was still downloading
+ # when its batch hit the batch deadline, so it is reported as a timeout.
+ assert seen[0][1] is None
+ assert isinstance(seen[0][2], TimeoutError)
+ assert elapsed < 2 * (0.2 + 0.3), (
+ "the wait must end one proxy deadline after the batch's"
+ )
diff --git a/tests/web/tools/test_composio_proxy.py b/tests/web/tools/test_composio_proxy.py
index 883419759..27a951efc 100644
--- a/tests/web/tools/test_composio_proxy.py
+++ b/tests/web/tools/test_composio_proxy.py
@@ -1541,3 +1541,35 @@ def test_an_account_answer_of_an_unexpected_shape_is_a_composio_error(proxy, pay
assert "no base_url" not in str(raised.value)
assert raised.value.status is None
assert _secrets_in(str(raised.value)) == []
+
+
+def test_a_request_outside_a_batch_is_not_cut_off_at_its_timeout(monkeypatch, proxy):
+ """``requests``' ``timeout`` bounds one connect attempt and each socket
+ read, not the whole exchange. A request sent outside a batch keeps just
+ that: no metered call goes on to wait for it, so a body that keeps arriving
+ is not cut off at an end-to-end deadline."""
+
+ def trickling(**kwargs: Any) -> _Response:
+ trickling_until = time.monotonic() + 0.5
+ while time.monotonic() < trickling_until:
+ time.sleep(0.02)
+ return _Response(200, {"status": 200, "data": {"ok": True}})
+
+ monkeypatch.setattr(composio_proxy.requests, "request", trickling)
+
+ token = composio_proxy.begin_request_count()
+ started = time.monotonic()
+ try:
+ response = composio_proxy.proxy_request(
+ "GET",
+ "https://gmail.googleapis.com/gmail/v1/users/me/profile",
+ allowed_hosts=GMAIL_HOSTS,
+ timeout=0.3,
+ )
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+ elapsed = time.monotonic() - started
+
+ assert (response.status, response.data) == (200, {"ok": True})
+ assert accepted == 1
+ assert elapsed >= 0.5, "the call must not be cut off at its timeout"
diff --git a/tests/web/tools/test_composio_tools.py b/tests/web/tools/test_composio_tools.py
index 290c5eec3..94462a31f 100644
--- a/tests/web/tools/test_composio_tools.py
+++ b/tests/web/tools/test_composio_tools.py
@@ -418,6 +418,40 @@ def test_execute_tool_sends_the_account_the_user_and_the_arguments(http):
assert call["hooks"]["response"] is composio_tools._TOOL_REDIRECT_REFUSAL
+def test_execute_tool_counts_one_accepted_request(http):
+ http.answer(
+ "/tools/execute/GOOGLEDRIVE_CREATE_FILE",
+ 200,
+ {"data": {"id": "drive1"}, "error": None, "successful": True},
+ )
+
+ token = composio_proxy.begin_request_count()
+ try:
+ result = _execute(GOOGLEDRIVE_CREATE_FILE, {"name": "notes.txt"})
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+
+ assert result.successful is True
+ assert accepted == 1
+
+
+def test_a_refused_execute_tool_counts_nothing(http):
+ http.answer(
+ "/tools/execute/GOOGLEDRIVE_CREATE_FILE",
+ 429,
+ {"error": {"message": "rate limited", "slug": "TooManyRequests"}},
+ )
+
+ token = composio_proxy.begin_request_count()
+ try:
+ with pytest.raises(composio_tools.ComposioToolError):
+ _execute(GOOGLEDRIVE_CREATE_FILE, {"name": "notes.txt"})
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+
+ assert accepted == 0
+
+
@pytest.mark.parametrize(
("status", "location"),
[
diff --git a/tests/web/tools/test_gmail_composio.py b/tests/web/tools/test_gmail_composio.py
index 82e24483c..7a18d446b 100644
--- a/tests/web/tools/test_gmail_composio.py
+++ b/tests/web/tools/test_gmail_composio.py
@@ -12,14 +12,17 @@ import base64
import json
import logging
import time
+from contextlib import asynccontextmanager
from email import policy
from email.parser import BytesParser
+from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock
import httplib2
import pytest
from googleapiclient.discovery import build
+from mcp.types import CallToolResult
from tests.web.tools.conftest import (
ACCOUNT_ID,
@@ -27,6 +30,10 @@ from tests.web.tools.conftest import (
COMPOSIO_USER,
_Response,
)
+from xagent.core.model.chat.token_context import TokenContextManager
+from xagent.core.tools.adapters.vibe import mcp_adapter as mcp_adapter_module
+from xagent.core.tools.adapters.vibe.mcp_adapter import MCPToolAdapter
+from xagent.core.tools.core.mcp.composio_requests import COMPOSIO_REQUESTS_META_KEY
from xagent.web.tools import config as tools_config
from xagent.web.tools.mcp import composio_proxy, gmail, google_api_proxy
@@ -339,7 +346,9 @@ def test_read_threads_sends_one_request_per_thread(proxy, monkeypatch):
],
"errors": None,
}
- assert [call["endpoint"] for call in proxy.calls] == [
+ # The two requests are sent concurrently, so the order in which they reach
+ # the proxy is not fixed; only the order of the results is.
+ assert sorted(call["endpoint"] for call in proxy.calls) == [
"https://gmail.googleapis.com/gmail/v1/users/me/threads/t1",
"https://gmail.googleapis.com/gmail/v1/users/me/threads/t2",
]
@@ -1042,3 +1051,164 @@ def test_a_group_send_echoed_with_rewritten_whitespace_stays_bounded(
assert "A" * 64 not in text
assert "@example.com" not in text
assert elapsed < 1.0, "a rewritten echo must not multiply the body's cost"
+
+
+# --- Metering: one usage row per Composio request ----------------------------
+
+
+def _gmail_metering_adapter() -> MCPToolAdapter:
+ return MCPToolAdapter(
+ mcp_tool=SimpleNamespace(
+ name="gmail_search_messages",
+ description="Search Gmail messages",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "max_results": {"type": "integer"},
+ "label_ids": {"type": "array", "items": {"type": "string"}},
+ },
+ },
+ ),
+ connection={
+ "transport": "stdio",
+ "command": "python",
+ "args": [],
+ "composio": True,
+ },
+ name_prefix="mcp_Gmail_",
+ source_server="gmail",
+ )
+
+
+def _session_running_gmail():
+ """A session whose calls run the real Gmail MCP tool in this process."""
+
+ class _GmailSession:
+ async def initialize(self):
+ return None
+
+ async def call_tool(self, name, arguments, **kwargs):
+ return await gmail.mcp.call_tool(name, arguments)
+
+ @asynccontextmanager
+ async def _fake_create_session(_connection):
+ yield _GmailSession()
+
+ return _fake_create_session
+
+
+def _answer_search(proxy, message_ids: list[str]) -> None:
+ """Answer one list request and one metadata read per message id."""
+ for message_id in message_ids:
+ proxy.answer(
+ f"/messages/{message_id}",
+ 200,
+ {**_MESSAGE, "id": message_id, "threadId": f"t-{message_id}"},
+ )
+ proxy.answer("/messages", 200, {"messages": [{"id": m} for m in message_ids]})
+
+
+async def _search_through_the_adapter(monkeypatch, arguments: dict[str, Any]):
+ monkeypatch.setattr(mcp_adapter_module, "create_session", _session_running_gmail())
+ adapter = _gmail_metering_adapter()
+ with TokenContextManager() as manager:
+ result = await adapter.run_json_async(arguments)
+ details = manager.get_usage().details
+ return result, details
+
+
+async def test_the_gmail_result_reports_the_requests_composio_accepted(
+ proxy, monkeypatch
+):
+ _answer_search(proxy, ["msg0", "msg1"])
+ monkeypatch.setattr(gmail, "get_gmail_service", lambda: _proxy_service())
+
+ from mcp.shared.memory import create_connected_server_and_client_session
+
+ async with create_connected_server_and_client_session(
+ gmail.mcp._mcp_server
+ ) as session:
+ result = await session.call_tool("gmail_search_messages", {"max_results": 2})
+
+ assert isinstance(result, CallToolResult)
+ assert result.meta == {COMPOSIO_REQUESTS_META_KEY: 3}
+ assert len(proxy.calls) == 3
+
+
+async def test_a_ten_message_search_records_its_eleven_requests(proxy, monkeypatch):
+ # One list plus one metadata read per message: eleven billed requests.
+ message_ids = [f"msg{number}" for number in range(10)]
+ _answer_search(proxy, message_ids)
+ monkeypatch.setattr(gmail, "get_gmail_service", lambda: _proxy_service())
+
+ result, details = await _search_through_the_adapter(
+ monkeypatch, {"max_results": 10}
+ )
+
+ assert result["is_error"] is False
+ assert len(proxy.calls) == 11
+ assert len(details) == 11
+ assert {row["call_type"] for row in details} == {"composio"}
+ assert {row["unit"] for row in details} == {"requests"}
+ assert {row["quantity"] for row in details} == {1.0}
+ assert {row["model_id"] for row in details} == {"platform/composio"}
+
+
+async def test_a_composio_refusal_records_nothing(proxy, monkeypatch):
+ proxy.answer_with(500, {"error": {"message": "rate limited"}})
+ monkeypatch.setattr(gmail, "get_gmail_service", lambda: _proxy_service())
+
+ result, details = await _search_through_the_adapter(
+ monkeypatch, {"max_results": 10}
+ )
+
+ assert json.loads(result["content"][0]["text"])["status"] == "error"
+ assert len(proxy.calls) == 1
+ assert details == []
+
+
+async def test_a_search_refused_before_sending_records_nothing(proxy, monkeypatch):
+ # Two label ids are refused on a Composio grant before the list request.
+ proxy.answer("/messages", 200, {"messages": []})
+ monkeypatch.setattr(gmail, "get_gmail_service", lambda: _proxy_service())
+
+ result, details = await _search_through_the_adapter(
+ monkeypatch, {"max_results": 1, "label_ids": ["INBOX", "STARRED"]}
+ )
+
+ assert json.loads(result["content"][0]["text"])["status"] == "error"
+ assert proxy.calls == []
+ assert details == []
+
+
+async def test_a_partly_failed_batch_records_only_the_accepted_requests(
+ proxy, monkeypatch
+):
+ # msg0 is read, msg1 answers 404 (Composio accepted and relayed it), and
+ # msg2 is refused by Composio itself. The list and the first two reads are
+ # billed; the refused read is not.
+ proxy.answer(
+ "/messages/msg0", 200, {**_MESSAGE, "id": "msg0", "threadId": "t-msg0"}
+ )
+ proxy.answer("/messages/msg1", 404, _NOT_FOUND)
+ proxy.by_endpoint.append(
+ ("/messages/msg2", _Response(500, {"error": {"message": "rate limited"}}))
+ )
+ proxy.answer(
+ "/messages",
+ 200,
+ {"messages": [{"id": "msg0"}, {"id": "msg1"}, {"id": "msg2"}]},
+ )
+ monkeypatch.setattr(gmail, "get_gmail_service", lambda: _proxy_service())
+
+ result, details = await _search_through_the_adapter(monkeypatch, {"max_results": 3})
+
+ payload = json.loads(result["content"][0]["text"])
+ assert len(payload["errors"]) == 2
+ assert len(proxy.calls) == 4
+ assert len(details) == 3
diff --git a/tests/web/tools/test_google_api_proxy.py b/tests/web/tools/test_google_api_proxy.py
index e7d94115f..e234350ca 100644
--- a/tests/web/tools/test_google_api_proxy.py
+++ b/tests/web/tools/test_google_api_proxy.py
@@ -1168,3 +1168,46 @@ def test_the_transport_can_override_the_shared_body_limit(proxy):
)
assert proxy.calls == []
+
+
+def test_a_single_binary_download_is_not_cut_off_at_its_timeout(proxy, monkeypatch):
+ """A download outside a batch keeps only the ``timeout`` given to
+ ``requests``: nothing waits for that request afterwards, so it is given no
+ end-to-end deadline, and a body that keeps arriving is not cut off."""
+
+ def trickling(url: str, timeout: float, **kwargs: Any) -> _Download:
+ trickling_until = time.monotonic() + 0.5
+ while time.monotonic() < trickling_until:
+ time.sleep(0.02)
+ return _Download(200, b"%PDF-1.4 real bytes")
+
+ monkeypatch.setattr(google_api_proxy.requests, "get", trickling)
+ proxy.answer_with(
+ 200,
+ {
+ "status": 200,
+ "data": None,
+ "binary_data": {
+ "url": "https://files.composio.dev/signed",
+ "content_type": "application/pdf",
+ "size": 19,
+ },
+ },
+ )
+
+ token = composio_proxy.begin_request_count()
+ started = time.monotonic()
+ try:
+ response, content = google_api_proxy.GoogleApiProxyHttp(
+ allowed_hosts=GMAIL_HOSTS, timeout=0.3
+ ).request(
+ "https://gmail.googleapis.com/gmail/v1/users/me/messages/m1/attachments/a"
+ )
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+ elapsed = time.monotonic() - started
+
+ assert response.status == 200
+ assert content == b"%PDF-1.4 real bytes"
+ assert accepted == 1
+ assert elapsed >= 0.5, "the download must not be cut off at its timeout"
diff --git a/tests/web/tools/test_meta_graph.py b/tests/web/tools/test_meta_graph.py
index 903c7cad4..d360c6e2b 100644
--- a/tests/web/tools/test_meta_graph.py
+++ b/tests/web/tools/test_meta_graph.py
@@ -301,6 +301,81 @@ def test_proxy_get_maps_params_to_query_and_sends_no_authorization(
}
+def test_proxy_posts_one_accepted_request(monkeypatch, composio_env):
+ _capture_proxy(monkeypatch, _proxy_response({"id": "fb-user-1"}))
+
+ token = composio_proxy.begin_request_count()
+ try:
+ meta_graph.graph_request("GET", "/me")
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+
+ assert accepted == 1
+
+
+def test_a_refused_proxy_call_accepts_nothing(monkeypatch, composio_env):
+ body = {"error": {"message": "rate limited", "slug": "TooManyRequests"}}
+ _capture_proxy(
+ monkeypatch, MockResponse(body, text=json.dumps(body), status_code=429)
+ )
+
+ token = composio_proxy.begin_request_count()
+ try:
+ with pytest.raises(meta_graph.ComposioProxyError):
+ meta_graph.graph_request("GET", "/me")
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+
+ assert accepted == 0
+
+
+ "body",
+ [
+ {},
+ {"data": {"id": "fb-user-1"}},
+ {"data": {"id": "fb-user-1"}, "status": None},
+ {"data": {"id": "fb-user-1"}, "status": "200"},
+ {"data": {"id": "fb-user-1"}, "status": 200.0},
+ {"data": {"id": "fb-user-1"}, "status": True},
+ ],
+)
+def test_a_proxy_answer_without_an_integer_status_is_refused_and_not_counted(
+ monkeypatch, composio_env, body
+):
+ """An outer 2xx whose envelope has no readable Graph status is not an
+ answer the caller can use, so it adds no accepted request (#3779)."""
+ _capture_proxy(monkeypatch, MockResponse(body, text=json.dumps(body)))
+
+ token = composio_proxy.begin_request_count()
+ try:
+ with pytest.raises(meta_graph.ComposioProxyError) as caught:
+ meta_graph.graph_request("GET", "/me")
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+
+ assert accepted == 0
+ assert "provider's status" in str(caught.value)
+ assert "fb-user-1" not in str(caught.value)
+
+
+def test_a_graph_error_through_the_proxy_is_still_one_accepted_request(
+ monkeypatch, composio_env
+):
+ graph_body = {"error": {"message": "(#100) bad field", "code": 100}}
+ _capture_proxy(monkeypatch, _proxy_response(graph_body, status=400))
+
+ token = composio_proxy.begin_request_count()
+ try:
+ with pytest.raises(meta_graph.GraphAPIError) as caught:
+ meta_graph.graph_request("GET", "/me")
+ finally:
+ accepted = composio_proxy.end_request_count(token)
+
+ assert accepted == 1
+ assert not isinstance(caught.value, meta_graph.ComposioProxyError)
+
+
@pytest.mark.parametrize(
"kwargs, path",
[