Skip to main content
Glama
README.md
# tn5250-mcp

An MCP server that lets an AI agent drive IBM i (AS/400) 5250 green-screen
sessions: data entry, automated testing, navigating menus. It ships with a live
web viewer, so a person can watch, sign on, or take over at any time.

With a jt400 jar (JTOpen) it can also query Db2 for i with SQL and read and
write IFS files through the IBM i host servers.

Procedures you use often can be written down as **screen flows** in YAML.
Each flow becomes an MCP tool with checked parameters, and the same files run
from a CLI, from Python and from pytest, so they also work as tests in CI.

It speaks the 5250 protocol itself, in pure Python. There is no screen
scraping, and it doesn't need Java or a terminal emulator. That gives the agent
the host's real field table: positions, lengths, numeric and signed fields,
mandatory and hidden fields, and the exact keyboard state.

## Why not just script a terminal emulator?

| | screen scraping | tn5250-mcp |
|---|---|---|
| Input fields | guessed from underlines | exact, from the host's format table |
| Numeric / signed / right-adjusted fields | you send Field Exit / Field Minus yourself | handled per field (`"QTY": "-3"`) |
| Password fields | invisible | listed as hidden, contents never shown to the agent |
| "Is the host done?" | wait for the screen to stop changing | exact: the host's read command + keyboard unlock |
| Wrong-screen typing | possible | refused (`expect` / `screen_id` checks) |
| Mandatory / must-fill / check-digit fields | the host complains afterwards | refused before sending, like a real terminal |
| Destructive commands | nothing stops them | configurable block list |
| Repeatable procedures | prompt the agent again | YAML screen flows, run as tools or tests |
| Writing those procedures | by hand | record them in the viewer or with the agent |
| Host drops the session | start over by hand | reconnects by itself |

## Install

```sh
git clone https://github.com/Helaas/tn5250-mcp && cd tn5250-mcp
python3 -m venv .venv && .venv/bin/pip install -e .
```

Python 3.11+. Dependencies: the official `mcp` SDK (2.x) and PyYAML. For the
optional SQL/IFS tools: a JTOpen `jt400.jar` and Java 11+. No Java? Install
with the `java` extra (`.venv/bin/pip install -e ".[java]"`): it brings
[jdk4py](https://pypi.org/project/jdk4py/), OpenJDK packaged for pip (about
30 MB, GPLv2 with Classpath exception), and the server uses it by itself.

## Hook it up

**Claude Code** (stdio, server starts with the session):

```sh
claude mcp add tn5250 -- /path/to/tn5250-mcp/.venv/bin/tn5250-mcp --log-dir ~/tn5250-logs
```

**Long-running server** (sessions survive client restarts; several clients can share it):

```sh
.venv/bin/tn5250-mcp --transport http --port 8250 --log-dir logs
claude mcp add --transport http tn5250 http://127.0.0.1:8250/mcp
```

**Claude Desktop** (`claude_desktop_config.json`):

```json
{ "mcpServers": { "tn5250": {
    "command": "/path/to/tn5250-mcp/.venv/bin/tn5250-mcp",
    "args": ["--allowed-hosts", "pub400.com,*.test.example.com", "--log-dir", "/path/to/logs"] } } }
```

## Tools

| tool | what it does |
|---|---|
| `connect` | open a session with a saved `profile`, or `host`, `port` 992/23, `tls`, `device_name` (`AGENT*` = AGENTA, AGENTB, ...), `wide` for 27x132, `codepage` |
| `list_profiles` | the saved connection profiles |
| `get_screen` | screen text with rulers, cursor, keyboard state, `screen_id`, input-field table |
| `fill` | put values into fields (by `"row,col"`, `"#index"` or label) without sending |
| `press` | optional fills + cursor, then send a key and return the host's reply screen |
| `wait` | wait until the host wants input (optionally for some text) |
| `viewer` | link to the live viewer |
| `record_start`, `record_stop` | record a session's key presses as a new flow |
| `disconnect` | sign off from the screen's command line, then close (`signoff: false` to skip) |
| `get_session_log` | the session's transcript (passwords masked), also after a disconnect |
| `forget_password` | forget saved passwords (memory and keychain) |
| `host_connect`, `host_disconnect` | open a SQL/IFS connection (with `--jt400`) |
| `sql_query` | run a query; the connection is read-only on the server side |
| `sql_execute` | change data (only with `--allow-sql-write`) |
| `ifs_list`, `ifs_read` | list folders, read stream files (text in their CCSID, or base64) |
| `ifs_write` | write stream files (only inside `--ifs-write-root` folders) |
| `run_command` | run a CL command with a library list, get IBM i's messages (only with `--allow-commands`) |
| `compile` | compile a source and get its errors as file:line:column (only into `--allow-compile` libraries) |
| `call_program` | call a program with typed parameters, get the output parameters back (only with `--allow-commands`) |
| `build_project` | upload a local project folder and build what changed, errors as local file:line:column |
| `pase` | run a PASE shell command (git, make, python3, `system`), get exit code, stdout, stderr (only with `--allow-shell`) |
| `source_members`, `member_read` | list source files and members, read a member |
| `member_write` | replace or create a source member (only in `--allow-member-write` libraries) |
| `describe` | what an object looks like: a file's fields (RPG types) and keys, a display file's fields, a program's modules and sources, a service program's exports |
| `explain_message` | a message's text, cause and recovery (compile, run-time, CL, SQL messages) |
| `job_log` | a job's messages: why a command, compile or batch job failed |
| `spooled_files`, `spooled_file` | list and read printed output: reports, listings, job logs |
| `list_sessions`, `keys` | housekeeping |
| *your flows* | one tool per screen flow loaded with `--flows` |
| *your command tools* | one tool per command tool (`commands:` in the same files): your CL commands, with errors read from their listings |

Several sessions can run side by side (`session` argument).

Example `press` call:

```json
{ "key": "Enter", "expect": "1:WORK WITH DATA IN A FILE",
  "values": { "ID": "3", "NAME": "SPROCKET", "QTY": "-3" } }
```

## SQL and IFS (host servers)

Besides the screen, IBM i offers its data through the *host servers*:
the database server (SQL) and the file server (IFS). tn5250-mcp uses them
through the IBM Toolbox for Java, which **you supply**:

