|
| 1 | +"""Handler for REST API call to list available tools from MCP servers.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Annotated, Any |
| 5 | + |
| 6 | +from fastapi import APIRouter, Depends, HTTPException, Request, status |
| 7 | +from llama_stack_client import APIConnectionError |
| 8 | + |
| 9 | +from authentication import get_auth_dependency |
| 10 | +from authentication.interface import AuthTuple |
| 11 | +from authorization.middleware import authorize |
| 12 | +from client import AsyncLlamaStackClientHolder |
| 13 | +from configuration import configuration |
| 14 | +from models.config import Action |
| 15 | +from models.responses import ToolsResponse |
| 16 | +from utils.endpoints import check_configuration_loaded |
| 17 | +from utils.tool_formatter import format_tools_list |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | +router = APIRouter(tags=["tools"]) |
| 21 | + |
| 22 | + |
| 23 | +tools_responses: dict[int | str, dict[str, Any]] = { |
| 24 | + 200: { |
| 25 | + "description": "Successful Response", |
| 26 | + "content": { |
| 27 | + "application/json": { |
| 28 | + "example": { |
| 29 | + "tools": [ |
| 30 | + { |
| 31 | + "identifier": "", |
| 32 | + "description": "", |
| 33 | + "parameters": [ |
| 34 | + { |
| 35 | + "name": "", |
| 36 | + "description": "", |
| 37 | + "parameter_type": "", |
| 38 | + "required": "True/False", |
| 39 | + "default": "null", |
| 40 | + } |
| 41 | + ], |
| 42 | + "provider_id": "", |
| 43 | + "toolgroup_id": "", |
| 44 | + "server_source": "", |
| 45 | + "type": "tool", |
| 46 | + } |
| 47 | + ] |
| 48 | + } |
| 49 | + } |
| 50 | + }, |
| 51 | + }, |
| 52 | + 500: {"description": "Connection to Llama Stack is broken or MCP server error"}, |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +@router.get("/tools", responses=tools_responses) |
| 57 | +@authorize(Action.GET_TOOLS) |
| 58 | +async def tools_endpoint_handler( |
| 59 | + request: Request, |
| 60 | + auth: Annotated[AuthTuple, Depends(get_auth_dependency())], |
| 61 | +) -> ToolsResponse: |
| 62 | + """ |
| 63 | + Handle requests to the /tools endpoint. |
| 64 | +
|
| 65 | + Process GET requests to the /tools endpoint, returning a consolidated list of |
| 66 | + available tools from all configured MCP servers. |
| 67 | +
|
| 68 | + Raises: |
| 69 | + HTTPException: If unable to connect to the Llama Stack server or if |
| 70 | + tool retrieval fails for any reason. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + ToolsResponse: An object containing the consolidated list of available tools |
| 74 | + with metadata including tool name, description, parameters, and server source. |
| 75 | + """ |
| 76 | + # Used only by the middleware |
| 77 | + _ = auth |
| 78 | + |
| 79 | + # Nothing interesting in the request |
| 80 | + _ = request |
| 81 | + |
| 82 | + check_configuration_loaded(configuration) |
| 83 | + |
| 84 | + try: |
| 85 | + # Get Llama Stack client |
| 86 | + client = AsyncLlamaStackClientHolder().get_client() |
| 87 | + |
| 88 | + consolidated_tools = [] |
| 89 | + mcp_server_names = ( |
| 90 | + {mcp_server.name for mcp_server in configuration.mcp_servers} |
| 91 | + if configuration.mcp_servers |
| 92 | + else set() |
| 93 | + ) |
| 94 | + |
| 95 | + # Get all available toolgroups |
| 96 | + try: |
| 97 | + logger.debug("Retrieving tools from all toolgroups") |
| 98 | + toolgroups_response = await client.toolgroups.list() |
| 99 | + |
| 100 | + for toolgroup in toolgroups_response: |
| 101 | + try: |
| 102 | + # Get tools for each toolgroup |
| 103 | + tools_response = await client.tools.list( |
| 104 | + toolgroup_id=toolgroup.identifier |
| 105 | + ) |
| 106 | + |
| 107 | + # Convert tools to dict format |
| 108 | + tools_count = 0 |
| 109 | + server_source = "unknown" |
| 110 | + |
| 111 | + for tool in tools_response: |
| 112 | + tool_dict = dict(tool) |
| 113 | + |
| 114 | + # Determine server source based on toolgroup type |
| 115 | + if toolgroup.identifier in mcp_server_names: |
| 116 | + # This is an MCP server toolgroup |
| 117 | + mcp_server = next( |
| 118 | + ( |
| 119 | + s |
| 120 | + for s in configuration.mcp_servers |
| 121 | + if s.name == toolgroup.identifier |
| 122 | + ), |
| 123 | + None, |
| 124 | + ) |
| 125 | + tool_dict["server_source"] = ( |
| 126 | + mcp_server.url if mcp_server else toolgroup.identifier |
| 127 | + ) |
| 128 | + else: |
| 129 | + # This is a built-in toolgroup |
| 130 | + tool_dict["server_source"] = "builtin" |
| 131 | + |
| 132 | + consolidated_tools.append(tool_dict) |
| 133 | + tools_count += 1 |
| 134 | + server_source = tool_dict["server_source"] |
| 135 | + |
| 136 | + logger.debug( |
| 137 | + "Retrieved %d tools from toolgroup %s (source: %s)", |
| 138 | + tools_count, |
| 139 | + toolgroup.identifier, |
| 140 | + server_source, |
| 141 | + ) |
| 142 | + |
| 143 | + except Exception as e: # pylint: disable=broad-exception-caught |
| 144 | + # Catch any exception from individual toolgroup failures to allow |
| 145 | + # processing of other toolgroups to continue (partial failure scenario) |
| 146 | + logger.warning( |
| 147 | + "Failed to retrieve tools from toolgroup %s: %s", |
| 148 | + toolgroup.identifier, |
| 149 | + e, |
| 150 | + ) |
| 151 | + continue |
| 152 | + |
| 153 | + except APIConnectionError as e: |
| 154 | + logger.warning("Failed to retrieve tools from toolgroups: %s", e) |
| 155 | + raise |
| 156 | + except (ValueError, AttributeError) as e: |
| 157 | + logger.warning("Failed to retrieve tools from toolgroups: %s", e) |
| 158 | + |
| 159 | + logger.info( |
| 160 | + "Retrieved total of %d tools (%d from built-in toolgroups, %d from MCP servers)", |
| 161 | + len(consolidated_tools), |
| 162 | + len([t for t in consolidated_tools if t.get("server_source") == "builtin"]), |
| 163 | + len([t for t in consolidated_tools if t.get("server_source") != "builtin"]), |
| 164 | + ) |
| 165 | + |
| 166 | + # Format tools with structured description parsing |
| 167 | + formatted_tools = format_tools_list(consolidated_tools) |
| 168 | + |
| 169 | + return ToolsResponse(tools=formatted_tools) |
| 170 | + |
| 171 | + # Connection to Llama Stack server |
| 172 | + except APIConnectionError as e: |
| 173 | + logger.error("Unable to connect to Llama Stack: %s", e) |
| 174 | + raise HTTPException( |
| 175 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 176 | + detail={ |
| 177 | + "response": "Unable to connect to Llama Stack", |
| 178 | + "cause": str(e), |
| 179 | + }, |
| 180 | + ) from e |
| 181 | + # Any other exception that can occur during tool listing |
| 182 | + except Exception as e: |
| 183 | + logger.error("Unable to retrieve list of tools: %s", e) |
| 184 | + raise HTTPException( |
| 185 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 186 | + detail={ |
| 187 | + "response": "Unable to retrieve list of tools", |
| 188 | + "cause": str(e), |
| 189 | + }, |
| 190 | + ) from e |
0 commit comments