jenkins mcp 설치 방법과 jenkin server에 등록된 job list 를 불러오는 방법과 실제 동작하는 소스코드를 제공합니다. jenkins mcp가 2025년 6월18일에 공개되어서 github에 올라와 있는 jenkins mcp 프로젝트들을 모두 실행해 보았으나 정상 작동하지 않는 것을 확인하였습니다. 시행착오를 거치면서 직접 작동하는 jenkins mcp 코드를 공개합니다.

Table of Contents
작업 디렉토리 생성하기
jenkins job 목록을 가져올 행동을 하는 애플리케이션 파일 이름을 client.py 라고 생성합니다. 동일한 디렉토리에서 사용할 파이선의 가상 .venv 디렉토리도 아래 명령어를 실행하여 생성합니다. 제가 사용하는 python 버전은 3.13.5 입니다.
python 가상 환경 설정하기
앞으로 설치되는 패키지들은 가상환경인 .venv 에 설치되도록 pip install <패키지명>으로 설치하여 사용합니다. 일단 가상 환경이 리눅스 환경에서 실행되도록 source명령어로 아래와 같이 activate 시켜줍니다.
mkidr jenkins_job
cd ./jenkins_job
touch client.py
python -m venv .venv
source .venv/bin/activate
jenkins mcp 개발 패키지 설치
jenkins mcp 의 서버 코드를 개발하려면 기본적으로 HTTP 통신을 지원하고 로그를 출력하기 위한 패키지들을 설치해야 합니다. requirements.txt 라는 파일 안에 아래와 같이 기입하고 저장합니다. 아래의 pip 명령어를 실행하면 패키지들이 설치됩니다.
pip install -r requirements.txt
프로젝트를 생성한 디렉토리에 .env파일에 아래와 같은 내용을 기록합니다.
pip install python-dotenv
vim .env
아래에는 .env 파일에 기록해야 하는 내용입니다. vim 에디터에서 글자를 입력하는 명령어는 i 글자를 눌어줘야 합니다. 기록을 완료한 후에 파일에 저장하려면 ESP 버튼을 한번 누른후에 :wq! 라고 입력을 해주어야 합니다. 그냥 vim 에디터에서 빠져나오면 파일에 기록한 내용이 디스크에 저장되지 않습니다.
JENKINS_URL="http://localhost:8080"
JENKINS_USERNAME="아이디"
JENKINS_PASSWORD="비밀번호"
JENKINS_TOKEN="jenkins서버에서 발급받은 API토큰키"
jenkins mcp 프로그램은 client 프로그램으로서 jenkins server를 설치하여 동작하고 있어야 합니다. client.py 파일의 내용에 아래의 내용을 복사해서 붙여넣습니다. vim client.py 를 실행하여 에디터 화면으로 들어간 후에 i 키를 눌러서 편집 모드로 들어갑니다.
마우스 오른쪽 키를 클릭해서 복사한 아래의 소스코드를 에디터 창에 붙여넣기를 합니다. ESC 키를 누른후에 :wq! 를 눌러주면 소스코드 내용이 파일에 저장되고 vim 에디터에서 빠져나오게 됩니다.
import os
import ssl
import jenkins
from dotenv import load_dotenv
load_dotenv() # .env 파일에서 환경 변수 로드
# --- Jenkins 서버 설정 (환경 변수 또는 직접 설정) ---
# 보안을 위해 환경 변수 사용을 강력히 권장합니다.
# 예시:
# export JENKINS_URL="http://your.jenkins.server:8080"
# export JENKINS_USER="your_jenkins_username"
# export JENKINS_TOKEN="your_jenkins_api_token" # API 토큰을 사용하세요!
JENKINS_URL = os.getenv("JENKINS_URL", "http://localhost:8080") # 기본값 설정
JENKINS_USER = os.getenv("JENKINS_USER", "user")
JENKINS_TOKEN = os.getenv("JENKINS_TOKEN", "your_api_token_here") # 실제 토큰으로 교체!
# SSL 인증서 검증 비활성화 (개발/테스트 환경에서만 사용 권장)
# 실제 운영 환경에서는 유효한 SSL 인증서를 사용하거나 올바른 방식으로 검증을 활성화해야 합니다.
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't have _create_unverified_context
pass
else:
ssl._create_default_https_context = _create_unverified_https_context
def get_all_jenkins_jobs():
"""
python-jenkins 라이브러리를 사용하여 Jenkins의 모든 Job 목록을 가져옵니다.
"""
try:
# Jenkins 클라이언트 생성
# python-jenkins 라이브러리를 사용하여 Jenkins 서버에 직접 연결합니다.
jenkins_client = jenkins.Jenkins(
JENKINS_URL,
username=JENKINS_USER,
password=JENKINS_TOKEN # API 토큰을 비밀번호로 사용
)
print(f"Jenkins 서버에 연결 중: {JENKINS_URL} (사용자: {JENKINS_USER})...")
# get_jobs() 메서드 호출
# 이 메서드는 Jenkins 서버에서 모든 Job 목록을 가져옵니다.
jobs = jenkins_client.get_jobs()
if jobs:
print("\n--- Jenkins Job 목록 (via python-jenkins client) ---")
for job in jobs:
# 'name' 키를 사용하여 Job 이름을 출력합니다.
if isinstance(job, dict) and 'name' in job:
print(f"- {job['name']}")
else:
print(f"- Job 정보 형식 오류 또는 예상치 못한 데이터: {job}")
print("---------------------------------------")
else:
print("Jenkins 서버에 Job이 존재하지 않거나 가져올 수 없습니다.")
except Exception as e:
print(f"오류 발생: {e}")
print("Jenkins URL, 사용자 이름, API 토큰(또는 비밀번호)이 올바른지 확인하거나,")
print("Jenkins 서버가 실행 중이고 접근 가능한지 확인하십시오.")
if __name__ == "__main__":
get_all_jenkins_jobs()
jenkins mcp git 으로 코드받아오기
제가 개발해서 테스트에 성공할 예제 코드는 아래의 git 명령어를 실행하셔서 다운로드 받을 수 있습니다.
git clone https://github.com/big0001data/jenkins_mcp.git
jenkins mcp 서버 구현하기
| Tool | Description |
|---|---|
| get_all_jobs | Get all jobs |
| get_job_config | Get job config |
| search_jobs | Search job by specific field |
| get_running_builds | Get running builds |
| stop_build | Stop running build |
| get_build_info | Get build info |
| get_build_sourcecode | Get the pipeline source code of a specific build in Jenkins |
| get_job_info | Get job info |
| build_job | Build a job with param |
| get_build_logs | Get build logs |
| get_all_nodes | Get nodes |
| get_node_config | Get the config of node |
| get_all_queue_items | Get all queue items |
| get_queue_item | Get queue item info |
| cancel_queue_item | Cancel queue item |
| get_multibranch_jobs | Get all multibranch pipeline jobs from Jenkins, optionally filtered by patterns |
| get_multibranch_branches | Get all branches for a specific multibranch pipeline job |
| scan_multibranch_pipeline | Trigger a scan of a multibranch pipeline to discover new branches |
jenkins mcp 서버 구현
mcp_sever 로 동작하는 기능은 sysinfo.py에 구현되어 있습니다. mcp_client 의 기능과 mcp_server 가 연동할 때에는 config.json 파일에 mcp_server 기능을 하는 python 코드의 경로를 지정합니다.
가장 간단한 예제로서 MCP_SERVER에서 cpu의 플랫폼 정보(버전, 릴지즈번호 등)와 GPU 정보를 읽어서 mcp_client에게 전달해주는 역할을 합니다.
import platform
import psutil
import GPUtil
import asyncio
async def get_system_info():
output = []
system_info = platform.uname()
output.append("System Information:")
cpu_info = platform.processor()
cpu_count = psutil.cpu_count(logical=False)
logical_cpu_count = psutil.cpu_count(logical=True)
output.append("\nCPU Information:")
memory_info = psutil.virtual_memory()
output.append("\nMemory Information:")
disk_info = psutil.disk_usage('/')
output.append("\nDisk Information:")
output.append(f"Total Disk Space: {disk_info.total} bytes")
return "\n".join(output)
if __name__ == "__main__":
res = asyncio.run(get_system_info())
print(res)
jenkins api와 채팅 자연어 입력을 연결하는 구문
get_sysinfo() 라는 함수의 앞부분에 @mcp.tool() 데코레이터를 부착하면 mcp서버가 채팅으로 입력한 자연어와 jenkins api 함수를 연결하는 목적으로 사용학 ㅔ됩니다.
from typing import Any
from mcp.server.fastmcp import FastMCP
from fetch_info import get_system_info
# Initialize FastMCP server
mcp = FastMCP("sysinfo")
@mcp.tool()
async def get_sysinfo() -> str:
"""Get the current system information.
Gives system information such as System, Node name, Release, Version, Machine, Processor
CPU Information such as Processor, Physical Cores, Logical Cores
Memory Information such as Total Memory, Available Memory, Used Memory, Memory Utilization
Disk Information such as Total Disk Space, Used Disk Space, Free Disk Space, Disk Space Utilization
"""
data = await get_system_info()
return data
if __name__ == "__main__":
# Initialize and run the server
mcp.run(transport='stdio')
jenkins mcp client 구현
jenkins mcp client 기능은 채팅으로 자연어를 입력받는 부분과 자연어로 해석한 후에 jenkins api 기능을 호출하는 기능을 구현합니다.
jenkins mcp 를 이용해서 http://localhost:8080 으로 동작하고 있는 jenkins server로부터 job목록을 불러오는 기능을 아래와 같이 구현을 하고 채팅클라이언트앱에서 불러올 수 있도록 @mcp.too( ) 이라는 데코레이터를 추가해둡니다.
jenkins job 목록을 읽어오는 jenkins mcp 서버 기능 추가하기
함수의 이름 앞에 영어로 주석을 추가하면 채팅 클라이언트 앱에서 OPENAI 언어 모델 또는 OLLAMA 언어모델이 아래 함수를 이해해서 아래 함수를 호출하게 됩니다. 각 함수의 내부에서는 jenkins 회사에서 제공하는 공식 jenkins_api 를 호출하도록 구성됩니다.
# The job list request uses the GET method.
# No request body or Content-Type header is required.
@mcp.tool( )
def get_jenkins_job_list():
# Send GET request
try:
print("Fetching Jenkins job list...")
response = requests.get( # Use GET instead of POST.
api_url,
auth=(username, api_token),
# requests library follows redirects by default.
# verify=False skips SSL certificate verification (not needed for HTTP).
)
# Check response status code
if response.status_code == 200:
print("Successfully fetched Jenkins job list.")
# Parse JSON response
jobs_data = response.json()
# Check for "jobs" key in response and print job list
if "jobs" in jobs_data:
print("\n--- Jenkins Job List ---")
if jobs_data["jobs"]:
for job in jobs_data["jobs"]:
# Print only the job_list provided as "name".
print(f"- {job['name']}")
else:
print("No jobs found in Jenkins.")
else:
print("Could not find 'jobs' key in response. Check Jenkins API response format.")
print(f"Full response: {jobs_data}")
else:
print(f"Error fetching job list: {response.status_code} - {response.text}")
print("Jenkins response details:")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
Jenkins mcp 서버에서 job 을 create 하는 방법
job_config.xml 파일을 jenkins 서버가 동작하고 있는 http://localhost:8080 으로 전송하면 jenkins 서버의 job 목록에 새로운 job이 생성됩니다. job_config.xml 은 아래와 같은 형태로 작성할 수 있습니다.
<?xml version='1.1' encoding='UTF-8'?>
<project>
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers/>
<concurrentBuild>false</concurrentBuild>
<builders>
<hudson.tasks.Shell>
<command>{shell_command}</command>
</hudson.tasks.Shell>
</builders>
<publishers/>
<buildWrappers/>
</project>
위 코드에서 <command>{shell_command}</command> 부분에 jenkins 서버에서 실행하고자 하는 작업을 쉘 스크립트로 추가할 수 있습니다. job_config.xml 파일을 만들지 않고 python 코드 내부에서 컨텐츠의 내용을 직접 메세지로 만들어서 jenkins 서버에게 전송할 수 있습니다.
jenkins mcp 를 job 실행하기
jenkins mcp에서 jenkins 서버의 job 목록을 선정하여 build 하도록 요청하면 job이 실행된 결과를 jenkins_mcp_server 에게 전송합니다. jenkins 서버에서 job 실행에 성공하면 jenkins_mcp_server 에 성공 메세지가 출력됩니다.
@mcp.tool()
def jenkins_server_build_job(job_name: str) -> str:
"""
Triggers a build for the specified Jenkins job.
Args:
job_name (str): The name of the Jenkins job to build.
Returns:
str: Success or error message.
"""
api_url = f"{jenkins_url}/job/{job_name}/build"
try:
response = requests.post(
api_url,
auth=(username, api_token),
timeout=10
)
if response.status_code in [200, 201, 302]:
msg = f"Job '{job_name}' build triggered successfully."
if response.status_code == 302 and 'Location' in response.headers:
msg += f" Redirected to: {response.headers['Location']}"
return msg
else:
return f"Error triggering build for job '{job_name}': {response.status_code} - {response.text}"
except requests.exceptions.RequestException as e:
return f"Request failed: {e}"
except Exception as e:
return f"Unexpected error: {e}"
chatting jenkins mcp client 앱과 jenkins mcp server를 연결하는 방법
jenkins mcp 서버를 직접 개발하실 때 핵심은 채팅앱 코드( ex: mcp_client.py )와 jenkins 서버코드 ( ex: jenkins_mcp_server.py )을 연결하는 부분이었습니다. mcp_client 디렉토리에 있는 mcp_config.json 에 “jenkins_mcp” 이름과 실제 jenkins mcp server 로 동작하는 코드의 경로와 실행파일 jenkins_mcp_server.py 를 추가하는 것입니다.
mcp_config.json 파일을 mcp_client/main.py에서 동작하는 언어모델인 OPANAI 또는 OLLAMA 가 인식하여 jenkins_mcp_server.py 를 파싱하게 되고 함수의 바로 앞에 배치한 데코레이터인 @mcp.tool( ) 을 인식합니다.
언어모델은 @mcp.tool( ) 앞뒤에 있는 주석들을 해석하여 어떤 역할을 하는 함수인지 판단하게 됩니다. 사용자가 채팅창을 통해서 입력한 자연어 요청을 언어모델이 해석하여 jenkins api를 활용해서 제공할 수 있는 서비스라고 판단이 되면 @mcp.tool( )로 마킹된 함수 중에서 가장 유사한 주석의 내용에 해당하는 jenkins api 를 호출하게 됩니다.
jenkins_mcp_server.py 내부의 특정 함수가 호출되면서 requests 프레임 형태로 진짜 jenkins 서버가 동작중인 서버 엔드포인트인 http://localhost:8080 에게 job을 create 시켜달라거나 또는 job 을 삭제시켜달라거나 또는 job 의 목록을 제공해달라는 요청을 하게됩니다.
jenkins서버 엔드포인트는 요청한 jenkins_mcp_server.py 에게 요청에 대한 응답을 해주게 되고 다시 그 내용을 언어모델이 해석하여 사람이 읽을 수 있는 자연어로 변환하여 채팅창에 답변으로 제공하게 됩니다.
함께보면 jenkins mcp server 개발에 정말 도움 되는 글
smithery에 올라온 각종 mcp 서버 모듈을 불러다가 사용하면 편리하기는 합니다. 하지만, 개발자가 직접 서비스를 제공하는 mcp server 개발 능력을 갖추지 못하고 직접 수익화를 시키는 방법을 익히지 못한다면 gemini_cli 와 같은 자동 코드 생성 서비스들이 무료로 제공되는 시대에 생존의 위험에 처하게 될 것입니다.
atlassian mcp 설치 방법 및 사용 방법 자세히 알아보기
claude 를 이용해서 atlasian mcp를 설치하고 채팅창에서 자연어로 입력하여 jira 웹페이지를 생성 및 삭제하고 collab 페이지를 생성 및 내용 업데이트와 삭제하는 방법에 관하여 자세히 설명하였으니 꼭 한번 읽어보시기 바랍니다.
나가며
jenkins mcp 서버의 기능을 직접 구현하는 방법에 대해서 자세히 알아보았습니다. jenkins mcp 서버는 jenkins mcp client에서 자연어 채팅 입력을 통해서 입력받은 메세지를 해석하여 jenkins api를 호출합니다. jenkins api 를 통해서 Jenkins Server에게 요청 메세지를 전달하며 job을 생성하고 삭제하는 기능을 수행할 수 있습니다.
다음 포스팅에서는 jenkins mcp server 코드에서 젠킨스 엔드포인트 서버에서 pipeline을 실행하도록 하는 코드를 어떻게 개발하는지 자세히 다뤄보도록 하겠습니다.