Building MCP Control for a VM App with a File Queue
When an application's API cannot cross the VM boundary and long commands through the hypervisor break on quoting, what remains is files in a folder both sides can see. A file queue looks old-fashioned, but it is the only channel that leaves an audit trail for every job.
1-minute summary
- Symptom / problem
- An engineering program inside a VM has an API that cannot be called across machines from the host.
- Who should read
- Anyone who needs an AI to drive a program running in a VM through MCP.
- Fix in short
- Have the host-side MCP server write job files into a shared folder and wait for the result file, one job at a time, with a two-layer gate for dangerous tools.
I had just finished modifying a set of PLC programs using scripts I wrote one file at a time, more than 30 in total, both .ps1 and .cmd. Each did one thing: open a project, export blocks, import source, compile, or archive. When I was about to start the next round of work, I had to remember which script took which parameters. So I wrapped them all in one MCP server, letting the next AI session call them as tools immediately. The problem was that this engineering application lived in a VM, and its API could not be called from another machine. What finally worked was the most old-fashioned option: a file queue in a folder shared between the host and guest.
I have replaced all paths, folder names, and tool names in this article with generic names, but the structure, timeout values, and error messages are what I actually use.
I use this MCP server with a simulator in a single lab VM. I have never connected it to a real PLC, and the guest does not even have a bridged network adapter connecting it to machinery. The numbers and sequences in this article apply only to this lab. Any work that touches real machine outputs must be reviewed and approved every time by the controls engineer responsible for the site. AI-written code must always pass compilation, simulator testing, and human review first.
Three constraints that dictated the design
If the application were on the same machine as the AI, this would be straightforward, as when I connected SketchUp to MCP through a socket on the same machine. This time, though, three constraints overlapped.
First, the application is TIA Portal, installed in a Windows 10 VM on VMware Workstation. The host has neither the application nor its API DLLs (Openness), and this API has no remote calling mode. Its DLLs must be loaded on the same machine as the application.
Second, the API must attach to an instance open on the screen. On my first attempt, I ran the script directly through the hypervisor's command execution channel. It landed in session 0, the service session, which has no desktop. Querying for instances returned an empty list even though the application was plainly open on the screen. For a while, I wrongly assumed the application had not finished starting, so I added more sleep time. That did nothing, because no amount of waiting would let session 0 see the user's windows.
Third, once I could launch scripts in the logged-in user's desktop session, I tried sending an entire long PowerShell command line through vmrun. Nested quoting and redirection broke. The command that reached the guest differed from what I had typed, and there was no reliable way to get the output back.
Send a full command line across the VM boundary
- Nested quoting broke as soon as a path contained spaces
- Redirection was interpreted on the wrong side
- No channel for results beyond an exit code
- Failures left no evidence of what had been sent
A file queue in a shared folder
- Only the launcher name and job id cross the boundary as a command
- Scripts and parameters are files, with no quoting involved
- The complete result comes back as JSON
- For a stuck job, I can open the files to see what was sent
A file queue, six steps per job
The VMware shared folder is the only place both sides can read and write without a network. On the host, I put it at D:/VMs/_share/mcp. The guest sees it as a shared-folder UNC path. The actual working directory in the guest is C:/Work/mcp, on its local disk.
Following the numbers in the diagram: 1) the host generates a job id and writes <id>.json for the parameters and <id>.job.ps1 for that tool's PowerShell script, placing any attachments under files/<id>/; 2) the host invokes the launcher in the desktop session to run job.cmd <id>; 3) job.cmd copies the runner and job files from the share to the local disk; 4) the runner loads the DLLs, attaches to the application open on the screen, and runs the job; 5) the runner writes <id>.out, followed by <id>.done; 6) the polling host sees .done, reads .out, and deletes that job's files.
On the host, one job() function
The server is written in Python, using the mcp library to communicate with the AI over stdio. The whole file is 502 lines long, but its core is a single shared function that every tool calls.
import json, time, uuid, threading
from pathlib import Path
SHARE = Path('D:/VMs/_share/mcp') # ฝั่ง host
BS = chr(92) # backslash สร้างใน Python ไม่พิมพ์ผ่าน shell
GUEST_SHARE = BS * 2 + 'vmware-host' + BS + 'Shared Folders' + BS + 'share' + BS + 'mcp'
LOCK = threading.Lock() # ทีละงานเท่านั้น
def job(body, params=None, need_app=True, files=None, timeout=900):
"""รันตัว PowerShell หนึ่งก้อนใน guest แล้วคืนผลเป็น dict"""
with LOCK:
jid = time.strftime('%H%M%S') + uuid.uuid4().hex[:6]
p = dict(params or {}); p['needApp'] = need_app; p['job'] = jid
(SHARE / f'{jid}.json').write_text(json.dumps(p, ensure_ascii=False), encoding='utf-8')
(SHARE / f'{jid}.job.ps1').write_text(body, encoding='utf-8-sig')
launch_in_desktop_session(GUEST_SHARE + BS + 'job.cmd', jid)
done, out = SHARE / f'{jid}.done', SHARE / f'{jid}.out'
t0 = time.time()
while not done.exists():
if time.time() - t0 > timeout:
return {'ok': False,
'error': f'timeout after {timeout} s (job {jid} may still be running in the VM)'}
time.sleep(1.0)
try:
r = json.loads(out.read_text(encoding='utf-8'))
except Exception as e:
r = {'ok': False, 'error': f'bad result file: {e}'}
for f in (done, out, SHARE / f'{jid}.json', SHARE / f'{jid}.job.ps1'):
f.unlink(missing_ok=True)
r['seconds'] = round(time.time() - t0, 1)
return r
There are three things I deliberately included. The first is a lock, because there is only one application instance in the guest and one open project. Two jobs arriving together would compete to attach, so I allow only one job at a time, with no parallel queue.
The second is a timeout message that explicitly says the job may still be running in the VM. The host giving up its wait does not mean the guest has stopped working. If the AI receives this error and immediately submits the job again, two jobs will overlap. The message therefore needs to carry that warning.
The third is a different timeout for each tool. I set these based on the actual measured duration of each type of job.
| tool | timeout (seconds) | Reason |
|---|---|---|
| status | 90 | Only queries status; anything longer indicates a session problem |
| open | 900 | Opening a freshly copied project includes a configuration update |
| retrieve / archive | 1800 | Extracts or compresses the entire project archive |
| compile | 3600 | Compiles the entire PLC, including hardware |
Meanwhile, start takes 2-5 minutes from a cold start, because it must start the VM, wait for auto-logon to the desktop, open the application, wait until it can attach, and then start another background process to watch for modal dialogs.
On the guest, the launcher and runner
The launcher is a short .cmd file that takes only a job id. It has four responsibilities.
- Create the job directory on the local disk if it does not exist
- Copy the runner and helper files from the share to the local disk every time, so the guest gets the latest version edited on the host
- Copy
<id>.json,<id>.job.ps1, and that job's attachment folder to the local disk - Invoke
powershell.exeversion 5.1 with-WindowStyle Hiddento run the runner with the job id
Why copy to the local disk first? On my first attempt, I had PowerShell run scripts directly from the share and hit two problems: occasional Access is denied errors, and files already loaded by the guest staying locked so the host could not overwrite them with newer versions. Both problems disappeared once I copied the files to the local disk and ran them there. It also has to be powershell.exe 5.1, not PowerShell 7, because the API DLLs use .NET Framework.
param([string]$Job)
$dir = 'C:\Work\mcp'
$share = '\\vmware-host\Shared Folders\share\mcp'
$dll = 'C:\Program Files\Siemens\Automation\Portal V15_1\PublicAPI\V15.1\Siemens.Engineering.dll'
$ErrorActionPreference = 'Stop'
$res = [ordered]@{ ok = $true; job = $Job }
try {
$P = Get-Content (Join-Path $dir "$Job.json") -Raw -Encoding UTF8 | ConvertFrom-Json
[Reflection.Assembly]::LoadFrom($dll) | Out-Null
$app = $null; $prj = $null
$tries = 1; if ($P.needApp) { $tries = 6 }
for ($t = 1; $t -le $tries -and -not $app; $t++) {
try {
$pr = [Siemens.Engineering.TiaPortal]::GetProcesses()
if ($pr.Count -gt 0) { $app = $pr[0].Attach() }
} catch { $app = $null }
if (-not $app -and $t -lt $tries) { Start-Sleep 5 }
}
if ($P.needApp -and -not $app) { throw 'program is not running in the VM desktop session (use start)' }
if ($app -and $app.Projects.Count -gt 0) { $prj = $app.Projects[0] }
$res.result = & (Join-Path $dir "$Job.job.ps1") # ตัวงานเห็น $app / $prj / $P และฟังก์ชันช่วย
} catch {
$res.ok = $false
$e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }
$res.error = $e.GetType().Name + ': ' + $e.Message
$res.at = "$($_.InvocationInfo.ScriptLineNumber): $($_.InvocationInfo.Line)".Trim()
}
The entire runner is 73 lines long. The rest consists of helper functions, such as one for requesting a generic service, one for finding a PLC in the project, one for recursively walking block groups, and one for compiling and returning the state and counts of errors and warnings. Each tool's job script can therefore be short, because the basics are already in place.
Attaching has 6 retries, 5 seconds apart, because querying for the process can throw a temporary exception just after the previous script releases the application. For errors, I follow InnerException down to the innermost level, because calling methods through reflection wraps the real error in TargetInvocationException. Returning the outermost exception would give the AI a message that says nothing useful. I also include the line number and the failing line itself in at, so the AI can fix the right part of the job script on the next attempt.
Results: no BOM, and .done must come last
The end of the runner is the part I revised the most.
try { $json = $res | ConvertTo-Json -Depth 12 }
catch { $json = '{"ok":false,"error":"result could not be converted to JSON"}' }
# เขียนลง local ก่อน ด้วย UTF-8 ไม่มี BOM
[IO.File]::WriteAllText((Join-Path $dir "$Job.out"), $json, (New-Object Text.UTF8Encoding($false)))
Copy-Item (Join-Path $dir "$Job.out") (Join-Path $share "$Job.out") -Force
# .done เป็นไฟล์สุดท้ายเสมอ
Set-Content (Join-Path $share "$Job.done") 'done'
Remove-Item (Join-Path $dir "$Job.*") -Force -ErrorAction SilentlyContinue
The BOM issue is that PowerShell 5.1 adds a leading BOM when writing UTF-8 files with its normal commands. Then json.loads on the host, reading with plain utf-8, fails at the first character. So I write through [IO.File]::WriteAllText with UTF8Encoding($false) to explicitly omit the BOM.
The ordering issue is that if the host polls directly for .out, it may see the file before the guest finishes writing it and read incomplete JSON. So I use two separate files. .out holds the result, which is fully written locally before being copied to the share. .done is an empty flag created last. The host waits only for this flag; once it appears, .out is guaranteed to be complete.
There is a reason for ConvertTo-Json -Depth 12, too. The default depth is 2, which truncates deeply nested trees of compile messages to type names. And if a job accidentally returns a live API object that cannot be serialized, there is still a fallback JSON result saying serialization failed. That is better than having no .out and leaving the host waiting until it times out.
This is the same principle I used in the command queue across NAT: the receiving side must be able to tell whether what it sees is complete. For files, the simplest approach is to finish writing the content first, then create the flag file afterward. The receiving side checks only the flag, without guessing from the file size or mtime.
Dangerous tools must pass two gates
There are 19 wrapped tools, grouped into status/start/stop, open/close/save, retrieve/archive, list/hw/tags/export_block, import_scl/import_xml/set_tag_address, compile, online, download, and ps, which accepts raw PowerShell as an escape hatch for work that does not yet have a dedicated tool.
All editing tools modify the project in the VM without touching the PLC. Only download sends anything to the target, and download stops the CPU before loading, then starts it again. If the target is a real machine, that means stopping it in the middle of its work. So I will not let the AI make this decision with a single parameter.
import os
@mcp.tool()
def app_download(plc: str, pc_interface: str = 'PLCSIM', hardware: bool = True, confirm: str = '') -> dict:
"""Compile, save, download. THE CPU IS STOPPED AND RESTARTED. Default goes to the simulator."""
if 'PLCSIM' not in pc_interface.upper():
if os.environ.get('ALLOW_REAL_DOWNLOAD') != '1':
return {'ok': False,
'error': 'download to a real PLC is disabled (server env ALLOW_REAL_DOWNLOAD=1 is not set)'}
if not confirm or confirm != plc:
return {'ok': False,
'error': 'real-PLC download needs confirm = exact PLC name (no wildcard)'}
return job(DOWNLOAD_PS, {'plc': plc, 'pc': pc_interface, 'hw': hardware,
'exact': 'PLCSIM' not in pc_interface.upper()}, timeout=1800)
The first gate is an environment variable set when starting the server. The AI cannot set it itself from within the conversation; a person must start the server with this value. The second gate requires confirm to match the PLC name exactly, character for character. Other tools accept wildcards such as PLC* for convenience, but this one does not. Failing either gate returns an error immediately without creating a queued job. The guest also checks again that the PLC name it finds exactly matches the requested name.
The download interface parameter defaults to the simulator. If the AI calls it without specifying anything, the download always goes to the simulator. Reaching a real PLC requires three deliberate actions together: starting the server with the env setting, specifying the real interface, and typing the exact target name. The tool's docstring also states in uppercase that the CPU will be stopped, because the AI reads the docstring before every call.
Things that went wrong along the way
The first was backslashes. I passed a UNC path through Git Bash to the VM command launcher, and the leading pair of backslashes was reduced to one. The \v and \t in the middle of the path were also interpreted as escapes, leaving the destination with an unusable path. The fix was to avoid typing the path through the shell at all and have Python construct it from chr(92), as in the code above.
The second was robocopy. I mirrored the tools folder from the share to the guest with /MIR, which makes the destination identical to the source, including deleting files absent from the source. Logs the guest had just written therefore disappeared on every sync. They needed an exclusion.
# ผิด: log ที่ guest เขียนไว้ในโฟลเดอร์เดียวกันถูกลบทุกรอบ
robocopy "\\vmware-host\Shared Folders\share\tools" C:\Work\tools /MIR
# ถูก: ไม่แตะไฟล์ log ทั้งสองฝั่ง
robocopy "\\vmware-host\Shared Folders\share\tools" C:\Work\tools /MIR /XF *.log
The third was registration. After registering it, I could not find the tools in the same session and thought I had registered it incorrectly. In fact, newly added MCP tools appear only in a new session.
# ลงทะเบียนระดับ user ใช้ได้ทุกโปรเจกต์
claude mcp add -s user plcvm -- "C:/Tools/py/python.exe" "C:/Tools/mcp/server.py"
claude mcp list
# จากนั้นปิด session เดิม เปิดใหม่ tool ถึงจะขึ้น
Numbers and limitations I need to state plainly
I want to spell out all the limitations of this approach. First, it is definitely slower than RPC. Even a short status query incurs the overhead of starting a new process in the guest and waiting for polling at 1-second intervals. Second, it handles only one job at a time. Third, if the host times out first, the guest job keeps running and leaves result files on the share that someone must clean up. Fourth, all of this has been tested only with a simulator. I have never connected it to a real PLC, and the guest still has no bridged network adapter, so the download gates described here have never been used in a real-world situation.
Personally, I accept the extra delay for one benefit: every job leaves files I can open and inspect. If a job gets stuck, opening .job.ps1 and .json on the share tells me what the AI sent, without having to guess from socket logs. If you have an application whose API is similarly tied to a desktop session, feel free to use this structure. If your application already has a remote API, there is no need to take this more cumbersome route. If I have left anything out or made a typo, I will come back and correct it later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first