Files
cp1-agents/outcome-pattern/solution_architecture/mcp-servers/_support/azure_tools.py
Jonathan Boniface bc84ee4df6
Some checks failed
check agents / check (push) Failing after 13s
Solution architecture outcome pattern: agent and its MCP servers
The cp1-solution-architecture-agent and the sa-aws/azure/gcp-cloud MCP servers, a separate
stream from the individual and sub-agent patterns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:13:25 +00:00

103 lines
5.5 KiB
Python

# sa-azure-cloud: the Azure counterpart of each source tool. Reads go through Resource Graph where it holds the data,
# under the connection's scope, and otherwise through ARM GET on a subscription or resource inside that scope.
AZURE_ID = r"/subscriptions/[A-Za-z0-9\-]+(/[A-Za-z0-9._()\-]+)+"
AZURE_ROLE_ASSIGNMENTS = "microsoft.authorization/roleassignments"
AZURE_ROLE_DEFINITIONS = "microsoft.authorization/roledefinitions"
async def _azure_list(tool: str, arguments: Dict[str, Any], table: str, types: List[str]) -> Dict[str, Any]:
return await _azure_page(tool, arguments, _azure_type_query(table, types))
async def _azure_get(tool: str, arguments: Dict[str, Any], table: str, types: List[str]) -> Dict[str, Any]:
resource_id = str(arguments.get("resource_id") or "")
if not re.fullmatch(AZURE_ID, resource_id) and not resource_id.startswith("/providers/Microsoft.Authorization/"):
return _refuse("invalid_argument", "resource_id must be a full ARM resource id")
if "'" in resource_id:
return _refuse("invalid_argument", "resource_id must be a full ARM resource id")
listed = ", ".join(f"'{t}'" for t in types)
try:
body = await _azure_graph(f"{table} | where id =~ '{resource_id}' and type in~ ({listed})", 1)
except Exception as error:
return _upstream_failed("azure", error)
if not body.get("data"):
return _refuse("outside_scope", "no such resource inside this connection's scope")
return _one_result("azure", tool, arguments, body["data"][0])
async def _azure_in_scope(resource_id: str) -> bool:
if not re.fullmatch(AZURE_ID, resource_id) or "'" in resource_id:
return False
return bool((await _azure_graph(f"Resources | where id =~ '{resource_id}'", 1)).get("data"))
async def _azure_arm(tool: str, arguments: Dict[str, Any], path: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""One page from ARM. A next link carries the bearer token wherever it points, so it must stay on this path."""
try:
upstream, skip = _read_page(arguments)
except (ValueError, KeyError, TypeError):
return _refuse("invalid_page_token", "page_token isn't one this server issued")
connection = get_connection()
base = f"{_azure_endpoints(connection)['arm']}{path}"
if upstream and not upstream.startswith(f"{base}?"):
return _refuse("invalid_page_token", "page_token isn't one this server issued")
try:
token = await _azure_token(connection)
send = {"headers": {"Authorization": f"Bearer {token}"}}
if not upstream:
send["params"] = params
response = await _with_backoff(lambda: _azure_client().get(upstream or base, **send))
response.raise_for_status()
body = response.json()
except Exception as error:
return _upstream_failed("azure", error)
items = body.get("value", [body] if body else [])
return _page_result("azure", tool, arguments, items, upstream, body.get("nextLink"), skip)
async def _azure_subscription_arm(tool: str, arguments: Dict[str, Any], tail: str, params: Dict[str, Any]) -> Dict[str, Any]:
try:
subscription = await _azure_lock_subscription(arguments)
except Exception as error:
return _upstream_failed("azure", error)
if not subscription:
return _refuse("outside_scope", "subscription_id must name a subscription under this connection's scope")
return await _azure_arm(tool, arguments, f"/subscriptions/{subscription}{tail}", params)
async def _azure_resource_arm(tool: str, arguments: Dict[str, Any], tail: str, params: Dict[str, Any]) -> Dict[str, Any]:
resource_id = str(arguments.get("resource_id") or "")
try:
inside = await _azure_in_scope(resource_id)
except Exception as error:
return _upstream_failed("azure", error)
if not inside:
return _refuse("outside_scope", "no such resource inside this connection's scope")
return await _azure_arm(tool, arguments, f"{resource_id}{tail}", params)
async def _azure_attached_disks(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
resource_id = str(arguments.get("resource_id") or "")
if not re.fullmatch(AZURE_ID, resource_id) or "'" in resource_id:
return _refuse("invalid_argument", "resource_id must be a full ARM resource id")
return await _azure_page(tool, arguments, f"Resources | where type =~ 'microsoft.compute/disks' and managedBy =~ '{resource_id}' | order by id asc")
async def _azure_node_pools(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
return await _azure_page(tool, arguments, "Resources | where type =~ 'microsoft.containerservice/managedclusters' | mv-expand pool = properties.agentPoolProfiles | project id, name, pool | order by id asc")
async def _azure_access(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
"""Role assignments, optionally for one principal or below one scope."""
query = f"AuthorizationResources | where type =~ '{AZURE_ROLE_ASSIGNMENTS}'"
principal, scope = arguments.get("principal_id"), arguments.get("scope")
if principal:
if not re.fullmatch(r"[A-Fa-f0-9\-]{36}", str(principal)):
return _refuse("invalid_argument", "principal_id must be an object id")
query += f" | where properties.principalId =~ '{principal}'"
if scope:
if not re.fullmatch(r"/[A-Za-z0-9._()/\-]+", str(scope)):
return _refuse("invalid_argument", "scope must be an ARM scope")
query += f" | where properties.scope startswith '{scope}'"
return await _azure_page(tool, arguments, query + " | order by id asc")