Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions stackone_ai/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
import asyncio
import base64
import calendar
import functools
import json
import logging
import math
import random
import re
import ssl
import threading
import time
from collections import Counter
Expand Down Expand Up @@ -629,6 +631,12 @@ def is_rate_limited(exc: BaseException) -> bool:
return False


@functools.cache
def _ssl_context() -> ssl.SSLContext:
"""One SSL context for every MCP client: building one loads the CA bundle each time."""
return httpx.create_ssl_context()


@asynccontextmanager
async def _mcp_transport(
endpoint: str, headers: dict[str, str], timeout: float, throttle: _Throttle | None = None
Expand All @@ -651,6 +659,7 @@ async def _mcp_transport(
throttle=throttle,
headers=headers,
timeout=httpx.Timeout(timeout),
verify=_ssl_context(),
follow_redirects=True,
event_hooks={"response": [_buffer_error_body]},
) as client:
Expand Down
5 changes: 4 additions & 1 deletion stackone_ai/toolset.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
_js_number,
_json_text,
_json_type,
_ssl_context,
build_request_headers,
fetch_mcp_tools,
is_end_user_refusal,
Expand Down Expand Up @@ -936,7 +937,9 @@ def _settle_accounts(
def _request_accounts(self, sequence: int) -> list[JsonDict]:
url = f"{self.base_url.rstrip('/')}/accounts"
try:
with RateLimitRetryingClient(timeout=self._timeout, retry_within=self._timeout) as client:
with RateLimitRetryingClient(
timeout=self._timeout, retry_within=self._timeout, verify=_ssl_context()
) as client:
response = client.get(
url,
headers=build_request_headers(api_key=self.api_key, extra_headers=self._headers),
Expand Down
26 changes: 24 additions & 2 deletions tests/test_tool_calling.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Tests for tool calling functionality"""

import logging
import ssl
from typing import Any

import pytest

from stackone_ai import StackOneError, StackOneTool, ToolArgumentsError
from stackone_ai.tools import StackOneMcpTool, _header_text
from stackone_ai import StackOneError, StackOneTool, StackOneToolSet, ToolArgumentsError
from stackone_ai.tools import StackOneMcpTool, _header_text, _ssl_context
from stackone_ai.types import ExecuteConfig, ToolParameters


Expand Down Expand Up @@ -357,3 +358,24 @@ def test_an_argument_error_is_a_stackone_error_and_a_value_error(call, seen):
assert isinstance(excinfo.value, StackOneError)
assert isinstance(excinfo.value, ValueError)
assert seen == {}


def test_calls_share_one_ssl_context(mcp_mock_server, monkeypatch, request):
"""Building a context loads the CA bundle, so discovery, listing and calling build it once."""
loads: list[object] = []
load_verify_locations = ssl.SSLContext.load_verify_locations

def counting(self, *args, **kwargs):
loads.append(args)
return load_verify_locations(self, *args, **kwargs)

monkeypatch.setattr(ssl.SSLContext, "load_verify_locations", counting)
_ssl_context.cache_clear()
request.addfinalizer(_ssl_context.cache_clear)

toolset = StackOneToolSet(api_key="test-key", base_url=mcp_mock_server)
tool = toolset.fetch_tools()[0]
tool.execute({})
tool.execute({})

assert len(loads) == 1
Loading