1. Get **JTOpen**, the open-source Toolbox (IBM Public License 1.0), as
   `jt400.jar`: from [GitHub](https://github.com/IBM/JTOpen/releases) or Maven
   Central (`net.sf.jt400:jt400`). Don't take the copy inside IBM i Access
   Client Solutions: its licence doesn't allow using its parts on their own.
2. Have Java 11 or newer: either install the `java` extra (`pip install
   "tn5250-mcp[java]"`, a Java runtime as a Python package), or use one you
   have (`brew install openjdk@21`). It's found by itself in this order:
   `--java`, `$T5250_JAVA`, `$JAVA_HOME`, the `java` extra, the system's.
3. Start the server with `--jt400 /path/to/jt400.jar`.

```sh
tn5250-mcp --jt400 ~/lib/jt400.jar --profiles profiles.yaml \
           --ifs-write-root /home/MYUSER/out          # optional: allow ifs_write here
           # --allow-sql-write                        # optional: allow sql_execute
```

The agent calls `host_connect` (with a profile, whose `user` key names the
user profile, or with `host` and `user`), then `sql_query`, `ifs_list` or
`ifs_read`. The password is typed in the viewer, or comes from
`$T5250_PASSWORD` when nobody has the viewer open (CI). The agent never sees
it.

- `sql_query` runs on a connection the database server keeps read-only
  (`access=read only`), so even a statement that slips past every other check
  can't change data. It supports `?` parameter markers, a row limit, and
  output as a table or as JSON. Naming is system naming: `MYLIB/TABLE` or
  `MYLIB.TABLE`, plus the library list. QSYS2 services work too, for example
  `QSYS2.ACTIVE_JOB_INFO` or `QSYS2.IFS_OBJECT_STATISTICS`.
- `sql_execute` (INSERT, UPDATE, DELETE, CREATE, CALL, ...) is offered only with
  `--allow-sql-write`.
- `ifs_read` converts text from the file's CCSID; `binary: true` returns
  base64. `ifs_write` creates new files tagged with the CCSID you give (1208 =
  UTF-8 by default, 37 = EBCDIC US), refuses to replace a file unless
  `overwrite` or `append` is set, and is offered only with `--ifs-write-root`.
  It never writes outside those folders, and `..` isn't accepted.
- SQL text and write paths go through the block list (`QCMDEXC`, `DROP
  SCHEMA`, ...). The transcript (`get_session_log` with session `host-main`)
  records statements and file names, not file contents.
- The work is done by a small Java helper that talks JSON to the server. It
  ships compiled (`java/t5250-helper.jar`, our own classes only, for Java
  11+), so a runtime without a compiler is enough. After changing
  `T5250Helper.java`, rebuild it with `python scripts/build_helper.py
  /path/to/jt400.jar` (a test checks the jar matches the source). In Python:
  `HostServers("jt400.jar").connect(...)`, `.query(...)`, `.ifs_read(...)`.

## Commands, compiling, job logs, spooled files

With the jt400 helper an agent can also run CL commands and compile, through
the host servers' remote command server (not the screen). That gives a coding
agent the loop it needs: write the source, compile, read the errors, fix,
compile again, run, check.

```text
ifs_write  /home/ME/src/hello.rpgle
compile    {"source": "/home/ME/src/hello.rpgle", "object": "MYLIB/HELLO"}
→ compile FAILED for MYLIB/HELLO: CRTBNDRPG PGM(MYLIB/HELLO) SRCSTMF(...) OPTION(*EVENTF) ...
  /home/ME/src/hello.rpgle:3:9 severe 30 RNF7030 The name or indicator TOTL is not defined.
run_command {"command": "CALL PGM(HELLO)"}          # found through the library list
job_log    {}                                        # the full story if something failed
```

- **Library list.** `host_connect` takes `libl` (or a profile's `libl` key);
  it applies to SQL, commands and compiles. `run_command` and `compile` can
  set another one for a call.
- **`run_command`** (with `--allow-commands`; `--command-allow "DSP*,WRK*,CALL"`
  limits it to some commands) returns every message: ID, severity, text. All
  commands go through the block list. Commands that show screens belong to the
  5250 session.
- **`compile`** (with `--allow-compile MYLIB[,LIB2]`, the libraries it may
  create objects in; `*` = any) takes an IFS stream file or a member
  `LIB/FILE(MBR)`, and picks the command from the type or file extension:
  `rpg` (`.rpgle`), `sqlrpg` (`.sqlrpgle`), `rpgmod`, `sqlrpgmod`, `cl`
  (`.clle`), `clmod`, `dspf`, `prtf`, `pf`, `lf`. It adds `OPTION(*EVENTF)`
  and reads the compiler's event file, like Code for IBM i, for errors with
  line and column. For stream files it compiles with `TGTCCSID(*JOB)` (RPG) or
  `CVTCCSID(*JOB)` (SQL RPG), because RPG can't compile a UTF-8 file with its
  default (RNS9380). `options` adds parameters; `format: json` returns it all
  as data.
- **`job_log`** shows a job's messages (by default the job that ran this
  connection's commands and compiles). On PUB400 it pointed straight at the
  UTF-8 problem above.
- **`spooled_files`** lists your newest spooled files (`QSYS2.SPOOLED_FILE_INFO`,
  which is fast where the output queue views hit query time limits);
  **`spooled_file`** reads one. Output of commands run through the host
  servers lands in your `QPRTJOB` job, not in the command's job.
- From a shell or CI: `tn5250-run cmd "CRTBNDRPG ..." --libl MYLIB,QGPL` and
  `tn5250-run compile src/hello.rpgle MYLIB/HELLO`, with `--profile` or
  `--host/--user`. The password comes from the keychain, `$T5250_PASSWORD`, or
  a prompt. They exit 0 on success and 1 on failure, and print errors as
  `file:line:column: ...`, which editors and CI understand.

### Calling programs

`call_program` calls a program with real, typed parameters, the way another
program would, and returns the output parameters. No screen, no `CALL PARM()`
string building, no guessing how CL passes numbers. That makes it the tool for
unit-testing programs (and service procedures, through a small wrapper
program).

```text
call_program {"program": "MYLIB/CALC", "params": [
  {"type": "char(10)", "value": "Ada"},
  {"type": "packed(7,2)", "value": 12.25},
  {"type": "packed(7,2)", "value": 0.5},
  {"type": "packed(9,2)", "out": true},
  {"type": "char(20)", "out": true}]}
→ ok: CALL MYLIB/CALC
    parameter 4 packed(9,2) = "12.75"
    parameter 5 char(20) = "Hello Ada"
```

Types are written as in RPG: `char(n)`, `varchar(n)`, `packed(d,p)`,
`zoned(d,p)`, `int(5|10|20)`, `uns(5|10)`, `float(4|8)`, `ind`. Decimal values
come back as strings so no digits are lost. The call runs in the same job as
`run_command`, with its library list (`libl` sets one), and needs
`--allow-commands` (and `CALL` among `--command-allow` if you set that).
`QCMDEXC` and `QCAPCMD` are on the block list, so a call can't run commands
around it. From a shell: `tn5250-run call MYLIB/CALC "char(10)=Ada"
"packed(7,2)=12.25" "packed(7,2)=0.5" "packed(9,2):out" "char(20):out"`.

### When a call fails

A program that crashes under `call_program` (or `run_command` with `CALL`)
normally reports only "CEE9901 Application error. RNX9998 unmonitored",
which tells you nothing. The RPG runtime couldn't send its inquiry message
in a server job. So on failure the tool reads the job log back to the call
and reports what actually happened, at its source line:

```text
FAILED: CALL MYLIB/T5DIV
error MCH1211 at MYLIB/QRPGLESRC(T5DIV):8 in MYLIB/T5DIV: Attempt made to divide by zero for fixed point operation.
  RPG status 00102 (RNQ0102): Attempt to divide by zero (C G D F).
  8 | r = 10 / a;
```

- **Where.** It reports the message that started it, from the program
  itself, with its module, procedure (in a service program too) and
  statement.
- **The line.** The statement is mapped to a line of the module's source,
  found through `QSYS2.BOUND_MODULE_INFO`. For ILE RPG a statement number is
  a line of the compile listing, so `/COPY` and `/INCLUDE` members are
  expanded to count it. For CL it's the sequence number.
- **SQL RPG.** Statements refer to the precompiler's output, so you get the
  statement and a note instead of a line.
- **RPG status.** It comes from the RNQ message the runtime tried to send
  (00102 divide by zero, 00121 array index, ...), with its text.

### Describing objects

`describe` shows what code is written against, so the agent uses real field
names and types instead of guessing:

```text
describe {"object": "MYLIB/CUSTMAST"}
→ MYLIB/CUSTMAST *FILE PF - Customers
    physical file, 1 record format
    format CUSTR (50 bytes) - customer
      CUSTID     char(5)          Cust ID
      NAME       char(30)         Name; alias CUSTOMER_NAME
      BAL        packed(9:2)
      SINCE      date(*ISO)
    keys: CUSTID (unique)
```

- **Files** (tables, physical, logical, display and printer files): record
  formats and fields with RPG types, text or column headings, aliases,
  null-capable fields, and the keys. For display and printer files, also
  each field's usage (input, output, both, hidden) and position. It comes
  from `DSPFFD` and `DSPFD TYPE(*ACCPTH)` outfiles in the helper's own
  `QTEMP`.
- **Programs and service programs:** their modules with each module's
  source, the service programs they bind, and a service program's exported
  procedures and data.
- **The rest:** a binding directory's entries, a message file's messages
  (`pattern: "CPF98*"`) and a data area's value.
- **Without a library**, the library list is searched. When several objects
  share the name (a program and a file), each is described, unless `type`
  picks one.

`explain_message` returns a message ID's text, cause and recovery. It looks
in the message file the prefix points to (RNF/RNS compile, RNQ/RNX run-time,
CPF/CPD/MCH system, SQL, CEE), which takes about a second, or in `file` for
your own messages. From a shell: `tn5250-run describe MYLIB/CUSTMAST` and
`tn5250-run explain RNQ0121`.

### The PASE shell

`pase` (with `--allow-shell`) runs a command in PASE, IBM i's AIX runtime,
with `/QOpenSys/usr/bin/sh` and `/QOpenSys/pkgs/bin` first on the `PATH`. So
the open-source tools work where they're installed (on PUB400: git, make,
python3, node), and so does `system "CL command"`.

```text
pase {"command": "git status --short", "cwd": "/home/ME/hello"}
→ exit 0
  --- stdout
   M src/main.rpgle
```

- It runs in the same job as `run_command` and `call_program`, so `libl`
  applies to `system` and to Db2 calls.
- `timeout` (default 60 s, at most 3600) kills the command and everything it
  started. stdin is empty, so nothing can wait for input.
- Output comes back as UTF-8 text, up to 100,000 bytes per stream.
- The command goes through the block list, like CL commands, so
  `system PWRDWNSYS` is refused. The shell itself can still do anything your
  user profile can, which is why it is off unless you turn it on.
- How it works: the command and a small wrapper go to a fresh folder under
  `/tmp`, which is deleted afterwards. `QSH` starts the wrapper, which records
  the exit code and runs a watchdog for the timeout. Each call takes about
  three seconds on PUB400.
- From a shell: `tn5250-run sh "make -C /home/ME/hello" --profile pub400`
  prints stdout and stderr and exits with the command's exit code.

### Source members

Not every shop keeps source in the IFS. `source_members` lists a library's
source files, or one file's members with their type, text, number of lines
and last change. `member_read` returns a member as text (`numbers: true`
shows sequence numbers and dates, SEU style). `member_write` (with
`--allow-member-write LIB[,LIB]`) replaces a member's text, creating the
member with `type` and `description` if it doesn't exist.

- Lines that didn't change keep their date, and new or changed lines get
  today's, as SEU does, so the member's history still shows what changed.
  The result says how many lines changed.
- A line wider than the source file (record length - 12) is refused before
  anything is written.
- `compile` takes a member as its source (`MYLIB/QRPGLESRC(HELLO)`). Without
  `type`, it uses the member's source type (RPGLE, SQLRPGLE, CLLE, CLP, DSPF,
  PRTF, PF, LF).
