mcp-instana 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,680 @@
1
+ """
2
+ Application Alert MCP Tools Module
3
+
4
+ This module provides application alert configuration tools for Instana monitoring.
5
+ """
6
+
7
+ import sys
8
+ import traceback
9
+ from typing import Dict, Any, Optional, List, Union
10
+ from datetime import datetime
11
+
12
+ # Import the necessary classes from the SDK
13
+ try:
14
+ from instana_client.api.application_alert_configuration_api import ApplicationAlertConfigurationApi
15
+ from instana_client.api_client import ApiClient
16
+ from instana_client.configuration import Configuration
17
+ from instana_client.models.application_alert_config import ApplicationAlertConfig
18
+ from instana_client.models.application_alert_config_with_metadata import ApplicationAlertConfigWithMetadata
19
+ from instana_client.models.config_version import ConfigVersion
20
+ except ImportError as e:
21
+ traceback.print_exc(file=sys.stderr)
22
+ raise
23
+
24
+ from .instana_client_base import BaseInstanaClient, register_as_tool
25
+
26
+ # Helper function for debug printing
27
+ def debug_print(*args, **kwargs):
28
+ """Print debug information to stderr instead of stdout"""
29
+ print(*args, file=sys.stderr, **kwargs)
30
+
31
+ class ApplicationAlertMCPTools(BaseInstanaClient):
32
+ """Tools for application alerts in Instana MCP."""
33
+
34
+ def __init__(self, read_token: str, base_url: str):
35
+ """Initialize the Application Alert MCP tools client."""
36
+ super().__init__(read_token=read_token, base_url=base_url)
37
+
38
+ try:
39
+
40
+ # Configure the API client with the correct base URL and authentication
41
+ configuration = Configuration()
42
+ configuration.host = base_url
43
+ configuration.api_key['ApiKeyAuth'] = read_token
44
+ configuration.api_key_prefix['ApiKeyAuth'] = 'apiToken'
45
+
46
+ # Create an API client with this configuration
47
+ api_client = ApiClient(configuration=configuration)
48
+
49
+ # Initialize the Instana SDK's ApplicationAlertConfigurationApi with our configured client
50
+ self.alert_api = ApplicationAlertConfigurationApi(api_client=api_client)
51
+ except Exception as e:
52
+ debug_print(f"Error initializing ApplicationAlertConfigurationApi: {e}")
53
+ traceback.print_exc(file=sys.stderr)
54
+ raise
55
+
56
+ @register_as_tool
57
+ async def find_application_alert_config(self,
58
+ id: str,
59
+ valid_on: Optional[int] = None,
60
+ ctx=None) -> Dict[str, Any]:
61
+ """
62
+ Get a specific Smart Alert Configuration.
63
+
64
+ This tool retrieves a specific Smart Alert Configuration by its ID.
65
+ This may return a deleted Configuration.
66
+
67
+ Args:
68
+ id: The ID of the Smart Alert Configuration
69
+ valid_on: Optional timestamp (in milliseconds) to retrieve the configuration as it was at that time
70
+ ctx: The MCP context (optional)
71
+
72
+ Returns:
73
+ Dictionary containing the Smart Alert Configuration or error information
74
+ """
75
+ try:
76
+ debug_print(f"get_application_alert_config called with id={id}, valid_on={valid_on}")
77
+
78
+ # Validate required parameters
79
+ if not id:
80
+ return {"error": "id is required"}
81
+
82
+ # Call the find_application_alert_config method from the SDK
83
+ debug_print(f"Calling find_application_alert_config with id={id}, valid_on={valid_on}")
84
+ result = self.alert_api.find_application_alert_config(
85
+ id=id,
86
+ valid_on=valid_on
87
+ )
88
+
89
+ # Convert the result to a dictionary
90
+ if hasattr(result, 'to_dict'):
91
+ result_dict = result.to_dict()
92
+ else:
93
+ # If it's already a dict or another format, use it as is
94
+ result_dict = result
95
+
96
+ debug_print(f"Result from find_application_alert_config: {result_dict}")
97
+ return result_dict
98
+ except Exception as e:
99
+ debug_print(f"Error in get_application_alert_config: {e}")
100
+ traceback.print_exc(file=sys.stderr)
101
+ return {"error": f"Failed to get application alert config: {str(e)}"}
102
+
103
+
104
+ @register_as_tool
105
+ async def find_application_alert_config_versions(self,
106
+ id: str,
107
+ ctx=None) -> Dict[str, Any]:
108
+ """
109
+ Get Smart Alert Config Versions . Get all versions of a Smart Alert Configuration.
110
+
111
+ This tool retrieves all versions of a Smart Alert Configuration by its ID.
112
+ This may return deleted Configurations. Configurations are sorted by creation date in descending order.
113
+
114
+ Args:
115
+ id: The ID of the Smart Alert Configuration
116
+ ctx: The MCP context (optional)
117
+
118
+ Returns:
119
+ Dictionary containing the Smart Alert Configuration versions or error information
120
+ """
121
+ try:
122
+ debug_print(f"get_application_alert_config_versions called with id={id}")
123
+
124
+ # Validate required parameters
125
+ if not id:
126
+ return {"error": "id is required"}
127
+
128
+ # Call the find_application_alert_config_versions method from the SDK
129
+ debug_print(f"Calling find_application_alert_config_versions with id={id}")
130
+ result = self.alert_api.find_application_alert_config_versions(
131
+ id=id
132
+ )
133
+
134
+ # Convert the result to a dictionary
135
+ if isinstance(result, list):
136
+ # If result is a list, convert each item to a dictionary
137
+ result_dict = [item.to_dict() if hasattr(item, 'to_dict') else item for item in result]
138
+ elif hasattr(result, 'to_dict'):
139
+ result_dict = result.to_dict()
140
+ else:
141
+ # If it's already a dict or another format, use it as is
142
+ result_dict = result
143
+
144
+ debug_print(f"Result from find_application_alert_config_versions: {result_dict}")
145
+ return result_dict
146
+ except Exception as e:
147
+ debug_print(f"Error in get_application_alert_config_versions: {e}")
148
+ traceback.print_exc(file=sys.stderr)
149
+ return {"error": f"Failed to get application alert config versions: {str(e)}"}
150
+
151
+ @register_as_tool
152
+ async def get_application_alert_configs(self,
153
+ application_id: Optional[str] = None,
154
+ alert_ids: Optional[List[str]] = None,
155
+ ctx=None) -> Dict[str, Any]:
156
+ """
157
+ Get Smart Alert Configurations for a specific application.
158
+
159
+ This tool retrieves Smart Alert Configurations, optionally filtered by application ID and alert IDs.
160
+ Configurations are sorted by creation date in descending order.
161
+
162
+ Args:
163
+ application_id: Optional ID of the application to filter configurations
164
+ alert_ids: Optional list of alert IDs to filter configurations
165
+ ctx: The MCP context (optional)
166
+
167
+ Returns:
168
+ Dictionary containing Smart Alert Configurations or error information
169
+ """
170
+ try:
171
+ debug_print(f"get_application_alert_configs called with application_id={application_id}, alert_ids={alert_ids}")
172
+
173
+ # Call the find_active_application_alert_configs method from the SDK
174
+ debug_print(f"Calling find_active_application_alert_configs with application_id={application_id}, alert_ids={alert_ids}")
175
+ result = self.alert_api.find_active_application_alert_configs(
176
+ application_id=application_id,
177
+ alert_ids=alert_ids
178
+ )
179
+
180
+ # Convert the result to a dictionary
181
+ if isinstance(result, list):
182
+ # If result is a list, convert each item to a dictionary
183
+ result_dict = [item.to_dict() if hasattr(item, 'to_dict') else item for item in result]
184
+ elif hasattr(result, 'to_dict'):
185
+ result_dict = result.to_dict()
186
+ else:
187
+ # If it's already a dict or another format, use it as is
188
+ result_dict = result
189
+
190
+ debug_print(f"Result from find_active_application_alert_configs: {result_dict}")
191
+ return result_dict
192
+ except Exception as e:
193
+ debug_print(f"Error in get_application_alert_configs: {e}")
194
+ traceback.print_exc(file=sys.stderr)
195
+ return {"error": f"Failed to get application alert configs: {str(e)}"}
196
+
197
+ @register_as_tool
198
+ async def delete_application_alert_config(self,
199
+ id: str,
200
+ ctx=None) -> Dict[str, Any]:
201
+ """
202
+ Delete a Smart Alert Configuration.
203
+
204
+ This tool deletes a specific Smart Alert Configuration by its ID.
205
+ Once deleted, the configuration will no longer trigger alerts.
206
+
207
+ Args:
208
+ id: The ID of the Smart Alert Configuration to delete
209
+ ctx: The MCP context (optional)
210
+
211
+ Returns:
212
+ Dictionary containing the result of the deletion operation or error information
213
+ """
214
+ try:
215
+ debug_print(f"delete_application_alert_config called with id={id}")
216
+
217
+ # Validate required parameters
218
+ if not id:
219
+ return {"error": "id is required"}
220
+
221
+ # Call the delete_application_alert_config method from the SDK
222
+ debug_print(f"Calling delete_application_alert_config with id={id}")
223
+ self.alert_api.delete_application_alert_config(id=id)
224
+
225
+ # The delete operation doesn't return a result, so we'll create a success message
226
+ result_dict = {
227
+ "success": True,
228
+ "message": f"Smart Alert Configuration with ID '{id}' has been successfully deleted"
229
+ }
230
+
231
+ debug_print(f"Result from delete_application_alert_config: {result_dict}")
232
+ return result_dict
233
+ except Exception as e:
234
+ debug_print(f"Error in delete_application_alert_config: {e}")
235
+ traceback.print_exc(file=sys.stderr)
236
+ return {"error": f"Failed to delete application alert config: {str(e)}"}
237
+
238
+ @register_as_tool
239
+ async def enable_application_alert_config(self,
240
+ id: str,
241
+ ctx=None) -> Dict[str, Any]:
242
+ """
243
+ Enable a Smart Alert Configuration.
244
+
245
+ This tool enables a specific Smart Alert Configuration by its ID.
246
+ Once enabled, the configuration will start triggering alerts when conditions are met.
247
+
248
+ Args:
249
+ id: The ID of the Smart Alert Configuration to enable
250
+ ctx: The MCP context (optional)
251
+
252
+ Returns:
253
+ Dictionary containing the result of the enable operation or error information
254
+ """
255
+ try:
256
+ debug_print(f"enable_application_alert_config called with id={id}")
257
+
258
+ # Validate required parameters
259
+ if not id:
260
+ return {"error": "id is required"}
261
+
262
+ # Call the enable_application_alert_config method from the SDK
263
+ debug_print(f"Calling enable_application_alert_config with id={id}")
264
+ result = self.alert_api.enable_application_alert_config(id=id)
265
+
266
+ # Convert the result to a dictionary
267
+ if hasattr(result, 'to_dict'):
268
+ result_dict = result.to_dict()
269
+ else:
270
+ # If it's already a dict or another format, use it as is
271
+ result_dict = result or {
272
+ "success": True,
273
+ "message": f"Smart Alert Configuration with ID '{id}' has been successfully enabled"
274
+ }
275
+
276
+ debug_print(f"Result from enable_application_alert_config: {result_dict}")
277
+ return result_dict
278
+ except Exception as e:
279
+ debug_print(f"Error in enable_application_alert_config: {e}")
280
+ traceback.print_exc(file=sys.stderr)
281
+ return {"error": f"Failed to enable application alert config: {str(e)}"}
282
+
283
+ @register_as_tool
284
+ async def disable_application_alert_config(self,
285
+ id: str,
286
+ ctx=None) -> Dict[str, Any]:
287
+ """
288
+ Disable a Smart Alert Configuration.
289
+
290
+ This tool disables a specific Smart Alert Configuration by its ID.
291
+ Once disabled, the configuration will stop triggering alerts even when conditions are met.
292
+
293
+ Args:
294
+ id: The ID of the Smart Alert Configuration to disable
295
+ ctx: The MCP context (optional)
296
+
297
+ Returns:
298
+ Dictionary containing the result of the disable operation or error information
299
+ """
300
+ try:
301
+ debug_print(f"disable_application_alert_config called with id={id}")
302
+
303
+ # Validate required parameters
304
+ if not id:
305
+ return {"error": "id is required"}
306
+
307
+ # Call the disable_application_alert_config method from the SDK
308
+ debug_print(f"Calling disable_application_alert_config with id={id}")
309
+ result = self.alert_api.disable_application_alert_config(id=id)
310
+
311
+ # Convert the result to a dictionary
312
+ if hasattr(result, 'to_dict'):
313
+ result_dict = result.to_dict()
314
+ else:
315
+ # If it's already a dict or another format, use it as is
316
+ result_dict = result or {
317
+ "success": True,
318
+ "message": f"Smart Alert Configuration with ID '{id}' has been successfully disabled"
319
+ }
320
+
321
+ debug_print(f"Result from disable_application_alert_config: {result_dict}")
322
+ return result_dict
323
+ except Exception as e:
324
+ debug_print(f"Error in disable_application_alert_config: {e}")
325
+ traceback.print_exc(file=sys.stderr)
326
+ return {"error": f"Failed to disable application alert config: {str(e)}"}
327
+
328
+ @register_as_tool
329
+ async def restore_application_alert_config(self,
330
+ id: str,
331
+ created: int,
332
+ ctx=None) -> Dict[str, Any]:
333
+ """
334
+ Restore a deleted Smart Alert Configuration.
335
+
336
+ This tool restores a previously deleted Smart Alert Configuration by its ID and creation timestamp.
337
+ Once restored, the configuration will be active again and can trigger alerts when conditions are met.
338
+
339
+ Args:
340
+ id: The ID of the Smart Alert Configuration to restore
341
+ created: Unix timestamp representing the creation time of the specific Smart Alert Configuration version
342
+ ctx: The MCP context (optional)
343
+
344
+ Returns:
345
+ Dictionary containing the result of the restore operation or error information
346
+ """
347
+ try:
348
+ debug_print(f"restore_application_alert_config called with id={id}, created={created}")
349
+
350
+ # Validate required parameters
351
+ if not id:
352
+ return {"error": "id is required"}
353
+
354
+ if not created:
355
+ return {"error": "created timestamp is required"}
356
+
357
+ # Call the restore_application_alert_config method from the SDK
358
+ debug_print(f"Calling restore_application_alert_config with id={id}, created={created}")
359
+ result = self.alert_api.restore_application_alert_config(id=id, created=created)
360
+
361
+ # Convert the result to a dictionary
362
+ if hasattr(result, 'to_dict'):
363
+ result_dict = result.to_dict()
364
+ else:
365
+ # If it's already a dict or another format, use it as is
366
+ result_dict = result or {
367
+ "success": True,
368
+ "message": f"Smart Alert Configuration with ID '{id}' and creation timestamp '{created}' has been successfully restored"
369
+ }
370
+
371
+ debug_print(f"Result from restore_application_alert_config: {result_dict}")
372
+ return result_dict
373
+ except Exception as e:
374
+ debug_print(f"Error in restore_application_alert_config: {e}")
375
+ traceback.print_exc(file=sys.stderr)
376
+ return {"error": f"Failed to restore application alert config: {str(e)}"}
377
+
378
+ @register_as_tool
379
+ async def update_application_alert_config_baseline(self,
380
+ id: str,
381
+ ctx=None) -> Dict[str, Any]:
382
+ """
383
+ Recalculate the historic baseline for a Smart Alert Configuration.
384
+
385
+ This tool recalculates and updates the historic baseline (static seasonal threshold) of a Smart Alert Configuration.
386
+ The 'LastUpdated' field of the Configuration is changed to the current time.
387
+
388
+ Args:
389
+ id: The ID of the Smart Alert Configuration to recalculate
390
+ ctx: The MCP context (optional)
391
+
392
+ Returns:
393
+ Dictionary containing the result of the baseline update operation or error information
394
+ """
395
+ try:
396
+ debug_print(f"update_application_alert_config_baseline called with id={id}")
397
+
398
+ # Validate required parameters
399
+ if not id:
400
+ return {"error": "id is required"}
401
+
402
+ # Call the update_application_historic_baseline method from the SDK
403
+ debug_print(f"Calling update_application_historic_baseline with id={id}")
404
+ result = self.alert_api.update_application_historic_baseline(id=id)
405
+
406
+ # Convert the result to a dictionary
407
+ if hasattr(result, 'to_dict'):
408
+ result_dict = result.to_dict()
409
+ else:
410
+ # If it's already a dict or another format, use it as is
411
+ result_dict = result or {
412
+ "success": True,
413
+ "message": f"Historic baseline for Smart Alert Configuration with ID '{id}' has been successfully recalculated"
414
+ }
415
+
416
+ debug_print(f"Result from update_application_historic_baseline: {result_dict}")
417
+ return result_dict
418
+ except Exception as e:
419
+ debug_print(f"Error in update_application_alert_config_baseline: {e}")
420
+ traceback.print_exc(file=sys.stderr)
421
+ return {"error": f"Failed to update application alert config baseline: {str(e)}"}
422
+
423
+ @register_as_tool
424
+ async def create_application_alert_config(self,
425
+ payload: Union[Dict[str, Any], str],
426
+ ctx=None) -> Dict[str, Any]:
427
+ """
428
+ Create a new Smart Alert Configuration.
429
+
430
+ This tool creates a new Smart Alert Configuration with the provided configuration details.
431
+ Once created, the configuration will be active and can trigger alerts when conditions are met.
432
+
433
+ Sample payload:
434
+ {
435
+ "name": "My Alert Config",
436
+ "description": "Alert for high CPU usage",
437
+ "severity": 10,
438
+ "triggering": true,
439
+ "enabled": true,
440
+ "rule": {
441
+ "alertType": "...",
442
+ "metricName": "...",
443
+ "aggregation": "...",
444
+ "conditionOperator": "...",
445
+ "conditionValue": 90
446
+ },
447
+ "applicationId": "your-application-id",
448
+ "boundaryScope": "...",
449
+ "tagFilterExpression": {
450
+ "type": "EXPRESSION",
451
+ "logicalOperator": "AND",
452
+ "elements": []
453
+ },
454
+ "granularity": 60000,
455
+ "timeThreshold": 300000
456
+ }
457
+
458
+ Args:
459
+ payload: The Smart Alert Configuration details as a dictionary or JSON string
460
+ ctx: The MCP context (optional)
461
+
462
+ Returns:
463
+ Dictionary containing the created Smart Alert Configuration or error information
464
+ """
465
+ try:
466
+ debug_print(f"create_application_alert_config called with payload={payload}")
467
+
468
+ # Parse the payload if it's a string
469
+ if isinstance(payload, str):
470
+ debug_print(f"Payload is a string, attempting to parse")
471
+ try:
472
+ import json
473
+ try:
474
+ parsed_payload = json.loads(payload)
475
+ debug_print(f"Successfully parsed payload as JSON")
476
+ request_body = parsed_payload
477
+ except json.JSONDecodeError as e:
478
+ debug_print(f"JSON parsing failed: {e}, trying with quotes replaced")
479
+
480
+ # Try replacing single quotes with double quotes
481
+ fixed_payload = payload.replace("'", "\"")
482
+ try:
483
+ parsed_payload = json.loads(fixed_payload)
484
+ debug_print(f"Successfully parsed fixed JSON")
485
+ request_body = parsed_payload
486
+ except json.JSONDecodeError:
487
+ # Try as Python literal
488
+ import ast
489
+ try:
490
+ parsed_payload = ast.literal_eval(payload)
491
+ debug_print(f"Successfully parsed payload as Python literal")
492
+ request_body = parsed_payload
493
+ except (SyntaxError, ValueError) as e2:
494
+ debug_print(f"Failed to parse payload string: {e2}")
495
+ return {"error": f"Invalid payload format: {e2}", "payload": payload}
496
+ except Exception as e:
497
+ debug_print(f"Error parsing payload string: {e}")
498
+ return {"error": f"Failed to parse payload: {e}", "payload": payload}
499
+ else:
500
+ # If payload is already a dictionary, use it directly
501
+ debug_print(f"Using provided payload dictionary")
502
+ request_body = payload
503
+
504
+ # Validate the payload
505
+ if not request_body:
506
+ return {"error": "Payload is required"}
507
+
508
+ # Import the ApplicationAlertConfig class
509
+ try:
510
+ from instana_client.models.application_alert_config import ApplicationAlertConfig
511
+ debug_print("Successfully imported ApplicationAlertConfig")
512
+ except ImportError as e:
513
+ debug_print(f"Error importing ApplicationAlertConfig: {e}")
514
+ return {"error": f"Failed to import ApplicationAlertConfig: {str(e)}"}
515
+
516
+ # Create an ApplicationAlertConfig object from the request body
517
+ try:
518
+ debug_print(f"Creating ApplicationAlertConfig with params: {request_body}")
519
+ config_object = ApplicationAlertConfig(**request_body)
520
+ debug_print(f"Successfully created config object")
521
+ except Exception as e:
522
+ debug_print(f"Error creating ApplicationAlertConfig: {e}")
523
+ return {"error": f"Failed to create config object: {str(e)}"}
524
+
525
+ # Call the create_application_alert_config method from the SDK
526
+ debug_print("Calling create_application_alert_config with config object")
527
+ result = self.alert_api.create_application_alert_config(application_alert_config=config_object)
528
+
529
+ # Convert the result to a dictionary
530
+ if hasattr(result, 'to_dict'):
531
+ result_dict = result.to_dict()
532
+ else:
533
+ # If it's already a dict or another format, use it as is
534
+ result_dict = result
535
+
536
+ debug_print(f"Result from create_application_alert_config: {result_dict}")
537
+ return result_dict
538
+ except Exception as e:
539
+ debug_print(f"Error in create_application_alert_config: {e}")
540
+ traceback.print_exc(file=sys.stderr)
541
+ return {"error": f"Failed to create application alert config: {str(e)}"}
542
+
543
+ @register_as_tool
544
+ async def update_application_alert_config(self,
545
+ id: str,
546
+ payload: Union[Dict[str, Any], str],
547
+ ctx=None) -> Dict[str, Any]:
548
+ """
549
+ Update an existing Smart Alert Configuration.
550
+
551
+ This tool updates an existing Smart Alert Configuration with the provided configuration details.
552
+ The configuration is identified by its ID, and the payload contains the updated configuration.
553
+
554
+ Sample payload:
555
+ {
556
+ "name": "Updated Alert Config",
557
+ "description": "Updated alert for high CPU usage",
558
+ "severity": 5,
559
+ "triggering": true,
560
+ "enabled": true,
561
+ "rule": {
562
+ "alertType": "...",
563
+ "metricName": "...",
564
+ "aggregation": "...",
565
+ "conditionOperator": "...",
566
+ "conditionValue": 95
567
+ },
568
+ "applicationId": "your-application-id",
569
+ "boundaryScope": "...",
570
+ "tagFilterExpression": {
571
+ "type": "EXPRESSION",
572
+ "logicalOperator": "AND",
573
+ "elements": []
574
+ },
575
+ "granularity": 60000,
576
+ "timeThreshold": 300000
577
+ }
578
+
579
+ Args:
580
+ id: The ID of the Smart Alert Configuration to update
581
+ payload: The updated Smart Alert Configuration details as a dictionary or JSON string
582
+ ctx: The MCP context (optional)
583
+
584
+ Returns:
585
+ Dictionary containing the updated Smart Alert Configuration or error information
586
+ """
587
+ try:
588
+ debug_print(f"update_application_alert_config called with id={id}, payload={payload}")
589
+
590
+ # Validate required parameters
591
+ if not id:
592
+ return {"error": "id is required"}
593
+
594
+ if not payload:
595
+ return {"error": "payload is required"}
596
+
597
+ # Parse the payload if it's a string
598
+ if isinstance(payload, str):
599
+ debug_print(f"Payload is a string, attempting to parse")
600
+ try:
601
+ import json
602
+ try:
603
+ parsed_payload = json.loads(payload)
604
+ debug_print(f"Successfully parsed payload as JSON")
605
+ request_body = parsed_payload
606
+ except json.JSONDecodeError as e:
607
+ debug_print(f"JSON parsing failed: {e}, trying with quotes replaced")
608
+
609
+ # Try replacing single quotes with double quotes
610
+ fixed_payload = payload.replace("'", "\"")
611
+ try:
612
+ parsed_payload = json.loads(fixed_payload)
613
+ debug_print(f"Successfully parsed fixed JSON")
614
+ request_body = parsed_payload
615
+ except json.JSONDecodeError:
616
+ # Try as Python literal
617
+ import ast
618
+ try:
619
+ parsed_payload = ast.literal_eval(payload)
620
+ debug_print(f"Successfully parsed payload as Python literal")
621
+ request_body = parsed_payload
622
+ except (SyntaxError, ValueError) as e2:
623
+ debug_print(f"Failed to parse payload string: {e2}")
624
+ return {"error": f"Invalid payload format: {e2}", "payload": payload}
625
+ except Exception as e:
626
+ debug_print(f"Error parsing payload string: {e}")
627
+ return {"error": f"Failed to parse payload: {e}", "payload": payload}
628
+ else:
629
+ # If payload is already a dictionary, use it directly
630
+ debug_print(f"Using provided payload dictionary")
631
+ request_body = payload
632
+
633
+ # Import the ApplicationAlertConfig class
634
+ try:
635
+ from instana_client.models.application_alert_config import ApplicationAlertConfig
636
+ debug_print("Successfully imported ApplicationAlertConfig")
637
+ except ImportError as e:
638
+ debug_print(f"Error importing ApplicationAlertConfig: {e}")
639
+ return {"error": f"Failed to import ApplicationAlertConfig: {str(e)}"}
640
+
641
+ # Create an ApplicationAlertConfig object from the request body
642
+ try:
643
+ debug_print(f"Creating ApplicationAlertConfig with params: {request_body}")
644
+ config_object = ApplicationAlertConfig(**request_body)
645
+ debug_print(f"Successfully created config object")
646
+ except Exception as e:
647
+ debug_print(f"Error creating ApplicationAlertConfig: {e}")
648
+ return {"error": f"Failed to create config object: {str(e)}"}
649
+
650
+ # Call the update_application_alert_config method from the SDK
651
+ debug_print(f"Calling update_application_alert_config with id={id} and config object")
652
+ result = self.alert_api.update_application_alert_config(
653
+ id=id,
654
+ application_alert_config=config_object
655
+ )
656
+
657
+ # Convert the result to a dictionary
658
+ if hasattr(result, 'to_dict'):
659
+ result_dict = result.to_dict()
660
+ else:
661
+ # If it's already a dict or another format, use it as is
662
+ result_dict = result or {
663
+ "success": True,
664
+ "message": f"Smart Alert Configuration with ID '{id}' has been successfully updated"
665
+ }
666
+
667
+ debug_print(f"Result from update_application_alert_config: {result_dict}")
668
+ return result_dict
669
+ except Exception as e:
670
+ debug_print(f"Error in update_application_alert_config: {e}")
671
+ traceback.print_exc(file=sys.stderr)
672
+ return {"error": f"Failed to update application alert config: {str(e)}"}
673
+
674
+
675
+
676
+
677
+
678
+
679
+
680
+