From 41a89657c1d72318d965b3f62e68aebdcbe8e647 Mon Sep 17 00:00:00 2001 From: S2D2 Date: Tue, 10 Nov 2026 21:05:54 +0000 Subject: [PATCH 1/3] perf: share one SSL context across MCP calls Every MCP exchange built a new httpx.AsyncClient, and each one built its own SSL context, loading the whole CA bundle: about 7ms per tool call, listing or search. One context built on first use is shared instead. httpx builds it the same way (create_ssl_context with trust_env), so SSL_CERT_FILE and SSL_CERT_DIR are still honoured, read once rather than per call. Against the local MCP mock, the median tool.execute() drops from about 20ms to about 12ms. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- stackone_ai/tools.py | 9 +++++++++ tests/test_tool_calling.py | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index 486b6aa..ee053bc 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -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 @@ -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, about 7ms a call.""" + return httpx.create_ssl_context() + + @asynccontextmanager async def _mcp_transport( endpoint: str, headers: dict[str, str], timeout: float, throttle: _Throttle | None = None @@ -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: diff --git a/tests/test_tool_calling.py b/tests/test_tool_calling.py index f25396d..34efb17 100644 --- a/tests/test_tool_calling.py +++ b/tests/test_tool_calling.py @@ -357,3 +357,27 @@ 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): + """Building a context loads the CA bundle, which cost every MCP call about 7ms.""" + import ssl + + from stackone_ai.toolset import StackOneToolSet + + 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) + + toolset = StackOneToolSet(api_key="test-key", base_url=mcp_mock_server, account_id="default") + tool = toolset.fetch_tools()[0] + tool.execute({}) + tool.execute({}) + + # None if an earlier call built it, one if these did; on main it was one per call. + assert len(loads) <= 1 From 96d729d0fe6d7b414577654200318fd537ddb40a Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 00:35:32 +0000 Subject: [PATCH 2/3] test: assert the shared SSL context exactly, drop a machine-specific figure The test now clears the cache and requires one CA-bundle load for a listing and two calls, so it fails if the shared context is not used (it also passed with zero loads before). The docstring no longer quotes a timing that varies by machine. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- stackone_ai/tools.py | 2 +- tests/test_tool_calling.py | 15 ++++++--------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index ee053bc..667e17c 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -633,7 +633,7 @@ def is_rate_limited(exc: BaseException) -> bool: @functools.cache def _ssl_context() -> ssl.SSLContext: - """One SSL context for every MCP client: building one loads the CA bundle, about 7ms a call.""" + """One SSL context for every MCP client: building one loads the CA bundle each time.""" return httpx.create_ssl_context() diff --git a/tests/test_tool_calling.py b/tests/test_tool_calling.py index 34efb17..85de459 100644 --- a/tests/test_tool_calling.py +++ b/tests/test_tool_calling.py @@ -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 @@ -360,11 +361,7 @@ def test_an_argument_error_is_a_stackone_error_and_a_value_error(call, seen): def test_calls_share_one_ssl_context(mcp_mock_server, monkeypatch): - """Building a context loads the CA bundle, which cost every MCP call about 7ms.""" - import ssl - - from stackone_ai.toolset import StackOneToolSet - + """Building a context loads the CA bundle, so listing and calling must build it once between them.""" loads: list[object] = [] load_verify_locations = ssl.SSLContext.load_verify_locations @@ -373,11 +370,11 @@ def counting(self, *args, **kwargs): return load_verify_locations(self, *args, **kwargs) monkeypatch.setattr(ssl.SSLContext, "load_verify_locations", counting) + _ssl_context.cache_clear() toolset = StackOneToolSet(api_key="test-key", base_url=mcp_mock_server, account_id="default") tool = toolset.fetch_tools()[0] tool.execute({}) tool.execute({}) - # None if an earlier call built it, one if these did; on main it was one per call. - assert len(loads) <= 1 + assert len(loads) == 1 From fb4976c94c6d5174ccc2be8872d59d3705bdf296 Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 00:42:25 +0000 Subject: [PATCH 3/3] perf: share the SSL context with the accounts request GET /accounts built its own SSL context, so discovery still loaded the CA bundle a second time. The test now discovers accounts too and clears the cached context when it finishes, so later tests start fresh. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- stackone_ai/toolset.py | 5 ++++- tests/test_tool_calling.py | 7 ++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 0780659..8330db7 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -30,6 +30,7 @@ _js_number, _json_text, _json_type, + _ssl_context, build_request_headers, fetch_mcp_tools, is_end_user_refusal, @@ -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), diff --git a/tests/test_tool_calling.py b/tests/test_tool_calling.py index 85de459..18c4aee 100644 --- a/tests/test_tool_calling.py +++ b/tests/test_tool_calling.py @@ -360,8 +360,8 @@ def test_an_argument_error_is_a_stackone_error_and_a_value_error(call, seen): assert seen == {} -def test_calls_share_one_ssl_context(mcp_mock_server, monkeypatch): - """Building a context loads the CA bundle, so listing and calling must build it once between them.""" +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 @@ -371,8 +371,9 @@ def counting(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, account_id="default") + toolset = StackOneToolSet(api_key="test-key", base_url=mcp_mock_server) tool = toolset.fetch_tools()[0] tool.execute({}) tool.execute({})