altr-mcp 0.2.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.
altr_mcp/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from altr_mcp.models import (
4
+ AccessRateThreshold,
5
+ TimeRange,
6
+ TimeWindowThreshold,
7
+ validate_access_rate_thresholds,
8
+ validate_time_window_thresholds,
9
+ )
10
+ from altr_mcp.settings import get_settings
11
+
12
+ try:
13
+ __version__ = version("altr-mcp")
14
+ except PackageNotFoundError:
15
+ __version__ = "0.0.0-dev"
16
+
17
+ __all__ = [
18
+ "__version__",
19
+ "get_settings",
20
+ "AccessRateThreshold",
21
+ "TimeRange",
22
+ "TimeWindowThreshold",
23
+ "validate_access_rate_thresholds",
24
+ "validate_time_window_thresholds",
25
+ ]
@@ -0,0 +1,84 @@
1
+ ALTR MCP server for managing data security on Snowflake. Provides tools for tag management, masking policy and rule CRUD, automated data classification, role discovery, access management, audits, telemetry, and sidecar configuration.
2
+
3
+ IMPORTANT: Classification jobs (create_job) are async and can take 10-30+ minutes. After creating a job, stop and tell the user to wait for completion. Poll with get_jobs until status is COMPLETED before calling get_classification_report.
4
+
5
+ MASKING LEVELS (use these exact values with add_rules):
6
+ 10000 = No Mask, 10001 = Full Mask, 10002 = Email Mask, 10003 = Show Last Four, 10004 = Constant Mask, 10005 = Null, 10006 = Full Mask Hash, 10007 = Email Hash, 10008 = Show Last Four Hash, 10009 = Constant Date. There are exactly 10 masking levels (10000-10009). Do NOT claim any level is invalid or unsupported.
7
+
8
+ TOOL USAGE GUIDANCE
9
+
10
+ These tools cover four areas of ALTR data security:
11
+
12
+ Discovery — get_databases, get_database_id,
13
+ get_roles, get_tags, get_tag_values,
14
+ get_policies, get_rules
15
+ Classification — get_classifiers, create_classifier,
16
+ delete_classifier, get_collections,
17
+ create_collection, delete_collection,
18
+ create_job, get_jobs,
19
+ update_job_status,
20
+ get_classification_report
21
+ Tagging — connect_tag,
22
+ update_tag, delete_tag,
23
+ delete_tag_by_details,
24
+ get_tag_details,
25
+ get_tag_details_by_group_id
26
+ Policy/Rules — create_policy, add_rules,
27
+ update_rule, delete_policy,
28
+ delete_rule
29
+ Access Mgmt — create_snowflake_access_policy,
30
+ create_oltp_access_policy,
31
+ update_snowflake_access_policy,
32
+ trigger_access_policy_check
33
+ Access Request — create_access_request,
34
+ get_access_requests,
35
+ get_access_request,
36
+ approve_access_request,
37
+ deny_access_request,
38
+ cancel_access_request
39
+ Telemetry — get_agent_instances,
40
+ get_agent_instance,
41
+ delete_agent_instance,
42
+ get_agent_task_telemetry,
43
+ get_sidecar_instances,
44
+ get_sidecar_instance,
45
+ delete_sidecar_instance,
46
+ get_task_telemetry,
47
+ delete_task_telemetry
48
+ Audits — search_audits, get_audit_results
49
+ Sidecar Config — list_sc_agents, create_sc_agent, get_sc_agent,
50
+ update_sc_agent, delete_sc_agent,
51
+ list_sc_repos, create_sc_repo, get_sc_repo,
52
+ update_sc_repo, delete_sc_repo,
53
+ list_sc_repo_users, create_sc_repo_user, get_sc_repo_user,
54
+ update_sc_repo_user, delete_sc_repo_user,
55
+ list_sc_service_users, create_sc_service_user,
56
+ get_sc_service_user, update_sc_service_user,
57
+ delete_sc_service_user,
58
+ list_sc_sidecars, create_sc_sidecar, get_sc_sidecar,
59
+ update_sc_sidecar, delete_sc_sidecar,
60
+ list_sc_sidecar_listeners, register_sc_sidecar_listener,
61
+ deregister_sc_sidecar_listener,
62
+ list_sc_sidecar_bindings, list_sc_repo_bindings,
63
+ get_sc_sidecar_binding, create_sc_sidecar_binding,
64
+ delete_sc_sidecar_binding
65
+
66
+ Common workflow (end-to-end setup):
67
+
68
+ 1. Discover existing state — databases, tags, policies, roles
69
+ 2. Run a classification job to find sensitive columns
70
+ IMPORTANT: Classification jobs are async and can take 10-30+ minutes.
71
+ After creating a job, STOP and tell the user to wait for it to finish.
72
+ Do NOT proceed until get_jobs shows status COMPLETED.
73
+ 3. Review the classification report (get_classification_report)
74
+ 4. Check if the needed Snowflake tags already exist using get_tags.
75
+ This server connects existing Snowflake tags to ALTR — it does not
76
+ create tags in Snowflake. If tags are missing, instruct the user to
77
+ create them in Snowflake first (via the Snowflake console, SQL, or
78
+ another MCP server like snowflake-labs-mcp).
79
+ 5. Connect Snowflake tags to ALTR (connect_tag)
80
+ 6. Create masking policies (create_policy) and add rules (add_rules)
81
+
82
+ These steps are not always required in order — users may skip classification
83
+ if they already know which columns to tag, or they may only need to add rules
84
+ to an existing policy. Adapt to what the user asks for.
altr_mcp/middleware.py ADDED
@@ -0,0 +1,56 @@
1
+ """Tool restriction middleware.
2
+
3
+ Hides and blocks tools listed in RESTRICTED_TOOLS.
4
+ """
5
+
6
+ from typing import Optional
7
+
8
+ import structlog
9
+ from fastmcp.exceptions import ToolError
10
+ from fastmcp.server.middleware import Middleware, MiddlewareContext
11
+
12
+ logger = structlog.get_logger(__name__)
13
+
14
+
15
+ class ToolRestrictionMiddleware(Middleware):
16
+ """Hide restricted tools from tools/list and block them on tools/call."""
17
+
18
+ def __init__(self, restricted_tools: Optional[str] = None) -> None:
19
+ raw = restricted_tools or ""
20
+ self.restricted_tools: set[str] = {
21
+ t.strip() for t in raw.split(",") if t.strip()
22
+ }
23
+ if self.restricted_tools:
24
+ logger.info(
25
+ "tool_restriction_middleware.init",
26
+ restricted_count=len(self.restricted_tools),
27
+ restricted_tools=sorted(self.restricted_tools),
28
+ )
29
+
30
+ async def on_call_tool(self, context: MiddlewareContext, call_next):
31
+ tool_name = context.message.name
32
+ if tool_name in self.restricted_tools:
33
+ logger.warning(
34
+ "tool_restriction_middleware.blocked",
35
+ tool=tool_name,
36
+ )
37
+ raise ToolError(
38
+ f"Tool '{tool_name}' is not available"
39
+ " due to access restrictions"
40
+ )
41
+ return await call_next(context)
42
+
43
+ async def on_list_tools(self, context: MiddlewareContext, call_next):
44
+ all_tools = await call_next(context)
45
+ if not self.restricted_tools:
46
+ return all_tools
47
+ filtered = [
48
+ t for t in all_tools
49
+ if t.name not in self.restricted_tools
50
+ ]
51
+ logger.debug(
52
+ "tool_restriction_middleware.filtered",
53
+ total=len(all_tools),
54
+ visible=len(filtered),
55
+ )
56
+ return filtered
altr_mcp/models.py ADDED
@@ -0,0 +1,115 @@
1
+ import structlog
2
+ from typing import Optional
3
+
4
+ from pydantic import BaseModel, Field, ValidationError
5
+
6
+ logger = structlog.get_logger(__name__)
7
+
8
+
9
+ class TimeRange(BaseModel):
10
+ hour: int
11
+ minute: int
12
+
13
+
14
+ class AccessRateThreshold(BaseModel):
15
+ access_rate_unit: str
16
+ access_rate_limit: int
17
+ action: str
18
+
19
+
20
+ class TimeWindowThreshold(BaseModel):
21
+ day: list[str]
22
+ start_time: TimeRange
23
+ end_time: TimeRange
24
+ timezone: str
25
+ action: str
26
+
27
+
28
+ def validate_access_rate_thresholds(items: list[dict]) -> Optional[str]:
29
+ """Validate a list of access rate threshold dicts.
30
+
31
+ Returns None if all items are valid, or a newline-joined string of
32
+ field-level error messages if any items are invalid.
33
+ """
34
+ if items is None:
35
+ return None
36
+
37
+ errors = []
38
+ for i, item in enumerate(items):
39
+ try:
40
+ AccessRateThreshold.model_validate(item)
41
+ except ValidationError as exc:
42
+ for err in exc.errors():
43
+ loc = ".".join(str(p) for p in err["loc"])
44
+ msg = err["msg"]
45
+ errors.append(f"access_rate_thresholds[{i}].{loc}: {msg}")
46
+
47
+ return "\n".join(errors) if errors else None
48
+
49
+
50
+ class MaskingRule(BaseModel):
51
+ """Single masking rule for add_rules tool."""
52
+ masking_policy: int = Field(ge=10000, le=10009)
53
+ role: str
54
+ tag_value: str
55
+
56
+
57
+ def validate_masking_rules(items: list[dict]) -> Optional[str]:
58
+ """Validate a list of masking rule dicts.
59
+
60
+ Returns None if valid, error string if invalid.
61
+ """
62
+ if not items:
63
+ return "No rules provided"
64
+ errors = []
65
+ for i, item in enumerate(items):
66
+ try:
67
+ MaskingRule.model_validate(item)
68
+ except ValidationError as exc:
69
+ for err in exc.errors():
70
+ loc = ".".join(str(p) for p in err["loc"])
71
+ errors.append(f"rules[{i}].{loc}: {err['msg']}")
72
+ return "\n".join(errors) if errors else None
73
+
74
+
75
+ class SidecarBinding(BaseModel):
76
+ """Sidecar listener binding parameters."""
77
+ port: int = Field(gt=0, le=65535)
78
+ repo_name: str
79
+
80
+
81
+ class SnowflakeAccessPolicyRule(BaseModel):
82
+ """Rule within a Snowflake access policy."""
83
+ masking_policy: int = Field(ge=10000, le=10009)
84
+ role: str
85
+ tag_value: str
86
+
87
+
88
+ class OltpAccessPolicyConfig(BaseModel):
89
+ """OLTP access policy configuration."""
90
+ database_id: str
91
+ table_name: str
92
+ column_name: str
93
+ tag: str
94
+
95
+
96
+ def validate_time_window_thresholds(items: list[dict]) -> Optional[str]:
97
+ """Validate a list of time window threshold dicts.
98
+
99
+ Returns None if all items are valid, or a newline-joined string of
100
+ field-level error messages if any items are invalid.
101
+ """
102
+ if items is None:
103
+ return None
104
+
105
+ errors = []
106
+ for i, item in enumerate(items):
107
+ try:
108
+ TimeWindowThreshold.model_validate(item)
109
+ except ValidationError as exc:
110
+ for err in exc.errors():
111
+ loc = ".".join(str(p) for p in err["loc"])
112
+ msg = err["msg"]
113
+ errors.append(f"time_window_thresholds[{i}].{loc}: {msg}")
114
+
115
+ return "\n".join(errors) if errors else None
altr_mcp/server.py ADDED
@@ -0,0 +1,66 @@
1
+ import asyncio as _asyncio
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from fastmcp import FastMCP
6
+ from pydantic import ValidationError
7
+
8
+ from altr_mcp.middleware import ToolRestrictionMiddleware
9
+ from altr_mcp.settings import get_settings
10
+ from altr_mcp.utils.logging import _configure_logging
11
+ from altr_mcp.tools import register_all
12
+
13
+ _INSTRUCTIONS = (
14
+ Path(__file__).parent / "instructions.md"
15
+ ).read_text(encoding="utf-8")
16
+ mcp = FastMCP("altr", instructions=_INSTRUCTIONS)
17
+ register_all(mcp)
18
+
19
+ _tool_count = len(_asyncio.get_event_loop().run_until_complete(mcp.get_tools()))
20
+ assert _tool_count == 97, (
21
+ f"Expected 97 tools registered, got {_tool_count}. "
22
+ f"Check tools/ modules for missing register() calls."
23
+ )
24
+
25
+
26
+ def main():
27
+ from dotenv import load_dotenv
28
+
29
+ load_dotenv(override=True)
30
+ try:
31
+ settings = get_settings()
32
+ except ValidationError as e:
33
+ missing = [
34
+ err["loc"][0]
35
+ for err in e.errors()
36
+ if err["type"] == "missing"
37
+ ]
38
+ if missing:
39
+ fields = ", ".join(str(f).upper() for f in missing)
40
+ print(
41
+ f"ERROR: Missing required environment variables: {fields}",
42
+ file=sys.stderr,
43
+ )
44
+ else:
45
+ print(
46
+ f"ERROR: Configuration validation failed:\n{e}",
47
+ file=sys.stderr,
48
+ )
49
+ sys.exit(1)
50
+ _configure_logging(settings)
51
+
52
+ # Register middleware before starting the server
53
+ mcp.add_middleware(
54
+ ToolRestrictionMiddleware(restricted_tools=settings.restricted_tools)
55
+ )
56
+
57
+ # Build transport kwargs — host/port only for non-stdio transports
58
+ kwargs: dict = {"transport": settings.mcp_transport}
59
+ if settings.mcp_transport in ("sse", "streamable-http"):
60
+ kwargs["host"] = settings.mcp_host
61
+ kwargs["port"] = settings.mcp_port
62
+ mcp.run(**kwargs)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
altr_mcp/settings.py ADDED
@@ -0,0 +1,74 @@
1
+ from functools import lru_cache
2
+ from typing import Literal, Optional
3
+
4
+ import httpx
5
+ from pydantic import SecretStr, computed_field
6
+ from pydantic_settings import BaseSettings, SettingsConfigDict
7
+
8
+
9
+ class Settings(BaseSettings):
10
+ model_config = SettingsConfigDict(
11
+ extra="ignore",
12
+ case_sensitive=False,
13
+ )
14
+
15
+ # Required — startup fails with ValidationError if missing
16
+ org_id: str
17
+ mapi_key: SecretStr
18
+ mapi_secret: SecretStr
19
+
20
+ # Logging configuration
21
+ log_level: str = "INFO"
22
+ log_format: str = "console" # "console" or "json"
23
+ max_retries: int = 3
24
+ disable_retry: bool = False
25
+
26
+ # Transport configuration
27
+ # MCP_TRANSPORT — "stdio", "sse", "streamable-http"
28
+ mcp_transport: Literal["stdio", "sse", "streamable-http"] = "stdio"
29
+ # MCP_HOST — bind address for HTTP transports
30
+ mcp_host: str = "0.0.0.0"
31
+ # MCP_PORT — port for HTTP transports
32
+ mcp_port: int = 8000
33
+ # RESTRICTED_TOOLS — comma-separated tool names
34
+ restricted_tools: Optional[str] = None
35
+
36
+ # URL overrides with production defaults
37
+ altr_api_base_url: str = "https://api.live.altr.com"
38
+ altr_altrnet_base_url: str = "https://altrnet.live.altr.com"
39
+ altr_classification_base_url: Optional[str] = None
40
+ altr_sc_control_base_url: Optional[str] = None
41
+ altr_service_user_base_url: Optional[str] = None
42
+
43
+ @computed_field
44
+ @property
45
+ def classification_base_url(self) -> str:
46
+ if self.altr_classification_base_url:
47
+ return self.altr_classification_base_url
48
+ return f"https://{self.org_id}.classification.live.altr.com"
49
+
50
+ @computed_field
51
+ @property
52
+ def sc_control_base_url(self) -> str:
53
+ if self.altr_sc_control_base_url:
54
+ return self.altr_sc_control_base_url
55
+ return f"https://{self.org_id}.sc-control.live.altr.com"
56
+
57
+ @computed_field
58
+ @property
59
+ def service_user_base_url(self) -> str:
60
+ if self.altr_service_user_base_url:
61
+ return self.altr_service_user_base_url
62
+ return f"https://{self.org_id}.service-user.live.altr.com"
63
+
64
+ @property
65
+ def auth(self) -> httpx.BasicAuth:
66
+ return httpx.BasicAuth(
67
+ username=self.mapi_key.get_secret_value(),
68
+ password=self.mapi_secret.get_secret_value(),
69
+ )
70
+
71
+
72
+ @lru_cache(maxsize=1)
73
+ def get_settings() -> Settings:
74
+ return Settings()
@@ -0,0 +1,29 @@
1
+ from fastmcp import FastMCP
2
+
3
+
4
+ def register_all(mcp: FastMCP) -> None:
5
+ """Register all tool handlers with the MCP server.
6
+
7
+ Imports are deferred to avoid circular dependencies with server.py.
8
+ """
9
+ from altr_mcp.tools import (
10
+ access_management,
11
+ access_request,
12
+ audit,
13
+ classification,
14
+ database,
15
+ policy,
16
+ sidecar_config,
17
+ tag,
18
+ telemetry,
19
+ )
20
+
21
+ policy.register(mcp)
22
+ tag.register(mcp)
23
+ classification.register(mcp)
24
+ database.register(mcp)
25
+ access_management.register(mcp)
26
+ access_request.register(mcp)
27
+ telemetry.register(mcp)
28
+ audit.register(mcp)
29
+ sidecar_config.register(mcp)
@@ -0,0 +1,172 @@
1
+ from fastmcp import FastMCP
2
+ from altr_mcp.utils.logging import log_tool
3
+ from altr_mcp.settings import get_settings
4
+ from altr_mcp.utils import access_management
5
+
6
+
7
+ def register(mcp: FastMCP) -> None:
8
+ @mcp.tool()
9
+ @log_tool
10
+ async def create_snowflake_access_policy(
11
+ policy_name: str,
12
+ description: str,
13
+ connection_id: int,
14
+ rules: str | list[dict],
15
+ policy_maintenance: dict | None = None,
16
+ access_request_id: str | None = None
17
+ ) -> dict:
18
+ """Create an access management policy for a Snowflake datasource.
19
+
20
+ Defines which roles can access which databases, schemas, or tables
21
+ with read or write permissions. Policies are enforced by ALTR and
22
+ checked on a schedule.
23
+
24
+ Each rule in the list must contain:
25
+ - actors: list of dicts with 'type' ("role"),
26
+ 'condition' ("equals"|"starts_with"|"ends_with"),
27
+ and 'identifiers' (list of str).
28
+ - objects: list of dicts with 'type'
29
+ ("database"|"schema"|"table"), 'condition'
30
+ ("equals"|"starts_with"|"ends_with"|
31
+ "fully_qualified"), and 'identifiers' (list of
32
+ str) or 'fully_qualified_identifiers' (list of
33
+ dicts with database/schema/table/view keys).
34
+ - access: list of dicts with 'name' ("read"|"write").
35
+
36
+ Optionally, rules may include 'tagged_objects' for tag-based targeting:
37
+ - tagged_objects: list of dicts with 'check_against'
38
+ (list of "databases"|"schemas"|"tables"|"views"),
39
+ 'tagged_with' (list of dicts with database/schema/name/value keys),
40
+ and 'tag_condition' ("or"|"and").
41
+
42
+ Args:
43
+ policy_name: Name for the policy (1-255 chars).
44
+ description: Description of the policy (1-255 chars).
45
+ connection_id: ALTR connection ID for the Snowflake database.
46
+ rules: List of access rule objects, or a JSON string encoding
47
+ such a list.
48
+ policy_maintenance: Optional schedule dict with
49
+ 'rate' ("day"|"cron") and 'value' (number
50
+ or cron string).
51
+ access_request_id: Optional access request ID this policy fulfills.
52
+ """
53
+ if isinstance(rules, str):
54
+ import json
55
+ rules = json.loads(rules)
56
+ data = {
57
+ "policy_name": policy_name,
58
+ "description": description,
59
+ "connection_ids": [connection_id],
60
+ "rules": rules,
61
+ }
62
+ if policy_maintenance is not None:
63
+ data["policy_maintenance"] = policy_maintenance
64
+ if access_request_id is not None:
65
+ data["access_request_id"] = access_request_id
66
+
67
+ settings = get_settings()
68
+ response = await access_management.create_snowflake_access_policy(
69
+ settings.auth, data)
70
+ return {"success": True, "data": response, "error": None}
71
+
72
+ @mcp.tool()
73
+ @log_tool
74
+ async def create_oltp_access_policy(
75
+ policy_name: str,
76
+ description: str,
77
+ repo_name: str,
78
+ database_type: int,
79
+ database_type_name: str,
80
+ rules: str | list[dict],
81
+ case_sensitivity: str = "case_sensitive"
82
+ ) -> dict:
83
+ """Create an access management policy for an OLTP datasource.
84
+
85
+ Each rule in the list must contain:
86
+ - type: "read"
87
+ - actors: list of dicts with 'type' ("idp_user"|"idp_group"),
88
+ 'condition' ("equals"), and 'identifiers' (list of str).
89
+ - objects: list of dicts with 'type' ("column") and 'identifiers'
90
+ (list of dicts with database/schema/table/column keys, each having
91
+ 'name' (str) and 'wildcard' (bool)).
92
+
93
+ Args:
94
+ policy_name: Name for the policy (1-255 chars).
95
+ description: Description of the policy (1-255 chars).
96
+ repo_name: Repository/connection name.
97
+ database_type: Database type code (e.g., 4 for Oracle).
98
+ database_type_name: Database type name (e.g., "oracle").
99
+ rules: List of OLTP access rule objects, or a JSON string
100
+ encoding such a list.
101
+ case_sensitivity: Case sensitivity setting
102
+ (default: "case_sensitive").
103
+ """
104
+ if isinstance(rules, str):
105
+ import json
106
+ rules = json.loads(rules)
107
+ data = {
108
+ "policy_name": policy_name,
109
+ "description": description,
110
+ "repo_name": repo_name,
111
+ "database_type": database_type,
112
+ "database_type_name": database_type_name,
113
+ "rules": rules,
114
+ "case_sensitivity": case_sensitivity,
115
+ }
116
+
117
+ settings = get_settings()
118
+ response = await access_management.create_oltp_access_policy(
119
+ settings.auth, data)
120
+ return {"success": True, "data": response, "error": None}
121
+
122
+ @mcp.tool()
123
+ @log_tool
124
+ async def update_snowflake_access_policy(
125
+ policy_id: str,
126
+ policy_name: str,
127
+ rules: str | list[dict],
128
+ description: str | None = None
129
+ ) -> dict:
130
+ """Update an existing Snowflake access management policy.
131
+
132
+ Replaces the policy's name, description, and rules. See
133
+ `create_snowflake_access_policy` for the rule format.
134
+
135
+ Args:
136
+ policy_id: Raw policy ID. Do not URL-encode.
137
+ policy_name: Updated policy name (1-255 chars).
138
+ rules: Updated list of access rule objects, or a JSON string
139
+ encoding such a list.
140
+ description: Updated description (1-255 chars).
141
+ """
142
+ if isinstance(rules, str):
143
+ import json
144
+ rules = json.loads(rules)
145
+ data = {
146
+ "policy_name": policy_name,
147
+ "rules": rules,
148
+ }
149
+ if description is not None:
150
+ data["description"] = description
151
+
152
+ settings = get_settings()
153
+ response = await access_management.update_snowflake_access_policy(
154
+ settings.auth, policy_id, data)
155
+ return {"success": True, "data": response, "error": None}
156
+
157
+ @mcp.tool()
158
+ @log_tool
159
+ async def trigger_access_policy_check(policy_id: str) -> dict:
160
+ """Trigger a manual compliance check for a
161
+ grant/access management policy.
162
+
163
+ Runs the policy check immediately instead of waiting for the next
164
+ scheduled run.
165
+
166
+ Args:
167
+ policy_id: Raw policy ID. Do not URL-encode.
168
+ """
169
+ settings = get_settings()
170
+ response = await access_management.trigger_access_policy_check(
171
+ settings.auth, policy_id)
172
+ return {"success": True, "data": response, "error": None}