tn5250-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@tn5250-mcp connect to pub400.com, sign on, and open the inventory menu"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 ( |
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 ( |
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 |
Related MCP server: ibmi-mcp
Install
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, 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):
claude mcp add tn5250 -- /path/to/tn5250-mcp/.venv/bin/tn5250-mcp --log-dir ~/tn5250-logsLong-running server (sessions survive client restarts; several clients can share it):
.venv/bin/tn5250-mcp --transport http --port 8250 --log-dir logs
claude mcp add --transport http tn5250 http://127.0.0.1:8250/mcpClaude Desktop (claude_desktop_config.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 |
| open a session with a saved |
| the saved connection profiles |
| screen text with rulers, cursor, keyboard state, |
| put values into fields (by |
| optional fills + cursor, then send a key and return the host's reply screen |
| wait until the host wants input (optionally for some text) |
| link to the live viewer |
| record a session's key presses as a new flow |
| sign off from the screen's command line, then close ( |
| the session's transcript (passwords masked), also after a disconnect |
| forget saved passwords (memory and keychain) |
| open a SQL/IFS connection (with |
| run a query; the connection is read-only on the server side |
| change data (only with |
| list folders, read stream files (text in their CCSID, or base64) |
| write stream files (only inside |
| run a CL command with a library list, get IBM i's messages (only with |
| compile a source and get its errors as file:line:column (only into |
| call a program with typed parameters, get the output parameters back (only with |
| upload a local project folder and build what changed, errors as local file:line:column |
| run a PASE shell command (git, make, python3, |
| list source files and members, read a member |
| replace or create a source member (only in |
| 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 |
| a message's text, cause and recovery (compile, run-time, CL, SQL messages) |
| a job's messages: why a command, compile or batch job failed |
| list and read printed output: reports, listings, job logs |
| housekeeping |
your flows | one tool per screen flow loaded with |
your command tools | one tool per command tool ( |
Several sessions can run side by side (session argument).
Example press call:
{ "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:
Get JTOpen, the open-source Toolbox (IBM Public License 1.0), as
jt400.jar: from GitHub 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.Have Java 11 or newer: either install the
javaextra (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, thejavaextra, the system's.Start the server with
--jt400 /path/to/jt400.jar.
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_executeThe 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_queryruns 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/TABLEorMYLIB.TABLE, plus the library list. QSYS2 services work too, for exampleQSYS2.ACTIVE_JOB_INFOorQSYS2.IFS_OBJECT_STATISTICS.sql_execute(INSERT, UPDATE, DELETE, CREATE, CALL, ...) is offered only with--allow-sql-write.ifs_readconverts text from the file's CCSID;binary: truereturns base64.ifs_writecreates new files tagged with the CCSID you give (1208 = UTF-8 by default, 37 = EBCDIC US), refuses to replace a file unlessoverwriteorappendis 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_logwith sessionhost-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 changingT5250Helper.java, rebuild it withpython 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.
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 failedLibrary list.
host_connecttakeslibl(or a profile'sliblkey); it applies to SQL, commands and compiles.run_commandandcompilecan 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 memberLIB/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 addsOPTION(*EVENTF)and reads the compiler's event file, like Code for IBM i, for errors with line and column. For stream files it compiles withTGTCCSID(*JOB)(RPG) orCVTCCSID(*JOB)(SQL RPG), because RPG can't compile a UTF-8 file with its default (RNS9380).optionsadds parameters;format: jsonreturns it all as data.job_logshows 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_fileslists your newest spooled files (QSYS2.SPOOLED_FILE_INFO, which is fast where the output queue views hit query time limits);spooled_filereads one. Output of commands run through the host servers lands in yourQPRTJOBjob, not in the command's job.From a shell or CI:
tn5250-run cmd "CRTBNDRPG ..." --libl MYLIB,QGPLandtn5250-run compile src/hello.rpgle MYLIB/HELLO, with--profileor--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 asfile: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).
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:
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/COPYand/INCLUDEmembers 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:
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
DSPFFDandDSPFD TYPE(*ACCPTH)outfiles in the helper's ownQTEMP.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
typepicks 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".
pase {"command": "git status --short", "cwd": "/home/ME/hello"}
→ exit 0
--- stdout
M src/main.rpgleIt runs in the same job as
run_commandandcall_program, soliblapplies tosystemand 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 PWRDWNSYSis 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.QSHstarts 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 pub400prints 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.
compiletakes a member as its source (MYLIB/QRPGLESRC(HELLO)). Withouttype, 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.rpgleandtn5250-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.
# 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 typeThe file names say what to create (see examples/project):
file | becomes |
| program NAME from one source ( |
| module NAME, for |
| file NAME from DDS |
|
|
| binder source for a service program |
| 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.jsonkeeps hashes of what was uploaded and built (put it in.gitignore). A rebuild covers what changed plus what depends on it: sources that/copyor/includea 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.rpgleincworks as it does locally.DDS:
CRTPF,CRTLF,CRTDSPFandCRTPRTFdon't read stream files (CPD0043 on IBM i 7.5), so the build copies the source into a member inQTEMPfirst; errors still point at your local file.CRTPFandCRTLFcan'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 getBNDDIR(...)andDFTACTGRP(*NO), since the command's defaultDFTACTGRP(*YES)refuses a binding directory before the source'sctl-optis 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.RUNSQLSTMwrites a listing only on errors; the build reads it for line and column and deletes it.Limits: the project's
libmust be among--allow-compile, and itsifsfolder inside an--ifs-write-root. The CLI allows exactly the project's library and folder.
$ 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: FAILEDCommand 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.
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 themAfter 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: truewaits 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
QPRTJOBjob while it ran. Compiler listings are turned intomember:line:columnerrors: ILE RPG, SQL RPG (both the precompiler's listing and the RPG step's, mapped back from theQTEMPcopy to your member), ILE CL and DDS (PF, LF, DSPF, PRTF).RUNSQLSTMlistings are read the same way.Job log. A spooled job log (
QPJOBLOG) is read for its escape and diagnostic messages.QSYS2.JOBLOG_INFOcan't read the log of a job that has ended.
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: truea value may only hold name-like characters (letters, digits,_ $ # @ . * / , + - :), so no parameter can add parameters or commands. Withquote: trueit goes in as a quoted string.Rules. Command tools need
--allow-commands. Every command goes through--command-allowand the block list, and forSBMJOBso does the command it submits.--allow-compiledoesn't limit them: a command tool runs what its YAML says. They're never offered in--read-onlymode, and--toolsetsapplies.Line numbers. Listings print source sequence numbers.
lineassumes members numbered 1.00, 2.00, ..., as SEU,member_writeandCPYFRMSTMFnumber them; the number as printed is inseq(format: json).Example. 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 NAMEprints the same report and exits 1 on failure.tn5250-run checklists 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.
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: cp273Keys: 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_connectflow 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
connectsays 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-onlyrefusesconnectwith 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-jt400for 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.
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.
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: F3tn5250-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 listParameters (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 |
| text (or |
| only run this step if this text is on screen; otherwise skip it (pop-ups, confirm screens) |
| field → value. Fields by label, |
| put the cursor on a field or position first |
| key to send, then wait for the host's answer |
| wait for text after the key (or on its own); default timeout 30 s |
| after the step: |
| name → regex with one group, |
| run another flow with these parameters |
| with |
| with |
| run read-only SQL (needs |
| do the step again until |
| 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:
- 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 inend code 0 .for a normal end (20 and up: abnormal). Also,JOB_INFO'sJOB_USER_FILTERtakes 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*BREAKmode.Write
CAST(? AS TIMESTAMP)rather thanTIMESTAMP(?): Db2 for i refuses an untyped?there (SQL0418).
See 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 (orkeyboard: errorwhen 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):
tn5250-run test tests/data_entry.yaml --var lib=MYLIB --profiles profiles.yaml \
--jt400 lib/jt400.jar --junit results.xml --html report.htmlsuite: 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}/T5250TESTTests run a
flow(withwith) or severalsteps.data:(a CSV file) orcases:(a list) runs a test once per row; row values are{name}templates, and a test withoutwithpasses the row's matching columns to the flow.skip: reasonskips a test.Expectations after the flows:
captured(regex per captured value),screen/not_screen(texts, or"row:text"),snapshot(see below) andsql(a read-onlyquerywithparams, thenrowsexactly,containssome rows, or a rowcount).expect_failureexpects a flow to fail, with a message matching the regex.Recovery. With
home, each test starts from that screen: the runner presses Reset and thekeysuntil 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: truefor 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/, orsnapshots:) and compare it on later runs. Dates, times, job names and device names are masked, andignore:adds regexes. A difference fails the test with a diff;--update-snapshotssaves the current screens as the new expected ones. In Python and pytest:t5250.assert_snapshot("main_menu").Reports.
--junitwrites JUnit XML that CI systems (GitHub Actions, Jenkins, GitLab) show per test.--htmlwrites 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 REGEXruns some tests.Signing on. The suite uses the profile's sign-on flow: with a password in the keychain (or
$T5250_PASSWORDin CI) nothing asks. SQL and commands use the same saved password, so--jt400is all they need.
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:
tn5250-run run --host pub400.com --flows examples/flows data_entry_test lib=MYLIBSign-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:
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):
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"]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:
A saved password for this user and host is used, if there is one (see below). This needs
user_param: useron the secret, naming the parameter that holds the user profile, as in the examplesignonflow.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).
Otherwise the parameter's
envvariable is used (CI secrets).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
keyringextra (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-rememberhides 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_passwordtool clear memory and keychain.list_sessionsnames 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/pressmust carryexpect(text that must be on the screen, or"row:text") orscreen_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 SCHEMAorQCMDEXCare refused (full list insrc/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-onlyto allow only your saved connection profiles.Flows instead of free typing.
--flows-onlyremovesfillandpress, so the agent can read screens and run your flows, nothing else.--read-onlyalso drops every flow not markedread_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
pressis 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 DIRalso writes it to files, useful as test evidence.Clean sign-off.
disconnectfirst typesSIGNOFFon 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()andtn5250-run --signoffdo 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 |
|
|
|
|
|
|
|
|
|
|
| any |
|
| none extra |
|
| defaults on |
|
| checks required |
|
| no logs |
| random per start (set it to keep viewer links valid across restarts) | |
|
|
|
|
| none |
|
| all |
|
| off |
|
| off |
|
|
|
|
|
|
|
|
|
|
| recordings are returned, not saved |
|
| none |
|
| off |
|
|
|
|
| checkbox shown when |
|
| no SQL/IFS tools |
|
| found automatically (Java 11+) |
|
| off |
|
| no |
|
| no |
|
| any command (block list still applies) |
|
| no |
|
| no |
|
| no |
Examples and tests
examples/call.py TOOL '{json args}': call one tool against an HTTP server.examples/flows/: example screen flows, includingdata_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, usingpressdirectly.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.
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 emulator was used as the protocol reference.
License
MIT, see 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). The
bundled t5250-helper.jar holds only this project's own classes, built from
T5250Helper.java.
Available Tools
14 toolsconnectA
Open a 5250 session and return the first screen: Sign On, or the screen after the profile's after-connect flow (e.g. a menu once signed on).
Inputs: tls, host, port, wide, +5 more. Returns: result
disconnectAIdempotent
Sign off (from the command line of the current screen) and close the session. A screen without a command line can't be signed off from; the result says so.
Inputs: session, signoff. Returns: result
fillA
Type values into input fields without sending anything to the host.
Inputs: values (required), expect, session, screen_id. Returns: result
forget_passwordAIdempotent
Forget saved passwords (kept after sign-ons that worked, in memory and, if the user chose so, in the system keychain). The next sign-on asks again.
Inputs: host, user. Returns: result
get_screenARead-only
Read the current screen: text with row/column rulers, cursor, keyboard state, screen_id and the input fields.
Inputs: fields, session. Returns: result
get_session_logARead-only
The session's transcript: connects, fills (passwords masked), keys, flows, reconnects and recordings, newest last. Useful to retrace what happened, also after a disconnect.
Inputs: last, screens, session. Returns: result
keysARead-only
List the key names press accepts.
Inputs: no named parameters. Returns: result
list_profilesARead-only
List the saved connection profiles you can connect with.
Inputs: no named parameters. Returns: result
list_sessionsARead-only
List open sessions and their state.
Inputs: no named parameters. Returns: result
pressADestructive
Send a key to the host (after optional fills) and return the screen the host answers with. Reset only clears an operator error locally.
Inputs: key (required), cursor, expect, values, +4 more. Returns: result
record_startA
Start recording a screen flow on this session: every key pressed from now on (by you or by the user in the viewer) becomes a step. Passwords are never recorded. Finish with record_stop.
Inputs: session. Returns: result
record_stopA
Stop recording and return the flow as YAML (saved when the server has a record folder). The flow is available as a tool right away. Review it before relying on it.
Inputs: name, save, params, session, +1 more. Returns: result
viewerARead-only
Link to the live web viewer, where the human can watch, sign on or take over. Give it to the user when a password is needed.
Inputs: no named parameters. Returns: result
waitARead-only
Wait until the host is waiting for input (and optionally for some text), e.g. after a long-running command or while the user signs on.
Inputs: text, session, timeout. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 14 tools
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.
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.
14 tools is well-scoped for a 5250 terminal automation server, covering connection lifecycle, screen interaction, recording, and support tools without excess.
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
Related MCP Connectors
Remote Desktop Commander: use files, terminal and processes on your own computers from any AI app.
Connect AI assistants to your approved computer for files, commands, browser and desktop tasks.
Let AI operate servers without SSH. Choose actions, approve risky changes, and audit every step.
Secure AI access to Windows, macOS, Linux computers and a hosted Cloud Browser.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with IBM i systems through the Model Context Protocol, providing secure SQL-based access to Db2 for i databases for querying, monitoring, and executing operations.Apache 2.0
- AlicenseAqualityCmaintenanceGive your AI Agent terminal access to your IBM i system via TN5250. ibmi-mcp is an MCP server that lets AI Agents like Claude interact with IBM i the same way a human would through a 5250 green-screen terminal.815BSD 2-Clause "Simplified"
- AlicenseNot gradedqualityCmaintenanceEnables AI assistants to securely interact with IBM i (AS/400) systems via ODBC, supporting SQL queries, CL commands, source code reading, compilation, and spoolfile analysis.2MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with IBM i (AS/400) systems for RPA automation via 37 tools for 5250 navigation, CL commands, DB2 queries, and system management.MIT