microsoft-agents-a365-tooling-extensions-agentframework 0.2.0.dev5__tar.gz → 0.2.1.dev2__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.
Files changed (14) hide show
  1. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/PKG-INFO +1 -1
  2. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365/tooling/extensions/agentframework/__init__.py +2 -1
  3. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365/tooling/extensions/agentframework/services/__init__.py +2 -1
  4. microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2/microsoft_agents_a365/tooling/extensions/agentframework/services/mcp_tool_registration_service.py +350 -0
  5. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365_tooling_extensions_agentframework.egg-info/PKG-INFO +1 -1
  6. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365_tooling_extensions_agentframework.egg-info/top_level.txt +1 -0
  7. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/pyproject.toml +4 -0
  8. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/setup.py +1 -1
  9. microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5/microsoft_agents_a365/tooling/extensions/agentframework/services/mcp_tool_registration_service.py +0 -158
  10. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/README.md +0 -0
  11. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365_tooling_extensions_agentframework.egg-info/SOURCES.txt +0 -0
  12. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365_tooling_extensions_agentframework.egg-info/dependency_links.txt +0 -0
  13. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/microsoft_agents_a365_tooling_extensions_agentframework.egg-info/requires.txt +0 -0
  14. {microsoft_agents_a365_tooling_extensions_agentframework-0.2.0.dev5 → microsoft_agents_a365_tooling_extensions_agentframework-0.2.1.dev2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: microsoft-agents-a365-tooling-extensions-agentframework
3
- Version: 0.2.0.dev5
3
+ Version: 0.2.1.dev2
4
4
  Summary: Agent Framework integration tools for Agent 365 AI agent tooling
5
5
  Author-email: Microsoft <support@microsoft.com>
6
6
  License: MIT
@@ -1,4 +1,5 @@
1
- # Copyright (c) Microsoft. All rights reserved.
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
2
3
 
3
4
  """
4
5
  Agent 365 Tooling Agent Framework Extensions
@@ -1,4 +1,5 @@
1
- # Copyright (c) Microsoft. All rights reserved.
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
2
3
 
3
4
  """
4
5
  Services module for Agent Framework tooling.
@@ -0,0 +1,350 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ import logging
5
+ import uuid
6
+ from datetime import datetime, timezone
7
+ from typing import Any, List, Optional, Sequence, Union
8
+
9
+ from agent_framework import ChatAgent, ChatMessage, ChatMessageStoreProtocol, MCPStreamableHTTPTool
10
+ from agent_framework.azure import AzureOpenAIChatClient
11
+ from agent_framework.openai import OpenAIChatClient
12
+
13
+ from microsoft_agents.hosting.core import Authorization, TurnContext
14
+
15
+ from microsoft_agents_a365.runtime import OperationResult
16
+ from microsoft_agents_a365.runtime.utility import Utility
17
+ from microsoft_agents_a365.tooling.models import ChatHistoryMessage, ToolOptions
18
+ from microsoft_agents_a365.tooling.services.mcp_tool_server_configuration_service import (
19
+ McpToolServerConfigurationService,
20
+ )
21
+ from microsoft_agents_a365.tooling.utils.constants import Constants
22
+ from microsoft_agents_a365.tooling.utils.utility import (
23
+ get_mcp_platform_authentication_scope,
24
+ )
25
+
26
+
27
+ class McpToolRegistrationService:
28
+ """
29
+ Provides MCP tool registration services for Agent Framework agents.
30
+
31
+ This service handles registration and management of MCP (Model Context Protocol)
32
+ tool servers with Agent Framework agents.
33
+ """
34
+
35
+ _orchestrator_name: str = "AgentFramework"
36
+
37
+ def __init__(self, logger: Optional[logging.Logger] = None):
38
+ """
39
+ Initialize the MCP Tool Registration Service for Agent Framework.
40
+
41
+ Args:
42
+ logger: Logger instance for logging operations.
43
+ """
44
+ self._logger = logger or logging.getLogger(self.__class__.__name__)
45
+ self._mcp_server_configuration_service = McpToolServerConfigurationService(
46
+ logger=self._logger
47
+ )
48
+ self._connected_servers = []
49
+
50
+ async def add_tool_servers_to_agent(
51
+ self,
52
+ chat_client: Union[OpenAIChatClient, AzureOpenAIChatClient],
53
+ agent_instructions: str,
54
+ initial_tools: List[Any],
55
+ auth: Authorization,
56
+ auth_handler_name: str,
57
+ turn_context: TurnContext,
58
+ auth_token: Optional[str] = None,
59
+ ) -> Optional[ChatAgent]:
60
+ """
61
+ Add MCP tool servers to a chat agent (mirrors .NET implementation).
62
+
63
+ Args:
64
+ chat_client: The chat client instance (Union[OpenAIChatClient, AzureOpenAIChatClient])
65
+ agent_instructions: Instructions for the agent behavior
66
+ initial_tools: List of initial tools to add to the agent
67
+ auth: Authorization context for token exchange
68
+ auth_handler_name: Name of the authorization handler.
69
+ turn_context: Turn context for the operation
70
+ auth_token: Optional bearer token for authentication
71
+
72
+ Returns:
73
+ ChatAgent instance with MCP tools registered, or None if creation failed
74
+ """
75
+ try:
76
+ # Exchange token if not provided
77
+ if not auth_token:
78
+ scopes = get_mcp_platform_authentication_scope()
79
+ authToken = await auth.exchange_token(turn_context, scopes, auth_handler_name)
80
+ auth_token = authToken.token
81
+
82
+ agentic_app_id = Utility.resolve_agent_identity(turn_context, auth_token)
83
+
84
+ self._logger.info(f"Listing MCP tool servers for agent {agentic_app_id}")
85
+
86
+ options = ToolOptions(orchestrator_name=self._orchestrator_name)
87
+
88
+ # Get MCP server configurations
89
+ server_configs = await self._mcp_server_configuration_service.list_tool_servers(
90
+ agentic_app_id=agentic_app_id,
91
+ auth_token=auth_token,
92
+ options=options,
93
+ )
94
+
95
+ self._logger.info(f"Loaded {len(server_configs)} MCP server configurations")
96
+
97
+ # Create the agent with all tools (initial + MCP tools)
98
+ all_tools = list(initial_tools)
99
+
100
+ # Add servers as MCPStreamableHTTPTool instances
101
+ for config in server_configs:
102
+ # Use mcp_server_name if available (not None or empty), otherwise fall back to mcp_server_unique_name
103
+ server_name = config.mcp_server_name or config.mcp_server_unique_name
104
+
105
+ try:
106
+ # Prepare auth headers
107
+ headers = {}
108
+ if auth_token:
109
+ headers[Constants.Headers.AUTHORIZATION] = (
110
+ f"{Constants.Headers.BEARER_PREFIX} {auth_token}"
111
+ )
112
+
113
+ headers[Constants.Headers.USER_AGENT] = Utility.get_user_agent_header(
114
+ self._orchestrator_name
115
+ )
116
+
117
+ # Create and configure MCPStreamableHTTPTool
118
+ mcp_tools = MCPStreamableHTTPTool(
119
+ name=server_name,
120
+ url=config.url,
121
+ headers=headers,
122
+ description=f"MCP tools from {server_name}",
123
+ )
124
+
125
+ # Let Agent Framework handle the connection automatically
126
+ self._logger.info(f"Created MCP plugin for '{server_name}' at {config.url}")
127
+
128
+ all_tools.append(mcp_tools)
129
+ self._connected_servers.append(mcp_tools)
130
+
131
+ self._logger.info(f"Added MCP plugin '{server_name}' to agent tools")
132
+
133
+ except Exception as tool_ex:
134
+ self._logger.warning(
135
+ f"Failed to create MCP plugin for {server_name}: {tool_ex}"
136
+ )
137
+ continue
138
+
139
+ # Create the ChatAgent
140
+ agent = ChatAgent(
141
+ chat_client=chat_client,
142
+ tools=all_tools,
143
+ instructions=agent_instructions,
144
+ )
145
+
146
+ self._logger.info(f"Agent created with {len(all_tools)} total tools")
147
+ return agent
148
+
149
+ except Exception as ex:
150
+ self._logger.error(f"Failed to add tool servers to agent: {ex}")
151
+ raise
152
+
153
+ def _convert_chat_messages_to_history(
154
+ self,
155
+ chat_messages: Sequence[ChatMessage],
156
+ ) -> List[ChatHistoryMessage]:
157
+ """
158
+ Convert Agent Framework ChatMessage objects to ChatHistoryMessage format.
159
+
160
+ This internal helper method transforms Agent Framework's native ChatMessage
161
+ objects into the ChatHistoryMessage format expected by the MCP platform's
162
+ real-time threat protection endpoint.
163
+
164
+ Args:
165
+ chat_messages: Sequence of ChatMessage objects to convert.
166
+
167
+ Returns:
168
+ List of ChatHistoryMessage objects ready for the MCP platform.
169
+
170
+ Note:
171
+ - If message_id is None, a new UUID is generated
172
+ - Role is extracted via the .value property of the Role object
173
+ - Timestamp is set to current UTC time (ChatMessage has no timestamp)
174
+ - Messages with empty or whitespace-only content are filtered out and
175
+ logged at WARNING level. This is because ChatHistoryMessage requires
176
+ non-empty content for validation. The filtered messages will not be
177
+ sent to the MCP platform.
178
+ """
179
+ history_messages: List[ChatHistoryMessage] = []
180
+ current_time = datetime.now(timezone.utc)
181
+
182
+ for msg in chat_messages:
183
+ message_id = msg.message_id if msg.message_id is not None else str(uuid.uuid4())
184
+ if msg.role is None:
185
+ self._logger.warning(
186
+ "Skipping message %s with missing role during conversion", message_id
187
+ )
188
+ continue
189
+ # Defensive handling: use .value if role is an enum, otherwise convert to string
190
+ role = msg.role.value if hasattr(msg.role, "value") else str(msg.role)
191
+ content = msg.text if msg.text is not None else ""
192
+
193
+ # Skip messages with empty content as ChatHistoryMessage validates non-empty content
194
+ if not content.strip():
195
+ self._logger.warning(
196
+ "Skipping message %s with empty content during conversion", message_id
197
+ )
198
+ continue
199
+
200
+ history_message = ChatHistoryMessage(
201
+ id=message_id,
202
+ role=role,
203
+ content=content,
204
+ timestamp=current_time,
205
+ )
206
+ history_messages.append(history_message)
207
+
208
+ self._logger.debug(
209
+ "Converted message %s with role '%s' to ChatHistoryMessage", message_id, role
210
+ )
211
+
212
+ return history_messages
213
+
214
+ async def send_chat_history_messages(
215
+ self,
216
+ chat_messages: Sequence[ChatMessage],
217
+ turn_context: TurnContext,
218
+ tool_options: Optional[ToolOptions] = None,
219
+ ) -> OperationResult:
220
+ """
221
+ Send chat history messages to the MCP platform for real-time threat protection.
222
+
223
+ This is the primary implementation method that handles message conversion
224
+ and delegation to the core tooling service.
225
+
226
+ Args:
227
+ chat_messages: Sequence of Agent Framework ChatMessage objects to send.
228
+ Can be empty - the request will still be sent to register
229
+ the user message from turn_context.activity.text.
230
+ turn_context: TurnContext from the Agents SDK containing conversation info.
231
+ tool_options: Optional configuration for the request. Defaults to
232
+ AgentFramework-specific options if not provided.
233
+
234
+ Returns:
235
+ OperationResult indicating success or failure of the operation.
236
+
237
+ Raises:
238
+ ValueError: If chat_messages or turn_context is None.
239
+
240
+ Note:
241
+ Even if chat_messages is empty or all messages are filtered during
242
+ conversion, the request will still be sent to the MCP platform. This
243
+ ensures the user message from turn_context.activity.text is registered
244
+ correctly for real-time threat protection.
245
+
246
+ Example:
247
+ >>> service = McpToolRegistrationService()
248
+ >>> messages = [ChatMessage(role=Role.USER, text="Hello")]
249
+ >>> result = await service.send_chat_history_messages(messages, turn_context)
250
+ >>> if result.succeeded:
251
+ ... print("Chat history sent successfully")
252
+ """
253
+ # Input validation
254
+ if chat_messages is None:
255
+ raise ValueError("chat_messages cannot be None")
256
+
257
+ if turn_context is None:
258
+ raise ValueError("turn_context cannot be None")
259
+
260
+ self._logger.info(f"Send chat history initiated with {len(chat_messages)} messages")
261
+
262
+ # Use default options if not provided
263
+ if tool_options is None:
264
+ tool_options = ToolOptions(orchestrator_name=self._orchestrator_name)
265
+
266
+ # Convert messages to ChatHistoryMessage format
267
+ history_messages = self._convert_chat_messages_to_history(chat_messages)
268
+
269
+ # Call core service even with empty history_messages to register
270
+ # the user message from turn_context.activity.text in the MCP platform.
271
+ if len(history_messages) == 0:
272
+ self._logger.info(
273
+ "Empty history messages (either no input or all filtered), "
274
+ "still sending to register user message"
275
+ )
276
+
277
+ # Delegate to core service
278
+ result = await self._mcp_server_configuration_service.send_chat_history(
279
+ turn_context=turn_context,
280
+ chat_history_messages=history_messages,
281
+ options=tool_options,
282
+ )
283
+
284
+ if result.succeeded:
285
+ self._logger.info(
286
+ f"Chat history sent successfully with {len(history_messages)} messages"
287
+ )
288
+ else:
289
+ self._logger.error(f"Failed to send chat history: {result}")
290
+
291
+ return result
292
+
293
+ async def send_chat_history_from_store(
294
+ self,
295
+ chat_message_store: ChatMessageStoreProtocol,
296
+ turn_context: TurnContext,
297
+ tool_options: Optional[ToolOptions] = None,
298
+ ) -> OperationResult:
299
+ """
300
+ Send chat history from a ChatMessageStore to the MCP platform.
301
+
302
+ This is a convenience method that extracts messages from the store
303
+ and delegates to send_chat_history_messages().
304
+
305
+ Args:
306
+ chat_message_store: ChatMessageStore containing the conversation history.
307
+ turn_context: TurnContext from the Agents SDK containing conversation info.
308
+ tool_options: Optional configuration for the request.
309
+
310
+ Returns:
311
+ OperationResult indicating success or failure of the operation.
312
+
313
+ Raises:
314
+ ValueError: If chat_message_store or turn_context is None.
315
+
316
+ Example:
317
+ >>> service = McpToolRegistrationService()
318
+ >>> result = await service.send_chat_history_from_store(
319
+ ... thread.chat_message_store, turn_context
320
+ ... )
321
+ """
322
+ # Input validation
323
+ if chat_message_store is None:
324
+ raise ValueError("chat_message_store cannot be None")
325
+
326
+ if turn_context is None:
327
+ raise ValueError("turn_context cannot be None")
328
+
329
+ # Extract messages from the store
330
+ messages = await chat_message_store.list_messages()
331
+
332
+ # Delegate to the primary implementation
333
+ return await self.send_chat_history_messages(
334
+ chat_messages=messages,
335
+ turn_context=turn_context,
336
+ tool_options=tool_options,
337
+ )
338
+
339
+ async def cleanup(self):
340
+ """Clean up any resources used by the service."""
341
+ try:
342
+ for plugin in self._connected_servers:
343
+ try:
344
+ if hasattr(plugin, "close"):
345
+ await plugin.close()
346
+ except Exception as cleanup_ex:
347
+ self._logger.debug(f"Error during cleanup: {cleanup_ex}")
348
+ self._connected_servers.clear()
349
+ except Exception as ex:
350
+ self._logger.debug(f"Error during service cleanup: {ex}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: microsoft-agents-a365-tooling-extensions-agentframework
3
- Version: 0.2.0.dev5
3
+ Version: 0.2.1.dev2
4
4
  Summary: Agent Framework integration tools for Agent 365 AI agent tooling
5
5
  Author-email: Microsoft <support@microsoft.com>
6
6
  License: MIT
@@ -67,6 +67,10 @@ target-version = ['py311']
67
67
  line-length = 100
68
68
  target-version = "py311"
69
69
 
70
+ [tool.ruff.lint.flake8-copyright]
71
+ notice-rgx = "# Copyright \\(c\\) Microsoft Corporation\\.\\r?\\n# Licensed under the MIT License\\."
72
+ min-file-size = 1
73
+
70
74
  [tool.mypy]
71
75
  python_version = "3.11"
72
76
  strict = true
@@ -13,7 +13,7 @@ package_version = environ.get("AGENT365_PYTHON_SDK_PACKAGE_VERSION", "0.0.0")
13
13
  helper_path = Path(__file__).parent.parent.parent / "versioning" / "helper"
14
14
  sys.path.insert(0, str(helper_path))
15
15
 
16
- from setup_utils import get_dynamic_dependencies
16
+ from setup_utils import get_dynamic_dependencies # noqa: E402
17
17
 
18
18
  # Use minimum version strategy:
19
19
  # - Internal packages get: >= current_base_version (e.g., >= 0.1.0)
@@ -1,158 +0,0 @@
1
- # Copyright (c) Microsoft. All rights reserved.
2
-
3
- from typing import Optional, List, Any, Union
4
- import logging
5
-
6
- from agent_framework import ChatAgent, MCPStreamableHTTPTool
7
- from agent_framework.azure import AzureOpenAIChatClient
8
- from agent_framework.openai import OpenAIChatClient
9
-
10
- from microsoft_agents.hosting.core import Authorization, TurnContext
11
-
12
- from microsoft_agents_a365.runtime.utility import Utility
13
- from microsoft_agents_a365.tooling.services.mcp_tool_server_configuration_service import (
14
- McpToolServerConfigurationService,
15
- )
16
- from microsoft_agents_a365.tooling.utils.constants import Constants
17
-
18
- from microsoft_agents_a365.tooling.utils.utility import (
19
- get_mcp_platform_authentication_scope,
20
- )
21
-
22
-
23
- class McpToolRegistrationService:
24
- """
25
- Provides MCP tool registration services for Agent Framework agents.
26
-
27
- This service handles registration and management of MCP (Model Context Protocol)
28
- tool servers with Agent Framework agents.
29
- """
30
-
31
- def __init__(self, logger: Optional[logging.Logger] = None):
32
- """
33
- Initialize the MCP Tool Registration Service for Agent Framework.
34
-
35
- Args:
36
- logger: Logger instance for logging operations.
37
- """
38
- self._logger = logger or logging.getLogger(self.__class__.__name__)
39
- self._mcp_server_configuration_service = McpToolServerConfigurationService(
40
- logger=self._logger
41
- )
42
- self._connected_servers = []
43
-
44
- async def add_tool_servers_to_agent(
45
- self,
46
- chat_client: Union[OpenAIChatClient, AzureOpenAIChatClient],
47
- agent_instructions: str,
48
- initial_tools: List[Any],
49
- auth: Authorization,
50
- auth_handler_name: str,
51
- turn_context: TurnContext,
52
- auth_token: Optional[str] = None,
53
- ) -> Optional[ChatAgent]:
54
- """
55
- Add MCP tool servers to a chat agent (mirrors .NET implementation).
56
-
57
- Args:
58
- chat_client: The chat client instance (Union[OpenAIChatClient, AzureOpenAIChatClient])
59
- agent_instructions: Instructions for the agent behavior
60
- initial_tools: List of initial tools to add to the agent
61
- auth: Authorization context for token exchange
62
- auth_handler_name: Name of the authorization handler.
63
- turn_context: Turn context for the operation
64
- auth_token: Optional bearer token for authentication
65
-
66
- Returns:
67
- ChatAgent instance with MCP tools registered, or None if creation failed
68
- """
69
- try:
70
- # Exchange token if not provided
71
- if not auth_token:
72
- scopes = get_mcp_platform_authentication_scope()
73
- authToken = await auth.exchange_token(turn_context, scopes, auth_handler_name)
74
- auth_token = authToken.token
75
-
76
- agentic_app_id = Utility.resolve_agent_identity(turn_context, auth_token)
77
-
78
- self._logger.info(f"Listing MCP tool servers for agent {agentic_app_id}")
79
-
80
- # Get MCP server configurations
81
- server_configs = await self._mcp_server_configuration_service.list_tool_servers(
82
- agentic_app_id=agentic_app_id,
83
- auth_token=auth_token,
84
- )
85
-
86
- self._logger.info(f"Loaded {len(server_configs)} MCP server configurations")
87
-
88
- # Create the agent with all tools (initial + MCP tools)
89
- all_tools = list(initial_tools)
90
-
91
- # Add servers as MCPStreamableHTTPTool instances
92
- for config in server_configs:
93
- try:
94
- server_url = getattr(config, "server_url", None) or getattr(
95
- config, "mcp_server_unique_name", None
96
- )
97
- if not server_url:
98
- self._logger.warning(f"MCP server config missing server_url: {config}")
99
- continue
100
-
101
- # Prepare auth headers
102
- headers = {}
103
- if auth_token:
104
- headers[Constants.Headers.AUTHORIZATION] = (
105
- f"{Constants.Headers.BEARER_PREFIX} {auth_token}"
106
- )
107
-
108
- server_name = getattr(config, "mcp_server_name", "Unknown")
109
-
110
- # Create and configure MCPStreamableHTTPTool
111
- mcp_tools = MCPStreamableHTTPTool(
112
- name=server_name,
113
- url=server_url,
114
- headers=headers,
115
- description=f"MCP tools from {server_name}",
116
- )
117
-
118
- # Let Agent Framework handle the connection automatically
119
- self._logger.info(f"Created MCP plugin for '{server_name}' at {server_url}")
120
-
121
- all_tools.append(mcp_tools)
122
- self._connected_servers.append(mcp_tools)
123
-
124
- self._logger.info(f"Added MCP plugin '{server_name}' to agent tools")
125
-
126
- except Exception as tool_ex:
127
- server_name = getattr(config, "mcp_server_name", "Unknown")
128
- self._logger.warning(
129
- f"Failed to create MCP plugin for {server_name}: {tool_ex}"
130
- )
131
- continue
132
-
133
- # Create the ChatAgent
134
- agent = ChatAgent(
135
- chat_client=chat_client,
136
- tools=all_tools,
137
- instructions=agent_instructions,
138
- )
139
-
140
- self._logger.info(f"Agent created with {len(all_tools)} total tools")
141
- return agent
142
-
143
- except Exception as ex:
144
- self._logger.error(f"Failed to add tool servers to agent: {ex}")
145
- raise
146
-
147
- async def cleanup(self):
148
- """Clean up any resources used by the service."""
149
- try:
150
- for plugin in self._connected_servers:
151
- try:
152
- if hasattr(plugin, "close"):
153
- await plugin.close()
154
- except Exception as cleanup_ex:
155
- self._logger.debug(f"Error during cleanup: {cleanup_ex}")
156
- self._connected_servers.clear()
157
- except Exception as ex:
158
- self._logger.debug(f"Error during service cleanup: {ex}")