[KongchangAI]
· 4 min read· 2,460 words

AI Agent Writes SCL Programs for Siemens S7-1500 via MCP

AI Agent Writes SCL Programs for Siemens S7-1500 via MCP

AI Agent drives TIA Portal via MCP to independently complete an S7-1500 sorting program and clearly define its capability boundaries.

This article documents a real industrial control experiment: using the self-developed MCP server TiaLink to expose the TIA Portal V19 Openness API to an AI Agent, which writes a conveyor sorting control program for the S7-1500 and completes the full closed loop in S7-PLCSIM. The Agent sets up verification before coding and delivers an 11-state state machine, two key designs, 14 test cases, and 12 race condition analyses. It explicitly refuses to replace hardware safety, pneumatic hard interlocking, or real-machine tuning.

Title

AI Agent Writes SCL Programs for Siemens S7-1500 via MCP

Meta Description

An AI Agent bridges Siemens TIA Portal V19 through MCP to independently complete a conveyor sorting control program for the S7-1500: from creating a CPU and writing the SCL state machine to delivering 14 test cases, proactively flagging 12 race conditions and boundary issues, while explicitly refusing to take on safety functions.

Article Content

Connecting a large language model to Siemens TIA Portal and letting it independently complete a conveyor sorting control program — this is no longer just a proof of concept.

Someone actually built an MCP server (TiaLink) that exposes the TIA Portal V19 Openness API to an AI Agent (WorkBuddyAd), then gave it a real engineering task: implement conveyor sorting control for an S7-1500 (CPU 1511-1 PN) and verify it in S7-PLCSIM.

rss source: An AI Agent Programmed a Siemens S7-1500 Through an MCP Bridge

This isn't "generate a code snippet" — it's a complete closed loop: add CPU → compile → start simulation → create FB/UDT → write SCL → compile → download → verify.

The most interesting part isn't the code itself, but which engineering decisions the Agent made, and where it explicitly refused to cross the line.

Toolchain and Task Setup

The entire toolchain is divided into three layers: the Agent (WorkBuddy) is responsible for reading specifications, planning steps, writing code, and testing; the MCP bridge (TiaLink) exposes TIA Portal operations as MCP tools — add device, create block, write SCL, compile, download, read back; the target environment is TIA Portal V19 + Openness, with verification done in S7-PLCSIM. The bridge program runs on the same industrial PC as TIA Portal, and the Agent can connect remotely.

The task specification is quite specific: SCL state machine state numbers must match the specification (so that HMI, alarms, tests, and field commissioning all reference the same set of numbers); logic is encapsulated as a reusable FB with its own instance DB; input/output/internal variables are clearly separated with i_ / q_ / stat_ prefixes; use IEC timer TON_TIME rather than hand-written scan cycle accumulation; implement entrance deduplication, quality result latching, dual-cylinder interlocking, fault latching, manual reset, normal stop, and other functions.

There's also a key requirement: every output must be written with a deterministic value every scan cycle, not relying on residual values from the previous cycle. And at the very end: "First add a CPU, and check whether the simulator is available."

This last sentence is precisely the focus of the test. Configuration tasks can be judged from screenshots, but programs must be judged by behavior. Will the Agent first set up the verification environment, or start writing code directly?

MCP (Model Context Protocol) is an open protocol proposed by Anthropic at the end of 2024 to establish a standardized interface between AI models and external tools/data sources. Its core idea is similar to "USB-C for the AI world": encapsulate any software capability (file system, database, industrial software API) as a unified tool description, and the model can complete operations through structured calls. In this scenario, TiaLink maps TIA Portal's Openness API item by item into MCP tools, so the Agent doesn't need to understand the underlying COM interface details — it just initiates calls like "add device" or "write SCL" according to the MCP protocol.

Siemens Openness API is the official automation interface provided by Siemens for TIA Portal, based on .NET/COM, allowing external programs to programmatically perform project creation, hardware configuration, block generation, compilation, and download operations, typically used for batch engineering, version migration, and CI scenarios. It is the underlying foundation that enables TiaLink to "remotely control" TIA Portal, but it itself is not designed for large language models and requires the MCP bridge to provide a layer of semantic encapsulation.

Agent's Execution Order and State Machine Design

The order the Agent chose was: first check whether a CPU already exists, then add PLC_1 (CPU 1511-1 PN); compile and start S7-PLCSIM, confirm download/run is normal; create FB_ConveyorSort and write the SCL state machine; create required UDTs; call the FB in OB1 using instance DB DB_ConveyorSort_1; compile and download without errors; finally deliver the state transition table, 14 test cases, and race condition/boundary analysis.

