Coverage for stackone_ai / toolset.py: 99%
445 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"""The StackOne toolset: fetches the served tool catalog and exposes it to agent frameworks."""
3from __future__ import annotations
5import concurrent.futures
6import contextlib
7import copy
8import fnmatch
9import functools
10import logging
11import os
12import threading
13import time
14from collections.abc import Callable, Sequence
15from dataclasses import dataclass, field
16from typing import Any, TypeVar
17from urllib.parse import urlencode
19import httpx
21from stackone_ai.tools import (
22 AccountPair,
23 McpToolDefinition,
24 RateLimitRetryingClient,
25 RateLimitTimeout,
26 StackOneAccountPairTool,
27 StackOneMcpTool,
28 StackOneTool,
29 Tools,
30 _js_number,
31 _json_text,
32 _json_type,
33 _ssl_context,
34 build_request_headers,
35 fetch_mcp_tools,
36 is_rate_limited,
37 is_sdk_owned_header,
38 retry_for_end_user,
39)
40from stackone_ai.types import (
41 DEFAULT_BASE_URL,
42 EXECUTE_ACTION_TOOL_NAME,
43 SEARCH_ACTIONS_TOOL_NAME,
44 SUBMIT_FEEDBACK_TOOL_NAME,
45 ExecuteToolsConfig,
46 FeedbackCategory,
47 FeedbackRating,
48 FeedbackSource,
49 Headers,
50 JsonDict,
51 StackOneAPIError,
52 StackOneError,
53 ToolMode,
54 ToolParameters,
55 ToolsetConfigError,
56 ToolsetLoadError,
57)
59logger = logging.getLogger("stackone.tools")
61_UNSET = object()
62"""Sentinel: `mode=None` is a real mode (individual), so it cannot mean "use the default"."""
64_Listing = tuple[McpToolDefinition, str | None, str]
65"""A served tool, the account that listed it, and the endpoint it was listed from."""
67# stackone_search_actions' served schema caps top_k at 50.
68_MAX_TOP_K = 50
70# The server spans at most this many accounts in one search_execute request.
71_MAX_SEARCH_EXECUTE_ACCOUNTS = 50
73FAILED_ACCOUNT_RETRY_SECONDS = 30.0
74"""How long an account that failed to list tools is left out of a cached individual-mode
75catalog.
77Its healthy siblings' listings are cached all the same. A later call within this window
78serves them without the failed account, and without warning about it again; the first
79call after it lists the failed account again. A ``search_execute`` catalog is one listing
80for the whole scope, so it has no account to leave out.
81"""
83# Looked up at call time, so tests can move it on rather than wait.
84_clock = time.monotonic
87@dataclass(frozen=True)
88class _Catalog:
89 """A cached catalog: each healthy account's listing, and when each failed one failed.
91 A ``search_execute`` catalog is one listing for the whole scope, under ``None``.
92 """
94 listings: dict[str | None, list[_Listing]]
95 failed_at: dict[str | None, float] = field(default_factory=dict)
97 def in_order(self, account_scope: list[str | None]) -> list[_Listing]:
98 return [listing for account in account_scope for listing in self.listings.get(account, [])]
101_Item = TypeVar("_Item")
102_Result = TypeVar("_Result")
105def _fan_out(
106 fn: Callable[[_Item], _Result], items: Sequence[_Item]
107) -> list[tuple[_Item, _Result | Exception]]:
108 """Run ``fn`` over ``items`` concurrently; each item's result or failure, in item order.
110 A 429 that outlasted its retries is raised at once instead of being returned: the
111 caller would skip it like any other failure and hand back a partial result. Work not
112 yet started is cancelled; calls already running finish in the background, unread.
113 """
114 pool = concurrent.futures.ThreadPoolExecutor(max_workers=min(len(items), 10))
115 try:
116 futures = {pool.submit(fn, item): index for index, item in enumerate(items)}
117 outcomes: dict[int, _Result | Exception] = {}
118 for future in concurrent.futures.as_completed(futures):
119 try:
120 outcomes[futures[future]] = future.result()
121 except Exception as exc:
122 if is_rate_limited(exc):
123 raise
124 outcomes[futures[future]] = exc
125 finally:
126 pool.shutdown(wait=False, cancel_futures=True)
127 return [(item, outcomes[index]) for index, item in enumerate(items)]
130def _all_accounts_failed(failures: list[tuple[str | None, Exception]]) -> Exception:
131 """The error for a listing in which every account failed, in account order.
133 When every failure is a StackOneAPIError with the same status, the first of them: two
134 accounts answering 401 are a revoked key, and a caller must be able to tell that from a
135 429 as it can with one account. Otherwise a ToolsetLoadError, caused by an
136 ExceptionGroup of the failures and keeping them in ``failures`` too.
137 """
138 errors = [failure for _, failure in failures]
139 first = errors[0]
140 if isinstance(first, StackOneAPIError) and all(
141 isinstance(error, StackOneAPIError) and error.status_code == first.status_code for error in errors
142 ):
143 return first
144 error = ToolsetLoadError(
145 "Every account failed to list tools: "
146 + "; ".join(f"{account}: {failure}" for account, failure in failures),
147 failures=errors,
148 )
149 error.__cause__ = ExceptionGroup("Every account failed to list tools", errors)
150 return error
153class StackOneToolSet:
154 """Main class for accessing StackOne tools.
156 The toolset is a thin client over the served catalog: it lists tools from the
157 MCP endpoint and executes each one over MCP ``tools/call`` on the endpoint, and
158 with the account, that listed it. It does not rewrite, filter or invent schemas.
159 """
161 def __init__(
162 self,
163 api_key: str | None = None,
164 account_id: str | None = None,
165 base_url: str | None = None,
166 execute: ExecuteToolsConfig | None = None,
167 timeout: float | None = None,
168 tool_mode: ToolMode | None = None,
169 headers: Headers | None = None,
170 include_non_shared: bool = False,
171 ) -> None:
172 """Initialize StackOne tools with authentication
174 Args:
175 api_key: Optional API key. If not provided, will try to get from STACKONE_API_KEY env var
176 account_id: Optional account ID
177 base_url: Optional base URL override for API requests. Falls back to
178 STACKONE_BASE_URL, then to the default, https://api.stackone.com. An
179 empty string, whether passed here or read from the environment, is
180 treated as not set rather than as a literal empty host.
181 execute: Execution configuration. Controls default account scoping
182 for tool execution. Pass ``{"account_ids": ["acc-1"]}`` to scope
183 tools to specific accounts.
184 timeout: Request timeout in seconds for tool listing and execution.
185 Default: 60. Takes precedence over ``execute.timeout`` if set.
186 Increase for slow providers (e.g. Workday).
187 tool_mode: How the endpoint lists tools. ``"search_execute"`` returns
188 ``stackone_list_accounts``, ``stackone_search_actions`` and
189 ``stackone_execute_action``, spanning every account in scope (at most
190 50), instead of one tool per action, keeping the catalog small enough
191 for a model's context. For one account the server serves that account's
192 own search and execute pair, presented under the same two names, and no
193 ``stackone_list_accounts``.
194 headers: Extra HTTP headers sent with every request this toolset makes
195 (``GET /accounts`` and every MCP request). ``Authorization``,
196 ``x-account-id`` and ``User-Agent`` are always the SDK's own and
197 cannot be set here. ``x-end-user-id`` can: it is passed through as
198 given, unless ``GET /accounts`` reported the account's end user,
199 which then replaces it.
200 include_non_shared: Whether account discovery uses non-shared accounts
201 (``shared`` false in ``GET /accounts``). Each belongs to a single end
202 user, so by default discovery skips them, with a warning naming them;
203 pass their ids to use them without this.
205 Raises:
206 ToolsetConfigError: If no API key is provided or found in environment, or
207 ``account_id`` is an empty string
208 """
209 # An empty account_id is usually an unset variable, and treating it as unset would
210 # silently widen every call to all active shared accounts.
211 if account_id == "":
212 raise ToolsetConfigError("account_id must not be an empty string")
213 api_key_value = api_key or os.getenv("STACKONE_API_KEY")
214 if not api_key_value:
215 raise ToolsetConfigError(
216 "An API key must be provided, either to the toolset or in the STACKONE_API_KEY "
217 "environment variable"
218 )
219 ignored_headers = [name for name in (headers or {}) if is_sdk_owned_header(name)]
220 if ignored_headers:
221 logger.warning(
222 "Ignoring headers %s: the SDK sets them itself. Pass the API key and account ids "
223 "through their own options instead.",
224 ", ".join(_json_text(name) for name in ignored_headers),
225 )
227 self.api_key: str = api_key_value
228 self.account_id = account_id
229 self.base_url = base_url or os.getenv("STACKONE_BASE_URL") or DEFAULT_BASE_URL
230 self._headers: Headers = dict(headers or {})
231 self._account_ids: list[str] = self._validate_account_ids(
232 execute.get("account_ids") if execute else None
233 )
234 execute_timeout = execute.get("timeout") if execute else None
235 self._timeout: float = (
236 timeout if timeout is not None else (execute_timeout if execute_timeout is not None else 60.0)
237 )
238 # Cache the listing, not the Tools wrapper. StackOneTool objects are mutable
239 # (Tools.set_account_id rebinds them), so handing the same instances back on a
240 # cache hit let one caller silently rescope every later caller's tools.
241 self._catalog_cache: dict[tuple[Any, ...], _Catalog] = {}
242 self._discovered_account_ids: list[str] | None = None
243 # Shared while in flight, so concurrent fetch_tools() and search() calls on a
244 # fresh toolset make one GET /accounts between them rather than one each.
245 self._discovering: concurrent.futures.Future[list[str]] | None = None
246 # Bumped by clear_catalog_cache(). A listing already in flight when the cache is
247 # cleared captured the generation it started under, and refuses to write back if
248 # it has moved — otherwise the stale catalog lands *after* the clear and is
249 # served for the life of the process, which is the one thing the clear exists
250 # to prevent.
251 self._cache_generation = 0
252 self._cache_lock = threading.Lock()
253 # Each non-shared account's end-user id, from the last successful GET /accounts.
254 # Replaced whole by the next one, and kept by clear_catalog_cache(): it describes
255 # the accounts, not the catalog.
256 self._end_user_ids: dict[str, str] = {}
257 # Each account's provider, from the same GET /accounts and replaced with it: what
258 # fetch_tools(providers=...) narrows a search_execute scope by.
259 self._providers: dict[str, str] = {}
260 # The GET /accounts in flight, if any: an account's end user is looked up by joining
261 # it rather than making another.
262 self._fetching_accounts: concurrent.futures.Future[list[JsonDict]] | None = None
263 self._include_non_shared = include_non_shared
264 # Bumped at the start of every fetch_accounts() call, so two overlapping calls —
265 # fetch_accounts() racing discovery, say — are ordered by when they started
266 # rather than when they returned: a slower, older-started response must not
267 # overwrite a newer one that already landed.
268 self._accounts_sequence = 0
269 self._end_user_ids_sequence = 0
270 self._tool_mode: ToolMode | None = tool_mode
272 # 2.x read STACKONE_ACCOUNT_ID; 3.x never does, and without an account it uses every
273 # active shared account on the key. Anyone upgrading with only the variable set would
274 # otherwise widen to other end users' accounts with no sign of it. An empty
275 # account_ids list is unset too, the same as _resolve_account_ids() treats it.
276 scoped = account_id is not None or bool(self._account_ids)
277 if os.getenv("STACKONE_ACCOUNT_ID") and not scoped:
278 logger.warning(
279 "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, "
280 "every active shared account on this API key is used. Pass an account id to scope the "
281 "toolset."
282 )
284 def set_accounts(self, account_ids: list[str] | None) -> StackOneToolSet:
285 """Set account IDs for filtering tools
287 Returns:
288 This toolset instance for chaining
289 """
290 self._account_ids = self._validate_account_ids(account_ids)
291 self.clear_catalog_cache()
292 return self
294 def clear_catalog_cache(self) -> None:
295 """Invalidate the cached tool catalog.
297 Call when linked accounts change outside of ``set_accounts`` or when
298 you need to force a fresh fetch from the StackOne MCP endpoint. The end-user ids
299 and providers recorded from GET /accounts are kept until the next one replaces them.
300 """
301 with self._cache_lock:
302 self._cache_generation += 1
303 self._catalog_cache.clear()
304 self._discovered_account_ids = None
305 self._discovering = None
307 def fetch_tools(
308 self,
309 *,
310 account_ids: list[str] | None = None,
311 providers: list[str] | None = None,
312 actions: list[str] | None = None,
313 mode: ToolMode | None = _UNSET, # ty: ignore[invalid-parameter-default]
314 ) -> Tools:
315 """Fetch tools with optional filtering by account IDs, providers, and actions
317 Args:
318 account_ids: Optional list of account IDs to filter by.
319 If not provided, uses accounts set via set_accounts()
320 providers: Optional list of provider names (e.g., ['hibob', 'bamboohr']).
321 Case-insensitive matching. In individual mode it keeps the tools named
322 after these providers; in ``search_execute`` mode, whose tools are named
323 after no provider, it narrows the accounts listed to those whose
324 ``GET /accounts`` provider is one of these, looking them up first if
325 needed. No matching account means no tools.
326 actions: Optional list of action patterns with glob support
327 (e.g., ['*_list_employees', 'hibob_create_employees'])
328 mode: ``tool_mode`` for this call only. ``None`` lists one tool per action,
329 even on a toolset built with ``tool_mode="search_execute"``. Defaults to the
330 toolset's ``tool_mode``.
332 Returns:
333 Collection of tools matching the filter criteria
335 Raises:
336 ToolsetLoadError: If there is an error loading the tools. When every account
337 fails for differing reasons, its ``failures`` holds each account's error,
338 and its ``__cause__`` is an ExceptionGroup of them.
339 StackOneAPIError: With ``status_code`` 429 if the API is still rate limiting
340 after retries, even when only one of several accounts is; or with the API's
341 status when every account fails with that same status, so a caller can tell
342 a revoked key's 401 from a 429. Other per-account failures skip that account
343 with a warning, and leave it out for ``FAILED_ACCOUNT_RETRY_SECONDS``. In
344 ``search_execute`` mode every account is listed in one request, so any
345 failure is raised.
347 A 429 is retried up to three times, after the server's ``Retry-After`` (capped at
348 30 seconds) or else a 1s, 2s, 4s backoff with jitter. A wait that would not end
349 within ``timeout`` is not started, and the 429 is raised instead.
351 Examples:
352 tools = toolset.fetch_tools(account_ids=['123', '456'])
353 tools = toolset.fetch_tools(providers=['hibob', 'bamboohr'])
354 tools = toolset.fetch_tools(actions=['*_list_employees'])
356 Note:
357 For organizations with multiple connected accounts, calling `fetch_tools()`
358 without `account_ids` discovers and fetches the catalog for every active shared
359 account (non-shared ones too with ``include_non_shared=True``).
360 If your organization has many accounts, pass explicit `account_ids` to avoid
361 excessive round trips and blowing model context limits.
363 Discovery skips non-shared accounts unless the toolset was built with
364 ``include_non_shared=True``.
365 """
366 mode = self._tool_mode if mode is _UNSET else mode
367 try:
368 # Captured before account resolution, which may discover accounts: a
369 # clear_catalog_cache() landing mid-discovery must stop the catalog it
370 # resolves to from being cached too, not just the discovered list itself.
371 generation = self._cache_generation
372 account_scope: list[str | None] = sorted(
373 dict.fromkeys(self._resolve_account_ids(account_ids)), key=lambda a: (a is None, a)
374 )
375 if mode == "search_execute" and providers:
376 # The trio is named after no provider: narrow the accounts it spans instead.
377 account_scope = [*self._accounts_of_providers(account_scope, providers)]
378 if not account_scope:
379 return Tools([])
380 providers = None
382 # Keyed on what was fetched, not on how it is filtered: providers and
383 # actions narrow the list in memory, so they must not force a refetch.
384 # base_url and api_key belong here — leaving them out meant reassigning
385 # either one kept serving the old catalog, still pointed at the old host.
386 listings = self._catalog(account_scope, mode, generation)
388 # One account is served its own search and execute pair rather than the trio.
389 pair_account = account_scope[0] if mode == "search_execute" and len(account_scope) == 1 else None
390 all_tools = [
391 self._create_tool(tool_def, account, endpoint, pair_account)
392 for tool_def, account, endpoint in self._dedupe_global_tools(listings)
393 ]
395 if providers:
396 all_tools = [tool for tool in all_tools if self._filter_by_provider(tool.name, providers)]
398 if actions:
399 all_tools = [tool for tool in all_tools if self._filter_by_action(tool.name, actions)]
401 return Tools(all_tools)
403 except StackOneError:
404 # StackOneAPIError carries the HTTP status. Re-wrapping it below would throw
405 # that away, so a caller could not tell a 401 from a 429.
406 raise
407 except Exception as exc: # pragma: no cover - unexpected runtime errors
408 raise ToolsetLoadError(f"Error fetching tools: {exc}") from exc
410 @staticmethod
411 def _validate_account_ids(account_ids: Any) -> list[str]:
412 """A copy of the account ids, refusing a bare string, a non-list, a non-string id or
413 an empty id. ``None`` means not given: no ids.
415 An empty or ``None`` id would be sent with no ``x-account-id``, so it is rejected
416 rather than letting the server answer for an account nobody chose, as in Node. A
417 dict is refused rather than iterated, which read ``{"id": "acc-1"}`` as the account
418 ``"id"``.
419 """
420 if account_ids is None:
421 return []
422 if isinstance(account_ids, str):
423 raise ToolsetConfigError(
424 "account_ids must be a list of account ids, not a string. "
425 f"Did you mean [{_json_text(account_ids)}]?"
426 )
427 if not isinstance(account_ids, list) or not all(isinstance(i, str) for i in account_ids):
428 raise ToolsetConfigError("account_ids must be a list of account id strings")
429 ids = list(account_ids)
430 if "" in ids:
431 raise ToolsetConfigError("account_ids must not contain an empty account id")
432 return ids
434 def _resolve_account_ids(self, account_ids: list[str] | None) -> list[str]:
435 """The accounts a call is scoped to, in the order they were given or discovered.
437 The argument, then ``set_accounts()``, then the constructor's ``account_id``, then
438 every active shared account ``GET /accounts`` lists (non-shared ones too with
439 ``include_non_shared=True``).
440 """
441 if account_ids is not None:
442 account_ids = self._validate_account_ids(account_ids)
443 resolved = account_ids or self._account_ids
444 if not resolved and self.account_id:
445 resolved = [self.account_id]
446 if not resolved:
447 resolved = self._discover_account_ids()
448 return list(resolved)
450 def _catalog(
451 self,
452 account_scope: list[str | None],
453 mode: ToolMode | None,
454 generation: int,
455 ) -> list[_Listing]:
456 """Every scoped account's catalog, from the cache where it can be.
458 In ``search_execute`` mode, see :meth:`_search_execute_catalog`. Otherwise one
459 unusable account must not cost the caller every other account's tools, so a
460 failing account is skipped with a warning. The healthy accounts' listings are cached
461 all the same, and the failed account is left out, silently, until
462 ``FAILED_ACCOUNT_RETRY_SECONDS`` have passed, when the next call lists it again. Not
463 caching at all made every call re-list every account, and wait out the full timeout
464 on one that hangs.
466 A 429 that outlasts its retries is raised, not skipped: it is the key's, not the
467 account's, and skipping it would hand back a catalog missing whichever accounts
468 happened to be throttled. When every account fails, see :func:`_all_accounts_failed`.
470 ``generation`` is the cache generation as of the start of the call that resolved
471 ``account_scope``: a clear_catalog_cache() during account discovery must stop the
472 catalog this scope resolves to from being cached, same as the discovered list.
473 """
474 key = self._cache_key(account_scope, mode)
475 if mode == "search_execute":
476 return self._search_execute_catalog(
477 [account for account in account_scope if account is not None], key, generation
478 )
479 with self._cache_lock:
480 cached = self._catalog_cache.get(key)
481 now = _clock()
482 if cached is None:
483 due = account_scope
484 else:
485 due = [
486 account
487 for account, failed_at in cached.failed_at.items()
488 if now - failed_at >= FAILED_ACCOUNT_RETRY_SECONDS
489 ]
490 if not due:
491 return cached.in_order(account_scope)
493 # No param-style pin: arguments are sent verbatim and the server maps them with its
494 # own reverse map, so the model sees whatever style the server serves.
495 endpoint = f"{self.base_url.rstrip('/')}/mcp"
496 if mode:
497 endpoint = f"{endpoint}?tool-mode={mode}"
499 def _fetch_for_account(
500 account: str | None,
501 ) -> list[_Listing]:
502 without_end_user = [account] if account is not None and self._end_user_id(account) is None else []
503 listed = retry_for_end_user(
504 lambda: fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout),
505 without_end_user,
506 self._look_up_end_user,
507 )
508 return [(tool_def, account, endpoint) for tool_def in listed]
510 def _store(catalog: _Catalog) -> None:
511 # Merged with whatever is cached now, not overwritten: a concurrent call for the
512 # same key may have stored a healthier catalog since this call read it, and a
513 # wholesale overwrite would hide its successes behind this call's failures for
514 # FAILED_ACCOUNT_RETRY_SECONDS. A listing wins over a failure for the same account.
515 with self._cache_lock:
516 if generation != self._cache_generation:
517 return
518 existing = self._catalog_cache.get(key)
519 if existing is not None:
520 merged_listings = {**existing.listings, **catalog.listings}
521 merged_failed_at = {**existing.failed_at, **catalog.failed_at}
522 for account in catalog.listings:
523 merged_failed_at.pop(account, None)
524 catalog = _Catalog(merged_listings, merged_failed_at)
525 self._catalog_cache[key] = catalog
527 if len(account_scope) == 1:
528 catalog = _Catalog({account_scope[0]: _fetch_for_account(account_scope[0])})
529 _store(catalog)
530 return catalog.in_order(account_scope)
532 listings = dict(cached.listings) if cached else {}
533 failed_at = dict(cached.failed_at) if cached else {}
534 failures: list[tuple[str | None, Exception]] = []
535 for account, outcome in _fan_out(_fetch_for_account, due):
536 if isinstance(outcome, Exception):
537 failures.append((account, outcome))
538 else:
539 listings[account] = outcome
540 failed_at.pop(account, None)
541 if not listings:
542 raise _all_accounts_failed(failures)
543 failed_now = _clock()
544 for account, failure in failures:
545 logger.warning("Skipping account that failed to list tools — %s: %s", account, failure)
546 failed_at[account] = failed_now
548 catalog = _Catalog(listings, failed_at)
549 _store(catalog)
550 return catalog.in_order(account_scope)
552 def _search_execute_catalog(
553 self, account_scope: list[str], key: tuple[Any, ...], generation: int
554 ) -> list[_Listing]:
555 """The ``search_execute`` tools spanning every scoped account, from one listing: the
556 trio for several accounts, the account's own pair for one.
558 The server spans every account the request names behind one search and one execute
559 tool, so there is no account to skip: a failure is raised. A refusal for want of the
560 end user of an account sent without one is answered as in individual mode: the end
561 users are looked up, and the scope listed once more. The tools bind no account and
562 execute on the endpoint that listed them, which names the accounts.
564 Raises:
565 ToolsetConfigError: If the scope has more accounts than one request can span,
566 before any request is made.
567 """
568 if len(account_scope) > _MAX_SEARCH_EXECUTE_ACCOUNTS:
569 raise ToolsetConfigError(
570 f"{len(account_scope)} accounts are in scope, but search and execute span at most "
571 f"{_MAX_SEARCH_EXECUTE_ACCOUNTS} in one request. Pass account ids to narrow the scope."
572 )
573 with self._cache_lock:
574 cached = self._catalog_cache.get(key)
575 if cached is not None:
576 return cached.listings[None]
578 def _list() -> list[_Listing]:
579 endpoint = self._search_execute_endpoint(account_scope)
580 listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(None), timeout=self._timeout)
581 return [(tool_def, None, endpoint) for tool_def in listed]
583 without_end_user = [account for account in account_scope if self._end_user_id(account) is None]
584 listings = retry_for_end_user(_list, without_end_user, self._look_up_end_user)
586 with self._cache_lock:
587 if generation == self._cache_generation: 587 ↛ 589line 587 didn't jump to line 589
588 self._catalog_cache[key] = _Catalog({None: listings})
589 return listings
591 def _search_execute_endpoint(self, account_scope: list[str]) -> str:
592 """The MCP endpoint listing search and execute for these accounts.
594 The accounts go as one ``x-account-id`` query value, joined by commas, and the recorded
595 end user of each non-shared one as a repeated ``x-end-user-id``: the server matches each
596 end user exactly, so they cannot be joined, and as headers some HTTP stacks would join
597 them.
598 """
599 end_users = dict.fromkeys(
600 end_user for account in account_scope if (end_user := self._end_user_id(account)) is not None
601 )
602 query = [
603 ("tool-mode", "search_execute"),
604 ("x-account-id", ",".join(account_scope)),
605 *(("x-end-user-id", end_user) for end_user in end_users),
606 ]
607 return f"{self.base_url.rstrip('/')}/mcp?{urlencode(query)}"
609 def _accounts_of_providers(self, account_scope: list[str | None], providers: list[str]) -> list[str]:
610 """The scoped accounts whose provider, as ``GET /accounts`` names it, is one of
611 ``providers`` (case-insensitive). One ``GET /accounts`` is joined or made first when
612 any of their providers is not yet known.
613 """
614 accounts = [account for account in account_scope if account is not None]
615 with self._cache_lock:
616 unknown = any(account not in self._providers for account in accounts)
617 if unknown:
618 self._join_accounts_listing()
619 wanted = {provider.lower() for provider in providers}
620 with self._cache_lock:
621 return [account for account in accounts if self._providers.get(account, "").lower() in wanted]
623 @staticmethod
624 def _dedupe_global_tools(
625 listings: list[_Listing],
626 ) -> list[_Listing]:
627 """Keep only the first listing of the feedback tool.
629 It is global rather than account-scoped, so every account's listing carries an
630 identical copy. Left in, N accounts meant N same-named tools and a duplicate-name
631 warning about a clash that cannot misroute anything — noise that teaches callers
632 to ignore the warning that does matter.
633 """
634 seen_feedback = False
635 kept: list[_Listing] = []
636 for listing in listings:
637 if listing[0].name == SUBMIT_FEEDBACK_TOOL_NAME:
638 if seen_feedback:
639 continue
640 seen_feedback = True
641 kept.append(listing)
642 return kept
644 def _cache_key(self, account_scope: list[str | None], mode: ToolMode | None) -> tuple[Any, ...]:
645 return (
646 tuple(sorted(account_scope, key=lambda a: (a is None, a))),
647 mode,
648 self.base_url,
649 self.api_key,
650 )
652 def search(
653 self,
654 query: str,
655 *,
656 top_k: int = 10,
657 account_ids: list[str] | None = None,
658 ) -> list[JsonDict]:
659 """Find actions matching a natural-language query.
661 One ``stackone_search_actions`` call, which the server answers across every connector
662 linked on the accounts in scope, so the catalog never has to be loaded into a model's
663 context. One account or many, the call and its hits look the same: see
664 :class:`~stackone_ai.tools.AccountPair`.
666 Args:
667 query: What you want to do, e.g. "list recent comments".
668 top_k: Maximum results.
669 account_ids: Restrict to these accounts. Defaults to the toolset's own, or every
670 active shared one (non-shared ones too with ``include_non_shared=True``).
672 Returns:
673 At most ``top_k`` hits, best first, each as the server serves it: at least
674 ``action_id`` and ``description``, and ``available_accounts``, the accounts in
675 scope that can run it, as ``{"id", "name"}`` (just ``{"id"}`` when one account is
676 in scope). Each also carries the search's
677 ``session_id`` when the server issued one. Pass ``session_id`` to
678 :meth:`execute` and :meth:`submit_feedback` to link the calls, and, when
679 ``available_accounts`` lists more than one, the chosen ``id`` in ``account_ids``.
681 Raises:
682 ToolsetLoadError: If the server did not serve ``stackone_search_actions``.
683 StackOneAPIError: If the listing or the search fails, including a 429 that
684 outlasted its retries (retried as in :meth:`fetch_tools`).
685 """
686 # The server rejects anything outside 1..50, but only after a round trip, and reports
687 # it as a tool error, which reads like an outage rather than a typo. Fail here
688 # instead, where the caller can see why.
689 if not isinstance(top_k, int) or isinstance(top_k, bool) or not 1 <= top_k <= _MAX_TOP_K:
690 raise ToolsetConfigError(
691 f"top_k must be an integer between 1 and {_MAX_TOP_K}, got {_json_text(top_k)}"
692 )
694 tool = self._trio_tool(SEARCH_ACTIONS_TOOL_NAME, account_ids)
695 found = tool.execute({"query": query, "top_k": top_k})
696 # The server returns session_id once per search, beside the actions; each hit carries
697 # it so a caller handing one hit on still links the calls.
698 session_id = found.get("session_id")
699 traced: JsonDict = {"session_id": session_id} if isinstance(session_id, str) and session_id else {}
700 actions = found.get("actions")
701 hits = [action for action in actions if isinstance(action, dict)] if isinstance(actions, list) else []
702 return [{**action, **traced} for action in hits[:top_k]]
704 def execute(
705 self,
706 action_id: str,
707 arguments: JsonDict | None = None,
708 *,
709 account_ids: list[str] | None = None,
710 session_id: str | None = None,
711 ) -> JsonDict:
712 """Execute an action by id, as returned by :meth:`search`.
714 One ``stackone_execute_action`` call, so ``arguments`` is the nested form every
715 action's ``example_request`` shows: ``{"query": {...}, "path": {...}, "body":
716 {...}}``. A ``fetch_tools()`` tool takes the keys its own served schema names instead.
718 ``arguments["headers"]`` is forwarded to the action: ``stackone_execute_action``
719 serves an open ``headers`` object, so any header name is accepted except
720 Authorization, x-account-id, User-Agent and x-end-user-id, which the SDK sets itself
721 and which are dropped.
723 ``account_ids`` scopes the call. With exactly one id, it is sent as
724 ``stackone_account_id``, so pass a search hit's chosen ``available_accounts`` id to run
725 the action on that account. Otherwise the server picks the only account in scope
726 linked to the action's connector, or answers with an error naming the choices.
728 ``session_id`` is the value a :meth:`search` hit carries. Passing it links this call
729 to that search server-side.
731 Raises:
732 ToolsetConfigError: If ``action_id``, ``arguments`` or ``session_id`` is malformed.
733 ToolArgumentsError: If the arguments cannot be encoded as JSON.
734 ToolsetLoadError: If the server did not serve ``stackone_execute_action``.
735 StackOneAPIError: If the action fails, including when the server rejects the
736 arguments or the account is ambiguous.
737 """
738 if not isinstance(action_id, str) or not action_id:
739 raise ToolsetConfigError(f"action_id must be a non-empty string, got {_json_text(action_id)}")
740 if arguments is not None and not isinstance(arguments, dict):
741 raise ToolsetConfigError(f"arguments must be a JSON object, got {_json_type(arguments)}")
742 if session_id is not None and (not isinstance(session_id, str) or not session_id):
743 raise ToolsetConfigError(f"session_id must be a non-empty string, got {_json_text(session_id)}")
745 tool = self._trio_tool(EXECUTE_ACTION_TOOL_NAME, account_ids)
746 # Each key the caller pins is removed and set again, so it is set however the model
747 # filled the arguments, and action_id lands last in key order, as in Node. Spreading
748 # arguments over it let a model-supplied "action_id" silently replace the action the
749 # caller pinned. Optional keys only when given: the served schema makes them optional
750 # strings, so an absent key is valid and a null is not.
751 call_arguments: JsonDict = dict(arguments or {})
752 pinned_accounts = set(account_ids or [])
753 if len(pinned_accounts) == 1:
754 call_arguments.pop("stackone_account_id", None)
755 call_arguments["stackone_account_id"] = next(iter(pinned_accounts))
756 if session_id is not None:
757 call_arguments.pop("session_id", None)
758 call_arguments["session_id"] = session_id
759 call_arguments.pop("action_id", None)
760 call_arguments["action_id"] = action_id
761 # Returned as the server wrote it, the same shape tool.execute() returns.
762 return tool.execute(call_arguments)
764 def _trio_tool(self, name: str, account_ids: list[str] | None) -> StackOneTool:
765 """One of the ``search_execute`` tools spanning these accounts, whatever this toolset's
766 mode.
768 The mode is passed down rather than assigned to ``self``: flipping instance state
769 raced with a concurrent ``fetch_tools()``, which could cache the trio under the
770 individual-mode key.
772 Raises:
773 ToolsetLoadError: If the listing did not serve it, as when the project's policy
774 disables ``search_execute``.
775 """
776 tool = self.fetch_tools(account_ids=account_ids, mode="search_execute").get_tool(name)
777 if tool is None:
778 raise ToolsetLoadError(f"The server did not serve {name} for this account scope.")
779 return tool
781 def submit_feedback(
782 self,
783 rating: FeedbackRating,
784 tool_names: Sequence[str],
785 *,
786 feedback: str | None = None,
787 category: FeedbackCategory | None = None,
788 session_id: str | None = None,
789 source: FeedbackSource = "model",
790 account_ids: list[str] | None = None,
791 action_run_id: str | None = None,
792 ) -> JsonDict:
793 """Record a verdict on how well the tools served this session.
795 Calls the server's ``stackone_submit_feedback`` tool once, through the account with
796 the lowest id among those the call is scoped to: ``account_ids``, or else the
797 toolset's, or else every active shared one (non-shared ones too with
798 ``include_non_shared=True``). Pass the ``session_id`` from a :meth:`search`
799 hit to attach the feedback to that session.
801 Args:
802 rating: ``"positive"``, ``"negative"`` or ``"neutral"``.
803 tool_names: The tools or action ids the feedback is about.
804 feedback: An optional one-line reason.
805 category: What the feedback is about, e.g. ``"search"`` or ``"execute"``.
806 session_id: The session to link this feedback to.
807 source: Who produced the feedback.
808 account_ids: Accounts to choose from; only the lowest id is used. Defaults to
809 the toolset's own.
810 action_run_id: The action run the feedback is about. Sent only when given.
812 Raises:
813 ToolsetConfigError: If ``tool_names`` is a string or ``session_id`` is empty or
814 not a string.
815 ToolsetLoadError: If feedback is not enabled for this project.
816 """
817 if isinstance(tool_names, str):
818 raise ToolsetConfigError(
819 "tool_names must be a list of tool names, not a string. "
820 f"Did you mean [{_json_text(tool_names)}]?"
821 )
822 if session_id is not None and (not isinstance(session_id, str) or not session_id):
823 raise ToolsetConfigError(f"session_id must be a non-empty string, got {_json_text(session_id)}")
825 # Found in the served catalog, never built here: the server only serves the tool
826 # when the org flag and the project setting are both on, and a client-side stand-in
827 # would report success for feedback that went nowhere. It is global and served in
828 # every mode, so one account's search_execute listing — the trio, not one tool per
829 # action — is enough to find it.
830 # The lowest id is the one a caller can predict, whatever order GET /accounts lists
831 # them in.
832 scope = self._resolve_account_ids(account_ids)
833 tool = self.fetch_tools(account_ids=[min(scope)], mode="search_execute").get_tool(
834 SUBMIT_FEEDBACK_TOOL_NAME
835 )
836 if tool is None:
837 raise ToolsetLoadError(
838 f"The server did not serve {SUBMIT_FEEDBACK_TOOL_NAME}: feedback is not enabled "
839 "for this project."
840 )
842 # Unset optionals are omitted, never sent as null: the served schema declares them
843 # as optional strings, so a null is a present key of the wrong type and fails
844 # validation where an absent one would not.
845 arguments: JsonDict = {"rating": rating, "tool_names": list(tool_names)}
846 optional = {
847 "feedback": feedback,
848 "category": category,
849 "session_id": session_id,
850 "action_run_id": action_run_id,
851 "source": source,
852 }
853 arguments.update({key: value for key, value in optional.items() if value is not None})
854 return tool.execute(arguments)
856 def openai(self, *, account_ids: list[str] | None = None) -> list[JsonDict]:
857 """Get tools in OpenAI function calling format."""
858 return self.fetch_tools(account_ids=account_ids).to_openai()
860 def langchain(self, *, account_ids: list[str] | None = None) -> Any:
861 """Get tools in LangChain format."""
862 return self.fetch_tools(account_ids=account_ids).to_langchain()
864 def pydantic_ai(self, *, account_ids: list[str] | None = None) -> list[Any]:
865 """Get tools as Pydantic AI ``Tool`` instances.
867 Requires ``stackone-ai[pydantic-ai]`` (installs ``pydantic-ai-slim``).
868 """
869 return self.fetch_tools(account_ids=account_ids).to_pydantic_ai()
871 def _filter_by_provider(self, tool_name: str, providers: list[str]) -> bool:
872 """Whether a tool belongs to one of the given providers (case-insensitive).
874 Matched as a full prefix rather than on the first underscore-separated token:
875 splitting on "_" reads `browser_linkedin_search_people` as provider `browser`,
876 so asking for `browser_linkedin` returned nothing at all — silently, since an
877 empty result is indistinguishable from a provider with no tools.
878 """
879 lowered = tool_name.lower()
880 return any(lowered.startswith(provider.lower() + "_") for provider in providers)
882 def _filter_by_action(self, tool_name: str, actions: list[str]) -> bool:
883 """Whether a tool name matches any of the given glob patterns."""
884 return any(fnmatch.fnmatch(tool_name, pattern) for pattern in actions)
886 def fetch_accounts(self) -> list[JsonDict]:
887 """List the accounts linked to this API key.
889 Each entry carries at least ``id``, ``provider`` and ``status``. Only
890 accounts with ``status == "active"`` can serve tools.
892 For each account with ``shared`` false and an ``origin_username``, that username is
893 recorded as the account's end-user id, and each account's ``provider`` as its
894 provider. The record replaces that of any call that started before this one; a call
895 that started earlier but finishes after this one records nothing. Every MCP request
896 this toolset's tools make for that account then carries it in ``x-end-user-id``,
897 which the API requires for a non-shared account. An account passed by id is listed
898 here only when the API refuses one of its requests for want of an end user: the
899 toolset then calls this once, and retries the request with the end user it recorded.
901 Raises:
902 StackOneAPIError: If the API answers with an error, including a 429 that
903 outlasted its retries.
904 """
905 with self._cache_lock:
906 self._accounts_sequence += 1
907 sequence = self._accounts_sequence
908 fetching: concurrent.futures.Future[list[JsonDict]] = concurrent.futures.Future()
909 self._fetching_accounts = fetching
910 return self._settle_accounts(fetching, sequence)
912 def _settle_accounts(
913 self, fetching: concurrent.futures.Future[list[JsonDict]], sequence: int
914 ) -> list[JsonDict]:
915 """Make the GET /accounts started as ``sequence``, settling ``fetching`` with it."""
916 try:
917 accounts = self._request_accounts(sequence)
918 except BaseException as exc:
919 fetching.set_exception(exc)
920 raise
921 else:
922 fetching.set_result(accounts)
923 return accounts
924 finally:
925 with self._cache_lock:
926 if self._fetching_accounts is fetching:
927 self._fetching_accounts = None
929 def _request_accounts(self, sequence: int) -> list[JsonDict]:
930 url = f"{self.base_url.rstrip('/')}/accounts"
931 try:
932 with RateLimitRetryingClient(
933 timeout=self._timeout, retry_within=self._timeout, verify=_ssl_context()
934 ) as client:
935 response = client.get(
936 url,
937 headers=build_request_headers(api_key=self.api_key, extra_headers=self._headers),
938 )
939 except RateLimitTimeout as exc:
940 # Timing out while a 429 is retried is still the rate limit, as it is over MCP.
941 raise StackOneAPIError(
942 f"Listing accounts at {url} was rate limited (429) and timed out after "
943 f"{_js_number(self._timeout)}s while retrying",
944 429,
945 None,
946 ) from exc
947 except httpx.HTTPError as exc:
948 # The only public method with no error handling at all: a dead host, a bad
949 # scheme or a timeout leaked httpx's own exception type straight out of the
950 # SDK, outside the documented hierarchy.
951 raise ToolsetLoadError(f"Could not reach {url}: {exc}") from exc
953 if response.is_error:
954 # Without this the catch-all in fetch_tools flattens it to a message and
955 # the status is lost, so a caller cannot tell 401 from 429.
956 error = StackOneAPIError(
957 f"Listing accounts at {url} failed with "
958 f"{response.status_code} {response.reason_phrase}: {response.text.strip()}",
959 response.status_code,
960 response.text,
961 )
962 if response.status_code == 429:
963 # Chained to the HTTP 429 so is_rate_limited() reads it as the rate limit it
964 # is: fatal to a fan-out, as a 429 over MCP is.
965 raise error from httpx.HTTPStatusError("429", request=response.request, response=response)
966 raise error
967 try:
968 body = response.json()
969 except (ValueError, UnicodeDecodeError) as exc:
970 raise ToolsetLoadError(f"Invalid JSON returned by {url}: {exc}") from exc
971 accounts = body.get("data", body) if isinstance(body, dict) else body
972 if not isinstance(accounts, list):
973 # list(dict) yields the KEYS, so coercing here turned an unexpected wrapper
974 # into a list of strings that blew up much later as an AttributeError.
975 raise ToolsetLoadError(
976 f"Unexpected /accounts response shape: expected a list, got {_json_type(accounts)}"
977 )
978 end_user_ids = {
979 account["id"]: account["origin_username"]
980 for account in accounts
981 if isinstance(account, dict)
982 and isinstance(account.get("id"), str)
983 and account["id"]
984 and account.get("shared") is False
985 and isinstance(account.get("origin_username"), str)
986 and account["origin_username"]
987 }
988 providers = {
989 account["id"]: account["provider"]
990 for account in accounts
991 if isinstance(account, dict)
992 and isinstance(account.get("id"), str)
993 and account["id"]
994 and isinstance(account.get("provider"), str)
995 and account["provider"]
996 }
997 with self._cache_lock:
998 # Only if newer, by start order, than the result last written: a call that
999 # started first but finished last is answering a question a newer call has
1000 # since answered better, and must not clobber it. Compared with the last
1001 # write rather than the last start, so a newer call that fails leaves this
1002 # one to write.
1003 if sequence > self._end_user_ids_sequence:
1004 self._end_user_ids = end_user_ids
1005 self._providers = providers
1006 self._end_user_ids_sequence = sequence
1007 return accounts
1009 def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool:
1010 """Given the API's refusal of an account's request for want of its end user, list the
1011 accounts and say whether that one now has an end user recorded to retry with.
1013 A GET /accounts already in flight is joined rather than another made. If it fails, the
1014 refusal is raised with that failure as its cause: a key without the scope to list
1015 accounts would otherwise be told only that the header does not match.
1016 """
1017 try:
1018 self._join_accounts_listing()
1019 except Exception as exc:
1020 # A rate limit is the key's, not the account's, and stays fatal to a fan-out.
1021 if is_rate_limited(exc):
1022 raise
1023 raise refusal from exc
1024 return self._end_user_id(account_id) is not None
1026 def _join_accounts_listing(self) -> None:
1027 """Wait for the GET /accounts in flight, or make one: what it records is then current.
1029 Raises:
1030 Exception: Whatever that GET /accounts failed with.
1031 """
1032 with self._cache_lock:
1033 fetching = self._fetching_accounts
1034 sequence = 0
1035 if fetching is None:
1036 self._accounts_sequence += 1
1037 sequence = self._accounts_sequence
1038 fetching = self._fetching_accounts = concurrent.futures.Future()
1039 if sequence:
1040 with contextlib.suppress(Exception):
1041 self._settle_accounts(fetching, sequence)
1042 fetching.result()
1044 def _end_user_id(self, account_id: str) -> str | None:
1045 """The end-user id GET /accounts recorded for an account, if it is not shared."""
1046 with self._cache_lock:
1047 return self._end_user_ids.get(account_id)
1049 def _discover_account_ids(self) -> list[str]:
1050 """List the linked accounts this API key can use.
1052 The MCP endpoint requires an ``x-account-id`` on every request, so an API
1053 key on its own is not enough to list tools. Rather than make every caller
1054 supply one, ask the API which accounts the key has.
1056 Warning: For organizations with many connected accounts, relying on discovery
1057 fetches the tool catalog for every account. If you have a large number of
1058 accounts, it is highly recommended to supply specific ``account_id`` or
1059 ``account_ids`` to avoid excessive API round trips and huge model contexts.
1061 Non-shared accounts are skipped, with one warning naming them, unless the toolset was
1062 built with ``include_non_shared=True``: each belongs to a single end user.
1064 Raises:
1065 ToolsetConfigError: If the key has no accounts, none are active, or every active
1066 one is non-shared and skipped.
1067 """
1068 if self._discovered_account_ids is not None:
1069 return self._discovered_account_ids
1071 with self._cache_lock:
1072 if self._discovered_account_ids is not None: 1072 ↛ 1073line 1072 didn't jump to line 1073 because the condition on line 1072 was never true
1073 return self._discovered_account_ids
1074 future = self._discovering
1075 owner = future is None
1076 if owner:
1077 future = self._discovering = concurrent.futures.Future()
1079 if future is None: 1079 ↛ 1080line 1079 didn't jump to line 1080 because the condition on line 1079 was never true
1080 raise RuntimeError("account discovery future was not initialized")
1081 if not owner:
1082 # A discovery already in flight: wait for it rather than issue a second
1083 # GET /accounts. Its result, or its exception, is shared with every waiter.
1084 return future.result()
1086 try:
1087 active = self._fetch_active_account_ids()
1088 except BaseException as exc:
1089 with self._cache_lock:
1090 if self._discovering is future:
1091 self._discovering = None
1092 future.set_exception(exc)
1093 raise
1094 with self._cache_lock:
1095 if self._discovering is future:
1096 self._discovering = None
1097 future.set_result(active)
1098 return active
1100 def _fetch_active_account_ids(self) -> list[str]:
1101 generation = self._cache_generation
1102 accounts = self.fetch_accounts()
1104 active = [a["id"] for a in accounts if a.get("status") == "active" and a.get("id")]
1105 if not active:
1106 if not accounts:
1107 raise ToolsetConfigError(
1108 "This API key has no linked accounts. Link one in the StackOne "
1109 "dashboard, or pass an account id explicitly."
1110 )
1111 listed = ", ".join(f"{a.get('provider')} ({a.get('status')})" for a in accounts)
1112 raise ToolsetConfigError(
1113 f"None of this API key's {len(accounts)} linked accounts are active: {listed}. "
1114 "Re-link them in the StackOne dashboard, or pass an account id explicitly."
1115 )
1117 # Each non-shared account belongs to a single end user: discovering it would put one
1118 # end user's tools in front of whoever uses this toolset.
1119 if not self._include_non_shared:
1120 skipped = sorted(
1121 {a["id"] for a in accounts if a.get("id") in active and a.get("shared") is False}
1122 )
1123 if skipped and len(skipped) == len(set(active)):
1124 raise ToolsetConfigError(
1125 f"None of this API key's {len(skipped)} active account(s) are shared: each "
1126 "belongs to a single end user. Pass their account ids, or opt in to non-shared "
1127 "accounts, to use them."
1128 )
1129 if skipped:
1130 logger.warning(
1131 "Discovery skipped %d non-shared account(s) (%s): each belongs to a single end "
1132 "user. Pass their account ids, or opt in to non-shared accounts, to use them.",
1133 len(skipped),
1134 ", ".join(skipped),
1135 )
1136 active = [account for account in active if account not in skipped]
1138 # Not kept if clear_catalog_cache() ran while the list was in flight: it may name
1139 # accounts the clear was meant to forget.
1140 with self._cache_lock:
1141 if generation == self._cache_generation:
1142 self._discovered_account_ids = active
1143 return active
1145 def _build_mcp_headers(self, account_id: str | None) -> dict[str, str]:
1146 end_user_id = self._end_user_id(account_id) if account_id else None
1147 return build_request_headers(
1148 api_key=self.api_key,
1149 account_id=account_id,
1150 end_user_id=end_user_id,
1151 extra_headers=self._headers,
1152 )
1154 def _create_tool(
1155 self,
1156 tool_def: McpToolDefinition,
1157 account_id: str | None,
1158 endpoint: str,
1159 pair_account: str | None = None,
1160 ) -> StackOneTool:
1161 """Build an executable tool from a served catalog entry.
1163 Every tool, in every mode, executes over MCP ``tools/call`` on the endpoint that
1164 listed it, with the ``x-account-id`` of the account that listed it, and the
1165 ``x-end-user-id`` recorded for that account when the request is made. A tool of
1166 ``pair_account``'s search and execute pair is presented as the trio tool it stands for.
1167 """
1168 served_name = tool_def.name
1169 pair = AccountPair.serving(served_name, pair_account) if pair_account else None
1170 if pair is not None:
1171 tool_def = pair.presented(tool_def)
1173 schema = tool_def.input_schema or {}
1174 # Pop keys we explicitly override to avoid "multiple values for keyword argument"
1175 rest = dict(schema)
1176 # A string type is passed through; anything else, such as ["object", "null"], is
1177 # "object", as in Node. str() handed the model "['object', 'null']".
1178 served_type = rest.pop("type", "object")
1179 schema_type = served_type if isinstance(served_type, str) else "object"
1180 rest.pop("properties", None)
1181 schema_properties = self._normalize_schema_properties(schema)
1183 parameters = ToolParameters(
1184 **rest,
1185 type=schema_type,
1186 properties=schema_properties,
1187 )
1188 tool_class = (
1189 StackOneMcpTool if pair is None else functools.partial(StackOneAccountPairTool, pair=pair)
1190 )
1191 tool = tool_class(
1192 name=tool_def.name,
1193 description=tool_def.description or "",
1194 parameters=parameters,
1195 api_key=self.api_key,
1196 endpoint=endpoint,
1197 account_id=account_id,
1198 headers=self._headers,
1199 timeout=self._timeout,
1200 served_name=served_name,
1201 )
1202 tool._end_user_id_of = self._end_user_id
1203 tool._look_up_end_user = self._look_up_end_user
1204 return tool
1206 def _normalize_schema_properties(self, schema: dict[str, Any]) -> dict[str, Any]:
1207 """Mirror the served schema's properties, recording requiredness per property.
1209 The served schema expresses requiredness as a top-level ``required`` list.
1210 The SDK carries it per-property as ``nullable`` so each property is
1211 self-describing; everything else in the property is preserved verbatim.
1212 """
1213 properties = schema.get("properties")
1214 if not isinstance(properties, dict):
1215 return {}
1217 raw_required = schema.get("required")
1218 # A string `required` would iterate as characters and mark every real property
1219 # optional; a null would raise and fail the whole catalog over one bad tool. A
1220 # non-string entry is dropped, as to_openai_function() drops it, so the marker and
1221 # the `required` a model is shown cannot disagree.
1222 served_required = raw_required if isinstance(raw_required, list) else []
1223 required_fields = {name for name in served_required if isinstance(name, str)}
1224 normalized: dict[str, Any] = {}
1226 for name, details in properties.items():
1227 prop: dict[str, Any]
1228 if isinstance(details, dict):
1229 prop = copy.deepcopy(details)
1230 else:
1231 prop = {"description": str(details)}
1233 # Assign, never setdefault: a served `nullable` (OpenAPI 3.0 style) means
1234 # "accepts null", not "optional". Letting it stand would drop the field
1235 # from `required` and the model would omit it.
1236 prop["nullable"] = name not in required_fields
1237 normalized[str(name)] = prop
1239 return normalized