1+ import asyncio
12import importlib
23import inspect
34import json
1011import jsonref
1112from mcpadapt .smolagents_adapter import _sanitize_function_name
1213
13- from consts .const import LOCAL_MCP_SERVER
14+ from consts .const import DEFAULT_USER_ID , LOCAL_MCP_SERVER
1415from consts .exceptions import MCPConnectionError
1516from consts .model import ToolInstanceInfoRequest , ToolInfo , ToolSourceEnum
1617from database .remote_mcp_db import get_mcp_records_by_tenant
2021 query_tool_instances_by_id ,
2122 update_tool_table_from_scan_tool_list
2223)
24+ from database .user_tenant_db import get_all_tenant_ids
2325
2426logger = logging .getLogger ("tool_configuration_service" )
2527
@@ -346,4 +348,69 @@ async def list_all_tools(tenant_id: str):
346348 }
347349 formatted_tools .append (formatted_tool )
348350
349- return formatted_tools
351+ return formatted_tools
352+
353+
354+ async def initialize_tools_on_startup ():
355+ """
356+ Initialize and scan all tools during server startup for all tenants
357+
358+ This function scans all available tools (local, LangChain, and MCP)
359+ and updates the database with the latest tool information for all tenants.
360+ """
361+
362+ logger .info ("Starting tool initialization on server startup..." )
363+
364+ try :
365+ # Get all tenant IDs from the database
366+ tenant_ids = get_all_tenant_ids ()
367+
368+ if not tenant_ids :
369+ logger .warning ("No tenants found in database, skipping tool initialization" )
370+ return
371+
372+ logger .info (f"Found { len (tenant_ids )} tenants: { tenant_ids } " )
373+
374+ total_tools = 0
375+ successful_tenants = 0
376+ failed_tenants = []
377+
378+ # Process each tenant
379+ for tenant_id in tenant_ids :
380+ try :
381+ logger .info (f"Initializing tools for tenant: { tenant_id } " )
382+
383+ # Add timeout to prevent hanging during startup
384+ try :
385+ await asyncio .wait_for (
386+ update_tool_list (tenant_id = tenant_id , user_id = DEFAULT_USER_ID ),
387+ timeout = 60.0 # 60 seconds timeout per tenant
388+ )
389+
390+ # Get the count of tools for this tenant
391+ tools_info = query_all_tools (tenant_id )
392+ tenant_tool_count = len (tools_info )
393+ total_tools += tenant_tool_count
394+ successful_tenants += 1
395+
396+ logger .info (f"Tenant { tenant_id } : { tenant_tool_count } tools initialized" )
397+
398+ except asyncio .TimeoutError :
399+ logger .error (f"Tool initialization timed out for tenant { tenant_id } " )
400+ failed_tenants .append (f"{ tenant_id } (timeout)" )
401+
402+ except Exception as e :
403+ logger .error (f"Tool initialization failed for tenant { tenant_id } : { str (e )} " )
404+ failed_tenants .append (f"{ tenant_id } (error: { str (e )} )" )
405+
406+ # Log final results
407+ logger .info (f"Tool initialization completed!" )
408+ logger .info (f"Total tools available across all tenants: { total_tools } " )
409+ logger .info (f"Successfully processed: { successful_tenants } /{ len (tenant_ids )} tenants" )
410+
411+ if failed_tenants :
412+ logger .warning (f"Failed tenants: { ', ' .join (failed_tenants )} " )
413+
414+ except Exception as e :
415+ logger .error (f"❌ Tool initialization failed: { str (e )} " )
416+ raise
0 commit comments