Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): faster, concurrent and diagnosable keyless Exa search (#2998)

Call White18aac8404d8b
diff --git a/core/handlers/model_hub/fetch_chain.py b/core/handlers/model_hub/fetch_chain.py
index 021776dc8..456137788 100644
--- a/core/handlers/model_hub/fetch_chain.py
+++ b/core/handlers/model_hub/fetch_chain.py
@@ -28,6 +28,7 @@ from .hosted_executor import ExecutorCall, call_timeout
from .hosted_turn import ExecutorSlot, TurnHostedTools
from .retry import source_identity
from .search_services import ATTEMPT_SECONDS
+from .service_diagnostics import log_service_failure
from vibe.model_hub_runtime.fetch_catalog import fetch_service
@@ -248,23 +249,37 @@ class FetchChain:
async def _service_attempt(self, slot: ExecutorSlot, source, service):
loop = asyncio.get_running_loop()
+ started_at = loop.time()
attempt_deadline = min(self.deadline, loop.time() + ATTEMPT_SECONDS)
if is_keyless_exa_source(source):
remaining = max(0.0, attempt_deadline - loop.time())
try:
- await asyncio.wait_for(self.owner._keyless_exa_attempt_lock.acquire(), timeout=remaining)
+ await asyncio.wait_for(self.owner._keyless_exa_call_semaphore.acquire(), timeout=remaining)
except asyncio.TimeoutError:
+ await log_service_failure(
+ tool=self.call.tool,
+ source_id=slot.source_id,
+ service_id=slot.model_id,
+ outcome="failed",
+ error_code="service_unavailable",
+ response=SearchResponse(None, {}, None, "timeout"),
+ elapsed_ms=round((loop.time() - started_at) * 1000),
+ )
return None, {
"source_id": slot.source_id, "label": source.display_name[:64], "kind": "service",
"outcome": "skipped", "skipped": "service_busy",
}
try:
- return await self._service_attempt_locked(slot, source, service, attempt_deadline=attempt_deadline)
+ return await self._service_attempt_locked(
+ slot, source, service, attempt_deadline=attempt_deadline, started_at=started_at,
+ )
finally:
- self.owner._keyless_exa_attempt_lock.release()
- return await self._service_attempt_locked(slot, source, service, attempt_deadline=attempt_deadline)
+ self.owner._keyless_exa_call_semaphore.release()
+ return await self._service_attempt_locked(
+ slot, source, service, attempt_deadline=attempt_deadline, started_at=started_at,
+ )
- async def _service_attempt_locked(self, slot, source, service, *, attempt_deadline: float):
+ async def _service_attempt_locked(self, slot, source, service, *, attempt_deadline: float, started_at: float):
sent = False
response: SearchResponse | None = None
cooldown_generation = None
@@ -350,6 +365,15 @@ class FetchChain:
if not sent:
if stopped:
raise asyncio.CancelledError
+ await log_service_failure(
+ tool=self.call.tool,
+ source_id=source.id,
+ service_id=slot.model_id,
+ outcome="failed",
+ error_code="service_unavailable",
+ response=response,
+ elapsed_ms=round((asyncio.get_running_loop().time() - started_at) * 1000),
+ )
return None, {
"source_id": slot.source_id, "label": source.display_name[:64], "kind": "service",
"outcome": "skipped", "skipped": "service_busy" if timed_out else "unavailable",
@@ -362,6 +386,16 @@ class FetchChain:
)
if stopped:
result = replace(result, cooling=False)
+ if not stopped and (result.record["status"] != "completed" or response.error == "timeout"):
+ await log_service_failure(
+ tool=self.call.tool,
+ source_id=source.id,
+ service_id=slot.model_id,
+ outcome="failed",
+ error_code=result.record.get("error_code") or "service_unavailable",
+ response=response,
+ elapsed_ms=round((asyncio.get_running_loop().time() - started_at) * 1000),
+ )
await self._settle_owned(source, slot, result, response, cooldown_generation, health_generation, sent)
return result
diff --git a/core/handlers/model_hub/search_chain.py b/core/handlers/model_hub/search_chain.py
index c3e9c053b..bf9c94677 100644
--- a/core/handlers/model_hub/search_chain.py
+++ b/core/handlers/model_hub/search_chain.py
@@ -27,7 +27,14 @@ from .hosted_executor import ExecutorCall, Failure, call_timeout, failed_record
from .hosted_turn import ExecutorSlot, TurnHostedTools
from .resolver import parse_model_hub_timestamp
from .retry import source_identity
-from .search_services import ATTEMPT_SECONDS, ZERO, map_response, search_request
+from .search_services import (
+ ATTEMPT_SECONDS,
+ KEYLESS_EXA_SEARCH_ATTEMPT_SECONDS,
+ ZERO,
+ map_response,
+ search_request,
+)
+from .service_diagnostics import log_service_failure
if TYPE_CHECKING:
from .service import ModelHubService
@@ -218,23 +225,38 @@ class SearchChain:
async def service_attempt(self, slot, source, catalog):
loop = asyncio.get_running_loop()
- attempt_deadline = loop.time() + max(0.0, min(ATTEMPT_SECONDS, self.deadline - loop.time()))
+ started_at = loop.time()
+ budget = KEYLESS_EXA_SEARCH_ATTEMPT_SECONDS if is_keyless_exa_source(source) else ATTEMPT_SECONDS
+ attempt_deadline = loop.time() + max(0.0, min(budget, self.deadline - loop.time()))
if is_keyless_exa_source(source):
remaining = max(0.0, attempt_deadline - loop.time())
try:
- await asyncio.wait_for(self.owner._keyless_exa_attempt_lock.acquire(), timeout=remaining)
+ await asyncio.wait_for(self.owner._keyless_exa_call_semaphore.acquire(), timeout=remaining)
except asyncio.TimeoutError:
+ await log_service_failure(
+ tool=self.call.tool,
+ source_id=slot.source_id,
+ service_id=slot.model_id,
+ outcome="failed",
+ error_code="service_unavailable",
+ response=SearchResponse(None, {}, None, "timeout"),
+ elapsed_ms=round((loop.time() - started_at) * 1000),
+ )
return None, {
"source_id": slot.source_id, "label": source.display_name[:64],
"kind": "service", "outcome": "skipped", "skipped": "unavailable",
}
try:
- return await self._service_attempt_locked(slot, source, catalog, attempt_deadline=attempt_deadline)
+ return await self._service_attempt_locked(
+ slot, source, catalog, attempt_deadline=attempt_deadline, started_at=started_at,
+ )
finally:
- self.owner._keyless_exa_attempt_lock.release()
- return await self._service_attempt_locked(slot, source, catalog, attempt_deadline=attempt_deadline)
+ self.owner._keyless_exa_call_semaphore.release()
+ return await self._service_attempt_locked(
+ slot, source, catalog, attempt_deadline=attempt_deadline, started_at=started_at,
+ )
- async def _service_attempt_locked(self, slot, source, catalog, *, attempt_deadline: float):
+ async def _service_attempt_locked(self, slot, source, catalog, *, attempt_deadline: float, started_at: float):
from .service import _ExecutorAttempt
owner = self.owner
@@ -354,6 +376,16 @@ class SearchChain:
# Stop is not a vendor failure. Keep billing/authentication facts
# but never infer an unreadable response or a retry deadline.
result = replace(result, cooling=False)
+ if not stopped and (result.record["status"] != "completed" or response.error == "timeout"):
+ await log_service_failure(
+ tool=self.call.tool,
+ source_id=source.id,
+ service_id=slot.model_id,
+ outcome="failed",
+ error_code=result.record.get("error_code") or "service_unavailable",
+ response=response,
+ elapsed_ms=round((asyncio.get_running_loop().time() - started_at) * 1000),
+ )
# Queue first, synchronously; stopped calls cannot lose sent usage.
write = owner.usage_writer.record_service(
source_id=source.id, service_id=slot.model_id, billable=result.billable,
@@ -366,14 +398,14 @@ class SearchChain:
current = source if keyless_source else next((s for s in previous.sources if s.id == source.id), None)
identity_current = keyless_source or (current is not None and source_identity(current) == source_identity(source))
health_current = not keyless_source and identity_current and owner._settlement_current(current, health_generation)
- cooldown_current = identity_current and owner._service_cooldowns.current(current, slot.model_id, cooldown_generation)
+ cooldown_admitted = identity_current and owner._service_cooldowns.same_epoch(current, slot.model_id, cooldown_generation)
writes_health = result.blocker is not None or result.authenticated
writes_cooldown = result.cooling or result.record["status"] == "completed"
superseded = (
(health_generation is not None and writes_health and not health_current)
- or (cooldown_generation is not None and writes_cooldown and not cooldown_current)
+ or (cooldown_generation is not None and writes_cooldown and not cooldown_admitted)
)
- if cooldown_current:
+ if cooldown_admitted:
owner._service_cooldowns.settle(current, slot.model_id, cooldown_generation, result, response, ended_at)
if health_current:
state = current.state
diff --git a/core/handlers/model_hub/search_services.py b/core/handlers/model_hub/search_services.py
index b2fd64380..b19047f1d 100644
--- a/core/handlers/model_hub/search_services.py
+++ b/core/handlers/model_hub/search_services.py
@@ -29,6 +29,7 @@ from .hosted_executor import Failure, failed_record
from .retry import retry_after_deadline, source_identity
ATTEMPT_SECONDS = 30.0
+KEYLESS_EXA_SEARCH_ATTEMPT_SECONDS = 15.0
ZERO = HostedCost(basis="list", usd=0)
BLOCKERS = {
"service_key_invalid": "models.source.needs_action.credential_revoked",
@@ -324,9 +325,11 @@ def map_response(
@dataclass
class _Cooldown:
identity: tuple
- generation: int
+ generation: tuple[int, int, int]
+ epoch: int
failures: int = 0
until: datetime | None = None
+ failure_version: int = 0
class ServiceCooldowns:
@@ -338,6 +341,7 @@ class ServiceCooldowns:
def __init__(self) -> None:
self._serial = 0
+ self._failure_version = 0
self._states: dict[tuple[str, str], _Cooldown] = {}
def reconcile(self, config: ModelHubConfig) -> None:
@@ -345,24 +349,39 @@ class ServiceCooldowns:
live.update({source.id: source_identity(source) for source in model_hub_builtin_sources()})
self._states = {key: state for key, state in self._states.items() if live.get(key[0]) == state.identity}
- def advance(self, source: ModelHubSourceConfig, service_id: str, *, clear: bool = False) -> int:
+ def advance(self, source: ModelHubSourceConfig, service_id: str, *, clear: bool = False) -> tuple[int, int, int]:
key = (source.id, service_id)
previous = self._states.get(key)
- self._serial += 1
same = previous is not None and previous.identity == source_identity(source) and not clear
+ epoch = previous.epoch if same else (previous.epoch + 1 if previous is not None else 1)
+ self._serial += 1
+ generation = (epoch, self._serial, self._failure_version)
self._states[key] = _Cooldown(
- source_identity(source), self._serial,
- previous.failures if same else 0, previous.until if same else None,
+ source_identity(source), generation, epoch,
+ previous.failures if same else 0,
+ previous.until if same else None,
+ self._failure_version,
)
- return self._serial
+ return generation
- def generation(self, source: ModelHubSourceConfig, service_id: str) -> int | None:
+ def generation(self, source: ModelHubSourceConfig, service_id: str) -> tuple[int, int, int] | None:
state = self._states.get((source.id, service_id))
return state.generation if state is not None and state.identity == source_identity(source) else None
- def current(self, source: ModelHubSourceConfig, service_id: str, generation: int | None) -> bool:
+ def current(self, source: ModelHubSourceConfig, service_id: str, generation: tuple[int, int, int] | None) -> bool:
return generation is not None and self.generation(source, service_id) == generation
+ def same_epoch(self, source: ModelHubSourceConfig, service_id: str, generation: tuple[int, int, int] | None) -> bool:
+ """Allow concurrent in-flight calls to settle, but not a cleared epoch."""
+
+ state = self._states.get((source.id, service_id))
+ return (
+ generation is not None
+ and state is not None
+ and state.identity == source_identity(source)
+ and state.epoch == generation[0]
+ )
+
def until(self, source: ModelHubSourceConfig, service_id: str, now: datetime) -> datetime | None:
state = self._states.get((source.id, service_id))
if state is not None and state.identity == source_identity(source) and state.until is not None and state.until > now:
@@ -370,16 +389,16 @@ class ServiceCooldowns:
return None
def settle(
- self, source: ModelHubSourceConfig, service_id: str, generation: int,
+ self, source: ModelHubSourceConfig, service_id: str, generation: tuple[int, int, int],
result: ServiceResult, response: SearchResponse, now: datetime,
) -> bool:
- if not self.current(source, service_id, generation):
+ if not self.same_epoch(source, service_id, generation):
return False
state = self._states[(source.id, service_id)]
if result.cooling:
state.failures = min(state.failures + 1, 5)
- advice = None
received_at = response.response_received_at or now
+ advice = None
value = next((v for k, v in response.headers.items() if k.lower() == "retry-after"), None)
advice = retry_after_deadline(value, received_at)
reset = next((v for k, v in response.headers.items() if k.lower() == "x-ratelimit-reset"), None)
@@ -387,8 +406,18 @@ class ServiceCooldowns:
if reset_deadline is not None and (advice is None or reset_deadline > advice):
advice = reset_deadline
base_seconds = 60 if source.vendor == "jina-reader" else 30
- state.until = advice if advice is not None else now + timedelta(seconds=min(base_seconds * 2 ** (state.failures - 1), 300))
+ candidate_until = advice if advice is not None else now + timedelta(seconds=min(base_seconds * 2 ** (state.failures - 1), 300))
+ if state.until is None or state.until <= now or candidate_until > state.until:
+ state.until = candidate_until
+ self._failure_version += 1
+ state.failure_version = self._failure_version
elif result.record["status"] == "completed":
- state.failures = 0
- state.until = None
+ active = state.until is not None and state.until > now
+ # A call admitted before a concurrent failure must not clear the
+ # shared cooldown that the failure published after its admission.
+ published_after_admission = state.failure_version != generation[2]
+ if not active or not published_after_admission:
+ state.failures = 0
+ state.until = None
+ state.failure_version = self._failure_version
return True
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index dbe99ea0a..33a7c5dd7 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -1608,7 +1608,9 @@ class ModelHubService:
self._search_trial_identities: dict[str, tuple] = {}
self._search_reenable_checks: dict[str, asyncio.Task] = {}
self._service_cooldowns = ServiceCooldowns()
- self._keyless_exa_attempt_lock = asyncio.Lock()
+ # Exa's anonymous endpoint is per-IP limited; cap active MCP calls
+ # without serializing a turn or the session's independent JSON-RPC ids.
+ self._keyless_exa_call_semaphore = asyncio.Semaphore(3)
self._jina_fetch_sent_at: deque[datetime] = deque()
self._local_fetch_engine = None
self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATION
diff --git a/core/handlers/model_hub/service_diagnostics.py b/core/handlers/model_hub/service_diagnostics.py
new file mode 100644
index 000000000..6b6b2a429
--- /dev/null
+++ b/core/handlers/model_hub/service_diagnostics.py
@@ -0,0 +1,150 @@
+"""Redacted diagnostics for failed hosted service attempts.
+
+This module deliberately inspects only bounded transport envelopes and emits
+stable fields. It never includes the request arguments or response content.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections.abc import Mapping
+from typing import Any
+
+from .adapter import SearchResponse
+
+
+logger = logging.getLogger(__name__)
+_JSONRPC_ERROR_CODE_FIELD = "code"
+
+
+def _safe_field(value: object) -> str:
+ """Keep a structured log field on one line without carrying user text."""
+
+ return str(value).replace("\r", " ").replace("\n", " ")[:128]
+
+
+def _json_objects(body: bytes | None) -> tuple[Mapping[str, Any], ...]:
+ if not body:
+ return ()
+ try:
+ text = body.decode("utf-8")
+ except UnicodeDecodeError:
+ return ()
+ values: list[Mapping[str, Any]] = []
+ try:
+ value = json.loads(text)
+ except (json.JSONDecodeError, RecursionError):
+ value = None
+ if isinstance(value, Mapping):
+ values.append(value)
+ for line in text.splitlines():
+ if not line.startswith("data:"):
+ continue
+ data = line[5:].strip()
+ if not data or data == "[DONE]":
+ continue
+ try:
+ value = json.loads(data)
+ except (json.JSONDecodeError, RecursionError):
+ continue
+ if isinstance(value, Mapping):
+ values.append(value)
+ return tuple(values)
+
+
+def _jsonrpc_error_code(values: tuple[Mapping[str, Any], ...]) -> str | None:
+ for value in values:
+ error = value.get("error")
+ if not isinstance(error, Mapping):
+ continue
+ code = error.get(_JSONRPC_ERROR_CODE_FIELD)
+ if isinstance(code, (str, int)) and not isinstance(code, bool):
+ return _safe_field(code)
+ return None
+
+
+def _mcp_is_error(values: tuple[Mapping[str, Any], ...]) -> bool:
+ return any(
+ isinstance(value.get("result"), Mapping) and value["result"].get("isError") is True
+ for value in values
+ )
+
+
+def transport_cause(response: SearchResponse) -> str:
+ """Return transport facts only, never provider prose or request content."""
+
+ if response.error:
+ return _safe_field(response.error)
+ values = _json_objects(response.body)
+ if (code := _jsonrpc_error_code(values)) is not None:
+ return f"jsonrpc_error={code}"
+ if _mcp_is_error(values):
+ return "mcp_isError=true"
+ if response.http_status is not None:
+ return f"http_status={response.http_status}"
+ return "unknown"
+
+
+async def log_service_failure(
+ *,
+ tool: str,
+ source_id: str,
+ service_id: str,
+ outcome: str,
+ error_code: str,
+ response: SearchResponse,
+ elapsed_ms: int,
+) -> None:
+ """Emit one redacted warning without parsing the response on the event loop."""
+
+ await asyncio.to_thread(
+ _write_service_failure,
+ tool=tool,
+ source_id=source_id,
+ service_id=service_id,
+ outcome=outcome,
+ error_code=error_code,
+ response=response,
+ elapsed_ms=elapsed_ms,
+ )
+
+
+def _write_service_failure(
+ *,
+ tool: str,
+ source_id: str,
+ service_id: str,
+ outcome: str,
+ error_code: str,
+ response: SearchResponse,
+ elapsed_ms: int,
+) -> None:
+ """Write exactly one redacted warning for one failed service attempt."""
+
+ phase = next(
+ (value for name, value in response.headers.items() if name.lower() == "x-avibe-mcp-phase"),
+ None,
+ )
+ message = (
+ "Model Hub service attempt failed "
+ "tool=%s source_id=%s service_id=%s outcome=%s error_code=%s "
+ "transport_cause=%s elapsed_ms=%d"
+ )
+ values: list[Any] = [
+ _safe_field(tool),
+ _safe_field(source_id),
+ _safe_field(service_id),
+ _safe_field(outcome),
+ _safe_field(error_code),
+ transport_cause(response),
+ max(0, int(elapsed_ms)),
+ ]
+ if phase is not None:
+ message += " phase=%s"
+ values.append(_safe_field(phase))
+ logger.warning(message, *values)
+
+
+__all__ = ["log_service_failure", "transport_cause"]
diff --git a/core/hosted_activity.py b/core/hosted_activity.py
index 8124c2c61..4772cfbf6 100644
--- a/core/hosted_activity.py
+++ b/core/hosted_activity.py
@@ -480,6 +480,8 @@ def _attempts_cost(attempts: tuple[HostedAttemptView, ...]) -> tuple[Optional[Ho
reported = bool(nonzero) and all(cost.basis == "reported" for cost in nonzero)
estimate = reported and any(cost.estimate for cost in nonzero)
usd = round(sum(cost.usd or 0.0 for cost in priced), 6)
+ if usd == 0 and unpriced:
+ return None, False
return HostedCost(basis="reported" if reported else "list", usd=usd, estimate=True if estimate else None), unpriced
@@ -601,8 +603,11 @@ def _chain_cost(execution: Optional[ProxyExecution]) -> tuple[Optional[HostedCos
priced = [cost for cost in known if cost.basis != "included"]
if not priced:
return (HostedCost(basis="included"), False) if known and not unpriced else (None, False)
+ total = round(sum(cost.usd or 0.0 for cost in priced), 6)
+ if total == 0 and unpriced:
+ return None, False
basis = "reported" if all(cost.basis == "reported" for cost in priced) else "list"
- return HostedCost(basis=basis, usd=round(sum(cost.usd or 0.0 for cost in priced), 6)), unpriced
+ return HostedCost(basis=basis, usd=total), unpriced
def _runner_label(activity: HostedActivity, lang: str, escape: Callable[[str], str]) -> Optional[str]:
diff --git a/docs/plans/web-fetch-gateway-delivery.md b/docs/plans/web-fetch-gateway-delivery.md
index 1c49ae970..c6816229b 100644
--- a/docs/plans/web-fetch-gateway-delivery.md
+++ b/docs/plans/web-fetch-gateway-delivery.md
@@ -45,14 +45,14 @@ response → settlement lifecycle. Boundary tests now own these invariants:
| --- | --- |
| Activation boundary | Global flag rejects stale turns before local or configured transport admission. Configured providers became eligible only with #2976; WF-3 exercises defaults without flag-on test patches. |
| Admission | Every service submission re-gates only the original URL; a refusal stops forwarding but retains usage for earlier sent attempts. |
-| Attempt ownership | One capped deadline starts before the shared Exa lock, includes subsequent transport work, and allows Jina fallback on expiry. |
+| Attempt ownership | One capped deadline starts before keyless Exa admission, includes bounded setup/semaphore wait and subsequent transport work, and allows Jina fallback on expiry. |
| No-send | Disabled/unavailable/contended/over-budget candidates have only skipped facts, no usage, no capability success and no cooldown write. |
| Shared health | The actual sent callback carries the cooldown generation into settlement; stale generations cannot overwrite newer search/fetch state. Built-ins never reserve or write credential health. |
| Scope | Catalog MCP refusals precede generic errors; target failures/refusals never cool the service. Service failures and 429 do, honoring server advice. Jina's no-advice backoff starts at 60 seconds. |
| Protocol vs document | Top-level JSON-RPC errors, tool errors and missing/wrong-shaped result payloads are service faults unless a recognized target/refusal/rate signal overrides them. Valid JSON alone is not a successful envelope. Successful text documents (including JSON/scalars/error-looking prose) remain literal content. Search and fetch reuse the error-shaped MCP rate-limit classifier. |
| Truncation | An extractor's `content_overflow` survives normalization into the stored budget-truncation fact and model-facing marker, even when sanitization leaves fewer than 48,000 bytes. |
| Accounting | Every sent local/keyless attempt, including cancellation and failure, has exactly one zero-cost fetch usage row; mapping/settlement survive cancellation. |
-| MCP transport | Search and fetch reuse one session; fetch sends `urls` and the explicit character bound, rejects missing controls/unknown required inputs before `tools/call`, and handles JSON/SSE. |
+| MCP transport | Search and fetch reuse one session; setup is single-flight, concurrent tool calls use independent JSON-RPC ids under the small keyless-call cap, fetch sends `urls` and the explicit character bound, rejects missing controls/unknown required inputs before `tools/call`, and handles JSON/SSE. |
Primary tests: `tests/test_model_hub_fetch_chain.py` and the real loopback MCP
fixture in `tests/test_model_hub_keyless_exa.py`. Existing search-chain and fetch
diff --git a/docs/plans/web-fetch.md b/docs/plans/web-fetch.md
index ff099e133..c4c90eb01 100644
--- a/docs/plans/web-fetch.md
+++ b/docs/plans/web-fetch.md
@@ -494,11 +494,14 @@ fetch transient cooldown is not model-routing health.
### 5.4 Keyless Exa and Jina
-**Exa:** reuse #2924 §§3/5/6/9 for identity, session lock, schema refresh,
-SSE/JSON-RPC parsing, deadlines, admission and shared cooldown. Fetch-specific
-failure scope in §6 explicitly overrides #2924 §5.3/§6's generic `isError` /
-cooldown classification, not the shared identity or cooldown used for genuine
-service failures.
+**Exa:** reuse #2924 §§3/5/6/9 for identity, session setup, schema cache,
+SSE/JSON-RPC parsing, deadlines, admission and shared cooldown. Session
+establishment (`initialize`, `notifications/initialized`, and `tools/list`) is
+single-flight, while `tools/call` requests run concurrently by JSON-RPC id
+under the small per-runtime keyless-call cap. Fetch-specific failure scope in
+§6 explicitly overrides #2924 §5.3/§6's generic `isError` / cooldown
+classification, not the shared identity or cooldown used for genuine service
+failures.
Endpoint
is `https://mcp.exa.ai/mcp?tools=web_search_advanced_exa,web_fetch_exa`; do not
create another session keyed by tool or revert search to `web_search_exa`.
diff --git a/docs/plans/web-search-keyless-exa.md b/docs/plans/web-search-keyless-exa.md
index fcec07366..dad412598 100644
--- a/docs/plans/web-search-keyless-exa.md
+++ b/docs/plans/web-search-keyless-exa.md
@@ -498,13 +498,14 @@ runtime, endpoint, authentication mode, and honest client identity—not per
MCP tool name. This makes the same initialized client reusable for the phase-2
`web_fetch_exa` tool without creating a second session or rate-limit burst. It
is not written to disk and is not shared with another runtime. A per-session
-async lock spans session lookup or creation, initialize,
-`notifications/initialized`, `tools/list`, schema invalidation, and
-`tools/call`; lock wait consumes the same overall 30-second service deadline.
-At most one tool call is admitted for a session at a time, which avoids
-response association and burst surprises without adding a scheduler.
+async lock covers only session establishment (`initialize`,
+`notifications/initialized`, and the first `tools/list`) plus any required
+schema refresh. Once setup is ready, `tools/call` requests run concurrently
+under independent JSON-RPC ids; the service layer caps active keyless Exa
+calls at three per runtime to respect the shared per-IP limit.
-The first call, within the one service attempt's existing 30-second cap, does:
+The first call, within the one service attempt's existing **15-second search**
+cap (or the designed **30-second fetch** cap), does:
1. connect over HTTPS to the pinned `mcp.exa.ai` host;
2. send MCP `initialize` with the supported protocol version, no capabilities
@@ -523,21 +524,19 @@ its conforming HTTP 202 response with an empty body as success. Do not apply
that empty-body exception to `initialize`, `tools/list`, or `tools/call`, which
must return a matching JSON-RPC response.
-Later calls reuse the session, but each admitted search refreshes `tools/list`
-under the same lock before mapping arguments; this bounded refresh is the
-authoritative protection against schema changes when no idle receive stream is
-open. It is not a new search request and does not increment usage. A
-`notifications/tools/list_changed` message received in any active response
-stream still invalidates the cache immediately, so the next call's mandatory
-refresh uses the new schema. A missing/expired session is reinitialized once
-before the request. If a session-bound `notifications/initialized`,
-`tools/list`, or `tools/call` exchange receives the MCP session-not-found
-response (the standard HTTP 404/session error, not an endpoint/protocol 404),
-clear the stale session, initialize again, resend `notifications/initialized`,
-and replay the affected pre-tool request once within the original deadline;
-this is safe because the server has not accepted the tool call. Once the
-replay's `tools/call` request bytes begin, Avibe never retries it automatically:
-a retry could duplicate a search and a usage request.
+Later calls reuse the session and cached `tools/list`; a warm call sends no
+second listing. A `notifications/tools/list_changed` message, a re-established
+session, or a tool-call schema error invalidates the cache, and the next call
+refreshes it under the setup lock before mapping arguments. The refresh is not
+a new search request and does not increment usage. A missing/expired session is
+reinitialized once before the request. If a session-bound
+`notifications/initialized`, `tools/list`, or `tools/call` exchange receives
+the MCP session-not-found response (the standard HTTP 404/session error, not
+an endpoint/protocol 404), clear the stale session, initialize again, resend
+`notifications/initialized`, and replay the affected pre-tool request once
+within the original deadline; this is safe because the server has not accepted
+the tool call. Once the replay's `tools/call` request bytes begin, Avibe never
+retries it automatically: a retry could duplicate a search and a usage request.
Every exchange uses `Accept: application/json, text/event-stream`,
`Content-Type: application/json`, and the retained negotiated
@@ -546,11 +545,12 @@ Every exchange uses `Accept: application/json, text/event-stream`,
`event: message` / `data: <JSON-RPC>` shape and a single `application/json`
JSON-RPC response, matching the response id in either form. A
`notifications/tools/list_changed` notification is not discarded as
-unrelated: it invalidates any cached schema, and the next call's mandatory
-`tools/list` refresh runs before building arguments. The implementation does
-not depend on an always-open idle receive stream; the bounded per-call refresh
-is the correctness rule. The 8 MiB existing response-body cap applies to either
-response form; notifications are processed only within that cap.
+unrelated: it invalidates any cached schema, and the next call refreshes
+`tools/list` before building arguments. A schema error from `tools/call` uses
+the same invalidation path. The implementation does not depend on an always-
+open idle receive stream; the cached session schema remains authoritative until
+one of these invalidation events. The 8 MiB existing response-body cap applies
+to either response form; notifications are processed only within that cap.
No API key, bearer token, Vault reference, or user credential is present in the
MCP request. The adapter is still the custody/transport boundary and returns
@@ -585,11 +585,12 @@ highlight and `textMaxCharacters` controls, classify the service as
`service_unavailable` rather than silently switching to the ambiguous text
formatter.
-Use a single overall 30-second service deadline, including a cold-session
-initialize/list. Connection/TLS setup has the existing 5-second transport
-budget; each subsequent exchange receives only the remaining deadline. A
-reused session gives the `tools/call` the full remaining 30 seconds. The
-search chain's single 180-second budget remains authoritative.
+Use a **15-second** overall search service deadline, including a cold-session
+initialize/list and any capped admission wait. Fetch keeps its designed
+**30-second** service deadline. Connection/TLS setup has the existing 5-second
+transport budget; each exchange receives only the remaining deadline. A warm
+session gives `tools/call` the remaining budget without another `tools/list`.
+The search chain's single 180-second budget remains authoritative.
### 5.3 Response mapping
@@ -918,16 +919,17 @@ coordinated activation; no lane merges this design PR.
turn/service and mapped to advanced `numResults`; the adapter sends only the
selected highlight controls and never forwards model-supplied filters,
summaries, or crawl fields.
-6. A reused MCP session performs one initialize lifecycle and one bounded
- `tools/list` refresh before each attempted tool call; cold starts serialize
- that lifecycle under the session lock; the negotiated protocol version is
- validated and reused; `tools/list_changed` causes a fresh list before the
- next call; an expired session can reinitialize and replay once only before
- the server accepts the tool call, but an admitted call is never automatically
- duplicated. The same session/client boundary is reusable for
- `web_fetch_exa` in phase 2.
-7. All service work fits the existing 30-second service cap and 180-second
- chain deadline; no blocking parse runs on the controller loop.
+6. A reused MCP session performs one initialize lifecycle and caches one
+ `tools/list` response for the session; setup is single-flight, while
+ `tools/call` requests are concurrent under a three-call per-runtime cap; the
+ negotiated protocol version is validated and reused; `tools/list_changed`,
+ re-establishment, or a schema error causes a fresh list; an expired session
+ can reinitialize and replay once only before the server accepts the tool
+ call, but an admitted call is never automatically duplicated. The same
+ session/client boundary is reusable for `web_fetch_exa` in phase 2.
+7. Keyless Exa search work fits its 15-second service cap, fetch retains its
+ 30-second cap, and both retain the 180-second chain deadline; no blocking
+ parse runs on the controller loop.
8. Valid results are highlights-only, bounded, ordered, and become one
canonical completed record. The advanced adapter requests at most the
defensive one-character text field, ignores it, and never requests or
@@ -970,16 +972,22 @@ JSON-RPC fixtures:
- `web_fetch_exa` is a phase-2 parser fixture only; the shared session/client
boundary accepts it as a second validated tool without a second initialize or
session key; no phase-2 production activation is implied by the test.
-- Session reuse sends one initialize and one `tools/list` refresh per search for
- two searches; an expired session returns the standard session-not-found 404
+- Session reuse sends one initialize lifecycle and one `tools/list` total for
+ two warm calls; an expired session returns the standard session-not-found 404
during initialization notification or before the tool call, reinitializes,
resends the notification, and reconnects/replays the affected pre-tool
request once before admission; a connection failure after the call is sent is
- not retried.
+ not retried. The stub also proves keep-alive connection reuse and two
+ concurrent `tools/call` ids after one setup.
- The stub can emit `notifications/tools/list_changed`; the cached schema is
invalidated and the next call performs `tools/list` before mapping arguments.
-- Two parallel cold starts share one initialize/list lifecycle under the lock,
- and lock wait consumes the service deadline.
+- The service-chain fixtures prove at most three keyless Exa calls are active,
+ that search uses a 15-second attempt cap, and that a cooldown published by
+ one attempt is visible to new admissions without allowing an in-flight call
+ to clear it.
+- Two parallel cold starts share one initialize/list lifecycle under the setup
+ lock; calls do not queue behind a turn-wide lock, and semaphore wait consumes
+ the service attempt deadline.
- The transport fixture covers both SSE and direct `application/json` JSON-RPC
responses.
- HTTP 429 with `Retry-After`, HTTP 429 with reset headers (including
diff --git a/tests/test_hosted_activity.py b/tests/test_hosted_activity.py
index a0b1873db..6edde91ef 100644
--- a/tests/test_hosted_activity.py
+++ b/tests/test_hosted_activity.py
@@ -818,11 +818,31 @@ def test_a_search_services_card_and_line_say_the_same_in_both_languages(case):
id="keyless after a paid attempt keeps the paid total",
),
pytest.param(
- (_tried(TAVILY, "completed"), _tried(KEYLESS, "completed", usd=0.0)), _service_ran(KEYLESS, "exa-mcp", 0.0), "completed",
- {"executor_kind": "service", "source_id": KEYLESS, "source_name": "Exa", "provider": "exa-mcp"},
- {"basis": "list", "usd": 0, "calls": 1, "at_least": True}, "at least $0",
- id="keyless with an unknown earlier charge is not free",
+ (_tried(KEYLESS, error_code="service_unavailable", usd=0.0),
+ _tried(DEEPSEEK, "completed", kind="model")),
+ ProxyExecution(
+ executor_origin=Origin(provider="deepseek", api="openai_chat", model="deepseek-chat"),
+ executor_source_id=DEEPSEEK,
+ executor_billing="metered",
+ cost=None,
+ ), "completed",
+ {"executor_kind": "model", "source_id": DEEPSEEK, "source_name": "DeepSeek", "provider": "deepseek", "model": "deepseek-chat"},
+ None, None,
+ id="a free failed attempt does not become at least zero",
),
+ pytest.param(
+ (_tried(TAVILY, error_code="service_unavailable", usd=0.008),
+ _tried(DEEPSEEK, "completed", kind="model")),
+ ProxyExecution(
+ executor_origin=Origin(provider="deepseek", api="openai_chat", model="deepseek-chat"),
+ executor_source_id=DEEPSEEK,
+ executor_billing="metered",
+ cost=None,
+ ), "completed", {"executor_kind": "model", "source_id": DEEPSEEK, "source_name": "DeepSeek", "provider": "deepseek", "model": "deepseek-chat"},
+ {"basis": "list", "usd": 0.008, "calls": 1, "at_least": True}, "at least ≈ $0.008",
+ id="a priced failed attempt remains a lower bound beside an unpriced success",
+ ),
+
pytest.param(
None, _service_ran(TAVILY, "tavily", 0.008), "completed",
{"executor_kind": "service", "source_id": TAVILY, "source_name": "Tavily", "provider": "tavily"},
diff --git a/tests/test_model_hub_fetch_chain.py b/tests/test_model_hub_fetch_chain.py
index 4a8a0f04b..edf72888c 100644
--- a/tests/test_model_hub_fetch_chain.py
+++ b/tests/test_model_hub_fetch_chain.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import json
+import logging
import threading
from dataclasses import replace
from datetime import timedelta
@@ -128,6 +129,39 @@ async def test_flag_off_rejects_configured_fetch_from_a_previously_frozen_turn(t
assert calls == []
+async def test_failed_fetch_service_attempt_logs_redacted_transport_facts(tmp_path, caplog):
+ service, config = _service(
+ tmp_path, enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False}, order=(FREE_EXA,),
+ )
+ caplog.set_level(logging.WARNING, logger="core.handlers.model_hub.service_diagnostics")
+
+ async def fetch(*args, on_sent):
+ await on_sent()
+ return SearchResponse(
+ 200,
+ {"x-avibe-mcp-phase": "tools_call"},
+ json.dumps({"result": {"isError": True, "content": [{"type": "text", "text": "secret page body"}]}}).encode(),
+ )
+
+ service.adapter.fetch = fetch
+ await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://secret.example/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ records = [record for record in caplog.records if record.name == "core.handlers.model_hub.service_diagnostics"]
+ assert len(records) == 1
+ message = records[0].getMessage()
+ assert "tool=web_fetch" in message
+ assert "source_id=src_exakeyless" in message
+ assert "service_id=exa/mcp" in message
+ assert "outcome=failed" in message
+ assert "error_code=service_unavailable" in message
+ assert "transport_cause=mcp_isError=true" in message
+ assert "phase=tools_call" in message
+ assert "secret.example" not in message and "secret page body" not in message
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("sid,status,body,expected,delay", [
(FREE_EXA, 429, {}, "service_rate_limited", 600),
@@ -206,13 +240,15 @@ async def test_stale_keyless_fetch_cannot_overwrite_a_newer_shared_generation(tm
@pytest.mark.asyncio
@pytest.mark.parametrize("release_lock", [False, True])
-async def test_keyless_attempt_deadline_includes_lock_wait_and_allows_jina_fallback(tmp_path, monkeypatch, release_lock):
- """The original chain consumed 180s in the lock; resetting 30s after admission is also wrong."""
+async def test_keyless_attempt_deadline_includes_semaphore_wait_and_allows_jina_fallback(tmp_path, monkeypatch, release_lock):
+ """The capped semaphore wait consumes the fetch attempt budget without serializing all calls."""
monkeypatch.setattr(fetch_chain_module, "ATTEMPT_SECONDS", 0.3, raising=False)
service, config = _service(
tmp_path, enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: True}, order=(FREE_EXA, JINA),
)
- await service._keyless_exa_attempt_lock.acquire()
+ semaphore = service._keyless_exa_call_semaphore
+ for _ in range(3):
+ await semaphore.acquire()
sent = []
async def fetch(source_id, *args, on_sent):
@@ -226,7 +262,10 @@ async def test_keyless_attempt_deadline_includes_lock_wait_and_allows_jina_fallb
return SearchResponse(200, {}, json.dumps(body).encode())
service.adapter.fetch = fetch
- release_handle = asyncio.get_running_loop().call_later(0.12, service._keyless_exa_attempt_lock.release) if release_lock else None
+ def release_one():
+ semaphore.release()
+
+ release_handle = asyncio.get_running_loop().call_later(0.12, release_one) if release_lock else None
try:
result = await asyncio.wait_for(service.run_hosted_tool(
"web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=service.freeze_turn_hosted_tools(config),
@@ -234,8 +273,8 @@ async def test_keyless_attempt_deadline_includes_lock_wait_and_allows_jina_fallb
finally:
if release_handle:
release_handle.cancel()
- if service._keyless_exa_attempt_lock.locked():
- service._keyless_exa_attempt_lock.release()
+ for _ in range(3):
+ semaphore.release()
assert result["record"]["content"] == "Jina fallback"
first = result["record"]["attempts"][0]
assert first["outcome"] == ("failed" if release_lock else "skipped")
diff --git a/tests/test_model_hub_keyless_exa.py b/tests/test_model_hub_keyless_exa.py
index d386005ca..eb14f0e61 100644
--- a/tests/test_model_hub_keyless_exa.py
+++ b/tests/test_model_hub_keyless_exa.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import json
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
@@ -11,6 +12,7 @@ import pytest
from core.handlers.model_hub.adapter import SearchResponse
from core.handlers.model_hub.search_services import ServiceCooldowns, map_response
+from core.handlers.model_hub.service_diagnostics import transport_cause
from config.v2_config import model_hub_keyless_exa_source
from vibe.model_hub_runtime.api_key_vendors import search_service
from vibe.model_hub_runtime.keyless_exa_mcp import KeylessExaMcpClient
@@ -21,6 +23,11 @@ SERVICE = search_service("exa-mcp", "search")
assert SERVICE is not None
+def test_service_diagnostics_reads_jsonrpc_error_from_sse_without_content() -> None:
+ body = b'event: message\ndata: {"jsonrpc":"2.0","id":1,"error":{"code":-32001,"message":"secret body"}}\n\n'
+ assert transport_cause(SearchResponse(200, {}, body)) == "jsonrpc_error=-32001"
+
+
def _rpc(request_id: int, result: object) -> dict:
return {"jsonrpc": "2.0", "id": request_id, "result": result}
@@ -56,7 +63,7 @@ async def _mcp_stub(
async def handle(request: web.Request) -> web.StreamResponse:
payload = await request.json()
- calls.append({"headers": dict(request.headers), "payload": payload})
+ calls.append({"connection": id(request.transport), "headers": dict(request.headers), "payload": payload})
method = payload["method"]
request_id = payload.get("id")
if method == "initialize":
@@ -135,6 +142,7 @@ async def test_keyless_mcp_negotiates_once_adapts_live_schema_and_maps_highlight
},
on_sent=lambda: sent.append(True),
)
+ await client.close()
assert [call["payload"]["method"] for call in calls] == [
"initialize", "notifications/initialized", "tools/list", "tools/call",
@@ -177,9 +185,11 @@ async def test_fetch_reuses_search_mcp_session_and_sends_explicit_page_bound(sse
await client.search({"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1})
sent = []
response = await client.fetch({"urls": ["https://example.com/"], "maxCharacters": 48000}, on_sent=lambda: sent.append(True))
+ await client.close()
assert [call["payload"]["method"] for call in calls] == [
- "initialize", "notifications/initialized", "tools/list", "tools/call", "tools/list", "tools/call",
+ "initialize", "notifications/initialized", "tools/list", "tools/call", "tools/call",
]
+ assert len({call["connection"] for call in calls}) == 1
assert calls[-1]["headers"]["Mcp-Session-Id"] == calls[-3]["headers"]["Mcp-Session-Id"]
assert calls[-1]["payload"]["params"] == {
"name": "web_fetch_exa", "arguments": {"urls": ["https://example.com/"], "maxCharacters": 48000},
@@ -205,7 +215,9 @@ async def test_fetch_incompatible_live_schema_or_arguments_never_send(variant):
arguments.pop("urls")
async with _mcp_stub(fetch_schema=schema) as (endpoint, calls):
sent = []
- response = await KeylessExaMcpClient(endpoint=endpoint).fetch(arguments, on_sent=lambda: sent.append(True))
+ client = KeylessExaMcpClient(endpoint=endpoint)
+ response = await client.fetch(arguments, on_sent=lambda: sent.append(True))
+ await client.close()
assert response.error == "invalid_endpoint"
assert sent == []
assert [call["payload"]["method"] for call in calls] == ["initialize", "notifications/initialized", "tools/list"]
@@ -215,7 +227,9 @@ async def test_fetch_incompatible_live_schema_or_arguments_never_send(variant):
async def test_keyless_mcp_does_not_continue_after_initialized_transport_error() -> None:
"""KEX-2: notification transport failures stop the handshake before tools/list."""
async with _mcp_stub(notification_status=500) as (endpoint, calls):
- response = await KeylessExaMcpClient(endpoint=endpoint).search({"query": "avibe"})
+ client = KeylessExaMcpClient(endpoint=endpoint)
+ response = await client.search({"query": "avibe"})
+ await client.close()
assert response.http_status == 500
assert [call["payload"]["method"] for call in calls] == ["initialize", "notifications/initialized"]
@@ -227,6 +241,7 @@ async def test_keyless_mcp_discards_session_after_invalid_initialization() -> No
client = KeylessExaMcpClient(endpoint=endpoint)
first = await client.search({"query": "first"})
second = await client.search({"query": "second", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1})
+ await client.close()
assert first.error == "connection"
assert second.http_status == 200
assert [call["payload"]["method"] for call in calls] == [
@@ -235,16 +250,35 @@ async def test_keyless_mcp_discards_session_after_invalid_initialization() -> No
@pytest.mark.asyncio
-async def test_keyless_mcp_refreshes_tools_schema_for_each_search_on_one_session() -> None:
- """KEX-2: a reused session still refreshes tools/list before every admitted search."""
+async def test_keyless_mcp_caches_tools_schema_for_warm_searches_on_one_session() -> None:
+ """KEX-2: a warm session caches tools/list until the server invalidates it."""
async with _mcp_stub() as (endpoint, calls):
client = KeylessExaMcpClient(endpoint=endpoint, client_version="test")
arguments = {"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1}
await client.search(arguments)
await client.search(arguments)
+ await client.close()
assert [call["payload"]["method"] for call in calls] == [
- "initialize", "notifications/initialized", "tools/list", "tools/call", "tools/list", "tools/call",
+ "initialize", "notifications/initialized", "tools/list", "tools/call", "tools/call",
]
+ assert len({call["connection"] for call in calls}) == 1
+
+
+async def test_keyless_mcp_parallel_calls_share_setup_but_not_tool_calls() -> None:
+ """KEX-2: setup is single-flight; independent JSON-RPC calls run concurrently."""
+ async with _mcp_stub() as (endpoint, calls):
+ client = KeylessExaMcpClient(endpoint=endpoint, client_version="test")
+ arguments = {"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1}
+ responses = await asyncio.gather(client.search(arguments), client.search(arguments))
+ await client.close()
+ assert all(response.http_status == 200 for response in responses)
+ methods = [call["payload"]["method"] for call in calls]
+ assert methods[:3] == ["initialize", "notifications/initialized", "tools/list"]
+ assert methods.count("initialize") == methods.count("tools/list") == 1
+ tool_calls = [call for call in calls if call["payload"]["method"] == "tools/call"]
+ assert len(tool_calls) == 2
+ assert len({call["payload"]["id"] for call in tool_calls}) == 2
@pytest.mark.asyncio
@@ -257,6 +291,7 @@ async def test_keyless_mcp_replays_one_stale_pre_tool_session_without_double_cou
{"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1},
on_sent=lambda: admitted.append(True),
)
+ await client.close()
assert response.http_status == 200
assert admitted == [True]
assert [call["payload"]["method"] for call in calls] == [
@@ -269,7 +304,9 @@ async def test_keyless_mcp_replays_one_stale_pre_tool_session_without_double_cou
async def test_keyless_mcp_rejects_a_schema_without_text_bound_before_tools_call() -> None:
"""KEX-2: a missing required highlight/text control is unavailable without sending a call."""
async with _mcp_stub(missing="textMaxCharacters") as (endpoint, calls):
- response = await KeylessExaMcpClient(endpoint=endpoint).search({"query": "avibe", "numResults": 3})
+ client = KeylessExaMcpClient(endpoint=endpoint)
+ response = await client.search({"query": "avibe", "numResults": 3})
+ await client.close()
assert response.error == "invalid_endpoint"
assert [call["payload"]["method"] for call in calls] == [
"initialize", "notifications/initialized", "tools/list",
@@ -314,3 +351,19 @@ def test_keyless_cooldown_prefers_later_epoch_millisecond_reset() -> None:
)
assert cooldowns.settle(source, "exa/mcp", generation, result, SearchResponse(429, {"Retry-After": "5", "X-RateLimit-Reset": str(int(later.timestamp() * 1000))}, b"{}", response_received_at=NOW), NOW)
assert cooldowns.until(source, "exa/mcp", NOW) == later
+
+
+def test_keyless_cooldown_keeps_longest_concurrent_deadline() -> None:
+ """A later concurrent failure must not shorten an explicit provider deadline."""
+ source = model_hub_keyless_exa_source()
+ cooldowns = ServiceCooldowns()
+ first_generation = cooldowns.advance(source, "exa/mcp")
+ first_response = SearchResponse(429, {"Retry-After": "120"}, b"{}", response_received_at=NOW)
+ first_result = map_response(SERVICE, first_response, sent=True, results=3, say=lambda key, **_: key)
+ assert cooldowns.settle(source, "exa/mcp", first_generation, first_result, first_response, NOW)
+
+ second_generation = cooldowns.advance(source, "exa/mcp")
+ second_response = SearchResponse(503, {}, b"{}", response_received_at=NOW)
+ second_result = map_response(SERVICE, second_response, sent=True, results=3, say=lambda key, **_: key)
+ assert cooldowns.settle(source, "exa/mcp", second_generation, second_result, second_response, NOW)
+ assert cooldowns.until(source, "exa/mcp", NOW) == NOW + timedelta(seconds=120)
diff --git a/tests/test_model_hub_search_chain.py b/tests/test_model_hub_search_chain.py
index 8773d5c60..601279299 100644
--- a/tests/test_model_hub_search_chain.py
+++ b/tests/test_model_hub_search_chain.py
@@ -8,6 +8,7 @@ settlement, C-1 serialization and metering; only the credential adapter is faked
import asyncio
import copy
import json
+import logging
import threading
from dataclasses import replace
from datetime import timedelta
@@ -388,8 +389,8 @@ async def test_keyless_rate_limit_settles_service_cooldown_without_persisted_sou
@pytest.mark.asyncio
-async def test_keyless_overlapping_searches_settle_rate_limit_before_next_admission(tmp_path, monkeypatch):
- """KEX-2: a queued keyless turn cannot invalidate the active cooldown generation."""
+async def test_keyless_parallel_searches_preserve_cooldown_after_failure(tmp_path, monkeypatch):
+ """KEX-2: concurrent calls do not serialize, and a failure remains shared after a success."""
service = owner(
tmp_path,
(),
@@ -402,6 +403,7 @@ async def test_keyless_overlapping_searches_settle_rate_limit_before_next_admiss
)
entered = asyncio.Event()
release = asyncio.Event()
+ second_entered = asyncio.Event()
calls = []
async def search(source_id, vendor, service_id, credential_ref, request, *, on_sent):
@@ -411,23 +413,79 @@ async def test_keyless_overlapping_searches_settle_rate_limit_before_next_admiss
entered.set()
await release.wait()
return wire(429, {"error": {"message": "slow down"}}, headers={"Retry-After": "60"})
- raise AssertionError("queued keyless search reached the adapter")
+ second_entered.set()
+ await release.wait()
+ return wire()
monkeypatch.setattr(service.adapter, "search", search, raising=False)
active = asyncio.create_task(run(service))
await entered.wait()
queued = asyncio.create_task(run(service))
- await asyncio.sleep(0)
+ await second_entered.wait()
release.set()
first, second = await asyncio.gather(active, queued)
- assert calls == [(KEYLESS_EXA_SOURCE_ID, KEYLESS_EXA_SERVICE_ID)]
+ assert len(calls) == 2
assert first["record"]["attempts"][0]["error_code"] == "service_rate_limited"
- assert second["record"]["attempts"][0]["skipped"] == "cooling"
+ assert second["record"]["status"] == "completed"
+ assert service._service_cooldowns.until(model_hub_keyless_exa_source(), KEYLESS_EXA_SERVICE_ID, NOW) is not None
+
+
+async def test_failed_keyless_service_attempt_logs_redacted_transport_facts(tmp_path, monkeypatch, caplog):
+ service = owner(
+ tmp_path,
+ (),
+ include_keyless=True,
+ web={
+ "executor_order": [KEYLESS_EXA_SOURCE_ID],
+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},
+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},
+ },
+ )
+ caplog.set_level(logging.WARNING, logger="core.handlers.model_hub.service_diagnostics")
+ response = wire(
+ 200,
+ {"jsonrpc": "2.0", "id": 1, "error": {"code": -32001, "message": "secret query body"}},
+ headers={"x-avibe-mcp-phase": "tools_call"},
+ )
+ answers(monkeypatch, service, response)
+ await run(service, query="secret query")
+ records = [record for record in caplog.records if record.name == "core.handlers.model_hub.service_diagnostics"]
+ assert len(records) == 1
+ message = records[0].getMessage()
+ assert records[0].levelno == logging.WARNING
+ assert "tool=web_search" in message
+ assert "source_id=src_exakeyless" in message
+ assert "service_id=exa/mcp" in message
+ assert "outcome=failed" in message
+ assert "error_code=service_unavailable" in message
+ assert "transport_cause=jsonrpc_error=-32001" in message
+ assert "elapsed_ms=" in message
+ assert "phase=tools_call" in message
+ assert "secret query" not in message and "secret query body" not in message
+
+
+async def test_failed_keyed_service_attempt_logs_http_status_without_body(tmp_path, monkeypatch, caplog):
+ service = owner(tmp_path, ("tavily",))
+ caplog.set_level(logging.WARNING, logger="core.handlers.model_hub.service_diagnostics")
+ answers(monkeypatch, service, wire(503, {"detail": "secret body for query"}))
+ await run(service, query="secret query")
+ records = [record for record in caplog.records if record.name == "core.handlers.model_hub.service_diagnostics"]
+ assert len(records) == 1
+ message = records[0].getMessage()
+ assert "tool=web_search" in message
+ assert "source_id=src_tavily01" in message
+ assert "service_id=tavily/search" in message
+ assert "error_code=service_unavailable" in message
+ assert "transport_cause=http_status=503" in message
+ assert "phase=" not in message
+ assert "secret query" not in message and "secret body for query" not in message
@pytest.mark.asyncio
async def test_keyless_queued_waiter_times_out_before_admission(tmp_path, monkeypatch):
- """KEX-2: lock wait consumes the attempt budget and never sends a keyless request."""
+ """KEX-2: the capped semaphore wait consumes the attempt budget and never sends a fourth call."""
service = owner(
tmp_path,
(),
@@ -438,13 +496,16 @@ async def test_keyless_queued_waiter_times_out_before_admission(tmp_path, monkey
"services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},
},
)
- monkeypatch.setattr(search_chain, "ATTEMPT_SECONDS", 0.01)
- await service._keyless_exa_attempt_lock.acquire()
+ monkeypatch.setattr(search_chain, "KEYLESS_EXA_SEARCH_ATTEMPT_SECONDS", 0.01)
+ semaphore = service._keyless_exa_call_semaphore
+ for _ in range(3):
+ await semaphore.acquire()
calls = answers(monkeypatch, service, wire())
try:
result = await run(service)
finally:
- service._keyless_exa_attempt_lock.release()
+ for _ in range(3):
+ semaphore.release()
assert calls == []
assert result["record"]["attempts"] == [{
"source_id": KEYLESS_EXA_SOURCE_ID, "label": "Exa (free)", "kind": "service",
@@ -452,6 +513,124 @@ async def test_keyless_queued_waiter_times_out_before_admission(tmp_path, monkey
}]
+async def test_keyless_attempts_run_concurrently_up_to_the_small_cap(tmp_path, monkeypatch):
+ service = owner(
+ tmp_path,
+ (),
+ include_keyless=True,
+ web={
+ "executor_order": [KEYLESS_EXA_SOURCE_ID],
+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},
+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},
+ },
+ )
+ monkeypatch.setattr(search_chain, "call_timeout", lambda tool: 1)
+ active = maximum = 0
+ entered = []
+
+ async def search(*args, on_sent):
+ nonlocal active, maximum
+ await on_sent()
+ active += 1
+ maximum = max(maximum, active)
+ entered.append(True)
+ await asyncio.sleep(0.05)
+ active -= 1
+ return wire()
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ results = await asyncio.gather(*(run(service, query=f"query-{index}") for index in range(4)))
+ assert all(result["record"]["status"] == "completed" for result in results)
+ assert len(entered) == 4
+ assert maximum == 3
+
+
+async def test_keyless_inflight_success_does_not_clear_a_published_shared_cooldown(tmp_path, monkeypatch):
+ service = owner(
+ tmp_path,
+ (),
+ include_keyless=True,
+ web={
+ "executor_order": [KEYLESS_EXA_SOURCE_ID],
+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},
+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},
+ },
+ )
+ started = asyncio.Event()
+ first_release = asyncio.Event()
+ second_release = asyncio.Event()
+ calls = 0
+
+ async def search(*args, on_sent):
+ nonlocal calls
+ await on_sent()
+ calls += 1
+ index = calls
+ if calls == 2:
+ started.set()
+ if index == 1:
+ await first_release.wait()
+ return wire(503, {"error": {"message": "temporary"}})
+ await second_release.wait()
+ return wire()
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ first = asyncio.create_task(run(service, query="first"))
+ second = asyncio.create_task(run(service, query="second"))
+ await asyncio.wait_for(started.wait(), timeout=1)
+ first_release.set()
+ first_result = await first
+ source = model_hub_keyless_exa_source()
+ assert first_result["record"]["error_code"] == "service_unavailable"
+ assert service._service_cooldowns.until(source, KEYLESS_EXA_SERVICE_ID, NOW) is not None
+ second_release.set()
+ second_result = await second
+ assert second_result["record"]["status"] == "completed"
+ assert service._service_cooldowns.until(source, KEYLESS_EXA_SERVICE_ID, NOW) is not None
+ third = await run(service, query="after-cooldown")
+ assert third["record"]["attempts"][0]["skipped"] == "cooling"
+ assert calls == 2
+
+ service = owner(
+ tmp_path,
+ (),
+ include_keyless=True,
+ web={
+ "executor_order": [KEYLESS_EXA_SOURCE_ID],
+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},
+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},
+ },
+ )
+ success_release = asyncio.Event()
+ failure_started = asyncio.Event()
+ calls = 0
+
+ async def success_then_failure(*args, on_sent):
+ nonlocal calls
+ await on_sent()
+ calls += 1
+ if calls == 1:
+ await success_release.wait()
+ return wire()
+ failure_started.set()
+ return wire(503, {"error": {"message": "temporary"}})
+
+ monkeypatch.setattr(service.adapter, "search", success_then_failure, raising=False)
+ success = asyncio.create_task(run(service, query="success-first"))
+ failure = asyncio.create_task(run(service, query="failure-second"))
+ await asyncio.wait_for(failure_started.wait(), timeout=1)
+ failure_result = await failure
+ assert failure_result["record"]["error_code"] == "service_unavailable"
+ assert service._service_cooldowns.until(source, KEYLESS_EXA_SERVICE_ID, NOW) is not None
+ success_release.set()
+ success_result = await success
+ assert success_result["record"]["status"] == "completed"
+ assert service._service_cooldowns.until(source, KEYLESS_EXA_SERVICE_ID, NOW) is not None
+ assert (await run(service, query="after-success-settlement"))["record"]["attempts"][0]["skipped"] == "cooling"
+
+
@pytest.mark.asyncio
async def test_keyless_retry_branch_accepts_the_synthetic_source(tmp_path):
"""KEX-3: a built-in cooldown clears without a credential Source or network call."""
diff --git a/ui/src/components/workbench/HostedToolRow.test.tsx b/ui/src/components/workbench/HostedToolRow.test.tsx
index ff428ab97..24b536300 100644
--- a/ui/src/components/workbench/HostedToolRow.test.tsx
+++ b/ui/src/components/workbench/HostedToolRow.test.tsx
@@ -309,6 +309,20 @@ describe('search service cards', () => {
expect(document.body.textContent).not.toMatch(/\/search/);
});
+ it('does not render an exact zero lower bound as a price', () => {
+ const card = {
+ ...services.service_completed.payload,
+ call_id: 'call_unknown_zero',
+ source_id: 'src_exakeyless',
+ source_name: 'Exa',
+ provider: 'exa-mcp',
+ executor_kind: 'service',
+ cost: { basis: 'list', calls: 1, usd: 0, at_least: true },
+ };
+ renderGroup([card], 'en');
+ expect(row('call_unknown_zero').textContent).not.toMatch(/at least|\$0/);
+ });
+
it('says who ran it, and reads a reason this client does not know yet as a failure', () => {
renderGroup([
services.service_completed.payload,
diff --git a/ui/src/components/workbench/HostedToolRow.tsx b/ui/src/components/workbench/HostedToolRow.tsx
index bafea8c72..e29c16416 100644
--- a/ui/src/components/workbench/HostedToolRow.tsx
+++ b/ui/src/components/workbench/HostedToolRow.tsx
@@ -97,7 +97,7 @@ const formatBytes = (bytes: number): string =>
const useHostedCost = (card: HostedActivity): string | null => {
const { t } = useTranslation();
const cost = card.cost;
- if (!cost) return null;
+ if (!cost || (cost.at_least && cost.usd === 0)) return null;
const figure = builtinKey(card.source_id) && cost.usd === 0 && !cost.at_least
? t('chat.agentActivity.hosted.cost.free') as string
: cost.basis === 'included'
diff --git a/ui/src/lib/hostedActivity.ts b/ui/src/lib/hostedActivity.ts
index a1fe21baa..e83ea240b 100644
--- a/ui/src/lib/hostedActivity.ts
+++ b/ui/src/lib/hostedActivity.ts
@@ -150,7 +150,7 @@ export const hostedActivityFrom = (raw: unknown): HostedActivity | undefined =>
if (typeof card.tool !== 'string' || !TOOLS.includes(card.tool)) return undefined;
if (card.mode !== 'native' && card.mode !== 'proxy' && card.mode !== 'direct') return undefined;
if (typeof card.status !== 'string' || !STATUSES.includes(card.status)) return undefined;
- return {
+ const projected = {
...(card as unknown as HostedActivity),
sources: Array.isArray(card.sources) ? (card.sources as HostedActivitySource[]).filter((s) => typeof s?.url === 'string' || typeof s?.title === 'string') : [],
images: Array.isArray(card.images) ? (card.images as HostedActivityImage[]).filter((i) => typeof i?.path === 'string') : [],
@@ -159,6 +159,12 @@ export const hostedActivityFrom = (raw: unknown): HostedActivity | undefined =>
switch: switchFrom(card.switch),
fetch: fetchFrom(card.fetch),
};
+ // A lower bound of exactly $0 carries no useful price information. Keep the
+ // reader aligned with the owner by treating it as unknown rather than showing
+ // "at least $0".
+ if (projected.cost?.at_least && projected.cost.usd === 0) delete projected.cost;
+ return projected;
+
};
/**
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 4acbfe8e4..4fafd4e74 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -1899,6 +1899,7 @@ class CLIProxyEngineAdapter:
raise
except Exception: # noqa: BLE001
pass
+ await self._keyless_exa_client.close()
await asyncio.to_thread(self.supervisor.stop)
async def status(self) -> EngineStatus:
diff --git a/vibe/model_hub_runtime/keyless_exa_mcp.py b/vibe/model_hub_runtime/keyless_exa_mcp.py
index 5fa568489..3db0f667d 100644
--- a/vibe/model_hub_runtime/keyless_exa_mcp.py
+++ b/vibe/model_hub_runtime/keyless_exa_mcp.py
@@ -43,6 +43,7 @@ class _Exchange:
received_at: datetime | None = None
messages: tuple[Mapping[str, Any], ...] = ()
request_id: int | None = None
+ phase: str | None = None
def _parse_messages(body: bytes | None) -> tuple[Mapping[str, Any], ...]:
@@ -122,7 +123,7 @@ def _tool_properties(
class KeylessExaMcpClient:
- """One serialized MCP session, reusable by Exa search and future fetch."""
+ """Reusable MCP session with single-flight setup and concurrent tool calls."""
def __init__(
self,
@@ -136,11 +137,48 @@ class KeylessExaMcpClient:
self.client_version = client_version
self.timeout_seconds = timeout_seconds
self.connect_timeout_seconds = connect_timeout_seconds
- self._lock = asyncio.Lock()
+ self._setup_lock = asyncio.Lock()
self._session_id: str | None = None
self._protocol_version: str | None = None
self._tools: dict[str, Mapping[str, Any]] | None = None
self._next_id = 0
+ self._http_session: aiohttp.ClientSession | None = None
+ self._trace_config = aiohttp.TraceConfig()
+ self._trace_config.on_request_headers_sent.append(self._on_request_headers_sent)
+
+ @staticmethod
+ async def _on_request_headers_sent(_session, trace_ctx, _params) -> None:
+ request_ctx = getattr(trace_ctx, "trace_request_ctx", None)
+ if not isinstance(request_ctx, Mapping):
+ return
+ callback = request_ctx.get("on_sent")
+ callback_state = request_ctx.get("callback_state")
+ if not callable(callback) or not isinstance(callback_state, dict) or callback_state.get("called"):
+ return
+ admission = callback()
+ if inspect.isawaitable(admission):
+ await admission
+ callback_state["called"] = True
+
+ async def _http(self) -> aiohttp.ClientSession:
+ session = self._http_session
+ if session is None or session.closed:
+ session = aiohttp.ClientSession(
+ timeout=aiohttp.ClientTimeout(total=self.timeout_seconds),
+ connector=aiohttp.TCPConnector(limit=10, force_close=False),
+ trust_env=False,
+ trace_configs=[self._trace_config],
+ )
+ self._http_session = session
+ return session
+
+ async def close(self) -> None:
+ """Close the keep-alive client at runtime shutdown."""
+
+ session, self._http_session = self._http_session, None
+ self._clear_session()
+ if session is not None and not session.closed:
+ await session.close()
def _request_id(self) -> int:
self._next_id += 1
@@ -165,7 +203,7 @@ class KeylessExaMcpClient:
notification: bool = False,
) -> _Exchange:
if time.monotonic() >= deadline:
- return _Exchange(None, {}, None, "timeout")
+ return _Exchange(None, {}, None, "timeout", phase=method)
request_id = None if notification else self._request_id()
payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
if request_id is not None:
@@ -182,76 +220,70 @@ class KeylessExaMcpClient:
}
if self._session_id is not None:
headers[MCP_SESSION_HEADER] = self._session_id
- callback_called = False
+ callback_state = {"called": False}
response_status: int | None = None
response_headers: dict[str, str] = {}
response_received_at: datetime | None = None
-
timeout_total = max(0.001, deadline - time.monotonic())
timeout = aiohttp.ClientTimeout(
total=timeout_total,
connect=min(self.connect_timeout_seconds, timeout_total),
)
-
- class McpRequest(aiohttp.ClientRequest):
- async def send(self, conn):
- nonlocal callback_called
- if not callback_called and on_sent is not None:
- admission = on_sent()
- if inspect.isawaitable(admission):
- await admission
- callback_called = True
- return await super().send(conn)
+ trace_request_ctx = (
+ {"on_sent": on_sent, "callback_state": callback_state}
+ if on_sent is not None else None
+ )
try:
- async with aiohttp.ClientSession(
+ session = await self._http()
+ async with session.post(
+ self.endpoint,
+ headers=headers,
+ json=payload,
+ allow_redirects=False,
timeout=timeout,
- trust_env=False,
- request_class=McpRequest,
- ) as session:
- async with session.post(
- self.endpoint,
- headers=headers,
- json=payload,
- allow_redirects=False,
- ) as response:
- response_status = response.status
- response_received_at = datetime.now(timezone.utc)
- response_headers = {
- name: value
- for name, value in response.headers.items()
- if name.lower() in {
- "content-type", "retry-after", "x-ratelimit-reset", "mcp-session-id", "date", "content-length",
- }
+ trace_request_ctx=trace_request_ctx,
+ ) as response:
+ response_status = response.status
+ response_received_at = datetime.now(timezone.utc)
+ response_headers = {
+ name: value
+ for name, value in response.headers.items()
+ if name.lower() in {
+ "content-type", "retry-after", "x-ratelimit-reset", "mcp-session-id", "date", "content-length",
}
- body, too_large = await _read_bounded(response.content)
- if too_large:
- return _Exchange(
- response_status, response_headers, None, "body_too_large", callback_called,
- response_received_at, request_id=request_id,
- )
- messages = await asyncio.to_thread(_parse_messages, body)
- if request_id is not None and not messages and body:
- # Preserve malformed/opaque errors for the service mapper.
- return _Exchange(
- response_status, response_headers, body, "", callback_called,
- response_received_at, request_id=request_id,
- )
+ }
+ body, too_large = await _read_bounded(response.content)
+ if too_large:
return _Exchange(
- response_status, response_headers, body, "", callback_called,
- response_received_at, messages, request_id,
+ response_status, response_headers, None, "body_too_large", callback_state["called"],
+ response_received_at, request_id=request_id, phase=method,
)
+ messages = await asyncio.to_thread(_parse_messages, body)
+ if request_id is not None and not messages and body:
+ # Preserve malformed/opaque errors for the service mapper.
+ return _Exchange(
+ response_status, response_headers, body, "", callback_state["called"],
+ response_received_at, request_id=request_id, phase=method,
+ )
+ return _Exchange(
+ response_status, response_headers, body, "", callback_state["called"],
+ response_received_at, messages, request_id, method,
+ )
except asyncio.CancelledError:
return _Exchange(
- response_status, response_headers, None, "cancelled", callback_called, response_received_at,
+ response_status, response_headers, None, "cancelled", callback_state["called"],
+ response_received_at, phase=method,
)
except asyncio.TimeoutError:
return _Exchange(
- response_status, response_headers, None, "timeout", callback_called, response_received_at,
+ response_status, response_headers, None, "timeout", callback_state["called"],
+ response_received_at, phase=method,
)
- except (aiohttp.ClientError, OSError, ValueError):
+ except (aiohttp.ClientError, OSError, RuntimeError, ValueError):
return _Exchange(
- response_status, response_headers, None, "connection", callback_called, response_received_at,
+ response_status, response_headers, None, "connection", callback_state["called"],
+ response_received_at, phase=method,
)
async def _initialize(self, *, deadline: float) -> _Exchange:
@@ -277,7 +309,7 @@ class KeylessExaMcpClient:
if exchange.status == 200 and exchange.messages and not exchange.error:
return _Exchange(
exchange.status, exchange.headers, exchange.body, "connection", exchange.sent,
- exchange.received_at, exchange.messages, exchange.request_id,
+ exchange.received_at, exchange.messages, exchange.request_id, exchange.phase,
)
return exchange
self._protocol_version = protocol
@@ -313,6 +345,30 @@ class KeylessExaMcpClient:
self._tools = tools
return None
+ async def _ensure_ready(self, *, deadline: float) -> _Exchange | None:
+ """Single-flight only the session setup and cached schema refresh."""
+
+ async with self._setup_lock:
+ if self._session_id is None:
+ initialized = await self._initialize(deadline=deadline)
+ if initialized.error or initialized.status != 200 or self._session_id is None:
+ return initialized
+ if self._tools is None:
+ return await self._list_tools(deadline=deadline)
+ return None
+
+ async def _clear_if_stale(self, session_id: str | None) -> None:
+ async with self._setup_lock:
+ if session_id is None or self._session_id == session_id:
+ self._clear_session()
+
+ @staticmethod
+ def _schema_changed(exchange: _Exchange) -> bool:
+ message = _matching_message(exchange.messages, exchange.request_id) if exchange.request_id is not None else None
+ error = message.get("error") if isinstance(message, Mapping) else None
+ code = error.get("code") if isinstance(error, Mapping) else None
+ return code in {-32601, -32602}
+
@staticmethod
def _adapt_arguments(properties: Mapping[str, Any], arguments: Mapping[str, Any]) -> dict[str, Any] | None:
# The live schema is authoritative. Unknown catalog defaults never cross
@@ -328,68 +384,66 @@ class KeylessExaMcpClient:
on_sent: Callable[[], Awaitable[None] | None] | None = None,
) -> SearchResponse:
"""Call one live-schema MCP tool; retry one stale session before the call."""
- async with self._lock:
- deadline = time.monotonic() + self.timeout_seconds
- last: _Exchange | None = None
- sent_callback_called = False
-
- async def admit_once() -> None:
- nonlocal sent_callback_called
- if sent_callback_called or on_sent is None:
- return
- admission = on_sent()
- if inspect.isawaitable(admission):
- await admission
- sent_callback_called = True
-
- for _ in range(2):
- if self._session_id is None:
- initialized = await self._initialize(deadline=deadline)
- last = initialized
- if _session_not_found(initialized):
- self._clear_session()
- continue
- if initialized.error or initialized.status != 200 or self._session_id is None:
- return await self._as_search_response(initialized)
- listed = await self._list_tools(deadline=deadline)
- if listed is not None:
- last = listed
- if _session_not_found(listed):
- self._clear_session()
- continue
- return await self._as_search_response(listed)
- tool = (self._tools or {}).get(tool_name)
- properties = _tool_properties(
+
+ deadline = time.monotonic() + self.timeout_seconds
+ last: _Exchange | None = None
+ sent_callback_called = False
+
+ async def admit_once() -> None:
+ nonlocal sent_callback_called
+ if sent_callback_called or on_sent is None:
+ return
+ admission = on_sent()
+ if inspect.isawaitable(admission):
+ await admission
+ sent_callback_called = True
+
+ for _ in range(2):
+ setup_failure = await self._ensure_ready(deadline=deadline)
+ if setup_failure is not None:
+ last = setup_failure
+ if _session_not_found(setup_failure):
+ await self._clear_if_stale(self._session_id)
+ continue
+ return await self._as_search_response(setup_failure)
+ tool = (self._tools or {}).get(tool_name)
+ properties = (
+ _tool_properties(
tool,
require_search_controls=tool_name == KEYLESS_EXA_SEARCH_TOOL,
require_fetch_controls=tool_name == KEYLESS_EXA_FETCH_TOOL,
- ) if isinstance(tool, Mapping) else None
- if properties is None:
- return SearchResponse(None, {}, None, "invalid_endpoint")
- adapted = self._adapt_arguments(properties, arguments)
- if adapted is None:
- return SearchResponse(None, {}, None, "invalid_endpoint")
- if tool_name == KEYLESS_EXA_FETCH_TOOL:
- required = tool["inputSchema"].get("required", [])
- if (
- not isinstance(required, list)
- or not all(isinstance(name, str) and name in adapted for name in required)
- or not _REQUIRED_FETCH_FIELDS.issubset(adapted)
- ):
- return SearchResponse(None, {}, None, "invalid_endpoint")
- called = await self._request(
- "tools/call",
- {"name": tool_name, "arguments": adapted},
- deadline=deadline,
- on_sent=admit_once,
)
- last = called
- self._observe_notifications(called.messages)
- if _session_not_found(called):
- self._clear_session()
- continue
- return await self._as_search_response(called)
- return await self._as_search_response(last or _Exchange(None, {}, None, "connection"))
+ if isinstance(tool, Mapping) else None
+ )
+ if properties is None:
+ return SearchResponse(None, {"x-avibe-mcp-phase": "tools_list"}, None, "invalid_endpoint")
+ adapted = self._adapt_arguments(properties, arguments)
+ if adapted is None:
+ return SearchResponse(None, {"x-avibe-mcp-phase": "tools_list"}, None, "invalid_endpoint")
+ if tool_name == KEYLESS_EXA_FETCH_TOOL:
+ required = tool["inputSchema"].get("required", [])
+ if (
+ not isinstance(required, list)
+ or not all(isinstance(name, str) and name in adapted for name in required)
+ or not _REQUIRED_FETCH_FIELDS.issubset(adapted)
+ ):
+ return SearchResponse(None, {"x-avibe-mcp-phase": "tools_list"}, None, "invalid_endpoint")
+ request_session = self._session_id
+ called = await self._request(
+ "tools/call",
+ {"name": tool_name, "arguments": adapted},
+ deadline=deadline,
+ on_sent=admit_once,
+ )
+ last = called
+ self._observe_notifications(called.messages)
+ if _session_not_found(called):
+ await self._clear_if_stale(request_session)
+ continue
+ if self._schema_changed(called):
+ self._tools = None
+ return await self._as_search_response(called)
+ return await self._as_search_response(last or _Exchange(None, {}, None, "connection", phase="tools_call"))
async def search(
self,
@@ -428,9 +482,12 @@ class KeylessExaMcpClient:
)
if not error and exchange.status is not None and 300 <= exchange.status < 400:
error = "redirect"
+ headers = dict(exchange.headers)
+ if exchange.phase is not None:
+ headers["x-avibe-mcp-phase"] = exchange.phase
return SearchResponse(
exchange.status,
- exchange.headers,
+ headers,
body,
error,
on_sent_fired=exchange.sent,