Skip to content
Back to search

junos-mcp-server

This is a Junos Model Context Protocol (MCP) Server project that provides a bridge between MCP-compatible clients (like Claude Desktop) and Juniper Junos network devices.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/juniper--junos-mcp-server/badge.svg)](/listings/juniper--junos-mcp-server)

HTML

<a href="/listings/juniper--junos-mcp-server"><img src="/api/listings/juniper--junos-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Get the code.

git clone https://github.com/Juniper/junos-mcp-server.git
cd junos-mcp-server
pip install -r requirements.txt

Running with uv

If you're using [uv](https://github.com/astral-sh/uv), you can run the server directly:

uv run python jmcp.py -f devices.json -t stdio

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 886 lines · 1 finding marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # junos-mcp-server
  2. A Model Context Protocol (MCP) server for Juniper Junos devices that enables
  3. LLM interactions with network equipment.
  4. ## Table of Contents
  5. - [junos-mcp-server](#junos-mcp-server)
  6. - [Table of Contents](#table-of-contents)
  7. - [Important Security Notice](#important-security-notice)
  8. - [Security Requirements](#security-requirements)
  9. - [Security Best Practices](#security-best-practices)
  10. - [Important Configuration Notice](#important-configuration-notice)
  11. - [Getting Started](#getting-started)
  12. - [Running with uv](#running-with-uv)
  13. - [Start Junos MCP Server](#start-junos-mcp-server)
  14. - [Configuration](#configuration)
  15. - [Config for Claude Desktop (stdio transport)](#config-for-claude-desktop-stdio-transport)
  16. - [Config for Claude Desktop (using uv)](#config-for-claude-desktop-using-uv)
  17. - [Config for Claude Desktop (Docker container)](#config-for-claude-desktop-docker-container)
  18. - [Docker Usage](#docker-usage)
  19. - [Build Docker Container](#build-docker-container)
  20. - [Running with Default Settings](#running-with-default-settings)
  21. - [Overriding Default Arguments](#overriding-default-arguments)
  22. - [Junos Device Configuration](#junos-device-configuration)
  23. - [VSCode + GitHub Copilot Integration](#vscode--github-copilot-integration)
  24. - [Start Your Server](#start-your-server)
  25. - [Point to This URL in Your VSCode Config](#point-to-this-url-in-your-vscode-config)
  26. - [Authentication for MCP Server Access](#authentication-for-mcp-server-access)
  27. - [Authentication Behavior](#authentication-behavior)
  28. - [Token Management](#token-management)
  29. - [Generate a New Token](#generate-a-new-token)
  30. - [List All Tokens](#list-all-tokens)
  31. - [Show Token Value (Recovery)](#show-token-value-recovery)
  32. - [Revoke a Token](#revoke-a-token)
  33. - [Server Authentication Status](#server-authentication-status)
  34. - [Client Configuration with Authentication](#client-configuration-with-authentication)
  35. - [VSCode Configuration with Token](#vscode-configuration-with-token)
  36. - [Testing with curl](#testing-with-curl)
  37. - [Docker with Authentication](#docker-with-authentication)
  38. - [Security Best Practices](#security-best-practices-1)
  39. - [Token File Format](#token-file-format)
  40. - [GuardRails for Config Commit](#guardrails-for-config-commit)
  41. - [GuardRails for Executing Operational Commands](#guardrails-for-executing-operational-commands)
  42. - [Using MCP Server with Juniper Cloud-Native Router (JCNR)](#using-mcp-server-with-juniper-cloud-native-router-jcnr)
  43. - [Developer Guide](#developer-guide)
  44. - [Architecture Overview](#architecture-overview)
  45. - [How Tools Work](#how-tools-work)
  46. - [Adding a New Tool](#adding-a-new-tool)
  47. - [Step 1: Create a Handler Function](#step-1-create-a-handler-function)
  48. - [Step 2: Register the Handler](#step-2-register-the-handler)
  49. - [Step 3: Define Tool Metadata](#step-3-define-tool-metadata)
  50. - [Example: Creating a BGP Neighbors Tool](#example-creating-a-bgp-neighbors-tool)
  51. - [Best Practices for Tool Development](#best-practices-for-tool-development)
  52. - [Using PyEZ for Advanced Operations](#using-pyez-for-advanced-operations)
  53. - [Testing Your Tools](#testing-your-tools)
  54. - [Debugging Tips](#debugging-tips)
  55. ## Important Security Notice
  56. > **Warning:** This server enables LLM access to your network infrastructure. Please review these security considerations carefully.
  57. ### Security Requirements
  58. - **Corporate Policy Compliance**: Only use this server if your company's
  59. policy allows sending data of Junos devices to LLM services.
  60. - **Server Security**: Always secure your Junos MCP server before deployment in
  61. production environments.
  62. - **Authentication**: Do **not** use password authentication for production
  63. deployments. We strongly recommend using SSH key-based authentication for
  64. enhanced security.
  65. - **Deployment Strategy**: Until your MCP server is properly secured, only
  66. deploy locally for testing purposes. Do not deploy remote servers in production
  67. without proper security measures.
  68. ### Security Best Practices
  69. - Use SSH key authentication instead of passwords
  70. - Implement proper network access controls
  71. - Monitor and log all MCP server activities
  72. - Regular security audits and updates
  73. - Follow your organization's security policies
  74. ## Important Configuration Notice
  75. > **Warning:** The Junos MCP server supports configuration changes, but please ensure you only use this functionality when you want LLM-generated configurations to be loaded and committed on your Junos router.
  76. **Always review the configuration being generated by the LLM and only allow tool
  77. execution if it's the correct configuration for your use case.**
  78. ## Getting Started
  79. Get the code.
  80. ```bash
  81. git clone https://github.com/Juniper/junos-mcp-server.git
  82. cd junos-mcp-server
  83. pip install -r requirements.txt
  84. ```
  85. ### Running with uv
  86. If you're using [uv](https://github.com/astral-sh/uv), you can run the server directly:
  87. ```bash
  88. uv run python jmcp.py -f devices.json -t stdio
  89. ```
  90. ## Start Junos MCP Server
  91. ```bash
  92. python3.11 jmcp.py --help
  93. Junos MCP Server
  94. options:
  95. -h, --help show this help message and exit
  96. -f DEVICE_MAPPING, --device-mapping DEVICE_MAPPING
  97. the name of the JSON file containing the device mapping
  98. -H HOST, --host HOST Junos MCP Server host
  99. -t TRANSPORT, --transport TRANSPORT
  100. Junos MCP Server transport
  101. -p PORT, --port PORT Junos MCP Server port
  102. ```
  103. Junos MCP server supports both streamable-http and stdio transport. Do not use
  104. --host with stdio transport.
  105. ### Environment Variables
  106. - `JUNOS_TIMEOUT`: Command timeout in seconds for Junos CLI operations.
  107. - `JMCP_POOL_IDLE_TIMEOUT`: Idle timeout in seconds for pooled SSH/NETCONF connections.
  108. - SSH sessions are reused across tool calls via a connection pool; a background
  109. cleanup thread (running once a minute) closes connections idle longer than this timeout.
  110. - Default: `300`. Invalid values are logged and fall back to the default.
  111. ## Configuration
  112. ### Config for Claude Desktop (stdio transport)
  113. ```json
  114. {
  115. "mcpServers": {
  116. "jmcp": {
  117. "type": "stdio",
  118. "command": "python3",
  119. "args": ["jmcp.py", "-f", "devices.json", "-t", "stdio"]
  120. }
  121. }
  122. }
  123. ```
  124. ### Config for Claude Desktop (using uv)
  125. ```json
  126. {
  127. "mcpServers": {
  128. "jmcp": {
  129. "type": "stdio",
  130. "command": "uv",
  131. "args": ["run", "python", "jmcp.py", "-f", "devices.json", "-t", "stdio"]
  132. }
  133. }
  134. }
  135. ```
  136. **Note:** Please provide absolute path for jmcp.py and devices.json file.
  137. ### Config for Claude Desktop (Docker container)
  138. ```json
  139. {
  140. "mcpServers": {
  141. "jmcp": {
  142. "type": "stdio",
  143. "command": "/usr/local/bin/docker",
  144. "args": [
  145. "run",
  146. "--rm",
  147. "-i",
  148. "-v",
  149. "devices.json:/app/config/devices.json",
  150. "-v",
  151. "vsrx_keypair.pem:/app/config/vsrx_keypair.pem",
  152. "junos-mcp-server:latest"
  153. ]
  154. }
  155. }
  156. }
  157. ```
  158. ## Docker Usage
  159. ### Build Docker Container
  160. ```bash
  161. docker build -t junos-mcp-server:latest .
  162. ```
  163. ### Running with Default Settings
  164. By default, the Docker container runs with stdio transport:
  165. ```bash
  166. docker run --rm -it -v /path/to/your/devices.json:/app/config/devices.json
  167. junos-mcp-server:latest
  168. ```
  169. This uses the default command: `python jmcp.py -f /app/config/devices.json -t
  170. stdio`
  171. ### Overriding Default Arguments
  172. You can override any arguments by specifying the full command:
  173. **For stdio transport:**
  174. ```bash
  175. docker run --rm -it -v /path/to/your/devices.json:/app/config/devices.json
  176. junos-mcp-server:latest python jmcp.py -f /app/config/devices.json -t stdio
  177. ```
  178. **For streamable-http transport:**
  179. > **Security:** the streamable-http transport refuses to start without a valid
  180. > `.tokens` file. Generate one with `python jmcp_token_manager.py generate
  181. > --id <token-id>` and mount it into the container as shown below. See
  182. > [Authentication](#authentication) for details, or pass
  183. > `--allow-unauthenticated-http` for loopback-only local development.
  184. ```bash
  185. docker run --rm -it \
  186. -v /path/to/your/devices.json:/app/config/devices.json \
  187. -v /path/to/.tokens:/app/.tokens \
  188. -p 30030:30030 \
  189. junos-mcp-server:latest \
  190. python jmcp.py -f /app/config/devices.json -t streamable-http -H 0.0.0.0
  191. ```
  192. **For streamable-http with custom port:**
  193. ```bash
  194. docker run --rm -it \
  195. -v /path/to/your/devices.json:/app/config/devices.json \
  196. -v /path/to/.tokens:/app/.tokens \
  197. -p 8080:8080 \
  198. junos-mcp-server:latest \
  199. python jmcp.py -f /app/config/devices.json -t streamable-http -p 8080 -H 0.0.0.0
  200. ```
  201. **Note:**
  202. - Always mount your device configuration file using `-v /path/to/you/
  203. devices.json:/app/config/devices.json`
  204. - For streamable-http transport, expose the port using `-p
  205. host_port:container_port`
  206. - Mount any SSH private key files if using key-based authentication (e.g., `-v
  207. /path/to/key.pem:/app/config/key.pem`)
  208. Build docker container for Junos MCP Server
  209. ```bash
  210. docker build -t junos-mcp-server:latest .
  211. ```
  212. **Note:** Mount your config file `devices.json` and mount any other files, in
  213. my case I am using pem file for ssh priv key authentication so I am also
  214. mounting vsrx_keypair.pem
  215. ## Junos Device Configuration
  216. Junos MCP server supports both `password` based auth as well as `SSH key` based
  217. authentication (See first 2 routers configs [router-1, router-2]).
  218. ```json
  219. {
  220. "router-1": {
  221. "ip": "ip-addr",
  222. "port": 22,
  223. "username": "user",
  224. "auth": {
  225. "type": "password",
  226. "password": "pwd"
  227. }
  228. },
  229. "router-2": {
  230. "ip": "ip-addr",
  231. "port": 22,
  232. "username": "user",
  233. "auth": {
  234. "type": "ssh_key",
  235. "private_key_path": "/path/to/private/key.pem"
  236. }
  237. },
  238. "router-3": {
  239. "ip": "ip-addr",
  240. "port": 22,
  241. "username": "user",
  242. "ssh_config": "~/.ssh/config_dc",
  243. "auth": {
  244. "type": "ssh_key",
  245. "private_key_path": "/path/to/private/key.pem"
  246. }
  247. },
  248. "router-4": {
  249. "ip": "ip-addr",
  250. "port": 22,
  251. "username": "user",
  252. "ssh_config": "/home/user/.ssh/config_jumphost",
  253. "auth": {
  254. "type": "password",
  255. "password": "pwd"
  256. }
  257. }
  258. }
  259. ```
  260. Junos MCP server also provides support for `ProxyCommand`. (See last 2 routers
  261. configs [router-3, router-4]), which enables you to access a target device
  262. through an intermediary host that supports `netcat`. This is useful when you
  263. can only log in to the target device through the intermediate host (jumphost).
  264. This is an example of an SSH config file being used `.ssh/config_jumphost`:
  265. ```bash
  266. # Jumphost VM Connection
  267. Host jumphost-vm
  268. HostName 10.2.11.200
  269. User root
  270. # Used for MCP server
  271. IdentityFile /home/user/.ssh/id_rsa_claude
  272. IdentitiesOnly yes
  273. StrictHostKeyChecking no
  274. # cRPD Devices (via jump host)
  275. Host dt-crpd1 dtwin-crpd1 digital-twin-crpd1 clab-digital-twin-eop6-pe1
  276. HostName 172.20.20.11
  277. User claude
  278. IdentityFile c
  279. # ProxyJump jumphost-vm # Not working with JunOS MCP
  280. ProxyCommand ssh -l root jumphost-vm nc %h 22 2>/dev/null
  281. StrictHostKeyChecking no
  282. ```
  283. **Note #1:** `Port` value should be an integer (typically `22` for SSH).
  284. **Note #2:** `IdentityFile` recommendation use full path (e.g `/home/user/.ssh
  285. /id_rsa_claude` rather than `~/.ssh/id_rsa_claude`).
  286. ## VSCode + GitHub Copilot Integration
  287. ### Start Your Server
  288. ```bash
  289. python3.11 jmcp.py -f devices.json
  290. [06/11/25 08:26:11] INFO Starting MCP server 'jmcp-server' with transport
  291. 'streamable-http' on http://127.0.0.1:30030/mcp
  292. INFO: Started server process [33512]
  293. INFO: Waiting for application startup.
  294. INFO: Application startup complete.
  295. INFO: Uvicorn running on http://127.0.0.1:30030 (Press CTRL+C to quit)
  296. ```
  297. ### Point to This URL in Your VSCode Config
  298. ```json
  299. {
  300. "mcp": {
  301. "servers": {
  302. "my-junos-mcp-server": {
  303. "url": "http://127.0.0.1:30030/mcp/"
  304. }
  305. }
  306. }
  307. }
  308. ```
  309. **Note:** You can use VSCode's `Cmd+Shift+P` to configure MCP server.
  310. ## Authentication for MCP Server Access
  311. The Junos MCP server supports token-based authentication for secure client
  312. access when using streamable-http transport. This prevents unauthorized access
  313. to your network infrastructure.
  314. ### Authentication Behavior
  315. - **stdio transport** (Claude Desktop): No authentication required - secure by
  316. design as it runs locally
  317. - **streamable-http transport** (VSCode, web clients): Token-based
  318. authentication available
  319. ### Token Management
  320. The server includes a dedicated token management CLI tool:
  321. `jmcp_token_manager.py`
  322. By default, both the server and token manager use the `.tokens` file alongside
  323. `jmcp.py`, independent of the current working directory. On POSIX systems, the
  324. token manager creates the file with owner-only permissions (`0600`) and repairs
  325. those permissions whenever it writes an existing file.
  326. #### Generate a New Token
  327. ```bash
  328. # Basic token generation
  329. python jmcp_token_manager.py generate --id "vscode-dev"
  330. # With description
  331. python jmcp_token_manager.py generate --id "vscode-dev" --description "VSCode
  332. development environment"
  333. # Use a custom token file location
  334. python jmcp_token_manager.py --tokens-file /secure/path/tokens.json generate --id "vscode-dev"
  335. # Example output:
  336. Generated new token:
  337. ID: vscode-dev
  338. Token: jmcp_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8
  339. Description: VSCode development environment
  340. Save this token securely - it won't be shown again!
  341. ```
  342. #### List All Tokens
  343. ```bash
  344. python jmcp_token_manager.py list
  345. # Example output:
  346. ID Description Created
  347. -------------------------------------------------------------------------------------
  348. vscode-dev VSCode development environment
  349. 2025-01-28T10:30:00Z
  350. prod-client Production client access
  351. 2025-01-28T09:15:00Z
  352. ```
  353. #### Show Token Value (Recovery)
  354. ```bash
  355. python jmcp_token_manager.py show --id "vscode-dev"
  356. # Example output:
  357. Token ID: vscode-dev
  358. Token: jmcp_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8
  359. Description: VSCode development environment
  360. Created: 2025-01-28T10:30:00Z
  361. ```
  362. #### Revoke a Token
  363. ```bash
  364. python jmcp_token_manager.py revoke --id "vscode-dev"
  365. # Example output:
  366. Token 'vscode-dev' has been revoked
  367. ```
  368. ### Server Authentication Status
  369. For the `streamable-http` transport the server **fails closed**: it refuses to
  370. start unless a valid, non-empty `.tokens` file is present. The only way to
  371. start without tokens is the explicit `--allow-unauthenticated-http` flag,
  372. which is in turn restricted to loopback binds (`127.0.0.1`, `::1`,
  373. `localhost`).
  374. To use a custom location, pass the same path to the server:
  375. ```bash
  376. python jmcp.py -f devices.json -t streamable-http --tokens-file /secure/path/tokens.json
  377. ```
  378. **With tokens configured:**
  379. ```bash
  380. python jmcp.py -f devices.json -t streamable-http
  381. INFO - Token-based authentication enabled
  382. INFO - Clients must send 'Authorization: Bearer <token>' header
  383. INFO - Use jmcp_token_manager.py to manage tokens
  384. INFO - Streamable HTTP server started on http://127.0.0.1:30030
  385. ```
  386. **Without tokens configured (default - refuses to start):**
  387. ```bash
  388. python jmcp.py -f devices.json -t streamable-http
  389. ERROR - Refusing to start streamable-http transport without authentication: .tokens file not found
  390. ERROR - Generate a token with: python jmcp_token_manager.py generate --id <token-id>
  391. ERROR - Or, for local development on loopback only, re-run with --allow-unauthenticated-http
  392. ```
  393. **Explicit unauthenticated mode (loopback only, development only):**
  394. ```bash
  395. python jmcp.py -f devices.json -t streamable-http --allow-unauthenticated-http
  396. WARNING - *** Streamable HTTP authentication is DISABLED (--allow-unauthenticated-http). .tokens file not found. Server is open to any client that can reach 127.0.0.1:30030 and can commit configuration to mapped devices. Use only for local development. ***
  397. INFO - Streamable HTTP server started on http://127.0.0.1:30030
  398. ```
  399. Combining `--allow-unauthenticated-http` with a non-loopback bind (for
  400. example `-H 0.0.0.0`) is rejected at startup.
  401. ### Client Configuration with Authentication
  402. #### VSCode Configuration with Token
  403. ```json
  404. {
  405. "mcp": {
  406. "servers": {
  407. "my-junos-mcp-server": {
  408. "url": "http://127.0.0.1:30030/mcp/",
  409. "headers": {
  410. "Authorization": "Bearer
  411. jmcp_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8"
  412. }
  413. }
  414. }
  415. }
  416. }
  417. ```
  418. #### Testing with curl
  419. ```bash
  420. # Test authentication with valid token
  421. curl -X POST "http://127.0.0.1:30030/mcp/" \
  422. -H "Authorization: Bearer jmcp_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8" \
  423. -H "Content-Type: application/json" \
  424. -H "Accept: application/json, text/event-stream" \
  425. -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
  426. # Test without token (should fail with 401)
  427. curl -X POST "http://127.0.0.1:30030/mcp/" \
  428. -H "Content-Type: application/json" \
  429. -H "Accept: application/json, text/event-stream" \
  430. -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
  431. ```
  432. **Note:** MCP streamable-http requires the `Accept: application/json, tex
  433. /event-stream` header.
  434. #### Docker with Authentication
  435. When using Docker, mount the `.tokens` file to enable authentication:
  436. ```bash
  437. # Generate token first (outside container)
  438. python jmcp_token_manager.py generate --id "docker-client"
  439. # Run container with token file mounted
  440. docker run --rm -it \
  441. -v /path/to/devices.json:/app/config/devices.json \
  442. -v /path/to/.tokens:/app/.tokens \
  443. -p 30030:30030 \
  444. junos-mcp-server:latest \
  445. python jmcp.py -f /app/config/devices.json -t streamable-http -H 0.0.0.0
  446. ```
  447. ### Security Best Practices
  448. 1. **Token Security**:
  449. - Store tokens securely (password managers, environment variables)
  450. - Use descriptive token IDs for easy management
  451. - Regularly rotate tokens by revoking old ones and generating new ones
  452. - Never commit tokens to version control
  453. 2. **Access Control**:
  454. - Generate separate tokens for different clients/environments
  455. - Revoke tokens immediately when no longer needed
  456. - Monitor server logs for unauthorized access attempts
  457. 3. **Network Security**:
  458. - Run streamable-http server behind reverse proxy with HTTPS in production
  459. - Use firewall rules to restrict access to MCP server port
  460. - Consider VPN access for remote clients
  461. ### Token File Format
  462. The `.tokens` file stores tokens in JSON format:
  463. ```json
  464. {
  465. "vscode-dev": {
  466. "token": "jmcp_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8",
  467. "description": "VSCode development environment",
  468. "created": "2025-01-28T10:30:00Z"
  469. },
  470. "prod-client": {
  471. "token": "jmcp_x9y8z7w6v5u4t3s2r1q0p9o8n7m6l5k4j3i2",
  472. "description": "Production client access",
  473. "created": "2025-01-28T09:15:00Z"
  474. }
  475. }
  476. ```
  477. **Important**: Keep this file secure and don't commit it to version control.
  478. ## GuardRails for Config Commit
  479. The `load_and_commit_config` tool now includes a pre-commit guardrail check that validates the submitted candidate configuration against patterns in `block.cfg` before any device commit actions are attempted.
  480. ### How it works
  481. - Each non-comment line in `block.cfg` is treated as a blocked pattern.
  482. - Pattern matching is done against normalized config lines from the submitted `config_text`.
  483. - Patterns support regex tokens (for example to match dynamic usernames).
  484. - Literal keyword tokens also match non-empty Junos CLI abbreviations, so `set sys root-auth` matches `set system root-authentication`.
  485. - If any line matches, the request is rejected and **no configuration is loaded or committed**.
  486. ### Example `block.cfg`
  487. ```text
  488. # Blocked configuration prefixes/patterns for load_and_commit_config
  489. set system root-authentication
  490. set system login user ([^ ]+) authentication
  491. ```
  492. This protects common high-risk configuration areas (for example, root authentication or unmanaged local user credential changes) from being committed by automation.
  493. ## GuardRails for Executing Operational Commands
  494. The `execute_junos_command` and `execute_junos_command_batch` tools now include command guardrails using `block.cmd`.
  495. ### How it works
  496. - Each non-comment line in `block.cmd` is treated as a regex command pattern.
  497. - Submitted commands are normalized and checked before execution.
  498. - Literal keyword tokens match both their full form and non-empty Junos CLI abbreviations; regex patterns remain supported.
  499. - If a command matches a blocked pattern, execution is rejected.
  500. - For batch execution, the blocked command is rejected before dispatching to routers.
  501. ### Example `block.cmd`
  502. ```text
  503. # Blocked operational command prefixes/patterns for execute_junos_command
  504. request system reboot
  505. request system halt
  506. request system power-cycle
  507. request system power-off
  508. request system zeroize
  509. ```
  510. This blocks disruptive commands (reboot/power/zeroize class actions) while still allowing read-only operational show commands.
  511. ## Using MCP Server with Juniper Cloud-Native Router (JCNR)
  512. JCNR is a cloud native router that runs on various cloud environments. One can
  513. use this MCP server with JCNR as well by following the steps given below.
  514. Please refer to JCNR documentation for more details on configuration.
  515. - Configure SSH access in JCNR on a desired port other than 22. This is
  516. required because, JCNR runs as a container on shared operating system. Running
  517. SSH on default port is not recommended. By default SSH is enabled on port 24.
  518. But, it is preferred to change this to desired port depending on your
  519. networking needs.
  520. - Enable authentication method for SSH. JCNR supports SSH key and password
  521. based authentications.
  522. - Enable Netconf over SSH. This is enabled by default.
  523. ```junos
  524. set system services netconf ssh
  525. set system services ssh port 3030
  526. set system services ssh root-login allow
  527. set system root-authentication encrypted-password
  528. "$6$3vvMI$RNemhmu9izWXzO46msh38frIg4VoeFNJWJZugxgnU.NQso3OQ00QWOIZmzNePD.MWjDOD
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 670 on GitHub
  529. BBEYut/W7kfADdV." (or)
  530. set system root-authentication load-key-file <public key>
  531. ```
  532. ## Developer Guide
  533. This section explains the architecture of the Junos MCP server and how to
  534. extend it with new tools.
  535. ### Architecture Overview
  536. The Junos MCP server uses the Model Context Protocol (MCP) to enable LLMs to
  537. interact with Juniper network devices. The server architecture consists of:
  538. 1. **MCP Server Core** (`jmcp.py`): Handles MCP protocol communication
  539. 2. **Tool Handlers**: Individual functions that implement specific network
  540. operations
  541. 3. **Tool Registry**: Maps tool names to their handler functions
  542. 4. **Transport Layer**: Supports stdio (Claude Desktop) and streamable-http
  543. (VSCode)
  544. ### How Tools Work
  545. Each tool in the MCP server follows this flow:
  546. ![MCP Tool Flow](docs/diagrams/mcp-tool-flow.svg "MCP Tool Flow")
  547. ### Adding a New Tool
  548. Adding a new tool is a simple 3-step process:
  549. #### Step 1: Create a Handler Function
  550. Create an async handler function in `jmcp.py` (before the `TOOL_HANDLERS`
  551. dictionary):
  552. ```python
  553. async def handle_my_new_tool(arguments: dict) -> list[types.ContentBlock]:
  554. """Handler for my_new_tool - describe what it does"""
  555. # Extract arguments
  556. router_name = arguments.get("router_name", "")
  557. my_param = arguments.get("my_param", "default_value")
  558. # Validate router exists
  559. if router_name not in devices:
  560. result = f"Router {router_name} not found in the device mapping."
  561. else:
  562. # Your tool logic here
  563. log.debug(f"Executing my_new_tool on router {router_name}")
  564. result = _run_junos_cli_command(router_name, f"show {my_param}")
  565. return [types.TextContent(type="text", text=result)]
  566. ```
  567. #### Step 2: Register the Handler
  568. Add your handler to the `TOOL_HANDLERS` dictionary (around line 330):
  569. ```python
  570. TOOL_HANDLERS = {
  571. "execute_junos_command": handle_execute_junos_command,
  572. "get_junos_config": handle_get_junos_config,
  573. "junos_config_diff": handle_junos_config_diff,
  574. "gather_device_facts": handle_gather_device_facts,
  575. "get_router_list": handle_get_router_list,
  576. "load_and_commit_config": handle_load_and_commit_config,
  577. "my_new_tool": handle_my_new_tool, # Add your tool here
  578. }
  579. ```
  580. #### Step 3: Define Tool Metadata
  581. Add the tool definition to the `list_tools()` method (around line 410):
  582. ```python
  583. types.Tool(
  584. name="my_new_tool",
  585. description="Brief description of what your tool does",
  586. inputSchema={
  587. "type": "object",
  588. "properties": {
  589. "router_name": {"type": "string", "description": "The name of the
  590. router"},
  591. "my_param": {"type": "string", "description": "Description of
  592. parameter"}
  593. },
  594. "required": ["router_name"] # List required parameters
  595. }
  596. )
  597. ```
  598. ### Example: Creating a BGP Neighbors Tool
  599. Here's a complete example of adding a tool to show BGP neighbors:
  600. ```python
  601. # Step 1: Handler function
  602. async def handle_show_bgp_neighbors(arguments: dict) -> list[types.ContentBloc
  603. ]:
  604. """Handler for show_bgp_neighbors tool"""
  605. router_name = arguments.get("router_name", "")
  606. neighbor_address = arguments.get("neighbor_address", "")
  607. if router_name not in devices:
  608. result = f"Router {router_name} not found in the device mapping."
  609. else:
  610. log.debug(f"Getting BGP neighbors from router {router_name}")
  611. if neighbor_address:
  612. cmd = f"show bgp neighbor {neighbor_address}"
  613. else:
  614. cmd = "show bgp summary"
  615. result = _run_junos_cli_command(router_name, cmd)
  616. return [types.TextContent(type="text", text=result)]
  617. # Step 2: Add to TOOL_HANDLERS
  618. TOOL_HANDLERS = {
  619. # ... existing tools ...
  620. "show_bgp_neighbors": handle_show_bgp_neighbors,
  621. }
  622. # Step 3: Add to list_tools()
  623. types.Tool(
  624. name="show_bgp_neighbors",
  625. description="Show BGP neighbor information",
  626. inputSchema={
  627. "type": "object",
  628. "properties": {
  629. "router_name": {"type": "string", "description": "The name of the
  630. router"},
  631. "neighbor_address": {"type": "string", "description": "Optional:
  632. specific neighbor IP"}
  633. },
  634. "required": ["router_name"]
  635. }
  636. )
  637. ```
  638. ### Best Practices for Tool Development
  639. 1. **Error Handling**: Always handle connection errors and invalid inputs
  640. gracefully
  641. 2. **Logging**: Use the global `log` logger for debugging
  642. 3. **Validation**: Check if router exists before attempting operations
  643. 4. **Documentation**: Write clear descriptions for tools and parameters
  644. 5. **Timeouts**: Support configurable timeouts for long-running operations
  645. 6. **Return Format**: Always return `list[types.ContentBlock]` with text content
  646. 7. **Context Parameter**: Use the `context: Context` parameter to send progress
  647. and log messages to the client
  648. ### Using PyEZ for Advanced Operations
  649. For operations beyond CLI commands, use PyEZ directly:
  650. ```python
  651. from jnpr.junos import Device
  652. from jnpr.junos.utils.config import Config
  653. # Example: Using PyEZ tables
  654. async def handle_get_interfaces(arguments: dict) -> list[types.ContentBlock]:
  655. router_name = arguments.get("router_name", "")
  656. if router_name not in devices:
  657. result = f"Router {router_name} not found in the device mapping."
  658. else:
  659. device_info = devices[router_name]
  660. try:
  661. connect_params = prepare_connection_params(device_info, router_name)
  662. with Device(**connect_params) as junos_device:
  663. # Use PyEZ tables or other utilities
  664. interfaces = junos_device.rpc.get_interface_information()
  665. # Process interfaces...
  666. result = "Interface information..."
  667. except Exception as e:
  668. result = f"Error: {e}"
  669. return [types.TextContent(type="text", text=result)]
  670. ```
  671. ### Testing Your Tools
  672. 1. **Unit Testing**: Test handler functions with mock arguments
  673. 2. **Integration Testing**: Test with actual Junos devices or vSRX
  674. 3. **Error Cases**: Test with invalid routers, network failures, etc.
  675. Example test:
  676. ```python
  677. # Test the handler directly
  678. result = await handle_my_new_tool({
  679. "router_name": "router-1",
  680. "my_param": "test"
  681. })
  682. print(result[0].text)
  683. ```
  684. ### Debugging Tips
  685. 1. Enable debug logging to see detailed execution:
  686. ```python
  687. logging.basicConfig(level=logging.DEBUG)
  688. ```
  689. 2. Use the stdio transport for easier debugging:
  690. ```bash
  691. python jmcp.py -f devices.json -t stdio
  692. ```
  693. 3. Test individual commands manually:
  694. ```python
  695. result = _run_junos_cli_command("router-1", "show version")
  696. print(result)
  697. ```

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.