NewETAPE projectEmuframe Tape Server (ETAPE) project
IBM Bob
This page was auto-translated from Spanish

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs

In IBM Bob Shell on z/OS: install it in USS and a first test and in IBM Bob on z/OS with Enterprise COBOL I installed Bob inside z/OS, in USS. In this article I do it the other way round: Bob IDE stays on my RHEL virtual machine, the one from IBM Bob with COBOL and Podman on RHEL, and I install nothing on z/OS. Bob works with z/OS through the z/OSMF REST API.

IBM has the IBM Bob Premium Package for Z, which connects to z/OS with Zowe Explorer and Z Open Editor, but it is bought separately (the Bob pricing page lists it only for Enterprise) and I do not have it. What Bob IDE does have is support for MCP servers: programs that give it new tools. So I write a small one, in Python, with five tools that call z/OSMF.

I already used the z/OSMF REST API in IBM watsonx Orchestrate - Connect AI Assistant with z/OS. Here I call it from my own code.

This is a lab idea: a way to try out, in isolation, something that occurred to me. There are probably better or more complete ways to do it. The idea is to see that it works and for everyone to adapt it to what they need, always keeping in mind what IBM licenses allow.

The tools

ToolWhat it doesz/OSMF call
list_datasetsLists the data sets that match a pattern (IBMUSER.*)GET /zosmf/restfiles/ds?dslevel=
list_membersLists the members of a PDSGET /zosmf/restfiles/ds/PDS/member
read_memberReads a memberGET /zosmf/restfiles/ds/PDS(MEMBER)
submit_jobSubmits the JCL in a member and waits for it to endPUT /zosmf/restjobs/jobs
job_outputReturns the spool outputGET /zosmf/restjobs/jobs/JOB/ID/files

I give it no tools to write or delete data sets: Bob can read, and submit jobs that already exist, nothing more. And the password is not in the Bob configuration: the MCP server reads it from a file that only my user can read.

My z/OS is the ADCD S0W1: z/OSMF is at https://s0w1.dal-ebis.ihost.com:10443/zosmf and the user is IBMUSER. Everyone uses the name or IP address of their own z/OS and the port of their own z/OSMF.

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 1

Check that z/OSMF answers

z/OSMF uses a self-signed certificate. In my lab I do not check it: as in the watsonx Orchestrate article, I accept the certificate without verifying it. The connection is still encrypted, but the client does not check that it is really my z/OS on the other side.

This is only acceptable in an isolated lab. On a real system, import into the client the CA that signs the z/OSMF certificate and let the client check it.

My VM did not know the name of the z/OS, so first I add it to /etc/hosts with the IP address of my z/OS (IP_DEL_ZOS: everyone uses their own) and check that it now resolves:

echo "IP_DEL_ZOS  s0w1.dal-ebis.ihost.com" | sudo tee -a /etc/hosts
getent hosts s0w1.dal-ebis.ihost.com

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 2

Then I check that z/OSMF answers. In curl, the -k option is the one that does not check the certificate:

mkdir -p ~/zosmf-mcp && cd ~/zosmf-mcp
curl -k -H "X-CSRF-ZOSMF-HEADER: true" https://s0w1.dal-ebis.ihost.com:10443/zosmf/info

z/OSMF requires the X-CSRF-ZOSMF-HEADER header on every request; without it, it rejects them.

This request (zosmf/info) needs no user or password.

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 3

The password

I store it in a file that only my user can read. With read -s it is not shown while I type it and it does not stay in the history:

read -rs -p "IBMUSER password: " PW; echo

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 4

(umask 077; printf '%s' "$PW" > ~/.zosmf-password)
unset PW
ls -l ~/.zosmf-password

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 5

The MCP server only uses it on the first call. z/OSMF returns a session cookie (LtpaToken2), which the server stores next to it, also with 600 permissions, and uses on the following calls. When it expires, the server logs in again with the password and stores the new one.

The MCP server

I use the official MCP SDK for Python, in a virtual environment:

cd ~/zosmf-mcp
python3 -m venv .venv
.venv/bin/pip install "mcp>=2,<3"

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 6

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 7

And I create the file ~/zosmf-mcp/zosmf_mcp.py:

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 8

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 9

"""MCP server for IBM Bob: a few z/OSMF REST API calls as tools.

Lab idea, not a product. Read-only on data sets; submit_job only runs JCL
that already exists in a data set. The password is read from a file that
only the owner can read; it is not in the MCP configuration of Bob.
"""
import base64
import json
import os
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

