diff --git a/pyproject.toml b/pyproject.toml index 21b682d6..09a708f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,7 @@ dependencies = [ ] [project.optional-dependencies] -extensibility = ["a2a-sdk>=0.2.0,<2"] +extensibility = ["a2a-sdk>=0.2.0,<1.0"] starlette = ["starlette>=0.40.0,<1"] fastapi = ["fastapi>=0.100.0,<1"] aiohttp = ["aiohttp>=3.9.0,<4"] @@ -76,7 +76,7 @@ dev = [ "sqlalchemy>=2.0.0", "django>=4.0", "flask>=3.0", - "a2a-sdk>=0.2.0", + "a2a-sdk>=0.2.0,<1.0", "langchain-core>=1.2.7", "langgraph>=0.2.0", "langchain-community>=0.3.0", diff --git a/src/sap_cloud_sdk/extensibility/_models.py b/src/sap_cloud_sdk/extensibility/_models.py index 7780484a..50ca6041 100644 --- a/src/sap_cloud_sdk/extensibility/_models.py +++ b/src/sap_cloud_sdk/extensibility/_models.py @@ -236,12 +236,21 @@ class N8nWorkflowConfig: """n8n workflow configuration embedded in a hook. Attributes: - workflow_id: n8n workflow ID. + ord_id: ORD ID of the API resource for this workflow. + card_ord_id: MCP translation card ORD ID (per ADR-021). + tool_name: MCP tool name (apiName segment of ordId, per ADR-021). + global_tenant_id: Global tenant ID of the n8n workflow tenant (per ADR-022). method: HTTP method for the n8n webhook call. + workflow_id: n8n workflow ID. Retained for backward compatibility; not + populated by the current backend (defaults to ""). """ - workflow_id: str + ord_id: str + card_ord_id: str + tool_name: str + global_tenant_id: str method: HTTPMethod + workflow_id: str = "" @classmethod def from_dict(cls, obj: Dict[str, Any]) -> N8nWorkflowConfig: @@ -250,7 +259,10 @@ def from_dict(cls, obj: Dict[str, Any]) -> N8nWorkflowConfig: Expected JSON shape:: { - "workflowId": "unique_n8n_workflow_id", + "ordId": "sap.n8nwfrt:apiResource:invoice-po-solution_my-workflow.postInvoice:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:invoice-po-solution_my-workflow.postInvoice_mcp:v1", + "toolName": "postInvoice", + "globalTenantId": "tenant-abc", "method": "POST" } @@ -262,8 +274,12 @@ def from_dict(cls, obj: Dict[str, Any]) -> N8nWorkflowConfig: """ method = _parse_http_method(obj.get("method", "POST")) or HTTPMethod.POST return cls( - workflow_id=obj.get("workflowId", ""), + ord_id=obj.get("ordId", ""), + card_ord_id=obj.get("cardOrdId", ""), + tool_name=obj.get("toolName", ""), + global_tenant_id=obj.get("globalTenantId", ""), method=method, + workflow_id=obj.get("workflowId", ""), ) @@ -338,7 +354,10 @@ def from_dict(cls, obj: Dict[str, Any]) -> Hook: "order": 1, "canShortCircuit": true, "n8nWorkflowConfig": { - "workflowId": "unique_n8n_workflow_id", + "ordId": "sap.n8nwfrt:apiResource:invoice-po-solution_my-workflow.postInvoice:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:invoice-po-solution_my-workflow.postInvoice_mcp:v1", + "toolName": "postInvoice", + "globalTenantId": "tenant-abc", "method": "POST" } } @@ -698,7 +717,10 @@ def from_dict(cls, obj: Dict[str, Any]) -> ExtensionCapabilityImplementation: "order": 1, "canShortCircuit": true, "n8nWorkflowConfig": { - "workflowId": "unique_n8n_workflow_id", + "ordId": "sap.n8nwfrt:apiResource:invoice-po-solution_my-workflow.postInvoice:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:invoice-po-solution_my-workflow.postInvoice_mcp:v1", + "toolName": "postInvoice", + "globalTenantId": "tenant-abc", "method": "POST" } } diff --git a/src/sap_cloud_sdk/extensibility/_ums_transport.py b/src/sap_cloud_sdk/extensibility/_ums_transport.py index 2573d4e0..0a9346f6 100644 --- a/src/sap_cloud_sdk/extensibility/_ums_transport.py +++ b/src/sap_cloud_sdk/extensibility/_ums_transport.py @@ -74,7 +74,7 @@ additions { type mcpConfig { globalTenantId ordId toolNames } } } hooks { id hookId type name onFailure timeout deploymentType canShortCircuit - n8nWorkflowConfig { workflowId method } + n8nWorkflowConfig { ordId cardOrdId toolName globalTenantId method } } } } @@ -280,10 +280,11 @@ def _build_hook(raw: Dict[str, Any]) -> Optional[Hook]: return None n8n_config = raw.get("n8nWorkflowConfig") or {} - workflow_id = n8n_config.get("workflowId", "") - if not workflow_id: + tool_name = n8n_config.get("toolName", "") + card_ord_id = n8n_config.get("cardOrdId", "") + if not tool_name or not card_ord_id: logger.warning( - "Skipping hook with missing workflowId (hookId=%s)", + "Skipping hook with missing toolName or cardOrdId (hookId=%s)", raw.get("hookId"), ) return None @@ -295,7 +296,13 @@ def _build_hook(raw: Dict[str, Any]) -> Optional[Hook]: return Hook( id=raw.get("id", ""), hook_id=raw.get("hookId", ""), - n8n_workflow_config=N8nWorkflowConfig(workflow_id=workflow_id, method=method), + n8n_workflow_config=N8nWorkflowConfig( + ord_id=n8n_config.get("ordId", ""), + card_ord_id=n8n_config.get("cardOrdId", ""), + tool_name=tool_name, + global_tenant_id=n8n_config.get("globalTenantId", ""), + method=method, + ), name=raw.get("name", ""), type=hook_type, deployment_type=deployment_type, diff --git a/src/sap_cloud_sdk/extensibility/client.py b/src/sap_cloud_sdk/extensibility/client.py index d6deda28..9f0e4b3a 100644 --- a/src/sap_cloud_sdk/extensibility/client.py +++ b/src/sap_cloud_sdk/extensibility/client.py @@ -2,11 +2,11 @@ from __future__ import annotations -import asyncio import itertools import json import logging import time +import warnings from typing import TYPE_CHECKING, Any, Optional, Union, cast import httpx @@ -40,7 +40,6 @@ _EXECUTE_WORKFLOW_TOOL_NAME = "execute_workflow" _GET_EXECUTION_TOOL_NAME = "get_execution" -_N8N_MCP_SERVER_NAME = "sap.btpn8n:apiResource:ManagedN8nMcpServer:v1" _JSONRPC_VERSION = "2.0" @@ -217,6 +216,7 @@ def get_extension_capability_implementation( @record_metrics( Module.EXTENSIBILITY, Operation.EXTENSIBILITY_CALL_HOOK, + deprecated=True, ) def call_hook( self, @@ -225,6 +225,11 @@ def call_hook( ) -> Optional[Message]: """Call a hook's MCP endpoint and poll until completion. + .. deprecated:: + Use :meth:`call_hook_agw` instead, which invokes the hook through + Agent Gateway (handles tenant resolution, user-token exchange, and + the per-hook MCP translation-card contract). + Executes the workflow via ``execute-workflow``, then polls ``get-execution`` every 500 ms until the execution succeeds, fails, or ``hook.timeout`` seconds elapse. @@ -264,6 +269,12 @@ def call_hook( ) ``` """ + warnings.warn( + "call_hook() is deprecated. Use call_hook_agw() instead, which " + "invokes the hook through Agent Gateway.", + DeprecationWarning, + stacklevel=2, + ) headers = {**_JSONRPC_HEADERS} inject(headers) @@ -398,76 +409,54 @@ def call_hook( ) async def _discover_n8n_tools( - self, agw_client: Any, user_token: Optional[str] - ) -> tuple[Any, Any]: + self, agw_client: Any, hook: Hook, user_token: Optional[str] + ) -> Any: tools = await agw_client.list_mcp_tools(user_token=user_token or None) - execute_tool = next( - ( - t - for t in tools - if t.name == _EXECUTE_WORKFLOW_TOOL_NAME - and t.server_name == _N8N_MCP_SERVER_NAME - ), - None, - ) - if execute_tool is None: - raise ExtensibilityError( - f"MCP tool '{_EXECUTE_WORKFLOW_TOOL_NAME}' on server '{_N8N_MCP_SERVER_NAME}' " - "not found via Agent Gateway." - ) - logger.info("Fetched n8n execute_tool: %s", _EXECUTE_WORKFLOW_TOOL_NAME) - - get_exec_tool = next( - ( - t - for t in tools - if t.name == _GET_EXECUTION_TOOL_NAME - and t.server_name == _N8N_MCP_SERVER_NAME - ), + tool_name = hook.n8n_workflow_config.tool_name + card_ord_id = hook.n8n_workflow_config.card_ord_id + + hook_tool = next( + (t for t in tools if t.name == tool_name and t.server_name == card_ord_id), None, ) - if get_exec_tool is None: + if hook_tool is None: raise ExtensibilityError( - f"MCP tool '{_GET_EXECUTION_TOOL_NAME}' on server '{_N8N_MCP_SERVER_NAME}' " + f"MCP tool '{tool_name}' on server '{card_ord_id}' " "not found via Agent Gateway." ) - logger.info("Fetched n8n get_exec_tool: %s", _GET_EXECUTION_TOOL_NAME) - - return execute_tool, get_exec_tool + logger.info("Discovered hook tool: name=%s server=%s", tool_name, card_ord_id) + return hook_tool async def _execute_workflow_via_agw( self, agw_client: Any, - execute_tool: Any, + hook_tool: Any, hook: Hook, user_token: Optional[str], message: Optional[Any], headers: Optional[dict], - ) -> tuple[str, Any]: - message_body = message.model_dump(mode="json") if message is not None else {} - execute_arguments = { - "workflowId": hook.n8n_workflow_config.workflow_id, - "inputs": { - "type": "webhook", - "webhookData": { - "method": hook.n8n_workflow_config.method, - "query": {}, - "body": message_body, - "headers": headers or {}, - }, - }, - } - logger.info("Executing workflow id=%s", hook.n8n_workflow_config.workflow_id) + ) -> Optional[Message]: + message_body = ( + message.model_dump(mode="json", exclude_none=True) + if message is not None + else {} + ) + tool_arguments = {"body": message_body} + logger.info( + "Calling hook tool=%s server=%s", + hook.n8n_workflow_config.tool_name, + hook.n8n_workflow_config.card_ord_id, + ) try: result_str = await agw_client.call_mcp_tool( - execute_tool, + hook_tool, user_token=user_token or None, - **execute_arguments, # type: ignore[arg-type] + **tool_arguments, # type: ignore[arg-type] ) except Exception as exc: raise TransportError( - f"AGW tool call for '{_EXECUTE_WORKFLOW_TOOL_NAME}' failed: {exc}" + f"AGW tool call for '{hook.n8n_workflow_config.tool_name}' failed: {exc}" ) from exc try: @@ -475,101 +464,16 @@ async def _execute_workflow_via_agw( except Exception as exc: raise TransportError(f"Could not parse hook response: {exc}") from exc - status = data.get("status", "") - if status in _EXECUTE_TERMINAL_STATUSES: - error_msg = data.get("error", "") - raise ExtensibilityError( - f"Workflow execution failed with status {status!r}" - + (f": {error_msg}" if error_msg else "") - ) - - execution_id = data.get("executionId") - logger.info( - "Workflow execution complete: execution_id=%s, status=%s", - execution_id, - status, - ) - return str(execution_id), status - - @staticmethod - def _extract_message(data: dict) -> Message: try: - result_data = data.get("data", {}).get("resultData", {}) - last_node = result_data.get("lastNodeExecuted", "") - response_json = ( - result_data.get("runData", {}) - .get(last_node, [{}])[0] - .get("data", {}) - .get("main", [[{}]])[0][0] - .get("json", {}) + structured = ( + data.get("structuredContent") or data.get("value") if data else None ) - return Message(**response_json) - except (KeyError, IndexError, TypeError, ValidationError) as exc: - raise TransportError( - f"Failed to extract response from last executed node: {exc}" + return Message(**structured) if structured else None + except (TypeError, ValidationError) as exc: + raise ExtensibilityError( + f"Hook response did not conform to the A2A Message protocol: {exc}" ) from exc - async def _poll_hook_execution( - self, - agw_client: Any, - get_exec_tool: Any, - hook: Hook, - execution_id: str, - user_token: Optional[str], - initial_status: str, - ) -> Optional[Message]: - deadline = time.monotonic() + hook.timeout - last_status = initial_status - logger.info( - "Polling for workflow %s execution result (timeout=%ss)", - hook.n8n_workflow_config.workflow_id, - hook.timeout, - ) - - while time.monotonic() < deadline: - await asyncio.sleep(_HOOK_POLL_INTERVAL) - - try: - get_execution_arguments = { - "workflowId": hook.n8n_workflow_config.workflow_id, - "executionId": execution_id, - "includeData": True, - } - result_str = await agw_client.call_mcp_tool( - get_exec_tool, - user_token=user_token or None, - **get_execution_arguments, # type: ignore[arg-type] - ) - except Exception as exc: - raise TransportError( - f"AGW tool call for '{_GET_EXECUTION_TOOL_NAME}' failed: {exc}" - ) from exc - - try: - data = json.loads(result_str) - except Exception as exc: - raise TransportError(f"Could not parse hook response: {exc}") from exc - - last_status = data.get("execution", {}).get("status", "") or data.get( - "status", "" - ) - - if last_status == "success": - logger.info("Execution %s completed successfully", execution_id) - return self._extract_message(data) - - if last_status in _EXECUTION_TERMINAL_STATUSES: - error_msg = data.get("error", "") - raise ExtensibilityError( - f"Workflow execution failed with status {last_status!r}" - + (f": {error_msg}" if error_msg else "") - ) - - raise ExtensibilityError( - f"Workflow execution timed out after {hook.timeout}s. " - f"Last status: {last_status!r}" - ) - @record_metrics( Module.EXTENSIBILITY, Operation.EXTENSIBILITY_CALL_HOOK, @@ -584,16 +488,16 @@ async def call_hook_agw( ) -> Optional[Message]: """Call a hook via Agent Gateway MCP tool invocation. - Discovers the N8N MCP tools via Agent Gateway, executes the workflow via - ``execute_workflow``, then polls ``get_execution`` every 500 ms until the - execution succeeds, fails, or ``hook.timeout`` seconds elapse. + Discovers the hook's MCP tool via Agent Gateway by matching ``tool_name`` + and ``card_ord_id`` from the hook config, then calls it and returns + the result. Auth and endpoint resolution are handled internally by an AGW client created from ``tenant_subdomain`` — no manual token or URL configuration is required. Args: - hook: Hook configuration (workflow ID, method, timeout). + hook: Hook configuration (tool name, card ORD ID, method, timeout). user_token: Optional user token forwarded to the Agent Gateway client for MCP tool discovery and invocation. message: Optional A2A ``Message`` payload serialised into the webhook @@ -604,12 +508,12 @@ async def call_hook_agw( Gateway client. Pass ``None`` to use the default subdomain. Returns: - Parsed ``Message`` from the last executed workflow node, or ``None`` + Parsed ``Message`` from the hook tool response, or ``None`` if the hook completed successfully but produced no message. Raises: - TransportError: On AGW tool call errors, terminal execution failures, - or timeout. + TransportError: On AGW tool call errors or unparseable responses. + ExtensibilityError: When the hook tool is not found via Agent Gateway. Example: ```python @@ -633,18 +537,8 @@ async def call_hook_agw( logger.info( "AGW client created successfully for tenant_subdomain=%s", tenant_subdomain ) - execute_tool, get_exec_tool = await self._discover_n8n_tools( - agw_client, user_token - ) - logger.info("Discovered n8n tools") - execution_id, status = await self._execute_workflow_via_agw( - agw_client, execute_tool, hook, user_token, message, headers - ) - logger.info( - "Workflow triggered: execution_id=%s, initial_status=%s", - execution_id, - status, - ) - return await self._poll_hook_execution( - agw_client, get_exec_tool, hook, execution_id, user_token, status + hook_tool = await self._discover_n8n_tools(agw_client, hook, user_token) + logger.info("Discovered n8n workflow tool") + return await self._execute_workflow_via_agw( + agw_client, hook_tool, hook, user_token, message, headers ) diff --git a/src/sap_cloud_sdk/extensibility/local_extensibility_example.json b/src/sap_cloud_sdk/extensibility/local_extensibility_example.json index 77b9120e..7141d726 100644 --- a/src/sap_cloud_sdk/extensibility/local_extensibility_example.json +++ b/src/sap_cloud_sdk/extensibility/local_extensibility_example.json @@ -19,7 +19,10 @@ "hookType": "BEFORE", "deploymentType": "N8N", "n8nWorkflowConfig": { - "workflowId": "wf-currency-conversion-001", + "ordId": "sap.n8nwfrt:apiResource:invoice-po-solution_currency-conversion.convertCurrency:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:invoice-po-solution_currency-conversion.convertCurrency_mcp:v1", + "toolName": "convertCurrency", + "globalTenantId": "tenant-example-001", "method": "POST" }, "timeout": 30, @@ -35,7 +38,10 @@ "hookType": "AFTER", "deploymentType": "N8N", "n8nWorkflowConfig": { - "workflowId": "wf-trigger-email-notification-001", + "ordId": "sap.n8nwfrt:apiResource:invoice-po-solution_notify.sendEmailNotification:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:invoice-po-solution_notify.sendEmailNotification_mcp:v1", + "toolName": "sendEmailNotification", + "globalTenantId": "tenant-example-001", "method": "POST" }, "timeout": 30, diff --git a/src/sap_cloud_sdk/extensibility/user-guide.md b/src/sap_cloud_sdk/extensibility/user-guide.md index 4baa74fd..5c43c173 100644 --- a/src/sap_cloud_sdk/extensibility/user-guide.md +++ b/src/sap_cloud_sdk/extensibility/user-guide.md @@ -61,7 +61,7 @@ for server in ext.mcp_servers: print("Approved tools:", server.tool_names) for hook in ext.hooks: - print(hook.id, hook.n8n_workflow_config.workflow_id) + print(hook.id, hook.n8n_workflow_config.tool_name) if ext.instruction: print("Extension instruction:", ext.instruction) @@ -97,7 +97,7 @@ agent_extensions = build_extension_capabilities(capabilities) - **MCP Server**: A Model Context Protocol server contributed by an extension. Each server has an ORD ID and an optional allowlist of approved tool names. -- **Hook**: A workflow to be executed before or after the agent execution. Each hook has a unique UUID `id`, a developer-facing `hook_id` (not guaranteed to be unique), and an `n8n_workflow_config` containing the workflow ID and HTTP method. Hook payloads and responses use the `Message` type from the `a2a.types` module for standardized agent-to-agent communication. +- **Hook**: A workflow to be executed before or after the agent execution. Each hook has a unique UUID `id`, a developer-facing `hook_id` (not guaranteed to be unique), and an `n8n_workflow_config` containing the ORD IDs, tool name, global tenant ID, and HTTP method that identify the hook's MCP server and tool. Hook payloads and responses use the `Message` type from the `a2a.types` module for standardized agent-to-agent communication. - **UMS (Unified Metadata Service)**: The SAP backend service that manages agent extensions. The module communicates with it via GraphQL over mTLS, using the BTP Destination Service for URL and credential resolution. @@ -161,7 +161,7 @@ def call_hook( - Raises `ExtensibilityError` if the workflow reaches a terminal failure status, times out, or n8n returns an application-level error. - The hook's `timeout` setting is used for the HTTP request timeout. - The hook HTTP method is taken from `hook.n8n_workflow_config.method`. -- The workflow ID is taken from `hook.n8n_workflow_config.workflow_id`. +- The workflow ID is taken from `hook.n8n_workflow_config.workflow_id` (legacy direct-HTTP path). ### `ExtensibilityClient.call_hook_agw()` @@ -185,15 +185,18 @@ async def call_hook_agw( - `tenant_subdomain`: Tenant subdomain used to instantiate the Agent Gateway client. Pass `None` to use the default subdomain. - Returns the response data as a `Message` object, or `None` if no message is produced. - Raises `TransportError` if the AGW tool call itself fails (network error, etc.). -- Raises `ExtensibilityError` if the n8n MCP tools are not found via AGW, the workflow reaches a terminal failure status, times out, or n8n returns an application-level error. +- Raises `ExtensibilityError` if the hook MCP tool is not found via AGW, or the hook response does not conform to the A2A Message protocol. #### `N8nWorkflowConfig` ```python @dataclass class N8nWorkflowConfig: - workflow_id: str # Workflow ID - method: HTTPMethod # HTTP method used by webhook execution + ord_id: str # ORD ID of the n8n API resource + card_ord_id: str # ORD ID of the n8n MCP translation card (server identifier) + tool_name: str # MCP tool name to call on the card server + global_tenant_id: str # LWT global tenant ID for the workflow + method: HTTPMethod # HTTP method used by webhook execution ``` #### `HookConfig` @@ -322,7 +325,7 @@ class Hook: type: HookType # Hook type (BEFORE, AFTER) deployment_type: DeploymentType # Deployment type (N8N, SERVERLESS) n8n_workflow_config: ( - N8nWorkflowConfig # Workflow config (workflow ID + HTTP method) + N8nWorkflowConfig # Workflow config (ORD IDs, tool name, global tenant ID, HTTP method) ) timeout: int # Timeout in seconds execution_mode: ExecutionMode # Execution mode (SYNC, ASYNC) @@ -582,7 +585,7 @@ The `HTTPMethod` enum ensures type safety: - `HTTPMethod.PATCH` - Partially update data - `HTTPMethod.DELETE` - Delete or cancel an operation -The workflow used for execution comes from `hook.n8n_workflow_config.workflow_id`. +The hook tool name and server come from `hook.n8n_workflow_config.tool_name` and `hook.n8n_workflow_config.card_ord_id`. #### Synchronous Hook Execution @@ -857,7 +860,10 @@ The JSON file uses the same schema as the extensibility backend response: "type": "BEFORE", "deploymentType": "N8N", "n8nWorkflowConfig": { - "workflowId": "wf-currency-conversion-001", + "ordId": "sap.n8nwfrt:apiResource:invoice-po-solution_currency-conversion.convertCurrency:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:invoice-po-solution_currency-conversion.convertCurrency_mcp:v1", + "toolName": "convertCurrency", + "globalTenantId": "tenant-example-001", "method": "POST" }, "timeout": 30, @@ -872,6 +878,15 @@ The JSON file uses the same schema as the extensibility backend response: See `src/sap_cloud_sdk/extensibility/local_extensibility_example.json` for a ready-to-use template. +## Multi-tenancy + +| Field | Value | +|---|---| +| **Supported** | Yes | +| **Authentication** | XSUAA / IAS (delegated to Agent Gateway) | +| **How to use** | Pass `tenant` (local tenant ID from the incoming JWT) to `get_extension_capability_implementation()` — it is used to filter extensions in the UMS GraphQL query and as a cache isolation key. For hook execution via `call_hook_agw()`, pass `tenant_subdomain` to scope the Agent Gateway client to the subscriber tenant, and `user_token` to forward the user's token for on-behalf-of flows. | +| **Further reading** | [Agent Gateway module](../agentgateway/user-guide.md) | + ## Notes - Create one `ExtensibilityClient` (via `create_client()`) and reuse it for multiple capability lookups where appropriate. diff --git a/tests/extensibility/unit/_ums_test_helpers.py b/tests/extensibility/unit/_ums_test_helpers.py index 2a91e4a0..1ba257a8 100644 --- a/tests/extensibility/unit/_ums_test_helpers.py +++ b/tests/extensibility/unit/_ums_test_helpers.py @@ -72,7 +72,10 @@ "deploymentType": "N8N", "canShortCircuit": False, "n8nWorkflowConfig": { - "workflowId": "wf-before-001", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": "POST", }, } @@ -149,7 +152,10 @@ "deploymentType": "N8N", "canShortCircuit": False, "n8nWorkflowConfig": { - "workflowId": "wf-after-001", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": "POST", }, } diff --git a/tests/extensibility/unit/test_client.py b/tests/extensibility/unit/test_client.py index 569ef73c..97f68532 100644 --- a/tests/extensibility/unit/test_client.py +++ b/tests/extensibility/unit/test_client.py @@ -10,7 +10,6 @@ ExtensibilityClient, _EXECUTE_WORKFLOW_TOOL_NAME, _GET_EXECUTION_TOOL_NAME, - _N8N_MCP_SERVER_NAME, ) from sap_cloud_sdk.extensibility._models import ( ExtensionCapabilityImplementation, @@ -28,6 +27,16 @@ from sap_cloud_sdk.agentgateway._models import MCPTool +# --------------------------------------------------------------------------- +# Shared constants for hook tool identity +# --------------------------------------------------------------------------- + +_TOOL_NAME = "convertCurrency" +_CARD_ORD_ID = "sap.n8nwfrt:apiResource:invoice-po-solution_currency-conversion.convertCurrency_mcp:v1" +_ORD_ID = "sap.n8nwfrt:apiResource:invoice-po-solution_currency-conversion.convertCurrency:v1" +_GLOBAL_TENANT_ID = "tenant-example-001" + + class TestCreateClient: """Tests for the create_client factory.""" @@ -102,7 +111,10 @@ def test_success(self): hook_id="agent_pre_hook", id="9f6e5f66-7e4f-4ef0-a9f6-e6e1c1220c11", n8n_workflow_config=N8nWorkflowConfig( - workflow_id="wf-pre-001", + ord_id=_ORD_ID, + card_ord_id=_CARD_ORD_ID, + tool_name=_TOOL_NAME, + global_tenant_id=_GLOBAL_TENANT_ID, method=HTTPMethod.POST, ), name="Before Agent Hook", @@ -118,7 +130,10 @@ def test_success(self): hook_id="agent_post_hook", id="6a9e0cef-eed6-4f1b-9f86-3d8e9f5c1d22", n8n_workflow_config=N8nWorkflowConfig( - workflow_id="wf-post-001", + ord_id=_ORD_ID, + card_ord_id=_CARD_ORD_ID, + tool_name=_TOOL_NAME, + global_tenant_id=_GLOBAL_TENANT_ID, method=HTTPMethod.POST, ), name="After Agent Hook", @@ -217,15 +232,22 @@ def test_error_logging(self): # --------------------------------------------------------------------------- -# Helpers shared across call_hook tests +# Helpers shared across call_hook_agw tests # --------------------------------------------------------------------------- -def _make_hook(workflow_id: str = "wf-001", timeout: int = 30) -> Hook: +def _make_hook( + tool_name: str = _TOOL_NAME, + card_ord_id: str = _CARD_ORD_ID, + timeout: int = 30, +) -> Hook: return Hook( hook_id="agent_pre_hook", id="9f6e5f66-7e4f-4ef0-a9f6-e6e1c1220c11", n8n_workflow_config=N8nWorkflowConfig( - workflow_id=workflow_id, + ord_id=_ORD_ID, + card_ord_id=card_ord_id, + tool_name=tool_name, + global_tenant_id=_GLOBAL_TENANT_ID, method=HTTPMethod.POST, ), name="Pre Hook", @@ -239,88 +261,39 @@ def _make_hook(workflow_id: str = "wf-001", timeout: int = 30) -> Hook: ) -def _make_n8n_tool(name: str) -> MCPTool: - """Return an MCPTool belonging to the N8N MCP server.""" +def _make_hook_tool( + tool_name: str = _TOOL_NAME, + card_ord_id: str = _CARD_ORD_ID, +) -> MCPTool: + """Return an MCPTool matching the hook's tool_name and card_ord_id.""" return MCPTool( - name=name, - server_name=_N8N_MCP_SERVER_NAME, + name=tool_name, + server_name=card_ord_id, description="", input_schema={}, - url="https://agw.example.com/v1/mcp/sap.btpn8n:apiResource:ManagedN8nMcpServer:v1/gtid-1", + url="https://agw.example.com/v1/mcp/sap.n8nwfrt.../gtid-1", ) -def _make_other_server_tool(name: str) -> MCPTool: - """Return an MCPTool with the same name but from a different MCP server.""" +def _make_other_server_tool(tool_name: str = _TOOL_NAME) -> MCPTool: + """Return an MCPTool with the same tool name but from a different MCP server.""" return MCPTool( - name=name, - server_name="sap.other:apiResource:OtherMcpServer:v1", + name=tool_name, + server_name="sap.other:apiResource:OtherServer:v1", description="", input_schema={}, url="https://agw.example.com/v1/mcp/other/gtid-2", ) -def _success_payload(workflow_id: str = "wf-001") -> str: - return json.dumps({ - "status": "success", - "data": { - "resultData": { - "lastNodeExecuted": "Respond to Webhook", - "runData": { - "Respond to Webhook": [ - { - "data": { - "main": [ - [ - { - "json": { - "message_id": "msg-1", - "context_id": "ctx-1", - "role": 2, - } - } - ] - ] - } - } - ] - }, - } - }, - }) - - -def _running_payload(execution_id: str = "exec-1") -> str: - return json.dumps({"status": "running", "executionId": execution_id}) - - -def _poll_success_payload() -> str: +def _success_payload() -> str: + """Full MCP tool result JSON; AGW puts the A2A Message in structuredContent.""" return json.dumps({ - "status": "success", - "data": { - "resultData": { - "lastNodeExecuted": "Respond to Webhook", - "runData": { - "Respond to Webhook": [ - { - "data": { - "main": [ - [ - { - "json": { - "message_id": "msg-2", - "context_id": "ctx-1", - "role": 2, - } - } - ] - ] - } - } - ] - }, - } + "content": [{"type": "text", "text": "Currency converted successfully."}], + "structuredContent": { + "messageId": "msg-1", + "role": "agent", + "parts": [{"kind": "text", "text": "Currency converted successfully."}], }, }) @@ -334,238 +307,118 @@ def _make_agw_client(tools: list, tool_responses: list) -> MagicMock: # --------------------------------------------------------------------------- -# Tests for ExtensibilityClient.call_hook +# Tests for ExtensibilityClient.call_hook_agw # --------------------------------------------------------------------------- -class TestCallHook: - """Tests for ExtensibilityClient.call_hook (async, AGW-based).""" +class TestCallHookAgw: + """Tests for ExtensibilityClient.call_hook_agw (AGW-based MCP invocation).""" - def _make_client(self, agw: MagicMock) -> ExtensibilityClient: - """Build an ExtensibilityClient with a mock transport and patched AGW factory.""" + def _make_client(self) -> ExtensibilityClient: return ExtensibilityClient(MagicMock()) @pytest.mark.asyncio - async def test_execute_tool_not_found_raises(self): - """Raises ExtensibilityError when execute_workflow tool is absent.""" + async def test_tool_not_found_raises(self): + """Raises ExtensibilityError when no tool matches tool_name + card_ord_id.""" agw = _make_agw_client(tools=[], tool_responses=[]) - client = self._make_client(agw) + client = self._make_client() with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, ): - with pytest.raises(ExtensibilityError, match=_EXECUTE_WORKFLOW_TOOL_NAME): + with pytest.raises(ExtensibilityError, match=_TOOL_NAME): await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") @pytest.mark.asyncio - async def test_get_exec_tool_not_found_raises(self): - """Raises ExtensibilityError when get_execution tool is absent.""" - tools = [_make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME)] - agw = _make_agw_client(tools=tools, tool_responses=[]) - client = self._make_client(agw) + async def test_wrong_server_does_not_match(self): + """A tool with the right name but wrong server_name must not match.""" + agw = _make_agw_client(tools=[_make_other_server_tool()], tool_responses=[]) + client = self._make_client() with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, ): - with pytest.raises(ExtensibilityError, match=_GET_EXECUTION_TOOL_NAME): + with pytest.raises(ExtensibilityError, match=_TOOL_NAME): await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") @pytest.mark.asyncio - async def test_composite_key_ignores_wrong_server(self): - """Tools from a different server with the same names must not match.""" - tools = [ - _make_other_server_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_other_server_tool(_GET_EXECUTION_TOOL_NAME), - ] - agw = _make_agw_client(tools=tools, tool_responses=[]) - client = self._make_client(agw) - with patch( - "sap_cloud_sdk.extensibility.client.create_agw_client", - return_value=agw, - ): - with pytest.raises(ExtensibilityError, match=_EXECUTE_WORKFLOW_TOOL_NAME): - await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") - - @pytest.mark.asyncio - async def test_composite_key_picks_correct_tool_among_duplicates(self): - """Picks the N8N tool when another server exposes identically-named tools.""" - tools = [ - _make_other_server_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_other_server_tool(_GET_EXECUTION_TOOL_NAME), - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - agw = _make_agw_client( - tools=tools, - tool_responses=[_running_payload(), _poll_success_payload()], - ) - client = self._make_client(agw) - with patch( - "sap_cloud_sdk.extensibility.client.create_agw_client", - return_value=agw, - ), patch( - "sap_cloud_sdk.extensibility.client.asyncio.sleep", - new_callable=AsyncMock, - ): - result = await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") - assert result is not None - # Both tool calls must have used the N8N server tools, not the other one - for call in agw.call_mcp_tool.call_args_list: - assert call[0][0].server_name == _N8N_MCP_SERVER_NAME - - @pytest.mark.asyncio - async def test_success_synchronous(self): - """Returns a Message when get_execution responds with status=success.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - agw = _make_agw_client( - tools=tools, - tool_responses=[_running_payload(), _poll_success_payload()], - ) - client = self._make_client(agw) + async def test_success_returns_message(self): + """Returns a Message on a successful single tool call.""" + agw = _make_agw_client(tools=[_make_hook_tool()], tool_responses=[_success_payload()]) + client = self._make_client() with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, - ), patch( - "sap_cloud_sdk.extensibility.client.asyncio.sleep", - new_callable=AsyncMock, ): result = await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") assert result is not None - assert result.message_id == "msg-2" - assert agw.call_mcp_tool.call_count == 2 + assert result.message_id == "msg-1" + assert agw.call_mcp_tool.call_count == 1 @pytest.mark.asyncio - async def test_success_after_polling(self): - """Returns a Message after one poll round via get_execution.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - agw = _make_agw_client( - tools=tools, - tool_responses=[_running_payload(), _poll_success_payload()], - ) - client = self._make_client(agw) + async def test_picks_correct_tool_among_duplicates(self): + """Picks the hook's card tool when another server exposes an identically-named tool.""" + tools = [_make_other_server_tool(), _make_hook_tool()] + agw = _make_agw_client(tools=tools, tool_responses=[_success_payload()]) + client = self._make_client() with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, - ), patch( - "sap_cloud_sdk.extensibility.client.asyncio.sleep", - new_callable=AsyncMock, ): result = await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") assert result is not None - assert result.message_id == "msg-2" - assert agw.call_mcp_tool.call_count == 2 - - @pytest.mark.asyncio - async def test_terminal_status_from_execute_raises(self): - """Raises ExtensibilityError on a terminal status from execute_workflow.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - terminal_payload = json.dumps({"status": "error", "error": "workflow crashed"}) - agw = _make_agw_client(tools=tools, tool_responses=[terminal_payload]) - client = self._make_client(agw) - with patch( - "sap_cloud_sdk.extensibility.client.create_agw_client", - return_value=agw, - ): - with pytest.raises(ExtensibilityError, match="workflow crashed"): - await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") + assert agw.call_mcp_tool.call_args[0][0].server_name == _CARD_ORD_ID @pytest.mark.asyncio - async def test_terminal_status_from_poll_raises(self): - """Raises ExtensibilityError on a terminal status from get_execution poll.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - poll_terminal = json.dumps({"status": "error", "error": "node failed"}) - agw = _make_agw_client( - tools=tools, - tool_responses=[_running_payload(), poll_terminal], - ) - client = self._make_client(agw) + async def test_agw_call_exception_raises_transport_error(self): + """Wraps call_mcp_tool exceptions in TransportError.""" + agw = MagicMock() + agw.list_mcp_tools = AsyncMock(return_value=[_make_hook_tool()]) + agw.call_mcp_tool = AsyncMock(side_effect=RuntimeError("network error")) + client = self._make_client() with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, - ), patch( - "sap_cloud_sdk.extensibility.client.asyncio.sleep", - new_callable=AsyncMock, ): - with pytest.raises(ExtensibilityError, match="node failed"): + with pytest.raises(TransportError, match="network error"): await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") @pytest.mark.asyncio - async def test_timeout_raises(self): - """Raises ExtensibilityError when deadline is exceeded without a success status.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - # Always returns "running" so the loop never exits via success/terminal - agw = _make_agw_client( - tools=tools, - tool_responses=[_running_payload()] + [_running_payload()] * 100, - ) - client = self._make_client(agw) - # Use a hook with timeout=0 so monotonic deadline is immediately exceeded - hook = _make_hook(timeout=0) + async def test_non_a2a_response_raises_extensibility_error(self): + """Raises ExtensibilityError when structuredContent is not a valid A2A Message.""" + bad_payload = json.dumps({"structuredContent": {"not": "a2a"}}) + agw = _make_agw_client(tools=[_make_hook_tool()], tool_responses=[bad_payload]) + client = self._make_client() with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, - ), patch( - "sap_cloud_sdk.extensibility.client.asyncio.sleep", - new_callable=AsyncMock, ): - with pytest.raises(ExtensibilityError, match="timed out"): - await client.call_hook_agw(hook=hook, tenant_subdomain="t") - - @pytest.mark.asyncio - async def test_agw_call_mcp_tool_exception_raises_transport_error(self): - """Wraps call_mcp_tool exceptions in TransportError.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - agw = MagicMock() - agw.list_mcp_tools = AsyncMock(return_value=tools) - agw.call_mcp_tool = AsyncMock(side_effect=RuntimeError("network error")) - client = self._make_client(agw) - with patch( - "sap_cloud_sdk.extensibility.client.create_agw_client", - return_value=agw, - ): - with pytest.raises(TransportError, match="network error"): + with pytest.raises(ExtensibilityError, match="A2A"): await client.call_hook_agw(hook=_make_hook(), tenant_subdomain="t") @pytest.mark.asyncio - async def test_workflow_id_passed_to_execute_tool(self): - """Verifies the correct workflowId is forwarded to call_mcp_tool.""" - tools = [ - _make_n8n_tool(_EXECUTE_WORKFLOW_TOOL_NAME), - _make_n8n_tool(_GET_EXECUTION_TOOL_NAME), - ] - agw = _make_agw_client( - tools=tools, - tool_responses=[_running_payload(), _poll_success_payload()], - ) - client = self._make_client(agw) + async def test_message_forwarded_as_body_to_tool(self): + """The A2A message is forwarded under 'body' (per the hook tool schema), not wrapped in 'inputs'.""" + agw = _make_agw_client(tools=[_make_hook_tool()], tool_responses=[_success_payload()]) + client = self._make_client() + message = MagicMock() + message.model_dump.return_value = { + "messageId": "msg-in-1", + "role": "user", + "parts": [{"kind": "text", "text": "hi"}], + } with patch( "sap_cloud_sdk.extensibility.client.create_agw_client", return_value=agw, - ), patch( - "sap_cloud_sdk.extensibility.client.asyncio.sleep", - new_callable=AsyncMock, ): await client.call_hook_agw( - hook=_make_hook(workflow_id="wf-xyz"), tenant_subdomain="t" + hook=_make_hook(), message=message, tenant_subdomain="t" ) - # First call is execute_workflow — check workflowId was forwarded correctly - first_call_kwargs = agw.call_mcp_tool.call_args_list[0][1] - assert first_call_kwargs["workflowId"] == "wf-xyz" + call_kwargs = agw.call_mcp_tool.call_args[1] + assert "inputs" not in call_kwargs + assert call_kwargs["body"] == { + "messageId": "msg-in-1", + "role": "user", + "parts": [{"kind": "text", "text": "hi"}], + } + message.model_dump.assert_called_once_with(mode="json", exclude_none=True) diff --git a/tests/extensibility/unit/test_local_transport.py b/tests/extensibility/unit/test_local_transport.py index 19bf5caa..f4433cb6 100644 --- a/tests/extensibility/unit/test_local_transport.py +++ b/tests/extensibility/unit/test_local_transport.py @@ -79,7 +79,7 @@ "name": "Before Tool Execution Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-before-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 30, "executionMode": "SYNC", "onFailure": "CONTINUE", @@ -108,7 +108,7 @@ "name": "Pre Execution Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-pre-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 20, "executionMode": "SYNC", "onFailure": "CONTINUE", @@ -137,7 +137,7 @@ "name": "Before Tool Execution Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-before-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 30, "executionMode": "SYNC", "onFailure": "BLOCK", @@ -150,7 +150,7 @@ "name": "After Tool Execution Hook", "hookType": "AFTER", "deploymentType": "SERVERLESS", - "n8nWorkflowConfig": {"workflowId": "wf-after-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 60, "executionMode": "ASYNC", "onFailure": "CONTINUE", @@ -163,7 +163,7 @@ "name": "Validation Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-validate-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 15, "executionMode": "SYNC", "onFailure": "BLOCK", @@ -203,7 +203,10 @@ def _make_hook( hook_id=hook_id, id=hook_uuid, n8n_workflow_config=N8nWorkflowConfig( - workflow_id=f"wf-{hook_id}", + ord_id="sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + card_ord_id="sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + tool_name="testHook", + global_tenant_id="tenant-test-001", method=HTTPMethod.POST, ), name=f"Test Hook {hook_id}", @@ -304,7 +307,7 @@ def test_reads_response_with_hooks(self, tmp_path: Path): hook = result.hooks[0] assert hook.hook_id == "before_tool_execution" assert hook.id == "9f6e5f66-7e4f-4ef0-a9f6-e6e1c1220c11" - assert hook.n8n_workflow_config.workflow_id == "wf-before-001" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.name == "Before Tool Execution Hook" assert hook.type == HookType.BEFORE assert hook.deployment_type == DeploymentType.N8N diff --git a/tests/extensibility/unit/test_models.py b/tests/extensibility/unit/test_models.py index b5156591..a99b1aa5 100644 --- a/tests/extensibility/unit/test_models.py +++ b/tests/extensibility/unit/test_models.py @@ -269,7 +269,7 @@ def test_from_dict_with_hooks(self): "name": "Before Tool Execution Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 30, "executionMode": "SYNC", "onFailure": "CONTINUE", @@ -286,7 +286,7 @@ def test_from_dict_with_hooks(self): assert hook.name == "Before Tool Execution Hook" assert hook.type == HookType.BEFORE assert hook.deployment_type == DeploymentType.N8N - assert hook.n8n_workflow_config.workflow_id == "wf-001" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.timeout == 30 assert hook.execution_mode == ExecutionMode.SYNC assert hook.on_failure == OnFailure.CONTINUE @@ -317,7 +317,7 @@ def test_from_dict_multiple_hooks(self): "name": "Before Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-before", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 30, "executionMode": "SYNC", "onFailure": "CONTINUE", @@ -330,7 +330,7 @@ def test_from_dict_multiple_hooks(self): "name": "After Hook", "hookType": "AFTER", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-after", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 60, "executionMode": "ASYNC", "onFailure": "BLOCK", @@ -387,7 +387,10 @@ def test_construction(self): hook_id="before_tool_execution", id="9f6e5f66-7e4f-4ef0-a9f6-e6e1c1220c11", n8n_workflow_config=N8nWorkflowConfig( - workflow_id="wf-001", + ord_id="sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + card_ord_id="sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + tool_name="testHook", + global_tenant_id="tenant-test-001", method=HTTPMethod.POST, ), name="Before Tool Execution Hook", @@ -401,7 +404,7 @@ def test_construction(self): ) assert hook.hook_id == "before_tool_execution" assert hook.id == "9f6e5f66-7e4f-4ef0-a9f6-e6e1c1220c11" - assert hook.n8n_workflow_config.workflow_id == "wf-001" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.n8n_workflow_config.method == HTTPMethod.POST assert hook.name == "Before Tool Execution Hook" assert hook.type == "BEFORE" @@ -420,7 +423,7 @@ def test_from_dict_complete(self): "name": "Before Tool Execution Hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 30, "executionMode": "SYNC", "onFailure": "CONTINUE", @@ -433,7 +436,7 @@ def test_from_dict_complete(self): assert hook.name == "Before Tool Execution Hook" assert hook.type == HookType.BEFORE assert hook.deployment_type == DeploymentType.N8N - assert hook.n8n_workflow_config.workflow_id == "wf-001" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.n8n_workflow_config.method == HTTPMethod.POST assert hook.timeout == 30 assert hook.execution_mode == ExecutionMode.SYNC @@ -453,11 +456,11 @@ def test_from_dict_partial_fields(self): "hookId": "partial_hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-partial", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } hook = Hook.from_dict(data) assert hook.hook_id == "partial_hook" - assert hook.n8n_workflow_config.workflow_id == "wf-partial" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.type == HookType.BEFORE assert hook.deployment_type == DeploymentType.N8N # Other fields should use defaults @@ -472,7 +475,7 @@ def test_from_dict_async_execution_mode(self): "name": "Async Hook", "hookType": "AFTER", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-async-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, "timeout": 60, "executionMode": "ASYNC", "onFailure": "BLOCK", @@ -492,7 +495,7 @@ def test_from_dict_different_deployment_types(self): "hookId": "n8n_hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-n8n", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } n8n_hook = Hook.from_dict(n8n_data) assert n8n_hook.deployment_type == DeploymentType.N8N @@ -502,7 +505,10 @@ def test_from_dict_different_deployment_types(self): "hookType": "AFTER", "deploymentType": "SERVERLESS", "n8nWorkflowConfig": { - "workflowId": "wf-serverless", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": "POST", }, } @@ -515,7 +521,7 @@ def test_from_dict_different_hook_types(self): "hookId": "before", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-before", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } before_hook = Hook.from_dict(before_data) assert before_hook.type == HookType.BEFORE @@ -524,7 +530,7 @@ def test_from_dict_different_hook_types(self): "hookId": "after", "hookType": "AFTER", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-after", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } after_hook = Hook.from_dict(after_data) assert after_hook.type == HookType.AFTER @@ -536,7 +542,7 @@ def test_from_dict_can_short_circuit_true(self): "hookType": "BEFORE", "deploymentType": "N8N", "canShortCircuit": True, - "n8nWorkflowConfig": {"workflowId": "wf-short", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } hook = Hook.from_dict(data) assert hook.can_short_circuit is True @@ -548,7 +554,7 @@ def test_from_dict_can_short_circuit_false(self): "hookType": "BEFORE", "deploymentType": "N8N", "canShortCircuit": False, - "n8nWorkflowConfig": {"workflowId": "wf-no-short", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } hook = Hook.from_dict(data) assert hook.can_short_circuit is False @@ -559,10 +565,10 @@ def test_from_dict_workflow_config_preserved(self): "hookId": "wf_hook", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-special-123", "method": "PUT"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "PUT"}, } hook = Hook.from_dict(data) - assert hook.n8n_workflow_config.workflow_id == "wf-special-123" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.n8n_workflow_config.method == HTTPMethod.PUT def test_from_dict_empty_string_values(self): @@ -573,7 +579,7 @@ def test_from_dict_empty_string_values(self): "name": "", "hookType": "", "deploymentType": "", - "n8nWorkflowConfig": {"workflowId": "", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } with pytest.raises(ValueError, match="Invalid or missing hookType"): Hook.from_dict(data) @@ -592,7 +598,10 @@ def test_from_dict_different_http_methods(self): "hookType": "BEFORE", "deploymentType": "N8N", "n8nWorkflowConfig": { - "workflowId": f"wf-{method_str.lower()}", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": method_str, }, } @@ -605,7 +614,7 @@ def test_from_dict_method_defaults_to_post(self): "hookId": "hook_without_method", "hookType": "BEFORE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-no-method"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001"}, } hook = Hook.from_dict(data) assert hook.n8n_workflow_config.method == HTTPMethod.POST @@ -616,7 +625,7 @@ def test_from_dict_invalid_hook_type_raises_error(self): "hookId": "invalid_hook", "hookType": "INVALID_TYPE", "deploymentType": "N8N", - "n8nWorkflowConfig": {"workflowId": "wf-invalid-type", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } with pytest.raises( ValueError, match="Invalid or missing hookType.*INVALID_TYPE" @@ -630,7 +639,10 @@ def test_from_dict_invalid_deployment_type_raises_error(self): "hookType": "BEFORE", "deploymentType": "INVALID_DEPLOYMENT", "n8nWorkflowConfig": { - "workflowId": "wf-invalid-deployment", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": "POST", }, } @@ -874,7 +886,10 @@ def test_from_dict_with_source_new_format(self): "hookType": "BEFORE", "deploymentType": "N8N", "n8nWorkflowConfig": { - "workflowId": "wf-before-001", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": "POST", }, "timeout": 30, diff --git a/tests/extensibility/unit/test_ums_parsing.py b/tests/extensibility/unit/test_ums_parsing.py index 09b2892a..77bc8df0 100644 --- a/tests/extensibility/unit/test_ums_parsing.py +++ b/tests/extensibility/unit/test_ums_parsing.py @@ -74,7 +74,7 @@ def test_before_hook(self): "timeout": 30, "deploymentType": "N8N", "canShortCircuit": False, - "n8nWorkflowConfig": {"workflowId": "wf-before-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } hook = _build_hook(raw) assert hook is not None @@ -83,7 +83,7 @@ def test_before_hook(self): assert hook.name == "Before Tool Execution" assert hook.type == HookType.BEFORE assert hook.deployment_type == DeploymentType.N8N - assert hook.n8n_workflow_config.workflow_id == "wf-before-001" + assert hook.n8n_workflow_config.tool_name == "testHook" assert hook.n8n_workflow_config.method == HTTPMethod.POST assert hook.timeout == 30 assert hook.execution_mode == ExecutionMode.SYNC @@ -100,7 +100,7 @@ def test_after_hook(self): "timeout": 60, "deploymentType": "SERVERLESS", "canShortCircuit": True, - "n8nWorkflowConfig": {"workflowId": "wf-after-001", "method": "POST"}, + "n8nWorkflowConfig": {"ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", "toolName": "testHook", "globalTenantId": "tenant-test-001", "method": "POST"}, } hook = _build_hook(raw) assert hook is not None @@ -467,7 +467,10 @@ def test_hooks_with_unknown_type_skipped(self): "deploymentType": "N8N", "canShortCircuit": False, "n8nWorkflowConfig": { - "workflowId": "wf-valid", + "ordId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook:v1", + "cardOrdId": "sap.n8nwfrt:apiResource:test-solution_hook.testHook_mcp:v1", + "toolName": "testHook", + "globalTenantId": "tenant-test-001", "method": "POST", }, }, diff --git a/uv.lock b/uv.lock index 4a24c109..09c3530c 100644 --- a/uv.lock +++ b/uv.lock @@ -16,22 +16,18 @@ resolution-markers = [ [[package]] name = "a2a-sdk" -version = "1.0.2" +version = "0.3.26" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "culsans", marker = "python_full_version < '3.13'" }, { name = "google-api-core" }, - { name = "googleapis-common-protos" }, { name = "httpx" }, { name = "httpx-sse" }, - { name = "json-rpc" }, - { name = "packaging" }, { name = "protobuf" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/88/f3/1c312eae0298542eef1a096be378a3ad2d20b171ea0ac6be26b81f542720/a2a_sdk-1.0.2.tar.gz", hash = "sha256:e4ee4dd509894c32c9a6df728319875fa4f049e70ae82476fa447353e3a4b648", size = 375193, upload-time = "2026-04-24T13:50:24.303Z" } +sdist = { url = "https://files.pythonhosted.org/packages/be/97/a6840e01795b182ce751ca165430d46459927cde9bfab838087cbb24aef7/a2a_sdk-0.3.26.tar.gz", hash = "sha256:44068e2d037afbb07ab899267439e9bc7eaa7ac2af94f1e8b239933c993ad52d", size = 274598, upload-time = "2026-04-09T15:21:13.902Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/03/58c92a44e7b94a42614880df2365f074969e47067c4c736e31e855aca2fd/a2a_sdk-1.0.2-py3-none-any.whl", hash = "sha256:4dbc083b6808ee28207ac6daad263360f87612c37b2d06f5521efb530318141c", size = 234302, upload-time = "2026-04-24T13:50:22.412Z" }, + { url = "https://files.pythonhosted.org/packages/dd/d5/51f4ee1bf3b736add42a542d3c8a3fd3fa85f3d36c17972127defc46c26f/a2a_sdk-0.3.26-py3-none-any.whl", hash = "sha256:754e0573f6d33b225c1d8d51f640efa69cbbed7bdfb06ce9c3540ea9f58d4a91", size = 151016, upload-time = "2026-04-09T15:21:12.35Z" }, ] [[package]] @@ -161,20 +157,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a4/37/cfd1ed540a4d318da025590d96b728e63713c09e9377950fc655dadeb856/aiohttp-3.14.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2e1161602f45a54de2ce0905243a95f58cb42dcd378402f3697f5e0b21e9d2e7", size = 469280, upload-time = "2026-07-23T01:57:24.241Z" }, ] -[[package]] -name = "aiologic" -version = "0.17.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "sniffio" }, - { name = "typing-extensions" }, - { name = "wrapt" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f1/7a/d51f2fde1e8ae8a83431f8e97b7a71e9358cdb1d4d2ce6be387fa44d68de/aiologic-0.17.1.tar.gz", hash = "sha256:2e1b93b9e88ced318c2a63ad7b382688f40cbfe40e3d42258d49dc9c5aea179d", size = 252354, upload-time = "2026-06-27T20:41:33.25Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5b/d3/2d310b1b839014034dba0cba685e492df8a5c7ad32c19cab7e979eed6554/aiologic-0.17.1-py3-none-any.whl", hash = "sha256:c66b319830fedb7ca3d2b2125fa6f5b653f89418c2a27ea76f259ec5f00943c0", size = 161331, upload-time = "2026-06-27T20:41:31.877Z" }, -] - [[package]] name = "aiosignal" version = "1.4.0" @@ -811,19 +793,6 @@ version = "0.4" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/55/ca/d323556e2bf9bfb63219fbb849ce61bb830cc42d1b25b91cde3815451b91/cuid-0.4.tar.gz", hash = "sha256:74eaba154916a2240405c3631acee708c263ef8fa05a86820b87d0f59f84e978", size = 4986, upload-time = "2023-03-06T00:41:12.708Z" } -[[package]] -name = "culsans" -version = "0.11.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "aiologic" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e0/5d/9fb19fb38f6d6120422064279ea5532e22b84aa2be8831d49607194feda3/culsans-0.11.0-py3-none-any.whl", hash = "sha256:278d118f63fc75b9db11b664b436a1b83cc30d9577127848ba41420e66eb5a47", size = 21811, upload-time = "2025-12-31T23:15:37.189Z" }, -] - [[package]] name = "deprecated" version = "1.3.1" @@ -1600,15 +1569,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, ] -[[package]] -name = "json-rpc" -version = "1.15.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, -] - [[package]] name = "jsonpatch" version = "1.33" @@ -4440,7 +4400,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "a2a-sdk", marker = "extra == 'extensibility'", specifier = ">=0.2.0,<2" }, + { name = "a2a-sdk", marker = "extra == 'extensibility'", specifier = ">=0.2.0,<1.0" }, { name = "aiohttp", marker = "extra == 'aiohttp'", specifier = ">=3.9.0,<4" }, { name = "cryptography", specifier = ">=48.0.1,<51" }, { name = "django", marker = "extra == 'django'", specifier = ">=4.0,<5" }, @@ -4483,7 +4443,7 @@ provides-extras = ["extensibility", "starlette", "fastapi", "aiohttp", "sqlalche [package.metadata.requires-dev] dev = [ - { name = "a2a-sdk", specifier = ">=0.2.0" }, + { name = "a2a-sdk", specifier = ">=0.2.0,<1.0" }, { name = "aiohttp", specifier = ">=3.9.0" }, { name = "anyio", specifier = ">=3.6.2" }, { name = "cryptography", specifier = ">=48.0.1,<51" },