-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoolset.py
More file actions
1218 lines (1004 loc) · 43.6 KB
/
toolset.py
File metadata and controls
1218 lines (1004 loc) · 43.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import base64
import concurrent.futures
import fnmatch
import json
import logging
import os
import threading
from collections.abc import Coroutine, Sequence
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Literal, TypedDict, TypeVar
from pydantic import BaseModel, Field, PrivateAttr, ValidationError, field_validator
from stackone_ai.constants import DEFAULT_BASE_URL
from stackone_ai.models import (
ExecuteConfig,
JsonDict,
ParameterLocation,
StackOneAPIError,
StackOneTool,
ToolParameters,
Tools,
)
from stackone_ai.semantic_search import (
SemanticSearchClient,
SemanticSearchError,
SemanticSearchResult,
)
from stackone_ai.utils.normalize import _normalize_action_name
logger = logging.getLogger("stackone.tools")
SearchMode = Literal["auto", "semantic", "local"]
class SearchConfig(TypedDict, total=False):
"""Search configuration for the StackOneToolSet constructor.
When provided as a dict, sets default search options that flow through
to ``search_tools()``, ``get_search_tool()``, and ``search_action_names()``.
Per-call options override these defaults.
When set to ``None``, search is disabled entirely.
When omitted, defaults to ``{"method": "auto"}``.
"""
method: SearchMode
"""Search backend to use. Defaults to ``"auto"``."""
top_k: int
"""Maximum number of tools to return."""
min_similarity: float
"""Minimum similarity score threshold 0-1."""
class ExecuteToolsConfig(TypedDict, total=False):
"""Execution configuration for the StackOneToolSet constructor.
Controls default account scoping for tool execution.
When set to ``None`` (default), no account scoping is applied.
When provided, ``account_ids`` flow through to ``openai(mode="search_and_execute")``
and ``fetch_tools()`` as defaults.
"""
account_ids: list[str]
"""Account IDs to scope tool discovery and execution."""
_SEARCH_DEFAULT: SearchConfig = {"method": "auto"}
try:
_SDK_VERSION = metadata.version("stackone-ai")
except metadata.PackageNotFoundError: # pragma: no cover - best-effort fallback when running from source
_SDK_VERSION = "dev"
_RPC_PARAMETER_LOCATIONS = {
"action": ParameterLocation.BODY,
"body": ParameterLocation.BODY,
"headers": ParameterLocation.BODY,
"path": ParameterLocation.BODY,
"query": ParameterLocation.BODY,
}
_USER_AGENT = f"stackone-ai-python/{_SDK_VERSION}"
# --- Internal tool_search + tool_execute ---
class _SearchInput(BaseModel):
"""Input validation for tool_search."""
query: str = Field(..., min_length=1)
connector: str | None = None
top_k: int | None = Field(default=None, ge=1, le=50)
@field_validator("query")
@classmethod
def validate_query(cls, v: str) -> str:
trimmed = v.strip()
if not trimmed:
raise ValueError("query must be a non-empty string")
return trimmed
class _SearchTool(StackOneTool):
"""LLM-callable tool that searches for available StackOne tools."""
_toolset: Any = PrivateAttr(default=None)
def execute(
self, arguments: str | JsonDict | None = None, *, options: JsonDict | None = None
) -> JsonDict:
try:
if isinstance(arguments, str):
raw_params = json.loads(arguments)
else:
raw_params = arguments or {}
parsed = _SearchInput(**raw_params)
search_config = self._toolset._search_config or {}
results = self._toolset.search_tools(
parsed.query,
connector=parsed.connector or search_config.get("connector"),
top_k=parsed.top_k or search_config.get("top_k") or 5,
min_similarity=search_config.get("min_similarity"),
search=search_config.get("method"),
account_ids=self._toolset._account_ids,
)
return {
"tools": [
{
"name": t.name,
"description": t.description,
"parameters": t.parameters.properties,
}
for t in results
],
"total": len(results),
"query": parsed.query,
}
except (json.JSONDecodeError, ValidationError) as exc:
return {"error": f"Invalid input: {exc}", "query": raw_params if "raw_params" in dir() else None}
class _ExecuteInput(BaseModel):
"""Input validation for tool_execute."""
tool_name: str = Field(..., min_length=1)
parameters: dict[str, Any] = Field(default_factory=dict)
@field_validator("tool_name")
@classmethod
def validate_tool_name(cls, v: str) -> str:
trimmed = v.strip()
if not trimmed:
raise ValueError("tool_name must be a non-empty string")
return trimmed
class _ExecuteTool(StackOneTool):
"""LLM-callable tool that executes a StackOne tool by name."""
_toolset: Any = PrivateAttr(default=None)
_cached_tools: Any = PrivateAttr(default=None)
def execute(
self, arguments: str | JsonDict | None = None, *, options: JsonDict | None = None
) -> JsonDict:
tool_name = "unknown"
try:
if isinstance(arguments, str):
raw_params = json.loads(arguments)
else:
raw_params = arguments or {}
parsed = _ExecuteInput(**raw_params)
tool_name = parsed.tool_name
if self._cached_tools is None:
self._cached_tools = self._toolset.fetch_tools(account_ids=self._toolset._account_ids)
target = self._cached_tools.get_tool(parsed.tool_name)
if target is None:
return {
"error": (
f'Tool "{parsed.tool_name}" not found. Use tool_search to find available tools.'
),
}
return target.execute(parsed.parameters, options=options)
except StackOneAPIError as exc:
return {
"error": str(exc),
"status_code": exc.status_code,
"response_body": exc.response_body,
"tool_name": tool_name,
}
except (json.JSONDecodeError, ValidationError) as exc:
return {"error": f"Invalid input: {exc}", "tool_name": tool_name}
def _create_search_tool(api_key: str) -> _SearchTool:
name = "tool_search"
description = (
"Search for available tools by describing what you need. "
"Returns matching tool names, descriptions, and parameter schemas. "
"Use the returned parameter schemas to know exactly what to pass "
"when calling tool_execute."
)
parameters = ToolParameters(
type="object",
properties={
"query": {
"type": "string",
"description": (
"Natural language description of what you need "
'(e.g. "create an employee", "list time off requests")'
),
},
"connector": {
"type": "string",
"description": 'Optional connector filter (e.g. "bamboohr")',
"nullable": True,
},
"top_k": {
"type": "integer",
"description": "Max results to return (1-50, default 5)",
"minimum": 1,
"maximum": 50,
"nullable": True,
},
},
)
execute_config = ExecuteConfig(
name=name,
method="POST",
url="local://meta/search",
parameter_locations={
"query": ParameterLocation.BODY,
"connector": ParameterLocation.BODY,
"top_k": ParameterLocation.BODY,
},
)
tool = _SearchTool.__new__(_SearchTool)
StackOneTool.__init__(
tool,
description=description,
parameters=parameters,
_execute_config=execute_config,
_api_key=api_key,
)
return tool
def _create_execute_tool(api_key: str) -> _ExecuteTool:
name = "tool_execute"
description = (
"Execute a tool by name with the given parameters. "
"Use tool_search first to find available tools. "
"The parameters field must match the parameter schema returned "
"by tool_search. Pass parameters as a nested object matching "
"the schema structure."
)
parameters = ToolParameters(
type="object",
properties={
"tool_name": {
"type": "string",
"description": "Exact tool name from tool_search results",
},
"parameters": {
"type": "object",
"description": "Parameters for the tool, matching the schema from tool_search.",
"nullable": True,
},
},
)
execute_config = ExecuteConfig(
name=name,
method="POST",
url="local://meta/execute",
parameter_locations={
"tool_name": ParameterLocation.BODY,
"parameters": ParameterLocation.BODY,
},
)
tool = _ExecuteTool.__new__(_ExecuteTool)
StackOneTool.__init__(
tool,
description=description,
parameters=parameters,
_execute_config=execute_config,
_api_key=api_key,
)
return tool
T = TypeVar("T")
@dataclass
class _McpToolDefinition:
name: str
description: str | None
input_schema: dict[str, Any]
class ToolsetError(Exception):
"""Base exception for toolset errors"""
pass
class ToolsetConfigError(ToolsetError):
"""Raised when there is an error in the toolset configuration"""
pass
class ToolsetLoadError(ToolsetError):
"""Raised when there is an error loading tools"""
pass
def _run_async(awaitable: Coroutine[Any, Any, T]) -> T:
"""Run a coroutine, even when called from an existing event loop."""
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(awaitable)
result: dict[str, T] = {}
error: dict[str, BaseException] = {}
def runner() -> None:
try:
result["value"] = asyncio.run(awaitable)
except BaseException as exc: # pragma: no cover - surfaced in caller context
error["error"] = exc
thread = threading.Thread(target=runner, daemon=True)
thread.start()
thread.join()
if "error" in error:
raise error["error"]
return result["value"]
def _build_auth_header(api_key: str) -> str:
token = base64.b64encode(f"{api_key}:".encode()).decode()
return f"Basic {token}"
def _fetch_mcp_tools(endpoint: str, headers: dict[str, str]) -> list[_McpToolDefinition]:
try:
from mcp import types as mcp_types # ty: ignore[unresolved-import]
from mcp.client.session import ClientSession # ty: ignore[unresolved-import]
from mcp.client.streamable_http import streamablehttp_client # ty: ignore[unresolved-import]
except ImportError as exc: # pragma: no cover - depends on optional extra
raise ToolsetConfigError(
"MCP dependencies are required for fetch_tools. Install with 'pip install \"stackone-ai[mcp]\"'."
) from exc
async def _list() -> list[_McpToolDefinition]:
async with streamablehttp_client(endpoint, headers=headers) as (read_stream, write_stream, _):
session = ClientSession(
read_stream,
write_stream,
client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION),
)
async with session:
await session.initialize()
cursor: str | None = None
collected: list[_McpToolDefinition] = []
while True:
result = await session.list_tools(cursor)
for tool in result.tools:
input_schema = tool.inputSchema or {}
collected.append(
_McpToolDefinition(
name=tool.name,
description=tool.description,
input_schema=dict(input_schema),
)
)
cursor = result.nextCursor
if cursor is None:
break
return collected
return _run_async(_list())
class _StackOneRpcTool(StackOneTool):
"""RPC-backed tool wired to the StackOne actions RPC endpoint."""
def __init__(
self,
*,
name: str,
description: str,
parameters: ToolParameters,
api_key: str,
base_url: str,
account_id: str | None,
) -> None:
execute_config = ExecuteConfig(
method="POST",
url=f"{base_url.rstrip('/')}/actions/rpc",
name=name,
headers={},
body_type="json",
parameter_locations=dict(_RPC_PARAMETER_LOCATIONS),
)
super().__init__(
description=description,
parameters=parameters,
_execute_config=execute_config,
_api_key=api_key,
_account_id=account_id,
)
def execute(
self, arguments: str | dict[str, Any] | None = None, *, options: dict[str, Any] | None = None
) -> dict[str, Any]:
parsed_arguments = self._parse_arguments(arguments)
body_payload = self._extract_record(parsed_arguments.pop("body", None))
headers_payload = self._extract_record(parsed_arguments.pop("headers", None))
path_payload = self._extract_record(parsed_arguments.pop("path", None))
query_payload = self._extract_record(parsed_arguments.pop("query", None))
rpc_body: dict[str, Any] = dict(body_payload or {})
for key, value in parsed_arguments.items():
rpc_body[key] = value
payload: dict[str, Any] = {
"action": self.name,
"body": rpc_body,
"headers": self._build_action_headers(headers_payload),
}
if path_payload:
payload["path"] = path_payload
if query_payload:
payload["query"] = query_payload
return super().execute(payload, options=options)
def _parse_arguments(self, arguments: str | dict[str, Any] | None) -> dict[str, Any]:
if arguments is None:
return {}
if isinstance(arguments, str):
parsed = json.loads(arguments)
else:
parsed = arguments
if not isinstance(parsed, dict):
raise ValueError("Tool arguments must be a JSON object")
return dict(parsed)
@staticmethod
def _extract_record(value: Any) -> dict[str, Any] | None:
if isinstance(value, dict):
return dict(value)
return None
def _build_action_headers(self, additional_headers: dict[str, Any] | None) -> dict[str, str]:
headers: dict[str, str] = {}
account_id = self.get_account_id()
if account_id:
headers["x-account-id"] = account_id
if additional_headers:
for key, value in additional_headers.items():
if value is None:
continue
headers[str(key)] = str(value)
headers.pop("Authorization", None)
return headers
class SearchTool:
"""Callable search tool that wraps StackOneToolSet.search_tools().
Designed for agent loops — call it with a query to get Tools back.
Example::
toolset = StackOneToolSet()
search_tool = toolset.get_search_tool()
tools = search_tool("manage employee records", account_ids=["acc-123"])
"""
def __init__(self, toolset: StackOneToolSet, config: SearchConfig | None = None) -> None:
self._toolset = toolset
self._config: SearchConfig = config or {}
def __call__(
self,
query: str,
*,
connector: str | None = None,
top_k: int | None = None,
min_similarity: float | None = None,
account_ids: list[str] | None = None,
search: SearchMode | None = None,
) -> Tools:
"""Search for tools using natural language.
Args:
query: Natural language description of needed functionality
connector: Optional provider/connector filter (e.g., "bamboohr", "slack")
top_k: Maximum number of tools to return. Overrides constructor default.
min_similarity: Minimum similarity score threshold 0-1. Overrides constructor default.
account_ids: Optional account IDs (uses set_accounts() if not provided)
search: Override the default search mode for this call
Returns:
Tools collection with matched tools
"""
effective_top_k = top_k if top_k is not None else self._config.get("top_k")
effective_min_sim = (
min_similarity if min_similarity is not None else self._config.get("min_similarity")
)
effective_search = search if search is not None else self._config.get("method", "auto")
return self._toolset.search_tools(
query,
connector=connector,
top_k=effective_top_k,
min_similarity=effective_min_sim,
account_ids=account_ids,
search=effective_search,
)
class StackOneToolSet:
"""Main class for accessing StackOne tools"""
def __init__(
self,
api_key: str | None = None,
account_id: str | None = None,
base_url: str | None = None,
search: SearchConfig | None = None,
execute: ExecuteToolsConfig | None = None,
) -> None:
"""Initialize StackOne tools with authentication
Args:
api_key: Optional API key. If not provided, will try to get from STACKONE_API_KEY env var
account_id: Optional account ID
base_url: Optional base URL override for API requests
search: Search configuration. Controls default search behavior.
Pass ``None`` (default) to disable search — ``toolset.openai()``
will return all regular tools.
Pass ``{}`` or ``{"method": "auto"}`` to enable search with defaults.
Pass ``{"method": "semantic", "top_k": 5}`` for custom defaults.
Per-call options always override these defaults.
execute: Execution configuration. Controls default account scoping
for tool execution. Pass ``{"account_ids": ["acc-1"]}`` to scope
meta tools to specific accounts.
Raises:
ToolsetConfigError: If no API key is provided or found in environment
"""
api_key_value = api_key or os.getenv("STACKONE_API_KEY")
if not api_key_value:
raise ToolsetConfigError(
"API key must be provided either through api_key parameter or "
"STACKONE_API_KEY environment variable"
)
self.api_key: str = api_key_value
self.account_id = account_id
self.base_url = base_url or DEFAULT_BASE_URL
self._account_ids: list[str] = []
self._semantic_client: SemanticSearchClient | None = None
self._search_config: SearchConfig | None = search
self._execute_config: ExecuteToolsConfig | None = execute
self._tools_cache: Tools | None = None
def set_accounts(self, account_ids: list[str]) -> StackOneToolSet:
"""Set account IDs for filtering tools
Args:
account_ids: List of account IDs to filter tools by
Returns:
This toolset instance for chaining
"""
self._account_ids = account_ids
return self
def get_search_tool(self, *, search: SearchMode | None = None) -> SearchTool:
"""Get a callable search tool that returns Tools collections.
Returns a callable that wraps :meth:`search_tools` for use in agent loops.
The returned tool is directly callable: ``search_tool("query")`` returns
:class:`Tools`.
Uses the constructor's search config as defaults. Per-call options override.
Args:
search: Override the default search mode. If not provided, uses
the constructor's search config.
Returns:
SearchTool instance
Example::
toolset = StackOneToolSet()
search_tool = toolset.get_search_tool()
tools = search_tool("manage employee records", account_ids=["acc-123"])
"""
if self._search_config is None:
raise ToolsetConfigError(
"Search is disabled. Initialize StackOneToolSet with a search config to enable."
)
config: SearchConfig = {**self._search_config}
if search is not None:
config["method"] = search
return SearchTool(self, config=config)
def _build_tools(self, account_ids: list[str] | None = None) -> Tools:
"""Build tool_search + tool_execute tools scoped to this toolset."""
if self._search_config is None:
raise ToolsetConfigError(
"Search is disabled. Initialize StackOneToolSet with a search config to enable."
)
if account_ids:
self._account_ids = account_ids
search_tool = _create_search_tool(self.api_key)
search_tool._toolset = self
execute_tool = _create_execute_tool(self.api_key)
execute_tool._toolset = self
return Tools([search_tool, execute_tool])
def openai(
self,
*,
mode: Literal["search_and_execute"] | None = None,
account_ids: list[str] | None = None,
) -> list[dict[str, Any]]:
"""Get tools in OpenAI function calling format.
Args:
mode: Tool mode.
``None`` (default): fetch all tools and convert to OpenAI format.
``"search_and_execute"``: return two meta tools (tool_search + tool_execute)
that let the LLM discover and execute tools on-demand.
account_ids: Account IDs to scope tools. Overrides the ``execute``
config from the constructor.
Returns:
List of tool definitions in OpenAI function format.
Examples::
# All tools
toolset = StackOneToolSet()
tools = toolset.openai()
# Meta tools for agent-driven discovery
toolset = StackOneToolSet()
tools = toolset.openai(mode="search_and_execute")
"""
effective_account_ids = account_ids or (
self._execute_config.get("account_ids") if self._execute_config else None
)
if mode == "search_and_execute":
return self._build_tools(account_ids=effective_account_ids).to_openai()
return self.fetch_tools(account_ids=effective_account_ids).to_openai()
def langchain(
self,
*,
mode: Literal["search_and_execute"] | None = None,
account_ids: list[str] | None = None,
) -> Sequence[Any]:
"""Get tools in LangChain format.
Args:
mode: Tool mode.
``None`` (default): fetch all tools and convert to LangChain format.
``"search_and_execute"``: return two tools (tool_search + tool_execute)
that let the LLM discover and execute tools on-demand.
The framework handles tool execution automatically.
account_ids: Account IDs to scope tools. Overrides the ``execute``
config from the constructor.
Returns:
List of LangChain tool objects.
"""
effective_account_ids = account_ids or (
self._execute_config.get("account_ids") if self._execute_config else None
)
if mode == "search_and_execute":
return self._build_tools(account_ids=effective_account_ids).to_langchain()
return self.fetch_tools(account_ids=effective_account_ids).to_langchain()
def execute(
self,
tool_name: str,
arguments: str | dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Execute a tool by name.
Use with ``openai(mode="search_and_execute")`` in manual agent loops —
pass the tool name and arguments from the LLM's tool call directly.
Tools are cached after the first call.
Args:
tool_name: The tool name from the LLM's tool call
(e.g. ``"tool_search"`` or ``"tool_execute"``).
arguments: The arguments from the LLM's tool call,
as a JSON string or dict.
Returns:
Tool execution result as a dict.
"""
if self._tools_cache is None:
self._tools_cache = self._build_tools()
tool = self._tools_cache.get_tool(tool_name)
if tool is None:
return {"error": f'Tool "{tool_name}" not found.'}
return tool.execute(arguments)
@property
def semantic_client(self) -> SemanticSearchClient:
"""Lazy initialization of semantic search client.
Returns:
SemanticSearchClient instance configured with the toolset's API key and base URL
"""
if self._semantic_client is None:
self._semantic_client = SemanticSearchClient(
api_key=self.api_key,
base_url=self.base_url,
)
return self._semantic_client
def _local_search(
self,
query: str,
all_tools: Tools,
*,
connector: str | None = None,
top_k: int | None = None,
min_similarity: float | None = None,
) -> Tools:
"""Run local BM25+TF-IDF search over already-fetched tools."""
from stackone_ai.local_search import ToolIndex
available_connectors = all_tools.get_connectors()
if not available_connectors:
return Tools([])
index = ToolIndex(list(all_tools))
results = index.search(
query,
limit=top_k if top_k is not None else 5,
min_score=min_similarity if min_similarity is not None else 0.0,
)
matched_names = [r.name for r in results]
tool_map = {t.name: t for t in all_tools}
filter_connectors = {connector.lower()} if connector else available_connectors
matched_tools = [
tool_map[name]
for name in matched_names
if name in tool_map and name.split("_")[0].lower() in filter_connectors
]
return Tools(matched_tools[:top_k] if top_k is not None else matched_tools)
def search_tools(
self,
query: str,
*,
connector: str | None = None,
top_k: int | None = None,
min_similarity: float | None = None,
account_ids: list[str] | None = None,
search: SearchMode | None = None,
) -> Tools:
"""Search for and fetch tools using semantic or local search.
This method discovers relevant tools based on natural language queries.
Constructor search config provides defaults; per-call args override.
Args:
query: Natural language description of needed functionality
(e.g., "create employee", "send a message")
connector: Optional provider/connector filter (e.g., "bamboohr", "slack")
top_k: Maximum number of tools to return. Overrides constructor default.
min_similarity: Minimum similarity score threshold 0-1. Overrides constructor default.
account_ids: Optional account IDs (uses set_accounts() if not provided)
search: Search backend to use. Overrides constructor default.
- ``"auto"`` (default): try semantic search first, fall back to local
BM25+TF-IDF if the API is unavailable.
- ``"semantic"``: use only the semantic search API; raises
``SemanticSearchError`` on failure.
- ``"local"``: use only local BM25+TF-IDF search (no API call to the
semantic search endpoint).
Returns:
Tools collection with matched tools from linked accounts
Raises:
ToolsetConfigError: If search is disabled (``search=None`` in constructor)
SemanticSearchError: If the API call fails and search is ``"semantic"``
Examples:
# Semantic search (default with local fallback)
tools = toolset.search_tools("manage employee records", top_k=5)
# Explicit semantic search
tools = toolset.search_tools("manage employees", search="semantic")
# Local BM25+TF-IDF search
tools = toolset.search_tools("manage employees", search="local")
# Filter by connector
tools = toolset.search_tools(
"create time off request",
connector="bamboohr",
search="semantic",
)
"""
if self._search_config is None:
raise ToolsetConfigError(
"Search is disabled. Initialize StackOneToolSet with a search config to enable."
)
# Merge constructor defaults with per-call overrides
effective_search: SearchMode = (
search if search is not None else self._search_config.get("method", "auto")
)
effective_top_k = top_k if top_k is not None else self._search_config.get("top_k")
effective_min_sim = (
min_similarity if min_similarity is not None else self._search_config.get("min_similarity")
)
all_tools = self.fetch_tools(account_ids=account_ids)
available_connectors = all_tools.get_connectors()
if not available_connectors:
return Tools([])
# Local-only search — skip semantic API entirely
if effective_search == "local":
return self._local_search(
query, all_tools, connector=connector, top_k=effective_top_k, min_similarity=effective_min_sim
)
try:
# Determine which connectors to search
if connector:
connectors_to_search = {connector.lower()} & available_connectors
if not connectors_to_search:
return Tools([])
else:
connectors_to_search = available_connectors
# Search each connector in parallel
def _search_one(c: str) -> list[SemanticSearchResult]:
resp = self.semantic_client.search(
query=query, connector=c, top_k=effective_top_k, min_similarity=effective_min_sim
)
return list(resp.results)
all_results: list[SemanticSearchResult] = []
last_error: SemanticSearchError | None = None
max_workers = min(len(connectors_to_search), 10)
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as pool:
futures = {pool.submit(_search_one, c): c for c in connectors_to_search}
for future in concurrent.futures.as_completed(futures):
try:
all_results.extend(future.result())
except SemanticSearchError as e:
last_error = e
# If ALL connector searches failed, re-raise to trigger fallback
if not all_results and last_error is not None:
raise last_error
# Sort by score, apply top_k
all_results.sort(key=lambda r: r.similarity_score, reverse=True)
if effective_top_k is not None:
all_results = all_results[:effective_top_k]
if not all_results:
return Tools([])
# 1. Parse composite IDs to MCP-format action names, deduplicate
seen_names: set[str] = set()
action_names: list[str] = []
for result in all_results:
name = _normalize_action_name(result.id)
if name in seen_names:
continue
seen_names.add(name)
action_names.append(name)
if not action_names:
return Tools([])
# 2. Use MCP tools (already fetched) — schemas come from the source of truth
# 3. Filter to only the tools search found, preserving search relevance order
action_order = {name: i for i, name in enumerate(action_names)}
matched_tools = [t for t in all_tools if t.name in seen_names]
matched_tools.sort(key=lambda t: action_order.get(t.name, float("inf")))
# Auto mode: if semantic returned results but none matched MCP tools, fall back to local
if effective_search == "auto" and len(matched_tools) == 0:
logger.warning(
"Semantic search returned %d results but none matched MCP tools, "
"falling back to local search",
len(all_results),
)
return self._local_search(
query,
all_tools,
connector=connector,
top_k=effective_top_k,
min_similarity=effective_min_sim,
)
return Tools(matched_tools)
except SemanticSearchError as e:
if effective_search == "semantic":
raise
logger.warning("Semantic search failed (%s), falling back to local BM25+TF-IDF search", e)
return self._local_search(
query, all_tools, connector=connector, top_k=effective_top_k, min_similarity=effective_min_sim
)
def search_action_names(
self,
query: str,
*,
connector: str | None = None,
account_ids: list[str] | None = None,
top_k: int | None = None,
min_similarity: float | None = None,
) -> list[SemanticSearchResult]:
"""Search for action names without fetching tools.
Useful when you need to inspect search results before fetching,
or when building custom filtering logic.
Args:
query: Natural language description of needed functionality
connector: Optional provider/connector filter (single connector)
account_ids: Optional account IDs to scope results to connectors
available in those accounts (uses set_accounts() if not provided).
When provided, results are filtered to only matching connectors.
top_k: Maximum number of results. If None, uses the backend default.
min_similarity: Minimum similarity score threshold 0-1. If not provided,
the server uses its default.
Returns:
List of SemanticSearchResult with action names, scores, and metadata.
Versioned API names are normalized to MCP format but results are NOT
deduplicated — multiple API versions of the same action may appear
with their individual scores.
Examples:
# Lightweight: inspect results before fetching
results = toolset.search_action_names("manage employees")
for r in results:
print(f"{r.id}: {r.similarity_score:.2f}")
# Account-scoped: only results for connectors in linked accounts
results = toolset.search_action_names(
"create employee",