diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index c6243fb..f3c71b8 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -128,3 +128,41 @@ export const updateModelConfig = ( ...jsonBody(update), method: 'PUT' }); + +// ── Tool Servers ──────────────────────────────────────────── + +export interface ToolServer { + id: string; + type: 'openapi' | 'mcp'; + url: string; + path: string; + auth_type: string; + key: string; + name: string; + description: string; + headers: Record | null; + enabled: boolean; +} + +export const listToolServers = async (): Promise => { + const data = await fetchJSON<{ servers: ToolServer[] }>('/api/admin/tools/servers'); + return data.servers; +}; + +export const createToolServer = (server: Omit) => + fetchJSON('/api/admin/tools/servers', jsonBody(server)); + +export const updateToolServer = (id: string, updates: Partial>) => + fetchJSON(`/api/admin/tools/servers/${id}`, { + ...jsonBody(updates), + method: 'PUT' + }); + +export const deleteToolServer = (id: string) => + fetchJSON(`/api/admin/tools/servers/${id}`, { method: 'DELETE' }); + +export const verifyToolServer = (id: string) => + fetchJSON<{ ok: boolean; tools?: { name: string; description: string }[]; message?: string }>( + `/api/admin/tools/servers/${id}/verify`, + { method: 'POST' } + ); diff --git a/cptr/frontend/src/lib/components/Admin/ToolServers.svelte b/cptr/frontend/src/lib/components/Admin/ToolServers.svelte new file mode 100644 index 0000000..4b4e6b4 --- /dev/null +++ b/cptr/frontend/src/lib/components/Admin/ToolServers.svelte @@ -0,0 +1,444 @@ + + +
+

{$t('toolServers.title')}

