Solution architecture outcome pattern: agent and its MCP servers
Some checks failed
check agents / check (push) Failing after 13s

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>
This commit is contained in:
2026-11-05 22:13:25 +00:00
parent 8bb62a4a42
commit bc84ee4df6
267 changed files with 44287 additions and 45 deletions

View File

@@ -0,0 +1,47 @@
# sa-aws-cloud: the AWS counterpart of each source tool. Only list, describe and get operations are named here, and
# every call goes through the customer's read-only role, inside the connection's accounts and regions.
async def _aws_list(tool: str, arguments: Dict[str, Any], entry: tuple, wanted: Optional[List[str]] = None) -> Dict[str, Any]:
"""One page; `wanted` adds caller values to the fixed request, as (parameter, argument) pairs of a required value."""
service, operation, result_key, token_in, token_out, fixed = entry
fixed = dict(fixed)
for parameter, argument in wanted or []:
if not arguments.get(argument):
return _refuse("invalid_argument", f"{argument} is required")
fixed[parameter] = arguments[argument]
return await _aws_kind(tool, {**arguments, "kind": "one"}, {"one": (service, operation, result_key, token_in, token_out, fixed)}, "one")
async def _aws_get(tool: str, arguments: Dict[str, Any], service: str, operation: str, request: Dict[str, Any]) -> Dict[str, Any]:
account, region, refused = _aws_target(arguments)
if refused:
return refused
missing = [k for k, v in request.items() if v in (None, "", [], [None])]
if missing:
return _refuse("invalid_argument", "missing: " + ", ".join(missing))
try:
body = await _aws_call(arguments, service, operation, region, **request)
except Exception as error:
return _upstream_failed("aws", error)
body.pop("ResponseMetadata", None)
return _one_result("aws", tool, arguments, body)
async def _aws_metric_data(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
queries, start, end = arguments.get("metric_queries"), arguments.get("start_time"), arguments.get("end_time")
if not isinstance(queries, list) or not queries or not start or not end:
return _refuse("invalid_argument", "metric_queries, start_time and end_time are required")
return await _aws_get(tool, arguments, "cloudwatch", "get_metric_data",
{"MetricDataQueries": queries, "StartTime": start, "EndTime": end})
def _aws_docs_connection() -> Dict[str, Any]:
connection = get_connection()
return {"aws_access_key_id": connection.get("docs_access_key_id") or connection.get("access_key_id"),
"aws_secret_access_key": connection.get("docs_secret_access_key") or connection.get("secret_access_key")}
def _aws_docs_request(url: Any) -> Dict[str, Any]:
"""The call shape AWS's documentation reader takes (agent-toolkit-for-aws)."""
return {"requests": [{"url": url, "max_length": 100000}]}

View File

@@ -0,0 +1,102 @@
# 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")

View File

@@ -0,0 +1,5 @@
# Every documentation query is logged. Free text by the owner's decision (see ../README.md).
def _docs_query_logged(provider: str, tool: str, query: Any) -> None:
logger.info("docs_query", provider=provider, tool=tool, query=str(query))

View File

@@ -0,0 +1,41 @@
# Documentation search, free text by the owner's decision (see ../README.md). Queries go to the vendor as written and
# every one is logged. Built on the session and sign-in code in the shared knowledge_support.py.
DOCS_MAX_TEXT = 20000
async def _docs_call(provider: str, connection: Dict[str, Any], name: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Call one tool on the vendor's documentation server, once that server says it still offers it."""
session = await _knowledge_session(provider, connection)
tools = {t.get("name") for t in await _knowledge_tools(provider, connection, session)}
if name not in tools:
raise LookupError(f"{provider} no longer offers {name}")
response = await _knowledge_post(provider, connection, {
"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": name, "arguments": arguments}}, session)
parts = _knowledge_message(response).get("result", {}).get("content", [])
return [{"text": str(p.get("text"))[:DOCS_MAX_TEXT]} for p in parts if p.get("type") == "text"]
async def _docs_search(provider: str, tool: str, arguments: Dict[str, Any], connection: Dict[str, Any]) -> Dict[str, Any]:
query = str(arguments.get("query") or "").strip()
if not query:
return _refuse("invalid_argument", "query is required")
_docs_query_logged(provider, tool, query)
try:
found = await _knowledge_search(provider, connection, query)
except Exception as error:
return _upstream_failed(provider, error)
return _page_result(provider, tool, arguments, found, None, None)
async def _docs_read(provider: str, tool: str, arguments: Dict[str, Any], connection: Dict[str, Any], name: str,
field: str, shape=None) -> Dict[str, Any]:
target = arguments.get(field)
if not target:
return _refuse("invalid_argument", f"{field} is required")
_docs_query_logged(provider, tool, target)
try:
found = await _docs_call(provider, connection, name, shape(target) if shape else {field: target})
except Exception as error:
return _upstream_failed(provider, error)
return _page_result(provider, tool, arguments, found, None, None)

View File

@@ -0,0 +1,130 @@
# sa-gcp-cloud: the tools of gcp_solution_architecture_agent, forwarded to the same hosted Google MCP servers under the
# same allow lists (providers/gcp.yaml). Nothing outside GCP_MCP_SERVERS is reachable.
GCP_MCP_SERVERS = {
"developer_knowledge": {"url": "https://developerknowledge.googleapis.com/mcp",
"allow": ("search_documents", "get_documents", "answer_query")},
"resource_manager": {"url": "https://cloudresourcemanager.googleapis.com/mcp", "allow": ("search_projects",)},
"asset_inventory": {"url": "https://cloudasset.googleapis.com/mcp", "allow": ("list_assets", "analyze_iam_policy")},
"compute": {"url": "https://compute.googleapis.com/mcp",
"allow": ("list_instances", "get_instance_basic_info", "list_instance_attached_disks",
"list_instance_group_managers", "get_instance_group_manager_basic_info",
"list_instance_templates", "get_instance_template_properties", "list_disks",
"get_disk_basic_info", "list_reservations", "list_commitments")},
"gke": {"url": "https://container.googleapis.com/mcp",
"allow": ("list_clusters", "get_cluster", "list_node_pools", "get_node_pool", "get_k8s_version")},
"cloud_run": {"url": "https://run.googleapis.com/mcp", "allow": ("list_services", "get_service")},
"cloud_sql": {"url": "https://sqladmin.googleapis.com/mcp", "allow": ("list_instances", "get_instance")},
"storage": {"url": "https://storage.googleapis.com/storage/mcp", "allow": ("list_buckets",)},
"pubsub": {"url": "https://pubsub.googleapis.com/mcp",
"allow": ("list_topics", "get_topic", "list_subscriptions", "get_subscription")},
"iam": {"url": "https://iam.googleapis.com/mcp",
"allow": ("list_roles", "get_role", "list_deny_policies", "get_deny_policy")},
"monitoring": {"url": "https://monitoring.googleapis.com/mcp",
"allow": ("list_alert_policies", "get_alert_policy", "list_dashboards", "list_metric_descriptors",
"list_timeseries")},
"network_intelligence": {"url": "https://networkmanagement.googleapis.com/mcp",
"allow": ("list_connectivity_tests", "get_connectivity_test")},
}
GCP_DOCS_SERVER = "developer_knowledge"
async def _gcp_mcp_headers(server_name: str) -> Dict[str, str]:
headers = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json"}
connection = get_connection()
if server_name == GCP_DOCS_SERVER and connection.get("docs_api_key"):
headers["X-Goog-Api-Key"] = str(connection["docs_api_key"])
else:
headers["Authorization"] = f"Bearer {await _gcp_token()}"
if connection.get("quota_project"):
headers["X-Goog-User-Project"] = str(connection["quota_project"])
return headers
async def _gcp_mcp_post(server_name: str, body: Dict[str, Any], session: Optional[str] = None):
headers = await _gcp_mcp_headers(server_name)
if session:
headers["Mcp-Session-Id"] = session
url = GCP_MCP_SERVERS[server_name]["url"]
response = await _with_backoff(lambda: _gcp_client().post(url, content=json.dumps(body), headers=headers))
response.raise_for_status()
return response
def _gcp_mcp_message(response) -> Dict[str, Any]:
"""The JSON-RPC reply, whether it came back as JSON or as a server-sent event."""
if "text/event-stream" in response.headers.get("content-type", ""):
lines = [line[5:].strip() for line in response.text.splitlines() if line.startswith("data:")]
return json.loads(lines[-1]) if lines else {}
return response.json()
async def _gcp_mcp_session(server_name: str) -> Optional[str]:
response = await _gcp_mcp_post(server_name, {
"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "sa-gcp-cloud", "version": "0.1.0"}}})
session = response.headers.get("mcp-session-id")
await _gcp_mcp_post(server_name, {"jsonrpc": "2.0", "method": "notifications/initialized"}, session)
return session
async def _gcp_mcp_tools(server_name: str, session: Optional[str]) -> Dict[str, Dict[str, Any]]:
response = await _gcp_mcp_post(server_name, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, session)
return {t.get("name"): t for t in _gcp_mcp_message(response).get("result", {}).get("tools", [])}
def _gcp_mcp_payload(result: Dict[str, Any]) -> Any:
if result.get("structuredContent") is not None:
return result["structuredContent"]
parts = []
for part in result.get("content", []):
if part.get("type") != "text":
continue
try:
parts.append(json.loads(part["text"]))
except ValueError:
parts.append(part["text"])
return parts[0] if len(parts) == 1 else parts
async def _gcp_forward(tool: str, server_name: str, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
"""One allow-listed tool on one hosted server. As in the source, a tool must declare itself read-only."""
entry = GCP_MCP_SERVERS.get(server_name)
if not entry or name not in entry["allow"]:
return _refuse("not_allowed", "this tool isn't on the allow list")
passed = arguments.get("tool_arguments") or {}
if not isinstance(passed, dict):
return _refuse("invalid_argument", "tool_arguments must be an object")
if server_name == GCP_DOCS_SERVER:
_docs_query_logged("gcp", tool, json.dumps(passed, sort_keys=True))
try:
session = await _gcp_mcp_session(server_name)
tools = await _gcp_mcp_tools(server_name, session)
if name not in tools:
return _refuse("not_offered", "Google no longer offers this tool")
if not tools[name].get("annotations", {}).get("readOnlyHint"):
return _refuse("not_read_only", "the tool doesn't declare itself read-only")
response = await _gcp_mcp_post(server_name, {
"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": name, "arguments": passed}}, session)
message = _gcp_mcp_message(response)
except Exception as error:
return _upstream_failed("gcp", error)
result = message.get("result") or {}
if message.get("error") or result.get("isError"):
return _refuse("upstream_refused", f"{name} refused the request")
return _one_result("gcp", tool, arguments, _gcp_mcp_payload(result))
async def _gcp_describe(arguments: Dict[str, Any]) -> Dict[str, Any]:
server_name, name = str(arguments.get("server") or ""), str(arguments.get("tool") or "")
entry = GCP_MCP_SERVERS.get(server_name)
if not entry or name not in entry["allow"]:
return _refuse("not_allowed", "this tool isn't on the allow list")
try:
tools = await _gcp_mcp_tools(server_name, await _gcp_mcp_session(server_name))
except Exception as error:
return _upstream_failed("gcp", error)
if name not in tools:
return _refuse("not_offered", "Google no longer offers this tool")
return _one_result("gcp", "gcp_describe_tool", arguments, {
"description": tools[name].get("description"), "input_schema": tools[name].get("inputSchema")})