- From a shell: `tn5250-run member list MYLIB/QRPGLESRC`,
  `tn5250-run member read MYLIB/QRPGLESRC(HELLO) hello.rpgle` and
  `tn5250-run member write MYLIB/QRPGLESRC(HELLO) hello.rpgle --type RPGLE`
  (stdin and stdout when there is no file).

## Building a project

`build_project` (and `tn5250-run build`) builds a whole project from a local
folder, so an agent can work in files on your machine, with git, and build on
IBM i. It uploads the sources that changed to the project's IFS folder,
creates what needs creating, in order, and returns errors as **local**
`file:line:column`, ready to fix.

```yaml
# tn5250-project.yaml
project: hello
lib: MYLIB                   # objects are created here
libl: [MYLIB, QGPL]          # library list while building (default: [lib])
ifs: /home/ME/hello          # the folder is mirrored here
src: src                     # where the sources are (default: the project folder)
bnddir: HELLO                # optional: gets the service programs; programs bind to it
srvpgms:
  GREET: {modules: [GREET], bnd: greet.bnd}     # or leave out bnd for EXPORT(*ALL)
programs:
  MAIN: {modules: [MAIN], srvpgms: [GREET]}
options: {rpgmod: "TGTRLS(*CURRENT)"}           # extra parameters per type
```

The file names say what to create (see [examples/project](examples/project)):

| file | becomes |
|---|---|
| `name.pgm.rpgle`, `.pgm.sqlrpgle`, `.pgm.clle` | program NAME from one source (`CRTBNDRPG`, `CRTSQLRPGI`, `CRTBNDCL`) |
| `name.rpgle`, `.sqlrpgle`, `.clle` | module NAME, for `srvpgms` and `programs` |
| `name.pf`, `.lf`, `.dspf`, `.prtf` | file NAME from DDS |
| `name.sql`, `.table`, `.view`, `.index`, `.sqlprc`, `.sqludf`, `.sqltrg` | `RUNSQLSTM` (needs `--allow-sql-write`; write `CREATE OR REPLACE`) |
| `name.bnd` | binder source for a service program |
| `name.rpgleinc`, `.rpginc`, `.inc`, `.cpy`, `.clinc` | include: uploaded, no object |

