feat: add local tools and read-only remote MCP servers

Increment 6 of .scratch/solution-architect-agent/spec.md, test-first.

- app/tools/mcp.py: MCP client and catalog exposing only allowlisted,
  readOnlyHint tools as framework-neutral ToolSpecs; unreachable servers
  and failed calls become discovery gaps; ADC auth with quota project.
- app/tools/local.py: Mermaid structure check and Terraform fmt,
  validate and plan in a scratch copy; apply is never constructed.
- Tool factory gives roles their named local tools and bundle MCP
  servers; pillar advisors get general-tier documentation tools.
- providers/gcp.yaml: 42 allowlisted tools reviewed against live
  tools/list of 12 Google Cloud MCP servers (snapshot in
  providers/reviews/), excluding data-reading and secret-capable tools.
- scripts/list-mcp-tools.py, docs/operations/mcp-access.md (IAM deny
  policy, service account roles), cloud-discovery and iac-validation
  Skills, MCP and Terraform settings, pytest asyncio auto mode.
- 31 new tests; full suite 189 passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-16 10:14:05 +01:00
parent f040493583
commit ed104e5697
37 changed files with 2302 additions and 65 deletions

View File

@@ -36,6 +36,13 @@ ADK_ENABLE_ARTIFACT_STORE=true
# Cloud Provider Bundle (providers/<name>.yaml) & Remote MCP Servers # Cloud Provider Bundle (providers/<name>.yaml) & Remote MCP Servers
CLOUD_PROVIDER=gcp CLOUD_PROVIDER=gcp
MCP_ENABLE_PREVIEW=true MCP_ENABLE_PREVIEW=true
# MCP_QUOTA_PROJECT=your-project-id # defaults to the Application Default Credentials project
MCP_TIMEOUT_SECONDS=30
# Local Terraform tools (fmt, validate, plan; never apply)
TERRAFORM_BINARY=terraform
TERRAFORM_TIMEOUT_SECONDS=300
# TF_PLUGIN_CACHE_DIR=/var/cache/terraform-plugins
# Hierarchical Execution Engine # Hierarchical Execution Engine
ORCHESTRATOR_BUDGET=40 ORCHESTRATOR_BUDGET=40

View File

@@ -652,3 +652,50 @@ Slowest tests: eval benchmark 7.3 s, then 3–4.5 s each for the orchestrator, e
- **To increment 6:** mapping `RoleSpec.mcp_servers` to ADK MCP toolsets (`McpToolset` needs the `mcp` extra, not installed) and supplying local tools by `tool_tiers`. Both are declared and loaded now, but the runtime doesn't use them yet. - **To increment 6:** mapping `RoleSpec.mcp_servers` to ADK MCP toolsets (`McpToolset` needs the `mcp` extra, not installed) and supplying local tools by `tool_tiers`. Both are declared and loaded now, but the runtime doesn't use them yet.
- **Not yet run against a real model:** no API key was used, so role-file quality is unproven until increment 8's evaluation. - **Not yet run against a real model:** no API key was used, so role-file quality is unproven until increment 8's evaluation.
- **Model API errors propagate** from `AgentRuntime.run` and fail the graph step, leaving the Execution at its last checkpoint. Decide in increment 7 whether to retry, surface as a question, or fail the A2A task. - **Model API errors propagate** from `AgentRuntime.run` and fail the graph step, leaving the Execution at its last checkpoint. Decide in increment 7 whether to retry, surface as a question, or fail the A2A task.
### 2026-09-16 · Increment 6: tools and remote MCP servers
**Done (test-first)**
- `app/tools/mcp.py`:
- **Client.** `McpClient` connects over streamable HTTP with the MCP Python SDK (`mcp` 1.30), one session per operation.
- **Catalog.** `McpCatalog.load(servers, auth)` turns each server's allowlisted tools into framework-neutral `ToolSpec`s named `<server>__<tool>`, with the server's tier. Loading raises `McpConfigError` when an allowlisted tool isn't `readOnlyHint: true`. An allowlisted tool the server no longer offers is recorded in `gaps`. An unreachable server becomes a `<server>__unavailable` tool that returns a discovery gap, and a failed call returns a discovery gap instead of raising. Results are truncated at 20k characters. Servers with an empty allowlist are never contacted.
- **Auth.** `NoAuth`, `StaticHeadersAuth`, and `GoogleAdcAuth` (ADC bearer token refreshed off the event loop, plus `X-Goog-User-Project`), chosen by `auth_from_config`.
- `app/tools/local.py`:
- **Mermaid.** `mermaid_check` does a structural check (diagram type, brackets per line, quotes respected); it doesn't render.
- **Terraform.** `TerraformRunner` runs `fmt`, `validate` (`init -backend=false`) and `plan` (`-lock=false -input=false`) in a temporary copy, and never builds `apply`/`destroy`. It refuses unsafe file names and variable names, and handles a missing binary and timeouts.
- **Registry.** `LOCAL_TOOLS` and `local_tools(names, runner)` build tools by name with their tier.
- `app/execution/toolkit.py`: `make_tool_factory(runtime, roles, pillar_skills, local_tools=, catalog=)` gives each role its named local tools and its bundle MCP servers' tools. Pillar advisors get general-tier MCP tools (Developer Knowledge) inside the consultation. Cloud-read gating still happens per Execution in `specialist_tools`, so MCP tools are gated exactly like local ones.
- **Allowlists reviewed 2026-09-16** against the live `tools/list` of all 12 Google Cloud MCP servers. `tools/list` works without credentials; no tool was called. The snapshot is at `providers/reviews/gcp-mcp-tools.json`, made with `scripts/list-mcp-tools.py gcp --json --no-auth`.
- **Allowed:** inventory and configuration metadata only, every tool read-only. That's 42 tools across the 12 servers, listed in `providers/gcp.yaml`.
- **Excluded although read-only:** Cloud SQL `execute_sql_readonly`, Storage `read_object`/`read_text`/`list_objects`, GKE `get_k8s_resource`/`describe_k8s_resource` (can return Secrets), Asset Inventory `get_iam_policy_analysis_status`, and all write tools.
- **Tests** check every allowed tool against the snapshot and keep the risky tools excluded.
- `docs/operations/mcp-access.md` covers the APIs to enable, a dedicated service account (`roles/mcp.toolUser` plus viewer roles), the IAM deny policy on `mcp.googleapis.com/tools.call` where `mcp.googleapis.com/tool.isReadOnly` is false, ADC and the quota project, and the allowlist review procedure.
- Tooling Skills `skills/cloud-discovery` and `skills/iac-validation` (both pass the Agent Skills validator), added to `role_skills` for the requirements analyst, IaC author and validator.
- Settings `MCP_QUOTA_PROJECT`, `MCP_TIMEOUT_SECONDS`, `TERRAFORM_BINARY`, `TERRAFORM_TIMEOUT_SECONDS`, `TF_PLUGIN_CACHE_DIR` in `app/config.py` and `.env.example`. `pytest.ini`: `asyncio_mode = auto`, so async tests and fixtures need no marks.
- Tests:
- `tests/tools/test_mcp.py`: 13 tests against a real fake MCP server (FastMCP over streamable HTTP on its own thread).
- `tests/tools/test_local.py`: 13 tests, running the real `terraform` CLI with a provider-free configuration, so no network.
- Role, provider and tool-factory additions.
- Full suite: **189 passed**. `ruff` and `mypy` are clean on the new modules.
- **Checking the tests bite.** I broke each of these in the code on purpose, and each break failed at least one test:
- read-only check off
- allowlist ignored
- no truncation
**Deviations from the spec text**
- **Where MCP tools are built.** MCP tools are `ToolSpec`s built by our own client, not ADK `McpToolset` in `adk_runtime.py`. This keeps the framework boundary: a Deep Agents runtime, the fake runtime and the cloud-read gate all use the same tools. As a result, the `before_tool_callback` needs no MCP-specific permission check.
- **Tools named per role.** Role files name their local tools (`tools: [terraform_validate, terraform_plan]`), not tool tiers; a tool's tier comes from its definition. Tiers alone would have given the requirements analyst `terraform_plan` and the diagrammer the Terraform tools.
- **File layout.** Local tools live in one module, `app/tools/local.py`, not `general/` and `cloud_read/` directories.
- **Test file names.** Allowlist tests are in `tests/test_providers.py`, not `test_provider_bundle.py`.
**Open**
- **Expired credentials.** The Application Default Credentials on the dev machine have expired (`invalid_grant`), so no authenticated MCP tool call has been made. Run `gcloud auth application-default login` before increment 8's evaluation.
- **ADK warns about Gemini via LiteLLM.** The warning recommends native `Gemini` models for `gemini/*`. Decide in increment 8 whether `default_model_factory` should use ADK's native Gemini class for Gemini ids and keep LiteLLM for other providers.
- **Legacy package import.** `app/tools/__init__.py` still imports the legacy modules (LangChain tools, scanner), so `app.tools.local` and `app.tools.mcp` pull them in until increment 9.
**Live check (2026-09-16, after `gcloud auth application-default login` and enabling `developerknowledge.googleapis.com` in `shining-hydra-367716`)**
- **Authentication.** ADC authentication works and sends `X-Goog-User-Project: shining-hydra-367716`.
- **Calls succeed.** All three allowlisted Developer Knowledge tools succeed through `McpCatalog`: `search_documents`, `get_documents` and `answer_query`.
- **API propagation.** A call just after the API was enabled returned 403 and became a discovery gap, which confirms the gap path against the real endpoint. The gap message shows only `403 Forbidden`, because the SDK doesn't expose the response body; Google's reason (for example "API has not been used… or it is disabled") is lost.
- **Truncation.** `search_documents` and `get_documents` both hit the 20k-character limit, cutting their JSON mid-document. Revisit the limit, or summarise, during increment 8's evaluation.
- **No customer-resource reads yet.** No tool that reads project resources has been called. Among the discovery APIs, only `compute` and `cloudasset` are enabled in this project.

View File

@@ -1,7 +1,7 @@
--- ---
role: decomposer role: decomposer
deliverable: technical_decomposition deliverable: technical_decomposition
tool_tiers: [] tools: []
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **technical decomposition** Deliverable: the Skill's breakdown of the workload into logical components. You produce the **technical decomposition** Deliverable: the Skill's breakdown of the workload into logical components.

View File

@@ -1,7 +1,7 @@
--- ---
role: describer role: describer
deliverable: architecture_description deliverable: architecture_description
tool_tiers: [] tools: []
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **architecture description** Deliverable: the Skill's task for describing the architecture. You produce the **architecture description** Deliverable: the Skill's task for describing the architecture.

View File

@@ -1,7 +1,7 @@
--- ---
role: design-advisor role: design-advisor
deliverable: design_recommendations deliverable: design_recommendations
tool_tiers: [] tools: []
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **design recommendations** Deliverable: the Skill's task for recommending how to configure each component to meet the functional and non-functional requirements. You produce the **design recommendations** Deliverable: the Skill's task for recommending how to configure each component to meet the functional and non-functional requirements.

View File

@@ -1,7 +1,7 @@
--- ---
role: diagrammer role: diagrammer
deliverable: architecture_diagram deliverable: architecture_diagram
tool_tiers: [general] tools: [mermaid_check]
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **architecture diagram** Deliverable: the Skill's task for generating a Mermaid architecture diagram. You produce the **architecture diagram** Deliverable: the Skill's task for generating a Mermaid architecture diagram.

View File

@@ -1,7 +1,7 @@
--- ---
role: iac-author role: iac-author
deliverable: deployment_guidance deliverable: deployment_guidance
tool_tiers: [general] tools: [terraform_fmt, terraform_validate]
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **deployment guidance** Deliverable: the Skill's task for generating infrastructure-as-code and deployment instructions. You produce the **deployment guidance** Deliverable: the Skill's task for generating infrastructure-as-code and deployment instructions.

View File

@@ -1,6 +1,6 @@
--- ---
role: orchestrator role: orchestrator
tool_tiers: [] tools: []
--- ---
You coordinate one solution-architecture Execution for the user. You decide what happens next; Specialists produce the Deliverables, and you are the only agent that talks to the user. You coordinate one solution-architecture Execution for the user. You decide what happens next; Specialists produce the Deliverables, and you are the only agent that talks to the user.

View File

