"""The roles' MCP tools, through the platform's gateway. Each is a tool on the provider's server in mcp-servers/, named by the bundle. As in the source, a failed call is a discovery gap for the Specialist to record, and never stops the Execution.""" from __future__ import annotations import json from collections.abc import Mapping, Sequence from typing import Any from app.core.providers import ProviderBundle from app.engine.runtime import ToolResult, ToolSpec GAP_INSTRUCTION = "Record it under discovery gaps and carry on." MAX_CHARS = 60_000 async def _call(name: str, arguments: Mapping[str, Any]) -> Any: from kyndryl_agent_runtime.tools import acall_tool return await acall_tool(name, arguments) def _declared_schema(name: str) -> Mapping[str, Any]: """The tool's arguments as the gateway reports them, so a Specialist can see them.""" try: from kyndryl_agent_runtime.tools import declared_tools found = next((tool for tool in declared_tools() if tool.name == name), None) except Exception: # no gateway here, as in a test: any arguments are passed on found = None return (found.input_schema if found else None) or {"type": "object", "additionalProperties": True} def _text(result: Any) -> tuple[bool, str]: if isinstance(result, Mapping) and result.get("success") is False: error = result.get("error") or {} return False, str(error.get("message") or error.get("code") or "refused") text = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str) return True, text if len(text) <= MAX_CHARS else text[:MAX_CHARS] + "\n[truncated]" class McpCatalog: def __init__(self, bundle: ProviderBundle, *, docs_search: bool = False, call: Any = _call) -> None: self._bundle = bundle self._docs_search = docs_search self._call = call def _tool(self, server: str, tier: str, name: str, passes_arguments: bool) -> ToolSpec: full = self._bundle.mcp_tool_name(server, name) async def handler(**arguments: Any) -> ToolResult: sent = {"tool_arguments": arguments} if passes_arguments else arguments try: worked, text = _text(await self._call(full, sent)) except Exception as exc: # a remote failure is a gap, as in the source return ToolResult(f"Discovery gap: {full} failed ({type(exc).__name__}). {GAP_INSTRUCTION}") return ToolResult(text if worked else f"Discovery gap: {full} failed ({text}). {GAP_INSTRUCTION}") return ToolSpec( full, f"{name} on the {server} server. Read-only.", {"type": "object", "additionalProperties": True} if passes_arguments else _declared_schema(full), handler, tier=tier, ) def tools_for(self, server_ids: Sequence[str]) -> list[ToolSpec]: tools: list[ToolSpec] = [] passes = bool(self._bundle.mcp_describe_tool) for server_id in server_ids: server = self._bundle.mcp_servers[server_id] if server.tier == "general" and not self._docs_search: continue # free-text search is off until a deployment turns it on tools += [self._tool(server_id, server.tier, name, passes) for name in server.allow] if passes and tools: tools.append(self._describe(tools[0].tier)) return tools def _describe(self, tier: str) -> ToolSpec: name = self._bundle.mcp_describe_tool async def handler(server: str, tool: str) -> ToolResult: try: worked, text = _text(await self._call(name, {"server": server, "tool": tool})) except Exception as exc: return ToolResult(f"Discovery gap: {name} failed ({type(exc).__name__}). {GAP_INSTRUCTION}") return ToolResult(text if worked else f"Discovery gap: {name} failed ({text}). {GAP_INSTRUCTION}") return ToolSpec( name, "Read a hosted tool's arguments before calling it.", { "type": "object", "properties": {"server": {"type": "string"}, "tool": {"type": "string"}}, "required": ["server", "tool"], }, handler, tier="general", )