Coverage for stackone_ai / types.py: 100%
56 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"""Shared types, configuration and errors for the StackOne AI SDK."""
3from __future__ import annotations
5from collections.abc import Sequence
6from typing import Annotated, Any, Literal, TypeAlias, TypedDict
8from pydantic import (
9 BaseModel,
10 ConfigDict,
11 Field,
12 PlainSerializer,
13 SerializerFunctionWrapHandler,
14 SkipValidation,
15 model_serializer,
16)
18JsonDict: TypeAlias = dict[str, Any]
19Headers: TypeAlias = dict[str, str]
21# StackOne API base URL
22DEFAULT_BASE_URL: str = "https://api.stackone.com"
25ToolMode = Literal["individual", "search_execute"]
26"""How the MCP endpoint lists tools.
28``"individual"`` (the server default) lists one tool per action — hundreds per
29account. ``"search_execute"`` lists one fixed trio across every account instead:
30``stackone_list_accounts``, ``stackone_search_actions``, which ranks actions for a
31natural-language query, and ``stackone_execute_action``, which runs one by id. The
32catalog stays the same size however many accounts are linked, which is what keeps it
33inside a model's context. For a single account the server serves that account's own
34search and execute pair, which the SDK presents under the same two names.
35"""
37SEARCH_ACTIONS_TOOL_NAME: str = "stackone_search_actions"
38"""The ``search_execute`` tool that ranks actions, across every account in scope."""
40EXECUTE_ACTION_TOOL_NAME: str = "stackone_execute_action"
41"""The ``search_execute`` tool that runs an action by id, on the account it names or the
42only one in scope linked to the action's connector."""
44SUBMIT_FEEDBACK_TOOL_NAME: str = "stackone_submit_feedback"
45"""The one global tool the MCP endpoint serves in every mode when feedback is enabled.
47It is not a connector action, and it is global rather than account-scoped, so the toolset
48keeps one copy of it however many accounts list it.
49"""
51FeedbackRating = Literal["positive", "negative", "neutral"]
52FeedbackSource = Literal["model", "user", "system"]
53FeedbackCategory = Literal["search", "execute", "defender", "connection", "general"]
56class StackOneError(Exception):
57 """Base exception for StackOne errors"""
59 pass
62class StackOneAPIError(StackOneError):
63 """Raised when the StackOne API returns an error"""
65 def __init__(self, message: str, status_code: int, response_body: Any) -> None:
66 super().__init__(message)
67 self.status_code = status_code
68 self.response_body = response_body
71class ToolArgumentsError(StackOneError, ValueError):
72 """Raised when a tool's arguments are unusable, before any request is made:
74 - a JSON string argument that does not parse, or parses to something other than
75 an object
76 - an argument that cannot be encoded as JSON (a set, bytes, NaN/Infinity, a lone
77 surrogate, or a value that refers to itself, directly or through a cycle)
78 - ``call()`` given both positional and keyword arguments, or more than one
79 positional argument
81 A subclass of both StackOneError, so ``except StackOneError`` catches it, and
82 ValueError, which is what these errors were before, so existing
83 ``except ValueError`` clauses still do.
84 """
86 pass
89class ToolsetError(StackOneError):
90 """Base exception for toolset errors.
92 A subclass of StackOneError, so ``except StackOneError`` catches everything this
93 SDK raises. The two used to be unrelated siblings, which meant the obvious
94 catch-all silently missed ToolsetConfigError and ToolsetLoadError — the errors a
95 user is most likely to hit on their very first call. Existing
96 ``except ToolsetError`` clauses are unaffected.
97 """
99 pass
102class ToolsetConfigError(ToolsetError):
103 """Raised when there is an error in the toolset configuration"""
105 pass
108class ToolsetLoadError(ToolsetError):
109 """Raised when there is an error loading tools.
111 ``failures`` holds each account's error when every account failed to list tools for
112 differing reasons, in account order; otherwise it is empty.
113 """
115 def __init__(self, message: str, *, failures: Sequence[Exception] = ()) -> None:
116 super().__init__(message)
117 self.failures: list[Exception] = list(failures)
120class ExecuteToolsConfig(TypedDict, total=False):
121 """Execution configuration for the StackOneToolSet constructor.
123 Controls default account scoping and timeout for tool execution.
124 """
126 account_ids: list[str]
127 """Account IDs to scope tool discovery and execution."""
129 timeout: float
130 """Request timeout in seconds. Default: 60. Can also be set as a top-level
131 constructor param which takes precedence."""
134class ExecuteConfig(BaseModel):
135 """How a tool is called: its name, any extra request headers, and the timeout.
137 Every tool executes over MCP ``tools/call``, so there is no HTTP method, URL, body
138 type or parameter location to configure. Extra fields are refused rather than ignored,
139 so code still passing them finds out here instead of assuming they took effect.
140 """
142 model_config = ConfigDict(extra="forbid")
144 name: str = Field(description="Tool name")
145 headers: Headers = Field(
146 default_factory=dict,
147 description="Extra HTTP headers for the MCP request. Authorization, x-account-id and "
148 "User-Agent are always the SDK's own and cannot be replaced here.",
149 )
150 timeout: float = Field(default=60.0, description="Request timeout in seconds")
153class ToolParameters(BaseModel):
154 """Schema definition for tool parameters.
156 ``properties`` is a faithful mirror of the ``inputSchema`` the MCP server served,
157 with the SDK's internal ``nullable`` marker added per property. Every other root
158 keyword the server sent, ``required`` included, is kept verbatim as an extra field.
159 Consumers that need the raw served schema (for example the ADK plugin) read this
160 directly, so nothing here may be invented or dropped.
161 """
163 model_config = ConfigDict(extra="allow")
165 type: str = Field(description="JSON Schema type")
166 properties: JsonDict = Field(description="JSON Schema properties")
167 # Typed for callers building a tool by hand, but neither validated nor converted: a
168 # served `required` is kept exactly as sent, even when malformed, and the adapters
169 # drop what is not a list of names.
170 required: Annotated[SkipValidation[list[str] | None], PlainSerializer(lambda value: value)] = Field(
171 default=None, description="The names of the required properties, as served"
172 )
174 @model_serializer(mode="wrap")
175 def _dump_as_served(self, handler: SerializerFunctionWrapHandler) -> JsonDict:
176 # Omitted when it was never given, so a schema served without `required` dumps
177 # without one, as it did when `required` was only an extra field.
178 dumped = handler(self)
179 if "required" not in self.model_fields_set:
180 dumped.pop("required", None)
181 return dumped