Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from agent_framework import ChatAgent, ChatMessage, ChatMessageStoreProtocol, MCPStreamableHTTPTool
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.openai import OpenAIChatClient
import httpx

from microsoft_agents.hosting.core import Authorization, TurnContext

Expand All @@ -24,6 +25,10 @@
)


# Default timeout for MCP server HTTP requests (in seconds)
MCP_HTTP_CLIENT_TIMEOUT_SECONDS = 90.0


class McpToolRegistrationService:
"""
Provides MCP tool registration services for Agent Framework agents.
Expand All @@ -46,6 +51,7 @@ def __init__(self, logger: Optional[logging.Logger] = None):
logger=self._logger
)
self._connected_servers = []
self._http_clients: List[httpx.AsyncClient] = []

async def add_tool_servers_to_agent(
self,
Expand Down Expand Up @@ -114,11 +120,17 @@ async def add_tool_servers_to_agent(
self._orchestrator_name
)

# Create and configure MCPStreamableHTTPTool
# Create httpx client with auth headers configured
http_client = httpx.AsyncClient(
headers=headers, timeout=MCP_HTTP_CLIENT_TIMEOUT_SECONDS
)
self._http_clients.append(http_client)

# Create and configure MCPStreamableHTTPTool with http_client
mcp_tools = MCPStreamableHTTPTool(
name=server_name,
url=config.url,
headers=headers,
http_client=http_client,
description=f"MCP tools from {server_name}",
)

Expand Down Expand Up @@ -339,12 +351,21 @@ async def send_chat_history_from_store(
async def cleanup(self):
"""Clean up any resources used by the service."""
try:
# Close MCP server connections
for plugin in self._connected_servers:
try:
if hasattr(plugin, "close"):
await plugin.close()
except Exception as cleanup_ex:
self._logger.debug(f"Error during cleanup: {cleanup_ex}")
self._logger.debug(f"Error during plugin cleanup: {cleanup_ex}")
self._connected_servers.clear()

# Close httpx clients to prevent connection/file descriptor leaks
for http_client in self._http_clients:
try:
await http_client.aclose()
except Exception as client_ex:
self._logger.debug(f"Error closing http client: {client_ex}")
self._http_clients.clear()
except Exception as ex:
self._logger.debug(f"Error during service cleanup: {ex}")
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies = [
"agent-framework-azure-ai >= 1.0.0b251114",
"azure-identity >= 1.12.0",
"typing-extensions >= 4.0.0",
"httpx >= 0.27.0",
]

[project.urls]
Expand Down
Loading