generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 1k
feat: Interactive service auditing in batches #1530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
blairhyy-amazon
wants to merge
7
commits into
awslabs:main
Choose a base branch
from
blairhyy-amazon:2nd_batch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
64923f3
interactive service auditing in batches
blairhyy-amazon 48db5e8
Merge branch 'main' into 2nd_batch
blairhyy-amazon ea2b59d
Merge branch 'main' into 2nd_batch
blairhyy-amazon 4fbfcbd
Retry auditing the same batch when it fails & remove cleanup_audit_se…
blairhyy-amazon 4ea1df8
Clean up old batch sessions when a new one starts
blairhyy-amazon dec2f5c
Merge branch 'main' into 2nd_batch
blairhyy-amazon 0fdd7a0
Merge branch 'main' into 2nd_batch
blairhyy-amazon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
209 changes: 209 additions & 0 deletions
209
...-appsignals-mcp-server/awslabs/cloudwatch_appsignals_mcp_server/batch_processing_utils.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Utilities for interactive batch processing of audit operations.""" | ||
|
|
||
| import json | ||
| import uuid | ||
| from datetime import datetime, timezone | ||
| from loguru import logger | ||
| from typing import Any, Dict, List, Optional | ||
|
|
||
|
|
||
| # Global storage for batch sessions (in production, this would be in a database) | ||
| _batch_sessions: Dict[str, Dict[str, Any]] = {} | ||
|
|
||
|
|
||
| def create_batch_session( | ||
| targets: List[Dict[str, Any]], | ||
| input_obj: Dict[str, Any], | ||
| region: str, | ||
| banner: str, | ||
| batch_size: int = 10, | ||
| auto_complete: Optional[bool] = None, | ||
| ) -> str: | ||
| """Create a new batch processing session. | ||
|
|
||
| Args: | ||
| targets: List of all targets to process | ||
| input_obj: Base input object for API calls | ||
| region: AWS region | ||
| banner: Banner text for display | ||
| batch_size: Number of targets per batch | ||
| auto_complete: If True, process all batches automatically. If False, use interactive mode. | ||
| If None, auto-decide based on target count. | ||
|
|
||
| Returns: | ||
| Session ID for tracking the batch processing | ||
| """ | ||
| session_id = str(uuid.uuid4()) | ||
|
|
||
| # Auto-decide batch processing mode if not specified | ||
| if auto_complete is None: | ||
| auto_complete = len(targets) <= batch_size # Auto-complete for small lists | ||
|
|
||
| # Create batches | ||
| batches = [] | ||
| for i in range(0, len(targets), batch_size): | ||
| batch = targets[i : i + batch_size] | ||
| batches.append(batch) | ||
|
|
||
| now = datetime.now(timezone.utc).isoformat() | ||
| session = { | ||
| 'session_id': session_id, | ||
| 'created_at': now, | ||
| 'last_activity': now, | ||
| 'targets': targets, | ||
| 'input_obj': input_obj, | ||
| 'batches': batches, | ||
| 'current_batch_index': 0, | ||
| 'processed_batches': [], | ||
| 'failed_batches': [], | ||
| 'all_findings': [], | ||
| 'auto_complete': auto_complete, | ||
| 'status': 'created', | ||
| } | ||
|
|
||
| _batch_sessions[session_id] = session | ||
| logger.info(f'Created batch session {session_id} with {len(batches)} batches') | ||
|
|
||
| return session_id | ||
|
|
||
|
|
||
| def get_batch_session(session_id: str) -> Optional[Dict[str, Any]]: | ||
| """Get batch session by ID.""" | ||
| return _batch_sessions.get(session_id) | ||
|
|
||
|
|
||
| def update_batch_session_activity(session_id: str) -> None: | ||
| """Update last activity timestamp for session.""" | ||
| if session_id in _batch_sessions: | ||
| _batch_sessions[session_id]['last_activity'] = datetime.now(timezone.utc).isoformat() | ||
|
|
||
|
|
||
| def _create_batch_metadata( | ||
| session: Dict[str, Any], current_batch: List[Dict[str, Any]] | ||
| ) -> Dict[str, Any]: | ||
| """Create common batch metadata.""" | ||
| current_index = session['current_batch_index'] | ||
| return { | ||
| 'batch_index': current_index + 1, | ||
| 'total_batches': len(session['batches']), | ||
| 'targets_in_batch': len(current_batch), | ||
| 'targets': current_batch, | ||
| } | ||
|
|
||
|
|
||
| def _build_api_input( | ||
| session: Dict[str, Any], current_batch: List[Dict[str, Any]] | ||
| ) -> Dict[str, Any]: | ||
| """Build API input object for the current batch.""" | ||
| batch_input = { | ||
| 'StartTime': datetime.fromtimestamp(session['input_obj']['StartTime'], tz=timezone.utc), | ||
| 'EndTime': datetime.fromtimestamp(session['input_obj']['EndTime'], tz=timezone.utc), | ||
| 'AuditTargets': current_batch, | ||
| } | ||
| if 'Auditors' in session['input_obj']: | ||
| batch_input['Auditors'] = session['input_obj']['Auditors'] | ||
| return batch_input | ||
|
|
||
|
|
||
| def _update_session_after_batch(session: Dict[str, Any], batch_result: Dict[str, Any]) -> None: | ||
| """Update session state after processing a batch.""" | ||
| session['current_batch_index'] += 1 | ||
|
|
||
| if batch_result['status'] == 'success': | ||
| session['processed_batches'].append(batch_result) | ||
| session['all_findings'].extend(batch_result.get('findings', [])) | ||
| else: | ||
| session['failed_batches'].append(batch_result) | ||
|
|
||
| # Update overall session status | ||
| session['status'] = ( | ||
| 'completed' if session['current_batch_index'] >= len(session['batches']) else 'in_progress' | ||
| ) | ||
|
|
||
|
|
||
| def process_next_batch(session_id: str, appsignals_client) -> Dict[str, Any]: | ||
blairhyy-amazon marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """Process the next batch in the session. | ||
|
|
||
| Returns: | ||
| Dictionary with batch results and session status | ||
| """ | ||
| session = get_batch_session(session_id) | ||
| if not session: | ||
| return {'error': 'Session not found or expired'} | ||
|
|
||
| update_batch_session_activity(session_id) | ||
|
|
||
| current_index = session['current_batch_index'] | ||
| batches = session['batches'] | ||
|
|
||
| if current_index >= len(batches): | ||
| return {'error': 'No more batches to process', 'status': 'completed'} | ||
|
|
||
| current_batch = batches[current_index] | ||
| batch_metadata = _create_batch_metadata(session, current_batch) | ||
|
|
||
| try: | ||
| # Build and execute API call | ||
| batch_input = _build_api_input(session, current_batch) | ||
| response = appsignals_client.list_audit_findings(**batch_input) | ||
blairhyy-amazon marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Create success result | ||
| batch_findings = response.get('AuditFindings', []) | ||
| batch_result = { | ||
| **batch_metadata, | ||
| 'findings_count': len(batch_findings), | ||
| 'findings': batch_findings, | ||
| 'status': 'success', | ||
| } | ||
|
|
||
| except Exception as e: | ||
| # Create error result | ||
| batch_result = {**batch_metadata, 'error': str(e), 'status': 'failed'} | ||
|
|
||
| # Update session state and return result | ||
| _update_session_after_batch(session, batch_result) | ||
| return batch_result | ||
|
|
||
|
|
||
| def cleanup_batch_sessions() -> None: | ||
| """Clean up all batch sessions from memory.""" | ||
| global _batch_sessions | ||
|
|
||
| initial_count = len(_batch_sessions) | ||
| _batch_sessions.clear() | ||
| logger.info(f'Cleaned up all {initial_count} batch sessions') | ||
|
|
||
|
|
||
| def format_batch_result(batch_result: Dict[str, Any], session: Dict[str, Any]) -> str: | ||
| """Format batch processing result for user display with essential information only.""" | ||
| batch_index = batch_result['batch_index'] | ||
| total_batches = batch_result['total_batches'] | ||
|
|
||
| if batch_result.get('error'): | ||
| return f'❌ Batch {batch_index}/{total_batches} failed: {batch_result["error"]}' | ||
|
|
||
| findings_count = len(batch_result.get('findings', [])) | ||
|
|
||
| if findings_count == 0: | ||
| status = f'✅ Batch {batch_index}/{total_batches}: {batch_result["targets_in_batch"]} services healthy' | ||
| if batch_index < total_batches: | ||
| status += f" | Continue: continue_audit_batch('{session['session_id']}')" | ||
| return status | ||
|
|
||
| # Keep full JSON for MCP observation when findings exist | ||
| findings_json = json.dumps(batch_result['findings'], indent=2, default=str) | ||
| return f'⚠️ Batch {batch_index}/{total_batches}: {findings_count} findings\n```\n{findings_json}\n```' | ||
84 changes: 84 additions & 0 deletions
84
src/cloudwatch-appsignals-mcp-server/awslabs/cloudwatch_appsignals_mcp_server/batch_tools.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Batch processing tools for interactive audit workflows.""" | ||
|
|
||
| from .aws_clients import appsignals_client | ||
| from .batch_processing_utils import ( | ||
| cleanup_batch_sessions, | ||
| format_batch_result, | ||
| get_batch_session, | ||
| process_next_batch, | ||
| ) | ||
| from loguru import logger | ||
| from pydantic import Field | ||
|
|
||
|
|
||
| async def continue_audit_batch( | ||
| batch_session_id: str = Field( | ||
| ..., description='Session ID from previous batch processing to continue' | ||
| ), | ||
| ) -> str: | ||
| """Continue processing the next batch in an active audit session. | ||
|
|
||
| **INTERACTIVE BATCH PROCESSING TOOL** | ||
| Use this tool to continue processing the next batch of targets in an ongoing audit session. | ||
|
|
||
| **WHEN TO USE:** | ||
| - **When there are no findings from the last batch** - Services appear healthy, continue to next batch | ||
| - **When customer wants to continue processing next batch** | ||
|
|
||
| **RETURNS:** | ||
| - Results from the next batch with progress information | ||
| - Full JSON findings for MCP observation and service name extraction | ||
| - Continuation instructions if more batches remain | ||
| - Error message if session is invalid or expired | ||
| """ | ||
| try: | ||
| batch_result = process_next_batch(batch_session_id, appsignals_client) | ||
| session = get_batch_session(batch_session_id) | ||
|
|
||
| if batch_result.get('error'): | ||
| return f'Error: {batch_result["error"]}' | ||
|
|
||
| if not session: | ||
| return 'Error: Session not found or expired' | ||
|
|
||
| # Format and return batch result | ||
| formatted_result = format_batch_result(batch_result, session) | ||
|
|
||
| return formatted_result | ||
|
|
||
| except Exception as e: | ||
| logger.error(f'Error in continue_audit_batch: {e}', exc_info=True) | ||
| return f'Error: {str(e)}' | ||
|
|
||
|
|
||
| async def cleanup_audit_sessions() -> str: | ||
| """Clean up all batch audit sessions from memory. | ||
|
|
||
| **BATCH SESSION CLEANUP TOOL** | ||
| Use this tool to free memory by cleaning up all completed batch audit sessions. | ||
|
|
||
| **WHEN TO USE:** | ||
| - After completing a full service audit to free memory | ||
| - To clean up all sessions and free memory resources | ||
| """ | ||
| try: | ||
| cleanup_batch_sessions() | ||
| return 'All batch sessions cleaned up successfully.' | ||
|
|
||
| except Exception as e: | ||
| logger.error(f'Error in cleanup_audit_sessions: {e}', exc_info=True) | ||
| return f'Error: {str(e)}' |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ideally, MCP server should be stateless. And it looks like you're generating random session id as key for the cache for each call. Does cache really work?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We're going to support remote MCP soon, I think the way we maintain the cache on MCP server won't work out for 1) single user w/ multi-sessions, 2) multi-talent w/ muti-sessions cases, etc. Do we have to have the cache to improve the performance? Isn't API pagination support not sufficient?