- **Order:** SQL, physical files, logical files, display and printer files,
  modules, service programs, programs. If something fails, what needs it is
  skipped with a reason, and the rest still builds.
- **Incremental:** a local `.tn5250-build.json` keeps hashes of what was
  uploaded and built (put it in `.gitignore`). A rebuild covers what changed
  plus what depends on it: sources that `/copy` or `/include` a changed
  include, programs and service programs over changed modules, sources that
  declare a changed file (`dcl-f`, F specs, `PFILE`). `rebuild_all` (`--all`)
  does everything; `only` (`--only NAME`) builds just those objects.
- **Includes:** RPG compiles get `INCDIR('<ifs folder>')`, so
  `/copy inc/greet_h.rpgleinc` works as it does locally.
- **DDS:** `CRTPF`, `CRTLF`, `CRTDSPF` and `CRTPRTF` don't read stream files
  (CPD0043 on IBM i 7.5), so the build copies the source into a member in
  `QTEMP` first; errors still point at your local file. `CRTPF` and `CRTLF`
  can't replace a file, so a changed physical or logical file is deleted
  (logical files first) and created again: **its data is lost**, as it would
  be for a build in a development library.
- **Programs and binding directories:** with `bnddir`, programs from one
  source get `BNDDIR(...)` and `DFTACTGRP(*NO)`, since the command's default
  `DFTACTGRP(*YES)` refuses a binding directory before the source's `ctl-opt`
  is read (RNF9302).
- **Listings:** builds use `OUTPUT(*NONE)` and `*NOLIST`, so they don't leave
  a spooled file per compile; the event file has the errors. `RUNSQLSTM`
  writes a listing only on errors; the build reads it for line and column and
  deletes it.
- **Limits:** the project's `lib` must be among `--allow-compile`, and its
  `ifs` folder inside an `--ifs-write-root`. The CLI allows exactly the
  project's library and folder.

```text
$ tn5250-run build examples/project --profile pub400
FAILED  MYLIB/MAIN (rpgmod)
  /work/hello/src/main.rpgle:9:19: severe 30 RNF7030 The name or indicator NME is not defined.
BUILT   MYLIB/GREET (srvpgm)
SKIPPED MYLIB/MAIN (pgm): needs MAIN, which failed
hello: FAILED
```

## Command tools

Many shops don't compile with `CRTBNDRPG` directly. A change-management tool,
a build command or a CL program does it, often in a batch job, and that is
the way an agent should go too. A **command tool** is such a command with
typed parameters, defined in YAML under `commands:` (in the files you load
with `--flows`, next to or instead of `flows:`). Each one becomes a tool of
its own.

```yaml
toolset: build
commands:
  compile_member:
    description: Compile a member the way this shop does
    params:
      member: {type: string, upper: true, pattern: '^[A-Z$#@][A-Z0-9_$#@]{0,9}$'}
      note: {type: string, quote: true, default: ""}     # goes in as 'it''s'
    libl: [TOOLLIB, MYLIB, QGPL]
    command: MYBUILD MBR({member}) TEXT({note})          # or a list, run in order
    wait: true            # wait for the job it submits; ok only if that ends normally
    timeout: 600
    delete_spooled: true  # remove the listings and job log after reading them
```

After the command, the tool reads what the work left behind and returns the
errors with line numbers, the same way for every command:

- **The job.** When a command submits a job (message CPC1221), `wait: true`
  waits for that job's end message in the history log (CPF1164). The tool
  fails unless the end code is 0 or 10.
- **Listings.** It reads the submitted job's spooled files. For a command that
  doesn't submit anything, it reads what landed in your `QPRTJOB` job while
  it ran. Compiler listings are turned into `member:line:column` errors:
  ILE RPG, SQL RPG (both the precompiler's listing and the RPG step's, mapped
  back from the `QTEMP` copy to your member), ILE CL and DDS (PF, LF, DSPF,
  PRTF). `RUNSQLSTM` listings are read the same way.
- **Job log.** A spooled job log (`QPJOBLOG`) is read for its escape and
  diagnostic messages. `QSYS2.JOBLOG_INFO` can't read the log of a job that
  has ended.

```text
FAILED: batch_compile_rpg (job 434989/ME/T5RPG, end code 20)
ran SBMJOB CMD(CRTBNDRPG PGM(MYLIB/T5RPG) SRCFILE(MYLIB/QRPGLESRC) ...) JOB(T5RPG) MSGQ(*NONE)
errors from the listings, most severe first:
  MYLIB/QRPGLESRC(T5RPG):3: severe 30 RNF7030 The name or indicator TOTL is not defined.
job log:
  RNS9310 (escape, severity 50) Compilation failed. Program T5RPG not created in library MYLIB.
read: T5RPG 1 (rpg listing), QPJOBLOG 2 (job log)
```

- **Safe values.** Values go into the command as CL tokens. Without
  `quote: true` a value may only hold name-like characters (letters, digits,
  `_ $ # @ . * / , + - :`), so no parameter can add parameters or commands.
  With `quote: true` it goes in as a quoted string.
- **Rules.** Command tools need `--allow-commands`. Every command goes
  through `--command-allow` and the block list, and for `SBMJOB` so does the
  command it submits. `--allow-compile` doesn't limit them: a command tool
  runs what its YAML says. They're never offered in `--read-only` mode, and
  `--toolsets` applies.
- **Line numbers.** Listings print source sequence numbers. `line` assumes
  members numbered 1.00, 2.00, ..., as SEU, `member_write` and `CPYFRMSTMF`
  number them; the number as printed is in `seq` (`format: json`).
- **Example.** [examples/flows/commands.yaml](examples/flows/commands.yaml)
  has `batch_compile_rpg` (SBMJOB CRTBNDRPG, wait, errors). On PUB400 a
  batch compile with its listing and job log takes about 12 seconds.
- **From a shell:** `tn5250-run tool compile_member member=HELLO --flows
  tools.yaml --profile NAME` prints the same report and exits 1 on failure.
  `tn5250-run check` lists command tools with the flows.

## Connection profiles

Save the systems you use in a YAML file and start the server with
`--profiles profiles.yaml` (a file or a folder). The agent then connects with
`connect {"profile": "pub400"}` and never needs the host details.

```yaml
profiles:
  pub400:
    description: PUB400.COM, a free public IBM i
    host: pub400.com
    port: 992                         # tls: true is the default; port 23 without TLS
    after_connect: {flow: signon, with: {user: MYUSER}}
    on_reconnect: true                # sign on again after the host drops the session
  dev:
    host: dev400.example.com
    tls: false
    device_name: "AGENT*"             # AGENTA, AGENTB, ... (= is a random character)
    codepage: cp273
```

