fix(capabilities): build the business client off the MCP event loop (#8281)

* fix(capabilities): build the business client off the MCP event loop

`BusinessClient._request` constructed `httpx.AsyncClient()` inline whenever no
client was injected, which is every production call: `build_server` mints a
client per tool invocation for the bundled dingtalk, wecom and HubSpot tools.
`httpx.AsyncClient()` runs `ssl.create_default_context(cafile=certifi...)` in
its constructor, so each notification and CRM request loaded the CA bundle on
the event loop it was serving.

Construct it through `asyncio.to_thread`, the rule the community fetch clients
already follow (crawl4ai, browserless, groundroute), and add the per-client
`tests/blocking_io` regression the family carries so the inline construction
cannot come back unnoticed.

* Enhance cancellation safety for HTTP client in business.py

Refactor HTTP client construction for cancellation safety and ensure proper closure.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Heo Hao 2026-11-17 07:46:01 +08:00 committed by GitHub
parent 4167e2b551
commit 3d5e360139
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 65 additions and 1 deletions

View File

@ -5,6 +5,7 @@ stay in MCP process environment, never in tool arguments or discovery results.
"""
import argparse
import asyncio
import base64
import hashlib
import hmac
@ -81,8 +82,18 @@ class BusinessClient:
if self.http is not None:
return await perform(self.http)
async with httpx.AsyncClient() as client:
# Client construction loads the TLS trust store synchronously; keep it off
# the MCP server's event loop, like the community fetch clients.
#
# Cancellation-safety: if this coroutine is cancelled while awaiting
# `to_thread(...)`, the background thread may still construct the client,
# but we would never enter an `async with` block to close it. Shield the
# construction and always close the client in a finally.
client = await asyncio.shield(asyncio.to_thread(httpx.AsyncClient))
try:
return await perform(client)
finally:
await asyncio.shield(client.aclose())
async def send_message(self, content: str, message_type: Literal["text", "markdown"] = "text", title: str = "Notification") -> dict[str, Any]:
if self.provider not in ("dingtalk", "wecom"):

View File

@ -0,0 +1,53 @@
"""The bundled business tools must load HTTPX TLS trust off the MCP event loop."""
import ssl
import threading
import httpx
import pytest
from deerflow.capabilities.business import BusinessClient
DINGTALK = {"access_token": "token", "sign_secret": "secret"}
HUBSPOT = {"access_token": "token"}
@pytest.mark.asyncio
@pytest.mark.parametrize(
"provider,credentials,call,expected_path",
[
("dingtalk", DINGTALK, "send_message", "/robot/send"),
("hubspot", HUBSPOT, "get_companies", "/crm/v3/objects/companies"),
],
)
async def test_business_client_tls_setup_runs_off_loop(provider, credentials, call, expected_path, monkeypatch):
loop_thread = threading.get_ident()
original_context = ssl.create_default_context
contexts = []
clients = []
def create_context(*args, **kwargs):
assert threading.get_ident() != loop_thread, "TLS trust loading blocks the MCP event loop"
context = original_context(*args, **kwargs)
contexts.append(context)
return context
async def send(self, request, **kwargs):
assert threading.get_ident() == loop_thread
clients.append(self)
assert request.url.path == expected_path
payload = {"errcode": 0, "errmsg": "ok"} if provider == "dingtalk" else {"results": []}
return httpx.Response(200, request=request, json=payload)
monkeypatch.setattr(ssl, "create_default_context", create_context)
monkeypatch.setattr(httpx.AsyncClient, "send", send)
client = BusinessClient(provider, credentials)
if call == "send_message":
assert await client.send_message("synthetic notification") == {"sent": True}
else:
assert (await client.get_companies())["companies"] == []
assert len(contexts) == 1
assert len(clients) == 1
assert clients[0].is_closed