Skip to main content
Glama
JLKmach

ServiceNow MCP Server

by JLKmach

reorder_workflow_activities

Change the sequence of activities in a ServiceNow workflow by specifying their new order. Use this tool to update workflow logic and process flow.

Instructions

Reorder activities in a workflow

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
workflow_idYesWorkflow ID or sys_id
activity_idsYesList of activity IDs in the desired order

Implementation Reference

  • The main handler function that implements the reorder_workflow_activities tool logic. It updates the 'order' field of each wf_activity record via ServiceNow REST API PATCH requests.
    def reorder_workflow_activities(
        auth_manager: AuthManager,
        server_config: ServerConfig,
        params: Dict[str, Any],
    ) -> Dict[str, Any]:
        """
        Reorder activities in a workflow.
        
        Args:
            auth_manager: Authentication manager
            server_config: Server configuration
            params: Parameters for reordering workflow activities
            
        Returns:
            Dict[str, Any]: Result of the reordering operation
        """
        # Unwrap parameters if needed
        params = _unwrap_params(params, ReorderWorkflowActivitiesParams)
        
        # Get the correct auth_manager and server_config
        try:
            auth_manager, server_config = _get_auth_and_config(auth_manager, server_config)
        except ValueError as e:
            logger.error(f"Error getting auth and config: {e}")
            return {"error": str(e)}
        
        workflow_id = params.get("workflow_id")
        if not workflow_id:
            return {"error": "Workflow ID is required"}
        
        activity_ids = params.get("activity_ids")
        if not activity_ids:
            return {"error": "Activity IDs are required"}
        
        # Make the API requests to update the order of each activity
        try:
            headers = auth_manager.get_headers()
            results = []
            
            for i, activity_id in enumerate(activity_ids):
                # Calculate the new order value (100, 200, 300, etc.)
                new_order = (i + 1) * 100
                
                url = f"{server_config.instance_url}/api/now/table/wf_activity/{activity_id}"
                data = {"order": new_order}
                
                try:
                    response = requests.patch(url, headers=headers, json=data)
                    response.raise_for_status()
                    
                    results.append({
                        "activity_id": activity_id,
                        "new_order": new_order,
                        "success": True,
                    })
                except requests.RequestException as e:
                    logger.error(f"Error updating activity order: {e}")
                    results.append({
                        "activity_id": activity_id,
                        "error": str(e),
                        "success": False,
                    })
            
            return {
                "message": "Activities reordered",
                "workflow_id": workflow_id,
                "results": results,
            }
        except Exception as e:
            logger.error(f"Unexpected error reordering workflow activities: {e}")
            return {"error": str(e)}
  • Pydantic model defining the input parameters for the reorder_workflow_activities tool: workflow_id and list of activity_ids.
    class ReorderWorkflowActivitiesParams(BaseModel):
        """Parameters for reordering workflow activities."""
        
        workflow_id: str = Field(..., description="Workflow ID or sys_id")
        activity_ids: List[str] = Field(..., description="List of activity IDs in the desired order")
  • Registration of the tool in the get_tool_definitions() function, mapping name to (handler, schema, return_type, description, serialization).
    "reorder_workflow_activities": (
        reorder_workflow_activities_tool,
        ReorderWorkflowActivitiesParams,
        str,
        "Reorder activities in a workflow",
        "str",  # Tool returns simple message
    ),
  • Export/import of the handler function in tools/__init__.py for module-level access.
    from servicenow_mcp.tools.workflow_tools import (
        activate_workflow,
        add_workflow_activity,
        create_workflow,
        deactivate_workflow,
        delete_workflow_activity,
        get_workflow_activities,
        get_workflow_details,
        list_workflow_versions,
        list_workflows,
        reorder_workflow_activities,
        update_workflow,
        update_workflow_activity,
    )
  • Helper function used by the handler to unwrap and validate input parameters using the Pydantic schema.
    def _unwrap_params(params: Any, param_class: Type[T]) -> Dict[str, Any]:
        """
        Unwrap parameters if they're wrapped in a Pydantic model.
        This helps handle cases where the parameters are passed as a model instead of a dict.
        """
        if isinstance(params, dict):
            return params
        if isinstance(params, param_class):
            return params.dict(exclude_none=True)
        return params

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/JLKmach/servicenow-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server