Keys: `host` (required), `description`, `port`, `tls`, `verify_tls`,
`device_name`, `wide`, `codepage`, `user` and `libl` (for `host_connect`), `after_connect` (a flow name, or `{flow,
with}`), `on_reconnect`. Profiles never hold passwords; a file with a
`password` key is refused. Use a sign-on flow as `after_connect`: it asks for
the password in the viewer, or reads it from the environment.

- When the server starts it checks that every `after_connect` flow exists
  and that its parameters are valid.
- If the after-connect flow can't finish (for example nobody has the viewer
  open), the session stays connected and `connect` says why.
- After a reconnect the session asks for the same device name again, so the
  host can hand back the same job (depending on `QDSCJOBITV`).
- `--profiles-only` refuses `connect` with a host name, so the agent can only
  reach the systems you saved.
- Outside MCP: `Terminal.from_profile("pub400", "profiles.yaml", flows=[...])`,
  `tn5250-run run --profile pub400 ...` and pytest `--t5250-profile pub400`
  (add `--jt400` / `--t5250-jt400` for flows with query steps).
  When the sign-on flow needs a password that isn't in the environment, these
  print the viewer link and wait for you.

See [`examples/profiles.yaml`](examples/profiles.yaml).

## Screen flows

A flow is a named procedure: a fixed list of steps with typed parameters. The
agent (or a test) only supplies the parameters; it can't type outside the flow.

```yaml
toolset: orders                       # default toolset for the flows below
flows:
  add_order:
    description: Add an order on the order entry screen.   # the agent reads this
    params:
      customer: {type: string, upper: true, pattern: "^[A-Z0-9]{1,8}$"}
      qty:      {type: integer, min: 1, max: 9999}
    steps:
      - call: open_order_entry        # flows can call flows
      - name: enter the order
        expect: "1:ORDER ENTRY"       # must be on screen, or the flow stops
        fill: {Customer: "{customer}", Quantity: "{qty}"}
        press: Enter
        check: {not_text: "not found"}
        capture: {order_no: 'Order (\d+) created'}
      - expect: "Order {order_no} created"
        press: F3
```

```sh
tn5250-mcp --flows flows/                  # offer the flows as tools (next to fill/press)
tn5250-mcp --flows flows/ --flows-only     # only flows: no free typing for the agent
tn5250-mcp --flows flows/ --toolsets orders,ibmi
tn5250-run check flows/                    # validate and list
```

**Parameters** (`params`): `type` is `string` (`min_length`, `max_length`,
`pattern`, `enum`, `upper`), `integer` or `number` (`min`, `max`, `decimals`),
`boolean` (typed as `true_value`/`false_value`, default `Y`/`N`) or `secret`
(a password; optional `prompt` label and `env: VAR`; see "Passwords" below).
Add `default` to make a parameter optional, and
`description` for the agent. Values are checked before anything is typed:
for this flow, for every flow it calls, and against the block list. A flow is
refused as a whole; it doesn't stop half-way because of a bad value.

**Steps** (run in order):

| key | meaning |
|---|---|
| `expect` | text (or `"row:text"`, or a list) that must be on screen before the step acts. Required for any step that fills or presses (`Reset` excepted). |
| `when` | only run this step if this text is on screen; otherwise skip it (pop-ups, confirm screens) |
| `fill` | field → value. Fields by label, `"row,col"`, `"#index"` or `@cursor` |
| `cursor` | put the cursor on a field or position first |
| `press` | key to send, then wait for the host's answer |
| `wait_for`, `timeout` | wait for text after the key (or on its own); default timeout 30 s |
| `check` | after the step: `text`, `not_text`, `regex`, `keyboard` (`ready`, `error`, `any`; default: an operator error fails the step), `captured` (capture → regex) |
| `capture` | name → regex with one group, `{field: ref}` or `{rows: "3-22"}`. Usable as `{name}` in later steps and returned to the caller |
| `call`, `with` | run another flow with these parameters |
| `fail` | with `when`: stop the flow with this message if the text is there |
| `change_password` | with `when`: the password has expired; ask for a new one in the viewer and fill the change screen (`{secret: password}`, optional `current`, `new`, `verify` field labels) |
| `query`, `params` | run read-only SQL (needs `--jt400`) with `?` markers filled from `params` (templates allowed there, not in the SQL); `capture` then takes columns of the first row (`{status: JOB_STATUS}`, or `#rows` for the row count), and `check` looks at the result |
| `repeat` | do the step again until `until` holds (a condition like `check`, or a list of them: any one): `{until: ..., fail_if: ..., every: 5, timeout: 300}`. Works on query steps (polling) and screen steps (e.g. press F5 until a text appears) |
| `name` | step label for logs and errors |

`{name}` inserts a parameter or capture. In regexes the value matches
literally. Flow options: `description` (required), `toolset`, `read_only`
(your promise that the flow only displays things; such a flow may only call
other read-only flows), `expose: false` (a helper for other flows, not a tool),
`pace` (seconds to wait after each step so a person can follow in the viewer;
`--pace` sets it for all flows).

A failing flow reports the flow, the step and the screen at that moment. Over
MCP, a flow returns its step log, its captures and the final screen.

### Waiting for a batch job

Screens often submit a batch job. A flow can wait for it with SQL and only go
on when it ended normally:

```yaml
- name: submit
  expect: "1:Update Prices"
  fill: {Option: "1"}
  press: Enter
  capture: {job_name: 'Job (\d+/\w+/\w+) submitted'}
- name: wait until it has ended
  query: >-
    SELECT COUNT(*) AS ENDED, MAX(VARCHAR(MESSAGE_TEXT, 200)) AS END_MESSAGE
      FROM TABLE(QSYS2.HISTORY_LOG_INFO(START_TIME => CAST(? AS TIMESTAMP))) X
     WHERE MESSAGE_ID = 'CPF1164' AND FROM_JOB = ?
  params: ["{since}", "{job_name}"]
  capture: {ended: ENDED, end_message: END_MESSAGE}
  repeat: {until: {captured: {ended: "^[1-9]"}}, every: 5, timeout: 900}
  check: {captured: {end_message: 'end code 0 '}}    # anything else stops the flow
- name: next screen
  ...
```

While it waits, the agent's screen and the viewer show the attempt and the last
values. The flow opens its own SQL connection as the signed-on user, reusing
the saved password (no extra prompt). The ready-made `submit_and_wait` flow
(`examples/flows/batch.yaml`) does this for any CL command; call it from your
own flows. Notes from trying this on a real system:

