Files
cp1-agents/outcome-pattern/solution_architecture/mcp-servers/_support/gcp_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

131 lines
7.2 KiB
Python

# 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")})