Skip to content

Commit e86dc83

Browse files
committed
fix: improve error handling and validation in ProjectContext initialization
1 parent 75b338b commit e86dc83

File tree

2 files changed

+20
-32
lines changed

2 files changed

+20
-32
lines changed

template/v2/dirs/etc/sagemaker-ui/sagemaker-mcp/smus-mcp.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
11
"""
22
SageMaker Unified Studio Project Context MCP Server in stdio transport.
33
4-
This is a self-contained MCP Server, ready to be used directly.
5-
Dependencies:
6-
pip install mcp[cli]
7-
pip install sagemaker_studio
84
"""
95

106
import json
117
import logging
128
import os
139
from typing import Any, Dict
1410

15-
import boto3
1611
from mcp.server.fastmcp import FastMCP
17-
from sagemaker_studio import ClientConfig, Project
1812

1913
# Configure logging
2014
logging.basicConfig(level=logging.INFO)
@@ -43,15 +37,16 @@ def __init__(self):
4337
self.domain_id = metadata["AdditionalMetadata"]["DataZoneDomainId"]
4438
self.project_id = metadata["AdditionalMetadata"]["DataZoneProjectId"]
4539
self.region = metadata["AdditionalMetadata"]["DataZoneDomainRegion"]
46-
47-
logger.info(f"Read self.domain: {self.domain_id}")
48-
49-
self.session = boto3.Session(profile_name="DomainExecutionRoleCreds", region_name=self.region)
50-
client_conf = ClientConfig(session=self.session, region=self.region)
51-
self.project = Project(id=self.project_id, domain_id=self.domain_id, config=client_conf)
5240
except Exception as e:
5341
raise RuntimeError(f"Failed to initialize project: {e}")
5442

43+
if not self.domain_id:
44+
raise RuntimeError(f"Domain id should not be empty")
45+
if not self.project_id:
46+
raise RuntimeError(f"Project id should not be empty")
47+
if not self.region:
48+
raise RuntimeError(f"Region should not be empty")
49+
5550

5651
def safe_get_attr(obj: Any, attr: str, default: Any = None) -> Any:
5752
"""Safely get an attribute from an object."""
@@ -66,12 +61,12 @@ def safe_get_attr(obj: Any, attr: str, default: Any = None) -> Any:
6661
try:
6762
return value()
6863
except (RuntimeError, Exception) as e:
69-
logger.debug(f"Error calling attribute {attr}: {e}")
64+
logger.error(f"Error calling attribute {attr}: {e}")
7065
return default
7166
return value
7267
return default
7368
except Exception as e:
74-
logger.debug(f"Error getting attribute {attr}: {e}")
69+
logger.error(f"Error getting attribute {attr}: {e}")
7570
return default
7671

7772

@@ -99,7 +94,6 @@ async def aws_context_provider() -> Dict[str, Any]:
9994
- domain identifier: Unique identifier for the AWS DataZone domain
10095
- project identifier: Identifier for the specific project being worked on
10196
- profile name: Name of the AWS profile to use for credentials
102-
- project profile connection name: Connection name for project integration
10397
- region: AWS region where operations should be performed
10498
- aws profiles: use the aws profile named DomainExecutionRoleCreds for calling datazone APIs; otherwise use default AWS profile
10599
@@ -116,7 +110,7 @@ async def aws_context_provider() -> Dict[str, Any]:
116110
return {"response": identifiers_response}
117111
except Exception as e:
118112
logger.error(f"Error providing SMUS context identifiers: {e}")
119-
return {"response": identifiers_response, "error": str(e)}
113+
return {"response": identifiers_response, "error": "Error providing SMUS context identifiers"}
120114

121115

122116
if __name__ == "__main__":

template/v3/dirs/etc/sagemaker-ui/sagemaker-mcp/smus-mcp.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
11
"""
22
SageMaker Unified Studio Project Context MCP Server in stdio transport.
33
4-
This is a self-contained MCP Server, ready to be used directly.
5-
Dependencies:
6-
pip install mcp[cli]
7-
pip install sagemaker_studio
84
"""
95

106
import json
117
import logging
128
import os
139
from typing import Any, Dict
1410

15-
import boto3
1611
from mcp.server.fastmcp import FastMCP
17-
from sagemaker_studio import ClientConfig, Project
1812

1913
# Configure logging
2014
logging.basicConfig(level=logging.INFO)
@@ -43,15 +37,16 @@ def __init__(self):
4337
self.domain_id = metadata["AdditionalMetadata"]["DataZoneDomainId"]
4438
self.project_id = metadata["AdditionalMetadata"]["DataZoneProjectId"]
4539
self.region = metadata["AdditionalMetadata"]["DataZoneDomainRegion"]
46-
47-
logger.info(f"Read self.domain: {self.domain_id}")
48-
49-
self.session = boto3.Session(profile_name="DomainExecutionRoleCreds", region_name=self.region)
50-
client_conf = ClientConfig(session=self.session, region=self.region)
51-
self.project = Project(id=self.project_id, domain_id=self.domain_id, config=client_conf)
5240
except Exception as e:
5341
raise RuntimeError(f"Failed to initialize project: {e}")
5442

43+
if not self.domain_id:
44+
raise RuntimeError(f"Domain id should not be empty")
45+
if not self.project_id:
46+
raise RuntimeError(f"Project id should not be empty")
47+
if not self.region:
48+
raise RuntimeError(f"Region should not be empty")
49+
5550

5651
def safe_get_attr(obj: Any, attr: str, default: Any = None) -> Any:
5752
"""Safely get an attribute from an object."""
@@ -66,12 +61,12 @@ def safe_get_attr(obj: Any, attr: str, default: Any = None) -> Any:
6661
try:
6762
return value()
6863
except (RuntimeError, Exception) as e:
69-
logger.debug(f"Error calling attribute {attr}: {e}")
64+
logger.error(f"Error calling attribute {attr}: {e}")
7065
return default
7166
return value
7267
return default
7368
except Exception as e:
74-
logger.debug(f"Error getting attribute {attr}: {e}")
69+
logger.error(f"Error getting attribute {attr}: {e}")
7570
return default
7671

7772

@@ -99,7 +94,6 @@ async def aws_context_provider() -> Dict[str, Any]:
9994
- domain identifier: Unique identifier for the AWS DataZone domain
10095
- project identifier: Identifier for the specific project being worked on
10196
- profile name: Name of the AWS profile to use for credentials
102-
- project profile connection name: Connection name for project integration
10397
- region: AWS region where operations should be performed
10498
- aws profiles: use the aws profile named DomainExecutionRoleCreds for calling datazone APIs; otherwise use default AWS profile
10599
@@ -116,7 +110,7 @@ async def aws_context_provider() -> Dict[str, Any]:
116110
return {"response": identifiers_response}
117111
except Exception as e:
118112
logger.error(f"Error providing SMUS context identifiers: {e}")
119-
return {"response": identifiers_response, "error": str(e)}
113+
return {"response": identifiers_response, "error": "Error providing SMUS context identifiers"}
120114

121115

122116
if __name__ == "__main__":

0 commit comments

Comments
 (0)