universal-mcp-agents 0.1.22__py3-none-any.whl → 0.1.23__py3-none-any.whl

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.

Potentially problematic release.


This version of universal-mcp-agents might be problematic. Click here for more details.

@@ -1,22 +1,21 @@
1
1
  import asyncio
2
- import json
2
+ import base64
3
3
  from collections import defaultdict
4
+ from pathlib import Path
4
5
  from typing import Annotated, Any
5
6
 
6
7
  from langchain_core.tools import tool
7
- from loguru import logger
8
8
  from pydantic import Field
9
+ from universal_mcp.agentr.client import AgentrClient
9
10
  from universal_mcp.agentr.registry import AgentrRegistry
11
+ from universal_mcp.applications.markitdown.app import MarkitdownApp
10
12
  from universal_mcp.types import ToolFormat
11
13
 
12
-
13
- def enter_playbook_mode():
14
- """Call this function to enter playbook mode. Playbook mode is when the user wants to store a repeated task as a script with some inputs for the future."""
15
- return
14
+ from universal_mcp.agents.codeact0.prompts import build_tool_definitions
16
15
 
17
16
 
18
- def exit_playbook_mode():
19
- """Call this function to exit playbook mode. Playbook mode is when the user wants to store a repeated task as a script with some inputs for the future."""
17
+ def enter_agent_builder_mode():
18
+ """Call this function to enter agent builder mode. Agent builder mode is when the user wants to store a repeated task as a script with some inputs for the future."""
20
19
  return
21
20
 
22
21
 
@@ -26,189 +25,323 @@ def create_meta_tools(tool_registry: AgentrRegistry) -> dict[str, Any]:
26
25
  @tool