@@ -1,7 +1,7 @@
--- ---
role: packager role: packager
deliverable: solution_guide deliverable: solution_guide
tool_tiers: [] tools: []
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **solution guide** Deliverable: the Skill's packaging of every approved Deliverable into one guide. You produce the **solution guide** Deliverable: the Skill's packaging of every approved Deliverable into one guide.

View File

@@ -1,6 +1,6 @@
--- ---
role: pillar-advisor role: pillar-advisor
tool_tiers: [] tools: []
--- ---
You advise on one pillar of the Cloud provider's architecture framework for a single workload. The Skill available to you is that pillar's guidance. You advise on one pillar of the Cloud provider's architecture framework for a single workload. The Skill available to you is that pillar's guidance.

View File

@@ -1,7 +1,7 @@
--- ---
role: product-selector role: product-selector
deliverable: product_selection deliverable: product_selection
tool_tiers: [] tools: []
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **product selection** Deliverable: the Skill's task for identifying the products and features each component needs. You produce the **product selection** Deliverable: the Skill's task for identifying the products and features each component needs.

View File

@@ -1,7 +1,7 @@
--- ---
role: requirements-analyst role: requirements-analyst
deliverable: requirements deliverable: requirements
tool_tiers: [cloud_read] tools: []
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **requirements** Deliverable: the Skill's requirements-discovery gathering and its resolution of ambiguities and contradictions. You produce the **requirements** Deliverable: the Skill's requirements-discovery gathering and its resolution of ambiguities and contradictions.

View File

@@ -1,7 +1,7 @@
--- ---
role: validator role: validator
deliverable: validation_results deliverable: validation_results
tool_tiers: [general, cloud_read] tools: [terraform_validate, terraform_plan]
includes: [specialist-protocol] includes: [specialist-protocol]
--- ---
You produce the **validation results** Deliverable: the Skill's pre-deployment validation, done statically without provisioning anything. You produce the **validation results** Deliverable: the Skill's pre-deployment validation, done statically without provisioning anything.

View File