It set up the verification environment first — a good sign.

The state machine spans 11 states from 0 to 100: INIT (first scan, clear latches and fault codes) → READY (wait for start) → FEED (conveyor running, entrance deduplication, quality latching, sorting timeout monitoring) → CHECK (stop at sorting position, branch based on latched result) → PUSH_A / PUSH_B (OK pushes cylinder A, NG pushes cylinder B) → RETRACT (confirm retraction in position) → DISCHARGE (wait for workpiece to leave sorting position) → back to FEED. There are also FAULT (fault latch, all outputs off) and STOPPED (normal stop, restartable).

Notable design details: state 30 (CHECK) directly decides whether to go to 50 or 60 based on the latched result, without any real-time judgment; state 70 (RETRACT) simultaneously monitors the retraction limit switch and timeout timer, jumping to the fault state on timeout.

Two Core Designs in the SCL Code

In the complete FB code delivered by the Agent, there are two designs worth examining closely.

Section 0's deterministic output writing. At the beginning of each scan cycle, all outputs are first written to FALSE or deterministic values, then set as needed in subsequent logic. This directly addresses the specification's requirement that "every output must have a deterministic value each cycle." If a programmer habitually writes outputs only when conditions are met, once the residual value from the previous cycle is not overwritten, dangerous behavior could result.

Section 7's interlocking and output mapping. Cylinder A extension requires three conditions simultaneously: an A extension request, no B extension request, and B cylinder confirmed retracted. The same applies to cylinder B. The retraction output directly takes the inverse of the extension output — for a double-acting cylinder, this is the direction that is safe when de-energized.

In code comments, the Agent also specifically notes: for spring-return cylinders, the retraction output should be forced to 0 (retract on power loss), rather than actively driven.

Regarding safety logic, Section 2 only reads i_xSafetyOK as the safety circuit status input, and explicitly writes in comments "do not implement safety functions here." Section 3 performs sensor plausibility checks — if the extension and retraction limit switches of the same cylinder are both 1, a fault is triggered immediately. Section 5's fault reset requires the operator to press the reset button, the safety circuit to recover, and all sensor contradictions to disappear — none can be missing.

SCL (Structured Control Language) is a high-level structured text language defined by the IEC 61131-3 standard. In Siemens TIA Portal, it stands alongside Ladder Diagram (LAD) and Function Block Diagram (FBD), with syntax close to Pascal, supporting IF/CASE/FOR and other structures, and is particularly suitable for writing state machines, algorithms, and complex branching logic. In this article, the state machine, interlocks, and timer logic generated by the Agent are all expressed in SCL, because it is easier for text models to accurately generate and verify than graphical languages.

FB (Function Block) and Instance DB are key concepts in Siemens PLC programming. An FB is a reusable logic unit with "memory," whose internal static variables are stored in a separate instance data block (Instance DB), so the same timer or edge detector does not interfere across different call instances. This is precisely the technical root of the "multi-instance" race condition mentioned in the article: if multiple production lines share the same instance DB, timer states will overwrite each other. UDT (User-Defined Data Type) is used to package a group of related variables into a structure, facilitating transfer between FB interfaces and HMI.

The 12 Race Conditions and Boundary Conditions It Proactively Flagged

This part is the most engineering-valuable content in the entire record. While delivering the code, the Agent explicitly listed 12 race conditions and boundary cases that need attention:

  1. Entrance deduplication and sensor sticking — latching until the workpiece leaves the entrance photoelectric sensor is how deduplication works, but if the workpiece doesn't leave due to sticking, subsequent workpieces will be missed. The process must ensure single-piece spacing.

  2. Timing of quality result latching — latched at the entrance rather than the sorting position, because the quality system result may still be unstable when it reaches the sorting position, causing a race with the position signal. If quality inspection is very slow, a handshake/queue mechanism should be used rather than simply delaying the read.

  3. Arrival and timeout in the same scan cycle — IEC TON sets Q to TRUE in the scan cycle when PT is reached. The code checks timeout before arrival, and explicitly resets the timer on arrival. If "arrival priority" is desired, the order must be adjusted.

  4. Re-triggering after pushing — after the workpiece is pushed away, it may briefly block the sorting position photoelectric sensor. If going directly from 70 back to 20, double sorting would occur. State 80 (DISCHARGE) waits for the photoelectric signal to clear before re-arming.

  5. Hierarchy of interlocking — software interlocking only prevents simultaneous logical requests; it cannot replace pneumatic/electrical hard interlocking or mechanical limits.

  6. Button priority within the same scan cycle — fault/safety > stop > reset > start. This priority must be frozen in the requirements document, otherwise different implementations will diverge.

  7. Two meanings of stopping — immediate stop or stop after completing the current workpiece. The code implements immediate stop (state 100); if controlled completion is needed, a StopPending flag must be added.

  8. PT = 0 boundary — TON triggers immediately, potentially turning a timeout into an inevitable fault. If the time parameter can be modified by the HMI, a lower bound must be validated.

  9. Reset button long press — edge-triggered, so a long press won't continuously mask recurring faults.

  10. First scan initialization — state 0 completes initialization; a real project should also use OB100. State 0 is retained to make initialization visible and testable within the state machine.

  11. Multiple instances — timers and edge storage are all in FB static variables; absolutely do not share a single instance DB across multiple production lines.

  12. Simulation ≠ field — the simulator does not simulate photoelectric jitter, pneumatic delays, or safety circuit response times. All time parameters must be tuned on real hardware.

