|
| 1 | +""" |
| 2 | +Dynamic action tools for Port MCP server. |
| 3 | +
|
| 4 | +This module provides functionality to dynamically create tools for Port actions. |
| 5 | +""" |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import re |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from pydantic import BaseModel, Field |
| 12 | +from pydantic.json_schema import SkipJsonSchema |
| 13 | + |
| 14 | +from src.client.client import PortClient |
| 15 | +from src.models.action_run.action_run import ActionRun |
| 16 | +from src.models.actions.action import Action |
| 17 | +from src.models.common.annotations import Annotations |
| 18 | +from src.models.common.base_pydantic import BaseModel as PortBaseModel |
| 19 | +from src.models.tools.tool import Tool |
| 20 | +from src.tools.action.get_action import GetActionTool, GetActionToolSchema |
| 21 | +from src.tools.action.list_actions import ListActionsTool, ListActionsToolSchema |
| 22 | +from src.utils import logger |
| 23 | + |
| 24 | + |
| 25 | +class DynamicActionToolSchema(BaseModel): |
| 26 | + """Simple schema for dynamic action tools.""" |
| 27 | + |
| 28 | + entity_identifier: str | SkipJsonSchema[None] = Field( |
| 29 | + default=None, |
| 30 | + description="Optional entity identifier if action is entity-specific, if the action contains blueprint and the type is DAY-2 or DELETE, create an entity first and pass the identifier here", |
| 31 | + ) |
| 32 | + properties: dict[str, Any] | SkipJsonSchema[None] = Field( |
| 33 | + default=None, |
| 34 | + description="Properties for the action. To see required properties, first call get_action with action_identifier to view the userInputs schema.", |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +class DynamicActionToolResponse(PortBaseModel): |
| 39 | + """Response model for dynamic action tools.""" |
| 40 | + |
| 41 | + action_run: ActionRun = Field(description="Action run details including run_id for tracking") |
| 42 | + |
| 43 | + |
| 44 | +def _camel_to_snake(name: str) -> str: |
| 45 | + """Convert CamelCase to snake_case.""" |
| 46 | + s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) |
| 47 | + return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() |
| 48 | + |
| 49 | + |
| 50 | +class DynamicActionToolsManager: |
| 51 | + """Manager for creating and registering dynamic action tools.""" |
| 52 | + |
| 53 | + def __init__(self, port_client: PortClient): |
| 54 | + self.port_client = port_client |
| 55 | + |
| 56 | + def _create_dynamic_action_tool(self, action: Action) -> Tool: |
| 57 | + """Create a dynamic tool for a specific Port action.""" |
| 58 | + |
| 59 | + async def dynamic_action_function(props: DynamicActionToolSchema) -> dict[str, Any]: |
| 60 | + if not self.port_client.action_runs: |
| 61 | + raise ValueError("Action runs client not available") |
| 62 | + |
| 63 | + if props.entity_identifier: |
| 64 | + action_run = await self.port_client.create_entity_action_run( |
| 65 | + action_identifier=action.identifier, |
| 66 | + entity=props.entity_identifier, |
| 67 | + properties=props.properties or {}, |
| 68 | + ) |
| 69 | + else: |
| 70 | + action_run = await self.port_client.create_global_action_run( |
| 71 | + action_identifier=action.identifier, |
| 72 | + properties=props.properties or {}, |
| 73 | + ) |
| 74 | + |
| 75 | + return DynamicActionToolResponse(action_run=action_run).model_dump() |
| 76 | + |
| 77 | + base_tool_name = f"run_{_camel_to_snake(action.identifier)}" |
| 78 | + tool_name = base_tool_name[:40] if len(base_tool_name) > 40 else base_tool_name |
| 79 | + |
| 80 | + description = f"Execute the '{action.title}' action" |
| 81 | + if action.description: |
| 82 | + description += f": {action.description}" |
| 83 | + description += f"\n\nTo see required properties, first call get_action with action_identifier='{action.identifier}' to view the userInputs schema." |
| 84 | + |
| 85 | + return Tool( |
| 86 | + name=tool_name, |
| 87 | + description=description, |
| 88 | + function=dynamic_action_function, |
| 89 | + input_schema=DynamicActionToolSchema, |
| 90 | + output_schema=DynamicActionToolResponse, |
| 91 | + annotations=Annotations( |
| 92 | + title=f"Run {action.title}", |
| 93 | + readOnlyHint=False, |
| 94 | + destructiveHint=False, |
| 95 | + idempotentHint=False, |
| 96 | + openWorldHint=True, |
| 97 | + ), |
| 98 | + ) |
| 99 | + |
| 100 | + async def get_dynamic_action_tools(self) -> list[Tool]: |
| 101 | + """Get all dynamic action tools by fetching actions from Port.""" |
| 102 | + tools = [] |
| 103 | + try: |
| 104 | + list_actions_tool = ListActionsTool(self.port_client) |
| 105 | + actions_response = await list_actions_tool.list_actions(ListActionsToolSchema()) |
| 106 | + actions = actions_response.get("actions", []) |
| 107 | + |
| 108 | + get_action_tool = GetActionTool(self.port_client) |
| 109 | + |
| 110 | + for action_data in actions: |
| 111 | + try: |
| 112 | + action_identifier = ( |
| 113 | + action_data.get("identifier") |
| 114 | + if isinstance(action_data, dict) |
| 115 | + else action_data.identifier |
| 116 | + ) |
| 117 | + |
| 118 | + if not action_identifier: |
| 119 | + logger.warning("Skipping action with no identifier") |
| 120 | + continue |
| 121 | + |
| 122 | + action_response = await get_action_tool.get_action( |
| 123 | + GetActionToolSchema(action_identifier=str(action_identifier)) |
| 124 | + ) |
| 125 | + |
| 126 | + action = Action.model_validate(action_response, strict=False) |
| 127 | + |
| 128 | + if action: |
| 129 | + dynamic_tool = self._create_dynamic_action_tool(action) |
| 130 | + tools.append(dynamic_tool) |
| 131 | + |
| 132 | + except Exception as e: |
| 133 | + logger.warning( |
| 134 | + f"Failed to create dynamic tool for action {action_identifier}: {e}" |
| 135 | + ) |
| 136 | + continue |
| 137 | + |
| 138 | + logger.info(f"Created {len(tools)} dynamic action tools") |
| 139 | + |
| 140 | + except Exception as e: |
| 141 | + logger.error(f"Failed to create dynamic action tools: {e}") |
| 142 | + |
| 143 | + return tools |
| 144 | + |
| 145 | + def get_dynamic_action_tools_sync(self) -> list[Tool]: |
| 146 | + """Synchronous wrapper for getting dynamic action tools.""" |
| 147 | + return asyncio.run(self.get_dynamic_action_tools()) |
0 commit comments