Solution architecture outcome pattern: agent and its MCP servers
Some checks failed
check agents / check (push) Failing after 13s
Some checks failed
check agents / check (push) Failing after 13s
The cp1-solution-architecture-agent and the sa-aws/azure/gcp-cloud MCP servers, a separate stream from the individual and sub-agent patterns. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
54
outcome-pattern/solution_architecture/mcp-servers/README.md
Normal file
54
outcome-pattern/solution_architecture/mcp-servers/README.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Solution Architecture MCP servers
|
||||
|
||||
One server per hyperscaler, used only by the Solution Architecture agent. Each carries the tool set of `gcp_solution_architecture_agent` (its `providers/gcp.yaml`), like for like, so the agent doesn't depend on the shared servers in the repository's root `mcp-servers/`.
|
||||
|
||||
| Server | Port | Tools | How it reaches the cloud |
|
||||
|---|---|---|---|
|
||||
| [`sa-gcp-cloud`](sa-gcp-cloud/) | 8115 | 44 | Forwards to the same 12 hosted Google MCP servers as the source, under the same allow lists |
|
||||
| [`sa-azure-cloud`](sa-azure-cloud/) | 8116 | 40 | Microsoft Learn, Resource Graph and ARM GET |
|
||||
| [`sa-aws-cloud`](sa-aws-cloud/) | 8117 | 44 | The AWS documentation server, and read-only API calls through the customer's role |
|
||||
|
||||
## How the Google tools work
|
||||
|
||||
Each tool is `gcp_<server>_<tool>`, such as `gcp_compute_list_instances`, and takes `tool_arguments`, passed through unchanged. `gcp_describe_tool` returns a hosted tool's live description and argument schema. A tool must be on the allow list and must declare `readOnlyHint` when it's called, or it's refused.
|
||||
|
||||
## Azure and AWS counterparts
|
||||
|
||||
The Azure and AWS tools keep the source's tool names where they can. The match is by capability, not by behaviour:
|
||||
|
||||
| Source | Azure | AWS |
|
||||
|---|---|---|
|
||||
| `answer_query` | None | None |
|
||||
| `search_projects` | Subscriptions | Organization accounts |
|
||||
| `analyze_iam_policy` | Role assignments | Account authorization details |
|
||||
| Cloud Run | Container Apps, App Service | App Runner, plus Lambda |
|
||||
| Cloud SQL | SQL, PostgreSQL, MySQL servers | RDS |
|
||||
| Cloud Storage | Storage accounts | S3 |
|
||||
| Pub/Sub | Service Bus, Event Hubs, Event Grid | SNS |
|
||||
| Deny policies | Deny assignments | Service control policies |
|
||||
| Connectivity tests | Connection monitors | Reachability Analyzer paths |
|
||||
| Commitments | Reserved capacity orders | Savings Plans |
|
||||
|
||||
Azure has no `get_subscription` or `get_deny_policy`, because Event Grid subscriptions and deny assignments come through a subscription-wide list.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Free-text documentation search is an accepted exception** to the root `mcp-servers/README.md` rule. Queries go to the vendor as written and aren't scrubbed. Each one is logged (`docs_query`). Replies are scrubbed as usual.
|
||||
- **Read-only.** Don't add a tool that creates, changes or deletes anything.
|
||||
- **Store each server's connection per project, never tenant-wide.** It holds the customer's credential.
|
||||
- **Don't edit `<server>/server.py` or `*.server.yaml` by hand.** They're generated.
|
||||
|
||||
## Working on a server
|
||||
|
||||
The sources are `build_definitions.py` (the tool tables), `_support/`, and the shared `../../../mcp-servers/_common/`, which these servers reuse and never change.
|
||||
|
||||
```sh
|
||||
python3 build_definitions.py
|
||||
for n in sa-gcp-cloud sa-azure-cloud sa-aws-cloud; do
|
||||
python3 ../../../scripts/render_mcp_server.py $n.server.yaml --out $n \
|
||||
--platform ~/platform-engineering/kyndryl-agent-builder/modernization-platform
|
||||
SERVER_DIR=$PWD/$n python3 -m pytest tests/test_servers.py
|
||||
done
|
||||
```
|
||||
|
||||
Rendering needs `pydantic`, `pyyaml`, `httpx`, `pymongo` and `jinja2`. Testing also needs the packages in each server's `requirements.txt`, and `pytest`.
|
||||
@@ -0,0 +1,47 @@
|
||||
# sa-aws-cloud: the AWS counterpart of each source tool. Only list, describe and get operations are named here, and
|
||||
# every call goes through the customer's read-only role, inside the connection's accounts and regions.
|
||||
|
||||
|
||||
async def _aws_list(tool: str, arguments: Dict[str, Any], entry: tuple, wanted: Optional[List[str]] = None) -> Dict[str, Any]:
|
||||
"""One page; `wanted` adds caller values to the fixed request, as (parameter, argument) pairs of a required value."""
|
||||
service, operation, result_key, token_in, token_out, fixed = entry
|
||||
fixed = dict(fixed)
|
||||
for parameter, argument in wanted or []:
|
||||
if not arguments.get(argument):
|
||||
return _refuse("invalid_argument", f"{argument} is required")
|
||||
fixed[parameter] = arguments[argument]
|
||||
return await _aws_kind(tool, {**arguments, "kind": "one"}, {"one": (service, operation, result_key, token_in, token_out, fixed)}, "one")
|
||||
|
||||
|
||||
async def _aws_get(tool: str, arguments: Dict[str, Any], service: str, operation: str, request: Dict[str, Any]) -> Dict[str, Any]:
|
||||
account, region, refused = _aws_target(arguments)
|
||||
if refused:
|
||||
return refused
|
||||
missing = [k for k, v in request.items() if v in (None, "", [], [None])]
|
||||
if missing:
|
||||
return _refuse("invalid_argument", "missing: " + ", ".join(missing))
|
||||
try:
|
||||
body = await _aws_call(arguments, service, operation, region, **request)
|
||||
except Exception as error:
|
||||
return _upstream_failed("aws", error)
|
||||
body.pop("ResponseMetadata", None)
|
||||
return _one_result("aws", tool, arguments, body)
|
||||
|
||||
|
||||
async def _aws_metric_data(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
queries, start, end = arguments.get("metric_queries"), arguments.get("start_time"), arguments.get("end_time")
|
||||
if not isinstance(queries, list) or not queries or not start or not end:
|
||||
return _refuse("invalid_argument", "metric_queries, start_time and end_time are required")
|
||||
return await _aws_get(tool, arguments, "cloudwatch", "get_metric_data",
|
||||
{"MetricDataQueries": queries, "StartTime": start, "EndTime": end})
|
||||
|
||||
|
||||
def _aws_docs_connection() -> Dict[str, Any]:
|
||||
connection = get_connection()
|
||||
return {"aws_access_key_id": connection.get("docs_access_key_id") or connection.get("access_key_id"),
|
||||
"aws_secret_access_key": connection.get("docs_secret_access_key") or connection.get("secret_access_key")}
|
||||
|
||||
|
||||
def _aws_docs_request(url: Any) -> Dict[str, Any]:
|
||||
"""The call shape AWS's documentation reader takes (agent-toolkit-for-aws)."""
|
||||
return {"requests": [{"url": url, "max_length": 100000}]}
|
||||
@@ -0,0 +1,102 @@
|
||||
# sa-azure-cloud: the Azure counterpart of each source tool. Reads go through Resource Graph where it holds the data,
|
||||
# under the connection's scope, and otherwise through ARM GET on a subscription or resource inside that scope.
|
||||
AZURE_ID = r"/subscriptions/[A-Za-z0-9\-]+(/[A-Za-z0-9._()\-]+)+"
|
||||
AZURE_ROLE_ASSIGNMENTS = "microsoft.authorization/roleassignments"
|
||||
AZURE_ROLE_DEFINITIONS = "microsoft.authorization/roledefinitions"
|
||||
|
||||
|
||||
async def _azure_list(tool: str, arguments: Dict[str, Any], table: str, types: List[str]) -> Dict[str, Any]:
|
||||
return await _azure_page(tool, arguments, _azure_type_query(table, types))
|
||||
|
||||
|
||||
async def _azure_get(tool: str, arguments: Dict[str, Any], table: str, types: List[str]) -> Dict[str, Any]:
|
||||
resource_id = str(arguments.get("resource_id") or "")
|
||||
if not re.fullmatch(AZURE_ID, resource_id) and not resource_id.startswith("/providers/Microsoft.Authorization/"):
|
||||
return _refuse("invalid_argument", "resource_id must be a full ARM resource id")
|
||||
if "'" in resource_id:
|
||||
return _refuse("invalid_argument", "resource_id must be a full ARM resource id")
|
||||
listed = ", ".join(f"'{t}'" for t in types)
|
||||
try:
|
||||
body = await _azure_graph(f"{table} | where id =~ '{resource_id}' and type in~ ({listed})", 1)
|
||||
except Exception as error:
|
||||
return _upstream_failed("azure", error)
|
||||
if not body.get("data"):
|
||||
return _refuse("outside_scope", "no such resource inside this connection's scope")
|
||||
return _one_result("azure", tool, arguments, body["data"][0])
|
||||
|
||||
|
||||
async def _azure_in_scope(resource_id: str) -> bool:
|
||||
if not re.fullmatch(AZURE_ID, resource_id) or "'" in resource_id:
|
||||
return False
|
||||
return bool((await _azure_graph(f"Resources | where id =~ '{resource_id}'", 1)).get("data"))
|
||||
|
||||
|
||||
async def _azure_arm(tool: str, arguments: Dict[str, Any], path: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""One page from ARM. A next link carries the bearer token wherever it points, so it must stay on this path."""
|
||||
try:
|
||||
upstream, skip = _read_page(arguments)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return _refuse("invalid_page_token", "page_token isn't one this server issued")
|
||||
connection = get_connection()
|
||||
base = f"{_azure_endpoints(connection)['arm']}{path}"
|
||||
if upstream and not upstream.startswith(f"{base}?"):
|
||||
return _refuse("invalid_page_token", "page_token isn't one this server issued")
|
||||
try:
|
||||
token = await _azure_token(connection)
|
||||
send = {"headers": {"Authorization": f"Bearer {token}"}}
|
||||
if not upstream:
|
||||
send["params"] = params
|
||||
response = await _with_backoff(lambda: _azure_client().get(upstream or base, **send))
|
||||
response.raise_for_status()
|
||||
body = response.json()
|
||||
except Exception as error:
|
||||
return _upstream_failed("azure", error)
|
||||
items = body.get("value", [body] if body else [])
|
||||
return _page_result("azure", tool, arguments, items, upstream, body.get("nextLink"), skip)
|
||||
|
||||
|
||||
async def _azure_subscription_arm(tool: str, arguments: Dict[str, Any], tail: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
try:
|
||||
subscription = await _azure_lock_subscription(arguments)
|
||||
except Exception as error:
|
||||
return _upstream_failed("azure", error)
|
||||
if not subscription:
|
||||
return _refuse("outside_scope", "subscription_id must name a subscription under this connection's scope")
|
||||
return await _azure_arm(tool, arguments, f"/subscriptions/{subscription}{tail}", params)
|
||||
|
||||
|
||||
async def _azure_resource_arm(tool: str, arguments: Dict[str, Any], tail: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
resource_id = str(arguments.get("resource_id") or "")
|
||||
try:
|
||||
inside = await _azure_in_scope(resource_id)
|
||||
except Exception as error:
|
||||
return _upstream_failed("azure", error)
|
||||
if not inside:
|
||||
return _refuse("outside_scope", "no such resource inside this connection's scope")
|
||||
return await _azure_arm(tool, arguments, f"{resource_id}{tail}", params)
|
||||
|
||||
|
||||
async def _azure_attached_disks(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
resource_id = str(arguments.get("resource_id") or "")
|
||||
if not re.fullmatch(AZURE_ID, resource_id) or "'" in resource_id:
|
||||
return _refuse("invalid_argument", "resource_id must be a full ARM resource id")
|
||||
return await _azure_page(tool, arguments, f"Resources | where type =~ 'microsoft.compute/disks' and managedBy =~ '{resource_id}' | order by id asc")
|
||||
|
||||
|
||||
async def _azure_node_pools(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return await _azure_page(tool, arguments, "Resources | where type =~ 'microsoft.containerservice/managedclusters' | mv-expand pool = properties.agentPoolProfiles | project id, name, pool | order by id asc")
|
||||
|
||||
|
||||
async def _azure_access(tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Role assignments, optionally for one principal or below one scope."""
|
||||
query = f"AuthorizationResources | where type =~ '{AZURE_ROLE_ASSIGNMENTS}'"
|
||||
principal, scope = arguments.get("principal_id"), arguments.get("scope")
|
||||
if principal:
|
||||
if not re.fullmatch(r"[A-Fa-f0-9\-]{36}", str(principal)):
|
||||
return _refuse("invalid_argument", "principal_id must be an object id")
|
||||
query += f" | where properties.principalId =~ '{principal}'"
|
||||
if scope:
|
||||
if not re.fullmatch(r"/[A-Za-z0-9._()/\-]+", str(scope)):
|
||||
return _refuse("invalid_argument", "scope must be an ARM scope")
|
||||
query += f" | where properties.scope startswith '{scope}'"
|
||||
return await _azure_page(tool, arguments, query + " | order by id asc")
|
||||
@@ -0,0 +1,5 @@
|
||||
# Every documentation query is logged. Free text by the owner's decision (see ../README.md).
|
||||
|
||||
|
||||
def _docs_query_logged(provider: str, tool: str, query: Any) -> None:
|
||||
logger.info("docs_query", provider=provider, tool=tool, query=str(query))
|
||||
@@ -0,0 +1,41 @@
|
||||
# Documentation search, free text by the owner's decision (see ../README.md). Queries go to the vendor as written and
|
||||
# every one is logged. Built on the session and sign-in code in the shared knowledge_support.py.
|
||||
|
||||
DOCS_MAX_TEXT = 20000
|
||||
|
||||
|
||||
async def _docs_call(provider: str, connection: Dict[str, Any], name: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
"""Call one tool on the vendor's documentation server, once that server says it still offers it."""
|
||||
session = await _knowledge_session(provider, connection)
|
||||
tools = {t.get("name") for t in await _knowledge_tools(provider, connection, session)}
|
||||
if name not in tools:
|
||||
raise LookupError(f"{provider} no longer offers {name}")
|
||||
response = await _knowledge_post(provider, connection, {
|
||||
"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": name, "arguments": arguments}}, session)
|
||||
parts = _knowledge_message(response).get("result", {}).get("content", [])
|
||||
return [{"text": str(p.get("text"))[:DOCS_MAX_TEXT]} for p in parts if p.get("type") == "text"]
|
||||
|
||||
|
||||
async def _docs_search(provider: str, tool: str, arguments: Dict[str, Any], connection: Dict[str, Any]) -> Dict[str, Any]:
|
||||
query = str(arguments.get("query") or "").strip()
|
||||
if not query:
|
||||
return _refuse("invalid_argument", "query is required")
|
||||
_docs_query_logged(provider, tool, query)
|
||||
try:
|
||||
found = await _knowledge_search(provider, connection, query)
|
||||
except Exception as error:
|
||||
return _upstream_failed(provider, error)
|
||||
return _page_result(provider, tool, arguments, found, None, None)
|
||||
|
||||
|
||||
async def _docs_read(provider: str, tool: str, arguments: Dict[str, Any], connection: Dict[str, Any], name: str,
|
||||
field: str, shape=None) -> Dict[str, Any]:
|
||||
target = arguments.get(field)
|
||||
if not target:
|
||||
return _refuse("invalid_argument", f"{field} is required")
|
||||
_docs_query_logged(provider, tool, target)
|
||||
try:
|
||||
found = await _docs_call(provider, connection, name, shape(target) if shape else {field: target})
|
||||
except Exception as error:
|
||||
return _upstream_failed(provider, error)
|
||||
return _page_result(provider, tool, arguments, found, None, None)
|
||||
@@ -0,0 +1,130 @@
|
||||
# sa-gcp-cloud: the tools of gcp_solution_architecture_agent, forwarded to the same hosted Google MCP servers under the
|
||||
# same allow lists (providers/gcp.yaml). Nothing outside GCP_MCP_SERVERS is reachable.
|
||||
GCP_MCP_SERVERS = {
|
||||
"developer_knowledge": {"url": "https://developerknowledge.googleapis.com/mcp",
|
||||
"allow": ("search_documents", "get_documents", "answer_query")},
|
||||
"resource_manager": {"url": "https://cloudresourcemanager.googleapis.com/mcp", "allow": ("search_projects",)},
|
||||
"asset_inventory": {"url": "https://cloudasset.googleapis.com/mcp", "allow": ("list_assets", "analyze_iam_policy")},
|
||||
"compute": {"url": "https://compute.googleapis.com/mcp",
|
||||
"allow": ("list_instances", "get_instance_basic_info", "list_instance_attached_disks",
|
||||
"list_instance_group_managers", "get_instance_group_manager_basic_info",
|
||||
"list_instance_templates", "get_instance_template_properties", "list_disks",
|
||||
"get_disk_basic_info", "list_reservations", "list_commitments")},
|
||||
"gke": {"url": "https://container.googleapis.com/mcp",
|
||||
"allow": ("list_clusters", "get_cluster", "list_node_pools", "get_node_pool", "get_k8s_version")},
|
||||
"cloud_run": {"url": "https://run.googleapis.com/mcp", "allow": ("list_services", "get_service")},
|
||||
"cloud_sql": {"url": "https://sqladmin.googleapis.com/mcp", "allow": ("list_instances", "get_instance")},
|
||||
"storage": {"url": "https://storage.googleapis.com/storage/mcp", "allow": ("list_buckets",)},
|
||||
"pubsub": {"url": "https://pubsub.googleapis.com/mcp",
|
||||
"allow": ("list_topics", "get_topic", "list_subscriptions", "get_subscription")},
|
||||
"iam": {"url": "https://iam.googleapis.com/mcp",
|
||||
"allow": ("list_roles", "get_role", "list_deny_policies", "get_deny_policy")},
|
||||
"monitoring": {"url": "https://monitoring.googleapis.com/mcp",
|
||||
"allow": ("list_alert_policies", "get_alert_policy", "list_dashboards", "list_metric_descriptors",
|
||||
"list_timeseries")},
|
||||
"network_intelligence": {"url": "https://networkmanagement.googleapis.com/mcp",
|
||||
"allow": ("list_connectivity_tests", "get_connectivity_test")},
|
||||
}
|
||||
GCP_DOCS_SERVER = "developer_knowledge"
|
||||
|
||||
|
||||
async def _gcp_mcp_headers(server_name: str) -> Dict[str, str]:
|
||||
headers = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json"}
|
||||
connection = get_connection()
|
||||
if server_name == GCP_DOCS_SERVER and connection.get("docs_api_key"):
|
||||
headers["X-Goog-Api-Key"] = str(connection["docs_api_key"])
|
||||
else:
|
||||
headers["Authorization"] = f"Bearer {await _gcp_token()}"
|
||||
if connection.get("quota_project"):
|
||||
headers["X-Goog-User-Project"] = str(connection["quota_project"])
|
||||
return headers
|
||||
|
||||
|
||||
async def _gcp_mcp_post(server_name: str, body: Dict[str, Any], session: Optional[str] = None):
|
||||
headers = await _gcp_mcp_headers(server_name)
|
||||
if session:
|
||||
headers["Mcp-Session-Id"] = session
|
||||
url = GCP_MCP_SERVERS[server_name]["url"]
|
||||
response = await _with_backoff(lambda: _gcp_client().post(url, content=json.dumps(body), headers=headers))
|
||||
response.raise_for_status()
|
||||
return response
|
||||
|
||||
|
||||
def _gcp_mcp_message(response) -> Dict[str, Any]:
|
||||
"""The JSON-RPC reply, whether it came back as JSON or as a server-sent event."""
|
||||
if "text/event-stream" in response.headers.get("content-type", ""):
|
||||
lines = [line[5:].strip() for line in response.text.splitlines() if line.startswith("data:")]
|
||||
return json.loads(lines[-1]) if lines else {}
|
||||
return response.json()
|
||||
|
||||
|
||||
async def _gcp_mcp_session(server_name: str) -> Optional[str]:
|
||||
response = await _gcp_mcp_post(server_name, {
|
||||
"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
||||
"params": {"protocolVersion": "2025-06-18", "capabilities": {},
|
||||
"clientInfo": {"name": "sa-gcp-cloud", "version": "0.1.0"}}})
|
||||
session = response.headers.get("mcp-session-id")
|
||||
await _gcp_mcp_post(server_name, {"jsonrpc": "2.0", "method": "notifications/initialized"}, session)
|
||||
return session
|
||||
|
||||
|
||||
async def _gcp_mcp_tools(server_name: str, session: Optional[str]) -> Dict[str, Dict[str, Any]]:
|
||||
response = await _gcp_mcp_post(server_name, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, session)
|
||||
return {t.get("name"): t for t in _gcp_mcp_message(response).get("result", {}).get("tools", [])}
|
||||
|
||||
|
||||
def _gcp_mcp_payload(result: Dict[str, Any]) -> Any:
|
||||
if result.get("structuredContent") is not None:
|
||||
return result["structuredContent"]
|
||||
parts = []
|
||||
for part in result.get("content", []):
|
||||
if part.get("type") != "text":
|
||||
continue
|
||||
try:
|
||||
parts.append(json.loads(part["text"]))
|
||||
except ValueError:
|
||||
parts.append(part["text"])
|
||||
return parts[0] if len(parts) == 1 else parts
|
||||
|
||||
|
||||
async def _gcp_forward(tool: str, server_name: str, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""One allow-listed tool on one hosted server. As in the source, a tool must declare itself read-only."""
|
||||
entry = GCP_MCP_SERVERS.get(server_name)
|
||||
if not entry or name not in entry["allow"]:
|
||||
return _refuse("not_allowed", "this tool isn't on the allow list")
|
||||
passed = arguments.get("tool_arguments") or {}
|
||||
if not isinstance(passed, dict):
|
||||
return _refuse("invalid_argument", "tool_arguments must be an object")
|
||||
if server_name == GCP_DOCS_SERVER:
|
||||
_docs_query_logged("gcp", tool, json.dumps(passed, sort_keys=True))
|
||||
try:
|
||||
session = await _gcp_mcp_session(server_name)
|
||||
tools = await _gcp_mcp_tools(server_name, session)
|
||||
if name not in tools:
|
||||
return _refuse("not_offered", "Google no longer offers this tool")
|
||||
if not tools[name].get("annotations", {}).get("readOnlyHint"):
|
||||
return _refuse("not_read_only", "the tool doesn't declare itself read-only")
|
||||
response = await _gcp_mcp_post(server_name, {
|
||||
"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": name, "arguments": passed}}, session)
|
||||
message = _gcp_mcp_message(response)
|
||||
except Exception as error:
|
||||
return _upstream_failed("gcp", error)
|
||||
result = message.get("result") or {}
|
||||
if message.get("error") or result.get("isError"):
|
||||
return _refuse("upstream_refused", f"{name} refused the request")
|
||||
return _one_result("gcp", tool, arguments, _gcp_mcp_payload(result))
|
||||
|
||||
|
||||
async def _gcp_describe(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
server_name, name = str(arguments.get("server") or ""), str(arguments.get("tool") or "")
|
||||
entry = GCP_MCP_SERVERS.get(server_name)
|
||||
if not entry or name not in entry["allow"]:
|
||||
return _refuse("not_allowed", "this tool isn't on the allow list")
|
||||
try:
|
||||
tools = await _gcp_mcp_tools(server_name, await _gcp_mcp_session(server_name))
|
||||
except Exception as error:
|
||||
return _upstream_failed("gcp", error)
|
||||
if name not in tools:
|
||||
return _refuse("not_offered", "Google no longer offers this tool")
|
||||
return _one_result("gcp", "gcp_describe_tool", arguments, {
|
||||
"description": tools[name].get("description"), "input_schema": tools[name].get("inputSchema")})
|
||||
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the three <server>.server.yaml definitions from the tables below, then render with ../../../scripts/render_mcp_server.py.
|
||||
|
||||
One server per hyperscaler, each carrying the tool set of gcp_solution_architecture_agent (its providers/gcp.yaml), so
|
||||
the agent never depends on the shared servers in the repository's root mcp-servers/.
|
||||
|
||||
Usage: python3 build_definitions.py
|
||||
"""
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SHARED = "../../../mcp-servers/_common"
|
||||
PAGING = [
|
||||
{"name": "page_size", "type": "integer", "description": "Items per page, up to 200. Default 50.", "required": False},
|
||||
{"name": "page_token", "type": "string", "description": "next_page_token from the previous reply.", "required": False},
|
||||
]
|
||||
AWS_WHERE = [
|
||||
{"name": "account_id", "type": "string", "description": "A member account of the connection.", "required": False},
|
||||
{"name": "region", "type": "string", "description": "One of the connection's regions; the first by default.", "required": False},
|
||||
]
|
||||
|
||||
|
||||
def param(name, description, kind="string", required=True):
|
||||
return {"name": name, "type": kind, "description": description, "required": required}
|
||||
|
||||
|
||||
def tool(name, description, body, parameters=()):
|
||||
return {"name": name, "display_name": name.replace("_", " ").capitalize(), "description": description,
|
||||
"parameters": list(parameters),
|
||||
"ai_implementation": f"async def {name}(arguments: Dict[str, Any]) -> Dict[str, Any]:\n{body}\n"}
|
||||
|
||||
|
||||
def gcp():
|
||||
source = (HERE / "_support" / "gcp_tools.py").read_text()
|
||||
catalog = next(ast.literal_eval(n.value) for n in ast.parse(source).body
|
||||
if isinstance(n, ast.Assign) and n.targets[0].id == "GCP_MCP_SERVERS")
|
||||
tools = [
|
||||
tool("gcp_check_connection", "Test the stored connection: sign in and open the resource manager server.",
|
||||
' try:\n await _gcp_mcp_session("resource_manager")\n except Exception as error:\n'
|
||||
' return {"ok": False, "message": _upstream_failed("gcp", error)["error"]["message"]}\n'
|
||||
' return {"ok": True, "message": "Signed in and reached Google\'s hosted servers."}'),
|
||||
tool("gcp_describe_tool", "Read a hosted tool's live description and argument schema, before calling it.",
|
||||
" return await _gcp_describe(arguments)",
|
||||
[param("server", "The hosted server, such as compute."), param("tool", "The hosted tool, such as list_instances.")]),
|
||||
]
|
||||
for server, entry in catalog.items():
|
||||
for name in entry["allow"]:
|
||||
tools.append(tool(f"gcp_{server}_{name}",
|
||||
f"Google's {name} on its {server} MCP server, read-only. Call gcp_describe_tool for its arguments.",
|
||||
f' return await _gcp_forward("gcp_{server}_{name}", "{server}", "{name}", arguments)',
|
||||
[param("tool_arguments", "The hosted tool's arguments.", "object", False)]))
|
||||
return {
|
||||
"server_id": "sa-gcp-cloud", "name": "Solution Architecture Google Cloud",
|
||||
"description": "Google Cloud documentation and read-only estate tools for the Solution Architecture agent, "
|
||||
"through Google's hosted MCP servers.",
|
||||
"version": "0.1.0", "port": 8115, "verify_tool": "gcp_check_connection",
|
||||
"shared_code": [f"{SHARED}/tool_support.py", f"{SHARED}/gcp_support.py", "_support/docs_log.py", "_support/gcp_tools.py"],
|
||||
"extra_requirements": ["google-auth==2.62.0", "requests==2.32.5"],
|
||||
"connection_fields": [
|
||||
{"name": "service_account_json", "title": "Service account key", "description": "The read-only service account's JSON key.", "required": True, "secret": True},
|
||||
{"name": "scope_root", "title": "Scope root", "description": "organizations/<id>, folders/<id> or projects/<id>.", "required": True, "secret": False},
|
||||
{"name": "quota_project", "title": "Quota project", "description": "Sent as X-Goog-User-Project. Optional.", "required": False, "secret": False},
|
||||
{"name": "docs_api_key", "title": "Documentation API key", "description": "Developer Knowledge API key. Without it, the service account signs in.", "required": False, "secret": True},
|
||||
],
|
||||
"tools": tools,
|
||||
}
|
||||
|
||||
|
||||
def azure():
|
||||
sub = param("subscription_id", "Needed when the connection's scope is a management group.", required=False)
|
||||
rid = param("resource_id", "The full ARM resource id.")
|
||||
tools = [
|
||||
tool("azure_check_connection", "Test the stored connection: sign in and read the scope root. Returns no customer data.",
|
||||
' try:\n await _azure_graph("ResourceContainers | limit 1", 1)\n except Exception as error:\n'
|
||||
' return {"ok": False, "message": _upstream_failed("azure", error)["error"]["message"]}\n'
|
||||
' return {"ok": True, "message": "Signed in and read the scope root."}'),
|
||||
tool("azure_search_documents", "Search Microsoft Learn in free text. Queries are sent as written and logged.",
|
||||
' return await _docs_search("azure", "azure_search_documents", arguments, {})', [param("query", "What to look up. Keep client detail out.")]),
|
||||
tool("azure_get_documents", "Fetch one Microsoft Learn page by URL.",
|
||||
' return await _docs_read("azure", "azure_get_documents", arguments, {}, "microsoft_docs_fetch", "url")', [param("url", "A learn.microsoft.com URL.")]),
|
||||
tool("azure_analyze_access", "List role assignments, optionally for one principal or below one scope.",
|
||||
' return await _azure_access("azure_analyze_access", arguments)',
|
||||
[param("principal_id", "An object id.", required=False), param("scope", "An ARM scope.", required=False), *PAGING]),
|
||||
tool("azure_list_instance_attached_disks", "List the disks attached to one virtual machine.",
|
||||
' return await _azure_attached_disks("azure_list_instance_attached_disks", arguments)', [rid, *PAGING]),
|
||||
tool("azure_list_node_pools", "List AKS node pools.", ' return await _azure_node_pools("azure_list_node_pools", arguments)', PAGING),
|
||||
]
|
||||
graph = [
|
||||
("azure_search_subscriptions", "ResourceContainers", ["microsoft.resources/subscriptions"], "subscriptions"),
|
||||
("azure_list_instances", "Resources", ["microsoft.compute/virtualmachines"], "virtual machines"),
|
||||
("azure_list_instance_group_managers", "Resources", ["microsoft.compute/virtualmachinescalesets"], "scale sets"),
|
||||
("azure_list_instance_templates", "Resources", ["microsoft.resources/templatespecs", "microsoft.compute/galleries/images"], "template specs and gallery images"),
|
||||
("azure_list_disks", "Resources", ["microsoft.compute/disks"], "managed disks"),
|
||||
("azure_list_reservations", "Resources", ["microsoft.compute/capacityreservationgroups"], "capacity reservation groups"),
|
||||
("azure_list_clusters", "Resources", ["microsoft.containerservice/managedclusters"], "AKS clusters"),
|
||||
("azure_list_services", "Resources", ["microsoft.app/containerapps", "microsoft.web/sites"], "Container Apps and App Service apps"),
|
||||
("azure_list_sql_instances", "Resources", ["microsoft.sql/servers", "microsoft.sql/managedinstances", "microsoft.dbforpostgresql/flexibleservers", "microsoft.dbformysql/flexibleservers"], "SQL, PostgreSQL and MySQL servers"),
|
||||
("azure_list_buckets", "Resources", ["microsoft.storage/storageaccounts"], "storage accounts"),
|
||||
("azure_list_topics", "Resources", ["microsoft.servicebus/namespaces", "microsoft.eventhub/namespaces", "microsoft.eventgrid/topics"], "Service Bus, Event Hubs and Event Grid topics"),
|
||||
("azure_list_roles", "AuthorizationResources", ["microsoft.authorization/roledefinitions"], "role definitions"),
|
||||
("azure_list_alert_policies", "Resources", ["microsoft.insights/metricalerts", "microsoft.insights/activitylogalerts", "microsoft.insights/scheduledqueryrules"], "alert rules"),
|
||||
("azure_list_dashboards", "Resources", ["microsoft.portal/dashboards"], "dashboards"),
|
||||
("azure_list_connectivity_tests", "Resources", ["microsoft.network/networkwatchers/connectionmonitors"], "connection monitors"),
|
||||
]
|
||||
for name, table, types, what in graph:
|
||||
tools.append(tool(name, f"List {what}.", f' return await _azure_list("{name}", arguments, "{table}", {types!r})', PAGING))
|
||||
for name, table, types, what in [
|
||||
("azure_get_instance_basic_info", "Resources", ["microsoft.compute/virtualmachines"], "one virtual machine"),
|
||||
("azure_get_instance_group_manager_basic_info", "Resources", ["microsoft.compute/virtualmachinescalesets"], "one scale set"),
|
||||
("azure_get_instance_template_properties", "Resources", ["microsoft.resources/templatespecs", "microsoft.compute/galleries/images"], "one template spec or gallery image"),
|
||||
("azure_get_disk_basic_info", "Resources", ["microsoft.compute/disks"], "one disk"),
|
||||
("azure_get_cluster", "Resources", ["microsoft.containerservice/managedclusters"], "one AKS cluster"),
|
||||
("azure_get_service", "Resources", ["microsoft.app/containerapps", "microsoft.web/sites"], "one app"),
|
||||
("azure_get_sql_instance", "Resources", ["microsoft.sql/servers", "microsoft.sql/managedinstances", "microsoft.dbforpostgresql/flexibleservers", "microsoft.dbformysql/flexibleservers"], "one database server"),
|
||||
("azure_get_topic", "Resources", ["microsoft.servicebus/namespaces", "microsoft.eventhub/namespaces", "microsoft.eventgrid/topics"], "one messaging resource"),
|
||||
("azure_get_role", "AuthorizationResources", ["microsoft.authorization/roledefinitions"], "one role definition"),
|
||||
("azure_get_alert_policy", "Resources", ["microsoft.insights/metricalerts", "microsoft.insights/activitylogalerts", "microsoft.insights/scheduledqueryrules"], "one alert rule"),
|
||||
("azure_get_connectivity_test", "Resources", ["microsoft.network/networkwatchers/connectionmonitors"], "one connection monitor"),
|
||||
]:
|
||||
tools.append(tool(name, f"Read {what}.", f' return await _azure_get("{name}", arguments, "{table}", {types!r})', [rid]))
|
||||
tools += [
|
||||
tool("azure_list_assets", "List every resource in scope, or one resource type.",
|
||||
' kind = arguments.get("resource_type")\n if kind and not re.fullmatch(r"[A-Za-z0-9./]+", str(kind)):\n return _refuse("invalid_argument", "resource_type must be an ARM type")\n'
|
||||
' where = f" | where type =~ \'{kind}\'" if kind else ""\n'
|
||||
' return await _azure_page("azure_list_assets", arguments, f"Resources{where} | project id, name, type, location, resourceGroup, subscriptionId, tags | order by id asc")',
|
||||
[param("resource_type", "An ARM type.", required=False), *PAGING]),
|
||||
tool("azure_get_node_pool", "Read one AKS node pool.",
|
||||
' return await _azure_resource_arm("azure_get_node_pool", arguments, f"/agentPools/{arguments.get(\'pool\')}", {"api-version": "2024-05-01"}) if re.fullmatch(r"[A-Za-z0-9]+", str(arguments.get("pool"))) else _refuse("invalid_argument", "pool must be a pool name")',
|
||||
[rid, param("pool", "The node pool's name.")]),
|
||||
tool("azure_list_commitments", "List reserved capacity orders, Azure's committed-use discounts.",
|
||||
' return await _azure_arm("azure_list_commitments", arguments, "/providers/Microsoft.Capacity/reservationOrders", {"api-version": "2022-11-01"})', PAGING),
|
||||
tool("azure_get_k8s_version", "List the Kubernetes versions AKS offers in one location.",
|
||||
' location = str(arguments.get("location") or "")\n if not re.fullmatch(r"[a-z0-9]+", location):\n return _refuse("invalid_argument", "location must be an Azure region name")\n'
|
||||
' return await _azure_subscription_arm("azure_get_k8s_version", arguments, f"/providers/Microsoft.ContainerService/locations/{location}/kubernetesVersions", {"api-version": "2024-05-01"})',
|
||||
[param("location", "An Azure region, such as uksouth."), sub]),
|
||||
tool("azure_list_subscriptions", "List Event Grid event subscriptions.",
|
||||
' return await _azure_subscription_arm("azure_list_subscriptions", arguments, "/providers/Microsoft.EventGrid/eventSubscriptions", {"api-version": "2022-06-15"})', [sub, *PAGING]),
|
||||
tool("azure_list_deny_policies", "List deny assignments.",
|
||||
' return await _azure_subscription_arm("azure_list_deny_policies", arguments, "/providers/Microsoft.Authorization/denyAssignments", {"api-version": "2022-04-01"})', [sub, *PAGING]),
|
||||
tool("azure_list_metric_descriptors", "List the metrics one resource publishes.",
|
||||
' return await _azure_resource_arm("azure_list_metric_descriptors", arguments, "/providers/Microsoft.Insights/metricDefinitions", {"api-version": "2018-01-01"})', [rid]),
|
||||
tool("azure_list_timeseries", "Read metric values for one resource.",
|
||||
' wanted = {k: arguments.get(k) for k in ("metricnames", "timespan", "interval", "aggregation") if arguments.get(k)}\n'
|
||||
' if "metricnames" not in wanted or "timespan" not in wanted:\n return _refuse("invalid_argument", "metricnames and timespan are required")\n'
|
||||
' return await _azure_resource_arm("azure_list_timeseries", arguments, "/providers/Microsoft.Insights/metrics", {"api-version": "2018-01-01", **wanted})',
|
||||
[rid, param("metricnames", "Comma-separated metric names."), param("timespan", "ISO 8601 interval, start/end."),
|
||||
param("interval", "ISO 8601 duration, such as PT1H.", required=False), param("aggregation", "Average, Total, Maximum, Minimum or Count.", required=False)]),
|
||||
]
|
||||
return {
|
||||
"server_id": "sa-azure-cloud", "name": "Solution Architecture Azure",
|
||||
"description": "Azure documentation and read-only estate tools for the Solution Architecture agent, through "
|
||||
"Microsoft Learn, Resource Graph and ARM.",
|
||||
"version": "0.1.0", "port": 8116, "verify_tool": "azure_check_connection",
|
||||
"shared_code": [f"{SHARED}/tool_support.py", f"{SHARED}/azure_support.py", f"{SHARED}/knowledge_support.py", "_support/docs_log.py", "_support/docs_support.py", "_support/azure_tools.py"],
|
||||
"extra_requirements": ["boto3==1.43.122"],
|
||||
"connection_fields": [
|
||||
{"name": "tenant_id", "title": "Tenant id", "description": "The Entra tenant id.", "required": False, "secret": False},
|
||||
{"name": "client_id", "title": "Client id", "description": "The app registration's id.", "required": False, "secret": False},
|
||||
{"name": "client_secret", "title": "Client secret", "description": "The client secret.", "required": False, "secret": True},
|
||||
{"name": "scope_root", "title": "Scope root", "description": "managementGroups/<id> or subscriptions/<id>.", "required": True, "secret": False},
|
||||
{"name": "cloud", "title": "Cloud", "description": "public, usgov or china. Optional.", "required": False, "secret": False},
|
||||
],
|
||||
"tools": tools,
|
||||
}
|
||||
|
||||
|
||||
def aws():
|
||||
where = [*AWS_WHERE, *PAGING]
|
||||
aws_id = lambda name, what: param(name, what) # noqa: E731
|
||||
listing = [
|
||||
("aws_search_projects", "the organisation's accounts", ("organizations", "list_accounts", "Accounts", "NextToken", "NextToken", {})),
|
||||
("aws_list_assets", "tagged resources", ("resourcegroupstaggingapi", "get_resources", "ResourceTagMappingList", "PaginationToken", "PaginationToken", {})),
|
||||
("aws_list_instances", "EC2 instances", ("ec2", "describe_instances", "Reservations", "NextToken", "NextToken", {})),
|
||||
("aws_list_instance_group_managers", "Auto Scaling groups", ("autoscaling", "describe_auto_scaling_groups", "AutoScalingGroups", "NextToken", "NextToken", {})),
|
||||
("aws_list_instance_templates", "launch templates", ("ec2", "describe_launch_templates", "LaunchTemplates", "NextToken", "NextToken", {})),
|
||||
("aws_list_disks", "EBS volumes", ("ec2", "describe_volumes", "Volumes", "NextToken", "NextToken", {})),
|
||||
("aws_list_reservations", "capacity reservations", ("ec2", "describe_capacity_reservations", "CapacityReservations", "NextToken", "NextToken", {})),
|
||||
("aws_list_commitments", "Savings Plans", ("savingsplans", "describe_savings_plans", "savingsPlans", "nextToken", "nextToken", {})),
|
||||
("aws_list_clusters", "EKS clusters", ("eks", "list_clusters", "clusters", "nextToken", "nextToken", {})),
|
||||
("aws_list_services", "App Runner services", ("apprunner", "list_services", "ServiceSummaryList", "NextToken", "NextToken", {})),
|
||||
("aws_list_functions", "Lambda functions", ("lambda", "list_functions", "Functions", "Marker", "NextMarker", {})),
|
||||
("aws_list_sql_instances", "RDS instances", ("rds", "describe_db_instances", "DBInstances", "Marker", "Marker", {})),
|
||||
("aws_list_buckets", "S3 buckets", ("s3", "list_buckets", "Buckets", "ContinuationToken", "ContinuationToken", {})),
|
||||
("aws_list_topics", "SNS topics", ("sns", "list_topics", "Topics", "NextToken", "NextToken", {})),
|
||||
("aws_list_subscriptions", "SNS subscriptions", ("sns", "list_subscriptions", "Subscriptions", "NextToken", "NextToken", {})),
|
||||
("aws_list_roles", "IAM roles", ("iam", "list_roles", "Roles", "Marker", "Marker", {})),
|
||||
("aws_list_deny_policies", "service control policies", ("organizations", "list_policies", "Policies", "NextToken", "NextToken", {"Filter": "SERVICE_CONTROL_POLICY"})),
|
||||
("aws_list_alert_policies", "CloudWatch metric alarms", ("cloudwatch", "describe_alarms", "MetricAlarms", "NextToken", "NextToken", {})),
|
||||
("aws_list_dashboards", "CloudWatch dashboards", ("cloudwatch", "list_dashboards", "DashboardEntries", "NextToken", "NextToken", {})),
|
||||
("aws_list_metric_descriptors", "CloudWatch metrics", ("cloudwatch", "list_metrics", "Metrics", "NextToken", "NextToken", {})),
|
||||
("aws_list_connectivity_tests", "Reachability Analyzer paths", ("ec2", "describe_network_insights_paths", "NetworkInsightsPaths", "NextToken", "NextToken", {})),
|
||||
]
|
||||
tools = [
|
||||
tool("aws_check_connection", "Test the stored connection: assume the role and read its identity. Returns no customer data.",
|
||||
' try:\n await _aws_call(arguments, "sts", "get_caller_identity")\n except Exception as error:\n'
|
||||
' return {"ok": False, "message": _upstream_failed("aws", error)["error"]["message"]}\n'
|
||||
' return {"ok": True, "message": "Assumed the role."}'),
|
||||
tool("aws_search_documents", "Search AWS documentation in free text. Queries are sent as written and logged.",
|
||||
' return await _docs_search("aws", "aws_search_documents", arguments, _aws_docs_connection())', [param("query", "What to look up. Keep client detail out.")]),
|
||||
tool("aws_get_documents", "Read one AWS documentation page by URL.",
|
||||
' return await _docs_read("aws", "aws_get_documents", arguments, _aws_docs_connection(), "aws___read_documentation", "url", _aws_docs_request)', [param("url", "A docs.aws.amazon.com URL.")]),
|
||||
]
|
||||
for name, what, entry in listing:
|
||||
tools.append(tool(name, f"List {what}.", f' return await _aws_list("{name}", arguments, {entry!r})', where))
|
||||
tools += [
|
||||
tool("aws_list_node_pools", "List one EKS cluster's node groups.",
|
||||
" return await _aws_list(\"aws_list_node_pools\", arguments, (\"eks\", \"list_nodegroups\", \"nodegroups\", \"nextToken\", \"nextToken\", {}), [(\"clusterName\", \"cluster\")])",
|
||||
[aws_id("cluster", "The cluster's name."), *where]),
|
||||
tool("aws_list_instance_attached_disks", "List the EBS volumes attached to one instance.",
|
||||
' instance = arguments.get("instance_id")\n if not instance:\n return _refuse("invalid_argument", "instance_id is required")\n'
|
||||
' return await _aws_list("aws_list_instance_attached_disks", arguments, ("ec2", "describe_volumes", "Volumes", "NextToken", "NextToken", {"Filters": [{"Name": "attachment.instance-id", "Values": [str(instance)]}]}))',
|
||||
[aws_id("instance_id", "The instance id."), *where]),
|
||||
]
|
||||
for name, what, service, operation, request, parameters in [
|
||||
("aws_get_instance_basic_info", "one EC2 instance", "ec2", "describe_instances", '{"InstanceIds": [arguments.get("instance_id")]}', [aws_id("instance_id", "The instance id.")]),
|
||||
("aws_get_instance_group_manager_basic_info", "one Auto Scaling group", "autoscaling", "describe_auto_scaling_groups", '{"AutoScalingGroupNames": [arguments.get("name")]}', [aws_id("name", "The group's name.")]),
|
||||
("aws_get_instance_template_properties", "a launch template's versions", "ec2", "describe_launch_template_versions", '{"LaunchTemplateId": arguments.get("template_id")}', [aws_id("template_id", "The template id.")]),
|
||||
("aws_get_disk_basic_info", "one EBS volume", "ec2", "describe_volumes", '{"VolumeIds": [arguments.get("volume_id")]}', [aws_id("volume_id", "The volume id.")]),
|
||||
("aws_get_cluster", "one EKS cluster", "eks", "describe_cluster", '{"name": arguments.get("name")}', [aws_id("name", "The cluster's name.")]),
|
||||
("aws_get_node_pool", "one EKS node group", "eks", "describe_nodegroup", '{"clusterName": arguments.get("cluster"), "nodegroupName": arguments.get("name")}', [aws_id("cluster", "The cluster's name."), aws_id("name", "The node group's name.")]),
|
||||
("aws_get_k8s_version", "EKS's supported Kubernetes versions", "eks", "describe_cluster_versions", "{}", []),
|
||||
("aws_get_service", "one App Runner service", "apprunner", "describe_service", '{"ServiceArn": arguments.get("arn")}', [aws_id("arn", "The service's ARN.")]),
|
||||
("aws_get_function", "one Lambda function's configuration", "lambda", "get_function_configuration", '{"FunctionName": arguments.get("name")}', [aws_id("name", "The function's name.")]),
|
||||
("aws_get_sql_instance", "one RDS instance", "rds", "describe_db_instances", '{"DBInstanceIdentifier": arguments.get("name")}', [aws_id("name", "The instance's identifier.")]),
|
||||
("aws_get_topic", "one SNS topic", "sns", "get_topic_attributes", '{"TopicArn": arguments.get("arn")}', [aws_id("arn", "The topic's ARN.")]),
|
||||
("aws_get_subscription", "one SNS subscription", "sns", "get_subscription_attributes", '{"SubscriptionArn": arguments.get("arn")}', [aws_id("arn", "The subscription's ARN.")]),
|
||||
("aws_get_role", "one IAM role", "iam", "get_role", '{"RoleName": arguments.get("name")}', [aws_id("name", "The role's name.")]),
|
||||
("aws_get_deny_policy", "one service control policy", "organizations", "describe_policy", '{"PolicyId": arguments.get("policy_id")}', [aws_id("policy_id", "The policy id.")]),
|
||||
("aws_get_alert_policy", "named CloudWatch alarms", "cloudwatch", "describe_alarms", '{"AlarmNames": [arguments.get("name")]}', [aws_id("name", "The alarm's name.")]),
|
||||
("aws_get_connectivity_test", "one Reachability Analyzer path", "ec2", "describe_network_insights_paths", '{"NetworkInsightsPathIds": [arguments.get("path_id")]}', [aws_id("path_id", "The path id.")]),
|
||||
("aws_analyze_access", "the account's IAM users, groups, roles and policies", "iam", "get_account_authorization_details", "{}", []),
|
||||
]:
|
||||
tools.append(tool(name, f"Read {what}.", f' return await _aws_get("{name}", arguments, "{service}", "{operation}", {request})', [*parameters, *AWS_WHERE]))
|
||||
tools.append(tool("aws_list_timeseries", "Read CloudWatch metric values.", ' return await _aws_metric_data("aws_list_timeseries", arguments)',
|
||||
[param("metric_queries", "CloudWatch MetricDataQueries.", "array"), param("start_time", "ISO 8601 start."), param("end_time", "ISO 8601 end."), *AWS_WHERE]))
|
||||
return {
|
||||
"server_id": "sa-aws-cloud", "name": "Solution Architecture AWS",
|
||||
"description": "AWS documentation and read-only estate tools for the Solution Architecture agent, through "
|
||||
"the customer's read-only role.",
|
||||
"version": "0.1.0", "port": 8117, "verify_tool": "aws_check_connection",
|
||||
"shared_code": [f"{SHARED}/tool_support.py", f"{SHARED}/aws_support.py", f"{SHARED}/knowledge_support.py", "_support/docs_log.py", "_support/docs_support.py", "_support/aws_tools.py"],
|
||||
"extra_requirements": ["boto3==1.43.122"],
|
||||
"connection_fields": [
|
||||
{"name": "access_key_id", "title": "Access key id", "description": "The broker identity that assumes the role.", "required": True, "secret": True},
|
||||
{"name": "secret_access_key", "title": "Secret access key", "description": "Its secret key.", "required": True, "secret": True},
|
||||
{"name": "role_arn", "title": "Role ARN", "description": "The read-only role.", "required": True, "secret": False},
|
||||
{"name": "external_id", "title": "External id", "description": "The role's external id.", "required": False, "secret": True},
|
||||
{"name": "regions", "title": "Regions", "description": "Comma-separated; the first is the default.", "required": True, "secret": False},
|
||||
{"name": "account_ids", "title": "Account ids", "description": "Optional member accounts.", "required": False, "secret": False},
|
||||
{"name": "member_role_name", "title": "Member role name", "description": "The role's name in member accounts.", "required": False, "secret": False},
|
||||
{"name": "docs_access_key_id", "title": "Documentation access key id", "description": "Identity for the AWS documentation server. Defaults to the broker identity.", "required": False, "secret": True},
|
||||
{"name": "docs_secret_access_key", "title": "Documentation secret key", "description": "Its secret key.", "required": False, "secret": True},
|
||||
],
|
||||
"tools": tools,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
for definition in (gcp(), azure(), aws()):
|
||||
path = HERE / f"{definition['server_id']}.server.yaml"
|
||||
header = "# Generated by build_definitions.py; don't edit by hand.\n# Credentials arrive per call from the Vault Service. Store them per project.\n\n"
|
||||
path.write_text(header + yaml.safe_dump(definition, sort_keys=False, width=120))
|
||||
print(path.name, len(definition["tools"]), "tools")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,586 @@
|
||||
# Generated by build_definitions.py; don't edit by hand.
|
||||
# Credentials arrive per call from the Vault Service. Store them per project.
|
||||
|
||||
server_id: sa-aws-cloud
|
||||
name: Solution Architecture AWS
|
||||
description: AWS documentation and read-only estate tools for the Solution Architecture agent, through the customer's read-only
|
||||
role.
|
||||
version: 0.1.0
|
||||
port: 8117
|
||||
verify_tool: aws_check_connection
|
||||
shared_code:
|
||||
- ../../../mcp-servers/_common/tool_support.py
|
||||
- ../../../mcp-servers/_common/aws_support.py
|
||||
- ../../../mcp-servers/_common/knowledge_support.py
|
||||
- _support/docs_log.py
|
||||
- _support/docs_support.py
|
||||
- _support/aws_tools.py
|
||||
extra_requirements:
|
||||
- boto3==1.43.122
|
||||
connection_fields:
|
||||
- name: access_key_id
|
||||
title: Access key id
|
||||
description: The broker identity that assumes the role.
|
||||
required: true
|
||||
secret: true
|
||||
- name: secret_access_key
|
||||
title: Secret access key
|
||||
description: Its secret key.
|
||||
required: true
|
||||
secret: true
|
||||
- name: role_arn
|
||||
title: Role ARN
|
||||
description: The read-only role.
|
||||
required: true
|
||||
secret: false
|
||||
- name: external_id
|
||||
title: External id
|
||||
description: The role's external id.
|
||||
required: false
|
||||
secret: true
|
||||
- name: regions
|
||||
title: Regions
|
||||
description: Comma-separated; the first is the default.
|
||||
required: true
|
||||
secret: false
|
||||
- name: account_ids
|
||||
title: Account ids
|
||||
description: Optional member accounts.
|
||||
required: false
|
||||
secret: false
|
||||
- name: member_role_name
|
||||
title: Member role name
|
||||
description: The role's name in member accounts.
|
||||
required: false
|
||||
secret: false
|
||||
- name: docs_access_key_id
|
||||
title: Documentation access key id
|
||||
description: Identity for the AWS documentation server. Defaults to the broker identity.
|
||||
required: false
|
||||
secret: true
|
||||
- name: docs_secret_access_key
|
||||
title: Documentation secret key
|
||||
description: Its secret key.
|
||||
required: false
|
||||
secret: true
|
||||
tools:
|
||||
- name: aws_check_connection
|
||||
display_name: Aws check connection
|
||||
description: 'Test the stored connection: assume the role and read its identity. Returns no customer data.'
|
||||
parameters: []
|
||||
ai_implementation: "async def aws_check_connection(arguments: Dict[str, Any]) -> Dict[str, Any]:\n try:\n await\
|
||||
\ _aws_call(arguments, \"sts\", \"get_caller_identity\")\n except Exception as error:\n return {\"ok\": False,\
|
||||
\ \"message\": _upstream_failed(\"aws\", error)[\"error\"][\"message\"]}\n return {\"ok\": True, \"message\": \"Assumed\
|
||||
\ the role.\"}\n"
|
||||
- name: aws_search_documents
|
||||
display_name: Aws search documents
|
||||
description: Search AWS documentation in free text. Queries are sent as written and logged.
|
||||
parameters:
|
||||
- name: query
|
||||
type: string
|
||||
description: What to look up. Keep client detail out.
|
||||
required: true
|
||||
ai_implementation: "async def aws_search_documents(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _docs_search(\"\
|
||||
aws\", \"aws_search_documents\", arguments, _aws_docs_connection())\n"
|
||||
- name: aws_get_documents
|
||||
display_name: Aws get documents
|
||||
description: Read one AWS documentation page by URL.
|
||||
parameters:
|
||||
- name: url
|
||||
type: string
|
||||
description: A docs.aws.amazon.com URL.
|
||||
required: true
|
||||
ai_implementation: "async def aws_get_documents(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _docs_read(\"\
|
||||
aws\", \"aws_get_documents\", arguments, _aws_docs_connection(), \"aws___read_documentation\", \"url\", _aws_docs_request)\n"
|
||||
- name: aws_search_projects
|
||||
display_name: Aws search projects
|
||||
description: List the organisation's accounts.
|
||||
parameters:
|
||||
- &id001
|
||||
name: account_id
|
||||
type: string
|
||||
description: A member account of the connection.
|
||||
required: false
|
||||
- &id002
|
||||
name: region
|
||||
type: string
|
||||
description: One of the connection's regions; the first by default.
|
||||
required: false
|
||||
- &id003
|
||||
name: page_size
|
||||
type: integer
|
||||
description: Items per page, up to 200. Default 50.
|
||||
required: false
|
||||
- &id004
|
||||
name: page_token
|
||||
type: string
|
||||
description: next_page_token from the previous reply.
|
||||
required: false
|
||||
ai_implementation: "async def aws_search_projects(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_search_projects\", arguments, ('organizations', 'list_accounts', 'Accounts', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_assets
|
||||
display_name: Aws list assets
|
||||
description: List tagged resources.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_assets(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_assets\", arguments, ('resourcegroupstaggingapi', 'get_resources', 'ResourceTagMappingList', 'PaginationToken',\
|
||||
\ 'PaginationToken', {}))\n"
|
||||
- name: aws_list_instances
|
||||
display_name: Aws list instances
|
||||
description: List EC2 instances.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_instances(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_instances\", arguments, ('ec2', 'describe_instances', 'Reservations', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_instance_group_managers
|
||||
display_name: Aws list instance group managers
|
||||
description: List Auto Scaling groups.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_instance_group_managers(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _aws_list(\"aws_list_instance_group_managers\", arguments, ('autoscaling', 'describe_auto_scaling_groups', 'AutoScalingGroups',\
|
||||
\ 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_instance_templates
|
||||
display_name: Aws list instance templates
|
||||
description: List launch templates.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_instance_templates(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _aws_list(\"aws_list_instance_templates\", arguments, ('ec2', 'describe_launch_templates', 'LaunchTemplates', 'NextToken',\
|
||||
\ 'NextToken', {}))\n"
|
||||
- name: aws_list_disks
|
||||
display_name: Aws list disks
|
||||
description: List EBS volumes.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_disks(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_disks\", arguments, ('ec2', 'describe_volumes', 'Volumes', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_reservations
|
||||
display_name: Aws list reservations
|
||||
description: List capacity reservations.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_reservations(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_reservations\", arguments, ('ec2', 'describe_capacity_reservations', 'CapacityReservations', 'NextToken', 'NextToken',\
|
||||
\ {}))\n"
|
||||
- name: aws_list_commitments
|
||||
display_name: Aws list commitments
|
||||
description: List Savings Plans.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_commitments(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_commitments\", arguments, ('savingsplans', 'describe_savings_plans', 'savingsPlans', 'nextToken', 'nextToken',\
|
||||
\ {}))\n"
|
||||
- name: aws_list_clusters
|
||||
display_name: Aws list clusters
|
||||
description: List EKS clusters.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_clusters(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_clusters\", arguments, ('eks', 'list_clusters', 'clusters', 'nextToken', 'nextToken', {}))\n"
|
||||
- name: aws_list_services
|
||||
display_name: Aws list services
|
||||
description: List App Runner services.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_services(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_services\", arguments, ('apprunner', 'list_services', 'ServiceSummaryList', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_functions
|
||||
display_name: Aws list functions
|
||||
description: List Lambda functions.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_functions(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_functions\", arguments, ('lambda', 'list_functions', 'Functions', 'Marker', 'NextMarker', {}))\n"
|
||||
- name: aws_list_sql_instances
|
||||
display_name: Aws list sql instances
|
||||
description: List RDS instances.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_sql_instances(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_sql_instances\", arguments, ('rds', 'describe_db_instances', 'DBInstances', 'Marker', 'Marker', {}))\n"
|
||||
- name: aws_list_buckets
|
||||
display_name: Aws list buckets
|
||||
description: List S3 buckets.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_buckets(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_buckets\", arguments, ('s3', 'list_buckets', 'Buckets', 'ContinuationToken', 'ContinuationToken', {}))\n"
|
||||
- name: aws_list_topics
|
||||
display_name: Aws list topics
|
||||
description: List SNS topics.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_topics(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_topics\", arguments, ('sns', 'list_topics', 'Topics', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_subscriptions
|
||||
display_name: Aws list subscriptions
|
||||
description: List SNS subscriptions.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_subscriptions(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_subscriptions\", arguments, ('sns', 'list_subscriptions', 'Subscriptions', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_roles
|
||||
display_name: Aws list roles
|
||||
description: List IAM roles.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_roles(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_roles\", arguments, ('iam', 'list_roles', 'Roles', 'Marker', 'Marker', {}))\n"
|
||||
- name: aws_list_deny_policies
|
||||
display_name: Aws list deny policies
|
||||
description: List service control policies.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_deny_policies(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_deny_policies\", arguments, ('organizations', 'list_policies', 'Policies', 'NextToken', 'NextToken', {'Filter':\
|
||||
\ 'SERVICE_CONTROL_POLICY'}))\n"
|
||||
- name: aws_list_alert_policies
|
||||
display_name: Aws list alert policies
|
||||
description: List CloudWatch metric alarms.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_alert_policies(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_alert_policies\", arguments, ('cloudwatch', 'describe_alarms', 'MetricAlarms', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_dashboards
|
||||
display_name: Aws list dashboards
|
||||
description: List CloudWatch dashboards.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_dashboards(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_dashboards\", arguments, ('cloudwatch', 'list_dashboards', 'DashboardEntries', 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_metric_descriptors
|
||||
display_name: Aws list metric descriptors
|
||||
description: List CloudWatch metrics.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_metric_descriptors(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _aws_list(\"aws_list_metric_descriptors\", arguments, ('cloudwatch', 'list_metrics', 'Metrics', 'NextToken', 'NextToken',\
|
||||
\ {}))\n"
|
||||
- name: aws_list_connectivity_tests
|
||||
display_name: Aws list connectivity tests
|
||||
description: List Reachability Analyzer paths.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_connectivity_tests(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _aws_list(\"aws_list_connectivity_tests\", arguments, ('ec2', 'describe_network_insights_paths', 'NetworkInsightsPaths',\
|
||||
\ 'NextToken', 'NextToken', {}))\n"
|
||||
- name: aws_list_node_pools
|
||||
display_name: Aws list node pools
|
||||
description: List one EKS cluster's node groups.
|
||||
parameters:
|
||||
- name: cluster
|
||||
type: string
|
||||
description: The cluster's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_node_pools(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_list(\"\
|
||||
aws_list_node_pools\", arguments, (\"eks\", \"list_nodegroups\", \"nodegroups\", \"nextToken\", \"nextToken\", {}), [(\"\
|
||||
clusterName\", \"cluster\")])\n"
|
||||
- name: aws_list_instance_attached_disks
|
||||
display_name: Aws list instance attached disks
|
||||
description: List the EBS volumes attached to one instance.
|
||||
parameters:
|
||||
- name: instance_id
|
||||
type: string
|
||||
description: The instance id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
- *id003
|
||||
- *id004
|
||||
ai_implementation: "async def aws_list_instance_attached_disks(arguments: Dict[str, Any]) -> Dict[str, Any]:\n instance\
|
||||
\ = arguments.get(\"instance_id\")\n if not instance:\n return _refuse(\"invalid_argument\", \"instance_id is\
|
||||
\ required\")\n return await _aws_list(\"aws_list_instance_attached_disks\", arguments, (\"ec2\", \"describe_volumes\"\
|
||||
, \"Volumes\", \"NextToken\", \"NextToken\", {\"Filters\": [{\"Name\": \"attachment.instance-id\", \"Values\": [str(instance)]}]}))\n"
|
||||
- name: aws_get_instance_basic_info
|
||||
display_name: Aws get instance basic info
|
||||
description: Read one EC2 instance.
|
||||
parameters:
|
||||
- name: instance_id
|
||||
type: string
|
||||
description: The instance id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_instance_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _aws_get(\"aws_get_instance_basic_info\", arguments, \"ec2\", \"describe_instances\", {\"InstanceIds\": [arguments.get(\"\
|
||||
instance_id\")]})\n"
|
||||
- name: aws_get_instance_group_manager_basic_info
|
||||
display_name: Aws get instance group manager basic info
|
||||
description: Read one Auto Scaling group.
|
||||
parameters:
|
||||
- name: name
|
||||
type: string
|
||||
description: The group's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_instance_group_manager_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n\
|
||||
\ return await _aws_get(\"aws_get_instance_group_manager_basic_info\", arguments, \"autoscaling\", \"describe_auto_scaling_groups\"\
|
||||
, {\"AutoScalingGroupNames\": [arguments.get(\"name\")]})\n"
|
||||
- name: aws_get_instance_template_properties
|
||||
display_name: Aws get instance template properties
|
||||
description: Read a launch template's versions.
|
||||
parameters:
|
||||
- name: template_id
|
||||
type: string
|
||||
description: The template id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_instance_template_properties(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _aws_get(\"aws_get_instance_template_properties\", arguments, \"ec2\", \"describe_launch_template_versions\",\
|
||||
\ {\"LaunchTemplateId\": arguments.get(\"template_id\")})\n"
|
||||
- name: aws_get_disk_basic_info
|
||||
display_name: Aws get disk basic info
|
||||
description: Read one EBS volume.
|
||||
parameters:
|
||||
- name: volume_id
|
||||
type: string
|
||||
description: The volume id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_disk_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_disk_basic_info\", arguments, \"ec2\", \"describe_volumes\", {\"VolumeIds\": [arguments.get(\"volume_id\")]})\n"
|
||||
- name: aws_get_cluster
|
||||
display_name: Aws get cluster
|
||||
description: Read one EKS cluster.
|
||||
parameters:
|
||||
- name: name
|
||||
type: string
|
||||
description: The cluster's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_cluster(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_cluster\", arguments, \"eks\", \"describe_cluster\", {\"name\": arguments.get(\"name\")})\n"
|
||||
- name: aws_get_node_pool
|
||||
display_name: Aws get node pool
|
||||
description: Read one EKS node group.
|
||||
parameters:
|
||||
- name: cluster
|
||||
type: string
|
||||
description: The cluster's name.
|
||||
required: true
|
||||
- name: name
|
||||
type: string
|
||||
description: The node group's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_node_pool(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_node_pool\", arguments, \"eks\", \"describe_nodegroup\", {\"clusterName\": arguments.get(\"cluster\"), \"nodegroupName\"\
|
||||
: arguments.get(\"name\")})\n"
|
||||
- name: aws_get_k8s_version
|
||||
display_name: Aws get k8s version
|
||||
description: Read EKS's supported Kubernetes versions.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_k8s_version(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_k8s_version\", arguments, \"eks\", \"describe_cluster_versions\", {})\n"
|
||||
- name: aws_get_service
|
||||
display_name: Aws get service
|
||||
description: Read one App Runner service.
|
||||
parameters:
|
||||
- name: arn
|
||||
type: string
|
||||
description: The service's ARN.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_service(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_service\", arguments, \"apprunner\", \"describe_service\", {\"ServiceArn\": arguments.get(\"arn\")})\n"
|
||||
- name: aws_get_function
|
||||
display_name: Aws get function
|
||||
description: Read one Lambda function's configuration.
|
||||
parameters:
|
||||
- name: name
|
||||
type: string
|
||||
description: The function's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_function(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_function\", arguments, \"lambda\", \"get_function_configuration\", {\"FunctionName\": arguments.get(\"name\")})\n"
|
||||
- name: aws_get_sql_instance
|
||||
display_name: Aws get sql instance
|
||||
description: Read one RDS instance.
|
||||
parameters:
|
||||
- name: name
|
||||
type: string
|
||||
description: The instance's identifier.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_sql_instance(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_sql_instance\", arguments, \"rds\", \"describe_db_instances\", {\"DBInstanceIdentifier\": arguments.get(\"name\"\
|
||||
)})\n"
|
||||
- name: aws_get_topic
|
||||
display_name: Aws get topic
|
||||
description: Read one SNS topic.
|
||||
parameters:
|
||||
- name: arn
|
||||
type: string
|
||||
description: The topic's ARN.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_topic(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_topic\", arguments, \"sns\", \"get_topic_attributes\", {\"TopicArn\": arguments.get(\"arn\")})\n"
|
||||
- name: aws_get_subscription
|
||||
display_name: Aws get subscription
|
||||
description: Read one SNS subscription.
|
||||
parameters:
|
||||
- name: arn
|
||||
type: string
|
||||
description: The subscription's ARN.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_subscription(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_subscription\", arguments, \"sns\", \"get_subscription_attributes\", {\"SubscriptionArn\": arguments.get(\"arn\"\
|
||||
)})\n"
|
||||
- name: aws_get_role
|
||||
display_name: Aws get role
|
||||
description: Read one IAM role.
|
||||
parameters:
|
||||
- name: name
|
||||
type: string
|
||||
description: The role's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_role(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"aws_get_role\"\
|
||||
, arguments, \"iam\", \"get_role\", {\"RoleName\": arguments.get(\"name\")})\n"
|
||||
- name: aws_get_deny_policy
|
||||
display_name: Aws get deny policy
|
||||
description: Read one service control policy.
|
||||
parameters:
|
||||
- name: policy_id
|
||||
type: string
|
||||
description: The policy id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_deny_policy(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_deny_policy\", arguments, \"organizations\", \"describe_policy\", {\"PolicyId\": arguments.get(\"policy_id\")})\n"
|
||||
- name: aws_get_alert_policy
|
||||
display_name: Aws get alert policy
|
||||
description: Read named CloudWatch alarms.
|
||||
parameters:
|
||||
- name: name
|
||||
type: string
|
||||
description: The alarm's name.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_alert_policy(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_get_alert_policy\", arguments, \"cloudwatch\", \"describe_alarms\", {\"AlarmNames\": [arguments.get(\"name\")]})\n"
|
||||
- name: aws_get_connectivity_test
|
||||
display_name: Aws get connectivity test
|
||||
description: Read one Reachability Analyzer path.
|
||||
parameters:
|
||||
- name: path_id
|
||||
type: string
|
||||
description: The path id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_get_connectivity_test(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _aws_get(\"aws_get_connectivity_test\", arguments, \"ec2\", \"describe_network_insights_paths\", {\"NetworkInsightsPathIds\"\
|
||||
: [arguments.get(\"path_id\")]})\n"
|
||||
- name: aws_analyze_access
|
||||
display_name: Aws analyze access
|
||||
description: Read the account's IAM users, groups, roles and policies.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_analyze_access(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_get(\"\
|
||||
aws_analyze_access\", arguments, \"iam\", \"get_account_authorization_details\", {})\n"
|
||||
- name: aws_list_timeseries
|
||||
display_name: Aws list timeseries
|
||||
description: Read CloudWatch metric values.
|
||||
parameters:
|
||||
- name: metric_queries
|
||||
type: array
|
||||
description: CloudWatch MetricDataQueries.
|
||||
required: true
|
||||
- name: start_time
|
||||
type: string
|
||||
description: ISO 8601 start.
|
||||
required: true
|
||||
- name: end_time
|
||||
type: string
|
||||
description: ISO 8601 end.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def aws_list_timeseries(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _aws_metric_data(\"\
|
||||
aws_list_timeseries\", arguments)\n"
|
||||
@@ -0,0 +1,62 @@
|
||||
# ============================================
|
||||
# Solution Architecture AWS - Environment Variables
|
||||
# ============================================
|
||||
# Generated by Agent Builder Platform
|
||||
#
|
||||
# SETUP INSTRUCTIONS:
|
||||
# 1. Copy this file to .env: cp .env.example .env
|
||||
# 2. Generate a secure API key: openssl rand -hex 32
|
||||
# 3. Update MCP_REGISTRATION_API_KEY with the generated key
|
||||
# 4. Build the image from the Dockerfile and run it where the MCP Gateway
|
||||
# can reach it (see README.md)
|
||||
#
|
||||
# MCP GATEWAY INTEGRATION:
|
||||
# When registering with the MCP Gateway, use the URL the Gateway reaches this
|
||||
# server at; for a container on the Gateway's network, its container name:
|
||||
# http://solution-architecture-aws:8117
|
||||
# ============================================
|
||||
|
||||
# Server Identity
|
||||
MCP_SERVER_NAME=Solution Architecture AWS
|
||||
MCP_SERVER_ID=sa-aws-cloud
|
||||
MCP_SERVER_VERSION=0.1.0
|
||||
|
||||
# Server Configuration
|
||||
MCP_SERVER_PORT=8117
|
||||
|
||||
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format
|
||||
# (json = one object per line, for log stores; console = for reading by eye)
|
||||
LOG_LEVEL=INFO
|
||||
LOG_FORMAT=json
|
||||
|
||||
# ============================================
|
||||
# AUTHENTICATION (REQUIRED for production!)
|
||||
# ============================================
|
||||
# This key authenticates MCP Gateway requests to this server.
|
||||
# The Gateway stores this key and includes it in all tool/call requests.
|
||||
#
|
||||
# Generate a secure key:
|
||||
# openssl rand -hex 32
|
||||
#
|
||||
# IMPORTANT: Keep this key secret! It's stored in:
|
||||
# - This .env file (gitignored)
|
||||
# - MCP Gateway database (encrypted)
|
||||
MCP_REGISTRATION_API_KEY=<generate one: openssl rand -hex 32>
|
||||
|
||||
# Set to "false" ONLY for local development/testing
|
||||
# WARNING: Disabling auth in production is a security risk!
|
||||
REQUIRE_AUTH=true
|
||||
|
||||
# ============================================
|
||||
# CREDENTIALS FOR THE UPSTREAM (sent with each request, not set here)
|
||||
# ============================================
|
||||
# The MCP Gateway sends the tenant's credential with each call, from the Vault Service.
|
||||
# true: a call without one is refused. Set to false only for local runs, where the
|
||||
# server may use its own environment.
|
||||
REQUIRE_VAULT_CONNECTION=true
|
||||
|
||||
# ============================================
|
||||
# Add your own settings below
|
||||
# ============================================
|
||||
# Credentials for the upstream are not set here: the gateway sends them with each request.
|
||||
# EXAMPLE_SETTING=value
|
||||
15
outcome-pattern/solution_architecture/mcp-servers/sa-aws-cloud/.gitignore
vendored
Normal file
15
outcome-pattern/solution_architecture/mcp-servers/sa-aws-cloud/.gitignore
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
|
||||
# Editors
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,47 @@
|
||||
# MCP Server Dockerfile
|
||||
# Generated by Agent Builder Platform (template 1.1.0)
|
||||
#
|
||||
# Built on the platform's MCP server base image: Chainguard Python with the
|
||||
# packages in requirements.txt already installed, a non-root user (1000) and
|
||||
# no pip. This image adds only the server's own files.
|
||||
#
|
||||
# docker build -t <server>:<version> .
|
||||
# docker build --build-arg BASE_IMAGE=<local base image> -t ... .
|
||||
ARG BASE_IMAGE=kyndryl.jfrog.io/kc-ai-agent-factory-docker-local/mcp-server-base:1.1.0
|
||||
|
||||
# Stage 1: the server's extra Python packages, if requirements.txt lists any.
|
||||
# The base image's build image (<base image>-build: the base image plus uv) installs
|
||||
# them with its vendor-install script: only the packages added go on to
|
||||
# /vendor, and one that would change a package the base image already has stops
|
||||
# the build. uv never reaches the server's image.
|
||||
FROM ${BASE_IMAGE}-build AS vendor
|
||||
COPY requirements.txt constraints.txt /tmp/
|
||||
RUN vendor-install /tmp/requirements.txt /vendor /tmp/constraints.txt
|
||||
|
||||
# Stage 2: the server: the base image, its extra packages and its files.
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
LABEL maintainer="Agent Builder Platform"
|
||||
LABEL description="AWS documentation and read-only estate tools for the Solution Architecture agent, through the customer's read-only role."
|
||||
LABEL version="0.1.0"
|
||||
LABEL server.id="sa-aws-cloud"
|
||||
LABEL template.version="1.1.0"
|
||||
|
||||
COPY --from=vendor /vendor /app/vendor/
|
||||
COPY server.py mcp_connection.py /app/
|
||||
|
||||
# Environment
|
||||
# The ConfigMap's SERVER_PORT overrides this, so the container, Service and probes agree
|
||||
ENV SERVER_PORT=8117
|
||||
ENV LOG_LEVEL=INFO
|
||||
ENV LOG_FORMAT=json
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8117
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD python -c "import os, urllib.request; urllib.request.urlopen('http://localhost:%s/health' % (os.getenv('MCP_SERVER_PORT') or os.getenv('SERVER_PORT') or '8117'))" || exit 1
|
||||
|
||||
# Run the server
|
||||
CMD ["python", "server.py"]
|
||||
@@ -0,0 +1,236 @@
|
||||
# Solution Architecture AWS
|
||||
|
||||
AWS documentation and read-only estate tools for the Solution Architecture agent, through the customer's read-only role.
|
||||
|
||||
**Version:** 0.1.0
|
||||
**Server ID:** sa-aws-cloud
|
||||
**Port:** 8117
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### As a container (recommended)
|
||||
|
||||
The Dockerfile builds the server's image. Run it on the same network as the
|
||||
MCP Gateway, so the Gateway can reach it by its container name:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # then set MCP_REGISTRATION_API_KEY
|
||||
podman build -t <image-name> .
|
||||
podman run -d --name <container-name> --env-file .env --network <gateway-network> <image-name>
|
||||
```
|
||||
|
||||
Register it with the MCP Gateway at `http://<container-name>:8117`.
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with your configuration
|
||||
|
||||
# Run the server
|
||||
python server.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📡 API Endpoints
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/health` | GET | Health check (no auth) |
|
||||
| `/.well-known/mcp-auth` | GET | Authentication requirements |
|
||||
| `/messages` | POST | MCP JSON-RPC 2.0 endpoint |
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Available Tools
|
||||
|
||||
- **aws_check_connection**: Test the stored connection: assume the role and read its identity. Returns no customer data.
|
||||
- **aws_search_documents**: Search AWS documentation in free text. Queries are sent as written and logged.
|
||||
- **aws_get_documents**: Read one AWS documentation page by URL.
|
||||
- **aws_search_projects**: List the organisation's accounts.
|
||||
- **aws_list_assets**: List tagged resources.
|
||||
- **aws_list_instances**: List EC2 instances.
|
||||
- **aws_list_instance_group_managers**: List Auto Scaling groups.
|
||||
- **aws_list_instance_templates**: List launch templates.
|
||||
- **aws_list_disks**: List EBS volumes.
|
||||
- **aws_list_reservations**: List capacity reservations.
|
||||
- **aws_list_commitments**: List Savings Plans.
|
||||
- **aws_list_clusters**: List EKS clusters.
|
||||
- **aws_list_services**: List App Runner services.
|
||||
- **aws_list_functions**: List Lambda functions.
|
||||
- **aws_list_sql_instances**: List RDS instances.
|
||||
- **aws_list_buckets**: List S3 buckets.
|
||||
- **aws_list_topics**: List SNS topics.
|
||||
- **aws_list_subscriptions**: List SNS subscriptions.
|
||||
- **aws_list_roles**: List IAM roles.
|
||||
- **aws_list_deny_policies**: List service control policies.
|
||||
- **aws_list_alert_policies**: List CloudWatch metric alarms.
|
||||
- **aws_list_dashboards**: List CloudWatch dashboards.
|
||||
- **aws_list_metric_descriptors**: List CloudWatch metrics.
|
||||
- **aws_list_connectivity_tests**: List Reachability Analyzer paths.
|
||||
- **aws_list_node_pools**: List one EKS cluster's node groups.
|
||||
- **aws_list_instance_attached_disks**: List the EBS volumes attached to one instance.
|
||||
- **aws_get_instance_basic_info**: Read one EC2 instance.
|
||||
- **aws_get_instance_group_manager_basic_info**: Read one Auto Scaling group.
|
||||
- **aws_get_instance_template_properties**: Read a launch template's versions.
|
||||
- **aws_get_disk_basic_info**: Read one EBS volume.
|
||||
- **aws_get_cluster**: Read one EKS cluster.
|
||||
- **aws_get_node_pool**: Read one EKS node group.
|
||||
- **aws_get_k8s_version**: Read EKS's supported Kubernetes versions.
|
||||
- **aws_get_service**: Read one App Runner service.
|
||||
- **aws_get_function**: Read one Lambda function's configuration.
|
||||
- **aws_get_sql_instance**: Read one RDS instance.
|
||||
- **aws_get_topic**: Read one SNS topic.
|
||||
- **aws_get_subscription**: Read one SNS subscription.
|
||||
- **aws_get_role**: Read one IAM role.
|
||||
- **aws_get_deny_policy**: Read one service control policy.
|
||||
- **aws_get_alert_policy**: Read named CloudWatch alarms.
|
||||
- **aws_get_connectivity_test**: Read one Reachability Analyzer path.
|
||||
- **aws_analyze_access**: Read the account's IAM users, groups, roles and policies.
|
||||
- **aws_list_timeseries**: Read CloudWatch metric values.
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Authentication
|
||||
|
||||
This server uses Bearer token authentication for MCP protocol messages.
|
||||
|
||||
```bash
|
||||
# Test with authentication
|
||||
curl -X POST http://localhost:8117/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $MCP_REGISTRATION_API_KEY" \
|
||||
-d '{"jsonrpc": "2.0", "id": "1", "method": "tools/list", "params": {}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 MCP Gateway Registration
|
||||
|
||||
To register this server with the MCP Gateway:
|
||||
|
||||
1. Start the server (see Quick Start) where the MCP Gateway can reach it
|
||||
2. In the MCP Gateway Hub, go to **MCP Servers** → **Add MCP Server**
|
||||
3. Enter the server details:
|
||||
- **URL**: Use the **container name** as the hostname (e.g., `http://weather-mcp-server:8117`)
|
||||
- **API Key**: The `MCP_REGISTRATION_API_KEY` from your `.env` file
|
||||
4. Click the connection test icon to verify connectivity
|
||||
5. Enable the server
|
||||
|
||||
> **Note:** The URL is the one the MCP Gateway uses, so for a container on the Gateway's network use its container name, not `localhost`.
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Credentials per tenant
|
||||
|
||||
This server does not hold credentials for its upstream. The MCP Gateway reads the tenant's credential from the Vault Service and sends it with each call, in `params._meta["com.kyndryl.mcp/connection"]`. The server advertises what it needs when the gateway calls `initialize`:
|
||||
|
||||
| Field | Required | Secret |
|
||||
|---|---|---|
|
||||
| `access_key_id` | yes | yes |
|
||||
| `secret_access_key` | yes | yes |
|
||||
| `role_arn` | yes | no |
|
||||
| `external_id` | no | yes |
|
||||
| `regions` | yes | no |
|
||||
| `account_ids` | no | no |
|
||||
| `member_role_name` | no | no |
|
||||
| `docs_access_key_id` | no | yes |
|
||||
| `docs_secret_access_key` | no | yes |
|
||||
|
||||
- In your tool code, read the connection with `get_connection()`, and reuse an upstream client with `get_upstream_client("<client kind>", build)`, which keeps one per kind and distinct connection.
|
||||
- `REQUIRE_VAULT_CONNECTION` (default `true`): a call that arrives without a connection is refused, instead of using this server's own environment. Set it to `false` only for local runs.
|
||||
- `verify_connection` is the tool the gateway calls to test a stored credential. It reports failure until you implement the check against the upstream.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Check it before you push
|
||||
|
||||
`tests/test_conformance.py` checks the running server against what the MCP Gateway expects: it
|
||||
refuses callers without its key, answers JSON-RPC correctly, and, if it declares credential fields,
|
||||
takes the account from each request, refuses a call that carries none, names a missing field, and
|
||||
never repeats a credential in a reply. It needs only `pytest` and `httpx` and imports nothing from
|
||||
the server.
|
||||
|
||||
```bash
|
||||
pip install pytest httpx
|
||||
# with the server running (see Quick Start) and its key from .env
|
||||
MCP_SERVER_URL=http://localhost:8117 MCP_REGISTRATION_API_KEY=<the key> pytest tests/ -v
|
||||
```
|
||||
|
||||
A check that fails says what to fix. Run it again after you implement your tools, since a tool that
|
||||
reads an environment variable for its credential, or repeats one in an error, fails it. Checks that
|
||||
do not apply (a server with no credential fields) are skipped, not passed. To run it with
|
||||
`REQUIRE_VAULT_CONNECTION=false` on your own machine, set `CONFORMANCE_EXPECT_FAIL_CLOSED=false`.
|
||||
|
||||
---
|
||||
|
||||
## 🚢 Deploying through the tools repository
|
||||
|
||||
To have CI build and deploy this server, put this folder in the root of the
|
||||
`modernization-tools-mcp-servers` repository as `solution-architecture-aws/`, then add it to
|
||||
`mcp_servers_to_deploy.yaml` in that repository with the instances it should
|
||||
run on:
|
||||
|
||||
```yaml
|
||||
- name: "solution-architecture-aws"
|
||||
instances:
|
||||
- az_dev
|
||||
```
|
||||
|
||||
The pipeline reads `kubernetes/configmap.yaml` for the server's name and port
|
||||
(`MCP_SERVER_NAME`, `SERVER_PORT`), generates the registration key and sets it
|
||||
in the pod, and registers the server with the MCP Gateway.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Logging
|
||||
|
||||
Every line the server writes to stdout is one JSON object (`timestamp`, `level`,
|
||||
`event`, `logger`, `server_id`, and for a request `request_id`, `method`, `tool`),
|
||||
including uvicorn's and your tools' own. Each request ends with one
|
||||
`mcp_request_completed` line carrying `outcome`, `duration_ms` and `error_code`.
|
||||
|
||||
- `LOG_LEVEL` sets the level (default `INFO`).
|
||||
- `LOG_FORMAT=console` prints readable lines instead, for local work.
|
||||
- In your tool code use the module's `logger`: `logger.info("fetched_issue", key=issue_key)`.
|
||||
- Do not log credentials, tokens or Authorization headers.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Development
|
||||
|
||||
### Implementing Tools
|
||||
|
||||
Open `server.py` and find the tool implementation functions. Each tool has a placeholder that needs to be implemented:
|
||||
|
||||
```python
|
||||
async def your_tool_name(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# TODO: Implement this tool
|
||||
raise NotImplementedError("Tool 'your_tool_name' needs implementation")
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Health check
|
||||
curl http://localhost:8117/health
|
||||
|
||||
# List tools
|
||||
curl -X POST http://localhost:8117/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $MCP_REGISTRATION_API_KEY" \
|
||||
-d '{"jsonrpc": "2.0", "id": "1", "method": "tools/list", "params": {}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
Generated by Agent Builder Platform - Kyndryl (template 1.1.0)
|
||||
@@ -0,0 +1,29 @@
|
||||
# Every package installed in a generated MCP server, pinned to one exact version:
|
||||
# the ones requirements.txt names and everything they bring in. They are
|
||||
# installed in the MCP server base image (Dockerfile.base), so every server
|
||||
# built from this template gets the same versions as the platform's own
|
||||
# services.
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
certifi==2026.10.19
|
||||
click==8.5.0
|
||||
fastapi==0.143.2
|
||||
h11==0.16.0
|
||||
httpcore==1.0.9
|
||||
httptools==0.9.0
|
||||
httpx==0.28.1
|
||||
idna==3.20
|
||||
opentelemetry-api==1.45.1
|
||||
pydantic==2.14.1
|
||||
pydantic-core==2.50.1
|
||||
python-dotenv==1.2.4
|
||||
pyyaml==6.0.3
|
||||
starlette==1.8.0
|
||||
structlog==26.1.0
|
||||
typing-extensions==4.16.0
|
||||
typing-inspection==0.4.4
|
||||
uvicorn==0.54.0
|
||||
uvloop==0.23.0
|
||||
watchfiles==1.3.0
|
||||
websockets==16.1.1
|
||||
@@ -0,0 +1,25 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>-config # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
data:
|
||||
|
||||
# Read by the CI/CD pipeline: the server's name, and the port it listens on
|
||||
# (used for the container, the Service and the probes)
|
||||
MCP_SERVER_NAME: "solution-architecture-aws"
|
||||
SERVER_PORT: "8117"
|
||||
|
||||
# One JSON object per line; LOG_FORMAT=console prints readable lines
|
||||
LOG_LEVEL: "INFO"
|
||||
LOG_FORMAT: "json"
|
||||
|
||||
# Leave on. The Gateway authenticates to this server with a bearer token, and
|
||||
# turning this off makes every tool callable by anything that can reach the
|
||||
# pod inside the cluster.
|
||||
REQUIRE_AUTH: "true"
|
||||
|
||||
# Refuse a call that arrives without the tenant's credential from the Vault Service
|
||||
REQUIRE_VAULT_CONNECTION: "true"
|
||||
|
||||
# Add your own settings here
|
||||
# EXAMPLE_SETTING: "value"
|
||||
@@ -0,0 +1,71 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- name: jfrog-secret
|
||||
containers:
|
||||
- name: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
image: <placeholder_for_image> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
name: http
|
||||
# Load all environment variables from ConfigMap
|
||||
envFrom:
|
||||
- secretRef:
|
||||
name: <placeholder_for_mcp_server_name>-secrets # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
optional: true # Won't fail if secret doesn't exist
|
||||
- secretRef:
|
||||
name: <placeholder_for_mcp_server_name>-dotenv-secrets # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
optional: true # Won't fail if secret doesn't exist
|
||||
- configMapRef:
|
||||
name: <placeholder_for_mcp_server_name>-config # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
# The registration key and server id are generated by the CI/CD pipeline;
|
||||
# the server needs the key to accept the Gateway's calls
|
||||
env:
|
||||
- name: MCP_REGISTRATION_API_KEY
|
||||
value: "<placeholder_for_registration_api_key>" # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
- name: MCP_SERVER_ID
|
||||
value: "<placeholder_for_server_id>" # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
resources:
|
||||
requests:
|
||||
memory: "128Mi"
|
||||
cpu: "10m"
|
||||
limits:
|
||||
memory: "1024Mi"
|
||||
cpu: "1000m"
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
initialDelaySeconds: 30 # Wait X seconds before first check
|
||||
periodSeconds: 15 # Check every X seconds
|
||||
timeoutSeconds: 10 # Each check can take up to X seconds to respond
|
||||
failureThreshold: 5 # Allow X consecutive failures before marking unhealthy
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
initialDelaySeconds: 30 # Wait X seconds before first check
|
||||
periodSeconds: 15 # Check every X seconds
|
||||
timeoutSeconds: 10 # Each check can take up to X seconds to respond
|
||||
failureThreshold: 5 # Allow X consecutive failures before marking unhealthy
|
||||
|
||||
# volumes:
|
||||
# - name: execution-storage
|
||||
# persistentVolumeClaim:
|
||||
# claimName: execution-storage-pvc # Same PVC name as core-components
|
||||
@@ -0,0 +1,20 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- configmap.yaml
|
||||
- secretnames.yaml
|
||||
|
||||
# Optionally add common labels
|
||||
|
||||
# Namespace for all resources
|
||||
namespace: mcp-servers
|
||||
labels:
|
||||
- includeSelectors: true
|
||||
pairs:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
environment: production
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
@@ -0,0 +1,7 @@
|
||||
# Do not modify this file, otherwise CI/CD pipeline will fail
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: mcp-servers
|
||||
labels:
|
||||
name: mcp-servers
|
||||
@@ -0,0 +1,18 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>-secrets
|
||||
type: Opaque
|
||||
data:
|
||||
# Base64 encoded values (NOT RECOMMENDED for sensitive data)
|
||||
# To encode: echo -n 'your-secret-value' | base64
|
||||
# Example: api-key: eW91ci1hcGkta2V5LXZhbHVl
|
||||
|
||||
stringData:
|
||||
# Plain text values saved on GitHub Secrets (RECOMMENDED)
|
||||
# Example:
|
||||
#
|
||||
# DB_PASSWORD: ${DB_PASSWORD_GITHUB_SECRET}
|
||||
# ANOTHER_SECRET: ${ANOTHER_GITHUB_SECRET}
|
||||
#
|
||||
# ${DB_PASSWORD_GITHUB_SECRET} and ${ANOTHER_GITHUB_SECRET} must exist as GitHub Secrets
|
||||
@@ -0,0 +1,33 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name>
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
targetPort: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
app: <placeholder_for_mcp_server_name>
|
||||
---
|
||||
# Optional: LoadBalancer service for external access
|
||||
# apiVersion: v1
|
||||
# kind: Service
|
||||
# metadata:
|
||||
# name: <placeholder_for_mcp_server_name>-external
|
||||
# labels:
|
||||
# app: <placeholder_for_mcp_server_name>
|
||||
# spec:
|
||||
# type: LoadBalancer
|
||||
# ports:
|
||||
# - port: 80
|
||||
# targetPort: 8080
|
||||
# protocol: TCP
|
||||
# name: http
|
||||
# selector:
|
||||
# app: <placeholder_for_mcp_server_name>
|
||||
@@ -0,0 +1,256 @@
|
||||
"""The connection a request carries: which upstream account this call is for.
|
||||
|
||||
An MCP server that talks to a third-party system needs that system's address and credentials. Taking
|
||||
them from environment variables makes one process serve one account for ever. Here the MCP Gateway
|
||||
sends them with each call, from the Vault Service, in MCP's own `_meta` field, under our vendor prefix:
|
||||
|
||||
initialize result _meta["com.kyndryl.mcp/connection-schema"] what this server needs (JSON Schema)
|
||||
_meta["com.kyndryl.mcp/verify-tool"] the tool that tests a connection
|
||||
tools/call, resources/read, prompts/get
|
||||
params._meta["com.kyndryl.mcp/connection"] the values, matching that schema
|
||||
|
||||
`_meta` is where the specification tells implementations to put their own data, so a client that does
|
||||
not know these keys ignores them. The values never travel in `arguments`, which is what the model
|
||||
writes and reads, so a credential cannot enter the model's context.
|
||||
|
||||
The connection is bound for the life of one request and read with `active()`. It is None when the caller
|
||||
sent nothing; whether the server may then use its own environment is decided in server.py
|
||||
(REQUIRE_VAULT_CONNECTION, which is on by default).
|
||||
|
||||
WHAT IS STANDARD AND WHAT IS OURS
|
||||
---------------------------------
|
||||
The mechanism is standard. `_meta` is the specification's sanctioned place for implementation-specific
|
||||
data, with formal key-naming rules (2026-07-28, "General fields / _meta"):
|
||||
|
||||
Prefix ... SHOULD use reverse DNS notation. Any prefix where the second label is
|
||||
`modelcontextprotocol` or `mcp` is reserved for MCP use ... third-party extensions use their own
|
||||
vendor prefix.
|
||||
|
||||
`com.kyndryl.mcp/` satisfies that: the second label is `kyndryl`, so it is a legitimate vendor prefix and
|
||||
not reserved. A client that does not recognise our keys ignores them, which is exactly what `_meta` is for.
|
||||
The value carried is a *separate* upstream credential, never the caller's own token (the specification
|
||||
says a server MUST NOT pass through the token it received from its client).
|
||||
|
||||
Only the three key names and the shape of their payloads are ours. When SEP-2127 (MCP Server Card) lands,
|
||||
the schema is what moves onto the card, and the key names are the only thing that changes.
|
||||
|
||||
The third key, VERIFY_TOOL_KEY, adds very little. Checking a credential is a plain `tools/call` against an
|
||||
ordinary tool that appears in `tools/list` like any other: no new method, no new transport. The only
|
||||
question that needed answering is WHICH tool, and the alternative was for the gateway to guess by name. A
|
||||
server that advertises nothing here is simply not verifiable.
|
||||
|
||||
STATELESSNESS
|
||||
-------------
|
||||
The 2026-07-28 specification made MCP explicitly stateless: "Servers MUST NOT rely on prior requests over
|
||||
the same connection to establish context ... Every request supplies this metadata in its _meta field."
|
||||
A module-level connection built once at import is exactly the state the specification tells servers not to
|
||||
keep. Binding the connection per request is therefore not only what multi-tenancy needs, it is what the
|
||||
protocol asks for.
|
||||
|
||||
HOW IT IS USED (server.py does all of this; a tool only calls get_connection())
|
||||
------------------------------------------------------------------------------
|
||||
import mcp_connection
|
||||
|
||||
# advertise, in the initialize result
|
||||
result["_meta"] = mcp_connection.schema_meta(CONNECTION_SCHEMA, verify_tool="verify_connection")
|
||||
|
||||
# bind, for the life of one request
|
||||
token = mcp_connection.bind(mcp_connection.from_params(request.params))
|
||||
try:
|
||||
... # mcp_connection.active() anywhere below
|
||||
finally:
|
||||
mcp_connection.unbind(token)
|
||||
|
||||
LOGS AND ERROR MESSAGES
|
||||
-----------------------
|
||||
`scrub()` is applied to every log line, and to the `error` text of a failed tool call, so the connection's
|
||||
values and credential-looking URL parameters (`?key=...`) never leave the process. `redact()` does the
|
||||
connection values alone. Neither is applied to a successful result: a presigned URL a tool returns on
|
||||
purpose must survive.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
VENDOR = "com.kyndryl.mcp"
|
||||
SCHEMA_KEY = f"{VENDOR}/connection-schema"
|
||||
CONNECTION_KEY = f"{VENDOR}/connection"
|
||||
VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool"
|
||||
|
||||
_active: contextvars.ContextVar[Optional[Dict[str, Any]]] = contextvars.ContextVar(
|
||||
"mcp_connection", default=None
|
||||
)
|
||||
|
||||
# Per process, so a fingerprint in a log cannot be checked against a guessed credential offline
|
||||
_FINGERPRINT_KEY = secrets.token_bytes(32)
|
||||
|
||||
|
||||
def schema_meta(schema: Dict[str, Any], verify_tool: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""The `_meta` object that advertises `schema` on an initialize result."""
|
||||
meta: Dict[str, Any] = {SCHEMA_KEY: schema}
|
||||
if verify_tool:
|
||||
meta[VERIFY_TOOL_KEY] = verify_tool
|
||||
return meta
|
||||
|
||||
|
||||
def verify_tool_from_initialize(result: Optional[Dict[str, Any]]) -> Optional[str]:
|
||||
"""The verify tool an initialize result advertises, or None.
|
||||
|
||||
The reader half of schema_meta, here rather than in the gateway so the two ends of the key cannot
|
||||
drift apart.
|
||||
"""
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
meta = result.get("_meta")
|
||||
if not isinstance(meta, dict):
|
||||
return None
|
||||
name = meta.get(VERIFY_TOOL_KEY)
|
||||
return name if isinstance(name, str) and name.strip() else None
|
||||
|
||||
|
||||
def from_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""The connection in a request's `params._meta`, or None.
|
||||
|
||||
Anything that is not an object counts as absent: a malformed connection must not be more
|
||||
powerful than none at all.
|
||||
"""
|
||||
if not isinstance(params, dict):
|
||||
return None
|
||||
meta = params.get("_meta")
|
||||
if not isinstance(meta, dict):
|
||||
return None
|
||||
profile = meta.get(CONNECTION_KEY)
|
||||
return profile if isinstance(profile, dict) and profile else None
|
||||
|
||||
|
||||
def bind(profile: Optional[Dict[str, Any]]) -> contextvars.Token:
|
||||
"""Make `profile` the connection for this request."""
|
||||
return _active.set(profile)
|
||||
|
||||
|
||||
def unbind(token: contextvars.Token) -> None:
|
||||
try:
|
||||
_active.reset(token)
|
||||
except ValueError:
|
||||
_active.set(None)
|
||||
|
||||
|
||||
def active() -> Optional[Dict[str, Any]]:
|
||||
"""The connection for this request, or None."""
|
||||
return _active.get()
|
||||
|
||||
|
||||
def fingerprint(profile: Optional[Dict[str, Any]]) -> str:
|
||||
"""A short id for a connection, safe to log and to cache on; the credential never is the key."""
|
||||
if not profile:
|
||||
return "env"
|
||||
canonical = json.dumps(profile, sort_keys=True, separators=(",", ":"), default=str)
|
||||
return hmac.new(_FINGERPRINT_KEY, canonical.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
|
||||
|
||||
|
||||
def redact(text: Any) -> str:
|
||||
"""`text` with every value of this request's connection replaced, for logs and error replies.
|
||||
|
||||
A tool can put a credential in an exception message without meaning to. Values shorter than four
|
||||
characters are left alone: replacing them would garble ordinary text.
|
||||
"""
|
||||
result = str(text)
|
||||
values = [v for v in (active() or {}).values() if isinstance(v, str) and len(v) >= 4]
|
||||
for value in sorted(values, key=len, reverse=True):
|
||||
result = result.replace(value, "[redacted]")
|
||||
return result
|
||||
|
||||
|
||||
# Query parameters that carry a credential in the URL of an upstream request
|
||||
_URL_CREDENTIAL = re.compile(
|
||||
r"([?&;](?:api[_-]?key|apikey|key|token|access[_-]?token|auth|secret|password|passwd|"
|
||||
r"client[_-]?secret|appid|app[_-]?id|sig|signature)=)[^&\s\"'#<>]+",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def scrub(value: Any, _depth: int = 0) -> Any:
|
||||
"""`value` with credentials taken out, for anything that is logged or sent back to a caller.
|
||||
|
||||
Strings lose the request's connection values and the value of any credential query parameter in a
|
||||
URL (`?key=...`); dicts, lists and tuples are scrubbed inside. Anything else is returned as it is.
|
||||
Not for tool results in general: a presigned URL a tool returns on purpose would be damaged.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
return _URL_CREDENTIAL.sub(r"\1[redacted]", redact(value))
|
||||
if _depth > 5:
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {k: scrub(v, _depth + 1) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return type(value)(scrub(v, _depth + 1) for v in value)
|
||||
return value
|
||||
|
||||
|
||||
def missing_fields(profile: Optional[Dict[str, Any]], schema: Dict[str, Any]) -> List[str]:
|
||||
"""The required fields of `schema` that `profile` does not supply."""
|
||||
if not profile:
|
||||
return []
|
||||
required = schema.get("required") or []
|
||||
return [name for name in required if not str(profile.get(name) or "").strip()]
|
||||
|
||||
|
||||
def install_invalid_request_handler(app: Any, on_invalid: Optional[Callable[[str], None]] = None) -> None:
|
||||
"""Answer a request that is not valid JSON-RPC with a JSON-RPC error that does not repeat the request.
|
||||
|
||||
FastAPI's own answer (HTTP 422) repeats the request body under "input". The body is where the gateway puts
|
||||
the tenant's connection, so a request that is merely malformed (no "id", say) would get the credential back
|
||||
in the reply, and in the log of anything that records replies. The status stays 422; the body is a JSON-RPC
|
||||
error (-32600) that names only the fields at fault. `on_invalid`, if given, is called with that text, already
|
||||
reduced to harmless characters, so the caller can log it in its own style.
|
||||
|
||||
Call it once, right after `app = FastAPI(...)`. FastAPI is imported here, not at module level, so the rest of
|
||||
this module stays importable without it.
|
||||
"""
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def invalid_request(request, exc):
|
||||
names = {
|
||||
"body" if error.get("type") == "json_invalid" else ".".join(str(p) for p in error.get("loc", ())[1:]) or "body"
|
||||
for error in exc.errors()
|
||||
}
|
||||
fields = re.sub(r"[^\w.\-, ]", "?", ", ".join(sorted(names)))[:200]
|
||||
if on_invalid is not None:
|
||||
on_invalid(fields)
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"result": None,
|
||||
"error": {"code": -32600, "message": "Invalid request: check " + fields},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"install_invalid_request_handler",
|
||||
"VENDOR",
|
||||
"SCHEMA_KEY",
|
||||
"CONNECTION_KEY",
|
||||
"VERIFY_TOOL_KEY",
|
||||
"schema_meta",
|
||||
"verify_tool_from_initialize",
|
||||
"from_params",
|
||||
"bind",
|
||||
"unbind",
|
||||
"active",
|
||||
"fingerprint",
|
||||
"redact",
|
||||
"scrub",
|
||||
"missing_fields",
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
# MCP Server Dependencies
|
||||
# Generated by Agent Builder Platform
|
||||
|
||||
# Each dependency is pinned to one exact version, and constraints.txt pins everything they bring
|
||||
# in, so two builds of the same server get the same packages -- the same versions as the
|
||||
# platform's own services. The packages below are already installed in the MCP server base
|
||||
# image the Dockerfile builds on; a package added to this file is installed on top of them at
|
||||
# build time. Changing the version of one the base has stops the build: the base image moves
|
||||
# those, with the template.
|
||||
|
||||
# Core Framework
|
||||
# FastAPI - Modern web framework for MCP server
|
||||
fastapi==0.143.2
|
||||
|
||||
# ASGI Server
|
||||
# Uvicorn - Lightning-fast ASGI server
|
||||
uvicorn[standard]==0.54.0
|
||||
|
||||
# Data Validation
|
||||
# Pydantic - Data validation using Python type hints
|
||||
pydantic==2.14.1
|
||||
|
||||
# HTTP Client
|
||||
# HTTPX - Async HTTP client for API calls
|
||||
httpx==0.28.1
|
||||
|
||||
# Environment Variables
|
||||
# python-dotenv - Load environment from .env files
|
||||
python-dotenv==1.2.4
|
||||
|
||||
# Structured Logging
|
||||
# structlog - JSON log lines (see LOG_FORMAT in server.py)
|
||||
structlog==26.1.0
|
||||
|
||||
# Optional: Add your custom dependencies below
|
||||
# requests>=2.31.0
|
||||
# aiofiles>=23.2.1
|
||||
# sqlalchemy>=2.0.0
|
||||
# redis>=5.0.0
|
||||
|
||||
# Added by this server's definition
|
||||
boto3==1.43.122
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,360 @@
|
||||
"""Conformance checks for an MCP server that takes its upstream credentials from the MCP Gateway.
|
||||
|
||||
Run these against a running server before you push it. They need only `pytest` and `httpx`, import
|
||||
nothing from the server and talk to it over HTTP, so they work on a server from the MCP Server
|
||||
Builder and on one written by hand.
|
||||
|
||||
pip install pytest httpx
|
||||
MCP_SERVER_URL=http://localhost:8100 MCP_REGISTRATION_API_KEY=<the server's key> pytest tests/ -v
|
||||
|
||||
What is checked, and why:
|
||||
|
||||
Protocol the server answers /health, refuses callers without its key, and speaks JSON-RPC
|
||||
correctly (initialize, tools/list, ids echoed, errors as errors).
|
||||
Connection a server that needs an upstream account says so in its initialize result
|
||||
(`_meta["com.kyndryl.mcp/connection-schema"]`) and takes the account from each
|
||||
request (`params._meta["com.kyndryl.mcp/connection"]`), not from its own environment.
|
||||
Such a server refuses a call that carries none (fail closed), reports which required
|
||||
field is missing, takes nothing from `arguments`, and never repeats a credential in a
|
||||
reply (the values of fields marked `writeOnly`; every value if none is marked). A server that needs no account skips these checks.
|
||||
|
||||
Settings (environment variables):
|
||||
|
||||
MCP_SERVER_URL default http://localhost:8100
|
||||
MCP_REGISTRATION_API_KEY the key the server was started with (required unless the
|
||||
server has authentication switched off)
|
||||
CONFORMANCE_EXPECT_FAIL_CLOSED default true. Set false only for a server you run locally
|
||||
with REQUIRE_VAULT_CONNECTION=false, so that checks which
|
||||
need a refusal are skipped rather than failed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
VENDOR = "com.kyndryl.mcp"
|
||||
SCHEMA_KEY = f"{VENDOR}/connection-schema"
|
||||
VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool"
|
||||
CONNECTION_KEY = f"{VENDOR}/connection"
|
||||
|
||||
BASE_URL = os.getenv("MCP_SERVER_URL", "http://localhost:8100").rstrip("/")
|
||||
API_KEY = os.getenv("MCP_REGISTRATION_API_KEY", "")
|
||||
EXPECT_FAIL_CLOSED = os.getenv("CONFORMANCE_EXPECT_FAIL_CLOSED", "true").strip().lower() != "false"
|
||||
|
||||
# A value no server could contain by accident, so finding it in a reply means the server repeated it.
|
||||
SENTINEL = f"sentinel-{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ helpers
|
||||
|
||||
|
||||
def auth_headers(key: Optional[str] = None) -> Dict[str, str]:
|
||||
key = API_KEY if key is None else key
|
||||
return {"Authorization": f"Bearer {key}"} if key else {}
|
||||
|
||||
|
||||
def rpc(
|
||||
client: httpx.Client,
|
||||
method: str,
|
||||
params: Optional[Dict[str, Any]] = None,
|
||||
*,
|
||||
request_id: Any = "1",
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
) -> httpx.Response:
|
||||
return client.post(
|
||||
"/messages",
|
||||
json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}},
|
||||
headers=auth_headers() if headers is None else headers,
|
||||
)
|
||||
|
||||
|
||||
def result_of(client: httpx.Client, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
response = rpc(client, method, params)
|
||||
assert response.status_code == 200, f"{method} answered HTTP {response.status_code}: {response.text[:300]}"
|
||||
body = response.json()
|
||||
assert not body.get("error"), f"{method} returned an error: {body['error']}"
|
||||
return body["result"]
|
||||
|
||||
|
||||
def with_connection(params: Dict[str, Any], connection: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
if connection is None:
|
||||
return params
|
||||
return {**params, "_meta": {CONNECTION_KEY: connection}}
|
||||
|
||||
|
||||
def value_for(name: str, spec: Dict[str, Any]) -> Any:
|
||||
"""A value of the right shape for a connection field, carrying the sentinel."""
|
||||
kind = spec.get("type", "string")
|
||||
if kind == "string" and spec.get("format") == "uri":
|
||||
return f"https://{SENTINEL}.invalid"
|
||||
if kind == "integer":
|
||||
return 12345
|
||||
if kind == "boolean":
|
||||
return True
|
||||
return f"{SENTINEL}-{name}"
|
||||
|
||||
|
||||
def full_connection(schema: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {name: value_for(name, spec) for name, spec in (schema.get("properties") or {}).items()}
|
||||
|
||||
|
||||
def secret_values(schema: Dict[str, Any]) -> List[str]:
|
||||
"""The sent values that must never come back: those of fields marked secret (`writeOnly`).
|
||||
|
||||
A tool may repeat a base URL or a region. If the server marks no field secret, every value is
|
||||
treated as one, because then nothing says which are safe to repeat.
|
||||
"""
|
||||
connection = full_connection(schema)
|
||||
properties = schema.get("properties") or {}
|
||||
marked = [n for n, spec in properties.items() if spec.get("writeOnly")]
|
||||
return [str(connection[n]) for n in (marked or list(properties))]
|
||||
|
||||
|
||||
def repeated(response: httpx.Response, schema: Dict[str, Any]) -> List[str]:
|
||||
return [v for v in secret_values(schema) if v in response.text]
|
||||
|
||||
|
||||
def _string_values(node: Any) -> List[str]:
|
||||
"""Every string anywhere in a JSON value."""
|
||||
if isinstance(node, str):
|
||||
return [node]
|
||||
if isinstance(node, dict):
|
||||
return [v for item in node.values() for v in _string_values(item)]
|
||||
if isinstance(node, list):
|
||||
return [v for item in node for v in _string_values(item)]
|
||||
return []
|
||||
|
||||
|
||||
def call(client: httpx.Client, tool: str, connection: Optional[Dict[str, Any]], arguments: Optional[Dict] = None):
|
||||
return rpc(client, "tools/call", with_connection({"name": tool, "arguments": arguments or {}}, connection))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
with httpx.Client(base_url=BASE_URL, timeout=30.0) as session:
|
||||
try:
|
||||
session.get("/health")
|
||||
except httpx.HTTPError as error:
|
||||
pytest.exit(f"Cannot reach the server at {BASE_URL}: {error}. Start it, or set MCP_SERVER_URL.", 2)
|
||||
yield session
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def initialize(client) -> Dict[str, Any]:
|
||||
return result_of(client, "initialize", {"protocolVersion": "1.0.0", "clientInfo": {"name": "conformance"}})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tools(client) -> List[Dict[str, Any]]:
|
||||
return result_of(client, "tools/list")["tools"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def schema(initialize) -> Optional[Dict[str, Any]]:
|
||||
return (initialize.get("_meta") or {}).get(SCHEMA_KEY)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def needs_connection(schema) -> Dict[str, Any]:
|
||||
if not schema or not schema.get("properties"):
|
||||
pytest.skip("the server advertises no connection fields, so it takes no per-request credentials")
|
||||
return schema
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def probe_tool(initialize, tools) -> str:
|
||||
"""The tool to call in the connection checks: the verify tool when there is one."""
|
||||
verify = (initialize.get("_meta") or {}).get(VERIFY_TOOL_KEY)
|
||||
if verify:
|
||||
return verify
|
||||
assert tools, "the server lists no tools to call"
|
||||
return tools[0]["name"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ protocol
|
||||
|
||||
|
||||
def test_health_answers(client):
|
||||
assert client.get("/health").status_code == 200
|
||||
|
||||
|
||||
def test_the_public_auth_endpoint_reveals_no_key(client):
|
||||
response = client.get("/.well-known/mcp-auth")
|
||||
if response.status_code == 404:
|
||||
pytest.skip("the server has no /.well-known/mcp-auth endpoint")
|
||||
assert response.status_code == 200
|
||||
if API_KEY:
|
||||
# A value that equals the key is always a leak. A short key can also appear inside ordinary words
|
||||
# ("nc" in "auth_required"), so searching the text for it is only meaningful for a real-length key.
|
||||
assert API_KEY not in _string_values(response.json()), "/.well-known/mcp-auth returns the server's key"
|
||||
if len(API_KEY) >= 12:
|
||||
assert API_KEY not in response.text, "/.well-known/mcp-auth returns the server's key"
|
||||
|
||||
|
||||
def test_a_call_without_the_servers_key_is_refused(client):
|
||||
response = rpc(client, "tools/list", headers={})
|
||||
assert response.status_code in (401, 403), f"answered HTTP {response.status_code} to a caller with no key"
|
||||
|
||||
|
||||
def test_a_call_with_the_wrong_key_is_refused(client):
|
||||
response = rpc(client, "tools/list", headers=auth_headers("not-the-key-" + uuid.uuid4().hex))
|
||||
assert response.status_code in (401, 403), f"answered HTTP {response.status_code} to a caller with the wrong key"
|
||||
|
||||
|
||||
def test_initialize_describes_the_server(initialize):
|
||||
assert initialize["serverInfo"]["name"]
|
||||
assert isinstance(initialize.get("capabilities"), dict)
|
||||
|
||||
|
||||
def test_tools_have_a_name_a_description_and_an_object_schema(tools):
|
||||
assert isinstance(tools, list)
|
||||
names = [t["name"] for t in tools]
|
||||
assert len(names) == len(set(names)), "two tools share a name"
|
||||
for tool in tools:
|
||||
assert tool["name"] and tool.get("description"), f"tool {tool.get('name')!r} lacks a name or description"
|
||||
assert tool["inputSchema"]["type"] == "object", f"{tool['name']} has no object inputSchema"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_id", ["conformance-1", 7])
|
||||
def test_the_reply_echoes_the_request_id(client, request_id):
|
||||
response = rpc(client, "tools/list", request_id=request_id)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == request_id
|
||||
|
||||
|
||||
def test_an_unknown_method_is_an_error_not_a_crash(client):
|
||||
response = rpc(client, "no/such/method")
|
||||
assert response.status_code == 200
|
||||
assert response.json().get("error"), "an unknown method returned no error"
|
||||
|
||||
|
||||
def test_an_unknown_tool_is_an_error_not_a_crash(client):
|
||||
response = rpc(client, "tools/call", {"name": f"no_such_tool_{uuid.uuid4().hex[:8]}", "arguments": {}})
|
||||
assert response.status_code == 200
|
||||
assert response.json().get("error"), "an unknown tool returned no error"
|
||||
|
||||
|
||||
def test_arguments_that_are_not_an_object_are_the_callers_mistake(client, tools, schema):
|
||||
params = {"name": tools[0]["name"], "arguments": ["not", "an", "object"]}
|
||||
# With a connection, when the server wants one: a refusal for lacking it would answer -32602 too
|
||||
response = rpc(client, "tools/call", with_connection(params, full_connection(schema) if schema else None))
|
||||
assert response.status_code == 200
|
||||
error = response.json().get("error")
|
||||
assert error and error.get("code") == -32602, f"expected invalid params (-32602), got: {response.text[:300]}"
|
||||
|
||||
|
||||
def test_an_invalid_request_does_not_repeat_what_it_carried():
|
||||
# No "id": the request is not valid JSON-RPC, and what it carried (a connection) must not come back.
|
||||
# It has a connection of its own: a server that answers a bad request by dropping the connection (an
|
||||
# unhandled error makes uvicorn do that) must not make the NEXT check fail with "connection reset".
|
||||
marker = f"{SENTINEL}-carried"
|
||||
try:
|
||||
response = httpx.post(
|
||||
f"{BASE_URL}/messages",
|
||||
json={"jsonrpc": "2.0", "method": "tools/list", "params": {"_meta": {CONNECTION_KEY: {"field": marker}}}},
|
||||
headers=auth_headers(),
|
||||
timeout=30.0,
|
||||
)
|
||||
except httpx.TransportError:
|
||||
return # nothing came back, so nothing was repeated
|
||||
assert marker not in response.text, "the reply to an invalid request repeated the request"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ connection
|
||||
|
||||
|
||||
def test_the_connection_schema_is_a_json_schema_object(needs_connection):
|
||||
assert needs_connection["type"] == "object"
|
||||
properties = needs_connection["properties"]
|
||||
assert isinstance(properties, dict) and properties
|
||||
assert set(needs_connection.get("required", [])) <= set(properties), "a required field is not a property"
|
||||
|
||||
|
||||
def test_the_verify_tool_is_listed(initialize, tools, needs_connection):
|
||||
verify = (initialize.get("_meta") or {}).get(VERIFY_TOOL_KEY)
|
||||
assert verify, f"initialize does not name a verify tool in _meta[{VERIFY_TOOL_KEY!r}]"
|
||||
assert verify in [t["name"] for t in tools], f"the verify tool {verify!r} is not in tools/list"
|
||||
|
||||
|
||||
def test_a_call_with_no_connection_is_refused(client, needs_connection, probe_tool):
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
response = call(client, probe_tool, None)
|
||||
assert response.json().get("error"), (
|
||||
"a call with no connection was served. The server is using its own environment for the "
|
||||
"upstream account, so every tenant would share one. Refuse it (REQUIRE_VAULT_CONNECTION)."
|
||||
)
|
||||
|
||||
|
||||
def test_a_connection_in_the_arguments_is_not_accepted(client, needs_connection, probe_tool):
|
||||
"""The credential travels in `_meta`, which the model never sees; one in `arguments` is not one."""
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
response = call(client, probe_tool, None, arguments=full_connection(needs_connection))
|
||||
assert response.json().get("error"), "a connection passed as tool arguments was accepted"
|
||||
assert not repeated(response, needs_connection), "the reply repeats a credential that was sent as an argument"
|
||||
|
||||
|
||||
def test_a_call_with_a_connection_is_not_refused_for_lacking_one(client, needs_connection, probe_tool):
|
||||
response = call(client, probe_tool, full_connection(needs_connection))
|
||||
assert response.status_code == 200
|
||||
error = response.json().get("error") or {}
|
||||
message = str(error.get("message", "")).lower()
|
||||
assert "no connection" not in message and "missing" not in message, (
|
||||
f"a complete connection was refused as incomplete: {error}"
|
||||
)
|
||||
|
||||
|
||||
def test_an_incomplete_connection_names_what_is_missing(client, needs_connection, probe_tool):
|
||||
required = list(needs_connection.get("required", []))
|
||||
if not required:
|
||||
pytest.skip("no field is required")
|
||||
connection = full_connection(needs_connection)
|
||||
dropped = required[-1]
|
||||
connection.pop(dropped)
|
||||
if not connection:
|
||||
# The only field is required, and an empty connection counts as none. Send one that has a value
|
||||
# but not the field, which is what a mistyped field name in the credential looks like.
|
||||
connection = {"not_a_field_of_this_server": "x"}
|
||||
|
||||
response = call(client, probe_tool, connection)
|
||||
error = response.json().get("error")
|
||||
assert error, f"a connection without the required field {dropped!r} was served"
|
||||
assert dropped in str(error.get("message", "")), f"the refusal does not name the missing field {dropped!r}: {error}"
|
||||
assert not repeated(response, needs_connection), "the refusal repeats a credential value"
|
||||
|
||||
|
||||
def test_no_reply_repeats_the_credential(client, needs_connection, probe_tool, tools):
|
||||
connection = full_connection(needs_connection)
|
||||
replies = [call(client, probe_tool, connection)]
|
||||
for tool in tools[:5]:
|
||||
replies.append(call(client, tool["name"], connection, arguments={"conformance": "probe"}))
|
||||
replies.append(call(client, "no_such_tool", connection))
|
||||
for response in replies:
|
||||
assert not repeated(response, needs_connection), f"a reply repeats the credential: {response.text[:300]}"
|
||||
|
||||
|
||||
def test_a_malformed_connection_is_no_better_than_none(client, needs_connection, probe_tool):
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
for bad in ("just-a-string", ["a", "list"], 42):
|
||||
params = {"name": probe_tool, "arguments": {}, "_meta": {CONNECTION_KEY: bad}}
|
||||
body = rpc(client, "tools/call", params).json()
|
||||
assert body.get("error"), f"a connection of type {type(bad).__name__} was served"
|
||||
|
||||
|
||||
def test_resources_and_prompts_are_listed_when_advertised(client, initialize):
|
||||
capabilities = initialize.get("capabilities") or {}
|
||||
if capabilities.get("resources"):
|
||||
assert isinstance(result_of(client, "resources/list")["resources"], list)
|
||||
if capabilities.get("prompts"):
|
||||
assert isinstance(result_of(client, "prompts/list")["prompts"], list)
|
||||
@@ -0,0 +1,429 @@
|
||||
# Generated by build_definitions.py; don't edit by hand.
|
||||
# Credentials arrive per call from the Vault Service. Store them per project.
|
||||
|
||||
server_id: sa-azure-cloud
|
||||
name: Solution Architecture Azure
|
||||
description: Azure documentation and read-only estate tools for the Solution Architecture agent, through Microsoft Learn,
|
||||
Resource Graph and ARM.
|
||||
version: 0.1.0
|
||||
port: 8116
|
||||
verify_tool: azure_check_connection
|
||||
shared_code:
|
||||
- ../../../mcp-servers/_common/tool_support.py
|
||||
- ../../../mcp-servers/_common/azure_support.py
|
||||
- ../../../mcp-servers/_common/knowledge_support.py
|
||||
- _support/docs_log.py
|
||||
- _support/docs_support.py
|
||||
- _support/azure_tools.py
|
||||
extra_requirements:
|
||||
- boto3==1.43.122
|
||||
connection_fields:
|
||||
- name: tenant_id
|
||||
title: Tenant id
|
||||
description: The Entra tenant id.
|
||||
required: false
|
||||
secret: false
|
||||
- name: client_id
|
||||
title: Client id
|
||||
description: The app registration's id.
|
||||
required: false
|
||||
secret: false
|
||||
- name: client_secret
|
||||
title: Client secret
|
||||
description: The client secret.
|
||||
required: false
|
||||
secret: true
|
||||
- name: scope_root
|
||||
title: Scope root
|
||||
description: managementGroups/<id> or subscriptions/<id>.
|
||||
required: true
|
||||
secret: false
|
||||
- name: cloud
|
||||
title: Cloud
|
||||
description: public, usgov or china. Optional.
|
||||
required: false
|
||||
secret: false
|
||||
tools:
|
||||
- name: azure_check_connection
|
||||
display_name: Azure check connection
|
||||
description: 'Test the stored connection: sign in and read the scope root. Returns no customer data.'
|
||||
parameters: []
|
||||
ai_implementation: "async def azure_check_connection(arguments: Dict[str, Any]) -> Dict[str, Any]:\n try:\n await\
|
||||
\ _azure_graph(\"ResourceContainers | limit 1\", 1)\n except Exception as error:\n return {\"ok\": False, \"\
|
||||
message\": _upstream_failed(\"azure\", error)[\"error\"][\"message\"]}\n return {\"ok\": True, \"message\": \"Signed\
|
||||
\ in and read the scope root.\"}\n"
|
||||
- name: azure_search_documents
|
||||
display_name: Azure search documents
|
||||
description: Search Microsoft Learn in free text. Queries are sent as written and logged.
|
||||
parameters:
|
||||
- name: query
|
||||
type: string
|
||||
description: What to look up. Keep client detail out.
|
||||
required: true
|
||||
ai_implementation: "async def azure_search_documents(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _docs_search(\"\
|
||||
azure\", \"azure_search_documents\", arguments, {})\n"
|
||||
- name: azure_get_documents
|
||||
display_name: Azure get documents
|
||||
description: Fetch one Microsoft Learn page by URL.
|
||||
parameters:
|
||||
- name: url
|
||||
type: string
|
||||
description: A learn.microsoft.com URL.
|
||||
required: true
|
||||
ai_implementation: "async def azure_get_documents(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _docs_read(\"\
|
||||
azure\", \"azure_get_documents\", arguments, {}, \"microsoft_docs_fetch\", \"url\")\n"
|
||||
- name: azure_analyze_access
|
||||
display_name: Azure analyze access
|
||||
description: List role assignments, optionally for one principal or below one scope.
|
||||
parameters:
|
||||
- name: principal_id
|
||||
type: string
|
||||
description: An object id.
|
||||
required: false
|
||||
- name: scope
|
||||
type: string
|
||||
description: An ARM scope.
|
||||
required: false
|
||||
- &id001
|
||||
name: page_size
|
||||
type: integer
|
||||
description: Items per page, up to 200. Default 50.
|
||||
required: false
|
||||
- &id002
|
||||
name: page_token
|
||||
type: string
|
||||
description: next_page_token from the previous reply.
|
||||
required: false
|
||||
ai_implementation: "async def azure_analyze_access(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_access(\"\
|
||||
azure_analyze_access\", arguments)\n"
|
||||
- name: azure_list_instance_attached_disks
|
||||
display_name: Azure list instance attached disks
|
||||
description: List the disks attached to one virtual machine.
|
||||
parameters:
|
||||
- &id003
|
||||
name: resource_id
|
||||
type: string
|
||||
description: The full ARM resource id.
|
||||
required: true
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_instance_attached_disks(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _azure_attached_disks(\"azure_list_instance_attached_disks\", arguments)\n"
|
||||
- name: azure_list_node_pools
|
||||
display_name: Azure list node pools
|
||||
description: List AKS node pools.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_node_pools(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_node_pools(\"\
|
||||
azure_list_node_pools\", arguments)\n"
|
||||
- name: azure_search_subscriptions
|
||||
display_name: Azure search subscriptions
|
||||
description: List subscriptions.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_search_subscriptions(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_list(\"azure_search_subscriptions\", arguments, \"ResourceContainers\", ['microsoft.resources/subscriptions'])\n"
|
||||
- name: azure_list_instances
|
||||
display_name: Azure list instances
|
||||
description: List virtual machines.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_instances(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_instances\", arguments, \"Resources\", ['microsoft.compute/virtualmachines'])\n"
|
||||
- name: azure_list_instance_group_managers
|
||||
display_name: Azure list instance group managers
|
||||
description: List scale sets.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_instance_group_managers(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _azure_list(\"azure_list_instance_group_managers\", arguments, \"Resources\", ['microsoft.compute/virtualmachinescalesets'])\n"
|
||||
- name: azure_list_instance_templates
|
||||
display_name: Azure list instance templates
|
||||
description: List template specs and gallery images.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_instance_templates(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_list(\"azure_list_instance_templates\", arguments, \"Resources\", ['microsoft.resources/templatespecs', 'microsoft.compute/galleries/images'])\n"
|
||||
- name: azure_list_disks
|
||||
display_name: Azure list disks
|
||||
description: List managed disks.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_disks(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_disks\", arguments, \"Resources\", ['microsoft.compute/disks'])\n"
|
||||
- name: azure_list_reservations
|
||||
display_name: Azure list reservations
|
||||
description: List capacity reservation groups.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_reservations(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_reservations\", arguments, \"Resources\", ['microsoft.compute/capacityreservationgroups'])\n"
|
||||
- name: azure_list_clusters
|
||||
display_name: Azure list clusters
|
||||
description: List AKS clusters.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_clusters(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_clusters\", arguments, \"Resources\", ['microsoft.containerservice/managedclusters'])\n"
|
||||
- name: azure_list_services
|
||||
display_name: Azure list services
|
||||
description: List Container Apps and App Service apps.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_services(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_services\", arguments, \"Resources\", ['microsoft.app/containerapps', 'microsoft.web/sites'])\n"
|
||||
- name: azure_list_sql_instances
|
||||
display_name: Azure list sql instances
|
||||
description: List SQL, PostgreSQL and MySQL servers.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_sql_instances(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_sql_instances\", arguments, \"Resources\", ['microsoft.sql/servers', 'microsoft.sql/managedinstances', 'microsoft.dbforpostgresql/flexibleservers',\
|
||||
\ 'microsoft.dbformysql/flexibleservers'])\n"
|
||||
- name: azure_list_buckets
|
||||
display_name: Azure list buckets
|
||||
description: List storage accounts.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_buckets(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_buckets\", arguments, \"Resources\", ['microsoft.storage/storageaccounts'])\n"
|
||||
- name: azure_list_topics
|
||||
display_name: Azure list topics
|
||||
description: List Service Bus, Event Hubs and Event Grid topics.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_topics(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_topics\", arguments, \"Resources\", ['microsoft.servicebus/namespaces', 'microsoft.eventhub/namespaces', 'microsoft.eventgrid/topics'])\n"
|
||||
- name: azure_list_roles
|
||||
display_name: Azure list roles
|
||||
description: List role definitions.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_roles(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_roles\", arguments, \"AuthorizationResources\", ['microsoft.authorization/roledefinitions'])\n"
|
||||
- name: azure_list_alert_policies
|
||||
display_name: Azure list alert policies
|
||||
description: List alert rules.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_alert_policies(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_list(\"azure_list_alert_policies\", arguments, \"Resources\", ['microsoft.insights/metricalerts', 'microsoft.insights/activitylogalerts',\
|
||||
\ 'microsoft.insights/scheduledqueryrules'])\n"
|
||||
- name: azure_list_dashboards
|
||||
display_name: Azure list dashboards
|
||||
description: List dashboards.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_dashboards(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_list(\"\
|
||||
azure_list_dashboards\", arguments, \"Resources\", ['microsoft.portal/dashboards'])\n"
|
||||
- name: azure_list_connectivity_tests
|
||||
display_name: Azure list connectivity tests
|
||||
description: List connection monitors.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_connectivity_tests(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_list(\"azure_list_connectivity_tests\", arguments, \"Resources\", ['microsoft.network/networkwatchers/connectionmonitors'])\n"
|
||||
- name: azure_get_instance_basic_info
|
||||
display_name: Azure get instance basic info
|
||||
description: Read one virtual machine.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_instance_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_get(\"azure_get_instance_basic_info\", arguments, \"Resources\", ['microsoft.compute/virtualmachines'])\n"
|
||||
- name: azure_get_instance_group_manager_basic_info
|
||||
display_name: Azure get instance group manager basic info
|
||||
description: Read one scale set.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_instance_group_manager_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n\
|
||||
\ return await _azure_get(\"azure_get_instance_group_manager_basic_info\", arguments, \"Resources\", ['microsoft.compute/virtualmachinescalesets'])\n"
|
||||
- name: azure_get_instance_template_properties
|
||||
display_name: Azure get instance template properties
|
||||
description: Read one template spec or gallery image.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_instance_template_properties(arguments: Dict[str, Any]) -> Dict[str, Any]:\n \
|
||||
\ return await _azure_get(\"azure_get_instance_template_properties\", arguments, \"Resources\", ['microsoft.resources/templatespecs',\
|
||||
\ 'microsoft.compute/galleries/images'])\n"
|
||||
- name: azure_get_disk_basic_info
|
||||
display_name: Azure get disk basic info
|
||||
description: Read one disk.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_disk_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_get(\"azure_get_disk_basic_info\", arguments, \"Resources\", ['microsoft.compute/disks'])\n"
|
||||
- name: azure_get_cluster
|
||||
display_name: Azure get cluster
|
||||
description: Read one AKS cluster.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_cluster(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_get(\"\
|
||||
azure_get_cluster\", arguments, \"Resources\", ['microsoft.containerservice/managedclusters'])\n"
|
||||
- name: azure_get_service
|
||||
display_name: Azure get service
|
||||
description: Read one app.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_service(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_get(\"\
|
||||
azure_get_service\", arguments, \"Resources\", ['microsoft.app/containerapps', 'microsoft.web/sites'])\n"
|
||||
- name: azure_get_sql_instance
|
||||
display_name: Azure get sql instance
|
||||
description: Read one database server.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_sql_instance(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_get(\"\
|
||||
azure_get_sql_instance\", arguments, \"Resources\", ['microsoft.sql/servers', 'microsoft.sql/managedinstances', 'microsoft.dbforpostgresql/flexibleservers',\
|
||||
\ 'microsoft.dbformysql/flexibleservers'])\n"
|
||||
- name: azure_get_topic
|
||||
display_name: Azure get topic
|
||||
description: Read one messaging resource.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_topic(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_get(\"\
|
||||
azure_get_topic\", arguments, \"Resources\", ['microsoft.servicebus/namespaces', 'microsoft.eventhub/namespaces', 'microsoft.eventgrid/topics'])\n"
|
||||
- name: azure_get_role
|
||||
display_name: Azure get role
|
||||
description: Read one role definition.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_role(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_get(\"\
|
||||
azure_get_role\", arguments, \"AuthorizationResources\", ['microsoft.authorization/roledefinitions'])\n"
|
||||
- name: azure_get_alert_policy
|
||||
display_name: Azure get alert policy
|
||||
description: Read one alert rule.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_alert_policy(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_get(\"\
|
||||
azure_get_alert_policy\", arguments, \"Resources\", ['microsoft.insights/metricalerts', 'microsoft.insights/activitylogalerts',\
|
||||
\ 'microsoft.insights/scheduledqueryrules'])\n"
|
||||
- name: azure_get_connectivity_test
|
||||
display_name: Azure get connectivity test
|
||||
description: Read one connection monitor.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_get_connectivity_test(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_get(\"azure_get_connectivity_test\", arguments, \"Resources\", ['microsoft.network/networkwatchers/connectionmonitors'])\n"
|
||||
- name: azure_list_assets
|
||||
display_name: Azure list assets
|
||||
description: List every resource in scope, or one resource type.
|
||||
parameters:
|
||||
- name: resource_type
|
||||
type: string
|
||||
description: An ARM type.
|
||||
required: false
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_assets(arguments: Dict[str, Any]) -> Dict[str, Any]:\n kind = arguments.get(\"\
|
||||
resource_type\")\n if kind and not re.fullmatch(r\"[A-Za-z0-9./]+\", str(kind)):\n return _refuse(\"invalid_argument\"\
|
||||
, \"resource_type must be an ARM type\")\n where = f\" | where type =~ '{kind}'\" if kind else \"\"\n return await\
|
||||
\ _azure_page(\"azure_list_assets\", arguments, f\"Resources{where} | project id, name, type, location, resourceGroup,\
|
||||
\ subscriptionId, tags | order by id asc\")\n"
|
||||
- name: azure_get_node_pool
|
||||
display_name: Azure get node pool
|
||||
description: Read one AKS node pool.
|
||||
parameters:
|
||||
- *id003
|
||||
- name: pool
|
||||
type: string
|
||||
description: The node pool's name.
|
||||
required: true
|
||||
ai_implementation: "async def azure_get_node_pool(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_resource_arm(\"\
|
||||
azure_get_node_pool\", arguments, f\"/agentPools/{arguments.get('pool')}\", {\"api-version\": \"2024-05-01\"}) if re.fullmatch(r\"\
|
||||
[A-Za-z0-9]+\", str(arguments.get(\"pool\"))) else _refuse(\"invalid_argument\", \"pool must be a pool name\")\n"
|
||||
- name: azure_list_commitments
|
||||
display_name: Azure list commitments
|
||||
description: List reserved capacity orders, Azure's committed-use discounts.
|
||||
parameters:
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_commitments(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_arm(\"\
|
||||
azure_list_commitments\", arguments, \"/providers/Microsoft.Capacity/reservationOrders\", {\"api-version\": \"2022-11-01\"\
|
||||
})\n"
|
||||
- name: azure_get_k8s_version
|
||||
display_name: Azure get k8s version
|
||||
description: List the Kubernetes versions AKS offers in one location.
|
||||
parameters:
|
||||
- name: location
|
||||
type: string
|
||||
description: An Azure region, such as uksouth.
|
||||
required: true
|
||||
- &id004
|
||||
name: subscription_id
|
||||
type: string
|
||||
description: Needed when the connection's scope is a management group.
|
||||
required: false
|
||||
ai_implementation: "async def azure_get_k8s_version(arguments: Dict[str, Any]) -> Dict[str, Any]:\n location = str(arguments.get(\"\
|
||||
location\") or \"\")\n if not re.fullmatch(r\"[a-z0-9]+\", location):\n return _refuse(\"invalid_argument\"\
|
||||
, \"location must be an Azure region name\")\n return await _azure_subscription_arm(\"azure_get_k8s_version\", arguments,\
|
||||
\ f\"/providers/Microsoft.ContainerService/locations/{location}/kubernetesVersions\", {\"api-version\": \"2024-05-01\"\
|
||||
})\n"
|
||||
- name: azure_list_subscriptions
|
||||
display_name: Azure list subscriptions
|
||||
description: List Event Grid event subscriptions.
|
||||
parameters:
|
||||
- *id004
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_subscriptions(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_subscription_arm(\"\
|
||||
azure_list_subscriptions\", arguments, \"/providers/Microsoft.EventGrid/eventSubscriptions\", {\"api-version\": \"2022-06-15\"\
|
||||
})\n"
|
||||
- name: azure_list_deny_policies
|
||||
display_name: Azure list deny policies
|
||||
description: List deny assignments.
|
||||
parameters:
|
||||
- *id004
|
||||
- *id001
|
||||
- *id002
|
||||
ai_implementation: "async def azure_list_deny_policies(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _azure_subscription_arm(\"\
|
||||
azure_list_deny_policies\", arguments, \"/providers/Microsoft.Authorization/denyAssignments\", {\"api-version\": \"2022-04-01\"\
|
||||
})\n"
|
||||
- name: azure_list_metric_descriptors
|
||||
display_name: Azure list metric descriptors
|
||||
description: List the metrics one resource publishes.
|
||||
parameters:
|
||||
- *id003
|
||||
ai_implementation: "async def azure_list_metric_descriptors(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _azure_resource_arm(\"azure_list_metric_descriptors\", arguments, \"/providers/Microsoft.Insights/metricDefinitions\"\
|
||||
, {\"api-version\": \"2018-01-01\"})\n"
|
||||
- name: azure_list_timeseries
|
||||
display_name: Azure list timeseries
|
||||
description: Read metric values for one resource.
|
||||
parameters:
|
||||
- *id003
|
||||
- name: metricnames
|
||||
type: string
|
||||
description: Comma-separated metric names.
|
||||
required: true
|
||||
- name: timespan
|
||||
type: string
|
||||
description: ISO 8601 interval, start/end.
|
||||
required: true
|
||||
- name: interval
|
||||
type: string
|
||||
description: ISO 8601 duration, such as PT1H.
|
||||
required: false
|
||||
- name: aggregation
|
||||
type: string
|
||||
description: Average, Total, Maximum, Minimum or Count.
|
||||
required: false
|
||||
ai_implementation: "async def azure_list_timeseries(arguments: Dict[str, Any]) -> Dict[str, Any]:\n wanted = {k: arguments.get(k)\
|
||||
\ for k in (\"metricnames\", \"timespan\", \"interval\", \"aggregation\") if arguments.get(k)}\n if \"metricnames\"\
|
||||
\ not in wanted or \"timespan\" not in wanted:\n return _refuse(\"invalid_argument\", \"metricnames and timespan\
|
||||
\ are required\")\n return await _azure_resource_arm(\"azure_list_timeseries\", arguments, \"/providers/Microsoft.Insights/metrics\"\
|
||||
, {\"api-version\": \"2018-01-01\", **wanted})\n"
|
||||
@@ -0,0 +1,62 @@
|
||||
# ============================================
|
||||
# Solution Architecture Azure - Environment Variables
|
||||
# ============================================
|
||||
# Generated by Agent Builder Platform
|
||||
#
|
||||
# SETUP INSTRUCTIONS:
|
||||
# 1. Copy this file to .env: cp .env.example .env
|
||||
# 2. Generate a secure API key: openssl rand -hex 32
|
||||
# 3. Update MCP_REGISTRATION_API_KEY with the generated key
|
||||
# 4. Build the image from the Dockerfile and run it where the MCP Gateway
|
||||
# can reach it (see README.md)
|
||||
#
|
||||
# MCP GATEWAY INTEGRATION:
|
||||
# When registering with the MCP Gateway, use the URL the Gateway reaches this
|
||||
# server at; for a container on the Gateway's network, its container name:
|
||||
# http://solution-architecture-azure:8116
|
||||
# ============================================
|
||||
|
||||
# Server Identity
|
||||
MCP_SERVER_NAME=Solution Architecture Azure
|
||||
MCP_SERVER_ID=sa-azure-cloud
|
||||
MCP_SERVER_VERSION=0.1.0
|
||||
|
||||
# Server Configuration
|
||||
MCP_SERVER_PORT=8116
|
||||
|
||||
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format
|
||||
# (json = one object per line, for log stores; console = for reading by eye)
|
||||
LOG_LEVEL=INFO
|
||||
LOG_FORMAT=json
|
||||
|
||||
# ============================================
|
||||
# AUTHENTICATION (REQUIRED for production!)
|
||||
# ============================================
|
||||
# This key authenticates MCP Gateway requests to this server.
|
||||
# The Gateway stores this key and includes it in all tool/call requests.
|
||||
#
|
||||
# Generate a secure key:
|
||||
# openssl rand -hex 32
|
||||
#
|
||||
# IMPORTANT: Keep this key secret! It's stored in:
|
||||
# - This .env file (gitignored)
|
||||
# - MCP Gateway database (encrypted)
|
||||
MCP_REGISTRATION_API_KEY=<generate one: openssl rand -hex 32>
|
||||
|
||||
# Set to "false" ONLY for local development/testing
|
||||
# WARNING: Disabling auth in production is a security risk!
|
||||
REQUIRE_AUTH=true
|
||||
|
||||
# ============================================
|
||||
# CREDENTIALS FOR THE UPSTREAM (sent with each request, not set here)
|
||||
# ============================================
|
||||
# The MCP Gateway sends the tenant's credential with each call, from the Vault Service.
|
||||
# true: a call without one is refused. Set to false only for local runs, where the
|
||||
# server may use its own environment.
|
||||
REQUIRE_VAULT_CONNECTION=true
|
||||
|
||||
# ============================================
|
||||
# Add your own settings below
|
||||
# ============================================
|
||||
# Credentials for the upstream are not set here: the gateway sends them with each request.
|
||||
# EXAMPLE_SETTING=value
|
||||
15
outcome-pattern/solution_architecture/mcp-servers/sa-azure-cloud/.gitignore
vendored
Normal file
15
outcome-pattern/solution_architecture/mcp-servers/sa-azure-cloud/.gitignore
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
|
||||
# Editors
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,47 @@
|
||||
# MCP Server Dockerfile
|
||||
# Generated by Agent Builder Platform (template 1.1.0)
|
||||
#
|
||||
# Built on the platform's MCP server base image: Chainguard Python with the
|
||||
# packages in requirements.txt already installed, a non-root user (1000) and
|
||||
# no pip. This image adds only the server's own files.
|
||||
#
|
||||
# docker build -t <server>:<version> .
|
||||
# docker build --build-arg BASE_IMAGE=<local base image> -t ... .
|
||||
ARG BASE_IMAGE=kyndryl.jfrog.io/kc-ai-agent-factory-docker-local/mcp-server-base:1.1.0
|
||||
|
||||
# Stage 1: the server's extra Python packages, if requirements.txt lists any.
|
||||
# The base image's build image (<base image>-build: the base image plus uv) installs
|
||||
# them with its vendor-install script: only the packages added go on to
|
||||
# /vendor, and one that would change a package the base image already has stops
|
||||
# the build. uv never reaches the server's image.
|
||||
FROM ${BASE_IMAGE}-build AS vendor
|
||||
COPY requirements.txt constraints.txt /tmp/
|
||||
RUN vendor-install /tmp/requirements.txt /vendor /tmp/constraints.txt
|
||||
|
||||
# Stage 2: the server: the base image, its extra packages and its files.
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
LABEL maintainer="Agent Builder Platform"
|
||||
LABEL description="Azure documentation and read-only estate tools for the Solution Architecture agent, through Microsoft Learn, Resource Graph and ARM."
|
||||
LABEL version="0.1.0"
|
||||
LABEL server.id="sa-azure-cloud"
|
||||
LABEL template.version="1.1.0"
|
||||
|
||||
COPY --from=vendor /vendor /app/vendor/
|
||||
COPY server.py mcp_connection.py /app/
|
||||
|
||||
# Environment
|
||||
# The ConfigMap's SERVER_PORT overrides this, so the container, Service and probes agree
|
||||
ENV SERVER_PORT=8116
|
||||
ENV LOG_LEVEL=INFO
|
||||
ENV LOG_FORMAT=json
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8116
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD python -c "import os, urllib.request; urllib.request.urlopen('http://localhost:%s/health' % (os.getenv('MCP_SERVER_PORT') or os.getenv('SERVER_PORT') or '8116'))" || exit 1
|
||||
|
||||
# Run the server
|
||||
CMD ["python", "server.py"]
|
||||
@@ -0,0 +1,228 @@
|
||||
# Solution Architecture Azure
|
||||
|
||||
Azure documentation and read-only estate tools for the Solution Architecture agent, through Microsoft Learn, Resource Graph and ARM.
|
||||
|
||||
**Version:** 0.1.0
|
||||
**Server ID:** sa-azure-cloud
|
||||
**Port:** 8116
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### As a container (recommended)
|
||||
|
||||
The Dockerfile builds the server's image. Run it on the same network as the
|
||||
MCP Gateway, so the Gateway can reach it by its container name:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # then set MCP_REGISTRATION_API_KEY
|
||||
podman build -t <image-name> .
|
||||
podman run -d --name <container-name> --env-file .env --network <gateway-network> <image-name>
|
||||
```
|
||||
|
||||
Register it with the MCP Gateway at `http://<container-name>:8116`.
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with your configuration
|
||||
|
||||
# Run the server
|
||||
python server.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📡 API Endpoints
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/health` | GET | Health check (no auth) |
|
||||
| `/.well-known/mcp-auth` | GET | Authentication requirements |
|
||||
| `/messages` | POST | MCP JSON-RPC 2.0 endpoint |
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Available Tools
|
||||
|
||||
- **azure_check_connection**: Test the stored connection: sign in and read the scope root. Returns no customer data.
|
||||
- **azure_search_documents**: Search Microsoft Learn in free text. Queries are sent as written and logged.
|
||||
- **azure_get_documents**: Fetch one Microsoft Learn page by URL.
|
||||
- **azure_analyze_access**: List role assignments, optionally for one principal or below one scope.
|
||||
- **azure_list_instance_attached_disks**: List the disks attached to one virtual machine.
|
||||
- **azure_list_node_pools**: List AKS node pools.
|
||||
- **azure_search_subscriptions**: List subscriptions.
|
||||
- **azure_list_instances**: List virtual machines.
|
||||
- **azure_list_instance_group_managers**: List scale sets.
|
||||
- **azure_list_instance_templates**: List template specs and gallery images.
|
||||
- **azure_list_disks**: List managed disks.
|
||||
- **azure_list_reservations**: List capacity reservation groups.
|
||||
- **azure_list_clusters**: List AKS clusters.
|
||||
- **azure_list_services**: List Container Apps and App Service apps.
|
||||
- **azure_list_sql_instances**: List SQL, PostgreSQL and MySQL servers.
|
||||
- **azure_list_buckets**: List storage accounts.
|
||||
- **azure_list_topics**: List Service Bus, Event Hubs and Event Grid topics.
|
||||
- **azure_list_roles**: List role definitions.
|
||||
- **azure_list_alert_policies**: List alert rules.
|
||||
- **azure_list_dashboards**: List dashboards.
|
||||
- **azure_list_connectivity_tests**: List connection monitors.
|
||||
- **azure_get_instance_basic_info**: Read one virtual machine.
|
||||
- **azure_get_instance_group_manager_basic_info**: Read one scale set.
|
||||
- **azure_get_instance_template_properties**: Read one template spec or gallery image.
|
||||
- **azure_get_disk_basic_info**: Read one disk.
|
||||
- **azure_get_cluster**: Read one AKS cluster.
|
||||
- **azure_get_service**: Read one app.
|
||||
- **azure_get_sql_instance**: Read one database server.
|
||||
- **azure_get_topic**: Read one messaging resource.
|
||||
- **azure_get_role**: Read one role definition.
|
||||
- **azure_get_alert_policy**: Read one alert rule.
|
||||
- **azure_get_connectivity_test**: Read one connection monitor.
|
||||
- **azure_list_assets**: List every resource in scope, or one resource type.
|
||||
- **azure_get_node_pool**: Read one AKS node pool.
|
||||
- **azure_list_commitments**: List reserved capacity orders, Azure's committed-use discounts.
|
||||
- **azure_get_k8s_version**: List the Kubernetes versions AKS offers in one location.
|
||||
- **azure_list_subscriptions**: List Event Grid event subscriptions.
|
||||
- **azure_list_deny_policies**: List deny assignments.
|
||||
- **azure_list_metric_descriptors**: List the metrics one resource publishes.
|
||||
- **azure_list_timeseries**: Read metric values for one resource.
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Authentication
|
||||
|
||||
This server uses Bearer token authentication for MCP protocol messages.
|
||||
|
||||
```bash
|
||||
# Test with authentication
|
||||
curl -X POST http://localhost:8116/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $MCP_REGISTRATION_API_KEY" \
|
||||
-d '{"jsonrpc": "2.0", "id": "1", "method": "tools/list", "params": {}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 MCP Gateway Registration
|
||||
|
||||
To register this server with the MCP Gateway:
|
||||
|
||||
1. Start the server (see Quick Start) where the MCP Gateway can reach it
|
||||
2. In the MCP Gateway Hub, go to **MCP Servers** → **Add MCP Server**
|
||||
3. Enter the server details:
|
||||
- **URL**: Use the **container name** as the hostname (e.g., `http://weather-mcp-server:8116`)
|
||||
- **API Key**: The `MCP_REGISTRATION_API_KEY` from your `.env` file
|
||||
4. Click the connection test icon to verify connectivity
|
||||
5. Enable the server
|
||||
|
||||
> **Note:** The URL is the one the MCP Gateway uses, so for a container on the Gateway's network use its container name, not `localhost`.
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Credentials per tenant
|
||||
|
||||
This server does not hold credentials for its upstream. The MCP Gateway reads the tenant's credential from the Vault Service and sends it with each call, in `params._meta["com.kyndryl.mcp/connection"]`. The server advertises what it needs when the gateway calls `initialize`:
|
||||
|
||||
| Field | Required | Secret |
|
||||
|---|---|---|
|
||||
| `tenant_id` | no | no |
|
||||
| `client_id` | no | no |
|
||||
| `client_secret` | no | yes |
|
||||
| `scope_root` | yes | no |
|
||||
| `cloud` | no | no |
|
||||
|
||||
- In your tool code, read the connection with `get_connection()`, and reuse an upstream client with `get_upstream_client("<client kind>", build)`, which keeps one per kind and distinct connection.
|
||||
- `REQUIRE_VAULT_CONNECTION` (default `true`): a call that arrives without a connection is refused, instead of using this server's own environment. Set it to `false` only for local runs.
|
||||
- `verify_connection` is the tool the gateway calls to test a stored credential. It reports failure until you implement the check against the upstream.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Check it before you push
|
||||
|
||||
`tests/test_conformance.py` checks the running server against what the MCP Gateway expects: it
|
||||
refuses callers without its key, answers JSON-RPC correctly, and, if it declares credential fields,
|
||||
takes the account from each request, refuses a call that carries none, names a missing field, and
|
||||
never repeats a credential in a reply. It needs only `pytest` and `httpx` and imports nothing from
|
||||
the server.
|
||||
|
||||
```bash
|
||||
pip install pytest httpx
|
||||
# with the server running (see Quick Start) and its key from .env
|
||||
MCP_SERVER_URL=http://localhost:8116 MCP_REGISTRATION_API_KEY=<the key> pytest tests/ -v
|
||||
```
|
||||
|
||||
A check that fails says what to fix. Run it again after you implement your tools, since a tool that
|
||||
reads an environment variable for its credential, or repeats one in an error, fails it. Checks that
|
||||
do not apply (a server with no credential fields) are skipped, not passed. To run it with
|
||||
`REQUIRE_VAULT_CONNECTION=false` on your own machine, set `CONFORMANCE_EXPECT_FAIL_CLOSED=false`.
|
||||
|
||||
---
|
||||
|
||||
## 🚢 Deploying through the tools repository
|
||||
|
||||
To have CI build and deploy this server, put this folder in the root of the
|
||||
`modernization-tools-mcp-servers` repository as `solution-architecture-azure/`, then add it to
|
||||
`mcp_servers_to_deploy.yaml` in that repository with the instances it should
|
||||
run on:
|
||||
|
||||
```yaml
|
||||
- name: "solution-architecture-azure"
|
||||
instances:
|
||||
- az_dev
|
||||
```
|
||||
|
||||
The pipeline reads `kubernetes/configmap.yaml` for the server's name and port
|
||||
(`MCP_SERVER_NAME`, `SERVER_PORT`), generates the registration key and sets it
|
||||
in the pod, and registers the server with the MCP Gateway.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Logging
|
||||
|
||||
Every line the server writes to stdout is one JSON object (`timestamp`, `level`,
|
||||
`event`, `logger`, `server_id`, and for a request `request_id`, `method`, `tool`),
|
||||
including uvicorn's and your tools' own. Each request ends with one
|
||||
`mcp_request_completed` line carrying `outcome`, `duration_ms` and `error_code`.
|
||||
|
||||
- `LOG_LEVEL` sets the level (default `INFO`).
|
||||
- `LOG_FORMAT=console` prints readable lines instead, for local work.
|
||||
- In your tool code use the module's `logger`: `logger.info("fetched_issue", key=issue_key)`.
|
||||
- Do not log credentials, tokens or Authorization headers.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Development
|
||||
|
||||
### Implementing Tools
|
||||
|
||||
Open `server.py` and find the tool implementation functions. Each tool has a placeholder that needs to be implemented:
|
||||
|
||||
```python
|
||||
async def your_tool_name(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# TODO: Implement this tool
|
||||
raise NotImplementedError("Tool 'your_tool_name' needs implementation")
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Health check
|
||||
curl http://localhost:8116/health
|
||||
|
||||
# List tools
|
||||
curl -X POST http://localhost:8116/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $MCP_REGISTRATION_API_KEY" \
|
||||
-d '{"jsonrpc": "2.0", "id": "1", "method": "tools/list", "params": {}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
Generated by Agent Builder Platform - Kyndryl (template 1.1.0)
|
||||
@@ -0,0 +1,29 @@
|
||||
# Every package installed in a generated MCP server, pinned to one exact version:
|
||||
# the ones requirements.txt names and everything they bring in. They are
|
||||
# installed in the MCP server base image (Dockerfile.base), so every server
|
||||
# built from this template gets the same versions as the platform's own
|
||||
# services.
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
certifi==2026.10.19
|
||||
click==8.5.0
|
||||
fastapi==0.143.2
|
||||
h11==0.16.0
|
||||
httpcore==1.0.9
|
||||
httptools==0.9.0
|
||||
httpx==0.28.1
|
||||
idna==3.20
|
||||
opentelemetry-api==1.45.1
|
||||
pydantic==2.14.1
|
||||
pydantic-core==2.50.1
|
||||
python-dotenv==1.2.4
|
||||
pyyaml==6.0.3
|
||||
starlette==1.8.0
|
||||
structlog==26.1.0
|
||||
typing-extensions==4.16.0
|
||||
typing-inspection==0.4.4
|
||||
uvicorn==0.54.0
|
||||
uvloop==0.23.0
|
||||
watchfiles==1.3.0
|
||||
websockets==16.1.1
|
||||
@@ -0,0 +1,25 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>-config # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
data:
|
||||
|
||||
# Read by the CI/CD pipeline: the server's name, and the port it listens on
|
||||
# (used for the container, the Service and the probes)
|
||||
MCP_SERVER_NAME: "solution-architecture-azure"
|
||||
SERVER_PORT: "8116"
|
||||
|
||||
# One JSON object per line; LOG_FORMAT=console prints readable lines
|
||||
LOG_LEVEL: "INFO"
|
||||
LOG_FORMAT: "json"
|
||||
|
||||
# Leave on. The Gateway authenticates to this server with a bearer token, and
|
||||
# turning this off makes every tool callable by anything that can reach the
|
||||
# pod inside the cluster.
|
||||
REQUIRE_AUTH: "true"
|
||||
|
||||
# Refuse a call that arrives without the tenant's credential from the Vault Service
|
||||
REQUIRE_VAULT_CONNECTION: "true"
|
||||
|
||||
# Add your own settings here
|
||||
# EXAMPLE_SETTING: "value"
|
||||
@@ -0,0 +1,71 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- name: jfrog-secret
|
||||
containers:
|
||||
- name: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
image: <placeholder_for_image> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
name: http
|
||||
# Load all environment variables from ConfigMap
|
||||
envFrom:
|
||||
- secretRef:
|
||||
name: <placeholder_for_mcp_server_name>-secrets # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
optional: true # Won't fail if secret doesn't exist
|
||||
- secretRef:
|
||||
name: <placeholder_for_mcp_server_name>-dotenv-secrets # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
optional: true # Won't fail if secret doesn't exist
|
||||
- configMapRef:
|
||||
name: <placeholder_for_mcp_server_name>-config # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
# The registration key and server id are generated by the CI/CD pipeline;
|
||||
# the server needs the key to accept the Gateway's calls
|
||||
env:
|
||||
- name: MCP_REGISTRATION_API_KEY
|
||||
value: "<placeholder_for_registration_api_key>" # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
- name: MCP_SERVER_ID
|
||||
value: "<placeholder_for_server_id>" # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
resources:
|
||||
requests:
|
||||
memory: "128Mi"
|
||||
cpu: "10m"
|
||||
limits:
|
||||
memory: "1024Mi"
|
||||
cpu: "1000m"
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
initialDelaySeconds: 30 # Wait X seconds before first check
|
||||
periodSeconds: 15 # Check every X seconds
|
||||
timeoutSeconds: 10 # Each check can take up to X seconds to respond
|
||||
failureThreshold: 5 # Allow X consecutive failures before marking unhealthy
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
initialDelaySeconds: 30 # Wait X seconds before first check
|
||||
periodSeconds: 15 # Check every X seconds
|
||||
timeoutSeconds: 10 # Each check can take up to X seconds to respond
|
||||
failureThreshold: 5 # Allow X consecutive failures before marking unhealthy
|
||||
|
||||
# volumes:
|
||||
# - name: execution-storage
|
||||
# persistentVolumeClaim:
|
||||
# claimName: execution-storage-pvc # Same PVC name as core-components
|
||||
@@ -0,0 +1,20 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- configmap.yaml
|
||||
- secretnames.yaml
|
||||
|
||||
# Optionally add common labels
|
||||
|
||||
# Namespace for all resources
|
||||
namespace: mcp-servers
|
||||
labels:
|
||||
- includeSelectors: true
|
||||
pairs:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
environment: production
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
@@ -0,0 +1,7 @@
|
||||
# Do not modify this file, otherwise CI/CD pipeline will fail
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: mcp-servers
|
||||
labels:
|
||||
name: mcp-servers
|
||||
@@ -0,0 +1,18 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>-secrets
|
||||
type: Opaque
|
||||
data:
|
||||
# Base64 encoded values (NOT RECOMMENDED for sensitive data)
|
||||
# To encode: echo -n 'your-secret-value' | base64
|
||||
# Example: api-key: eW91ci1hcGkta2V5LXZhbHVl
|
||||
|
||||
stringData:
|
||||
# Plain text values saved on GitHub Secrets (RECOMMENDED)
|
||||
# Example:
|
||||
#
|
||||
# DB_PASSWORD: ${DB_PASSWORD_GITHUB_SECRET}
|
||||
# ANOTHER_SECRET: ${ANOTHER_GITHUB_SECRET}
|
||||
#
|
||||
# ${DB_PASSWORD_GITHUB_SECRET} and ${ANOTHER_GITHUB_SECRET} must exist as GitHub Secrets
|
||||
@@ -0,0 +1,33 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name>
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
targetPort: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
app: <placeholder_for_mcp_server_name>
|
||||
---
|
||||
# Optional: LoadBalancer service for external access
|
||||
# apiVersion: v1
|
||||
# kind: Service
|
||||
# metadata:
|
||||
# name: <placeholder_for_mcp_server_name>-external
|
||||
# labels:
|
||||
# app: <placeholder_for_mcp_server_name>
|
||||
# spec:
|
||||
# type: LoadBalancer
|
||||
# ports:
|
||||
# - port: 80
|
||||
# targetPort: 8080
|
||||
# protocol: TCP
|
||||
# name: http
|
||||
# selector:
|
||||
# app: <placeholder_for_mcp_server_name>
|
||||
@@ -0,0 +1,256 @@
|
||||
"""The connection a request carries: which upstream account this call is for.
|
||||
|
||||
An MCP server that talks to a third-party system needs that system's address and credentials. Taking
|
||||
them from environment variables makes one process serve one account for ever. Here the MCP Gateway
|
||||
sends them with each call, from the Vault Service, in MCP's own `_meta` field, under our vendor prefix:
|
||||
|
||||
initialize result _meta["com.kyndryl.mcp/connection-schema"] what this server needs (JSON Schema)
|
||||
_meta["com.kyndryl.mcp/verify-tool"] the tool that tests a connection
|
||||
tools/call, resources/read, prompts/get
|
||||
params._meta["com.kyndryl.mcp/connection"] the values, matching that schema
|
||||
|
||||
`_meta` is where the specification tells implementations to put their own data, so a client that does
|
||||
not know these keys ignores them. The values never travel in `arguments`, which is what the model
|
||||
writes and reads, so a credential cannot enter the model's context.
|
||||
|
||||
The connection is bound for the life of one request and read with `active()`. It is None when the caller
|
||||
sent nothing; whether the server may then use its own environment is decided in server.py
|
||||
(REQUIRE_VAULT_CONNECTION, which is on by default).
|
||||
|
||||
WHAT IS STANDARD AND WHAT IS OURS
|
||||
---------------------------------
|
||||
The mechanism is standard. `_meta` is the specification's sanctioned place for implementation-specific
|
||||
data, with formal key-naming rules (2026-07-28, "General fields / _meta"):
|
||||
|
||||
Prefix ... SHOULD use reverse DNS notation. Any prefix where the second label is
|
||||
`modelcontextprotocol` or `mcp` is reserved for MCP use ... third-party extensions use their own
|
||||
vendor prefix.
|
||||
|
||||
`com.kyndryl.mcp/` satisfies that: the second label is `kyndryl`, so it is a legitimate vendor prefix and
|
||||
not reserved. A client that does not recognise our keys ignores them, which is exactly what `_meta` is for.
|
||||
The value carried is a *separate* upstream credential, never the caller's own token (the specification
|
||||
says a server MUST NOT pass through the token it received from its client).
|
||||
|
||||
Only the three key names and the shape of their payloads are ours. When SEP-2127 (MCP Server Card) lands,
|
||||
the schema is what moves onto the card, and the key names are the only thing that changes.
|
||||
|
||||
The third key, VERIFY_TOOL_KEY, adds very little. Checking a credential is a plain `tools/call` against an
|
||||
ordinary tool that appears in `tools/list` like any other: no new method, no new transport. The only
|
||||
question that needed answering is WHICH tool, and the alternative was for the gateway to guess by name. A
|
||||
server that advertises nothing here is simply not verifiable.
|
||||
|
||||
STATELESSNESS
|
||||
-------------
|
||||
The 2026-07-28 specification made MCP explicitly stateless: "Servers MUST NOT rely on prior requests over
|
||||
the same connection to establish context ... Every request supplies this metadata in its _meta field."
|
||||
A module-level connection built once at import is exactly the state the specification tells servers not to
|
||||
keep. Binding the connection per request is therefore not only what multi-tenancy needs, it is what the
|
||||
protocol asks for.
|
||||
|
||||
HOW IT IS USED (server.py does all of this; a tool only calls get_connection())
|
||||
------------------------------------------------------------------------------
|
||||
import mcp_connection
|
||||
|
||||
# advertise, in the initialize result
|
||||
result["_meta"] = mcp_connection.schema_meta(CONNECTION_SCHEMA, verify_tool="verify_connection")
|
||||
|
||||
# bind, for the life of one request
|
||||
token = mcp_connection.bind(mcp_connection.from_params(request.params))
|
||||
try:
|
||||
... # mcp_connection.active() anywhere below
|
||||
finally:
|
||||
mcp_connection.unbind(token)
|
||||
|
||||
LOGS AND ERROR MESSAGES
|
||||
-----------------------
|
||||
`scrub()` is applied to every log line, and to the `error` text of a failed tool call, so the connection's
|
||||
values and credential-looking URL parameters (`?key=...`) never leave the process. `redact()` does the
|
||||
connection values alone. Neither is applied to a successful result: a presigned URL a tool returns on
|
||||
purpose must survive.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
VENDOR = "com.kyndryl.mcp"
|
||||
SCHEMA_KEY = f"{VENDOR}/connection-schema"
|
||||
CONNECTION_KEY = f"{VENDOR}/connection"
|
||||
VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool"
|
||||
|
||||
_active: contextvars.ContextVar[Optional[Dict[str, Any]]] = contextvars.ContextVar(
|
||||
"mcp_connection", default=None
|
||||
)
|
||||
|
||||
# Per process, so a fingerprint in a log cannot be checked against a guessed credential offline
|
||||
_FINGERPRINT_KEY = secrets.token_bytes(32)
|
||||
|
||||
|
||||
def schema_meta(schema: Dict[str, Any], verify_tool: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""The `_meta` object that advertises `schema` on an initialize result."""
|
||||
meta: Dict[str, Any] = {SCHEMA_KEY: schema}
|
||||
if verify_tool:
|
||||
meta[VERIFY_TOOL_KEY] = verify_tool
|
||||
return meta
|
||||
|
||||
|
||||
def verify_tool_from_initialize(result: Optional[Dict[str, Any]]) -> Optional[str]:
|
||||
"""The verify tool an initialize result advertises, or None.
|
||||
|
||||
The reader half of schema_meta, here rather than in the gateway so the two ends of the key cannot
|
||||
drift apart.
|
||||
"""
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
meta = result.get("_meta")
|
||||
if not isinstance(meta, dict):
|
||||
return None
|
||||
name = meta.get(VERIFY_TOOL_KEY)
|
||||
return name if isinstance(name, str) and name.strip() else None
|
||||
|
||||
|
||||
def from_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""The connection in a request's `params._meta`, or None.
|
||||
|
||||
Anything that is not an object counts as absent: a malformed connection must not be more
|
||||
powerful than none at all.
|
||||
"""
|
||||
if not isinstance(params, dict):
|
||||
return None
|
||||
meta = params.get("_meta")
|
||||
if not isinstance(meta, dict):
|
||||
return None
|
||||
profile = meta.get(CONNECTION_KEY)
|
||||
return profile if isinstance(profile, dict) and profile else None
|
||||
|
||||
|
||||
def bind(profile: Optional[Dict[str, Any]]) -> contextvars.Token:
|
||||
"""Make `profile` the connection for this request."""
|
||||
return _active.set(profile)
|
||||
|
||||
|
||||
def unbind(token: contextvars.Token) -> None:
|
||||
try:
|
||||
_active.reset(token)
|
||||
except ValueError:
|
||||
_active.set(None)
|
||||
|
||||
|
||||
def active() -> Optional[Dict[str, Any]]:
|
||||
"""The connection for this request, or None."""
|
||||
return _active.get()
|
||||
|
||||
|
||||
def fingerprint(profile: Optional[Dict[str, Any]]) -> str:
|
||||
"""A short id for a connection, safe to log and to cache on; the credential never is the key."""
|
||||
if not profile:
|
||||
return "env"
|
||||
canonical = json.dumps(profile, sort_keys=True, separators=(",", ":"), default=str)
|
||||
return hmac.new(_FINGERPRINT_KEY, canonical.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
|
||||
|
||||
|
||||
def redact(text: Any) -> str:
|
||||
"""`text` with every value of this request's connection replaced, for logs and error replies.
|
||||
|
||||
A tool can put a credential in an exception message without meaning to. Values shorter than four
|
||||
characters are left alone: replacing them would garble ordinary text.
|
||||
"""
|
||||
result = str(text)
|
||||
values = [v for v in (active() or {}).values() if isinstance(v, str) and len(v) >= 4]
|
||||
for value in sorted(values, key=len, reverse=True):
|
||||
result = result.replace(value, "[redacted]")
|
||||
return result
|
||||
|
||||
|
||||
# Query parameters that carry a credential in the URL of an upstream request
|
||||
_URL_CREDENTIAL = re.compile(
|
||||
r"([?&;](?:api[_-]?key|apikey|key|token|access[_-]?token|auth|secret|password|passwd|"
|
||||
r"client[_-]?secret|appid|app[_-]?id|sig|signature)=)[^&\s\"'#<>]+",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def scrub(value: Any, _depth: int = 0) -> Any:
|
||||
"""`value` with credentials taken out, for anything that is logged or sent back to a caller.
|
||||
|
||||
Strings lose the request's connection values and the value of any credential query parameter in a
|
||||
URL (`?key=...`); dicts, lists and tuples are scrubbed inside. Anything else is returned as it is.
|
||||
Not for tool results in general: a presigned URL a tool returns on purpose would be damaged.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
return _URL_CREDENTIAL.sub(r"\1[redacted]", redact(value))
|
||||
if _depth > 5:
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {k: scrub(v, _depth + 1) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return type(value)(scrub(v, _depth + 1) for v in value)
|
||||
return value
|
||||
|
||||
|
||||
def missing_fields(profile: Optional[Dict[str, Any]], schema: Dict[str, Any]) -> List[str]:
|
||||
"""The required fields of `schema` that `profile` does not supply."""
|
||||
if not profile:
|
||||
return []
|
||||
required = schema.get("required") or []
|
||||
return [name for name in required if not str(profile.get(name) or "").strip()]
|
||||
|
||||
|
||||
def install_invalid_request_handler(app: Any, on_invalid: Optional[Callable[[str], None]] = None) -> None:
|
||||
"""Answer a request that is not valid JSON-RPC with a JSON-RPC error that does not repeat the request.
|
||||
|
||||
FastAPI's own answer (HTTP 422) repeats the request body under "input". The body is where the gateway puts
|
||||
the tenant's connection, so a request that is merely malformed (no "id", say) would get the credential back
|
||||
in the reply, and in the log of anything that records replies. The status stays 422; the body is a JSON-RPC
|
||||
error (-32600) that names only the fields at fault. `on_invalid`, if given, is called with that text, already
|
||||
reduced to harmless characters, so the caller can log it in its own style.
|
||||
|
||||
Call it once, right after `app = FastAPI(...)`. FastAPI is imported here, not at module level, so the rest of
|
||||
this module stays importable without it.
|
||||
"""
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def invalid_request(request, exc):
|
||||
names = {
|
||||
"body" if error.get("type") == "json_invalid" else ".".join(str(p) for p in error.get("loc", ())[1:]) or "body"
|
||||
for error in exc.errors()
|
||||
}
|
||||
fields = re.sub(r"[^\w.\-, ]", "?", ", ".join(sorted(names)))[:200]
|
||||
if on_invalid is not None:
|
||||
on_invalid(fields)
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"result": None,
|
||||
"error": {"code": -32600, "message": "Invalid request: check " + fields},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"install_invalid_request_handler",
|
||||
"VENDOR",
|
||||
"SCHEMA_KEY",
|
||||
"CONNECTION_KEY",
|
||||
"VERIFY_TOOL_KEY",
|
||||
"schema_meta",
|
||||
"verify_tool_from_initialize",
|
||||
"from_params",
|
||||
"bind",
|
||||
"unbind",
|
||||
"active",
|
||||
"fingerprint",
|
||||
"redact",
|
||||
"scrub",
|
||||
"missing_fields",
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
# MCP Server Dependencies
|
||||
# Generated by Agent Builder Platform
|
||||
|
||||
# Each dependency is pinned to one exact version, and constraints.txt pins everything they bring
|
||||
# in, so two builds of the same server get the same packages -- the same versions as the
|
||||
# platform's own services. The packages below are already installed in the MCP server base
|
||||
# image the Dockerfile builds on; a package added to this file is installed on top of them at
|
||||
# build time. Changing the version of one the base has stops the build: the base image moves
|
||||
# those, with the template.
|
||||
|
||||
# Core Framework
|
||||
# FastAPI - Modern web framework for MCP server
|
||||
fastapi==0.143.2
|
||||
|
||||
# ASGI Server
|
||||
# Uvicorn - Lightning-fast ASGI server
|
||||
uvicorn[standard]==0.54.0
|
||||
|
||||
# Data Validation
|
||||
# Pydantic - Data validation using Python type hints
|
||||
pydantic==2.14.1
|
||||
|
||||
# HTTP Client
|
||||
# HTTPX - Async HTTP client for API calls
|
||||
httpx==0.28.1
|
||||
|
||||
# Environment Variables
|
||||
# python-dotenv - Load environment from .env files
|
||||
python-dotenv==1.2.4
|
||||
|
||||
# Structured Logging
|
||||
# structlog - JSON log lines (see LOG_FORMAT in server.py)
|
||||
structlog==26.1.0
|
||||
|
||||
# Optional: Add your custom dependencies below
|
||||
# requests>=2.31.0
|
||||
# aiofiles>=23.2.1
|
||||
# sqlalchemy>=2.0.0
|
||||
# redis>=5.0.0
|
||||
|
||||
# Added by this server's definition
|
||||
boto3==1.43.122
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,360 @@
|
||||
"""Conformance checks for an MCP server that takes its upstream credentials from the MCP Gateway.
|
||||
|
||||
Run these against a running server before you push it. They need only `pytest` and `httpx`, import
|
||||
nothing from the server and talk to it over HTTP, so they work on a server from the MCP Server
|
||||
Builder and on one written by hand.
|
||||
|
||||
pip install pytest httpx
|
||||
MCP_SERVER_URL=http://localhost:8100 MCP_REGISTRATION_API_KEY=<the server's key> pytest tests/ -v
|
||||
|
||||
What is checked, and why:
|
||||
|
||||
Protocol the server answers /health, refuses callers without its key, and speaks JSON-RPC
|
||||
correctly (initialize, tools/list, ids echoed, errors as errors).
|
||||
Connection a server that needs an upstream account says so in its initialize result
|
||||
(`_meta["com.kyndryl.mcp/connection-schema"]`) and takes the account from each
|
||||
request (`params._meta["com.kyndryl.mcp/connection"]`), not from its own environment.
|
||||
Such a server refuses a call that carries none (fail closed), reports which required
|
||||
field is missing, takes nothing from `arguments`, and never repeats a credential in a
|
||||
reply (the values of fields marked `writeOnly`; every value if none is marked). A server that needs no account skips these checks.
|
||||
|
||||
Settings (environment variables):
|
||||
|
||||
MCP_SERVER_URL default http://localhost:8100
|
||||
MCP_REGISTRATION_API_KEY the key the server was started with (required unless the
|
||||
server has authentication switched off)
|
||||
CONFORMANCE_EXPECT_FAIL_CLOSED default true. Set false only for a server you run locally
|
||||
with REQUIRE_VAULT_CONNECTION=false, so that checks which
|
||||
need a refusal are skipped rather than failed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
VENDOR = "com.kyndryl.mcp"
|
||||
SCHEMA_KEY = f"{VENDOR}/connection-schema"
|
||||
VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool"
|
||||
CONNECTION_KEY = f"{VENDOR}/connection"
|
||||
|
||||
BASE_URL = os.getenv("MCP_SERVER_URL", "http://localhost:8100").rstrip("/")
|
||||
API_KEY = os.getenv("MCP_REGISTRATION_API_KEY", "")
|
||||
EXPECT_FAIL_CLOSED = os.getenv("CONFORMANCE_EXPECT_FAIL_CLOSED", "true").strip().lower() != "false"
|
||||
|
||||
# A value no server could contain by accident, so finding it in a reply means the server repeated it.
|
||||
SENTINEL = f"sentinel-{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ helpers
|
||||
|
||||
|
||||
def auth_headers(key: Optional[str] = None) -> Dict[str, str]:
|
||||
key = API_KEY if key is None else key
|
||||
return {"Authorization": f"Bearer {key}"} if key else {}
|
||||
|
||||
|
||||
def rpc(
|
||||
client: httpx.Client,
|
||||
method: str,
|
||||
params: Optional[Dict[str, Any]] = None,
|
||||
*,
|
||||
request_id: Any = "1",
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
) -> httpx.Response:
|
||||
return client.post(
|
||||
"/messages",
|
||||
json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}},
|
||||
headers=auth_headers() if headers is None else headers,
|
||||
)
|
||||
|
||||
|
||||
def result_of(client: httpx.Client, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
response = rpc(client, method, params)
|
||||
assert response.status_code == 200, f"{method} answered HTTP {response.status_code}: {response.text[:300]}"
|
||||
body = response.json()
|
||||
assert not body.get("error"), f"{method} returned an error: {body['error']}"
|
||||
return body["result"]
|
||||
|
||||
|
||||
def with_connection(params: Dict[str, Any], connection: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
if connection is None:
|
||||
return params
|
||||
return {**params, "_meta": {CONNECTION_KEY: connection}}
|
||||
|
||||
|
||||
def value_for(name: str, spec: Dict[str, Any]) -> Any:
|
||||
"""A value of the right shape for a connection field, carrying the sentinel."""
|
||||
kind = spec.get("type", "string")
|
||||
if kind == "string" and spec.get("format") == "uri":
|
||||
return f"https://{SENTINEL}.invalid"
|
||||
if kind == "integer":
|
||||
return 12345
|
||||
if kind == "boolean":
|
||||
return True
|
||||
return f"{SENTINEL}-{name}"
|
||||
|
||||
|
||||
def full_connection(schema: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {name: value_for(name, spec) for name, spec in (schema.get("properties") or {}).items()}
|
||||
|
||||
|
||||
def secret_values(schema: Dict[str, Any]) -> List[str]:
|
||||
"""The sent values that must never come back: those of fields marked secret (`writeOnly`).
|
||||
|
||||
A tool may repeat a base URL or a region. If the server marks no field secret, every value is
|
||||
treated as one, because then nothing says which are safe to repeat.
|
||||
"""
|
||||
connection = full_connection(schema)
|
||||
properties = schema.get("properties") or {}
|
||||
marked = [n for n, spec in properties.items() if spec.get("writeOnly")]
|
||||
return [str(connection[n]) for n in (marked or list(properties))]
|
||||
|
||||
|
||||
def repeated(response: httpx.Response, schema: Dict[str, Any]) -> List[str]:
|
||||
return [v for v in secret_values(schema) if v in response.text]
|
||||
|
||||
|
||||
def _string_values(node: Any) -> List[str]:
|
||||
"""Every string anywhere in a JSON value."""
|
||||
if isinstance(node, str):
|
||||
return [node]
|
||||
if isinstance(node, dict):
|
||||
return [v for item in node.values() for v in _string_values(item)]
|
||||
if isinstance(node, list):
|
||||
return [v for item in node for v in _string_values(item)]
|
||||
return []
|
||||
|
||||
|
||||
def call(client: httpx.Client, tool: str, connection: Optional[Dict[str, Any]], arguments: Optional[Dict] = None):
|
||||
return rpc(client, "tools/call", with_connection({"name": tool, "arguments": arguments or {}}, connection))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
with httpx.Client(base_url=BASE_URL, timeout=30.0) as session:
|
||||
try:
|
||||
session.get("/health")
|
||||
except httpx.HTTPError as error:
|
||||
pytest.exit(f"Cannot reach the server at {BASE_URL}: {error}. Start it, or set MCP_SERVER_URL.", 2)
|
||||
yield session
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def initialize(client) -> Dict[str, Any]:
|
||||
return result_of(client, "initialize", {"protocolVersion": "1.0.0", "clientInfo": {"name": "conformance"}})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tools(client) -> List[Dict[str, Any]]:
|
||||
return result_of(client, "tools/list")["tools"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def schema(initialize) -> Optional[Dict[str, Any]]:
|
||||
return (initialize.get("_meta") or {}).get(SCHEMA_KEY)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def needs_connection(schema) -> Dict[str, Any]:
|
||||
if not schema or not schema.get("properties"):
|
||||
pytest.skip("the server advertises no connection fields, so it takes no per-request credentials")
|
||||
return schema
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def probe_tool(initialize, tools) -> str:
|
||||
"""The tool to call in the connection checks: the verify tool when there is one."""
|
||||
verify = (initialize.get("_meta") or {}).get(VERIFY_TOOL_KEY)
|
||||
if verify:
|
||||
return verify
|
||||
assert tools, "the server lists no tools to call"
|
||||
return tools[0]["name"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ protocol
|
||||
|
||||
|
||||
def test_health_answers(client):
|
||||
assert client.get("/health").status_code == 200
|
||||
|
||||
|
||||
def test_the_public_auth_endpoint_reveals_no_key(client):
|
||||
response = client.get("/.well-known/mcp-auth")
|
||||
if response.status_code == 404:
|
||||
pytest.skip("the server has no /.well-known/mcp-auth endpoint")
|
||||
assert response.status_code == 200
|
||||
if API_KEY:
|
||||
# A value that equals the key is always a leak. A short key can also appear inside ordinary words
|
||||
# ("nc" in "auth_required"), so searching the text for it is only meaningful for a real-length key.
|
||||
assert API_KEY not in _string_values(response.json()), "/.well-known/mcp-auth returns the server's key"
|
||||
if len(API_KEY) >= 12:
|
||||
assert API_KEY not in response.text, "/.well-known/mcp-auth returns the server's key"
|
||||
|
||||
|
||||
def test_a_call_without_the_servers_key_is_refused(client):
|
||||
response = rpc(client, "tools/list", headers={})
|
||||
assert response.status_code in (401, 403), f"answered HTTP {response.status_code} to a caller with no key"
|
||||
|
||||
|
||||
def test_a_call_with_the_wrong_key_is_refused(client):
|
||||
response = rpc(client, "tools/list", headers=auth_headers("not-the-key-" + uuid.uuid4().hex))
|
||||
assert response.status_code in (401, 403), f"answered HTTP {response.status_code} to a caller with the wrong key"
|
||||
|
||||
|
||||
def test_initialize_describes_the_server(initialize):
|
||||
assert initialize["serverInfo"]["name"]
|
||||
assert isinstance(initialize.get("capabilities"), dict)
|
||||
|
||||
|
||||
def test_tools_have_a_name_a_description_and_an_object_schema(tools):
|
||||
assert isinstance(tools, list)
|
||||
names = [t["name"] for t in tools]
|
||||
assert len(names) == len(set(names)), "two tools share a name"
|
||||
for tool in tools:
|
||||
assert tool["name"] and tool.get("description"), f"tool {tool.get('name')!r} lacks a name or description"
|
||||
assert tool["inputSchema"]["type"] == "object", f"{tool['name']} has no object inputSchema"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_id", ["conformance-1", 7])
|
||||
def test_the_reply_echoes_the_request_id(client, request_id):
|
||||
response = rpc(client, "tools/list", request_id=request_id)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == request_id
|
||||
|
||||
|
||||
def test_an_unknown_method_is_an_error_not_a_crash(client):
|
||||
response = rpc(client, "no/such/method")
|
||||
assert response.status_code == 200
|
||||
assert response.json().get("error"), "an unknown method returned no error"
|
||||
|
||||
|
||||
def test_an_unknown_tool_is_an_error_not_a_crash(client):
|
||||
response = rpc(client, "tools/call", {"name": f"no_such_tool_{uuid.uuid4().hex[:8]}", "arguments": {}})
|
||||
assert response.status_code == 200
|
||||
assert response.json().get("error"), "an unknown tool returned no error"
|
||||
|
||||
|
||||
def test_arguments_that_are_not_an_object_are_the_callers_mistake(client, tools, schema):
|
||||
params = {"name": tools[0]["name"], "arguments": ["not", "an", "object"]}
|
||||
# With a connection, when the server wants one: a refusal for lacking it would answer -32602 too
|
||||
response = rpc(client, "tools/call", with_connection(params, full_connection(schema) if schema else None))
|
||||
assert response.status_code == 200
|
||||
error = response.json().get("error")
|
||||
assert error and error.get("code") == -32602, f"expected invalid params (-32602), got: {response.text[:300]}"
|
||||
|
||||
|
||||
def test_an_invalid_request_does_not_repeat_what_it_carried():
|
||||
# No "id": the request is not valid JSON-RPC, and what it carried (a connection) must not come back.
|
||||
# It has a connection of its own: a server that answers a bad request by dropping the connection (an
|
||||
# unhandled error makes uvicorn do that) must not make the NEXT check fail with "connection reset".
|
||||
marker = f"{SENTINEL}-carried"
|
||||
try:
|
||||
response = httpx.post(
|
||||
f"{BASE_URL}/messages",
|
||||
json={"jsonrpc": "2.0", "method": "tools/list", "params": {"_meta": {CONNECTION_KEY: {"field": marker}}}},
|
||||
headers=auth_headers(),
|
||||
timeout=30.0,
|
||||
)
|
||||
except httpx.TransportError:
|
||||
return # nothing came back, so nothing was repeated
|
||||
assert marker not in response.text, "the reply to an invalid request repeated the request"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ connection
|
||||
|
||||
|
||||
def test_the_connection_schema_is_a_json_schema_object(needs_connection):
|
||||
assert needs_connection["type"] == "object"
|
||||
properties = needs_connection["properties"]
|
||||
assert isinstance(properties, dict) and properties
|
||||
assert set(needs_connection.get("required", [])) <= set(properties), "a required field is not a property"
|
||||
|
||||
|
||||
def test_the_verify_tool_is_listed(initialize, tools, needs_connection):
|
||||
verify = (initialize.get("_meta") or {}).get(VERIFY_TOOL_KEY)
|
||||
assert verify, f"initialize does not name a verify tool in _meta[{VERIFY_TOOL_KEY!r}]"
|
||||
assert verify in [t["name"] for t in tools], f"the verify tool {verify!r} is not in tools/list"
|
||||
|
||||
|
||||
def test_a_call_with_no_connection_is_refused(client, needs_connection, probe_tool):
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
response = call(client, probe_tool, None)
|
||||
assert response.json().get("error"), (
|
||||
"a call with no connection was served. The server is using its own environment for the "
|
||||
"upstream account, so every tenant would share one. Refuse it (REQUIRE_VAULT_CONNECTION)."
|
||||
)
|
||||
|
||||
|
||||
def test_a_connection_in_the_arguments_is_not_accepted(client, needs_connection, probe_tool):
|
||||
"""The credential travels in `_meta`, which the model never sees; one in `arguments` is not one."""
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
response = call(client, probe_tool, None, arguments=full_connection(needs_connection))
|
||||
assert response.json().get("error"), "a connection passed as tool arguments was accepted"
|
||||
assert not repeated(response, needs_connection), "the reply repeats a credential that was sent as an argument"
|
||||
|
||||
|
||||
def test_a_call_with_a_connection_is_not_refused_for_lacking_one(client, needs_connection, probe_tool):
|
||||
response = call(client, probe_tool, full_connection(needs_connection))
|
||||
assert response.status_code == 200
|
||||
error = response.json().get("error") or {}
|
||||
message = str(error.get("message", "")).lower()
|
||||
assert "no connection" not in message and "missing" not in message, (
|
||||
f"a complete connection was refused as incomplete: {error}"
|
||||
)
|
||||
|
||||
|
||||
def test_an_incomplete_connection_names_what_is_missing(client, needs_connection, probe_tool):
|
||||
required = list(needs_connection.get("required", []))
|
||||
if not required:
|
||||
pytest.skip("no field is required")
|
||||
connection = full_connection(needs_connection)
|
||||
dropped = required[-1]
|
||||
connection.pop(dropped)
|
||||
if not connection:
|
||||
# The only field is required, and an empty connection counts as none. Send one that has a value
|
||||
# but not the field, which is what a mistyped field name in the credential looks like.
|
||||
connection = {"not_a_field_of_this_server": "x"}
|
||||
|
||||
response = call(client, probe_tool, connection)
|
||||
error = response.json().get("error")
|
||||
assert error, f"a connection without the required field {dropped!r} was served"
|
||||
assert dropped in str(error.get("message", "")), f"the refusal does not name the missing field {dropped!r}: {error}"
|
||||
assert not repeated(response, needs_connection), "the refusal repeats a credential value"
|
||||
|
||||
|
||||
def test_no_reply_repeats_the_credential(client, needs_connection, probe_tool, tools):
|
||||
connection = full_connection(needs_connection)
|
||||
replies = [call(client, probe_tool, connection)]
|
||||
for tool in tools[:5]:
|
||||
replies.append(call(client, tool["name"], connection, arguments={"conformance": "probe"}))
|
||||
replies.append(call(client, "no_such_tool", connection))
|
||||
for response in replies:
|
||||
assert not repeated(response, needs_connection), f"a reply repeats the credential: {response.text[:300]}"
|
||||
|
||||
|
||||
def test_a_malformed_connection_is_no_better_than_none(client, needs_connection, probe_tool):
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
for bad in ("just-a-string", ["a", "list"], 42):
|
||||
params = {"name": probe_tool, "arguments": {}, "_meta": {CONNECTION_KEY: bad}}
|
||||
body = rpc(client, "tools/call", params).json()
|
||||
assert body.get("error"), f"a connection of type {type(bad).__name__} was served"
|
||||
|
||||
|
||||
def test_resources_and_prompts_are_listed_when_advertised(client, initialize):
|
||||
capabilities = initialize.get("capabilities") or {}
|
||||
if capabilities.get("resources"):
|
||||
assert isinstance(result_of(client, "resources/list")["resources"], list)
|
||||
if capabilities.get("prompts"):
|
||||
assert isinstance(result_of(client, "prompts/list")["prompts"], list)
|
||||
@@ -0,0 +1,495 @@
|
||||
# Generated by build_definitions.py; don't edit by hand.
|
||||
# Credentials arrive per call from the Vault Service. Store them per project.
|
||||
|
||||
server_id: sa-gcp-cloud
|
||||
name: Solution Architecture Google Cloud
|
||||
description: Google Cloud documentation and read-only estate tools for the Solution Architecture agent, through Google's hosted
|
||||
MCP servers.
|
||||
version: 0.1.0
|
||||
port: 8115
|
||||
verify_tool: gcp_check_connection
|
||||
shared_code:
|
||||
- ../../../mcp-servers/_common/tool_support.py
|
||||
- ../../../mcp-servers/_common/gcp_support.py
|
||||
- _support/docs_log.py
|
||||
- _support/gcp_tools.py
|
||||
extra_requirements:
|
||||
- google-auth==2.62.0
|
||||
- requests==2.32.5
|
||||
connection_fields:
|
||||
- name: service_account_json
|
||||
title: Service account key
|
||||
description: The read-only service account's JSON key.
|
||||
required: true
|
||||
secret: true
|
||||
- name: scope_root
|
||||
title: Scope root
|
||||
description: organizations/<id>, folders/<id> or projects/<id>.
|
||||
required: true
|
||||
secret: false
|
||||
- name: quota_project
|
||||
title: Quota project
|
||||
description: Sent as X-Goog-User-Project. Optional.
|
||||
required: false
|
||||
secret: false
|
||||
- name: docs_api_key
|
||||
title: Documentation API key
|
||||
description: Developer Knowledge API key. Without it, the service account signs in.
|
||||
required: false
|
||||
secret: true
|
||||
tools:
|
||||
- name: gcp_check_connection
|
||||
display_name: Gcp check connection
|
||||
description: 'Test the stored connection: sign in and open the resource manager server.'
|
||||
parameters: []
|
||||
ai_implementation: "async def gcp_check_connection(arguments: Dict[str, Any]) -> Dict[str, Any]:\n try:\n await\
|
||||
\ _gcp_mcp_session(\"resource_manager\")\n except Exception as error:\n return {\"ok\": False, \"message\":\
|
||||
\ _upstream_failed(\"gcp\", error)[\"error\"][\"message\"]}\n return {\"ok\": True, \"message\": \"Signed in and reached\
|
||||
\ Google's hosted servers.\"}\n"
|
||||
- name: gcp_describe_tool
|
||||
display_name: Gcp describe tool
|
||||
description: Read a hosted tool's live description and argument schema, before calling it.
|
||||
parameters:
|
||||
- name: server
|
||||
type: string
|
||||
description: The hosted server, such as compute.
|
||||
required: true
|
||||
- name: tool
|
||||
type: string
|
||||
description: The hosted tool, such as list_instances.
|
||||
required: true
|
||||
ai_implementation: "async def gcp_describe_tool(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_describe(arguments)\n"
|
||||
- name: gcp_developer_knowledge_search_documents
|
||||
display_name: Gcp developer knowledge search documents
|
||||
description: Google's search_documents on its developer_knowledge MCP server, read-only. Call gcp_describe_tool for its
|
||||
arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_developer_knowledge_search_documents(arguments: Dict[str, Any]) -> Dict[str, Any]:\n \
|
||||
\ return await _gcp_forward(\"gcp_developer_knowledge_search_documents\", \"developer_knowledge\", \"search_documents\"\
|
||||
, arguments)\n"
|
||||
- name: gcp_developer_knowledge_get_documents
|
||||
display_name: Gcp developer knowledge get documents
|
||||
description: Google's get_documents on its developer_knowledge MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_developer_knowledge_get_documents(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_developer_knowledge_get_documents\", \"developer_knowledge\", \"get_documents\", arguments)\n"
|
||||
- name: gcp_developer_knowledge_answer_query
|
||||
display_name: Gcp developer knowledge answer query
|
||||
description: Google's answer_query on its developer_knowledge MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_developer_knowledge_answer_query(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_developer_knowledge_answer_query\", \"developer_knowledge\", \"answer_query\", arguments)\n"
|
||||
- name: gcp_resource_manager_search_projects
|
||||
display_name: Gcp resource manager search projects
|
||||
description: Google's search_projects on its resource_manager MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_resource_manager_search_projects(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_resource_manager_search_projects\", \"resource_manager\", \"search_projects\", arguments)\n"
|
||||
- name: gcp_asset_inventory_list_assets
|
||||
display_name: Gcp asset inventory list assets
|
||||
description: Google's list_assets on its asset_inventory MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_asset_inventory_list_assets(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_asset_inventory_list_assets\", \"asset_inventory\", \"list_assets\", arguments)\n"
|
||||
- name: gcp_asset_inventory_analyze_iam_policy
|
||||
display_name: Gcp asset inventory analyze iam policy
|
||||
description: Google's analyze_iam_policy on its asset_inventory MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_asset_inventory_analyze_iam_policy(arguments: Dict[str, Any]) -> Dict[str, Any]:\n \
|
||||
\ return await _gcp_forward(\"gcp_asset_inventory_analyze_iam_policy\", \"asset_inventory\", \"analyze_iam_policy\", arguments)\n"
|
||||
- name: gcp_compute_list_instances
|
||||
display_name: Gcp compute list instances
|
||||
description: Google's list_instances on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_instances(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_compute_list_instances\", \"compute\", \"list_instances\", arguments)\n"
|
||||
- name: gcp_compute_get_instance_basic_info
|
||||
display_name: Gcp compute get instance basic info
|
||||
description: Google's get_instance_basic_info on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_get_instance_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_compute_get_instance_basic_info\", \"compute\", \"get_instance_basic_info\", arguments)\n"
|
||||
- name: gcp_compute_list_instance_attached_disks
|
||||
display_name: Gcp compute list instance attached disks
|
||||
description: Google's list_instance_attached_disks on its compute MCP server, read-only. Call gcp_describe_tool for its
|
||||
arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_instance_attached_disks(arguments: Dict[str, Any]) -> Dict[str, Any]:\n \
|
||||
\ return await _gcp_forward(\"gcp_compute_list_instance_attached_disks\", \"compute\", \"list_instance_attached_disks\"\
|
||||
, arguments)\n"
|
||||
- name: gcp_compute_list_instance_group_managers
|
||||
display_name: Gcp compute list instance group managers
|
||||
description: Google's list_instance_group_managers on its compute MCP server, read-only. Call gcp_describe_tool for its
|
||||
arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_instance_group_managers(arguments: Dict[str, Any]) -> Dict[str, Any]:\n \
|
||||
\ return await _gcp_forward(\"gcp_compute_list_instance_group_managers\", \"compute\", \"list_instance_group_managers\"\
|
||||
, arguments)\n"
|
||||
- name: gcp_compute_get_instance_group_manager_basic_info
|
||||
display_name: Gcp compute get instance group manager basic info
|
||||
description: Google's get_instance_group_manager_basic_info on its compute MCP server, read-only. Call gcp_describe_tool
|
||||
for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_get_instance_group_manager_basic_info(arguments: Dict[str, Any]) -> Dict[str,\
|
||||
\ Any]:\n return await _gcp_forward(\"gcp_compute_get_instance_group_manager_basic_info\", \"compute\", \"get_instance_group_manager_basic_info\"\
|
||||
, arguments)\n"
|
||||
- name: gcp_compute_list_instance_templates
|
||||
display_name: Gcp compute list instance templates
|
||||
description: Google's list_instance_templates on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_instance_templates(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_compute_list_instance_templates\", \"compute\", \"list_instance_templates\", arguments)\n"
|
||||
- name: gcp_compute_get_instance_template_properties
|
||||
display_name: Gcp compute get instance template properties
|
||||
description: Google's get_instance_template_properties on its compute MCP server, read-only. Call gcp_describe_tool for
|
||||
its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_get_instance_template_properties(arguments: Dict[str, Any]) -> Dict[str, Any]:\n\
|
||||
\ return await _gcp_forward(\"gcp_compute_get_instance_template_properties\", \"compute\", \"get_instance_template_properties\"\
|
||||
, arguments)\n"
|
||||
- name: gcp_compute_list_disks
|
||||
display_name: Gcp compute list disks
|
||||
description: Google's list_disks on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_disks(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_compute_list_disks\", \"compute\", \"list_disks\", arguments)\n"
|
||||
- name: gcp_compute_get_disk_basic_info
|
||||
display_name: Gcp compute get disk basic info
|
||||
description: Google's get_disk_basic_info on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_get_disk_basic_info(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_compute_get_disk_basic_info\", \"compute\", \"get_disk_basic_info\", arguments)\n"
|
||||
- name: gcp_compute_list_reservations
|
||||
display_name: Gcp compute list reservations
|
||||
description: Google's list_reservations on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_reservations(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_compute_list_reservations\", \"compute\", \"list_reservations\", arguments)\n"
|
||||
- name: gcp_compute_list_commitments
|
||||
display_name: Gcp compute list commitments
|
||||
description: Google's list_commitments on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_compute_list_commitments(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_compute_list_commitments\", \"compute\", \"list_commitments\", arguments)\n"
|
||||
- name: gcp_gke_list_clusters
|
||||
display_name: Gcp gke list clusters
|
||||
description: Google's list_clusters on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_gke_list_clusters(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_gke_list_clusters\", \"gke\", \"list_clusters\", arguments)\n"
|
||||
- name: gcp_gke_get_cluster
|
||||
display_name: Gcp gke get cluster
|
||||
description: Google's get_cluster on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_gke_get_cluster(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_gke_get_cluster\", \"gke\", \"get_cluster\", arguments)\n"
|
||||
- name: gcp_gke_list_node_pools
|
||||
display_name: Gcp gke list node pools
|
||||
description: Google's list_node_pools on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_gke_list_node_pools(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_gke_list_node_pools\", \"gke\", \"list_node_pools\", arguments)\n"
|
||||
- name: gcp_gke_get_node_pool
|
||||
display_name: Gcp gke get node pool
|
||||
description: Google's get_node_pool on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_gke_get_node_pool(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_gke_get_node_pool\", \"gke\", \"get_node_pool\", arguments)\n"
|
||||
- name: gcp_gke_get_k8s_version
|
||||
display_name: Gcp gke get k8s version
|
||||
description: Google's get_k8s_version on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_gke_get_k8s_version(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_gke_get_k8s_version\", \"gke\", \"get_k8s_version\", arguments)\n"
|
||||
- name: gcp_cloud_run_list_services
|
||||
display_name: Gcp cloud run list services
|
||||
description: Google's list_services on its cloud_run MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_cloud_run_list_services(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_cloud_run_list_services\", \"cloud_run\", \"list_services\", arguments)\n"
|
||||
- name: gcp_cloud_run_get_service
|
||||
display_name: Gcp cloud run get service
|
||||
description: Google's get_service on its cloud_run MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_cloud_run_get_service(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_cloud_run_get_service\", \"cloud_run\", \"get_service\", arguments)\n"
|
||||
- name: gcp_cloud_sql_list_instances
|
||||
display_name: Gcp cloud sql list instances
|
||||
description: Google's list_instances on its cloud_sql MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_cloud_sql_list_instances(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_cloud_sql_list_instances\", \"cloud_sql\", \"list_instances\", arguments)\n"
|
||||
- name: gcp_cloud_sql_get_instance
|
||||
display_name: Gcp cloud sql get instance
|
||||
description: Google's get_instance on its cloud_sql MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_cloud_sql_get_instance(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_cloud_sql_get_instance\", \"cloud_sql\", \"get_instance\", arguments)\n"
|
||||
- name: gcp_storage_list_buckets
|
||||
display_name: Gcp storage list buckets
|
||||
description: Google's list_buckets on its storage MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_storage_list_buckets(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_storage_list_buckets\", \"storage\", \"list_buckets\", arguments)\n"
|
||||
- name: gcp_pubsub_list_topics
|
||||
display_name: Gcp pubsub list topics
|
||||
description: Google's list_topics on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_pubsub_list_topics(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_pubsub_list_topics\", \"pubsub\", \"list_topics\", arguments)\n"
|
||||
- name: gcp_pubsub_get_topic
|
||||
display_name: Gcp pubsub get topic
|
||||
description: Google's get_topic on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_pubsub_get_topic(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_pubsub_get_topic\", \"pubsub\", \"get_topic\", arguments)\n"
|
||||
- name: gcp_pubsub_list_subscriptions
|
||||
display_name: Gcp pubsub list subscriptions
|
||||
description: Google's list_subscriptions on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_pubsub_list_subscriptions(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_pubsub_list_subscriptions\", \"pubsub\", \"list_subscriptions\", arguments)\n"
|
||||
- name: gcp_pubsub_get_subscription
|
||||
display_name: Gcp pubsub get subscription
|
||||
description: Google's get_subscription on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_pubsub_get_subscription(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_pubsub_get_subscription\", \"pubsub\", \"get_subscription\", arguments)\n"
|
||||
- name: gcp_iam_list_roles
|
||||
display_name: Gcp iam list roles
|
||||
description: Google's list_roles on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_iam_list_roles(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_iam_list_roles\", \"iam\", \"list_roles\", arguments)\n"
|
||||
- name: gcp_iam_get_role
|
||||
display_name: Gcp iam get role
|
||||
description: Google's get_role on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_iam_get_role(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_iam_get_role\", \"iam\", \"get_role\", arguments)\n"
|
||||
- name: gcp_iam_list_deny_policies
|
||||
display_name: Gcp iam list deny policies
|
||||
description: Google's list_deny_policies on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_iam_list_deny_policies(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_iam_list_deny_policies\", \"iam\", \"list_deny_policies\", arguments)\n"
|
||||
- name: gcp_iam_get_deny_policy
|
||||
display_name: Gcp iam get deny policy
|
||||
description: Google's get_deny_policy on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_iam_get_deny_policy(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await _gcp_forward(\"\
|
||||
gcp_iam_get_deny_policy\", \"iam\", \"get_deny_policy\", arguments)\n"
|
||||
- name: gcp_monitoring_list_alert_policies
|
||||
display_name: Gcp monitoring list alert policies
|
||||
description: Google's list_alert_policies on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_monitoring_list_alert_policies(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_monitoring_list_alert_policies\", \"monitoring\", \"list_alert_policies\", arguments)\n"
|
||||
- name: gcp_monitoring_get_alert_policy
|
||||
display_name: Gcp monitoring get alert policy
|
||||
description: Google's get_alert_policy on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_monitoring_get_alert_policy(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return\
|
||||
\ await _gcp_forward(\"gcp_monitoring_get_alert_policy\", \"monitoring\", \"get_alert_policy\", arguments)\n"
|
||||
- name: gcp_monitoring_list_dashboards
|
||||
display_name: Gcp monitoring list dashboards
|
||||
description: Google's list_dashboards on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_monitoring_list_dashboards(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_monitoring_list_dashboards\", \"monitoring\", \"list_dashboards\", arguments)\n"
|
||||
- name: gcp_monitoring_list_metric_descriptors
|
||||
display_name: Gcp monitoring list metric descriptors
|
||||
description: Google's list_metric_descriptors on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_monitoring_list_metric_descriptors(arguments: Dict[str, Any]) -> Dict[str, Any]:\n \
|
||||
\ return await _gcp_forward(\"gcp_monitoring_list_metric_descriptors\", \"monitoring\", \"list_metric_descriptors\", arguments)\n"
|
||||
- name: gcp_monitoring_list_timeseries
|
||||
display_name: Gcp monitoring list timeseries
|
||||
description: Google's list_timeseries on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_monitoring_list_timeseries(arguments: Dict[str, Any]) -> Dict[str, Any]:\n return await\
|
||||
\ _gcp_forward(\"gcp_monitoring_list_timeseries\", \"monitoring\", \"list_timeseries\", arguments)\n"
|
||||
- name: gcp_network_intelligence_list_connectivity_tests
|
||||
display_name: Gcp network intelligence list connectivity tests
|
||||
description: Google's list_connectivity_tests on its network_intelligence MCP server, read-only. Call gcp_describe_tool
|
||||
for its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_network_intelligence_list_connectivity_tests(arguments: Dict[str, Any]) -> Dict[str, Any]:\n\
|
||||
\ return await _gcp_forward(\"gcp_network_intelligence_list_connectivity_tests\", \"network_intelligence\", \"list_connectivity_tests\"\
|
||||
, arguments)\n"
|
||||
- name: gcp_network_intelligence_get_connectivity_test
|
||||
display_name: Gcp network intelligence get connectivity test
|
||||
description: Google's get_connectivity_test on its network_intelligence MCP server, read-only. Call gcp_describe_tool for
|
||||
its arguments.
|
||||
parameters:
|
||||
- name: tool_arguments
|
||||
type: object
|
||||
description: The hosted tool's arguments.
|
||||
required: false
|
||||
ai_implementation: "async def gcp_network_intelligence_get_connectivity_test(arguments: Dict[str, Any]) -> Dict[str, Any]:\n\
|
||||
\ return await _gcp_forward(\"gcp_network_intelligence_get_connectivity_test\", \"network_intelligence\", \"get_connectivity_test\"\
|
||||
, arguments)\n"
|
||||
@@ -0,0 +1,62 @@
|
||||
# ============================================
|
||||
# Solution Architecture Google Cloud - Environment Variables
|
||||
# ============================================
|
||||
# Generated by Agent Builder Platform
|
||||
#
|
||||
# SETUP INSTRUCTIONS:
|
||||
# 1. Copy this file to .env: cp .env.example .env
|
||||
# 2. Generate a secure API key: openssl rand -hex 32
|
||||
# 3. Update MCP_REGISTRATION_API_KEY with the generated key
|
||||
# 4. Build the image from the Dockerfile and run it where the MCP Gateway
|
||||
# can reach it (see README.md)
|
||||
#
|
||||
# MCP GATEWAY INTEGRATION:
|
||||
# When registering with the MCP Gateway, use the URL the Gateway reaches this
|
||||
# server at; for a container on the Gateway's network, its container name:
|
||||
# http://solution-architecture-google-cloud:8115
|
||||
# ============================================
|
||||
|
||||
# Server Identity
|
||||
MCP_SERVER_NAME=Solution Architecture Google Cloud
|
||||
MCP_SERVER_ID=sa-gcp-cloud
|
||||
MCP_SERVER_VERSION=0.1.0
|
||||
|
||||
# Server Configuration
|
||||
MCP_SERVER_PORT=8115
|
||||
|
||||
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format
|
||||
# (json = one object per line, for log stores; console = for reading by eye)
|
||||
LOG_LEVEL=INFO
|
||||
LOG_FORMAT=json
|
||||
|
||||
# ============================================
|
||||
# AUTHENTICATION (REQUIRED for production!)
|
||||
# ============================================
|
||||
# This key authenticates MCP Gateway requests to this server.
|
||||
# The Gateway stores this key and includes it in all tool/call requests.
|
||||
#
|
||||
# Generate a secure key:
|
||||
# openssl rand -hex 32
|
||||
#
|
||||
# IMPORTANT: Keep this key secret! It's stored in:
|
||||
# - This .env file (gitignored)
|
||||
# - MCP Gateway database (encrypted)
|
||||
MCP_REGISTRATION_API_KEY=<generate one: openssl rand -hex 32>
|
||||
|
||||
# Set to "false" ONLY for local development/testing
|
||||
# WARNING: Disabling auth in production is a security risk!
|
||||
REQUIRE_AUTH=true
|
||||
|
||||
# ============================================
|
||||
# CREDENTIALS FOR THE UPSTREAM (sent with each request, not set here)
|
||||
# ============================================
|
||||
# The MCP Gateway sends the tenant's credential with each call, from the Vault Service.
|
||||
# true: a call without one is refused. Set to false only for local runs, where the
|
||||
# server may use its own environment.
|
||||
REQUIRE_VAULT_CONNECTION=true
|
||||
|
||||
# ============================================
|
||||
# Add your own settings below
|
||||
# ============================================
|
||||
# Credentials for the upstream are not set here: the gateway sends them with each request.
|
||||
# EXAMPLE_SETTING=value
|
||||
15
outcome-pattern/solution_architecture/mcp-servers/sa-gcp-cloud/.gitignore
vendored
Normal file
15
outcome-pattern/solution_architecture/mcp-servers/sa-gcp-cloud/.gitignore
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
|
||||
# Editors
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,47 @@
|
||||
# MCP Server Dockerfile
|
||||
# Generated by Agent Builder Platform (template 1.1.0)
|
||||
#
|
||||
# Built on the platform's MCP server base image: Chainguard Python with the
|
||||
# packages in requirements.txt already installed, a non-root user (1000) and
|
||||
# no pip. This image adds only the server's own files.
|
||||
#
|
||||
# docker build -t <server>:<version> .
|
||||
# docker build --build-arg BASE_IMAGE=<local base image> -t ... .
|
||||
ARG BASE_IMAGE=kyndryl.jfrog.io/kc-ai-agent-factory-docker-local/mcp-server-base:1.1.0
|
||||
|
||||
# Stage 1: the server's extra Python packages, if requirements.txt lists any.
|
||||
# The base image's build image (<base image>-build: the base image plus uv) installs
|
||||
# them with its vendor-install script: only the packages added go on to
|
||||
# /vendor, and one that would change a package the base image already has stops
|
||||
# the build. uv never reaches the server's image.
|
||||
FROM ${BASE_IMAGE}-build AS vendor
|
||||
COPY requirements.txt constraints.txt /tmp/
|
||||
RUN vendor-install /tmp/requirements.txt /vendor /tmp/constraints.txt
|
||||
|
||||
# Stage 2: the server: the base image, its extra packages and its files.
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
LABEL maintainer="Agent Builder Platform"
|
||||
LABEL description="Google Cloud documentation and read-only estate tools for the Solution Architecture agent, through Google's hosted MCP servers."
|
||||
LABEL version="0.1.0"
|
||||
LABEL server.id="sa-gcp-cloud"
|
||||
LABEL template.version="1.1.0"
|
||||
|
||||
COPY --from=vendor /vendor /app/vendor/
|
||||
COPY server.py mcp_connection.py /app/
|
||||
|
||||
# Environment
|
||||
# The ConfigMap's SERVER_PORT overrides this, so the container, Service and probes agree
|
||||
ENV SERVER_PORT=8115
|
||||
ENV LOG_LEVEL=INFO
|
||||
ENV LOG_FORMAT=json
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8115
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD python -c "import os, urllib.request; urllib.request.urlopen('http://localhost:%s/health' % (os.getenv('MCP_SERVER_PORT') or os.getenv('SERVER_PORT') or '8115'))" || exit 1
|
||||
|
||||
# Run the server
|
||||
CMD ["python", "server.py"]
|
||||
@@ -0,0 +1,231 @@
|
||||
# Solution Architecture Google Cloud
|
||||
|
||||
Google Cloud documentation and read-only estate tools for the Solution Architecture agent, through Google's hosted MCP servers.
|
||||
|
||||
**Version:** 0.1.0
|
||||
**Server ID:** sa-gcp-cloud
|
||||
**Port:** 8115
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### As a container (recommended)
|
||||
|
||||
The Dockerfile builds the server's image. Run it on the same network as the
|
||||
MCP Gateway, so the Gateway can reach it by its container name:
|
||||
|
||||
```bash
|
||||
cp .env.example .env # then set MCP_REGISTRATION_API_KEY
|
||||
podman build -t <image-name> .
|
||||
podman run -d --name <container-name> --env-file .env --network <gateway-network> <image-name>
|
||||
```
|
||||
|
||||
Register it with the MCP Gateway at `http://<container-name>:8115`.
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with your configuration
|
||||
|
||||
# Run the server
|
||||
python server.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📡 API Endpoints
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/health` | GET | Health check (no auth) |
|
||||
| `/.well-known/mcp-auth` | GET | Authentication requirements |
|
||||
| `/messages` | POST | MCP JSON-RPC 2.0 endpoint |
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Available Tools
|
||||
|
||||
- **gcp_check_connection**: Test the stored connection: sign in and open the resource manager server.
|
||||
- **gcp_describe_tool**: Read a hosted tool's live description and argument schema, before calling it.
|
||||
- **gcp_developer_knowledge_search_documents**: Google's search_documents on its developer_knowledge MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_developer_knowledge_get_documents**: Google's get_documents on its developer_knowledge MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_developer_knowledge_answer_query**: Google's answer_query on its developer_knowledge MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_resource_manager_search_projects**: Google's search_projects on its resource_manager MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_asset_inventory_list_assets**: Google's list_assets on its asset_inventory MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_asset_inventory_analyze_iam_policy**: Google's analyze_iam_policy on its asset_inventory MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_instances**: Google's list_instances on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_get_instance_basic_info**: Google's get_instance_basic_info on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_instance_attached_disks**: Google's list_instance_attached_disks on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_instance_group_managers**: Google's list_instance_group_managers on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_get_instance_group_manager_basic_info**: Google's get_instance_group_manager_basic_info on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_instance_templates**: Google's list_instance_templates on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_get_instance_template_properties**: Google's get_instance_template_properties on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_disks**: Google's list_disks on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_get_disk_basic_info**: Google's get_disk_basic_info on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_reservations**: Google's list_reservations on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_compute_list_commitments**: Google's list_commitments on its compute MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_gke_list_clusters**: Google's list_clusters on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_gke_get_cluster**: Google's get_cluster on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_gke_list_node_pools**: Google's list_node_pools on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_gke_get_node_pool**: Google's get_node_pool on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_gke_get_k8s_version**: Google's get_k8s_version on its gke MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_cloud_run_list_services**: Google's list_services on its cloud_run MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_cloud_run_get_service**: Google's get_service on its cloud_run MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_cloud_sql_list_instances**: Google's list_instances on its cloud_sql MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_cloud_sql_get_instance**: Google's get_instance on its cloud_sql MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_storage_list_buckets**: Google's list_buckets on its storage MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_pubsub_list_topics**: Google's list_topics on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_pubsub_get_topic**: Google's get_topic on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_pubsub_list_subscriptions**: Google's list_subscriptions on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_pubsub_get_subscription**: Google's get_subscription on its pubsub MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_iam_list_roles**: Google's list_roles on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_iam_get_role**: Google's get_role on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_iam_list_deny_policies**: Google's list_deny_policies on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_iam_get_deny_policy**: Google's get_deny_policy on its iam MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_monitoring_list_alert_policies**: Google's list_alert_policies on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_monitoring_get_alert_policy**: Google's get_alert_policy on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_monitoring_list_dashboards**: Google's list_dashboards on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_monitoring_list_metric_descriptors**: Google's list_metric_descriptors on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_monitoring_list_timeseries**: Google's list_timeseries on its monitoring MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_network_intelligence_list_connectivity_tests**: Google's list_connectivity_tests on its network_intelligence MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
- **gcp_network_intelligence_get_connectivity_test**: Google's get_connectivity_test on its network_intelligence MCP server, read-only. Call gcp_describe_tool for its arguments.
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Authentication
|
||||
|
||||
This server uses Bearer token authentication for MCP protocol messages.
|
||||
|
||||
```bash
|
||||
# Test with authentication
|
||||
curl -X POST http://localhost:8115/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $MCP_REGISTRATION_API_KEY" \
|
||||
-d '{"jsonrpc": "2.0", "id": "1", "method": "tools/list", "params": {}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 MCP Gateway Registration
|
||||
|
||||
To register this server with the MCP Gateway:
|
||||
|
||||
1. Start the server (see Quick Start) where the MCP Gateway can reach it
|
||||
2. In the MCP Gateway Hub, go to **MCP Servers** → **Add MCP Server**
|
||||
3. Enter the server details:
|
||||
- **URL**: Use the **container name** as the hostname (e.g., `http://weather-mcp-server:8115`)
|
||||
- **API Key**: The `MCP_REGISTRATION_API_KEY` from your `.env` file
|
||||
4. Click the connection test icon to verify connectivity
|
||||
5. Enable the server
|
||||
|
||||
> **Note:** The URL is the one the MCP Gateway uses, so for a container on the Gateway's network use its container name, not `localhost`.
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Credentials per tenant
|
||||
|
||||
This server does not hold credentials for its upstream. The MCP Gateway reads the tenant's credential from the Vault Service and sends it with each call, in `params._meta["com.kyndryl.mcp/connection"]`. The server advertises what it needs when the gateway calls `initialize`:
|
||||
|
||||
| Field | Required | Secret |
|
||||
|---|---|---|
|
||||
| `service_account_json` | yes | yes |
|
||||
| `scope_root` | yes | no |
|
||||
| `quota_project` | no | no |
|
||||
| `docs_api_key` | no | yes |
|
||||
|
||||
- In your tool code, read the connection with `get_connection()`, and reuse an upstream client with `get_upstream_client("<client kind>", build)`, which keeps one per kind and distinct connection.
|
||||
- `REQUIRE_VAULT_CONNECTION` (default `true`): a call that arrives without a connection is refused, instead of using this server's own environment. Set it to `false` only for local runs.
|
||||
- `verify_connection` is the tool the gateway calls to test a stored credential. It reports failure until you implement the check against the upstream.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Check it before you push
|
||||
|
||||
`tests/test_conformance.py` checks the running server against what the MCP Gateway expects: it
|
||||
refuses callers without its key, answers JSON-RPC correctly, and, if it declares credential fields,
|
||||
takes the account from each request, refuses a call that carries none, names a missing field, and
|
||||
never repeats a credential in a reply. It needs only `pytest` and `httpx` and imports nothing from
|
||||
the server.
|
||||
|
||||
```bash
|
||||
pip install pytest httpx
|
||||
# with the server running (see Quick Start) and its key from .env
|
||||
MCP_SERVER_URL=http://localhost:8115 MCP_REGISTRATION_API_KEY=<the key> pytest tests/ -v
|
||||
```
|
||||
|
||||
A check that fails says what to fix. Run it again after you implement your tools, since a tool that
|
||||
reads an environment variable for its credential, or repeats one in an error, fails it. Checks that
|
||||
do not apply (a server with no credential fields) are skipped, not passed. To run it with
|
||||
`REQUIRE_VAULT_CONNECTION=false` on your own machine, set `CONFORMANCE_EXPECT_FAIL_CLOSED=false`.
|
||||
|
||||
---
|
||||
|
||||
## 🚢 Deploying through the tools repository
|
||||
|
||||
To have CI build and deploy this server, put this folder in the root of the
|
||||
`modernization-tools-mcp-servers` repository as `solution-architecture-google-cloud/`, then add it to
|
||||
`mcp_servers_to_deploy.yaml` in that repository with the instances it should
|
||||
run on:
|
||||
|
||||
```yaml
|
||||
- name: "solution-architecture-google-cloud"
|
||||
instances:
|
||||
- az_dev
|
||||
```
|
||||
|
||||
The pipeline reads `kubernetes/configmap.yaml` for the server's name and port
|
||||
(`MCP_SERVER_NAME`, `SERVER_PORT`), generates the registration key and sets it
|
||||
in the pod, and registers the server with the MCP Gateway.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Logging
|
||||
|
||||
Every line the server writes to stdout is one JSON object (`timestamp`, `level`,
|
||||
`event`, `logger`, `server_id`, and for a request `request_id`, `method`, `tool`),
|
||||
including uvicorn's and your tools' own. Each request ends with one
|
||||
`mcp_request_completed` line carrying `outcome`, `duration_ms` and `error_code`.
|
||||
|
||||
- `LOG_LEVEL` sets the level (default `INFO`).
|
||||
- `LOG_FORMAT=console` prints readable lines instead, for local work.
|
||||
- In your tool code use the module's `logger`: `logger.info("fetched_issue", key=issue_key)`.
|
||||
- Do not log credentials, tokens or Authorization headers.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Development
|
||||
|
||||
### Implementing Tools
|
||||
|
||||
Open `server.py` and find the tool implementation functions. Each tool has a placeholder that needs to be implemented:
|
||||
|
||||
```python
|
||||
async def your_tool_name(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# TODO: Implement this tool
|
||||
raise NotImplementedError("Tool 'your_tool_name' needs implementation")
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Health check
|
||||
curl http://localhost:8115/health
|
||||
|
||||
# List tools
|
||||
curl -X POST http://localhost:8115/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $MCP_REGISTRATION_API_KEY" \
|
||||
-d '{"jsonrpc": "2.0", "id": "1", "method": "tools/list", "params": {}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
Generated by Agent Builder Platform - Kyndryl (template 1.1.0)
|
||||
@@ -0,0 +1,29 @@
|
||||
# Every package installed in a generated MCP server, pinned to one exact version:
|
||||
# the ones requirements.txt names and everything they bring in. They are
|
||||
# installed in the MCP server base image (Dockerfile.base), so every server
|
||||
# built from this template gets the same versions as the platform's own
|
||||
# services.
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
certifi==2026.10.19
|
||||
click==8.5.0
|
||||
fastapi==0.143.2
|
||||
h11==0.16.0
|
||||
httpcore==1.0.9
|
||||
httptools==0.9.0
|
||||
httpx==0.28.1
|
||||
idna==3.20
|
||||
opentelemetry-api==1.45.1
|
||||
pydantic==2.14.1
|
||||
pydantic-core==2.50.1
|
||||
python-dotenv==1.2.4
|
||||
pyyaml==6.0.3
|
||||
starlette==1.8.0
|
||||
structlog==26.1.0
|
||||
typing-extensions==4.16.0
|
||||
typing-inspection==0.4.4
|
||||
uvicorn==0.54.0
|
||||
uvloop==0.23.0
|
||||
watchfiles==1.3.0
|
||||
websockets==16.1.1
|
||||
@@ -0,0 +1,25 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>-config # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
data:
|
||||
|
||||
# Read by the CI/CD pipeline: the server's name, and the port it listens on
|
||||
# (used for the container, the Service and the probes)
|
||||
MCP_SERVER_NAME: "solution-architecture-google-cloud"
|
||||
SERVER_PORT: "8115"
|
||||
|
||||
# One JSON object per line; LOG_FORMAT=console prints readable lines
|
||||
LOG_LEVEL: "INFO"
|
||||
LOG_FORMAT: "json"
|
||||
|
||||
# Leave on. The Gateway authenticates to this server with a bearer token, and
|
||||
# turning this off makes every tool callable by anything that can reach the
|
||||
# pod inside the cluster.
|
||||
REQUIRE_AUTH: "true"
|
||||
|
||||
# Refuse a call that arrives without the tenant's credential from the Vault Service
|
||||
REQUIRE_VAULT_CONNECTION: "true"
|
||||
|
||||
# Add your own settings here
|
||||
# EXAMPLE_SETTING: "value"
|
||||
@@ -0,0 +1,71 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- name: jfrog-secret
|
||||
containers:
|
||||
- name: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
image: <placeholder_for_image> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
name: http
|
||||
# Load all environment variables from ConfigMap
|
||||
envFrom:
|
||||
- secretRef:
|
||||
name: <placeholder_for_mcp_server_name>-secrets # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
optional: true # Won't fail if secret doesn't exist
|
||||
- secretRef:
|
||||
name: <placeholder_for_mcp_server_name>-dotenv-secrets # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
optional: true # Won't fail if secret doesn't exist
|
||||
- configMapRef:
|
||||
name: <placeholder_for_mcp_server_name>-config # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
# The registration key and server id are generated by the CI/CD pipeline;
|
||||
# the server needs the key to accept the Gateway's calls
|
||||
env:
|
||||
- name: MCP_REGISTRATION_API_KEY
|
||||
value: "<placeholder_for_registration_api_key>" # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
- name: MCP_SERVER_ID
|
||||
value: "<placeholder_for_server_id>" # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
resources:
|
||||
requests:
|
||||
memory: "128Mi"
|
||||
cpu: "10m"
|
||||
limits:
|
||||
memory: "1024Mi"
|
||||
cpu: "1000m"
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
initialDelaySeconds: 30 # Wait X seconds before first check
|
||||
periodSeconds: 15 # Check every X seconds
|
||||
timeoutSeconds: 10 # Each check can take up to X seconds to respond
|
||||
failureThreshold: 5 # Allow X consecutive failures before marking unhealthy
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
initialDelaySeconds: 30 # Wait X seconds before first check
|
||||
periodSeconds: 15 # Check every X seconds
|
||||
timeoutSeconds: 10 # Each check can take up to X seconds to respond
|
||||
failureThreshold: 5 # Allow X consecutive failures before marking unhealthy
|
||||
|
||||
# volumes:
|
||||
# - name: execution-storage
|
||||
# persistentVolumeClaim:
|
||||
# claimName: execution-storage-pvc # Same PVC name as core-components
|
||||
@@ -0,0 +1,20 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- configmap.yaml
|
||||
- secretnames.yaml
|
||||
|
||||
# Optionally add common labels
|
||||
|
||||
# Namespace for all resources
|
||||
namespace: mcp-servers
|
||||
labels:
|
||||
- includeSelectors: true
|
||||
pairs:
|
||||
app: <placeholder_for_mcp_server_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
environment: production
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
@@ -0,0 +1,7 @@
|
||||
# Do not modify this file, otherwise CI/CD pipeline will fail
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: mcp-servers
|
||||
labels:
|
||||
name: mcp-servers
|
||||
@@ -0,0 +1,18 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>-secrets
|
||||
type: Opaque
|
||||
data:
|
||||
# Base64 encoded values (NOT RECOMMENDED for sensitive data)
|
||||
# To encode: echo -n 'your-secret-value' | base64
|
||||
# Example: api-key: eW91ci1hcGkta2V5LXZhbHVl
|
||||
|
||||
stringData:
|
||||
# Plain text values saved on GitHub Secrets (RECOMMENDED)
|
||||
# Example:
|
||||
#
|
||||
# DB_PASSWORD: ${DB_PASSWORD_GITHUB_SECRET}
|
||||
# ANOTHER_SECRET: ${ANOTHER_GITHUB_SECRET}
|
||||
#
|
||||
# ${DB_PASSWORD_GITHUB_SECRET} and ${ANOTHER_GITHUB_SECRET} must exist as GitHub Secrets
|
||||
@@ -0,0 +1,33 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: <placeholder_for_mcp_server_name>
|
||||
labels:
|
||||
app: <placeholder_for_mcp_server_name>
|
||||
repo: <placeholder_for_repo_name> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
targetPort: <placeholder_for_port> # Do not modify, this will be replaced during deployment by the CI/CD pipeline
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
app: <placeholder_for_mcp_server_name>
|
||||
---
|
||||
# Optional: LoadBalancer service for external access
|
||||
# apiVersion: v1
|
||||
# kind: Service
|
||||
# metadata:
|
||||
# name: <placeholder_for_mcp_server_name>-external
|
||||
# labels:
|
||||
# app: <placeholder_for_mcp_server_name>
|
||||
# spec:
|
||||
# type: LoadBalancer
|
||||
# ports:
|
||||
# - port: 80
|
||||
# targetPort: 8080
|
||||
# protocol: TCP
|
||||
# name: http
|
||||
# selector:
|
||||
# app: <placeholder_for_mcp_server_name>
|
||||
@@ -0,0 +1,256 @@
|
||||
"""The connection a request carries: which upstream account this call is for.
|
||||
|
||||
An MCP server that talks to a third-party system needs that system's address and credentials. Taking
|
||||
them from environment variables makes one process serve one account for ever. Here the MCP Gateway
|
||||
sends them with each call, from the Vault Service, in MCP's own `_meta` field, under our vendor prefix:
|
||||
|
||||
initialize result _meta["com.kyndryl.mcp/connection-schema"] what this server needs (JSON Schema)
|
||||
_meta["com.kyndryl.mcp/verify-tool"] the tool that tests a connection
|
||||
tools/call, resources/read, prompts/get
|
||||
params._meta["com.kyndryl.mcp/connection"] the values, matching that schema
|
||||
|
||||
`_meta` is where the specification tells implementations to put their own data, so a client that does
|
||||
not know these keys ignores them. The values never travel in `arguments`, which is what the model
|
||||
writes and reads, so a credential cannot enter the model's context.
|
||||
|
||||
The connection is bound for the life of one request and read with `active()`. It is None when the caller
|
||||
sent nothing; whether the server may then use its own environment is decided in server.py
|
||||
(REQUIRE_VAULT_CONNECTION, which is on by default).
|
||||
|
||||
WHAT IS STANDARD AND WHAT IS OURS
|
||||
---------------------------------
|
||||
The mechanism is standard. `_meta` is the specification's sanctioned place for implementation-specific
|
||||
data, with formal key-naming rules (2026-07-28, "General fields / _meta"):
|
||||
|
||||
Prefix ... SHOULD use reverse DNS notation. Any prefix where the second label is
|
||||
`modelcontextprotocol` or `mcp` is reserved for MCP use ... third-party extensions use their own
|
||||
vendor prefix.
|
||||
|
||||
`com.kyndryl.mcp/` satisfies that: the second label is `kyndryl`, so it is a legitimate vendor prefix and
|
||||
not reserved. A client that does not recognise our keys ignores them, which is exactly what `_meta` is for.
|
||||
The value carried is a *separate* upstream credential, never the caller's own token (the specification
|
||||
says a server MUST NOT pass through the token it received from its client).
|
||||
|
||||
Only the three key names and the shape of their payloads are ours. When SEP-2127 (MCP Server Card) lands,
|
||||
the schema is what moves onto the card, and the key names are the only thing that changes.
|
||||
|
||||
The third key, VERIFY_TOOL_KEY, adds very little. Checking a credential is a plain `tools/call` against an
|
||||
ordinary tool that appears in `tools/list` like any other: no new method, no new transport. The only
|
||||
question that needed answering is WHICH tool, and the alternative was for the gateway to guess by name. A
|
||||
server that advertises nothing here is simply not verifiable.
|
||||
|
||||
STATELESSNESS
|
||||
-------------
|
||||
The 2026-07-28 specification made MCP explicitly stateless: "Servers MUST NOT rely on prior requests over
|
||||
the same connection to establish context ... Every request supplies this metadata in its _meta field."
|
||||
A module-level connection built once at import is exactly the state the specification tells servers not to
|
||||
keep. Binding the connection per request is therefore not only what multi-tenancy needs, it is what the
|
||||
protocol asks for.
|
||||
|
||||
HOW IT IS USED (server.py does all of this; a tool only calls get_connection())
|
||||
------------------------------------------------------------------------------
|
||||
import mcp_connection
|
||||
|
||||
# advertise, in the initialize result
|
||||
result["_meta"] = mcp_connection.schema_meta(CONNECTION_SCHEMA, verify_tool="verify_connection")
|
||||
|
||||
# bind, for the life of one request
|
||||
token = mcp_connection.bind(mcp_connection.from_params(request.params))
|
||||
try:
|
||||
... # mcp_connection.active() anywhere below
|
||||
finally:
|
||||
mcp_connection.unbind(token)
|
||||
|
||||
LOGS AND ERROR MESSAGES
|
||||
-----------------------
|
||||
`scrub()` is applied to every log line, and to the `error` text of a failed tool call, so the connection's
|
||||
values and credential-looking URL parameters (`?key=...`) never leave the process. `redact()` does the
|
||||
connection values alone. Neither is applied to a successful result: a presigned URL a tool returns on
|
||||
purpose must survive.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
VENDOR = "com.kyndryl.mcp"
|
||||
SCHEMA_KEY = f"{VENDOR}/connection-schema"
|
||||
CONNECTION_KEY = f"{VENDOR}/connection"
|
||||
VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool"
|
||||
|
||||
_active: contextvars.ContextVar[Optional[Dict[str, Any]]] = contextvars.ContextVar(
|
||||
"mcp_connection", default=None
|
||||
)
|
||||
|
||||
# Per process, so a fingerprint in a log cannot be checked against a guessed credential offline
|
||||
_FINGERPRINT_KEY = secrets.token_bytes(32)
|
||||
|
||||
|
||||
def schema_meta(schema: Dict[str, Any], verify_tool: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""The `_meta` object that advertises `schema` on an initialize result."""
|
||||
meta: Dict[str, Any] = {SCHEMA_KEY: schema}
|
||||
if verify_tool:
|
||||
meta[VERIFY_TOOL_KEY] = verify_tool
|
||||
return meta
|
||||
|
||||
|
||||
def verify_tool_from_initialize(result: Optional[Dict[str, Any]]) -> Optional[str]:
|
||||
"""The verify tool an initialize result advertises, or None.
|
||||
|
||||
The reader half of schema_meta, here rather than in the gateway so the two ends of the key cannot
|
||||
drift apart.
|
||||
"""
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
meta = result.get("_meta")
|
||||
if not isinstance(meta, dict):
|
||||
return None
|
||||
name = meta.get(VERIFY_TOOL_KEY)
|
||||
return name if isinstance(name, str) and name.strip() else None
|
||||
|
||||
|
||||
def from_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""The connection in a request's `params._meta`, or None.
|
||||
|
||||
Anything that is not an object counts as absent: a malformed connection must not be more
|
||||
powerful than none at all.
|
||||
"""
|
||||
if not isinstance(params, dict):
|
||||
return None
|
||||
meta = params.get("_meta")
|
||||
if not isinstance(meta, dict):
|
||||
return None
|
||||
profile = meta.get(CONNECTION_KEY)
|
||||
return profile if isinstance(profile, dict) and profile else None
|
||||
|
||||
|
||||
def bind(profile: Optional[Dict[str, Any]]) -> contextvars.Token:
|
||||
"""Make `profile` the connection for this request."""
|
||||
return _active.set(profile)
|
||||
|
||||
|
||||
def unbind(token: contextvars.Token) -> None:
|
||||
try:
|
||||
_active.reset(token)
|
||||
except ValueError:
|
||||
_active.set(None)
|
||||
|
||||
|
||||
def active() -> Optional[Dict[str, Any]]:
|
||||
"""The connection for this request, or None."""
|
||||
return _active.get()
|
||||
|
||||
|
||||
def fingerprint(profile: Optional[Dict[str, Any]]) -> str:
|
||||
"""A short id for a connection, safe to log and to cache on; the credential never is the key."""
|
||||
if not profile:
|
||||
return "env"
|
||||
canonical = json.dumps(profile, sort_keys=True, separators=(",", ":"), default=str)
|
||||
return hmac.new(_FINGERPRINT_KEY, canonical.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
|
||||
|
||||
|
||||
def redact(text: Any) -> str:
|
||||
"""`text` with every value of this request's connection replaced, for logs and error replies.
|
||||
|
||||
A tool can put a credential in an exception message without meaning to. Values shorter than four
|
||||
characters are left alone: replacing them would garble ordinary text.
|
||||
"""
|
||||
result = str(text)
|
||||
values = [v for v in (active() or {}).values() if isinstance(v, str) and len(v) >= 4]
|
||||
for value in sorted(values, key=len, reverse=True):
|
||||
result = result.replace(value, "[redacted]")
|
||||
return result
|
||||
|
||||
|
||||
# Query parameters that carry a credential in the URL of an upstream request
|
||||
_URL_CREDENTIAL = re.compile(
|
||||
r"([?&;](?:api[_-]?key|apikey|key|token|access[_-]?token|auth|secret|password|passwd|"
|
||||
r"client[_-]?secret|appid|app[_-]?id|sig|signature)=)[^&\s\"'#<>]+",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def scrub(value: Any, _depth: int = 0) -> Any:
|
||||
"""`value` with credentials taken out, for anything that is logged or sent back to a caller.
|
||||
|
||||
Strings lose the request's connection values and the value of any credential query parameter in a
|
||||
URL (`?key=...`); dicts, lists and tuples are scrubbed inside. Anything else is returned as it is.
|
||||
Not for tool results in general: a presigned URL a tool returns on purpose would be damaged.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
return _URL_CREDENTIAL.sub(r"\1[redacted]", redact(value))
|
||||
if _depth > 5:
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {k: scrub(v, _depth + 1) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return type(value)(scrub(v, _depth + 1) for v in value)
|
||||
return value
|
||||
|
||||
|
||||
def missing_fields(profile: Optional[Dict[str, Any]], schema: Dict[str, Any]) -> List[str]:
|
||||
"""The required fields of `schema` that `profile` does not supply."""
|
||||
if not profile:
|
||||
return []
|
||||
required = schema.get("required") or []
|
||||
return [name for name in required if not str(profile.get(name) or "").strip()]
|
||||
|
||||
|
||||
def install_invalid_request_handler(app: Any, on_invalid: Optional[Callable[[str], None]] = None) -> None:
|
||||
"""Answer a request that is not valid JSON-RPC with a JSON-RPC error that does not repeat the request.
|
||||
|
||||
FastAPI's own answer (HTTP 422) repeats the request body under "input". The body is where the gateway puts
|
||||
the tenant's connection, so a request that is merely malformed (no "id", say) would get the credential back
|
||||
in the reply, and in the log of anything that records replies. The status stays 422; the body is a JSON-RPC
|
||||
error (-32600) that names only the fields at fault. `on_invalid`, if given, is called with that text, already
|
||||
reduced to harmless characters, so the caller can log it in its own style.
|
||||
|
||||
Call it once, right after `app = FastAPI(...)`. FastAPI is imported here, not at module level, so the rest of
|
||||
this module stays importable without it.
|
||||
"""
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def invalid_request(request, exc):
|
||||
names = {
|
||||
"body" if error.get("type") == "json_invalid" else ".".join(str(p) for p in error.get("loc", ())[1:]) or "body"
|
||||
for error in exc.errors()
|
||||
}
|
||||
fields = re.sub(r"[^\w.\-, ]", "?", ", ".join(sorted(names)))[:200]
|
||||
if on_invalid is not None:
|
||||
on_invalid(fields)
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"result": None,
|
||||
"error": {"code": -32600, "message": "Invalid request: check " + fields},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"install_invalid_request_handler",
|
||||
"VENDOR",
|
||||
"SCHEMA_KEY",
|
||||
"CONNECTION_KEY",
|
||||
"VERIFY_TOOL_KEY",
|
||||
"schema_meta",
|
||||
"verify_tool_from_initialize",
|
||||
"from_params",
|
||||
"bind",
|
||||
"unbind",
|
||||
"active",
|
||||
"fingerprint",
|
||||
"redact",
|
||||
"scrub",
|
||||
"missing_fields",
|
||||
]
|
||||
@@ -0,0 +1,43 @@
|
||||
# MCP Server Dependencies
|
||||
# Generated by Agent Builder Platform
|
||||
|
||||
# Each dependency is pinned to one exact version, and constraints.txt pins everything they bring
|
||||
# in, so two builds of the same server get the same packages -- the same versions as the
|
||||
# platform's own services. The packages below are already installed in the MCP server base
|
||||
# image the Dockerfile builds on; a package added to this file is installed on top of them at
|
||||
# build time. Changing the version of one the base has stops the build: the base image moves
|
||||
# those, with the template.
|
||||
|
||||
# Core Framework
|
||||
# FastAPI - Modern web framework for MCP server
|
||||
fastapi==0.143.2
|
||||
|
||||
# ASGI Server
|
||||
# Uvicorn - Lightning-fast ASGI server
|
||||
uvicorn[standard]==0.54.0
|
||||
|
||||
# Data Validation
|
||||
# Pydantic - Data validation using Python type hints
|
||||
pydantic==2.14.1
|
||||
|
||||
# HTTP Client
|
||||
# HTTPX - Async HTTP client for API calls
|
||||
httpx==0.28.1
|
||||
|
||||
# Environment Variables
|
||||
# python-dotenv - Load environment from .env files
|
||||
python-dotenv==1.2.4
|
||||
|
||||
# Structured Logging
|
||||
# structlog - JSON log lines (see LOG_FORMAT in server.py)
|
||||
structlog==26.1.0
|
||||
|
||||
# Optional: Add your custom dependencies below
|
||||
# requests>=2.31.0
|
||||
# aiofiles>=23.2.1
|
||||
# sqlalchemy>=2.0.0
|
||||
# redis>=5.0.0
|
||||
|
||||
# Added by this server's definition
|
||||
google-auth==2.62.0
|
||||
requests==2.32.5
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,360 @@
|
||||
"""Conformance checks for an MCP server that takes its upstream credentials from the MCP Gateway.
|
||||
|
||||
Run these against a running server before you push it. They need only `pytest` and `httpx`, import
|
||||
nothing from the server and talk to it over HTTP, so they work on a server from the MCP Server
|
||||
Builder and on one written by hand.
|
||||
|
||||
pip install pytest httpx
|
||||
MCP_SERVER_URL=http://localhost:8100 MCP_REGISTRATION_API_KEY=<the server's key> pytest tests/ -v
|
||||
|
||||
What is checked, and why:
|
||||
|
||||
Protocol the server answers /health, refuses callers without its key, and speaks JSON-RPC
|
||||
correctly (initialize, tools/list, ids echoed, errors as errors).
|
||||
Connection a server that needs an upstream account says so in its initialize result
|
||||
(`_meta["com.kyndryl.mcp/connection-schema"]`) and takes the account from each
|
||||
request (`params._meta["com.kyndryl.mcp/connection"]`), not from its own environment.
|
||||
Such a server refuses a call that carries none (fail closed), reports which required
|
||||
field is missing, takes nothing from `arguments`, and never repeats a credential in a
|
||||
reply (the values of fields marked `writeOnly`; every value if none is marked). A server that needs no account skips these checks.
|
||||
|
||||
Settings (environment variables):
|
||||
|
||||
MCP_SERVER_URL default http://localhost:8100
|
||||
MCP_REGISTRATION_API_KEY the key the server was started with (required unless the
|
||||
server has authentication switched off)
|
||||
CONFORMANCE_EXPECT_FAIL_CLOSED default true. Set false only for a server you run locally
|
||||
with REQUIRE_VAULT_CONNECTION=false, so that checks which
|
||||
need a refusal are skipped rather than failed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
VENDOR = "com.kyndryl.mcp"
|
||||
SCHEMA_KEY = f"{VENDOR}/connection-schema"
|
||||
VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool"
|
||||
CONNECTION_KEY = f"{VENDOR}/connection"
|
||||
|
||||
BASE_URL = os.getenv("MCP_SERVER_URL", "http://localhost:8100").rstrip("/")
|
||||
API_KEY = os.getenv("MCP_REGISTRATION_API_KEY", "")
|
||||
EXPECT_FAIL_CLOSED = os.getenv("CONFORMANCE_EXPECT_FAIL_CLOSED", "true").strip().lower() != "false"
|
||||
|
||||
# A value no server could contain by accident, so finding it in a reply means the server repeated it.
|
||||
SENTINEL = f"sentinel-{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ helpers
|
||||
|
||||
|
||||
def auth_headers(key: Optional[str] = None) -> Dict[str, str]:
|
||||
key = API_KEY if key is None else key
|
||||
return {"Authorization": f"Bearer {key}"} if key else {}
|
||||
|
||||
|
||||
def rpc(
|
||||
client: httpx.Client,
|
||||
method: str,
|
||||
params: Optional[Dict[str, Any]] = None,
|
||||
*,
|
||||
request_id: Any = "1",
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
) -> httpx.Response:
|
||||
return client.post(
|
||||
"/messages",
|
||||
json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}},
|
||||
headers=auth_headers() if headers is None else headers,
|
||||
)
|
||||
|
||||
|
||||
def result_of(client: httpx.Client, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
response = rpc(client, method, params)
|
||||
assert response.status_code == 200, f"{method} answered HTTP {response.status_code}: {response.text[:300]}"
|
||||
body = response.json()
|
||||
assert not body.get("error"), f"{method} returned an error: {body['error']}"
|
||||
return body["result"]
|
||||
|
||||
|
||||
def with_connection(params: Dict[str, Any], connection: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
if connection is None:
|
||||
return params
|
||||
return {**params, "_meta": {CONNECTION_KEY: connection}}
|
||||
|
||||
|
||||
def value_for(name: str, spec: Dict[str, Any]) -> Any:
|
||||
"""A value of the right shape for a connection field, carrying the sentinel."""
|
||||
kind = spec.get("type", "string")
|
||||
if kind == "string" and spec.get("format") == "uri":
|
||||
return f"https://{SENTINEL}.invalid"
|
||||
if kind == "integer":
|
||||
return 12345
|
||||
if kind == "boolean":
|
||||
return True
|
||||
return f"{SENTINEL}-{name}"
|
||||
|
||||
|
||||
def full_connection(schema: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {name: value_for(name, spec) for name, spec in (schema.get("properties") or {}).items()}
|
||||
|
||||
|
||||
def secret_values(schema: Dict[str, Any]) -> List[str]:
|
||||
"""The sent values that must never come back: those of fields marked secret (`writeOnly`).
|
||||
|
||||
A tool may repeat a base URL or a region. If the server marks no field secret, every value is
|
||||
treated as one, because then nothing says which are safe to repeat.
|
||||
"""
|
||||
connection = full_connection(schema)
|
||||
properties = schema.get("properties") or {}
|
||||
marked = [n for n, spec in properties.items() if spec.get("writeOnly")]
|
||||
return [str(connection[n]) for n in (marked or list(properties))]
|
||||
|
||||
|
||||
def repeated(response: httpx.Response, schema: Dict[str, Any]) -> List[str]:
|
||||
return [v for v in secret_values(schema) if v in response.text]
|
||||
|
||||
|
||||
def _string_values(node: Any) -> List[str]:
|
||||
"""Every string anywhere in a JSON value."""
|
||||
if isinstance(node, str):
|
||||
return [node]
|
||||
if isinstance(node, dict):
|
||||
return [v for item in node.values() for v in _string_values(item)]
|
||||
if isinstance(node, list):
|
||||
return [v for item in node for v in _string_values(item)]
|
||||
return []
|
||||
|
||||
|
||||
def call(client: httpx.Client, tool: str, connection: Optional[Dict[str, Any]], arguments: Optional[Dict] = None):
|
||||
return rpc(client, "tools/call", with_connection({"name": tool, "arguments": arguments or {}}, connection))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
with httpx.Client(base_url=BASE_URL, timeout=30.0) as session:
|
||||
try:
|
||||
session.get("/health")
|
||||
except httpx.HTTPError as error:
|
||||
pytest.exit(f"Cannot reach the server at {BASE_URL}: {error}. Start it, or set MCP_SERVER_URL.", 2)
|
||||
yield session
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def initialize(client) -> Dict[str, Any]:
|
||||
return result_of(client, "initialize", {"protocolVersion": "1.0.0", "clientInfo": {"name": "conformance"}})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tools(client) -> List[Dict[str, Any]]:
|
||||
return result_of(client, "tools/list")["tools"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def schema(initialize) -> Optional[Dict[str, Any]]:
|
||||
return (initialize.get("_meta") or {}).get(SCHEMA_KEY)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def needs_connection(schema) -> Dict[str, Any]:
|
||||
if not schema or not schema.get("properties"):
|
||||
pytest.skip("the server advertises no connection fields, so it takes no per-request credentials")
|
||||
return schema
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def probe_tool(initialize, tools) -> str:
|
||||
"""The tool to call in the connection checks: the verify tool when there is one."""
|
||||
verify = (initialize.get("_meta") or {}).get(VERIFY_TOOL_KEY)
|
||||
if verify:
|
||||
return verify
|
||||
assert tools, "the server lists no tools to call"
|
||||
return tools[0]["name"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ protocol
|
||||
|
||||
|
||||
def test_health_answers(client):
|
||||
assert client.get("/health").status_code == 200
|
||||
|
||||
|
||||
def test_the_public_auth_endpoint_reveals_no_key(client):
|
||||
response = client.get("/.well-known/mcp-auth")
|
||||
if response.status_code == 404:
|
||||
pytest.skip("the server has no /.well-known/mcp-auth endpoint")
|
||||
assert response.status_code == 200
|
||||
if API_KEY:
|
||||
# A value that equals the key is always a leak. A short key can also appear inside ordinary words
|
||||
# ("nc" in "auth_required"), so searching the text for it is only meaningful for a real-length key.
|
||||
assert API_KEY not in _string_values(response.json()), "/.well-known/mcp-auth returns the server's key"
|
||||
if len(API_KEY) >= 12:
|
||||
assert API_KEY not in response.text, "/.well-known/mcp-auth returns the server's key"
|
||||
|
||||
|
||||
def test_a_call_without_the_servers_key_is_refused(client):
|
||||
response = rpc(client, "tools/list", headers={})
|
||||
assert response.status_code in (401, 403), f"answered HTTP {response.status_code} to a caller with no key"
|
||||
|
||||
|
||||
def test_a_call_with_the_wrong_key_is_refused(client):
|
||||
response = rpc(client, "tools/list", headers=auth_headers("not-the-key-" + uuid.uuid4().hex))
|
||||
assert response.status_code in (401, 403), f"answered HTTP {response.status_code} to a caller with the wrong key"
|
||||
|
||||
|
||||
def test_initialize_describes_the_server(initialize):
|
||||
assert initialize["serverInfo"]["name"]
|
||||
assert isinstance(initialize.get("capabilities"), dict)
|
||||
|
||||
|
||||
def test_tools_have_a_name_a_description_and_an_object_schema(tools):
|
||||
assert isinstance(tools, list)
|
||||
names = [t["name"] for t in tools]
|
||||
assert len(names) == len(set(names)), "two tools share a name"
|
||||
for tool in tools:
|
||||
assert tool["name"] and tool.get("description"), f"tool {tool.get('name')!r} lacks a name or description"
|
||||
assert tool["inputSchema"]["type"] == "object", f"{tool['name']} has no object inputSchema"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_id", ["conformance-1", 7])
|
||||
def test_the_reply_echoes_the_request_id(client, request_id):
|
||||
response = rpc(client, "tools/list", request_id=request_id)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == request_id
|
||||
|
||||
|
||||
def test_an_unknown_method_is_an_error_not_a_crash(client):
|
||||
response = rpc(client, "no/such/method")
|
||||
assert response.status_code == 200
|
||||
assert response.json().get("error"), "an unknown method returned no error"
|
||||
|
||||
|
||||
def test_an_unknown_tool_is_an_error_not_a_crash(client):
|
||||
response = rpc(client, "tools/call", {"name": f"no_such_tool_{uuid.uuid4().hex[:8]}", "arguments": {}})
|
||||
assert response.status_code == 200
|
||||
assert response.json().get("error"), "an unknown tool returned no error"
|
||||
|
||||
|
||||
def test_arguments_that_are_not_an_object_are_the_callers_mistake(client, tools, schema):
|
||||
params = {"name": tools[0]["name"], "arguments": ["not", "an", "object"]}
|
||||
# With a connection, when the server wants one: a refusal for lacking it would answer -32602 too
|
||||
response = rpc(client, "tools/call", with_connection(params, full_connection(schema) if schema else None))
|
||||
assert response.status_code == 200
|
||||
error = response.json().get("error")
|
||||
assert error and error.get("code") == -32602, f"expected invalid params (-32602), got: {response.text[:300]}"
|
||||
|
||||
|
||||
def test_an_invalid_request_does_not_repeat_what_it_carried():
|
||||
# No "id": the request is not valid JSON-RPC, and what it carried (a connection) must not come back.
|
||||
# It has a connection of its own: a server that answers a bad request by dropping the connection (an
|
||||
# unhandled error makes uvicorn do that) must not make the NEXT check fail with "connection reset".
|
||||
marker = f"{SENTINEL}-carried"
|
||||
try:
|
||||
response = httpx.post(
|
||||
f"{BASE_URL}/messages",
|
||||
json={"jsonrpc": "2.0", "method": "tools/list", "params": {"_meta": {CONNECTION_KEY: {"field": marker}}}},
|
||||
headers=auth_headers(),
|
||||
timeout=30.0,
|
||||
)
|
||||
except httpx.TransportError:
|
||||
return # nothing came back, so nothing was repeated
|
||||
assert marker not in response.text, "the reply to an invalid request repeated the request"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ connection
|
||||
|
||||
|
||||
def test_the_connection_schema_is_a_json_schema_object(needs_connection):
|
||||
assert needs_connection["type"] == "object"
|
||||
properties = needs_connection["properties"]
|
||||
assert isinstance(properties, dict) and properties
|
||||
assert set(needs_connection.get("required", [])) <= set(properties), "a required field is not a property"
|
||||
|
||||
|
||||
def test_the_verify_tool_is_listed(initialize, tools, needs_connection):
|
||||
verify = (initialize.get("_meta") or {}).get(VERIFY_TOOL_KEY)
|
||||
assert verify, f"initialize does not name a verify tool in _meta[{VERIFY_TOOL_KEY!r}]"
|
||||
assert verify in [t["name"] for t in tools], f"the verify tool {verify!r} is not in tools/list"
|
||||
|
||||
|
||||
def test_a_call_with_no_connection_is_refused(client, needs_connection, probe_tool):
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
response = call(client, probe_tool, None)
|
||||
assert response.json().get("error"), (
|
||||
"a call with no connection was served. The server is using its own environment for the "
|
||||
"upstream account, so every tenant would share one. Refuse it (REQUIRE_VAULT_CONNECTION)."
|
||||
)
|
||||
|
||||
|
||||
def test_a_connection_in_the_arguments_is_not_accepted(client, needs_connection, probe_tool):
|
||||
"""The credential travels in `_meta`, which the model never sees; one in `arguments` is not one."""
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
response = call(client, probe_tool, None, arguments=full_connection(needs_connection))
|
||||
assert response.json().get("error"), "a connection passed as tool arguments was accepted"
|
||||
assert not repeated(response, needs_connection), "the reply repeats a credential that was sent as an argument"
|
||||
|
||||
|
||||
def test_a_call_with_a_connection_is_not_refused_for_lacking_one(client, needs_connection, probe_tool):
|
||||
response = call(client, probe_tool, full_connection(needs_connection))
|
||||
assert response.status_code == 200
|
||||
error = response.json().get("error") or {}
|
||||
message = str(error.get("message", "")).lower()
|
||||
assert "no connection" not in message and "missing" not in message, (
|
||||
f"a complete connection was refused as incomplete: {error}"
|
||||
)
|
||||
|
||||
|
||||
def test_an_incomplete_connection_names_what_is_missing(client, needs_connection, probe_tool):
|
||||
required = list(needs_connection.get("required", []))
|
||||
if not required:
|
||||
pytest.skip("no field is required")
|
||||
connection = full_connection(needs_connection)
|
||||
dropped = required[-1]
|
||||
connection.pop(dropped)
|
||||
if not connection:
|
||||
# The only field is required, and an empty connection counts as none. Send one that has a value
|
||||
# but not the field, which is what a mistyped field name in the credential looks like.
|
||||
connection = {"not_a_field_of_this_server": "x"}
|
||||
|
||||
response = call(client, probe_tool, connection)
|
||||
error = response.json().get("error")
|
||||
assert error, f"a connection without the required field {dropped!r} was served"
|
||||
assert dropped in str(error.get("message", "")), f"the refusal does not name the missing field {dropped!r}: {error}"
|
||||
assert not repeated(response, needs_connection), "the refusal repeats a credential value"
|
||||
|
||||
|
||||
def test_no_reply_repeats_the_credential(client, needs_connection, probe_tool, tools):
|
||||
connection = full_connection(needs_connection)
|
||||
replies = [call(client, probe_tool, connection)]
|
||||
for tool in tools[:5]:
|
||||
replies.append(call(client, tool["name"], connection, arguments={"conformance": "probe"}))
|
||||
replies.append(call(client, "no_such_tool", connection))
|
||||
for response in replies:
|
||||
assert not repeated(response, needs_connection), f"a reply repeats the credential: {response.text[:300]}"
|
||||
|
||||
|
||||
def test_a_malformed_connection_is_no_better_than_none(client, needs_connection, probe_tool):
|
||||
if not EXPECT_FAIL_CLOSED:
|
||||
pytest.skip("CONFORMANCE_EXPECT_FAIL_CLOSED=false")
|
||||
for bad in ("just-a-string", ["a", "list"], 42):
|
||||
params = {"name": probe_tool, "arguments": {}, "_meta": {CONNECTION_KEY: bad}}
|
||||
body = rpc(client, "tools/call", params).json()
|
||||
assert body.get("error"), f"a connection of type {type(bad).__name__} was served"
|
||||
|
||||
|
||||
def test_resources_and_prompts_are_listed_when_advertised(client, initialize):
|
||||
capabilities = initialize.get("capabilities") or {}
|
||||
if capabilities.get("resources"):
|
||||
assert isinstance(result_of(client, "resources/list")["resources"], list)
|
||||
if capabilities.get("prompts"):
|
||||
assert isinstance(result_of(client, "prompts/list")["prompts"], list)
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Run once per server: SERVER_DIR=<folder> pytest tests/test_servers.py. Upstreams are simulated; nothing leaves this machine."""
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
SERVER_DIR = Path(os.environ["SERVER_DIR"]).resolve()
|
||||
sys.path.insert(0, str(SERVER_DIR))
|
||||
import mcp_connection # noqa: E402
|
||||
import server # noqa: E402
|
||||
|
||||
NAME = SERVER_DIR.name
|
||||
HERE = Path(__file__).resolve().parents[1]
|
||||
CONNECTIONS = {
|
||||
"sa-gcp-cloud": {"scope_root": "projects/p1", "service_account_json": "{}"},
|
||||
"sa-azure-cloud": {"tenant_id": "t", "client_id": "c", "client_secret": "s", "scope_root": "subscriptions/sub-1"},
|
||||
"sa-aws-cloud": {"access_key_id": "a", "secret_access_key": "b", "role_arn": "arn:aws:iam::111111111111:role/r",
|
||||
"regions": "eu-west-2"},
|
||||
}
|
||||
# Every tool the source allows, by the name it has on each server. See README.md for the mapping.
|
||||
SOURCE_CAPABILITIES = ("search_documents", "get_documents", "analyze", "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", "list_clusters", "get_cluster", "list_node_pools", "get_node_pool",
|
||||
"get_k8s_version", "list_services", "get_service", "list_buckets", "list_topics", "get_topic",
|
||||
"list_subscriptions", "list_roles", "get_role", "list_deny_policies", "list_alert_policies",
|
||||
"get_alert_policy", "list_dashboards", "list_metric_descriptors", "list_timeseries",
|
||||
"list_connectivity_tests", "get_connectivity_test")
|
||||
|
||||
|
||||
def tool_names():
|
||||
return [t["name"] for t in server.TOOLS_REGISTRY]
|
||||
|
||||
|
||||
def run(tool, arguments, connection=None):
|
||||
async def go():
|
||||
bound = mcp_connection.bind(connection or CONNECTIONS[NAME])
|
||||
try:
|
||||
return await getattr(server, tool)(arguments)
|
||||
finally:
|
||||
mcp_connection.unbind(bound)
|
||||
return asyncio.run(go())
|
||||
|
||||
|
||||
def test_every_tool_has_a_handler_and_a_real_check():
|
||||
names = tool_names()
|
||||
assert "verify_connection" in names and len(names) == len(set(names))
|
||||
assert all(callable(getattr(server, n)) for n in names)
|
||||
assert "does not check it against" not in (SERVER_DIR / "server.py").read_text()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("capability", SOURCE_CAPABILITIES)
|
||||
def test_each_source_capability_has_a_tool(capability):
|
||||
assert [n for n in tool_names() if capability in n], capability
|
||||
|
||||
|
||||
def test_a_connection_is_required():
|
||||
assert server.config.REQUIRE_VAULT_CONNECTION is True
|
||||
with pytest.raises(ValueError):
|
||||
server.check_connection(None)
|
||||
|
||||
|
||||
def test_people_and_secrets_are_scrubbed():
|
||||
text = json.dumps(server._scrub({"tags": {"owner": "Ana Silva"}, "note": "ana@customer.example",
|
||||
"osProfile": {"adminPassword": "x"}}))
|
||||
assert "Ana Silva" not in text and "ana@" not in text and '"x"' not in text
|
||||
|
||||
|
||||
def test_failures_do_not_quote_the_upstream():
|
||||
assert "ana@" not in json.dumps(server._upstream_failed("x", RuntimeError("ana@customer.example")))
|
||||
|
||||
|
||||
def aws_calls():
|
||||
"""Every (service, operation, result key, token in, token out) the AWS definition names, from the rendered code."""
|
||||
code = (SERVER_DIR / "server.py").read_text()
|
||||
entries = re.findall(r'\("([a-z0-9]+)", "([a-z_]+)", "([A-Za-z]+)", "([A-Za-z]+)", "([A-Za-z]+)", \{', code)
|
||||
gets = re.findall(r'_aws_get\("aws_[a-z0-9_]+", arguments, "([a-z0-9]+)", "([a-z_]+)"', code)
|
||||
return entries, gets
|
||||
|
||||
|
||||
@pytest.mark.skipif(NAME != "sa-aws-cloud", reason="only AWS names operations")
|
||||
def test_aws_names_only_read_operations_that_exist():
|
||||
import boto3
|
||||
from botocore import xform_name
|
||||
|
||||
entries, gets = aws_calls()
|
||||
assert len(entries) + len(gets) > 35
|
||||
session = boto3.Session(aws_access_key_id="a", aws_secret_access_key="b", region_name="eu-west-2")
|
||||
problems = []
|
||||
for service, operation, *rest in [*entries, *gets]:
|
||||
if operation.split("_")[0] not in ("list", "describe", "get"):
|
||||
problems.append(f"{operation} isn't a read")
|
||||
model = session.client(service).meta.service_model
|
||||
names = {xform_name(n): n for n in model.operation_names}
|
||||
if operation not in names:
|
||||
problems.append(f"{service}.{operation} doesn't exist")
|
||||
continue
|
||||
if rest:
|
||||
shape = model.operation_model(names[operation])
|
||||
output = shape.output_shape.members if shape.output_shape else {}
|
||||
inputs = shape.input_shape.members if shape.input_shape else {}
|
||||
result, token_in, token_out = rest
|
||||
problems += [f"{operation}: no {n}" for n, there in ((result, output), (token_out, output), (token_in, inputs)) if n not in there]
|
||||
assert not problems, problems
|
||||
|
||||
|
||||
@pytest.mark.skipif(NAME != "sa-aws-cloud", reason="AWS")
|
||||
def test_aws_stays_inside_the_connection_regions():
|
||||
result = run("aws_list_instances", {"region": "us-east-1"})
|
||||
assert result["error"]["code"] == "outside_scope"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NAME != "sa-aws-cloud", reason="AWS")
|
||||
def test_aws_get_needs_its_identifier():
|
||||
assert run("aws_get_role", {})["error"]["code"] == "invalid_argument"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NAME != "sa-azure-cloud", reason="Azure")
|
||||
def test_azure_refuses_a_quote_in_an_id():
|
||||
assert run("azure_get_cluster", {"resource_id": "/subscriptions/s/x' or 1==1"})["success"] is False
|
||||
|
||||
|
||||
class Hosted:
|
||||
"""A hosted Google MCP server."""
|
||||
|
||||
def __init__(self, read_only=True, name="list_instances", error=False):
|
||||
self.read_only, self.name, self.error, self.called, self.urls = read_only, name, error, None, []
|
||||
|
||||
def __call__(self, request):
|
||||
self.urls.append(str(request.url))
|
||||
body = json.loads(request.content)
|
||||
method = body.get("method")
|
||||
if method == "initialize":
|
||||
return httpx.Response(200, json={"result": {}}, headers={"mcp-session-id": "s1"})
|
||||
if method == "tools/list":
|
||||
return httpx.Response(200, json={"result": {"tools": [
|
||||
{"name": self.name, "annotations": {"readOnlyHint": self.read_only}, "inputSchema": {"type": "object"}}]}})
|
||||
if method == "tools/call":
|
||||
self.called = body["params"]
|
||||
return httpx.Response(200, json={"result": {"isError": self.error, "content": [
|
||||
{"type": "text", "text": json.dumps({"owner": "ana@customer.example", "name": "vm-1"})}]}})
|
||||
return httpx.Response(202)
|
||||
|
||||
|
||||
def forward(tool, arguments, hosted):
|
||||
async def go():
|
||||
client = httpx.AsyncClient(transport=httpx.MockTransport(hosted))
|
||||
original, token = server.get_upstream_client, server._gcp_token
|
||||
server.get_upstream_client = lambda kind, build: client
|
||||
|
||||
async def fake():
|
||||
return "tok"
|
||||
server._gcp_token = fake
|
||||
bound = mcp_connection.bind(CONNECTIONS[NAME])
|
||||
try:
|
||||
return await getattr(server, tool)(arguments)
|
||||
finally:
|
||||
mcp_connection.unbind(bound)
|
||||
server.get_upstream_client, server._gcp_token = original, token
|
||||
await client.aclose()
|
||||
return asyncio.run(go())
|
||||
|
||||
|
||||
gcp = pytest.mark.skipif(NAME != "sa-gcp-cloud", reason="Google Cloud")
|
||||
|
||||
|
||||
@gcp
|
||||
def test_gcp_exposes_exactly_the_source_allow_list():
|
||||
source = (HERE / "_support" / "gcp_tools.py").read_text()
|
||||
catalog = next(ast.literal_eval(n.value) for n in ast.parse(source).body
|
||||
if isinstance(n, ast.Assign) and n.targets[0].id == "GCP_MCP_SERVERS")
|
||||
assert sum(len(e["allow"]) for e in catalog.values()) == 42
|
||||
assert {f"gcp_{s}_{t}" for s, e in catalog.items() for t in e["allow"]} <= set(tool_names())
|
||||
|
||||
|
||||
@gcp
|
||||
def test_gcp_forwards_arguments_and_scrubs_the_reply():
|
||||
hosted = Hosted()
|
||||
result = forward("gcp_compute_list_instances", {"tool_arguments": {"project": "p1"}}, hosted)
|
||||
assert hosted.called == {"name": "list_instances", "arguments": {"project": "p1"}}
|
||||
assert hosted.urls[0] == "https://compute.googleapis.com/mcp"
|
||||
assert result["success"] and "ana@" not in json.dumps(result)
|
||||
|
||||
|
||||
@gcp
|
||||
def test_gcp_refuses_a_tool_that_is_not_read_only():
|
||||
hosted = Hosted(read_only=False)
|
||||
assert forward("gcp_compute_list_instances", {}, hosted)["error"]["code"] == "not_read_only"
|
||||
assert hosted.called is None
|
||||
|
||||
|
||||
@gcp
|
||||
def test_gcp_reports_a_refused_call_without_quoting_it():
|
||||
assert forward("gcp_compute_list_instances", {}, Hosted(error=True))["error"]["code"] == "upstream_refused"
|
||||
|
||||
|
||||
@gcp
|
||||
def test_gcp_refuses_anything_off_the_allow_list():
|
||||
assert forward("gcp_describe_tool", {"server": "compute", "tool": "delete_instance"}, Hosted())["error"]["code"] == "not_allowed"
|
||||
|
||||
|
||||
@gcp
|
||||
def test_gcp_logs_documentation_queries(monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(server, "_docs_query_logged", lambda *a: seen.append(a))
|
||||
forward("gcp_developer_knowledge_search_documents", {"tool_arguments": {"query": "Cloud SQL limits"}}, Hosted(name="search_documents"))
|
||||
assert seen and "Cloud SQL limits" in seen[0][2]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NAME != "sa-aws-cloud", reason="AWS")
|
||||
def test_aws_documentation_reader_gets_the_shape_it_takes(monkeypatch):
|
||||
sent = {}
|
||||
|
||||
async def call(provider, connection, name, arguments):
|
||||
sent.update(name=name, arguments=arguments)
|
||||
return [{"text": "page"}]
|
||||
|
||||
monkeypatch.setattr(server, "_docs_call", call)
|
||||
run("aws_get_documents", {"url": "https://docs.aws.amazon.com/x"})
|
||||
assert sent["name"] == "aws___read_documentation"
|
||||
assert sent["arguments"] == {"requests": [{"url": "https://docs.aws.amazon.com/x", "max_length": 100000}]}
|
||||
Reference in New Issue
Block a user