IEC timer TON_TIME is the standard on-delay timer defined by IEC 61131-3: it starts timing when IN is TRUE, sets Q to TRUE in the scan cycle when the preset time PT is reached; it resets immediately when IN becomes FALSE. Its time base is provided by the PLC system clock, with accuracy far higher than "hand-written scan cycle counter accumulation," which would be distorted by scan cycle jitter. Boundary condition 8 (PT = 0) in the article comes precisely from TON's semantics — when PT is 0, Q is set immediately in the same cycle; if the time parameter comes from the HMI without lower-bound validation, "timeout protection" becomes "inevitable fault."

Scan Cycle is the basic rhythm of PLC operation: read input image → execute user program → refresh output image, repeating cyclically, with a typical cycle in the millisecond range. All state machines, interlocks, and timer logic are evaluated within this rhythm. The so-called "every output must be written with a deterministic value every cycle" is essentially about countering the residual effect of the output image — if a cycle skips the write operation because conditions are not met, the output will retain the previous cycle's value, which may cause danger in safety-related scenarios.

Three Things It Explicitly Refused to Do

This part is why the author thought it most worth writing out.

After completing the software portion, the AI Agent explicitly returned three things to humans:

Emergency stop must be implemented by a hardware safety circuit (safety relay/safety PLC). The program only reads i_xSafetyOK as a status input and does not take on safety functions.

Dual-cylinder hard interlocking must be implemented by pneumatic or electrical solutions. Software interlocking is only a supplementary means and cannot replace it.

Time parameter and sensor tuning must be completed on real hardware. The simulator cannot provide real photoelectric jitter or pneumatic delay data.

It finished the part software can do, then returned the responsibility it could not verify to humans, without pretending it had "completed" what it could not do.

The author writes at the end: "This is what I expect from any code generator that touches industrial control — generate the verifiable parts, and clearly state the parts it cannot verify."

Honest Limitations

The author also lists several limitations: passing simulation does not mean it can go on site; he only verified code compilation, download, and logic-level test case matching, and did not perform bench testing on real hardware; the Agent's self-reported step logs need to be viewed with the usual skepticism.

The simulator does not simulate photoelectric sensor jitter, pneumatic valve response delays, or safety circuit power-off times — all of these must be tuned on real equipment. A state machine that runs successfully in PLCSIM still has a considerable distance to go before stable on-site operation.

Also worth noting: both the Agent and the TIA Portal MCP bridge are tools developed by the author's team (Huizhiwang), so the perspective needs a discount.

An AI Agent being able to independently complete the entire PLC programming loop from environment setup to code delivery is itself noteworthy. But more noteworthy is that it knows where the boundaries of its capabilities are, and did not try to cross them.

One-line Summary

AI Agent drives TIA Portal through an MCP bridge, independently completes the full S7-1500 sorting program workflow, and proactively draws clear capability boundaries.

Paragraph Summary

This article records a real industrial control experiment: through the self-developed MCP server TiaLink, the TIA Portal V19 Openness API is exposed to an AI Agent, letting it write a conveyor sorting control program for the S7-1500 and complete the full closed loop in S7-PLCSIM: "add CPU → compile → simulate → create FB/UDT → write SCL → download → verify." The Agent first sets up the verification environment before writing code, and delivers an 11-state state machine, two key designs (deterministic output writing every cycle, dual-cylinder software interlocking), a state transition table, 14 test cases, and 12 race condition analyses. More notably, it explicitly refuses three things: replacing hardware safety circuits to implement emergency stop, replacing pneumatic hard interlocking, and tuning time parameters in simulation. The author reminds that passing simulation does not mean field readiness, and because the tools are self-developed, the perspective needs a discount.

#AI Agent#MCP#Siemens S7-1500#TIA Portal#SCL
Share:

Related articles