stackone-ai 3.0.0__tar.gz → 3.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.1.0](https://github.com/StackOneHQ/stackone-ai-python/compare/stackone-ai-v3.0.0...stackone-ai-v3.1.0) (2026-11-17)
4
+
5
+
6
+ ### Features
7
+
8
+ * **deps:** support mcp 2 alongside mcp 1 ([#274](https://github.com/StackOneHQ/stackone-ai-python/issues/274)) ([7dfbf28](https://github.com/StackOneHQ/stackone-ai-python/commit/7dfbf28977f227e603d66f9a27faf545fe9456d0))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **deps:** clear open security alerts with lockfile bumps ([#264](https://github.com/StackOneHQ/stackone-ai-python/issues/264)) ([2ca1845](https://github.com/StackOneHQ/stackone-ai-python/commit/2ca1845036f846b5dc276871dd2347d78d09706b))
14
+ * **deps:** require the patched mcp and python-dotenv releases ([#265](https://github.com/StackOneHQ/stackone-ai-python/issues/265)) ([43ebf5e](https://github.com/StackOneHQ/stackone-ai-python/commit/43ebf5eaed9e23e65024bd428209ae05a8ec3d63))
15
+ * **examples:** exit non-zero when credentials are missing or nothing is listed ([#258](https://github.com/StackOneHQ/stackone-ai-python/issues/258)) ([9818a04](https://github.com/StackOneHQ/stackone-ai-python/commit/9818a042cfe5a40179d23cf05bdb0be60b5aab92))
16
+ * **packaging:** declare the Apache 2.0 licence and use absolute README links ([#255](https://github.com/StackOneHQ/stackone-ai-python/issues/255)) ([dc214cb](https://github.com/StackOneHQ/stackone-ai-python/commit/dc214cba11f664fcc6ef34d42cc764bcea928d22))
17
+ * **tools:** warn about duplicate tool names once, when a collection is built ([#266](https://github.com/StackOneHQ/stackone-ai-python/issues/266)) ([67e6973](https://github.com/StackOneHQ/stackone-ai-python/commit/67e6973f2d152b3d262a20c949483780ce1d4eab))
18
+
19
+
20
+ ### Performance Improvements
21
+
22
+ * share one SSL context across MCP calls ([#263](https://github.com/StackOneHQ/stackone-ai-python/issues/263)) ([751a60e](https://github.com/StackOneHQ/stackone-ai-python/commit/751a60e1c21fd6add56ddb483a4f510f50e3c23e))
23
+
24
+
25
+ ### Documentation
26
+
27
+ * align CLAUDE.md and make format with the code and CI ([#256](https://github.com/StackOneHQ/stackone-ai-python/issues/256)) ([7fb0139](https://github.com/StackOneHQ/stackone-ai-python/commit/7fb013969ce84b31e37a4450ab173a442aba6a4d))
28
+
3
29
  ## [3.0.0](https://github.com/StackOneHQ/stackone-ai-python/compare/stackone-ai-v2.10.1...stackone-ai-v3.0.0) (2026-10-29)
4
30
 
5
31
 
@@ -96,11 +96,11 @@ names = toolset.search_action_names("time off requests", top_k=5)
96
96
 
97
97
  # 3.0
98
98
  toolset = StackOneToolSet()
99
- hits = toolset.search("list employees", top_k=5) # a list of action dicts, best first
99
+ hits = toolset.search("list employees", top_k=5) # a list of action dicts, best first
100
100
  hit = hits[0]
101
101
  result = toolset.execute(
102
102
  hit["action_id"],
103
- {"query": {"page_size": 25}}, # the nested form in hit["input_schema"]
103
+ {"query": {"page_size": 25}}, # the nested form in hit["input_schema"]
104
104
  account_ids=[hit["available_accounts"][0]["id"]],
105
105
  session_id=hit.get("session_id"),
106
106
  )
@@ -193,7 +193,7 @@ import httpx
193
193
 
194
194
  link = download.execute({"id": "file-id"})["result"]
195
195
  # {"download_url": ..., "expires_at": ..., "file": {"name", "content_type", "content_length"}}
196
- name = Path(link["file"]["name"] or "download.bin").name # chosen by the provider: keep only the basename
196
+ name = Path(link["file"]["name"] or "download.bin").name # chosen by the provider: keep only the basename
197
197
  Path(name).write_bytes(httpx.get(link["download_url"]).content)
198
198
  ```
199
199
 
@@ -385,13 +385,23 @@ tool = StackOneTool(
385
385
  description="Get an employee",
386
386
  parameters=ToolParameters(type="object", properties={"id": {"type": "string"}}),
387
387
  _execute_config=ExecuteConfig(
388
- name="get_employee", method="GET", url="https://api.example.com/employees/{id}",
388
+ name="get_employee",
389
+ method="GET",
390
+ url="https://api.example.com/employees/{id}",
389
391
  parameter_locations={"id": ParameterLocation.PATH},
390
392
  ),
391
393
  _api_key="...",
392
394
  )
393
395
 
396
+
394
397
  # 3.0
398
+ import json
399
+
400
+ import httpx
401
+
402
+ from stackone_ai import ExecuteConfig, StackOneTool, ToolParameters
403
+
404
+
395
405
  class GetEmployee(StackOneTool):
396
406
  def __init__(self) -> None:
397
407
  super().__init__(
@@ -404,6 +414,7 @@ class GetEmployee(StackOneTool):
404
414
  args = json.loads(arguments) if isinstance(arguments, str) else dict(arguments or {})
405
415
  return httpx.get(f"https://api.example.com/employees/{args['id']}").json()
406
416
 
417
+
407
418
  tool = GetEmployee()
408
419
  ```
409
420
 
@@ -433,10 +444,12 @@ directly:
433
444
  ```python
434
445
  # 2.x
435
446
  from stackone_ai.integrations import to_tool_node
447
+
436
448
  node = to_tool_node(tools)
437
449
 
438
450
  # 3.0
439
451
  from langgraph.prebuilt import ToolNode
452
+
440
453
  node = ToolNode(tools.to_langchain())
441
454
  ```
442
455
 
@@ -1,12 +1,15 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stackone-ai
3
- Version: 3.0.0
3
+ Version: 3.1.0
4
4
  Summary: agents performing actions on your SaaS
5
+ Project-URL: Repository, https://github.com/StackOneHQ/stackone-ai-python
6
+ Project-URL: Changelog, https://github.com/StackOneHQ/stackone-ai-python/blob/main/CHANGELOG.md
7
+ Project-URL: Issues, https://github.com/StackOneHQ/stackone-ai-python/issues
5
8
  Author-email: StackOne <support@stackone.com>
9
+ License-Expression: Apache-2.0
6
10
  License-File: LICENSE
7
11
  Classifier: Development Status :: 4 - Beta
8
12
  Classifier: Intended Audience :: Developers
9
- Classifier: License :: OSI Approved :: MIT License
10
13
  Classifier: Programming Language :: Python :: 3
11
14
  Classifier: Programming Language :: Python :: 3.11
12
15
  Classifier: Programming Language :: Python :: 3.12
@@ -14,11 +17,12 @@ Classifier: Programming Language :: Python :: 3.13
14
17
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
18
  Requires-Python: >=3.11
16
19
  Requires-Dist: httpx>=0.28.0
17
- Requires-Dist: mcp<2.0.0,>=1.24.3
20
+ Requires-Dist: mcp!=2.0.*,!=2.1.*,<3.0.0,>=1.30.0
18
21
  Requires-Dist: pydantic>=2.10.6
19
22
  Provides-Extra: dev
20
23
  Requires-Dist: hypothesis>=6.141.1; extra == 'dev'
21
24
  Requires-Dist: langchain-core>=0.3.36; extra == 'dev'
25
+ Requires-Dist: pydantic-ai-slim>=1.83.0; extra == 'dev'
22
26
  Requires-Dist: pytest-asyncio>=0.25.3; extra == 'dev'
23
27
  Requires-Dist: pytest-cov>=6.0.0; extra == 'dev'
24
28
  Requires-Dist: pytest>=8.3.4; extra == 'dev'
@@ -29,7 +33,7 @@ Requires-Dist: langchain-openai>=1.1.14; extra == 'examples'
29
33
  Requires-Dist: langchain>=1.0.0; extra == 'examples'
30
34
  Requires-Dist: openai>=2.32.0; extra == 'examples'
31
35
  Requires-Dist: pydantic-ai>=1.83.0; extra == 'examples'
32
- Requires-Dist: python-dotenv>=1.0.1; extra == 'examples'
36
+ Requires-Dist: python-dotenv>=1.2.2; extra == 'examples'
33
37
  Provides-Extra: langchain
34
38
  Requires-Dist: langchain-core>=0.3.36; extra == 'langchain'
35
39
  Provides-Extra: pydantic-ai
@@ -144,7 +148,7 @@ model can call itself.
144
148
 
145
149
  Every block below runs as written against any linked account — the `*_list_*`
146
150
  filter discovers whatever your key can reach rather than assuming a provider.
147
- Each has a matching runnable script in [examples/](examples/).
151
+ Each has a matching runnable script in [examples/](https://github.com/StackOneHQ/stackone-ai-python/tree/main/examples).
148
152
 
149
153
  <details>
150
154
  <summary>OpenAI</summary>
@@ -157,7 +161,7 @@ from stackone_ai import StackOneToolSet
157
161
 
158
162
  toolset = StackOneToolSet()
159
163
  tools = toolset.fetch_tools(actions=["*_list_*"])
160
- openai_tools = tools.to_openai()[:20] # keep the catalog inside the context window
164
+ openai_tools = tools.to_openai()[:20] # keep the catalog inside the context window
161
165
 
162
166
  client = OpenAI()
163
167
  messages = [{"role": "user", "content": "Use a tool to list a few records, then summarise them."}]
@@ -166,7 +170,7 @@ response = client.chat.completions.create(
166
170
  )
167
171
 
168
172
  message = response.choices[0].message
169
- messages.append(message.model_dump(exclude_none=True)) # the assistant turn comes first
173
+ messages.append(message.model_dump(exclude_none=True)) # the assistant turn comes first
170
174
  messages.extend(tools.execute_openai_tool_calls(message.tool_calls))
171
175
  ```
172
176
 
@@ -175,7 +179,7 @@ messages.extend(tools.execute_openai_tool_calls(message.tool_calls))
175
179
  messages to send back. A failed call becomes an error message the model can read and
176
180
  retry from, rather than an exception. Chat Completions accepts at
177
181
  most **128 tools**, so filter before binding. See
178
- [examples/openai_integration.py](examples/openai_integration.py) for the full
182
+ [examples/openai_integration.py](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/openai_integration.py) for the full
179
183
  round trip, including feeding results back for a final answer.
180
184
 
181
185
  </details>
@@ -260,19 +264,18 @@ applied locally to one cached listing — changing a filter never refetches. Cal
260
264
  ```python
261
265
  toolset = StackOneToolSet()
262
266
 
263
- toolset.fetch_tools() # every tool, every active shared account
264
- toolset.fetch_tools(providers=["linear"]) # one connector
265
- toolset.fetch_tools(actions=["linear_list_*"]) # one connector's list actions
266
- toolset.fetch_tools(actions=["linear_get_issue"]) # exactly one tool
267
- toolset.fetch_tools(providers=["linear"],
268
- actions=["*_get_*"]) # both filters, AND-ed
267
+ toolset.fetch_tools() # every tool, every active shared account
268
+ toolset.fetch_tools(providers=["linear"]) # one connector
269
+ toolset.fetch_tools(actions=["linear_list_*"]) # one connector's list actions
270
+ toolset.fetch_tools(actions=["linear_get_issue"]) # exactly one tool
271
+ toolset.fetch_tools(providers=["linear"], actions=["*_get_*"]) # both filters, AND-ed
269
272
  toolset.fetch_tools(account_ids=["acc-123", "acc-456"])
270
273
  ```
271
274
 
272
275
  - **`account_ids`** — restrict to these accounts. Omit it and the SDK discovers
273
276
  your active shared accounts (non-shared ones too with `include_non_shared=True`). An empty list means "no filter", not "no accounts". A
274
- single failing account is logged and skipped, not fatal — unless it is rate
275
- limited (see [Rate limits](#rate-limits)) — and left out of the cached catalog for
277
+ single failing account is logged and skipped, not fatal (unless it is rate limited, see
278
+ [Rate limits](https://github.com/StackOneHQ/stackone-ai-python#rate-limits)), and left out of the cached catalog for
276
279
  30 seconds, after which the next call lists it again. If every account fails with
277
280
  the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is raised;
278
281
  otherwise a `ToolsetLoadError` whose `failures` holds each account's error.
@@ -353,7 +356,7 @@ The SDK exposes the same actions through two surfaces. Both execute over MCP
353
356
  your arguments as given, except header arguments: each is forwarded only if the tool's
354
357
  schema declares it, and `Authorization`, `x-account-id`, `User-Agent` and `x-end-user-id`
355
358
  never are (see
356
- [the migration guide](MIGRATION.md#tool-arguments-and-headers)). They take **different
359
+ [the migration guide](https://github.com/StackOneHQ/stackone-ai-python/blob/main/MIGRATION.md#tool-arguments-and-headers)). They take **different
357
360
  argument shapes**, because each mirrors the schema the server served for it. Both return the server's result exactly
358
361
  as it wrote it: `{"isError": false, "result": ..., "defenderMetadata"?, "policyMetadata"?}`.
359
362
 
@@ -414,14 +417,14 @@ Falls back to the `STACKONE_BASE_URL` environment variable, then to
414
417
 
415
418
  ## Examples
416
419
 
417
- For more examples, check out the [examples/](examples/) directory:
420
+ For more examples, check out the [examples/](https://github.com/StackOneHQ/stackone-ai-python/tree/main/examples) directory:
418
421
 
419
- - [OpenAI Integration](examples/openai_integration.py) — OpenAI function calling
420
- - [Search and Execute](examples/search_and_execute.py) — the recommended flow
421
- - [LangChain Integration](examples/langchain_integration.py) — LangChain tools
422
- - [LangGraph Integration](examples/langgraph_integration.py) — LangGraph agent
423
- - [Pydantic AI Integration](examples/pydantic_ai_integration.py) — Pydantic AI agent
424
- - [Auth Management](examples/auth_management.py) — API key and account ID patterns
422
+ - [OpenAI Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/openai_integration.py): OpenAI function calling
423
+ - [Search and Execute](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/search_and_execute.py): the recommended flow
424
+ - [LangChain Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/langchain_integration.py): LangChain tools
425
+ - [LangGraph Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/langgraph_integration.py): LangGraph agent
426
+ - [Pydantic AI Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/pydantic_ai_integration.py): Pydantic AI agent
427
+ - [Auth Management](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/auth_management.py): API key and account ID patterns
425
428
 
426
429
  ## Development
427
430
 
@@ -106,7 +106,7 @@ model can call itself.
106
106
 
107
107
  Every block below runs as written against any linked account — the `*_list_*`
108
108
  filter discovers whatever your key can reach rather than assuming a provider.
109
- Each has a matching runnable script in [examples/](examples/).
109
+ Each has a matching runnable script in [examples/](https://github.com/StackOneHQ/stackone-ai-python/tree/main/examples).
110
110
 
111
111
  <details>
112
112
  <summary>OpenAI</summary>
@@ -119,7 +119,7 @@ from stackone_ai import StackOneToolSet
119
119
 
120
120
  toolset = StackOneToolSet()
121
121
  tools = toolset.fetch_tools(actions=["*_list_*"])
122
- openai_tools = tools.to_openai()[:20] # keep the catalog inside the context window
122
+ openai_tools = tools.to_openai()[:20] # keep the catalog inside the context window
123
123
 
124
124
  client = OpenAI()
125
125
  messages = [{"role": "user", "content": "Use a tool to list a few records, then summarise them."}]
@@ -128,7 +128,7 @@ response = client.chat.completions.create(
128
128
  )
129
129
 
130
130
  message = response.choices[0].message
131
- messages.append(message.model_dump(exclude_none=True)) # the assistant turn comes first
131
+ messages.append(message.model_dump(exclude_none=True)) # the assistant turn comes first
132
132
  messages.extend(tools.execute_openai_tool_calls(message.tool_calls))
133
133
  ```
134
134
 
@@ -137,7 +137,7 @@ messages.extend(tools.execute_openai_tool_calls(message.tool_calls))
137
137
  messages to send back. A failed call becomes an error message the model can read and
138
138
  retry from, rather than an exception. Chat Completions accepts at
139
139
  most **128 tools**, so filter before binding. See
140
- [examples/openai_integration.py](examples/openai_integration.py) for the full
140
+ [examples/openai_integration.py](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/openai_integration.py) for the full
141
141
  round trip, including feeding results back for a final answer.
142
142
 
143
143
  </details>
@@ -222,19 +222,18 @@ applied locally to one cached listing — changing a filter never refetches. Cal
222
222
  ```python
223
223
  toolset = StackOneToolSet()
224
224
 
225
- toolset.fetch_tools() # every tool, every active shared account
226
- toolset.fetch_tools(providers=["linear"]) # one connector
227
- toolset.fetch_tools(actions=["linear_list_*"]) # one connector's list actions
228
- toolset.fetch_tools(actions=["linear_get_issue"]) # exactly one tool
229
- toolset.fetch_tools(providers=["linear"],
230
- actions=["*_get_*"]) # both filters, AND-ed
225
+ toolset.fetch_tools() # every tool, every active shared account
226
+ toolset.fetch_tools(providers=["linear"]) # one connector
227
+ toolset.fetch_tools(actions=["linear_list_*"]) # one connector's list actions
228
+ toolset.fetch_tools(actions=["linear_get_issue"]) # exactly one tool
229
+ toolset.fetch_tools(providers=["linear"], actions=["*_get_*"]) # both filters, AND-ed
231
230
  toolset.fetch_tools(account_ids=["acc-123", "acc-456"])
232
231
  ```
233
232
 
234
233
  - **`account_ids`** — restrict to these accounts. Omit it and the SDK discovers
235
234
  your active shared accounts (non-shared ones too with `include_non_shared=True`). An empty list means "no filter", not "no accounts". A
236
- single failing account is logged and skipped, not fatal — unless it is rate
237
- limited (see [Rate limits](#rate-limits)) — and left out of the cached catalog for
235
+ single failing account is logged and skipped, not fatal (unless it is rate limited, see
236
+ [Rate limits](https://github.com/StackOneHQ/stackone-ai-python#rate-limits)), and left out of the cached catalog for
238
237
  30 seconds, after which the next call lists it again. If every account fails with
239
238
  the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is raised;
240
239
  otherwise a `ToolsetLoadError` whose `failures` holds each account's error.
@@ -315,7 +314,7 @@ The SDK exposes the same actions through two surfaces. Both execute over MCP
315
314
  your arguments as given, except header arguments: each is forwarded only if the tool's
316
315
  schema declares it, and `Authorization`, `x-account-id`, `User-Agent` and `x-end-user-id`
317
316
  never are (see
318
- [the migration guide](MIGRATION.md#tool-arguments-and-headers)). They take **different
317
+ [the migration guide](https://github.com/StackOneHQ/stackone-ai-python/blob/main/MIGRATION.md#tool-arguments-and-headers)). They take **different
319
318
  argument shapes**, because each mirrors the schema the server served for it. Both return the server's result exactly
320
319
  as it wrote it: `{"isError": false, "result": ..., "defenderMetadata"?, "policyMetadata"?}`.
321
320
 
@@ -376,14 +375,14 @@ Falls back to the `STACKONE_BASE_URL` environment variable, then to
376
375
 
377
376
  ## Examples
378
377
 
379
- For more examples, check out the [examples/](examples/) directory:
378
+ For more examples, check out the [examples/](https://github.com/StackOneHQ/stackone-ai-python/tree/main/examples) directory:
380
379
 
381
- - [OpenAI Integration](examples/openai_integration.py) — OpenAI function calling
382
- - [Search and Execute](examples/search_and_execute.py) — the recommended flow
383
- - [LangChain Integration](examples/langchain_integration.py) — LangChain tools
384
- - [LangGraph Integration](examples/langgraph_integration.py) — LangGraph agent
385
- - [Pydantic AI Integration](examples/pydantic_ai_integration.py) — Pydantic AI agent
386
- - [Auth Management](examples/auth_management.py) — API key and account ID patterns
380
+ - [OpenAI Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/openai_integration.py): OpenAI function calling
381
+ - [Search and Execute](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/search_and_execute.py): the recommended flow
382
+ - [LangChain Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/langchain_integration.py): LangChain tools
383
+ - [LangGraph Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/langgraph_integration.py): LangGraph agent
384
+ - [Pydantic AI Integration](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/pydantic_ai_integration.py): Pydantic AI agent
385
+ - [Auth Management](https://github.com/StackOneHQ/stackone-ai-python/blob/main/examples/auth_management.py): API key and account ID patterns
387
386
 
388
387
  ## Development
389
388
 
@@ -1,14 +1,15 @@
1
1
  [project]
2
2
  name = "stackone-ai"
3
- version = "3.0.0"
3
+ version = "3.1.0"
4
4
  description = "agents performing actions on your SaaS"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
7
9
  authors = [{ name = "StackOne", email = "support@stackone.com" }]
8
10
  classifiers = [
9
11
  "Development Status :: 4 - Beta",
10
12
  "Intended Audience :: Developers",
11
- "License :: OSI Approved :: MIT License",
12
13
  "Programming Language :: Python :: 3",
13
14
  "Programming Language :: Python :: 3.11",
14
15
  "Programming Language :: Python :: 3.12",
@@ -20,11 +21,17 @@ dependencies = [
20
21
  "httpx>=0.28.0",
21
22
  # fetch_tools() is the only route to a tool and talks MCP, so the client is
22
23
  # not optional: without it the SDK cannot do anything.
23
- "mcp>=1.24.3,<2.0.0",
24
+ # 1.30.0 and 2.2.0 are the first of each major with every published advisory fixed.
25
+ "mcp>=1.30.0,!=2.0.*,!=2.1.*,<3.0.0",
24
26
  ]
25
27
 
28
+ [project.urls]
29
+ Repository = "https://github.com/StackOneHQ/stackone-ai-python"
30
+ Changelog = "https://github.com/StackOneHQ/stackone-ai-python/blob/main/CHANGELOG.md"
31
+ Issues = "https://github.com/StackOneHQ/stackone-ai-python/issues"
32
+
26
33
  [build-system]
27
- requires = ["hatchling"]
34
+ requires = ["hatchling>=1.27"]
28
35
  build-backend = "hatchling.build"
29
36
 
30
37
  [tool.hatch.build.targets.wheel]
@@ -45,11 +52,12 @@ examples = [
45
52
  "langchain-openai>=1.1.14",
46
53
  "openai>=2.32.0",
47
54
  "pydantic-ai>=1.83.0",
48
- "python-dotenv>=1.0.1",
55
+ "python-dotenv>=1.2.2",
49
56
  ]
50
57
  dev = [
51
58
  "hypothesis>=6.141.1",
52
59
  "langchain-core>=0.3.36",
60
+ "pydantic-ai-slim>=1.83.0",
53
61
  "pytest>=8.3.4",
54
62
  "pytest-asyncio>=0.25.3",
55
63
  "pytest-cov>=6.0.0",
@@ -62,12 +70,11 @@ testpaths = ["tests"]
62
70
  asyncio_mode = "strict"
63
71
  asyncio_default_fixture_loop_scope = "function"
64
72
 
65
- [tool.ruff.lint.per-file-ignores]
66
- "examples/**.py" = ["E501", "F841", "E402"]
67
-
68
73
  [tool.ruff]
69
74
  line-length = 110
70
75
  target-version = "py311"
76
+ # Vendored byte for byte from sdk-conformance; CI diffs it against the pinned commit.
77
+ extend-exclude = ["tests/vectors"]
71
78
 
72
79
  [tool.ruff.lint]
73
80
  select = [
@@ -83,10 +90,7 @@ select = [
83
90
  [tool.coverage.run]
84
91
  source = ["stackone_ai"]
85
92
  branch = true
86
- omit = ["stackone_ai/__init__.py", "**/py.typed"]
87
-
88
- [tool.coverage.report]
89
- exclude_lines = ["pragma: no cover"]
93
+ omit = ["stackone_ai/__init__.py"]
90
94
 
91
95
  [tool.coverage.json]
92
96
  output = "coverage/coverage.json"
@@ -37,4 +37,4 @@ __all__ = [
37
37
  "ToolsetConfigError",
38
38
  "ToolsetLoadError",
39
39
  ]
40
- __version__ = "3.0.0"
40
+ __version__ = "3.1.0"
@@ -11,21 +11,23 @@ from __future__ import annotations
11
11
  import asyncio
12
12
  import base64
13
13
  import calendar
14
+ import functools
14
15
  import json
15
16
  import logging
16
17
  import math
17
18
  import random
18
19
  import re
20
+ import ssl
19
21
  import threading
20
22
  import time
21
23
  from collections import Counter
22
- from collections.abc import AsyncIterator, Callable, Coroutine, Iterable, Sequence
24
+ from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable, Sequence
23
25
  from contextlib import asynccontextmanager
24
26
  from dataclasses import dataclass
25
27
  from datetime import UTC, datetime, timedelta
26
28
  from decimal import Decimal
27
29
  from importlib import metadata
28
- from typing import Any, NoReturn, TypeVar
30
+ from typing import TYPE_CHECKING, Any, NoReturn, TypeVar
29
31
 
30
32
  import anyio
31
33
  import httpx
@@ -42,12 +44,18 @@ from stackone_ai.types import (
42
44
  ToolArgumentsError,
43
45
  ToolParameters,
44
46
  ToolsetConfigError,
45
- ToolsetError,
46
47
  ToolsetLoadError,
47
48
  )
48
49
 
49
50
  logger = logging.getLogger("stackone.tools")
50
51
 
52
+ # The HTTP library the installed mcp transport takes: httpx before mcp 2, httpx2 (an mcp 2
53
+ # dependency) from then on. GET /accounts always uses httpx.
54
+ if TYPE_CHECKING or int(metadata.version("mcp").split(".")[0]) >= 2:
55
+ import httpx2 as _mcp_http
56
+ else:
57
+ _mcp_http = httpx
58
+
51
59
  T = TypeVar("T")
52
60
 
53
61
  try:
@@ -344,10 +352,10 @@ def build_auth_header(api_key: str) -> str:
344
352
  return f"Basic {token}"
345
353
 
346
354
 
347
- async def _buffer_error_body(response: httpx.Response) -> None:
355
+ async def _buffer_error_body(response: _mcp_http.Response) -> None:
348
356
  """Read an error response's body while its stream is still open.
349
357
 
350
- The ``mcp`` client raises on the status after the streamed response is closed, so
358
+ An error status is raised after the streamed response is closed, so
351
359
  reading the body afterwards got nothing and every failure said only "400 Bad
352
360
  Request". The body is where the server explains itself: "Legacy accounts cannot be
353
361
  used with MCP", or a 412 asking for the account to be re-linked. Node already
@@ -463,7 +471,7 @@ def _backoff_delay(retry: int, retry_after: float | None, random_value: float |
463
471
  return min(retry_after, RATE_LIMIT_MAX_DELAY_SECONDS)
464
472
 
465
473
 
466
- def _rate_limit_delay(response: httpx.Response, retry: int) -> float:
474
+ def _rate_limit_delay(response: httpx.Response | _mcp_http.Response, retry: int) -> float:
467
475
  """How long to wait before retry number ``retry`` (1-based) of this 429."""
468
476
  return _backoff_delay(retry, _retry_after_seconds(response.headers.get("retry-after")))
469
477
 
@@ -473,7 +481,7 @@ def _waits_for_retry(delay: float, remaining: float) -> bool:
473
481
  return delay < remaining
474
482
 
475
483
 
476
- def _log_rate_limit_retry(request: httpx.Request, attempt: int, delay: float) -> None:
484
+ def _log_rate_limit_retry(request: httpx.Request | _mcp_http.Request, attempt: int, delay: float) -> None:
477
485
  logger.warning(
478
486
  "%s %s was rate limited (429) on attempt %d of %d; retrying in %ss",
479
487
  request.method,
@@ -484,7 +492,9 @@ def _log_rate_limit_retry(request: httpx.Request, attempt: int, delay: float) ->
484
492
  )
485
493
 
486
494
 
487
- def _outlasts_deadline(request: httpx.Request, attempt: int, delay: float, remaining: float) -> bool:
495
+ def _outlasts_deadline(
496
+ request: httpx.Request | _mcp_http.Request, attempt: int, delay: float, remaining: float
497
+ ) -> bool:
488
498
  """Whether waiting ``delay`` would not end before the deadline, logging when so.
489
499
 
490
500
  Such a wait is not started. Sleeping into the deadline would turn the 429 into a
@@ -556,11 +566,11 @@ class _Throttle:
556
566
  GET, say, answered while a ``tools/list`` retry hangs, must not clear that retry's 429.
557
567
  """
558
568
 
559
- response: httpx.Response | None = None
569
+ response: _mcp_http.Response | None = None
560
570
  retrying: int = 0
561
571
 
562
572
 
563
- class RateLimitRetryingAsyncClient(httpx.AsyncClient):
573
+ class RateLimitRetryingAsyncClient(_mcp_http.AsyncClient):
564
574
  """The async counterpart of :class:`RateLimitRetryingClient`, used for every MCP request.
565
575
 
566
576
  The MCP client streams its responses; a discarded 429 is read and closed here, and
@@ -578,7 +588,7 @@ class RateLimitRetryingAsyncClient(httpx.AsyncClient):
578
588
  super().__init__(*args, **kwargs)
579
589
  self._throttle = throttle
580
590
 
581
- async def send(self, request: httpx.Request, **kwargs: Any) -> httpx.Response:
591
+ async def send(self, request: _mcp_http.Request, **kwargs: Any) -> _mcp_http.Response:
582
592
  attempt = 1
583
593
  retried = False
584
594
  response = await super().send(request, **kwargs)
@@ -602,6 +612,13 @@ class RateLimitRetryingAsyncClient(httpx.AsyncClient):
602
612
  self._throttle.retrying -= 1
603
613
  if self._throttle.retrying == 0:
604
614
  self._throttle.response = None
615
+ if request.method == "POST" and response.is_error and response.status_code != 404:
616
+ # mcp 2 answers a failed POST with a JSON-RPC error that drops the status and the
617
+ # body; raised as mcp 1 does, it keeps both. A 404 is left to mcp: a lost session.
618
+ await response.aclose()
619
+ raise _mcp_http.HTTPStatusError(
620
+ f"{response.status_code} {response.reason_phrase}", request=request, response=response
621
+ )
605
622
  return response
606
623
 
607
624
 
@@ -622,17 +639,26 @@ def is_rate_limited(exc: BaseException) -> bool:
622
639
  if id(current) in seen:
623
640
  continue
624
641
  seen.add(id(current))
625
- if isinstance(current, httpx.HTTPStatusError) and current.response.status_code == 429:
642
+ if (
643
+ isinstance(current, httpx.HTTPStatusError | _mcp_http.HTTPStatusError)
644
+ and current.response.status_code == 429
645
+ ):
626
646
  return True
627
647
  stack.extend(getattr(current, "exceptions", None) or [])
628
648
  stack.extend(e for e in (current.__cause__, current.__context__) if e is not None)
629
649
  return False
630
650
 
631
651
 
652
+ @functools.cache
653
+ def _ssl_context() -> ssl.SSLContext:
654
+ """One SSL context for every MCP client: building one loads the CA bundle each time."""
655
+ return httpx.create_ssl_context()
656
+
657
+
632
658
  @asynccontextmanager
633
659
  async def _mcp_transport(
634
660
  endpoint: str, headers: dict[str, str], timeout: float, throttle: _Throttle | None = None
635
- ) -> AsyncIterator[tuple[Any, Any, Any]]:
661
+ ) -> AsyncGenerator[tuple[Any, Any]]:
636
662
  """Open the streamable-HTTP transport with the caller's timeout on every leg.
637
663
 
638
664
  The client's own defaults are a 30s connect and a 300s SSE read, and neither was
@@ -645,80 +671,104 @@ async def _mcp_transport(
645
671
  than headers and timeouts. It retries a 429, so the MCP client never sees one that
646
672
  a retry got past.
647
673
  """
648
- from mcp.client.streamable_http import streamable_http_client # ty: ignore[unresolved-import]
674
+ from mcp.client.streamable_http import streamable_http_client
649
675
 
650
676
  async with RateLimitRetryingAsyncClient(
651
677
  throttle=throttle,
652
678
  headers=headers,
653
- timeout=httpx.Timeout(timeout),
679
+ timeout=_mcp_http.Timeout(timeout),
680
+ verify=_ssl_context(),
654
681
  follow_redirects=True,
655
682
  event_hooks={"response": [_buffer_error_body]},
656
683
  ) as client:
657
684
  async with streamable_http_client(endpoint, http_client=client) as streams:
658
- yield streams
685
+ # mcp 1 also yields a session-id getter, which nothing here reads.
686
+ yield streams[0], streams[1]
659
687
 
660
688
 
661
- def fetch_mcp_tools(
662
- endpoint: str, headers: dict[str, str], *, timeout: float = 60.0
663
- ) -> list[McpToolDefinition]:
664
- """List every tool the MCP endpoint serves, following pagination.
689
+ def _run_mcp_session(
690
+ endpoint: str,
691
+ headers: dict[str, str],
692
+ timeout: float,
693
+ work: Callable[[Any], Coroutine[Any, Any, T]],
694
+ ) -> T:
695
+ """Open an initialized MCP session to ``endpoint``, run ``work`` on it and close it.
665
696
 
666
- ``timeout`` bounds the whole exchange, handshake included.
697
+ ``timeout`` bounds the whole exchange, handshake included. Any failure is raised
698
+ through :func:`_raise_mcp_failure`.
667
699
  """
668
700
  try:
669
- from mcp import types as mcp_types # ty: ignore[unresolved-import]
670
- from mcp.client.session import ClientSession # ty: ignore[unresolved-import]
671
- except ImportError as exc: # pragma: no cover - depends on optional extra
701
+ from mcp import types as mcp_types
702
+ from mcp.client.session import ClientSession
703
+ except ImportError as exc: # pragma: no cover - only a broken install gets here
672
704
  raise ToolsetConfigError(
673
705
  "mcp is a core dependency of stackone-ai but could not be imported — reinstall the package."
674
706
  ) from exc
675
707
 
676
708
  throttle = _Throttle()
677
709
 
678
- async def _list() -> list[McpToolDefinition]:
710
+ async def _run() -> T:
679
711
  with anyio.fail_after(timeout):
680
- return await _list_within_deadline()
681
-
682
- async def _list_within_deadline() -> list[McpToolDefinition]:
683
- async with _mcp_transport(endpoint, headers, timeout, throttle) as (
684
- read_stream,
685
- write_stream,
686
- _,
687
- ):
688
- session = ClientSession(
689
- read_stream,
690
- write_stream,
691
- client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION),
692
- )
693
- async with session:
694
- await session.initialize()
695
- cursor: str | None = None
696
- collected: list[McpToolDefinition] = []
697
- while True:
698
- result = await session.list_tools(cursor)
699
- for tool in result.tools:
700
- input_schema = tool.inputSchema or {}
701
- collected.append(
702
- McpToolDefinition(
703
- name=tool.name,
704
- description=tool.description,
705
- input_schema=dict(input_schema),
706
- )
707
- )
708
- cursor = result.nextCursor
709
- if cursor is None:
710
- break
711
- return collected
712
+ async with _mcp_transport(endpoint, headers, timeout, throttle) as (read_stream, write_stream):
713
+ session = ClientSession(
714
+ read_stream,
715
+ write_stream,
716
+ client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION),
717
+ )
718
+ async with session:
719
+ await session.initialize()
720
+ return await work(session)
712
721
 
713
722
  try:
714
- return run_async(_list())
723
+ return run_async(_run())
715
724
  except Exception as exc:
716
725
  # Exception, not BaseException: Ctrl-C and SystemExit must stop the caller, not come
717
726
  # back as a ToolsetLoadError that an agent framework hands the model as a tool result.
718
727
  _raise_mcp_failure(exc, endpoint, timeout, throttle)
719
728
 
720
729
 
721
- def _response_body(response: httpx.Response) -> str:
730
+ def _mcp_field(model: Any, name: str, wire_name: str, default: Any = None) -> Any:
731
+ """A field of an mcp model: mcp 2 names it in snake_case, mcp 1 as the wire does."""
732
+ try:
733
+ return getattr(model, name)
734
+ except AttributeError:
735
+ return getattr(model, wire_name, default)
736
+
737
+
738
+ def fetch_mcp_tools(
739
+ endpoint: str, headers: dict[str, str], *, timeout: float = 60.0
740
+ ) -> list[McpToolDefinition]:
741
+ """List every tool the MCP endpoint serves, following pagination.
742
+
743
+ ``timeout`` bounds the whole exchange, handshake included.
744
+ """
745
+
746
+ async def _list(session: Any) -> list[McpToolDefinition]:
747
+ from mcp import types as mcp_types
748
+
749
+ cursor: str | None = None
750
+ collected: list[McpToolDefinition] = []
751
+ while True:
752
+ params = mcp_types.PaginatedRequestParams(cursor=cursor) if cursor is not None else None
753
+ result = await session.list_tools(params=params)
754
+ for tool in result.tools:
755
+ input_schema = _mcp_field(tool, "input_schema", "inputSchema") or {}
756
+ collected.append(
757
+ McpToolDefinition(
758
+ name=tool.name,
759
+ description=tool.description,
760
+ input_schema=dict(input_schema),
761
+ )
762
+ )
763
+ cursor = _mcp_field(result, "next_cursor", "nextCursor")
764
+ if cursor is None:
765
+ break
766
+ return collected
767
+
768
+ return _run_mcp_session(endpoint, headers, timeout, _list)
769
+
770
+
771
+ def _response_body(response: _mcp_http.Response) -> str:
722
772
  """Best-effort read of an error body.
723
773
 
724
774
  The MCP transport streams, so `.text` raises until the stream is read, and by
@@ -755,9 +805,9 @@ def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) ->
755
805
  seen.add(id(current))
756
806
  # Our own errors are already descriptive. They reach here wrapped in an
757
807
  # ExceptionGroup because they are raised inside the session's TaskGroup.
758
- if isinstance(current, StackOneError | ToolsetError):
808
+ if isinstance(current, StackOneError):
759
809
  return current
760
- if isinstance(current, httpx.HTTPStatusError):
810
+ if isinstance(current, _mcp_http.HTTPStatusError):
761
811
  body = _response_body(current.response)
762
812
  detail = f": {body}" if body else ""
763
813
  status = f"{current.response.status_code} {current.response.reason_phrase}".rstrip()
@@ -777,7 +827,7 @@ def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) ->
777
827
  # for the deadline's TimeoutError that is the cancellation, or whatever the
778
828
  # cancelled task happened to be catching.
779
829
  leaf = _leaf_failure(exc)
780
- if isinstance(leaf, TimeoutError | httpx.TimeoutException):
830
+ if isinstance(leaf, TimeoutError | _mcp_http.TimeoutException):
781
831
  return ToolsetLoadError(f"MCP request to {endpoint} timed out after {_js_number(timeout)}s")
782
832
  return ToolsetLoadError(f"MCP request to {endpoint} failed: {type(leaf).__name__}: {leaf}")
783
833
 
@@ -785,7 +835,7 @@ def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) ->
785
835
  def _leaf_failure(exc: BaseException) -> BaseException:
786
836
  """The innermost cause through group members and ``__cause__``, stopping at a timeout."""
787
837
  leaf = exc
788
- while not isinstance(leaf, TimeoutError | httpx.TimeoutException):
838
+ while not isinstance(leaf, TimeoutError | _mcp_http.TimeoutException):
789
839
  members = getattr(leaf, "exceptions", None)
790
840
  if members:
791
841
  leaf = members[0]
@@ -806,8 +856,8 @@ def _raise_mcp_failure(exc: Exception, endpoint: str, timeout: float, throttle:
806
856
  :func:`is_rate_limited` reads it as the HTTP 429 it is.
807
857
  """
808
858
  throttled = throttle.response
809
- if throttled is not None and isinstance(_leaf_failure(exc), TimeoutError | httpx.TimeoutException):
810
- status = httpx.HTTPStatusError(
859
+ if throttled is not None and isinstance(_leaf_failure(exc), TimeoutError | _mcp_http.TimeoutException):
860
+ status = _mcp_http.HTTPStatusError(
811
861
  f"429 {throttled.reason_phrase}", request=throttled.request, response=throttled
812
862
  )
813
863
  status.__cause__ = exc
@@ -903,7 +953,7 @@ def parse_tool_result(result: Any, name: str) -> JsonDict:
903
953
  non_text = [_plain_part(part) for part in result.content if not getattr(part, "text", "")]
904
954
 
905
955
  parsed: JsonDict = {}
906
- structured = getattr(result, "structuredContent", None)
956
+ structured = _mcp_field(result, "structured_content", "structuredContent")
907
957
  if payload:
908
958
  try:
909
959
  # NaN and Infinity are not JSON; json.loads accepts them, JSON.parse does not,
@@ -918,7 +968,7 @@ def parse_tool_result(result: Any, name: str) -> JsonDict:
918
968
  # not write into the caller's result.
919
969
  parsed = dict(structured)
920
970
 
921
- if getattr(result, "isError", False):
971
+ if _mcp_field(result, "is_error", "isError", False):
922
972
  # The transport succeeded, so there is no HTTP status here — but the payload
923
973
  # carries the real one, and a caller cannot branch on 0.
924
974
  detail = payload or json.dumps(parsed, ensure_ascii=False, separators=(",", ":"), default=str)
@@ -936,45 +986,20 @@ def call_mcp_tool(
936
986
 
937
987
  ``arguments`` are sent exactly as given; the server maps them onto the action.
938
988
  """
939
- from mcp import types as mcp_types # ty: ignore[unresolved-import]
940
- from mcp.client.session import ClientSession # ty: ignore[unresolved-import]
941
-
942
- throttle = _Throttle()
989
+ from mcp import types as mcp_types
990
+
991
+ async def _call(session: Any) -> JsonDict:
992
+ # send_request rather than call_tool: call_tool validates structuredContent
993
+ # against the tool's output schema, and on a fresh session that means a
994
+ # tools/list first — relisting the whole catalog on every call, which the
995
+ # Node SDK never does. The result is parsed below either way.
996
+ request = mcp_types.CallToolRequest(
997
+ params=mcp_types.CallToolRequestParams(name=name, arguments=arguments)
998
+ )
999
+ result = await session.send_request(request, mcp_types.CallToolResult)
1000
+ return parse_tool_result(result, name)
943
1001
 
944
- async def _call() -> JsonDict:
945
- with anyio.fail_after(timeout):
946
- return await _call_within_deadline()
947
-
948
- async def _call_within_deadline() -> JsonDict:
949
- async with _mcp_transport(endpoint, headers, timeout, throttle) as (
950
- read_stream,
951
- write_stream,
952
- _,
953
- ):
954
- session = ClientSession(
955
- read_stream,
956
- write_stream,
957
- client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION),
958
- )
959
- async with session:
960
- await session.initialize()
961
- # send_request rather than call_tool: call_tool validates structuredContent
962
- # against the tool's output schema, and on a fresh session that means a
963
- # tools/list first — relisting the whole catalog on every call, which the
964
- # Node SDK never does. The result is parsed below either way.
965
- request = mcp_types.ClientRequest(
966
- mcp_types.CallToolRequest(
967
- params=mcp_types.CallToolRequestParams(name=name, arguments=arguments),
968
- )
969
- )
970
- result = await session.send_request(request, mcp_types.CallToolResult)
971
- return parse_tool_result(result, name)
972
-
973
- try:
974
- return run_async(_call())
975
- except Exception as exc:
976
- # Not BaseException, as in fetch_mcp_tools: KeyboardInterrupt and SystemExit propagate.
977
- _raise_mcp_failure(exc, endpoint, timeout, throttle)
1002
+ return _run_mcp_session(endpoint, headers, timeout, _call)
978
1003
 
979
1004
 
980
1005
  def is_end_user_refusal(exc: BaseException, account_id: str) -> bool:
@@ -1001,6 +1026,21 @@ def is_end_user_refusal(exc: BaseException, account_id: str) -> bool:
1001
1026
  return message.rstrip().rsplit(" ", 1)[-1].strip("\"'") == account_id
1002
1027
 
1003
1028
 
1029
+ def retry_for_end_user(
1030
+ call: Callable[[], T], accounts: Iterable[str], look_up: Callable[[str, Exception], bool] | None
1031
+ ) -> T:
1032
+ """``call()``, made once more if the API refused it for want of the end user of one of
1033
+ ``accounts`` (those it was sent without one for) and ``look_up`` then finds that end user.
1034
+ """
1035
+ try:
1036
+ return call()
1037
+ except StackOneAPIError as exc:
1038
+ refused = next((account for account in accounts if is_end_user_refusal(exc, account)), None)
1039
+ if refused is None or look_up is None or not look_up(refused, exc):
1040
+ raise
1041
+ return call()
1042
+
1043
+
1004
1044
  def _strip_internal_keys(schema: Any) -> Any:
1005
1045
  """Recursively drop the SDK's internal markers from a property schema.
1006
1046
 
@@ -1298,7 +1338,7 @@ class StackOneTool(BaseModel):
1298
1338
  class StackOneLangChainTool(BaseTool):
1299
1339
  name: str = parent_tool.name
1300
1340
  description: str = parent_tool.description
1301
- args_schema: dict[str, Any] = args_json_schema # ty: ignore[invalid-assignment]
1341
+ args_schema: dict[str, Any] = args_json_schema # ty: ignore[incompatible-mutable-override]
1302
1342
 
1303
1343
  def _run(self, **kwargs: Any) -> Any:
1304
1344
  # Drop unsupplied optionals. pydantic materialises every optional field
@@ -1321,8 +1361,8 @@ class StackOneTool(BaseModel):
1321
1361
  # handing the error back.
1322
1362
  body = getattr(exc, "response_body", None)
1323
1363
  failure = ToolException(f"{exc}: {body}" if body else str(exc))
1324
- failure.status_code = getattr(exc, "status_code", None) # type: ignore[attr-defined]
1325
- failure.response_body = getattr(exc, "response_body", None) # type: ignore[attr-defined]
1364
+ failure.status_code = getattr(exc, "status_code", None) # ty: ignore[missing-attribute]
1365
+ failure.response_body = getattr(exc, "response_body", None) # ty: ignore[missing-attribute]
1326
1366
  raise failure from exc
1327
1367
 
1328
1368
  return StackOneLangChainTool()
@@ -1496,20 +1536,10 @@ class StackOneMcpTool(StackOneTool):
1496
1536
  )
1497
1537
 
1498
1538
  account_id = self._account_id
1499
- without_end_user = account_id is not None and self._recorded_end_user_id() is None
1500
- try:
1501
- return call()
1502
- except StackOneAPIError as exc:
1503
- # Sent with no recorded end user and refused for want of one: the account is
1504
- # non-shared and its end user can be looked up. Retried once, with it.
1505
- if not (
1506
- without_end_user
1507
- and account_id is not None
1508
- and self._look_up_end_user is not None
1509
- and self._look_up_end_user(account_id, exc)
1510
- ):
1511
- raise
1512
- return call()
1539
+ without_end_user = (
1540
+ [account_id] if account_id is not None and self._recorded_end_user_id() is None else []
1541
+ )
1542
+ return retry_for_end_user(call, without_end_user, self._look_up_end_user)
1513
1543
 
1514
1544
 
1515
1545
  @dataclass(frozen=True)
@@ -1674,7 +1704,6 @@ class Tools:
1674
1704
  name would not find. OpenAI was sent two functions of one name, and LangChain and
1675
1705
  Pydantic AI each kept whichever their own lookup happened to find.
1676
1706
  """
1677
- self._warn_duplicate_names()
1678
1707
  return list(self._tool_map.values())
1679
1708
 
1680
1709
  def __getitem__(self, index: int) -> StackOneTool:
@@ -30,11 +30,12 @@ from stackone_ai.tools import (
30
30
  _js_number,
31
31
  _json_text,
32
32
  _json_type,
33
+ _ssl_context,
33
34
  build_request_headers,
34
35
  fetch_mcp_tools,
35
- is_end_user_refusal,
36
36
  is_rate_limited,
37
37
  is_sdk_owned_header,
38
+ retry_for_end_user,
38
39
  )
39
40
  from stackone_ai.types import (
40
41
  DEFAULT_BASE_URL,
@@ -52,7 +53,6 @@ from stackone_ai.types import (
52
53
  ToolMode,
53
54
  ToolParameters,
54
55
  ToolsetConfigError,
55
- ToolsetError,
56
56
  ToolsetLoadError,
57
57
  )
58
58
 
@@ -231,7 +231,6 @@ class StackOneToolSet:
231
231
  self._account_ids: list[str] = self._validate_account_ids(
232
232
  execute.get("account_ids") if execute else None
233
233
  )
234
- self._execute_config: ExecuteToolsConfig | None = execute
235
234
  execute_timeout = execute.get("timeout") if execute else None
236
235
  self._timeout: float = (
237
236
  timeout if timeout is not None else (execute_timeout if execute_timeout is not None else 60.0)
@@ -311,7 +310,7 @@ class StackOneToolSet:
311
310
  account_ids: list[str] | None = None,
312
311
  providers: list[str] | None = None,
313
312
  actions: list[str] | None = None,
314
- mode: Any = _UNSET,
313
+ mode: ToolMode | None = _UNSET, # ty: ignore[invalid-parameter-default]
315
314
  ) -> Tools:
316
315
  """Fetch tools with optional filtering by account IDs, providers, and actions
317
316
 
@@ -326,6 +325,9 @@ class StackOneToolSet:
326
325
  needed. No matching account means no tools.
327
326
  actions: Optional list of action patterns with glob support
328
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``.
329
331
 
330
332
  Returns:
331
333
  Collection of tools matching the filter criteria
@@ -398,7 +400,7 @@ class StackOneToolSet:
398
400
 
399
401
  return Tools(all_tools)
400
402
 
401
- except (ToolsetError, StackOneError):
403
+ except StackOneError:
402
404
  # StackOneAPIError carries the HTTP status. Re-wrapping it below would throw
403
405
  # that away, so a caller could not tell a 401 from a 429.
404
406
  raise
@@ -497,15 +499,12 @@ class StackOneToolSet:
497
499
  def _fetch_for_account(
498
500
  account: str | None,
499
501
  ) -> list[_Listing]:
500
- without_end_user = account is not None and self._end_user_id(account) is None
501
- try:
502
- listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout)
503
- except StackOneAPIError as exc:
504
- # Refused for want of an end user it was sent without: look it up, and retry
505
- # once with it.
506
- if not (without_end_user and account is not None and self._look_up_end_user(account, exc)):
507
- raise
508
- listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout)
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
+ )
509
508
  return [(tool_def, account, endpoint) for tool_def in listed]
510
509
 
511
510
  def _store(catalog: _Catalog) -> None:
@@ -582,13 +581,7 @@ class StackOneToolSet:
582
581
  return [(tool_def, None, endpoint) for tool_def in listed]
583
582
 
584
583
  without_end_user = [account for account in account_scope if self._end_user_id(account) is None]
585
- try:
586
- listings = _list()
587
- except StackOneAPIError as exc:
588
- refused = next((a for a in without_end_user if is_end_user_refusal(exc, a)), None)
589
- if refused is None or not self._look_up_end_user(refused, exc):
590
- raise
591
- listings = _list()
584
+ listings = retry_for_end_user(_list, without_end_user, self._look_up_end_user)
592
585
 
593
586
  with self._cache_lock:
594
587
  if generation == self._cache_generation:
@@ -936,7 +929,9 @@ class StackOneToolSet:
936
929
  def _request_accounts(self, sequence: int) -> list[JsonDict]:
937
930
  url = f"{self.base_url.rstrip('/')}/accounts"
938
931
  try:
939
- with RateLimitRetryingClient(timeout=self._timeout, retry_within=self._timeout) as client:
932
+ with RateLimitRetryingClient(
933
+ timeout=self._timeout, retry_within=self._timeout, verify=_ssl_context()
934
+ ) as client:
940
935
  response = client.get(
941
936
  url,
942
937
  headers=build_request_headers(api_key=self.api_key, extra_headers=self._headers),
@@ -1015,13 +1010,10 @@ class StackOneToolSet:
1015
1010
  """Given the API's refusal of an account's request for want of its end user, list the
1016
1011
  accounts and say whether that one now has an end user recorded to retry with.
1017
1012
 
1018
- Only the API's 400 naming this account counts. A GET /accounts already in flight is
1019
- joined rather than another made. If it fails, the refusal is raised with that failure
1020
- as its cause: a key without the scope to list accounts would otherwise be told only
1021
- that the header does not match.
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.
1022
1016
  """
1023
- if not is_end_user_refusal(refusal, account_id):
1024
- return False
1025
1017
  try:
1026
1018
  self._join_accounts_listing()
1027
1019
  except Exception as exc:
@@ -1232,6 +1224,7 @@ class StackOneToolSet:
1232
1224
  normalized: dict[str, Any] = {}
1233
1225
 
1234
1226
  for name, details in properties.items():
1227
+ prop: dict[str, Any]
1235
1228
  if isinstance(details, dict):
1236
1229
  prop = copy.deepcopy(details)
1237
1230
  else:
File without changes
File without changes