+ +
+ +{#if loading} +
+ +
+{:else} +
+ {#each servers as s} + + {/each} + + {#if servers.length === 0} +

+ {$t('toolServers.empty')} +

+ {/if} +
+{/if} + +{#if showModal} + (showModal = false)} class="w-full max-w-md mx-4"> + +
{ + if (e.key === 'Enter' && formUrl.trim()) handleSubmit(); + }} + > +

+ {editServer ? $t('toolServers.edit') : $t('toolServers.add')} +

+ + +
+
+ + +
+
+ + +
+
+ + + + + + + + + + + {#if formType === 'openapi'} + + + {/if} + + +
+
+ + +
+ {#if formAuthType === 'bearer'} +
+ + +
+ {/if} +
+ + + + + + + +

{$t('toolServers.headersHint')}

+ + + + + {#if verifyResult?.ok && verifyResult.tools} +
+ {verifyResult.tools.length} + {$t('toolServers.toolsFound')}: + {verifyResult.tools.map((t) => t.name).join(', ')} +
+ {/if} + + +
+
+ {#if editServer} + + + {/if} +
+ +
+
+
+{/if} diff --git a/cptr/frontend/src/lib/components/SettingsModal.svelte b/cptr/frontend/src/lib/components/SettingsModal.svelte index 27adebe..3c341f5 100644 --- a/cptr/frontend/src/lib/components/SettingsModal.svelte +++ b/cptr/frontend/src/lib/components/SettingsModal.svelte @@ -12,6 +12,7 @@ import Gateway from './Admin/Gateway.svelte'; import AudioSettings from './Admin/AudioSettings.svelte'; import AdminWeb from './Admin/Web.svelte'; + import ToolServers from './Admin/ToolServers.svelte'; import { session } from '$lib/session'; import { t } from '$lib/i18n'; @@ -26,7 +27,8 @@ | 'messaging' | 'gateway' | 'audio' - | 'web'; + | 'web' + | 'toolservers'; interface Props { onclose: () => void; @@ -53,7 +55,8 @@ { id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' }, { id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' }, { id: 'audio', label: $t('admin.audio.title'), icon: 'microphone' }, - { id: 'web', label: $t('admin.web'), icon: 'globe' } + { id: 'web', label: $t('admin.web'), icon: 'globe' }, + { id: 'toolservers', label: $t('admin.toolServers'), icon: 'plug' } ]); @@ -132,6 +135,8 @@ {:else if activeTab === 'web'} + {:else if activeTab === 'toolservers'} + {/if} diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index b0370fa..1da33d5 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -178,8 +178,16 @@ return _t('chat.tool.fetchUrlFallback'); } } - default: + default: { + // External tool: {server_id}_{tool_name} → "tool_name (server_id)" + const idx = name.indexOf('_'); + if (idx > 0) { + const serverId = name.slice(0, idx); + const toolName = name.slice(idx + 1); + return `${toolName} (${serverId})`; + } return name; + } } } diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index c03f4e4..27c8f4e 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -645,6 +645,41 @@ "chat.dictate.unsupported": "Speech recognition not supported in this browser.", "chat.fallbackTitle": "Chat", - "chat.greeting": "What can I help you with?" + "chat.greeting": "What can I help you with?", + + "admin.toolServers": "Tool Servers", + + "toolServers.title": "Tool Servers", + "toolServers.empty": "No tool servers configured", + "toolServers.add": "Add Server", + "toolServers.edit": "Edit Server", + "toolServers.id": "ID", + "toolServers.name": "Name", + "toolServers.type": "Type", + "toolServers.namePlaceholder": "My MCP Server", + "toolServers.url": "URL", + "toolServers.specPath": "Spec path", + "toolServers.fieldsRequired": "ID and URL are required", + "toolServers.idInvalid": "ID must be lowercase letters, numbers, and underscores only", + "toolServers.auth": "Auth", + "toolServers.authNone": "None", + "toolServers.authBearer": "Bearer", + "toolServers.apiKey": "API Key", + "toolServers.description": "Description", + "toolServers.descriptionPlaceholder": "What does this server do?", + "toolServers.headers": "Headers", + "toolServers.headersHint": "Additional HTTP headers as JSON.", + "toolServers.headersInvalid": "Headers must be a valid JSON object", + "toolServers.verify": "Verify", + "toolServers.connected": "Connected", + "toolServers.toolsFound": "tools found", + "toolServers.delete": "Delete", + "toolServers.loadError": "Failed to load tool servers", + "toolServers.urlRequired": "URL is required", + "toolServers.created": "Tool server added", + "toolServers.updated": "Tool server updated", + "toolServers.deleted": "Tool server deleted", + "toolServers.saveFailed": "Failed to save tool server", + "toolServers.deleteFailed": "Failed to delete tool server" } diff --git a/cptr/routers/admin.py b/cptr/routers/admin.py index 7ab2436..effd75e 100644 --- a/cptr/routers/admin.py +++ b/cptr/routers/admin.py @@ -425,3 +425,170 @@ async def update_model_config( await Config.upsert({CONFIG_KEY_CHAT_MODELS: all_config}) return {"ok": True} + +# ── Tool servers ───────────────────────────────────────────── + +CONFIG_KEY_TOOL_SERVERS = "tool_servers" + + +async def _get_tool_servers() -> list[dict]: + """Get all tool server configs from config store.""" + return await Config.get(CONFIG_KEY_TOOL_SERVERS) or [] + + +async def _save_tool_servers(servers: list[dict]): + """Save tool server configs and invalidate cache.""" + await Config.upsert({CONFIG_KEY_TOOL_SERVERS: servers}) + from cptr.utils.tools import invalidate_tool_server_cache + + invalidate_tool_server_cache() + + +def _mask_tool_server(server: dict) -> dict: + """Return server with masked API key for display.""" + masked = {**server} + if masked.get("key"): + key = masked["key"] + masked["key"] = key[:4] + "****" + key[-4:] if len(key) > 8 else "****" + return masked + + +@router.get("/tools/servers") +async def list_tool_servers(request: Request): + """List all configured tool servers (keys masked).""" + require_admin(request) + servers = await _get_tool_servers() + return {"servers": [_mask_tool_server(s) for s in servers]} + + +class CreateToolServerRequest(BaseModel): + id: str + type: str = "openapi" # "openapi" | "mcp" + url: str + path: str = "openapi.json" # OpenAPI spec path (OpenAPI only) + auth_type: str = "bearer" # "bearer" | "none" + key: Optional[str] = None + name: str = "" + description: str = "" + headers: Optional[dict] = None + enabled: bool = True + + +@router.post("/tools/servers") +async def create_tool_server(body: CreateToolServerRequest, request: Request): + """Add a new external tool server.""" + require_admin(request) + import re as _re + + server_id = body.id.strip() + if not server_id or not _re.fullmatch(r"[a-z0-9_]+", server_id): + raise HTTPException(400, "ID must be lowercase alphanumeric with underscores only") + + servers = await _get_tool_servers() + if any(s["id"] == server_id for s in servers): + raise HTTPException(409, f"Server ID '{server_id}' already exists") + + server = { + "id": server_id, + "type": body.type, + "url": body.url, + "path": body.path, + "auth_type": body.auth_type, + "key": body.key or "", + "name": body.name or server_id, + "description": body.description, + "headers": body.headers, + "enabled": body.enabled, + } + servers.append(server) + await _save_tool_servers(servers) + return {"ok": True, "id": server["id"]} + + +class UpdateToolServerRequest(BaseModel): + type: Optional[str] = None + url: Optional[str] = None + path: Optional[str] = None + auth_type: Optional[str] = None + key: Optional[str] = None + name: Optional[str] = None + description: Optional[str] = None + headers: Optional[dict] = None + enabled: Optional[bool] = None + + +@router.put("/tools/servers/{server_id}") +async def update_tool_server(server_id: str, body: UpdateToolServerRequest, request: Request): + """Update an existing tool server.""" + require_admin(request) + servers = await _get_tool_servers() + server = next((s for s in servers if s["id"] == server_id), None) + if not server: + raise HTTPException(404, "tool server not found") + + for field in ("type", "url", "path", "auth_type", "name", "description"): + val = getattr(body, field) + if val is not None: + server[field] = val + if body.key is not None and body.key != "": + server["key"] = body.key + if body.headers is not None: + server["headers"] = body.headers + if body.enabled is not None: + server["enabled"] = body.enabled + + await _save_tool_servers(servers) + return {"ok": True} + + +@router.delete("/tools/servers/{server_id}") +async def delete_tool_server(server_id: str, request: Request): + """Delete a tool server.""" + require_admin(request) + servers = [s for s in await _get_tool_servers() if s["id"] != server_id] + await _save_tool_servers(servers) + return {"ok": True} + + +@router.post("/tools/servers/{server_id}/verify") +async def verify_tool_server(server_id: str, request: Request): + """Test connectivity to a tool server. Returns discovered tools.""" + require_admin(request) + servers = await _get_tool_servers() + server = next((s for s in servers if s["id"] == server_id), None) + if not server: + raise HTTPException(404, "tool server not found") + + server_type = server.get("type", "openapi") + url = server.get("url", "") + headers = dict(server.get("headers") or {}) + if server.get("auth_type") == "bearer" and server.get("key"): + headers["Authorization"] = f"Bearer {server['key']}" + + try: + if server_type == "mcp": + from cptr.utils.mcp.client import MCPClient + + client = MCPClient() + await client.connect(url, headers or None) + try: + specs = await client.list_tool_specs() + return {"ok": True, "tools": specs} + finally: + await client.disconnect() + + else: # openapi + from cptr.utils.openapi import fetch_openapi_spec, convert_openapi_to_tool_specs + + path = server.get("path", "openapi.json") + if path.startswith("http"): + spec_url = path + else: + spec_url = f"{url.rstrip('/')}/{path.lstrip('/')}" + + spec = await fetch_openapi_spec(spec_url, headers or None) + tools = convert_openapi_to_tool_specs(spec) + return {"ok": True, "tools": tools} + + except Exception as e: + return JSONResponse({"ok": False, "message": str(e)}, 400) diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index fa699c7..705b250 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -26,7 +26,7 @@ from cptr.utils.ai import ( ) from cptr.utils.config import _get_jwt_secret, now_ms from cptr.utils.crypto import decrypt_key -from cptr.utils.tools import TOOLS, execute_tool, get_tool_list, _fn_to_schema, create_artifact +from cptr.utils.tools import ALL_TOOLS, execute_tool, get_tool_list, _fn_to_schema, create_artifact from cptr.utils.chat_export import export_chat_to_file from cptr.utils.json_parser import extract_json @@ -891,7 +891,7 @@ async def run_chat_task( # Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache) plan_mode = chat_params.get("plan_mode", False) if plan_mode: - tools = [t for t in tools if TOOLS.get(t["name"], {}).get("auto")] + tools = [t for t in tools if ALL_TOOLS.get(t["name"], {}).get("auto")] # Inject create_artifact (only available in plan mode) tools.append(_fn_to_schema("create_artifact", create_artifact)) messages.append({"role": "user", "content": PLAN_MODE_PROMPT}) @@ -1037,7 +1037,7 @@ async def run_chat_task( flushed_item = _flush_text() name = event["name"] - tool = TOOLS.get(name) + tool = ALL_TOOLS.get(name) item = { "type": "function_call", "id": str(uuid.uuid4()), diff --git a/cptr/utils/mcp/__init__.py b/cptr/utils/mcp/__init__.py new file mode 100644 index 0000000..aaa1082 --- /dev/null +++ b/cptr/utils/mcp/__init__.py @@ -0,0 +1 @@ +# MCP client utilities diff --git a/cptr/utils/mcp/client.py b/cptr/utils/mcp/client.py new file mode 100644 index 0000000..4df3b52 --- /dev/null +++ b/cptr/utils/mcp/client.py @@ -0,0 +1,147 @@ +"""MCP (Model Context Protocol) client for Streamable HTTP transport. + +Wraps the `mcp` library's ClientSession to provide a simple interface +for connecting to MCP servers, listing tools, and calling tools. + +Usage:: + + client = MCPClient() + await client.connect("https://mcp.example.com/sse", headers={"Authorization": "Bearer ..."}) + specs = await client.list_tool_specs() + result = await client.call_tool("my_tool", {"arg": "value"}) + await client.disconnect() +""" + +from __future__ import annotations + +import asyncio +import logging +from contextlib import AsyncExitStack + +import anyio +from mcp import ClientSession +from mcp.client.streamable_http import streamablehttp_client +from mcp.types import CallToolResult + +logger = logging.getLogger(__name__) + +_INIT_TIMEOUT = 30 # seconds + + +class MCPClient: + """Manages a single MCP server connection over Streamable HTTP.""" + + def __init__(self): + self.session: ClientSession | None = None + self._exit_stack: AsyncExitStack | None = None + + async def connect(self, url: str, headers: dict | None = None) -> None: + """Connect to an MCP server. + + Args: + url: The server's Streamable HTTP endpoint URL. + headers: Optional HTTP headers (e.g. Authorization). + """ + async with AsyncExitStack() as exit_stack: + try: + transport = await exit_stack.enter_async_context( + streamablehttp_client(url=url, headers=headers) + ) + read, write, _ = transport + + self.session = await exit_stack.enter_async_context( + ClientSession(read_stream=read, write_stream=write) + ) + + with anyio.fail_after(_INIT_TIMEOUT): + await self.session.initialize() + + # Transfer ownership — prevent exit_stack.__aexit__ from + # tearing everything down when we leave this block. + self._exit_stack = exit_stack.pop_all() + logger.info("[mcp] Connected to %s", url) + except Exception: + await asyncio.shield(self.disconnect()) + raise + + async def list_tool_specs(self) -> list[dict]: + """List tools from the connected server as OpenAI-compatible schemas. + + Returns a list of dicts, each with: name, description, parameters. + """ + if not self.session: + raise RuntimeError("MCPClient is not connected") + + result = await self.session.list_tools() + specs = [] + + for tool in result.tools: + spec = { + "name": tool.name, + "description": tool.description or "", + "parameters": { + "type": "object", + "properties": {}, + "required": [], + }, + } + + if tool.inputSchema: + schema = tool.inputSchema + spec["parameters"]["properties"] = schema.get("properties", {}) + spec["parameters"]["required"] = schema.get("required", []) + + specs.append(spec) + + return specs + + async def call_tool(self, name: str, function_args: dict | None = None) -> list: + """Call a tool on the connected server. + + Args: + name: The tool name. + function_args: Arguments to pass to the tool. + + Returns: + A list of content items from the tool result. + + Raises: + RuntimeError: If the tool returns an error result. + """ + if not self.session: + raise RuntimeError("MCPClient is not connected") + + result: CallToolResult = await self.session.call_tool( + name, arguments=function_args or {} + ) + + content = [item.model_dump() for item in result.content] + + if result.isError: + raise RuntimeError(f"MCP tool error: {content}") + + return content + + async def disconnect(self) -> None: + """Disconnect from the MCP server. Idempotent. + + IMPORTANT: Do NOT use asyncio.shield() or anyio.CancelScope here. + The MCP SDK requires its TaskGroup to be exited in the same task + that created it. Simply call aclose() directly. + """ + exit_stack = self._exit_stack + if exit_stack is None: + return + + # Prevent double-close from concurrent callers + self._exit_stack = None + self.session = None + + try: + await exit_stack.aclose() + except TimeoutError: + logger.warning("[mcp] disconnect timed out") + except RuntimeError as exc: + logger.debug("[mcp] disconnect suppressed RuntimeError: %s", exc) + except Exception: + logger.debug("[mcp] Error during disconnect", exc_info=True) diff --git a/cptr/utils/openapi.py b/cptr/utils/openapi.py new file mode 100644 index 0000000..faa8725 --- /dev/null +++ b/cptr/utils/openapi.py @@ -0,0 +1,311 @@ +"""OpenAPI tool server client. + +Handles fetching OpenAPI specs, converting them to LLM-compatible tool schemas, +and executing tool calls against OpenAPI servers. +""" + +from __future__ import annotations + +import copy +import json +import logging +from typing import Any + +import httpx + +logger = logging.getLogger(__name__) + +# Valid HTTP methods per OpenAPI 3.x +_HTTP_METHODS = {"get", "put", "post", "delete", "options", "head", "patch", "trace"} + +_TIMEOUT = 15 # seconds + + +# ── Spec fetching ─────────────────────────────────────────── + + +async def fetch_openapi_spec( + url: str, headers: dict | None = None, timeout: float = _TIMEOUT +) -> dict: + """Fetch and parse an OpenAPI spec from a URL. + + Supports JSON and YAML (if PyYAML is installed). Falls back to YAML + parsing for non-JSON content. + + Args: + url: Full URL to the OpenAPI spec endpoint. + headers: Optional HTTP headers (e.g. Authorization). + timeout: Request timeout in seconds. + + Returns: + The parsed OpenAPI spec as a dict. + """ + _headers = {"Accept": "application/json"} + if headers: + _headers.update(headers) + + async with httpx.AsyncClient(timeout=timeout, verify=True) as client: + resp = await client.get(url, headers=_headers) + resp.raise_for_status() + + text = resp.text + if url.lower().endswith((".yaml", ".yml")): + import yaml + + return yaml.safe_load(text) + + try: + return json.loads(text) + except json.JSONDecodeError: + # Fallback to YAML for non-.yml URLs that aren't valid JSON + import yaml + + return yaml.safe_load(text) + + +# ── Schema conversion ────────────────────────────────────── + + +def _resolve_schema( + schema: dict, components: dict, resolved: set | None = None +) -> dict: + """Recursively resolve $ref references in a JSON schema.""" + if not schema: + return {} + + if resolved is None: + resolved = set() + + if "$ref" in schema: + ref_path = schema["$ref"] + schema_name = ref_path.split("/")[-1] + + if schema_name in resolved: + return {} # Avoid infinite recursion + + resolved.add(schema_name) + + ref_parts = ref_path.strip("#/").split("/") + target = components + for part in ref_parts[1:]: # Skip 'components' + target = target.get(part, {}) + return _resolve_schema(target, components, resolved) + + result = copy.deepcopy(schema) + + if "properties" in result: + for prop, prop_schema in result["properties"].items(): + result["properties"][prop] = _resolve_schema(prop_schema, components) + + if "items" in result: + result["items"] = _resolve_schema(result["items"], components) + + for keyword in ("oneOf", "anyOf", "allOf"): + if keyword in result and isinstance(result[keyword], list): + result[keyword] = [ + _resolve_schema(inner, components, resolved) for inner in result[keyword] + ] + + return result + + +def convert_openapi_to_tool_specs(openapi_spec: dict) -> list[dict]: + """Convert an OpenAPI specification into tool schemas for the LLM. + + Each operation with an ``operationId`` becomes a tool. Parameters and + request body properties are flattened into a single ``parameters`` object. + + Args: + openapi_spec: The parsed OpenAPI spec dict. + + Returns: + A list of tool spec dicts with name, description, and parameters. + """ + specs = [] + components = openapi_spec.get("components", {}) + + for path, methods in openapi_spec.get("paths", {}).items(): + if not isinstance(methods, dict): + continue + + path_params = methods.get("parameters", []) + if not isinstance(path_params, list): + path_params = [] + + for method, operation in methods.items(): + if method not in _HTTP_METHODS: + continue + if not isinstance(operation, dict): + continue + if not operation.get("operationId"): + continue + + tool = { + "name": operation["operationId"], + "description": operation.get( + "description", operation.get("summary", "No description available.") + ), + "parameters": {"type": "object", "properties": {}, "required": []}, + } + + # Merge path-level and operation-level params + op_params = operation.get("parameters", []) + if not isinstance(op_params, list): + op_params = [] + + merged = {} + for param in path_params: + if isinstance(param, dict) and param.get("name"): + merged[(param["name"], param.get("in", ""))] = param + for param in op_params: + if isinstance(param, dict) and param.get("name"): + merged[(param["name"], param.get("in", ""))] = param + + for param in merged.values(): + pname = param.get("name") + if not pname: + continue + pschema = param.get("schema", {}) + desc = pschema.get("description", "") or param.get("description", "") + if pschema.get("enum") and isinstance(pschema["enum"], list): + desc += f'. Possible values: {", ".join(str(v) for v in pschema["enum"])}' + + prop = { + "type": pschema.get("type") or "string", + "description": desc, + } + if pschema.get("type") == "array" and "items" in pschema: + prop["items"] = pschema["items"] + + prop = {k: v for k, v in prop.items() if v is not None} + tool["parameters"]["properties"][pname] = prop + if param.get("required"): + tool["parameters"]["required"].append(pname) + + # Extract requestBody + request_body = operation.get("requestBody") + if request_body: + content = request_body.get("content", {}) + json_schema = content.get("application/json", {}).get("schema") + if json_schema: + resolved = _resolve_schema(json_schema, components) + if resolved.get("properties"): + tool["parameters"]["properties"].update(resolved["properties"]) + if "required" in resolved: + tool["parameters"]["required"] = list( + set(tool["parameters"]["required"] + resolved["required"]) + ) + elif resolved.get("type") == "array": + tool["parameters"] = resolved + + specs.append(tool) + + return specs + + +# ── Tool execution ────────────────────────────────────────── + + +async def execute_openapi_tool( + server_url: str, + openapi_spec: dict, + tool_name: str, + args: dict, + headers: dict | None = None, + timeout: float = 60, +) -> str: + """Execute a tool call against an OpenAPI server. + + Resolves the route by operationId, separates path/query/body params, + and makes the appropriate HTTP request. + + Args: + server_url: Base URL of the OpenAPI server. + openapi_spec: The full parsed OpenAPI spec. + tool_name: The operationId to call. + args: Arguments from the LLM tool call. + headers: Optional HTTP headers. + timeout: Request timeout in seconds. + + Returns: + The response body as a string (JSON-serialized if structured). + """ + paths = openapi_spec.get("paths", {}) + + # Find matching route + route_path = None + http_method = None + operation = None + + for rpath, methods in paths.items(): + if not isinstance(methods, dict): + continue + for method, op in methods.items(): + if method not in _HTTP_METHODS: + continue + if isinstance(op, dict) and op.get("operationId") == tool_name: + route_path = rpath + http_method = method + operation = op + break + if route_path: + break + + if not route_path or not operation: + return json.dumps({"error": f"Operation '{tool_name}' not found in OpenAPI spec"}) + + # Classify parameters + path_params = {} + query_params = {} + body_params = dict(args) + + all_params = (operation.get("parameters") or []) + ( + paths.get(route_path, {}).get("parameters") or [] + ) + + for param in all_params: + pname = param.get("name", "") + pin = param.get("in", "") + if pname in body_params: + if pin == "path": + path_params[pname] = body_params.pop(pname) + elif pin == "query": + query_params[pname] = body_params.pop(pname) + elif pin == "header": + body_params.pop(pname) # skip header params for now + + # Build URL with path params + url = server_url.rstrip("/") + route_path + for pname, pval in path_params.items(): + url = url.replace(f"{{{pname}}}", str(pval)) + + _headers = {"Content-Type": "application/json"} + if headers: + _headers.update(headers) + + try: + async with httpx.AsyncClient(timeout=timeout, verify=True) as client: + if http_method in ("get", "head", "options"): + resp = await client.request( + http_method.upper(), url, headers=_headers, params=query_params + ) + else: + resp = await client.request( + http_method.upper(), + url, + headers=_headers, + params=query_params, + json=body_params if body_params else None, + ) + + # Try to parse as JSON + try: + data = resp.json() + return json.dumps(data, indent=2, ensure_ascii=False) + except Exception: + return resp.text + + except httpx.TimeoutException: + return json.dumps({"error": f"Request to {url} timed out after {timeout}s"}) + except Exception as e: + return json.dumps({"error": str(e)}) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 7ca14c1..4cb05f2 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -1198,7 +1198,7 @@ TOOLS: dict[str, dict] = { "delete_automation": {"fn": delete_automation, "auto": False}, } -# Browser tools — registered conditionally based on browser.enabled config +# Browser tools — conditionally included in schemas based on browser.enabled BROWSER_TOOLS: dict[str, dict] = { "browser_navigate": {"fn": browser_navigate, "auto": False}, "browser_snapshot": {"fn": browser_snapshot, "auto": True}, @@ -1208,6 +1208,157 @@ BROWSER_TOOLS: dict[str, dict] = { "browser_evaluate": {"fn": browser_evaluate, "auto": False}, } +# Combined lookup for execution and approval (always available regardless of config) +ALL_TOOLS: dict[str, dict] = {**TOOLS, **BROWSER_TOOLS} + + +# ── External tool servers ─────────────────────────────────── + +_tool_server_cache: dict | None = None # {"servers": [...], "tools": {name: {server, spec}}} + + +async def _load_tool_servers() -> dict: + """Load and cache external tool server config + specs. + + Returns a dict with 'servers' (raw config list) and 'tools' mapping + prefixed tool names to {server, spec, type}. + """ + global _tool_server_cache + if _tool_server_cache is not None: + return _tool_server_cache + + from cptr.models import Config + + servers = await Config.get("tool_servers") or [] + tools: dict[str, dict] = {} + + for server in servers: + if not server.get("enabled", True): + continue + + server_id = server.get("id", "") + server_type = server.get("type", "openapi") + + try: + if server_type == "openapi": + from cptr.utils.openapi import fetch_openapi_spec, convert_openapi_to_tool_specs + + url = server.get("url", "").rstrip("/") + path = server.get("path", "openapi.json") + if path.startswith("http"): + spec_url = path + else: + spec_url = f"{url}/{path.lstrip('/')}" + + headers = _build_server_headers(server) + openapi_spec = await fetch_openapi_spec(spec_url, headers) + server["_openapi_spec"] = openapi_spec + + for spec in convert_openapi_to_tool_specs(openapi_spec): + prefixed = f"{server_id}_{spec['name']}" + tools[prefixed] = { + "server": server, + "spec": {**spec, "name": prefixed}, + "original_name": spec["name"], + "type": "openapi", + } + + elif server_type == "mcp": + from cptr.utils.mcp.client import MCPClient + + client = MCPClient() + headers = _build_server_headers(server) + await client.connect(server.get("url", ""), headers) + + for spec in await client.list_tool_specs(): + prefixed = f"{server_id}_{spec['name']}" + tools[prefixed] = { + "server": server, + "spec": {**spec, "name": prefixed}, + "original_name": spec["name"], + "type": "mcp", + } + + await client.disconnect() + + except Exception: + import logging + + logging.getLogger(__name__).warning( + "Failed to load tool server '%s'", server_id, exc_info=True + ) + + _tool_server_cache = {"servers": servers, "tools": tools} + return _tool_server_cache + + +def invalidate_tool_server_cache() -> None: + """Clear the external tool server cache, forcing a reload on next access.""" + global _tool_server_cache + _tool_server_cache = None + + +def _build_server_headers(server: dict) -> dict | None: + """Build auth + custom headers for a tool server connection.""" + headers = dict(server.get("headers") or {}) + auth_type = server.get("auth_type", "bearer") + if auth_type == "bearer": + key = server.get("key", "") + if key: + headers["Authorization"] = f"Bearer {key}" + return headers or None + + +async def _execute_external_tool(name: str, args: dict) -> str: + """Execute an external tool by its prefixed name ({server_id}_{tool_name}).""" + cache = await _load_tool_servers() + tool_info = cache["tools"].get(name) + if not tool_info: + return f"Error: external tool '{name}' not found" + + server = tool_info["server"] + original_name = tool_info["original_name"] + tool_type = tool_info["type"] + headers = _build_server_headers(server) + + try: + if tool_type == "mcp": + from cptr.utils.mcp.client import MCPClient + + client = MCPClient() + await client.connect(server.get("url", ""), headers) + try: + result = await client.call_tool(original_name, args) + # MCP returns a list of content items; extract text + texts = [] + for item in result: + if isinstance(item, dict): + if item.get("type") == "text": + texts.append(item.get("text", "")) + else: + texts.append(json.dumps(item)) + return "\n".join(texts) if texts else "(no output)" + finally: + await client.disconnect() + + elif tool_type == "openapi": + from cptr.utils.openapi import execute_openapi_tool + + openapi_spec = server.get("_openapi_spec", {}) + return await execute_openapi_tool( + server_url=server.get("url", "").rstrip("/"), + openapi_spec=openapi_spec, + tool_name=original_name, + args=args, + headers=headers, + ) + + else: + return f"Error: unknown tool server type: {tool_type}" + + except Exception as e: + return f"Error executing external tool '{name}': {e}" + # ── Schema from function signature ────────────────────────── @@ -1264,7 +1415,8 @@ def _fn_to_schema(name: str, fn) -> dict: async def get_tool_list() -> list[dict]: """Return tool schemas for the LLM. - Automatically includes browser tools when browser.enabled is true in config. + Automatically includes browser tools when browser.enabled is true, + and external tool server tools when configured. """ tools = dict(TOOLS) try: @@ -1274,21 +1426,38 @@ async def get_tool_list() -> list[dict]: tools.update(BROWSER_TOOLS) except Exception: pass - return [_fn_to_schema(name, t["fn"]) for name, t in tools.items()] + + schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()] + + # Add external tool server schemas + try: + cache = await _load_tool_servers() + for tool_info in cache["tools"].values(): + schemas.append(tool_info["spec"]) + except Exception: + pass + + return schemas async def execute_tool(name: str, args: dict, __context__: dict) -> str: """Execute a tool by name, injecting execution context.""" - info = TOOLS.get(name) or BROWSER_TOOLS.get(name) - if not info: - return f"Error: unknown tool: {name}" - fn = info["fn"] - try: - sig = inspect.signature(fn) - if "__context__" in sig.parameters: - return await fn(**args, __context__=__context__) - else: - # Legacy tools: inject workspace directly - return await fn(**args, workspace=__context__["workspace"]) - except Exception as e: - return f"Error executing {name}: {e}" + info = ALL_TOOLS.get(name) + if info: + fn = info["fn"] + try: + sig = inspect.signature(fn) + if "__context__" in sig.parameters: + return await fn(**args, __context__=__context__) + else: + # Legacy tools: inject workspace directly + return await fn(**args, workspace=__context__["workspace"]) + except Exception as e: + return f"Error executing {name}: {e}" + + # Check external tool servers + cache = await _load_tool_servers() + if name in cache["tools"]: + return await _execute_external_tool(name, args) + + return f"Error: unknown tool: {name}" diff --git a/pyproject.toml b/pyproject.toml index bda26ce..d7a9e10 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dependencies = [ [project.optional-dependencies] pam = ["python-pam>=2.0"] +mcp = ["mcp>=1.8"] [dependency-groups] dev = [