Coverage for stackone_ai / tools.py: 96%
805 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-24 19:59 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-24 19:59 +0000
1"""Tools served by the StackOne MCP endpoint, and their execution over MCP ``tools/call``.
3The guiding property of this module is that a tool is the served catalog entry:
4the schema listed to a model is the schema the MCP server sent, and a call sends the
5model's arguments back to the endpoint that listed it, as given. Nothing is invented,
6nothing is dropped, nothing is rebuilt.
7"""
9from __future__ import annotations
11import asyncio
12import base64
13import calendar
14import functools
15import json
16import logging
17import math
18import random
19import re
20import ssl
21import threading
22import time
23from collections import Counter
24from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable, Sequence
25from contextlib import asynccontextmanager
26from dataclasses import dataclass
27from datetime import UTC, datetime, timedelta
28from decimal import Decimal
29from importlib import metadata
30from typing import TYPE_CHECKING, Any, NoReturn, TypeVar
32import anyio
33import httpx
34from pydantic import BaseModel, Field, PrivateAttr
36from stackone_ai.types import (
37 EXECUTE_ACTION_TOOL_NAME,
38 SEARCH_ACTIONS_TOOL_NAME,
39 ExecuteConfig,
40 Headers,
41 JsonDict,
42 StackOneAPIError,
43 StackOneError,
44 ToolArgumentsError,
45 ToolParameters,
46 ToolsetConfigError,
47 ToolsetLoadError,
48)
50logger = logging.getLogger("stackone.tools")
52# The HTTP library the installed mcp transport takes: httpx before mcp 2, httpx2 (an mcp 2
53# dependency) from then on. GET /accounts always uses httpx.
54if TYPE_CHECKING or int(metadata.version("mcp").split(".")[0]) >= 2: 54 ↛ 57line 54 didn't jump to line 57 because the condition on line 54 was always true
55 import httpx2 as _mcp_http
56else:
57 _mcp_http = httpx
59T = TypeVar("T")
61try:
62 _SDK_VERSION = metadata.version("stackone-ai")
63except metadata.PackageNotFoundError: # pragma: no cover - best-effort fallback when running from source
64 _SDK_VERSION = "dev"
66USER_AGENT = f"stackone-ai-python/{_SDK_VERSION}"
68_HEADER_NAME_PATTERN = re.compile(r"[A-Za-z0-9!#$%&'*+.^_`|~-]+")
69_HEADER_VALUE_PATTERN = re.compile(r"[\x20-\x7e\t\x80-\xff]*")
71# What JavaScript's String.prototype.trim() strips: its WhiteSpace and LineTerminator
72# characters. str.strip() also strips \x1c-\x1f and \x85, which made "x-custom\x1f" a
73# valid name here when Node refuses it as malformed, and misses the byte order mark.
74_JS_WHITESPACE = (
75 "\t\n\v\f\r \xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
76 "\u2028\u2029\u202f\u205f\u3000\ufeff"
77)
80def _trim_header_name(name: str) -> str:
81 """A header name trimmed as Node trims it."""
82 return name.strip(_JS_WHITESPACE)
85def is_sdk_owned_header(name: str) -> bool:
86 """Whether a caller-supplied header name is one the SDK owns and will override."""
87 return _ascii_lower(_trim_header_name(name)) in _SDK_OWNED_HEADERS
90def build_request_headers(
91 *,
92 api_key: str,
93 account_id: str | None = None,
94 end_user_id: str | None = None,
95 extra_headers: Headers | None = None,
96) -> Headers:
97 """The HTTP headers for a request to StackOne: the caller's extra headers first, then
98 the SDK's own, so Authorization, x-account-id and User-Agent are always the SDK's —
99 and so is x-end-user-id when an ``end_user_id`` is given.
101 Case variants of the owned names are dropped first — a server would otherwise see
102 both. With no ``account_id``, no x-account-id is sent at all; with no
103 ``end_user_id``, a caller's x-end-user-id is passed through as given.
104 """
105 replaced = _SDK_SET_HEADER_ARGUMENTS if end_user_id else _SDK_OWNED_HEADERS
106 headers: Headers = {
107 name: value
108 for name, value in (extra_headers or {}).items()
109 if _ascii_lower(_trim_header_name(name)) not in replaced
110 }
111 headers["User-Agent"] = USER_AGENT
112 headers["Authorization"] = build_auth_header(api_key)
113 if account_id:
114 headers["x-account-id"] = account_id
115 if end_user_id:
116 headers[END_USER_ID_HEADER] = end_user_id
117 return headers
120# Header names the SDK sets itself, after every other header. A tool call may not supply
121# them even when a served schema declares them: they are the credential, the tenant
122# selector and the client identity.
123_SDK_OWNED_HEADERS = frozenset({"authorization", "x-account-id", "user-agent"})
125# The end user a non-shared account belongs to, which the API requires on every MCP request
126# for that account. The SDK sets it when GET /accounts recorded one for the account; a
127# caller's configured headers may carry it otherwise. A model may never supply it.
128END_USER_ID_HEADER = "x-end-user-id"
130# Header names a tool call's header arguments may not carry, even when declared.
131_SDK_SET_HEADER_ARGUMENTS = _SDK_OWNED_HEADERS | {END_USER_ID_HEADER}
133# A top-level argument with this prefix is a header argument, as is an entry of a nested
134# `headers` object argument.
135_FLAT_HEADER_PREFIX = "headers_"
137# Why a header argument was dropped: each reason code, and the text its warning gives.
138_HEADER_REASONS = {
139 "set-by-sdk": "set by the SDK",
140 "not-declared": "not declared by the schema",
141 "malformed": "malformed",
142 "not-an-object": "not an object",
143 "not-a-scalar": "not a string, number or boolean",
144}
147def _warn_header_dropped(argument: str, header: str | None, reason: str) -> None:
148 """Warn that a header argument, or one entry of a ``headers`` object, was dropped."""
149 if header is None:
150 logger.warning(
151 "Dropping header argument %s from a tool call: %s", _json_text(argument), _HEADER_REASONS[reason]
152 )
153 else:
154 logger.warning("Dropping header %s from a tool call: %s", _json_text(header), _HEADER_REASONS[reason])
157# How a 429 is retried, on every request the SDK makes: up to three more attempts, each
158# after the server's Retry-After (capped) or else an exponential backoff with jitter. A
159# wait that would not end before the request's deadline is not started: the 429 is
160# returned at once instead.
161RATE_LIMIT_MAX_RETRIES = 3
162RATE_LIMIT_BACKOFF_SECONDS = (1.0, 2.0, 4.0)
163RATE_LIMIT_JITTER = (0.5, 1.0)
164RATE_LIMIT_MAX_DELAY_SECONDS = 30.0
166# Looked up at call time, so tests can replace them and not actually wait.
167_sleep = time.sleep
168_async_sleep = anyio.sleep
169_clock = time.monotonic
170_async_clock = anyio.current_time
173@dataclass
174class McpToolDefinition:
175 """A tool exactly as the MCP server listed it."""
177 name: str
178 description: str | None
179 input_schema: dict[str, Any]
182def run_async(awaitable: Coroutine[Any, Any, T]) -> T:
183 """Run a coroutine, even when called from an existing event loop."""
185 try:
186 asyncio.get_running_loop()
187 except RuntimeError:
188 in_a_loop = False
189 else:
190 in_a_loop = True
191 # Run outside the except block, or every failure would carry the probe's
192 # "no running event loop" as its __context__.
193 if not in_a_loop:
194 return asyncio.run(awaitable)
196 result: dict[str, T] = {}
197 error: dict[str, BaseException] = {}
199 def runner() -> None:
200 try:
201 result["value"] = asyncio.run(awaitable)
202 except BaseException as exc: # pragma: no cover - surfaced in caller context
203 error["error"] = exc
205 thread = threading.Thread(target=runner, daemon=True)
206 thread.start()
207 thread.join()
209 if "error" in error:
210 raise error["error"]
212 return result["value"]
215def _js_number(value: float) -> str:
216 """A float as JavaScript's ``String(number)`` writes it: ``1.0`` is "1", ``1e-7`` is "1e-7".
218 Both languages print the shortest digits that round-trip, so only the layout differs:
219 the cut-offs for exponent notation, and the exponent's sign and padding.
220 """
221 if math.isnan(value):
222 return "NaN"
223 if math.isinf(value):
224 return "Infinity" if value > 0 else "-Infinity"
225 if value == 0:
226 return "0"
227 sign = "-" if value < 0 else ""
228 parsed = Decimal(repr(abs(value))).normalize().as_tuple()
229 digits = "".join(map(str, parsed.digits))
230 k = len(digits)
231 n = int(parsed.exponent) + k
232 if k <= n <= 21:
233 return sign + digits + "0" * (n - k)
234 if 0 < n <= 21:
235 return sign + digits[:n] + "." + digits[n:]
236 if -6 < n <= 0:
237 return sign + "0." + "0" * -n + digits
238 mantissa = digits if k == 1 else f"{digits[0]}.{digits[1:]}"
239 return f"{sign}{mantissa}e{'+' if n > 0 else '-'}{abs(n - 1)}"
242def _js_json(value: Any) -> str:
243 """``value`` as JavaScript's ``JSON.stringify`` writes it: compact, numbers as JS prints them.
245 Raises:
246 TypeError: If ``value`` holds something JSON cannot represent, such as a set.
247 """
248 if value is None:
249 return "null"
250 if isinstance(value, bool):
251 return "true" if value else "false"
252 if isinstance(value, int):
253 return str(value)
254 if isinstance(value, float):
255 return _js_number(value) if math.isfinite(value) else "null"
256 if isinstance(value, str):
257 return json.dumps(value, ensure_ascii=False)
258 if isinstance(value, dict):
259 entries = (
260 f"{json.dumps(key if isinstance(key, str) else _header_text(key) or 'null', ensure_ascii=False)}:"
261 f"{_js_json(item)}"
262 for key, item in value.items()
263 )
264 return "{" + ",".join(entries) + "}"
265 if isinstance(value, list | tuple):
266 return "[" + ",".join(_js_json(item) for item in value) + "]"
267 raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
270def _json_text(value: Any) -> str:
271 """A value as compact JSON, the way every message quotes a name or a value.
273 ``repr`` wrote Python's spelling (``'x'``, ``None``, ``True``); JSON reads the same from
274 either SDK. A value JSON cannot hold, such as a set, falls back to its ``repr``.
275 """
276 try:
277 return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
278 except (TypeError, ValueError):
279 return repr(value)
282def _json_type(value: Any) -> str:
283 """The JSON type of a value: object, array, string, number, boolean or null.
285 A value with no JSON type, such as a set, is named by its Python type.
286 """
287 if value is None: 287 ↛ 288line 287 didn't jump to line 288 because the condition on line 287 was never true
288 return "null"
289 if isinstance(value, bool): 289 ↛ 290line 289 didn't jump to line 290 because the condition on line 289 was never true
290 return "boolean"
291 if isinstance(value, int | float): 291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true
292 return "number"
293 if isinstance(value, str):
294 return "string"
295 if isinstance(value, list | tuple):
296 return "array"
297 if isinstance(value, dict): 297 ↛ 299line 297 didn't jump to line 299 because the condition on line 297 was always true
298 return "object"
299 return type(value).__name__
302def _seconds_2dp(seconds: float) -> str:
303 """Seconds rounded half up to two decimals, then written as JavaScript writes a number."""
304 return _js_number(math.floor(seconds * 100 + 0.5) / 100)
307_ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
310def _ascii_lower(name: str) -> str:
311 """A header name lower-cased in ASCII only, as HTTP compares names.
313 ``casefold()`` folded "ſ" (U+017F) to "s", so "uſer-agent" read as User-Agent. It is
314 not a token at all, and is refused as malformed instead.
315 """
316 return name.translate(_ASCII_LOWER)
319def _declares_object_type(schema_type: Any) -> bool:
320 """Whether a JSON Schema ``type`` declares (among others) ``"object"``.
322 ``type`` is either a single string or, per the JSON Schema spec, a list of strings
323 naming every allowed type, e.g. ``["object", "null"]``.
324 """
325 if isinstance(schema_type, str):
326 return schema_type == "object"
327 if isinstance(schema_type, list):
328 return "object" in schema_type
329 return False
332def _header_text(value: Any) -> str | None:
333 """A header argument's value as text, as Node's ``headerText`` writes it; ``None`` if null.
335 Strings as they are, booleans as ``true``/``false``, numbers as JavaScript prints them
336 and anything else as compact JSON. ``str()`` sent Python's spelling instead: ``True``,
337 ``1.0``, ``['a', 'b']``.
338 """
339 if value is None:
340 return None
341 if isinstance(value, str):
342 return value
343 if isinstance(value, bool | int):
344 return _js_json(value)
345 if isinstance(value, float):
346 return _js_number(value)
347 return _js_json(value)
350def build_auth_header(api_key: str) -> str:
351 token = base64.b64encode(f"{api_key}:".encode()).decode()
352 return f"Basic {token}"
355async def _buffer_error_body(response: _mcp_http.Response) -> None:
356 """Read an error response's body while its stream is still open.
358 An error status is raised after the streamed response is closed, so
359 reading the body afterwards got nothing and every failure said only "400 Bad
360 Request". The body is where the server explains itself: "Legacy accounts cannot be
361 used with MCP", or a 412 asking for the account to be re-linked. Node already
362 carries it.
363 """
364 if response.is_error:
365 await response.aread()
368# The three HTTP-date forms of RFC 9110 §5.6.7, exactly: case-sensitive, single spaces, and
369# GMT only. re.ASCII, or \d would also match "٣".
370_DAY = r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)"
371_MONTH = r"(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"
372_TIME = r"(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)"
373_IMF_FIXDATE = re.compile(rf"{_DAY}, (?P<day>\d\d) {_MONTH} (?P<year>\d{{4}}) {_TIME} GMT", re.ASCII)
374_RFC850_DATE = re.compile(
375 rf"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), "
376 rf"(?P<day>\d\d)-{_MONTH}-(?P<year>\d\d) {_TIME} GMT",
377 re.ASCII,
378)
379_ASCTIME_DATE = re.compile(rf"{_DAY} {_MONTH} (?P<day>\d\d| \d) {_TIME} (?P<year>\d{{4}})", re.ASCII)
380_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
383def _add_years(when: datetime, years: int) -> datetime:
384 """``when`` moved by whole years; 29 February lands on the 28th in a common year."""
385 try:
386 return when.replace(year=when.year + years)
387 except ValueError:
388 return when.replace(year=when.year + years, day=28)
391def _parse_http_date(value: str, now: datetime) -> float | None:
392 """An RFC 9110 HTTP-date as seconds since the epoch, or ``None`` if it is not one.
394 Written out rather than left to ``email.utils.parsedate_to_datetime``, which reads
395 far more than an HTTP-date: trailing text, numeric zones, two-digit years in any form.
396 The weekday is not checked against the date, as RFC 9110 does not ask it to be.
398 Seconds since the epoch, not a ``datetime``, because a leap second (second 60) on
399 the last representable instant, e.g. ``Fri, 31 Dec 9999 23:59:60 GMT``, rolls over
400 into year 10000, which ``datetime`` cannot hold. ``calendar.timegm`` takes the date
401 fields as plain integers and does the arithmetic without that ceiling.
402 """
403 match = _IMF_FIXDATE.fullmatch(value) or _ASCTIME_DATE.fullmatch(value)
404 two_digit_year = False
405 if match is None:
406 match = _RFC850_DATE.fullmatch(value)
407 two_digit_year = True
408 if match is None:
409 return None
410 year = int(match["year"])
411 month = _MONTHS.index(match["month"]) + 1
412 day = int(match["day"])
413 hour = int(match["hour"])
414 minute = int(match["minute"])
415 second = int(match["second"])
416 if second > 60:
417 return None
418 if two_digit_year:
419 # §5.6.7: a two-digit year more than 50 years ahead is the most recent past year
420 # with those digits.
421 year += now.year - now.year % 100
422 try:
423 # Second 60 is a leap second: validated as if it were 59, the instant before the
424 # next minute starts. Also catches day 32, hour 25, 30 February, year 0.
425 datetime(year, month, day, hour, minute, min(second, 59), tzinfo=UTC)
426 except ValueError:
427 return None
428 if two_digit_year:
429 # Bounded to a century around `now`, so no overflow risk going through datetime.
430 when = datetime(year, month, day, hour, minute, min(second, 59), tzinfo=UTC)
431 if second == 60: 431 ↛ 432line 431 didn't jump to line 432 because the condition on line 431 was never true
432 when += timedelta(seconds=1)
433 if when > _add_years(now, 50):
434 when = _add_years(when, -100)
435 elif _add_years(when, 100) <= _add_years(now, 50): 435 ↛ 436line 435 didn't jump to line 436 because the condition on line 435 was never true
436 when = _add_years(when, 100)
437 return calendar.timegm(when.utctimetuple())
438 return calendar.timegm((year, month, day, hour, minute, second))
441def _retry_after_seconds(value: str | None, now: datetime | None = None) -> float | None:
442 """A Retry-After header as seconds from ``now``: delta-seconds or an HTTP-date.
444 ``None`` when the header is absent or unreadable, so the caller falls back to its
445 own backoff. A date in the past means retry now. ``now`` defaults to the current time.
446 """
447 if value is None:
448 return None
449 value = value.strip(_JS_WHITESPACE)
450 # ASCII digits only: str.isdigit() also accepts "²", which float() then refuses.
451 if re.fullmatch(r"[0-9]+", value):
452 return float(value)
453 now = now or datetime.now(UTC)
454 when_epoch = _parse_http_date(value, now)
455 if when_epoch is None:
456 return None
457 now_epoch = calendar.timegm(now.utctimetuple()) + now.microsecond / 1e6
458 return max(0.0, when_epoch - now_epoch)
461def _backoff_delay(retry: int, retry_after: float | None, random_value: float | None = None) -> float:
462 """How long to wait before retry number ``retry`` (1-based) of a 429.
464 ``retry_after`` is the 429's Retry-After in seconds, or ``None`` if it had none readable;
465 then the backoff for ``retry`` is jittered by ``random_value``, uniform in [0, 1).
466 """
467 if retry_after is None:
468 r = random.random() if random_value is None else random_value
469 low, high = RATE_LIMIT_JITTER
470 retry_after = RATE_LIMIT_BACKOFF_SECONDS[retry - 1] * (low + (high - low) * r)
471 return min(retry_after, RATE_LIMIT_MAX_DELAY_SECONDS)
474def _rate_limit_delay(response: httpx.Response | _mcp_http.Response, retry: int) -> float:
475 """How long to wait before retry number ``retry`` (1-based) of this 429."""
476 return _backoff_delay(retry, _retry_after_seconds(response.headers.get("retry-after")))
479def _waits_for_retry(delay: float, remaining: float) -> bool:
480 """Whether a wait of ``delay`` ends before a deadline ``remaining`` seconds away."""
481 return delay < remaining
484def _log_rate_limit_retry(request: httpx.Request | _mcp_http.Request, attempt: int, delay: float) -> None:
485 logger.warning(
486 "%s %s was rate limited (429) on attempt %d of %d; retrying in %ss",
487 request.method,
488 request.url,
489 attempt,
490 RATE_LIMIT_MAX_RETRIES + 1,
491 _seconds_2dp(delay),
492 )
495def _outlasts_deadline(
496 request: httpx.Request | _mcp_http.Request, attempt: int, delay: float, remaining: float
497) -> bool:
498 """Whether waiting ``delay`` would not end before the deadline, logging when so.
500 Such a wait is not started. Sleeping into the deadline would turn the 429 into a
501 timeout, which a multi-account call skips like any per-account failure, and hand back
502 a partial catalog that looks complete. The 429 itself ends the call.
503 """
504 if _waits_for_retry(delay, remaining):
505 return False
506 logger.warning(
507 "%s %s was rate limited (429) on attempt %d of %d; not retrying, because waiting %ss "
508 "would pass the deadline",
509 request.method,
510 request.url,
511 attempt,
512 RATE_LIMIT_MAX_RETRIES + 1,
513 _seconds_2dp(delay),
514 )
515 return True
518class RateLimitRetryingClient(httpx.Client):
519 """An ``httpx.Client`` that retries a 429 before the caller ever sees it.
521 Retried in ``send`` rather than in a wrapping transport: passing a custom transport
522 makes httpx ignore the proxy environment variables, which would quietly break the SDK
523 behind a corporate proxy. The last 429 is returned as it came, so the caller reports
524 the server's body.
526 ``retry_within`` is the deadline in seconds, measured from the first attempt: a retry
527 whose wait would not end before it is not made, and the 429 is returned instead. A
528 retry that times out raises :class:`RateLimitTimeout`: the account is rate limited, and
529 an ordinary timeout would let a caller skip it like any other failure.
530 """
532 def __init__(self, *args: Any, retry_within: float | None = None, **kwargs: Any) -> None:
533 super().__init__(*args, **kwargs)
534 self._retry_within = retry_within
536 def send(self, request: httpx.Request, **kwargs: Any) -> httpx.Response:
537 deadline = _clock() + self._retry_within if self._retry_within is not None else None
538 attempt = 1
539 response = super().send(request, **kwargs)
540 while response.status_code == 429 and attempt <= RATE_LIMIT_MAX_RETRIES:
541 delay = _rate_limit_delay(response, attempt)
542 if deadline is not None and _outlasts_deadline(request, attempt, delay, deadline - _clock()):
543 break
544 # Read before closing, so the connection goes back to the pool.
545 response.read()
546 response.close()
547 _log_rate_limit_retry(request, attempt, delay)
548 _sleep(delay)
549 attempt += 1
550 try:
551 response = super().send(request, **kwargs)
552 except httpx.TimeoutException as exc:
553 raise RateLimitTimeout(str(exc), request=request) from exc
554 return response
557class RateLimitTimeout(httpx.TimeoutException):
558 """A request retried after a 429 timed out: the 429's doing, not an ordinary timeout."""
561@dataclass
562class _Throttle:
563 """The last 429 an MCP exchange retried, while any request is still retrying one.
565 Counted per request because an exchange's requests overlap: the MCP client's event-stream
566 GET, say, answered while a ``tools/list`` retry hangs, must not clear that retry's 429.
567 """
569 response: _mcp_http.Response | None = None
570 retrying: int = 0
573class RateLimitRetryingAsyncClient(_mcp_http.AsyncClient):
574 """The async counterpart of :class:`RateLimitRetryingClient`, used for every MCP request.
576 The MCP client streams its responses; a discarded 429 is read and closed here, and
577 the final one still passes through the response hooks, so its body is buffered.
579 The deadline is the enclosing cancel scope's: the ``anyio.fail_after(timeout)`` that
580 bounds the whole MCP exchange. A retry whose wait would not end before it is not made.
582 ``throttle`` records each 429 that is retried. The exchange's timeout cancels the retry
583 rather than raising in it, so the caller reads this afterwards to report a timeout
584 after a retried 429 as that 429 (see :func:`_raise_mcp_failure`).
585 """
587 def __init__(self, *args: Any, throttle: _Throttle | None = None, **kwargs: Any) -> None:
588 super().__init__(*args, **kwargs)
589 self._throttle = throttle
591 async def send(self, request: _mcp_http.Request, **kwargs: Any) -> _mcp_http.Response:
592 attempt = 1
593 retried = False
594 response = await super().send(request, **kwargs)
595 while response.status_code == 429 and attempt <= RATE_LIMIT_MAX_RETRIES:
596 delay = _rate_limit_delay(response, attempt)
597 remaining = anyio.current_effective_deadline() - _async_clock()
598 if _outlasts_deadline(request, attempt, delay, remaining):
599 break
600 await response.aread()
601 await response.aclose()
602 if self._throttle is not None:
603 self._throttle.response = response
604 if not retried:
605 retried = True
606 self._throttle.retrying += 1
607 _log_rate_limit_retry(request, attempt, delay)
608 await _async_sleep(delay)
609 attempt += 1
610 response = await super().send(request, **kwargs)
611 if self._throttle is not None and retried and response.status_code != 429:
612 self._throttle.retrying -= 1
613 if self._throttle.retrying == 0: 613 ↛ 615line 613 didn't jump to line 615 because the condition on line 613 was always true
614 self._throttle.response = None
615 if request.method == "POST" and response.is_error and response.status_code != 404:
616 # mcp 2 answers a failed POST with a JSON-RPC error that drops the status and the
617 # body; raised as mcp 1 does, it keeps both. A 404 is left to mcp: a lost session.
618 await response.aclose()
619 raise _mcp_http.HTTPStatusError(
620 f"{response.status_code} {response.reason_phrase}", request=request, response=response
621 )
622 return response
625def is_rate_limited(exc: BaseException) -> bool:
626 """Whether a failure is a 429 that outlasted every retry.
628 Such a failure ends the whole call: skipping the account and carrying on would hand
629 back a partial catalog that looks complete. Only an HTTP 429 counts, as in Node: a
630 tool result whose payload says 429 was never retried, so it is that connector's
631 failure, skipped like any other.
632 """
633 if not (isinstance(exc, StackOneAPIError) and exc.status_code == 429):
634 return False
635 seen: set[int] = set()
636 stack: list[BaseException] = [exc]
637 while stack:
638 current = stack.pop()
639 if id(current) in seen: 639 ↛ 640line 639 didn't jump to line 640 because the condition on line 639 was never true
640 continue
641 seen.add(id(current))
642 if (
643 isinstance(current, httpx.HTTPStatusError | _mcp_http.HTTPStatusError)
644 and current.response.status_code == 429
645 ):
646 return True
647 stack.extend(getattr(current, "exceptions", None) or [])
648 stack.extend(e for e in (current.__cause__, current.__context__) if e is not None)
649 return False
652@functools.cache
653def _ssl_context() -> ssl.SSLContext:
654 """One SSL context for every MCP client: building one loads the CA bundle each time."""
655 return httpx.create_ssl_context()
658@asynccontextmanager
659async def _mcp_transport(
660 endpoint: str, headers: dict[str, str], timeout: float, throttle: _Throttle | None = None
661) -> AsyncGenerator[tuple[Any, Any]]:
662 """Open the streamable-HTTP transport with the caller's timeout on every leg.
664 The client's own defaults are a 30s connect and a 300s SSE read, and neither was
665 overridden — so ``StackOneToolSet(timeout=2)`` against a host that accepts and never
666 answers hung for five minutes. The execution path honoured ``timeout``; the MCP
667 path, which search() and execute() and every listing use, did not.
669 The HTTP client is built here with the settings the ``mcp`` package's own factory
670 uses (redirects followed), because ``streamable_http_client`` takes a client rather
671 than headers and timeouts. It retries a 429, so the MCP client never sees one that
672 a retry got past.
673 """
674 from mcp.client.streamable_http import streamable_http_client
676 async with RateLimitRetryingAsyncClient(
677 throttle=throttle,
678 headers=headers,
679 timeout=_mcp_http.Timeout(timeout),
680 verify=_ssl_context(),
681 follow_redirects=True,
682 event_hooks={"response": [_buffer_error_body]},
683 ) as client:
684 async with streamable_http_client(endpoint, http_client=client) as streams:
685 # mcp 1 also yields a session-id getter, which nothing here reads.
686 yield streams[0], streams[1]
689def _run_mcp_session(
690 endpoint: str,
691 headers: dict[str, str],
692 timeout: float,
693 work: Callable[[Any], Coroutine[Any, Any, T]],
694) -> T:
695 """Open an initialized MCP session to ``endpoint``, run ``work`` on it and close it.
697 ``timeout`` bounds the whole exchange, handshake included. Any failure is raised
698 through :func:`_raise_mcp_failure`.
699 """
700 try:
701 from mcp import types as mcp_types
702 from mcp.client.session import ClientSession
703 except ImportError as exc: # pragma: no cover - only a broken install gets here
704 raise ToolsetConfigError(
705 "mcp is a core dependency of stackone-ai but could not be imported — reinstall the package."
706 ) from exc
708 throttle = _Throttle()
710 async def _run() -> T:
711 with anyio.fail_after(timeout):
712 async with _mcp_transport(endpoint, headers, timeout, throttle) as (read_stream, write_stream):
713 session = ClientSession(
714 read_stream,
715 write_stream,
716 client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION),
717 )
718 async with session:
719 await session.initialize()
720 return await work(session)
722 try:
723 return run_async(_run())
724 except Exception as exc:
725 # Exception, not BaseException: Ctrl-C and SystemExit must stop the caller, not come
726 # back as a ToolsetLoadError that an agent framework hands the model as a tool result.
727 _raise_mcp_failure(exc, endpoint, timeout, throttle)
730def _mcp_field(model: Any, name: str, wire_name: str, default: Any = None) -> Any:
731 """A field of an mcp model: mcp 2 names it in snake_case, mcp 1 as the wire does."""
732 try:
733 return getattr(model, name)
734 except AttributeError:
735 return getattr(model, wire_name, default)
738def fetch_mcp_tools(
739 endpoint: str, headers: dict[str, str], *, timeout: float = 60.0
740) -> list[McpToolDefinition]:
741 """List every tool the MCP endpoint serves, following pagination.
743 ``timeout`` bounds the whole exchange, handshake included.
744 """
746 async def _list(session: Any) -> list[McpToolDefinition]:
747 from mcp import types as mcp_types
749 cursor: str | None = None
750 collected: list[McpToolDefinition] = []
751 while True:
752 params = mcp_types.PaginatedRequestParams(cursor=cursor) if cursor is not None else None
753 result = await session.list_tools(params=params)
754 for tool in result.tools:
755 input_schema = _mcp_field(tool, "input_schema", "inputSchema") or {}
756 collected.append(
757 McpToolDefinition(
758 name=tool.name,
759 description=tool.description,
760 input_schema=dict(input_schema),
761 )
762 )
763 cursor = _mcp_field(result, "next_cursor", "nextCursor")
764 if cursor is None:
765 break
766 return collected
768 return _run_mcp_session(endpoint, headers, timeout, _list)
771def _response_body(response: _mcp_http.Response) -> str:
772 """Best-effort read of an error body.
774 The MCP transport streams, so `.text` raises until the stream is read, and by
775 the time the error surfaces the stream may already be closed. The body is the
776 only place the server explains itself, so it is worth trying; an empty string
777 just means the message falls back to the status code.
778 """
779 try:
780 return response.text.strip()
781 except Exception:
782 pass
783 try:
784 response.read()
785 return response.text.strip()
786 except Exception:
787 return ""
790def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) -> Exception:
791 """Turn the MCP client's nested failure into something a caller can act on.
793 The listing runs inside a TaskGroup, so any HTTP error arrives wrapped in an
794 ExceptionGroup whose str() is "unhandled errors in a TaskGroup (1 sub-exception)".
795 Unwrap to the underlying error and carry the status code and response body,
796 which is where the server explains itself — a dead account, for example,
797 answers 412 with "re-link the account to resume". A timeout says so, as in Node.
798 """
799 seen: set[int] = set()
800 stack: list[BaseException] = [exc]
801 while stack:
802 current = stack.pop()
803 if current is None or id(current) in seen:
804 continue
805 seen.add(id(current))
806 # Our own errors are already descriptive. They reach here wrapped in an
807 # ExceptionGroup because they are raised inside the session's TaskGroup.
808 if isinstance(current, StackOneError):
809 return current
810 if isinstance(current, _mcp_http.HTTPStatusError):
811 body = _response_body(current.response)
812 detail = f": {body}" if body else ""
813 status = f"{current.response.status_code} {current.response.reason_phrase}".rstrip()
814 # StackOneAPIError carries the status and body as attributes, so a caller
815 # can branch on 412 rather than pattern-matching the message.
816 return StackOneAPIError(
817 f"MCP request to {endpoint} failed with {status}{detail}",
818 current.response.status_code,
819 body or None,
820 )
821 stack.extend(getattr(current, "exceptions", None) or [])
822 stack.extend(e for e in (current.__cause__, current.__context__) if e is not None)
824 # The innermost cause, through group members and __cause__ only. An ExceptionGroup's
825 # own str() is the "unhandled errors in a TaskGroup" boilerplate that hides the real
826 # cause, and a __context__ is only what was being handled when the error was raised:
827 # for the deadline's TimeoutError that is the cancellation, or whatever the
828 # cancelled task happened to be catching.
829 leaf = _leaf_failure(exc)
830 if isinstance(leaf, TimeoutError | _mcp_http.TimeoutException):
831 return ToolsetLoadError(f"MCP request to {endpoint} timed out after {_js_number(timeout)}s")
832 return ToolsetLoadError(f"MCP request to {endpoint} failed: {type(leaf).__name__}: {leaf}")
835def _leaf_failure(exc: BaseException) -> BaseException:
836 """The innermost cause through group members and ``__cause__``, stopping at a timeout."""
837 leaf = exc
838 while not isinstance(leaf, TimeoutError | _mcp_http.TimeoutException):
839 members = getattr(leaf, "exceptions", None)
840 if members:
841 leaf = members[0]
842 elif leaf.__cause__ is not None: 842 ↛ 843line 842 didn't jump to line 843 because the condition on line 842 was never true
843 leaf = leaf.__cause__
844 else:
845 break
846 return leaf
849def _raise_mcp_failure(exc: Exception, endpoint: str, timeout: float, throttle: _Throttle) -> NoReturn:
850 """Raise an MCP exchange's failure as :func:`_describe_mcp_failure` describes it.
852 Except a timeout after a retried 429, which is raised as that 429. The retry's wait
853 ended before the deadline, but the retried request itself could still run past it, and
854 as a timeout a multi-account call skipped the account like any other failure and handed
855 back a partial catalog. Chained through an ``HTTPStatusError``, so
856 :func:`is_rate_limited` reads it as the HTTP 429 it is.
857 """
858 throttled = throttle.response
859 if throttled is not None and isinstance(_leaf_failure(exc), TimeoutError | _mcp_http.TimeoutException):
860 status = _mcp_http.HTTPStatusError(
861 f"429 {throttled.reason_phrase}", request=throttled.request, response=throttled
862 )
863 status.__cause__ = exc
864 raise StackOneAPIError(
865 f"MCP request to {endpoint} was rate limited (429) and timed out after "
866 f"{_js_number(timeout)}s while retrying",
867 429,
868 None,
869 ) from status
870 raise _describe_mcp_failure(exc, endpoint, timeout) from exc
873def _status_of(parsed: JsonDict) -> int:
874 """Dig the HTTP status out of an MCP error payload.
876 The transport succeeded, so there is no status on the response itself — but the
877 payload carries one, and a caller cannot branch on 0. Both spellings and all the
878 wrapper keys the API actually uses are checked: `statusCode` is what this repo's
879 own mock emits, and `error`/`data` are real wrappers, so looking only for
880 `status_code` under `result` reported 0 for the most likely shapes.
881 """
882 for candidate in (parsed, parsed.get("result"), parsed.get("error"), parsed.get("data")):
883 if not isinstance(candidate, dict):
884 continue
885 for key in ("status_code", "statusCode"):
886 status = candidate.get(key)
887 # bool is an int subclass; True is not a status code.
888 if isinstance(status, int) and not isinstance(status, bool):
889 return status
890 return 0
893def _reject_json_constant(constant: str) -> Any:
894 raise ValueError(f"{constant} is not valid JSON")
897def _first_non_finite(value: Any) -> float | None:
898 """The first NaN or infinity in ``value``, depth first in key order, or ``None``.
900 A container already on the path is skipped, so a cycle ends here and is reported by
901 ``json.dumps`` as a circular reference.
902 """
903 path: set[int] = set()
905 def walk(item: Any) -> float | None:
906 if isinstance(item, float):
907 return None if math.isfinite(item) else item
908 if not isinstance(item, dict | list | tuple) or id(item) in path:
909 return None
910 path.add(id(item))
911 try:
912 for child in item.values() if isinstance(item, dict) else item:
913 found = walk(child)
914 if found is not None:
915 return found
916 return None
917 finally:
918 path.discard(id(item))
920 return walk(value)
923def _plain_part(part: Any) -> Any:
924 """A content part as the JSON it arrived as: wire field names, unset fields left out."""
925 if isinstance(part, BaseModel): 925 ↛ 927line 925 didn't jump to line 927 because the condition on line 925 was always true
926 return part.model_dump(mode="json", by_alias=True, exclude_none=True)
927 return part
930def parse_tool_result(result: Any, name: str) -> JsonDict:
931 """Turn an MCP ``CallToolResult`` into a plain dict.
933 Text parts are joined and parsed as JSON; a non-object is wrapped as
934 ``{"result": ...}``. With no text at all, ``structuredContent`` is used, and text
935 wins when both are present. Parts that are not text (images, embedded resources)
936 are kept under ``content_parts`` as plain JSON, the form they arrived in.
938 The result is returned as the server wrote it. For an action tool, ``stackone_execute_action``
939 and feedback that is ``{"isError": false, "result": ..., "defenderMetadata"?: ...,
940 "policyMetadata"?: ...}``; a search result is bare JSON.
942 Raises:
943 StackOneAPIError: If the result carries ``isError``. A failed tool call comes
944 back as an ordinary response with that flag set, so without this check the
945 error body is handed to the caller as though it were a success.
946 """
947 texts = [getattr(part, "text", "") for part in result.content]
948 payload = "".join(t for t in texts if t)
949 # Parts that are not text (images, embedded resources) have no `.text`; keep them
950 # rather than silently returning an empty dict. As plain JSON, as Node returns them:
951 # the mcp package's pydantic objects broke json.dumps on the result, and
952 # execute_openai_tool_calls() sent the model their repr.
953 non_text = [_plain_part(part) for part in result.content if not getattr(part, "text", "")]
955 parsed: JsonDict = {}
956 structured = _mcp_field(result, "structured_content", "structuredContent")
957 if payload:
958 try:
959 # NaN and Infinity are not JSON; json.loads accepts them, JSON.parse does not,
960 # and the Node SDK hands such a payload back as text.
961 loaded = json.loads(payload, parse_constant=_reject_json_constant)
962 except ValueError:
963 loaded = payload
964 parsed = loaded if isinstance(loaded, dict) else {"result": loaded}
965 elif isinstance(structured, dict):
966 # A result may carry only structuredContent. Without this it came back as `{}`,
967 # a success with the whole payload missing. A copy, so content_parts below does
968 # not write into the caller's result.
969 parsed = dict(structured)
971 if _mcp_field(result, "is_error", "isError", False):
972 # The transport succeeded, so there is no HTTP status here — but the payload
973 # carries the real one, and a caller cannot branch on 0.
974 detail = payload or json.dumps(parsed, ensure_ascii=False, separators=(",", ":"), default=str)
975 raise StackOneAPIError(f"Tool {_json_text(name)} failed: {detail}", _status_of(parsed), parsed)
977 if non_text:
978 parsed["content_parts"] = non_text
979 return parsed
982def call_mcp_tool(
983 endpoint: str, headers: dict[str, str], name: str, arguments: JsonDict, *, timeout: float = 60.0
984) -> JsonDict:
985 """Invoke a tool over MCP ``tools/call``, the one way every tool is executed.
987 ``arguments`` are sent exactly as given; the server maps them onto the action.
988 """
989 from mcp import types as mcp_types
991 async def _call(session: Any) -> JsonDict:
992 # send_request rather than call_tool: call_tool validates structuredContent
993 # against the tool's output schema, and on a fresh session that means a
994 # tools/list first — relisting the whole catalog on every call, which the
995 # Node SDK never does. The result is parsed below either way.
996 request = mcp_types.CallToolRequest(
997 params=mcp_types.CallToolRequestParams(name=name, arguments=arguments)
998 )
999 result = await session.send_request(request, mcp_types.CallToolResult)
1000 return parse_tool_result(result, name)
1002 return _run_mcp_session(endpoint, headers, timeout, _call)
1005def is_end_user_refusal(exc: BaseException, account_id: str) -> bool:
1006 """Whether ``exc`` is the API's 400 for an account's request without its end user.
1008 The API answers an MCP request for a non-shared account whose ``x-end-user-id`` does not
1009 name the account's end user with a 400 whose message names the account, as in Node.
1010 """
1011 if not (isinstance(exc, StackOneAPIError) and exc.status_code == 400):
1012 return False
1013 body = exc.response_body
1014 if isinstance(body, str): 1014 ↛ 1019line 1014 didn't jump to line 1019 because the condition on line 1014 was always true
1015 try:
1016 body = json.loads(body)
1017 except ValueError:
1018 pass
1019 message = body.get("message") if isinstance(body, dict) else body
1020 # The guard's fixed wording, ending with this account's id, quoted or not: not an exact
1021 # string, so a change to how the id is written does not silently turn the lookup off.
1022 if not isinstance(message, str) or not message.startswith(
1023 "x-end-user-id header does not match account end user id"
1024 ):
1025 return False
1026 return message.rstrip().rsplit(" ", 1)[-1].strip("\"'") == account_id
1029def retry_for_end_user(
1030 call: Callable[[], T], accounts: Iterable[str], look_up: Callable[[str, Exception], bool] | None
1031) -> T:
1032 """``call()``, made once more if the API refused it for want of the end user of one of
1033 ``accounts`` (those it was sent without one for) and ``look_up`` then finds that end user.
1034 """
1035 try:
1036 return call()
1037 except StackOneAPIError as exc:
1038 refused = next((account for account in accounts if is_end_user_refusal(exc, account)), None)
1039 if refused is None or look_up is None or not look_up(refused, exc):
1040 raise
1041 return call()
1044def _strip_internal_keys(schema: Any) -> Any:
1045 """Recursively drop the SDK's internal markers from a property schema.
1047 Everything else is preserved verbatim: ``format``, ``pattern``, ``default``,
1048 ``minimum``/``maximum``, ``oneOf``/``anyOf``, nested ``required`` and any
1049 keyword the server sends that this SDK has never heard of.
1050 """
1051 if isinstance(schema, dict):
1052 return {
1053 key: _strip_internal_keys(value)
1054 for key, value in schema.items()
1055 if not (key == "nullable" and isinstance(value, bool))
1056 }
1057 if isinstance(schema, list):
1058 return [_strip_internal_keys(item) for item in schema]
1059 return schema
1062class StackOneTool(BaseModel):
1063 """A single tool: its served schema, and how to call it.
1065 The base class describes a tool and converts it for agent frameworks, but cannot run
1066 it: :meth:`execute` raises. Tools from :meth:`StackOneToolSet.fetch_tools` are
1067 :class:`StackOneMcpTool` instances, which execute over MCP ``tools/call``. A hand-built
1068 tool must override :meth:`execute`.
1069 """
1071 name: str = Field(description="Tool name")
1072 description: str = Field(description="Tool description")
1073 parameters: ToolParameters = Field(description="Tool parameters")
1074 _execute_config: ExecuteConfig = PrivateAttr()
1075 _api_key: str | None = PrivateAttr(default=None)
1076 _account_id: str | None = PrivateAttr(default=None)
1078 def __init__(
1079 self,
1080 description: str,
1081 parameters: ToolParameters,
1082 _execute_config: ExecuteConfig,
1083 # Optional: the base class cannot execute, so it has nothing to authenticate. Kept
1084 # as a parameter so existing hand-built tools and overrides that read it still work.
1085 _api_key: str | None = None,
1086 _account_id: str | None = None,
1087 ) -> None:
1088 super().__init__(
1089 name=_execute_config.name,
1090 description=description,
1091 parameters=parameters,
1092 )
1093 self._execute_config = _execute_config
1094 self._api_key = _api_key
1095 self._account_id = _account_id
1097 def _parse_arguments(self, arguments: str | JsonDict | None) -> JsonDict:
1098 """Arguments as a dict, from a dict, a JSON string, or nothing.
1100 Raises:
1101 ToolArgumentsError: If the string is not JSON, or the value is not a JSON object.
1102 """
1103 if arguments is None:
1104 return {}
1105 if isinstance(arguments, str):
1106 try:
1107 # NaN and Infinity are not JSON: json.loads accepts them, JSON.parse does not.
1108 parsed = json.loads(arguments, parse_constant=_reject_json_constant)
1109 except ValueError as exc:
1110 raise ToolArgumentsError(
1111 f"Invalid JSON in arguments for {_json_text(self.name)}: {exc}"
1112 ) from exc
1113 else:
1114 parsed = arguments
1115 if not isinstance(parsed, dict):
1116 raise ToolArgumentsError(f"Tool arguments for {_json_text(self.name)} must be a JSON object")
1117 return dict(parsed)
1119 def _declared_headers(self) -> tuple[set[str] | None, set[str], bool]:
1120 """The header names this tool's served schema declares.
1122 Returns ``(nested, flat, ordinary_headers_field)``: the names under a nested
1123 ``headers`` object, lower-cased in ASCII, each flat ``headers_<name>`` property exactly as
1124 served — a flat header is a top-level argument, so it is declared only under its
1125 own key, as in Node — and whether the schema declares a top-level ``headers``
1126 property as something other than an object, an ordinary field that happens to be
1127 named ``headers`` rather than a header container.
1128 ``nested`` is ``None`` when the ``headers`` object is open — ``type: "object"`` with
1129 no ``properties`` and ``additionalProperties`` not ``false``, as ``stackone_execute_action``
1130 serves it — which declares every name. Any other schema with no ``properties``
1131 declares none.
1132 """
1133 properties = self.parameters.properties or {}
1134 flat = {prop for prop in properties if prop.startswith(_FLAT_HEADER_PREFIX)}
1135 nested: set[str] | None = set()
1136 schema = properties.get("headers")
1137 schema_type = schema.get("type") if isinstance(schema, dict) else None
1138 declares_object = _declares_object_type(schema_type)
1139 # A declared type of `["string", "null"]` is a plain field that happens to be
1140 # named `headers`; `["object", "null"]` is still a header container, same as a
1141 # bare "object". Only a declared, non-object type makes it ordinary.
1142 ordinary_headers_field = (
1143 isinstance(schema, dict) and isinstance(schema_type, str | list) and not declares_object
1144 )
1145 if isinstance(schema, dict):
1146 if "properties" not in schema:
1147 if declares_object and schema.get("additionalProperties") is not False:
1148 nested = None
1149 elif isinstance(schema["properties"], dict):
1150 nested = {_ascii_lower(str(name)) for name in schema["properties"]}
1151 return nested, flat, ordinary_headers_field
1153 @staticmethod
1154 def _header_refusal(name: str, text: str, declared: bool) -> str | None:
1155 """The reason code a header argument may not be forwarded for, or ``None`` if it may."""
1156 # Normalise before comparing: " x-foo" and "X-FOO\t" are the same header to any
1157 # server. ASCII only: a name that differs from an owned one outside ASCII is not a
1158 # token, and is refused as malformed below.
1159 if _ascii_lower(_trim_header_name(name)) in _SDK_SET_HEADER_ARGUMENTS:
1160 return "set-by-sdk"
1161 if not declared:
1162 return "not-declared"
1163 # Defence in depth on a declared header's model-supplied value. fullmatch, not
1164 # match: `$` also matches just before a trailing newline, so `match` let "value\n"
1165 # — the one character class this rejects — straight through.
1166 if not (_HEADER_NAME_PATTERN.fullmatch(name) and _HEADER_VALUE_PATTERN.fullmatch(text)):
1167 return "malformed"
1168 return None
1170 def _sanitise_headers(self, supplied: dict[str, Any] | None) -> dict[str, str]:
1171 """Keep only the entries of a nested ``headers`` argument the served schema declares.
1173 An allowlist, not a denylist. Tool arguments are model-controlled, so a
1174 prompt-injected call reaches this dict directly — and a denylist has to
1175 enumerate every synonym of "credential" and "tenant selector" in every
1176 provider's vocabulary (Proxy-Authorization, x-stackone-account-id, Cookie,
1177 X-Api-Key, ...) and is wrong the moment one is missed.
1179 The allowlist is the served schema itself, so this needs no maintenance. An open
1180 ``headers`` object declares every name. Authorization, x-account-id, User-Agent and
1181 x-end-user-id are refused even when declared: the SDK sets them itself.
1182 """
1183 declared, _, _ = self._declared_headers()
1185 clean: dict[str, str] = {}
1186 for key, value in (supplied or {}).items():
1187 text = _header_text(value)
1188 if text is None or not isinstance(key, str):
1189 continue
1190 name = _trim_header_name(key)
1191 reason = self._header_refusal(name, text, declared is None or _ascii_lower(name) in declared)
1192 if reason:
1193 _warn_header_dropped("headers", name, reason)
1194 continue
1195 clean[name] = text
1196 return clean
1198 def _sanitise_header_arguments(self, arguments: JsonDict) -> JsonDict:
1199 """Filter the header arguments in a call; every other argument is kept unchanged.
1201 A header argument is an entry of a nested ``headers`` object, or a top-level
1202 ``headers_<name>``. Each is forwarded only if the served schema declares it in the
1203 same form, and never if it is one the SDK sets itself. A declared ``headers_<name>``
1204 keeps its value as given, as every other top-level argument does; nested entries
1205 are written as text, as Node writes them.
1207 A top-level ``headers`` argument that isn't a plain object is forwarded unchanged
1208 when the schema declares ``headers`` as something other than an object (it's an
1209 ordinary field that happens to be named ``headers``), and dropped otherwise. A flat
1210 ``headers_<name>`` whose value is a list or dict is dropped too — only a string,
1211 number or boolean can be a header value.
1213 Raises:
1214 TypeError: If a header value holds something JSON cannot represent.
1215 """
1216 _, declared_flat, ordinary_headers_field = self._declared_headers()
1217 clean: JsonDict = {}
1218 for key, value in arguments.items():
1219 if key == "headers":
1220 if ordinary_headers_field:
1221 clean[key] = value
1222 elif isinstance(value, dict):
1223 clean[key] = self._sanitise_headers(value)
1224 else:
1225 _warn_header_dropped(key, None, "not-an-object")
1226 continue
1227 if not key.startswith(_FLAT_HEADER_PREFIX):
1228 clean[key] = value
1229 continue
1230 if isinstance(value, dict | list):
1231 _warn_header_dropped(key, None, "not-a-scalar")
1232 continue
1233 text = _header_text(value)
1234 if text is None:
1235 continue
1236 reason = self._header_refusal(key[len(_FLAT_HEADER_PREFIX) :], text, key in declared_flat)
1237 if reason:
1238 _warn_header_dropped(key, None, reason)
1239 continue
1240 clean[key] = value
1241 return clean
1243 def execute(self, arguments: str | JsonDict | None = None) -> JsonDict:
1244 """Execute the tool. Not implemented on the base class.
1246 Tools from :meth:`StackOneToolSet.fetch_tools` execute over MCP ``tools/call``.
1247 A hand-built ``StackOneTool`` has nothing to call, so override this to run one.
1249 Raises:
1250 StackOneError: Always, on the base class.
1251 """
1252 raise StackOneError(
1253 f"Tool {_json_text(self.name)} has no executor. Override execute() to run a hand-built tool."
1254 )
1256 def call(self, *args: Any, **kwargs: Any) -> JsonDict:
1257 """Call the tool with the given arguments
1259 Examples:
1260 >>> tool.call({"name": "John", "email": "john@example.com"})
1261 >>> tool.call(name="John", email="john@example.com")
1262 """
1263 if args and kwargs:
1264 raise ToolArgumentsError("Cannot provide both positional and keyword arguments")
1266 if args:
1267 if len(args) > 1:
1268 raise ToolArgumentsError("Only one positional argument is allowed")
1269 return self.execute(args[0])
1271 return self.execute(kwargs if kwargs else None)
1273 def __call__(self, *args: Any, **kwargs: Any) -> JsonDict:
1274 """Make the tool directly callable. Alias for :meth:`call`."""
1275 return self.call(*args, **kwargs)
1277 def to_openai_function(self) -> JsonDict:
1278 """Convert this tool to OpenAI's function format.
1280 The served schema is passed through verbatim apart from the SDK's internal
1281 ``nullable`` marker, which is stripped. Constraints such as ``format``,
1282 ``pattern``, ``default``, ``minimum``/``maximum`` and ``oneOf``/``anyOf``
1283 reach the model intact — without them a model cannot generate valid arguments
1284 for a constrained field. ``required`` is the served list, in the served order,
1285 and is omitted when the server sent none or an empty one.
1286 """
1287 properties: JsonDict = {}
1288 for name, prop in self.parameters.properties.items():
1289 properties[name] = _strip_internal_keys(prop) if isinstance(prop, dict) else {"type": "string"}
1291 parameters: JsonDict = self.parameters.model_dump()
1292 parameters["properties"] = properties
1294 # Taken from the served root, not rebuilt from the per-property markers: that
1295 # rebuild re-sorted `required` into property order, so the model saw a list the
1296 # server never sent. A non-list `required`, or a non-string entry in one, is
1297 # malformed and dropped rather than iterated as characters or sent on.
1298 required = parameters.pop("required", None)
1299 names = [name for name in required if isinstance(name, str)] if isinstance(required, list) else []
1300 if names:
1301 parameters["required"] = names
1303 return {
1304 "type": "function",
1305 "function": {
1306 "name": self.name,
1307 "description": self.description,
1308 "parameters": parameters,
1309 },
1310 }
1312 def to_langchain(self) -> Any:
1313 """Convert this tool to LangChain format.
1315 Returns a ``langchain_core.tools.BaseTool``, typed as ``Any`` because
1316 ``langchain-core`` is an optional dependency and must not be imported at
1317 module level.
1319 Requires ``stackone-ai[langchain]``.
1320 """
1321 try:
1322 from langchain_core.tools import BaseTool, ToolException
1323 except ImportError as e:
1324 raise ImportError(
1325 "Install `langchain-core` (or `stackone-ai[langchain]`) to use the LangChain integration."
1326 ) from e
1328 # Hand the served JSON Schema over as-is. The previous version rebuilt a
1329 # pydantic model from the top-level `type` of each property, which threw away
1330 # every nested object's fields, every enum, format, bound, item type and union —
1331 # roughly half the schema, so the model was told "pass an object" with no field
1332 # names. langchain-core accepts a JSON Schema dict directly, which makes this
1333 # surface byte-equivalent to to_openai_function() for free.
1334 args_json_schema = self.to_openai_function()["function"]["parameters"]
1336 parent_tool = self
1338 class StackOneLangChainTool(BaseTool):
1339 name: str = parent_tool.name
1340 description: str = parent_tool.description
1341 args_schema: dict[str, Any] = args_json_schema # ty: ignore[incompatible-mutable-override]
1343 def _run(self, **kwargs: Any) -> Any:
1344 # Drop unsupplied optionals. pydantic materialises every optional field
1345 # as None and BaseTool passes them all through, and the API reads an
1346 # explicit null as "required field missing" — which 400'd every single
1347 # tool call made through this adapter.
1348 supplied = {key: value for key, value in kwargs.items() if value is not None}
1349 try:
1350 return parent_tool.execute(supplied)
1351 except (StackOneError, ValueError) as exc:
1352 # LangChain's handle_tool_error only catches ToolException, so a
1353 # StackOneError would kill the graph rather than reaching the
1354 # agent. Models guess arguments wrong and StackOne's 400 names the
1355 # offending field — re-raising in LangChain's own vocabulary lets
1356 # a caller opt into feeding that back and retrying.
1357 # Carry the structured fields across: without them handle_tool_error
1358 # leaves a caller with only str(exc), unable to tell 401 from 429.
1359 # The field that is actually wrong is often only in response_body.
1360 # Without it the agent retries blind, which is the whole point of
1361 # handing the error back.
1362 body = getattr(exc, "response_body", None)
1363 failure = ToolException(f"{exc}: {body}" if body else str(exc))
1364 failure.status_code = getattr(exc, "status_code", None) # ty: ignore[missing-attribute]
1365 failure.response_body = getattr(exc, "response_body", None) # ty: ignore[missing-attribute]
1366 raise failure from exc
1368 return StackOneLangChainTool()
1370 def to_pydantic_ai_tool(self) -> Any:
1371 """Convert this tool to a Pydantic AI ``Tool``.
1373 Returns ``pydantic_ai.tools.Tool``, typed as ``Any`` because ``pydantic-ai``
1374 is an optional dependency and must not be imported at module level.
1376 Requires ``stackone-ai[pydantic-ai]`` (installs ``pydantic-ai-slim``).
1377 """
1378 try:
1379 from pydantic_ai.exceptions import ModelRetry
1380 from pydantic_ai.tools import Tool
1381 except ImportError as e:
1382 raise ImportError(
1383 "Install `pydantic-ai-slim` (or `stackone-ai[pydantic-ai]`) "
1384 "to use the Pydantic AI integration."
1385 ) from e
1387 openai_function = self.to_openai_function()
1388 json_schema = openai_function["function"]["parameters"]
1389 parent_tool = self
1391 def implementation(**kwargs: Any) -> Any:
1392 try:
1393 return parent_tool.execute(kwargs)
1394 except (StackOneError, ValueError) as exc:
1395 # Tool.from_schema skips argument validation entirely, so every wrong
1396 # guess the model makes reaches the API — and a raised StackOneError
1397 # escaped the agent loop and ended the run. ModelRetry hands the
1398 # server's explanation back to the model so it can correct itself,
1399 # which is what the LangChain adapter already does via ToolException.
1400 body = getattr(exc, "response_body", None)
1401 raise ModelRetry(f"{exc}: {body}" if body else str(exc)) from exc
1403 return Tool.from_schema(
1404 function=implementation,
1405 name=self.name,
1406 description=self.description,
1407 json_schema=json_schema,
1408 )
1410 def set_account_id(self, account_id: str | None) -> None:
1411 """Set the account ID for this tool"""
1412 self._account_id = account_id
1414 def get_account_id(self) -> str | None:
1415 """Get the current account ID for this tool"""
1416 return self._account_id
1419class StackOneMcpTool(StackOneTool):
1420 """A tool executed over MCP ``tools/call`` on the endpoint that listed it.
1422 Every tool the toolset builds is one of these: per-action tools, the
1423 ``search_execute`` trio and ``stackone_submit_feedback``.
1424 """
1426 _endpoint: str = PrivateAttr()
1427 # The name the server listed the tool under, which tools/call must use: the same as
1428 # ``name`` except for a one-account pair presented under the trio's names.
1429 _served_name: str = PrivateAttr()
1430 # Set by the toolset that built the tool: the end-user id it recorded for an account.
1431 # Looked up per request, so a tool keeps up with a later GET /accounts and with
1432 # set_account_id().
1433 _end_user_id_of: Callable[[str], str | None] | None = PrivateAttr(default=None)
1434 # Also set by the toolset: given the API's refusal of a request sent without an end
1435 # user, looks the account's end user up, and says whether there now is one to retry with.
1436 _look_up_end_user: Callable[[str, Exception], bool] | None = PrivateAttr(default=None)
1438 def __init__(
1439 self,
1440 *,
1441 name: str,
1442 description: str,
1443 parameters: ToolParameters,
1444 api_key: str,
1445 endpoint: str,
1446 account_id: str | None,
1447 headers: Headers | None = None,
1448 timeout: float = 60.0,
1449 served_name: str | None = None,
1450 ) -> None:
1451 super().__init__(
1452 description=description,
1453 parameters=parameters,
1454 _execute_config=ExecuteConfig(name=name, headers=dict(headers or {}), timeout=timeout),
1455 _api_key=api_key,
1456 _account_id=account_id,
1457 )
1458 self._endpoint = endpoint
1459 self._served_name = served_name or name
1461 def _prepare_headers(self) -> Headers:
1462 """The request headers: the configured extras first, then the SDK's own.
1464 Authorization, x-account-id and User-Agent are set last, and any case variant of
1465 them among the extras is dropped first, so neither can replace the credential or
1466 retarget the call at another account. So is x-end-user-id, when the toolset recorded
1467 one for this tool's account; otherwise a configured x-end-user-id is sent as given.
1468 """
1469 end_user_id = self._recorded_end_user_id()
1470 # The constructor requires the key; only code that clears it afterwards gets here.
1471 if not self._api_key: 1471 ↛ 1472line 1471 didn't jump to line 1472 because the condition on line 1471 was never true
1472 raise StackOneError(f'Tool "{self.name}" has no API key to authenticate with.')
1473 return build_request_headers(
1474 api_key=self._api_key,
1475 account_id=self._account_id,
1476 end_user_id=end_user_id,
1477 extra_headers=self._execute_config.headers,
1478 )
1480 def _recorded_end_user_id(self) -> str | None:
1481 if self._end_user_id_of is None or not self._account_id:
1482 return None
1483 return self._end_user_id_of(self._account_id)
1485 def execute(self, arguments: str | JsonDict | None = None) -> JsonDict:
1486 """Call the tool over MCP ``tools/call``.
1488 Arguments are sent as given; the server maps them onto the action. Header arguments
1489 — the entries of a ``headers`` object and any ``headers_<name>`` — are the exception:
1490 these arguments are model-controlled, so each is kept only if this tool's own schema
1491 declares it, and never if it is Authorization, x-account-id, User-Agent or
1492 x-end-user-id.
1494 Returns:
1495 The tool's result as the server wrote it (see :func:`parse_tool_result`): for an
1496 action, ``{"isError": false, "result": ..., ...}``. A file action's ``result`` is a
1497 download link, not the file.
1499 Raises:
1500 StackOneAPIError: If the result carries ``isError``, with the status from its
1501 payload, or the endpoint answers with an HTTP error. A 400 asking for the
1502 end user of an account the toolset has none recorded for is answered first:
1503 the toolset looks it up with ``GET /accounts`` and the call is sent once more.
1504 ToolArgumentsError: If the arguments are not a JSON object or cannot be encoded.
1505 A subclass of both StackOneError and ValueError.
1506 """
1507 parsed = self._parse_arguments(arguments)
1509 unencodable = f"Arguments for {_json_text(self.name)} could not be encoded as JSON"
1510 try:
1511 # Without this a prompt-injected call could put its own Authorization or
1512 # x-account-id in a header argument the server unpacks.
1513 parsed = self._sanitise_header_arguments(parsed)
1514 # NaN and Infinity are not JSON; the MCP client would send them as null.
1515 non_finite = _first_non_finite(parsed)
1516 json.dumps(parsed, ensure_ascii=False).encode("utf-8")
1517 except (UnicodeEncodeError, TypeError, ValueError) as exc:
1518 # A lone surrogate, in any string or key however deep — what a model emits when a
1519 # token boundary splits an emoji — or a value JSON cannot encode (a set, bytes,
1520 # a cycle) would otherwise fail deep inside the MCP client and surface as a
1521 # transport error. It is an argument problem.
1522 raise ToolArgumentsError(f"{unencodable}: {exc}") from exc
1523 except RecursionError as exc:
1524 # A header value that contains itself, directly or through a cycle of nested
1525 # dicts/lists, recurses forever as _header_text walks it. Not a different
1526 # defect than the ones above: it's still an argument the server could never
1527 # have accepted.
1528 raise ToolArgumentsError(f"{unencodable}: circular reference") from exc
1529 if non_finite is not None:
1530 raise ToolArgumentsError(f"{unencodable}: {_js_number(non_finite)} is not a JSON number")
1532 def call() -> JsonDict:
1533 timeout = self._execute_config.timeout
1534 return call_mcp_tool(
1535 self._endpoint, self._prepare_headers(), self._served_name, parsed, timeout=timeout
1536 )
1538 account_id = self._account_id
1539 without_end_user = (
1540 [account_id] if account_id is not None and self._recorded_end_user_id() is None else []
1541 )
1542 return retry_for_end_user(call, without_end_user, self._look_up_end_user)
1545@dataclass(frozen=True)
1546class AccountPair:
1547 """The search and execute tools the server serves a ``search_execute`` listing of one account.
1549 Several accounts get the trio; one gets its own pair, named
1550 ``<connector>_<account>_search_actions`` and ``<connector>_<account>_execute_action``. The
1551 SDK presents the pair under the trio's names, so a caller and a model see one search and
1552 one execute tool however many accounts are in scope.
1553 """
1555 account_id: str
1556 connector: str
1558 @classmethod
1559 def serving(cls, served_name: str, account_id: str) -> AccountPair | None:
1560 """The pair a served tool belongs to, if it is one of an account's pair."""
1561 for suffix in (f"_{account_id}_search_actions", f"_{account_id}_execute_action"):
1562 if served_name.endswith(suffix) and len(served_name) > len(suffix):
1563 return cls(account_id, served_name[: -len(suffix)])
1564 return None
1566 @property
1567 def trio_names(self) -> dict[str, str]:
1568 """Each served name, and the trio name it is presented as."""
1569 served = f"{self.connector}_{self.account_id}"
1570 return {
1571 f"{served}_search_actions": SEARCH_ACTIONS_TOOL_NAME,
1572 f"{served}_execute_action": EXECUTE_ACTION_TOOL_NAME,
1573 }
1575 def renamed(self, value: Any) -> Any:
1576 """``value`` with every served name in its strings, however deep, read as its trio name.
1578 Descriptions, schemas and results name the pair's tools to each other ("run a hit with
1579 ..."); left as served, they would send a model to a tool it was never given.
1580 """
1581 if isinstance(value, str):
1582 for served, trio_name in self.trio_names.items():
1583 value = value.replace(served, trio_name)
1584 return value
1585 if isinstance(value, dict):
1586 return {self.renamed(key): self.renamed(item) for key, item in value.items()}
1587 if isinstance(value, list):
1588 return [self.renamed(item) for item in value]
1589 return value
1591 def presented(self, tool_def: McpToolDefinition) -> McpToolDefinition:
1592 """A served tool of the pair as the trio tool it stands for."""
1593 return McpToolDefinition(
1594 name=self.trio_names[tool_def.name],
1595 description=self.renamed(tool_def.description),
1596 input_schema=self.renamed(tool_def.input_schema),
1597 )
1600class StackOneAccountPairTool(StackOneMcpTool):
1601 """One tool of an account's pair, presented and called as the trio tool it stands for.
1603 It takes the trio's arguments: ``stackone_account_id`` and ``provider`` choose among
1604 accounts, and with one in scope they can only name that account, so they are checked and
1605 dropped, never sent. Its results read in trio names, and a search's hits carry the
1606 ``available_accounts`` and ``provider`` a trio search gives them.
1607 """
1609 _pair: AccountPair = PrivateAttr()
1611 def __init__(self, *, pair: AccountPair, **kwargs: Any) -> None:
1612 super().__init__(**kwargs)
1613 self._pair = pair
1615 def execute(self, arguments: str | JsonDict | None = None) -> JsonDict:
1616 """Call the served tool with the trio's arguments, answering as the trio tool would.
1618 Raises:
1619 ToolArgumentsError: If ``stackone_account_id`` names another account, or
1620 ``provider`` another connector, before any request is made.
1621 StackOneAPIError: As :meth:`StackOneMcpTool.execute`, its text in trio names.
1622 """
1623 scoped = self._without_scope_arguments(self._parse_arguments(arguments))
1624 try:
1625 result = self._pair.renamed(super().execute(scoped))
1626 except StackOneAPIError as exc:
1627 renamed = StackOneAPIError(
1628 self._pair.renamed(str(exc)), exc.status_code, self._pair.renamed(exc.response_body)
1629 )
1630 raise renamed from exc
1631 return self._with_hits_scoped(result) if self.name == SEARCH_ACTIONS_TOOL_NAME else result
1633 def _without_scope_arguments(self, arguments: JsonDict) -> JsonDict:
1634 """The arguments without ``stackone_account_id`` and ``provider``, once each is checked
1635 to name this pair's account and connector. ``None`` is not given, as for ``session_id``."""
1636 scoped = dict(arguments)
1637 account = scoped.pop("stackone_account_id", None)
1638 if account is not None and account != self._pair.account_id:
1639 raise ToolArgumentsError(
1640 f"stackone_account_id {_json_text(account)} is not an account {_json_text(self.name)} "
1641 f"can run on; it runs on {_json_text(self._pair.account_id)}."
1642 )
1643 provider = scoped.pop("provider", None)
1644 if provider is not None and not (
1645 isinstance(provider, str) and provider.lower() == self._pair.connector.lower()
1646 ):
1647 raise ToolArgumentsError(
1648 f"provider {_json_text(provider)} is not linked in this account scope, "
1649 f"which has {_json_text(self._pair.connector)}."
1650 )
1651 return scoped
1653 def _with_hits_scoped(self, result: JsonDict) -> JsonDict:
1654 """A search result whose hits name the account and connector they run on, when the
1655 server left them out."""
1656 hits = result.get("actions")
1657 if not isinstance(hits, list): 1657 ↛ 1658line 1657 didn't jump to line 1658 because the condition on line 1657 was never true
1658 return result
1659 scope = {"available_accounts": [{"id": self._pair.account_id}], "provider": self._pair.connector}
1660 return {**result, "actions": [{**scope, **hit} if isinstance(hit, dict) else hit for hit in hits]}
1663def _read_openai_tool_call(call: Any) -> tuple[str, str, str | JsonDict]:
1664 """Pull (id, name, arguments) from an openai ToolCall object or its dict form."""
1665 if isinstance(call, dict):
1666 function = call.get("function") or {}
1667 return str(call.get("id", "")), str(function.get("name", "")), function.get("arguments") or {}
1668 function = call.function
1669 return str(call.id), str(function.name), function.arguments or {}
1672class Tools:
1673 """Container for Tool instances with lookup capabilities"""
1675 def __init__(self, tools: list[StackOneTool]) -> None:
1676 self.tools = tools
1677 # First listing wins, as Node's getTool() finds the first match.
1678 self._tool_map: dict[str, StackOneTool] = {}
1679 for tool in tools:
1680 self._tool_map.setdefault(tool.name, tool)
1682 # Two accounts on one provider serve identically named tools, and get_tool()
1683 # returns only one of them — the only symptom would otherwise be an action running
1684 # against an account the caller never chose.
1685 self._warn_duplicate_names()
1687 def _warn_duplicate_names(self) -> None:
1688 """Warn once if more than one tool has the same name."""
1689 if len(self._tool_map) == len(self.tools):
1690 return
1691 counts = Counter(tool.name for tool in self.tools)
1692 clashing = sorted(name for name, count in counts.items() if count > 1)
1693 logger.warning(
1694 "%d tool name(s) are served by more than one account (%s). The first one listed, from the "
1695 "lowest account id, is used — pass account ids to choose.",
1696 len(clashing),
1697 ", ".join(clashing[:5]),
1698 )
1700 def _first_per_name(self) -> list[StackOneTool]:
1701 """The first tool of each name, in order: the one :meth:`get_tool` returns.
1703 Every adapter is built from these, so a model is never offered a tool a lookup by
1704 name would not find. OpenAI was sent two functions of one name, and LangChain and
1705 Pydantic AI each kept whichever their own lookup happened to find.
1706 """
1707 return list(self._tool_map.values())
1709 def __getitem__(self, index: int) -> StackOneTool:
1710 return self.tools[index]
1712 def __len__(self) -> int:
1713 return len(self.tools)
1715 def __iter__(self) -> Any:
1716 """Make Tools iterable"""
1717 return iter(self.tools)
1719 def to_list(self) -> list[StackOneTool]:
1720 """Convert to list of tools"""
1721 return list(self.tools)
1723 def get_tool(self, name: str) -> StackOneTool | None:
1724 """Get a tool by its name, or None if absent.
1726 When more than one account serves the name, this is the first one listed.
1727 """
1728 return self._tool_map.get(name)
1730 def set_account_id(self, account_id: str | None) -> None:
1731 """Set the account ID for all tools in this collection"""
1732 for tool in self.tools:
1733 tool.set_account_id(account_id)
1735 def get_account_id(self) -> str | None:
1736 """Get the first non-None account ID found, or None if none set"""
1737 for tool in self.tools:
1738 account_id = tool.get_account_id()
1739 if isinstance(account_id, str):
1740 return account_id
1741 return None
1743 def to_openai(self) -> list[JsonDict]:
1744 """Convert the tools to OpenAI function format, the first of each name only."""
1745 return [tool.to_openai_function() for tool in self._first_per_name()]
1747 def execute_openai_tool_calls(self, tool_calls: Iterable[Any] | None) -> list[JsonDict]:
1748 """Run a Chat Completions response's tool calls and return the ``tool`` messages.
1750 The counterpart to :meth:`to_openai`: that turns these tools into what OpenAI
1751 accepts, this turns what OpenAI returns back into messages to send it. Append
1752 the assistant message first, then these, in order::
1754 message = response.choices[0].message
1755 messages.append(message.model_dump(exclude_none=True))
1756 messages.extend(tools.execute_openai_tool_calls(message.tool_calls))
1758 A failed call does not raise. Its error becomes the tool message's content, so
1759 the model can read why and retry — the same thing the LangChain and Pydantic AI
1760 adapters do. A call to a tool that is not in this collection is reported the
1761 same way.
1763 Accepts the ``openai`` package's objects or plain dicts, so it needs no extra.
1764 """
1765 messages: list[JsonDict] = []
1766 for call in tool_calls or []:
1767 call_id, name, arguments = _read_openai_tool_call(call)
1768 tool = self.get_tool(name)
1769 if tool is None:
1770 result: Any = {"error": f"Unknown tool {_json_text(name)}"}
1771 else:
1772 try:
1773 result = tool.execute(arguments)
1774 except (StackOneError, ValueError) as exc:
1775 body = getattr(exc, "response_body", None)
1776 result = {"error": str(exc), **({"response_body": body} if body else {})}
1777 # default=str: a hand-built tool may return something JSON cannot encode.
1778 content = json.dumps(result, default=str)
1779 messages.append({"role": "tool", "tool_call_id": call_id, "content": content})
1780 return messages
1782 def to_langchain(self) -> Sequence[Any]:
1783 """Convert the tools to LangChain format, the first of each name only.
1785 Requires ``stackone-ai[langchain]``.
1786 """
1787 return [tool.to_langchain() for tool in self._first_per_name()]
1789 def to_pydantic_ai(self) -> list[Any]:
1790 """Convert the tools to Pydantic AI ``Tool`` instances, the first of each name only.
1792 Requires ``stackone-ai[pydantic-ai]`` (installs ``pydantic-ai-slim``).
1793 """
1794 return [tool.to_pydantic_ai_tool() for tool in self._first_per_name()]