- A finished batch job without spooled output drops out of `QSYS2.JOB_INFO`,
  so the job's "ended" message (CPF1164, in the history log) is the reliable
  signal; its text ends in `end code 0 .` for a normal end (20 and up:
  abnormal). Also, `JOB_INFO`'s `JOB_USER_FILTER` takes a user name, not
  `*USER`.
- Submit with `MSGQ(*NONE)` when the flow waits by itself: otherwise the "job
  completed" message can pop up over the next screen if messages are delivered
  in `*BREAK` mode.
- Write `CAST(? AS TIMESTAMP)` rather than `TIMESTAMP(?)`: Db2 for i refuses an
  untyped `?` there (SQL0418).

See [`examples/flows/`](examples/flows/): `ibmi.yaml` (`signon`, `run_command`,
a read-only `sql_select`), `batch.yaml` (`submit_and_wait`) and `dfu_demo.yaml` (data entry through UPDDTA, plus
`data_entry_test`, the end-to-end test).

### Recording flows

Instead of writing a flow, record it. Click **Record** in the viewer (or let
the agent call `record_start`), go through the screens once, then stop and
give the flow a name and a description. Each key press becomes a step:

- `expect`: the title of the screen the key was pressed on;
- `fill`: the fields typed, by label when the label is unique on that screen;
- `check`: the title of the screen that came back (or `keyboard: error` when
  the host answered with an operator error).

Typed values become parameters, with what you typed as the default, so the
flow replays as is or runs with other values (`params: none` keeps them
literal). Passwords are never recorded: a hidden field becomes a `secret`
parameter that is asked for in the viewer when the flow runs.

The recording is checked to load as a valid flow, saved to `--record-dir` as
`<name>.yaml`, and offered as a tool right away; recordings in that folder
load again when the server starts. Review the expect/check texts once: a
recording knows which screens you went through, not which parts of them
matter. In Python: `t.record_start()` ... `t.record_stop("name", "what it
does", save_dir="flows")`.

## Test suites

A suite is a YAML file of tests built from flows. `tn5250-run test` runs it
and writes JUnit XML (for CI) and an HTML report (for people):

```sh
tn5250-run test tests/data_entry.yaml --var lib=MYLIB --profiles profiles.yaml \
    --jt400 lib/jt400.jar --junit results.xml --html report.html
```

```yaml
suite: data entry through UPDDTA
profile: pub400                           # or connect: {host: ..., port: ...}
flows: [../flows]
vars: {lib: MYLIB}                        # {lib} anywhere below; --var lib=X overrides
home: {text: "IBM i Main Menu", keys: [F3, Enter]}   # back here before each test

setup:                                    # sql, command or flow items
  - command: "DLTF FILE({lib}/T5250TEST)"
    ignore_errors: true
  - sql: CREATE TABLE {lib}/T5250TEST (...)

tests:
  - name: enter a record
    data: records.csv                     # one test per row (columns: id, name, qty)
    steps:
      - {flow: start_data_entry, with: {lib: "{lib}"}}
      - {flow: add_record, with: {id: "{id}", name: "{name}", qty: "{qty}"}}
      - {flow: end_data_entry, with: {expect_added: 1}}
    expect:
      screen: ["IBM i Main Menu"]
      snapshot: main_menu
      sql:
        - query: SELECT NAME, QTY FROM {lib}/T5250TEST WHERE ID = ?
          params: ["{id}"]
          rows: [["{name}", "{qty}"]]
  - name: a duplicate ID is refused
    steps: [...]
    expect_failure: "check failed"        # a negative test: the flow must fail like this

teardown:
  - sql: DROP TABLE {lib}/T5250TEST
```

- **Tests** run a `flow` (with `with`) or several `steps`. `data:` (a CSV file)
  or `cases:` (a list) runs a test once per row; row values are `{name}`
  templates, and a test without `with` passes the row's matching columns to
  the flow. `skip: reason` skips a test.
- **Expectations** after the flows: `captured` (regex per captured value),
  `screen` / `not_screen` (texts, or `"row:text"`), `snapshot` (see below) and
  `sql` (a read-only `query` with `params`, then `rows` exactly, `contains`
  some rows, or a row `count`). `expect_failure` expects a flow to fail, with
  a message matching the regex.
- **Recovery.** With `home`, each test starts from that screen: the runner
  presses Reset and the `keys` until it shows up, so one failing test doesn't
  break the next ones. Teardown goes home first too.
- **Setup and teardown** run SQL (`sql`, `params`), CL commands (`command`) or
  flows (`flow`, `with`); `ignore_errors: true` for things that may fail. A
  failed setup stops the suite and is reported as an error.
- **Snapshots** save a screen the first time (in `<suite>.snapshots/`, or
  `snapshots:`) and compare it on later runs. Dates, times, job names and
  device names are masked, and `ignore:` adds regexes. A difference fails the
  test with a diff; `--update-snapshots` saves the current screens as the new
  expected ones. In Python and pytest: `t5250.assert_snapshot("main_menu")`.
- **Reports.** `--junit` writes JUnit XML that CI systems (GitHub Actions,
  Jenkins, GitLab) show per test. `--html` writes a self-contained page: a
  summary, then per test its steps, captures, the final screen and any
  snapshot diff. The exit code is 0 when everything passed, 1 otherwise.
  `--only REGEX` runs some tests.
- **Signing on.** The suite uses the profile's sign-on flow: with a password in
  the keychain (or `$T5250_PASSWORD` in CI) nothing asks. SQL and commands use
  the same saved password, so `--jt400` is all they need.

[`examples/tests/data_entry.yaml`](examples/tests/data_entry.yaml) is the
suite above, with `records.csv`. Note: UPDDTA prints an audit list
(`QPDZDTALOG`) per run in the interactive job.

## Scripts, CI and pytest

The flows and the engine work without an MCP client.

**Command line:**

```sh
tn5250-run run --host pub400.com --flows examples/flows data_entry_test lib=MYLIB
```

Sign-on: `--signon env` uses `$T5250_USER` / `$T5250_PASSWORD` (CI secrets),
and `--signon viewer` prints a viewer link and waits for a person. `auto`, the
default, uses env when `$T5250_PASSWORD` is set. Add `--signoff`, `--json`,
`--screen` or `--log-dir logs` for transcripts. Exit codes: 0 passed, 1 flow
failed, 2 invalid flows or arguments, 3 connection or sign-on problem.

**Python:**

```python
from tn5250_mcp import Terminal

with Terminal("pub400.com", flows=["flows/"], log_dir="logs") as t:
    t.signon()                                   # from $T5250_USER / $T5250_PASSWORD
    r = t.run("add_order", customer="c100", qty=3)
    print(r.captures["order_no"])
    t.press("F3", expect="ORDER ENTRY")          # raw keys work too
    t.signoff()
```

**pytest** (the plugin is installed with the package):

```python
def test_add_order(t5250):                       # a signed-on session for the test run
    r = t5250.run("add_order", customer="C100", qty=3)
    assert r.captures["order_no"]
```