from mcp.server import MCPServer

URL = os.environ["ZOSMF_URL"]                  # https://host:port/zosmf
USER = os.environ["ZOSMF_USER"]
PASSWORD_FILE = Path(os.environ.get("ZOSMF_PASSWORD_FILE", "~/.zosmf-password")).expanduser()
COOKIE_FILE = PASSWORD_FILE.with_name(".zosmf-ltpa")  # session cookie, not the password
MAX_LINES = 400                                # spool lines returned to Bob

# Lab only: z/OSMF has a self-signed certificate, so it is not checked
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE

mcp = MCPServer("zosmf")


def _save_cookie(response):
    for cookie in response.headers.get_all("Set-Cookie") or []:
        if cookie.startswith("LtpaToken2="):
            fd = os.open(COOKIE_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(fd, "w") as f:
                f.write(cookie.split(";")[0].split("=", 1)[1])


def call(method, path, body=None, text=False):
    """Call z/OSMF: the saved cookie first, the password only if it expired."""
    headers = {"X-CSRF-ZOSMF-HEADER": "true"}
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    for attempt in (1, 2):
        h = dict(headers)
        if attempt == 1 and COOKIE_FILE.exists():
            h["Cookie"] = "LtpaToken2=" + COOKIE_FILE.read_text().strip()
        else:
            password = PASSWORD_FILE.read_text().strip()
            token = base64.b64encode(f"{USER}:{password}".encode()).decode()
            h["Authorization"] = "Basic " + token
        request = urllib.request.Request(URL + path, data=data, method=method, headers=h)
        try:
            with urllib.request.urlopen(request, context=CTX, timeout=60) as response:
                _save_cookie(response)
                raw = response.read().decode("utf-8", "replace")
                return raw if text else json.loads(raw or "{}")
        except urllib.error.HTTPError as error:
            if error.code == 401 and attempt == 1 and COOKIE_FILE.exists():
                COOKIE_FILE.unlink()
                continue
            detail = error.read().decode("utf-8", "replace")[:500]
            raise RuntimeError(f"z/OSMF {error.code}: {detail}")


def q(value):
    return urllib.parse.quote(value.upper(), safe="")


@mcp.tool()
def list_datasets(pattern: str) -> list[str]:
    """List the data sets that match a pattern, for example IBMUSER.*"""
    result = call("GET", f"/restfiles/ds?dslevel={q(pattern)}")
    return [item["dsname"] for item in result.get("items", [])]


@mcp.tool()
def list_members(dataset: str) -> list[str]:
    """List the members of a PDS or PDSE."""
    result = call("GET", f"/restfiles/ds/{q(dataset)}/member")
    return [item["member"] for item in result.get("items", [])]


@mcp.tool()
def read_member(dataset: str, member: str) -> str:
    """Read a member of a PDS or PDSE as text."""
    return call("GET", f"/restfiles/ds/{q(dataset)}({q(member)})", text=True)


@mcp.tool()
def submit_job(dataset: str, member: str, wait_seconds: int = 120) -> dict:
    """Submit the JCL in DATASET(MEMBER) and wait for it to end.

    Returns the job name, job ID, status and return code.
    """
    jcl = f"//'{dataset.upper()}({member.upper()})'"
    job = call("PUT", "/restjobs/jobs", {"file": jcl})
    name, jobid = job["jobname"], job["jobid"]
    end = time.time() + wait_seconds
    while time.time() < end:
        job = call("GET", f"/restjobs/jobs/{name}/{jobid}")
        if job["status"] == "OUTPUT":
            break
        time.sleep(3)
    return {"jobname": name, "jobid": jobid,
            "status": job["status"], "retcode": job.get("retcode")}


@mcp.tool()
def job_output(jobname: str, jobid: str) -> str:
    """Return the spool of a job (all its files), up to 400 lines."""
    lines = []
    job = f"/restjobs/jobs/{jobname}/{jobid}"
    for spool_file in call("GET", f"{job}/files"):
        lines.append(f"--- {spool_file['ddname']} ({spool_file.get('stepname') or ''})")
        records = call("GET", f"{job}/files/{spool_file['id']}/records", text=True)
        lines.extend(records.splitlines())
    if len(lines) > MAX_LINES:
        lines = lines[:MAX_LINES] + [f"... {len(lines) - MAX_LINES} more lines"]
    return "\n".join(lines)


if __name__ == "__main__":
    mcp.run()

Each tool is a function with @mcp.tool(): the SDK uses its name, its parameters and its comment to tell Bob what it does and how to call it. They all go through call(), which adds the z/OSMF header and the authentication. CTX is the same as curl's -k: it does not check the certificate. job_output cuts the output at 400 lines, so as not to send Bob a huge spool. But before cutting it, it gets the whole output from z/OSMF: with a very large spool the call takes too long and Bob is left without the output. It happened to me in the first test, with a LISTCAT LEVEL(IBMUSER) of more than 5,000 lines; that is why the test only lists ADCD.

Before connecting it to Bob, I test one tool from the shell:

cd ~/zosmf-mcp
export ZOSMF_URL=https://s0w1.dal-ebis.ihost.com:10443/zosmf ZOSMF_USER=IBMUSER
.venv/bin/python -c "import zosmf_mcp as z; print(*z.list_datasets('ADCD.**'), sep='\n')"

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 10

Connect it to Bob IDE

Bob's MCP servers are declared in ~/.bob/settings/mcp.json (for all projects) or in .bob/mcp.json (for one project). I use the global one and create it with the paths of my user. If you already have other servers in that file, add only the zosmf entry:

mkdir -p ~/.bob/settings

cat > ~/.bob/settings/mcp.json <<EOF
{
  "mcpServers": {
    "zosmf": {
      "command": "$HOME/zosmf-mcp/.venv/bin/python",
      "args": ["$HOME/zosmf-mcp/zosmf_mcp.py"],
      "env": {
        "ZOSMF_URL": "https://s0w1.dal-ebis.ihost.com:10443/zosmf",
        "ZOSMF_USER": "IBMUSER",
        "ZOSMF_PASSWORD_FILE": "$HOME/.zosmf-password"
      },
      "alwaysAllow": ["list_datasets", "list_members", "read_member", "job_output"]
    }
  }
}
EOF

cat ~/.bob/settings/mcp.json

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 11

With alwaysAllow I mark the tools that only read as "Always allow". For Bob to use them without asking, MCP auto-approval also has to be turned on in the chat, as I show further down. submit_job is not in the list: every time Bob wants to submit a job, it will ask me for permission.

In Bob IDE I go to Settings and, under MCP, the zosmf server appears:

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 12

I click the server and see that its tools are enabled:

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 13

In the ADCD, IBMUSER is a superuser. The tools limit what Bob can do, but everything it does, it does with IBMUSER's authority. On a real system you would use a user with just the permissions it needs: in the z/OSMF group (IZUUSER) and with access only to what it needs.

Test it with Bob

For the test I create the member BOBDEMO in my JCL library, IBMUSER.JCL, with one step that lists the ADCD data sets and another that asks for one that does not exist:

//BOBDEMO  JOB (ACCT),'BOB ZOSMF TEST',CLASS=A,MSGCLASS=X
//* 1. List the ADCD catalog entries
//LISTCAT  EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSIN    DD *
  LISTCAT LEVEL(ADCD)
/*
//* 2. Ask for a data set that does not exist
//NOTFOUND EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSIN    DD *
  LISTCAT ENTRIES(IBMUSER.DOES.NOT.EXIST)
/*

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 14

In Bob IDE I open the chat in Agent mode (all three Bob modes, Agent, Plan and Ask, can use MCP tools) and first I ask it to list the data sets of USER:

Which data sets does USER have? Group them by type.

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 15

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 16

Optionally, MCP can be marked as auto-approved under Permissions in the chat.

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 17

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 18

Then I ask it to explain the job:

Read IBMUSER.JCL(BOBDEMO) and explain what it does.

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 19

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 20

Watch out for one detail: Bob says that MSGCLASS=X suppresses the output. It does not: the output stays in the spool, and in fact Bob reads it later with job_output and it shows in SDSF. What Bob explains also has to be checked.

And last, I ask it to submit the job and tell me how it went:

Submit IBMUSER.JCL(BOBDEMO), tell me how it ended and, if a step failed, why.

First it asks for permission, because the tool is not auto-approved.

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 21

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 22

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 23

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 24

IBM Bob and z/OS through z/OSMF: my own MCP server for data sets and jobs – screenshot 25

Bob does not see z/OS directly: it only sees what the five tools return. That is enough for it to find a data set, read a job, submit it and explain its output, and I decide what it can do without asking and what it cannot.

© 2026 Emuframe·🍪 This site only uses functional cookies. No tracking or personal data collection.

On this page