@@ -1,7 +1,7 @@
"""Load role files (agents/<role>.md) into RoleSpecs for one Cloud provider. """Load role files (agents/<role>.md) into RoleSpecs for one Cloud provider.
Role files are framework- and provider-neutral: frontmatter names the role, the Role files are framework- and provider-neutral: frontmatter names the role, the
Deliverable it owns, its local tool tiers, an optional budget and shared partials to Deliverable it owns, the local tools it uses, an optional budget and shared partials to
include. The provider bundle supplies each role's Skills, MCP servers and model. include. The provider bundle supplies each role's Skills, MCP servers and model.
""" """
@@ -12,13 +12,13 @@ from pathlib import Path
from app.agent_skills import SkillFormatError, split_frontmatter from app.agent_skills import SkillFormatError, split_frontmatter
from app.agents.runtime import RoleSpec from app.agents.runtime import RoleSpec
from app.execution.deliverables import DEPENDENCY_GRAPH, DeliverableKind from app.execution.deliverables import DEPENDENCY_GRAPH, DeliverableKind
from app.providers import TIERS, ProviderBundle from app.providers import ProviderBundle
ORCHESTRATOR = "orchestrator" ORCHESTRATOR = "orchestrator"
PILLAR_ADVISOR = "pillar-advisor" PILLAR_ADVISOR = "pillar-advisor"
PARTIALS_DIR = "partials" PARTIALS_DIR = "partials"
_ALLOWED_FIELDS = {"role", "deliverable", "tool_tiers", "budget", "includes"} _ALLOWED_FIELDS = {"role", "deliverable", "tools", "budget", "includes"}
class RoleConfigError(ValueError): class RoleConfigError(ValueError):
@@ -96,10 +96,14 @@ def _load_role(
elif deliverable is not None: elif deliverable is not None:
raise fail(f"role {name!r} owns no Deliverable, but names {deliverable!r}") raise fail(f"role {name!r} owns no Deliverable, but names {deliverable!r}")
tiers = tuple(frontmatter.get("tool_tiers") or ()) tools = tuple(frontmatter.get("tools") or ())
bad_tiers = [tier for tier in tiers if tier not in TIERS] offered = {name for names in bundle.tools.values() for name in names}
if bad_tiers: unknown_tools = [tool for tool in tools if tool not in offered]
raise fail(f"'tool_tiers' {', '.join(bad_tiers)} must be among {TIERS}") if unknown_tools:
raise fail(
f"'tools' {', '.join(unknown_tools)} are not offered by the "
f"{bundle.name} provider bundle"
)
budget = frontmatter.get("budget", default_budget) budget = frontmatter.get("budget", default_budget)
if not isinstance(budget, int) or budget < 1: if not isinstance(budget, int) or budget < 1:
@@ -119,7 +123,7 @@ def _load_role(
instructions="\n\n".join(sections), instructions="\n\n".join(sections),
budget=budget, budget=budget,
skills=tuple(bundle.role_skills.get(name, ())), skills=tuple(bundle.role_skills.get(name, ())),
tool_tiers=tiers, tools=tools,
mcp_servers=tuple( mcp_servers=tuple(
server.id server.id
for server in bundle.mcp_servers_for_role(name, include_preview_mcp) for server in bundle.mcp_servers_for_role(name, include_preview_mcp)

View File

@@ -19,7 +19,7 @@ class RoleSpec:
instructions: str instructions: str
budget: int budget: int
skills: tuple[str, ...] = () skills: tuple[str, ...] = ()
tool_tiers: tuple[str, ...] = () tools: tuple[str, ...] = () # local tool names, e.g. terraform_validate
mcp_servers: tuple[str, ...] = () mcp_servers: tuple[str, ...] = ()
model: str | None = None model: str | None = None

View File

@@ -52,6 +52,13 @@ class Settings(BaseSettings):
# Cloud Provider Bundle (providers/<name>.yaml) & Remote MCP Servers # Cloud Provider Bundle (providers/<name>.yaml) & Remote MCP Servers
CLOUD_PROVIDER: str = "gcp" CLOUD_PROVIDER: str = "gcp"
MCP_ENABLE_PREVIEW: bool = True MCP_ENABLE_PREVIEW: bool = True
MCP_QUOTA_PROJECT: str | None = None # defaults to the ADC project
MCP_TIMEOUT_SECONDS: float = 30
# Local Terraform tools (fmt, validate, plan; never apply)
TERRAFORM_BINARY: str = "terraform"
TERRAFORM_TIMEOUT_SECONDS: float = 300
TF_PLUGIN_CACHE_DIR: str | None = None
# Hierarchical Execution Engine (LangGraph state, ReAct agents) # Hierarchical Execution Engine (LangGraph state, ReAct agents)
ORCHESTRATOR_BUDGET: int = 40 ORCHESTRATOR_BUDGET: int = 40

View File

@@ -26,6 +26,7 @@ def pillar_consultation_tool(
runtime: AgentRuntime, runtime: AgentRuntime,
advisor: RoleSpec, advisor: RoleSpec,
pillar_skills: Mapping[str, str], pillar_skills: Mapping[str, str],
extra_tools: Sequence[ToolSpec] = (),
) -> ToolSpec: ) -> ToolSpec:
"""A tool that runs one pillar advisor per pillar, in parallel, each with its Skill.""" """A tool that runs one pillar advisor per pillar, in parallel, each with its Skill."""
@@ -39,7 +40,9 @@ def pillar_consultation_tool(
) )
results = await asyncio.gather( results = await asyncio.gather(
*( *(
_advise(runtime, advisor, pillar, pillar_skills[pillar], brief) _advise(
runtime, advisor, pillar, pillar_skills[pillar], brief, extra_tools
)
for pillar in chosen for pillar in chosen
) )
) )
@@ -65,7 +68,12 @@ def pillar_consultation_tool(
async def _advise( async def _advise(
runtime: AgentRuntime, advisor: RoleSpec, pillar: str, skill: str, brief: str runtime: AgentRuntime,
advisor: RoleSpec,
pillar: str,
skill: str,
brief: str,
extra_tools: Sequence[ToolSpec],
) -> str: ) -> str:
role = dataclasses.replace(advisor, skills=(skill,)) role = dataclasses.replace(advisor, skills=(skill,))
task = AgentTask( task = AgentTask(
@@ -74,7 +82,7 @@ async def _advise(
context={"pillar": pillar, "brief": brief}, context={"pillar": pillar, "brief": brief},
) )
try: try:
outcome = await runtime.run(role, task, [_submit_advice_tool()]) outcome = await runtime.run(role, task, [_submit_advice_tool(), *extra_tools])
except Exception as exc: # noqa: BLE001 - one failed advisor must not lose the others except Exception as exc: # noqa: BLE001 - one failed advisor must not lose the others
return f"## {pillar}\n\nNo guidance: the advisor failed ({exc})." return f"## {pillar}\n\nNo guidance: the advisor failed ({exc})."
if isinstance(outcome, Submitted): if isinstance(outcome, Submitted):

View File

@@ -1,6 +1,8 @@
"""Which extra tools each role gets beyond the Execution tools. """Which tools each role gets beyond the Execution tools.
Increment 6 adds the local general and cloud-read tools and remote MCP servers here. A role gets the local tools its role file names, the tools of the remote MCP servers
the provider bundle assigns it, and, for the design advisor, the pillar consultation.
Cloud-read gating is applied later, per Execution, by `specialist_tools`.
""" """
from __future__ import annotations from __future__ import annotations
@@ -12,22 +14,36 @@ from app.agents.runtime import AgentRuntime, RoleSpec, ToolSpec
from app.execution.deliverables import DeliverableKind from app.execution.deliverables import DeliverableKind
from app.execution.graph import ToolFactory from app.execution.graph import ToolFactory
from app.execution.pillars import pillar_consultation_tool from app.execution.pillars import pillar_consultation_tool
from app.tools.mcp import McpCatalog
def make_tool_factory( def make_tool_factory(
runtime: AgentRuntime, runtime: AgentRuntime,
roles: Mapping[str, RoleSpec], roles: Mapping[str, RoleSpec],
pillar_skills: Mapping[str, str], pillar_skills: Mapping[str, str],
*,
local_tools: Sequence[ToolSpec] = (),
catalog: McpCatalog | None = None,
) -> ToolFactory: ) -> ToolFactory:
consult = ( local_by_name = {tool.name: tool for tool in local_tools}
pillar_consultation_tool(runtime, roles[PILLAR_ADVISOR], pillar_skills)
if pillar_skills and PILLAR_ADVISOR in roles def mcp_tools(role: RoleSpec) -> list[ToolSpec]:
else None return catalog.tools_for(role.mcp_servers) if catalog else []
)
consult = None
advisor = roles.get(PILLAR_ADVISOR)
if pillar_skills and advisor:
# Pillar advisors can't ask for permission, so they get general-tier tools only.
advisor_tools = [tool for tool in mcp_tools(advisor) if tool.tier == "general"]
consult = pillar_consultation_tool(
runtime, advisor, pillar_skills, extra_tools=advisor_tools
)
def tools_for(role: RoleSpec, deliverable: str | None) -> Sequence[ToolSpec]: def tools_for(role: RoleSpec, deliverable: str | None) -> Sequence[ToolSpec]:
tools = [local_by_name[name] for name in role.tools if name in local_by_name]
tools += mcp_tools(role)
if consult and deliverable == DeliverableKind.DESIGN_RECOMMENDATIONS.value: if consult and deliverable == DeliverableKind.DESIGN_RECOMMENDATIONS.value:
return [consult] tools.append(consult)
return [] return tools
return tools_for return tools_for

289
app/tools/local.py Normal file
View File

@@ -0,0 +1,289 @@
"""Local tools: a Mermaid syntax check and Terraform checks in a scratch directory.
Terraform runs only fmt, init -backend=false, validate and plan. No command that
changes cloud resources is ever constructed.
"""
from __future__ import annotations
import asyncio
import os
import re
import tempfile
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any
from app.agents.runtime import ToolResult, ToolSpec
_MAX_OUTPUT = 8_000
_TERRAFORM_SUFFIXES = (".tf", ".tfvars", ".tf.json")
_VARIABLE_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*$")
_MERMAID_TYPES = (
"flowchart",
"graph",
"sequenceDiagram",
"classDiagram",
"stateDiagram",
"stateDiagram-v2",
"erDiagram",
"C4Context",
"C4Container",
"C4Component",
"C4Deployment",
"architecture-beta",
"block-beta",
)
_BRACKETS = {"]": "[", ")": "(", "}": "{"}
async def mermaid_check(diagram: str) -> ToolResult:
"""A basic structural check; it does not render the diagram."""
problems = []
lines = [
line.strip()
for line in diagram.splitlines()
if line.strip() and not line.strip().startswith("%%")
]
if not diagram.strip():
problems.append("the diagram is empty")
elif not lines or lines[0].split()[0] not in _MERMAID_TYPES:
problems.append(
"the first line must declare a diagram type, such as 'flowchart TD'"
)
for number, line in enumerate(diagram.splitlines(), start=1):
stack: list[str] = []
in_quotes = False
for char in line:
if char == '"':
in_quotes = not in_quotes
elif in_quotes:
continue
elif char in "[({":
stack.append(char)
elif char in _BRACKETS and (not stack or stack.pop() != _BRACKETS[char]):
stack.append("!")
break
if stack:
problems.append(f"Unbalanced brackets on line {number}: {line.strip()}")
if problems:
return ToolResult("Mermaid check failed: " + "; ".join(problems))
return ToolResult("Mermaid check passed (structure only; not rendered).")
@dataclass
class TerraformRunner:
binary: str = "terraform"
timeout_seconds: float = 300
plugin_cache_dir: str | None = None
async def fmt(self, files: Mapping[str, str]) -> ToolResult:
refusal = _check_files(files)
if refusal:
return refusal
with tempfile.TemporaryDirectory(prefix="tf-fmt-") as tmp:
root = _write(Path(tmp), files)
code, output = await self._run(
[self.binary, "fmt", "-recursive", "-list=true"], root
)
if code != 0:
return ToolResult(f"terraform fmt failed:\n{output}")
changed = [
name for name in files if (root / name).read_text() != files[name]
]
if not changed:
return ToolResult("terraform fmt: all files are already formatted.")
formatted = "\n\n".join(
f"--- {name}\n{(root / name).read_text()}" for name in changed
)
return ToolResult(
_clip(
f"terraform fmt reformatted {len(changed)} file(s):\n\n{formatted}"
)
)
async def validate(self, files: Mapping[str, str]) -> ToolResult:
refusal = _check_files(files)
if refusal:
return refusal
with tempfile.TemporaryDirectory(prefix="tf-validate-") as tmp:
root = _write(Path(tmp), files)
failure = await self._init(root)
if failure:
return failure
code, output = await self._run([self.binary, "validate", "-no-color"], root)
verdict = "passed" if code == 0 else "failed"
return ToolResult(_clip(f"terraform validate {verdict}:\n{output}"))
async def plan(
self, files: Mapping[str, str], variables: Mapping[str, str] | None = None
) -> ToolResult:
refusal = _check_files(files)
if refusal:
return refusal
variables = dict(variables or {})
bad = [name for name in variables if not _VARIABLE_NAME.match(name)]
if bad:
return ToolResult(f"Refused: invalid variable names {', '.join(bad)}")
with tempfile.TemporaryDirectory(prefix="tf-plan-") as tmp:
root = _write(Path(tmp), files)
failure = await self._init(root)
if failure:
return failure
args = [
self.binary,
"plan",
"-no-color",
"-input=false",
"-lock=false",
"-refresh=true",
*(f"-var={name}={value}" for name, value in variables.items()),
]
code, output = await self._run(args, root)
verdict = "completed" if code == 0 else "failed"
return ToolResult(
_clip(f"terraform plan {verdict} (nothing was applied):\n{output}")
)
async def _init(self, root: Path) -> ToolResult | None:
code, output = await self._run(
[self.binary, "init", "-backend=false", "-input=false", "-no-color"], root
)
if code != 0:
return ToolResult(_clip(f"terraform init failed:\n{output}"))
return None
async def _run(
self, args: list[str], cwd: Path, env: Mapping[str, str] | None = None
) -> tuple[int, str]:
environment = {**os.environ, "TF_IN_AUTOMATION": "1", **(env or {})}
if self.plugin_cache_dir:
environment["TF_PLUGIN_CACHE_DIR"] = self.plugin_cache_dir
try:
process = await asyncio.create_subprocess_exec(
*args,
cwd=cwd,
env=environment,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
except FileNotFoundError:
return 127, f"{self.binary} is not installed or not on PATH."
try:
stdout, _ = await asyncio.wait_for(
process.communicate(), timeout=self.timeout_seconds
)
except TimeoutError:
process.kill()
await process.wait()
return 124, f"{' '.join(args[:2])} timed out after {self.timeout_seconds}s."
return process.returncode or 0, stdout.decode(errors="replace")
def _check_files(files: Mapping[str, str]) -> ToolResult | None:
if not files:
return ToolResult("Refused: provide at least one Terraform file.")
bad = []
for name in files:
path = PurePosixPath(name)
if (
path.is_absolute()
or ".." in path.parts
or not name.endswith(_TERRAFORM_SUFFIXES)
):
bad.append(name)
if bad:
return ToolResult(
"Refused: file names must be relative .tf, .tf.json or .tfvars paths "
f"without '..': {', '.join(bad)}"
)
return None
def _write(root: Path, files: Mapping[str, str]) -> Path:
for name, content in files.items():
target = root / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return root
def _clip(text: str) -> str:
return text if len(text) <= _MAX_OUTPUT else text[:_MAX_OUTPUT] + "\n[truncated]"
_FILES_SCHEMA: dict[str, Any] = {
"type": "object",
"description": "Terraform files by relative path, e.g. {'main.tf': '...'}",
"additionalProperties": {"type": "string"},
}
LOCAL_TOOLS: dict[str, tuple[str, str]] = {
"mermaid_check": ("general", "Check a Mermaid diagram's basic structure."),
"terraform_fmt": ("general", "Format Terraform files and return any that changed."),
"terraform_validate": (
"general",
"Validate Terraform files offline (init -backend=false, validate).",
),
"terraform_plan": (
"cloud_read",
"Preview Terraform against the live cloud environment with a plan. Never applies.",
),
}
def local_tools(names: Iterable[str], runner: TerraformRunner) -> list[ToolSpec]:
builders = {
"mermaid_check": lambda: ToolSpec(
"mermaid_check",
LOCAL_TOOLS["mermaid_check"][1],
{
"type": "object",
"properties": {"diagram": {"type": "string"}},
"required": ["diagram"],
},
mermaid_check,
tier="general",
),
"terraform_fmt": lambda: ToolSpec(
"terraform_fmt",
LOCAL_TOOLS["terraform_fmt"][1],
{
"type": "object",
"properties": {"files": _FILES_SCHEMA},
"required": ["files"],
},
runner.fmt,
tier="general",
),
"terraform_validate": lambda: ToolSpec(
"terraform_validate",
LOCAL_TOOLS["terraform_validate"][1],
{
"type": "object",
"properties": {"files": _FILES_SCHEMA},
"required": ["files"],
},
runner.validate,
tier="general",
),
"terraform_plan": lambda: ToolSpec(
"terraform_plan",
LOCAL_TOOLS["terraform_plan"][1],
{
"type": "object",
"properties": {
"files": _FILES_SCHEMA,
"variables": {
"type": "object",
"additionalProperties": {"type": "string"},
},
},
"required": ["files"],
},
runner.plan,
tier="cloud_read",
),
}
return [builders[name]() for name in names]

287
app/tools/mcp.py Normal file
View File

@@ -0,0 +1,287 @@
"""Remote MCP servers hosted by the Cloud provider, exposed as read-only ToolSpecs.
Only tools on a server's reviewed allowlist are ever offered, and an allowlisted tool
must declare `readOnlyHint: true` or loading fails. Tools keep the server's tier, so
the Execution's cloud-read permission gate applies to them like any other tool.
Failures become discovery gaps the agent records, never exceptions.
"""
from __future__ import annotations
import asyncio
import logging
import re
from collections.abc import AsyncIterator, Iterable, Mapping
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, Protocol
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from mcp.shared._httpx_utils import create_mcp_http_client
from app.agents.runtime import ToolResult, ToolSpec
from app.providers import McpServerSpec
logger = logging.getLogger(__name__)
GAP_INSTRUCTION = "Record this under 'Assumptions / discovery gaps' and continue."
_MAX_TOOL_NAME = 64
_CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
class McpConfigError(RuntimeError):
"""An MCP server or its allowlist can't be used safely."""
# --- auth ------------------------------------------------------------------------------
class McpAuth(Protocol):
async def headers(self) -> dict[str, str]: ...
class NoAuth:
async def headers(self) -> dict[str, str]:
return {}
class StaticHeadersAuth:
def __init__(self, headers: Mapping[str, str]) -> None:
self._headers = dict(headers)
async def headers(self) -> dict[str, str]:
return dict(self._headers)
class GoogleAdcAuth:
"""Bearer token from Application Default Credentials, plus the quota project."""
def __init__(self, quota_project: str | None = None) -> None:
self._quota_project = quota_project
self._credentials: Any = None
self._project: str | None = None
self._lock = asyncio.Lock()
async def headers(self) -> dict[str, str]:
async with self._lock:
await asyncio.to_thread(self._refresh_if_needed)
headers = {"Authorization": f"Bearer {self._credentials.token}"}
project = self._quota_project or self._project
if project:
headers["X-Goog-User-Project"] = project
return headers
def _refresh_if_needed(self) -> None:
import google.auth
import google.auth.transport.requests
if self._credentials is None:
self._credentials, self._project = google.auth.default(
scopes=[_CLOUD_PLATFORM_SCOPE]
)
if not self._credentials.valid:
self._credentials.refresh(google.auth.transport.requests.Request())
def auth_from_config(
config: Mapping[str, Any], quota_project: str | None = None
) -> McpAuth:
kind = config.get("kind", "none")
if kind == "none":
return NoAuth()
if kind == "google_adc":
return GoogleAdcAuth(quota_project)
raise McpConfigError(f"Unsupported mcp_auth kind {kind!r}; use google_adc or none")
# --- client ----------------------------------------------------------------------------
@dataclass(frozen=True)
class McpToolInfo:
name: str
description: str
input_schema: Mapping[str, Any]
read_only: bool
class McpClient:
def __init__(
self, server: McpServerSpec, auth: McpAuth, timeout: float = 30
) -> None:
self._server = server
self._auth = auth
self._timeout = timeout
@asynccontextmanager
async def _session(self) -> AsyncIterator[ClientSession]:
headers = await self._auth.headers()
async with (
create_mcp_http_client(
headers=headers, timeout=httpx.Timeout(self._timeout)
) as http_client,
streamable_http_client(self._server.url, http_client=http_client) as (
read,
write,
_,
),
ClientSession(
read, write, read_timeout_seconds=timedelta(seconds=self._timeout)
) as session,
):
await session.initialize()
yield session
async def list_tools(self) -> list[McpToolInfo]:
tools: list[McpToolInfo] = []
async with self._session() as session:
cursor = None
while True:
page = await session.list_tools(cursor=cursor)
for tool in page.tools:
annotations = tool.annotations
tools.append(
McpToolInfo(
name=tool.name,
description=tool.description or tool.title or tool.name,
input_schema=tool.inputSchema or {"type": "object"},
read_only=bool(annotations and annotations.readOnlyHint),
)
)
cursor = page.nextCursor
if not cursor:
return tools
async def call_tool(
self, name: str, arguments: Mapping[str, Any]
) -> tuple[bool, str]:
"""Return (is_error, text)."""
async with self._session() as session:
result = await session.call_tool(name, dict(arguments))
text = "\n".join(
getattr(item, "text", None) or str(item) for item in result.content
)
if not text and result.structuredContent is not None:
text = str(result.structuredContent)
return bool(result.isError), text
# --- catalog ---------------------------------------------------------------------------
def tool_name(server_id: str, tool: str) -> str:
"""A tool name every model provider accepts: [A-Za-z0-9_-], at most 64 characters."""
name = re.sub(r"[^A-Za-z0-9_-]", "_", f"{server_id}__{tool}")
return name[:_MAX_TOOL_NAME]
class McpCatalog:
def __init__(self) -> None:
self._tools: dict[str, list[ToolSpec]] = {}
self.gaps: dict[str, str] = {}
@classmethod
async def load(
cls,
servers: Iterable[McpServerSpec],
auth: McpAuth,
*,
timeout: float = 30,
max_result_chars: int = 20_000,
) -> McpCatalog:
catalog = cls()
pending = [server for server in servers if server.allow]
results = await asyncio.gather(
*(McpClient(server, auth, timeout).list_tools() for server in pending),
return_exceptions=True,
)
for server, listed in zip(pending, results, strict=True):
client = McpClient(server, auth, timeout)
if isinstance(listed, BaseException):
reason = _describe(listed)
logger.warning("MCP server %s unavailable: %s", server.id, reason)
catalog.gaps[server.id] = reason
catalog._tools[server.id] = [_unavailable_tool(server, reason)]
continue
by_name = {tool.name: tool for tool in listed}
not_read_only = [
name
for name in server.allow
if name in by_name and not by_name[name].read_only
]
if not_read_only:
raise McpConfigError(
f"MCP server {server.id} allowlists tools not marked readOnlyHint: "
f"{', '.join(not_read_only)}. Remove them from the allowlist."
)
missing = [name for name in server.allow if name not in by_name]
if missing:
catalog.gaps[server.id] = (
f"allowlisted tools not offered by the server: {', '.join(missing)}"
)
catalog._tools[server.id] = [
_tool_spec(server, client, by_name[name], max_result_chars)
for name in server.allow
if name in by_name
]
return catalog
def tools_for(self, server_ids: Iterable[str]) -> list[ToolSpec]:
return [
tool for server_id in server_ids for tool in self._tools.get(server_id, [])
]
def _tool_spec(
server: McpServerSpec, client: McpClient, info: McpToolInfo, max_chars: int
) -> ToolSpec:
name = tool_name(server.id, info.name)
async def call(**arguments: Any) -> ToolResult:
try:
is_error, text = await client.call_tool(info.name, arguments)
except Exception as exc: # noqa: BLE001 - a remote failure is a discovery gap
return ToolResult(
f"Discovery gap: {name} failed ({_describe(exc)}). {GAP_INSTRUCTION}"
)
if is_error:
return ToolResult(
f"Discovery gap: {name} failed ({text}). {GAP_INSTRUCTION}"
)
if len(text) > max_chars:
text = text[:max_chars] + "\n[truncated]"
return ToolResult(text)
return ToolSpec(
name,
f"[{server.id} MCP, read-only] {info.description}",
dict(info.input_schema),
call,
tier=server.tier,
)
def _unavailable_tool(server: McpServerSpec, reason: str) -> ToolSpec:
async def report(**_: Any) -> ToolResult:
return ToolResult(
f"Discovery gap: {server.id} MCP server unavailable ({reason}). {GAP_INSTRUCTION}"
)
return ToolSpec(
tool_name(server.id, "unavailable"),
f"The {server.id} MCP server could not be reached; call to get the reason.",
{"type": "object", "properties": {}},
report,
tier=server.tier,
)
def _describe(exc: BaseException) -> str:
grouped = getattr(exc, "exceptions", None) # ExceptionGroup from anyio task groups
if grouped:
return _describe(grouped[0])
return f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__

View File

@@ -0,0 +1,66 @@
# Remote MCP access: Google Cloud
How to give the solution architect agent safe, read-only access to Google Cloud's hosted MCP servers. The servers the agent uses, and the only tools it may call on each, are listed in [`providers/gcp.yaml`](../../providers/gcp.yaml).
## How the agent limits itself
- **Allowlist.** An agent is only ever offered tools named in a server's `allow` list. Every other tool on the server is invisible to it.
- **Read-only check at startup.** If any allowlisted tool doesn't declare `readOnlyHint: true`, the agent refuses to start.
- **Content excluded.** Tools that return data content are excluded even though they are read-only: Cloud SQL `execute_sql_readonly`, Cloud Storage `read_object`/`read_text`/`list_objects`, and generic Kubernetes reads that can return Secrets (`get_k8s_resource`, `describe_k8s_resource`).
- **Permission per Execution.** Tools that read your environment (`cloud_read`) run only after the user grants permission in that Execution. Pre-approved Executions deny it unless the caller passes `allow_cloud_read=true`.
These are defence in depth. Enforce read-only access in Google Cloud as well.
## Set up a project the agent may read
1. **Enable the APIs** of the products you want discovered. A product's MCP endpoint is available once its API is enabled, for example `compute.googleapis.com`, `container.googleapis.com`, `run.googleapis.com`, `sqladmin.googleapis.com`, `pubsub.googleapis.com`, `cloudasset.googleapis.com`, `monitoring.googleapis.com` and `networkmanagement.googleapis.com`. A disabled API shows up as a recorded discovery gap, not a failure.
2. **Create a dedicated service account** for the agent, and grant it only:
- `roles/mcp.toolUser`, to call MCP tools
- `roles/viewer`, or narrower viewer roles for the products in scope
- `roles/cloudasset.viewer`, for asset inventory and IAM analysis
3. **Deny read-write tool calls** for every principal with an IAM deny policy. Save the policy as `policy.json`:
```json
{
"rules": [
{
"denyRule": {
"deniedPrincipals": ["principalSet://goog/public:all"],
"deniedPermissions": ["mcp.googleapis.com/tools.call"],
"denialCondition": {
"title": "Deny read-write tools",
"expression": "api.getAttribute('mcp.googleapis.com/tool.isReadOnly', false) == false"
}
}
}
]
}
```
Then attach it to the project:
```bash
gcloud iam policies create mcp-deny-policy \
--attachment-point=cloudresourcemanager.googleapis.com/projects/PROJECT_ID \
--kind=denypolicies \
--policy-file=policy.json
```
4. **Give the agent credentials.** It authenticates with Application Default Credentials: the attached service account on Cloud Run or GKE, or `GOOGLE_APPLICATION_CREDENTIALS` locally. Set `MCP_QUOTA_PROJECT` when quota should be charged to a project other than the credentials' project.
For local development, `gcloud auth application-default login` supplies ADC for your user.
## Reviewing the allowlists
Upstream tool sets change. To review them:
1. Refresh the snapshot. `tools/list` works without credentials, and the script lists tools without calling any:
```bash
.venv/bin/python scripts/list-mcp-tools.py gcp --json --no-auth > providers/reviews/gcp-mcp-tools.json
```
2. Read the diff. For each new read-only tool, decide whether it returns inventory or configuration metadata (allow it) or data content or secrets (leave it out).
3. Update the `allow` lists in `providers/gcp.yaml`. `tests/test_providers.py` fails if an allowlisted tool is missing from the snapshot or isn't read-only.
Last reviewed 2026-09-16, against all 12 servers.

View File

@@ -18,14 +18,14 @@ models:
# Skills each role may load. Role files stay provider-neutral; the bundle names Skills. # Skills each role may load. Role files stay provider-neutral; the bundle names Skills.
role_skills: role_skills:
orchestrator: [google-cloud-solution-architecture] orchestrator: [google-cloud-solution-architecture]
requirements-analyst: [google-cloud-solution-architecture] requirements-analyst: [google-cloud-solution-architecture, cloud-discovery]
decomposer: [google-cloud-solution-architecture] decomposer: [google-cloud-solution-architecture]
product-selector: [google-cloud-solution-architecture] product-selector: [google-cloud-solution-architecture]
diagrammer: [google-cloud-solution-architecture] diagrammer: [google-cloud-solution-architecture]
describer: [google-cloud-solution-architecture] describer: [google-cloud-solution-architecture]
design-advisor: [google-cloud-solution-architecture] design-advisor: [google-cloud-solution-architecture]
iac-author: [google-cloud-solution-architecture] iac-author: [google-cloud-solution-architecture, iac-validation]
validator: [google-cloud-solution-architecture] validator: [google-cloud-solution-architecture, iac-validation]
packager: [google-cloud-solution-architecture] packager: [google-cloud-solution-architecture]
# One advisor per architecture-framework pillar; each loads only its pillar's Skill. # One advisor per architecture-framework pillar; each loads only its pillar's Skill.
@@ -45,58 +45,104 @@ mcp_auth:
kind: google_adc # Application Default Credentials bearer token; sends X-Goog-User-Project kind: google_adc # Application Default Credentials bearer token; sends X-Goog-User-Project
# Remote MCP servers hosted by Google Cloud (streamable HTTP). # Remote MCP servers hosted by Google Cloud (streamable HTTP).
# `allow` lists stay empty (nothing exposed) until each server's tools/list is # `allow` lists name the only tools ever exposed. Reviewed 2026-09-16 against each
# reviewed for read-only tools in increment 6 of .scratch/solution-architect-agent/spec.md. # server's live tools/list (scripts/list-mcp-tools.py): inventory and configuration
# metadata only, every tool readOnlyHint=true. Deliberately excluded even though
# read-only: data content (Cloud SQL execute_sql_readonly, Storage read_object/read_text,
# list_objects), generic Kubernetes reads that can return Secrets (get_k8s_resource,
# describe_k8s_resource), and every write. See docs/operations/mcp-access.md.
mcp_servers: mcp_servers:
developer_knowledge: developer_knowledge:
url: https://developerknowledge.googleapis.com/mcp url: https://developerknowledge.googleapis.com/mcp
tier: general # public documentation, no customer data tier: general # public documentation, no customer data
allow: [] allow:
- search_documents
- get_documents
- answer_query
resource_manager: resource_manager:
url: https://cloudresourcemanager.googleapis.com/mcp url: https://cloudresourcemanager.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- search_projects
asset_inventory: asset_inventory:
url: https://cloudasset.googleapis.com/mcp url: https://cloudasset.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_assets
- analyze_iam_policy
preview: true preview: true
compute: compute:
url: https://compute.googleapis.com/mcp url: https://compute.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] 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: gke:
url: https://container.googleapis.com/mcp url: https://container.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_clusters
- get_cluster
- list_node_pools
- get_node_pool
- get_k8s_version
cloud_run: cloud_run:
url: https://run.googleapis.com/mcp url: https://run.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_services
- get_service
cloud_sql: cloud_sql:
url: https://sqladmin.googleapis.com/mcp url: https://sqladmin.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_instances
- get_instance
storage: storage:
url: https://storage.googleapis.com/storage/mcp url: https://storage.googleapis.com/storage/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_buckets
pubsub: pubsub:
url: https://pubsub.googleapis.com/mcp url: https://pubsub.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_topics
- get_topic
- list_subscriptions
- get_subscription
iam: iam:
url: https://iam.googleapis.com/mcp url: https://iam.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_roles
- get_role
- list_deny_policies
- get_deny_policy
monitoring: monitoring:
url: https://monitoring.googleapis.com/mcp url: https://monitoring.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_alert_policies
- get_alert_policy
- list_dashboards
- list_metric_descriptors
- list_timeseries
network_intelligence: network_intelligence:
url: https://networkmanagement.googleapis.com/mcp url: https://networkmanagement.googleapis.com/mcp
tier: cloud_read tier: cloud_read
allow: [] allow:
- list_connectivity_tests
- get_connectivity_test
preview: true preview: true
role_mcp_servers: role_mcp_servers:

View File

@@ -0,0 +1,854 @@
{
"developer_knowledge": {
"url": "https://developerknowledge.googleapis.com/mcp",
"tools": [
{
"name": "search_documents",
"read_only": true,
"allowed": true,
"description": "Use this tool to find documentation about Google developer products. The documents contain official APIs, code snippets, release notes, best practices, guides, debugging info, and more. It covers the "
},
{
"name": "answer_query",
"read_only": true,
"allowed": true,
"description": "Use answer_query to get a grounded answer to a query about Google developer products. This tool has limited quota. This tool will synthesize information from the corpus to generate an answer to the qu"
},
{
"name": "get_documents",
"read_only": true,
"allowed": true,
"description": "Use this tool to retrieve the full content of a single document or up to 20 documents in a single call. The document names should be obtained from the `parent` field of results from a call to the `sea"
}
]
},
"resource_manager": {
"url": "https://cloudresourcemanager.googleapis.com/mcp",
"tools": [
{
"name": "search_projects",
"read_only": true,
"allowed": true,
"description": "Searches for Google Cloud projects. This tool may be used whenever any tools or conversation context requires a GCP project. A SearchProjects call with an empty query will return all projects the user"
}
]
},
"asset_inventory": {
"url": "https://cloudasset.googleapis.com/mcp",
"tools": [
{
"name": "list_assets",
"read_only": true,
"allowed": true,
"description": "List assets from Cloud Asset Inventory"
},
{
"name": "analyze_iam_policy",
"read_only": true,
"allowed": true,
"description": "Analyzes Google Cloud IAM allow policies to determine who can do what on which resources. It can perform policy analysis such as finding resources accessible to a principal, finding principals with ac"
},
{
"name": "export_iam_analysis_results",
"read_only": false,
"allowed": false,
"description": "Analyzes Google Cloud IAM policies asynchronously and exports the results to a BigQuery dataset or Google Cloud Storage bucket. Use this for large-scale analysis (for example, expanding resources or i"
},
{
"name": "get_iam_policy_analysis_status",
"read_only": true,
"allowed": false,
"description": "Polls the status of a long-running IAM Policy Analyzer operation. Use this *only* to pass the operation `name` returned by the `export_iam_analysis_results` tool. If the operation is finished, the `do"
}
]
},
"compute": {
"url": "https://compute.googleapis.com/mcp",
"tools": [
{
"name": "create_instance",
"read_only": false,
"allowed": false,
"description": "Create a new Google Compute Engine virtual machine (VM) instance. Requires project, zone, and instance name as input. If machine_type is not provided, it defaults to `e2-medium`. If image_project and "
},
{
"name": "delete_instance",
"read_only": false,
"allowed": false,
"description": "Delete a Google Compute Engine virtual machine (VM) instance. Requires project, zone, and instance name as input. Proceed only if there is no error in response and the status of the operation is `DONE"
},
{
"name": "start_instance",
"read_only": false,
"allowed": false,
"description": "Starts a Google Compute Engine virtual machine (VM) instance. Requires project, zone, and instance name as input. Proceed only if there is no error in response and the status of the operation is `DONE"
},
{
"name": "stop_instance",
"read_only": false,
"allowed": false,
"description": "Stops a Google Compute Engine virtual machine (VM) instance. Requires project, zone, and instance name as input. Proceed only if there is no error in response and the status of the operation is `DONE`"
},
{
"name": "reset_instance",
"read_only": false,
"allowed": false,
"description": "Resets a Google Compute Engine virtual machine (VM) instance. Requires project, zone, and instance name as input. Proceed only if there is no error in response and the status of the operation is `DONE"
},
{
"name": "get_instance_basic_info",
"read_only": true,
"allowed": true,
"description": "Get basic information about a Compute Engine VM instance, including its name, ID, status, machine type, creation timestamp, and attached guest accelerators. Requires project, zone, and instance name a"
},
{
"name": "set_instance_machine_type",
"read_only": false,
"allowed": false,
"description": "Sets the machine type for a stopped Google Compute Engine instance to the specified machine type. Requires project, zone, instance name and machine type as input. Proceed only if there is no error in "
},
{
"name": "list_instance_attached_disks",
"read_only": true,
"allowed": true,
"description": "Lists the disks attached to a Compute Engine virtual machine (VM) instance. For each attached disk, the response includes details such as kind, type, mode, saved state, source, device name, index, boo"
},
{
"name": "list_instances",
"read_only": true,
"allowed": true,
"description": "Lists Compute Engine virtual machine (VM) instances. Details for each instance include name, ID, status, machine type, creation timestamp, and attached guest accelerators. Use other tools to get more "
},
{
"name": "get_instance_group_manager_basic_info",
"read_only": true,
"allowed": true,
"description": "Get basic information about a Compute Engine managed instance group (MIG), including its name, ID, instance template, base instance name, target size, target stopped size, target suspended size, statu"
},
{
"name": "list_instance_group_managers",
"read_only": true,
"allowed": true,
"description": "Lists Compute Engine managed instance groups (MIGs). Details for each MIG include name, ID, instance template, base instance name, target size, target stopped size, target suspended size, status and c"
},
{
"name": "list_managed_instances",
"read_only": true,
"allowed": false,
"description": "Lists managed instances for a given managed instance group (MIG). For each instance, details include id, instance URL, instance status, and current action. Requires project, zone, and MIG name as inpu"
},
{
"name": "list_instance_templates",
"read_only": true,
"allowed": true,
"description": "Lists Compute Engine instance templates. Details for each instance template include name, ID, description, machine type, region, and creation timestamp. Requires project as input."
},
{
"name": "get_instance_template_basic_info",
"read_only": true,
"allowed": false,
"description": "Get basic information about a Compute Engine instance template, including its name, ID, description, machine type, region, and creation timestamp. Requires project and instance template name as input."
},
{
"name": "get_instance_template_properties",
"read_only": true,
"allowed": true,
"description": "Get instance properties of a Compute Engine instance template. This includes properties such as description, tags, machine type, network interfaces, disks, metadata, service accounts, scheduling optio"
},
{
"name": "get_disk_basic_info",
"read_only": true,
"allowed": true,
"description": "Get basic information about a Compute Engine disk, including its name, ID, description, creation timestamp, size, type, status, last attach timestamp, and last detach timestamp. Requires project, zone"
},
{
"name": "get_disk_performance_config",
"read_only": true,
"allowed": false,
"description": "Get performance configuration of a Compute Engine disk, including its type, size, provisioned IOPS, provisioned throughput, physical block size, storage pool and access mode. Requires project, zone, a"
},
{
"name": "list_disks",
"read_only": true,
"allowed": true,
"description": "Lists Compute Engine disks. Details for each disk include name, ID, description, creation timestamp, size, type, status, last attach timestamp, and last detach timestamp. Requires project and zone as "
},
{
"name": "list_accelerator_types",
"read_only": true,
"allowed": false,
"description": "Lists the available Google Compute Engine accelerator types. Requires project and zone as input. Returns accelerator types, including id, creation timestamp, name, description, deprecated, zone, and m"
},
{
"name": "list_machine_types",
"read_only": true,
"allowed": false,
"description": "Lists the available Google Compute Engine machine types. Requires project and zone as input. Returns machine types, including id, creationTimestamp, name, description, guest cpus, memory, image space,"
},
{
"name": "list_images",
"read_only": true,
"allowed": false,
"description": "Lists Compute Engine Images. Details for each image include name, ID, status, family, and creation timestamp. Requires project as input."
},
{
"name": "get_zone_operation",
"read_only": true,
"allowed": false,
"description": "Get details of a zone operation, including its id, name, status, creation timestamp, error, warning, HTTP error message and HTTP error status code. Requires project, zone, and operation name as input."
},
{
"name": "get_reservation_basic_info",
"read_only": true,
"allowed": false,
"description": "Get Compute Engine reservation basic info including name, ID, creation timestamp, zone, status, specific reservation required, commitment, and linked commitments. Requires project, zone, and reservati"
},
{
"name": "get_reservation_details",
"read_only": true,
"allowed": false,
"description": "Get Compute Engine reservation details. Returns reservation details including name, ID, status, creation timestamp, specific reservation properties like machine type, guest accelerators and local SSDs"
},
{
"name": "list_reservations",
"read_only": true,
"allowed": true,
"description": "Lists Compute Engine reservations. Details for each reservation include name, ID, creation timestamp, zone, status, specific reservation required, commitment, and linked commitments. Requires project "
},
{
"name": "list_commitments",
"read_only": true,
"allowed": true,
"description": "Lists Compute Engine Commitments in a region. Details for each commitment include name, ID, status, plan, type, resources, and creation, start and end timestamps. Requires project and region as input."
},
{
"name": "get_commitment_basic_info",
"read_only": true,
"allowed": false,
"description": "Get basic information about a Compute Engine Commitment, including its name, ID, status, plan, type, resources, and creation, start and end timestamps. Requires project, region, and commitment name as"
},
{
"name": "list_commitment_reservations",
"read_only": true,
"allowed": false,
"description": "Lists reservations for a Compute Engine Commitment. Returns reservation details including name, ID, status, creation timestamp, specific reservation properties like machine type, guest accelerators an"
},
{
"name": "list_snapshots",
"read_only": true,
"allowed": false,
"description": "Lists snapshots in a project providing basic information per snapshot including name, id, status, creation time, disk size, storage bytes, source disk, and source disk id. Requires project as input."
}
]
},
"gke": {
"url": "https://container.googleapis.com/mcp",
"tools": [
{
"name": "list_k8s_api_resources",
"read_only": true,
"allowed": false,
"description": "Retrieves the available API groups and resources from a Kubernetes cluster. This is similar to running `kubectl api-resources`."
},
{
"name": "check_k8s_auth",
"read_only": true,
"allowed": false,
"description": "Checks whether an action is allowed on a Kubernetes resource. This is similar to running `kubectl auth can-i`."
},
{
"name": "describe_k8s_resource",
"read_only": true,
"allowed": false,
"description": "Shows the details of a specific Kubernetes resource. This is similar to running `kubectl describe`."
},
{
"name": "list_k8s_events",
"read_only": true,
"allowed": false,
"description": "Retrieves events from a Kubernetes cluster. This is similar to running `kubectl events`."
},
{
"name": "get_k8s_resource",
"read_only": true,
"allowed": false,
"description": "Gets one or more Kubernetes resources from a cluster. Resources can be filtered by type, name, namespace, and label selectors. Returns the resources in YAML format. This is similar to running `kubectl"
},
{
"name": "get_k8s_cluster_info",
"read_only": true,
"allowed": false,
"description": "Gets cluster endpoint information. This is similar to running `kubectl cluster-info`."
},
{
"name": "get_k8s_version",
"read_only": true,
"allowed": true,
"description": "Retrieves Kubernetes client and server versions for a given cluster. This is similar to running `kubectl version`."
},
{
"name": "get_k8s_rollout_status",
"read_only": true,
"allowed": false,
"description": "Checks the current rollout status of a Kubernetes resource. This is similar to running `kubectl rollout status`."
},
{
"name": "list_clusters",
"read_only": true,
"allowed": true,
"description": "Lists GKE clusters in a given project and location. Location can be a region, zone, or '-' for all locations."
},
{
"name": "create_cluster",
"read_only": false,
"allowed": false,
"description": "Creates a new GKE cluster in a given project and location. It's recommended to read the [GKE documentation](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/configuration-overview) to und"
},
{
"name": "update_cluster",
"read_only": false,
"allowed": false,
"description": "Updates a specific GKE cluster."
},
{
"name": "get_cluster",
"read_only": true,
"allowed": true,
"description": "Gets the details of a specific GKE cluster."
},
{
"name": "list_operations",
"read_only": true,
"allowed": false,
"description": "Lists GKE operations in a given project and location. Location can be a region, zone, or '-' for all locations."
},
{
"name": "get_operation",
"read_only": true,
"allowed": false,
"description": "Gets the details of a specific GKE operation."
},
{
"name": "cancel_operation",
"read_only": false,
"allowed": false,
"description": "Cancels a specific GKE operation."
},
{
"name": "create_node_pool",
"read_only": false,
"allowed": false,
"description": "Creates a node pool for a specific GKE cluster."
},
{
"name": "list_node_pools",
"read_only": true,
"allowed": true,
"description": "Lists the node pools for a specific GKE cluster."
},
{
"name": "get_node_pool",
"read_only": true,
"allowed": true,
"description": "Gets the details of a specific node pool within a GKE cluster."
},
{
"name": "update_node_pool",
"read_only": false,
"allowed": false,
"description": "Updates a specific node pool within a GKE cluster."
},
{
"name": "get_k8s_logs",
"read_only": true,
"allowed": false,
"description": "Gets logs from a Kubernetes container in a pod. This is similar to running `kubectl logs`."
},
{
"name": "apply_k8s_manifest",
"read_only": false,
"allowed": false,
"description": "Applies a Kubernetes manifest to a cluster using server-side apply. This is similar to running `kubectl apply --server-side`."
},
{
"name": "delete_k8s_resource",
"read_only": false,
"allowed": false,
"description": "Deletes a Kubernetes resource from a cluster. This is similar to running `kubectl delete`."
},
{
"name": "patch_k8s_resource",
"read_only": false,
"allowed": false,
"description": "Patches a Kubernetes resource. This is similar to running `kubectl patch`."
}
]
},
"cloud_run": {
"url": "https://run.googleapis.com/mcp",
"tools": [
{
"name": "get_service",
"read_only": true,
"allowed": true,
"description": "Get info about a Cloud Run service, such as its URI and whether the deploy succeeded."
},
{
"name": "list_services",
"read_only": true,
"allowed": true,
"description": "List Cloud Run services in a given Google Cloud project and region."
},
{
"name": "deploy_service_from_image",
"read_only": false,
"allowed": false,
"description": "Deploy a container image from Artifact Registry or Docker Hub as a Cloud Run service."
},
{
"name": "deploy_service_from_archive",
"read_only": false,
"allowed": false,
"description": "Deploy a Cloud Run service directly from a self-contained source code archive (.tar.gz),"
},
{
"name": "deploy_service_from_file_contents",
"read_only": false,
"allowed": false,
"description": "Deploys a Cloud Run service directly from local source files. This method is suitable for"
}
]
},
"cloud_sql": {
"url": "https://sqladmin.googleapis.com/mcp",
"tools": [
{
"name": "list_instances",
"read_only": true,
"allowed": true,
"description": "List all Cloud SQL instances in the project."
},
{
"name": "get_instance",
"read_only": true,
"allowed": true,
"description": "Get the details of a Cloud SQL instance."
},
{
"name": "create_instance",
"read_only": false,
"allowed": false,
"description": "Initiates the creation of a Cloud SQL instance."
},
{
"name": "execute_sql",
"read_only": false,
"allowed": false,
"description": "Execute any valid SQL statement, including data definition language (DDL),"
},
{
"name": "execute_sql_readonly",
"read_only": true,
"allowed": false,
"description": "Execute any valid read only SQL statement on a Cloud SQL instance."
},
{
"name": "get_operation",
"read_only": true,
"allowed": false,
"description": "Get the status of a long-running operation. A long-running operation can take several"
},
{
"name": "create_user",
"read_only": false,
"allowed": false,
"description": "Create a database user for a Cloud SQL instance."
},
{
"name": "update_user",
"read_only": false,
"allowed": false,
"description": "Update a database user for a Cloud SQL instance. A common use case for"
},
{
"name": "clone_instance",
"read_only": false,
"allowed": false,
"description": "Create a Cloud SQL instance as a clone of a source instance."
},
{
"name": "update_instance",
"read_only": false,
"allowed": false,
"description": "Partially updates the configuration settings of a Cloud SQL instance."
},
{
"name": "list_users",
"read_only": true,
"allowed": false,
"description": "List all database users for a Cloud SQL instance."
},
{
"name": "create_backup",
"read_only": false,
"allowed": false,
"description": "Takes a backup on a Cloud SQL instance. Always populate the project and instance fields on"
},
{
"name": "restore_backup",
"read_only": false,
"allowed": false,
"description": "Restores a backup to a Cloud SQL instance."
},
{
"name": "import_data",
"read_only": false,
"allowed": false,
"description": "Import data into a Cloud SQL instance."
},
{
"name": "postgres_upgrade_precheck",
"read_only": false,
"allowed": false,
"description": "Checks if a Cloud SQL for PostgreSQL instance is ready for a major version upgrade to the"
}
]
},
"storage": {
"url": "https://storage.googleapis.com/storage/mcp",
"tools": [
{
"name": "list_buckets",
"read_only": true,
"allowed": true,
"description": "Lists the buckets of a project."
},
{
"name": "list_objects",
"read_only": true,
"allowed": false,
"description": "Lists the objects in a bucket."
},
{
"name": "create_bucket",
"read_only": false,
"allowed": false,
"description": "Creates a bucket in a project."
},
{
"name": "delete_bucket",
"read_only": false,
"allowed": false,
"description": "Deletes a bucket from a project."
},
{
"name": "read_text",
"read_only": true,
"allowed": false,
"description": "DEPRECATED: Use `read_object` instead. Reads non-binary text content from an object."
},
{
"name": "read_object",
"read_only": true,
"allowed": false,
"description": "Reads an object from Cloud Storage. Supports both text and binary content (it will output text for text content and binary for binary content)."
},
{
"name": "write_text",
"read_only": false,
"allowed": false,
"description": "Writes text content to an object, overwriting any existing content."
},
{
"name": "delete_object",
"read_only": false,
"allowed": false,
"description": "Deletes an object from Cloud Storage."
},
{
"name": "get_object_metadata",
"read_only": true,
"allowed": false,
"description": "Gets the metadata of an object."
}
]
},
"pubsub": {
"url": "https://pubsub.googleapis.com/mcp",
"tools": [
{
"name": "create_topic",
"read_only": false,
"allowed": false,
"description": "Create a new Cloud Pub/Sub topic."
},
{
"name": "update_topic",
"read_only": false,
"allowed": false,
"description": "Update an existing Cloud Pub/Sub topic."
},
{
"name": "delete_topic",
"read_only": false,
"allowed": false,
"description": "Delete an existing Cloud Pub/Sub topic."
},
{
"name": "get_topic",
"read_only": true,
"allowed": true,
"description": "Get the configuration of a Cloud Pub/Sub topic."
},
{
"name": "list_topics",
"read_only": true,
"allowed": true,
"description": "List all Cloud Pub/Sub topics in a given project."
},
{
"name": "create_subscription",
"read_only": false,
"allowed": false,
"description": "Create a new Cloud Pub/Sub subscription to a given topic."
},
{
"name": "update_subscription",
"read_only": false,
"allowed": false,
"description": "Update an existing Cloud Pub/Sub subscription."
},
{
"name": "delete_subscription",
"read_only": false,
"allowed": false,
"description": "Delete an existing Cloud Pub/Sub subscription."
},
{
"name": "get_subscription",
"read_only": true,
"allowed": true,
"description": "Get the configuration of a Cloud Pub/Sub subscription."
},
{
"name": "list_subscriptions",
"read_only": true,
"allowed": true,
"description": "List all Cloud Pub/Sub subscriptions in a given project."
},
{
"name": "create_snapshot",
"read_only": false,
"allowed": false,
"description": "Create a new Cloud Pub/Sub snapshot from a given subscription."
},
{
"name": "delete_snapshot",
"read_only": false,
"allowed": false,
"description": "Delete an existing Cloud Pub/Sub snapshot."
},
{
"name": "get_snapshot",
"read_only": true,
"allowed": false,
"description": "Get the configuration of a Cloud Pub/Sub snapshot."
},
{
"name": "list_snapshots",
"read_only": true,
"allowed": false,
"description": "List all Cloud Pub/Sub snapshots in a given project."
},
{
"name": "publish",
"read_only": false,
"allowed": false,
"description": "Publish a series of one or more messages to an existing topic."
}
]
},
"iam": {
"url": "https://iam.googleapis.com/mcp",
"tools": [
{
"name": "list_deny_policies",
"read_only": true,
"allowed": true,
"description": "Lists IAM v2 deny policies attached to a Google Cloud project. Orgs and folders are not supported."
},
{
"name": "get_deny_policy",
"read_only": true,
"allowed": true,
"description": "Gets the details, metadata, and rules of an IAM v2 deny policy attached to a Google Cloud project. Orgs and folders are not supported."
},
{
"name": "create_deny_policy",
"read_only": false,
"allowed": false,
"description": "Creates a new IAM v2 deny policy attached to a Google Cloud project. Orgs and folders are not supported."
},
{
"name": "update_deny_policy",
"read_only": false,
"allowed": false,
"description": "Updates an existing IAM v2 deny policy attached to a Google Cloud project. Orgs and folders are not supported."
},
{
"name": "delete_deny_policy",
"read_only": false,
"allowed": false,
"description": "Permanently deletes an IAM v2 deny policy from a Google Cloud project. Orgs and folders are not supported."
},
{
"name": "get_deny_policy_status",
"read_only": true,
"allowed": false,
"description": "Gets the status of a long-running operation initiated by creating, updating, or deleting an IAM v2 deny policy."
},
{
"name": "list_roles",
"read_only": true,
"allowed": true,
"description": "Lists every custom IAM role that is defined for a Google Cloud project. Orgs and folders are not supported."
},
{
"name": "get_role",
"read_only": true,
"allowed": true,
"description": "Gets the definition of a custom role. Orgs are not supported."
},
{
"name": "create_role",
"read_only": false,
"allowed": false,
"description": "Creates a new custom IAM role for a project. Orgs are not supported."
},
{
"name": "update_role",
"read_only": false,
"allowed": false,
"description": "Updates the definition of an existing custom IAM role. Orgs are not supported."
},
{
"name": "delete_role",
"read_only": false,
"allowed": false,
"description": "Deletes a custom IAM role, making it inactive. Orgs are not supported."
},
{
"name": "undelete_role",
"read_only": false,
"allowed": false,
"description": "Restores (undeletes) a previously deleted custom IAM role. Orgs are not supported."
}
]
},
"monitoring": {
"url": "https://monitoring.googleapis.com/mcp",
"tools": [
{
"name": "list_timeseries",
"read_only": true,
"allowed": true,
"description": "Lists time series data from the Google Cloud Monitoring API"
},
{
"name": "query_range",
"read_only": true,
"allowed": false,
"description": "Evaluate a PromQL query in a range of time"
},
{
"name": "get_alert_policy",
"read_only": true,
"allowed": true,
"description": "Use this as the primary tool to get information about a specific alerting policy. Alerting policies define the conditions under which you want to be notified about issues with your services. This is u"
},
{
"name": "list_alert_policies",
"read_only": true,
"allowed": true,
"description": "Use this as the primary tool to list the alerting policies in a Google Cloud project. Alerting policies define the conditions under which you want to be notified about issues with your services. This "
},
{
"name": "get_alert",
"read_only": true,
"allowed": false,
"description": "Use this as the primary tool to get information about a specific alert. An alert is the representation of a violation of an alert policy. This is useful for understanding the details of a specific ale"
},
{
"name": "list_alerts",
"read_only": true,
"allowed": false,
"description": "Use this as the primary tool to list the alerts in a Google Cloud project. An alert is the representation of a violation of an alert policy. This is useful for understanding current and past violation"
},
{
"name": "list_metric_descriptors",
"read_only": true,
"allowed": true,
"description": "Use this as the primary tool to discover the types of metrics available in a Google Cloud project. This is a good first step to understanding what data is available for monitoring and building dashboa"
},
{
"name": "list_dashboards",
"read_only": true,
"allowed": true,
"description": "Use this as the primary tool to retrieve a list of existing custom monitoring dashboards in a Google Cloud project. Custom monitoring dashboards let users view and analyze data from different sources "
},
{
"name": "get_dashboard",
"read_only": true,
"allowed": false,
"description": "Use this as the primary tool to retrieve a single specific custom monitoring dashboard from a Google Cloud project using the resource name of the requested dashboard. Custom monitoring dashboards let "
}
]
},
"network_intelligence": {
"url": "https://networkmanagement.googleapis.com/mcp",
"tools": [
{
"name": "create_connectivity_test",
"read_only": false,
"allowed": false,
"description": "Creates and runs a Connectivity Test from the source to the destination endpoint. Test runs are billable after the project exceeds its free limit. Note that only test runs with results other than 'UND"
},
{
"name": "get_connectivity_test",
"read_only": true,
"allowed": true,
"description": "Gets the details of a specific Connectivity Test."
},
{
"name": "list_connectivity_tests",
"read_only": true,
"allowed": true,
"description": "Lists all Connectivity Tests owned by a project."
},
{
"name": "delete_connectivity_test",
"read_only": false,
"allowed": false,
"description": "Deletes a specific Connectivity Test."
},
{
"name": "get_networkmanagement_connectivity_test_iam_policy",
"read_only": true,
"allowed": false,
"description": "Gets the IAM access control policy for a Network Management resource. The 'resource' parameter must be the fully-qualified resource name, for example: 'projects/{project_id}/locations/global/connectiv"
},
{
"name": "set_networkmanagement_connectivity_test_iam_policy",
"read_only": false,
"allowed": false,
"description": "Sets the IAM access control policy for a Network Management resource. The 'resource' parameter must be the fully-qualified resource name, for example: 'projects/{project_id}/locations/global/connectiv"
},
{
"name": "test_networkmanagement_connectivity_test_iam_permissions",
"read_only": true,
"allowed": false,
"description": "Returns permissions that a caller has on the specified Network Management resource. The 'resource' parameter must be the fully-qualified resource name, for example: 'projects/{project_id}/locations/gl"
}
]
}
}

View File

@@ -1,2 +1,4 @@
[pytest] [pytest]
testpaths = tests testpaths = tests
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function

79
scripts/list-mcp-tools.py Normal file
View File

@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""List every tool a provider bundle's remote MCP servers offer, with read-only hints.
Use it to review allowlists: only list tools; this never calls one.
Usage: .venv/bin/python scripts/list-mcp-tools.py [provider] [--json] [--no-auth]
--no-auth lists without credentials; Google Cloud MCP servers allow tools/list anonymously.
"""
from __future__ import annotations
import asyncio
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.config import get_settings
from app.providers import load_provider
from app.tools.mcp import McpClient, NoAuth, auth_from_config
async def main(provider: str, as_json: bool, no_auth: bool) -> int:
bundle = load_provider(provider)
auth = (
NoAuth()
if no_auth
else auth_from_config(bundle.mcp_auth, get_settings().MCP_QUOTA_PROJECT)
)
report = {}
for server in bundle.mcp_servers.values():
try:
tools = await McpClient(server, auth, timeout=30).list_tools()
except Exception as exc: # noqa: BLE001 - report every server
report[server.id] = {
"url": server.url,
"error": f"{type(exc).__name__}: {exc}",
}
continue
report[server.id] = {
"url": server.url,
"tools": [
{
"name": tool.name,
"read_only": tool.read_only,
"allowed": tool.name in server.allow,
"description": tool.description.split("\n")[0][:200],
}
for tool in tools
],
}
if as_json:
print(json.dumps(report, indent=2))
return 0
for server_id, entry in report.items():
print(f"\n== {server_id} ({entry['url']})")
if "error" in entry:
print(f" ERROR {entry['error'][:200]}")
continue
for tool in entry["tools"]:
flag = "RO" if tool["read_only"] else "RW"
allowed = "allowed" if tool["allowed"] else ""
print(f" [{flag}] {tool['name']:<40} {allowed:<8} {tool['description']}")
return 0
if __name__ == "__main__":
args = [a for a in sys.argv[1:] if not a.startswith("--")]
sys.exit(
asyncio.run(
main(
args[0] if args else "gcp",
"--json" in sys.argv,
"--no-auth" in sys.argv,
)
)
)

View File

@@ -0,0 +1,38 @@
---
name: cloud-discovery
description: >-
Discovers and documents the current state of a workload's existing cloud
environment through the Cloud provider's read-only MCP discovery tools. Use
when requirements discovery needs the as-is architecture of resources that
already run in the user's cloud project or account.
metadata:
scope: requirements-discovery
---
# Cloud discovery
Describe what actually exists, so requirements rest on facts rather than recollection.
## Before you discover
Your discovery tools read the user's live cloud environment. The first call may pause the Execution to ask the user's permission. When permission is refused, work only from what the user tells you.
Ask the user which project, subscription or account and which regions hold the workload, unless the request already says. Discover only there.
## Steps
1. **Inventory first.** Use the broadest inventory tool available (an asset inventory or project search) to list the resource types and counts in scope.
2. **Detail what matters.** For each resource type that belongs to the workload, call the product's list and get tools for configuration: sizes, regions and zones, scaling, networking, identities and their roles.
3. **Map relationships.** Connect compute to its data stores, messaging, load balancers and identities, from configuration you have read, not from names alone.
4. **Record gaps.** When a tool reports a discovery gap (a server that's unavailable, an API that isn't enabled, a permission that's missing), list it under `Assumptions / discovery gaps` with the resource type it leaves unknown.
## Writing the current state
Under the `Current state` heading, give:
- a component inventory table: component, resource type, location, key configuration
- the relationships between components as a short list
- observed operational signals, such as alert policies and dashboards, when discovered
- `Assumptions / discovery gaps`
Report what exists, not what should change; recommendations belong to later Deliverables. Never include secrets, credentials, object contents or database rows, even when a tool returns them.

View File

@@ -0,0 +1,39 @@
---
name: iac-validation
description: >-
Checks Terraform infrastructure-as-code without provisioning anything, using
the local terraform_fmt, terraform_validate and terraform_plan tools. Use when
writing deployment guidance or validating it before deployment.
metadata:
scope: deployment-guidance validation
---
# IaC validation
Every check runs on a scratch copy of the files you pass. Nothing is applied, and no state is written.
## Tools
- `terraform_fmt(files)`: returns the files formatting changed. Replace your copies with the returned content.
- `terraform_validate(files)`: runs `init -backend=false` and `validate` offline. It reports syntax errors, unknown references, missing variables and invalid arguments.
- `terraform_plan(files, variables)`: previews the changes against the live cloud environment. It reads live state, so the first call may pause for the user's permission. Pass every variable the configuration requires.
## When writing deployment guidance
1. Run `terraform_fmt`, then `terraform_validate`, on the complete set of files you will attach.
2. Fix every error and run both again, until `terraform_validate` passes.
3. Attach the formatted files.
## When validating deployment guidance
1. Run `terraform_validate` on the attached files, and report its verdict and output.
2. When permission to read the live environment is granted, run `terraform_plan` with the variable values from the requirements, or clearly marked placeholders. Summarise the resources to add, change and destroy, and flag any destroy or replace.
3. When a check can't run (a missing CLI, a refused permission or a provider download failure), give the user the exact commands to run themselves:
```bash
terraform init -backend=false
terraform validate
terraform plan -lock=false -var-file=<your.tfvars>
```
Never suggest `terraform apply` as part of validation.

View File

@@ -4,7 +4,6 @@ import json
from collections.abc import AsyncGenerator from collections.abc import AsyncGenerator
from pathlib import Path from pathlib import Path
import pytest
from google.adk.models.base_llm import BaseLlm from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse from google.adk.models.llm_response import LlmResponse
@@ -20,8 +19,6 @@ from app.execution.recorder import InMemoryRecorder
from app.execution.toolkit import make_tool_factory from app.execution.toolkit import make_tool_factory
from app.providers import load_provider from app.providers import load_provider
pytestmark = pytest.mark.asyncio
AGENTS_DIR = Path(__file__).parents[2] / "agents" AGENTS_DIR = Path(__file__).parents[2] / "agents"

View File

@@ -25,8 +25,6 @@ from app.agents.runtime import (
) )
from app.providers import load_provider from app.providers import load_provider
pytestmark = pytest.mark.asyncio
SKILLS = {name: meta.path for name, meta in load_provider("gcp").skills.items()} SKILLS = {name: meta.path for name, meta in load_provider("gcp").skills.items()}

View File

@@ -37,6 +37,14 @@ def test_roles_take_skills_mcp_servers_and_models_from_the_bundle(bundle):
assert roles["orchestrator"].model == bundle.models.default assert roles["orchestrator"].model == bundle.models.default
def test_roles_name_only_the_local_tools_they_need(bundle):
roles = load_roles(AGENTS_DIR, bundle)
assert roles["diagrammer"].tools == ("mermaid_check",)
assert roles["validator"].tools == ("terraform_validate", "terraform_plan")
assert roles["requirements-analyst"].tools == ()
def test_preview_mcp_servers_can_be_excluded(bundle): def test_preview_mcp_servers_can_be_excluded(bundle):
roles = load_roles(AGENTS_DIR, bundle, include_preview_mcp=False) roles = load_roles(AGENTS_DIR, bundle, include_preview_mcp=False)
@@ -96,9 +104,9 @@ def write_agents(tmp_path: Path, bundle, overrides: dict[str, str]) -> Path:
( (
{ {
"decomposer.md": "---\nrole: decomposer\n" "decomposer.md": "---\nrole: decomposer\n"
"deliverable: technical_decomposition\ntool_tiers: [write]\n---\nB" "deliverable: technical_decomposition\ntools: [terraform_apply]\n---\nB"
}, },
"write", "terraform_apply",
), ),
( (
{ {

View File

@@ -5,7 +5,6 @@ Driven entirely through ExecutionEngine.start/resume with a scripted agent runti
from pathlib import Path from pathlib import Path
import pytest
from langgraph.checkpoint.memory import InMemorySaver from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
@@ -18,7 +17,6 @@ from app.execution.recorder import InMemoryRecorder
K = DeliverableKind K = DeliverableKind
P = PhaseId P = PhaseId
pytestmark = pytest.mark.asyncio
ROLES = { ROLES = {
"orchestrator": RoleSpec("orchestrator", "Coordinate the Execution.", budget=40), "orchestrator": RoleSpec("orchestrator", "Coordinate the Execution.", budget=40),

View File

@@ -1,15 +1,11 @@
"""The design advisor's fan-out to one advisor per architecture-framework pillar.""" """The design advisor's fan-out to one advisor per architecture-framework pillar."""
import pytest
from app.agents.fake_runtime import Call, FakeAgentRuntime from app.agents.fake_runtime import Call, FakeAgentRuntime
from app.agents.roles import PILLAR_ADVISOR from app.agents.roles import PILLAR_ADVISOR
from app.agents.runtime import RoleSpec, ToolSpec from app.agents.runtime import RoleSpec, ToolResult, ToolSpec
from app.execution.pillars import CONSULT_TOOL, pillar_consultation_tool from app.execution.pillars import CONSULT_TOOL, pillar_consultation_tool
from app.execution.toolkit import make_tool_factory from app.execution.toolkit import make_tool_factory
pytestmark = pytest.mark.asyncio
PILLARS = { PILLARS = {
"security": "waf-security", "security": "waf-security",
"reliability": "waf-reliability", "reliability": "waf-reliability",
@@ -99,6 +95,47 @@ async def test_an_advisor_that_fails_is_reported_without_losing_the_others():
assert "## reliability\n\nNo guidance:" in result.message assert "## reliability\n\nNo guidance:" in result.message
async def test_tool_factory_assembles_local_mcp_and_consultation_tools():
async def noop(**_):
return ToolResult("ok")
def tool(name, tier="general"):
return ToolSpec(name, name, {"type": "object", "properties": {}}, noop, tier)
class Catalog:
def tools_for(self, server_ids):
available = {
"docs": [tool("docs__search")],
"compute": [tool("compute__list_instances", "cloud_read")],
}
return [t for sid in server_ids for t in available.get(sid, [])]
advisor = RoleSpec(PILLAR_ADVISOR, "", budget=5, mcp_servers=("docs", "compute"))
runtime = FakeAgentRuntime({PILLAR_ADVISOR: [turn_for_pillar]})
factory = make_tool_factory(
runtime,
{PILLAR_ADVISOR: advisor},
{"security": "waf-security"},
local_tools=[tool("mermaid_check"), tool("terraform_plan", "cloud_read")],
catalog=Catalog(),
)
diagrammer = RoleSpec("diagrammer", "", budget=5, tools=("mermaid_check",))
analyst = RoleSpec("requirements-analyst", "", budget=5, mcp_servers=("compute",))
assert [t.name for t in factory(diagrammer, "architecture_diagram")] == [
"mermaid_check"
]
assert [t.name for t in factory(analyst, "requirements")] == [
"compute__list_instances"
]
[consult_tool] = factory(
RoleSpec("design-advisor", "", budget=5), "design_recommendations"
)
await consult_tool.handler(brief="b")
assert runtime.runs[0].tools == ("submit_advice", "docs__search")
async def test_tool_factory_gives_the_consultation_only_to_the_design_advisor(): async def test_tool_factory_gives_the_consultation_only_to_the_design_advisor():
roles = {PILLAR_ADVISOR: ADVISOR} roles = {PILLAR_ADVISOR: ADVISOR}
factory = make_tool_factory(FakeAgentRuntime({}), roles, PILLARS) factory = make_tool_factory(FakeAgentRuntime({}), roles, PILLARS)

View File

@@ -12,8 +12,6 @@ from app.execution.checkpointing import open_checkpointer
from app.execution.ledger import LedgerEvent from app.execution.ledger import LedgerEvent
from app.execution.recorder import DatabaseRecorder from app.execution.recorder import DatabaseRecorder
pytestmark = pytest.mark.asyncio
@pytest.fixture @pytest.fixture
def sqlite_db(tmp_path, monkeypatch): def sqlite_db(tmp_path, monkeypatch):

View File

@@ -177,3 +177,44 @@ def test_invalid_bundles_are_rejected(tmp_path, override, message):
with pytest.raises(ProviderConfigError, match=message): with pytest.raises(ProviderConfigError, match=message):
load_provider("test", root=tmp_path) load_provider("test", root=tmp_path)
REVIEW = REPO_ROOT / "providers" / "reviews" / "gcp-mcp-tools.json"
def test_every_allowlisted_mcp_tool_was_reviewed_as_read_only():
import json
review = json.loads(REVIEW.read_text(encoding="utf-8"))
bundle = load_provider("gcp")
for server in bundle.mcp_servers.values():
assert server.allow, f"{server.id} exposes no tools"
reviewed = {tool["name"]: tool for tool in review[server.id]["tools"]}
for name in server.allow:
assert name in reviewed, (
f"{server.id}.{name} was not in the reviewed tools/list"
)
assert reviewed[name]["read_only"], f"{server.id}.{name} is not read-only"
def test_data_reading_and_secret_capable_tools_stay_excluded():
bundle = load_provider("gcp")
excluded = {
"cloud_sql": {"execute_sql", "execute_sql_readonly"},
"storage": {"read_object", "read_text", "list_objects"},
"gke": {"get_k8s_resource", "describe_k8s_resource"},
}
for server_id, tools in excluded.items():
assert not tools & set(bundle.mcp_servers[server_id].allow), server_id
def test_bundle_places_each_local_tool_in_its_own_tier():
from app.tools.local import LOCAL_TOOLS
bundle = load_provider("gcp")
for tier, names in bundle.tools.items():
for name in names:
assert LOCAL_TOOLS[name][0] == tier, name

0
tests/tools/__init__.py Normal file
View File

142
tests/tools/test_local.py Normal file
View File

@@ -0,0 +1,142 @@
"""Local tools: Mermaid check and Terraform fmt/validate/plan in a scratch directory."""
import shutil
import pytest
from app.tools.local import (
LOCAL_TOOLS,
TerraformRunner,
local_tools,
mermaid_check,
)
needs_terraform = pytest.mark.skipif(
shutil.which("terraform") is None, reason="terraform CLI not installed"
)
VALID_TF = {
"main.tf": 'variable "region" {\n type = string\n}\n\noutput "region" {\n value = var.region\n}\n',
}
# --- mermaid ---------------------------------------------------------------------------
async def test_mermaid_accepts_a_flowchart():
result = await mermaid_check(
"flowchart TD\n A[Client] -->|HTTPS| B(Cloud Run)\n B --> C[(Database)]\n"
)
assert result.message.startswith("Mermaid check passed")
@pytest.mark.parametrize(
("diagram", "problem"),
[
("", "empty"),
("A --> B", "diagram type"),
("flowchart TD\n A[Client --> B", "Unbalanced"),
("%% comment only\n", "diagram type"),
],
)
async def test_mermaid_reports_problems(diagram, problem):
result = await mermaid_check(diagram)
assert result.message.startswith("Mermaid check failed")
assert problem in result.message
# --- terraform ---------------------------------------------------------------------------
@needs_terraform
async def test_fmt_returns_formatted_files_without_touching_the_input():
files = {"main.tf": 'variable "region" {\ntype=string\n}\n'}
result = await TerraformRunner().fmt(files)
assert "main.tf" in result.message
assert " type = string" in result.message
assert files["main.tf"] == 'variable "region" {\ntype=string\n}\n'
@needs_terraform
async def test_fmt_reports_already_formatted_files():
result = await TerraformRunner().fmt(VALID_TF)
assert result.message == "terraform fmt: all files are already formatted."
@needs_terraform
async def test_validate_passes_a_valid_configuration():
result = await TerraformRunner().validate(VALID_TF)
assert result.message.startswith("terraform validate passed")
@needs_terraform
async def test_validate_reports_errors():
result = await TerraformRunner().validate(
{"main.tf": 'output "x" {\n value = var.missing\n}\n'}
)
assert result.message.startswith("terraform validate failed")
assert "missing" in result.message
async def test_unsafe_file_names_are_refused():
runner = TerraformRunner()
for files in ({"../main.tf": ""}, {"/etc/main.tf": ""}, {"notes.txt": ""}, {}):
result = await runner.validate(files)
assert result.message.startswith("Refused"), files
async def test_missing_terraform_binary_is_reported_clearly():
result = await TerraformRunner(binary="terraform-not-installed").validate(VALID_TF)
assert "terraform-not-installed" in result.message
assert "not installed" in result.message
async def test_plan_never_runs_apply_and_refuses_unsafe_variables(monkeypatch):
commands: list[list[str]] = []
async def fake_run(self, args, cwd, env=None):
commands.append(list(args))
return 0, "ok"
monkeypatch.setattr(TerraformRunner, "_run", fake_run)
runner = TerraformRunner()
result = await runner.plan(VALID_TF, {"region": "europe-west2"})
refused = await runner.plan(VALID_TF, {"bad name": "x"})
assert result.message.startswith("terraform plan")
assert refused.message.startswith("Refused")
flat = [arg for command in commands for arg in command]
assert "apply" not in flat and "destroy" not in flat
plan = next(command for command in commands if command[1] == "plan")
assert "-lock=false" in plan and "-input=false" in plan
assert "-var=region=europe-west2" in plan
# --- registry ------------------------------------------------------------------------------
def test_local_tools_are_built_by_name_with_their_tier():
tools = local_tools(["mermaid_check", "terraform_plan"], TerraformRunner())
assert [(t.name, t.tier) for t in tools] == [
("mermaid_check", "general"),
("terraform_plan", "cloud_read"),
]
assert set(LOCAL_TOOLS) == {
"mermaid_check",
"terraform_fmt",
"terraform_validate",
"terraform_plan",
}
with pytest.raises(KeyError, match="terraform_apply"):
local_tools(["terraform_apply"], TerraformRunner())

229
tests/tools/test_mcp.py Normal file
View File

@@ -0,0 +1,229 @@
"""Remote MCP servers as read-only, allowlisted ToolSpecs, against a local fake server."""
import asyncio
import socket
import threading
import time
import pytest
import uvicorn
from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations
from app.execution.tools import gate_cloud_read
from app.providers import McpServerSpec
from app.tools.mcp import (
GoogleAdcAuth,
McpCatalog,
McpConfigError,
NoAuth,
StaticHeadersAuth,
auth_from_config,
tool_name,
)
READ_ONLY = ToolAnnotations(readOnlyHint=True)
def build_server(seen_headers: list[dict]) -> FastMCP:
server = FastMCP("fake-cloud", stateless_http=True, json_response=True)
@server.tool(annotations=READ_ONLY)
def list_projects(filter: str = "") -> str:
"""List projects."""
return f"projects matching {filter!r}: demo-project"
@server.tool(annotations=READ_ONLY)
def get_instance(name: str) -> str:
"""Get an instance."""
return f"instance {name}: RUNNING"
@server.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=True))
def delete_instance(name: str) -> str:
"""Delete an instance."""
return f"deleted {name}"
@server.tool()
def unannotated() -> str:
"""No annotations."""
return "?"
@server.tool(annotations=READ_ONLY)
def failing() -> str:
"""Always fails."""
raise RuntimeError("permission denied on project")
app = server.streamable_http_app()
async def recording_app(scope, receive, send):
if scope["type"] == "http":
seen_headers.append({k.decode(): v.decode() for k, v in scope["headers"]})
await app(scope, receive, send)
server.recording_app = recording_app # type: ignore[attr-defined]
return server
@pytest.fixture
def fake_server():
"""A fake MCP server on its own thread and event loop, like a real remote server."""
seen_headers: list[dict] = []
server = build_server(seen_headers)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
uv = uvicorn.Server(
uvicorn.Config(
server.recording_app,
host="127.0.0.1",
port=port,
log_level="warning",
lifespan="off",
)
)
async def serve():
async with server.session_manager.run():
await uv.serve()
thread = threading.Thread(target=asyncio.run, args=(serve(),), daemon=True)
thread.start()
deadline = time.monotonic() + 10
while not uv.started:
if time.monotonic() > deadline:
raise RuntimeError("fake MCP server did not start")
time.sleep(0.02)
yield f"http://127.0.0.1:{port}/mcp", seen_headers
uv.should_exit = True
thread.join(timeout=10)
def spec(url: str, allow, tier="cloud_read", server_id="compute") -> McpServerSpec:
return McpServerSpec(id=server_id, url=url, tier=tier, allow=tuple(allow))
async def test_only_allowlisted_read_only_tools_are_exposed(fake_server):
url, _ = fake_server
catalog = await McpCatalog.load(
[spec(url, ["list_projects", "get_instance"])], NoAuth()
)
tools = catalog.tools_for(["compute"])
assert [t.name for t in tools] == [
"compute__list_projects",
"compute__get_instance",
]
assert all(t.tier == "cloud_read" for t in tools)
assert tools[1].parameters["required"] == ["name"]
assert catalog.gaps == {}
async def test_calling_a_tool_returns_its_text(fake_server):
url, _ = fake_server
catalog = await McpCatalog.load([spec(url, ["get_instance"])], NoAuth())
result = await catalog.tools_for(["compute"])[0].handler(name="web-1")
assert result.message == "instance web-1: RUNNING"
assert result.outcome is None
@pytest.mark.parametrize("tool", ["delete_instance", "unannotated"])
async def test_allowlisting_a_tool_not_marked_read_only_fails_loudly(fake_server, tool):
url, _ = fake_server
with pytest.raises(McpConfigError, match=tool):
await McpCatalog.load([spec(url, [tool])], NoAuth())
async def test_empty_allowlist_exposes_nothing_and_never_connects():
catalog = await McpCatalog.load([spec("http://127.0.0.1:9/mcp", [])], NoAuth())
assert catalog.tools_for(["compute"]) == []
assert catalog.gaps == {}
async def test_allowlisted_tool_missing_upstream_is_recorded_as_a_gap(fake_server):
url, _ = fake_server
catalog = await McpCatalog.load([spec(url, ["list_projects", "renamed"])], NoAuth())
assert [t.name for t in catalog.tools_for(["compute"])] == [
"compute__list_projects"
]
assert "renamed" in catalog.gaps["compute"]
async def test_unreachable_server_becomes_a_discovery_gap_tool():
catalog = await McpCatalog.load(
[spec("http://127.0.0.1:9/mcp", ["list_projects"])], NoAuth(), timeout=2
)
[tool] = catalog.tools_for(["compute"])
result = await tool.handler()
assert tool.name == "compute__unavailable"
assert tool.tier == "cloud_read"
assert result.message.startswith("Discovery gap: compute MCP server unavailable")
assert "compute" in catalog.gaps
async def test_tool_error_is_returned_as_a_discovery_gap(fake_server):
url, _ = fake_server
catalog = await McpCatalog.load([spec(url, ["failing"])], NoAuth())
result = await catalog.tools_for(["compute"])[0].handler()
assert result.message.startswith("Discovery gap: compute__failing failed")
assert "permission denied" in result.message
async def test_cloud_read_mcp_tools_are_gated_like_any_tool(fake_server):
url, _ = fake_server
catalog = await McpCatalog.load([spec(url, ["list_projects"])], NoAuth())
tool = catalog.tools_for(["compute"])[0]
asked = await gate_cloud_read(tool, None).handler()
refused = await gate_cloud_read(tool, False).handler()
assert asked.outcome is not None and asked.outcome.permission == "cloud_read"
assert refused.message.startswith("Refused")
async def test_auth_headers_reach_the_server(fake_server):
url, seen = fake_server
await McpCatalog.load(
[spec(url, ["list_projects"])],
StaticHeadersAuth({"Authorization": "Bearer t", "X-Goog-User-Project": "p"}),
)
assert any(h.get("x-goog-user-project") == "p" for h in seen)
assert any(h.get("authorization") == "Bearer t" for h in seen)
async def test_long_results_are_truncated(fake_server):
url, _ = fake_server
catalog = await McpCatalog.load(
[spec(url, ["list_projects"])], NoAuth(), max_result_chars=20
)
result = await catalog.tools_for(["compute"])[0].handler(filter="x" * 50)
assert result.message.endswith("[truncated]")
def test_tool_names_are_safe_for_every_model_provider():
assert tool_name("asset_inventory", "search.all-resources") == (
"asset_inventory__search_all-resources"
)
assert len(tool_name("s" * 40, "t" * 40)) <= 64
def test_auth_is_chosen_from_bundle_config():
assert isinstance(auth_from_config({"kind": "none"}), NoAuth)
assert isinstance(
auth_from_config({"kind": "google_adc"}, quota_project="q"), GoogleAdcAuth
)
with pytest.raises(McpConfigError, match="oauth"):
auth_from_config({"kind": "oauth"})