```sh
T5250_HOST=pub400.com T5250_USER=... T5250_PASSWORD=... pytest --t5250-flows flows/
```

Without `T5250_HOST`, tests that use `t5250` are skipped. Without a password,
pass `--t5250-viewer-port 0` to sign on by hand in the viewer. A failing
test's report includes the 5250 screen. `--t5250-log-dir` keeps transcripts as
test evidence.

### Passwords

A `secret` parameter is never passed in by the caller. When the flow runs:

1. A **saved** password for this user and host is used, if there is one (see
   below). This needs `user_param: user` on the secret, naming the parameter
   that holds the user profile, as in the example `signon` flow.
2. Otherwise, if somebody is watching the session in the viewer, a password
   dialog opens there and the person types it. The dialog keeps password
   managers out and only sends what was actually typed or pasted, because an
   auto-filled stale password counts as a failed sign-on (and enough of those
   disable the user profile).
3. Otherwise the parameter's `env` variable is used (CI secrets).
4. Otherwise the flow stops before anything is typed and tells the agent to
   hand the user the viewer link.

The value goes to the host only: it is masked in transcripts, results and
errors, and never reaches the agent. Flows with secrets are offered over MCP
only when the viewer is running, without the secret in their parameters. So an
agent can run `signon`, and you type the password in the viewer.

**Saved passwords: one prompt, not one per connection.** A typed password that
signed on successfully is kept in the server's memory, per host and user, until
it has gone unused for 8 hours (`--password-cache-hours`, 0 = off). The 5250
sign-on, `host_connect` for SQL/IFS and the sign-on after a reconnect all use
it, so one prompt covers a whole session.

- **Remember on this computer.** With the `keyring` extra (`pip install
  "tn5250-mcp[keyring]"`), the password dialog has a checkbox that also stores
  it in the system keychain (macOS Keychain, Windows Credential Manager, Secret
  Service on Linux), so later sessions need no prompt at all.
  `--no-remember` hides the checkbox where policy forbids stored passwords.
  Anything running as you can ask the keychain for it, as with any saved
  password.
- **Forget.** The **Forget passwords** button in the viewer and the
  `forget_password` tool clear memory and keychain. `list_sessions` names the
  saved logins (never the passwords).
- **No retries with rejected passwords.** A saved password the host rejects
  (changed elsewhere, say) is dropped after that one attempt, and the next
  connection asks again.

**Expired passwords.** The old password is never tried again. Instead, the
person chooses a new one in the viewer, typing it twice. On the 5250 side, the
example `signon` flow's `change_password` step fills the "Password has expired"
screen. For SQL/IFS the change goes through jt400. Then:

- the saved password is replaced (in the keychain too), and open SQL/IFS
  connections of that user are closed, so nothing signs on with the old one;
- if a new password breaks the system's rules, the dialog shows IBM i's reason
  and asks again, at most three times; a wrong *current* password stops at
  once;
- with nobody at the viewer (CI), it stops: "has expired. Nothing was retried."

When a sign-on is inside the system's warning period (`QPWDEXPWRN`),
`host_connect` says how many days are left.

## Safety rails

- **Screen checks (on by default).** Every `fill`/`press` must carry `expect`
  (text that must be on the screen, or `"row:text"`) or `screen_id` (from the
  last read). If the screen changed in the meantime, because the host moved on
  or a person typed in the viewer, the call is refused.
- **Block list.** Values containing commands such as `PWRDWNSYS`, `ENDSBS`,
  `DLTLIB`, `CLRLIB`, `DLTUSRPRF`, `CHGSYSVAL`, `DROP SCHEMA` or `QCMDEXC` are
  refused (full list in `src/tn5250_mcp/guard.py`). Add your own with `--block REGEX`. It's a
  seatbelt, not a security boundary: give the agent's user profile only the
  authority it needs.
- **Host allow list.** `--allowed-hosts "dev400,*.test.example.com"`, or
  `--profiles-only` to allow only your saved connection profiles.
- **Flows instead of free typing.** `--flows-only` removes `fill` and `press`, so
  the agent can read screens and run your flows, nothing else. `--read-only`
  also drops every flow not marked `read_only`.
- **Passwords stay with people.** Hidden (non-display) fields are never shown
  to the agent. Sign on in the viewer, or let a sign-on flow ask for the
  password in the viewer; the agent carries on from there. A password that
  worked is reused for that user and host (and kept in the keychain if you
  chose so); rejected and expired passwords are never retried (see
  "Passwords").
- **Terminal-side field checks.** Like a real 5250 terminal, `press` (and the
  viewer) refuse to send when a mandatory-entry field is empty (operator error
  0007), a mandatory-fill field is only partly filled (0014) or a self-check
  field has a wrong modulus 10/11 check digit (0015). Alphabetic-only (0008),
  numeric-only (0009) and digits-only (0010) fields reject other characters.
  Nothing is sent, the cursor goes to the field, and the error says what to
  fix. Help, Clear, Print and the roll keys are exempt, as are keys whose field
  data the screen doesn't send.
- **Per-tool permissions.** Read tools are marked read-only and `press` is
  marked destructive, so MCP clients can auto-approve reading and still ask
  before keys are sent.