27
26
  async def search_functions(
28
27
  queries: Annotated[
29
- list[str] | str | None,
30
- Field(description="A single query or a list of queries to search for relevant functions"),
28
+ list[list[str]] | None,
29
+ Field(
30
+ description="A list of query lists. Each inner list contains one or more search terms that will be used together to find relevant tools."
31
+ ),
31
32
  ] = None,
32
- app_id: Annotated[
33
- str | None,
34
- Field(description="The ID or common name of a specific application to search within"),
33
+ app_ids: Annotated[
34
+ list[str] | None,
35
+ Field(description="The ID or list of IDs (common names) of specific applications to search within."),
35
36
  ] = None,
36
37
  ) -> str:
37
38
  """
38
- Searches for relevant functions across applications based on queries and/or a specific app.
39
- This function operates in three modes:
40
-
41
- 1. **Global Search (provide `queries` only):**
42
- - Use when the user wants to perform an action without specifying an application.
43
- - The system will search across all available functions.
44
- - Example: For "how can I create a presentation?", call with queries=["create presentation"].
45
-
46
- 2. **App Discovery (provide `app_id` only):**
47
- - Use when the user asks about the capabilities of a specific application.
48
- - The `app_id` can be the common name of the app (e.g., "Gmail", "Google Drive").
49
- - This will return all available functions for that application, up to a limit.
50
- - Example: For "what can you do with Gmail?", call with app_id="Gmail".
51
-
52
- 3. **Scoped Search (provide `queries` AND `app_id`):**
53
- - Use when the user wants to perform an action within a specific application.
54
- - This performs a targeted search only within the specified app's functions.
55
- - Example: For "how do I find an email in Gmail?", call with queries=["find email"], app_id="Gmail".
39
+ Searches for relevant functions based on queries and/or applications. This function
40
+ operates in three powerful modes with support for multi-query searches:
41
+
42
+ 1. **Global Search** (`queries` only as List[List[str]]):
43
+ - Searches all functions across all applications.
44
+ - Supports multiple independent searches in parallel.
45
+ - Each inner list represents a separate search query.
46
+
47
+ Examples:
48
+ - Single global search:
49
+ `search_functions(queries=[["create presentation"]])`
50
+
51
+ - Multiple independent global searches:
52
+ `search_functions(queries=[["send email"], ["schedule meeting"]])`
53
+
54
+ - Multi-term search for comprehensive results:
55
+ `search_functions(queries=[["send email", "draft email", "compose email"]])`
56
+
57
+ 2. **App Discovery** (`app_ids` only as List[str]):
58
+ - Returns ALL available functions for one or more specific applications.
59
+ - Use this to explore the complete capability set of an application.
60
+
61
+ Examples:
62
+ - Single app discovery:
63
+ `search_functions(app_ids=["Gmail"])`
64
+
65
+ - Multiple app discovery:
66
+ `search_functions(app_ids=["Gmail", "Google Calendar", "Slack"])`
67
+
68
+ 3. **Scoped Search** (`queries` as List[List[str]] and `app_ids` as List[str]):
69
+ - Performs targeted searches within specific applications in parallel.
70
+ - The number of app_ids must match the number of inner query lists.
71
+ - Each query list is searched within its corresponding app_id.
72
+ - Supports multiple search terms per app for comprehensive discovery.
73
+
74
+ Examples:
75
+ - Basic scoped search (one query per app):
76
+ `search_functions(queries=[["find email"], ["share file"]], app_ids=["Gmail", "Google_Drive"])`
77
+
78
+ - Multi-term scoped search (multiple queries per app):
79
+ `search_functions(
80
+ queries=[
81
+ ["send email", "draft email", "compose email", "reply to email"],
82
+ ["create event", "schedule meeting", "find free time"],
83
+ ["upload file", "share file", "create folder", "search files"]
84
+ ],
85
+ app_ids=["Gmail", "Google Calendar", "Google_Drive"]
86
+ )`
87
+
88
+ - Mixed complexity (some apps with single query, others with multiple):
89
+ `search_functions(
90
+ queries=[
91
+ ["list messages"],
92
+ ["create event", "delete event", "update event"]
93
+ ],
94
+ app_ids=["Gmail", "Google Calendar"]
95
+ )`
96
+
97
+ **Pro Tips:**
98
+ - Use multiple search terms in a single query list to cast a wider net and discover related functionality
99
+ - Multi-term searches are more efficient than separate calls
100
+ - Scoped searches return more focused results than global searches
101
+ - The function returns connection status for each app (connected vs NOT connected)
102
+ - All searches within a single call execute in parallel for maximum efficiency
103
+
104
+ **Parameters:**
105
+ - `queries` (List[List[str]], optional): A list of query lists. Each inner list contains one or more
106
+ search terms that will be used together to find relevant tools.
107
+ - `app_ids` (List[str], optional): A list of application IDs to search within or discover.
108
+
109
+ **Returns:**
110
+ - A structured response containing:
111
+ - Matched tools with their descriptions
112
+ - Connection status for each app
113
+ - Recommendations for which tools to load next
56
114
  """
57
- if isinstance(queries, str): # Handle JSON string input
58
- try:
59
- queries = json.loads(queries)
60
- except json.JSONDecodeError:
61
- # If it's a single query as a string, convert to list
62
- queries = [queries] if queries else None
115
+ registry = tool_registry
63
116
 
64
- if not queries and not app_id:
65
- raise ValueError("You must provide 'queries', an 'app_id', or both.")
117
+ TOOL_THRESHOLD = 0.75
118
+ APP_THRESHOLD = 0.7
66
119
 
67
- registry = tool_registry
68
- connections = await registry.list_connected_apps()
69
- connected_app_ids = {connection["app_id"] for connection in connections}
120
+ # --- Helper Functions for Different Search Modes ---
70
121
 
71
- canonical_app_id = None
72
- found_tools_result = []
73
- THRESHOLD = 0.8
74
-
75
- if app_id:
76
- relevant_apps = await registry.search_apps(query=app_id, distance_threshold=THRESHOLD)
77
- if not relevant_apps:
78
- return {
79
- "found_tools": [],
80
- "message": f"Search failed. Application '{app_id}' was not found.",
81
- }
82
- canonical_app_id = relevant_apps[0]["id"]
83
-
84
- if canonical_app_id and not queries:
85
- all_app_tools = await registry.search_tools(query="", app_id=canonical_app_id, limit=20)
86
-
87
- tool_list = []
88
- for tool in all_app_tools:
89
- cleaned_description = tool.get("description", "").split("Context:")[0].strip()
90
- tool_list.append({"id": tool["id"], "description": cleaned_description})
91
-
92
- found_tools_result.append(
93
- {
94
- "app_id": canonical_app_id,
95
- "connection_status": "connected" if canonical_app_id in connected_app_ids else "not_connected",
96
- "tools": tool_list,
97
- }
98
- )
122
+ async def _handle_global_search(queries: list[str]) -> list[list[dict[str, Any]]]:
123
+ """Performs a broad search across all apps to find relevant tools and apps."""
124
+ # 1. Perform initial broad searches for tools and apps concurrently.
125
+ initial_tool_tasks = [registry.search_tools(query=q, distance_threshold=TOOL_THRESHOLD) for q in queries]
126
+ app_search_tasks = [registry.search_apps(query=q, distance_threshold=APP_THRESHOLD) for q in queries]
99
127
 
100
- else:
101
- query_results = []
102
- prioritized_app_id_list = []
128
+ initial_tool_results, app_search_results = await asyncio.gather(
129
+ asyncio.gather(*initial_tool_tasks), asyncio.gather(*app_search_tasks)
130
+ )
103
131
 
104
- if canonical_app_id:
105
- prioritized_app_id_list = [canonical_app_id]
106
- else:
107
- # 1. Perform an initial broad search for tools.
108
- initial_tool_search_tasks = [registry.search_tools(query=q, distance_threshold=THRESHOLD) for q in queries]
109
- initial_tool_results = await asyncio.gather(*initial_tool_search_tasks)
110
-
111
- # 2. Search for relevant apps.
112
- app_search_tasks = [registry.search_apps(query=q, distance_threshold=THRESHOLD) for q in queries]
113
- app_search_results = await asyncio.gather(*app_search_tasks)
114
-
115
- # 3. Create a prioritized list of app IDs for the final search.
116
- # Apps found via search_apps are considered higher priority and come first.
117
- app_ids_from_apps = {app["id"] for result_list in app_search_results for app in result_list}
118
- # Use a list to maintain order.
119
- prioritized_app_id_list.extend(list(app_ids_from_apps))
120
-
121
- # Add app_ids from the initial tool search, ensuring no duplicates.
122
- app_ids_from_tools = {tool["app_id"] for result_list in initial_tool_results for tool in result_list}
123
-
124
- for tool_app_id in app_ids_from_tools:
125
- if tool_app_id not in app_ids_from_apps:
126
- prioritized_app_id_list.append(tool_app_id)
127
-
128
- # 4. Perform the final, comprehensive tool search across the prioritized list of apps.
129
- if prioritized_app_id_list:
130
- # print(f"Prioritized app IDs for final search: {prioritized_app_id_list}")
131
- final_tool_search_tasks = []
132
- for app_id_to_search in prioritized_app_id_list:
133
- for query in queries:
134
- final_tool_search_tasks.append(
135
- registry.search_tools(query=query, app_id=app_id_to_search, distance_threshold=THRESHOLD)
136
- )
137
- query_results = await asyncio.gather(*final_tool_search_tasks)
138
-
139
- # 5. Aggregate all found tools for easy lookup.
132
+ # 2. Create a prioritized list of app IDs for the final search.
133
+ app_ids_from_apps = {app["id"] for result_list in app_search_results for app in result_list}
134
+ prioritized_app_id_list = list(app_ids_from_apps)
135
+
136
+ app_ids_from_tools = {tool["app_id"] for result_list in initial_tool_results for tool in result_list}
137
+ for tool_app_id in app_ids_from_tools:
138
+ if tool_app_id not in app_ids_from_apps:
139
+ prioritized_app_id_list.append(tool_app_id)
140
+
141
+ if not prioritized_app_id_list:
142
+ return []
143
+
144
+ # 3. Perform the final, comprehensive tool search across the prioritized apps.
145
+ final_tool_search_tasks = [
146
+ registry.search_tools(query=query, app_id=app_id_to_search, distance_threshold=TOOL_THRESHOLD)
147
+ for app_id_to_search in prioritized_app_id_list
148
+ for query in queries
149
+ ]
150
+ return await asyncio.gather(*final_tool_search_tasks)
151
+
152
+ async def _handle_scoped_search(app_ids: list[str], queries: list[list[str]]) -> list[list[dict[str, Any]]]:
153
+ """Performs targeted searches for specific queries within specific applications."""
154
+ if len(app_ids) != len(queries):
155
+ raise ValueError("The number of app_ids must match the number of query lists.")
156
+
157
+ tasks = []
158
+ for app_id, query_list in zip(app_ids, queries):
159
+ for query in query_list:
160
+ # Create a search task for each query in the list for the corresponding app
161
+ tasks.append(registry.search_tools(query=query, app_id=app_id, distance_threshold=TOOL_THRESHOLD))
162
+
163
+ return await asyncio.gather(*tasks)
164
+
165
+ async def _handle_app_discovery(app_ids: list[str]) -> list[list[dict[str, Any]]]:
166
+ """Fetches all tools for a list of applications."""
167
+ tasks = [registry.search_tools(query="", app_id=app_id, limit=20) for app_id in app_ids]
168
+ return await asyncio.gather(*tasks)
169
+
170
+ # --- Helper Functions for Structuring and Formatting Results ---
171
+
172
+ def _format_response(structured_results: list[dict[str, Any]]) -> str:
173
+ """Builds the final, user-facing formatted string response from structured data."""
174
+ if not structured_results:
175
+ return "No relevant functions were found."
176
+
177
+ result_parts = []
178
+ apps_in_results = {app["app_id"] for app in structured_results}
179
+ connected_apps_in_results = {
180
+ app["app_id"] for app in structured_results if app["connection_status"] == "connected"
181
+ }
182
+
183
+ for app in structured_results:
184
+ app_id = app["app_id"]
185
+ app_status = "connected" if app["connection_status"] == "connected" else "NOT connected"
186
+ result_parts.append(f"Tools from {app_id} (status: {app_status} by user):")
187
+
188
+ for tool in app["tools"]:
189
+ result_parts.append(f" - {tool['id']}: {tool['description']}")
190
+ result_parts.append("") # Empty line for readability
191
+
192
+ # Add summary connection status messages
193
+ if not connected_apps_in_results and len(apps_in_results) > 1:
194
+ result_parts.append(
195
+ "Connection Status: None of the apps in the results are connected. "
196
+ "You must ask the user to choose the application."
197
+ )
198
+ elif len(connected_apps_in_results) > 1:
199
+ connected_list = ", ".join(sorted(list(connected_apps_in_results)))
200
+ result_parts.append(
201
+ f"Connection Status: Multiple apps are connected ({connected_list}). "
202
+ "You must ask the user to select which application they want to use."
203
+ )
204
+
205
+ result_parts.append("Call load_functions to select the required functions only.")
206
+ if 0 <= len(connected_apps_in_results) < len(apps_in_results):
207
+ result_parts.append(
208
+ "Unconnected app functions can also be loaded if asked for by the user, they will generate a connection link"
209
+ "but prefer connected ones. Ask the user to choose the app if none of the "
210
+ "relevant apps are connected."
211
+ )
212
+
213
+ return "\n".join(result_parts)
214
+
215
+ def _structure_tool_results(
216
+ raw_tool_lists: list[list[dict[str, Any]]], connected_app_ids: set[str]
217
+ ) -> list[dict[str, Any]]:
218
+ """
219
+ Converts raw search results into a structured format, handling duplicates,
220
+ cleaning descriptions, and adding connection status.
221
+ """
140
222
  aggregated_tools = defaultdict(dict)
141
- for tool_list in query_results:
223
+ # Use a list to maintain the order of apps as they are found.
224
+ ordered_app_ids = []
225
+
226
+ for tool_list in raw_tool_lists:
142
227
  for tool in tool_list:
143
- app_id_from_tool = tool.get("app_id", "unknown")
228
+ app_id = tool.get("app_id", "unknown")
144
229
  tool_id = tool.get("id")
145
- if not tool_id or tool_id in aggregated_tools[app_id_from_tool]:
230
+
231
+ if not tool_id:
146
232
  continue
147
- cleaned_description = tool.get("description", "").split("Context:")[0].strip()
148
- aggregated_tools[app_id_from_tool][tool_id] = {
149
- "id": tool_id,
150
- "description": cleaned_description,
151
- }
152
-
153
- # 6. Build the final results list, respecting the prioritized app order.
154
- for app_id_from_list in prioritized_app_id_list:
155
- if app_id_from_list in aggregated_tools and aggregated_tools[app_id_from_list]:
233
+
234
+ if app_id not in aggregated_tools:
235
+ ordered_app_ids.append(app_id)
236
+
237
+ if tool_id not in aggregated_tools[app_id]:
238
+ aggregated_tools[app_id][tool_id] = {
239
+ "id": tool_id,
240
+ "description": _clean_tool_description(tool.get("description", "")),
241
+ }
242
+
243
+ # Build the final results list respecting the discovery order.
244
+ found_tools_result = []
245
+ for app_id in ordered_app_ids:
246
+ if app_id in aggregated_tools and aggregated_tools[app_id]:
156
247
  found_tools_result.append(
157
248
  {
158
- "app_id": app_id_from_list,
159
- "connection_status": "connected"
160
- if app_id_from_list in connected_app_ids
161
- else "not_connected",
162
- "tools": list(aggregated_tools[app_id_from_list].values()),
249
+ "app_id": app_id,
250
+ "connection_status": "connected" if app_id in connected_app_ids else "not_connected",
251
+ "tools": list(aggregated_tools[app_id].values()),
163
252
  }
164
253
  )
254
+ return found_tools_result
165
255
 
166
- # Build result string efficiently
167
- result_parts = []
168
- apps_in_results = {app["app_id"] for app in found_tools_result}
169
- connected_apps_in_results = apps_in_results.intersection(connected_app_ids)
170
-
171
- for app in found_tools_result:
172
- app_id = app["app_id"]
173
- connection_status = app["connection_status"]
174
- tools = app["tools"]
175
-
176
- app_status = "connected" if connection_status == "connected" else "NOT connected"
177
- result_parts.append(f"Tools from {app_id} (status: {app_status} by user):")
178
-
179
- for tool in tools:
180
- tool_id = tool["id"]
181
- description = tool["description"]
182
- result_parts.append(f" - {tool_id}: {description}")
183
- result_parts.append("") # Empty line between apps
184
-
185
- # Add connection status information
186
- if len(connected_apps_in_results) == 0 and len(apps_in_results) > 0:
187
- result_parts.append(
188
- "Connection Status: None of the apps in the results are connected. You must ask the user to choose the application."
189
- )
190
- elif len(connected_apps_in_results) > 1:
191
- connected_list = ", ".join(connected_apps_in_results)
192
- result_parts.append(
193
- f"Connection Status: Multiple apps are connected ({connected_list}). You must ask the user to select which application they want to use."
256
+ def _clean_tool_description(description: str) -> str:
257
+ """Consistently formats tool descriptions by removing implementation details."""
258
+ return description.split("Context:")[0].strip()
259
+
260
+ # Main Function Logic
261
+
262
+ if not queries and not app_ids:
263
+ raise ValueError("You must provide 'queries', 'app_ids', or both.")
264
+
265
+ # --- Initialization and Input Normalization ---
266
+ connections = await registry.list_connected_apps()
267
+ connected_app_ids = {connection["app_id"] for connection in connections}
268
+
269
+ canonical_app_ids = []
270
+ if app_ids:
271
+ # Concurrently search for all provided app names
272
+ app_search_tasks = [
273
+ registry.search_apps(query=app_name, distance_threshold=APP_THRESHOLD) for app_name in app_ids
274
+ ]
275
+ app_search_results = await asyncio.gather(*app_search_tasks)
276
+
277
+ # Process results and build the list of canonical IDs, handling not found errors
278
+ for app_name, result_list in zip(app_ids, app_search_results):
279
+ if not result_list:
280
+ raise ValueError(f"Application '{app_name}' could not be found.")
281
+ # Assume the first result is the correct one
282
+ canonical_app_ids.append(result_list[0]["id"])
283
+
284
+ # --- Mode Dispatching ---
285
+ raw_results = []
286
+
287
+ if canonical_app_ids and queries:
288
+ raw_results = await _handle_scoped_search(canonical_app_ids, queries)
289
+ elif canonical_app_ids:
290
+ raw_results = await _handle_app_discovery(canonical_app_ids)
291
+ elif queries:
292
+ # Flatten list of lists to list of strings for global search
293
+ flat_queries = (
294
+ [q for sublist in queries for q in sublist] if queries and not isinstance(queries[0], str) else queries
194
295
  )
296
+ raw_results = await _handle_global_search(flat_queries)
195
297
 
196
- result_parts.append("Call load_functions to select the required functions only.")
197
- return "\n".join(result_parts)
298
+ # --- Structuring and Formatting ---
299
+ structured_data = _structure_tool_results(raw_results, connected_app_ids)
300
+ return _format_response(structured_data)
198
301
 
199
302
  @tool
200
303
  async def load_functions(tool_ids: list[str]) -> str:
201
- """Load specific functions by their IDs for use in subsequent steps.
304
+ """
305
+ Loads specified functions and returns their Python signatures and docstrings.
306
+ This makes the functions available for use inside the 'execute_ipython_cell' tool.
307
+ The agent MUST use the returned information to understand how to call the functions correctly.
202
308
 
203
309
  Args:
204
- tool_ids: Function ids in the form 'app__function'. Example: 'google_mail__send_email'
310
+ tool_ids: A list of function IDs in the format 'app__function'. Example: ['google_mail__send_email']
205
311
 
206
312
  Returns:
207
- Confirmation message about loaded functions
313
+ A string containing the signatures and docstrings of the successfully loaded functions,
314
+ ready for the agent to use in its code.
208
315
  """
209
- return f"Successfully loaded {len(tool_ids)} functions: {tool_ids}"
316
+ if not tool_ids:
317
+ return "No tool IDs provided to load."
318
+
319
+ # Step 1: Validate which tools are usable and get login links for others.
320
+ valid_tools, unconnected_links = await get_valid_tools(tool_ids=tool_ids, registry=tool_registry)
321
+
322
+ if not valid_tools:
323
+ response_string = "Error: None of the provided tool IDs could be validated or loaded."
324
+ return response_string, {}, [], ""
325
+
326
+ # Step 2: Export the schemas of the valid tools.
327
+ await tool_registry.load_tools(valid_tools)
328
+ exported_tools = await tool_registry.export_tools(
329
+ valid_tools, ToolFormat.NATIVE
330
+ ) # Get definition for only the new tools
331
+
332
+ # Step 3: Build the informational string for the agent.
333
+ tool_definitions, new_tools_context = build_tool_definitions(exported_tools)
334
+
335
+ result_parts = [
336
+ f"Successfully loaded {len(exported_tools)} functions. They are now available for use inside `execute_ipython_cell`:",
337
+ "\n".join(tool_definitions),
338
+ ]
339
+
340
+ response_string = "\n\n".join(result_parts)
341
+ unconnected_links = "\n".join(unconnected_links)
342
+
343
+ return response_string, new_tools_context, valid_tools, unconnected_links
210
344
 
211
- @tool
212
345
  async def web_search(query: str) -> dict:
213
346
  """
214
347
  Get an LLM answer to a question informed by Exa search results. Useful when you need information from a wide range of real-time sources on the web. Do not use this when you need to access contents of a specific webpage.
@@ -234,7 +367,95 @@ def create_meta_tools(tool_registry: AgentrRegistry) -> dict[str, Any]:
234
367
  "citations": response.get("citations", []),
235
368
  }
236
369
 
237
- return {"search_functions": search_functions, "load_functions": load_functions, "web_search": web_search}
370
+ async def read_file(uri: str) -> str:
371
+ """
372
+ Asynchronously reads a local file or uri and returns the content as a markdown string.
373
+
374
+ This tool aims to extract the main text content from various sources.
375
+ It automatically prepends 'file://' to the input string if it appears
376
+ to be a local path without a specified scheme (like http, https, data, file).
377
+
378
+ Args:
379
+ uri (str): The URI pointing to the resource or a local file path.
380
+ Supported schemes:
381
+ - http:// or https:// (Web pages, feeds, APIs)
382
+ - file:// (Local or accessible network files)
383
+ - data: (Embedded data)
384
+
385
+ Returns:
386
+ A string containing the markdown representation of the content at the specified URI
387
+
388
+ Raises:
389
+ ValueError: If the URI is invalid, empty, or uses an unsupported scheme
390
+ after automatic prefixing.
391
+
392
+ Tags:
393
+ convert, markdown, async, uri, transform, document, important
394
+ """
395
+ markitdown = MarkitdownApp()
396
+ response = await markitdown.convert_to_markdown(uri)
397
+ return response
398
+
399
+ def save_file(file_name: str, content: str) -> dict:
400
+ """
401
+ Saves a file to the local filesystem.
402
+
403
+ Args:
404
+ file_name (str): The name of the file to save.
405
+ content (str): The content to save to the file.
406
+
407
+ Returns:
408
+ dict: A dictionary containing the result of the save operation with the following fields:
409
+ - status (str): "success" if the save succeeded, "error" otherwise.
410
+ - message (str): A message returned by the server, typically indicating success or providing error details.
411
+ """
412
+ with Path(file_name).open("w") as f:
413
+ f.write(content)
414
+
415
+ return {
416
+ "status": "success",
417
+ "message": f"File {file_name} saved successfully",
418
+ "file_path": Path(file_name).absolute(),
419
+ }
420
+
421
+ def upload_file(file_name: str, mime_type: str, base64_data: str) -> dict:
422
+ """
423
+ Uploads a file to the server via the AgentrClient.
424
+
425
+ Args:
426
+ file_name (str): The name of the file to upload.
427
+ mime_type (str): The MIME type of the file.
428
+ base64_data (str): The file content encoded as a base64 string.
429
+
430
+ Returns:
431
+ dict: A dictionary containing the result of the upload operation with the following fields:
432
+ - status (str): "success" if the upload succeeded, "error" otherwise.
433
+ - message (str): A message returned by the server, typically indicating success or providing error details.
434
+ - signed_url (str or None): The signed URL to access the uploaded file if successful, None otherwise.
435
+ """
436
+ client: AgentrClient = tool_registry.client
437
+ bytes_data = base64.b64decode(base64_data)
438
+ response = client._upload_file(file_name, mime_type, bytes_data)
439
+ if response.get("status") != "success":
440
+ return {
441
+ "status": "error",
442
+ "message": response.get("message"),
443
+ "signed_url": None,
444
+ }
445
+ return {
446
+ "status": "success",
447
+ "message": response.get("message"),
448
+ "signed_url": response.get("signed_url"),
449
+ }
450
+
451
+ return {
452
+ "search_functions": search_functions,
453
+ "load_functions": load_functions,
454
+ "web_search": web_search,
455
+ "read_file": read_file,
456
+ "upload_file": upload_file,
457
+ "save_file": save_file,
458
+ }
238
459
 
239
460
 
240
461
  async def get_valid_tools(tool_ids: list[str], registry: AgentrRegistry) -> tuple[list[str], list[str]]:
@@ -282,7 +503,7 @@ async def get_valid_tools(tool_ids: list[str], registry: AgentrRegistry) -> tupl
282
503
  start = text.find(":") + 1
283
504
  end = text.find(". R", start)
284
505
  url = text[start:end].strip()
285
- markdown_link = f"[{app}]({url})"
506
+ markdown_link = f"![Connect to {app.capitalize()}]({url})"
286
507
  unconnected_links.append(markdown_link)
287
508
  for tool_id, tool_name in tool_entries:
288
509
  if tool_name in available: