Skip to content
Back to search

mcp-server-plugin

MCP Server Plugin for Jenkins The MCP (Model Context Protocol) Server Plugin for Jenkins implements the server-side component of the Model Context Protocol. This plugin enables Jenkins to act as an…

Safety scan

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

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/jenkinsci/mcp-server-plugin with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/jenkinsci/mcp-server-plugin'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

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

HTML

<a href="/listings/jenkinsci--mcp-server-plugin"><img src="/api/listings/jenkinsci--mcp-server-plugin/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.

Configuration

The MCP Server plugin automatically sets up necessary endpoints and tools upon installation, requiring no additional configuration.

System properties

The following system properties can be used to configure the MCP Server plugin:

- hard limit on max number of log lines to return with `io.jenkins.plugins.mcp.server.extensions.BuildLogsExtension.limit.max=10000` (default 10000) - disable stateless endpoint with `io.jenkins.plugins.mcp.server.Endpoint.disableMcpStateless=true` (default false) - disable SSE endpoint with `io.jenkins.plugins.mcp.server.Endpoint.disableMcpSse=true` (default false) - disable streamable HTTP endpoint with `io.jenkins.plugins.mcp.server.Endpoint.disableMcpStreamable=true` (default false)

Origin header validation

The MCP specification marks validating the `Origin` header of incoming requests as a `MUST`.

By default, when an `Origin` header is present it is validated against the configured Jenkins root URL (`io.jenkins.plugins.mcp.server.Endpoint.requireOriginMatch` defaults to `true`). Requests that do not send an `Origin` header are still allowed, so AI agents that omit it keep working (`io.jenkins.plugins.mcp.server.Endpoint.requireOriginHeader` defaults to `false`).

- To also reject requests that omit the `Origin` header, set `io.jenkins.plugins.mcp.server.Endpoint.requireOriginHeader=true`. - To disable Origin matching entirely (not recommended), set `io.jenkins.plugins.mcp.server.Endpoint.requireOriginMatch=false`.

Connection Resilience

The MCP Server plugin includes several features to improve connection reliability.