- **Transcripts.** Every action and every screen the host sent is recorded,
  with hidden fields and secrets masked (decided before the key is sent, so a
  fast host can't expose a password). The agent reads it with
  `get_session_log` (last 400 entries in memory); `--log-dir DIR` also writes
  it to files, useful as test evidence.
- **Clean sign-off.** `disconnect` first types `SIGNOFF` on the screen's CL
  command line (a `===>` field labelled with "command", as on menus, list
  panels and Command Entry; not the STRSQL statement line), so no job is
  left behind on the host. On a screen without one it types nothing and says
  so. `Terminal.signoff()` and `tn5250-run --signoff` do the same.

## Reconnecting

When the host drops a session (a line failure, an idle timeout, `SIGNOFF
ENDCNN(*YES)`), the server reconnects by itself, like a 5250 emulator: up to
`--reconnect-attempts` times (default 10), `--reconnect-interval` seconds
apart (default 5). Meanwhile the screen header and the viewer say
"reconnecting (attempt n of m)", `wait` waits for it, and keys are refused
with a message telling the agent to wait. Afterwards the session starts over
at the sign-on screen, and the header says when it reconnected. Sign on again,
in the viewer or with a sign-on flow. If every attempt fails, the session
stays disconnected (use `connect`, or **Reconnect** in the viewer).
`disconnect` never triggers a reconnect. The Python `Terminal` and
`tn5250-run` don't reconnect unless you ask (`reconnect_attempts=`), because
scripts should fail fast.

To get back the *same* job instead of a new one, connect with a fixed
`device_name`: the host can then reconnect you to the disconnected job,
depending on its `QDSCJOBITV` setting.

## The viewer

A local page (`http://127.0.0.1:8251/?token=…`, link from the `viewer` tool)
that shows the session live in colour with real input fields. It also shows
the password dialog when a flow needs a secret, has the **Record** button for
recording flows, shows reconnect progress, and reloads itself when the server
has a newer version of the page. Type, press Enter
or F-keys (Shift+F1-F12 = F13-F24), PageUp/PageDown, Esc = Reset. It only
listens on 127.0.0.1 and needs the random token, and it checks the Host header.
`--viewer-port 0` turns it off.

## Configuration

| flag | env | default |
|---|---|---|
| `--transport stdio\|http` | `T5250_TRANSPORT` | `stdio` |
| `--port` | `T5250_PORT` | `8250` (HTTP transport, path `/mcp`) |
| `--viewer-port` | `T5250_VIEWER_PORT` | `8251` (a free port if taken), `0` = off |
| `--allowed-hosts` | `T5250_ALLOWED_HOSTS` | any |
| `--block REGEX` (repeatable) | `T5250_BLOCK` (comma list) | none extra |
| `--no-default-blocks` | `T5250_NO_DEFAULT_BLOCKS=1` | defaults on |
| `--no-require-check` | `T5250_REQUIRE_CHECK=0` | checks required |
| `--log-dir` | `T5250_LOG_DIR` | no logs |
| | `T5250_VIEWER_TOKEN` | random per start (set it to keep viewer links valid across restarts) |
| `--codepage` | `T5250_CODEPAGE` | `cp037` (also cp273, cp500, cp1140, …) |
| `--flows PATH` (repeatable) | `T5250_FLOWS` (`:`-separated) | none |
| `--toolsets a,b` | `T5250_TOOLSETS` | all |
| `--flows-only` | `T5250_FLOWS_ONLY=1` | off |
| `--read-only` | `T5250_READ_ONLY=1` | off |
| `--pace SECONDS` | `T5250_PACE` | `0` (no wait between flow steps) |
| `--reconnect-attempts N` | `T5250_RECONNECT_ATTEMPTS` | `10`, `0` = off |
| `--reconnect-interval SECONDS` | `T5250_RECONNECT_INTERVAL` | `5` |
| `--record-dir DIR` | `T5250_RECORD_DIR` | recordings are returned, not saved |
| `--profiles PATH` (repeatable) | `T5250_PROFILES` (`:`-separated) | none |
| `--profiles-only` | `T5250_PROFILES_ONLY=1` | off |
| `--password-cache-hours H` | `T5250_PASSWORD_CACHE_HOURS` | `8`, `0` = don't keep passwords |
| `--no-remember` | `T5250_NO_REMEMBER=1` | checkbox shown when `keyring` is installed |
| `--jt400 PATH` | `T5250_JT400` | no SQL/IFS tools |
| `--java PATH` | `T5250_JAVA` | found automatically (Java 11+) |
| `--allow-sql-write` | `T5250_ALLOW_SQL_WRITE=1` | off |
| `--ifs-write-root DIR` (repeatable) | `T5250_IFS_WRITE_ROOT` (`:`-separated) | no `ifs_write` |
| `--allow-commands` | `T5250_ALLOW_COMMANDS=1` | no `run_command`, `call_program` |
| `--command-allow "DSP*,CALL"` | `T5250_COMMAND_ALLOW` | any command (block list still applies) |
| `--allow-shell` | `T5250_ALLOW_SHELL=1` | no `pase` |
| `--allow-member-write LIB[,LIB]` | `T5250_ALLOW_MEMBER_WRITE` | no `member_write`; `*` = any library |
| `--allow-compile LIB[,LIB]` | `T5250_ALLOW_COMPILE` | no `compile`, `build_project` (which also needs `--ifs-write-root`); `*` = any library |

## Examples and tests

- `examples/call.py TOOL '{json args}'`: call one tool against an HTTP server.
- `examples/flows/`: example screen flows, including `data_entry_test`, an
  end-to-end test. It creates a table, keys three records through UPDDTA (one
  negative quantity), checks them with STRSQL, then drops the table.
- `examples/data_entry_test.py LIB`: the same test written as an MCP client
  script, using `press` directly.
- `pytest`: offline tests (data stream parsing, field encoding, signed
  numbers, save/restore screens, guards, flows, MCP flow tools, CLI). They use
  a scripted fake host, so no IBM i is needed.

A free public IBM i to try it on: [PUB400.COM](https://pub400.com).

## Protocol coverage

TN5250 over TLS or plain telnet (RFC 1205/4777: terminal type, EOR, binary,
NEW-ENVIRON with DEVNAME). It handles Write to Display (SBA, SF with FFW/FCW,
SOH with the F-key data mask, IC, MC, RA, EA, TD, WEA), Clear Unit (24x80 and
27x132), Clear Format Table, Read MDT / Read Input / Read Immediate, Read
Screen Immediate, Write Error Code (operator errors and Reset), Save/Restore
Screen (pop-ups and F4 prompts), Roll, 5250 Query reply, SysReq, Attn,
continued (multi-line) fields and message-waiting.

Not covered: the GUI-enhanced 5250 constructs (windows, selection fields and
scroll bars as structured fields). The server announces itself as a
non-enhanced display, so the host draws those with plain characters instead.
DBCS and printer sessions aren't covered either.

The open-source [tn5250](https://github.com/tn5250/tn5250) emulator was used
as the protocol reference.

## License

MIT, see [LICENSE](LICENSE).

The SQL, IFS, command and compile tools use JTOpen (`jt400.jar`), which has
its own license (IBM Public License 1.0) and isn't part of this repository:
you download it yourself (see [SQL and IFS](#sql-and-ifs-host-servers)). The
bundled `t5250-helper.jar` holds only this project's own classes, built from
[T5250Helper.java](src/tn5250_mcp/java/T5250Helper.java).

TDQS

A3.7/5.0

Scored across 14 tools

Disambiguation4/5

Most tools target distinct actions: connect/disconnect, list_sessions/list_profiles, get_screen/get_session_log all have clear boundaries aided by descriptions. The closest overlap is fill vs press, but fill explicitly types without sending while press sends to host, so they remain distinguishable.

Naming Consistency3/5

A partial verb_noun convention appears in get_session_log, forget_password, list_profiles, list_sessions, get_screen, record_start, record_stop, but it is broken by bare verbs (connect, fill, press, wait) and bare nouns (viewer, keys). Readable but mixed conventions.

Tool Count5/5

14 tools is well-scoped for a 5250 terminal automation server, covering connection lifecycle, screen interaction, recording, and support tools without excess.

Completeness4/5

Core terminal workflow is covered: connect, navigate (get_screen, fill, press, wait), session/profile management, recording, and logging. Minor gaps exist around profile creation/editing and recording management (delete/list recordings).

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues