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

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]