The keep-alive and timeout tuning described below primarily concern the **SSE** transport (`/mcp-server/sse`), which holds a single long-lived server→client connection open and is therefore sensitive to idle timeouts in Jenkins, proxies, and load balancers. If you use **Streamable HTTP** (`/mcp-server/mcp`) with the usual request/response pattern, you are unlikely to need any of it (see [Transport Recommendation](#transport-recommendation)). The health, metrics, and graceful-shutdown features apply to all transports.

Keep-Alive Messages

For the **SSE** transport, the server sends periodic keep-alive pings over the open connection to detect broken connections and to stop idle timeouts (in Jenkins, proxies, or load balancers) from closing it. By default, pings are sent every 30 seconds.

You can configure this interval with the system property:

io.jenkins.plugins.mcp.server.Endpoint.keepAliveInterval=30

Set to `0` to disable keep-alive messages (not recommended for SSE).

> [!NOTE] > A ping is only delivered when there is an open server→client stream. SSE always has one. Streamable HTTP only has one while the client keeps a long-lived GET stream open; for a plain POST request/response client there is no stream to ping, so this setting has no effect.

Health Endpoint

A lightweight MCP-specific health endpoint is available for connection monitoring at:

<jenkins-url>/mcp-health

This endpoint: - Returns MCP server status and active connection counts - Requires no authentication for maximum accessibility - Returns immediately without MCP protocol overhead - Returns HTTP 200 when healthy, HTTP 503 during shutdown - Includes `Retry-After` header during shutdown

Response format:

{
  "mcpServerStatus": "ok",
  "activeConnections": 5,
  "shuttingDown": false,
  "timestamp": "2025-01-28T10:30:00Z"
}

**Recommended client usage:** - Poll the health endpoint periodically (e.g., every 10-30 seconds) - When the endpoint returns 503 or becomes unreachable, prepare for reconnection - Use the `Retry-After` header value when available

Metrics Endpoint

A metrics endpoint is available for monitoring connection statistics at:

<jenkins-url>/mcp-server/metrics

This endpoint requires authentication (standard Jenkins permissions) and provides:

{
  "sseConnectionsTotal": 42,

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 · 648 lines

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

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # MCP Server Plugin for Jenkins
  2. The MCP (Model Context Protocol) Server Plugin for Jenkins implements the server-side component of the Model Context Protocol. This plugin enables Jenkins to act as an MCP server, providing context, tools, and capabilities to MCP clients, such as LLM-powered applications or IDEs.
  3. ## Features
  4. - **MCP Server Implementation**: Implements the server-side of the Model Context Protocol.
  5. - **Jenkins Integration**: Exposes Jenkins functionalities as MCP tools and resources.
  6. - **Extensible Architecture**: Allows easy extension of MCP capabilities through the `McpServerExtension` interface.
  7. ## Key Components
  8. 1. **Endpoint**: The main entry point for MCP communication, handling MCP transport connections and message routing.
  9. 2. **DefaultMcpServer**: Implements `McpServerExtension`, providing default tools for interacting with Jenkins jobs and builds.
  10. 3. **McpToolWrapper**: Wraps Java methods as MCP tools, handling parameter parsing and result formatting.
  11. 4. **McpServerExtension**: Interface for extending MCP server capabilities.
  12. ## MCP SDK Version
  13. This MCP Server is based on the MCP Java SDK version 0.17.2, which implements the MCP specification version 2025-06-18.
  14. ## Getting Started
  15. ### Configuration
  16. The MCP Server plugin automatically sets up necessary endpoints and tools upon installation, requiring no additional configuration.
  17. #### System properties
  18. The following system properties can be used to configure the MCP Server plugin:
  19. - hard limit on max number of log lines to return with `io.jenkins.plugins.mcp.server.extensions.BuildLogsExtension.limit.max=10000` (default 10000)
  20. - longest `searchBuildLog` pattern accepted with `io.jenkins.plugins.mcp.server.extensions.BuildLogsExtension.pattern.maxLength=1000` (default 1000 characters)
  21. - how many characters one `searchBuildLog` regex may read from a single log line before the search is abandoned, with `io.jenkins.plugins.mcp.server.extensions.BuildLogsExtension.pattern.maxReadsPerLine=10000000` (default 10,000,000)
  22. - disable stateless endpoint with `io.jenkins.plugins.mcp.server.Endpoint.disableMcpStateless=true` (default false)
  23. - disable SSE endpoint with `io.jenkins.plugins.mcp.server.Endpoint.disableMcpSse=true` (default false)
  24. - disable streamable HTTP endpoint with `io.jenkins.plugins.mcp.server.Endpoint.disableMcpStreamable=true` (default false)
  25. - allow anonymous MCP clients to skip the CSRF crumb with `io.jenkins.plugins.mcp.server.Endpoint.allowUnauthenticatedMcp=true` (default false)
  26. - reclaim idle Streamable HTTP sessions with `io.jenkins.plugins.mcp.server.Endpoint.sessionSweepInterval=1800` (seconds, default 1800, 0 disables)
  27. > [!WARNING]
  28. > `io.jenkins.plugins.mcp.server.Endpoint.allowUnauthenticatedMcp=true` weakens CSRF protection. MCP POSTs that send an `Authorization` header are exempt from the crumb, because a page on another site cannot add that header. Anonymous and session-cookie clients are not exempt unless this property is set. With it on, those POSTs rely on the Origin check, which allows a missing `Origin` and does nothing when the Jenkins root URL is unset. Leave the property `false` on any controller that browsers or anonymous users can reach. `mvn hpi:run` sets it so a local development controller accepts an MCP client without a crumb.
  29. #### Search pattern cost
  30. `searchBuildLog` runs your regular expression against every line of a build log, and some patterns
  31. cost far more than their length suggests, because Java's regex engine backtracks.
  32. Each match therefore gets a budget of character reads, and a search that runs past it stops with an
  33. error instead of carrying on. The budget is generous on purpose, so you are unlikely to meet it. If
  34. you do, simplify the pattern or search for plain text with `useRegex=false`, which has no budget.
  35. #### Origin header validation
  36. The MCP specification marks validating the `Origin` header of incoming requests as a `MUST`.
  37. By default, when an `Origin` header is present it is validated against the configured Jenkins root URL
  38. (`io.jenkins.plugins.mcp.server.Endpoint.requireOriginMatch` defaults to `true`). Requests that do not send
  39. an `Origin` header are still allowed, so AI agents that omit it keep working
  40. (`io.jenkins.plugins.mcp.server.Endpoint.requireOriginHeader` defaults to `false`).
  41. - To also reject requests that omit the `Origin` header, set
  42. `io.jenkins.plugins.mcp.server.Endpoint.requireOriginHeader=true`.
  43. - To disable Origin matching entirely (not recommended), set
  44. `io.jenkins.plugins.mcp.server.Endpoint.requireOriginMatch=false`.
  45. ### Connection Resilience
  46. The MCP Server plugin includes several features to improve connection reliability.
  47. The keep-alive and timeout tuning described below primarily concern the **SSE** transport (`/mcp-server/sse`), which holds a single long-lived server→client connection open and is therefore sensitive to idle timeouts in Jenkins, proxies, and load balancers. If you use **Streamable HTTP** (`/mcp-server/mcp`) with the usual request/response pattern, you are unlikely to need any of it (see [Transport Recommendation](#transport-recommendation)). The health, metrics, and graceful-shutdown features apply to all transports.
  48. #### Keep-Alive Messages
  49. For the **SSE** transport, the server sends periodic keep-alive pings over the open connection to detect broken connections and to stop idle timeouts (in Jenkins, proxies, or load balancers) from closing it. By default, pings are sent every 30 seconds.
  50. You can configure this interval with the system property:
  51. ```
  52. io.jenkins.plugins.mcp.server.Endpoint.keepAliveInterval=30
  53. ```
  54. Set to `0` to disable keep-alive messages (not recommended for SSE).
  55. > [!NOTE]
  56. > A ping is only delivered when there is an open server→client stream. SSE always has one. Streamable HTTP only has one while the client keeps a long-lived GET stream open; for a plain POST request/response client there is no stream to ping, so this setting has no effect. Those clients are covered by [Idle Session Cleanup](#idle-session-cleanup) instead.
  57. #### Idle Session Cleanup
  58. A **Streamable HTTP** session outlives the connection it was created on, because the protocol lets a client reconnect to a session it was disconnected from. A client that disappears without sending `DELETE /mcp-server/mcp` therefore leaves its session behind, along with the socket and servlet async context behind it. Left alone, those pile up until the controller runs out of file descriptors.
  59. The server reclaims them: a session with no open stream that has gone a full interval without a request is closed and dropped. The interval defaults to 30 minutes, so a stranded session lives for 30 to 60 minutes.
  60. You can configure it with the system property:
  61. ```
  62. io.jenkins.plugins.mcp.server.Endpoint.sessionSweepInterval=1800
  63. ```
  64. Set to `0` to keep sessions until the client deletes them or Jenkins restarts. That is the old behaviour, and it leaks.
  65. A client whose session was reclaimed gets `404` on its next request and should start a new one with `initialize`, which is what the protocol asks of it. To watch the cleanup, add a Jenkins log recorder at `DEBUG` on `io.modelcontextprotocol.server.transport.HttpServletStreamableServerTransportProvider` and look for `Evicting idle session`, or read `streamableSessionsActive` from the [metrics endpoint](#metrics-endpoint).
  66. #### Health Endpoint
  67. A lightweight MCP-specific health endpoint is available for connection monitoring at:
  68. ```
  69. <jenkins-url>/mcp-health
  70. ```
  71. This endpoint:
  72. - Returns MCP server status and active connection counts
  73. - Requires no authentication for maximum accessibility
  74. - Returns immediately without MCP protocol overhead
  75. - Returns HTTP 200 when healthy, HTTP 503 during shutdown
  76. - Includes `Retry-After` header during shutdown
  77. Response format:
  78. ```json
  79. {
  80. "mcpServerStatus": "ok",
  81. "activeConnections": 5,
  82. "shuttingDown": false,
  83. "timestamp": "2025-01-28T10:30:00Z"
  84. }
  85. ```
  86. **Recommended client usage:**
  87. - Poll the health endpoint periodically (e.g., every 10-30 seconds)
  88. - When the endpoint returns 503 or becomes unreachable, prepare for reconnection
  89. - Use the `Retry-After` header value when available
  90. #### Metrics Endpoint
  91. A metrics endpoint is available for monitoring connection statistics at:
  92. ```
  93. <jenkins-url>/mcp-server/metrics
  94. ```
  95. This endpoint requires authentication (standard Jenkins permissions) and provides:
  96. ```json
  97. {
  98. "sseConnectionsTotal": 42,
  99. "sseConnectionsActive": 3,
  100. "streamableRequestsTotal": 150,
  101. "streamableSessionsActive": 4,
  102. "connectionErrorsTotal": 2,
  103. "uptimeSeconds": 3600,
  104. "startTime": "2025-01-28T10:00:00Z"
  105. }
  106. ```
  107. `streamableSessionsActive` is the number of Streamable HTTP sessions the server is currently holding. It is left out when the streamable endpoint is disabled or has not served a request yet.
  108. #### Graceful Shutdown
  109. When Jenkins shuts down, the health endpoint will return `503 Service Unavailable` with a brief grace period before full termination. This allows clients to detect the shutdown and prepare for reconnection.
  110. #### Transport Recommendation
  111. For better connection reliability, we recommend using **Streamable HTTP** (`/mcp-server/mcp`) instead of **SSE** (`/mcp-server/sse`). Streamable HTTP handles connection issues more gracefully and is the preferred transport for most MCP clients.
  112. #### Production Deployment
  113. When deploying the **SSE** transport behind a reverse proxy or in production environments, configure the timeout settings below so the long-lived connection is not dropped prematurely. Streamable HTTP users generally don't need this (see the note at the end of this section).
  114. **Jenkins/Jetty Configuration (SSE)**
  115. Jenkins uses Winstone (embedded Jetty) which defaults `httpKeepAliveTimeout` to 30 seconds. Since MCP keep-alive pings are also sent every 30 seconds, this creates a race condition where Jetty may close the SSE connection before the next ping arrives.
  116. Add this argument to your Jenkins startup command:
  117. ```
  118. --httpKeepAliveTimeout=600000
  119. ```
  120. For Docker deployments, add to your docker-compose.yml:
  121. ```yaml
  122. services:
  123. jenkins:
  124. image: jenkins/jenkins:lts
  125. command: ["--httpKeepAliveTimeout=600000"]
  126. ```
  127. **Reverse Proxy Configuration (Nginx)**
  128. For Nginx, extend timeouts for the MCP endpoints. This keeps SSE connections from being closed while idle:
  129. ```nginx
  130. location ~ ^/(mcp-server|mcp-health)/ {
  131. proxy_pass http://jenkins;
  132. proxy_http_version 1.1;
  133. proxy_request_buffering off;
  134. proxy_buffering off;
  135. proxy_set_header Connection "";
  136. proxy_read_timeout 600s;
  137. proxy_send_timeout 600s;
  138. }
  139. ```
  140. > [!NOTE]
  141. > The one timeout that can also affect **Streamable HTTP** is `proxy_read_timeout`: a single long-running tool call (for example a slow `triggerBuild`) can exceed a short default and return `504 Gateway Timeout`. Raising `proxy_read_timeout` as shown above prevents that regardless of transport. The `httpKeepAliveTimeout` race condition above is SSE-only.
  142. #### Transport Endpoints
  143. The MCP Server plugin provides three transport endpoints, all enabled by default:
  144. | Transport | Endpoint | Description |
  145. |-----------|----------|-------------|
  146. | **SSE** | `/mcp-server/sse` + `/mcp-server/message` | Server-Sent Events transport with session management |
  147. | **Streamable HTTP** | `/mcp-server/mcp` | Streamable HTTP transport with session management |
  148. | **Stateless** | `/mcp-server/stateless` | Stateless HTTP transport without session management |
  149. Each transport can be disabled independently using system properties:
  150. ```
  151. -Dio.jenkins.plugins.mcp.server.Endpoint.disableMcpSse=true
  152. -Dio.jenkins.plugins.mcp.server.Endpoint.disableMcpStreamable=true
  153. -Dio.jenkins.plugins.mcp.server.Endpoint.disableMcpStateless=true
  154. ```
  155. ##### When to use Stateless transport
  156. The stateless endpoint (`/mcp-server/stateless`) is useful for:
  157. - Simple deployments where session management overhead is not needed
  158. - Environments where clients make independent requests without maintaining a persistent connection
  159. - Testing and debugging scenarios
  160. - Clients that don't support session-based protocols
  161. ## Usage
  162. ### Connecting to the MCP Server
  163. MCP clients can connect to the server using:
  164. - Streamable HTTP Endpoint: `<jenkins-url>/mcp-server/mcp`
  165. - SSE Endpoint: `<jenkins-url>/mcp-server/sse`
  166. - Message Endpoint: `<jenkins-url>/mcp-server/message`
  167. - Stateless Endpoint: `<jenkins-url>/mcp-server/stateless`
  168. ### Authentication and Credentials
  169. The MCP Server Plugin requires the same credentials as the Jenkins instance it's running on. To authenticate your MCP queries:
  170. 1. **Jenkins API Token**: Generate an API token from your Jenkins user account.
  171. 2. **Basic Authentication**: Use the API token in the HTTP Basic Authentication header.
  172. #### Generate a personal access token
  173. To generate a personal access token:
  174. - Sign in to Jenkins.
  175. - Select your user icon in the upper-right corner, and then select `Security`.
  176. - Select `Add new token`.
  177. - Enter a name to distinguish the token, and then select `Generate`.
  178. - Copy the token and store it in a secure location for later use.
  179. > [!WARNING]
  180. > Once you leave the page, you cannot view or copy the token again.
  181. - Select `Done` to add the token.
  182. - Select `Save` to save your changes.
  183. #### Encode credentials for HTTP basic authentication
  184. Use basic HTTP authentication with the MCP agent by encoding it with the personal access token.
  185. To encode credentials on Linux, macOS, or Windows:
  186. Open a terminal and run the following command, replacing `<username>` and `<token>` with your actual username and the personal access token you generated in Jenkins
  187. - Linux or macOS
  188. ```bash
  189. echo -n "<username>:<token>" | base64
  190. ```
  191. - Windows (PowerShell)
  192. ```powershell
  193. [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("<username>:<token>"))
  194. ```
  195. if successful, the Base64-encoded credential is output, similar to the following:
  196. ```bash
  197. dXNlcm5hbWU6dG9rZW4=
  198. ```
  199. Store the encoded credential in a secure location for later use.
  200. > [!NOTE]
  201. > Base64 encoding is not encryption.
  202. > Anyone with access to the encoded string can decode it and obtain your credentials.
  203. > Always protect the encoded credentials as if they are the original username and token.
  204. ### Example Client Configurations
  205. #### Cline Configuration
  206. ```json
  207. {
  208. "mcpServers": {
  209. "jenkins": {
  210. "autoApprove": [
  211. ],
  212. "disabled": false,
  213. "timeout": 60,
  214. "type": "streamableHttp",
  215. "url": "https://jenkins-host/mcp-server/mcp",
  216. "headers": {
  217. "Authorization": "Basic <user:token base64>"
  218. }
  219. }
  220. }
  221. }
  222. ```
  223. #### Copilot Configuration
  224. I tested GitHub Copilot Chat in VS Code with the Streamable HTTP endpoint, and it successfully called the Jenkins `getStatus` tool. The Copilot CLI and desktop app have not been tested.
  225. ```json
  226. {
  227. "mcp": {
  228. "servers": {
  229. "jenkins": {
  230. "type": "http",
  231. "url": "https://jenkins-host/mcp-server/mcp",
  232. "headers": {
  233. "Authorization": "Basic <user:token base64>"
  234. }
  235. }
  236. }
  237. }
  238. }
  239. ```
  240. Streamable example:
  241. ```json
  242. {
  243. "servers":{
  244. "jenkins":{
  245. "type":"http",
  246. "url":"http://jenkins-host/mcp-server/mcp",
  247. "requestInit":{
  248. "headers":{
  249. "Authorization":"Basic <user:token base64>"
  250. }
  251. }
  252. }
  253. }
  254. }
  255. ```
  256. #### Windsurf Configuration
  257. ```json
  258. {
  259. "servers": {
  260. "jenkins": {
  261. "command": "npx",
  262. "args": [
  263. "mcp-remote",
  264. "http://jenkins-host/mcp-server/mcp",
  265. "--header",
  266. "Authorization: Bearer ${AUTH_TOKEN}"
  267. ],
  268. "env": {
  269. "AUTH_TOKEN": "Basic <user:token base64>"
  270. }
  271. }
  272. }
  273. }
  274. ```
  275. #### Cursor Configuration
  276. ```json
  277. {
  278. "mcpServers": {
  279. "jenkins": {
  280. "type": "http",
  281. "url": "https://jenkins-host/mcp-server/mcp",
  282. "headers": {
  283. "Authorization": "Basic <user:token base64>"
  284. }
  285. }
  286. }
  287. }
  288. ```
  289. #### Claude
  290. ```bash
  291. claude mcp add jenkins http://jenkins-host/mcp-server/mcp --transport http --header "Authorization: Basic <user:token base64>"
  292. ```
  293. #### Stateless Configuration Example
  294. For clients that prefer stateless communication without session management:
  295. ```json
  296. {
  297. "servers": {
  298. "jenkins": {
  299. "type": "http",
  300. "url": "http://jenkins-host/mcp-server/stateless",
  301. "requestInit": {
  302. "headers": {
  303. "Authorization": "Basic <user:token base64>"
  304. }
  305. }
  306. }
  307. }
  308. }
  309. ```
  310. #### Goose
  311. - Click *“Add custom extension”*
  312. - Give it a meaningful name
  313. - In the type Dropdown, select *“Streamable HTTP”*
  314. - Enter the endpoint URL. This should be something like `http://jenkins-host/mcp-server/mcp`
  315. - Scroll to *“Request Headers”*
  316. - In the empty field, type `Authorization` as the name. Then in the Value field, type `“Basic <user:token base64>”`
  317. - Click *"Add"*
  318. - Click *“Add Extension”*
  319. ### Available Tools
  320. The plugin provides the following built-in tools for interacting with Jenkins:
  321. #### Job Management
  322. - `createPipeline`: Create a new sandboxed Jenkins pipeline job (requires the Pipeline: Job and Pipeline: Groovy plugins). Required parameters: `jobName` (name or full path of the pipeline) and `pipelineScript` (Jenkins pipeline script). Parent folders must already exist. If a job with the provided name already exists, an error is returned.
  323. - `getJob`: Get a Jenkins job by its full path.
  324. - `getJobs`: Get a paginated list of Jenkins jobs, sorted by name.
  325. - `triggerBuild`: Trigger a build of a job.
  326. This tool supports parameterized builds. You can provide parameters as a JSON object where each key is the parameter name. For example:
  327. ```json
  328. {
  329. "jobFullName": "my-job",
  330. "parameters": {
  331. "BRANCH": "main",
  332. "DEBUG_MODE": "true"
  333. }
  334. }
  335. ```
  336. Note on Parameters:
  337. - **Core Jenkins Parameters**: Fully supported (String, Boolean, Choice, Text, Password, Run)
  338. - **Plugin Parameters**: Automatically detected and handled using reflection
  339. - **File Parameters**: Not supported via MCP (require file uploads)
  340. - **Multi-select Parameters**: Supported as arrays or lists
  341. - **Custom Plugin Parameters**: Automatically attempted using reflection-based detection
  342. - **Fallback Behavior**: Unsupported parameters fall back to default values with logging
  343. This tool returns a queue item if the job is successfully scheduled. You can use the returned queue item ID with the `getQueueItem` tool.
  344. - `getQueueItem`: Get information about a queued item using its ID.
  345. - `cancelBuild`: Cancel a running build or an item in the queue.
  346. #### Build Information
  347. - `getBuild`: Retrieve a specific build or the last build of a Jenkins job.
  348. - `updateBuild`: Update build display name and/or description.
  349. - `getBuildLog`: Retrieve log lines with pagination for a specific build or the last build. Supports forward reads, end-relative reads (negative `skip`/`limit`), and cursor pagination: every response carries a `nextCursor` you can pass back as `cursor` to keep reading without re-scanning from the top. The cursor is tied to the `(job, buildNumber)` it was issued for and is rejected if used against a different build. `totalLines` is exact for end-relative reads and `-1` for forward/cursor reads (which stop as soon as they have enough lines, so the total is never computed). Reads a non-blocking snapshot, so it returns promptly even while a build is still running. If `nextCursor` is set but `hasMoreContent` is false, you've read everything written so far and the build is still going; hold onto the cursor and call again later to pick up whatever was appended in between.
  350. - `searchBuildLog`: Search for log lines matching a pattern (string or regex) in build logs. Reads a non-blocking snapshot (returns promptly for in-progress builds) and stops scanning early once `maxMatches` is reached.
  351. - `rebuildBuild`: Re-run a build with the same parameters and the same trigger causes (for example a GitLab or GitHub webhook cause), like the Rebuild button. The new run is credited to the MCP caller, not to the user who started the original. Pipeline jobs run their current script (for a multibranch job, the current head of the branch); to re-run the original script, use `getReplayScripts` and `replayBuild`. Optional `buildNumber`; defaults to the last build. Returns the queue item for the new build.
  352. - `getReplayScripts`: Return the main script and loaded scripts of a replayable Pipeline build. Use this to inspect or modify script before calling `replayBuild`. Fails for non-Pipeline jobs. Optional `buildNumber`; defaults to the last build.
  353. - `replayBuild`: Run a Pipeline build again with a modified script. Provide `mainScript` (required) and optionally `loadedScripts`. Optional `buildNumber`; defaults to the last build. Fails if the build is not replayable or replay is not allowed (e.g. permissions or sandbox).
  354. - `getTestResults`: Retrieve test results of a specific build or the last build. Returns a compact summary by default (`summary=true`): the build number, the total/fail/skip/pass counts, how many tests were flaky, and one entry per failing test with its class name, test name, failure message (cut to 512 characters — the head of the stack trace is used when the test reported no message) and `age`, the number of consecutive builds it has been failing. Pass `summary=false` for the full junit records, which include each test's `stdout`, `stderr` and error stack trace and can run to several megabytes on a build with many failures. Pass `onlyFailingTests=true` to get those full records for the failing tests only — omitting `summary` while passing `onlyFailingTests=true` resolves `summary` to `false`, since asking for the failing tests on their own is taken as asking for their detail.
  355. - `getFlakyFailures`: Retrieve the flaky failures of a specific build or the last build — tests that failed and then passed on a retry. Also returns a compact summary by default: the build number, how many tests were flaky and how many attempts failed, plus each test's class name, test name and the message and type of every flaky attempt. Pass `summary=false` for each attempt's stack trace, `stdout` and `stderr`.
  356. #### SCM Integration
  357. - `getJobScm`: Retrieve SCM configurations of a Jenkins job.
  358. - `getBuildScm`: Retrieve SCM configurations of a specific build.
  359. - `getBuildChangeSets`: Retrieve change log sets of a specific build.
  360. - `findJobsWithScmUrl`: Find jobs using a specific SCM (git) repository URL
  361. #### Management Information
  362. - `whoAmI`: Get information about the current user.
  363. - `getStatus`: Checks the health and readiness status of a Jenkins instance. Use this tool to assess Jenkins instance health rather than simple up/down status.
  364. - `getSystemLog`: Read recent entries from the Jenkins system log (newest first), optionally from a named Log Recorder or filtered by a minimum level. Requires the Overall/SystemRead permission.
  365. - `getLogRecorders`: List the names of configured Jenkins Log Recorders, for use with `getSystemLog`. Requires the Overall/SystemRead permission.
  366. Each tool accepts specific parameters to customize its behavior. For detailed usage instructions and parameter descriptions, refer to the API documentation or use the MCP introspection capabilities.
  367. To use these tools, connect to the MCP server endpoint and make tool calls using your MCP client implementation.
  368. ### Enhanced Parameter Support
  369. The MCP Server Plugin now provides comprehensive support for Jenkins parameters:
  370. #### Supported Parameter Types
  371. - **String Parameters**: Text input with default values
  372. - **Boolean Parameters**: True/false values with automatic type conversion
  373. - **Choice Parameters**: Dropdown selections with validation
  374. - **Text Parameters**: Multi-line text input
  375. - **Password Parameters**: Secure input with Secret handling
  376. - **Run Parameters**: Build number references
  377. - **Plugin Parameters**: Automatically detected and handled
  378. #### Parameter Handling Features
  379. - **Type Conversion**: Automatic conversion between JSON types and Jenkins parameter types
  380. - **Validation**: Choice parameters validate input against available options
  381. - **Fallback**: Unsupported parameters gracefully fall back to defaults
  382. - **Reflection**: Plugin parameter types automatically detected and handled
  383. - **Logging**: Comprehensive logging for debugging parameter issues
  384. #### Example Usage
  385. ```json
  386. {
  387. "jobFullName": "my-parameterized-job",
  388. "parameters": {
  389. "BRANCH": "main",
  390. "DEBUG_MODE": true,
  391. "ENVIRONMENT": "production",
  392. "FEATURES": ["feature1", "feature2"],
  393. "NOTES": "Build triggered via MCP"
  394. }
  395. }
  396. ```
  397. ### Extending MCP Capabilities
  398. To add new MCP tools or functionalities:
  399. 1. Create a class implementing `McpServerExtension`.
  400. 2. Use `@Tool` to expose methods as MCP tools.
  401. 3. Use `@ToolParam` to define and describe tool parameters.
  402. Example:
  403. ```java
  404. @Extension
  405. public class MyCustomMcpExtension implements McpServerExtension {
  406. @Tool(description = "My custom tool")
  407. public String myCustomTool(@ToolParam(description = "Input parameter") String input) {
  408. // Tool implementation
  409. }
  410. }
  411. ```
  412. #### Constraining parameter values
  413. For an object-shaped parameter (typically a `Map`), you can advertise a JSON Schema constraint on the
  414. *values* while keeping the keys open, using `@ToolParam(additionalProperties = "<json>")`. The value is a
  415. raw JSON sub-schema — a JSON object or a boolean — emitted verbatim as the parameter's `additionalProperties`:
  416. ```java
  417. @Tool(description = "My custom tool")
  418. public String myCustomTool(
  419. @ToolParam(
  420. description = "Extra options",
  421. required = false,
  422. additionalProperties = "{\"type\":[\"string\",\"boolean\",\"integer\",\"number\",\"array\"]}")
  423. Map<String, Object> options) {
  424. // Tool implementation
  425. }
  426. ```
  427. Invalid JSON, or a value that isn't a JSON object or boolean, fails fast when the tool is registered.
  428. #### Restricting a tool by permission
  429. Add `permissions` to `@Tool` to require the caller to hold a Jenkins permission. List one or more
  430. permission ids (as returned by `Permission.getId()`, for example `hudson.model.Hudson.SystemRead`):
  431. ```java
  432. @Tool(
  433. description = "Read the Jenkins system log",
  434. permissions = {"hudson.model.Hudson.SystemRead"})
  435. public SystemLog readSystemLog() {
  436. // ...
  437. }
  438. ```
  439. The caller must hold **at least one** of the listed permissions. A tool that fails the check is hidden
  440. from `tools/list` and rejected on `tools/call`. When Jenkins security is disabled, every tool is
  441. available. Permission ids are resolved when the server starts, so a typo fails fast. For a sensitive
  442. operation, still call `Jenkins.get().checkPermission(...)` inside the method as defence in depth.
  443. **Overall permissions only.** The check runs against the Jenkins root, so `permissions` is for global
  444. permissions such as `Overall/SystemRead` or `Overall/Administer`. It cannot express item-scoped
  445. permissions like `Item.READ` on a particular folder or job — a tool has no item context. Enforce those
  446. inside the method against the specific item (for example `job.checkPermission(Item.READ)`).
  447. ### Overriding a Built-in Tool
  448. You can replace a built-in tool (or any tool contributed by another plugin) with your own
  449. implementation from a separate plugin. Declare a `@Tool` with the **same name** and set
  450. `override = true`:
  451. ```java
  452. @Extension
  453. public class MyBuildLogExtension implements McpServerExtension {
  454. @Tool(name = "getBuildLog", description = "My own getBuildLog", override = true)
  455. public MyResponse getBuildLog(@ToolParam(description = "Job full name") String jobFullName) {
  456. // Your implementation replaces the built-in getBuildLog
  457. }
  458. }
  459. ```
  460. Rules:
  461. - Overriding is an explicit opt-in. A tool only replaces another tool of the same name when it sets
  462. `override = true`. This guarantees a built-in tool is never silently shadowed by an accidental name
  463. clash.
  464. - If two tools share a name and **none** of them sets `override = true`, the existing (built-in) tool
  465. is kept and the duplicate is skipped with a warning in the logs.
  466. - The `@Extension(ordinal = ...)` value is only used to break ties when **several** tools declare
  467. `override = true` for the same name: the one provided by the extension with the highest ordinal
  468. wins.
  469. - Each tool name is exposed exactly once, so MCP clients always see a single `getBuildLog`.
  470. ### Result Handling
  471. The MCP Server Plugin handles various result types with the following approach:
  472. - **List Results**: Each element in the list is converted to a separate text content item in the response.
  473. - **Single Objects**: The entire object is converted into a single text content item.
  474. For serialization to text content:
  475. - **@ExportedBean Annotation**: If the result object is annotated with `@ExportedBean` (from `org.kohsuke.stapler.export`), Jenkins' `org.kohsuke.stapler.export.Flavor.JSON` exporting mechanism is used.
  476. - **Other Objects**: For objects without the `@ExportedBean` annotation, Jackson is used for JSON serialization.
  477. #### Field selection with `tree` and per-tool defaults
  478. Tools returning `@ExportedBean` objects accept an optional `tree` parameter using the
  479. [Jenkins Remote REST API tree syntax](https://www.jenkins.io/doc/book/using/remote-access-api/#RemoteaccessAPI-Depthcontrol)
  480. (for example `tree=name,url,lastBuild[number,result]`) to limit which fields are returned.
  481. A tool may also declare a **default tree** (`@Tool(defaultTree = "...")`), applied only when the
  482. caller does not pass `tree`. The built-in `getBuild`, `getJob` and `getJobs` tools use such compact
  483. defaults: without an explicit `tree` they return the identity/status essentials rather than the full
  484. exported model, which keeps responses small for LLM context windows. Pass your own `tree`
  485. expression to request any other fields — an explicit `tree` always takes precedence over the
  486. default, and passing `tree="*"` returns the full exported object (pruning disabled), bypassing the
  487. default entirely. Tools without a declared default keep returning the full exported object.
  488. This approach ensures flexible and efficient handling of different result types, accommodating both Jenkins-specific exported objects and standard Java objects.
  489. This flexible approach ensures that tool results are consistently and accurately represented in the MCP response, regardless of their complexity.
  490. ### Integration with GitHub Copilot
  491. The MCP Server Plugin seamlessly integrates with GitHub Copilot, enhancing your development experience by providing direct access to Jenkins information within your IDE. This integration allows you to interact with Jenkins jobs and builds using natural language queries.
  492. ![GitHub Copilot Integration](doc/copilot.png)
  493. As shown in the screenshot:
  494. 1. You can ask Copilot about Jenkins jobs using natural language, e.g., "list jenkins job under root".
  495. 2. Copilot uses the MCP Server to fetch and display information about Jenkins jobs, listing the jobs under the root directory.
  496. 3. You can also request specific information, such as "get the last build status of job a", and Copilot will provide the relevant details including build number, status, and URL.
  497. This integration streamlines your workflow by allowing you to access Jenkins information without leaving your development environment.
  498. ### Further Information
  499. For more details on the Model Context Protocol and its Java SDK:
  500. - [MCP Introduction](https://modelcontextprotocol.io/introduction)
  501. - [MCP Java SDK Server Component](https://modelcontextprotocol.io/sdk/java/mcp-server)
  502. ### Contributing
  503. Contributions to the MCP Server plugin are welcome. Please refer to the [Jenkins contribution guidelines](https://github.com/jenkinsci/.github/blob/master/CONTRIBUTING.md) for more information.
  504. ### License
  505. This project is licensed under the MIT License - see the [LICENSE](LICENSE.md) file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

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