Files
cp1-agents/scripts/render_mcp_server.py
Jonathan Boniface 416c66ced4
All checks were successful
check agents / check (push) Successful in 10s
Add CP1 Discovery agents in both patterns
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight
individual declarative agents (individual-agents/), with their KAB workflow
exports. Shared check, render and import scripts, the alz-discovery-sample
MCP server, the crucible-kab-dev deploy profile, deployment docs, platform
issue reports and the source material. Agent steps time out at 20 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:25:57 +00:00

107 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Render an MCP server definition through the platform's MCP Server Builder.
Runs the builder's own code -- MCPServerService._generate_code_files over the template in
packages/mcp-server-template -- the way packages/agent-builder-api/scripts/render_mcp_reference.py renders
the reference server, so the output is what the wizard would produce from the same definition.
The builder silently falls back to a NotImplementedError stub for a tool whose code it rejects. This script
refuses to write anything when that happens, and prints why each tool was rejected.
Usage (needs pydantic, pyyaml, httpx and pymongo for bson):
python3 scripts/render_mcp_server.py mcp-servers/alz-discovery-sample.server.yaml \
--out mcp-servers/alz-discovery-sample \
--platform ~/platform-engineering/kyndryl-agent-builder/modernization-platform
"""
from __future__ import annotations
import argparse
import logging
import sys
import types
from datetime import datetime
from pathlib import Path
import yaml
def load_builder(platform: Path):
api = platform / "packages" / "agent-builder-api"
if not (api / "src" / "services" / "mcp_server_service.py").exists():
raise SystemExit(f"{api} is not the agent-builder-api package")
sys.path.insert(0, str(api))
# The service imports the database client at module level; rendering never touches it.
stub = types.ModuleType("src.database.mongodb_client")
stub.get_mongodb_client = lambda *a, **k: None
sys.modules.setdefault("src.database.mongodb_client", stub)
from src.models import mcp_server_schemas as schemas
from src.services.mcp_server_service import MCPServerService
return schemas, MCPServerService
def build_server(schemas, data: dict):
now = datetime(2026, 1, 1) # fixed, so rendering twice gives the same files
tools = []
for tool in data["tools"]:
parameters = [schemas.ToolParameter(**p) for p in tool.get("parameters", [])]
tools.append(schemas.MCPToolResponse(
id=f"id-{tool['name']}", name=tool["name"], display_name=tool["display_name"],
description=" ".join(str(tool["description"]).split()), parameters=parameters,
parameters_schema=schemas.ToolParameterSchema.from_parameters(parameters), return_type="object",
implementation_notes=tool.get("implementation_notes"), ai_implementation=tool.get("ai_implementation"),
created_at=now, updated_at=now,
))
return schemas.MCPServerResponse(
id=data["server_id"], server_id=data["server_id"], name=data["name"],
description=" ".join(str(data["description"]).split()), version=data["version"], port=data["port"],
connection_fields=[schemas.ConnectionField(**f) for f in data.get("connection_fields", [])],
tools=tools, created_by="code_generated", created_at=now, updated_at=now,
)
class _Rejections(logging.Handler):
def __init__(self):
super().__init__(logging.WARNING)
self.messages = []
def emit(self, record):
message = record.getMessage()
if "not used" in message:
self.messages.append(message)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("definition", type=Path)
parser.add_argument("--out", type=Path, required=True, help="folder to write the server into")
parser.add_argument("--platform", type=Path, required=True, help="the modernization-platform checkout")
args = parser.parse_args(argv)
schemas, service = load_builder(args.platform.expanduser())
data = yaml.safe_load(args.definition.read_text())
rejections = _Rejections()
logging.getLogger().addHandler(rejections)
files = service()._generate_code_files(build_server(schemas, data)).all_files()
stubbed = [t["name"] for t in data["tools"] if f"Tool '{t['name']}' needs implementation" in files["server.py"]
or f"async def {t['name']}(" not in files["server.py"]]
if rejections.messages or stubbed:
for message in rejections.messages:
print(f"rejected: {message}", file=sys.stderr)
print(f"not rendered from the definition: {stubbed or 'see above'}; nothing written", file=sys.stderr)
return 1
for path, content in files.items():
target = args.out / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
print(f"Wrote {len(files)} files to {args.out} ({len(data['tools'])} tools)")
return 0
if __name__ == "__main__":
raise SystemExit(main())