Skip to content

Commit 0fe6354

Browse files
Merge pull request #30 from Juniper/fix/j2/format
Update render_and_apply_j2_template tool
2 parents 79e9e52 + bf23cfb commit 0fe6354

3 files changed

Lines changed: 104 additions & 55 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ jobs:
4343
- name: Run Code Quality Tools
4444
if: matrix.os == 'ubuntu-latest'
4545
run: |
46-
black --check .
46+
black --check --fast .
4747
pylint $(git ls-files '*.py' | grep -vE '^(docs/|build/|tests/|samples/|setup.py|versioneer.py)') --exit-zero
4848
4949
- name: Run Unit Tests

‎jmcp.py‎

Lines changed: 100 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1343,6 +1343,7 @@ async def handle_render_and_apply_j2_template(
13431343
- apply_config: Boolean to apply or just render (default: False)
13441344
- commit_comment: Optional commit comment
13451345
- dry_run: Boolean to show diff without committing (default: False)
1346+
- config_format: Override format detection ('set', 'text', 'xml'). Auto-detected if omitted.
13461347
context: MCP Context object
13471348
13481349
Returns:
@@ -1357,10 +1358,10 @@ async def handle_render_and_apply_j2_template(
13571358
"commit_comment", "Configuration applied via Jinja2 template"
13581359
)
13591360
dry_run = arguments.get("dry_run", False)
1361+
config_format_override = arguments.get("config_format", None)
13601362

13611363
results = []
13621364

1363-
# Step 1: Validate inputs
13641365
if not template_content:
13651366
return [
13661367
types.TextContent(
@@ -1373,11 +1374,20 @@ async def handle_render_and_apply_j2_template(
13731374
types.TextContent(type="text", text="❌ Error: vars_content is required")
13741375
]
13751376

1376-
# Handle single router_name or list of router_names
1377+
if config_format_override and config_format_override not in ("set", "text", "xml"):
1378+
return [
1379+
types.TextContent(
1380+
type="text",
1381+
text=(
1382+
f"❌ Error: invalid config_format '{config_format_override}'. "
1383+
"Must be 'set', 'text', or 'xml'."
1384+
),
1385+
)
1386+
]
1387+
13771388
if router_name and not router_names:
13781389
router_names = [router_name]
13791390

1380-
# Step 2: Load variables from YAML string
13811391
try:
13821392
await context.info("Parsing variables from YAML content...")
13831393
variables = yaml.safe_load(vars_content)
@@ -1398,7 +1408,6 @@ async def handle_render_and_apply_j2_template(
13981408
except Exception as e:
13991409
return [types.TextContent(type="text", text=f"❌ Error loading variables: {e}")]
14001410

1401-
# Step 3: Setup Jinja2 environment and render template
14021411
try:
14031412
await context.info("Rendering Jinja2 template...")
14041413

@@ -1420,18 +1429,14 @@ async def handle_render_and_apply_j2_template(
14201429
)
14211430
]
14221431

1423-
# Step 4: If not applying, just return the rendered config
14241432
if not apply_config:
1425-
result_text = f"""✅ Template rendered successfully!
1426-
1427-
**Rendered Configuration:**
1428-
```
1429-
{rendered_config}
1430-
```
1431-
1432-
To apply this configuration to devices, set apply_config=true and provide
1433-
router_name or router_names.
1434-
"""
1433+
result_text = (
1434+
"✅ Template rendered successfully!\n\n"
1435+
"**Rendered Configuration:**\n"
1436+
"```\n" + rendered_config + "\n```\n\n"
1437+
"To apply this configuration to devices, set apply_config=true and provide "
1438+
"router_name or router_names.\n"
1439+
)
14351440
return [
14361441
types.TextContent(
14371442
type="text",
@@ -1443,7 +1448,6 @@ async def handle_render_and_apply_j2_template(
14431448
)
14441449
]
14451450

1446-
# Step 5: Apply configuration to specified routers
14471451
if not router_names:
14481452
return [
14491453
types.TextContent(
@@ -1472,28 +1476,43 @@ async def handle_render_and_apply_j2_template(
14721476

14731477
device_info = devices[rtr_name]
14741478

1475-
# Use prepare_connection_params to get proper connection parameters
14761479
try:
14771480
connect_params = prepare_connection_params(device_info, rtr_name)
14781481
except ValueError as ve:
14791482
application_results.append(f"❌ {rtr_name}: {ve}")
14801483
await context.error(f"{rtr_name}: {ve}")
14811484
continue
14821485

1483-
# Connect to device
14841486
dev = Device(**connect_params)
14851487

14861488
try:
14871489
dev.open()
14881490
await context.info(f"Connected to {rtr_name}")
14891491

1490-
# Load configuration using exclusive mode
1492+
if config_format_override:
1493+
config_format = config_format_override
1494+
await context.info(f"Using explicit config format: {config_format}")
1495+
else:
1496+
config_format = "set"
1497+
for line in rendered_config.strip().splitlines():
1498+
stripped = line.strip()
1499+
if not stripped or stripped.startswith("#"):
1500+
continue
1501+
if not re.match(
1502+
r"^(set|delete|deactivate|activate)\s", stripped
1503+
):
1504+
config_format = "text"
1505+
break
1506+
await context.info(f"Auto-detected config format: {config_format}")
1507+
14911508
try:
14921509
with Config(dev, mode="exclusive") as cu:
1493-
await context.info(f"Loading configuration on {rtr_name}...")
1494-
cu.load(rendered_config, format="set")
1510+
await context.info(
1511+
f"Loading configuration on {rtr_name} "
1512+
f"(format={config_format})..."
1513+
)
1514+
cu.load(rendered_config, format=config_format)
14951515

1496-
# Get diff
14971516
diff = cu.diff()
14981517

14991518
if not diff:
@@ -1502,8 +1521,6 @@ async def handle_render_and_apply_j2_template(
15021521
await context.info(f"{rtr_name}: {result_msg}")
15031522
else:
15041523
if dry_run:
1505-
# DRY RUN: Perform commit check, show diff,
1506-
# and rollback without committing
15071524
await context.info(
15081525
f"Performing commit check on {rtr_name}..."
15091526
)
@@ -1539,17 +1556,11 @@ async def handle_render_and_apply_j2_template(
15391556
)
15401557
await context.error(f"{rtr_name}: {result_msg}")
15411558
finally:
1542-
# CRITICAL: Always rollback in dry-run mode
15431559
await context.info(
15441560
f"{rtr_name}: Rolling back changes (dry-run mode)"
15451561
)
15461562
try:
1547-
# Perform the rollback
15481563
cu.rollback()
1549-
# Verify rollback success by checking
1550-
# if there are pending changes.
1551-
# After a successful rollback, there
1552-
# should be no differences.
15531564
diff = cu.diff()
15541565

15551566
if diff:
@@ -1572,7 +1583,6 @@ async def handle_render_and_apply_j2_template(
15721583
f"error: {str(rollback_error)}"
15731584
)
15741585
else:
1575-
# REAL COMMIT: Perform commit check before committing
15761586
await context.info(
15771587
f"Performing commit check on {rtr_name}..."
15781588
)
@@ -1588,7 +1598,6 @@ async def handle_render_and_apply_j2_template(
15881598
await context.error(f"{rtr_name}: {result_msg}")
15891599
cu.rollback()
15901600
else:
1591-
# Apply the changes
15921601
await context.info(
15931602
f"Committing configuration on {rtr_name}..."
15941603
)
@@ -1614,7 +1623,6 @@ async def handle_render_and_apply_j2_template(
16141623
application_results.append(f"❌ {rtr_name}: {error_msg}")
16151624
await context.error(f"{rtr_name}: {error_msg}")
16161625
finally:
1617-
# Always close the device connection
16181626
try:
16191627
dev.close()
16201628
await context.info(f"Disconnected from {rtr_name}")
@@ -1630,23 +1638,18 @@ async def handle_render_and_apply_j2_template(
16301638
application_results.append(f"❌ {rtr_name}: {error_msg}")
16311639
await context.error(f"{rtr_name}: {error_msg}")
16321640

1633-
# Step 6: Format final results
16341641
summary = "\n".join(application_results)
16351642

16361643
mode_prefix = "🔍 DRY RUN - " if dry_run else ""
16371644
mode_name = "preview" if dry_run else "application"
1638-
final_text = f"""{mode_prefix}Configuration {mode_name} complete!
1639-
1640-
**Routers:** {', '.join(router_names)}
16411645

1642-
**Rendered Configuration:**
1643-
```
1644-
{rendered_config}
1645-
```
1646-
1647-
**Results:**
1648-
{summary}
1649-
"""
1646+
final_text = (
1647+
mode_prefix + "Configuration " + mode_name + " complete!\n\n"
1648+
"**Routers:** " + ", ".join(router_names) + "\n\n"
1649+
"**Rendered Configuration:**\n"
1650+
"```\n" + rendered_config + "\n```\n\n"
1651+
"**Results:**\n" + summary + "\n"
1652+
)
16501653

16511654
return [
16521655
types.TextContent(
@@ -2169,37 +2172,80 @@ async def list_tools() -> list[types.Tool]:
21692172
),
21702173
types.Tool(
21712174
name="render_and_apply_j2_template",
2172-
description="Render a Jinja2 template and apply it to the router",
2175+
description=(
2176+
"Render a Jinja2 template with YAML variables and optionally apply it "
2177+
"to one or more Junos routers. "
2178+
"When apply_config=false (default), the template is only rendered locally "
2179+
"— no device connection is made. "
2180+
"When apply_config=true, the tool connects to the device(s) and loads the "
2181+
"rendered configuration. "
2182+
"Combine apply_config=true with dry_run=true to perform a commit check "
2183+
"on the device and display the diff without committing — changes are "
2184+
"automatically rolled back after the check. "
2185+
"Use router_name for a single device or router_names (list) for multiple "
2186+
"devices; at least one must be provided when apply_config=true."
2187+
),
21732188
inputSchema={
21742189
"type": "object",
21752190
"properties": {
21762191
"router_name": {
21772192
"type": "string",
2178-
"description": "The name of the router",
2193+
"description": (
2194+
"Name of a single router to apply the configuration to. "
2195+
"Required when apply_config=true and router_names is not provided."
2196+
),
2197+
},
2198+
"router_names": {
2199+
"type": "array",
2200+
"items": {"type": "string"},
2201+
"description": (
2202+
"JSON array of router name strings to apply the configuration to "
2203+
"in sequence, e.g. ['pe1', 'pe2', 'pe3']. "
2204+
"Each element must exactly match a name in the device mapping. "
2205+
"Use this instead of router_name when targeting multiple devices. "
2206+
"Required when apply_config=true and router_name is not provided."
2207+
),
21792208
},
21802209
"template_content": {
21812210
"type": "string",
2182-
"description": "Jinja2 template to load",
2211+
"description": "Jinja2 template content as a string.",
21832212
},
21842213
"vars_content": {
21852214
"type": "string",
2186-
"description": "YAML variables to load",
2215+
"description": "YAML-formatted variables to render into the template.",
21872216
},
21882217
"apply_config": {
21892218
"type": "boolean",
2190-
"description": "Boolean to apply or just render (default: False)",
2219+
"description": (
2220+
"If false (default), only render the template locally without "
2221+
"connecting to any device. If true, connect to the device(s) "
2222+
"and load the rendered configuration."
2223+
),
21912224
},
21922225
"dry_run": {
21932226
"type": "boolean",
21942227
"description": (
2195-
"Boolean to show diff without committing "
2196-
"(default: False)"
2228+
"Only effective when apply_config=true. If true, perform a "
2229+
"commit check on the device and show the diff without committing. "
2230+
"Changes are automatically rolled back after the check. "
2231+
"If false (default), commit the configuration."
21972232
),
21982233
},
21992234
"commit_comment": {
22002235
"type": "string",
2201-
"description": "Commit comment",
2202-
"default": "Configuration loaded via MCP",
2236+
"description": "Commit comment recorded in the device commit log.",
2237+
"default": "Configuration applied via Jinja2 template",
2238+
},
2239+
"config_format": {
2240+
"type": "string",
2241+
"description": (
2242+
"Configuration format: 'set' (flat set commands), "
2243+
"'text' (stanza/hierarchical), or 'xml'. "
2244+
"If omitted, auto-detected from the rendered template content: "
2245+
"lines starting with set/delete/deactivate/activate → 'set', "
2246+
"otherwise → 'text'."
2247+
),
2248+
"enum": ["set", "text", "xml"],
22032249
},
22042250
},
22052251
"required": ["template_content", "vars_content"],

‎pyproject.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ dependencies = [
2020
[project.scripts]
2121
junos-mcp-server = "jmcp:main"
2222

23+
[tool.black]
24+
target-version = ["py310"]
25+
2326
[tool.setuptools]
2427
py-modules = ["jmcp", "jmcp_token_manager"]
2528

0 commit comments

Comments
 (0)