mcp_tool_common.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """Small pure helpers shared by the tools.mcp_tool_* modules: SDK 1.x/2.x field access,
  2. error-text sanitising, numeric/bool coercion, timeouts and jitter. No origin state."""
  3. import logging
  4. import math
  5. import os
  6. import random
  7. import re
  8. from typing import Any, Optional
  9. logger = logging.getLogger("tools.mcp_tool")
  10. class _OriginProxy:
  11. """Attribute proxy for ``tools.mcp_tool`` resolved at access time. The split modules read
  12. origin state (``_servers``, ``_lock``, SDK symbols, patchable helpers) through this so
  13. ``mock.patch("tools.mcp_tool.X")`` and origin-side rebinds stay effective, and so no split
  14. module needs the origin imported first (the origin imports them while initialising)."""
  15. __slots__ = ()
  16. def __getattr__(self, name: str):
  17. from tools import mcp_tool
  18. return getattr(mcp_tool, name)
  19. _core = _OriginProxy()
  20. _MISSING = object()
  21. def mcp_field(obj, snake: str, camel: str, default=None):
  22. """Read an MCP model field across the 1.x -> 2.x rename to snake_case. Pydantic aliases
  23. don't apply to attribute access, so ``getattr(result, "isError", False)`` silently returns
  24. the default on 2.x — failed calls read as successful, schemas as empty."""
  25. value = getattr(obj, snake, _MISSING)
  26. if value is _MISSING:
  27. value = getattr(obj, camel, _MISSING)
  28. return default if value is _MISSING else value
  29. _DEFAULT_TOOL_TIMEOUT = 300 # seconds for tool calls
  30. def _resolve_tool_timeout(config: dict) -> float:
  31. """Per-server tool-call timeout. Precedence: ``mcp_servers.<name>.timeout`` >
  32. ``timeouts.mcp.tool_call`` > the 300s default; values are platform-clamped by
  33. ``resolve_timeout``."""
  34. per_server = config.get("timeout")
  35. if per_server is not None:
  36. return per_server
  37. try:
  38. from agent.deadline import resolve_timeout
  39. resolved = resolve_timeout("mcp.tool_call", default=_DEFAULT_TOOL_TIMEOUT)
  40. if resolved is not None:
  41. return resolved
  42. except Exception:
  43. logger.debug("mcp.tool_call timeout resolution failed", exc_info=True)
  44. return _DEFAULT_TOOL_TIMEOUT
  45. # Jitter on reconnect backoff so servers that lost the same backend don't retry in lockstep.
  46. _BACKOFF_JITTER = 0.2 # +/-20%
  47. def _jittered(seconds: float) -> float:
  48. """``seconds`` with +/-20% uniform jitter, floored at 0."""
  49. return max(0.0, seconds * random.uniform(1.0 - _BACKOFF_JITTER, 1.0 + _BACKOFF_JITTER))
  50. # Credential patterns to strip from error messages: GitHub PAT, OpenAI-style key, Bearer token,
  51. # and ``token= / key= / API_KEY= / password= / secret=`` assignments.
  52. _CREDENTIAL_PATTERN = re.compile(
  53. r"(?:ghp_[A-Za-z0-9_]{1,255}|sk-[A-Za-z0-9_-](?:\.?[A-Za-z0-9_-]){0,254}|Bearer\s+\S+"
  54. r"|(?:token|key|API_KEY|password|secret)=[^\s&,;\"']{1,255})", re.IGNORECASE)
  55. def _env_ref_name(ref: str) -> str:
  56. """Bare env-var name from a ``${...}`` body; strips a Cursor-style ``env:`` prefix."""
  57. ref = ref.strip()
  58. if ref.startswith("env:"):
  59. ref = ref[len("env:"):].strip()
  60. return ref
  61. def _sanitize_error(text: str) -> str:
  62. """Replace credential-like patterns with [REDACTED] before text reaches the LLM."""
  63. return _CREDENTIAL_PATTERN.sub("[REDACTED]", text)
  64. def _exc_str(exc: BaseException) -> str:
  65. """Non-empty string for *exc*: some exceptions (``anyio.ClosedResourceError``) carry no
  66. message, so fall back to ``repr`` to keep diagnostics."""
  67. text = str(exc).strip()
  68. return text or repr(exc)
  69. def _prepend_path(env: dict, directory: str) -> dict:
  70. """Prepend *directory* to env PATH if it is not already present."""
  71. updated = dict(env or {})
  72. if directory:
  73. parts = [part for part in updated.get("PATH", "").split(os.pathsep) if part]
  74. if directory not in parts:
  75. parts = [directory, *parts]
  76. updated["PATH"] = os.pathsep.join(parts) if parts else directory
  77. return updated
  78. def _safe_numeric(value, default, coerce=int, minimum=1):
  79. """Coerce a config value (YAML strings included) to a number, clamped to *minimum*;
  80. *default* on failure or non-finite floats."""
  81. try:
  82. result = coerce(value)
  83. if isinstance(result, float) and not math.isfinite(result):
  84. return default
  85. return max(result, minimum)
  86. except (TypeError, ValueError, OverflowError):
  87. return default
  88. _TRUE_WORDS = frozenset({"true", "1", "yes", "on"})
  89. _FALSE_WORDS = frozenset({"false", "0", "no", "off"})
  90. def _parse_boolish(value: Any, default: bool = True) -> bool:
  91. """Parse a bool-like config value with safe fallback (YAML ``0``/``1`` are numbers, not words)."""
  92. if value is None:
  93. return default
  94. if isinstance(value, (bool, int, float)):
  95. return bool(value)
  96. if isinstance(value, str):
  97. lowered = value.strip().lower()
  98. if lowered in _TRUE_WORDS:
  99. return True
  100. if lowered in _FALSE_WORDS:
  101. return False
  102. logger.warning("MCP config expected a boolean-ish value, got %r; using default=%s", value, default)
  103. return default
  104. def mcp_server_enabled(cfg: dict) -> bool:
  105. """Whether ``mcp_servers.<name>`` is on. The ONE reader of the ``enabled`` key: the MCP client,
  106. the toolset resolver, the profile editor, and every list/status surface call it, so a value
  107. can never be on for one surface and off for another. Absent, ``null`` or unparseable = on."""
  108. return _parse_boolish(cfg.get("enabled", True), default=True)
  109. def _get_lifecycle_seconds(config: dict, key: str) -> Optional[float]:
  110. """Optional positive lifecycle timeout from top-level/nested ``lifecycle`` config (``0``
  111. disables; negatives and non-numbers are warned about and ignored)."""
  112. raw = config.get(key)
  113. if raw is None and isinstance(config.get("lifecycle"), dict):
  114. raw = config["lifecycle"].get(key)
  115. if raw is None:
  116. return None
  117. try:
  118. seconds = float(raw)
  119. except (TypeError, ValueError):
  120. logger.warning("MCP config %s must be a number of seconds; ignoring %r", key, raw)
  121. return None
  122. if seconds < 0:
  123. logger.warning("MCP config %s must be positive; ignoring %r", key, raw)
  124. return None
  125. return seconds or None